#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import \
    print_function, unicode_literals, absolute_import, division

import unittest
import roboptim.core
import numpy, numpy.testing
import pickle
import os
from concurrent.futures import ProcessPoolExecutor, as_completed

class Square (roboptim.core.PyDifferentiableFunction):
    def __init__ (self):
        roboptim.core.PyDifferentiableFunction.__init__ \
            (self, 1, 1, "square function")

    def impl_compute (self, result, x):
        result[0] = x[0] * x[0]

    def impl_gradient (self, result, x, f_id):
        result[0] = 2. * x[0]

class SquareJacobian (roboptim.core.PyDifferentiableFunction):
    def __init__ (self):
        roboptim.core.PyDifferentiableFunction.__init__ \
            (self, 1, 1, "square function")

    def impl_compute (self, result, x):
        result[0] = x[0] * x[0]

    def impl_gradient (self, result, x, f_id):
        raise NotImplementedError

    def impl_jacobian (self, result, x):
        result[0,0] = 2. * x[0]

class DoubleSquare (roboptim.core.PyDifferentiableFunction):
    def __init__ (self):
        roboptim.core.PyDifferentiableFunction.__init__ \
            (self, 1, 2, "double square function")

    def impl_compute (self, result, x):
        result[0] = x[0] * x[0]
        result[1] = x[0] * x[0]

    def impl_gradient (self, result, x, f_id):
        result[0] = 2. * x[0]

def test_function_multiprocess (args):
    f = args[0]
    x = args[1]
    i = args[2]
    print (f (x))
    return i, f (x)

class TestFunctionPy(unittest.TestCase):
    def test_function(self):
        class F(roboptim.core.PyFunction):
            def __init__ (self):
                roboptim.core.PyFunction.__init__ (self, 1, 1, "dummy function")

            def impl_compute (self, result, x):
                result[0] = 42.

        f = F()
        print (f.inputSize ())
        print (f.outputSize ())
        print (f.name ())
        x = numpy.array ([1.,])
        print ("f: %s" % f)
        print ("x = %s" % x)
        print ("f(x) = %s" % f (x))
        self.assertEqual (f (x), [42.])
        self.assertEqual ("dummy function (not differentiable)", "%s" % f)

    def test_differentiable_function(self):
        f = Square ()
        print (f.inputSize ())
        print (f.outputSize ())
        print (f.name ())
        x = numpy.array ([6.,])
        print ("f: %s" % f)
        print ("x = %s" % x)
        print ("f(x) = %s" % f (x))
        self.assertEqual (f (x), x[0] * x[0])
        print ("df(x) = %s" % f.gradient (x, 0))
        self.assertEqual (f.gradient (x, 0), 2. * x[0])
        self.assertEqual ("square function (differentiable function)", "%s" % f)

    def test_differentiable_function_jacobian(self):
        f = SquareJacobian ()
        print (f.inputSize ())
        print (f.outputSize ())
        print (f.name ())
        x = numpy.array ([6.,])
        print ("f: %s" % f)
        print ("x = %s" % x)
        print ("f(x) = %s" % f (x))
        self.assertEqual (f (x), x[0] * x[0])
        #self.assertRaises(NotImplementedError, lambda: f.gradient (x, 0))
        print ("Jac(f)(x) = %s" % f.jacobian (x))
        self.assertEqual (f.jacobian (x), 2. * x[0])
        self.assertEqual ("square function (differentiable function)", "%s" % f)

    def test_function_pickle(self):
        f = SquareJacobian ()
        file_name = "test_function_pickle.dump"
        dump_file = open (file_name,'wb')
        pickle.dump (f,dump_file)
        dump_file.close ()

        dump_file = open (file_name,'rb')
        f_pickled = pickle.load (dump_file)
        dump_file.close ()

        os.remove(file_name)

        # Compare f and f_pickled
        x = numpy.array ([6.,])
        print ("f: %s" % f)
        print ("f_pickled: %s" % f_pickled)
        print ("f(x) = %s" % f (x))
        print ("f_pickled(x) = %s" % f_pickled (x))
        self.assertEqual (f (x), f_pickled (x))
        print ("Jac(f)(x) = %s" % f.jacobian (x))
        print ("Jac(f_pickled)(x) = %s" % f_pickled.jacobian (x))
        self.assertEqual (f.jacobian (x), f_pickled.jacobian (x))

        def done_callback(future):
            idx, value = future.result()
            print("%i ---> %s" % (idx, value))
            self.assertEqual (idx**2, value)

        # Test scenario: multiprocess
        with ProcessPoolExecutor(max_workers=4) as executor:
            res = numpy.zeros (4)
            jobs = [executor.submit(test_function_multiprocess,
                    (f, numpy.array ([i]), i)) \
                    .add_done_callback(done_callback)
                    for i in range(4)]

    def test_problem(self):
        cost = Square()
        self.assertEqual ("square function (differentiable function)", "%s" % cost)
        problem = roboptim.core.PyProblem (cost)
        print (problem)
        self.assertEqual (problem.constraints, [])

    def test_solver(self):
        cost = Square()
        problem = roboptim.core.PyProblem (cost)
        self.assertFalse (problem.startingPoint)
        problem.startingPoint = numpy.array([0.,])
        self.assertEqual (problem.startingPoint, [0.])

        problem.argumentBounds = numpy.array([[-3.,4.],])
        numpy.testing.assert_almost_equal (problem.argumentBounds, [[-3.,4.],])

        problem.argumentScaling = numpy.array([2.,])
        numpy.testing.assert_almost_equal (problem.argumentScaling, [2.,])

        g1 = Square ()
        problem.addConstraint (g1, [-1., 10.,])

        g2 = DoubleSquare ()
        problem.addConstraint (g2, numpy.array ([[-1., 10.],[2., 3.]]))

        g3 = Square ()
        problem.addConstraint (g3, [-1., 10.,], 0.1)

        g4 = DoubleSquare ()
        problem.addConstraint (g4, numpy.array ([[-1., 10.],[2., 3.]]), [0.1, 0.2])

        self.assertEqual (problem.constraints, [g1, g2, g3, g4])

        solver = roboptim.core.PySolver ("ipopt", problem)
        print (solver)

        solver.solve ()
        r = solver.minimum ()
        print (r)

        # Add a new dummy parameter
        parameters = dict()
        parameters["dummy"] = tuple(("dummy description",
                                     "dummy value"))
        assert "dummy" in parameters
        assert parameters["dummy"][0] == "dummy description"
        assert parameters["dummy"][1] == "dummy value"
        solver.parameters = parameters

        print (solver)

        test_parameters = list()
        test_parameters.append (("foo_int", 42, "an integer"))
        test_parameters.append (("foo_double", 12., "a scalar"))
        test_parameters.append (("foo_bool", False, "a boolean"))
        test_parameters.append (("foo_str", "foo", "a string"))
        test_parameters.append (("foo_vec", numpy.array ([1., 2., 3., 4.]), "a vector"))

        for p in test_parameters:
            solver.setParameter (p[0], p[1], p[2])

        parameters = solver.parameters
        print(parameters)
        print(parameters["dummy"][0])
        print(parameters["dummy"][1])
        assert "dummy" in parameters
        assert parameters["dummy"][0] == "dummy description".encode('utf-8')
        assert parameters["dummy"][1] == "dummy value".encode('utf-8')

        for p in test_parameters:
            assert p[0] in parameters
            if isinstance (p[1], (str)):
                val = p[1].encode ('utf-8')
            else:
                val = p[1]
            assert parameters[p[0]][0] == p[2].encode ('utf-8')
            # NumPy check
            if type(val).__module__ == numpy.__name__:
                assert numpy.array_equal(parameters[p[0]][1], val)
            else:
                assert parameters[p[0]][1] == val

        print (solver)

if __name__ == '__main__':
    unittest.main()


#!/usr/bin/env python3
import os
import re

def get_file_list():
    files = [file for file in os.listdir() if re.findall('.[AaMm][KkPpVv][4IiVv]$', file)]

    return files

def rename_files(files):
    for file in files:
        file_name, file_ext = os.path.splitext(file)

        try:
            mod_name = re.split('[?:0-9]', file_name)[0]
            rel_year = re.findall('.[0-9][0-9][0-9][0-9].', file_name)[0].strip('.()')
            new_name = re.sub('\.', ' ', mod_name).strip('()') + '(' + rel_year + ')' + file_ext.lower()
            # new_name = str(re.findall('Crazy', file_name)[0]).upper() + file_ext.lower()

            if file == new_name:
                print(f'{file}: nothing to do')
            else:
                print(f'renamed: {new_name}')

                os.rename(file, new_name)
        except IndexError:
            print('error: no files to rename')
            exit(1)

def main():
    files = get_file_list()

    if len(files) < 1:
        exit(1)
    else:
        rename_files(files)

if __name__ == '__main__':
    main()


#!/usr/bin/env python
# -----------------------
# Supplementary Material for Deith and Brodie 2020; “Predicting defaunation – accurately mapping bushmeat hunting pressure over large areas”
#    doi: 10.1098/rspb.2019-2677
#------------------------
# Code to iterate through GFLOW results files, modify the outputs based on
#     human population density, and then sum this into a final cumulative
#     accessibility map.
#
# This script uses maps created with 'MSYBorneo_ResistanceMapLayers_Preparation.py'
#   and GFLOW.
# Created by Mairin Deith on Nov12 2017
# Last edited on Nov15 2019
#------------------------

# Import libraries
import os, sys
import subprocess
import gdal
import re
import glob
import rasterio as rio
import numpy as np
from pathlib import Path
from datetime import datetime
from collections import defaultdict

### HELPER FUNCTIONS
# From https://stackoverflow.com/questions/5419204/index-of-duplicates-items-in-a-python-list
# This function passes through a list and keeps a list of locations seen for each item,
#   and returns items seen more than once

def list_duplicates(seq):
    tally = defaultdict(list)
    for i,item in enumerate(seq):
        tally[item].append(i)
    return ((key,locs) for key,locs in tally.items()
                            if len(locs)>1)

def list_singles(seq):
    tally = defaultdict(list)
    for i,item in enumerate(seq):
        tally[item].append(i)
    return ((key,locs) for key,locs in tally.items()
                            if len(locs)==1)

### GLOBAL INFO
# File paths/gdalcalc paths

basedir = os.path.abspath('/home/mairin/Documents/GradSchool/Research/CircuitTheory_Borneo/Revised_CTMapCreation/')
basefname = 'ClusterOutput_Summation'

walk_types = ['AllNodes','VillageSabah','VillageSabahOther'] # types of nodes to identify from gazetteers

for w in walk_types:
    if w == 'AllNodes':
        rivers = ['impassableRivers', 'passableRivers'] #, 'passableRivers'] # uncomment after untarred
    else:
        rivers = ['impassableRivers']
    for r in rivers:
        print(w+", " + r)
        src_dir = os.path.join(basedir, 'SourceSinks_WalkingOnly_'+w, r,'NodesTSV')
        out_dir = os.path.join(basedir, 'GFlowOutputs','ClusterFlexOutputs', 'SepTmpOutputs_Walking'+w, r)
        asc_dir = out_dir
        output_fname = basefname + '_Walking' + w + '_' + r + '.asc'
        cum_outmap = os.path.join(asc_dir, output_fname)
        if os.path.exists(cum_outmap): # Don't bother if the file doesn't exist
            exists = True
            delete = str(input("\n\nShould the existing map (%s) be deleted?\n'Y' for yes, 'N' for no > " %(os.path.basename(cum_outmap))))
            delete = delete.upper()
            while delete!='N' and delete!='Y':
                delete = str(input("Sorry, I was expecting either 'Y' or 'N'. \nShould the existing map %s be deleted?\n'Y' for yes, 'N' for no >" %(os.path.basename(cum_outmap))))
                delete = delete.upper()
            if delete=='Y':
                os.remove(cum_outmap)
                exists = False
            if delete=='N':
                exists = True
        else:
            exists = False
        ### WORK ON FILES TO GENERATE CALCULATION INFORMATION
        asc_list = glob.glob(asc_dir+"/output_temp_*")
        # Untar the files if they have not already been extracted
        if len(asc_list)==0:
            tar_file = glob.glob(asc_dir+"/*.tar.gz")
            print(len(tar_file))
            if len(tar_file) == 0:
                print("!!! \n No .tar or .asc files in %s, moving on...\n!!!" %(asc_dir))
                continue
            if len(tar_file) == 1:
                print("...Untarring " + tar_file[0])
                with open(os.devnull, 'wb') as devnull:
                    subprocess.check_call(['tar','-C',asc_dir,'-zxvf', tar_file[0]], stdout=devnull, stderr=subprocess.STDOUT)
#                os.system('tar -C ' + asc_dir + ' -zxvf ' + asc_dir + '/*.tar.gz')
                asc_list = glob.glob(asc_dir+"/output_temp_*")
            if len(tar_file) > 1:
                print("!!!\nMore than one .tar file in %s, moving on...     \n!!!" %(asc_dir))
                continue
        # Modify file names to isolate just numbers
        iterpop = [a.replace('output_temp_', '').replace('_nodes', '').replace('.asc','') for a in asc_list]
        # Separate the number of iterations from population size (for lookups)
        niter = []
        p = []
        p_mult = []
        p_mult_tmp = []
        for a in iterpop:
            ntmp, ptmp = re.split("_", os.path.basename(a))[0:2]
            niter.append(int(ntmp))
            p.append(float(ptmp))
            multtmp = np.log10(float(ptmp)/78.54)*-0.054357+0.179789
            if multtmp < 0:
                multtmp = 0.0001
            p_mult_tmp.append(multtmp)
            p_mult.append(multtmp*float(ptmp))
        # Calculates the expected number of hunters based on mini lit review
        #   Each population density was calculated within a 5km buffer; so divide
        #   by 78.54 (approximate area of a 5km-radius circle) for density per km2
        # Find singles/duplicates:
        single_src = sorted(list_singles(p))
        dup_src = sorted(list_duplicates(p))
        ### CREATE EMPTY MAP OR READ EXISTING
        # Use same dimensions/transformation as asc_list[0]
        if exists == False:
            with rio.open(os.path.join(asc_dir,asc_list[0]), 'r') as ds:
                tmp_meta = ds.profile
                tmp_shape = ds.shape  # read in height and width
            intmap = np.empty(tmp_shape, dtype=np.float32)
            print("Creating blank output map: %s" %(os.path.basename(cum_outmap)))
            with rio.open(cum_outmap, 'w', **tmp_meta) as ds:
                ds.write_band(1, intmap)
        elif exists == True:
            print("Reading existing cumulative map %s" %(os.path.basename(cum_outmap)))
            with rio.open(cum_outmap, 'r') as ds:
                intmap = ds.read()
            with rio.open(os.path.join(asc_dir,asc_list[0]), 'r') as ds:
                tmp_meta = ds.profile
        ### BEGIN CALCULATIONS
        print("Calculating single-source file maps...")
        save_counter = 0 # save every 5 steps
        singles_counter = 0
        total = len(single_src)
        for s in single_src:
            singles_counter += 1
            print("\n...Processing map %s of %s...\n" %(singles_counter, total))
            ntmp = niter[int(s[1][0])]
            pmtmp = p_mult[int(s[1][0])]
            # Find corresponding source TSV file:
            src_f = glob.glob(src_dir+"/*%s*" %(str(ptmp)+"_"))[0]
            with open(src_f) as file:
                head = [next(file) for x in range(1)]
            # Number of sources is just the first # of the second column minus 1
            nsource = int(re.split("\t", head[0])[1].replace("\n", ""))-1
            asc_tmp = os.path.join(asc_dir, asc_list[int(s[1][0])])
            print("......Opening file: %s" %(os.path.basename(asc_tmp)))
            with rio.open(asc_tmp, 'r') as ds:
                tmp = ds.read()
            tmp[tmp == -9999] = 0
            intmap = intmap + ((tmp * nsource * pmtmp) / ntmp)
            Path(os.path.join(asc_dir, "Processed", os.path.basename(asc_tmp[0]))).touch()
            save_counter += 1
            if save_counter == 10:
                with rio.open(cum_outmap, 'w', **tmp_meta) as ds:
                    ds.write(intmap)
                save_counter = 0
            with open(os.devnull, 'wb') as devnull:
                    subprocess.check_call(['rm',asc_tmp],stdout=devnull, stderr=subprocess.STDOUT)
        if total!=0:
            with rio.open(cum_outmap, 'w', **tmp_meta) as ds:
                ds.write(intmap)
        total = len(dup_src)
        dup_counter = 0
        for d in dup_src:
            dup_counter += 1
            print("\n...Processing map %s of %s...\n" %(dup_counter, total))
            # Population at 0th index, location at 1st
            ptmp = d[0]
            pmtmp = p_mult[int(d[1][0])]
            for f in range(len(d[1])):
                ntmp = niter[int(d[1][f])]
                src_f = glob.glob(src_dir+"/*%s*" %(str(ptmp)+"_"))[f]
                with open(src_f) as file:
                    head = [next(file) for x in range(1)]
                nsource = int(re.split("\t", head[0])[1].replace("\n", ""))-1
                asc_tmp = os.path.join(asc_dir, asc_list[int(d[1][f])])
                print("......Opening file: %s" %(os.path.basename(asc_tmp)))
                with rio.open(asc_tmp, 'r') as ds:
                    tmp = ds.read()
                tmp[tmp == -9999] = 0
                intmap = intmap + ((tmp * nsource * pmtmp) / ntmp)
                Path(os.path.join(asc_dir, "Processed", os.path.basename(asc_tmp[0]))).touch()
                save_counter += 1
            if save_counter >= 10:
                with rio.open(cum_outmap, 'w', **tmp_meta) as ds:
                    ds.write(intmap)
                save_counter = 0
            with open(os.devnull, 'wb') as devnull:
                    subprocess.check_call(['rm',asc_tmp],stdout=devnull, stderr=subprocess.STDOUT)
        with rio.open(cum_outmap, 'w', **tmp_meta) as ds:
            ds.write(intmap)


import streamlit as st
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt

st.title("""
         EXPLORE DIFFERENT CLASSIFIERS
         """)
dataset_name=st.sidebar.selectbox("select Data Set",("Iris","Breast Cancer","Wine","Digits","DIABETES","BOSTON","LINNERUD"))
classifier_name=st.sidebar.selectbox("Select Classifier",("KNN","SVM","RANDOM FOREST","DECISION TREE","GAUSSION NB","MLP","ADABoost","QUADRATIC DISCRIMINANT"))

def get_dataset(dataset_name):
    if dataset_name=="Iris":
        data=datasets.load_iris()
    elif dataset_name=="Breast Cancer":
        data=datasets.load_breast_cancer()
    elif dataset_name=="Wine":
        data=datasets.load_wine()
    elif dataset_name:
        data=datasets.load_digits()
    x=data.data
    y=data.target
    return x,y
x,y=get_dataset(dataset_name)
st.write("SHAPE OF DATASET",x.shape)

def add_parameter(clf_name):
    p=dict()
    if clf_name=="KNN":
        K=st.sidebar.slider("K",1,15)
        p["K"]=K
    elif clf_name == "SVM":
        C = st.sidebar.slider("C", 0.01,10.00)
        p["C"] =C
    elif clf_name == "RANDOM FOREST":
        M_D= st.sidebar.slider("M_D",2,15)
        N_E=st.sidebar.slider("N_E",1,100)
        p["M_D"] =M_D
        p["N_E"]=N_E
    elif clf_name == "DECISION TREE":
        M_DD = st.sidebar.slider("M_DD", 2, 15)
        p["M_DD"] = M_DD
    elif clf_name == "MLP":
        p["A"] = 1
    return p

p=add_parameter(classifier_name)

def get_classifier(clf_name,p):
    if clf_name=="KNN":
        clf=KNeighborsClassifier(n_neighbors=p["K"])
    elif clf_name=="SVM":
        clf=SVC(C=p["C"])
    elif clf_name=="RANDOM FOREST":
        clf=RandomForestClassifier(max_depth=p["M_D"],n_estimators=p["N_E"],random_state=900)
    elif clf_name=="DECISION TREE":
        clf=DecisionTreeClassifier(max_depth=p["M_DD"])
    elif clf_name=="GAUSSION NB":
        clf=GaussianNB()
    elif clf_name=="MLP":
        clf=MLPClassifier(alpha=p["A"], max_iter=1000)
    elif clf_name=="ADABoost":
        clf=AdaBoostClassifier()
    elif clf_name == "QUADRATIC DISCRIMINANT":
        clf = QuadraticDiscriminantAnalysis()
    return clf

clf=get_classifier(classifier_name,p)

x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.33,random_state=900)
clf.fit(x_train,y_train)
y_p = clf.predict(x_test)
a=accuracy_score(y_test,y_p)
st.write(f"CLASSIFIER={classifier_name}")
st.write(f"ACCURACY={a}")

pca=PCA(2)
x_project=pca.fit_transform(x)

x1=x_project[:,0]
x2=x_project[:,1]
fig=plt.figure()
plt.scatter(x1,x2,c=y,alpha=0.8,cmap="viridis")
plt.xlabel("principle component 1")
plt.ylabel("principle component 2")
plt.colorbar()

st.pyplot(bbox_inches='tight')
st.set_option('deprecation.showPyplotGlobalUse', False)


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

'''

'''

#############
## LOGGING ##
#############

import logging
from fitsbits import log_sub, log_fmt, log_date_fmt

DEBUG = False
if DEBUG:
    level = logging.DEBUG
else:
    level = logging.INFO
LOGGER = logging.getLogger(__name__)
logging.basicConfig(
    level=level,
    style=log_sub,
    format=log_fmt,
    datefmt=log_date_fmt,
)

LOGDEBUG = LOGGER.debug
LOGINFO = LOGGER.info
LOGWARNING = LOGGER.warning
LOGERROR = LOGGER.error
LOGEXCEPTION = LOGGER.exception

#############
## IMPORTS ##
#############


"""This program is a basic warehouse inventory tracking software."""
from tkinter import *
from tkinter import messagebox

class Style:
    """Style class holds constants used for colors and fonts in the GUI."""

    def __init__(self):
        """Create Fonts used in GUI creation."""
        self.default_font = ("Arial", 10, "normal")
        self.title_font = ("Roboto", 30, "bold")
        self.button_font = ("Roboto", 10, "bold")
        self.widget_font = ("Roboto", 15, "normal")
        self.primary = "#d2d3db" # Light gray with a hint of blue
        self.secondary = "#9394a5" # Slightly darker gray with a hint of blue
        self.text_color = "black" # Black
        self.accent = "#b8b8b8" # Darkish gray
        self.background = "#fafafa" # White
        self.title_color = "#484b6a" # Dark pastel blue
        self.border_color = "#666666" # Dark gray
        self.accent2 = "#32a852" # Light pastel green

class ItemWidget:
    """Custom item Widget class."""

    def __init__(self, frame, name, count, ref_code, aisle, shelf):
        """This function initialises the class and creates a frame with widgets of the variables inputted."""
        self.frame = frame
        self.name = name
        self.count = count
        self.ref_code = ref_code
        self.aisle = aisle
        self.shelf = shelf

        self.item_frame = Frame(self.frame, bg=style.primary)
        self.name_label = Label(self.item_frame, text=self.name, font=style.default_font, fg=style.text_color, bg=style.primary, width=20)
        self.count_label = Label(self.item_frame, text=self.count, font=style.default_font, fg=style.text_color, bg=style.primary, width=20)
        self.ref_code_label = Label(self.item_frame, text=self.ref_code, font=style.default_font, fg=style.text_color, bg=style.primary, width=20)
        self.aisle_label = Label(self.item_frame, text=self.aisle, font=style.default_font, fg=style.text_color, bg=style.primary, width=20)
        self.shelf_label = Label(self.item_frame, text=self.shelf, font=style.default_font, fg=style.text_color, bg=style.primary, width=20)
        self.name_label.grid(row=0, column=0, padx=5, pady=2)
        self.count_label.grid(row=0, column=1, padx=5, pady=2)
        self.ref_code_label.grid(row=0, column=2, padx=5, pady=2)
        self.aisle_label.grid(row=0, column=3, padx=5, pady=2)
        self.shelf_label.grid(row=0, column=4, padx=5, pady=2)

class Gui:
    """Main GUI class."""

    def __init__(self, parent):
        """This function initialises the main GUI of the program."""
        self.main = Frame(parent)
        self.main.pack()
        self.items_list = []

        # Stock page
        # Create stock page frame
        self.stock_page = Frame(self.main, bg=style.primary)
        self.stock_page.pack()

        # The search tab section of the stock page.
        # Create search bar page frame
        stock_search = Frame(self.stock_page, bg=style.secondary, highlightbackground=style.border_color, highlightthickness=1, bd=0, relief="solid")
        stock_search.pack(fill='x')

        # Reload button
        reload_button = Button(stock_search, text="Reload", font=style.button_font, bg=style.accent, fg=style.text_color, command=self.reload_list)
        reload_button.grid(row=0, column=0, padx=5, pady=2, )
        # Add stock item button
        new_button = Button(stock_search, text="Add new stock", font=style.button_font, bg=style.accent, fg=style.text_color, command=self.new_item)
        new_button.grid(row=0, column=1, padx=5, pady=2, )

        # Radio button for which value to search
        radiobutton_frame = Frame(stock_search, bg=style.secondary)
        radiobutton_frame.grid(row=0, column=3, padx=5, pady=2, )
        self.rb_value = IntVar()
        self.rb_value.set(0)
        search_name = Radiobutton(radiobutton_frame, variable=self.rb_value, value=0, text="Name", bg=style.secondary, fg=style.text_color, font=style.default_font)
        search_count = Radiobutton(radiobutton_frame, variable=self.rb_value, value=1, text="Count", bg=style.secondary, fg=style.text_color, font=style.default_font)
        search_ref_code = Radiobutton(radiobutton_frame, variable=self.rb_value, value=2, text="Refrence Code", bg=style.secondary, fg=style.text_color, font=style.default_font)
        search_aisle = Radiobutton(radiobutton_frame, variable=self.rb_value, value=3, text="Aisle", bg=style.secondary, fg=style.text_color, font=style.default_font)
        search_shelf = Radiobutton(radiobutton_frame, variable=self.rb_value, value=4, text="Shelf", bg=style.secondary, fg=style.text_color, font=style.default_font)

        # Grid radio buttons
        search_name.grid(row=0, column=0)
        search_count.grid(row=1, column=0)
        search_aisle.grid(row=0, column=1)
        search_shelf.grid(row=1, column=1)
        search_ref_code.grid(row=0, column=2)

        # Search bar frame
        search_bar_frame = Frame(stock_search, bg=style.secondary)
        search_bar_frame.grid(row=0, column=4, padx=5, pady=2)
        self.search_bar = Entry(search_bar_frame, width=30)
        self.search_bar.grid(row=0, column=0)
        # Search button
        search_button = Button(search_bar_frame, text="Search", font=style.button_font, bg=style.accent, fg=style.text_color, command=self.search)
        search_button.grid(row=0, column=1, padx=5)

        # List Frame
        # Stock items list frame
        stock_items = Frame(self.stock_page, bg=style.primary)
        stock_items.pack()

        # Item titles label
        item_title = Frame(stock_items, bg=style.primary)
        item_title.pack(fill='x')

        name_label = Label(item_title, text="Name", font=style.default_font, fg=style.text_color, bg=style.primary, width=20)
        count_label = Label(item_title, text="Count", font=style.default_font, fg=style.text_color, bg=style.primary, width=20)
        ref_code_label = Label(item_title, text="Refrence code", font=style.default_font, fg=style.text_color, bg=style.primary, width=20)
        aisle_label = Label(item_title, text="Aisle", font=style.default_font, fg=style.text_color, bg=style.primary, width=20)
        shelf_label = Label(item_title, text="Shelf", font=style.default_font, fg=style.text_color, bg=style.primary, width=20)
        name_label.grid(row=0, column=0, padx=5, pady=2)
        count_label.grid(row=0, column=1, padx=5, pady=2)
        ref_code_label.grid(row=0, column=2, padx=5, pady=2)
        aisle_label.grid(row=0, column=3, padx=5, pady=2)
        shelf_label.grid(row=0, column=4, padx=5, pady=2)

        # Create a Canvas widget with a vertical Scrollbar
        self.canvas = Canvas(stock_items, height=200, bg=style.background)
        scrollbar = Scrollbar(stock_items, orient="vertical", command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=scrollbar.set)
        scrollbar.pack(side="right", fill="y")
        self.canvas.pack(side="left", fill="both", expand=True)

        # Create a frame inside the canvas to hold the content
        self.items_frame = Frame(self.canvas)
        self.canvas.create_window((0, 0), window=self.items_frame, anchor="nw")

        # Configure the canvas to fit the content and enable scrolling
        self.items_frame.update_idletasks()  # Update the frame to get accurate width and height
        self.canvas.config(scrollregion=self.canvas.bbox("all"))

    def new_item(self):
        """Creates a popup window to enter data in and create new items."""
        popup = Toplevel(bg=style.primary)
        popup.title("Add new item")
        popup.geometry("175x150")

        item_name = Label(popup, text="Item Name", font=style.default_font, fg=style.text_color, bg=style.primary)
        self.item_name_entry = Entry(popup, width=10)
        item_name.grid(row=0, column=0)
        self.item_name_entry.grid(row=1, column=0)

        item_count = Label(popup, text="Current count", font=style.default_font, fg=style.text_color, bg=style.primary)
        self.item_count_entry = Entry(popup, width=10)
        item_count.grid(row=0, column=1)
        self.item_count_entry.grid(row=1, column=1)

        item_aisle = Label(popup, text="Aisle", font=style.default_font, fg=style.text_color, bg=style.primary)
        self.item_aisle_entry = Entry(popup, width=10)
        item_aisle.grid(row=2, column=0)
        self.item_aisle_entry.grid(row=3, column=0)

        item_shelf = Label(popup, text="Shelf", font=style.default_font, fg=style.text_color, bg=style.primary)
        self.item_shelf_entry = Entry(popup, width=10)
        item_shelf.grid(row=2, column=1)
        self.item_shelf_entry.grid(row=3, column=1)

        item_ref_code = Label(popup, text="Refrence code", font=style.default_font, fg=style.text_color, bg=style.primary)
        self.item_ref_code_entry = Entry(popup, width=10)
        item_ref_code.grid(row=4, column=0)
        self.item_ref_code_entry.grid(row=4, column=1)

        add = Button(popup, text="Add +", command=self.add_item, font=style.button_font, bg=style.accent, fg=style.text_color)
        add.grid(row=5, column=1)

    def search(self):
        """Sets all items in the list to gray, then searches for items that match the search parameters and sets those items backgrounds to green."""
        if len(self.search_bar.get()) > 20:
            messagebox.showerror("Entry error", "Your search parameter must be less than 20 characters.")
        elif len(self.search_bar.get()) <= 20:
            for item in self.items_list:
                item.item_frame.configure(bg=style.primary)
                item.name_label.configure(bg=style.primary, fg=style.text_color)
                item.ref_code_label.configure(bg=style.primary, fg=style.text_color)
                item.count_label.configure(bg=style.primary, fg=style.text_color)
                item.aisle_label.configure(bg=style.primary, fg=style.text_color)
                item.shelf_label.configure(bg=style.primary, fg=style.text_color)
            for item in self.items_list:
                var_list = [item.name, item.count, item.ref_code, item.aisle, item.shelf]
                if self.search_bar.get() == var_list[self.rb_value.get()]:
                    item.item_frame.configure(bg=style.accent2)
                    item.name_label.configure(bg=style.accent2, fg=style.primary)
                    item.ref_code_label.configure(bg=style.accent2, fg=style.primary)
                    item.count_label.configure(bg=style.accent2, fg=style.primary)
                    item.aisle_label.configure(bg=style.accent2, fg=style.primary)
                    item.shelf_label.configure(bg=style.accent2, fg=style.primary)

    def add_item(self):
        """validates the inputs and then creates an instance of the ItemWidget subclass and appends it to a list, then clears the entrys."""
        if self.validate_str(self.item_name_entry.get(), 20) is False:
            messagebox.showerror("Entry error", "The name of your item cannot contain digits or must be shortened to less than 20 characters.")
        elif self.validate_int(self.item_count_entry.get(), 999999) is False:
            messagebox.showerror("Entry error", "Your item count cannot contain letters and must be less than 1,000,000")
        elif len(self.item_ref_code_entry.get()) > 6:
            messagebox.showerror("Entry error", "Your refrence code must be 6 digits or less.")
        else:
            self.items_list.append(ItemWidget(self.items_frame, self.item_name_entry.get(), self.item_count_entry.get(), self.item_ref_code_entry.get(), self.item_aisle_entry.get(), self.item_shelf_entry.get()))
            self.item_name_entry.delete(first=0, last=100)
            self.item_aisle_entry.delete(first=0, last=100)
            self.item_count_entry.delete(first=0, last=100)
            self.item_shelf_entry.delete(first=0, last=100)
            self.item_ref_code_entry.delete(first=0, last=100)
            self.reload_list()

    def reload_list(self):
        """Reloads the list and the main page."""
        for item in self.items_list:
            item.item_frame.pack()
        # Configure the canvas to fit the content and enable scrolling
        self.items_frame.update_idletasks()  # Update the frame to get accurate width and height
        self.canvas.config(scrollregion=self.canvas.bbox("all"))
        self.main.forget()
        self.main.pack()

    def validate_int(self, enter, limit):
        """Function to validate an integer"""
        try:
            int(enter)
            if int(enter) > limit:
                return False
            elif int(enter) <= limit:
                return True
        except ValueError:
            return False

    def validate_str(self, enter, limit):
        """Function to validate a string"""
        if len(enter) > limit:
            return False
        elif len(enter) <= limit:
            for i in enter:
                try:
                    int(i)
                    return False
                except ValueError:
                    i
            return True

if __name__ == "__main__":
    style = Style()
    root = Tk()
    root.title("Warehouse Software")
    root.configure(background=style.background)
    instance=Gui(root)
    root.mainloop()


## The wext merged datafile
import sys
input_file = sys.argv[1]
data_file = sys.argv[2]
output_file = sys.argv[3]
cutoff = float(sys.argv[4])
#cutoff = 5

import pandas as pd
from sklearn.metrics import precision_recall_curve
from random import random
import math
from scipy.stats import chi2
import numpy as np

import logging
#filename =
logging.basicConfig(filename="log/"+ sys.argv[0].split('/')[0] + ".log", level=logging.INFO)

#logging.getLogger().setLevel('DEBUG')

logging.debug("Data file: "+data_file)
logging.debug("Output file: "+output_file)
logging.debug("cuttoff: "+str(cutoff))

data = pd.read_csv(data_file, delimiter='\t')

logging.debug(data.columns)
data = data[(data['Index1'] != "Index1")] # get rid of extra headers from cat
data['Distance'] = data['Distance'].apply(int)
data['P-Value'] = data['P-Value'].apply(float)
data = data[data['Distance'] > 0]
data = data.drop_duplicates()

logging.debug("Imported data. DF size:"+str(data.shape))

data_sorted = data.fillna(1).replace(float('-inf'), 1).sort_values(by = 'P-Value')
data_sorted = data_sorted[data_sorted['P-Value'] > 0]
data_sorted['True'] = data_sorted.apply(lambda x: x['Gene1'][-1] == x['Gene2'][-1], axis=1)
data_sorted['Pair'] = data_sorted.apply(lambda x: x['Gene1'][:-1] + ':' +  x['Gene2'][:-1], axis = 1)
data_sorted['Index1'] = data_sorted['Index1'].apply(int)
data_sorted['Index2'] = data_sorted['Index2'].apply(int)
data_sorted['log p'] = data_sorted['P-Value'].apply(math.log)

logging.debug("Sorted data. DF size:"+str(data_sorted.shape))

def p_value(x):
    k = 4
    v = chi2.logsf(-2*x, k)
    return v

def is_correct(x):
    if x != 0:
        return x < 0
    else:
        return random() < 0.5

diff = data_sorted
diff = diff[['Pair', 'Distance',  'log p', 'True']].groupby(['Pair', 'Distance', 'True']).sum()
diff.reset_index(inplace=True)
diff['log p joint'] = diff['log p'].apply(p_value)
diff['log p sum'] = diff.apply(lambda x: x['log p joint'] if x['True'] else -x['log p joint'], axis=1)

logging.debug("Created diff. Diff size:" + str(diff.shape))

div = diff[['Pair', 'Distance', 'log p sum']].groupby(by = ['Pair','Distance']).sum()
div = div[div['log p sum'] != 0]
div['log p abs'] = div['log p sum'].apply(abs)
div['correct'] = div['log p sum'].apply(lambda x: x < 0)
div['correct2'] = div['log p sum'].apply(is_correct)
div.reset_index(inplace=True)

logging.debug("Created div. Div size:" + str(div.shape))
logging.debug("Score span: " + str(div['log p sum'].max()) +"\t"+ str(div['log p sum'].min()))

import vcf

pos_index_map = {}

data = pd.read_csv(input_file)

pos_index_map = {}
def make_pos_index_map(x):
    pos_index_map[x['loc']] = x.name + 1
data.apply(make_pos_index_map, axis=1)

def write_fragment(cutoff, output_file):
    with open(output_file,'w') as out:
        dclip = div[div['log p abs'] > cutoff]
        #dclip = div
        for i in range(len(dclip)):
            d = dclip.iloc[i]
            v1 = min(map(int, d['Pair'].split(':')))
            v2 = max(map(int, d['Pair'].split(':')))

            i1 = pos_index_map[v1]
            i2 = pos_index_map[v2]
            a1 = "0"
            a2 = "0"

            if d['log p sum'] < 0:
                if random() > 0.5: allele = "00"
                else: allele = "11"
            else:
                if random() > 0.5: allele = "10"
                else: allele = "01"

            if abs(i1 - i2) == 1:
                q = '++'
                line = "1 {0} {1} {2} {3}\n".format(d['Pair'], i1, allele, q)
            else:
                q = '++'
                line = "2 {0} {1} {2} {3} {4} {5}\n".format(d['Pair'], i1, allele[0], i2, allele[1], q)
            out.write(line)

write_fragment(cutoff, output_file)


from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from nltk.tokenize import word_tokenize
from gensim import corpora
import gensim
import gensim.downloader as api
from gensim.matutils import softcossim
#from gensim import fasttext_model300
from gensim import *
import fasttext
import gensim.downloader as api
#import csv

'''data = ["I love machine learning. Its awesome.",
        "I love coding in python",
        "I love building chatbots",
        "they chat amagingly well"]
        '''

data =[]
with open('out_mod.txt','r') as f:
    docs=f.readlines()
    for l in docs:
        st=l.strip('\n')
        if st!='':
            data.append(st)
#print(data)

documents=[]

for d in data:
    documents.append(d.split())

dictionary= corpora.Dictionary(documents)
fasttext_model300 = api.load('fasttext-wiki-news-subwords-300')
similarity_matrix = fasttext_model300.similarity_matrix(dictionary, tfidf=None, threshold=0.0, exponent=2.0, nonzero_limit=100)

tagged_data = [TaggedDocument(words=word_tokenize(_d.lower()), tags=[str(i)]) for i, _d in enumerate(data)]

max_epochs = 100
vec_size = 20
alpha = 0.025

model = Doc2Vec(size=vec_size,
                alpha=alpha,
                min_alpha=0.00025,
                min_count=1,
                dm =1)

model.build_vocab(tagged_data)

for epoch in range(max_epochs):
    #print('iteration {0}'.format(epoch))
    model.train(tagged_data,
                total_examples=model.corpus_count,
                epochs=model.iter)
    # decrease the learning rate
    model.alpha -= 0.0002
    # fix the learning rate, no decay
    model.min_alpha = model.alpha

model.save("d2v.model")
print("Model Saved")

model= Doc2Vec.load("d2v.model")
#to find the vector of a document which is not in training data
print("Model loaded Input the document")
s= input()
s=s.lower()
test_data = word_tokenize(s)

v1 = model.infer_vector(test_data)
print("V1_infer", v1)

#s = dictionary.doc2bow(s)

max=0
idx=0

for d in data:
    if softcossim(dictionary.doc2bow((s.lower()).split()), dictionary.doc2bow((d.lower()).split()), similarity_matrix) > max:
        max=  softcossim(dictionary.doc2bow((s.lower()).split()), dictionary.doc2bow((d.lower()).split()), similarity_matrix)
        idx= data.index(d)

print(max)
print(data[idx])

# to find most similar doc using tags
#similar_doc = model.docvecs.most_similar('1')

#print("work")
#print(similar_doc)


from django.conf.urls.defaults import *
from django.contrib.syndication.views import feed as feed_view
from django.views.generic import date_based, list_detail
from django.contrib import admin
from ebblog.blog.models import Entry
from ebblog.blog import feeds

admin.autodiscover()

info_dict = {
    'queryset': Entry.objects.order_by('pub_date'),
    'date_field': 'pub_date',
}

FEEDS = {
    'rss': feeds.BlogEntryFeed,
}

urlpatterns = patterns('',
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>\w+)/$', date_based.object_detail, dict(info_dict, slug_field='slug')),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/$', date_based.archive_day, info_dict),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$', date_based.archive_month, info_dict),
    (r'^(?P<year>\d{4})/$', date_based.archive_year, info_dict),
    (r'^(rss)/$', feed_view, {'feed_dict': FEEDS}),
    (r'^archives/', list_detail.object_list, {'queryset': Entry.objects.order_by('-pub_date'), 'template_name': 'blog/archive.html'}),
    (r'^$', date_based.archive_index, dict(info_dict, template_name='homepage.html')),
    ('^admin/', include(admin.site.urls)),
)


"""
Benjamin Granat
ITP 449
Assginment 9
Trains and tests a logistic regression based on diabetes classification data
Produces confusion matrix visualization
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix as cmatrix
from sklearn.metrics import accuracy_score as accscore
from sklearn.model_selection import train_test_split as tts
from sklearn.metrics import ConfusionMatrixDisplay as cms

# Function: remove_outliers
# Parameters: dataframe, columns
# Creates lower and upper quartile bounds for columns in dataframe.
# Drops values outside of the lower and upper bounds in the dataframe
# Returns updated dataframe
def remove_outliers(data, columns):
    for column in columns:
        Q3 = data[column].quantile(0.75)
        Q1 = data[column].quantile(0.25)
        IQR = Q3 - Q1
        lower = Q1 - 1.5 * IQR
        upper = Q3 + 1.5 * IQR
        df_filter = (data[column] >= lower) & (data[column] <= upper)
        data = data[df_filter]
    return data

def main():
    # Reading file into dataframe
    df = pd.read_csv('diabetes.csv')
    # Sorting columns most correlated with 'Outcome' column in descending order
    corr = df.corr()['Outcome'].abs().sort_values(ascending=False)
    # Isolates most correlated attributes
    corr_attrs = corr[1:4].index
    # Outcome column
    outcome = corr[0:1].index
    # Drop duplicates and null values
    df.drop_duplicates()
    df.dropna()
    # Removes outliers from dataframe using correlated columns and outcome column
    remove_outliers(df, corr_attrs)
    remove_outliers(df, outcome)
    # Creates feature vector and target vector
    X = df[corr_attrs].values
    Y = df[outcome].values
    # Partitions data into training and testing subsets
    X_train, X_test, Y_train, Y_test = tts(X, Y, random_state=42)
    # Runs logistic regression
    model = LogisticRegression()
    model.fit(X_train, Y_train)
    predict_Y = model.predict(X_test)
    # Creates confusion matrix based on predictions
    matrix = cmatrix(Y_test, predict_Y)
    # Calculates accuracy score and concatinates into a string
    accuracy = accscore(Y_test, predict_Y)
    accuracy_string = "Accuracy is " + str(accuracy)
    # Displaying the confusion matrix
    cm_disp = cms(confusion_matrix=matrix, display_labels=model.classes_)
    fig, axes = plt.subplots()
    cm_disp.plot(ax=axes)
    axes.set(title="Diabetes Logistic Regression Confusion Matrix" + "\n" + accuracy_string)
    plt.savefig('Diabetes Logistic Regression Confusion Matrix.png')

if __name__ == '__main__':
    main()


'''
Escreva um programa que leia um número inteiro positivo n e em seguida imprima n linhas do chamado
Triângulo de Floyd.
'''

num = int(input("Insira um valor n: "))
cont = 0

for i in range(1, num+1):
    for j in range(1, 1+i):
        cont += 1
        print(cont, end = ' ')
    print("\n")


'''
class employee:
    def getempval(self):pass
    def dispemp(self):pass

e1=employee()
e1.getempval()  # we dont need to call this method explcitly since in constructors
                we canuse it implicitly

'''
class employee:
    def __init__(self):
        self.eno=int(input("enter the eno: "))
        self.ename=input("enter the name: ")
        self.esal=float(input("enter the sal: "))

    def dispval(self):
        print("\tEmployee details")
        print("\tSno\tName\tSal")
        print("\t{}\t{}\t{}".format(self.eno,self.ename,self.esal))
        # print("employee number: {}".format(self.eno))
        # print("employee name: {}".format(self.ename))
        # print("employee sal: {}".format(self.esal))

e1=employee()
e2=employee()
e1.dispval()
e2.dispval()


import logging
from odoo.addons.base_rest import restapi
from odoo.addons.base_rest.components.service import to_int
from odoo.addons.base_rest_datamodel.restapi import Datamodel
from odoo.addons.component.core import Component

_logger = logging.getLogger(__name__)

class CyclosService(Component):
    _inherit = "base.rest.service"
    _name = "cyclos.service"
    _usage = "cyclos"
    _collection = "lokavaluto.private.services"
    _description = """
        Ping Services
        Access to the ping services is allowed to everyone
    """

    @restapi.method(
        [(["/credit"], "POST")],
        input_param=Datamodel("cyclos.credit.info"),
        output_param=Datamodel("cyclos.credit.response"),
    )
    def credit(self, params):
        """
        Credit user account with amount, and generate accounting entry
        """
        partner = self.env.user.partner_id
        base_url = self.env["ir.config_parameter"].sudo().get_param("web.base.url")
        _logger.debug("PARTNER ?: %s(%s)" % (partner.name, partner.id))
        owner_id = params.owner_id
        amount = params.amount
        CyclosCreditResponse = self.env.datamodels["cyclos.credit.response"]
        cyclos_response = CyclosCreditResponse(partial=True)
        if owner_id and amount:
            new_order = partner.cyclosCreateOrder(owner_id, amount)
            cyclos_response.order_url = base_url + new_order.get_portal_url()
        return cyclos_response

    @restapi.method(
        [(["/contact"], "POST")],
        input_param=Datamodel("cyclos.partners.info"),
    )
    def contact(self, params):
        """Return public name for contact matching comchain addresses"""

        partner = self.env["res.partner"]
        partner_ids = partner.search(
            [("lcc_backend_ids.cyclos_id", "in", params.addresses)]
        )
        res = {}
        for partner in partner_ids:
            backend_data = partner._cyclos_backend()
            res[backend_data.cyclos_id] = {
                "partner_id": partner.id,
                "public_name": partner.public_name,
            }
        return res


import matplotlib.image as mpimg
from tensorflow.keras.utils import img_to_array, load_img
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from keras.models import load_model

# Load the model
model = load_model('model12.h5')

# Convert the model to a quantized model
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]
quantized_model = converter.convert()

# Save the quantized model
with open("quantized_model.tflite", "wb") as f:
    f.write(quantized_model)

# Load the quantized model
interpreter = tf.lite.Interpreter(model_content=quantized_model)
interpreter.allocate_tensors()

# Get input and output tensors
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

image_path = 'chest_xray\\test\\PNEUMONIA\\test_pneu_130.jpg'
image = mpimg.imread(image_path)

test_image = load_img(image_path, target_size = (224, 224))
test_image = img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
pred = model.predict(test_image)
predict = np.argmax(pred, axis=-1)

if predict == 0:
    prediction = 'Normal'
else:
    prediction = 'Pneumonia +VE'

plt.imshow(image);plt.suptitle(prediction, fontsize = 20);plt.axis("off");plt.show()


import main
import alg_cluster
import random
import matplotlib.pyplot as plt
import time

def get_random_clusters(num_clusters):
    result_list = []
    for num in range(num_clusters):
        result_list.append(alg_cluster.Cluster(set([num]), random.random()*2 - 1, random.random()*2 - 1,0,0))
    return result_list

x_data = []
y_data = []
x1_data = []
y1_data = []
for n in range(2,201):
    cluster_list = get_random_clusters(n)

    start_time = time.time()
    main.slow_closest_pair(cluster_list)
    stop_time = time.time()
    elapsed_time = stop_time - start_time
    x_data.append(n)
    y_data.append(elapsed_time)

    start_time = time.time()
    main.fast_closest_pair(cluster_list)
    stop_time = time.time()
    elapsed_time = stop_time - start_time
    x1_data.append(n)
    y1_data.append(elapsed_time)

plt.plot(x_data,y_data, "g-", label = "Slow Closest Pair")
plt.plot(x1_data,y1_data, "r-", label = "Fast Closest Pair")
plt.legend()
plt.title("Running Time Comparison of Closest Pair Algorithms")
plt.suptitle("Desktop Python (PyCharm)")
plt.xlabel("Number of Initial Clusters")
plt.ylabel("Running time (seconds)")
plt.savefig("performanceTime.png")
plt.show()


#coding:utf-8
import  requests
import threading
from bs4 import BeautifulSoup
import re
import os
import time
import sys
content_url = "http://www.biquge.com.tw/12_12603/"
kv = {'user_agent': 'Mozilla/5.0'}  # 表示是一个浏览器
try:
    r = requests.get(content_url, headers=kv)
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    soup = BeautifulSoup(r.text, 'html.parser')
    article_name = soup.select('#wrapper .box_con #maininfo #info h1')[0].text
    # article_author = soup.select('#wrapper .box_con #maininfo #info p')[0].text
    article_intro = soup.select('#wrapper .box_con #maininfo #intro p')[0].text.strip()
    print('article name:'+article_name)
    # print('article author:'+article_author)
    print('article intro:'+article_intro)
    content_list = soup.find(id='list')
    chapter_list = soup.find_all('dd')
    fo = open(article_name+'.txt', "ab+")
    fo.write((article_name+"\r\n").encode('UTF-8'))
    fo.write(("*******简介*******\r\n").encode('UTF-8'))
    fo.write(("\t"+article_intro + "\r\n").encode('UTF-8'))
    fo.write(("******************\r\n").encode('UTF-8'))
    count = 0
    while (count < len(chapter_list)):
    	print('this count is:'+str(count))
    	print(chapter_list[count].find('a').text)
    	zhangval = chapter_list[count].find('a')['href'].split('/')[2]
    	urlll = content_url+str(zhangval)
    	print('url:'+urlll)
    	res = requests.get(content_url+str(zhangval), headers=kv)
    	res.encoding = 'gb18030'
    	soups = BeautifulSoup(res.text,"html.parser")
    	section_text = soups.select('#wrapper .content_read .box_con #content')[0]
    	# mytxt = re.sub( '\s+', '\r\n\t', section_text.text).strip('\r\n')
    	fo.write(('\r'+chapter_list[count].find('a').text+'\r\n').encode('UTF-8'))
    	fo.write((section_text.text).encode('UTF-8'))
    	count = count + 1
    fo.close()
except:
	print('error')


from __future__ import print_function
import argparse
import codecs
import numpy as np
import json
import requests

"""
This file is part of the computer assignments for the course DD1418/DD2418 Language engineering at KTH.
Created 2017 by Johan Boye and Patrik Jonell.
"""

"""
This module computes the minimum-cost alignment of two strings.
"""

"""
When printing the results, only print BREAKOFF characters per line.
"""
BREAKOFF = 60

def compute_backpointers(s0, s1):
    """

Computes and returns the backpointer array (see Jurafsky and Martin, Fig 3.27)
    arising from the calculation of the minimal edit distance of two strings
    s0 and s1.

The backpointer array has three dimensions. The first two are the row and
    column indices of the table in Fig 3.27. The third dimension either has
    the value 0 (in which case the value is the row index of the cell the backpointer
    is pointing to), or the value 1 (the value is the column index). For example, if
    the backpointer from cell (5,5) is to cell (5,4), then
    backptr[5][5][0]=5 and backptr[5][5][1]=4.

    :param s0: The first string.
    :param s1: The second string.
    :return: The backpointer array.
    """
    if s0 == None or s1 == None:
        raise Exception('Both s0 and s1 have to be set')

    backptr = [[[0, 0] for y in range(len(s1)+1)] for x in range(len(s0)+1)]

    # YOUR CODE HERE
    D = [[[0] for y in range(len(s1)+1)] for x in range(len(s0)+1)] # Distance matrix

    # Basic setup
    # First row, all columns
    for k in range(len(s1) + 1):
        D[0][k][0] = k
        if k == 0:
            continue
        backptr[0][k][0], backptr[0][k][1] = 0, k-1
    # First column, all rows
    for k in range(len(s0) + 1):
        D[k][0][0] = k
        if k == 0:
            continue
        backptr[k][0][0], backptr[k][0][1] = k-1, 0

    # Loop through both strings (inner part of matrix, i.e. excluding first column and first row)
    for i in range(1, len(s0)+1):
        for j in range(1, len(s1)+1):
            left_cost = D[i][j-1][0] + 1 # Cost to come from the left
            below_cost = D[i-1][j][0] + 1 # Cost to come from below
            # Cost to come from diagonally behind
            diag_cost = D[i-1][j-1][0]
            if (s0[i-1] != s1[j-1]):
                diag_cost += 2

            # Check which cost is cheapest (preference for diag_cost)
            if ((left_cost < below_cost) and (left_cost < diag_cost)):
                # We should come from the left in our backtrace matrix
                D[i][j][0] = left_cost
                backptr[i][j][0], backptr[i][j][1] = i, j-1
            elif ((below_cost <= left_cost) and (below_cost < diag_cost)):
                # We should come from below
                D[i][j][0] = below_cost
                backptr[i][j][0], backptr[i][j][1] = i-1, j
            elif ((diag_cost <= left_cost) and (diag_cost <= below_cost)):
                # We should come from diagonally behind
                D[i][j][0] = diag_cost
                backptr[i][j][0], backptr[i][j][1] = i-1, j-1

    return backptr

def subst_cost(c0, c1):
    """
    The cost of a substitution is 2 if the characters are different
    or 0 otherwise (when, in fact, there is no substitution).
    """
    return 0 if c0 == c1 else 2

def align(s0, s1, backptr):
    """

Finds the best alignment of two different strings s0
    and s1, given an array of backpointers.

The alignment is made by padding the input strings with spaces. If, for
    instance, the strings are around and rounded,
    then the padded strings should be around   and
     rounded.

    :param s0: The first string.
    :param s1: The second string.
    :param backptr: A three-dimensional matrix of backpointers, as returned by
    the diff method above.
    :return: An array containing exactly two strings. The first string (index 0
    in the array) contains the string s0 padded with spaces
    as described above, the second string (index 1 in the array) contains
    the string s1 padded with spaces.
    """
    result = ['', '']

    # YOUR CODE HERE
    i0 = len(s0)
    j0 = len(s1)
    # (i0, j0) gives us top right corner of backptr matrix

    while True:
        i, j = backptr[i0][j0][0], backptr[i0][j0][1]

        if ((i0 - 1 == i) and (j0 - 1 == j)):
            # Then, this is a diagonal move.
            result[0] += s0[i0 - 1]
            result[1] += s1[j0 - 1]
        elif (j0 - 1 == j):
            # This is a move from the left
            result[0] += ' '
            result[1] += s1[j0 - 1]
        elif (i0 - 1 == i):
            # This is a move from below
            result[0] += s0[i0 - 1]
            result[1] += ' '

        i0, j0 = i, j

        if ((i0 == 0) and (j0 == 0)):
            # We have reached index (0, 0) in the backptr matrix.
            break

    #print(backptr)

    return result

def print_alignment(s):
    """

Prints two aligned strings (= strings padded with spaces).
    Note that this printing method assumes that the padded strings
    are in the reverse order, compared to the original strings
    (because we are following backpointers from the end of the
    original strings).

    :param s: An array of two equally long strings, representing
    the alignment of the two original strings.
    """
    if s[0] == None or s[1] == None:
        return None
    start_index = len(s[0]) - 1
    while start_index > 0:
        end_index = max(0, start_index - BREAKOFF + 1)
        print_list = ['', '', '']
        for i in range(start_index, end_index-1 , -1):
            print_list[0] += s[0][i]
            print_list[1] += '|' if s[0][i] == s[1][i] else ' '
            print_list[2] += s[1][i]

        for x in print_list: print(x)
        start_index -= BREAKOFF

def main():
    """
    Parse command line arguments
    """
    parser = argparse.ArgumentParser(description='Aligner')
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--file', '-f', type=str, nargs=2, help='align two strings')
    group.add_argument('--string', '-s', type=str, nargs=2, help='align the contents of two files')

    parser.add_argument('--check', action='store_true', help='check if your alignment is correct')

    arguments = parser.parse_args()

    if arguments.file:
        f1, f2 = arguments.file
        with codecs.open(f1, 'r', 'utf-8') as f:
            s1 = f.read().replace('\n', '')
        with codecs.open(f2, 'r', 'utf-8') as f:
            s2 = f.read().replace('\n', '')

    elif arguments.string:
        s1, s2 = arguments.string

    if arguments.check:
        payload = json.dumps({
            's1': s1,
            's2': s2,
            'result': align(s1, s2, compute_backpointers(s1, s2))
        })
        response = requests.post(
            'https://language-engineering.herokuapp.com/correct',
            data=payload,
            headers={'content-type': 'application/json'}
        )
        response_data = response.json()
        if response_data['correct']:
            print_alignment( align(s1, s2, compute_backpointers(s1, s2)))
            print('Success! Your results are correct')
        else:
            print('Your results:\n')
            print_alignment( align(s1, s2, compute_backpointers(s1, s2)))
            print("The server's results\n")
            print_alignment(response_data['result'])
            print("Your results differ from the server's results")
    else:
        print_alignment( align(s1, s2, compute_backpointers(s1, s2)))

if __name__ == "__main__":
    main()


import numpy as np
from sympy import symbols, pi, sin, cos, atan2, sqrt, simplify
from sympy.matrices import Matrix
import tf

"""
Test file for building the Kuka 6 DoF manipulator's forward and inverse
kinematic code.

FK(thetas) -> pose
IK(pose) -> thetas
"""

def build_mod_dh_matrix(s, theta, alpha, d, a):
    """Build the modified DH transformation matrix based on the provided
    theta, alpha, d and a values.

    :param s: Dictionary of DH parameters for the manipulator
    :param theta: Sympy symbol
    :param alpha: Sympy symbol
    :param d: Sympy symbol
    :param a: Sympy symbol
    :return: Sympy Matrix object of the DH transformation matrix
    """
    # Create the transformation matrix template
    Ta_b = Matrix([[            cos(theta),           -sin(theta),           0,             a],
                   [ sin(theta)*cos(alpha), cos(theta)*cos(alpha), -sin(alpha), -sin(alpha)*d],
                   [ sin(theta)*sin(alpha), cos(theta)*sin(alpha),  cos(alpha),  cos(alpha)*d],
                   [                     0,                     0,           0,             1]])
    # Substitute in the DH parameters into the matrix
    Ta_b = Ta_b.subs(s)
    return Ta_b

def rot_x(q):
    r_x = Matrix([[ 1,      0,       0],
                  [ 0, cos(q), -sin(q)],
                  [ 0, sin(q),  cos(q)]])
    return r_x

def rot_y(q):
    r_y = Matrix([[  cos(q), 0, sin(q)],
                  [       0, 1,      0],
                  [ -sin(q), 0, cos(q)]])
    return r_y

def rot_z(q):
    r_z = Matrix([[ cos(q), -sin(q), 0],
                  [ sin(q),  cos(q), 0],
                  [      0,       0, 1]])
    return r_z

# Conversion factors between radians and degrees
rtd = 180 / pi
dtr = pi / 180

# Define DH parameter symbols
theta1, theta2, theta3, theta4, theta5, theta6, theta7 = symbols('theta1:8')
alpha0, alpha1, alpha2, alpha3, alpha4, alpha5, alpha6 = symbols('alpha0:7')
d1, d2, d3, d4, d5, d6, d7 = symbols('d1:8')    # link offsets
a0, a1, a2, a3, a4, a5, a6 = symbols('a0:7')    # link lengths

# Modified DH params for KUKA KR210
s = {alpha0:     0, d1:  0.75, a0:      0,
     alpha1: -pi/2, d2:     0, a1:   0.35, theta2: theta2 - pi/2,
     alpha2:     0, d3:     0, a2:   1.25,
     alpha3: -pi/2, d4:  1.50, a3: -0.054,
     alpha4:  pi/2, d5:     0, a4:      0,
     alpha5: -pi/2, d6:     0, a5:      0,
     alpha6:     0, d7: 0.303, a6:      0, theta7: 0,}

# EE location and orientation
#px = req.poses[x].position.x
#py = req.poses[x].position.y
#pz = req.poses[x].position.z
#(roll, pitch, yaw) = tf.transformations.euler_from_quaternion(
#    [req.poses[x].orientation.x, req.poses[x].orientation.y,
#     req.poses[x].orientation.z, req.poses[x].orientation.w])

# Test pose and orientation of the end effector with all angles at 0 degrees
px = 2.1529
py = 0.0
pz = 1.9465
roll = 0.0
pitch = 0.0
yaw = 0.0

##############################################################################
# Step 1: Convert pose and orientation into a transformation matrix to
#   compute the wrist center

# Build EE roation matrix
Rrpy = rot_z(yaw) * rot_y(pitch) * rot_x(roll)
lx = Rrpy[0, 0]
ly = Rrpy[1, 0]
lz = Rrpy[2, 0]

# Calculate the wrist center (test should be (1.85, 0, 1.947)
wx = px - (s[d7] + s[d6]) * lx
wy = py - (s[d7] + s[d6]) * ly
wz = pz - (s[d7] + s[d6]) * lz
#print('WC location: (%s, %s, %s)' % (wx, wy, wz))

##############################################################################
# Step 2: Calculate thetas for joint 1, 2 and 3 (determines EE position)

# Determine the angle for joint 1
theta1 = atan2(wy, wx).evalf()
theta1 = np.clip(theta1, -185*dtr, 185*dtr)

# Find the coordinates of x2, y2 and z2 considering theta 1
x2 = s[a1] * cos(theta1)
y2 = s[a1] * sin(theta1)
z2 = s[d1]

# Find the x, y and z distances between joint 2 and the wrist center
X2_WC = wx - x2
Y2_WC = wy - y2
Z2_WC = wz - z2

# Find the distances between joint 2 and the wrist center
L2_WC = sqrt(X2_WC**2 + Y2_WC**2 + Z2_WC**2)

# Find the distance between joint 2 and the wrist center
L3_4 = 0.96     # Distance from joint 3 to joint 4
L4_5 = 0.54     # Distance from joint 4 to joint 5 (WC)
L3_4_x = sqrt(L3_4**2 + abs(s[a3])**2)      # X distance from joint 3 to joint 4
phi1 = pi - atan2(abs(s[a3]), L3_4_x)
L3_WC = sqrt(L3_4**2 + L4_5**2 - 2 * L3_4 * L4_5 * cos(phi1))

# Determine the angle for joint 3
cos_phi2 = (L2_WC**2 - L3_WC**2 - s[a2]**2) / (-2 * L3_WC * s[a2])
if abs(cos_phi2) > 1:
    cos_phi2 = 1
    print('cos_phi2 is greater than 1')
phi2 = atan2(sqrt(1 - cos_phi2**2), cos_phi2)
theta3 = (pi/2 - phi2).evalf()
theta3 = np.clip(theta3, -210*dtr, (155-90)*dtr)

# Determine the angle for joint 2
L2_WC_xy = sqrt(X2_WC**2 + Y2_WC**2)
phi3 = atan2(Z2_WC, L2_WC_xy)
cos_phi4 = (L3_WC**2 - L2_WC**2 - s[a2]**2) / (-2 * L2_WC * s[a2])
if abs(cos_phi4) > 1:
    cos_phi4 = 1
    print('cos_phi4 is greater than 1')
phi4 = atan2(sqrt(1 - cos_phi4**2), cos_phi4)
theta2 = (pi/2 - (phi3 + phi4)).evalf()
theta2 = np.clip(theta2, -45*dtr, 85*dtr)

##############################################################################
# Step 3: Determine the rotation matrix for the spherical wrist joints

# Build the transformation matrices of the first 3 joints
T0_1 = build_mod_dh_matrix(s=s, theta=theta1, alpha=alpha0, d=d1, a=a0)
T1_2 = build_mod_dh_matrix(s=s, theta=theta2, alpha=alpha1, d=d2, a=a1)
T2_3 = build_mod_dh_matrix(s=s, theta=theta3, alpha=alpha2, d=d3, a=a2)

# Rotation matrix of the first three joints
R0_3 = (T0_1 * T1_2 * T2_3).evalf(subs={theta1: theta1,
                                        theta2: theta2,
                                        theta3: theta3})[0:3, 0:3]

# Correction to account for orientation difference between definition of
#   gripper link in the URDF file and the DH convention.
#   (rotation around Z axis by 180 deg and Y axis by -90 deg)
R_corr = simplify(rot_z(pi) * rot_y(-pi/2))

# Calculate the symbolic rotation matrix of the spherical wrist joints
R3_6 = R0_3.T * Rrpy * R_corr

##############################################################################
# Step 4: Calculate the spherical wrist joint angles by converting the
#   the rotation matrix to Euler angles

# tf requires a numpy matrix instead of a sympy matrix
R3_6_np = np.array(R3_6).astype(np.float64)

# Convert the rotation matrix to Euler angles using tf
alpha, beta, gamma = tf.transformations.euler_from_matrix(
    R3_6_np, axes='rxyz')   # xyx, yzx, xyz
theta4 = alpha
theta5 = beta
theta6 = gamma

theta4 = np.pi/2 + theta4
theta5 = np.pi/2 - theta5
#theta6 = theta6 - 2*np.pi

#r11 = R3_6[0, 0]
#r12 = R3_6[0, 1]
#r13 = R3_6[0, 2]
#r21 = R3_6[1, 0]
#r31 = R3_6[2, 0]
#r32 = R3_6[2, 1]
#r33 = R3_6[2, 2]
#
## Pitch angle; rotation around the y-axis
#theta5 = atan2(-r31, sqrt(r11**2 + r21**2)).evalf()
#theta5 = np.clip(theta5, -125*dtr, 125*dtr)
#
#if r31 == 1:
#    # Gimbal lock at pitch = -90
#    theta4 = 0                          # yaw = 0
#    theta6 = atan2(-r12, -r13).evalf()  # roll
#    print('Gimbal lock at pitch = -90')
#elif r31 == -1:
#    # Gimal lock at pitch = 90
#    theta4 = 0                          # yaw = 0
#    theta6 = atan2(r12, r13).evalf()    # roll
#    print('Gimbal lock at pitch = 90')
#else:
#    # General orientation
#
#    # Yaw angle; rotation around the z-axis
#    theta4 = (atan2(r21, r11)).evalf()
#    theta4 = np.clip(theta4, -350*dtr, 350*dtr)
#
#    # Roll angle; rotation around the x-axis
#    theta6 = (atan2(r32, r33)).evalf()
#    theta6 = np.clip(theta6, -350*dtr, 350*dtr)

print('Theta 1: %s' % theta1)
print('Theta 2: %s' % theta2)
print('Theta 3: %s' % theta3)
print('Theta 4: %s' % theta4)
print('Theta 5: %s' % theta5)
print('Theta 6: %s' % theta6)


#  https://www.codingame.com/ide/puzzle/the-helpdesk

import sys,math

def getWert(zwDict):
    ausgabe=""
    for nr in sorted(zwDict):
        wert = zwDict[nr]
        ausgabe+=str(wert)+" "
    return ausgabe

#3  1 1 1 21 1 1 1 1   0 0 0 2 0 0 0 0
worktime=40
eList=[0.5, 0.5, 0.5, 2.0, 0.5, 0.5, 0.5, 0.5]
hList=[180, 180, 180, 10, 180, 180, 180, 180, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]

#4   1 2   0 1
worktime=20
eList=[1.0,2.0]
hList=[30,40,10]

#5    4 4 4 7 7 4     3 3 1 4 5 3
worktime=20
eList=[1.0, 0.5, 0.75, 1.25, 1.5, 1.0]
hList=[50, 50, 10, 50, 30, 20, 60, 30, 40, 40, 60, 60, 50, 10, 10, 10, 50, 10, 20, 70, 10, 40, 10, 40, 60, 40, 40, 40, 20, 70]

#6
worktime=20
eList=[0.5, 0.75, 1.0, 1.25, 0.5]
hList=[30, 40, 30, 40, 60, 10, 30, 40, 10, 20, 60, 30, 40, 70, 20, 60, 10, 70, 10, 20, 40, 51, 60, 40, 20]

#- When a counter is available,
# it will instantly start with either helping the first visitor waiting in line,
#  or (if worktime minutes have passed) have a 10 minute break.

pos1=-1;pos2=-1;bisherPos=-1;nr=0
persDict={};breakDict={};timeDict={};arbeitDict={};bzDict={}
for i in range(len(eList)):
    persDict[i]=0;breakDict[i]=0;timeDict[i]=-100+i;arbeitDict[i]=0
for h in hList:
    while True:
        newDict = sorted(timeDict.items(), key=lambda kv: kv[1])
        pos1=newDict[0][0];pos2=newDict[1][0]
        print("{}#h: {} pos: {}  {}".format(nr,h,pos1,timeDict),file=sys.stderr)
        if nr == 24:
            a=0
        if arbeitDict[pos1] >= worktime:
            arbeitDict[pos1]=0
            timeDict[pos1]+=10
            breakDict[pos1]+=1
    #    else:
    #        if bisherPos > -1 and timeDict[pos1] == timeDict[bisherPos]:
    #            pos1 = bisherPos
    #        break
    #    if nr == len(hList) - 1 and timeDict[pos1] == timeDict[pos2]:
    #        break
    #    bisherPos=pos1

        if nr == len(hList) - 1:
            for aPos,tWert in timeDict.items():
                if arbeitDict[aPos] >= worktime and timeDict[aPos] < timeDict[pos1]:
                    arbeitDict[aPos]=0
                    timeDict[aPos]+=10
                    breakDict[aPos]+=1
        if (timeDict[pos1] <= timeDict[pos2])  or (arbeitDict[pos2]>=worktime and timeDict[pos1] <= timeDict[pos2]+10):
            break
    dauer=h/eList[pos1]
    arbeitDict[pos1]+=dauer
    timeDict[pos1] = dauer if timeDict[pos1] < 0 else timeDict[pos1]+dauer
    persDict[pos1]+=1
    nr+=1

print(getWert(persDict)[:-1])
print(getWert(breakDict)[:-1])


"""
Summary => will control the pen plotter.

Description => will control the pen plotter and print off the x and y
        coordinates given to it at run time. This object when run will go
        through a drawing out all the coordinates and making connections
        between each point. Then draw those lines out.

        When you want to start the process, call the method run().
        Then this method will go through the process of printing out the
        given coordinates.

Author => Matthew Howard (mah60).
Version => 0.1 - 15/03/2018 - This is the basic set up to this class.
                it has been designed to take coordinates and scale When
                first drawn. Then will proccess the coordinates to the plotter
                when the method run() is called.

                The methods run(), draw(), check_move(), connections(),
                move(), coordinate_to_plotter(), test_coords() have been made.
"""
from xy_coordinate import XYCoordinate
from serial_control import SerialControl as serial
import numpy as np

class PlotterController(object):
    """
    Summary => will control the proccess to plot out the coordinates given.

    Description => will process the coordinates given to it and print out those
            coordinates on the pen plotter when run() is called.

            This will make connections between each coordinate and draw
            lines between them.

    Args => coordinates - list - a list of xy coordinates.
            scale - float - this will be the scale of which you want to be
                    drawn at. e.g. half the size will be 2 and double the
                    size will be 0.5

    Return => None
    """

    def __init__(self, coordinates, scale):
        """
        Summary => initialize the PlotterController.

        Description => will create the plotter controller. Will take and input
            of coordinates and place them into a list until the method run()
            is called. To start the process.

        Args => coordinates - list - a list of xy coordinates
                scale - float - this will be the scale of which you want to be
                        drawn at. e.g. half the size will be 2 and double the
                        size will be 0.5

        Return => None
        """
        self.ser = serial("/dev/ttyUSB0")
        self.coordinates = coordinates
        self.scale = scale

    def run(self):
        """
        Summary => run the PlotterController.

        Description => will run the plotter controller, this will take the
            coordinates given and turn them into lines. Using a linked-list
            format.

            After the lines have been made it will print out the list of lines

        Args => None

        Return => None
        """
        self.test_coords()  # generate a bunch of test_coords
        self.draw()

    def draw(self):
        """
        Summary => draw the list of coordinates.

        Description => will loop through the list of coordinates given. Then
            will move to the given point and put the pen down. The method will
            proceed to find all connections to that point and draw to the new
            location. Then will return to the current location.

            After complete each coordinate value will be set to drawn,
            when then have been checked. So the program does not return to
            that location when drawing the other locations.

        Args => None

        Return => None
        """
        # select pen 1
        self.ser.write('SP 1;')
        for point in self.coordinates:
            # place pen at this points location
            x = self.coordinate_to_plotter(point.get_x())
            y = self.coordinate_to_plotter(point.get_y())
            str_command = "PA {} {};".format(x, y)
            self.ser.write(str_command)
            # put pen down
            self.ser.write('PD;')

            # check if there is a connection in each direction,
            # think of it like a compass North, North-East etc.
            self.check_move(point, x, y)
            # mark this point as drawn
            point.plotted()
            # at end bring pen back up
            self.ser.write("PU;")
        # select pen 0, disengage pen
        self.ser.write('SP 0;')

    def check_move(self, point, x, y):
        """
        Summary => check where the plotter can move to.

        Description => will check in all directions, north, west, north-West
            etc. To see where the pen can move_to following the constraits of
            other coordinates to this one.

            If the location has a connection to another point it will draw
            to that point and then return.

            Will check first if that point has already been drawn out to
            reduce the amount of cross overs.

        Args => point - XYCoordinate - this is the current location
                        coordinates.
                x - int - the x location of the current coordinate translated
                        to the plotters coordinates.
                y - int - the y location of the current coordinate translated
                        to the plotters coordinates.

        Return => None
        """
        for move_to in self.coordinates:
            # check if it is the same location as current point
            if point != move_to:
                # check if move_to has already been drawn
                if not move_to.is_plotted():
                    # check North
                    if self.connection(point, move_to, 0, 1):
                        self.move(point, move_to, x, y)
                    # check North-East
                    if self.connection(point, move_to, 1, 1):
                        self.move(point, move_to, x, y)
                    # check East
                    if self.connection(point, move_to, 1, 0):
                        self.move(point, move_to, x, y)
                    # check South-East
                    if self.connection(point, move_to, 1, -1):
                        self.move(point, move_to, x, y)
                    # check South
                    if self.connection(point, move_to, 0, -1):
                        self.move(point, move_to, x, y)
                    # check South-West
                    if self.connection(point, move_to, -1, -1):
                        self.move(point, move_to, x, y)
                    # check West
                    if self.connection(point, move_to, -1, 0):
                        self.move(point, move_to, x, y)
                    # check North-West
                    if self.connection(point, move_to, -1, 1):
                        self.move(point, move_to, x, y)

    def connection(self, point, move_to, x_modifier, y_modifier):
        """
        Summary => check if there is a connection between two points.

        Description => will check if there is a connection between two points,
            using a the x and y x_modifier to the current location of the pen.

            This will check if they are within the distance of connection of
            each other. To be able to connect to each other.

        Args => point - XYCoordinate - this is the current location
                        coordinates.
                move_to - XYCoordinate - this is the location of the
                        point that we may be moving to. If the test is
                        passed
                x_modifier - int - the modifier to the x plane, to compare if
                        it can move to given area.
                y_modifier - int -  the modifier to the y plane, to compare if
                        it can move to given area.

        Return => True if the two points match, when the current location is
                    modifed.
        """
        # check if both the y and x location are the same to the move_to point
        if ((point.get_x() + x_modifier) == move_to.get_x()) and (
                    (point.get_y() + y_modifier) == move_to.get_y()):
            # if they are the same when modifed return true
            return True
        else:
            # if they are not the same when modifed return false
            return False

    def move(self, point, move_to, x, y):
        """
        Summary => move to the new location and returns to point.

        Description => will move_to the new location given. After
                this the pen will be brought up and returns back to the
                current location point.

        Args => point - XYCoordinate - this is the current location
                        coordinates.
                move_to - XYCoordinate - this is the new location
                                coordinates.
                x - int - the x location of the current coordinate translated
                        to the plotters coordinates.
                y - int - the y location of the current coordinate translated
                        to the plotters coordinates.

        Return => int - the plotter value, that has been scaled.
        """
        # move pen to new found location, then return to current
        # point location
        str_command = "PA {} {};".format(self.coordinate_to_plotter(
                                      move_to.get_x()),
                                      self.coordinate_to_plotter(
                                      move_to.get_y()))
        self.ser.write(str_command)
        # pull pen up
        self.ser.write("PU;")
        # return to current location
        str_command = "PA {} {};".format(x, y)
        self.ser.write(str_command)
        # put pen down at returned point
        self.ser.write("PD;")

    def coordinate_to_plotter(self, xy_value):
        """
        Summary => will translate coordinates to plotter values.

        Description => will translate coordinates to plotter values. Which
            is fourty times the coordinate value for one point.

            The final value will be devided by the scale. Making it so
            the final result can be scaled up or down.

        Args => xy_value - int - the curret coordinate value, that wants to
                    be translated to plotter values.

        Return => int - the plotter value, that has been scaled.
        """
        return round(((xy_value * 40)/self.scale))

    def test_coords(self):
        """
        Summary => generates test values for the coordinates.

        Description => will create test values for the coordinates. To
        be sent through the plotting stages.

        Args => None

        Return => None
        """
        self.coordinates = np.zeros(16, dtype=XYCoordinate)
        self.coordinates[0] = XYCoordinate(1, 1)
        self.coordinates[1] = XYCoordinate(1, 10)
        self.coordinates[2] = XYCoordinate(1, 2)
        self.coordinates[3] = XYCoordinate(1, 3)
        self.coordinates[4] = XYCoordinate(1, 4)
        self.coordinates[5] = XYCoordinate(1, 5)
        self.coordinates[6] = XYCoordinate(1, 6)
        self.coordinates[7] = XYCoordinate(2, 4)
        self.coordinates[8] = XYCoordinate(3, 4)
        self.coordinates[9] = XYCoordinate(4, 5)
        self.coordinates[10] = XYCoordinate(5, 6)
        self.coordinates[11] = XYCoordinate(7, 1)
        self.coordinates[12] = XYCoordinate(7, 2)
        self.coordinates[13] = XYCoordinate(7, 3)
        self.coordinates[14] = XYCoordinate(7, 5)
        self.coordinates[15] = XYCoordinate(8, 8)


"""Sensor device."""
from __future__ import annotations

from flowchem.components.flowchem_component import FlowchemComponent
from flowchem.devices.flowchem_device import FlowchemDevice

class Sensor(FlowchemComponent):
    """A generic sensor."""

    def __init__(self, name: str, hw_device: FlowchemDevice) -> None:
        super().__init__(name, hw_device)
        self.add_api_route("/power-on", self.power_on, methods=["PUT"])
        self.add_api_route("/power-off", self.power_off, methods=["PUT"])
        # Ontology: HPLC isocratic pump
        self.component_info.owl_subclass_of.append(
            "http://purl.obolibrary.org/obo/NCIT_C50166",
        )

    async def power_on(self):
        """"""
        ...

    async def power_off(self):
        ...


import random
import sosbet
import datetime
import math
import sosfish_constants

def SellerText(data, user):

	fish = FishOfTheDay(data)

	output = f"You hear a local merchant offering to buy three {fish} for a {sosbet.CURRENCY}."

	if fish in data[user]["catchlog"].keys():

		if fish not in data[user]["sell_log"].keys():
			data[user]["sell_log"][fish] = 0

		count = data[user]["catchlog"][fish] - data[user]["sell_log"][fish]

		output += f" You have {count} {fish}"

		if count>=3:
			output += ", sell three of them with \"!fish sell\"."
		else:
			output += "."

	else:
		output += "\nUnfortunately you do not have any."

	return output

def Sell(data, user):
	fish = FishOfTheDay(data)

	if fish in data[user]["catchlog"].keys():

		if fish not in data[user]["sell_log"].keys():
			data[user]["sell_log"][fish] = 0
		count = data[user]["catchlog"][fish] - data[user]["sell_log"][fish]
		if count>=3:
			data[user]["sell_log"][fish] += 3
			sosbet.addMoney(user, 1)
			sosbet.saveMoney()
			return f"You sell three {fish} for {sosbet.CURRENCY}.\nYour new balance: {sosbet.balance(user, user)}"
		else:
			return f"You do not have enough {fish}."
	return f"You do not have any {fish}"

def FishOfTheDay(data):
	current_time = datetime.datetime.now()

	index = current_time.day + current_time.month * 31

	#index = random.randrange(1000)

	location_id =  int( math.floor(index/4) % len(data.keys()) )
	location_fish_id = (index%4)
	location = list(data.keys())[location_id]

	while "Mead and Madness" in location or "Cat Cafe" in location:
		index+=10
		location_id =  int( math.floor(index/4) % len(data.keys()) )
		location_fish_id = (index%4)
		location = list(data.keys())[location_id]

	location_fish = data[location]["fish"][str(location_fish_id)]["name"]

	while location_fish in sosfish_constants.pokemon["ALL"]:
		index+=10
		location_id =  int( math.floor(index/4) % len(data.keys()) )
		location_fish_id = (index%4)
		location = list(data.keys())[location_id]
		location_fish = data[location]["fish"][str(location_fish_id)]["name"]

	return location_fish

def amendProfile(data, name):
	if "sell_log" not in data[name]:
		data[name]["sell_log"] = {}


from django.urls import path
from .views import solicitar_turno, turnos_cliente, turnos_veterinario, VerTurnoVeterinario, ver_turno_cliente

urlpatterns = [
    path('solicitar_turno', solicitar_turno, name='solicitar_turno'),
    path('turnos_cliente', turnos_cliente, name='turnos_cliente'),  # No me gusta el nombre, después lo discutimos
    path('turnos_veterinario', turnos_veterinario, name='turnos_veterinario'),
    path('ver_turno_veterinario/<int:turno_id>', VerTurnoVeterinario.as_view(), name="ver_turno_veterinario"),
    path('ver_turno_cliente/<int:turno_id>', ver_turno_cliente, name='ver_turno_cliente')
]


ssize = 0
n = 0
k = 0
result = 0
nth = 0
n = int(input())
stos = [0] * n
for i in range(n):
    nth, k = [int(x) for x in input().split()]
    while ssize > 0 and stos[ssize-1] > k: ssize = ssize - 1
    if ssize == 0 or stos[ssize-1] < k:
        result = result + 1
        stos[ssize] = k
        ssize = ssize + 1
print(result)


import numpy as np

def InsertionSort(vetor):
  size = len(vetor)
  for i in range(size):
    marcado = vetor[i]
    j = i - 1
    while j >= 0 and marcado < vetor[j]:
      vetor[j+1] = vetor[j]
      j -= 1
    vetor[j+1] = marcado
  return vetor

print(InsertionSort(np.array([10, 9, 8, 7, 2, 0, 3])))
print(InsertionSort(np.array([10, 5, 4, 3, 2, 1, 0])))


from html_parser import MyHTMLParser
import urllib.request
from bs4 import BeautifulSoup
import requests

from language_detecter import LanguageDetector

parser = MyHTMLParser()
#url = "https://www.vpnverbinding.nl/beste-vpn/netflix/"
url = "https://www.vpnconexion.es/blog/mejor-vpn-para-netflix/?_ga=2.224715098.1306859094.1600959792-1235625754.1600959792"
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
response = urllib.request.urlopen(req)
html = response.read()
page = requests.get(url).text
soup = BeautifulSoup(page, "html.parser")
print("Analyzing....")
print(soup.title.string)

#get the webpage language
language = soup.html["lang"].replace("-","_")

print("The language webpage is: "+language)

lang_validate = LanguageDetector(language)

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

#find the titles h3,h2,h1 too text in p, div and span inside the divs
contentTable  = soup.find('div')
rows  = contentTable.find_all(['h3', 'h2', 'h1', 'p', 'div', 'span', 'img', 'li', 'ul'])
for row in rows:
	if not (row.string is None):
	   #print(row.string)
	   #print("············")
	   #append to set the blocks read in the webpage. (use Set for no repeated)
	   lang_validate.html_blocks.add(row)

for block in lang_validate.html_blocks:
	lang_validate.is_in_setlanguage(block.string.strip())

print("-----# blocks ------> "+str(len(lang_validate.html_blocks)))

print("=========================")
print("Words Not translated....")
print("=========================")
#lang_validate.clear_not_translated_words()
for i in lang_validate.not_translated:
	print(i)


import math

#1.
def calculateSphere(radius):

    v = 4/3*math.pi*radius**3
    a = 4*math.pi*(radius**2)

    print("The Volume of your sphere is " +str(v))
    print("the Area of your sphere is " +str(a))
#2.
def calPizzaSquarePrize(diameter,prize):
    radius = diameter/2
    area = math.pi*radius**2
    prizePerSquareInch = area/prize

    print("The prize of every square inch of your pizza is "+str(prizePerSquareInch))

#3.
def calculateMolecular(H,C,O,name):
    molWeight= 1.00794*H+C*12.0107+O*15.9994
    print("the molecular weight of "+name+" is " +molWeight)

#4.
def lightningDistance(seconds):
    distance = 1150*seconds/5280
    print("The distance between the lightning strikes is "+str(round(distance,2))+ " miles.")

#5.
def CoffeeOrderPrize(pounds):

    prize = 1.50 + 10.50*pounds+0.86*pounds
    print("The total prize for your order is " + str(prize) + " dollars.")

#6.
def slope(x1,x2,y1,y2):

    slope=(y2-y1)/(x2-x1)
    print("The slope of your line is "+ slope)

#7.
def pointDistance(x1,x2,y1,y2):

    distance = math.sqrt((x2-x1)**2+(y2-y1)**2)
    print("The distance between the two points is " + distance)

#8.
def calculateEaster(year):

    c = year//100
    print(c)

    epact=(8+(c//4)-c+((8*c+13)//25)+11*(year%19))%30

    print("easter falls on " +str(epact) )

#9.
def calculateTrianleArea(a,b,c,unit):

    s = (a+b+c)/2

    area = math.sqrt(s*(s-a)*(s-b)*(s-c))

    print("The area of your triangle is " + str(area) + " " + unit)

#10.
def calculateLadder(height,degreesAngle,unit):

    radians = (math.pi/180)*degreesAngle

    length= height/math.sin(radians)

    print("The length required for the ladder to reach the given height is " + str(round(length,2)) + " " + unit)

# 11.
def sumN(n):

    if n == 1:
        return 1
    else :
        return sumN(n-1) + n

#12.
def sumNcubed(n):
    if n == 1:
        return 1
    else :
        return sumNcubed(n-1) + n **3

#13.
def sumSeries():

    count = int(input("Count of numbers to add "))

    nums = list()
    sum = 0

    for i in range(count):

        num = int(input("Enter a number to add in your list "))
        nums.append(num)
        sum += num

    print("the sum of "+ str(nums)+ " is " + str(sum))

#14.

def averageSumSeries():

    count = int(input("Count of numbers to calculate average "))

    nums = list()
    average = 0

    for i in range(count):

        num = int(input("Enter a number to add in your list "))
        nums.append(num)
        average += num

    average /= count
    print("the the average of "+ str(nums)+ " is " + str(average))

#15.

def estimatePi(n):

    x=4
    y=1
    minus = True
    estimate = x/y

    for j in range(n-1):

        if minus:

            y +=2
            estimate -= x/y
            minus = False

        elif minus != True:
            y+=2
            estimate += x/y
            minus = True

    print(estimate)

#16.

def fib(n):

    if n == 1 or n == 2:
        return 1
    else:
        return fib(n-1) + fib(n-2)

#17.
def guessSquareRoot():
    x = float(input("Enter a number to approximate the square root of "))
    guesses = int(input('Enter the number of times to approximate '))
    guess = x/2

    for i in range(guesses):
       newX=(guess+(x/guess))/2

    print(newX)

print(sumNcubed(3))


'''
Consider a special family of Engineers and Doctors. This family has the following rules:

Everybody has two children.
The first child of an Engineer is an Engineer and the second child is a Doctor.
The first child of a Doctor is a Doctor and the second child is an Engineer.
All generations of Doctors and Engineers start with an Engineer.
We can represent the situation using this diagram:

                E
           /         \
          E           D
        /   \        /  \
       E     D      D    E
      / \   / \    / \   / \
     E   D D   E  D   E E   D
Given the level and position of a person in the ancestor tree above, find the profession of the person.
Note: in this tree first child is considered as left child, second - as right.
'''

'''
dynamic programming solution. This is exponential time, O(2^level), since we are processing each node in the tree.
We can optimize a little by checking whether we have found
(level,pos) in the middle of the while loop and stop.
'''
def findProfession(level, pos):
        # make a memo to track earlier outputs {(level,position) : "Doctor" or "Engineer"}
        # For simplicity, we can have True represent Engineer and False represent Doctor.
        memo = {(1,1): True}
        # Our inductive step:
        # memo[(i,j)] == memo[(i+1,2*j-1)] and memo[(i+1,2*j)] = not memo[(i,j)]
        # In other words, when we go a level down from (i,j), the value on the left
        # (which will now be at position 2*j-1) is equal to the value at (i,j), and
        # The value to the right (at position 2*j) will be the opposite of the value at
        # (i,j).
        i = 1
        while i < level:
                temp_memo = {}
                for tup in memo:
                        j = tup[1]
                        temp_memo[(i+1,2*j-1)] = memo[(i,j)]
                        temp_memo[(i+1,2*j)] = not memo[(i,j)]
                for new_tup in temp_memo:
                        memo[new_tup] = temp_memo[new_tup]
                i += 1
        if memo[(level,pos)]:
                return "Engineer"
        else:
                return "Doctor"

'''
A better solution would be to keep in mind the number of switches as we go down the tree. If we go left, there is no
switch. If we go right, the profession switches. There are 2^(level-1) professions in the level we are examining. Consider
level =4, pos = 3:
                E
           /         \
          E           D
        /   \        /  \
       E     D      D    E
      / \   / \    / \   / \
     E   D *D* E  D   E E   D
The number of switches for each position:
0
0 1
0 1, 1 2
0 1, 1 2, 1 2, 2 3
0 1, 1 2, 1 2, 2 3, 1 2, 2 3, 2 3, 3 4

Each position in one level spawns two new positions on the next level. The number of switches on the left is the same, and the number of
switches on the right is one greater.
'''
def switch_array(level):
	'''
	Input a level of the binary tree (counting from level 1 as the root).
	Output an array of the number of switches for each position on this level.
	'''
	switch_arr = [0]
	for i in range(level-1):
		temp = [k + 1 for k in switch_arr]
		switch_arr.extend(temp)
	return switch_arr

#print(switch_array(3))

def findProfession2(level,pos):
	switch_arr = switch_array(level)
	if switch_arr[pos-1] % 2 == 0:
		return "Engineer"
	else:
		return "Doctor"

#print(findProfession2(25,1000))

'''
This is faster than it was before, only timing out of one test rather than two. AHA. Tricksy, this is. By cheating,
I have learned that we can use binary representation to help us out.
'''

def findProfession3(level,pos):
    bits  = bin(pos-1).count('1')
    if bits%2 == 0:
        return "Engineer"
    else:
        return "Doctor"

'''
I don't understant this very well yet.
'''

'''
A different, better, more readable recursive solution
'''
def findProfession4(level,pos):
    if level == 1:
        return "Engineer"
    else:
        if pos %2 == 1:
            return findProfession(level-1,(pos+1)//2)
        else:
            parent_profession = findProfession(level-1,pos//2)
            if parent_profession == "Engineer":
                return "Doctor"
            else:
                return "Engineer"


import os
import re
import sys

def main(version):
    if len(sys.argv) != 4:
        print("[ERROR] Missing one of arguments: version (PREVIOUS) such as: X.Y.Z or userid or token")
        sys.exit()
    version = sys.argv[1]
    userid = sys.argv[2]
    token = sys.argv[3]
    ver_pattern = re.compile("^[0-9]+\.[0-9]+\.[0-9]+$")
    if not ver_pattern.match(version):
        print("[ERROR] Wrong argument version (PREVIOUS). It must be: X.Y.Z")
        sys.exit()
    cmd = 'github_changelog_generator --user {userid} --project react-bootstrap-combobox -t {token} --since-tag v{version} --no-unreleased'.format(**locals())
    os.system(cmd)

if __name__ == "__main__":
    main(sys.argv)


import cv2
import numpy as np
from calibrate_frame import *
from socket import gethostname

class Camera(object):
    """
    Camera access wrapper.
    """

    def __init__(self, pitch=0, port=0, test = 0):
        self.capture = cv2.VideoCapture(port)
        self.pitch = pitch
        self.test = test

    def get_frame(self, radial_dist=0):
        """
        Retrieve a frame from the camera.

        Returns the frame if available, otherwise returns None.
        """

        if self.test == 0:
            status, frame = self.capture.read()
            frame = step(frame, self.pitch)
        elif self.test == 1:
            frame = cv2.imread('pitch0.png')

        return frame

    def close(self):
        self.capture.release()


import integration_logic
from unittest import TestCase

class TestReadAndPreprocess(TestCase):
    def test_integration(self):
        with open(integration_logic.integration_sources + 'complex_preprocessed.c') as expected_file:
            expected_result = expected_file.read()
        preprecessed_source = integration_logic.read_and_preprocess()
        self.assertEquals(expected_result, preprecessed_source)