# -*- coding: utf-8 -*-
"""
Created on Fri Jan  6 16:08:18 2023

@author: Chris
"""
import os
import cv2
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import mediapipe as mp
from mediapipe.python.solutions.drawing_utils import _normalized_to_pixel_coordinates
import matplotlib as plt
from pylab import *

# Initalisierung der Benötigten Variablen aus Mediapipe
mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_pose = mp.solutions.pose
mp_face_mesh = mp.solutions.face_mesh
mp_face_detection = mp.solutions.face_detection
mp_holistic = mp.solutions.holistic

# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))

def rescale_frame(frame, percent):

    """
    Herrausziehen der einzelnen Frames und bestimmung wie viel Prozent der Gesamtanzahl der Frames Verwendet werden soll.
    https://www.kaggle.com/code/brodielamont/test-opencv-video-and-mediapipe
    """

    width = int(frame.shape[1] * percent/100)
    height = int(frame.shape[0] * percent/100)
    dimention = (width, height)

    return cv2.resize(frame, dimention, interpolation = cv2.INTER_AREA)

def get_Data_pose(path, model,n,n_plot):

    """
    Funktioniert. Gibt aber bei manchen Frames einen Attribut error zurück, weil es in diesen Frame die Pose nicht auslesen kann.
    Woran das liegt bin ich mir noch nicht sicher, weil der Kamerawinkel eigentlich garkeine Rolle spielen sollte. Dadurch kann er an
    manchen Punkten keine x,y,z Koordinate auslesen weswegen es zu einen Error kommt.
    https://google.github.io/mediapipe/solutions/pose.html
    https://mlhive.com/2021/11/person-pose-landmarks-detection-using-mediapipe
    https://www.kaggle.com/code/brodielamont/test-opencv-video-and-mediapipe
    """

    with mp_pose.Pose(static_image_mode=True, min_detection_confidence=0.5, min_tracking_confidence=0.5,enable_segmentation=False, model_complexity=model) as pose:

        # Import video file
        video_cap = cv2.VideoCapture(DATA_DIRECTORY+"/"+path)

        if (video_cap.isOpened()== False):
            print("Error opening video  file")

        success, image = video_cap.read()

        if success:
            print("success")

        # Resize video
        # Extract frames
        count = 1
        xyz = []
        error_l = []
        while success:
            try:
                image = rescale_frame(image, n)
                result = pose.process(image)
                x = result.pose_landmarks.landmark[0].x
                y = result.pose_landmarks.landmark[0].y
                z = result.pose_landmarks.landmark[0].z
                xyz.append([x,y,z])

                cv2.imwrite(FRAME_DIRECTORY+"/"+path[:-4]+"_"+str(count)+".jpeg", image)
                success, image = video_cap.read()
                count = count + 1

                if success==False:
                    break

                plot_landmark_pose(image,result,n_plot,count)

            except AttributeError:
                error_l.append(f"Attribute Error für Posedetection bei Frame: {count}")
                print(f"Attribute Error für Posedetection bei Frame: {count}")
                cv2.imwrite(FRAME_PAINT_DIRECTORY+"/"+path[:-4]+"_Frame_"+str(count)+".jpeg", image)
                count = count + 1

        data = np.array(xyz)
        saving_csv(path[:-4],data)
        saving_error(path[:-4], error_l)

        return data

def get_Data_mesh(path, model,n,n_plot):

    """
    Erkennt das Gesicht auf dem Video sehr gut wenn es einigermaßen zentral in dem Video ist. Sobald man das Gesicht von der Seite sieht
    oder nur zur Hälfte bekommt der Algorithmus Keine Informationen zurück und schmeißt einen Error. Beispiel: Video 001 wird alles sehr
    gut erkannt - in Video 016 hingegen gibt der Algorithmus nichts zurück, da er das Gesicht nicht erkennt.

    Was man versuchen kann ist bevor man den Facemesh durchführt. Eine Face detection davor zu bauen um darüber dann den Facemesh
    berechnen zu können. Wird gerade ausprobiert.
    https://github.com/serengil/tensorflow-101/blob/master/python/Mediapipe-Face-Detector.ipynb
    https://www.kaggle.com/code/brodielamont/test-opencv-video-and-mediapipe
    """

    with mp_face_mesh.FaceMesh(static_image_mode=True, min_detection_confidence=0.5, max_num_faces=model) as face_mesh:

        # Import video file
        video_cap = cv2.VideoCapture(DATA_DIRECTORY+"/"+path)

        if (video_cap.isOpened()== False):
            print("Error opening video  file")

        success, image = video_cap.read()

        print()
        if success:
            print("success")

        # Resize video
        # Extract frames
        count = 1
        xyz = []
        error_l = []
        while success:
            try:
                image = rescale_frame(image, n)
                result = face_mesh.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
                x = result.multi_face_landmarks[0].landmark[0].x
                y = result.multi_face_landmarks[0].landmark[0].y
                z = result.multi_face_landmarks[0].landmark[0].z
                xyz.append([x,y,z])

                cv2.imwrite(FRAME_DIRECTORY+"/"+path[:-4]+"_"+str(count)+".jpeg", image)
                success, image = video_cap.read()

                if success==False:
                    break

                count = count + 1

                landmarks = result.multi_face_landmarks[0]
                plot_landmark(image,landmarks,n_plot,count)

            except TypeError:
                error_l.append(f"Type Error für Facedetection bei Frame: {count}")
                print(f"Type Error für Facedetection bei Frame: {count}")
                cv2.imwrite(FRAME_PAINT_DIRECTORY+"/"+path[:-4]+"_Frame_"+str(count)+".jpeg", image)
                count = count + 1

        data = np.array(xyz)
        saving_csv(path[:-4],data)
        saving_error(path[:-4], error_l)

        return data

def get_Data_detection(path, model,n,n_plot):

    """
    Face Detection Funktioniert bekommt aber manchmal einen TypeError, das liegt daran das es in Manchen Videos Schwierigkeiten hat das
    Gesicht zu erkennen. Am Besten funktioniert der Algorithmus wenn man das Gesicht frontal aufgenommen hat in dem Video sobald ein
    etwas zu Kleiner Gesichtsteil nur von der Seite zu sehen ist, bekommt man einen Nonetype zurück was dann den Fehler des TypeErrors
    auslöst.
    So mit ist die Bedingung das das Gesicht gut erkennbar ist.
    Aber er funktioniert auch ganz solide wenn man eine Schräge Kameraperspektive hat. Sie darf nur einen gewissen winkel nicht
    überschreiten bzw. Das Gesicht muss gut erkennbar sein.
    https://pylessons.com/face-detection
    https://www.kaggle.com/code/brodielamont/test-opencv-video-and-mediapipe
    """

    with mp_face_detection.FaceDetection(model_selection=model, min_detection_confidence=0.5) as face_detection:

        # Import video file
        video_cap = cv2.VideoCapture(DATA_DIRECTORY+"/"+path)

        if (video_cap.isOpened()== False):
            print("Error opening video  file")

        success, image = video_cap.read()

        print()
        if success:
            print("success")

        # Resize video
        # Extract frames
        count = 1
        xyz = []
        while success:
            image = rescale_frame(image, n)
            result = face_detection.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))

            result_face_d = result.detections

            cv2.imwrite("image"+str(count)+".jpeg", image)
            success, image = video_cap.read()

            if success==False:
                break

            try:
                xyz = tlbr(image,result_face_d)
            except TypeError:
                print("TypeError")

            count = count + 1

            if count % n_plot == 0:
                plot_Face_Detect(image,result_face_d)

        data = np.array(xyz)

        return data

def get_Data_holistic(path, model,n,n_plot):

    """

    https://github.com/google/mediapipe/blob/master/mediapipe/python/solutions/holistic.py

    """

    with mp_holistic.Holistic(static_image_mode=True, refine_face_landmarks=True, model_complexity=model,enable_segmentation=True) as holistic:

        # Import video file
        video_cap = cv2.VideoCapture(DATA_DIRECTORY+"/"+path)

        fps = video_cap.get(cv2.CAP_PROP_FPS)
        #width  = int(video_cap.get(cv2.CAP_PROP_FRAME_WIDTH ))
        #height = int(video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT ))

        if (video_cap.isOpened()== False):
            print("Error opening video  file")

        success, image = video_cap.read()

        print()
        if success:
            print("success")

        # Resize video
        # Extract frames
        count = 1
        xyz_pose = []
        xyz_face = []
        xyz_hand_r = []
        xyz_hand_l = []
        vis_l = []
        error_l = []

        while success:

                image = rescale_frame(image, n)
                result = holistic.process(image)

                # outputs=['pose_landmarks', 'pose_world_landmarks', 'left_hand_landmarks','right_hand_landmarks',
                # 'face_landmarks', 'segmentation_mask']
                # Kann alles aus Results ausgelesen werden !!
                #print(result.pose_landmarks.landmarks[0])

                try:
                    x = result.pose_landmarks.landmark[0].x
                    y = result.pose_landmarks.landmark[0].y
                    z = result.pose_landmarks.landmark[0].z

                    xyz_pose.append([x,y,z])

                except AttributeError:
                    error_l.append(f"Attribute Error für Posedetection bei Frame: {count}")
                    print(f"Attribute Error für Posedetection bei Frame: {count}")
                    cv2.imwrite(FRAME_PAINT_DIRECTORY+"/"+path[:-4]+"_Frame_"+str(count)+".jpeg", image)
                    count = count + 1

                try:

                    x = result.face_landmarks.landmark[0].x
                    y = result.face_landmarks.landmark[0].y
                    z = result.face_landmarks.landmark[0].z

                    xyz_face.append([x,y,z])
                except:
                    error_l.append(f"Attribute Error für Facedetection bei Frame: {count}")
                    print(f"Attribute Error für Facedetection bei Frame: {count}")
                    cv2.imwrite(FRAME_PAINT_DIRECTORY+"/"+path[:-4]+"_Frame_"+str(count)+".jpeg", image)
                    count = count + 1

                """
                try:
                    x = result.right_hand_landmarks.landmark[0].x
                    y = result.right_hand_landmarks.landmark[0].y
                    z = result.right_hand_landmarks.landmark[0].z

                    xyz_hand_r.append([x,y,z])

                    x = result.left_hand_landmarks.landmark[0].x
                    y = result.left_hand_landmarks.landmark[0].y
                    z = result.left_hand_landmarks.landmark[0].z

                    xyz_hand_l.append([x,y,z])
                except AttributeError:
                     print(f"Attribute Error für Handdetection bei Frame: {count}")
                     count = count + 1

                """
                try:
                    cv2.imwrite(FRAME_DIRECTORY+"/"+path[:-4]+"_"+str(count)+".jpeg", image)
                    success, image = video_cap.read()

                    if success==False:
                        break

                    # Nicht jeder Frame würd durch die IF-Abfrage
                    # gezeichnet sondern nur jeder zehnte

                    #if count % 10 == 0:
                    helper = count
                    landmarks = result.face_landmarks
                    plotting_landmarks_f_p(image,landmarks,result,path[:-4],n_plot,helper)

                    count = count + 1

                except AttributeError:
                   error_l.append(f"Attribute Error für Plotting bei Frame: {count}")
                   print(f"Attribute Error für Plotting bei Frame: {count}")
                   cv2.imwrite(FRAME_PAINT_DIRECTORY+"/"+path[:-4]+"_Frame_"+str(count)+".jpeg", image)
                   count = count + 1

        vis_data = np.array(vis_l)
        data = np.array([xyz_pose,xyz_face])
        saving_error(path[:-4],error_l)
        saving_Video(path[:-4],count,fps)
        saving_csv(path[:-4],data)

        return data , vis_data

def tlbr(frame, mp_detections):

        """Return coorinates in typing.Iterable([[Top, Left, Bottom, Right]])

        Args:
            frame: (np.ndarray) - frame on which we want to apply detections
            mp_detections: (typing.List) - list of media pipe detections

        Returns:
            detections: (np.ndarray) - list of detection in [Top, Left, Bottom, Right] coordinates

        https://pylessons.com/face-detection
        """

        detections = []
        frame_height, frame_width, _ = frame.shape
        for detection in mp_detections:
            height = int(detection.location_data.relative_bounding_box.height * frame_height)
            width = int(detection.location_data.relative_bounding_box.width * frame_width)
            left = int(detection.location_data.relative_bounding_box.xmin * frame_width)
            top = int(detection.location_data.relative_bounding_box.ymin * frame_height)

            detections.append([top, left, top + height, left + width])

        return np.array(detections)

def plot_Face_Detect(frame,result_face_d, return_tlbr = False, mp_drawing_utils = True):

    """Main function to do face detection

        Args:
            frame: (np.ndarray) - frame to excecute face detection on
            return_tlbr: (bool) - bool option to return coordinates instead of frame with drawn detections

        Returns:
            typing.Union[
                frame: (np.ndarray) - processed frame with detected faces,
                detections: (typing.List) - detections in [Top, Left, Bottom, Right]
                ]

        https://pylessons.com/face-detection
        """

    if result_face_d:

            img = frame.copy()
            color = (255, 255, 255)
            thickness = 2

            if return_tlbr:
                return tlbr(frame, result_face_d.detections)

            if mp_drawing_utils:
                # Draw face detections of each face using media pipe drawing utils.
                for detection in result_face_d:
                    mp_drawing.draw_detection(img, detection)
                    img = cv2.resize(img, (384*2,288*2))

                    cv2.imshow('image',img)
                    cv2.waitKey(0)

            else:
                # Draw face detections of each face using our own tlbr and cv2.rectangle
                for tlbr_t in tlbr(frame, result_face_d):
                    cv2.rectangle(frame, tlbr_t[:2][::-1], tlbr_t[2:][::-1], color, thickness)

    return frame

def plot_landmark(img_base,landmarks,n_plot,count):

    img = img_base.copy()

    for idx, landmark in enumerate(landmarks.landmark):
        x = landmark.x
        y = landmark.y

        relative_x = int(img.shape[1] * x)
        relative_y = int(img.shape[0] * y)

        #print(relative_x, relative_y)
        cv2.circle(img, (relative_x, relative_y), 1, (0, 0, 255), -1)

    img = cv2.resize(img, (384*2,288*2))

    if count % n_plot == 0:
       cv2.imshow('image',img)
       cv2.waitKey(0)

def plot_landmark_pose(img_base,results,n_plot,count):

    annotated_image = img_base.copy()
    mp_drawing.draw_landmarks(
        annotated_image,
        results.pose_landmarks,
        mp_pose.POSE_CONNECTIONS)
    annotated_image = cv2.resize(annotated_image, (384*2,288*2))

    if count % n_plot == 0:
       cv2.imshow('image',annotated_image)
       cv2.waitKey(0)

def plotting_landmarks_f_p(img_base,landmarks,results,path,n_plot,count):

    img = img_base.copy()

    for idx, landmark in enumerate(landmarks.landmark):
        x = landmark.x
        y = landmark.y

        relative_x = int(img.shape[1] * x)
        relative_y = int(img.shape[0] * y)

        #print(relative_x, relative_y)
        cv2.circle(img, (relative_x, relative_y), 1, (0, 0, 255), -1)

    mp_drawing.draw_landmarks(
        img,
        results.pose_landmarks,
        mp_pose.POSE_CONNECTIONS,
        landmark_drawing_spec=mp_drawing_styles.get_default_pose_landmarks_style())

    img = cv2.resize(img, (384*2,288*2))
    cv2.imwrite(FRAME_PAINT_DIRECTORY+"/"+path+"_Frame_"+str(count)+".jpeg", img)

    if count % n_plot == 0:
        cv2.imshow('image',img)
        cv2.waitKey(0)

def saving_csv(path,data):

    data_l = len(data)

    if data_l >= 412:
        df = pd.DataFrame(data, columns = ['x','y','z'])
        df.to_csv(SAVING_DIRECTORY+"/"+path+".csv",index=False,header=True, sep='\t')
    else:
        for i,landmarks in enumerate(data):
            print(i)
            if i == 0:
                df = pd.DataFrame(landmarks, columns = ['x','y','z'])
                df.to_csv(SAVING_DIRECTORY+"/"+path+"_pose_landmarks.csv",index=False,header=True, sep='\t')
            elif i == 1:
                df = pd.DataFrame(landmarks, columns = ['x','y','z'])
                df.to_csv(SAVING_DIRECTORY+"/"+path+"_face_landmarks.csv",index=False,header=True, sep='\t')

def saving_Video(path,count,fps):

    """
    https://stackoverflow.com/questions/43048725/python-creating-video-from-images-using-opencv
    https://stackoverflow.com/questions/72249011/appending-video-frame-to-list-using-opencv-take-a-lot-of-resources-in-ram
    https://stackoverflow.com/questions/73609006/how-to-create-a-video-out-of-frames-without-saving-it-to-disk-using-python?noredirect=1&lq=1
    """
    frames = []
    fourcc = cv2.VideoWriter_fourcc(*"XVID")
    #fourcc = cv2.VideoWriter_fourcc(*'DIVX')

    print("Anzahl der Frames: "+str(count))

    for i in range(1,count):
        frames.append(cv2.imread(FRAME_PAINT_DIRECTORY+"/"+path+"_Frame_"+str(i)+".jpeg"))

    height,width,layers=frames[1].shape

    # Muss überlegt werden ob man die fs durch 1.25 rechnen will
    out = cv2.VideoWriter(SAVING_V_DIRECTORY+"/"+path+"_Test6_.mp4",fourcc,fps,(width,height))

    for frame in frames:
        #img_result = MyImageTreatmentFunction(frame) # returns a numpy array image
        out.write(frame)

    cv2.destroyAllWindows()
    out.release()

def saving_error(path,error_l):

    with open(ERROR_DIRECTORY+"/"+path+"_errors_for_Frames.txt", "w") as text_file:

        for error in error_l:

            text_file.write(error+"\n")

def sorted_alphanumeric(data):

    """
    Sorts alphanumerically.
    :param data: data to be sorted e.g. a list
    :return: sorted data alphanumerically e.g. "User_2" before "User_10"
    """

    convert = lambda text: int(text) if text.isdigit() else text.lower()
    alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
    return sorted(data, key=alphanum_key)

def timer(starttime,lasttime):
    """
    Input: starttime = die Anfangszeit
           lasttime = die Endzeit
    Output: Differenz zwischen Start und Endzeit
            --> Berechnung der benötigten Zeit für den Durchlauf einer Funktion
    """
    totaltime = round((lasttime-starttime), 2)
    print("Total Time: "+str(totaltime))

    #return round((starttime-lasttime), 2)

def main():

    """
    Ideen:
        - Das Modell von Facemesh und Posedetection vllt nicht bei jedem Frame berechnen, weil es sonst in dem zusammengeschnitten Video so
          aussieht als würde es Zittern und es bewegt sich obwohl sich die Person nicht bewegt
          --> Zum andern müssen wir es für Jeden Frame berechnen, da man sonst vllt die Mikroexpressionen im Gesicht detectieren kann.
          --> Man benötigt eigentlich mindestens eine 140 HZ Kamera damit 140 Bilder pro Sekunde aufgenommen werden können
          --> Da Mikroexpressionen innerhalb von 40 bis 60 ms Stattfinden
          --> Für die Posedetection sind auch nur 25 Hz ausreichend
        - ausprobieren ob ich bei der CSV-Datei alles x in ein spalte und die y und z die die Spalten danach speichern kann

        - (Dynamisch Ordner erstellen für jedes Video damit darin alle Frames Gesepeichert werden)--> Nicht undbedingt nötig
          wegen der Benennung

    Probleme:
    - Kann das dritte Video den ersten Frame anscheinend nicht bearbeiten und wirft deswegen einen Error
    - Wenn es nichts auslesen kann wirft es einen error muss mit einen Try and Catch umgangen werden
    - Oder mann mnuss darauf achten das in jeden frame die pose oder das gesicht, die Hand erkennbar sind

    - Was bedeutet die Z-Dimension für jeden einzelnen Frame? Bilder sind normalerweise 2-Dimensional!
      --> Ist das vllt die Tiefe des Bildes bzw. der Kamerawinkel? -> So wird das Bild als ein Dreidimensionaler Raum aufgefasst.

    https://github.com/google/mediapipe/tree/master/mediapipe/python/solutions
    https://google.github.io/mediapipe/solutions/face_detection.html
    https://www.kaggle.com/code/brodielamont/test-opencv-video-and-mediapipe

    """

    if not os.listdir(DATA_DIRECTORY):
        print('No input video files are present. Please put your files in the '
              '"data" directory, rebuild the image and run the container.')

    for i, file in enumerate(sorted_alphanumeric(os.listdir(DATA_DIRECTORY))):

        # Die zwei steht für die Modell komplexität
        # Die Hundert steht für den Frame welcher geplotted werden soll, so wird jeder Hunderste frame geplotted
        # Kann manchmal nicht die pose erkennen und wirft dadurch ein Error (Attributerror)

        #starttime = time.time()
        #print(get_Data_pose(file,2,100,200))
        #lasttime = time.time()
        #timer(starttime,lasttime)

        # Zur auswahl eines bestimmten Videos
        #print(get_Data_pose('trial_truth_010.mp4',2,100,1000))

        # Die eins steht für die Maximale Anzahle an Faces
        # Die Zweihundert steht für den Frame welcher geplotted werden soll, so wird jeder Zweihunderste frame geplotted
        # Kann manchmal nicht das Gesicht erkennen und wirft dadurch ein Error (TypeErrorerror)

        #starttime = time.time()
        #print(get_Data_mesh(file,1,100,100))
        #lasttime = time.time()
        #timer(starttime,lasttime)

        # Zur auswahl eines bestimmten Videos
        #print(get_Data_mesh('trial_truth_010.mp4',2,100,1000))

        # Die eins steht für die Anzahl der model selectionen
        # Die Hundert steht für den Frame welcher geplotted werden soll, so wird jeder Hunderste frame geplotted
        # Funktionniert ohne probleme und ohne error

        #starttime = time.time()
        #print(get_Data_detection(file,1,100,100)[0])
        #lasttime = time.time()
        #timer(starttime,lasttime)

        # Zur auswahl eines bestimmten Videos
        #print(get_Data_detection('trial_truth_010.mp4',2,100,1000)[0])

        # Holistic kann Facemesh,pose und Handdetection gleichzeitig machen und hat alles in results drinne
        # funktioniert nur für Video 001 010 011,012,047,048,039
        # Gibt gewisse schwächen und erknnt auch nicht immer das Gesicht oder die pose deswegen musste ich einen try and catch bauen
        starttime = time.time()
        #print(get_Data_holistic(file,2,100,1000))
        lasttime = time.time()
        timer(starttime,lasttime)

        # Zur auswahl eines bestimmten Videos
        print(get_Data_holistic('trial_truth_001.mp4',2,100,1000))

DATA_DIRECTORY = 'Clips/Truthful'
FRAME_DIRECTORY = 'Frame_Data'
ERROR_DIRECTORY = 'Error_Data'
SAVING_DIRECTORY = 'Detected_Data'
SAVING_V_DIRECTORY = 'Detected_V_Data'
FRAME_PAINT_DIRECTORY = 'Frame_P_Data'

main()


class Solution:
    def minPathSum(self, grid):
        n, m = len(grid), len(grid[0])
        dp = [0] * m
        for j in range(m):
            if j == 0:
                dp[j] = grid[0][j]
            else:
                dp[j] = dp[j-1] + grid[0][j]
        for i in range(1, n):
            for j in range(m):
                if j == 0:
                    dp[j] += grid[i][j]
                else:
                    dp[j] = grid[i][j] + min(dp[j], dp[j-1])
        return dp[m-1]


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def widthOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
		# level order traversal, child = parent*2+(0,1)
        l, res = [(root,1)], 0
        while l:
            res, ll = max(res, l[-1][1]-l[0][1]+1), []
            for node, id in l:
                if node.left: ll += [(node.left, id*2)]
                if node.right: ll += [(node.right, id*2+1)]
            l = ll
        return res


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from itertools import *

def solve():
    K,L,S = map(int,input().split())
    keys = input()
    target = input()

    # targetを1つ並べられる確率
    p = 1.0
    for ch in target:
        p *= keys.count(ch) / len(keys)

    # 期待値の線形性を使う
    expect = (S - len(target) + 1) * p

    # slide := targetを重ねられる最小移動数
    slide = len(target)
    for i in range(1, len(target)):
        if target.startswith( target[i:] ):
            slide = i
            break
    # 最大に並べられる数
    mx = 1 + (S - len(target)) // slide

    # 期待値が0のときに気をつける
    if expect == 0:
        return 0
    else:
        return mx - expect

def main():
    T = int(input())
    for t in range(T):
        a = solve()
        print ("Case #{0}: {1:.10f}".format(t+1, a))
        #print ("Case #" + str(t+1) + ":", a)

main()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Karthik and Yashvanth
# @Date:   2016-01-02 19:30:08

'''
Module to handle arithmetic black box functions
'''

import shamir_sharing as ss
import numpy as np
import net_share as ns
import net_recv as nr
import mod_math_helpers as mmh
from random import randint
from libnum import jacobi
from math import log, floor

'''
 Function to simply negate a share
  @arg		: share of x, N
  @returns	: share of -x
'''
def neg(sh, N):
	return (sh[0], N-sh[1])

def add(self_pid, socket_list, addend_shares, N):
	'''
	add shares listed in addend_shares
	@arg		: self party id, list of sockets, list of shares to be added, prime base
	@returns 	: sum of shares
	'''

	num_parties = len(socket_list)
	sum_of_shares = sum([addend_share[1] for addend_share in addend_shares])%N

	return (self_pid, sum_of_shares)

def gen_vandermonde(n):
	'''
	generates an nxn vandermond matrix
	@arg		: number of parties
	@returns 	: nxn vandermonde matrix
	'''
	vandermonde = np.array([[i**(j-1) for j in range(1,n+1)] for i in range(1,n+1)])
	return vandermonde

def gen_coeff_arr(n, N):
	'''
	generates reduction array
	@arg		: number of parties, number of corrupted parites (max)
	@returns 	: degree reduction array
	'''
	B = gen_vandermonde(n)
	B_inv = mmh.find_inv_mat(B, N)
	return (np.array(B_inv[0])).flatten()

def mult(self_pid, socket_list, mult_shares, t, N, nB):
	'''
	multiply shares listed in mult_shares
	@arg		: self party id, list of party sockets, tuple of shares to be multiplied, prime base, share size
	@returns 	: product share
	'''
	n = len(socket_list)

	# generate self share
	x_self,y_self = mult_shares[0][1], mult_shares[1][1]
	prod = x_self * y_self % N
	z_self = (self_pid, prod)

	#randomisation step
	h_shares = ss.gen_shares(n, t, z_self[1], N)
	ns.distribute_secret(h_shares, socket_list, nB)
	h_recvd_shares = nr.recv_shares(socket_list, nB)
	h_recvd_shares[self_pid-1] = h_shares[self_pid-1]
	h_recvd_shares_vals = [i[1] for i in h_recvd_shares]

	h_recvd_vals = np.array(h_recvd_shares_vals)
	coeff_arr = gen_coeff_arr(n,N)

	self_mult_share = np.dot(h_recvd_vals, coeff_arr)

	return (self_pid, self_mult_share % N)

def rec_mult(self_pid, socket_list, mult_shares, t, N, nB ):
	'''
	calculate recursively the product of all shares in mult_shares
	@arg		: self party id, list of party sockets, list of shares to be multiplied, prime base,
				  share size
	@returns 	: share of product
	'''
	num_shares = len(mult_shares)
	if num_shares %2 == 0:
		if num_shares == 2:
			return mult(self_pid, socket_list, mult_shares, t, N, nB)
		else:
			k_1 = rec_mult(self_pid, socket_list, mult_shares[:num_shares/2], t, N, nB)
			k_2 = rec_mult(self_pid, socket_list, mult_shares[num_shares/2:], t, N, nB)
			return mult(self_pid, socket_list, (k_1, k_2), t, N, nB)
	else:
		k_1 = rec_mult(self_pid, socket_list, mult_shares[:-1], t, N, nB)
		k_2 = mult_shares[-1]
		return mult(self_pid, socket_list, (k_1, k_2), t, N, nB)

def test_equality_once(self_pid, socket_list, comp_shares, t, N, nB, act_parties):
	'''
	test equality of two shared secrets, can give false positives with probability 1/2
	@arg		: self party id, list of party sockets, tuple of shares to be compared, prime base,
				  share size, pids of contributing parties
	@returns 	: share of equality boolean x==y
	'''
	n = len(socket_list)
	x,y = comp_shares
	d = add(self_pid, socket_list, (x,neg(y,N)), N)[1]
	x,y = x[1], y[1]

	A,B = act_parties # index of contributing parties
	party_A = socket_list[A-1]
	party_B = socket_list[B-1]

	# obtain random input shares
	if self_pid in act_parties:
		r_i = randint(1,N-1)
		r_shares = ss.gen_shares(n, t, r_i, N)
		ns.distribute_secret(r_shares, socket_list, nB)
		r_a = r_shares[self_pid-1][1]
		party_other_pid = [i for i in act_parties if i!=self_pid][0]
		party_other = socket_list[party_other_pid-1]
		r_b = nr.recv_share(party_other, nB)
	else:
		r_a = nr.recv_share(party_A, nB)
		r_b = nr.recv_share(party_B, nB)

	r = mult(self_pid, socket_list, [(self_pid, r_a), (self_pid, r_b)], t, N, nB)[1]

	# obtain random input s
	if self_pid == B:
		s_val = randint(1,N-1)
		s_shares = ss.gen_shares(n, t, s_val, N)
		ns.distribute_secret(s_shares, socket_list, nB)
		s = s_shares[self_pid-1][1]

	else:
		s = nr.recv_share(party_B, nB)

	u = mult(self_pid, socket_list, ((self_pid, r), (self_pid, r)), t, N, nB)[1]
	u = add(self_pid, socket_list, ((None, d), (None, u)), N)[1]
	u = mult(self_pid, socket_list, ((self_pid, u), (self_pid, s)), t, N, nB)[1]

	# reconstruct t (A) and find jacobi of t and s
	if self_pid == A:
		u_shares_recvd = nr.recv_shares(socket_list, nB)
		u_shares_recvd[A-1] = (A,u)
		f = ss.interpolate_poly(u_shares_recvd, N)
		u_val = f(0)
		j_u_val = jacobi(int(u_val),N)

	else:
		nr.send_share([party_A], u, nB)

	if self_pid == B:
		j_s_val = jacobi(int(s_val), N)

	# share jacobi symbols
	if self_pid == A:
		j_u_shares = ss.gen_shares(n, t, j_u_val, N)
		ns.distribute_secret(j_u_shares, socket_list, nB)
		j_u = j_u_shares[self_pid-1][1]
		j_s = nr.recv_share(party_B, nB)

	elif self_pid == B:
		j_s_shares = ss.gen_shares(n, t, j_s_val, N)
		ns.distribute_secret(j_s_shares, socket_list, nB)
		j_s = j_s_shares[self_pid-1][1]
		j_u = nr.recv_share(party_A, nB)

	else:
		j_u = nr.recv_share(party_A, nB)
		j_s = nr.recv_share(party_B, nB)

	# calculate jacobi symbol of d+r^2
	j_fin = mult(self_pid, socket_list, ((self_pid, j_u), (self_pid, j_s)), t, N, nB)[1]
	j_tilde = add(self_pid, socket_list, ((None,j_fin), (None,1)), N)[1]

	fin_share = j_tilde * mmh.find_inv_mod(2, N) % N
	return (self_pid, fin_share)

def test_equality(self_pid, socket_list, comp_shares, t, N, nB, act_parties, iters):
	'''
	test equality repeatedly of two shared secrets to reduce probability of false positives, probabilty of false positives is 1/2^iters
	@arg		: self party id, list of party sockets, tuple of shares to be compared, prime base,
				  share size, pids of contributing parties, number of test_equality_once iterations
	@returns 	: share of equality boolean x==y
	'''
	eq_shares = []
	for x in xrange(iters):
		eq_shares.append(test_equality_once(self_pid, socket_list, comp_shares, t, N, nB, act_parties))

	final_share = rec_mult(self_pid, socket_list, eq_shares, t, N, nB)
	return final_share

'''
 Implementation of Toft's comparison protocol
  @arg		: self party id, list of party sockets, tuple of shares to be compared, prime base,
  		  share size, pids of Alice and Bob, l parameter
  @returns	: secret share of boolean output x > y
'''
def compare(self_pid, socket_list, comp_shares, t, N, nB, act_parties, l):
	x, y = comp_shares
	n = len(socket_list)
	# Check if comparing single bit values. If so, answer is trivial
	if l == 1:
		# `gt' encodes x > y
		xy = mult(self_pid, socket_list, comp_shares, t, N, nB)
		gt = add(self_pid, socket_list, [x, neg(xy, N)], N)
		# `eq' encodes x == y by calculating xy + (1-x)(1-y)
		neg_x = (self_pid, (1 - x[1]) % N)
		neg_y = (self_pid, (1 - y[1]) % N)
		eq = mult(self_pid, socket_list, (neg_x, neg_y), t, N, nB)
		eq = add(self_pid, socket_list, (eq, xy), N)
		# Return gt_eq = gt | eq , calculated as x+y-xy
		gt_eq = mult(self_pid, socket_list, (eq, gt), t, N, nB)
		gt_eq = add(self_pid, socket_list, [gt, eq, gt_eq], N)
		return gt_eq

	# Note here that like equality testing, the roles of the active
	# parties are not the same; the first is Alice, and the second is
	# Bob
	alice, bob = act_parties
	z = add(self_pid, socket_list, [(None,2**l), x, neg(y,N)], N)
	if self_pid == bob:
		# Choose random r
		r = randint(1,N-1)
		# Generate and distribute shares of this random number
		r_sh = ss.gen_shares(n, t, r, N)
		ns.distribute_secret(r_sh, socket_list, nB)
		# Calculate Bob's share of `c' and send it to Alice
		c = add(self_pid, socket_list, [r_sh[self_pid-1], z], N)[1]
		nr.send_share([socket_list[alice-1]], c, nB)
		c = (self_pid, c)
		# Find r_bar, r_bot and r_top and share them
		r_bar = r % (2**l)
		r_bar_sh = ss.gen_shares(n, t, r_bar, N)
		ns.distribute_secret(r_bar_sh, socket_list, nB)

		r_bot = r % (2**(l/2))
		r_bot_sh = ss.gen_shares(n, t, r_bot, N)
		ns.distribute_secret(r_bot_sh, socket_list, nB)

		r_top = floor(r / (2**(l/2))) % 2**(l/2)
		r_top_sh = ss.gen_shares(n, t, r_top, N)
		ns.distribute_secret(r_top_sh, socket_list, nB)

		# Receive shares of c_bar, _bot, _top
		c_bar = (self_pid, nr.recv_share(socket_list[alice-1], nB))
		c_bot = (self_pid, nr.recv_share(socket_list[alice-1], nB))
		c_top = (self_pid, nr.recv_share(socket_list[alice-1], nB))

		# Replace clear values of `r', bar, bot, top with shares
		# This is done for consistency of convention across parties
		r = r_sh[self_pid - 1]
		r_bar = r_bar_sh[self_pid - 1]
		r_bot = r_bot_sh[self_pid - 1]
		r_top = r_top_sh[self_pid - 1]

	elif self_pid == alice:
		# Receive share of `r' from Bob
		r = nr.recv_share(socket_list[bob-1], nB)
		# Calculate own share of `c'
		c_own = add(self_pid, socket_list, [z,(None,r)], N)[1]
		# Reconstruct `c'
		c = nr.reconstruct_secret_recv_only(socket_list, (self_pid, c_own), self_pid, nB, N)
		# Find c_bar, c_bot and c_top and share them
		c_bar = c % (2**l)
		c_bar_sh = ss.gen_shares(n, t, c_bar, N)
		ns.distribute_secret(c_bar_sh, socket_list, nB)

		c_bot = c % (2**(l/2))
		c_bot_sh = ss.gen_shares(n, t, c_bot, N)
		ns.distribute_secret(c_bot_sh, socket_list, nB)

		c_top = floor(c / (2**(l/2))) % 2**(l/2)
		c_top_sh = ss.gen_shares(n, t, c_top, N)
		ns.distribute_secret(c_top_sh, socket_list, nB)

		# Receive shares of r_bar, _bot, _top
		r_bar = (self_pid, nr.recv_share(socket_list[bob-1], nB))
		r_bot = (self_pid, nr.recv_share(socket_list[bob-1], nB))
		r_top = (self_pid, nr.recv_share(socket_list[bob-1], nB))

		# Replace clear values of `c', bar, bot, top with shares
		# This is done for consistency of convention across parties
		c = (self_pid, c_own)
		c_bar = c_bar_sh[self_pid - 1]
		c_bot = c_bot_sh[self_pid - 1]
		c_top = c_top_sh[self_pid - 1]

	else:
		# Receive share of `r' from Bob
		r = nr.recv_share(socket_list[bob-1], nB)
		# Calculate own share of `c' and send to Alice
		c = add(self_pid, socket_list, [z,(None,r)], N)[1]
		nr.send_share([socket_list[alice-1]], c, nB)
		# Receive shares of r_bar, _bot, _top
		r_bar = (self_pid, nr.recv_share(socket_list[bob-1], nB))
		r_bot = (self_pid, nr.recv_share(socket_list[bob-1], nB))
		r_top = (self_pid, nr.recv_share(socket_list[bob-1], nB))
		# Receive shares of c_bar, _bot, _top
		c_bar = (self_pid, nr.recv_share(socket_list[alice-1], nB))
		c_bot = (self_pid, nr.recv_share(socket_list[alice-1], nB))
		c_top = (self_pid, nr.recv_share(socket_list[alice-1], nB))

	# Common steps carried out by all parties

	# Check if r_top = c_top, store in boolean `b'
	b = test_equality(self_pid, socket_list, [r_top, c_top], t, N, nB, act_parties, 10)
	# Compute c_tilde = b ? c_bot:c_top
	c_tilde = add(self_pid, socket_list, [c_bot, neg(c_top, N)], N)
	c_tilde = mult(self_pid, socket_list, [c_tilde, b], t, N, nB)
	c_tilde = add(self_pid, socket_list, [c_tilde, c_top], N)
	# Compute r_tilde = b ? r_bot:r_top
	r_tilde = add(self_pid, socket_list, [r_bot, neg(r_top, N)], N)
	r_tilde = mult(self_pid, socket_list, [r_tilde, b], t, N, nB)
	r_tilde = add(self_pid, socket_list, [r_tilde, r_top], N)

	# Compute u = 1 - (c_tilde>=r_tilde) recursively
	u = (1 - compare(self_pid, socket_list, [c_tilde, r_tilde], t, N, nB, act_parties, l/2)[1]) % N

	# Last few steps, local
	z_bar = add(self_pid, socket_list, [c_bar, neg(r_bar, N), (None, (2**l)*u % N)], N)
	z_l = add(self_pid, socket_list, [z, neg(z_bar, N)], N)
	z_l = (z_l[0], z_l[1] * mmh.find_inv_mod(2**l, N) % N)

	return z_l

'''
 Function to check whether the secret shared value contains boolean semantic
 or not
  @arg		: party ID, list of sockets, share to be checked, t, modulus,
  		  size of share, active parties for comparison
  @returns	: secret shared boolean value
'''
def is_boolean(self_pid, socket_list, x, t, N, nB, act_parties):
	# Check if the given value is zero
	is_0 = test_equality(self_pid, socket_list, [x,(self_pid,0)], t, N, nB, act_parties, 10)
	# Check if the given value is one
	is_1 = test_equality(self_pid, socket_list, [x,(self_pid,1)], t, N, nB, act_parties, 10)
	# As is_0 and is_1 are exclusive, adding them will be at most 1
	# Their sum will be zero iff `x' is not boolean
	ans = add(self_pid, socket_list, [is_0, is_1], N)
	return ans


#!/usr/bin/env python
# coding: utf-8

# In[1]:

import pandas as pd
import numpy as np

# In[2]:

df=pd.read_excel("C:/Users/alekh/Downloads/Data_file.xlsx")
df.head()

# In[3]:

#let us find missing values
df.nunique()

# In[5]:

df.shape

# In[6]:

df.isnull().sum()

# In[7]:

#pre-processing
college_dummies=pd.get_dummies(df['College'])
college_dummies.drop('Tier 3',axis=1,inplace=True)
college_dummies.head()

# In[9]:

role_dummies=pd.get_dummies(df['Role'])
role_dummies.drop('Manager',axis=1,inplace=True)
role_dummies.head()

# In[11]:

city_dummies=pd.get_dummies(df['City type'])
city_dummies.drop('Metro',axis=1,inplace=True)
city_dummies.head()

# In[12]:

df.drop(['S.No.','College','Role','City type'],axis=1,inplace=True)
new_df=pd.concat([college_dummies,role_dummies,city_dummies,df],axis=1)
new_df.head()

# In[23]:

new_df.head()

# In[33]:

new_df.drop('Executive',axis=1,inplace=True)

# In[34]:

new_df.head()

# In[37]:

from sklearn import preprocessing
value=new_df.values
min_max_scalar=preprocessing.MinMaxScaler()
val_scaled=min_max_scalar.fit_transform(value)
normalize_df=pd.DataFrame(val_scaled)
normalize_df.columns=['College_T1','College_T2','City_non metro','previous job changes','Exp (Months)']
df.rename(columns={'CTC':'Actual CTC'},inplace=True)

# In[38]:

#Training of model
X=normalize_df
Y=df['Actual CTC']

# In[39]:

from sklearn.linear_model import LinearRegression
model=LinearRegression()

# In[40]:

model.fit(X,Y)

# In[52]:

#Testing
test_df=pd.read_excel("C:/Users/alekh/Downloads/Test_data_file.xlsx")
test_df.head()

# In[46]:

test_df.nunique()
test_df.head()

# In[48]:

test_df.shape

# In[53]:

test_df.isnull().sum()

# In[54]:

test_df=test_df.drop(['College','Role','City type','Predicted CTC'],axis='columns')
test_df.head()

# In[60]:

new_test_df=test_df.copy(deep=True)
new_test_df.drop('Actual CTC',axis=1,inplace=True)
new_test_df.drop(['Role_Manager','Graduation marks','previous CTC'],axis=1,inplace=True)
new_test_df.head()

# In[61]:

#Normalize the data
test_val=new_test_df.values
test_val_scaled=min_max_scaler.fit_transform(test_val)
test_normalize_df=pd.DataFrame(test_val_scaled)
test_normalize_df.columns=['College_T1','College_T2','City_non metro','previous job changes','Exp (Months)']
test_normalize_df.head()

# In[63]:

#evaluate the modal
X_test=test_normalize_df
Y_test=test_df['Actual CTC']
predict=model.predict(X_test)
prediction=predict.reshape(-1,1)
print(prediction)

# In[65]:

test_df['Actual CTC']

# In[69]:

#to calculate mean squared error to evalaute
from sklearn.metrics import mean_squared_error
print('MSE',mean_squared_error(Y_test,prediction))

# In[ ]:

# In[ ]:


'''
1069 집으로 - 기하
점프보다 거리가 짧은 경우 그냥 걸어가는 것, 넘어갔다가 걸어오는 것, 돌아서 점프해서 오는 것
거리가 긴 경우 그냥 걸어가는 것, 조금 돌아가는 것, 조금 남기고 걸어가는 것
이렇게 각각 세 가지 경우 중 가장 짧게 걸리는 방법을 선택하면 된다.
'''
import sys
input=sys.stdin.readline
x,y,d,t=map(int,input().split())
k=(x**2+y**2)**(1/2)
if k<d:
  ans=min(t+d-k,2*t,k)
else:
  ans=min((k//d+1)*t,k//d*t+k%d,k)
print(ans)


from django.conf.urls import *
from rest_framework import routers
from controle import views

routerLuminosidade = routers.DefaultRouter()
routerLuminosidade.register(r'luminosidade', views.LuminosidadeViewSet)

routerIrrigacao = routers.DefaultRouter()
routerIrrigacao.register(r'irrigacao', views.IrrigacaoViewSet)

routerTemperatura = routers.DefaultRouter()
routerTemperatura.register(r'temperatura', views.TemperaturaViewSet)

urlpatterns = [
    url(r'^luminosidade_api/', include(routerLuminosidade.urls)),
    url(r'^irrigacao_api/', include(routerIrrigacao.urls)),
    url(r'^temperatura_api/', include(routerTemperatura.urls)),
]


from nornir import InitNornir
from nornir_utils.plugins.functions import print_result
from nornir_junos.tasks.junos_get import junos_get
from nornir.core.plugins.connections import ConnectionPluginRegister
from nornir_junos.connections import nornir_junos
ConnectionPluginRegister.register("nornir_junos", nornir_junos)
nr = InitNornir(
    runner={
        "plugin": "threaded",
        "options": {
            "num_workers": 100,
        },
    },
    inventory={
        "plugin": "SimpleInventory",
        "options": {
            "host_file": "inventory/hosts.yaml"
        },
    },
)

results = nr.run(
    task=junos_get, commands=["show system uptime"]
)
print_result(results)


#!/usr/bin/env python

"""livecharting.py: provides interface to display charts in real-time."""

import numpy as np
import time
import matplotlib
import threading

# Use backend that works with Mac OS
# matplotlib.use('TkAgg')
matplotlib.use('GTKAgg')

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.animation import FuncAnimation

plt.style.use(['dark_background'])

# Animation parameters
min_speed = 0.1
max_speed = 1.0

class LiveCharting(object):
    def __init__(self,
                 n_curves,
                 ymin,
                 ymax,
                 x_resolution=100,
                 ylabel=None,
                 data_labels=None,
                 xlabel='time'):
        # Setting up figure
        self.fig = plt.figure(figsize=(10, 5))
        self.ax = self.fig.add_subplot(111)
        self.ax.set_ylim(ymin, ymax)
        if ylabel is not None:
            self.ax.set_ylabel(ylabel)

        self.ax.set_xlabel(xlabel)

        self.X = np.linspace(-6, 0, x_resolution)
        self.YS = [np.zeros_like(self.X) for i in xrange(n_curves)]

        # Plot curves
        if data_labels is not None:
            self.plots = [self.ax.plot(self.X, Y, linewidth=2, label=lbl)
                          for lbl, Y in zip(data_labels, self.YS)]
            self.ax.legend(loc=2)
        else:
            self.plots = [self.ax.plot(self.X, Y, linewidth=2) for Y in self.YS]

        self.animation = FuncAnimation(self.fig,
                                       self.update,
                                       interval=10)

    def set_current_value(self, index, value):
        self.YS[index][:-1] = self.YS[index][1:]
        self.YS[index][-1] = value

    def update(self, num):
        for ((p,), Y) in zip(self.plots, self.YS):
            p.set_data(self.X, Y)


from flask import Flask
from AlphaBot2 import AlphaBot2
from flask import request
from lib.servo.servo import Servo
from werkzeug.contrib.cache import SimpleCache

cache = SimpleCache()

app = Flask(__name__)

Ab = AlphaBot2()
s = Servo()

@app.route("/forward/")
def forward():
    Ab.forward()
    return "forward!"

@app.route("/backward/")
def backward():
    Ab.backward()
    return "backward!"

@app.route("/stop/")
def stop():
    Ab.stop()
    return "stop!"

@app.route("/left/")
def left():
    Ab.left()
    return "left!"

@app.route("/right/")
def right():
    Ab.right()
    return "right!"

@app.route("/servo/leftright/")
def servo_leftright():
    handle_request(request, 0)
    return "servoleftright!"

@app.route("/servo/updown/")
def servo_updown():
    handle_request(request, 1)
    return "servoupdown!"

def handle_request(request, mode_id):
    position = int(request.args.get("position"))
    speed = int(request.args.get("speed"))
    defaults = s.leftright_range
    key = "leftright"
    if (mode_id == 1):
        key = "updown"
        defaults = s.updown_range

    current = cache.get(key)
    if (current is None):
        current = defaults[1]
    result = s.run_servo(current, position, speed, mode_id, defaults)
    cache.set(key, result)

@app.route("/servo/center/")
def servoCenter():
    current_updown = cache.get("updown")
    current_left_right = cache.get("leftright")
    if (current_left_right is None):
        current_left_right = s.leftright_range[0]
    if (current_updown is None):
        current_updown = s.leftright_range[1]
    s.center(current_left_right, current_updown)
    cache.set("leftright", 1500)
    cache.set("updown", 2600)
    return "servoupdown!"

@app.route("/setWheelSpeed/", methods=["POST"])
def setWheelSpeed():
    left = float(request.get_json()['leftWheelSpeed'])
    right = float(request.get_json()['rightWheelSpeed'])
    maximum = float(50)
    # Ab.setMotor(left, right)
    if (left < 0 and right < 0):
        left = -left
        right = -right
        Ab.backward()
    else:
        Ab.forward()
    print((maximum * (left / 100)))
    Ab.setPWMA(maximum * (left / 100))
    Ab.setPWMB(maximum * (right / 100))
    return "servoupdown!"

@app.route("/setWheelSpeedArg/")
def setWheelSpeedArg():
    left = float(request.args.get('leftWheelSpeed'))
    right = float(request.args.get('rightWheelSpeed'))
    maximum = float(50)
    # Ab.setMotor(left, right)
    if (left < 0 and right < 0):
        left = -left
        right = -right
        Ab.backward()
    else:
        Ab.forward()
    print((maximum * (left / 100)))
    Ab.setPWMA(maximum * (left / 100))
    Ab.setPWMB(maximum * (right / 100))
    return "servoupdown!"

if __name__ == '__main__':
    app.run(host="0.0.0.0", debug=True)


#!/usr/bin/python

import sys
import pickle
import json
import numpy as np
import time
sys.path.append("../tools/")

from feature_format import featureFormat, targetFeatureSplit
from tester import dump_classifier_and_data, test_classifier

from sklearn.pipeline import Pipeline

from sklearn.preprocessing import MaxAbsScaler

from sklearn.decomposition import PCA
from sklearn.feature_selection import SelectKBest

from sklearn.model_selection import GridSearchCV

from sklearn.naive_bayes import GaussianNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neighbors import NearestCentroid

from sklearn.cross_validation import StratifiedShuffleSplit

import warnings

# suppress warnings
warnings.filterwarnings('ignore')

# There was one user (EUGENE) with no data
def find_users_with_no_data(scan_data):
    no_data_users = []
    for ppl, features in scan_data.items():
        non_NaN = False
        for feature, value in features.items():
            if feature != 'poi':
                if value != 'NaN':
                    non_NaN = True
                    break

        if not non_NaN:
            no_data_users.append(ppl)

    return no_data_users

# There are no features with NaN set as the value for every user
def find_features_with_no_data(scan_data, feature_list):
    no_data_features = []
    for feature in feature_list:
        non_NaN = False
        for ppl, features in scan_data.items():
            try:
                if features[feature] != 'NaN':
                    non_NaN = True
                    break
            except KeyError:
                pass

        if not non_NaN:
            no_data_features.append(feature)

    return no_data_features

# Simple function to print out all the data from the data_dict
def display_values(data):
    # fields_of_interest = ['poi', 'deferral_payments', 'restricted_stock_deferred', 'total_stock_value', 'restricted_stock']
    fields_of_interest = ['restricted_stock_deferred']
    # persons_of_interest = ['BELFER ROBERT','BHATNAGAR SANJAY']
    persons_of_interest = []
    if len(persons_of_interest) > 0:
        for person in persons_of_interest:
            print(person, json.dumps(data[person], indent=4))
    else:
        for person, values in data.items():
            poi = data[person]['poi']
            for key, value in values.items():
                if key in fields_of_interest and value != 'NaN':
                    print(person, poi, key, value)

# Function to correct the entries in the data dictionary that were incorrectly set originally
def correct_invalid_values(data_to_correct):
    # There are some data input errors for BELFER ROBERT and BHATNAGAR SANJAY
    # This function corrects those errors back to their original state as per the provided PDF
    empty_value = 'NaN'

    data_to_correct['BELFER ROBERT']['deferred_income'] = -102500
    data_to_correct['BELFER ROBERT']['deferral_payments'] = empty_value
    data_to_correct['BELFER ROBERT']['expenses'] = 3285
    data_to_correct['BELFER ROBERT']['director_fees'] = 102500
    data_to_correct['BELFER ROBERT']['total_payments'] = 3285
    data_to_correct['BELFER ROBERT']['exercised_stock_options'] = empty_value
    data_to_correct['BELFER ROBERT']['restricted_stock'] = 44093
    data_to_correct['BELFER ROBERT']['restricted_stock_deferred'] = -44093
    data_to_correct['BELFER ROBERT']['total_stock_value'] = empty_value

    data_to_correct['BHATNAGAR SANJAY']['other'] = empty_value
    data_to_correct['BHATNAGAR SANJAY']['expenses'] = 137864
    data_to_correct['BHATNAGAR SANJAY']['director_fees'] = empty_value
    data_to_correct['BHATNAGAR SANJAY']['total_payments'] = 137864
    data_to_correct['BHATNAGAR SANJAY']['exercised_stock_options'] = 15456290
    data_to_correct['BHATNAGAR SANJAY']['restricted_stock'] = 2604490
    data_to_correct['BHATNAGAR SANJAY']['restricted_stock_deferred'] = -2604490
    data_to_correct['BHATNAGAR SANJAY']['total_stock_value'] = 15456290

    return data_to_correct

# Simple function to count how many non-zero values there are for each feature
def count_zeros_and_non_zeros(column):
    zeros = 0
    non_zeros = 0
    for entry in column:
        if entry == 0:
            zeros += 1
        else:
            non_zeros += 1

    return zeros, non_zeros

# Create some new features that show the % of emails sent and received by each individual to/from POIs
# These numbers may be more predictive than just absolute numbers as all individuals send different amounts of email
def create_new_features(existing_data):
    for person, features in existing_data.items():
        existing_data[person]['from_poi_pct'] = create_pct(features['from_poi_to_this_person'], features['to_messages'])
        existing_data[person]['to_poi_pct'] = create_pct(features['from_this_person_to_poi'], features['from_messages'])

    return existing_data

# Function to turn a number into a percent of a total value; used for feature engineering
def create_pct(partial, total):
    # Make sure the data is not NaN (if so return 0)
    if partial == 'NaN':
        partial = 0
    if total == 'NaN':
        return 0

    # If neither value is NAN, then return a percentage as a float value
    return (float(partial) / float(total)) * 100.

# Simple function to break the features and labels out of the original data dictionary
def split_features_from_labels(raw_data, target_features):
    new_data = featureFormat(raw_data, target_features, sort_keys=True)
    return targetFeatureSplit(new_data)

# Use the feature and labels data to try all possible combinations of parameters
# Return the best estimator (if it is performing above the baseline, and better than previous entries
# Otherwise return the previous estimator and score
def find_best_estimator_for_grid(classifier, pipe, params, data_set, feature_list, previous_score, previous_estimator):
    print('')
    print('-------------------------------------')
    print('--------- {classifier}'.format(classifier=classifier))
    print('-------------------------------------')
    print('')

    start = time.time()
    print('Started at {time}'.format(time=time.strftime("%H:%M:%S")))
    print('')

    np.random.seed(0)

    labels, features = split_features_from_labels(data_set, feature_list)

    cv = StratifiedShuffleSplit(labels, random_state=42)

    grid = GridSearchCV(pipe, param_grid=params, cv=cv, scoring='f1', n_jobs=1, verbose=1)
    grid.fit(features, labels)

    best_estimator = grid.best_estimator_

    # modified tester returns the scores for comparison purposes
    precision, recall, f1 = test_classifier(grid.best_estimator_, data_set, feature_list)
    if grid.best_params_.get('reduce_dim__k'):
        print('{x} features selected by SelectKBest'.format(x=grid.best_params_['reduce_dim__k']))
        for idx, feature in enumerate(feature_list[1:]):
            print(
                feature,
                grid.best_params_['reduce_dim'].scores_[idx],
                grid.best_params_['reduce_dim'].get_support()[idx]
            )
    else:
        print('PCA used for dim reduction; no features reportable.')

    # return the previous score and estimator if this is not better
    new_score = previous_score
    new_estimator = previous_estimator

    if precision >= 0.3 and recall >= 0.3 and f1 > previous_score:
        new_score = f1
        new_estimator = best_estimator

    print('-------------------------------------')
    end = time.time()
    log_time_to_complete(classifier, start, end)

    return new_estimator, new_score

# Simple logger to track how long each classifier is taking to analyze
def log_time_to_complete(classifier, start_time, end_time):
    print('Took {time} seconds, to find best {classifier}'.format(classifier=classifier, time=end_time-start_time))

# Pulling in all features, will select best features automatically in pipeline (either PCA or SelectKBest)
features_list = [
    'poi',
    'salary', 'to_messages', 'deferral_payments', 'loan_advances', 'bonus', 'restricted_stock_deferred',
    'deferred_income', 'total_stock_value', 'expenses', 'from_poi_to_this_person', 'exercised_stock_options',
    'from_messages', 'other','from_this_person_to_poi', 'long_term_incentive', 'shared_receipt_with_poi',
    'restricted_stock', 'director_fees'
]

# Load the dictionary containing the dataset
with open("final_project_dataset.pkl", "rb") as data_file:
    data_dict = pickle.load(data_file)

####
# Previous validation checks done to fix data
# outlier exists for "TOTAL" row of data
####

# print(sorted(data_dict))
# print(find_users_with_no_data(data_dict))
# print(find_features_with_no_data(data_dict, features_list[1:]))

####
# Remove the invalid outliers completely
####
outliers = ['TOTAL', 'LOCKHART EUGENE E', 'THE TRAVEL AGENCY IN THE PARK']
for outlier in outliers:
    data_dict.pop(outlier, 0)

####
# Fix the erroneous data for 2 entries
####
# display_values(data_dict)
data_dict = correct_invalid_values(data_dict)

# Task 3: Create new feature(s)
data_dict = create_new_features(data_dict)

# Store to my_dataset for easy export below.
my_dataset = data_dict

# Extract features and labels from dataset for local testing
labels, features = split_features_from_labels(my_dataset, features_list)
best_estimator = None
best_score = 0.

# Hyperparameter tuning tests
# General parameters (all classifiers)
n_features = range(2, 19)
scalers = [None, MaxAbsScaler()]

# KNearestNeighbor parameters
n_neighbours = [1, 3, 5, 7, 9, 10, 15, 20, 50]
n_neighbor_weights = ['uniform','distance']
n_neighbor_p = [1, 2]

# Centroid parameters
centroid_distances = ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', 'manhattan']
centroid_shrink = [None, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# DecisionTree parameters
tree_criterion = ['entropy', 'gini']
tree_splitter = ['random', 'best']
tree_min_splits = range(2, 20, 2)
tree_max_features = ['sqrt', 'log2', None]

# RandomForest parameters
forest_estimators = [5, 10, 15, 20, 25]

# AdaBoost parameters
boost_estimators = [25, 50, 75, 100, 500]

####
# Now try each different type of classifier to see how they perform independently
# Try out Gaussian NB
####
pipe = Pipeline([
    ('scale', MaxAbsScaler()),
    ('reduce_dim', PCA(random_state=42)),
    ('clf', GaussianNB())
])
param_grid = [
    {
        'scale': scalers,
        'reduce_dim': [PCA(random_state=42)],
        'reduce_dim__n_components': n_features
    },
    {
        'scale': scalers,
        'reduce_dim': [SelectKBest()],
        'reduce_dim__k': n_features
    }
]

best_estimator, best_score = find_best_estimator_for_grid('GaussianNB', pipe, param_grid, my_dataset, features_list, best_score, best_estimator)

####
# Now try KNearestNeighbors
####
pipe = Pipeline([
    ('scale', MaxAbsScaler()),
    ('reduce_dim', PCA(random_state=42)),
    ('clf', KNeighborsClassifier())
])
param_grid = [
    {
        'scale': scalers,
        'reduce_dim': [PCA(random_state=42)],
        'reduce_dim__n_components': n_features,
        'clf__n_neighbors': n_neighbours,
        'clf__weights': n_neighbor_weights,
        'clf__p': n_neighbor_p
    },
    {
        'scale': scalers,
        'reduce_dim': [SelectKBest()],
        'reduce_dim__k': n_features,
        'clf__n_neighbors': n_neighbours,
        'clf__weights': n_neighbor_weights,
        'clf__p': n_neighbor_p
    }
]

best_estimator, best_score = find_best_estimator_for_grid('KNearestNeighbors', pipe, param_grid, my_dataset, features_list, best_score, best_estimator)

####
#  Now try NearestCentroid
####
pipe = Pipeline([
    ('scale', MaxAbsScaler()),
    ('reduce_dim', PCA(random_state=42)),
    ('clf', NearestCentroid())
])
param_grid = [
    {
        'scale': scalers,
        'reduce_dim': [PCA(random_state=42)],
        'reduce_dim__n_components': n_features,
        'clf__metric': centroid_distances,
        'clf__shrink_threshold': centroid_shrink
    },
    {
        'scale': scalers,
        'reduce_dim': [SelectKBest()],
        'reduce_dim__k': n_features,
        'clf__metric': centroid_distances,
        'clf__shrink_threshold': centroid_shrink
    }
]

best_estimator, best_score = find_best_estimator_for_grid('NearestCentroid', pipe, param_grid, my_dataset, features_list, best_score, best_estimator)

####
#  Now try DecisionTree
####
pipe = Pipeline([
    ('reduce_dim', PCA(random_state=42)),
    ('clf', DecisionTreeClassifier(random_state=42))
])
param_grid = [
    {
        'reduce_dim': [PCA(random_state=42)],
        'reduce_dim__n_components': n_features,
        'clf__criterion': tree_criterion,
        'clf__max_features': tree_max_features,
        'clf__splitter': tree_splitter,
        'clf__min_samples_split': tree_min_splits
    },
    {
        'reduce_dim': [SelectKBest()],
        'reduce_dim__k': n_features,
        'clf__criterion': tree_criterion,
        'clf__max_features': tree_max_features,
        'clf__splitter': tree_splitter,
        'clf__min_samples_split': tree_min_splits
    }
]

best_estimator, best_score = find_best_estimator_for_grid('DecisionTree', pipe, param_grid, my_dataset, features_list, best_score, best_estimator)

####
#  Now try RandomForest
####
pipe = Pipeline([
    ('reduce_dim', PCA(random_state=42)),
    ('clf', RandomForestClassifier(random_state=42))
])
param_grid = [
    {
        'reduce_dim': [PCA(random_state=42)],
        'reduce_dim__n_components': n_features,
        'clf__n_estimators': forest_estimators,
        'clf__max_features': tree_max_features,
        'clf__min_samples_split': tree_min_splits
    },
    {
        'reduce_dim': [SelectKBest()],
        'reduce_dim__k': n_features,
        'clf__n_estimators': forest_estimators,
        'clf__max_features': tree_max_features,
        'clf__min_samples_split': tree_min_splits
    }
]

# best_estimator, best_score = find_best_estimator_for_grid('RandomForest', pipe, param_grid, my_dataset, features_list, best_score, best_estimator)

####
#  Now try AdaBoost
####
pipe = Pipeline([
    ('reduce_dim', PCA(random_state=42)),
    ('clf', AdaBoostClassifier(random_state=42))
])
param_grid = [
    {
        'reduce_dim': [PCA(random_state=42)],
        'reduce_dim__n_components': n_features,
        'clf__n_estimators': boost_estimators
    },
    {
        'reduce_dim': [SelectKBest()],
        'reduce_dim__k': n_features,
        'clf__n_estimators': boost_estimators
    }
]

# best_estimator, best_score = find_best_estimator_for_grid('AdaBoost', pipe, param_grid, my_dataset, features_list, best_score, best_estimator)

####
# Write out the details of the absolutely best estimator and the score received (f1 value)
####
print(best_score, best_estimator)

####
# Now that we know what classifier is most effective, persist it to disk for testing
####
dump_classifier_and_data(best_estimator, my_dataset, features_list)


import asyncio
from tmdb_api import TmdbApi
import os

async def main():
    api = TmdbApi(os.environ["API_KEY"])

    movie_ids = [500, 234, 600]

    movies = await asyncio.gather(*map(api.movie, movie_ids))

    for i, movie in enumerate(movies):
        print(f"{i+1:2} | {movie['title']:30} ({movie['tagline']})")

if __name__ == "__main__":
    # avoids windows specific issue, see https://stackoverflow.com/a/66772242
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

    asyncio.run(main())


import customtkinter as Ctk
from tkinter import *

Ctk.set_appearance_mode('white')
Ctk.set_default_color_theme('white')

janela=Ctk.Ctk()

janela.geometry('1000x700')

janela.title('Jogo da Forca')

def jogar_forca():
    palavra_secreta = input("Digite a palavra secreta: ").upper()
    letras_certas = []
    letras_erradas = []
    tentativas = 6

    while True:
        for letra in palavra_secreta:
            if letra in letras_certas:
                print(letra, end=" ")
            else:
                print("_", end=" ")
        print("\n")

        if len(letras_erradas) > 0:
            print("Letras erradas:", " ".join(letras_erradas))

        letra_palpite = input("Digite uma letra: ").upper()

        if letra_palpite in palavra_secreta:
            letras_certas.append(letra_palpite)
        else:
            letras_erradas.append(letra_palpite)
            tentativas -= 1

        if tentativas == 0:
            print("Você perdeu! A palavra secreta era:", palavra_secreta)
            break

        if all(letra in letras_certas for letra in palavra_secreta):
            print("Parabéns! Você venceu!")
            break

jogar_forca()

FORCA - HANGMAN/Jogo da forca - Hangman game.py


# Я не понял задание, какое-то оно слишком хардкорное,
#   мне следует просто потренироваться писать в файл?..

from common import gen_list

numbers_count = int(input('Введите количество произвольных чисел в списке: '))
print('in')
print(numbers_count)

lst = gen_list(numbers_count)

for el in lst:
    with open('task4.txt', 'a') as file:
        file.write("{}\n".format(el))


import argparse
import os
import multiprocessing
import glob
from functools import partial

def parse_args():
    parser = argparse.ArgumentParser(description='')

    requiredArgs = parser.add_argument_group("Required Arguments")

    requiredArgs.add_argument('-f', '--fas_tafile',
                               dest='faa_file',
                               required=True,
                               help='directory with the .faa proteins files'
                               )
    requiredArgs.add_argument('-hmms', '--hmms_folder',
                               dest='hmms_folder',
                               required=True,
                               help='hmm db built with hmmpress'
                               )

    requiredArgs.add_argument('-o', '--output_dir',
                               dest='out_dir',
                               required=True,
                               help=''
                               )

    return parser.parse_args()

def run_hmmsearch(faa_file, outdir, hmm_db):
    hmm_id   = os.path.basename(hmm_db).split(".hmm")[0]
    faa_id   = os.path.basename(faa_file).split(".faa")[0]
    #outfile   = f"{os.path.abspath(outdir)}/{file_id}.out"
    tblout    = f"{os.path.abspath(outdir)}/{faa_id}-{hmm_id}.tblout"
    domtblout = f"{os.path.abspath(outdir)}/{faa_id}-{hmm_id}.domtblout"

    os.system(f"time hmmsearch --noali --tblout {tblout} --domtblout {domtblout} --cpu 1 {hmm_db} {faa_file} > /dev/null")
    print(f"{hmm_id} completed")

def main():

    args = parse_args()

    # get all hmms to scan
    hmms = glob.glob(f"{args.hmms_folder}/*.hmm")

    # def partial function
    partial_func = partial(run_hmmsearch, args.faa_file, args.out_dir)

    # parallel
    pool = multiprocessing.Pool(processes=40)
    pool.map(partial_func, hmms)
    pool.close()
    pool.join()

if __name__ == "__main__":
    main()


#!/usr/bin/env python

import os

os.system("apt-get install figlet")

os.system("clear")

os.system("figlet ZAAFIYET ANALIZI")

print("""

Zaafiyet Analizi Aracina Hosgeldiniz

""")

hedefip = raw_input("Hedef Ip Girin")

os.system("nikto -h " + hedefip)