import unittest
from dictlib.convert import Converter, JsonConverter
from dictlib.schema import Schema, UnicodeField, DatetimeField
import datetime

class TestConverter(unittest.TestCase):
    def test_from_schema_exclude(self):
        # test if fields are excluded correctly
        converter = Converter(exclude=[u'x', u'y'])
        self.assertEquals({u'z': u'c'}, converter.from_schema({u'x': u'a',
                                                               u'y': u'b',
                                                               u'z': u'c'}))

    def test_to_schema_exclude(self):
        # nothing should happen when converting to the schema
        converter = Converter(exclude=[u'x', u'y'])
        self.assertEquals({u'x': u'a', u'y': u'b', u'z': u'c'},
                          converter.to_schema({u'x': u'a', u'y': u'b', u'z': u'c'}))

    def test_schema_exclude_recursive(self):
        converter = Converter(exclude=[u'a.b'])
        self.assertEquals({u'a': {}, u'x': u'y'},
                           converter.from_schema({u'a': {u'b': 666},
                                                  u'x': u'y'}))

    def test_from_schema_rename(self):
        # test if fields are renamed correctly
        converter = Converter(rename=[(u'x', u'g'), (u'y', u'h')])
        self.assertEquals({u'g': u'a', u'h': u'b', u'z': u'c'},
                          converter.from_schema({u'x': u'a',
                                                 u'y': u'b',
                                                 u'z': u'c'}))

    def test_to_schema_rename(self):
        # test if fields are reverse-renamed correctly
        converter = Converter(rename=[(u'x', u'g'), (u'y', u'h')])
        self.assertEquals({u'x': u'a', u'y': u'b', u'z': u'c'},
                          converter.to_schema({u'g': u'a',
                                               u'h': u'b',
                                               u'z': u'c'}))
    def test_rename_inverse(self):
        converter = Converter(rename=[(u'x', u'g'), (u'y', u'h')])
        doc = {u'x': u'a', u'y': u'b', u'z': u'c'}
        self.assertEquals(doc, converter.to_schema(converter.from_schema(doc)))

        doc = {u'g': u'a', u'h': u'b', u'z': u'c'}
        self.assertEquals(doc,
                          converter.from_schema(converter.to_schema(doc)))

    def test_converter_rename_and_exclude(self):
        # test if fields are reverse-renamed correctly
        converter = Converter(exclude=[u'x'],
                              rename=[(u'z', u'i')])
        self.assertEquals({u'y': u'b', u'i': u'c'},
                converter.from_schema({u'x': u'a', u'y': u'b', u'z': u'c'}))
        self.assertEquals({u'y': u'b', u'z': u'c'},
                converter.to_schema({u'y': u'b', u'i': u'c'}))

        # test Converter where order of exclude and rename is important
        # (here, 'x' is excluded first, and then *not* renamed because)
        converter = Converter(exclude=[u'x'],
                              rename=[(u'x', u'a')])
        self.assertEquals({u'y': u'b'}, converter.from_schema({u'x': u'a', u'y': u'b'}))

    def test_map_from(self):
        class MyConverter(Converter):
            def map_from(self, key, value):
                if isinstance(value, unicode):
                    value = u'YYY%s' % value
                return key, value

            def map_to(self, key, value):
                if isinstance(value, unicode) and value.startswith(u'YYY'):
                    value = value[3:]
                return key, value

        converter = MyConverter()
        self.assertEquals({u'x': u'YYYa'},
                          converter.from_schema({u'x': u'a'}))

    def test_json_converter(self):
        schema = Schema({u'a': UnicodeField(),
                         u'b': DatetimeField()})
        json_converter = JsonConverter(schema)
        result_doc = json_converter.from_schema({u'a': u'x',
                                                 u'b': datetime.datetime(2011, 9, 11, 17, 29, 0)})
        self.assertEquals({'a': 'x', 'b': '2011-09-11T17:29:00Z'}, result_doc)
        self.assertEquals({'a': 'x',
                           'b': '2011-09-11T17:29:00Z'},
                          json_converter.from_schema({u'a': u'x',
                                                      u'b': datetime.datetime(2011, 9, 11, 17, 29, 0)}))
        self.assertTrue(isinstance(result_doc.keys()[0], str))
        self.assertTrue(isinstance(result_doc.keys()[1], str))
        self.assertTrue(isinstance(result_doc['a'], str))
        self.assertEquals({u'a': u'x',
                           u'b': datetime.datetime(2011, 9, 11, 17, 29, 0)},
                          json_converter.to_schema({'a': u'x',
                                                    'b': '2011-09-11T17:29:00Z'}))


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

def get_inds(problem_type, length, num_kept_samples):
    """
    Given a number of samples to keep and a problem type, returns indices to keep from a list.

    Args:
        problem_type: What type of inpainting problem we are dealing with.
                      String in {"random", "equal", "forecast", "full", "log", "sqrt"}.
        length: The original length of the signal.
                Int.
        num_kept_samples: The number (or proportion) of samples to keep.
                          Int <= length OR float <= 1.0.

    Returns:
        kept_inds: Array with (sorted, increasing) indices of samples to keep from the original signal.
                   Numpy array of Ints.
        missing_inds: Array with  (sorted, increasing) indices of discarded sampled from the original signal.
                      Numpy array of Ints.
    """
    if isinstance(num_kept_samples, float) and num_kept_samples <= 1.0:
        num_kept_samples = int(length * num_kept_samples)
        num_kept_samples = max(num_kept_samples, 1)

    if problem_type=="random":
        kept_inds = np.random.choice(length, num_kept_samples, replace=False)
    elif problem_type=="equal":
        kept_inds = np.linspace(0, length-1, num=num_kept_samples, dtype=int)
    elif problem_type=="forecast":
        kept_inds = np.arange(0, num_kept_samples)
    elif problem_type=="full":
        kept_inds = np.arange(0, length)
    elif problem_type=="log":
        kept_inds = np.geomspace(1, length, num=num_kept_samples, dtype=int) #geomspace can't take 0 as start index
        kept_inds = kept_inds - 1
        kept_inds = np.sort(kept_inds) #making the list unique
        for i in range(1, len(kept_inds)):
            if kept_inds[i] <= kept_inds[i-1]:
                kept_inds[i] = kept_inds[i-1] + 1
    elif problem_type=="sqrt":
        r = (length - 1.) / ((num_kept_samples - 1.)**2) #base quadratic factor
        kept_inds = [round(r * (s**2)) for s in range(num_kept_samples - 1)]
        kept_inds.append(length-1)
        kept_inds = np.array(kept_inds)
        kept_inds = np.sort(kept_inds) #making the list unique
        for i in range(1, len(kept_inds)):
            if kept_inds[i] <= kept_inds[i-1]:
                kept_inds[i] = kept_inds[i-1] + 1
    else:
        raise NotImplementedError("THIS PROBLEM TYPE IS UNSUPPORTED")

    missing_inds = np.array([t for t in range(length) if t not in kept_inds])

    return np.sort(kept_inds), np.sort(missing_inds)

def get_network_from_file(root_pth, chip_num):
    """
    Grabs an SK-RF Network and its associated metadata from a given root path
        and chip number.
    Different from grab_chip_data since this function returns the raw Network object
        and not np arrays.

    Args:
        root_pth: Root of the folder containing chip info.
        chip_num: Chip number.

    Returns:
        out_dict: Dictionary with relevant entries.
                  Entries:
                    network: The ground truth network.
                             Scikit-RF Network object.
                    fmin: Minimum frequency sampled.
                          Float.
                    fmax: Max frequency sampled.
                          Float.
                    length: The length of the channels.
                            String.
                    sweep: The spacing between sampled points.
                           String.
                    port_pairs: The paied ports on the chip.
                                Array of tuples.
    """
    from skrf import Network

    #Grab the correct folder
    chip_num = str(chip_num) if chip_num > 9 else "0" + str(chip_num)
    fname = os.path.join(root_pth, "case"+chip_num)

    net_str = str(chip_num) + ".s"
    desc_str = "description.txt"

    #grab the correct file we want
    children = os.listdir(fname)

    net_fpth = [f for f in children if net_str in f][0]
    net_fpth = os.path.join(fname, net_fpth)

    desc_fpth = [f for f in children if desc_str in f][0]
    desc_fpth = os.path.join(fname, desc_fpth)

    #grab the network and metadata
    out_network = Network(net_fpth)

    with open(desc_fpth) as file:
        lines = [line.rstrip() for line in file]

    fmin = None
    fmax = None
    length = None
    sweep = None
    port_pairs = []

    for line in lines:
        if "fmin" in line:
            fmin = float(line.split(" ")[-1])
        elif "fmax" in line:
            fmax = float(line.split(" ")[-1])
        elif "length" in line:
            length = line.split(" ")[-1]
        elif "sweep" in line:
            sweep = line.split(" ")[-1]
        elif "port_pair" in line:
            port1 = int(line.split(" ")[-2])
            port2 = int(line.split(" ")[-1])
            port_pairs.append((port1, port2))

    out_dict = {"network": out_network,
                "fmin": fmin,
                "fmax": fmax,
                "length": length,
                "sweep": sweep,
                "port_pairs": port_pairs}

    return out_dict

def network_to_sparams(network):
    """
    Converts a given Sk-RF network object into a [1, 2*N_-sparams, N_freqs] torch tensor.

    Args:
        network: sk-rf network object.

    Returns:
        [1, 2*N_sparams, N_freqs] torch tensor. Channel dimenson has reals
            on the even indices and their respective imag's on the odd indices.
    """
    re_mat = network.s.real
    im_mat = network.s.imag
    out_mat = np.stack((re_mat, im_mat), axis=-1)

    out_mat = out_mat.reshape((out_mat.shape[0], -1, out_mat.shape[-1])) #[FREQ, N_PORT^2, RE/IM]
    out_mat = out_mat.reshape((out_mat.shape[0], -1)).transpose() #[Re/im Sparams, FREQ]

    return torch.from_numpy(out_mat).unsqueeze(0).type(torch.float32)

def matrix_to_network(data_matrix, data_freqs, name, resample_freqs=None):
    """
    Takes a raw 4D sparam matrix and returns a Scikit-RF Network object.

    Args:
        data_matrix: Raw 4D sparam matrix.
                     (4D torch tensor) - Axes are [Freq, In_port, Out_port, Re/Im].
        data_freqs: Sampled frequencies. Must be same length as first axis of data_matrix.
                    (1D numpy array).
        name: The name of the network.
              (String)
        resample_freqs: Frequencies to resample the data to. Default is None.
                        (1D numpy array).

    Returns:
        net: A scikit-RF Network object.
    """
    from skrf import Network, Frequency

    #Convert the data properly to complex
    temp_data = data_matrix.detach().cpu().numpy().astype('float64')

    net_data = np.empty(temp_data.shape[:-1], dtype=np.complex128)
    net_data.real = temp_data[..., 0]
    net_data.imag = temp_data[..., 1]

    #Make the network
    net_freqs = Frequency.from_f(data_freqs, unit="hz")

    net = Network(frequency=net_freqs, s=net_data, name=name)

    #Check if we need to re-sample
    if resample_freqs is not None:
        new_freqs = Frequency.from_f(resample_freqs)
        net.resample(new_freqs)

    return net

def sparams_to_mag(sparams, get_phase=False, in_db=False):
    """
    Computes the magnitude, and optionally the phase, of a given complex signal.

    Args:
        sparams: Signal with real and imaginary components.
                 Torch tensor [1, 2*num_unique_sparams, F].
                 We expect the real and imaginary components for each s-parameter to be adjacent
                    channels in the second axis.
        get_phase: If True, returns the phase of the signal as well.
        in_db: If True, will return the magnitude in Decibels.

    Returns:
        mag: Magnitude of the given signal. If in_db is True, will be in Decibels.
             Torch tensor [1, num_unique_sparams, F].
        phase (optional): Phase of the given signal in radians. Only returned if get_phase is true.
                          Torch tensor [1, num_unique_sparams, F].
    """

    x_complex = torch.complex(sparams[:, ::2, :], sparams[:, 1::2, :]) #evens are real, odds are imaginary

    x_mag = torch.abs(x_complex)
    if in_db:
        x_mag = 20 * torch.log10(x_mag) #multiply here by 20 instead of 10 because abs is a square root term

    if get_phase:
        x_phase = torch.angle(x_complex)
        return x_mag, x_phase
    else:
        return x_mag

def plot_mags(sparams_list, freqs=None, chip_labels=None, not_reciprocal=False, plot_subset_list=None, ylims=False):
    mag_list = [sparams_to_mag(sparam) for sparam in sparams_list]

    num_ports = (-1 + np.sqrt(8*mag_list[0].shape[1] + 1)) // 2
    num_ports = int(num_ports)
    if not_reciprocal:
        num_ports = int(np.sqrt(mag_list[0].shape[1]))

    x = freqs if freqs is not None else [np.arange(mag_list[0].shape[-1])]*len(mag_list)
    labels = chip_labels if chip_labels is not None else np.arange(len(mag_list))

    if not_reciprocal:
        sparam_str_list = [str(s_idx//num_ports) + str(s_idx%num_ports) for s_idx in range(mag_list[0].shape[1])]
    else:
        sparam_str_list = []
        for i in range(num_ports):
            for j in range(i+1):
                sparam_str_list.append(str(i) + str(j))

    plot_chips = plot_subset_list if plot_subset_list is not None else np.arange(len(mag_list))

    fig, axs = plt.subplots((mag_list[0].shape[1] + 1) // 2, 2, figsize=(20,15))

    for s_idx in range(mag_list[0].shape[1]):
        if s_idx >= mag_list[0].shape[1]:
            break
        for chip_idx in plot_chips:
            axs[s_idx//2, s_idx%2].plot(x[chip_idx], mag_list[chip_idx][0, s_idx], label=str(labels[chip_idx]))
        axs[s_idx//2, s_idx%2].set_title(sparam_str_list[s_idx])
        axs[s_idx//2, s_idx%2].legend()
        if ylims:
            axs[s_idx//2, s_idx%2].set_ylim(0, 1)

    fig.tight_layout()

class Measurement_MSE_Loss(nn.Module):
    """
    Given a signal x, observed measurements y, and observed indices kept_inds,
        return the mse over the measurements of x vs true measurements y.

    Args:
        kept_inds: Array with the indices of the kept measurements.
        per_param: Whether to reduce the MSE for each S-param individually
                    before reducing the loss.
                   This can help with robustly fitting each S-param well.
        reduction: ["mean", "sum"]
    """

    def __init__(self, kept_inds, per_param=False, reduction="mean"):
        super().__init__()

        self.kept_inds = kept_inds
        self.per_param = per_param
        self.reduction = reduction

        if not self.per_param:
            self.mse_loss = nn.MSELoss(reduction=self.reduction)

    def forward(self, x, y):
        if not self.per_param:
            return self.mse_loss(x[:, :, self.kept_inds], y)

        else:
            square_error = torch.square(x[:, :, self.kept_inds] - y) #[1, 2 * N_sparams, m]

            if self.reduction == "mean":
                mse_per_chan = torch.mean(square_error, dim=2) #[1, 2 * N_sparams]
                rmse_per_chan = torch.sqrt(mse_per_chan) #[1, 2 * N_sparams]

                return torch.mean(rmse_per_chan)

            elif self.reduction == "sum":
                sse_per_chan = torch.sum(square_error, dim=2) #[1, 2 * N_sparams]
                rsse_per_chan = torch.sqrt(sse_per_chan) #[1, 2 * N_sparams]

                return torch.sum(rsse_per_chan)

class Smoothing_Loss(nn.Module):
    """
    Loss function that penalizes nth-order differences in a time series.

    Args:
        per_param: Whether to reduce the loss for each S-param individually
                    before reducing the loss.
                   This can help with robustly fitting each S-param well.
        reduction: ["mean", "sum"]
    """
    def __init__(self, per_param=False, reduction="mean", order=2, norm=2):
        super().__init__()

        self.per_param = per_param
        self.reduction = reduction
        self.order = order
        self.norm = norm

    def forward(self, x):
        if self.order == 2:
            diffs = torch.diff(torch.diff(x, dim=2), dim=2)
        elif self.order == 3:
            diffs = torch.diff(torch.diff(torch.diff(x, dim=2), dim=2), dim=2)

        if self.norm == 1:
            diffs = torch.abs(diffs)
        elif self.norm == 2:
            diffs = torch.square(diffs)

        if not self.per_param:
            if self.reduction == "mean":
                return torch.mean(diffs)
            elif self.reduction == "sum":
                return torch.sum(diffs)

        else:
            if self.reduction == "mean":
                loss_per_chan = torch.mean(diffs, dim=2) #[1, 2 * N_sparams]
                rloss_per_chan = torch.sqrt(loss_per_chan) #[1, 2 * N_sparams]

                return torch.mean(rloss_per_chan)

            elif self.reduction == "sum":
                loss_per_chan = torch.sum(diffs, dim=2) #[1, 2 * N_sparams]
                rloss_per_chan = torch.sqrt(loss_per_chan) #[1, 2 * N_sparams]

                return torch.sum(rloss_per_chan)


import arcade
import pygame
import math
import random
from copy import deepcopy

class simplePoint():

	def __init__(self, x, y):
		self.x = x
		self.y = y

	def __str__(self):
		return "x: " + str(self.x) + " y: " + str(self.y)

	def __repr__(self):
		return "x: " + str(self.x) + " y: " + str(self.y)

	def __eq__(self, point):
		return self.convert_to_tuple() == point.convert_to_tuple()

	def __ne__(self, point):
		return not self == point

	def convert_to_tuple(self):
		return (self.x, self.y)

	def draw(self, colour, size, surface):
		#arcade.draw_point(self.x, self.y, colour, size)
		pygame.draw.line(surface, colour, [self.x, self.y], [self.x, self.y], size)

class simpleEdge():

	def __init__(self, p1, p2):
		self.p1 = p1
		self.p2 = p2
		self.length = distance_between(p1, p2)

	def draw(self, colour, size, surface):
		#arcade.draw_line(self.p1.x, self.p1.y, self.p2.x, self.p2.y, colour, size)
		pygame.draw.line(surface, colour, [self.p1.x, self.p1.y], [self.p2.x, self.p2.y], size)

class simpleCircle():

	def __init__(self, centre, radius):
		self.centre = centre
		self.radius = radius

	def point_inside(self, point):
		dist = distance_between(self.centre, point)
		if (dist <= self.radius):
			return True
		else:
			return False

	def draw(self, colour, size, filled, surface):
		if (filled):
			#arcade.draw_circle_filled(self.centre.x, self.centre.y, self.radius, colour)
			pygame.draw.circle(surface, colour, [self.centre.x, self.centre.y], self.radius)
		else:
			#arcade.draw_circle_outline(self.centre.x, self.centre.y, self.radius, colour, size)
			pygame.draw.circle(surface, colour, [self.centre.x, self.centre.y], self.radius, size)

class simpleEllipse():

	def __init__(self, centre, xRadius, yRadius, angle):
		self.centre = centre
		self.xRadius = xRadius
		self.yRadius = yRadius
		self.angle = angle

	def point_inside(self, point):
		cosa=math.cos(self.angle)
		sina=math.sin(self.angle)
		dx=self.xRadius/2*self.xRadius/2
		dy=self.yRadius/2*self.yRadius/2

		a =math.pow(cosa*(point.x-self.centre.x)+sina*(point.y-self.centre.y),2)
		b =math.pow(sina*(point.x-self.centre.x)-cosa*(point.y-self.centre.y),2)
		ellipse=(a/dx)+(b/dy)

		if ellipse <= 1:
			return True
		else:
			return False

	def draw(self, colour, size, filled, surface):
		if (filled):
			#arcade.draw_ellipse_filled(self.centre.x, self.centre.y, self.xRadius, self.yRadius, colour, self.angle)
			aRect = pygame.Rect([self.centre.x - self.xRadius, self.centre.y - self.yRadius, self.xRadius*2, self.yRadius*2])
			aRect.normalize()
			pygame.draw.ellipse(surface, colour, aRect)
		else:
			#arcade.draw_ellipse_outline(self.centre.x, self.centre.y, self.xRadius, self.yRadius, colour, size, self.angle)
			aRect = pygame.Rect([self.centre.x - self.xRadius, self.centre.y - self.yRadius, self.xRadius*2, self.yRadius*2])
			aRect.normalize()
			pygame.draw.ellipse(surface, colour, aRect, size)

class simplePolygon():

	def __init__(self, pointList):
		self.points = pointList
		self.edges = []
		for i in range(len(self.points)):
			edge = (self.points[i],self.points[i-1])
			self.edges.append(edge)

	def point_inside(self, point):

		poly = deepcopy(self.points)
		n = len(poly)
		inside =False

		p1 = poly[0]
		for i in range(n+1):
			p2 = poly[i % n]
			if point.y > min(p1.y,p2.y):
				if point.y <= max(p1.y,p2.y):
					if point.x <= max(p1.x,p2.x):
						if p1.y != p2.y:
							xinters = (point.y-p1.y)*(p2.x-p1.x)/(p2.y-p1.y)+p1.x
						if p1.x == p2.x or point.x <= xinters:
							inside = not inside
			p1.x,p1.y = p2.x,p2.y

		return inside

	def draw(self, colour, size, filled, surface):
		pointList = []
		for point in self.points:
			pointList.append(point.convert_to_tuple())
		if (filled):
			pygame.draw.polygon(surface, colour, pointList, 0)
		else:
			pygame.draw.polygon(surface, colour, pointList, size)

def round_to_base(x, base=5):
    return int(base * round(float(x)/base))

def normalise(numberRange, newMin, newMax):
	oldMin = min(numberRange)
	oldMax = max(numberRange)
	output = []
	for x in numberRange:
		y = (((newMax - newMin) * (x - oldMin)) / (oldMax - oldMin)) + newMin
		output.append(y)
	return output

def normalise_angle(angle):
	adjustedAngle = 270 - angle
	if (adjustedAngle >= 360):
		adjustedAngle -= 360
	return adjustedAngle

def distance_between(p1, p2):
	x = p2.x - p1.x
	y = p2.y - p1.y
	return math.sqrt(x*x + y*y)

def angle_between(p1, p2):
	dy = p1.y - p2.y
	dx = p1.x - p2.x
	return math.degrees(math.atan2(dy, dx))

def midpoint(p1, p2):
	x = (p1.x + p2.x)/2
	y = (p1.y + p2.y)/2
	return simplePoint(x, y)

def generate_polygon(centre, minDist, maxDist, numberOfPoints, randomise=True):
	random.seed()
	angleRange = 360/numberOfPoints
	points = []
	for index in range(numberOfPoints):
		dist = random.uniform(minDist, maxDist)
		if (randomise):
			angle = math.radians(random.uniform(index * angleRange, (index + 1) * angleRange))
		else:
			angle = math.radians(angleRange)
		x = dist * math.sin(angle) + centre.x
		y = dist * math.cos(angle) + centre.y
		points.append(simplePoint(x, y))
	poly = simplePolygon(points)
	return poly


import numpy as np
import pandas as pd
import plotly.graph_objects as go
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input,Output
import plotly.express as px
import dash_table

# external CSS stylesheets
external_stylesheets = [
   {
       'href': 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css',
       'rel': 'stylesheet',
       'integrity': 'sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO',
       'crossorigin': 'anonymous'
   }
]

covid_19_data=pd.read_csv('covid_19_data.csv')
us_cities=pd.read_csv('time_series_covid_19_deaths_US.csv')
world_c=pd.read_csv('time_series_covid_19_confirmed.csv')
world_c1=world_c[['Country/Region','Lat','Long']]
world_c1.rename(columns={'Country/Region':'Country_Region'},inplace=True)
world_c_US=pd.read_csv('time_series_covid_19_confirmed_US.csv')
world_c_US2=world_c_US[['Country_Region','Lat','Long_']]
world_c_US2.rename(columns={'Long_':'Long'},inplace=True)
world=world_c1.append(world_c_US2)

fig2 = px.scatter_mapbox(world, lat=world["Lat"], lon=world["Long"], hover_name=world["Country_Region"],
                        color_discrete_sequence=["fuchsia"], zoom=.5, height=600)
fig2.update_layout(title='The corona virus affected Countries around the World : ',
    mapbox_style="white-bg",
    mapbox_layers=[
        {
            "below": 'traces',
            "sourcetype": "raster",
            "source": [
                "https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}"
            ]
        }
      ])

fig = go.Figure(data=go.Scattergeo(
        locationmode = 'USA-states',
        lon=us_cities["Long_"],
        lat=us_cities["Lat"],
        text=us_cities["Province_State"],
        mode = 'markers',
        marker = dict(
            size = 8,
            opacity = 0.8,
            reversescale = True,
            autocolorscale = False,
            symbol = 'square',
            line = dict(
                width=1,
                color='rgba(102, 102, 102)'
            ),
            colorscale = 'Blues',
            cmin = 0,
            colorbar_title="The Deeper the colour the more affected the city is : "
        )))
fig.update_layout(
        title = 'The corona virus affected Cities in US -',
        geo = dict(
            scope='usa',
            projection_type='albers usa',
            showland = True,
            landcolor = "rgb(250, 250, 250)",
            subunitcolor = "rgb(217, 217, 217)",
            countrycolor = "rgb(217, 217, 217)",
            countrywidth = 0.5,
            subunitwidth = 0.5
        ),
    )

countries=covid_19_data['Country/Region'].unique().tolist()
total_c=[]
total_r=[]
total_d=[]
for i in countries:
    new_df=covid_19_data[covid_19_data['Country/Region']==i]
    if(new_df['Province/State'].count() == 0 ):
        count_c=new_df.drop_duplicates(subset='Country/Region',keep='last')['Confirmed'].sum()
        total_c.append(count_c)
        count_r=new_df.drop_duplicates(subset='Country/Region',keep='last')['Recovered'].sum()
        total_r.append(count_r)
        count_d=new_df.drop_duplicates(subset='Country/Region',keep='last')['Deaths'].sum()
        total_d.append(count_d)
    else:
        count_c=new_df.drop_duplicates(subset='Province/State',keep='last')['Confirmed'].sum()
        total_c.append(count_c)
        count_r=new_df.drop_duplicates(subset='Province/State',keep='last')['Recovered'].sum()
        total_r.append(count_r)
        count_d=new_df.drop_duplicates(subset='Province/State',keep='last')['Deaths'].sum()
        total_d.append(count_d)
total_confirmed=np.sum(total_c)
total_recovered=np.sum(total_r)
total_death=np.sum(total_d)
active_cases=total_confirmed-(total_recovered+total_death)
closed_cases=(total_recovered+total_death)

data11={'Countries': countries, 'Total cases' : total_c}
df11=pd.DataFrame(data11)
data22={'Countries': countries, 'Total cases' : total_r}
df22=pd.DataFrame(data22)
data33={'Countries': countries, 'Total cases' : total_d}
df33=pd.DataFrame(data33)

option=[
    {'label':'Infected', 'value':'Infected'},
    {'label':'Countries-Recovered','value':'total_recovered'}
]

options=[
   {'label':'All', 'value':'All'},
   {'label':'Total Recovered', 'value':'total_recovered'},
   {'label':'Total Confirmed', 'value':'total_confirmed'},
   {'label':'Total Death', 'value':'total_death'}
]

app2 = dash.Dash(__name__, external_stylesheets=external_stylesheets)
server=app2.server

app2.title='Corona Pandemic'

app2.layout=html.Div([
    html.H5("updated on : 06/04/2020, Time : 11:00 ", style={ 'text-align':'right', 'padding':'1%', 'color':'#FFFFFF'}),
    html.H1("Corona Virus Pandemic Analysis", style={'text-align': 'center'}, className='title'),
    html.Img(className='image', src='https://cdn.kalingatv.com/wp-content/uploads/2020/03/Coronavirus-COVID-19.jpg', alt='covid-19 image',
             style={
                 'height': '400px',
                 'float': 'center',
                 'position': 'relative',}

             ),
    html.H4('The structure of a COVID-19 Virus',className='structure', style= {
                    'color' : '#fc172e',
                    'text-align' : 'center',
                    'font-size' : '2rem',
                    'font-weight' : 'bold',
                    'padding' : '1%',
    }),
    html.A("Link to external site- World Health Organization reports", href='https://www.who.int/emergencies/diseases/novel-coronavirus-2019', target="_blank"),
    html.Hr(className='hrtag'),
    html.Div([
        html.Div([
            html.Div([
                html.Div([
                    html.Img(className='title-image',
                             src="https://webassets.mongodb.com/_com_assets/cms/3D_medical_animation_coronavirus_structure-0kardto2r8.jpg",
                             alt='Picture of a covid 19 virus',
                             style={
                                 'height': '60%',
                                 'width': '60%',
                                 'float': 'left',
                                 'position': 'relative',
                                 'padding-top': 0,
                                 'padding-right': 0},
                             ),
                    html.P('People may be sick with the virus for 1 to 14 days before developing symptoms.'
                           ' The most common symptoms of coronavirus disease (COVID-19) are fever, tiredness, and dry cough. Most people (about 80%) '
                           'recover from the disease without needing special treatment.More rarely, the disease can be serious and even fatal. Older people, and people with other medical conditions '
                           '(such as asthma, diabetes, or heart disease), may be more vulnerable to becoming severely ill.', className='para'),
                    html.Hr(className='hrtag'),

                ],className='card-body')
            ],className='card')
        ],className='col-lg-12')
    ],className='row'),
    html.H3('Present Status Across the World :', className='title-bar', style= {
        'color':'#fc172e'
    }),
    html.Div([
        html.Div([
            html.Div([
                html.Div([

                    html.H3("Total Cases", style={'font-size':'20px'}),
                    html.H4(total_confirmed, className='text-light')
                ], className='card-body')
            ], className='card bg-danger')
        ], className='col-md-2'),
        html.Div([
            html.Div([
                html.Div([

                    html.H3("Active Cases",style={'font-size':'20px'}),
                    html.H4(active_cases, className='text-light')
                ], className='card-body')
            ], className='card bg-info')
        ], className='col-md-3'),
        html.Div([
            html.Div([
                html.Div([

                    html.H3("Closed Cases", style={'font-size':'20px'}),
                    html.H4(closed_cases, className='text-light')
                ], className='card-body')
            ], className='card bg-success')
        ], className='col-md-2'),
        html.Div([
            html.Div([
                html.Div([

                    html.H3("Total Recovered", style={'font-size':'20px'}),
                    html.H4(total_recovered, className='text-light')
                ], className='card-body')
            ], className='card bg-danger')
        ], className='col-md-3'),
        html.Div([
            html.Div([
                html.Div([
                    html.H3("Total Death", style={'font-size':'20px'}),
                    html.H4(total_death, className='text-light')
                ], className='card-body')
            ], className='card bg-danger')
        ], className='col-md-2')
    ], className='row top-label'),
    html.Div([
        html.Div([
            html.Div([
                html.Div([
                    html.Hr(className='hrtag'),
                    html.H3('Graphical Information of collected data around the world  :', className='h3-first'),
                    dcc.Dropdown(id='picker',options=options,value='All'),
                    dcc.Graph(id='scatter')
                ],className='card-body')
            ],className='card')
        ],className='col-md-12')
    ],className='row first-graph'),
    html.Div([
        html.Div([
            html.Div([
                html.Div([
                    html.Hr(className='hrtag'),
                    html.H3('Infected Vs Recovered :'),
                    dcc.Dropdown(id='pick',options=option,value='Infected'),
                    dcc.Graph(id='overview')
                ],className='card-body')
            ],className='card')
        ],className='col-md-12')
    ],className='row second-graph'),
    html.Div([
        html.Div([
            html.Div([
                html.Div([
                    html.Hr(className='hrtag'),
                    html.H3('World Map of Infection Covid-19 :'),
                    dcc.Graph(figure=fig2)
                ],className='card-body')
            ],className='card')
        ],className='col-lg-12')
    ],className='row third-graph'),
    html.Div([
        html.Div([
            html.Div([
                html.Div([
                    html.Hr(className='hrtag'),
                    html.H3('United States Map of Infection Covid-19 :'),
                    dcc.Graph(figure=fig)
                ],className='card-body')
            ],className='card')
        ],className='col-lg-12')
    ],className='row forth-graph'),
    html.Div([
        html.Div([
            html.Div([
                html.Div([
                    html.H2('Total Confirmed Cases :-'),
                    dash_table.DataTable(id='table1',columns=[{"name": i, "id": i} for i in df11.columns],
                    data=df11.to_dict('records'),
                    style_table={"overflowY":"scroll",'height': 500},style_cell={'textAlign': 'center'},
                                         style_cell_conditional=[
                                             {
                                                 'if': {'column_id': 'Countries'},
                                                 'textAlign': 'right'
                                             }
                                         ],style_header={
                                                     'fontWeight': 'bold',
                                             'backgroundColor': 'rgb(230, 230, 230)',
                                         },style_data_conditional=[ {
                                                     'if': {'row_index': 'odd'},
                                                     'backgroundColor': 'rgb(248, 248, 248)'
                                                                        }]
                                         )
                ],className='card-body table-format')
            ],className='card')
        ],className='col-lg-4'),
        html.Div([
            html.Div([
                html.Div([
                    html.H2('Total Recoved Cases :-'),
                    dash_table.DataTable(id='table2',columns=[{"name": j, "id": j} for j in df22.columns],
                    data=df22.to_dict('records'),style_table={"overflowY": "scroll",'height': 500},style_cell={'textAlign': 'center'},
                                         style_cell_conditional=[
                                             {
                                                 'if': {'column_id': 'Countries'},
                                                 'textAlign': 'right'
                                             }
                                         ],style_header={
                                                     'fontWeight': 'bold',
                                             'backgroundColor': 'rgb(230, 230, 230)',
                                         },style_data_conditional=[ {
                                                     'if': {'row_index': 'odd'},
                                                     'backgroundColor': 'rgb(248, 248, 248)'
                                                                        }]
                                         )
                ],className='card-body table-format')
            ],className='card')
        ],className='col-lg-4'),
        html.Div([
            html.Div([
                html.Div([
                    html.H2('Total Death cases :-'),
                    dash_table.DataTable(id='table3',columns=[{"name": k, "id": k} for k in df33.columns],
                    data=df33.to_dict('records'),style_table={"overflowY": "scroll",'height': 500},style_cell={'textAlign': 'center'},
                                         style_cell_conditional=[
                                             {
                                                 'if': {'column_id': 'Countries'},
                                                 'textAlign': 'right'
                                             }],style_header={
                                                     'fontWeight': 'bold',
                                             'backgroundColor': 'rgb(230, 230, 230)',
                                         },style_data_conditional=[ {
                                                     'if': {'row_index': 'odd'},
                                                     'backgroundColor': 'rgb(248, 248, 248)'
                                                                        }
                                         ])
                ],className='card-body table-format')
            ],className='card')
        ],className='col-lg-4')
    ],className='row'),
    html.Footer([
        html.Div(['© Copyright 2020 : ',
            html.A('Tuhin Mukherjee',href="https://whitexgod.github.io/cv/")
        ],className='footer-copyright text-center py-3',style={'color':'#fc172e'})
    ],className='page-footer font-small blue')
],className='container')

@app2.callback(Output('scatter','figure'), [Input('picker','value')])
def update_graph(type):

    if type=='All':

            pscat=covid_19_data.groupby('Last Update')['Confirmed'].sum().sort_values().reset_index()
            return {'data':[go.Scatter(x=pscat['Last Update'], y=pscat['Confirmed'], mode='markers', marker={'color':'#00a65a', 'size':8})],
               'layout':go.Layout(title='Line of Virus Spread per day', xaxis={'title':'By Date'}, yaxis={'title':'No. of cases'})}

    elif type=='total_confirmed':
            data1={'Countries': countries, 'Total cases' : total_c}
            df1=pd.DataFrame(data1)
            return {'data': [go.Bar(x=df1['Countries'], y=df1['Total cases'])],
               'layout': go.Layout(title='Total number of Confirmed cases across the world', xaxis={'title': 'Countries'}, yaxis = {'title': 'Number of Cases'})}

    elif type=='total_recovered':
            data2={'Countries': countries, 'Total cases' : total_r}
            df2=pd.DataFrame(data2)
            return {'data': [go.Bar(x=df2['Countries'], y=df2['Total cases'])],
               'layout': go.Layout(title='Total number of Recovered cases across the world',xaxis={'title': 'Countries'}, yaxis = {'title': 'Number of Cases'})}

    elif type=='total_death':
            data3={'Countries': countries, 'Total cases' : total_d}
            df3=pd.DataFrame(data3)
            return {'data': [go.Bar(x=df3['Countries'], y=df3['Total cases'])],
               'layout': go.Layout(title='Total number of Deaths cases across the world',xaxis={'title': 'Countries'}, yaxis = {'title': 'Number of Cases'})}

@app2.callback(Output('overview','figure'), [Input('pick','value')])
def update_graph(type):

    if type=='Infected':

        data4 = {'Countries': countries, 'Total cases': total_c}
        df4 = pd.DataFrame(data4)
        return {'data': [go.Pie(labels=df4['Countries'], values=df4['Total cases'])]}

    elif type=='total_recovered':

        data5 = {'Countries': countries, 'Total cases': total_r}
        df5 = pd.DataFrame(data5)
        return {'data': [go.Pie(labels=df5['Countries'], values=df5['Total cases'])]}

if __name__=="__main__":
   app2.run_server(debug=True)


#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
# Distributed under terms of the MIT license.

"""

"""
from pybatfish.client.commands import *
from pybatfish.question.question import load_questions, list_questions
from pybatfish.question import bfq
from pybatfish.datamodel.flow import HeaderConstraints
import os
import tempfile

def create_inline_snapshot(text, format="cisco"):
    """ Create a quick inline snapshot """

    HOSTNAME = "TEST_INLINE"
    ACL_TEXT = """
    !RANCID-CONTENT-TYPE: {format}
    hostname {hostname}
    {text}
    """.format(format=format, hostname=HOSTNAME, text=text)
    temp = tempfile.TemporaryDirectory(prefix='bf_acl.')
    snap_dir = os.path.join(temp.name, 'configs')
    snap_filename = os.path.join(snap_dir, HOSTNAME)
    os.makedirs(snap_dir)
    with open(snap_filename, 'w') as outfile:
        outfile.write(ACL_TEXT)

    bf_set_network('__inline_snap')
    return bf_init_snapshot(temp.name)

if __name__ == "__main__":
    acl_def = """
    no ip access-list extended TEST_ACL
    ip access-list extended TEST_ACL
    10 permit tcp any any
    20 permit udp any any
    30 deny tcp any any eq ssh
    """

    load_questions()
    snap_gen = create_inline_snapshot(acl_def)
    print("#"*100)
    print("TEST ACL LINE REACHABILITY (here seq 30 should be useless and thus 'unreachable')")
    reacha = bfq.filterLineReachability().answer(snap_gen)
    print(reacha.frame())
    print("#"*100)
    print("CHECK IF ACL REALLY BLOCKS THE PACKET SPECIFIED")
    test_behav = bfq.searchfilters(
        action="permit", headers=HeaderConstraints(
            applications=["ssh"], srcIps="1.2.3.4", dstIps="4.5.6.7"
            )
        ).answer()
    print(test_behav)
    print("#"*100)
    print("DEFINES ON WHICH ENTRY THE PACKET SPECIFIED IS MATCHED")
    test_acl = bfq.testfilters(
        headers=HeaderConstraints(
            applications=["ssh"], srcIps="1.2.3.4", dstIps="4.5.6.7"
            )
        ).answer()
    print(test_acl)


from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtGui import QFontDatabase
from PyQt5.QtWidgets import QMessageBox, QDialog

from gui.code_edit import Ui_CodeEditDialog
from src.gui.file_transfer_dialog import FileTransferDialog
from src.utility.settings import Settings

class CodeEditDialog(QDialog, Ui_CodeEditDialog):
    mcu_file_saved = pyqtSignal()

    def __init__(self, parent, connection):
        super(CodeEditDialog, self).__init__(None, Qt.WindowCloseButtonHint)
        self.setupUi(self)

        geometry = Settings().retrieve_geometry("editor")
        if geometry:
            self.restoreGeometry(geometry)

        self._connection = connection

        self.saveLocalButton.clicked.connect(self._save_local)
        self.saveMcuButton.clicked.connect(self._save_to_mcu)
        #self.runButton.clicked.connect(self._run_file)
        self.runButton.hide()

        fixed_font = QFontDatabase.systemFont(QFontDatabase.FixedFont)
        self.codeEdit.setFont(fixed_font)

        if connection and connection.is_connected():
            self.connected(connection)
        else:
            self.disconnected()

    def closeEvent(self, event):
        Settings().update_geometry("editor", self.saveGeometry())
        super(CodeEditDialog, self).closeEvent(event)

    def disconnected(self):
        self._connection = None
        self.saveMcuButton.setEnabled(False)

    def connected(self, connection):
        self._connection = connection
        self.saveMcuButton.setEnabled(True)

    def _save_local(self):
        path = self.localPathEdit.text()
        if not path:
            QMessageBox.warning(self, "Invalid path", "Enter correct path for local file.")
            return

        try:
            with open(path, "w") as file:
                file.write(self.codeEdit.toPlainText())
        except IOError:
            QMessageBox.critical(self, "Save operation failed", "Couldn't save the file. Check path and permissions.")

    def _save_to_mcu(self):
        name = self.remotePathEdit.text()
        if not name:
            QMessageBox.warning(self, "Invalid name", "Enter correct name for remote file.")
            return

        content = self.codeEdit.toPlainText()
        if not content:
            QMessageBox.warning(self, "Empty file", "Can't write empty file.")
            return

        progress_dlg = FileTransferDialog(FileTransferDialog.UPLOAD)
        progress_dlg.finished.connect(self.mcu_file_saved.emit)
        progress_dlg.show()
        self._connection.write_file(name, content, progress_dlg.transfer)

    def set_code(self, local_path, remote_path, code):
        self.codeEdit.clear()
        self.codeEdit.setText(code)
        self.localPathEdit.setText(local_path if local_path else "")
        self.remotePathEdit.setText(remote_path if remote_path else "")


import os
import traceback

import grpc

from tensorflow.core.debug import debug_service_pb2
from tensorflow.python.client import session
from tensorflow.python.debug.lib import grpc_debug_test_server
from tensorflow.python.debug.lib import source_remote
from tensorflow.python.debug.lib import source_utils
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import math_ops
# Import resource_variable_ops for the variables-to-tensor implicit conversion.
from tensorflow.python.ops import resource_variable_ops  # pylint: disable=unused-import
from tensorflow.python.ops import variables
from tensorflow.python.platform import googletest
from tensorflow.python.platform import test
from tensorflow.python.util import tf_inspect

def line_number_above():
  return tf_inspect.stack()[1][2] - 1

class SendTracebacksTest(test_util.TensorFlowTestCase):

  @classmethod
  def setUpClass(cls):
    test_util.TensorFlowTestCase.setUpClass()
    (cls._server_port, cls._debug_server_url, cls._server_dump_dir,
     cls._server_thread,
     cls._server) = grpc_debug_test_server.start_server_on_separate_thread(
         poll_server=True)
    cls._server_address = "localhost:%d" % cls._server_port
    (cls._server_port_2, cls._debug_server_url_2, cls._server_dump_dir_2,
     cls._server_thread_2,
     cls._server_2) = grpc_debug_test_server.start_server_on_separate_thread()
    cls._server_address_2 = "localhost:%d" % cls._server_port_2
    cls._curr_file_path = os.path.normpath(os.path.abspath(__file__))

  @classmethod
  def tearDownClass(cls):
    # Stop the test server and join the thread.
    cls._server.stop_server().wait()
    cls._server_thread.join()
    cls._server_2.stop_server().wait()
    cls._server_thread_2.join()
    test_util.TensorFlowTestCase.tearDownClass()

  def tearDown(self):
    ops.reset_default_graph()
    self._server.clear_data()
    self._server_2.clear_data()
    super(SendTracebacksTest, self).tearDown()

  def _findFirstTraceInsideTensorFlowPyLibrary(self, op):
    """Find the first trace of an op that belongs to the TF Python library."""
    for trace in op.traceback:
      if source_utils.guess_is_tensorflow_py_library(trace.filename):
        return trace

  def testSendGraphTracebacksToSingleDebugServer(self):
    this_func_name = "testSendGraphTracebacksToSingleDebugServer"
    with session.Session() as sess:
      a = variables.Variable(21.0, name="a")
      a_lineno = line_number_above()
      b = variables.Variable(2.0, name="b")
      b_lineno = line_number_above()
      math_ops.add(a, b, name="x")
      x_lineno = line_number_above()

      send_stack = traceback.extract_stack()
      send_lineno = line_number_above()
      source_remote.send_graph_tracebacks(
          self._server_address, "dummy_run_key", send_stack, sess.graph)

      tb = self._server.query_op_traceback("a")
      self.assertIn((self._curr_file_path, a_lineno, this_func_name), tb)
      tb = self._server.query_op_traceback("b")
      self.assertIn((self._curr_file_path, b_lineno, this_func_name), tb)
      tb = self._server.query_op_traceback("x")
      self.assertIn((self._curr_file_path, x_lineno, this_func_name), tb)

      self.assertIn(
          (self._curr_file_path, send_lineno, this_func_name),
          self._server.query_origin_stack()[-1])

      self.assertEqual(
          "      a = variables.Variable(21.0, name=\"a\")",
          self._server.query_source_file_line(__file__, a_lineno))
      # Files in the TensorFlow code base shouldn not have been sent.
      tf_trace = self._findFirstTraceInsideTensorFlowPyLibrary(a.op)
      tf_trace_file_path = tf_trace.filename
      with self.assertRaises(ValueError):
        self._server.query_source_file_line(tf_trace_file_path, 0)
      self.assertEqual([debug_service_pb2.CallTraceback.GRAPH_EXECUTION],
                       self._server.query_call_types())
      self.assertEqual(["dummy_run_key"], self._server.query_call_keys())
      self.assertEqual(
          [sess.graph.version], self._server.query_graph_versions())

  def testSendGraphTracebacksToTwoDebugServers(self):
    this_func_name = "testSendGraphTracebacksToTwoDebugServers"
    with session.Session() as sess:
      a = variables.Variable(21.0, name="two/a")
      a_lineno = line_number_above()
      b = variables.Variable(2.0, name="two/b")
      b_lineno = line_number_above()
      x = math_ops.add(a, b, name="two/x")
      x_lineno = line_number_above()

      send_traceback = traceback.extract_stack()
      send_lineno = line_number_above()

      with test.mock.patch.object(
          grpc, "insecure_channel",
          wraps=grpc.insecure_channel) as mock_grpc_channel:
        source_remote.send_graph_tracebacks(
            [self._server_address, self._server_address_2],
            "dummy_run_key", send_traceback, sess.graph)
        mock_grpc_channel.assert_called_with(
            test.mock.ANY,
            options=[("grpc.max_receive_message_length", -1),
                     ("grpc.max_send_message_length", -1)])

      servers = [self._server, self._server_2]
      for server in servers:
        tb = server.query_op_traceback("two/a")
        self.assertIn((self._curr_file_path, a_lineno, this_func_name), tb)
        tb = server.query_op_traceback("two/b")
        self.assertIn((self._curr_file_path, b_lineno, this_func_name), tb)
        tb = server.query_op_traceback("two/x")
        self.assertIn((self._curr_file_path, x_lineno, this_func_name), tb)

        self.assertIn(
            (self._curr_file_path, send_lineno, this_func_name),
            server.query_origin_stack()[-1])

        self.assertEqual(
            "      x = math_ops.add(a, b, name=\"two/x\")",
            server.query_source_file_line(__file__, x_lineno))
        tf_trace = self._findFirstTraceInsideTensorFlowPyLibrary(a.op)
        tf_trace_file_path = tf_trace.filename
        with self.assertRaises(ValueError):
          server.query_source_file_line(tf_trace_file_path, 0)
        self.assertEqual([debug_service_pb2.CallTraceback.GRAPH_EXECUTION],
                         server.query_call_types())
        self.assertEqual(["dummy_run_key"], server.query_call_keys())
        self.assertEqual([sess.graph.version], server.query_graph_versions())

  def testSendEagerTracebacksToSingleDebugServer(self):
    this_func_name = "testSendEagerTracebacksToSingleDebugServer"
    send_traceback = traceback.extract_stack()
    send_lineno = line_number_above()
    source_remote.send_eager_tracebacks(self._server_address, send_traceback)

    self.assertEqual([debug_service_pb2.CallTraceback.EAGER_EXECUTION],
                     self._server.query_call_types())
    self.assertIn((self._curr_file_path, send_lineno, this_func_name),
                  self._server.query_origin_stack()[-1])

  def testGRPCServerMessageSizeLimit(self):
    """Assert gRPC debug server is started with unlimited message size."""
    with test.mock.patch.object(
        grpc, "server", wraps=grpc.server) as mock_grpc_server:
      (_, _, _, server_thread,
       server) = grpc_debug_test_server.start_server_on_separate_thread(
           poll_server=True)
      mock_grpc_server.assert_called_with(
          test.mock.ANY,
          options=[("grpc.max_receive_message_length", -1),
                   ("grpc.max_send_message_length", -1)])
    server.stop_server().wait()
    server_thread.join()

if __name__ == "__main__":
  googletest.main()


import os
import numpy as np
import pandas as pd
import torch
from torch.utils.data import DataLoader
from sklearn.model_selection import train_test_split

from utils import CofigDataset
from spectral_analysis import linear_classifier
from utils_BASiS import train_model, modelEvaluataion, sampleAnchors

import warnings
warnings.simplefilter("ignore", UserWarning)

# hyper parameters MNIST
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
classes = ('0', '1', '2', '3', '4',
           '5', '6', '7', '8', '9')
classNum = len(classes)

anchors_per_class = 25
anchors_num = classNum * anchors_per_class

batch_size = 512 - anchors_num
iter_num = 1000

# graph parameters
ms = 10
ms_normal = 7
sigmaFlag = 0

# RANSAC parameters
ransac_nIter = 100
ransac_tol = 0.1
ransac_nPoints = 20

# siamese features
train_features_list_pd = pd.read_pickle(
    r"../MNIST/Features/MNIST/mnist_train_siamese_features_list_pd.pkl")
test_features_list_pd = pd.read_pickle(
    r"../MNIST/Features/MNIST/mnist_test_siamese_features_list_pd.pkl")

train_features_list_np = np.array(train_features_list_pd.drop(['label'], axis=1))
train_features_list_torch = torch.from_numpy(train_features_list_np)
print("Train features shape:")
print(train_features_list_torch.shape)

train_labels_np = np.array(train_features_list_pd.label)
train_labels_list_torch = torch.from_numpy(train_labels_np)
print("Train labels shape:")
print(train_labels_list_torch.shape)

test_features_list_np = np.array(test_features_list_pd.drop(['label'], axis=1))
featrues_test = torch.from_numpy(test_features_list_np)
print("Test features shape:")
print(featrues_test.shape)

test_labels_np = np.array(test_features_list_pd.label)
labels_test = torch.from_numpy(test_labels_np)
print("Test labels shape:")
print(labels_test.shape)

featrues_train, featrues_val, labels_train, labels_val = train_test_split(train_features_list_torch,
                                                                          train_labels_list_torch, test_size=0.2,
                                                                          random_state=0)

if not os.path.exists('./results'):
    os.mkdir('./results')
    os.mkdir('./results/MNIST')

model_path = r".\results\MNIST\save_MNIST"
if not os.path.exists(model_path):
    os.mkdir(model_path)
    os.mkdir(model_path + '/images')
    os.mkdir(model_path + '/linear_classifier')

anchors_index, not_anchors_index = sampleAnchors(labels_test, anchors_per_class, classNum)
X_anchors = featrues_test[anchors_index]
X_not_anchors = featrues_test[not_anchors_index]

y_anchors = labels_test[anchors_index]
y_not_anchors = labels_test[not_anchors_index]

xTrain = torch.cat((X_anchors, featrues_train), dim=0)
yTrain = torch.cat((y_anchors, labels_train), dim=0)

xValid = torch.cat((X_anchors, featrues_val), dim=0)
yValid = torch.cat((y_anchors, labels_val), dim=0)

xTest = torch.cat((X_anchors, X_not_anchors), dim=0)
yTest = torch.cat((y_anchors, y_not_anchors), dim=0)

print('xTrain shape:')
print(xTrain.shape)
print('xValid shape:')
print(xValid.shape)
print('xTest shape:')
print(xTest.shape)

model, U_sampled_base = train_model(xTrain, yTrain, xValid, yValid, classes, anchors_per_class, anchors_num,
                                    batch_size, ms, ms_normal, sigmaFlag, ransac_nPoints, ransac_nIter, ransac_tol,
                                    iter_num, model_path, device)
torch.save(U_sampled_base, model_path + '/U_sampled.pt')
torch.save(xTest, model_path + '/xTest.pt')
torch.save(yTest, model_path + '/yTest.pt')

nmi, acc, grassmann, orthogonality = modelEvaluataion(model, xTest, yTest, U_sampled_base, classes, ms,
                                                          ms_normal, sigmaFlag, anchors_num,
                                                          ransac_nPoints, ransac_nIter, ransac_tol)

# linear regression
model_path = model_path + '/linear_classifier'

model.eval()  # put in evaluation mode
with torch.no_grad():
    encoded_xTrain = model(xTrain.float())
    encoded_xValid = model(xValid.float())
    encoded_xTest = model(xTest.float())

train_iter = CofigDataset(encoded_xTrain, yTrain)
train_loader = torch.utils.data.DataLoader(train_iter, batch_size=batch_size, shuffle=True, drop_last=True)
valid_iter = CofigDataset(encoded_xValid, yValid)
valid_loader = torch.utils.data.DataLoader(valid_iter, batch_size=batch_size, shuffle=False, drop_last=True)
test_iter = CofigDataset(encoded_xTest, yTest)
test_loader = torch.utils.data.DataLoader(test_iter, batch_size=batch_size, shuffle=False, drop_last=True)

test_accuracy = linear_classifier(train_loader, valid_loader, test_loader, encoded_xTrain, classes, model_path,
                                       device)

print("---------Test Eval -----------")
print("Test NMI: ", nmi)
print("Test ACC: ", acc)
print("Test Grassmann: ", grassmann)
print("Test Orthogonality: ", orthogonality)
print("Test Accuracy: ", test_accuracy)


from Contacto import Contacto
from io import BufferedReader, BufferedWriter
import os

class Agenda:

    def __init__(self, listaContacto = [], path = os.getcwd() + "\\agenda.txt") -> None:
        self.__ListaContacto    = listaContacto
        self.__Path             = path

    def getListaContacto(self):

        return self.__ListaContacto

    def setListaContacto(self, listaContacto):

        self.__ListaContacto = listaContacto

    def getPath(self):

        return self.__Path

    def setPath(self, path):

        self.__Path = path

    def cargarContacto(self):

        if (os.path.exists(self.__Path)):

            f  : BufferedReader = open(self.__Path, "r")

            lineas = f.readlines()

            for linea in lineas :

                self.__crearContactoFichero(linea)

            f.close()

    def __crearContactoFichero(self, linea):

        datos = linea.split(";")

        #Correo,Calle,Piso,Ciudad,CodigoPostal,Nombre,Apellido,FellaNacimiento,TMovil,TTrabajo,TFijo
        contacto : Contacto = Contacto()

        contacto.setEmail(datos[0])
        contacto.setCalle(datos[1])
        contacto.setPiso(datos[2])
        contacto.setCiudad(datos[3])
        contacto.setCodigoPostal(datos[4])
        contacto.setNombre(datos[5])
        contacto.setApellido(datos[6])
        contacto.setFNacimiento(datos[7])
        contacto.setTMovil(datos[8])
        contacto.setTTrabajo(datos[9])
        contacto.setTFijo(datos[10])

        self.__ListaContacto.append(contacto)

    def crearContacto(self):

        correo      = input("Correo Electronico : ")
        calle       = input("Calle : ")
        piso        = input("Piso : ")
        ciudad      = input("Ciudad : ")
        cPostal     = input("Codigo Postal : ")
        nombre      = input("Nombre : ")
        apellido    = input("Apellido : ")
        fNacimiento = input("Fecha Nacimiento : ")
        tMovil      = input("Telefono Movil : ")
        tTrabajo    = input("Telefono Trabajo : ")
        tFijo       = input("Telefono Fijo : ")

        contacto : Contacto = Contacto(correo)
        contacto.setCalle(calle)
        contacto.setPiso(piso)
        contacto.setCiudad(ciudad)
        contacto.setCodigoPostal(cPostal)
        contacto.setNombre(nombre)
        contacto.setApellido(apellido)
        contacto.setFNacimiento(fNacimiento)
        contacto.setTMovil(tMovil)
        contacto.setTTrabajo(tTrabajo)
        contacto.setTFijo(tFijo)

        self.__ListaContacto.append(contacto)

    def guardarContactos(self):

        # Crear Fichero
        try:

            f : BufferedWriter = open(self.__Path,"w+")

        except FileExistsError:

            print("ya esta creado")

        else:

            for contacto in self.__ListaContacto :

                contacto : Contacto = contacto

                linea  = contacto.getEmail() + ";" + contacto.getCalle() + ";" + contacto.getPiso() + ";" + contacto.getCiudad() + ";" + contacto.getCodigoPostal() + ";" + contacto.getNombre() + ";" + contacto.getApellido() + ";" + contacto.getFNacimiento() + ";" + contacto.getTMovil() + ";" + contacto.getTTrabajo() + ";" + contacto.getTFijo()

                f.write(linea)

            f.flush()

            f.close()

    def mostrarAgenda(self):

        for contacto in self.__ListaContacto :

            contacto : Contacto = contacto

            print("----------------CONTACTO--------------")

            print(contacto.mostrarContacto())

            print("--------------------------------------")

    def buscarContactoPorNombre(self, nombre):

        for contacto in self.__ListaContacto :

            if (contacto.getNombre().lower() == nombre.lower()):

                print("----------------CONTACTO--------------")

                print(contacto.mostrarContacto())

                print("--------------------------------------")

    def borrarContactoPorNombre(self, nombre):

        posicion = 0
        salir = False

        while (posicion < len(self.__ListaContacto) and not(salir)):

            contacto : Contacto = self.__ListaContacto[posicion]

            if (contacto.getNombre().lower() == nombre.lower()):

                salir = True
                print("Contacto a Borrar : " , nombre)
                self.__ListaContacto.pop(posicion)

            posicion += 1

        if (not(salir)):

            print("Contacto no encontrado")

    def buscarContactoPorNumero(self, telefono):

        for contacto in self.__ListaContacto :

            if (contacto.getTMovil().lower() == telefono.lower()):

                print("----------------CONTACTO--------------")

                print(contacto.mostrarContacto())

                print("--------------------------------------")

    def borrarContactoPorNumero(self, telefono):

        posicion = 0
        salir = False

        while (posicion < len(self.__ListaContacto) and not(salir)):

            contacto : Contacto = self.__ListaContacto[posicion]

            if (contacto.getTMovil().lower() == telefono.lower()):

                salir = True
                print("Contacto a Borrar : " , telefono)
                self.__ListaContacto.pop(posicion)

            posicion += 1

        if (not(salir)):

            print("Contacto no encontrado")


import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn.utils import shuffle
from sklearn.metrics import accuracy_score
from flaskr.task2 import data_cleansing, get_data
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression,SGDClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import cross_val_score
from sklearn.svm import SVC,LinearSVC
import matplotlib.pyplot as plt
from sklearn.model_selection import learning_curve
import numpy as np
from sklearn.model_selection import ShuffleSplit
from sklearn.neural_network import MLPClassifier
import json

def load_data(file_path,split_percentage):
    #use get_data method
    df=get_data(file_path)
    df=data_cleansing(df)
    # the shuffle function alters the data seq
    df = shuffle(df)
    input_val = df.drop('target', axis=1).values
    output_val = df['target'].values

    split_point = int(len(input_val) * split_percentage)
    input_train = input_val[:split_point]
    output_train = output_val[:split_point]
    input_test = input_val[split_point:]
    output_test = output_val[split_point:]

    return input_train, output_train, input_test, output_test

# 0 incurrs person is healthy
# 1 incurrs person is infected
def assign_labels(row):
    if row['target']==0:
        return 0
    else:
        return 1

# assign labels to exisitng data frame based on target values
def load_labelled_data(split_percentage):
    file_path='processed.cleveland.data'
    df=get_data(file_path)
    df=data_cleansing(df)
    df=shuffle(df)
    # add column label which is derived from target
    df['label']=df.apply(lambda row: assign_labels(row), axis=1)
    # remove label and target columns as they won't be a part of user input
    input_data=df.drop(['label','target'], axis=1).values
    output_data=df['label'].values
    # define split point
    split_point = int(len(input_data) * split_percentage)
    # split data to train and test values
    input_train=input_data[:split_point]
    output_train=output_data[:split_point]
    input_test=input_data[split_point:]
    output_test=output_data[split_point:]

    return input_train,output_train,input_test,output_test

# UserData should be a list of user inputs
# for eg [[34.0,1.0,1.0,118.0,182.0,0.0,2.0,174.0,0.0,0.0,1.0,0.0,3.0]]
def predict_data(UserData):
    input_train, output_train, _, _ = load_labelled_data(split_percentage=0.99)
    GNB=GaussianNB()
    GNB.fit(input_train,output_train)
    #print(GNB.predict(UserData).tolist())
    # return values are either [0] or [1] depending if person is healthy or infected
    return (GNB.predict(UserData))

# return the accurcy of each classifier
def accuracy_analysis():
    iris_X, iris_y, _, _ = load_labelled_data(split_percentage=1)
    classifiers = [KNeighborsClassifier(),
                   DecisionTreeClassifier(),
                   LinearDiscriminantAnalysis(),
                   LogisticRegression(solver="lbfgs",max_iter=2000),
                   GaussianNB(priors=None, var_smoothing=1e-09),
                   SGDClassifier(max_iter=1000, tol=1e-3),
                   MLPClassifier(solver='lbfgs', alpha=1e-5,hidden_layer_sizes=(5, 2), random_state=1)]
    classifier_accuracy_list = []
    for i, classifier in enumerate(classifiers):
        # split the dataset into 5 folds; then test the classifier against each fold one by one
        accuracies = cross_val_score(classifier, iris_X, iris_y, cv=10)
        classifier_accuracy_list.append((accuracies.mean(), type(classifier).__name__))
    classifier_accuracy_list = sorted(classifier_accuracy_list, reverse=True)
    for item in classifier_accuracy_list:
        print(item[1], ':', item[0])
    return classifier_accuracy_list

def plot_learning_curve(estimator, title, X, y, ylim=(0.7, 1.01), cv=None,
                        n_jobs=None, train_sizes=np.linspace(.1, 1.0, 5)):
    plt.figure()
    plt.title(title)
    if ylim is not None:
        plt.ylim(*ylim)
    # assign labels to coordinates
    plt.xlabel("Training examples")
    plt.ylabel("Score")
    train_sizes, train_scores, test_scores = learning_curve(
        estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
    train_scores_mean = np.mean(train_scores, axis=1)
    train_scores_std = np.std(train_scores, axis=1)
    test_scores_mean = np.mean(test_scores, axis=1)
    test_scores_std = np.std(test_scores, axis=1)
    plt.grid()

    plt.fill_between(train_sizes, train_scores_mean - train_scores_std,
                     train_scores_mean + train_scores_std, alpha=0.1,
                     color="r")
    plt.fill_between(train_sizes, test_scores_mean - test_scores_std,
                     test_scores_mean + test_scores_std, alpha=0.1, color="g")
    plt.plot(train_sizes, train_scores_mean, 'o-', color="r",
             label="Training score")
    plt.plot(train_sizes, test_scores_mean, 'o-', color="g",
             label="Cross-validation score")

    plt.legend(loc="best")
    return plt

def build_json(estimator=GaussianNB(),n_jobs=4,train_sizes=np.linspace(.1, 1.0, 5)):
    X, y, _, _ = load_labelled_data(split_percentage=0.90)
    cv = ShuffleSplit(n_splits=100, test_size=0.2, random_state=0)
    train_sizes, train_scores, test_scores = learning_curve(
        estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
    train_scores_mean = np.mean(train_scores, axis=1)
    train_scores_std = np.std(train_scores, axis=1)
    test_scores_mean = np.mean(test_scores, axis=1)
    test_scores_std = np.std(test_scores, axis=1)
    result=[]
    obj={}

    title={}
    title['text']=type(estimator).__name__
    obj['title']=title

    xAxis={}
    title['text']='Accuracy'
    xAxis['title']=title
    obj['xAxis']=xAxis

    yAxis={}
    title['text']='Iterations'
    yAxis['title']=title
    obj['yAxis']=yAxis

    #series property
    series=[]
    #line1 data
    line1={}
    line1['name']='Training score'
    data=[]
    for i,j in zip(train_sizes,train_scores_mean):
        data_sub=[]
        data_sub.append(float(i))
        data_sub.append(float(j))
        data.append(data_sub)
    line1['data']=data
    line1['zIndex']=1
    marker={}
    marker['fillColor']='white'
    marker['lineWidth']=2
    marker['lineColor']='red'
    line1['marker']=marker
    line1['lineColor']='red'
    series.append(line1)
    range1={}
    range1['name']='Range1'
    data=[]
    for i,j,k in zip(train_sizes,train_scores_mean-train_scores_std,train_scores_mean+train_scores_std):
        data_sub=[]
        data_sub.append(float(i))
        data_sub.append(float(j))
        data_sub.append(float(k))
        data.append(data_sub)
    range1['data']=data
    range1['type']='arearange'
    range1['lineWidth']=0
    range1['linkedTo']=':previous'
    range1['color']='rgb(196, 10, 0)'
    range1['fillOpacity']=0.2
    range1['zIndex']=0
    marker={}
    marker['enabled']="false"
    range1['marker']=marker
    series.append(range1)
    #line2 data
    line2={}
    line2['name']='Test Score'
    data=[]
    for i,j in zip(train_sizes,test_scores_mean):
        data_sub=[]
        data_sub.append(float(i))
        data_sub.append(float(j))
        data.append(data_sub)
    line2['data']=data
    line2['zIndex']=2
    marker={}
    marker['fillColor']='white'
    marker['lineWidth']=2
    marker['lineColor']='green'
    line2['marker']=marker
    line2['lineColor']='green'
    series.append(line2)
    range2={}
    range2['name']='Range2'
    data=[]
    for i,j,k in zip(train_sizes,test_scores_mean-test_scores_std,test_scores_mean+test_scores_std):
        data_sub=[]
        data_sub.append(float(i))
        data_sub.append(float(j))
        data_sub.append(float(k))
        data.append(data_sub)
    range2['data']=data
    range2['type']='arearange'
    range2['lineWidth']=0
    range2['linkedTo']=':previous'
    range2['color']='rgb(19, 196, 0)'
    range2['fillOpacity']=0.2
    range2['zIndex']=0
    marker={}
    marker['enabled']="false"
    range2['marker']=marker
    series.append(range2)

    obj['series']=series
    # obj=json.dumps(obj)
    result.append(obj)
    return result

if __name__ == '__main__':
    file_path='processed.cleveland.data'

    # input_train, output_train, input_test, output_test = load_labelled_data(split_percentage=1)
    estimator = GaussianNB()
    # title = "Learning Curves (Naive Bayes)"
    # cv = ShuffleSplit(n_splits=100, test_size=0.2, random_state=0)
    # plot_learning_curve(DecisionTreeClassifier(), title, input_train, output_train, ylim=(0.5, 1.01), cv=cv, n_jobs=4)
    # plt.show()
    '''estimators=[KNeighborsClassifier(),
                   DecisionTreeClassifier(),
                   LinearDiscriminantAnalysis(),
                   LogisticRegression(solver="lbfgs",max_iter=2000),
                   GaussianNB(priors=None, var_smoothing=1e-09),
                   SGDClassifier(max_iter=1000, tol=1e-3),
                   ]'''
    '''To use the build_json function use any estimator mentioned above'''
    #For eg. build_json(GaussianNB())
    json_data=build_json(estimator)
    print(json_data)


from prettytable import PrettyTable
from utils import *

class Node:

   def __init__(self, name):
       self.parent = 0
       self.name = name
       self.edges = []
       self.value = 0

class Edge:
   #self ist der Konstruktor
   def __init__(self, edge):
      self.start = edge[0]
      self.end = edge[1]
      self.value = edge[2]

class Graph:

   def __init__(self, node_list, edges):
      self.nodes = []
      for name in node_list:
         self.nodes.append(Node(name))

      for e in edges:
        e = (getNode(e[0],self.nodes), getNode(e[1], self.nodes), e[2])

        self.nodes[next((i for i,v in enumerate(self.nodes) if v.name == e[0].name), -1)].edges.append(Edge(e))
        self.nodes[next((i for i,v in enumerate(self.nodes) if v.name == e[1].name), -1)].edges.append(Edge((e[1], e[0], e[2])))

   def print(self):
      node_list = self.nodes

      t = PrettyTable(['  '] +[i.name for i in node_list])
      for node in node_list:
         edge_values = ['X'] * len(node_list)
         for edge in node.edges:
            edge_values[ next((i for i,e in enumerate(node_list) if e.name == edge.end.name) , -1)] = edge.value
         t.add_row([node.name] + edge_values)
      print(t)

romania = Graph( ['Or', 'Ne', 'Ze', 'Ia', 'Ar', 'Si', 'Fa',
 'Va', 'Ri', 'Ti', 'Lu', 'Pi', 'Ur', 'Hi',
 'Me', 'Bu', 'Dr', 'Ef', 'Cr', 'Gi'],
[
   ('Or', 'Ze', 71), ('Or', 'Si', 151),
   ('Ne', 'Ia', 87), ('Ze', 'Ar', 75),
   ('Ia', 'Va', 92), ('Ar', 'Si', 140),
   ('Ar', 'Ti', 118), ('Si', 'Fa', 99),
   ('Si', 'Ri', 80), ('Fa', 'Bu', 211),
   ('Va', 'Ur', 142), ('Ri', 'Pi', 97),
   ('Ri', 'Cr', 146), ('Ti', 'Lu', 111),
   ('Lu', 'Me', 70), ('Me', 'Dr', 75),
   ('Dr', 'Cr', 120), ('Cr', 'Pi', 138),
   ('Pi', 'Bu', 101), ('Bu', 'Gi', 90),
   ('Bu', 'Ur', 85), ('Ur', 'Hi', 98),
   ('Hi', 'Ef', 86)
])

class Queue:
    procedure = 'lifo'
    structeredData = list()

    def __init__(self, procedure):
        if (procedure in {'lifo', 'fifo', 'prio'}):
            self.procedure = procedure
            self.structeredData = list()
        else:
            print("Invalid Constructor Parameter")

    def push(self, data):
      if (self.procedure == 'lifo'):
         self.structeredData.insert(0, data)
      elif (self.procedure == 'fifo'):
         self.structeredData.append(data)
      elif (self.procedure == 'prio'):
         total_cost, node = data
         index = 0
         while (index < len(self.structeredData) and int(self.structeredData[index][0]) < total_cost):
               index += 1
         if (index >= len(self.structeredData)):
               self.structeredData.append((total_cost, node))
         else:
               self.structeredData.insert(index, (total_cost, node))

    def pop(self):
        if (not self.structeredData):  # empty Queue
            print('Queue is empty!!')
            return None
        else:
            return self.structeredData.pop(0)

    def contains(self, value):
        for element in self.structeredData:
            if(value == element):
                return True
        return False

    def empty(self):
        return (not self.structeredData)

    def contains(self, val):
        return val in self.structeredData

    def print(self):
        for element in self.structeredData:
            print(element, end=' , ')
        print('')

#nachbarn aus der adjazenzmatrix entnehmen
def neighbors(node_name):
   map = []
   for node in romania.nodes:
      if(node.name == node_name):
         for edges in node.edges:
            map.append({
                  "from": edges.start.name,
                  "to": edges.end.name,
                  "cost": edges.value
                })

   return map

"""
liste = adj_matrix('Or')
for edge in liste:
        print(edge['cost'])
"""
# minimum total cost - takes the cheapest path

def ucs(start_node,end_node):
    visited = set()
    queue = Queue('prio')
    start = getNode(start_node,romania.nodes)
    queue.push((0,start))
    paths = {start: [start]}
    while not queue.empty():
        r = queue.pop()
        cost = int(r[0])
        node = r[1]

        if node not in visited:
            visited.add(node)

            if node.name == end_node:
                return paths[node]
            n = neighbors(node.name)
            for neigh in n:
                toNode = getNode(neigh['to'], romania.nodes)
                if toNode not in visited:
                    total_cost = cost + int(neigh['cost'])
                    if toNode not in paths:
                        paths[toNode] = paths[node] + [toNode]
                    queue.push((total_cost,toNode))

def bfs(start_node, end_node):
    visited = []
    queue = Queue('fifo')
    start = getNode(start_node,romania.nodes)
    end = getNode(end_node,romania.nodes)
    queue.push(start)
    while not queue.empty():
        node = queue.pop()
        if node == end:
            visited.append(node)
            break
        if node not in visited:
            visited.append(node)
           #print(node.name)
            n = neighbors(node.name)
            for neighbour in n:
                neighbor_node = getNode(neighbour['to'], romania.nodes)
                if neighbor_node not in visited:
                    neighbor_node.parent = node
                    queue.push(neighbor_node)
    if end not in visited:
        print("Ziel nicht enthalten!")
        return []
    path = []
    node = end
    while node != start:
        path.insert(0, node)
        node = node.parent
    path.insert(0, start)
    return path

def dfs(start_node, end_node, path=None, visited=None):
    if path is None:
        path = []
    if visited is None:
        visited = set()

    start = getNode(start_node, romania.nodes)

    path.append(start)
    visited.add(start)

    if start.name == end_node:

        return path
    n = neighbors(start.name)
    for neigh in n:
        new_neigh = getNode(neigh['to'],romania.nodes)
        if new_neigh not in visited:
            result = dfs(neigh['to'], end_node, path, visited)
            if result is not None:
                return result
    path.pop()
    return path

bfs_test = bfs("Bu","Ti")
for t in bfs_test:
    print("BFS " +t.name)
print("\n")

dfs_test = dfs("Bu", "Ti")

for t in dfs_test:
    print( "DFS " + t.name)

print("\n")

ucs_test = ucs("Bu", "Ti")

for t in ucs_test:
    print("UCS " +t.name)


# -*- coding: utf-8 -*-

import yaml

from bag.core import BagProject

from analog_ec.layout.dac.rladder.core import ResLadderDAC

if __name__ == '__main__':
    with open('specs_test/analog_ec/rdac/unit.yaml', 'r') as f:
        block_specs = yaml.load(f)

    local_dict = locals()
    if 'bprj' not in local_dict:
        print('creating BAG project')
        bprj = BagProject()

    else:
        print('loading BAG project')
        bprj = local_dict['bprj']

    bprj.generate_cell(block_specs, ResLadderDAC, debug=True)
    # bprj.generate_cell(block_specs, ResLadderDAC, gen_sch=True, run_lvs=True, debug=True)


# 1. chain.from_iterable():
# This function is implemented similarly as a chain() but the argument
# here is a list of lists or any other iterable container.
# 2. It takes only one argument and argument needs to be 2D container.
import itertools

l1 = [1, 2, 3]
l2 = [4, 5, 6]
l3 = [7, 8, 9]
t1 = (1, 2, 3)

l4 = [t1, l2]
t2 = (l1, l2)

print(list(itertools.chain.from_iterable(t1)))


import sys
import os
import wave
import struct
import logging
import numpy as np

from time import time
from optparse import OptionParser
from kaldiasr.nnet3 import KaldiNNet3OnlineModel, KaldiNNet3OnlineDecoder

class DecoderWorker:
    def __init__(self, modeldir='/opt/kaldi/model/kaldi-generic-de-tdnn_f'):
        logging.basicConfig(level=logging.DEBUG)
        logging.debug('%s loading model...' % modeldir)
        time_start = time()

        kaldi_model = KaldiNNet3OnlineModel(
            modeldir, acoustic_scale=1.0, beam=7.0, frame_subsampling_factor=3)
        logging.debug('%s loading model... done, took %fs.' %
                      (modeldir, time()-time_start))

        logging.debug('%s creating decoder...' % modeldir)
        time_start = time()
        self.decoder = KaldiNNet3OnlineDecoder(kaldi_model)
        logging.debug('%s creating decoder... done, took %fs.' %
                      (modeldir, time()-time_start))

    def decode(self, wavfile):
        time_start = time()
        logging.debug('starting to decode...')
        if self.decoder.decode_wav_file(wavfile):
            s, l = self.decoder.get_decoded_string()

            logging.debug("%s decoding took %8.2fs, likelyhood: %f" %
                          (wavfile, time() - time_start, l))
            print(s)
            return s

        else:
            logging.error("decoding of %s failed." % wavfile)
            return None


# -*- coding: utf-8 -*-
from django.contrib import admin
from models import Category, Photo

class PhotoInline(admin.TabularInline):
    list_display = ('image', )
    model = Photo
    extra = 10

class CategoryAdmin(admin.ModelAdmin):
    inlines = [ PhotoInline, ]
    list_display = ('title', 'year')

admin.site.register(Category, CategoryAdmin)


import datetime
import gocept.amqparchive.testing
import gocept.amqprun.interfaces
import gocept.amqprun.testing
import gocept.testing.mock
import os
import shutil
import tempfile
import time
import zope.event

class IndexTest(gocept.amqparchive.testing.TestCase):

    def setUp(self):
        super(IndexTest, self).setUp()
        self.patches = gocept.testing.mock.Patches()

    def tearDown(self):
        self.patches.reset()
        super(IndexTest, self).tearDown()

    def create_message(self, body='<foo>testbody</foo>'):
        from gocept.amqprun.message import Message
        message = Message({}, body, routing_key='routing')
        message.header.message_id = 'myid'
        message.header.timestamp = time.mktime(
            datetime.datetime(2011, 7, 14, 14, 15).timetuple())
        return message

    def test_indexes_body_and_headers(self):
        message = self.create_message()
        zope.event.notify(gocept.amqprun.interfaces.MessageStored(
            message, '/foo/bar'))
        time.sleep(1)  # give elasticsearch time to settle
        result = self.elastic.search({'query': {'text': {'_all': 'foo'}}})
        hits = result['hits']
        self.assertEqual(1, hits['total'])
        item = hits['hits'][0]['_source']
        self.assertEqual('/foo/bar', item['path'])
        self.assertEqual('testbody', item['data']['foo'])
        self.assertEqual('myid', item['message_id'])

    def test_exceptions_are_logged_and_not_raised(self):
        message = self.create_message()
        index = self.patches.add_object(self.elastic, 'index')
        index.side_effect = RuntimeError('provoked')

        log_warning = self.patches.add_object(
            gocept.amqparchive.archive.log, 'warning')
        zope.event.notify(gocept.amqprun.interfaces.MessageStored(
            message, '/foo/bar'))
        self.assertTrue(log_warning.called)

    def test_invalid_xml_does_not_break_indexing(self):
        message = self.create_message('<qux')
        zope.event.notify(gocept.amqprun.interfaces.MessageStored(
            message, '/foo/bar'))
        time.sleep(1)  # give elasticsearch time to settle
        result = self.elastic.search({'query': {'text': {'_all': 'qux'}}})
        hits = result['hits']
        self.assertEqual(1, hits['total'])

class IndexIntegrationTest(gocept.amqprun.testing.MainTestCase,
                           gocept.amqparchive.testing.ElasticHelper):

    level = 3
    layer = gocept.amqparchive.testing.QUEUE_LAYER

    def setUp(self):
        super(IndexIntegrationTest, self).setUp()
        self.tmpdir = tempfile.mkdtemp()

    def tearDown(self):
        shutil.rmtree(self.tmpdir)
        super(IndexIntegrationTest, self).tearDown()

    def test_message_should_be_indexed(self):
        self.make_config(__name__, 'index', mapping=dict(
            routing_key='test.data',
            directory=self.tmpdir,
            queue_name=self.get_queue_name('test'),
            pattern='foo/bar/baz.xml',
            elastic_hostname=os.environ['ELASTIC_HOSTNAME']))
        self.start_server()

        body = '<foo>This is only a test.</foo>'
        self.send_message(body, routing_key='test.data')
        self.wait_for_processing()
        # we're concurrent to the handler and we seem to be too fast
        time.sleep(2)

        self.assertEqual(
            2, len(os.listdir(os.path.join(self.tmpdir, 'foo', 'bar'))))
        result = self.elastic.search({'query': {'text': {'_all': 'only'}}})
        self.assertEqual(1, result['hits']['total'])
        hit = result['hits']['hits'][0]
        self.assertEqual('foo/bar/baz.xml', hit['_source']['path'])


import pygame, sys, playgo
import config as c
import draw
from pygame.locals import *

def displayGame(gridsize, player1, player2, DISPLAY, FPSCLOCK):
	score_file = open("scores.txt", 'r+')
	words = score_file.read()
	DISPLAY.fill(c.TAN)

	if player1.resigned:
		winner = player2.name
	else:
		winner = player1.name

	gameOverLabel = draw.Label(c.STARTSCREENFONT, 45, False, " Game Over ", c.BLACK, 0.5, 0.3)
	winnerLabel = draw.Label(c.STARTSCREENFONT, 45, False,  winner + "wins!", c.BLACK, 0.5, .5, 0,)

	newGameLabel = draw.Label(c.STARTSCREENFONT, 30, False, " New Game ", c.BLACK, 0.5, .8, -150, 0)
	newGameLabel.drawRect(DISPLAY, c.WHITE, 100, 200, 0)
	newGameLabel.drawRect(DISPLAY, c.BLACK, 101, 201, 1)

	quitLabel = draw.Label(c.STARTSCREENFONT, 30, False, "     Quit     ", c.BLACK, 0.5, .8, 150, 0)
	quitLabel.drawRect(DISPLAY, c.WHITE, 100, 200, 0)
	quitLabel.drawRect(DISPLAY, c.BLACK, 101, 201, 1)

	DISPLAY.blit(gameOverLabel.labelText, gameOverLabel.labelRect)
	DISPLAY.blit(winnerLabel.labelText, winnerLabel.labelRect)
	DISPLAY.blit(newGameLabel.labelText, newGameLabel.labelRect)
	DISPLAY.blit(quitLabel.labelText, quitLabel.labelRect)

	newGame = False
	cont = True
	while cont:
		mousePress = False
		for event in pygame.event.get():
			if event.type == MOUSEBUTTONUP:
				if event.button == 1:
					mousex, mousey = event.pos
					mousePress = True
			elif event.type == MOUSEMOTION:
					mousex, mousey = event.pos
			elif event.type == KEYUP:
				if event.key == K_ESCAPE:
					pygame.quit()
					sys.exit()

		if mousePress:
			if newGameLabel.labelRect.collidepoint(mousex, mousey):
				newGame = True
				cont = False
			elif quitLabel.labelRect.collidepoint(mousex, mousey):
				newGame = False
				cont = False

		pygame.display.update()

	return newGame


from bs4 import BeautifulSoup
import requests

def matching_words(string_1, string_2):
    count = 0
    string_1 = string_1.split()

    for word in string_1:
        if word in string_2:
            count += 1
    return count

def good_match(string, num_matching_words):
    string = string.split()
    str_len = len(string)
    if str_len > 0:
        percent =(float(num_matching_words)*100/float(str_len))
        if percent >= 50:
            return True
    return False

def get_data(url):
    try:
        result      = requests.get(url)
        soup        = BeautifulSoup(result.text, "html.parser")
        thumbnails  = []
        title       = ""

        if "amazon.com" in url:
            soup_title  = soup.find("span",id="productTitle")
            soup_img    = soup.find_all("img", id="landingImage")

            if not soup_img:
                return {"error":1,"data":{},"message":"Unable to extract images."}
            else:
                for img in soup_img:
                    if img["src"] not in thumbnails:
                        thumbnails.append(img["src"])

                if soup_title:
                    title = soup_title.string

            return {"error":None,"data":{"title":title, "thumbnails":thumbnails},"message":"Success"}

        elif "ebay.com" in url:
            soup_title = soup.find("h1", id="itemTitle")
            soup_img = soup.find_all("img", id="icImg")

            if not soup_img:
                return {"error":1,"data":{},"message":"Unable to extract images."}
            else:
                for img in soup_img:
                    if img["src"] not in thumbnails:
                        thumbnails.append(img["src"])

                if soup_title:
                    children = []
                    for child in soup_title.children:
                        children.append(child)
                    title = children[1]

            return {"error":None,"data":{"title":title, "thumbnails":thumbnails},"message":"Success"}

        else:
            title = soup.title.string
            for img in soup.find_all("img", alt=True):
                alt = img['alt']
                src = img['src']
                numMatchingWords = matching_words(title,alt)
                if good_match(alt, numMatchingWords):
                    if src not in thumbnails and src[-4:]==".jpg" and "sprite" not in src:
                        thumbnails.append(src)

            if not thumbnails:
                for img in soup.findAll("img", src=True):
                    if "sprite" not in img["src"] and src[-4:]==".jpg":
                        thumbnails.append(img["src"])

            if not thumbnails:
                return {"error":1,"data":{},"message":"Unable to extract images."}

            return {"error":None,"data":{"title":title, "thumbnails":thumbnails},"message":"Success"}

    except requests.exceptions.RequestException:
        return {"error":2,"data":{},"message":"URL entered is invalid."}

url1 = "http://www.ebay.com/itm/ROLEX-Day-Date-II-Presidential-w-Factory-Diamond-Bezel-Dial-218348-/172103028001?hash=item281223cd21:g:gRcAAOSwezVWwhkv"
url2 = "http://intl.target.com/p/mr-coffee-cafe-barista-bvmc-ecmp1000/-/A-14575718#prodSlot=_1_8"
url3 = "http://www.amazon.com/gp/product/B00THKEKEQ/ref=s9_ri_gw_g421_i1_r?ie=UTF8&fpl=fresh&pf_rd_m=ATVPDKIKX0DER&pf_rd_s=desktop-4&pf_rd_r=1WEK74K6Y8MXQC6BSHDN&pf_rd_t=36701&pf_rd_p=2437869562&pf_rd_i=desktop"
url4 = "http://www.amazon.com/gp/product/B012GC5DX8/ref=s9_qpp_gw_d38_g107_i1_r?ie=UTF8&fpl=fresh&pf_rd_m=ATVPDKIKX0DER&pf_rd_s=desktop-1&pf_rd_r=0HX3HCEVK96HB5FDXMV0&pf_rd_t=36701&pf_rd_p=2437869742&pf_rd_i=desktop"
url5 = "http://www.ebay.com/itm/Lamborghini-Aventador-LP-750-4-SV-/231914556159?forcerrptr=true&hash=item35ff2f4aff:g:4ckAAOSwiYFXESqj&item=231914556159"
url6 = "http://www.amazon.com/Hifonics-ZRX2416-1D-Block-Vehicle-Amplifier/dp/B00T3VMTPQ?ie=UTF8&refRID=PX2YE82MNZZBNBDCRWSS&ref_=pd_ybh_a_1"
url7 = "http://www.amazon.com/Power-Acoustik-GW312-1200WATT-2500WATT/dp/B00B7C077G?ie=UTF8&psc=1&redirect=true&ref_=ox_sc_sfl_title_5&smid=A35DL6C7BAXYRR"
url8 = "http://www.ebay.com/itm/Apple-12-MacBook-Intel-Core-M-1-1GHz-8GB-RAM-256GB-Flash-Early-2015-Gold/262417285736?hash=item3d194a0268&_trkparms=5374%3AFeatured%7C5373%3A0"

#print get_data(url1)
#print get_data(url2)
#print get_data(url3)
#print get_data(url4)
#print get_data(url5)
#print get_data(url6)
#print get_data(url7)
#print get_data(url8)


#!/usr/bin/python3
import requests
import datetime
## Define NEOW URL
NEOURL = "https://api.nasa.gov/neo/rest/v1/feed?"

def validate_date(date_text):
        try:
            datetime.date.fromisoformat(date_text)
        except ValueError:
            raise ValueError("Incorrect data format, should be YYYY-MM-DD")

# this function grabs our credentials
# it is easily recycled from our previous script
def returncreds():
    ## first I want to grab my credentials
    with open("/home/student/nasa.creds", "r") as mycreds:
        nasacreds = mycreds.read()
    ## remove any newline characters from the api_key
    nasacreds = "api_key=" + nasacreds.strip("\n")
    return nasacreds

# this is our main function
def main():
    ## first grab credentials
    nasacreds = returncreds()
    print('Start date in YYYY-MM-DD format or just hit enter')
    sdate=input('>')
    if sdate:
        validate_date(sdate)
        startdate = "start_date="+sdate
    else:
        startdate = "start_date=2019-11-11"
    ## update the date below, if you like
    startdate = "start_date=2019-11-11"

    ## the value below is not being used in this
    ## version of the script
    # enddate = "end_date=END_DATE"

    # make a request with the request library
    neowrequest = requests.get(NEOURL + startdate + "&" + nasacreds)

    # strip off json attachment from our response
    neodata = neowrequest.json()

    ## display NASAs NEOW data
    print(neodata)

if __name__ == "__main__":
    main()