import os
import unittest

import numpy as np

import pydrake
from pydrake.attic.multibody import shapes
from pydrake.common.eigen_geometry import Isometry3

class TestShapes(unittest.TestCase):
    def test_api(self):
        box_size = [1., 2., 3.]
        radius = 0.1
        length = 0.2

        box = shapes.Box(size=box_size)
        self.assertTrue(np.allclose(box.size, box_size))
        self.assertEqual(box.getPoints().shape, (3, 8))
        self.assertEqual(len(box.getFaces()), 12)
        self.assertEqual(len(box.getFaces()[0]), 3)

        sphere = shapes.Sphere(radius=radius)
        self.assertEqual(sphere.radius, radius)
        self.assertEqual(sphere.getPoints().shape, (3, 1))
        with self.assertRaises(RuntimeError):
            sphere.getFaces()

        cylinder = shapes.Cylinder(radius=radius, length=length)
        self.assertEqual(cylinder.radius, radius)
        self.assertEqual(cylinder.length, length)

        capsule = shapes.Capsule(radius=radius, length=length)
        self.assertEqual(capsule.radius, radius)
        self.assertEqual(capsule.length, length)

        pts = np.tile(box_size, (10, 1)).T
        mesh_points = shapes.MeshPoints(pts)
        self.assertEqual(mesh_points.getPoints().shape, (3, 10))

        obj_mesh_path = os.path.join(
            pydrake.getDrakePath(), "examples/quadrotor/quadrotor_base.obj")
        obj_mesh_uri = "box_obj"
        mesh = shapes.Mesh(uri=obj_mesh_uri, resolved_filename=obj_mesh_path)
        self.assertTrue(np.allclose(mesh.scale, [1., 1., 1.]))
        self.assertEqual(mesh.uri, obj_mesh_uri)
        self.assertEqual(mesh.resolved_filename, obj_mesh_path)

    def test_visual_element_api(self):
        material_in = [0.3, 0.4, 0.5, 0.6]
        material_in_2 = [0.6, 0.7, 0.8, 0.9]
        box = shapes.Box(size=[1., 1., 1.])
        visual_element_np = shapes.VisualElement(box, np.eye(4), material_in)
        visual_element_isom = shapes.VisualElement(
            box, Isometry3.Identity(), material_in)
        self.assertTrue(np.allclose(visual_element_np.getMaterial(),
                                    material_in))
        visual_element_np.setMaterial(material_in_2)
        self.assertTrue(np.allclose(visual_element_np.getMaterial(),
                                    material_in_2))


fname = input("Enter a file name: ")

try:
    handle = open(fname)
except:
    print("Invalid file name.")
    quit()

domains = dict()
for line in handle:
    if not line.startswith("From "):
        continue
    words = line.split()
    domain = words[1].split("@")
    domains[domain[1]] = domains.get(domain[1], 0) + 1

print(domains)


from tkinter import *
import pygame as py
import os

window = Tk()
window.title("Ton Player")
window.geometry("650x260")
window.config(bg="black")

py.init()
playstate = 0
mainb = PhotoImage(file="Icons/play.png")
pauseimage = PhotoImage(file="Icons/stop.png")
playimage = PhotoImage(file="Icons/play.png")

def playstop():
    global playstate
    if playstate == 0:
        song = songList.get(ACTIVE)
        py.mixer.music.load(f"Songs/{song}")
        py.mixer.music.play()
        playstate = 1
        mainButton.configure(image=pauseimage)
    elif playstate == 1:
        py.mixer.music.pause()
        playstate = 2
        mainButton.configure(image=playimage)
    else:
        py.mixer.music.unpause()
        playstate = 1
        mainButton.configure(image=pauseimage)

def nextSong():
    current = songList.curselection()
    next = songList.get(current[0] + 1)
    py.mixer.music.load(f"Songs/{next}")
    py.mixer.music.play(loops=0)
    songList.selection_clear(0, END)
    songList.activate(current[0] + 1)
    songList.selection_set(current[0] + 1)

def previousSong():
    current = songList.curselection()
    previous = songList.get(current[0]-1)
    py.mixer.music.load(f"Songs/{previous}")
    py.mixer.music.play(loops=0)
    songList.selection_clear(0, END)
    songList.activate(current[0] - 1)
    songList.selection_set(current[0] - 1)

# App Name
logo = PhotoImage(file="Icons/logo.png")
isim = Label(window, image=logo, text="Ton Player", bg="black", fg="#1db954", font="Helvetica 17", compound="left")
isim.pack()

# Song List
songList = Listbox(window, bg="black", fg="white", width=100, selectbackground="gray", highlightcolor="black", bd=1)
songList.pack()
for i in os.listdir("Songs"):
    if i.endswith(".mp3"):
        songList.insert(END, i)

tustakim = Frame(window)
tustakim.pack()

# Previous Button
previousb = PhotoImage(file="Icons/previous.png")
previousButton = Button(tustakim, bg="black", image=previousb, width=62, height=59, bd=0, command=previousSong)
previousButton.grid(row=0, column=0)

# Play Button
mainButton = Button(tustakim, bg="black", image=mainb, width=62, height=59, bd=0, command=playstop)
mainButton.grid(row=0, column=1)

# Next Button
skipb = PhotoImage(file="Icons/skip.png")
skipButton = Button(tustakim, bg="black", image=skipb, width=62, height=59, bd=0, command=nextSong)
skipButton.grid(row=0, column=2)

window.iconbitmap("Icons/logo.ico")
window.mainloop()


#Purpose: Decode a steganographically coded image
#Author: Dewar P.

from PIL import Image

def hidden_num(pixel):

    r,g,b = pixel

    lsdr = r%10 *100
    lsdg = g%10 *10
    lsdb = b%10 *1

    return(lsdr+lsdg+lsdb)

def hidden_char(X):
    return(chr(X))

def decode(original_pic, N):
    piclist = original_pic.getdata()
    i = 0
    letter = ''
    message = ''

    while i < N:
        num = hidden_num(piclist[i])
        letter = hidden_char(num)
        message = message + letter

        i = i+1
    return message
##Your functions should be written above this line
##Don't modify any of the code below

def testfunctions():
    sample = [(241, 90, 147), (111 , 51, 31) ]
    if hidden_num(sample[0]) != 107:
        print("Your 'hidden_num' function has an error.")

    if hidden_char(107) != 'k':
        print("Your 'hidden_char' function has an error.")

    class dummy:
        def getdata(self):
            return [(241, 90, 147), (111 , 51, 31) ]

    if decode(dummy(), 2) != 'ko':
        print("Your 'decode' function has an error.")

    return

def main():
    print("\n\nTesting your functions.\n\n")
    testfunctions()
    print("\n\nReady to decode.\n\n")
    imgfile = "encoded.png"
    N = 654   # Remeber to set N: given from the decode function
    thepic = Image.open(imgfile)
    print(decode(thepic, N))
    return

###
main()


# This example requires the 'members' privileged intent to use the Member converter.
# This example also requires the 'message_content' privileged intent to function.

import traceback
import typing

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True
intents.message_content = True

bot = commands.Bot('!', intents=intents)

@bot.command()
async def userinfo(ctx: commands.Context, user: discord.User):
    # In the command signature above, you can see that the `user`
    # parameter is typehinted to `discord.User`. This means that
    # during command invocation we will attempt to convert
    # the value passed as `user` to a `discord.User` instance.
    # The documentation notes what can be converted, in the case of `discord.User`
    # you pass an ID, mention or username (discrim optional)
    # E.g. 80088516616269824, @Danny or Danny#0007

    # NOTE: typehinting acts as a converter within the `commands` framework only.
    # In standard Python, it is use for documentation and IDE assistance purposes.

    # If the conversion is successful, we will have a `discord.User` instance
    # and can do the following:
    user_id = user.id
    username = user.name
    avatar = user.display_avatar.url
    await ctx.send(f'User found: {user_id} -- {username}\n{avatar}')

@userinfo.error
async def userinfo_error(ctx: commands.Context, error: commands.CommandError):
    # If the conversion above fails for any reason, it will raise `commands.BadArgument`
    # so we handle this in this error handler:
    if isinstance(error, commands.BadArgument):
        return await ctx.send('Couldn\'t find that user.')
    # The default `on_command_error` will ignore errors from this command
    # because we made our own command-specific error handler,
    # so we need to log tracebacks ourselves.
    else:
        traceback.print_exception(type(error), error, error.__traceback__)

# Custom Converter here
class ChannelOrMemberConverter(commands.Converter):
    async def convert(self, ctx: commands.Context, argument: str):
        # In this example we have made a custom converter.
        # This checks if an input is convertible to a
        # `discord.Member` or `discord.TextChannel` instance from the
        # input the user has given us using the pre-existing converters
        # that the library provides.

        member_converter = commands.MemberConverter()
        try:
            # Try and convert to a Member instance.
            # If this fails, then an exception is raised.
            # Otherwise, we just return the converted member value.
            member = await member_converter.convert(ctx, argument)
        except commands.MemberNotFound:
            pass
        else:
            return member

        # Do the same for TextChannel...
        textchannel_converter = commands.TextChannelConverter()
        try:
            channel = await textchannel_converter.convert(ctx, argument)
        except commands.ChannelNotFound:
            pass
        else:
            return channel

        # If the value could not be converted we can raise an error
        # so our error handlers can deal with it in one place.
        # The error has to be CommandError derived, so BadArgument works fine here.
        raise commands.BadArgument(f'No Member or TextChannel could be converted from "{argument}"')

@bot.command()
async def notify(ctx: commands.Context, target: ChannelOrMemberConverter):
    # This command signature utilises the custom converter written above
    # What will happen during command invocation is that the `target` above will be passed to
    # the `argument` parameter of the `ChannelOrMemberConverter.convert` method and
    # the conversion will go through the process defined there.

    await target.send(f'Hello, {target.name}!')

@bot.command()
async def ignore(ctx: commands.Context, target: typing.Union[discord.Member, discord.TextChannel]):
    # This command signature utilises the `typing.Union` typehint.
    # The `commands` framework attempts a conversion of each type in this Union *in order*.
    # So, it will attempt to convert whatever is passed to `target` to a `discord.Member` instance.
    # If that fails, it will attempt to convert it to a `discord.TextChannel` instance.
    # See: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html#typing-union
    # NOTE: If a Union typehint converter fails it will raise `commands.BadUnionArgument`
    # instead of `commands.BadArgument`.

    # To check the resulting type, `isinstance` is used
    if isinstance(target, discord.Member):
        await ctx.send(f'Member found: {target.mention}, adding them to the ignore list.')
    elif isinstance(target, discord.TextChannel):  # this could be an `else` but for completeness' sake.
        await ctx.send(f'Channel found: {target.mention}, adding it to the ignore list.')

# Built-in type converters.
@bot.command()
async def multiply(ctx: commands.Context, number: int, maybe: bool):
    # We want an `int` and a `bool` parameter here.
    # `bool` is a slightly special case, as shown here:
    # See: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html#bool

    if maybe is True:
        return await ctx.send(number * 2)
    await ctx.send(number * 5)

bot.run('token')


import tkinter as tk
from tkinter import filedialog
from tkinter.ttk import Combobox
import pyperclip
from summarizetext import Summarizer
from languagedropdown import dropdown

# Create an instance of the Summarizer class
summarizer = Summarizer()

# Function to browse for a file
def browse_file():
    filename = filedialog.askopenfilename(filetypes=[("Text Files", "*.txt")])
    file_entry.delete(0, tk.END)
    file_entry.insert(0, filename)

# Function to browse for stopwords file
def browse_stopwords():
    stopwords_file = filedialog.askopenfilename(filetypes=[("Text Files", "*.txt")])
    stopwords_entry.delete(0, tk.END)
    stopwords_entry.insert(0, stopwords_file)

# Function to summarize the text
def summarize_text():
    filename = file_entry.get()
    stopwords_file = stopwords_entry.get()
    language = language_combobox.get()

    if filename and stopwords_file and language:
        summarizer.read_stopwords_from_file(language, stopwords_file)
        with open(filename, 'r', encoding='utf-8') as f:
            text = f.read()
        summary = summarizer.summarize(text)
        output_text.delete(1.0, tk.END)
        output_text.insert(tk.END, summary)
    else:
        output_text.delete(1.0, tk.END)
        output_text.insert(tk.END, "Please provide all the required information.")

# Function to copy the summary to the clipboard
def copy_summary():
    summary = output_text.get(1.0, tk.END)
    pyperclip.copy(summary)

# Create the main window
window = tk.Tk()
window.title("Text Summarizer")

# Create labels and entry fields
file_label = tk.Label(window, text="Text File:")
file_label.grid(row=0, column=0, padx=10, pady=5)
file_entry = tk.Entry(window, width=30)
file_entry.grid(row=0, column=1, padx=10, pady=5)
file_button = tk.Button(window, text="Browse", command=browse_file)
file_button.grid(row=0, column=2, padx=5, pady=5)

stopwords_label = tk.Label(window, text="Stopwords File:")
stopwords_label.grid(row=1, column=0, padx=10, pady=5)
stopwords_entry = tk.Entry(window, width=30)
stopwords_entry.grid(row=1, column=1, padx=10, pady=5)
stopwords_button = tk.Button(window, text="Browse", command=browse_stopwords)
stopwords_button.grid(row=1, column=2, padx=5, pady=5)

language_label = tk.Label(window, text="Language:")
language_label.grid(row=2, column=0, padx=10, pady=5)
language_combobox = dropdown(window, '/Users/tokyographer1/Sites/Python/pythonapps/summarizetext/languages.txt')
language_combobox.grid(row=2, column=1, padx=10, pady=5)

summarize_button = tk.Button(window, text="Summarize", command=summarize_text)
summarize_button.grid(row=3, column=0, columnspan=3, padx=10, pady=10)

output_label = tk.Label(window, text="Summary:")
output_label.grid(row=4, column=0, padx=10, pady=5)
output_text = tk.Text(window, width=40, height=10)
output_text.grid(row=4, column=1, padx=10, pady=5)

copy_button = tk.Button(window, text="Copy", command=copy_summary)
copy_button.grid(row=5, column=0, columnspan=3, padx=10, pady=10)

window.mainloop()


from django.urls import path
from . import views

app_name = 'math_chart'
urlpatterns = [
    path('', views.home, name='home'),
    path('my_chart_10/', views.my_chart_10, name='my_chart_10'),
    path('my_chart_20/', views.my_chart_20, name='my_chart_20'),
    path('b6_b6', views.b6_b6, name='b6_b6'),
    path('my_square', views.my_square, name='my_square'),
    path('my_sin', views.my_sin, name='my_sin'),
    path('my_cos', views.my_cos, name='my_cos'),
    path('my_tan', views.my_tan, name='my_tan'),
    path('trigonometry', views.trigonometry, name='trigonometry'),
]


# 212. Word Search II

# https://leetcode.com/problems/word-search-ii/
# https://leetcode.com/problems/word-search-ii/discuss/59780/Java-15ms-Easiest-Solution-(100.00)
# https://leetcode.com/problems/word-search-ii/discuss/59790/Python-dfs-solution-(directly-use-Trie-implemented).

class TrieNode:
    def __init__(self):
        self.children = defaultdict(TrieNode)
        self.is_word = False

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        node = self.root
        for w in word:
            node = node.children[w]
        node.is_word = True

class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        def dfs(node, i, j, path):
            if node.is_word:
                result.append(path)
                node.is_word = False
            if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]):
                return

            temp = board[i][j]
            node = node.children.get(temp)
            if not node:
                return
            board[i][j] = '#'
            dfs(node, i + 1, j, path + temp)
            dfs(node, i - 1, j, path + temp)
            dfs(node, i, j + 1, path + temp)
            dfs(node, i, j - 1, path + temp)
            board[i][j] = temp

        result = []
        trie = Trie()
        node = trie.root
        for word in words:
            trie.insert(word)

        for i in range(len(board)):
            for j in range(len(board[0])):
                dfs(node, i, j, '')

        return result


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

"""
Programme utilsant la version 2.7 de Python
Solution au pydefis : https://callicode.fr/pydefis/BoitesSucres/txt
Dans ce programme on donne la liste des nombres de sucres qui imposent une taille
de boite unique

252 sucres disposés en 4 couches de 7x9 sucres.
7x9x4

contenant 3 couches de 7x12 sucres (et donc toujours 252 sucres)
OU
contenant 3 couches de 14x6 sucres

entre 137 et 479 sucres

quel nombre de sucres pour quil y ai une seule boite possible ?
"""

"""
on met au mimimum 2 sucres (c'est à dire qu'une boîte de
dimensions 15x15x1 contenant 225 sucres ne conviendrait pas,
car aurait une dimension égale à 1)

en faisant des boîtes de 385 sucres, on est dans l'obligation
de réaliser de boîtes de dimensions 5x7x11.
"""

min=137 # nombre minimal de sucres dans une boite
max=479 # nombre maximal de sucres dans une boite

dim=[]
nombre=[]
for i in range(2,max+1):
    for j in range(2,max+1):
        for k in range(2,max+1):
            if min<=i*j*k<=max:
                tabi=sorted([i,j,k])
                # sil n'est pas deja dans nombre ajouter
                if tabi not in nombre:
                    nombre.append(tabi)
                    dim.append(i*j*k)

dim2=[]
# pour chaque element, s'il n'y en a que un seul alors c'est bon
for i in dim:
    if dim.count(i)==1:
        dim2.append(i)

    i+=1

Le probleme des boites a sucres/Le problème des boîtes à sucres.py


xp = 100           # start money
p = 5              # [%] interest rate
N = 4              # [years]
int_counter = 0    # counter for while loop

outfile = open('growth.dat','w')                       # saving new file growth.dat
outfile.write('Interest rate = %.2f percent\n' % p)    # file heading
outfile.write('year - money\n')                        # table heading
while int_counter <= N:
    outfile.write('   %i %8.2f\n' % (int_counter, xp)) # year and money print, including year 0
    x = (100 + p)/100.*xp
    xp = x
    int_counter += 1
outfile.close()

"""
simen@simen-VirtualBox:~/python/uke7$
"""


import torch
import torch.nn.functional as F

class Act(torch.nn.Module):
    def __init__(self, act: str, slope: float = 0.05) -> None:
        super(Act, self).__init__()
        self.act = act
        self.slope = slope
        self.shift = torch.log(torch.tensor(2.0)).item()

    def forward(self, input: torch.Tensor) -> torch.Tensor:
        if self.act == "relu":
            return F.relu(input)
        elif self.act == "leaky_relu":
            return F.leaky_relu(input)
        elif self.act == "sp":
            return F.softplus(input, beta=1)
        elif self.act == "leaky_sp":
            return F.softplus(input, beta=1) - self.slope * F.relu(-input)
        elif self.act == "elu":
            return F.elu(input, alpha=1)
        elif self.act == "leaky_elu":
            return F.elu(input, alpha=1) - self.slope * F.relu(-input)
        elif self.act == "ssp":
            return F.softplus(input, beta=1) - self.shift
        elif self.act == "leaky_ssp":
            return (
                F.softplus(input, beta=1)
                - self.slope * F.relu(-input)
                - self.shift
            )
        elif self.act == "tanh":
            return torch.tanh(input)
        elif self.act == "leaky_tanh":
            return torch.tanh(input) + self.slope * input
        elif self.act == "swish":
            return torch.sigmoid(input) * input
        else:
            raise RuntimeError(f"Undefined activation called {self.act}")


# Test script for 3-ch RPi Relay Board
import RPi.GPIO as GPIO
from time import sleep

# Relay channel definitions
relay1 = 26
relay2 = 20
relay3 = 21
# Initialise GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(relay1,GPIO.OUT)
GPIO.setup(relay2,GPIO.OUT)
GPIO.setup(relay3,GPIO.OUT)
# Relays are active-low
GPIO.output(relay1,True)
GPIO.output(relay2,True)
GPIO.output(relay3,True)
sleep(1)

print("Cycling relays")
GPIO.output(relay1,False)
sleep(0.5)
GPIO.output(relay2,False)
sleep(0.5)
GPIO.output(relay3,False)
sleep(1)
print("Done")

GPIO.cleanup()


# Importing libraries
import RPi.IO as IO
import time

# NOTEs:
# IO.LOW = Zero = False
# IO.HIGH = Non-Zero Value = True

# Garbage Collector
IO.cleanup()

# Setting pins numbering mode (BCM or BOARD)
IO.setmode(IO.BOARD)

# Global Data
ledPin = 12
ldrPin = 11
morningState = False

# Configuring pins
IO.setup(ledPin, IO.OUT)
IO.output(ledPin, False)
IO.setup(ldrPin, IO.IN)        # Pull Up / Pull Down disabledPin

# Super loop: turn on led if in evening, and off if in morning
while 1:
    if(IO.input(ldrPin) == morningState):
        print("Good morning")
        IO.output(ledPin, False)
    else:
        print("Good evening")
        IO.output(ledPin, True)
    time.sleep(1)

# Garbage Collector
IO.cleanup()


## Import Packages
import pandas as pd   #importing all the important packages
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import json
from ast import literal_eval

## Define dataset
df = pd.read_csv('movies_metadata.csv', encoding = 'UTF-8', low_memory=False)
df2 = pd.read_csv('credits.csv', encoding = 'UTF-8', low_memory=False)

## Filter Movies with more than 100 reviews and less than 40 minutes of runtime
df_fil = df[df["vote_count"] >= 100]
df_fil2 = df_fil[df_fil["runtime"] >= 40]
movie_data = df_fil2[df_fil2["runtime"] <= 180]

def get_actors(x):
    list_acts = []
    for i in x:
        if i['order'] < 3:
            list_acts.append( i['name'] )
    if not list_acts:
        return list("None")
    else:
        return list_acts

##
movie_data['id'] = movie_data['id'].astype('int')
df2['id'] = df2['id'].astype('int')
df2['cast'] = df2['cast'].apply(literal_eval)
df2['leads'] = df2['cast'].apply(get_actors)
movie_data = movie_data.merge(df2, on='id')

title = movie_data['title']
ratings = movie_data['vote_average']
leads = movie_data['leads']
act_ave_rate = []
np.leads = np.array(leads)

def round_two (floating):
    return float(format(floating, ".2f"))

def create_act_list ():
    act_ave = []
    count = []
    acts = []
    for x in range(0, len(leads)):
        if leads[0] != "None":
            for y in range(0, len(leads[x])):
                act = leads[x][y]
                if act not in acts:
                    acts.append(act)
                    count.append(1)
                    act_ave.append((ratings[x]))
                else:
                    index = acts.index(act)
                    count_ind = count[index]
                    count_ind += 1
                    act_ave[index] = (act_ave[index] + ratings[x]) / count_ind
    for x in range(0, len(act_ave)):
        act_ave[x] = round_two(act_ave[x])
    return [act_ave, acts]

act_and_ave = create_act_list()
actors = act_and_ave[1]
average = act_and_ave[0]
mean = round_two(np.array(average).mean())
sample_act = []
sample_ave2 = []

for x in range(0, len(actors)):
    if x % 60 == 0:
        sample_act.append(actors[x])
        sample_ave2.append(average[x])

sample_act.append("Mean Rating")
sample_ave2.append(mean)

f = sns.barplot(x = sample_act, y = sample_ave2)
f.set_xticklabels(sample_act, rotation=90)
f.set_title("Actors Average Film Rating", size = 30)
f.set_ylabel("Average Film Rating", size = 15)
f.set_xlabel("Actor", size = 15)

plt.subplots_adjust(bottom = 0.24)

mng = plt.get_current_fig_manager()
mng.window.state('zoomed')
plt.show()


import tensorflow as tf

from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt

(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()

# Normalize pixel values to be between 0 and 1, like we did in testproj 6
train_images, test_images = train_images / 255.0, test_images / 255.0

class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
               'dog', 'frog', 'horse', 'ship', 'truck']
print(train_images[0].shape)
#Getting shape of each item in our array, youll see why later.

#Viewing some of the images one by one, if required
# IMG_INDEX = 0
# plt.imshow(train_images[IMG_INDEX])
# plt.xlabel(class_names[train_labels[IMG_INDEX][0]])
    # The CIFAR labels happen to be arrays,
    # which is why you need the extra index
# plt.show()

#Viewing multiple images at once,
# plt.figure(figsize=(10,10))
# for i in range(25):
#     plt.subplot(5,5,i+1)
#     plt.xticks([])
#     plt.yticks([])
#       #Used to hide the x and y axis of the figures
#     plt.grid(False)
#     plt.imshow(train_images[i])
#     plt.xlabel(class_names[train_labels[i][0]])
# plt.show()

model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
#We dont need to specify the input shape after the first convalution layer, and the input shape given, (32, 32, 3) is the shape of the items in the CIFAR database.
#We will use 32 filters in this case, of size 3x3 over our input data then use the relu activation function
model.add(layers.MaxPooling2D((2, 2)))
#Downsamples the data into 2x2 samples. Since stride isnt specified, it takes the default value as 2x2, the same as the pooling size.
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
#Next layers is just a repeat of the same, but we use 64 filters instead of just 32.

model.summary()
#Getting summary of the model data, this can help us get the shape of outputs of the model in each layer.

#Now we have extracted features, we shall classify them using dense layers, like a Dense Neural Network.

model.add(layers.Flatten())
#Done this already, makes the entire array into a 1D array, making it like a list
model.add(layers.Dense(64, activation='relu'))
#64 artifical neuron dense layer with an activation function of relu.
model.add(layers.Dense(10))
#Final output layer, 10 nodes cuz uk 10 classes.

model.summary()

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
#Compiling just like we would any other type of NN Model
#We using a different loss function this time, until you play around with a few of them, trial and error is the best way to figure out which one works best for you.

history = model.fit(train_images, train_labels, epochs=10,
                    validation_data=(test_images, test_labels))
#Gives accuracy and loss with training data and validation data, unlike last time where we only gave training data in fitting stage.

plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')

# test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)
    #Not really required this time, since we already validated the data in fitting stage, so this is just running it once more for no use.

Convolutional Neural Network Models/testproj 7- CNN Model, Image Class.py


import sys
if sys.version_info[0] == 3:
    from builtins import str

import json
from ._loader import ClassLoader
from ._codec_utils import parseMoClassName, getParentDn, listWithTotalCount

def parseJSONError(rspText, errorClass, httpCode=None):
    try:
        rspDict = json.loads(rspText)
        data = rspDict.get('imdata', None)
        if data:
            firstRecord = data[0]
            if 'error' == list(firstRecord.keys())[0]:
                errorDict = firstRecord['error']
                reasonStr = errorDict['attributes']['text']
                errorCode = errorDict['attributes']['code']
                if errorClass:
                    raise errorClass(errorCode, reasonStr, httpCode)
                raise ValueError(reasonStr)
    except:
        raise ValueError(rspText)

def fromJSONStr(jsonStr, tree_only=False):
    # Remove the children and add it from the fetch data set
    moDict = json.loads(jsonStr)
    return fromJSONDict(moDict) if not tree_only else moDict

def fromJSONDict(moDict):
    rootNode = moDict["imdata"]

    allMos = listWithTotalCount()
    allMos.totalCount = int(moDict["totalCount"])
    for moNode in rootNode:
        className = list(moNode.keys())[0]
        moData = moNode[className]
        mo = _createMo(className, moData, None)
        allMos.append(mo)
    return allMos

def _createMo(moClassName, moData, parentMo):
    pkgName, className = parseMoClassName(moClassName)
    fqClassName = "cobra.model." + pkgName + "." + className
    pyClass = ClassLoader.loadClass(fqClassName)
    parentDnStr = None
    moProps = moData['attributes']
    if 'dn' in moProps:
        parentDnStr = getParentDn(moProps['dn'])
        del moProps['dn']
    if 'rn' in moProps:
        del moProps['rn']
    if 'instanceId' in moProps:
        del moProps['instanceId']
    if 'status' in moProps:
        del moProps['status']

    namingVals = []
    for propMeta in pyClass.meta.namingProps:
        propName = propMeta.moPropName
        namingVals.append(moProps[propName])
        del moProps[propName]

    parentMoOrDn = parentMo if parentMo else parentDnStr
    mo = pyClass(parentMoOrDn, *namingVals, markDirty=False, **moProps)
    mo.resetProps()
    parentMoOrDn = parentMo if parentMo else parentDnStr

    children = moData.get('children', [])
    for childNode in children:
        className = list(childNode.keys())[0]
        moData = childNode[className]
        _createMo(className, moData, mo)

    return mo

def __toJSONDict(mo, includeAllProps=False, prettyPrint=False, excludeChildren=False):
    meta = mo.meta
    className = meta.moClassName

    moDict = {}
    attrDict = {}
    for propMeta in meta.props:
        name = propMeta.name
        moPropName = propMeta.moPropName
        value = None
        if propMeta.isDn:
            if includeAllProps:
                value = str(mo.dn)
        elif propMeta.isRn:
            if includeAllProps:
                value = str(mo.rn)
        elif propMeta.isNaming or includeAllProps or mo.isPropDirty(name):
            value = getattr(mo, name)

        if value is not None:
            attrDict[moPropName] = {}
            attrDict[moPropName] = str(value)

    if len(attrDict) > 0:
        moDict['attributes'] = attrDict

    if not excludeChildren:
        childrenArray = []
        for childMo in mo.children:
            childMoDict = __toJSONDict(childMo, includeAllProps, prettyPrint, excludeChildren)
            childrenArray.append(childMoDict)
        if len(childrenArray) > 0:
            moDict['children'] = childrenArray

    return {className: moDict}

def toJSONStr(mo, includeAllProps=False, prettyPrint=False, excludeChildren=False):
    jsonDict = __toJSONDict(mo, includeAllProps, prettyPrint, excludeChildren)
    indent = 2 if prettyPrint else None
    jsonStr = json.dumps(jsonDict, indent=indent)

    return jsonStr