import json
import urllib.parse

import requests

CLIENT_ID = "20af609a-4a6f-45aa-a9b0-d7946274dc52"

class QueueException(Exception):
    pass

def _get_auth_token(user, key):
    # Get the auth token
    resp = requests.post(
        "https://identity.api.rackspacecloud.com/v2.0/tokens",
        data=json.dumps({
            "auth": {
                "RAX-KSKEY:apiKeyCredentials": {
                    "username": user,
                    "apiKey": key,
                }
            }
        }),
        headers={
            "Content-Type": "application/json",
        }
    )
    resp.raise_for_status()
    return resp.json()["access"]["token"]["id"]

def push(user, key, queue, message, ttl=1209600, retries=20, region="iad"):
    # Send message to queue
    for _ in range(retries):
        resp = requests.post(
            (
                "https://{}.queues.api.rackspacecloud.com/v1/queues/{}/"
                "messages".format(region, queue)
            ),
            data=json.dumps([{"ttl": ttl, "body": message}]),
            headers={
                "Content-Type": "application/json",
                "Accept": "application/json",
                "X-Auth-Token": _get_auth_token(user, key),
                "Client-ID": CLIENT_ID,
            }
        )
        resp.raise_for_status()

        if not resp.json()["partial"]:
            return
    else:
        raise QueueException("Cannot Queue Message")

def claim(user, key, queue, ttl=300, grace=300, region="iad"):
    resp = requests.post(
        (
            "https://{}.queues.api.rackspacecloud.com/v1/queues/{}/"
            "claims?limit=1".format(region, queue)
        ),
        data=json.dumps({"ttl": ttl, "grace": grace}),
        headers={
            "Content-Type": "application/json",
            "Accept": "application/json",
            "X-Auth-Token": _get_auth_token(user, key),
            "Client-ID": CLIENT_ID,
        }
    )
    resp.raise_for_status()

    # Check if we got any items returned
    if resp.status_code == 204:
        return

    # Insert the claim location into the data too
    data = resp.json()[0]
    data["claim"] = resp.headers["Location"]

    return data

def unclaim(user, key, queue, task, region="iad"):
    resp = requests.delete(
        urllib.parse.urljoin(
            "https://{}.queues.api.rackspacecloud.com/".format(region),
            task["claim"],
        ),
        headers={
            "Content-Type": "application/json",
            "Accept": "application/json",
            "X-Auth-Token": _get_auth_token(user, key),
            "Client-ID": CLIENT_ID,
        }
    )
    resp.raise_for_status()

def delete(user, key, queue, task, region="iad"):
    resp = requests.delete(
        urllib.parse.urljoin(
            "https://{}.queues.api.rackspacecloud.com/".format(region),
            task["href"],
        ),
        headers={
            "Content-Type": "application/json",
            "Accept": "application/json",
            "X-Auth-Token": _get_auth_token(user, key),
            "Client-ID": CLIENT_ID,
        }
    )
    resp.raise_for_status()


MD_PREFIX = "MD=CISCO_EPNM"
def filter_network_interface(data: list, fdn: str = None, name: str = None, interface_type: str = None, node_name: str = None, physical_interface: str = None, custommer: str = None, status: str = None):
    if isinstance(data, list):
        if fdn is not None:
            data = filter(lambda x: x["ni.fdn"] == fdn, data)
        if name is not None:
            data = filter(lambda x: x["ni.fdn"] == f"{MD_PREFIX}!NI={name}", data)
        if interface_type is not None:
            data = filter(lambda x: f"{interface_type}" in x["ni.type"], data)
        if node_name is not None:
            data = filter(lambda x: f"{MD_PREFIX}!ND={node_name}" in x["ni.port-ref"], data)
        if physical_interface is not None:
            data = filter(lambda x: f"FTP=name={physical_interface}" in x["ni.port-ref"], data)
        if custommer is not None:
            data = filter(lambda x: f"CUSTOMER={custommer}" in x["ni.subscriber-ref"], data)
        if status is not None:
            data = filter(lambda x: x["ni.status"] == status, data)
        data = list(data)
    elif data is None:
        pass
    return data


"""
Created on Tue Sep 10 12:00:38 2019

@author: devyanshitiwari
"""
# Step 1 convert the text file into csv file
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

dataset=pd.read_csv('data1.csv')
X=dataset.iloc[:,0:1]
y=dataset.iloc[:,1:2]

m=len(y) # number of training examples
# visualising the data by creating a scatter plot
plt.scatter(X,y,color='red')
plt.title('Population VS Profit')
plt.xlabel('Population in 10,000')
plt.ylabel('Profit in $10,000s')
plt.show()

# adding the intercept term and setting alpha=0.01
import statsmodels.api as sm
X=np.append(arr=np.ones((m,1)).astype(int),values=X,axis=1) # Adding the intercept

# calculating cost function for theta =0

alpha=0.01
theta=np.zeros([2,1])

def computecost(X,y,theta):
    t=np.dot(X,theta) -y
    return np.sum(np.power(t,2))/(2*m)

J=computecost(X,y,theta)
print(J.item) # 30.975

# Gradient Descent
# checking for convergence of gradient descent

def gradientdescent(X,y,theta,alpha,step):
    for i in range(step):
        t1=np.dot(X,theta)-y
        t2=np.dot(X.T,t1)
    return theta-(alpha*t2)/m

for i in range(1000):
 theta=gradientdescent(X,y,theta,alpha,1000)
 print(theta)
 J = computecost(X, y, theta)
 print(J.item) # it was observed that value of J was decreasing until still started to converge

# predicting the values
predict1 = [1, 3.5] * theta;
predict2 = [1, 7] * theta;
print(predict1,predict2)

# plotting the line of best fit
plt.scatter(X[:,1],y,color='red')
plt.plot(X[:,1],np.dot(X,theta),color='blue')
plt.title('Population VS Profit')
plt.xlabel('Population in 10,000')
plt.ylabel('Profit in $10,000s')
plt.show()


# gread = input('请输入成绩')
# greadNum = 0
# while True:
#     if not gread.isdigit():
#         print('输入成绩无效')
#         gread = input('请输入成绩')
#     elif int(gread) <0 or int(gread) >100:
#         print('输入成绩无效')
#         gread = input('请输入成绩')
#     else:
#         greadNum = int(gread)
#         break
# if greadNum >= 90:
#     print('A')
# elif greadNum >= 80:
#     print('B')
# elif greadNum >= 60:
#     print('C')
# else:
#     print('D')

x, y, z = 6, 5, 4
if x < y:
    small = x
    if z < small:
        small = z
elif y < z:
    small = y
else:
    small = z

print('source small = ' + str(small))

x, y, z = 6, 5, 4
small = (z if z <x else x ) if x<y else (y if y<z else  z)
print('sink small = ' + str(small))

x =1;y=2;z=3

x,y,z = y,z,x

print(x,y,z)

i = range(100)
print(i)


#!/usr/bin/env python
import rospy
import time, datetime

from geometry_msgs.msg import Twist
from sensor_msgs.msg import Imu, JointState
from trajectory_msgs.msg import JointTrajectoryPoint

from pyrr import Quaternion
from scipy.spatial.transform import Rotation

class LogWriter():
    def __init__(self) -> None:
        rospy.init_node("log_writer")
        self.rate = rospy.Rate(300)

        rospy.Subscriber("cmd_vel", Twist, self.cmd_vel_callback, queue_size=10)
        rospy.Subscriber("cmd_pose", Twist, self.cmd_pose_callback, queue_size=10)
        rospy.Subscriber("joint_states", JointState, self.cur_joint_pos_callback, queue_size=1)
        rospy.Subscriber("lcm/servo_cmd", JointTrajectoryPoint, self.ref_joint_pos_callback, queue_size=1)
        rospy.Subscriber("imu/data", Imu, self.imu_callback, queue_size=1)

        self.cmd_vel_msg = Twist()
        self.cmd_pose_msg = Twist()
        self.cur_joints_msg = JointState()
        self.ref_joints_msg = JointTrajectoryPoint()
        self.imu_msg = Imu()

        filename = f"log_{datetime.datetime.now().strftime('%Y%m%d-%H%M%S')}.csv"
        self.file = open(f"~/mors_ws/src/log_writer/logs/{filename}", 'w')

        line = "datetime, t, \
            cmd_vel[X], cmd_vel[Y], cmd_vel[Z], \
            cmd_pose_linear[X], cmd_pose_linear[Y], cmd_pose_linear[Z], cmd_pose_angular[X], cmd_pose_angular[Y], cmd_pose_angular[Z],\
            cur_joint[0], cur_joint[1], cur_joint[2], cur_joint[3], cur_joint[4], cur_joint[5], \
            cur_joint[6], cur_joint[7], cur_joint[8], cur_joint[9], cur_joint[10], cur_joint[11], \
            ref_joint[0], ref_joint[1], ref_joint[2], ref_joint[3], ref_joint[4], ref_joint[5], \
            ref_joint[6], ref_joint[7], ref_joint[8], ref_joint[9], ref_joint[10], ref_joint[11], \
            roll, pitch, yaw"
        self.file.write(line + '\n')

    def loop(self):
        start_t = int(datetime.datetime.now().strftime("%H%M%S%f"))
        while not rospy.is_shutdown():
            now = datetime.datetime.now()
            t = int(now.strftime("%H%M%S%f")) - start_t

            cur_joint_str = ""
            ref_joint_str = ""

            for i in range(12):
                if len(self.cur_joints_msg.position) >= 12:
                    cur_joint_str += f"{self.cur_joints_msg.position[i]}, " #f"1, "#
                else:
                    cur_joint_str += f"0, "
                if len(self.ref_joints_msg.positions) >= 12:
                    ref_joint_str += f"{self.ref_joints_msg.positions[i]}, " #f"2, "#
                else:
                    ref_joint_str += "0, "

            quat_df = [self.imu_msg.orientation.x, self.imu_msg.orientation.y, self.imu_msg.orientation.z, self.imu_msg.orientation.w]
            if quat_df[3] != 0:
                quat = Quaternion(quat_df).inverse
                rot = Rotation.from_quat(quat)
                rot_euler = rot.as_euler('xyz', degrees=False)
            else:
                rot_euler = [0, 0, 0]

            # self.cmd_pose_msg.angular.z = 100
            line = f"{now}, {t}, \
                {self.cmd_vel_msg.linear.x}, {self.cmd_vel_msg.linear.y}, {self.cmd_vel_msg.angular.z}, \
                {self.cmd_pose_msg.linear.x}, {self.cmd_pose_msg.linear.y}, {self.cmd_pose_msg.linear.z}, \
                {self.cmd_pose_msg.angular.x}, {self.cmd_pose_msg.angular.y}, {self.cmd_pose_msg.angular.z}, \
                {cur_joint_str}{ref_joint_str}\
                {rot_euler[0]}, {rot_euler[0]}, {rot_euler[0]}\
                \n"
            self.file.write(line)

            self.rate.sleep()

    def cmd_vel_callback(self, msg : Twist):
        self.cmd_vel_msg = msg

    def cmd_pose_callback(self, msg : Twist):
        self.cmd_pose_msg = msg

    def cur_joint_pos_callback(self, msg : JointState):
        self.cur_joints_msg = msg

    def ref_joint_pos_callback(self, msg : JointTrajectoryPoint):
        self.ref_joints_msg = msg

    def imu_callback(self, msg : Imu):
        self.imu_msg = msg

def main():
    lw = LogWriter()
    lw.loop()

if __name__ == '__main__':
    main()


import praw
from prawcore.exceptions import NotFound, RequestException, Redirect, ResponseException
from praw.exceptions import MissingRequiredAttributeException
from sys import exit
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime

class WordCount:
    """The bot requests for a subreddit and a text input, then searches
    the 1000 most recent posts to find who has said it the most."""

    def __init__(self):
        try:
            print("Word Counter bot for Reddit: version 1.0.1 - by u/TiagoPaolini")
            self.reddit = praw.Reddit()
            print("Search the 1000 most recent posts of a subreddit in order to find who has said some word or sentence the most.")
        except MissingRequiredAttributeException:
            print("Error: praw.ini file not found. This file was supplied with the bot and should be on the same directory as the bot. Please do not change or remove it, unless you know what you are doing.")
            input("Press ENTER to exit program.")
            exit()
        except ResponseException:
            print("Error: praw.ini file has invalid credentials. This file was supplied with the bot and should be on the same directory as the bot. Please do not change or remove it, unless you know what you are doing.")
            input("Press ENTER to exit program.")
            exit()

    def main(self):
        while True:
            # Ask user to input a subreddit
            search_sub = input("Subreddit to search: r/")

            try:
                # Test if it is possible to connect to the subreddit
                self.subreddit = self.reddit.subreddit(search_sub)
                self.subreddit.id

            except RequestException:
                print("Error: You seem to be offline. Please connect to the internet and try again.")
                continue
            except NotFound:
                print("Error: Subreddit not found. Please check your spelling and try again.")
                continue
            except Redirect:
                print("Error: Subreddit not found. Please check your spelling and try again.")
                continue

            # Ask the user for a text to search:
            self.search_text = input("Text to search: ").lower().strip()

            # Do the search
            self.file_name = f"{self.subreddit.display_name}_word_count.txt"
            self.search_posts(self.search_text)
            print(f"Search finished. Full results were saved to {self.file_name}")

            # Do another search or close
            while True:
                user_input = input("Do you want to perform another search? [y]es / [n]: ").lower()
                if user_input.startswith("y"):
                    break
                elif user_input.startswith("n"):
                    print("Closing program... Have a nice day!")
                    exit()

    def search_posts(self, text):

        print(f"Fetching the list of recent posts on r/{self.subreddit.display_name} (up to 1000 posts)...")
        total_posts = 0
        total_posts_previous = -1
        total_comments = 0
        results_page = 0
        previous_post = ""
        posts_set = set()
        word_counter = Counter()

        # Get the most recent posts of the subreddit (up to 1000 posts)
        while (total_posts != total_posts_previous) and (results_page < 10):
            total_posts_previous = total_posts
            results_page += 1
            query_parameters = {"after": previous_post, "count": total_posts}

            # Loop through the result page
            for submission in self.subreddit.new(limit=100, params=query_parameters):
                total_posts += 1
                previous_post = submission.name
                total_comments += submission.num_comments
                posts_set.add(submission)

            # Keep updating the same line on terminal
            print(f"{total_posts} posts found ({total_comments} comments)", end="\r", flush=True)

        print(f"\nSearching for '{text}' in the content of posts... Please be patient.")

        # Search for the text on the post body and comments of all found submissions
        with ThreadPoolExecutor(max_workers=10) as executor:
            self._content_total = max(total_posts + total_comments, 1)
            self._content_count = 0
            results = executor.map(self.text_crawler, posts_set)
            for result in results:
                word_counter.update(result)
        print("Progress: 100%   ")

        # Output the results
        print("Search complete! Results:")

        user_column_width = 0
        count_column_width = 0

        for user, count in word_counter.items():    # Determine maximum column width of the results
            user_column_width = max(len(user) + 2, user_column_width)
            count_column_width = max(len(str(count)), count_column_width)

        # Save the results to file and show them on the terminal
        with open(self.file_name, "a", encoding="utf-8") as file:

            date = str(datetime.now())[:19] + "\n"
            titles = "User".ljust(user_column_width) + "\t" + "Count".rjust(count_column_width)
            header = f"'{self.search_text}' count on {date}\n{titles}\n"
            file.write(header)
            print("\n" + titles)

            line_count = 0
            for user, count in word_counter.most_common():
                line_count += 1
                user_str = ("u/" + user).ljust(user_column_width)
                count_str = str(count).rjust(count_column_width)
                line = f"{user_str}\t{count_str}"
                file.write(line + "\n")
                if line_count <= 10:
                    print(line)

            footer = "".ljust(user_column_width + count_column_width + 4, "-")
            file.write(f"\n{footer}\n\n")
            print(footer + "\n")

    def text_crawler(self, submission):
        post_word_counter = Counter()

        # Search the post body for the text
        if (submission.is_self) and (submission.author is not None):
            post_author = submission.author.name
            post_body = submission.selftext.lower()
            text_count = post_body.count(self.search_text)
            if text_count > 0:
                post_word_counter.update({post_author: text_count})
            self._content_count += 1

        # Search the post comments and count the ocurrences
        submission.comments.replace_more(limit=None)    # Get all comments of the post
        for comment in submission.comments.list():
            if comment.author is None:
                continue
            comment_author = comment.author.name
            comment_body = comment.body.lower()
            text_count = comment_body.count(self.search_text)
            if text_count > 0:
                post_word_counter.update({comment_author: text_count})
            self._content_count += 1

            # Print the progress
            print(f"Progress: {self._content_count * 100 / self._content_total:.2f}%", end="\r", flush=True)

        # Return the count on the current post
        return post_word_counter

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


import os

def show_board(position):
    board = (f"|{position[1]}|{position[2]}|{position[3]}|\n"
             f"|{position[4]}|{position[5]}|{position[6]}|\n"
             f"|{position[7]}|{position[8]}|{position[9]}|")
    #  print(position)
    print(board)

def placement(xCoordinates, yCoordinate):
    if xCoordinates == '0' and yCoordinate == '0':
        place = 1
    elif xCoordinates == '0' and yCoordinate == '1':
        place = 2
    elif xCoordinates == '0' and yCoordinate == '2':
        place = 3
    elif xCoordinates == '1' and yCoordinate == '0':
        place = 4
    elif xCoordinates == '1' and yCoordinate == '1':
        place = 5
    elif xCoordinates == '1' and yCoordinate == '2':
        place = 6
    elif xCoordinates == '2' and yCoordinate == '0':
        place = 7
    elif xCoordinates == '2' and yCoordinate == '1':
        place = 8
    elif xCoordinates == '2' and yCoordinate == '2':
        place = 9
    else:
        print("choose the right coordinates")
        place = 0
    return place

def mark(turn):
    if turn % 2 == 0:
        return 'x'
    else:
        return 'o'

def check(position, choice):
    # row check used slicing method of list by casting dictionary to list and again getting keys value by casting
    # list to dictionary first_three_items\
    row1 = dict(list(position.items())[:3])
    print(row1[1], row1[2], row1[3])
    # items from 4 to 6
    row2 = dict(list(position.items())[3:6])
    print(row2[4], row2[5], row2[6])
    # items from 7 till end
    row3 = dict(list(position.items())[5:])
    print(row3[7], row3[8], row3[9])
    if row1[1] == row1[2] == row1[3] or row2[4] == row2[5] == row2[6] or row3[7] == row3[8] == row3[9]:
        print(f"Player {choice} won the game row wise")
        return 1
    elif position[1] == position[4] == position[7] or position[2] == position[5] == position[8] or position[3] == \
            position[6] == position[9]:
        print(f"Player {choice} won the game by column wise")
        return 1
    elif position[1] == position[5] == position[9] or position[3] == position[5] == position[7]:
        print(f"Player {choice} won the game diagonally")
        return 1
    else:
        return 0


import numpy as np
import tsplib95
import networkx
import time
import tracemalloc
import configparser
import math
import csv

def read_file_matrix(file_name):
    file = open(file_name,"r")
    dane = file.readlines()
    dane_new = []
    for i in dane:
        dane_new.append(list(map(int,i.strip().split())))
    return dane_new

class AntColony():
    def __init__(self,graph,CC,strat):
        self.graph = graph
        self.CC = CC
        self.alpha = 1
        self.beta = 4
        self.rho = 0.5
        self.n = len(graph)
        self.m = self.n
        self.tau0 = self.m/self.initial_solution_greedy()
        self.Q = 1
        self.strat = strat #1 - DAS #2 - QAS
        self.pheromones = [[self.tau0 for i in range(len(self.graph))] for j in range(len(self.graph))]

    def initial_solution_greedy(self):
        cur_node = 0
        solution = [cur_node]
        free_nodes = set(range(self.n))
        free_nodes.remove(cur_node)

        while free_nodes:
            min = float('Inf')
            for i in range(self.n):
                if(self.graph[cur_node][i] < min and self.graph[cur_node][i] != 0 and i in free_nodes):
                    min = self.graph[cur_node][i]
                    next_node = i
            free_nodes.remove(next_node)
            solution.append(next_node)
            cur_node = next_node

        cur_val = self.get_val(solution)

        return cur_val

    def updatePheromon(self):
        for i in range(self.n):
            for j in range(self.n):
                self.pheromones[i][j] *= self.rho
                for ant in range(self.m):
                    if self.strat ==1:       #DAS
                        self.pheromones[i][j]+=self.Q
                    elif self.strat ==2:     #QAS
                        if self.graph[i][j] != 0:
                            self.pheromones[i][j] +=self.Q/self.graph[i][j]

    def get_val(self,solution):
        val = 0
        save = 0
        for i in range(len(solution)-1):
            val += self.graph[solution[i]][solution[i+1]]
            save = i+1
        val += self.graph[solution[save]][solution[0]]
        return val

    def aco(self):
        print(self.n)
        best_solution = []
        best_val = float("inf")
        for i in range(self.CC):
            solutions = []
            for j in range(self.m): #dla każdej mrówy
                current_city = np.random.randint(self.n)
                solution = [current_city]
                unvisited_cities = set(range(self.n)) - {current_city}
                while unvisited_cities:
                    prob = [0 for z in range(self.n)]
                    for k in unvisited_cities:
                        prob[k] = (self.pheromones[current_city][k] ** self.alpha) * ((1 / self.graph[current_city][k]) ** self.beta)
                    suma = sum(prob)
                    for p in range(len(prob)):
                        prob[p]/= suma
                    next_city = np.random.choice(list(set(range(self.n))),p=prob)
                    solution.append(next_city)
                    current_city = next_city
                    unvisited_cities -= {next_city}
                val = self.get_val(solution)
                if(val<best_val):
                    best_solution = solution
                    best_val = val
                solutions.append(solution)
            if len(set(tuple(i) for i in solutions)) == 1:
                break
            self.updatePheromon()
        return best_solution,best_val

def getError(actual,expected):
    return (int(actual)-int(expected))/int(expected)*100

def messure_all(file_name,expected_value,parameters):
    problem = tsplib95.load('dane/'+file_name)
    graph=problem.get_graph()
    matrix = networkx.to_numpy_array(graph).tolist()
    aco = AntColony(matrix,int(parameters[0]),int(parameters[1]))   #CC,strat
    t0 = time.time()
    #tracemalloc.start()
    best_solution,best_val = aco.aco()
    #mem = tracemalloc.get_traced_memory()
    t1 = time.time() - t0
    #tracemalloc.stop()
    error = getError(best_val,expected_value)
    return file_name,best_solution,best_val,parameters[0],parameters[1],error,t1

def read_ini(file_name):
    config = configparser.ConfigParser()
    config.read(file_name)
    files = [config['section_a'][i].split() for i in config['section_a']]
    #files = [['gr17.tsp', '5', '2085', '1000', '2']]
    outputfile = config['section_b']['outputfile']
    #outputfile = 'outputACO.csv'
    parameters = [i[3:5] for i in files]
    return files,outputfile,parameters

if __name__ == "__main__":

    files,outputfile,parameters = read_ini('aco.ini')
    header = ['file','path','value','CC','strat','error','time']
    with open(outputfile,'w') as file:
        writer = csv.writer(file)
        writer.writerow(header)
        for i in range (len(files)):
            for j in range(eval(files[i][1])):
                writer.writerow(messure_all(files[i][0],files[i][2],parameters[i]))

    #graph = read_file_matrix("tsp_10.txt")

    #AC =  AntColony(graph,1000,1)
    #print(AC.aco())


import torch
import torch.nn as nn
import numpy as np
import pickle
import copy
import matplotlib.pyplot as plt

class MLPModel(nn.Module):
    """
        The class definition of the MLP model that inherits the nn.Module class.
    """

    def __init__(self, layerCount, hiddenNeurons, activationFunction):
        """
            Constructor of the class. Takes the total number of layers (excluding the input layer), total number of
            neurons in the hidden layers and the activation function as parameters.
        """
        super(MLPModel, self).__init__()
        self.layer1 = nn.Linear(784, hiddenNeurons)
        self.layer2 = nn.Linear(hiddenNeurons, 10)

        # Layer 3 is initially declared as None. If there are 2 hidden layers, this layer will be updated.
        self.layer3 = None

        if layerCount == 3:
            self.layer2 = nn.Linear(hiddenNeurons, hiddenNeurons)
            self.layer3 = nn.Linear(hiddenNeurons, 10)

        self.activation_function = activationFunction()

    def forward(self, x):
        """
            Feed-forward method of the MLP class. Takes the input dataset x as parameter.
        """
        hidden_layer_output = self.activation_function(self.layer1(x))

        # If there are 2 hidden layers, the output layer is once again updated.
        if self.layer3 is not None:
            hidden_layer_output = self.layer2(hidden_layer_output)
            output_layer = self.layer3(hidden_layer_output)

            return output_layer

        output_layer = self.layer2(hidden_layer_output)
        return output_layer

def accuracyCalculator(predictions, labels):
    """
        Helper function for calculating the accuracies. Compares the index values of the maximum values at each row
        of prediction tensor and the label tensor and returns the total number of matches.
    """
    max_probs = torch.argmax(predictions, dim=1)

    res = labels.eq(max_probs)

    return torch.count_nonzero(res).item()

# ============================== Data loading ===========================================
x_train, y_train = pickle.load(open("data/mnist_train.data", "rb"))
x_validation, y_validation = pickle.load(open("data/mnist_validation.data", "rb"))
x_test, y_test = pickle.load(open("data/mnist_test.data", "rb"))

x_train = x_train / 255.0
x_train = x_train.astype(np.float32)

x_test = x_test / 255.0
x_test = x_test.astype(np.float32)

x_validation = x_validation / 255.0
x_validation = x_validation.astype(np.float32)

x_train = torch.from_numpy(x_train)
y_train = torch.from_numpy(y_train).to(torch.long)

x_validation = torch.from_numpy(x_validation)
y_validation = torch.from_numpy(y_validation).to(torch.long)

x_test = torch.from_numpy(x_test)
y_test = torch.from_numpy(y_test).to(torch.long)
# ========================================================================================

# 12 configurations are used in the search and each configuration is declared as a dictionary. These dictionaries
# are stored in this array.
configs = [
    {'layer': 2, 'neuron': 16, 'func': nn.LeakyReLU},
    {'layer': 2, 'neuron': 16, 'func': nn.Sigmoid},
    {'layer': 2, 'neuron': 32, 'func': nn.LeakyReLU},
    {'layer': 2, 'neuron': 32, 'func': nn.Sigmoid},
    {'layer': 2, 'neuron': 64, 'func': nn.LeakyReLU},
    {'layer': 2, 'neuron': 64, 'func': nn.Sigmoid},
    {'layer': 3, 'neuron': 16, 'func': nn.LeakyReLU},
    {'layer': 3, 'neuron': 16, 'func': nn.Sigmoid},
    {'layer': 3, 'neuron': 32, 'func': nn.LeakyReLU},
    {'layer': 3, 'neuron': 32, 'func': nn.Sigmoid},
    {'layer': 3, 'neuron': 64, 'func': nn.LeakyReLU},
    {'layer': 3, 'neuron': 64, 'func': nn.Sigmoid},
]

loss_function = nn.CrossEntropyLoss()       # The cross-entropy loss is selected for the loss function

# Additional softmax function is defined from the torch.nn module to calculate probabilities of the predictions
soft_max_function = torch.nn.Softmax(dim=1)

i = 1

# The accuracy results of each run of each configuration will be stored as a matrix.
accuracies = []

# Traversing through every possible configuration
for config in configs:

    validation_accuracy = []

    # Running each configuration 10 times
    for j in range(1, 11):

        # For each run, a new model is defined
        model = MLPModel(layerCount=config['layer'], activationFunction=config['func'], hiddenNeurons=config['neuron'])

        # Adam optimizer is defined with the learning rate of 0.0001
        optimizer = torch.optim.Adam(model.parameters(), lr=0.0001)

        # Iteration (epoch) number is defined as 1000. Calculation of this value is explained in the report.
        ITERATION = 1000

        accuracy = 0

        for iteration in range(1, ITERATION + 1):
            optimizer.zero_grad()
            predictions = model(x_train)

            loss_value = loss_function(predictions, y_train)

            loss_value.backward()
            optimizer.step()

            with torch.no_grad():
                predictions = model(x_validation)
                loss_value = loss_function(predictions, y_validation)

                # Probability scores are calculated with the softmax function to calculate the accuracy
                probability_scores = soft_max_function(predictions)

                # Each iteration's accuracy scores are summed
                accuracy += accuracyCalculator(probability_scores, y_validation) / y_validation.size()[0]

                # Each loss is given as output for tracing
                print("Configuration: %d - Run : %d - Iteration: %d - Validation Loss: %f" % (
                    i, j, iteration, loss_value.item()))

        # The average of the accuracies are calculated and appended into the accuracy row corresponding row
        avgAccuracy = accuracy / ITERATION
        validation_accuracy.append(avgAccuracy)

    accuracies.append(validation_accuracy)

    i += 1

# Each configuration's confidence interval is calculated and given as output
i = 1
for acc in accuracies:
    n = np.array(acc)
    print(("The confidence interval of configuration %d: %f" + u"\u00B1" + ' %f') % (
        i, np.mean(n), np.std(n) / (1.96 * (len(acc)) ** 0.5)))
    i += 1

# The best configuration can be selected by the user by entering the index value as input
c = int(input('Pick a configuration for testing: '))
c -= 1

# The train and validation datasets along with their labels are combined
joined_x = torch.cat([x_train, x_validation])
joined_y = torch.cat([y_train, y_validation])

test_accuracies = []

for j in range(1, 11):

    # A new model is defined with the configuration that yiels the highest mean accuracy score
    model = MLPModel(layerCount=configs[c]['layer'], activationFunction=configs[c]['func'],
                     hiddenNeurons=configs[c]['neuron'])

    optimizer = torch.optim.Adam(model.parameters(), lr=0.0001)

    ITERATION = 1000

    for iteration in range(1, ITERATION + 1):
        optimizer.zero_grad()
        predictions = model(joined_x)

        loss_value = loss_function(predictions, joined_y)

        loss_value.backward()
        optimizer.step()

        with torch.no_grad():
            predictions = model(joined_x)
            loss_value = loss_function(predictions, joined_y)

            print("Test Run : %d - Iteration: %d - Loss: %f" % (
                j, iteration, loss_value.item()))

    with torch.no_grad():
        test_predictions = model(x_test)

        # Test accuracies are calculated and stored
        test_accuracy = accuracyCalculator(test_predictions, y_test) / y_test.size()[0]

        test_accuracies.append(test_accuracy)

# The confidence interval for the testing accuracies is calculated and given as output
n = np.array(test_accuracies)
print(("The confidence interval of testing: %f " + u"\u00B1" + ' %f') % (
    np.mean(n), np.std(n) / (1.96 * (len(test_accuracies)) ** 0.5)))


a = [0,1,2,3,4,5,6,7,8,9]

for permutation in range(999999):

    for k in range(len(a)-1):
        if a[k] < a[k + 1]:
            maxk = k

    for l in range(len(a)):
        if a[maxk] < a[l]:
            maxl = l

    #print a, maxk, maxl

    a[maxk], a[maxl] = a[maxl], a[maxk]

    for i in range(((len(a)-1) - (maxk + 1) + 1)//2):
        #print i
        a[maxk + 1 + i], a[len(a) - 1 - i] = a[len(a) - 1 - i], a[maxk + 1 + i]

	#print a, 'after reverse'

print(a)


import matplotlib.pyplot as matplotlib
import matplotlib.patches as mpatches
import os

from Utilities.OperatingSystemUtil import OperatingSystemUtil
from Utilities.SafeCastUtil import SafeCastUtil
from SupportedAnalysisTypes import SupportedAnalysisTypes

import logging

class GraphingService(object):

    log = logging.getLogger(__name__)
    logging.basicConfig()
    log.setLevel(logging.INFO)

    def __init__(self):
        pass

    DEFAULT_PLOT_FILENAME = "MachineLearningMultiBarPlot"
    COLOR_PROGRESSION = ['red', 'green', 'blue', 'purple', 'orange']

    def makeMultiBarPlotWithMultipleAnalysis(self, full_data, output_path, analysis_type, title):
        basic_plot = matplotlib.figure()

        full_data_sorted_by_percentage = self.sortByPercentage(full_data)

        location_on_plot = 1
        x_ticks = []

        for percentage in full_data_sorted_by_percentage.keys():
            data = full_data_sorted_by_percentage[percentage].values()
            keys = full_data_sorted_by_percentage[percentage].keys()
            positions = SafeCastUtil.safeCast(range(location_on_plot, location_on_plot + len(keys)), list)
            plot = matplotlib.boxplot(data, positions=positions, widths=0.6)
            self.color_by_analysis(keys, plot)
            x_ticks.append(location_on_plot + (len(keys) / 2))
            location_on_plot += 4

        matplotlib.title(title)

        # set axes limits and labels
        if analysis_type == SupportedAnalysisTypes.CLASSIFICATION:
            matplotlib.ylim(0, 1)
        else:
            matplotlib.ylim(-1, 1)
        matplotlib.ylabel("Accuracy distribution")

        matplotlib.xlim(0, location_on_plot - 1)
        matplotlib.xlabel("% Train")
        matplotlib.xticks(x_ticks, [SafeCastUtil.safeCast(k*100, int) for k in full_data_sorted_by_percentage.keys()])
        self.createLegend(full_data)

        basic_plot.show()

        current_path = os.getcwd()
        OperatingSystemUtil.changeWorkingDirectory(output_path)
        basic_plot.savefig(self.DEFAULT_PLOT_FILENAME, bbox_inches='tight')
        OperatingSystemUtil.changeWorkingDirectory(current_path)

    def sortByPercentage(self, full_data):
        by_percentage = {}
        for analysis_type in full_data.keys():
            for percentage_data in full_data[analysis_type].keys():
                if percentage_data not in by_percentage.keys():
                    by_percentage[percentage_data] = {analysis_type: full_data[analysis_type][percentage_data]}
                else:
                    by_percentage[percentage_data][analysis_type] = full_data[analysis_type][percentage_data]
        return by_percentage

    def color_by_analysis(self, keys, plot):
        for element in ['boxes', 'whiskers', 'fliers', 'means', 'medians', 'caps']:
            if len(keys) != 0 and len(plot[element]) % len(keys) == 0:
                color_split = SafeCastUtil.safeCast(len(plot[element]) / len(keys), int)
                i = 0
                color_index = 0
                while i < len(plot[element]):
                    if i % color_split == 0 and i > 0:
                        color_index += 1
                        if color_split >= len(self.COLOR_PROGRESSION):
                            color_index = 0
                    matplotlib.setp(plot[element][i], color=self.COLOR_PROGRESSION[color_index])
                    i += 1

    def createLegend(self, full_data):
        patches = []
        color_index = 0
        for key in full_data.keys():
            if color_index >= len(self.COLOR_PROGRESSION):
                color_index = 0
            patch = mpatches.Patch(color=self.COLOR_PROGRESSION[color_index], label=key)
            patches.append(patch)
            color_index += 1
        matplotlib.legend(handles=patches, loc=4)

# Required Citation (BibTex/LaTex):
# @Article{Hunter:2007,
#   Author    = {Hunter, J. D.},
#   Title     = {Matplotlib: A 2D graphics environment},
#   Journal   = {Computing In Science \& Engineering},
#   Volume    = {9},
#   Number    = {3},
#   Pages     = {90--95},
#   abstract  = {Matplotlib is a 2D graphics package used for Python
#   for application development, interactive scripting, and
#   publication-quality image generation across user
#   interfaces and operating systems.},
#   publisher = {IEEE COMPUTER SOC},
#   doi = {10.1109/MCSE.2007.55},
#   year      = 2007
# }


import pyarrow
import zmq
from absl import logging
from zeus.common.util.register import Registers

ZMQ_MIN_PORT = 20000
ZMQ_MAX_PORT = 40000

@Registers.comm
class CommByZmq(object):
    """Communication by zmq."""

    def __init__(self, comm_info):
        """Initialize."""
        super(CommByZmq, self).__init__()
        # For Controller, there is no 'addr' parameter given.
        logging.debug("zmq start with comm_info: {}".format(comm_info))
        addr = comm_info.get("addr", "*")
        port = comm_info.get("port")
        zmq_type = comm_info.get("type", "PUB")

        comm_type = {
            "PUB": zmq.PUB,
            "SUB": zmq.SUB,
            "PUSH": zmq.PUSH,
            "PULL": zmq.PULL,
            "REP": zmq.REP,
            "REQ": zmq.REQ,
        }.get(zmq_type)

        context = zmq.Context()
        socket = context.socket(comm_type)

        self._type = zmq_type
        self.bound_port = None
        if "*" in addr:
            # socket.bind("tcp://*:" + str(port))
            bound_port = socket.bind_to_random_port("tcp://*",
                                                    min_port=ZMQ_MIN_PORT,
                                                    max_port=ZMQ_MAX_PORT,
                                                    max_tries=100)
            self.bound_port = bound_port
        else:
            socket.connect("tcp://" + str(addr) + ":" + str(port))

        self.socket = socket

    def send(self, ctr_info, data, name=None, block=True):
        """Send message."""
        # msg = pickle.dumps(data)
        msg = []
        msg.append(pyarrow.serialize(ctr_info).to_buffer())
        msg.append(pyarrow.serialize(data).to_buffer())
        self.socket.send_multipart(msg)

    def recv(self, name=None, block=True):
        """Receive message."""
        msg = self.socket.recv_multipart()
        ctr_info = pyarrow.deserialize(msg[0])
        data = pyarrow.deserialize(msg[1])
        # data = pickle.loads(msg)
        return ctr_info, data

    def send_bytes(self, ctr_info, data):
        """Send bytes."""
        msg = list()
        msg.append(ctr_info)
        msg.append(data)
        self.socket.send_multipart(msg, copy=False)

    def recv_bytes(self, block):
        """Receive bytes."""
        recv_data = self.socket.recv_multipart()
        ctr_info, data = recv_data[0], recv_data[1]

        return ctr_info, data

    def __str__(self):
        """Rewrite the ste func, to return the class info."""
        return str({
            "port": self.bound_port,
            "type": self._type
        })

    def close(self):
        """Close."""
        if self.socket:
            self.socket.close()


from sys import stdin
n = int(stdin.readline())
total = 0
for _ in range(n):
	colour = "".join(x.lower() for x in stdin.readline())
	if "pink" in colour or "rose" in colour:
		total += 1
if total:
	print(total)
else:
	print("I must watch Star Wars with my daughter")


# -*- coding: utf-8 -*-
# #!/usr/bin/python
import os, fnmatch, sys, csv
from datetime import datetime, timedelta
import actor_imdb, actor_tmdb, time

mezzmodbfile = ''
mezzmoposterpath = ''
lastime = ''
csvout = ''
imageout = ''
badimage = ''
imdb_key = ''
imdb_count = '20'
imdb_limit = '1000'
tmdb_key = ''
tmdb_count = '20'
tmdb_limit = '1000'
tmdbact = imdbact = 0
tmdbtry = imdbtry = 0
imdbusy = 0
retry_limit = 5
actordb = 'mezzmo_artwork.db'
sysarg1 = ''
sysarg2 = ''
if len(sys.argv) == 2:
    sysarg1 = sys.argv[1].lower()
if len(sys.argv) == 3:
    sysarg1 = sys.argv[1].lower()
    sysarg2 = sys.argv[2].lower()

def getConfig():

    try:
        global mezzmodbfile, mezzmoposterpath, imdb_key, imdb_count, imdb_limit
        global tmdb_key, tmdb_count, tmdb_limit, retry_limit
        print ("Mezzmo actor comparison v1.0.13")
        fileh = open("config.txt")                                     # open the config file
        data = fileh.readline()
        dataa = data.split('#')                                        # Remove comments
        data = dataa[0].strip().rstrip("\n")                           # cleanup unwanted characters
        mezzmodbfile = data + "Mezzmo.db"
        data = fileh.readline()
        datab = data.split('#')                                        # Remove comments
        mezzmoposterpath = datab[0].strip().rstrip("\n")               # cleanup unwanted characters
        data = fileh.readline()                                        # Get IMDB API key
        if data != '':
            datac = data.split('#')                                    # Remove comments
            imdb_key = datac[0].strip().rstrip("\n")                   # cleanup unwanted characters
        data = fileh.readline()                                        # Get IMDB query count
        if data != '':
            datad = data.split('#')                                    # Remove comments
            count = datad[0].strip().rstrip("\n")                      # cleanup unwanted characters
        if int(count) > int(imdb_limit) or int(imdb_count) > int(imdb_limit):       # Set IMDB limit
            imdb_count = int(imdb_limit)
        elif sysarg2 == '':
            imdb_count = count
        data = fileh.readline()                                        # Get TMDB API key
        if data != '':
            datad = data.split('#')                                    # Remove comments
            tmdb_key = datad[0].strip().rstrip("\n")                   # cleanup unwanted characters
        data = fileh.readline()                                        # Get TMDB query count
        if data != '':
            datae = data.split('#')                                    # Remove comments
            count = datae[0].strip().rstrip("\n")                      # cleanup unwanted characters
        if int(count) > int(tmdb_limit) or int(tmdb_count) > int(tmdb_limit):       # Set TMDB limit
            tmdb_count = int(tmdb_limit)
            print('TMDB query count exceeded maximum.  Reset to ' + str(tmdb_limit))
        elif sysarg2 == '':
            tmdb_count = count
        data = fileh.readline()                                        # Get IMDB retry count
        if data != '':
            datad = data.split('#')                                    # Remove comments
            datae = int(datad[0].strip().rstrip("\n"))                 # cleanup unwanted characters
            if datae < 11:
                retry_limit = datae                                    # update IMDB retry count
        #print ('Retry count is: ' + str(retry_limit))
        fileh.close()                                                  # close the file

        if len(mezzmodbfile) < 5 or len(mezzmoposterpath) < 5:
            print("Invalid configuration file.  Please check the config.txt file.")
            exit()
        else:
            print ("Mezzo database file location: " + mezzmodbfile)
            print ("Mezzmo artwork folder: " + mezzmoposterpath)

        #print(imdb_key)
        #print(imdb_count)

    except Exception as e:
        print (e)
        pass

def checkClean(sysarg, sysargc):

    global csvout, imageout, badimage, imdb_count, tmdb_count, sysarg2
    if len(sysarg) > 1 and 'clean' not in sysarg and 'csv' not in sysarg and 'images' not in sysarg and \
    'bad' not in sysarg and 'noactor' not in sysarg:
        displayHelp()
        exit()
    elif 'clean' in sysarg:
        print('\nCleaning all records from the artwork tracker database.')
        db = openActorDB()
        db.execute('DELETE FROM actorArtwork',)
        db.execute('DELETE FROM userPosterFile',)
        db.execute('DELETE FROM posterFile',)
        db.commit()
        db.close()
        print('Artwork tracker database successfully cleaned.')
        print('Rerun the artwork tracker to repopulate the database.')
        exit()
    elif 'csv' in sysarg:
        csvout = 'true'
        print('CSV file output selected.')
    elif 'images' in sysarg:
        imageout = 'true'
        print('TMDB image fetching selected.')
        try:
            imdb_count = tmdb_count = int(sysargc)
            print('TMDB query count entered: ' + sysargc)
        except:
            if sysargc != '':
                print('The images query count was not a valid number.  Defaulting to config.txt values.')
                sysarg2 = ''
    elif 'bad' in sysarg:
        badimage = 'true'
        print('Bad image file marking selected.')

def displayHelp():                                 #  Command line help menu display

        print('\n=========================================================================================')
        print('\nThe only valid commands are -  clean, csv, images and bad  \n\nExample:  mezzmo_actor.py images')
        print('\n         -\tProviding no arguments runs the artwork tracker normally.')
        print('\nclean    -\tWill remove entries from all tables in artwork tracker database.')
        print('\ncsv      -\tWill run the actor comparison and provide a csv file for the actorArtwork')
        print('\t\ttable and an actor no match csv file which are Mezzmo actors without')
        print('\t\ta Poster or UserPoster file.')
        print('\nnoactor  -\tCreates a CSV file with Mezzmo information for actors not found in TMDB or IMDB')
        print('\nnoactor all -\tCreates a CSV file with Mezzmo information for actors not found in TMDB or IMDB')
        print('\t\tand creates CSV file of all movies with matching actors.')
        print('\nimages   -\tWill fetch missing actor images. TMDB will ge attempted first and if a valid ')
        print('\t\tIMDB API Key is found in the config file, IMDB will then be checked.')
        print('\t\tYou can also enter an optional query count value with images.')
        print('\n\t\tExample:   mezzmo_actor.py images 100     (Perform 100 TMDB image queries) ')
        print('\nbad      - \tFollowed by the image file name will mark an actor as having a bad image')
        print('\t\tand image checking on TMDB and IMDB will be skipped for this actor.')
        print('\n\t\tExample:   mezzmo_actor.py bad john-doe   (File extension is optional)  ')
        print('\n=========================================================================================')

def openActorDB():

    global actordb

    try:
        from sqlite3 import dbapi2 as sqlite
    except:
        from pysqlite2 import dbapi2 as sqlite

    db = sqlite.connect(actordb)

    return db

def checkDatabase():

    try:
        db = openActorDB()

        db.execute('CREATE table IF NOT EXISTS actorArtwork (dateAdded TEXT, actor TEXT, actorMatch TEXT,  \
        posterFile Type TEXT, userPosterFile TEXT)')
        db.execute('CREATE UNIQUE INDEX IF NOT EXISTS actor_1 ON actorArtwork (actor)')
        db.execute('CREATE INDEX IF NOT EXISTS actor_2 ON actorArtwork (actorMatch)')
        db.execute('CREATE table IF NOT EXISTS userPosterFile (dateAdded TEXT, file TEXT, mezzmoMatch TEXT)')
        db.execute('CREATE INDEX IF NOT EXISTS uposter_1 ON userPosterFile (file)')
        db.execute('CREATE table IF NOT EXISTS posterFile (dateAdded TEXT, file TEXT, mezzmoMatch TEXT)')
        db.execute('CREATE INDEX IF NOT EXISTS poster_1 ON posterFile (file)')

        db.execute('CREATE table IF NOT EXISTS actorIndex (fileID TEXT, ID TEXT)')
        db.execute('CREATE INDEX IF NOT EXISTS actorIdx_1 ON actorIndex (ID)')
        db.execute('CREATE INDEX IF NOT EXISTS actorIdx_2 ON actorIndex (fileID)')

        db.execute('CREATE table IF NOT EXISTS mezzmoFile (ID TEXT, file TEXT, title TEXT)')
        db.execute('CREATE INDEX IF NOT EXISTS mezzmof_1 ON mezzmoFile (ID)')

        db.execute('CREATE table IF NOT EXISTS mezzmoMovies (actor TEXT, actorID TEXT, posterFile TEXT, \
        userPosterFile TEXT, title TEXT, fileID TEXT, file TEXT)')
        db.execute('CREATE INDEX IF NOT EXISTS mezzmom_1 ON mezzmoMovies (actor)')

        try:                                          #  Added for v1.0.3
            db.execute('ALTER TABLE actorArtwork ADD COLUMN lastChecked TEXT')
        except:
            pass

        try:                                          #  Added for v1.0.3
            db.execute('CREATE INDEX IF NOT EXISTS actor_3 ON actorArtwork (lastChecked)')
        except:
            pass

        try:                                          #  Added for v1.0.3
            db.execute('ALTER TABLE actorArtwork ADD COLUMN checkStatus TEXT')
        except:
            pass

        try:                                          #  Added for v1.0.6
            db.execute('ALTER TABLE actorArtwork ADD COLUMN mezzmoChecked TEXT')
        except:
            pass

        try:                                          #  Added for v1.0.6
            db.execute('CREATE INDEX IF NOT EXISTS actor_4 ON actorArtwork (mezzmoChecked)')
        except:
            pass

        try:                                          #  Added for v1.0.9
            db.execute('ALTER TABLE actorArtwork ADD COLUMN actorID TEXT')
        except:
            pass

        try:                                          #  Added for v1.0.9
            db.execute('CREATE INDEX IF NOT EXISTS actor_5 ON actorArtwork (actorID)')
        except:
            pass

        db.commit()
        db.close()
        print ("Mezzmo check database completed.")

    except Exception as e:
        print (e)
        print ("There was a problem verifying the database file: " + actordb)
        exit()

def getMezzmo(dbfile):                  #  Query and import / update Mezzmo actors

    try:
        from sqlite3 import dbapi2 as sqlite
    except:
        from pysqlite2 import dbapi2 as sqlite

    try:
        print ("Getting Mezzmo database actor records.")
        db = sqlite.connect(dbfile)

        dbcurr = db.execute('SELECT Data, ID FROM MGOFileArtist',)
        dbtuples = dbcurr.fetchall()
        del dbcurr
        db.close()

        actdb = openActorDB()
        actdb.execute('UPDATE actorArtwork SET mezzmoChecked = NULL',)    #  Clear Mezzmo match
        actdb.commit()
        for a in range(len(dbtuples)):
            #print (dbtuples[a][0])
            pactormodify = dbtuples[a][0].lower().replace(' ', '-').replace('.','-').replace('&','-').replace("'",'-')
            actormodify = pactormodify.replace("(",'-').replace(')','-').replace('"','-').replace(',','')
            currDateTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            curp = actdb.execute('SELECT actor FROM actorArtwork WHERE actor=?',(dbtuples[a][0],))  #  Check actorArtwork
            actortuple = curp.fetchone()
            if not actortuple and len(dbtuples[a][0]) > 0:
                actdb.execute('INSERT into actorArtwork (dateAdded, actor, actorID, actorMatch, mezzmoChecked)   \
                values (?, ?, ?, ?, ?)', (currDateTime, dbtuples[a][0], dbtuples[a][1], actormodify, 'Yes',))
            else:
                actdb.execute('UPDATE actorArtwork SET mezzmoChecked=?, actorID=? WHERE actor=?',                 \
                ('Yes', dbtuples[a][1], dbtuples[a][0],))
        actdb.execute('UPDATE actorArtwork SET mezzmoChecked=? WHERE mezzmoChecked IS NOT ?', ('Deleted','Yes',))

        actdb.commit()
        curp = actdb.execute('SELECT count (*) FROM actorArtwork WHERE mezzmoChecked IS NOT ?', ('Deleted',))
        counttuple = curp.fetchone()
        print ("Mezzo actor records found: " + str(counttuple[0]))
        del curp
        actdb.close()

    except Exception as e:
        print (e)
        pass

def getMezzmoFile(dbfile, sysarg, sysarg2):          #  Query and export actors not found on TMDB / IMDB

    try:
        from sqlite3 import dbapi2 as sqlite
    except:
        from pysqlite2 import dbapi2 as sqlite

    try:
        if sysarg == 'noactor':
            print ("Getting Mezzmo database actor index records.")
            actdb = openActorDB()
            actdb.execute('DELETE FROM actorIndex',)
            actdb.execute('DELETE FROM mezzmoFile',)
            actdb.execute('DELETE from mezzmoMovies',)
            actdb.commit()
            db = sqlite.connect(dbfile)
            dbcurr = db.execute('SELECT FileID, ID FROM MGOFileArtistRelationship',)
            dbtuples = dbcurr.fetchall()
            del dbcurr
            for a in range(len(dbtuples)):
                actdb.execute('INSERT into actorIndex (FileID, ID) values (?, ?)', (dbtuples[a][0], dbtuples[a][1],))
            actdb.commit()
            print ("Finished getting Mezzmo actor index records.")
            print ("Getting Mezzmo database file records.")
            dbcurr = db.execute('SELECT ID, File, Title FROM MGOFile',)
            dbtuples = dbcurr.fetchall()
            del dbcurr
            for a in range(len(dbtuples)):
                actdb.execute('INSERT into mezzmoFile (ID, file, title) values (?, ?, ?)',    \
                (dbtuples[a][0], dbtuples[a][1], dbtuples[a][2],))
            actdb.commit()
            actdb.close()
            db.close()
            print ("Finished getting Mezzmo file records.")

            if sys.version_info[0] < 3:
                print('The CSV export utility requires Python version 3 or higher')
                exit()
            print('CSV noactor file export beginning.')
            actdb = openActorDB()
            curm = actdb.execute('SELECT actor, checkStatus, Title, file from mezzmoFile   \
            INNER JOIN actorIndex ON mezzmoFile.ID=actorIndex.fileId                       \
            INNER JOIN actorArtwork ON actorIndex.ID=actorArtwork.actorID                  \
            WHERE actorArtwork.checkStatus LIKE ? and mezzmoChecked IS NOT ?               \
            ORDER BY actor ASC', ("No actor%", "Deleted",))
            recs = curm.fetchall()
            headers = ['Actor','Status','Title','File Name']
            fpart = datetime.now().strftime('%H%M%S')
            filename = 'no_tmdb_match_' + fpart + '.csv'
            writeCSV(filename, headers, recs)
            del curm
            actdb.close()
            print('CSV noactor file export completed.')
            if sysarg2 == 'all':
                print('CSV noactor all file export beginning.')
                actdb = openActorDB()
                actdb.execute('INSERT into mezzmoMovies (actor, actorID, posterfile,            \
                userPosterFile, title, fileID, file) select actor, actorID,                     \
                actorArtwork.posterFile, actorArtwork.userPosterFile, title, mezzmoFile.ID,     \
                file from mezzmoFile inner join actorIndex ON mezzmoFile.ID = actorIndex.fileID \
                inner join actorArtwork ON actorIndex.ID = actorArtwork.actorID                 \
                where actor is not " " ORDER BY actor, title ASC',)
                actdb.commit()
                curm = actdb.execute('SELECT * from mezzmoMovies')
                mrecs = curm.fetchall()
                headers = ['Actor','ActorID','PosterFile','User Poster','Title','fileID', 'File Name']
                fpart = datetime.now().strftime('%H%M%S')
                filename = 'all_actor_matches_' + fpart + '.csv'
                writeCSV(filename, headers, mrecs)
                del curm
                actdb.close()
                print('CSV noactor all file export completed.')
            exit()

    except Exception as e:
        print (e)
        pass

def getUserPosters(path):

    try:
        print ("Getting Mezzmo UserPoster files.")
        actdb = openActorDB()
        userposter = path + "UserPoster\\"
        #print (userposter)
        listOfFiles = os.listdir(userposter)
        pattern = "*.jpg"
        actdb.execute('DELETE FROM userPosterFile WHERE mezzmoMatch=?', ('No',))
        actdb.commit()
        for x in listOfFiles:
            if fnmatch.fnmatch(x, pattern):
                curp = actdb.execute('SELECT file FROM userPosterFile WHERE file=?',(x,))
                actortuple = curp.fetchone()
                currDateTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                if not actortuple:
                    currDateTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    actdb.execute('INSERT into userPosterFile (dateAdded, file) values (?, ?)', \
                    (currDateTime, x,))
                    curm = actdb.execute('SELECT actor FROM actorArtwork WHERE actorMatch=?',(x[:-4].lower(),))
                    acttuple = curm.fetchone()
                    if acttuple:
                        actdb.execute('UPDATE actorArtwork SET dateAdded=?, userPosterFile=?,   \
                        lastChecked=?, checkStatus=? WHERE actorMatch=?', (currDateTime, x,     \
                        currDateTime, 'Found on Mezzmo', x[:-4].lower()))
                        actdb.execute('UPDATE userPosterFile SET mezzmoMatch=? WHERE file=?',   \
                        ('Yes', x,))
                    else:
                        actdb.execute('UPDATE userPosterFile SET mezzmoMatch=? WHERE file=?',   \
                        ('No', x,))
                else:
                    actdb.execute('UPDATE actorArtwork SET userPosterFile=?, lastChecked=?,     \
                    checkStatus=? WHERE actorMatch=?', (x, currDateTime,'Found on Mezzmo',      \
                    x[:-4].lower()))
                    curm = actdb.execute('SELECT actor FROM actorArtwork WHERE actorMatch=?',(x[:-4].lower(),))
                    acttuple = curm.fetchone()
                    if acttuple:
                        actdb.execute('UPDATE userPosterFile SET mezzmoMatch=? WHERE file=?',   \
                        ('Yes', x,))
                    else:
                        actdb.execute('UPDATE userPosterFile SET mezzmoMatch=? WHERE file=?',   \
                        ('No', x,))

        actdb.commit()
        del actortuple, curp, curm, acttuple
        actdb.close()

    except Exception as e:
        print (e)
        pass

def getPosters(path):

    try:
        print ("Getting Mezzmo Poster files.")
        actdb = openActorDB()
        userposter = path + "Poster\\"
        #print (userposter)
        listOfFiles = os.listdir(userposter)
        pattern = "cva_srch*.jpg"
        count = 0
        for x in listOfFiles:
            if fnmatch.fnmatch(x, pattern):
                curp = actdb.execute('SELECT file FROM posterFile WHERE file=?',(x,))
                actortuple = curp.fetchone()
                currDateTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                actquery = x[9:-4].lower()              #  Remove cva-srch- and file extension
                if not actortuple:
                    actdb.execute('INSERT into posterFile (dateAdded, file) values (?, ?)',      \
                    (currDateTime, x,))
                    #print (x)
                    #print (actquery)
                    curm = actdb.execute('SELECT actor FROM actorArtwork WHERE actorMatch=?',(actquery,))
                    acttuple = curm.fetchone()
                    if acttuple:
                        actdb.execute('UPDATE actorArtwork SET dateAdded=?, posterFile=?,       \
                        lastChecked=?, checkStatus=? WHERE actorMatch=?', (currDateTime, x,     \
                        currDateTime, 'Found on Mezzmo', actquery))
                        actdb.execute('UPDATE posterFile SET mezzmoMatch=? WHERE file=?',       \
                        ('Yes', x,))
                    else:
                        actdb.execute('UPDATE posterFile SET mezzmoMatch=? WHERE file=?',       \
                        ('No', x,))
                else:
                    actdb.execute('UPDATE actorArtwork SET posterFile=?, lastChecked=?,         \
                    checkStatus=? WHERE actorMatch=?', (x, currDateTime,'Found on Mezzmo', actquery))
                    curm = actdb.execute('SELECT actor FROM actorArtwork WHERE actorMatch=?',(actquery,))
                    acttuple = curm.fetchone()
                    if acttuple:
                        actdb.execute('UPDATE posterFile SET mezzmoMatch=? WHERE file=?',       \
                        ('Yes', x,))
                    else:
                        actdb.execute('UPDATE posterFile SET mezzmoMatch=? WHERE file=?',       \
                        ('No', x,))

            count += 1
            if count % 10000 == 0:
                print (str(count) + ' Mezzmo poster files processed.')

        actdb.commit()
        del actortuple, curp, curm, acttuple
        actdb.close()

    except Exception as e:
        print (e)
        pass

def checkCsv(selected):

    try:
        if selected == 'true':
            if sys.version_info[0] < 3:
                print('The CSV export utility requires Python version 3 or higher')
                exit()
            print('CSV file export beginning.')
            db = openActorDB()
            curm = db.execute('SELECT * FROM actorArtwork')
            recs = curm.fetchall()
            headers = [i[0] for i in curm.description]
            fpart = datetime.now().strftime('%H%M%S')
            filename = 'actorartwork_' + fpart + '.csv'
            writeCSV(filename, headers, recs)
            curm = db.execute('select * from actorArtwork where posterFile IS NULL and \
            userPosterFile IS NULL',)
            recs = curm.fetchall()
            headers = [i[0] for i in curm.description]
            fpart = datetime.now().strftime('%H%M%S')
            filename = 'actor_no_match_' + fpart + '.csv'
            writeCSV(filename, headers, recs)
            del curm
            db.close()
            print('CSV file exports completed.')

    except Exception as e:
        print (e)
        pass

def writeCSV(filename, headers, recs):

    try:
        csvFile = csv.writer(open(filename, 'w', encoding = 'utf-8'),
                         delimiter=',', lineterminator='\n',
                         quoting=csv.QUOTE_ALL)
        csvFile.writerow(headers)     # Add the headers and data to the CSV file.
        for row in recs:
            recsencode = []
            for item in range(len(row)):
                if isinstance(row[item], int) or isinstance(row[item], float):  # Convert to strings
                    recitem = str(row[item])
                else:
                    recitem = row[item]
                recsencode.append(recitem)
            csvFile.writerow(recsencode)

    except Exception as e:
        print (e)
        pass

def getIMDBimages():                                         #  Fetch missing actor images from IMDB

    try:
        global imdb_key, imdb_count, imageout, imdbact, imdbtry, retry_limit, imdbusy
        if imageout == 'true':
            print('\nIMDB image fetching beginning.')
            db = openActorDB()
            curp = db.execute('SELECT actor, checkStatus FROM actorArtwork WHERE checkStatus <> ? \
            ORDER BY lastChecked DESC LIMIT ?', ('Bad Image', int(imdb_count),))
            actortuple = curp.fetchall()
            #print ('Records returned: ' + str(len(actortuple)))
            for a in range(len(actortuple)):
                actorname = actortuple[a][0]
                cstatus = actortuple[a][1]
                #print(actorname)
                busycount = imdbfetch = 0
                while busycount < retry_limit and imdbfetch == 0:
                    imgresult = actor_imdb.getImage(imdb_key, actorname, cstatus)
                    currDateTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    if imgresult == 'imdb_found':
                        db.execute('UPDATE actorArtwork SET lastChecked=?, checkStatus=? WHERE actor=?',  \
                        (currDateTime,'Found at IMDB', actorname,))
                        imdbact += 1
                        imdbtry += 1
                        imdbfetch = 1
                    elif imgresult == 'imdb_error':
                        db.execute('UPDATE actorArtwork SET lastChecked=?, checkStatus=? WHERE actor=?',  \
                        (currDateTime,'IMDB error', actorname,))
                        print('Error fetching IMDB image for: ' + actorname)
                        busycount += 1
                        imdbtry += 1
                        imdbusy += 1
                    elif imgresult == 'imdb_busy':
                        busycount += 1
                        print('IMDB server busy. Retrying image fetch for: ' + actorname)
                        #print('IMDB server busy count: ' + str(busycount))
                        imdbtry += 1
                        imdbusy += 1
                        time.sleep(2)
                    elif imgresult == 'imdb_nopicture':
                        db.execute('UPDATE actorArtwork SET lastChecked=?, checkStatus=? WHERE actor=?',  \
                        (currDateTime,'No artwork at IMDB', actorname,))
                        busycount = 0
                        imdbtry += 1
                        imdbfetch = 1
                    elif imgresult == 'imdb_notfound':
                        db.execute('UPDATE actorArtwork SET lastChecked=?, checkStatus=? WHERE actor=?',  \
                        (currDateTime,'No actor match at IMDB', actorname,))
                        print('IMDB actor not found in database: ' + actorname)
                        busycount = 0
                        imdbtry += 1
                        imdbfetch = 1
                    elif imgresult == 'imdb_bad' or imgresult == 'imdb_mezzmo' or imgresult == 'tmdb_found':
                        db.execute('UPDATE actorArtwork SET lastChecked=? WHERE actor=?', (currDateTime,  \
                        actorname,))
                        imdbfetch = 1
                        imdbtry += 1
                    elif imgresult == 'imdb_badkey':
                        print('IMDB image fetching stopping. Invalid API key.')
                        break
                db.commit()
                if busycount == retry_limit and imdbfetch == 0:          # Stop after busy count reached
                    print('\nThe IMDB server appears to be busy or down.  Skipping fetch for ' + actorname + ' .\n')
            db.close()
            print('IMDB image fetching completed.')

    except Exception as e:
        print (e)
        pass

def getTMDBimages():                                         #  Fetch missing actor images from TMDB

    try:
        global tmdb_key, tmdb_count, imageout, tmdbact, tmdbtry, retry_limit
        if imageout == 'true':
            print('\nTMDB image fetching beginning.')
            db = openActorDB()
            curp = db.execute('SELECT actor, lastchecked, checkStatus FROM actorArtwork WHERE      \
            checkStatus IS NULL OR checkStatus IS NOT ? AND mezzmoChecked IS NOT ? AND             \
            checkStatus != ? ORDER BY lastChecked ASC LIMIT ?', ('Found on Mezzmo', 'Deleted',     \
            'Bad Image', int(tmdb_count),))
            actortuple = curp.fetchall()
            #print ('Records returned: ' + str(len(actortuple)))
            for a in range(len(actortuple)):
                actorname = actortuple[a][0]
                pchecktime = actortuple[a][1]
                cstatus = actortuple[a][2]
                #print(actorname)
                currDateTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
                #checktime = (datetime.now() + timedelta(days=-14)).strftime('%Y-%m-%d %H:%M:%S')
                #if pchecktime != None and checktime > pchecktime:
                #    cstatus = ''
                #print(checktime)
                imgresult = actor_tmdb.getImage(tmdb_key, actorname, cstatus)
                #print(imgresult)
                if imgresult == 'tmdb_error':
                    db.execute('UPDATE actorArtwork SET lastChecked=?, checkStatus=? WHERE actor=?',  \
                    (currDateTime,'TMDB error', actorname,))
                    print('Error fetching TMDB image for: ' + actorname)
                    tmdbtry += 1
                elif imgresult == 'tmdb_busy':
                    print('TMDB fetching skipped. Server busy: ' + actorname)
                    tmdbtry += 1
                elif imgresult == 'tmdb_found':
                    db.execute('UPDATE actorArtwork SET lastChecked=?, checkStatus=? WHERE actor=?',  \
                    (currDateTime,'Found at TMDB', actorname,))
                    tmdbact += 1
                    tmdbtry += 1
                elif imgresult == 'tmdb_nopicture':
                    db.execute('UPDATE actorArtwork SET lastChecked=?, checkStatus=? WHERE actor=?',  \
                    (currDateTime,'No artwork at TMDB', actorname,))
                    tmdbtry += 1
                elif imgresult == 'tmdb_notfound':
                    db.execute('UPDATE actorArtwork SET lastChecked=?, checkStatus=? WHERE actor=?',  \
                    (currDateTime,'No actor match at TMDB', actorname,))
                    print('TMDB actor not found in database: ' + actorname)
                    tmdbtry += 1
                elif imgresult == 'tmdb_bad' or imgresult == 'tmdb_mezzmo' or imgresult == 'tmdb_found':
                    db.execute('UPDATE actorArtwork SET lastChecked=? WHERE actor=?', (currDateTime,  \
                    actorname,))
                elif imgresult == 'tmdb_badkey':
                    print('TMDB image fetching stopping. Invalid API key.')
                    break
                db.commit()
            db.close()
            print('TMDB image fetching completed.')

    except Exception as e:
        print (e)
        pass

def checkBad():                                            # Mark bad image file

    try:
        global badimage, sysarg2
        badlist = []
        badfile = sysarg2.lower().split('.')[0]            # Handle file extension and mixed case
        #print(badfile)
        if badimage == 'true':
            #if len(badfile) < 4:
            if badfile:                                    # Append user entry
                badlist.append(badfile)                    # Process badfiles
            badresult = updateBad(badlist)
            if badresult == 'good':
                print('Bad file processing completed.')
            else:
                print('There was a problem completing the Bad file processing.')
            displayStats()
            exit()

    except Exception as e:
        print (e)
        pass

def updateBad(actorfiles):                                # Mark bad images from "\bad images"

    try:
        badfolder = "bad images\\"
        listOfFiles = os.listdir(badfolder)
        pattern = "*.jpg"
        for x in listOfFiles:                             #  Get bad folder list
            if fnmatch.fnmatch(x, pattern):
                actorfiles.append(x.split('.')[0] )       #  Remove file extension
        #print(actorfiles)
        if len(actorfiles) == 0:
            print('There are no bad image files or user entries to process.')
            return('bad')
        else:
            print('Bad file processing beginning.')
            db = openActorDB()
            for a in range(len(actorfiles)):
                matchfile = actorfiles[a]
                curp = db.execute('SELECT actorMatch FROM actorArtwork WHERE actorMatch=?', (matchfile,))
                actortuple = curp.fetchone()
                if actortuple:
                    currDateTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    db.execute('UPDATE actorArtwork SET lastChecked=?, checkStatus=? WHERE actorMatch=?',  \
                    (currDateTime,'Bad Image', matchfile,))
                    print('Actor image file marked bad: ' + matchfile)
                else:
                    print('Actor image file not found in database: ' + matchfile)

        del curp
        db.commit()
        db.close()
        return('good')

    except Exception as e:
        print (e)
        return('bad')
        pass

def getLast():                                      # Find last time checker ran

    try:
        global lastime
        db = openActorDB()
        curs = db.execute('select lastChecked FROM actorArtwork ORDER BY lastChecked \
        DESC LIMIT 1',)
        counttuple = curs.fetchone()
        if counttuple:
            lastime = str(counttuple[0])
        else:
            lastime = 'Never'

        del curs, counttuple
        db.close()

    except Exception as e:
        print (e)
        pass

def displayStats():                                 # Display stats from Mezzmo Tracker DB

    try:
        global lasttime, tmdbact, imdbact, imdb_count, tmdb_count
        global sysarg1, imdbtry, tmdbtry, imdbusy
        badcount = postfound = nopostmatch = upostfound = dactcount = 0
        actcount = mezcount = nomatch = noupostmatch = noart = noact = 0

        db = openActorDB()
        curs = db.execute('SELECT count (*) FROM userPosterFile',)
        counttuple = curs.fetchone()
        if counttuple:
            upostfound = str(counttuple[0])
        curs = db.execute('SELECT count (*) FROM userPosterFile WHERE mezzmoMatch=? ',('No',))
        counttuple = curs.fetchone()
        if counttuple:
            noupostmatch = str(counttuple[0])
        curs = db.execute('SELECT count (*) FROM posterFile',)
        counttuple = curs.fetchone()
        if counttuple:
            postfound = str(counttuple[0])
        curs = db.execute('SELECT count (*) FROM posterFile WHERE mezzmoMatch=? ',('No',))
        counttuple = curs.fetchone()
        if counttuple:
            nopostmatch = str(counttuple[0])
        curs = db.execute('select count (*) from actorArtwork where checkStatus=?',  \
        ('Bad Image',))
        counttuple = curs.fetchone()
        if counttuple:
            badcount =  str(counttuple[0])
        curs = db.execute('select count (*) from actorArtwork where mezzmoChecked=?', ('Yes',))
        counttuple = curs.fetchone()
        if counttuple:
            actcount =  str(counttuple[0])
        curs = db.execute('select count (*) from actorArtwork where mezzmoChecked=?', ('Deleted',))
        counttuple = curs.fetchone()
        if counttuple:
            dactcount =  str(counttuple[0])
        curs = db.execute('select count (*) from actorArtwork where checkStatus=?',  \
        ('Found on Mezzmo',))
        counttuple = curs.fetchone()
        if counttuple:
            mezcount =  str(counttuple[0])
        curs = db.execute('select count (*) from actorArtwork where posterFile IS    \
        NULL and userPosterFile IS NULL',)
        counttuple = curs.fetchone()
        if counttuple:
            nomatch =  str(counttuple[0])
        curs = db.execute('select count (*) from actorArtwork where checkStatus LIKE \
        ?', ('No artwork%',))
        counttuple = curs.fetchone()
        if counttuple:
            noart =  str(counttuple[0])
        curs = db.execute('select count (*) from actorArtwork where checkStatus LIKE \
        ?', ('No actor%',))
        counttuple = curs.fetchone()
        if counttuple:
            noact =  str(counttuple[0])

        if sysarg1 == 'images':
            print ("\nTMDB query count: \t\t\t" + str(tmdb_count))
            print ("TMDB image queries:\t\t\t" + str(tmdbtry))
            print ("TMDB images found on this query: \t" + str(tmdbact))
            print ("IMDB query count: \t\t\t" + str(imdb_count))
            print ("IMDB image queries:\t\t\t" + str(imdbtry))
            print ("IMDB images found on this query: \t" + str(imdbact))
            #if imdbusy == 0:
                #spercent = str(100 * ((float(imdb_count) - tmdbact) / imdbtry))
            #spercent = str(100 * (1 - (float(imdbusy) / (imdb_count - tmdbact))))
            spercent = str(100 * (1 - (float(imdbusy) / imdbtry)))
            sfind = spercent.find('.')
            fpercent = spercent[:sfind + 3]
            #else:
            #    fpercent = '100.00'
            print ("IMDB image query success rate: \t\t" + fpercent + "%")
        print ('\n\t ************  Mezzmo Artwork Checker Stats  *************\n')
        print ("Last time checker ran: \t\t\t" + lastime)
        print ("Mezzmo actors found: \t\t\t" + actcount)
        print ("Mezzmo actors deleted: \t\t\t" + dactcount)
        print ("Mezzmo Poster files found: \t\t" + postfound)
        print ("Mezzmo Poster files without actor: \t" + nopostmatch)
        print ("Mezzmo UserPoster files found: \t\t" + upostfound)
        print ("Mezzmo UserPoster files without actor: \t" + noupostmatch)
        print ("Mezzmo actor not found on IMDB/TMDB: \t" + noact)
        print ("Mezzmo actors with Good Image:  \t" + mezcount)
        print ("Mezzmo actors with Bad Image:  \t\t" + badcount)
        print ("Mezzmo actors with no Image:   \t\t" + nomatch)
        print ("Mezzmo actors with no Image found:   \t" + noart)

        del curs, counttuple
        db.close()

    except Exception as e:
        print (e)
        pass

def checkFolders():				    #  check initial folder structures

    try:
        if not os.path.exists('bad images'):        #  Check bad files location
            os.makedirs('bad images')
        if not os.path.exists('imdb'):              #  Check IMDB files location
            os.makedirs('imdb')
        if not os.path.exists('tmdb'):              #  Check TMDB files location
            os.makedirs('tmdb')

    except Exception as e:
        print (e)
        pass

def optimizeDB():                                   # Optimize database

    db = openActorDB()
    db.execute('REINDEX',)
    db.execute('VACUUM',)
    db.commit()
    db.close()
    print('Mezzmo artwork tracker database optimization complete.')

#  Main routines
checkFolders()
checkClean(sysarg1, sysarg2)
checkBad()
getConfig()
getLast()
checkDatabase()
optimizeDB()
getMezzmo(mezzmodbfile)
getMezzmoFile(mezzmodbfile, sysarg1, sysarg2)
getUserPosters(mezzmoposterpath)
getPosters(mezzmoposterpath)
getTMDBimages()
getIMDBimages()
checkCsv(csvout)
print('Mezzmo actor comparison completed successfully.')
displayStats()


"""
Author: Max Martinez Ruts
Date: October 2019
Idea:

Find an optimum porfolio by using a numerical method to simply try setting random weights and testing beta-return for each
combination of weights. Then selecting the beta-return point that leads to the highest return-beta slope (optimum portfolio)
"""

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Import data from several stock markets
stocks = []
stocks.append(pd.read_csv("DJI.csv")[-4000:])
stocks.append(pd.read_csv("GSPC.csv")[-4000:])
stocks.append(pd.read_csv("AAPL.csv")[-4000:])
stocks.append(pd.read_csv("MSI.csv")[-4000:])
stocks.append(pd.read_csv("MSFT.csv")[-4000:])
# stocks.append(pd.read_csv("GOOG.csv")[-4000:])

Rf = 1.00019942227

opens = []
closes = []
returns = []
rates = []

# Store relevant data
for stock in stocks:
    opens.append(np.array(stock['Open']))
    closes.append(np.array(stock['Close']))
    returns.append(closes[-1]/opens[-1])
    rates.append(closes[-1] / opens[-1])

# Create time array ranging from 0 to the last opening
ts = np.arange(0,len(opens[0]),1)

# Create the covariance matrix
mat = rates
cov = np.cov(mat)
corr = np.corrcoef(mat)
expret = np.mean(rates, axis=1)

print(expret)
ps = []

for i in range(len(stocks)):
    ps.append([np.sqrt(cov[i,i]),expret[i]])

xs = []
ys = []
max_slope = 0

X = 1000

# Repeat X times
for i in range(X):
    for j in range(len(stocks)):

        # Associate random weights
        ws = np.random.uniform(0,10,(len(stocks),1))
        ws = ws/np.sum(ws)

        # Determine the return and risk using such weights
        weighted_cov = np.sqrt(np.sum(np.matmul(ws, ws.transpose())* cov))
        weighted_ret = np.sum(np.dot(expret, ws))

        # Get return to beta slope
        slope = (weighted_ret-Rf)/weighted_cov

        # If the point found is better than any other found yet, update max
        if slope > max_slope:
            max_slope = slope
            max_point = [weighted_cov, weighted_ret]

        # Append to the list to plot them later
        xs.append(weighted_cov)
        ys.append(weighted_ret)
        # print('Weight:',w1, 'Risk:',weighted_cov, 'Return:',weighted_ret)

# Plot the points (each point represents a beta-return possible by using its associated weights)
plt.scatter(xs, ys)

# Plot important points and slope
plt.scatter([p[0] for p in ps], [p[1] for p in ps])
plt.scatter(max_point[0], max_point[1])
plt.scatter(0, Rf)

plt.show()


from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt, QAbstractListModel
import sys

import qtmodern.styles
import qtmodern.windows

class ListModel(QAbstractListModel):
    def __init__(self, datalist):
        super(ListModel, self).__init__()
        self.datalists = datalist

    def data(self, index, role):
        if role == Qt.DisplayRole:
            text = self.datalists[index.row()]
            return text

    def rowCount(self, index):
        result = len(self.datalists)
        return result

class MyApp(QMainWindow):
    def __init__(self):
        super(MyApp, self).__init__()
        self.mainUI()
        self.layoutVertical()
        self.setCentralWidget(self.setWidget)

    def mainUI(self):
        self.list = QListView()
        self.model = ListModel(datalist=[])
        self.list.setModel(self.model)
        self.btnAdd = QPushButton("Add")
        self.btnAdd.clicked.connect(self.addItem)
        self.buttonRemove = QPushButton("Remove")
        self.buttonRemove.clicked.connect(self.removeItems)
        self.btnClear = QPushButton("Clear")
        self.btnClear.clicked.connect(self.clear)
        self.btnUpdate = QPushButton("Update")
        self.btnUpdate.clicked.connect(self.update)
        self.btnDuplicate = QPushButton("Duplicate")
        self.btnDuplicate.clicked.connect(self.duplicate)

        # Slider
        self.slider = QSlider(Qt.Horizontal)
        self.slider.valueChanged.connect(self.valueSlider)

        # progressbar
        self.progressBar = QProgressBar()

    def layoutVertical(self):
        self.layoutList = QVBoxLayout()
        self.layoutList.addWidget(self.list)
        self.layoutList.addWidget(self.layoutHorizontal())
        self.layoutList.addWidget(self.slider)
        self.layoutList.addWidget(self.progressBar)

        self.setWidget = QWidget()
        self.setWidget.setLayout(self.layoutList)

    def layoutHorizontal(self):
        self.LayoutH = QHBoxLayout()
        self.LayoutH.addWidget(self.btnAdd)
        self.LayoutH.addWidget(self.buttonRemove)
        self.LayoutH.addWidget(self.btnClear)
        self.LayoutH.addWidget(self.btnUpdate)
        self.LayoutH.addWidget(self.btnDuplicate)

        self.widgetH = QWidget()
        self.widgetH.setLayout(self.LayoutH)
        return self.widgetH

    def addItem(self):
        add, ok = QInputDialog.getText(self, "Add item", "Add list item")
        if add != "" and ok == True:
            self.model.datalists.append(add)
            self.model.layoutChanged.emit()

        self.progressBar.setValue(len(self.model.datalists))

    def removeItems(self):
        index = self.list.selectedIndexes()
        if not index:
            QMessageBox.warning(self, "Warning", "Please select item !")
        else:
            indexes = index[0]
            del self.model.datalists[indexes.row()]
            self.model.layoutChanged.emit()
            self.progressBar.setValue(len(self.model.datalists))

    def clear(self):
        self.model.datalists.clear()
        self.model.layoutChanged.emit()
        self.progressBar.setValue(len(self.model.datalists))

    def update(self):
        index = self.list.selectedIndexes()
        if not index:
            QMessageBox.warning(self, "Warning", "Please select item !")
        else:
            selected = self.model.datalists[index[0].row()]
            update, ok = QInputDialog.getText(self, "Add item", "Add list item", text=selected)
            self.model.datalists[index[0].row()] = update
            self.model.layoutChanged.emit()

    def valueSlider(self):
        value = self.slider.value()
        return value

    def duplicate(self):
        value = self.valueSlider()
        index = self.list.selectedIndexes()
        if not index:
            QMessageBox.warning(self, "Warning", "Please select item !")
        else:
            results = self.model.datalists[index[0].row()]
            for x in range(value):
                self.model.datalists.append(results)
                self.model.layoutChanged.emit()

            self.progressBar.setValue(len(self.model.datalists))

if __name__ == "__main__":
    app = QApplication([])
    window = MyApp()
    qtmodern.styles.light(app)
    theme = qtmodern.windows.ModernWindow(window)
    theme.show()
    app.exec_()


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

def calculadoraEx(amount):
    mex_to_col = 145.97
    return amount * mex_to_col

def run():
    print('C a l c u l a d o r a  d e  D i v i s a s ')
    print('Convierte pesos Mexicanos a Colombianos')
    print('')

    amount = float(raw_input('Ingresa la cantidad de pesos Mexicanos a convertir: '))

    result = calculadoraEx(amount)

    print('El monto {} de pesos Mexicanos en pesos colombianos es {}'.format(amount, result))
    print('')
if __name__ == "__main__":
    run()


class Solution:
    """
    @param head: the given linked list
    @return: the array that store the values in reverse order
    """

    def reverseStore(self, head):
        self.res = []
        self.dfs(head)
        return self.res

    def dfs(self, head):
        if head is None:
            return
        self.dfs(head.next)
        self.res.append(head.val)


import serial
from gi.repository import Gtk
SER=serial.Serial('/dev/ttyUSB0',9600)
x='25'
class ThisWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self,title='ThisWindow')
        self.set_default_size(200,200)
        button0=Gtk.Button.new_with_label('send')
        button0.connect("clicked",self.on_clicked)
        self.add(button0)

    def on_clicked(self,widget):
        print (x)
        SER.write(x.encode())

win=ThisWindow()
win.connect("delete-event",Gtk.main_quit)
win.show_all()
Gtk.main()