from flask import Flask, request, jsonify
import datetime
import os

app = Flask(__name__)

# Global variable to store the start time
start_time = None

def get_start_time():
    global start_time
    if start_time is None:
        # Check if the start time is stored in a file or a database
        # If the file doesn't exist or database is empty, set the start time to the current time
        # For simplicity, I'll just set the start time to the current time
        start_time = datetime.datetime.now()
    return start_time

@app.route('/api/welcome', methods=['POST'])
def welcome_python_app():
    data = request.json
    user_input = data.get('user_input', '').lower()

    if user_input == 'hello':
        current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        reply = f'Welcome to the Python app! The app is active from last {calculate_time_since_start()}'
        return jsonify({'reply': reply})
    else:
        return jsonify({'reply': 'Unknown input'})

def calculate_time_since_start():
    current_time = datetime.datetime.now()
    duration = current_time - get_start_time()
    total_seconds = int(duration.total_seconds())

    minutes, seconds = divmod(total_seconds, 60)
    hours, minutes = divmod(minutes, 60)

    if hours > 0 and minutes > 0:
        return f'{hours} hours and {minutes} minutes.'
    elif hours > 0:
        return f'{hours} hours.'
    elif minutes > 0:
        return f'{minutes} minutes.'
    else:
        return 'less than a minute.'

@app.route('/', methods=['POST'])
def welcome_react_app():
    data = request.json
    user_input = data.get('user_input', '').lower()

    if user_input == 'hello':
        current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        reply = f'Welcome to the React app! The app is active from last {calculate_time_since_start()}'
        return jsonify({'reply': reply})
    else:
        return jsonify({'reply': 'Unknown input'})

if __name__ == '__main__':
    # On application start, get the start time
    start_time = get_start_time()
    app.run()


arr=input().replace("[","").replace("]","").split(",")
carr=arr.copy()
arr.sort()
start=0
count=0
for i in range(len(arr)):
    end=i+1
    new=carr[start:end]
    new.sort()
    if(new==arr[start:end]):
        count=count+1
        start=i+1
print(count)


#!/usr/bin/env python
import argparse, random

parser = argparse.ArgumentParser()
parser.add_argument("-n", type=int, help="number of words to print, default=6", default=6)
args = parser.parse_args()

r = random.SystemRandom()
with open('eff_large_wordlist.txt') as f:
    lines = list(f)
    print(' '.join(r.choice(lines).split()[1] for i in range(args.n)))


# Make sure to have the server side running in CoppeliaSim:
# in a child script of a CoppeliaSim scene, add following command
# to be executed just once, at simulation start:
#
# simRemoteApi.start(19999)
#
# then start simulation, and run this program.
#
# IMPORTANT: for each successful call to simxStart, there
# should be a corresponding call to simxFinish at the end!

try:
    import sim
except:
    print('--------------------------------------------------------------')
    print('"sim.py" could not be imported. This means very probably that')
    print('either "sim.py" or the remoteApi library could not be found.')
    print('Make sure both are in the same folder as this file,')
    print('or appropriately adjust the file "sim.py"')
    print('--------------------------------------------------------------')
    print('')

import time
import math
import sys
import numpy as np

from zmqRemoteApi import RemoteAPIClient

print('Program started')
sim.simxFinish(-1)  # just in case, close all opened connections
clientID = sim.simxStart('127.0.0.1', 19999, True, True, 5000, 5)  # Connect to CoppeliaSim

client = RemoteAPIClient()
sim_ = client.getObject('sim')

if clientID != -1:
    print('Connected to remote API server\n')
    time.sleep(0.02)
    err, dummy = sim.simxGetObjectHandle(clientID, 'Dummy', sim.simx_opmode_oneshot_wait)
    err, floor = sim.simxGetObjectHandle(clientID, 'Floor', sim.simx_opmode_oneshot_wait)

    # Criando stream de dados
    err, position_dummy = sim.simxGetObjectPosition(clientID, dummy, floor, sim.simx_opmode_streaming)
    err, orientation_dummy = sim.simxGetObjectOrientation(clientID, dummy, floor, sim.simx_opmode_streaming)

    time.sleep(5)

    err, position_dummy = sim.simxGetObjectPosition(clientID, dummy, floor, sim.simx_opmode_buffer)
    err, orientation_dummy = sim.simxGetObjectOrientation(clientID, dummy, floor, sim.simx_opmode_buffer)

    orientation_dummy_degree = [d * (180 / math.pi) for d in orientation_dummy]
    print(f"Position Dummy: {position_dummy}\n")
    print(f"Orientation Dummy: {orientation_dummy_degree}\n")

    matrix_transformation = sim_.getObjectMatrix(dummy, floor)
    matrix_transformation_formatted = np.array(matrix_transformation).reshape((3, 4))

    print(f"Transformation Matrix: \n{matrix_transformation_formatted}\n")

    sim.simxGetPingTime(clientID)

    sim.simxFinish(clientID)
else:
    print('Failed connecting to remote API server')
print('Program ended')


"""
__author__ = "Hager Rady and Mo'men AbdelRazek"

Main
-Capture the config file
-Process the json config passed
-Create an agent instance
-Run the agent
"""

import argparse
from utils.config import *

from agents import *

def main():
    # parse the path of the json config file
    arg_parser = argparse.ArgumentParser(description="")
    arg_parser.add_argument(
        'config',
        metavar='config_json_file',
        default='None',
        help='The Configuration file in json format')
    args = arg_parser.parse_args()

    # parse the config json file
    config = process_config(args.config)

    # Create the Agent and pass all the configuration to it then run it..
    agent_class = globals()[config.agent]
    agent = agent_class(config)
    agent.run()
    agent.finalize()

if __name__ == '__main__':
    main()


from django.shortcuts import render, redirect
from . models import *
from .forms import PostForm
# Create your views here.

def index(request):
    all_posts = Post.objects.all()
    context = {
        'all_posts':all_posts
    }
    return render(request, 'pages/index.html', context)

def createPost(request):
    form = PostForm()
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('indexPage')
    context = {
        'form':form,
        }
    return render(request, 'post/create.html', context)

def detailPost(request, pk):
    post = Post.objects.get(id=pk)
    form = PostForm()
    context = {
        'post':post,
        'form':form
    }
    return render(request, 'post/detail.html', context )


def prime(n):
    if n<2:
        return False
    for i in range(2,n):
        if n%i==0:
            return False
    return True
def pnd(n):
    n=str(n)
    if n==n[::-1]:
        return True
    return False
a=int(input())
b=a+1
while True:
    if prime(b) and pnd(b):
        print(b)
        break
    b+=1


from post_office.models import Email

from tenancy.test.cases import TenantsTestCase
from ..models import Notification

class NotificationsModelTestCase(TenantsTestCase):
    auto_create_schema = True

    @classmethod
    def setUpClass(cls) -> None:
        super().setUpClass()
        cls.user = cls.create_superuser('first', 'test@one.com', 'p',
                                        first_name='Pretty', last_name='Smart',
                                        tenant=0)

    @classmethod
    def tearDownClass(cls) -> None:
        cls.set_tenant(0)
        cls.user.delete()
        super().tearDownClass()

    def test_email_backend_notice_send(self) -> None:
        self.set_tenant(0)

        extra_context = dict(
            contact_link='http://localhost.localdomain/contacts/321',
            contact_name='Billy',
            company_name="Treasure hunters", phone_number='+1324567890',
            campaign_link='http://localhost.localdomain/campaigns/123', campaign_title='Where is the map?', )
        Notification.send(self.user, 'email_link_clicked', extra_context)

        emails = Email.objects.all()

        self.assertEqual(1, len(emails))
        email = emails[0]
        self.assertListEqual([self.user.email], email.to)
        html_message = email.html_message
        skipped_keys = [k for k, v in extra_context.items() if v not in html_message]

        self.assertFalse(skipped_keys, 'Message does not contain: %s' % ', '.join(skipped_keys))


import numpy as np
import matplotlib.pyplot as plt
from grid_world import standard_grid

SMALL_ENOUGH = 10e-4

def print_values(V, g):
    for i in range(g.rows):
        print("-" * 20)
        for j in range(g.cols):
            v = V.get((i, j), 0)
            if v >= 0:
                print(" %.2f|" %v, end = "")
            else:
                print("%.2f|" %v, end="")
        print("")
    print("\n")

def print_policy(P, g):
    for i in range(g.rows):
        print("-" * 20)
        for j in range(g.cols):
            p = P.get((i, j), ' ')
            print(" %s |" %p, end = "")
        print("")
    print("\n")

if __name__=="__main__":
    grid = standard_grid()
    states = grid.all_state()

    # random actions
    V={}
    for s in states:
        V[s] = 0
    gamma = 1 # discount factor

    while True:
        for s in states:
            delta = 0
            old_Vs = V[s]
            if s in grid.actions:
                new_Vs = 0
                best = float('-inf')
                pa_s = 1.0/len(grid.actions[s])
                for a in grid.actions[s]:
                    grid.set_state(s)
                    r = grid.move(a)
                    new_Vs += pa_s * (r + gamma * V[grid.current_state()])
                V[s] = new_Vs
                delta = max(delta, np.abs(old_Vs - V[s]))
        if delta < SMALL_ENOUGH:
            break
    #
    print("Values for uniformly random actions: ")
    print_values(V, grid)
    print("\n\n")

    policy = {
        (2, 0): 'U',
        (1, 0): 'U',
        (0, 0): 'R',
        (0, 1): 'R',
        (0, 2): 'R',
        (1, 2): 'R',
        (2, 1): 'R',
        (2, 2): 'R',
        (2, 3): 'U',
    }
    print_policy(policy, grid)

    print("Fixed policy/actions: ")
    print_policy(policy, grid)
    print("\n\n")

    V = {}
    for s in states:
        V[s] = 0

    gamma = 0.9

    count = 0
    while True:
        delta = 0
        count += 1
        for s in states:
            old_Vs = V[s]
            if s in policy:
                grid.set_state(s)
                V[s] = grid.move(policy[s]) + gamma * (V[grid.current_state()])
                delta = max(delta, np.abs(old_Vs-V[s]))

        if delta < SMALL_ENOUGH:
            break

    print("Fixed policy values: ")
    print_values(V, grid)
    print("\n\n")
    print(count)


import time

import keyboard
import mouse
import pytest

from ...ypackage.model.input import (
    ButtonEvent, InputRecorder, KeyboardEvent, MoveEvent, WheelEvent)

class TestInputRecorder:

    @pytest.fixture(autouse=True)
    def init_recorder(self):
        self.recorder = InputRecorder()

    def test_recoder_controls(self):
        return
        assert self.recorder.record()
        assert self.recorder.stop()
        assert not self.recorder.events

    def test_add_event(self):
        firsttime = time.time()
        secondtime = time.time()

        events = [
            MoveEvent(1, 2, firsttime),
            MoveEvent(1, 5, secondtime)
        ]

        for event in events:
            self.recorder.add_event(event)

        assert self.recorder.events == events

    def test_add_record(self):
        curtime = time.time()
        events = [
            MoveEvent(1, 2, curtime),
            KeyboardEvent(keyboard.KEY_UP, "a", time=curtime - 0.25),
            WheelEvent(1, curtime - 0.5),
            ButtonEvent(1, 2, curtime - 0.75)
        ]

        for event in events:
            self.recorder.add_event(event)
        assert self.recorder.events == events[::-1]

        self.recorder.events = []
        assert not self.recorder.events

        self.recorder.events = events
        assert self.recorder.events == events[::-1]

    def test_play_records(self):
        return
        curtime = time.time()

        events = [
            MoveEvent(200, 40, curtime),
            KeyboardEvent(keyboard.KEY_DOWN, "a", time=curtime + 0.1),
            KeyboardEvent(keyboard.KEY_UP, "a", time=curtime + 0.25),
            WheelEvent(-50, curtime + 0.5),
            ButtonEvent(mouse.DOWN, mouse.LEFT, curtime + 0.75),
            ButtonEvent(mouse.UP, mouse.LEFT, curtime + 0.85)
        ]
        self.recorder.events = events
        self.recorder.play()

        # Segmentation fault on Circle CI
        # assert (200, 40) == mouse.get_position()

    def test_wrong_event(self):
        with pytest.raises(ValueError):
            self.recorder.events = "YPackage"

        with pytest.raises(ValueError):
            self.recorder.add_event("YEmreAk")


def arr19():
    line1=input().split(" ")
    n,k=int(line1[0]),int(line1[1])
    arr=[int(x) for x in input().split(' ')]
    res=0
    for num in arr:
        s=str(num)
        cnt=0
        for x in s:
            if(x=='4' or x=='7'):
                cnt+=1
        if(cnt<=k):
            res+=1
    print(res)
    return

arr19()


from typing import Literal, Optional, Union

from . import xl, func_xltypes
from .func_xltypes import UNUSED, Unused
from .xlerrors import NumExcelError, ValueExcelError

dec = "dec"
Base = Literal[bin, dec, oct, hex]

PERMITTED_DIGITS = {
    bin: set("01"),
    oct: set("01234567"),
    hex: set("0123456789ABCDEFabcdef"),
}

BIT_WIDTHS = {bin: 10, oct: 30, hex: 40}

BASE_NUMBERS = {bin: 2, oct: 8, hex: 16}

BOUNDS = {
    frozenset([bin, oct]): 2 ** 9,
    frozenset([bin, dec]): 2 ** 9,
    frozenset([bin, hex]): 2 ** 9,
    frozenset([oct, dec]): 2 ** 29,
    frozenset([oct, hex]): 2 ** 29,
    frozenset([dec, hex]): 2 ** 39,
}

def handle_places(
        places: Union[Unused, func_xltypes.XlAnything]
) -> Optional[int]:
    if places is UNUSED:
        return None

    if isinstance(places, func_xltypes.Boolean):
        raise ValueExcelError('The `places` argument cannot be a boolean.')

    places = int(places)
    if not (1 <= places <= 10):
        raise NumExcelError('The number of places must be between 1 and 10.')

    return places

def handle_number(number: func_xltypes.XlAnything, origin) -> Union[int, str]:
    if isinstance(number, func_xltypes.Boolean):
        raise ValueExcelError('The number cannot be a boolean.')

    if origin == dec:
        return int(number)

    if isinstance(number, func_xltypes.Blank):
        as_str = "0"

    elif isinstance(number, func_xltypes.Number):
        if number.is_decimal and not number.value.is_integer():
            raise NumExcelError('Number is not an integer.')

        as_str = str(int(number))

    elif isinstance(number, func_xltypes.Text):
        as_str = str(number) if number else "0"

    if len(as_str) > 10:
        raise NumExcelError()

    if set(as_str) - PERMITTED_DIGITS[origin]:
        raise NumExcelError('There are invalid characters in the number.')

    return as_str

def pad_zeroes(string, was_negative, places):
    if places is None:
        return string

    desired_length = len(string) if was_negative else places
    if desired_length < len(string):
        raise NumExcelError(
            'The resulting string is longer than the desired length.')

    return string.zfill(desired_length)

def conversion(number, origin, destination, places):
    if origin == dec:
        # if origin base is dec we do not need to convert from it
        value = number
    else:
        # otherwise, convert to int in the appropriate base.
        as_int = int(number, BASE_NUMBERS[origin])

        # magic:
        mask = 1 << BIT_WIDTHS[origin] - 1
        value = (as_int & ~mask) - (as_int & mask)

    # This is another error-check, but it had to be delayed to here rather
    # than in handle_number because we had to convert it from the origin base
    # first.
    bound = BOUNDS[frozenset([origin, destination])]
    if not (-bound <= value < bound):
        raise NumExcelError('The input number is out of bounds')

    # if the destination base is dec, we are done
    if destination == dec:
        return value

    # magic (handles the 2s-complement-like wrapping behavior):
    was_negative = value < 0
    if was_negative:
        value += 1 << BIT_WIDTHS[destination]

    # Otherwise convert to appropriate string representation (return value is
    # (str, bool)).
    result = destination(value)[2:].upper()
    return pad_zeroes(result, was_negative, places)

def convert_bases(number, origin, destination, places=None):
    # If places is None, means it was not passed to this function, i.e. the
    # corresponding Excel function does not take it as an argument (the
    # ___2DEC functions). If it was passed in, we do error checking via the
    # handle_places function.
    if places is not None:
        places = handle_places(places)

    # Next, we do error checking on the number argument. This function does
    # not do any base-conversion logic, it simply raises exceptions if it
    # encounters invalid inputs.  If the origin base is dec, the result is an
    # integer, otherwise it is a string.
    number = handle_number(number, origin)

    # Now we actually convert from one base to another. The result of this can
    # also be either and integer or a string depending on the destination
    # base. If it is a string, it may also be zero-padded depending on the
    # places argument.
    return conversion(number, origin, destination, places)

@xl.register()
@xl.validate_args
def DEC2BIN(
        number: func_xltypes.XlAnything,
        places: func_xltypes.XlAnything = UNUSED
) -> func_xltypes.XlText:
    return convert_bases(number, dec, bin, places)

@xl.register()
@xl.validate_args
def DEC2OCT(
        number: func_xltypes.XlAnything,
        places: func_xltypes.XlAnything = UNUSED
) -> func_xltypes.XlText:
    return convert_bases(number, dec, oct, places)

@xl.register()
@xl.validate_args
def DEC2HEX(
        number: func_xltypes.XlAnything,
        places: func_xltypes.XlAnything = UNUSED
) -> func_xltypes.XlText:
    return convert_bases(number, dec, hex, places)

# the ___2DEC functions give a number not a string, and they do not take a
# `places` parameter
@xl.register()
@xl.validate_args
def BIN2DEC(
        number: func_xltypes.XlAnything
) -> func_xltypes.XlNumber:
    return convert_bases(number, bin, dec)

@xl.register()
@xl.validate_args
def BIN2OCT(
        number: func_xltypes.XlAnything,
        places: func_xltypes.XlAnything = UNUSED
) -> func_xltypes.XlText:
    return convert_bases(number, bin, oct, places)

@xl.register()
@xl.validate_args
def BIN2HEX(
        number: func_xltypes.XlAnything,
        places: func_xltypes.XlAnything = UNUSED
) -> func_xltypes.XlText:
    return convert_bases(number, bin, hex, places)

@xl.register()
@xl.validate_args
def OCT2DEC(
        number: func_xltypes.XlAnything
) -> func_xltypes.XlNumber:
    return convert_bases(number, oct, dec)

@xl.register()
@xl.validate_args
def OCT2BIN(
        number: func_xltypes.XlAnything,
        places: func_xltypes.XlAnything = UNUSED
) -> func_xltypes.XlText:
    return convert_bases(number, oct, bin, places)

@xl.register()
@xl.validate_args
def OCT2HEX(
        number: func_xltypes.XlAnything,
        places: func_xltypes.XlAnything = UNUSED
) -> func_xltypes.XlText:
    return convert_bases(number, oct, hex, places)

@xl.register()
@xl.validate_args
def HEX2DEC(
        number: func_xltypes.XlAnything
) -> func_xltypes.XlNumber:
    return convert_bases(number, hex, dec)

@xl.register()
@xl.validate_args
def HEX2BIN(
        number: func_xltypes.XlAnything,
        places: func_xltypes.XlAnything = UNUSED
) -> func_xltypes.XlText:
    return convert_bases(number, hex, bin, places)

@xl.register()
@xl.validate_args
def HEX2OCT(
        number: func_xltypes.XlAnything,
        places: func_xltypes.XlAnything = UNUSED
) -> func_xltypes.XlText:
    return convert_bases(number, hex, oct, places)


import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse
import matplotlib.transforms as transforms

def confidence_ellipse(x, y, ax, n_std=3.0, facecolor='none', **kwargs):
    """
    Create a plot of the covariance confidence ellipse of *x* and *y*.

    Parameters
    ----------
    x, y : array-like, shape (n, )
        Input data.

    ax : matplotlib.axes.Axes
        The axes object to draw the ellipse into.

    n_std : float
        The number of standard deviations to determine the ellipse's radiuses.

    **kwargs
        Forwarded to `~matplotlib.patches.Ellipse`

    Returns
    -------
    matplotlib.patches.Ellipse
    """
    if x.size != y.size:
        raise ValueError("x and y must be the same size")

    cov = np.cov(x, y)
    pearson = cov[0, 1]/np.sqrt(cov[0, 0] * cov[1, 1])
    # Using a special case to obtain the eigenvalues of this
    # two-dimensional dataset.
    ell_radius_x = np.sqrt(1 + pearson)
    ell_radius_y = np.sqrt(1 - pearson)
    ellipse = Ellipse((0, 0), width=ell_radius_x * 2, height=ell_radius_y * 2,
                      facecolor=facecolor, **kwargs)

    # Calculating the standard deviation of x from
    # the squareroot of the variance and multiplying
    # with the given number of standard deviations.
    scale_x = np.sqrt(cov[0, 0]) * n_std
    mean_x = np.mean(x)

    # calculating the standard deviation of y ...
    scale_y = np.sqrt(cov[1, 1]) * n_std
    mean_y = np.mean(y)

    transf = transforms.Affine2D() \
        .rotate_deg(45) \
        .scale(scale_x, scale_y) \
        .translate(mean_x, mean_y)

    ellipse.set_transform(transf + ax.transData)
    return ax.add_patch(ellipse)

# Excel-Datei mit Beisspieldatensatz in ein Dataframe einlesen
df_raw = pd.read_excel('beispieldatensatz.xlsx')

# Je ein Dataframe für m und eines für w erzeugen
df_m = df_raw.loc[df_raw['Geschlecht'] == 'm']
df_w = df_raw.loc[df_raw['Geschlecht'] == 'w']

# Für m und w nur die Daten in ein Dataframe laden, die Merkmalsausprägungen sind
data_m_groesse = df_m['Körpergröße']
data_m_gewicht = df_m['Körpergewicht']
data_w_groesse = df_w['Körpergröße']
data_w_gewicht = df_w['Körpergewicht']
df_summe_groesse = df_raw['Körpergröße']
df_summe_gewicht = df_raw['Körpergewicht']

# Plot erstellen
bp, ax = plt.subplots(figsize=(5, 4))
scatter = ax.scatter(df_summe_groesse, df_summe_gewicht, c='blue', s=20, zorder=5)

# Ellipse für Standardabweichung erzeugen
confidence_ellipse(df_summe_groesse, df_summe_gewicht, ax, \
                   alpha=0.5, facecolor='pink', edgecolor='purple', zorder=2)

# Achsen und Gitternetz konfigurieren
ax.set(xlabel='Körpergröße [in cm]', ylabel='Körpergewicht [in kg]')
ax.yaxis.grid(True, zorder=1)
ax.xaxis.grid(True, zorder=1)

# Vollständigen Plot anzeigen
plt.show()


'''
Modulo per il replay buffer

I suoi campi sono i seguenti:
 - observations: osservazione vista dall'agente all'inizio dello step,
                 quella su cui si è basato per scegliere l'azione
 - next_observations: osservazione vista dall'agente come conseguenza
                      dell'azione appena eseguita
 - actions: azione selezionata
 - rewards: la reward ottentua a seguito dell'azione
 - dones ("plurale di done"): segnale booleano di terminazione ricevuto dopo l'azione
'''

import numpy as np

# le chiavi usate nei dizionari restituiti dai ReplayBuffer
OBSERVATIONS = "observations"
NEXT_OBSERVATIONS = "next_observations"
ACTIONS = "actions"
REWARDS = "rewards"
DONES = "dones"

class ReplayBuffer:
    '''
    Crea un nuovo buffer.
    N.B.: observation_size e action_size devono essere scalari.
          Fortunatamente, nel nostro caso lo sono.
    '''
    def __init__(self, observation_size, action_size, buffer_size):
        # buffer per i cinque campi, vedi sopra
        self.observations = np.zeros([buffer_size, observation_size])
        self.next_observations = np.zeros([buffer_size, observation_size])
        self.actions = np.zeros([buffer_size, action_size])
        self.rewards = np.zeros(buffer_size)
        self.dones = np.zeros(buffer_size)
        # indice della prossima cella da riempire
        self.write_idx = 0
        # numero di elementi attualmente nel buffer
        self.size = 0
        # massima capacità del buffer:
        # una volta superata, elimineremo gli elementi più vecchi
        self.max_size = buffer_size

    '''
    Aggiunge una nuova entry al buffer.
    Se è pieno, l'entry più vecchia viene sovrascritta.
    '''
    def store(self, obs, next_obs, act, rew, done):
        # scrivi nel buffer alla cella indicata
        self.observations[self.write_idx] = obs
        self.next_observations[self.write_idx] = next_obs
        self.actions[self.write_idx] = act
        self.rewards[self.write_idx] = rew
        self.dones[self.write_idx] = done
        # fai avanzare l'indice di scrittura.
        # una volta raggiunta la fine, riparti dall'inizio:
        # questo fa in modo che sovrascriviamo le entry nello stesso ordine
        # in cui le abbiamo scritte, quindi l'entry cancellata sarà sempre
        # la più vecchia
        self.write_idx = (self.write_idx+1) % self.max_size
        # incrementa il numero di elementi nel buffer,
        # a meno che la condizione non sia falsa,
        # nel qual caso il buffer era già pieno
        # e abbiamo sovrascritto una vecchia entry
        if self.size < self.max_size:
            self.size += 1

    '''
    Estrae una batch casuale dal buffer.
    `batch_size` è il numero di elementi da estrarre.
    '''
    def random_batch(self, batch_size):
        # estrai `batch_size` indici casuali
        randomized_indices = np.random.randint(0, self.size, batch_size)
        # recupera i dati corrispondenti a quegli indici dal buffer
        # (grazie all'indicizzamento multiplo di numpy)
        obs_batch = self.observations[randomized_indices]
        next_obs_batch = self.next_observations[randomized_indices]
        act_batch = self.actions[randomized_indices]
        rew_batch = self.rewards[randomized_indices]
        done_batch = self.dones[randomized_indices]
        # restituisci l'intera batch sotto forma di dizionario
        return {
            OBSERVATIONS: obs_batch,
            NEXT_OBSERVATIONS: next_obs_batch,
            ACTIONS: act_batch,
            REWARDS: rew_batch,
            DONES: done_batch
        }


# -*- coding: utf-8 -*-
"""
Created on Sat Sep 17 00:50:32 2022

@author: Mukarram ali
"""

from funcs import ReadFromFile
from funcs import RandomArray
from funcs import InsertionSort
from funcs import MergeSort
from funcs import SelectionSort
from funcs import SaveTitleinFile
from funcs import SaveCredentialsInFile
from funcs import bubbleSort
import time

numbersarr=ReadFromFile()
SaveTitleinFile()
for i in range(0,len(numbersarr)):
    N=numbersarr[i]
    arr=RandomArray(numbersarr[i])
    dup_arr1=arr
    insertionStart=time.time()
    insertionArr=InsertionSort(dup_arr1, 0, len(dup_arr1))
    insertionEnd=time.time()
    insertiontime= insertionEnd-insertionStart
    dup_arr2=arr
    MergeStart=time.time()
    arr2=MergeSort(dup_arr2, 0, len(dup_arr2)-1)
    MergeEnd=time.time()
    MergeTime=MergeEnd-MergeStart
    dup_arr3=arr
    SelectionStart=time.time()
    arr3=SelectionSort(dup_arr3, 0, len(dup_arr3))
    SelectionEnd=time.time()
    SelectionTime=SelectionEnd-SelectionStart
    BubbleSortStart=time.time()
    bubbleSort(arr)
    Bubblesortend=time.time()
    BubbleSortTime=Bubblesortend-BubbleSortStart
    print(N)
    print("Insertion:",insertiontime)
    print("Merge:",MergeTime)
    print("Selection:",SelectionTime)
    print("Bubble Sort Time:",BubbleSortTime)
    SaveCredentialsInFile((N),insertiontime,MergeTime,SelectionTime,BubbleSortTime)


from pathlib import Path
from typing import Any, Callable, Dict, Optional, Type

from ziggurat.parser import Parser
from ziggurat.visitor import Renderer

class Template:
    transforms: Dict[str, Callable[[Any], Any]] = {
        "upper": str.upper,
        "lower": str.lower,
        "capitalize": str.capitalize,
    }

    def __init__(
        self,
        source: str,
        encoding: str = "utf8",
        parser_cls: Type[Parser] = Parser,
        renderer_cls: Type[Renderer] = Renderer,
    ):
        self.source = Path(source)
        self.renderer_cls = renderer_cls
        with open(source, "r", encoding=encoding) as tmpl:
            self.ast = parser_cls(tmpl.read()).parse()

    def render(self, ctx: Dict[str, Any]) -> str:
        renderer = self.renderer_cls(ctx, self.transforms, self.source.parent)
        self.ast.accept(renderer)
        return renderer.result

def register_transform(func: Callable[[Any], Any], name: Optional[str] = None):
    if name is None:
        name = func.__name__
    Template.transforms[name] = func
    return func


"""
python iedb_api.py seqs_nt.fasta hlafile.hla
"""
import skbio
import numpy as np
import pandas as pd
import time
import sys

sys.path.append('/home/agartlan/gitrepo')
import HLAPredCache
from dani_helpers import *

if __name__ == '__main__':
    mersFn = sys.argv[1]
    hlaFn = sys.argv[2]
    outFn = sys.argv[3]

    with open(mersFn, 'r') as fh:
        raw = fh.read()
    mers = raw.split('\n')[:-1]

    with open(hlaFn, 'r') as fh:
        raw = fh.read()
    hlas = raw.split('\n')[:-1]

    lengths = sorted(list(set([len(m) for m in mers])))

    results = []
    for l in lengths:
        tmpMers = [p for p in mers if len(p) == l]
        res = HLAPredCache.iedbPepPredict(hlas, tmpMers, method='netmhcpan', timeit=True)
        results.append(res)
    outDf = pd.concat(results, axis=0)

    outDf.to_csv(outFn[['allele', 'peptide', 'ic50']], index=False)


# Practical Worksheet P3: Graphical Programming
# your name, your number

from graphics import *
import math

def drawStickFigure():
    win = GraphWin("Stick figure")
    head = Circle(Point(100, 60), 20)
    head.draw(win)
    body = Line(Point(100, 80), Point(100, 120))
    body.draw(win)
    leftLeg = Line(Point(100,120), Point(80,140))
    leftLeg.draw(win)
    rightLeg = Line(Point(100,120), Point(120,140))
    rightLeg.draw(win)
    leftArm = Line(Point(100,100), Point(80,100))
    leftArm.draw(win)
    rightArm = Line(Point(100,100), Point(120,100))
    rightArm.draw(win)

    input()

def drawLine():
    win = GraphWin("Line drawer")
    message = Text(Point(100,100), "Click on first point")
    message.draw(win)
    p1 = win.getMouse()
    message.setText("Click on second point")
    p2 = win.getMouse()
    line = Line(p1, p2)
    line.draw(win)
    message.setText("")

# wk03,ex02 userinputs radius of circle to terminal, the output a circle with that radius to gui
def drawCircle():
    radius = int(input("Please enter the radius here: "))
    size = (radius * 2) + 30
    win = GraphWin("Circle", size, size)
    centre = Point(win.getHeight()/2, win.getWidth()/2)
    circle = Circle(centre, radius)
    circle.draw(win)

    input()

# wk03, ex03 draw archery target (3x concentric circle, each diff colour.)
def drawArcheryTarget():
    win = GraphWin("Archery Target", 400,400)
    centre = Point(win.getHeight()/2, win.getWidth()/2)
    circle1 = Circle(centre, 150)
    circle1.draw(win)
    circle1.setFill("blue")
    circle2 = Circle(centre, 100)
    circle2.draw(win)
    circle2.setFill("red")
    circle3 = Circle(centre, 50)
    circle3.draw(win)
    circle3.setFill("yellow")
    input()

# wk03 ex03a improved after demo to Mani - same as above except use loop to reduce lines of code
def drawArcheryTargetBetter():
    win = GraphWin("Archery Target", 400, 400)
    centre = Point(win.getHeight()/2, win.getWidth()/2)
    colours = ["blue", "red", "yellow"]
    radius = 150
    for x in range (0,3):
        circle = Circle(centre, radius)
        circle.draw(win)
        circle.setFill(colours[x])
        radius = radius - 50
    input()

# wk03, ex04 use input height and width of rectangle. draw in gui (200x200,assume user enters values less than this), draw rectangle with user values in centre of screen.
def drawRectangle():
    width = int(input("Enter width:"))
    height = int(input("Enter height: "))
    win = GraphWin("Rectangle Box", 200, 200)
    topLeft = Point((100-width/2), (100-height/2))
    bottomRight = Point((100+width/2), (100+height/2))
    rectangle = Rectangle(topLeft, bottomRight)
    rectangle.draw(win)
    input()

# wk03, ex05 user clicks in gui somewhere. draw a blue circle with radius 50 wherever they click
def blueCircle():
    win = GraphWin("Click for Circle", 200,200)
    mousePos = win.getMouse()
    circle = Circle(mousePos, 50)
    circle.draw(win)
    circle.setFill("blue")
    input()

# wk03, ex06 pt1 user clicks two points, draw line between them
def drawLine():
    win = GraphWin("Line box", 400, 400)
    lineStart = win.getMouse()
    lineEnd = win.getMouse()
    line = Line(lineStart, lineEnd)
    line.draw(win)
    input()

# wk03, ex06 pt2 user can draw 10 lines by clicking their start and end point
def tenLines():
    win = GraphWin("Ten line box", 500, 500)
    for x in range(0,10):
        lineStart = win.getMouse()
        lineEnd = win.getMouse()
        line = Line(lineStart, lineEnd)
        line.draw(win)
    input()

# wk03, ex07 user enters string into input box then click on screen to place it. repeat 10 times.
def tenStrings():
    win = GraphWin("String box", 600,600)
    inputBox = Entry(Point(100,100),20)
    inputBox.draw(win)
    for x in range(0,10):
        mousePos = win.getMouse()
        message = Text(mousePos, inputBox.getText())
        # TO BE CONTINUED HERE
        messageOnDisplay = Text(mousePos, message)
        messageOnDisplay.setText(inputBox.getText())
        messageOnDisplay.draw(win)

# wk03, ex08 user clicks top left bottom right corner of rectangle after entering colour of rect into text box
def tenColouredRectangles():
    win = GraphWin("Rectangle Box", 1000,1000)
    inputBox = Entry(Point(100,100),20)
    inputBox.draw(win)
    for x in range (0,10):
        mouse1 = win.getMouse()
        mouse2 = win.getMouse()
        rect = Rectangle(mouse1, mouse2)
        rect.draw(win)
        rect.setFill(inputBox.getText())

# wk03, wx09 user clicks five times to draw stick man
def fiveClickStickFigure():
    win = GraphWin("Five Click Stick Figure",600,600)
    point1 = win.getMouse()
    point2 = win.getMouse()
    faceRad = math.sqrt(((point2.getX() - point1.getX())**2) + ((point2.getY() - point1.getY())**2))
    face = Circle(point1, faceRad)
    face.draw(win)
    point3 = win.getMouse()
    body = Line(Point(point1.getX(),point1.getY() + faceRad), point3)
    body.draw(win)
    point4 = win.getMouse()
    armSpan = (point1.getX() - point4.getX()) * 2
    arms = Line(point4, Point(armSpan + point4.getX(), point4.getY()))
    arms.draw(win)
    point5 = win.getMouse()
    legL = Line(point3, point5)
    legL.draw(win)
    rightFoot = Point((((point3.getX() - point5.getX()) * 2) + point5.getX()), point5.getY())
    legR = Line(point3, rightFoot)
    legR.draw(win)

# wk03 ex10 plots histogram based on values the user enters
def plotRainfall():
    win = GraphWin("Rain over time", 600, 600)
    inputBox = Entry(Point(100, 25), 20)
    inputBox.draw(win)
    startX = 300
    startY = 500
    for x in range(0,7):
        mouse = win.getMouse()
        value = float(inputBox.getText())
        bottomLeft = Point(startX, startY)
        topRight = Point(startX + 10, startY-value)
        rect = Rectangle(bottomLeft, topRight)
        rect.draw(win)
        rect.setFill("pink")
        caption = Text(Point(startX + 4, startY + 10), x+1)
        caption.draw(win)
        startX = startX + 12
    input()

#################### MAIN PROGRAMME BELOW ################
#drawStickFigure()
#drawCircle()
#drawArcheryTarget()
#drawRectangle()
#blueCircle()
#drawLine()
#tenLines()
#tenStrings()
#tenColouredRectangles()
#fiveClickStickFigure()
#plotRainfall()
drawArcheryTargetBetter()


import numpy as np
import rospy
import roshelper
import helper
import ik.ik_helper
from geometry_msgs.msg import PoseStamped
from sensor_msgs.msg import JointState
import tf.transformations as tfm
from copy import deepcopy

def joints_from_poses(pose_left, pose_right, qf):
    if len(qf[0]) == 7:
        plan_dict_left = ik.ik_helper.joints_from_pose(pose_left, "l", seed=qf[0])
    else:
        plan_dict_left = ik.ik_helper.joints_from_pose(pose_left, "l", seed=None)
    if len(qf[1]) == 7:
        plan_dict_right = ik.ik_helper.joints_from_pose(pose_right, "r", seed=qf[1])
    else:
        plan_dict_right = ik.ik_helper.joints_from_pose(pose_right, "r", seed=None)
    return plan_dict_left, plan_dict_right

def raise_poses(poses, dz, arm=['r', 'l']):
    pose_left = deepcopy(poses[0])
    pose_right = deepcopy(poses[1])
    if 'l' in arm:
        pose_left.pose.position.z += dz
    if 'r' in arm:
        pose_right.pose.position.z += dz

    return [pose_left, pose_right]

def move_cart(desired_pose, plan_previous, primitive, speed=0.5, type='SetTraj', plan_name=None, N=100):
    #1. initialize variables
    is_execute = True
    out_dict = {}
    out_dict['is_failed_ik'] = False
    initial_pose = plan_previous['poses'][-1]
    object_pose = plan_previous['x_star'][-1]
    final_pose = desired_pose
    #2. interpolate poses individually (left and right)
    pose_left_interpolate_left = roshelper.interpolate_pose(initial_pose[0], final_pose[0], N)
    pose_left_interpolate_right = roshelper.interpolate_pose(initial_pose[1], final_pose[1], N)
    #3. Return robot plan
    out_dict['type'] = type
    out_dict['primitive'] = primitive
    out_dict['speed'] = speed
    out_dict['name'] = plan_name
    out_dict['is_replan'] = False
    out_dict['is_state_estimation'] = False
    out_dict['poses'] = [[pose_left_interpolate_left[x], pose_left_interpolate_right[x]] for x in
                         range(len(pose_left_interpolate_left))]
    # out_dict['poses_final'] = [final_pose[0], final_pose[1]]
    out_dict['x_star'] = [object_pose] * N
    out_dict['t_star'] = list(np.linspace(0, 1, num=N, endpoint=False))
    out_dict['is_execute'] = is_execute
    out_dict['replan_type'] = None
    return out_dict

def plan_sequence_poses(pose_list=[], primitive='', speed_list=[], name_list=[], previous_plan=None, check_collisions=True):
    robot_plan = []
    for counter in range(len(pose_list)):
        plan = move_cart(pose_list[counter],
                                         previous_plan,
                                         primitive,
                                         speed_list[counter],
                                         'SetCart',
                                         name_list[counter])
        plan['check_collisions'] = check_collisions
        robot_plan.append(plan)
        previous_plan = plan
    return robot_plan

def make_constant_plan(plan, plan_previous, N=11):
    plan['index_traj'] = []
    plan['object_traj'] = []
    for counter in range(N):
        try:
            plan['joint_traj'].points[counter]
        except:
            plan['joint_traj'].points.append(deepcopy(plan['joint_traj'].points[0]))
        plan['joint_traj'].points[counter].positions = deepcopy(plan['joint_traj'].points[0].positions)
        plan['joint_traj'].points[counter].time_from_start =  deepcopy(plan_previous['joint_traj'].points[counter].time_from_start)
        plan['index_traj'].append([counter * 100 / N, counter * 100 / N, 0.])
        plan['object_traj'].append(plan_previous['object_traj'][-1])
    return plan

def move_cart_synchro(final_pose, grasp_width, plan_previous, speed=1.0, primitive='', time=1, plan_name=None, N=100, is_replan=False, primitive_obj=None, is_state_estimation=False, is_state_estimation_initial=False,):
    #1. initialize variables
    joint_list = []
    out_dict = {}
    is_execute = True
    poses_inital = plan_previous['poses'][-1]
    object_pose = plan_previous['x_star'][-1]
    pose_initial_left_world = poses_inital[0]
    pose_final_left_world = final_pose
    # 2. define object pose relative to gripper frame
    pose_object_rel_gripper = roshelper.convert_reference_frame(object_pose,
                                                                pose_initial_left_world,
                                                                roshelper.unit_pose("yumi_body"),
                                                                frame_id="gripper_left")

    #2. interpolate gripper left pose trajectory
    pose_left_interpolate = roshelper.interpolate_pose(pose_initial_left_world, pose_final_left_world, N)
    #3. Loop through gripper poses and compute object poses
    object_pose_list = []
    pose_list = []
    for pose_left_world in pose_left_interpolate:
        pose_list_world = align_arm_poses(pose_left_world, grasp_width)
        pose_object_rel_world = roshelper.convert_reference_frame(pose_object_rel_gripper,
                                                        roshelper.unit_pose("yumi_body"),
                                                        pose_left_world,
                                                        frame_id="yumi_body")
        #4. append to list
        object_pose_list.append(pose_object_rel_world)
        pose_list.append([pose_list_world[0], pose_list_world[1]])
    #5. return final plan
    out_dict['poses'] = pose_list
    out_dict['poses_final'] = pose_list[-1]
    out_dict['type'] = 'SetTraj'
    out_dict['primitive'] = primitive
    out_dict['grasp_width'] = grasp_width
    out_dict['primitive_obj'] = primitive_obj
    out_dict['x_star'] = object_pose_list
    out_dict['speed'] = speed
    out_dict['time'] = time
    out_dict['is_replan'] = is_replan
    out_dict['replan_type'] = None
    out_dict['is_state_estimation'] = is_state_estimation
    out_dict['is_state_estimation_initial'] = is_state_estimation_initial
    out_dict['name'] = plan_name
    out_dict['t_star'] = list(np.linspace(0, time, num=N, endpoint=False))
    out_dict['is_execute'] = is_execute
    return out_dict

def move_object_synchro(rotation_base_initial, rotation_base_final, plan_previous, placement_list=None, delta_spring=0, anchor_offset=[], speed=0.5, primitive='', time=1, plan_name=None, N=100, planner=None, is_replan=False, is_state_estimation=False, is_state_estimation_initial=False, primitive_obj=None):
    #1. initialize variables
    out_dict = {}
    is_collision = False
    poses_inital = plan_previous['poses'][-1]
    object_pose_initial = plan_previous['x_star'][-1]
    pose_initial_left_offset_world = poses_inital[0]
    pose_initial_left_centered_world = offset_local_pose(pose_initial_left_offset_world, -np.array(anchor_offset))
    pose_initial_right_world = poses_inital[1]
    #interpolate object motion (rotate about rotate_base, i.e. corner of the object)
    pose_rotation_base_interpolate = roshelper.interpolate_pose(rotation_base_initial, rotation_base_final, N)

    #2. determinal relative poses between objects and rotate_base frame
    pose_object_rel_rotation_base, pose_gripper_left_rel_rotation_base, pose_gripper_right_rel_rotation_base = \
        roshelper.convert_list_reference_frames([object_pose_initial,
                                                 pose_initial_left_centered_world,
                                                 pose_initial_right_world],
                                                  [rotation_base_initial]*3,
                                                  [roshelper.unit_pose("yumi_body")]*3,
                                                  ["rotation_base"]*3)
    #4 loop through object poses and compute gripper poses
    gripper_pose_list = []
    object_pose_list = []
    angle_left_vec = np.linspace(0,90,len(pose_rotation_base_interpolate))
    angle_right_vec = np.linspace(3,3,len(pose_rotation_base_interpolate))

    for counter, pose_rotation_base_world in enumerate(pose_rotation_base_interpolate):
        #Find nominal gripper position in world based on object pose
        pose_gripper_left_world_tmp, \
        pose_gripper_right_world_tmp, \
        pose_object_world_tmp = roshelper.convert_list_reference_frames(
                                                        [pose_gripper_left_rel_rotation_base, pose_gripper_right_rel_rotation_base,pose_object_rel_rotation_base],
                                                        [roshelper.unit_pose("yumi_body")]*3,
                                                        [pose_rotation_base_world]*3,
                                                        ["yumi_body"]*3)
        #rotate gripper to desired orientation (about z gripper axis)
        pose_gripper_left_rotated_world, pose_gripper_right_rotated_world = rotate_gripper_poses([pose_gripper_left_world_tmp, pose_gripper_right_world_tmp],
                                                                                [[0,0,angle_left_vec[counter] * np.pi/180], [0,0,angle_right_vec[counter] * np.pi/180]])
        pose_gripper_left_rotated_world = offset_local_pose(pose_gripper_left_rotated_world, np.array(anchor_offset))
        # check for collision of left anchor:
        # if is_collision==False:
        pose_gripper_left_rotated_world, is_collision = avoid_collision(pose_gripper_left_rotated_world,
                                                          planner,
                                                          arm="l",
                                                          tol=0.003,
                                                          axis=[-1,0,0])
            # pose_gripper_left_safe = pose_gripper_left_rotated_world
        # else:
        #     pose_gripper_left_rotated_world = pose_gripper_left_safe

        object_pose_list.append(pose_object_world_tmp)
        gripper_pose_list.append([pose_gripper_left_rotated_world, pose_gripper_right_rotated_world])
    #5. return final plan
    out_dict['poses'] = gripper_pose_list
    out_dict['poses_final'] = gripper_pose_list[-1]
    out_dict['type'] = 'SetTraj'
    out_dict['primitive'] = primitive
    out_dict['primitive_obj'] = primitive_obj
    out_dict['x_star'] = object_pose_list
    out_dict['speed'] = speed
    out_dict['time'] = time
    out_dict['delta_spring'] = time
    out_dict['placement_list'] = placement_list
    out_dict['is_replan'] = is_replan
    out_dict['replan_type'] = None
    out_dict['is_state_estimation'] = is_state_estimation
    out_dict['is_state_estimation_initial'] = is_state_estimation_initial
    out_dict['name'] = plan_name
    out_dict['t_star'] = list(np.linspace(0, time, num=N, endpoint=False))
    return out_dict

def avoid_collision(pose_gripper, planner, arm="l", tol=0.003, axis=[-1,0,0]):
    is_collision = False
    pose_gripper_safe = deepcopy(pose_gripper)
    pose_gripper_safe.pose.position.z -= 0.006
    while planner.check_collisions_with_table(pose_gripper_safe, arm="l"):
        pose_gripper_safe = offset_local_pose(pose_gripper_safe, np.array(axis)*tol)
        is_collision = True
    pose_gripper = deepcopy(pose_gripper_safe)
    pose_gripper.pose.position.z += 0.006
    return pose_gripper, is_collision

def move_joints(desired_joints, plan_previous, primitive, speed=0.5, plan_name=None, N=100, check_collisions = True):
    desired_pose = [ik.ik_helper.compute_fk(desired_joints[0], "l"),
                    ik.ik_helper.compute_fk(desired_joints[1], "r")]
    out_dict = move_cart(desired_pose,
                         plan_previous,
                         primitive,
                         speed=speed,
                         type='SetJoints',
                         plan_name=plan_name,
                         N=N)
    out_dict['check_collisions'] = check_collisions
    out_dict['joints'] = [desired_joints]
    return out_dict

def offset_grasp(pose_stamped_world_frame, dist_grasp, offset, is_symmetric=True):
    '''Create new gripper poses offset from nominal gripper pose list'''

    pose_list_world = align_arm_poses(pose_stamped_world_frame[0], dist_grasp)
    offset_pose_list_world = offset_pose_list(pose_list_world, offset, is_symmetric)
    return offset_pose_list_world

def offset_local_pose(pose_world, offset):
    #1. convert to gripper reference frame
    pose_gripper = roshelper.convert_reference_frame(pose_world,
                                                         pose_world,
                                                         roshelper.unit_pose(frame_id="yumi_body"),
                                                         frame_id = "gripper_frame")

    #3. add offset to grasp poses in gripper frames
    pose_gripper.pose.position.x += offset[0]
    pose_gripper.pose.position.y += offset[1]
    pose_gripper.pose.position.z += offset[2]
    #4. convert back to world frame
    pose_new_world = roshelper.convert_reference_frame(pose_gripper,
                                                         roshelper.unit_pose(frame_id="yumi_body"),
                                                         pose_world,
                                                         frame_id = "yumi_body")
    return pose_new_world

def rotate_local_pose(pose_world, offset):
    angle_x = offset[0]
    angle_y = offset[1]
    angle_z = offset[2]
    pose_transform_tmp = roshelper.pose_from_matrix(tfm.euler_matrix(angle_x, angle_y, angle_z, 'sxyz'),
                                                frame_id="tmp")

    pose_rotated_world = roshelper.transform_body(pose_world, pose_transform_tmp)
    return pose_rotated_world

def rotate_gripper_poses(pose_world_list, offset_list):
    pose_rotated_world_list = []
    for i, pose_world in enumerate(pose_world_list):
            pose_rotated_world_list.append(rotate_local_pose(pose_world, offset_list[i]))
    return pose_rotated_world_list

def offset_gripper_poses(pose_stamped_world_frame, offset, is_offset=[True, True]):
    '''Create new gripper poses offset from nominal gripper pose list'''
    pose_new_world_list = []
    for i, pose_world in enumerate(pose_stamped_world_frame):
        if is_offset[i]:
            pose_new_world_list.append(offset_local_pose(pose_world, offset))
        else:
            pose_new_world_list.append(pose_world)
    return pose_new_world_list

def rotate_quat_y(pose):
    '''set orientation of right gripper as a mirror reflection of left gripper about y-axis'''
    quat = pose.pose.orientation
    R = tfm.quaternion_matrix([quat.x, quat.y, quat.z, quat.w])
    z_vec = R[0:3, 2]  # np.cross(x_vec, y_vec)
    y_vec = -R[0:3, 1]  # normal
    x_vec = np.cross(y_vec, z_vec)  # np.array([0,0,-1])
    x_vec = x_vec / np.linalg.norm(x_vec)
    y_vec = y_vec / np.linalg.norm(y_vec)
    z_vec = z_vec / np.linalg.norm(z_vec)
    # Normalized object frame
    hand_orient_norm = np.vstack((x_vec, y_vec, z_vec))
    hand_orient_norm = hand_orient_norm.transpose()
    quat = roshelper.mat2quat(hand_orient_norm)
    return quat

def align_arm_poses(pose, grasp_dist):
    '''Set position of right arm with respect to left arm'''
    T_left_world = roshelper.matrix_from_pose(pose)
    pose_right_left = PoseStamped()
    pose_right_left.header.frame_id = pose.header.frame_id
    pose_right_left.pose.position.y = - grasp_dist
    quat = rotate_quat_y(pose_right_left)
    pose_right_left.pose.orientation.x = quat[0]
    pose_right_left.pose.orientation.y = quat[1]
    pose_right_left.pose.orientation.z = quat[2]
    pose_right_left.pose.orientation.w = quat[3]
    T_right_left = roshelper.matrix_from_pose(pose_right_left)
    T_right_world = np.matmul(T_left_world, T_right_left)
    pose_right = roshelper.pose_from_matrix(T_right_world, type="PoseStamped")
    return [pose, pose_right]

def offset_pose_list(pose_list, offset = [0,0,0], is_symmetric=True):
    '''Offset pose_list by translation offset'''
    pose_offset_list = []
    arm_list = ['l', 'r']
    counter=0
    for pose, arm in zip(pose_list, arm_list):
        pose_stamped_hand = roshelper.unit_pose("tip_" + arm)
        if is_symmetric:
            pose_stamped_hand.pose.position.y =+ offset[1]
        else:
            if arm == 'r':
                pose_stamped_hand.pose.position.y =+ offset[1]
        if arm=='l':
            pose_stamped_hand.pose.position.x = + offset[0]
            pose_stamped_hand.pose.position.z = + offset[2]
        else:
            pose_stamped_hand.pose.position.x = - offset[0]
            pose_stamped_hand.pose.position.z = - offset[2]
        pose_stamped_world = roshelper.convert_reference_frame(pose_stamped_hand,
                                                                  roshelper.unit_pose("yumi_body"),
                                                                  pose)
        pose_offset_list.append(pose_stamped_world)
        counter+=1
    return pose_offset_list

def go_home_grasping(object_pose=None, speed=2., N=10, time=2):
    from sensor_msgs.msg import JointState
    #1. define final joint position
    final_joint_left = helper.yumi2robot_joints(rospy.get_param('grasping_left/yumi_convention/joints'), deg=True)
    final_joint_right = helper.yumi2robot_joints(rospy.get_param('grasping_right/yumi_convention/joints'), deg=True)

    #2. define initial (current) joint position
    if rospy.get_param('/have_robot'):
        if rospy.get_param('/egm_mode'):
            initial_joint_left_msg = rospy.wait_for_message('measured_joints_left', JointState)
            initial_joint_right_msg = rospy.wait_for_message('measured_joints_right', JointState)
            initial_joint_left = helper.yumi2robot_joints(initial_joint_left_msg.position)
            initial_joint_right = helper.yumi2robot_joints(initial_joint_right_msg.position)
        else:
            initial_joint_left = final_joint_left
            initial_joint_right = final_joint_right
    else:
        joint_states_msg = rospy.wait_for_message('/joint_states', JointState)
        initial_joint_left = joint_states_msg.position[7:14]
        initial_joint_right = joint_states_msg.position[0:7]

    #3. perform linear interpolation
    joint_left_interpolate = helper.linspace_array(initial_joint_left, final_joint_left, N)
    joint_right_interpolate = helper.linspace_array(initial_joint_right, final_joint_right, N)

    #4. loop through all joints and compute poses
    joints_list = []
    poses_list = []
    for joint_left, joint_right in zip(joint_left_interpolate, joint_right_interpolate):
        #5. compute fk
        pose_left = ik.ik_helper.compute_fk(joint_left, arm="l")
        pose_right = ik.ik_helper.compute_fk(joint_right, arm="r")
        #6. append joints and poses to list
        joints_list.append([joint_left, joint_right])
        poses_list.append([pose_left, pose_right])
    plan_dict = {}
    plan_dict['poses'] = poses_list
    plan_dict['poses_final'] = poses_list[-1]
    plan_dict['type'] = 'SetTraj'
    plan_dict['primitive'] = 'go_home'
    plan_dict['speed'] = speed
    plan_dict['time'] = time
    plan_dict['t_star'] = list(np.linspace(0, 1, num=N, endpoint=False))
    plan_dict['is_execute'] = True
    if object_pose is not None:
        plan_dict['x_star'] = [object_pose] * N
    plan_dict['joints'] = joints_list
    plan_dict['joints_final'] = joints_list[-1]
    return plan_dict


def permutations(arr, output, n):
    if len(output) == n:
        print(output)

    if len(output) < n:
        for i in range(len(arr)):
            if arr[i] not in output:
                output.append(arr[i])
                permutations(arr[:i] + arr[i+1:], output, n)
                output.pop(len(output)-1)
    else:
        return

permutations(["a", "b", "c"], [], 3)


# Create your views here.

from django.http import HttpResponse,HttpResponseNotFound
import random

def gimmeword(request, resource):
    if resource == 'first':
        word = random.choice(["The table", "My uncle", "A book", "The road", "Music"])
    elif resource == 'second':
        word = random.choice(["talks", "knows", "thinks", "works", "runs", "eats"])
    elif resource == 'third':
        word = random.choice(["fast", "low", "far away", "hard", "in pijama", "while dances cha-cha-cha"])
    else:
        return HttpResponseNotFound('Page not found')
    return HttpResponse(word)


#!/usr/bin/env python3

from operator import mul
from functools import reduce

for test in range(int(input())):
    size = reduce(mul, [int(n) for n in input().split()])
    if size%2 == 1:
        size += 2**0.5 - 1
    print('Scenario #{}:\n{:.2f}\n'.format(test+1, size))


from csv import writer

from python.types import Output

def write_data_to_file(file: str, data: Output) -> None:
    with open(file, "w+", newline="") as csvfile:
        output = writer(csvfile, delimiter=",")
        for row in data:
            output.writerow(row)


def d_to_b(n, num):
    # n: number(10진수)
    binary_text = format(num, "b")
    l = n - len(binary_text)
    binary_text = "0" * l + binary_text
    return binary_text

def solution(n, arr1, arr2):
    answer = []
    # 숫자 배열을 이진수로 변환한다.
    bi_arr1 = []
    bi_arr2 = []
    for i in range(n):
        # 변환한 이진수를 배열에 저장한다.
        bi_arr1.append(d_to_b(n, arr1[i]))
        bi_arr2.append(d_to_b(n, arr2[i]))
    # 두 배열을 인덱스로 순회하며, 새로운 배열을 만든다.
    for i in range(n):
        temp_row = ""
        for j in range(n):
            # 벽은 "#"으로, 공백(0)은 " "으로 저장한다.
            temp = " "
            # 새로운 배열을 만들 때, 어느 하나라도 벽(1)인 부분이 있다면 벽이다.
            if bi_arr1[i][j] == "1" or bi_arr2[i][j] == "1":
                temp = "#"
            temp_row += temp
        # row 단위로 만들어진 문자열을 저장한다.
        answer.append(temp_row)
    print(arr1, arr2)
    return answer

print(solution(6, [46, 33, 33 ,22, 31, 50], [27 ,56, 19, 14, 14, 10]))


# def bi_search(l, r, arr, x):  #binary searchก็แย่ละ!!!!!!!!!!!
#     if l>r:
#         return False
#     else:
#         if arr[r]==x:
#             return True
#         return bi_search(l,r-1,arr,x)   #******************
#     #return 0  *******************************

# def bi_search(l, r, arr, x):
#     mid = (r+l)//2#หาค่าตรงกลาง
#     if arr[mid]==x:return True#เจอค่า
#     elif l==r:return False#หมดลิสละไม่เจอค่า
#     elif x<arr[mid]:return bi_search(mid+1,r,arr,x)#ไปขวา
#     else:return bi_search(l,mid-1,arr,x)#ไปซ้าย

# inp = input('Enter Input : ').split('/')
# arr, k = list(map(int, inp[0].split())), int(inp[1])
# print(bi_search(0, len(arr) - 1, sorted(arr), k))

def bi_search(lst, x):
    if len(lst)==0:
        return False
    mid=len(lst)//2
    if lst[mid]==x:
        return True
    elif lst[mid]<x:
        return bi_search(lst[mid+1:],x)
    elif lst[mid]>x:
        return bi_search(lst[:mid-1],x)

inp = input('Enter Input : ').split('/')
arr, k = list(map(int, inp[0].split())), int(inp[1])
print(bi_search(sorted(arr), k))

# def binarysearch(List, x):
#     if len(List) == 0:
#         return False
#     mid = len(List)//2
#     if List[mid] == x:
#         return True
#     elif x > List[mid]:
#         return binarysearch(List[mid+1:], x)
#     elif x < List[mid]:
#         return binarysearch(List[:mid], x)

# IN, x = input("Enter Input : ").split('/')
# IN = sorted(list(map(int, IN.split())))
# print(binarysearch(IN, int(x)))


import sqlite3
import pandas as pd

conn = sqlite3.connect('markov_models.db')

sql = 'select features, percent_return from models'
df = pd.read_sql(sql, conn)

all_features_used = []
for key, value in df.iterrows():
    features = eval(df.loc[key, 'features'])
    all_features_used.extend(features)
    """
    features = sorted(features)
    for i in range(len(features)):

        df.loc[key,'feature_'+str(i)] = features[i]
    """
features_used = list(set(all_features_used))
for feature in features_used:
    df[feature] = 0
    for key, values in df.iterrows():
        if feature in df.loc[key, 'features']:
            df.loc[key, feature] = 1

print(df)

result_features = []
for feature in features_used:

    group = list(df.groupby(by=feature))[1]

    group = group[1]['percent_return']

    result_features.append([feature, len(group), group.mean()])

result_df = pd.DataFrame(result_features, columns = ['features', 'num_in_group', 'means'])
result_df = result_df.sort_values(by=['means'])
print(result_df)
overall_average = result_df['means'].mean()
best_features = sorted( result_df[result_df['means']>overall_average]['features'].values )
print(best_features)
#result_df.to_csv('best_features.csv')


import obspy
import os
from obspy.core import UTCDateTime
from obspy.io.sac import sactrace

sac_dir=input("PLEASE, enter name of directory containing your sac files:")

sac_files=[os.path.join(sac_dir,sf) for sf in os.listdir(sac_dir) if os.path.isfile(os.path.join(sac_dir,sf))]
catalog=obspy.core.event.Catalog()
#print(sac_files)
#st=obspy.read(pathname_or_url=sfiles)#,format='SAC') #read sac_file to obspy stream
#leave only sac trace files in the file lise:
for sf in sac_files:
   try:
     st=obspy.read(sf,format='SAC')
   except obspy.io.sac.util.SacIOError:
     print('File ',sf,'is not sac trace file, probably response file. Skipping.')
     sac_files.remove(sf)

#read sac headers
for sf in sac_files:
   sac_head=sactrace.SACTrace.read(sf,headonly=True) #sac header
   #extract event info
   if len(catalog)==0: #catalog is empty
    ev_name=sac_head.kevnm #sac event name as resource_id
    #generate Origin from
    #sac_head.o
    #sac_head.evla
    #sac_head.evlo
    #sac_head.evdp
    Origin=obspy.core.event.origin.Origin(time=UTCDateTime(sac_head.reftime+sac_head.o), longitude=sac_head.evlo, latitude=sac_head.evla, depth=sac_head.evdp)
    Magnitude=obspy.core.event.magnitude.Magnitude(mag=sac_head.mag)
    event=obspy.core.event.Event(resource_id=obspy.core.event.ResourceIdentifier(id=ev_name), origins=[Origin],magnitudes=[Magnitude])
    catalog=obspy.core.event.Catalog(events=[event])
   #check if event exists...
   else:
    if not (UTCDateTime(sac_head.reftime+sac_head.o) in [e.origins[0].time for e in catalog] and
       sac_head.evlo in [e.origins[0].longitude for e in catalog]   and
       sac_head.evla in [e.origins[0].latitude for e in catalog] and
       sac_head.evdp in [e.origins[0].depth for e in catalog] and
       sac_head.mag in [e.magnitudes[0].mag for e in catalog]):
    #if not (orig==Origin and magn==Magnitude):     not working probably due to resource_id....
      orig=obspy.core.event.origin.Origin(time=UTCDateTime(sac_head.reftime+sac_head.o), longitude=sac_head.evlo, latitude=sac_head.evla, depth=sac_head.evdp)
      magn=obspy.core.event.magnitude.Magnitude(mag=sac_head.mag)
      ev2=obspy.core.event.Event(resource_id=obspy.core.event.ResourceIdentifier(id=sac_head.kevnm), origins=[orig],magnitudes=[magn])
      catalog.append(ev2)

print('Found ',len(catalog),' events in sac files in directory: ',sac_dir)

#extract picks and add to first event in catalog #WARNING FOR CATALOGS LONGER THAN 1 THIS IS OMITTED
print('Obtaining picks:')
if len(catalog)==1:
   event=catalog[0]
   picks=[]
   for sf in sac_files:
       sac_head=sactrace.SACTrace.read(sf,headonly=True) #read sac header
       wfid=obspy.core.event.WaveformStreamID(network_code=sac_head.knetwk,station_code=sac_head.kstnm,channel_code=sac_head.kcmpnm) #prepare waveform_id for stream identification
       if not sac_head.a==None: #if not empty -> associate as P pick'
          print('Adding pick found in sac.header.a as P from ',wfid.get_seed_string())
          pick=obspy.core.event.origin.Pick(time= sac_head.reftime+sac_head.a, waveform_id=wfid,phase_hint='P')
          picks.append(pick)
       if not sac_head.t0==None: #if not empty -> associate as S pick'
       	  print('Adding pick found in sac.header.t0 as S from ',wfid.get_seed_string())
          pick=obspy.core.event.origin.Pick(time= sac_head.reftime+sac_head.t0, waveform_id=wfid,phase_hint='S')
          picks.append(pick)
   event.picks=picks #append picks to event
   print('Adding nodal planes to event:')
   print(event.origins[0])
   #input in str,dp,rk on 1 line
   str1, dip1, rake1=input('PLEASE, enter strike,dip,rake of nodal plane 1:').split()
   str2, dip2, rake2=input('PLEASE, enter strike,dip,rake of nodal plane 2:').split()
   nodals1=obspy.core.event.source.NodalPlane(strike=str1,dip=dip1,rake=rake1) #generate NP object for first NP
   nodals2=obspy.core.event.source.NodalPlane(strike=str2,dip=dip2,rake=rake2) #generate NP object for second NP

   event.focal_mechanisms=[obspy.core.event.source.FocalMechanism(nodal_planes=obspy.core.event.source.NodalPlanes(nodal_plane_1=nodals1,nodal_plane_2=nodals2))] #associate NP info to focal mechanism of event
   catalog[0]=event #rewrite in catalog with added info
#print(event)
#Write quake ML file
print('Writing QUAKEML file')
outfile=input('please, enter name of quakeml file:')#'quake.ml'
if outfile=='': #if no file name from user use default:
  outfile='quake.ml'
catalog.write(filename=outfile,format='QUAKEML')


input()
l = list(map(int,input().split()))
maxh = l.index(max(l))
cur = maxh
ans = 0
while cur> 0:
    t = l[0:cur].index(max(l[0:cur]))
    ans += l[t]*(cur-t)-sum(l[t:cur])
    cur = t
cur = maxh
while cur< len(l)-1:
    t = l[cur+1:].index(max(l[cur+1:]))+cur+1
    ans += l[t]*(t-cur)-sum(l[cur+1:t+1])
    cur = t
print(ans)


import requests_with_caching
import json

def get_movie_data(s):
    endpoint = 'http://www.omdbapi.com/'
    param = {}
    param['t'] = s
    param['r'] = 'json'
    res = requests_with_caching.get(endpoint, params=param)

    return res.json()
print(get_movie_data("Deadpool 2"))

def get_movie_rating(dic):
    rate = dic['Ratings']
    for dic_item in rate:
        if dic_item['Source'] == 'Rotten Tomatoes':
            return int(dic_item['Value'][:-1])
    return 0

# some invocations that we use in the automated tests; uncomment these if you are getting errors and want better error messages
# get_movie_rating(get_movie_data("Deadpool 2"))


from cryptography.fernet import Fernet
import argparse

def banner():
    print('''
+-----------------------------------------------+
| magicave file encryptor                       |
| magicave v.0.1                                |
| Author: Elvin --> 'elvinsl'                   |
| Github: https://github.com/elvinsl/magicave   |
+-----------------------------------------------+
    ''')

class EncDec:
    @classmethod
    def generate(cls, file):
        f = Fernet.generate_key()
        with open(file, 'wb') as key_file:
            key_file.write(f)

    @classmethod
    def encrypt(cls, file, key_file):
        key = open(key_file, 'rb').read()
        f = Fernet(key)
        with open(file, 'rb') as normal_file:
            file_data = normal_file.read()
        enc_data = f.encrypt(file_data)
        with open(file, 'wb') as normal_file:
            normal_file.write(enc_data)

    @classmethod
    def decrypt(cls, file, key_file):
        key = open(key_file, 'rb').read()
        f = Fernet(key)
        with open(file, 'rb') as enc_file:
            enc_data = enc_file.read()
        dec_data = f.decrypt(enc_data)
        with open(file, 'wb') as enc_file:
            enc_file.write(dec_data)

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--file', dest='file',
                        help='File to encrypt or decryp')
    parser.add_argument('-k', '--key', dest='key',
                        help='Key to encrypt or decrypt')
    parser.add_argument('-e', '--encrypt', dest='enc',
                        help='Encrypt the file with given key', action='store_true')
    parser.add_argument('-d', '--decrypt', dest='dec',
                        help='Decrypt the file with given key', action='store_true')
    parser.add_argument('-g', '--generate', dest='generate',
                        help='Generate new key file')
    dest_value = parser.parse_args()
    return dest_value

args = get_args()
banner()

if args.generate:
    EncDec().generate(args.generate)
elif args.dec and args.file and args.key:
    EncDec().decrypt(args.file, args.key)
elif args.enc and args.file and args.key:
    EncDec().encrypt(args.file, args.key)
else:
    print('''
Usage: '--help' for more info
Generate Key: python3 magicave.py --generate key.txt
Encrypt File: python3 magicave.py --encrypt --file <file> --key <key>
Encrypt File: python3 magicave.py --decrypt --file <file> --key <key>
    ''')


import os
import cv2
#import json
import numpy as np
#from matplotlib import pyplot as plt
#from matplotlib import figure

# #scikit image
from skimage import io
#from skimage.color import rgb2gray
#from skimage.filters import threshold_otsu
# from skimage.feature import (match_descriptors, corner_harris,
#                              corner_peaks, ORB, plot_matches)
#from skimage.morphology import remove_small_holes, remove_small_objects
from skimage.measure import label, regionprops

# scikit learning
#from sklearn.cluster import MeanShift, estimate_bandwidth
from function_shape_extract import feature_extract, feature_extract2, feature_extract3,  get_compare_imgs
from function_PreProcessTestImg import PreProcessTestImg
import time

# moments
from scipy.spatial import distance as dist
from ZernikeMoments import describe_shapes

fixed_dict_37class = {}   # dictionary for goldan name
list_37class = []         # list for goldan feature
Results_DIR = "./Results/"
Result_txt_path = Results_DIR+"RESULT.txt"
Result2_txt_path = Results_DIR+"RESULT2.txt"

match_sum = 0
match_number = 0
final_candidate_number = 0

def feature_compare(test_path, dict_goaldan):

    fo_2 = open( Result2_txt_path, "a" )

    fo_2.write( "FileName = "+ os.path.basename(test_path) +"\n")
    fo_2.write( "Total candicates is " + str(len(dict_goaldan)) + "\n")

    goldenpath = '../37class_img/37class_rotate/hor_name/' #can't have chinese name in path
    in_img = cv2.imread(test_path)
    in_crop_img = feature_extract2(in_img)
    in_h,in_w = in_crop_img.shape[:2]
    print(in_w,in_h)

    MSE_array = np.zeros([len(dict_goaldan),2], dtype=np.float64)

    MSE_idx_name = []
    idx = 0
    for key,values in dict_37class.items():
        #ody, ext = os.path.splitext(os.path.basename(values))
        file_name = goldenpath + 'hor180_' + str(values)
        print(file_name)
        img = cv2.imread(file_name)
        height, width = img.shape[:2]
        #img = cv2.resize(img, (int(width/2), int(height/2)), interpolation=cv2.INTER_LINEAR)
        #height, width = img.shape[:2]

        img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        _, contours, hierarchy = cv2.findContours(img_gray,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
        cnt = contours[0]
        rect = cv2.minAreaRect(cnt)
        x,y = rect[0]  # center
        w,h = rect[1]   # width height here is some problem
        if h > w: # find long side is width
            t = w
            w = h
            h = t
        #print('W',h,w)
        left_x = x-w/2+1
        left_y = y-h/2+1

        # crop golden object
        s_x = int(left_x)
        s_y = int(left_y)
        e_x = int(s_x+w)
        e_y = int(s_y+h)

        crop_img = img_gray[s_y:e_y, s_x:e_x]
        #cv2.imshow('goldan_ori', crop_img)
        cp_h,cp_w = crop_img.shape[:2]
        print("goaldan image crop image size",(cp_w,cp_h))

        B = cv2.resize(crop_img, (int(cp_w*in_w/cp_w), int(cp_h*in_w/cp_w)), interpolation=cv2.INTER_LINEAR)
        A = in_crop_img
        cp_h,cp_w = B .shape[:2]
        #cv2.imshow('goldan_resize', B)
        if cp_h > in_h :
            edge = int((cp_h-in_h)/2)
            A = cv2.copyMakeBorder(A,edge,edge,0,0,cv2.BORDER_CONSTANT,value=[0,0,0])
        else:
            edge = int((in_h-cp_h)/2)
            B = cv2.copyMakeBorder(B,edge,edge,0,0,cv2.BORDER_CONSTANT,value=[0,0,0])

        A_img, B_img0 = get_compare_imgs(A,B)
        sse0 = np.square(np.subtract(A_img, B_img0)).mean() #sum of square error
        # 180 degree
#        h,w = B_img0.shape[:2]
#        M = cv2.getRotationMatrix2D((w/2, h/2), 180, 1)
#        B_img1 = cv2.warpAffine(B_img0, M, (w, h))
        B_img1 = cv2.flip(B_img0, 1)
        sse1 = np.square(np.subtract(A_img, B_img1)).mean()
        #cv2.imshow('ori', A_img)
        #cv2.imshow('goldan1', B_img0)
        #cv2.imshow('goldan2', B_img1)
        #cv2.waitKey(0)
        print('idx:%02d,SSE0:%d,SSE2:%d' %(idx,sse0,sse1))
        MSE_array[idx,0] = sse0
        MSE_array[idx,1] = sse1
        fo_2.write( "candidate = "+ str(values) +", MSE1: "+ str(sse0) +", MSE2: "+ str(sse1)+";\n")
        MSE_idx_name.append(values)
        idx += 1
    #fo_2.write( "**********************************************************\n")

    similiar_idx = int(MSE_array.argmin()/2)
    print(similiar_idx)
    #find_idx = MSE_array.argmin()
    file_name = goldenpath + 'hor180_' + str(MSE_idx_name[similiar_idx])
    ans_img = cv2.imread(file_name)

    fo_2.write( "Shape compare ans : " + str(os.path.basename(file_name)) + "\n")
    fo_2.write(str(time.time() - process_start_time)+ "\n")
    fo_2.write( "**********************************************************\n")
    fo_2.close()
    body, ext = os.path.splitext(os.path.basename(test_path))
    cv2.imwrite(Results_DIR+body+"_ans.png", ans_img)
    return ans_img

#====== Load feature for goldan model ======#
model_features = open("../37class_img/RESULT/modelFeatures.txt", "r")
idx = 0
for line in model_features.readlines():
    line = ''.join(line).strip('\n')
    features = line.split(',')
    fixed_dict_37class[idx] = features[0]

    #moment
    features_set_moment = ()
    for i in range(len(features)):
        if(i <= 3):
            continue
        features_set_moment = features_set_moment + (float(features[i]),)

    features_set = (float(features[1]), float(features[2]), int(features[3]), [ np.array(features_set_moment).flatten() ])
    list_37class.append(features_set)
    idx +=1

print(fixed_dict_37class)
print(list_37class)
#fo = open( Result_txt_path, "w" )
#fo.write( "Total candicates is " + str(len(fixed_dict_37class)) + "\n")
#fo.close()

#====== Compare features for test image and goaldan image ======#
MODEL_DIR = "./Src/"  #
TESTMODEL_DIR = "./BW/"
fo = open( Result_txt_path, "w" )
fo.close()
fo_2 = open( Result2_txt_path, "w" )
fo_2.close()

for modelname in os.listdir( MODEL_DIR ):
    dict_37class = fixed_dict_37class.copy() # get goaldan model

    fo = open( Result_txt_path, "a" )
    global process_start_time
    process_start_time = time.time()
    fo.write( "Total candicates is " + str(len(dict_37class)) + "\n")

    # Check test image is png file
    if modelname.find('.jpg') == -1:
        print("Log: "+modelname+" not jpg")
        continue
    print("Log: "+modelname)

    modelpath = MODEL_DIR + modelname
    ori_img = io.imread( modelpath )

    img_model = PreProcessTestImg(ori_img)
    io.imsave( TESTMODEL_DIR+modelname, img_model )

    #moment
    #img_moment = cv2.imread(img_model)
    #calculate zernike moment, Second parameter must be false
    img_moment = img_model.astype('uint8')
    shapeFeatures = describe_shapes(img_moment, False)
    #print(shapeFeatures)

    #=======  extract Test image feature vector =======#
    label_img = label( img_model )
    regions = regionprops( label_img )
    test_name = modelname

    # inter hole
    cnts = label_img.astype('uint8')
    imgbinary ,contours,hierarchy = cv2.findContours(cnts,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)

    # Solidity,axis ratio, moment
    test_feature = (regions[0].solidity, (regions[0].major_axis_length/regions[0].minor_axis_length), int(len(contours)-1), shapeFeatures)
    fo.write( "FileName = "+ test_name +", features: "+ str(test_feature) +"\n")

    #======= Start using Compare feature (test and goldan) ######
    tmp_dict = {}
    '''
    ####### axis ratio #######
    for key,values in dict_37class.items():
        model_feature = list_37class[int(key)]
        error = abs(model_feature[0]-test_feature[0])  # absolute error
        tmp_dict[key] = error

    # sort and filter by error
    delet_num = 0
    for key,values in sorted(tmp_dict.items(), key=lambda item:item[1], reverse=True):
        print("# ", values , dict_37class[key])
        del dict_37class[key]
        if(delet_num+1>=(len(dict_37class))):  #  50% out
            break
        else:
            delet_num+=1
    tmp_dict.clear()
    fo.write( "After axisRatio candicates is " + str(len(dict_37class)) + "\n")
    '''
    ####### inter hole #######
    for key,values in dict_37class.items():
        model_feature = list_37class[int(key)]
        error = abs(model_feature[2]-test_feature[2])  # absolute error
        tmp_dict[key] = error

    # sort and filter by error
    delet_num = 0
    for key,values in sorted(tmp_dict.items(), key=lambda item:item[1], reverse=True):
        print("## ", values, dict_37class[key])
        if(values<=3):  # delete error more than 3
            break
        else:
            del dict_37class[key]
    tmp_dict.clear()
    fo.write( "After internal holes candicates is " + str(len(dict_37class)) + "\n")

    ####### Solidity #######
    for key,values in dict_37class.items():
        model_feature = list_37class[int(key)]
        error = abs(model_feature[1]-test_feature[1])  # absolute error
        tmp_dict[key] = error

    # sort and filter by error
    delet_num = len(dict_37class)*0.75
    delet_count = 0
    for key,values in sorted(tmp_dict.items(), key=lambda item:item[1], reverse=True):
        print("## ", values, dict_37class[key])
        if(delet_count+1>=delet_num):  # 75% out
            break
        else:
            del dict_37class[key]
            delet_count+=1
    tmp_dict.clear()
    fo.write( "After solidity candicates is " + str(len(dict_37class)) + "\n")

    ####### Moment #######
    for key,values in dict_37class.items():
        model_feature = list_37class[int(key)]
        # Calculate Euclidean Distance
        D = dist.cdist(model_feature[3], test_feature[3])
        error = D[0] # error of euclidean distance
        tmp_dict[key] = error

    # sort and filter by error
    delet_num = len(dict_37class)*0.6
    delet_count = 0
    for key,values in sorted(tmp_dict.items(), key=lambda item:item[1], reverse=True):
        print("## ", values, dict_37class[key])
        if(delet_count+1>=delet_num):
            break
        else:
            del dict_37class[key]
            delet_count+=1
    tmp_dict.clear()
    fo.write( "After moment candicates is " + str(len(dict_37class)) + "\n")

    ####### Output candidates item #######
    for key,values in dict_37class.items():
        #fo.write( "candidate = "+ str(values) +", features: "+ str(list_37class[int(key)]) +";\n")
        if(str(values) == test_name):
            match_number += 1
        fo.write( "candidate = "+ str(values) +", features: "+ str(list_37class[int(key)]) +";\n")

    final_candidate_number = len(dict_37class.items())
    match_sum += 1

    fo.write( "**********************************************************\n")
    fo.close()

    '''
    ####### shape compare part #######
    output_img = feature_compare(modelpath, dict_37class)
    body, ext = os.path.splitext(modelname)
    cv2.imwrite(Results_DIR+body+".png", ori_img)
    '''

print ("final candidate number: " + str(final_candidate_number))
print ("accuracy: " + str(match_number/match_sum))
fo.close()


import numpy as np
import tensorflow as tf
import pandas as pd

import matplotlib.pyplot as plt

df = pd.read_csv("lrTest.csv")

X = df.iloc[:,0:2]
X = np.array(X)
X = X.astype(float)
X = X/20
print("dataframe of X is: ")
print(X)

Y = df.iloc[:,2:3]
Y = np.array(Y)
Y = Y.astype(float)
Y = Y/20
print("dataframe of Y is: ")
print(Y)

# get the liens before 16 as training set
X_train, Y_train = X[:15], Y[:15]
print("dataframe of x_train is: ")
print(X_train)

print("dataframe of y_train is: ")
print(Y_train)

# get the line after 16 as testing set
X_test, Y_test = X[15:],Y[15:]
print("dataframe of x_test is: ")
print(X_test)

print("dataframe of y_test is: ")
print(Y_test)

# construct the models
model = tf.keras.models.Sequential(
    [tf.keras.layers.Dense(64, activation=tf.nn.relu),
     tf.keras.layers.Dense(64, activation=tf.nn.relu),
     tf.keras.layers.Dense(1)
     ])

optimizer = tf.keras.optimizers.RMSprop(0.001)

model.compile(loss='mean_squared_error',
              optimizer=optimizer,
              metrics=['mean_absolute_error', 'mean_squared_error'])

# epochs: iteration times
# batch_size: divide the data into batch and train these batch during the training process
model.fit(X_train,Y_train,epochs=5,batch_size=15)

prediction = model.predict(X_test, batch_size = 1)

print(prediction*20)


import os
import argparse
import time
import sqlite3
import uuid

import warnings
warnings.filterwarnings("ignore")

import numpy as np

from fingerprint import fingerprint_file, read_audio_file, fingerprint_audio
from recognize import recognize_song, get_matches, best_match, get_info_for_song_id

def str2bool(v):
    if isinstance(v, bool):
        return v
    if v.lower() in ('yes', 'true', 't', 'y', '1'):
        return True
    elif v.lower() in ('no', 'false', 'f', 'n', '0'):
        return False
    else:
        raise argparse.ArgumentTypeError('Boolean value expected.')

def get_args():
    parser = argparse.ArgumentParser()

    parser.add_argument("--db_path", type=str, default=None)
    parser.add_argument("--query_song", type=str, default=None)
    parser.add_argument("--song_mode", type=str2bool, default=True)
    parser.add_argument("--sample_rate", type=int, default=44100)
    parser.add_argument("--fft_window_size", type=float, default=0.2)
    parser.add_argument("--peak_box_size", type=int, default=30)
    parser.add_argument("--point_efficiency", type=float, default=0.8)
    parser.add_argument("--target_t", type=float, default=1.8)
    parser.add_argument("--target_f", type=int, default=4000)
    parser.add_argument("--target_start", type=float, default=0.05)

    args = parser.parse_args()

    return args

if __name__ == '__main__':
    args = get_args()

    db_path = args.db_path
    query_song = args.query_song
    song_mode = args.song_mode
    sample_rate = args.sample_rate
    fft_window_size = args.fft_window_size
    peak_box_size = args.peak_box_size
    point_efficiency = args.point_efficiency
    target_t = args.target_t
    target_f = args.target_f
    target_start = args.target_start

    assert 0. < fft_window_size < 1.
    assert 0. < point_efficiency <= 1.

    if song_mode:
        song = recognize_song(filename=query_song, db_path=db_path, sample_rate=sample_rate, fft_window_size=fft_window_size,
                              peak_box_size=peak_box_size, point_efficiency=point_efficiency, target_t=target_t,
                              target_f=target_f, target_start=target_start, threshold=5)
        print("Song mode, recognized song: {}".format(song))

    else:
        audio, sr = read_audio_file(audio_path=query_song, sr_desired=sample_rate)
        hashes = fingerprint_audio(frames=audio, sample_rate=sample_rate, fft_window_size=fft_window_size,
                                   peak_box_size=peak_box_size, point_efficiency=point_efficiency, target_t=target_t,
                                   target_f=target_f, target_start=target_start)
        matches = get_matches(hashes=hashes, db_path=db_path, threshold=5)
        matched_song = best_match(matches=matches)
        song = get_info_for_song_id(song_id=matched_song, db_path=db_path)

        print("Audio mode, recognized song: {}".format(song))


import os, shutil

episodes_titles = [
    "Uno","Mijo","Nacho","Hero","Alpine Shepherd Boy","Five-O","Bingo","Rico","Pimento","Marco",
        "Switch","Cobbler","Amarillo","Gloves Off","Rebecca","Bali Ha'i","Inflatable","Fifi","Nailed", "Klick"
        ,"Mabel","Witness","Sunk Costs","Sabrosito","Chicanery","Off Brand","Expenses","Slip","Fall", "Lantern"
        ,"Smoke","Breathe","Something Beautiful","Talk","Quite a Ride","Piñata","Something Stupid","Coushatta",
        "Wiedersehen", "Winner","Magic Man","50% Off","The Guy For This","Namaste","Dedicado a Max","Wexler v. Goodman","JMM","Bagman","Bad Choice Road", "Something Unforgivable"
        ]
#change to the path to where your Directory located
os.chdir('/home/omer358/Videos/Movies & Series/Series/Better Call Saul')
# A counter used to go through the episodes title list.
ep_title_count = 0
# Iterating through the current Directory and the subDirectory
for folderName, subfolders, filenames in sorted(os.walk('.')):
    # Iterating through each season Directory.
    for season in sorted(subfolders):
        # changing the dirctory to the season dirctory
        os.chdir(os.path.join(season))
        # This counter'll set to 1 for each new folder.
        ep_count = 1
        # Iterate through the episodes to change their names.
        for ep_name in sorted(os.listdir()):
            # format the new name.
            new_name = "Better_Call_Saul_{0}E{1}_{2}.mp4".format(
                        season,
                        ep_count,
                        episodes_titles[ep_title_count])
            # Print the new name
            print(shutil.move(ep_name,new_name))
            # Increase the counter by 1
            ep_count = ep_count+1
            # increase the counter by 1 to go to the next title
            ep_title_count = ep_title_count+1
        # go back to the previous directory
        os.chdir('..')


# -*- coding: utf-8 -*-
"""
Unittests

Things shared between unittests are defined here to keep code DRY.

.. author: Adrian Schlatter
"""

import ppf.datamatrix as put
import sys

# Datamatrix has the following encodings:
# TEXT, C40, X12, EDIFACT, BASE256
# TEXT and C40 both encode the entire ASCII character table (in a
# different way).
# X12 and EDIFACT are subsets of ASCII characters.
# BASE256 is the (binary) 8-bit alphabet.

ASCII = bytes(range(128)).decode('ascii')
EDIFACT = bytes(range(32, 95)).decode('ascii')
X12 = '\r*> 01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ'
BASE256 = bytes(range(256))

def msgs_from_alphabet(alphabet):
    """
    Creates test messages from alphabet

    Number of messages yielded is equal to length of alphabet. Length of
    messages varies from 0 to length of alphabet.
    """
    for i in range(len(alphabet)):
        if 2 * i > len(alphabet):
            msg = (alphabet[i:] +
                   alphabet[:2 * i - len(alphabet)])
        else:
            msg = alphabet[i:2 * i]

        yield msg

class Codec_Test(object):
    """
    Template class to test codec

    Create an actual test class by inheriting from this class and from
    unittest.TestCase. Make sure to customize class variables.
    """

    CODEC = 'name codec here'
    ALPHABET = 'list valid characters here'
    ALPHABET_ENC = b'what datamatrix-svg encodes ALPHABET to'
    KNOWN_PAIR = {'msg': 'A', 'enc': b'\x63'}
    CODEC_MODULE_NAME = 'codec_name'

    def test_consistency(self):
        """Verify that coding + decoding return the original message."""
        for msg in msgs_from_alphabet(self.ALPHABET):
            code = msg.encode(self.CODEC)
            decoded = code.decode(self.CODEC)
            self.assertEqual(decoded, msg)

    def test_raises(self):
        """Verify that error is raised for invalid code."""
        code = bytes([0])
        with self.assertRaises(ValueError):
            code.decode(self.CODEC)

    def test_encode_to_square_datamatrix(self):
        """Verify that encoding to square datamatrix works."""
        for msg in msgs_from_alphabet(self.ALPHABET):
            # assert that this does not raise:
            datamatrix = put.DataMatrix(msg)
            self.assertTrue(len(datamatrix.matrix) > 0)

    def test_encode_to_rect_datamatrix(self):
        """Verify that encoding to rectangular datamatrix works."""
        for msg in msgs_from_alphabet(self.ALPHABET):
            # assert that this does not raise:
            datamatrix = put.DataMatrix(msg, rect=True)
            m = datamatrix.matrix
            self.assertTrue(len(m) > 0)

    def test_encode_known(self):
        """Test single-char edifact encoding"""
        enc = self.KNOWN_PAIR['msg'].encode(self.CODEC)
        self.assertEqual(enc, self.KNOWN_PAIR['enc'])

    def test_encode_alphabet(self):
        """Encode entire alphabet and compare to datamatrix-svg."""
        enc = self.ALPHABET.encode(self.CODEC)
        self.assertEqual(enc, self.ALPHABET_ENC)

    def test_decode_invalid(self):
        """Try to decode invalid code."""

        code = 9 * b'\x00'
        with self.assertRaises(ValueError):
            code.decode(self.CODEC)

    def test_search_wrong_codec(self):
        """
        Test that search_codec callback returns None for non-matching
        codec.
        """

        full_mod_name = 'ppf.datamatrix.' + self.CODEC_MODULE_NAME
        __import__(full_mod_name)
        codec_mod = sys.modules[full_mod_name]
        self.assertTrue(codec_mod.search_codec('invalid') is None)


#!/usr/bin/env python3

a = {3,14,15,9,26,5,35,9}
b = {60, 22, 14, 0, 9}

Diff = a - b
Shared = a & b
Total = a | b
SymmDiff = a ^ b

print(Diff)
print(Shared)
print(Total)
print(SymmDiff)


#OnnoRokom SMS Website For Registration - https://onnorokomsms.com
import requests

# BASE URL
URL = 'https://api2.onnorokomsms.com/HttpSendSms.ashx'
#All Options Params
op              = 'NumberSms' #Request Method (Change as your requirement)
apiKey          = '' #API Key
smsText         = '' #SMS Text
mobile          = '' #Recipient Mobile Number (Single and Multiple Number Support (Comma Sperated) )
type            = 'TEXT' #SMS Type
maskName        = ''
campaignName    = ''

# data to be sent to api
PARAMS = {
    'op'            : op,
    'apiKey'        : apiKey,
    'smsText'       : smsText,
    'mobile'        : mobile,
    'type'          : type,
    'maskName'      : maskName,
    'campaignName'  : campaignName
}
# sending post request and saving response
res = requests.post(url = URL, data=PARAMS)
data = res.text
# Response Print
print("SMS Response: ", data)


import sys
from collections import defaultdict

words_dict = defaultdict(int)

for line in sys.stdin:
    words = line.rstrip("\n").split()
    for word in words:
        words_dict[word] += 1

print(len(words_dict.keys()))


import numpy as np
import matplotlib.pyplot as plt
import time
import math

def gaussian(x, sigma):
    """
    centered gaussian

    :param x:
    :param sigma:
    """

    return np.exp(-np.power(x, 2.) / (2 * np.power(sigma, 2.)))

def make_track(density = 0.05, ellipse_shape = (40, 24),
        bumps = [(0.05, 0.5), (0.4, 0.75), (0.65, 0.995)], track_width = 1,
        bump_scale=20, gauss_range=5, sigma=0.6
    ):
    """
    Creates 3 sets of 2D points defining a closed track

    :param density: point density
    :param ellipse_shape: length of the major & minor axis (stretching)
    :param bumps: list of 2-tuples, location of bumps (deformations) on the track e.g. [(0, 0.2)] = a single bump at the beginning.
        Values between 0 & 1.

    :param track_width: distance between corresponding inner & outer points
    :param bump_scale: the "size" of the bump
    :param sigma: gauss sigma

    :returns: 3-tuple -> points on the center line, points on the inside of track, points on the outside of the track
    """

    N_POINTS = 2000

    points = np.zeros((N_POINTS, 2))
    u, v = ellipse_shape

    for i in range(N_POINTS):
        angle = i/N_POINTS * 2*math.pi
        points[i] = [u * math.cos(angle), v * math.sin(angle)]

    for start, stop in bumps:
        start = int(start * N_POINTS)
        stop = int(stop * N_POINTS)

        sample = points[start:stop, :]
        size = stop - start
        middle = points[start + int(size /2), :]
        middle = middle / np.linalg.norm(middle)

        for i in range(stop-start):
            x = gauss_range * (i - size/2) / size
            shift = bump_scale * middle * gaussian(x, sigma)
            sample[i] = sample[i] - shift

        points[start:stop, :] = sample

    points_inner = np.zeros((N_POINTS, 2))
    points_outer = np.zeros((N_POINTS, 2))

    for i in range(N_POINTS - 1):
        a = points[i, :]
        b = points[i+1, :]

        p1, p2 = perpendicular_points(a, b, width=track_width)
        points_inner[i] = p1
        points_outer[i] = p2

    p1, p2 = perpendicular_points(points[-1, :], points[0, :], width=track_width)
    points_inner[-1] = p1
    points_outer[-1] = p2

    step = int(N_POINTS / (density * N_POINTS))

    return points[::step], points_inner[::step], points_outer[::step]

def perpendicular_points(a, b, width=1):
    """
    Creates two points perpendicular to the vector joining a & b

    :param a: 2D point on the centerline
    :param b: 2D point on the centerline
    :param width=1: the track width
    """

    x1, y1 = a
    x2, y2 = b

    vec = [x2-x1, y2-y1]
    perp = [-vec[1], vec[0]]
    perp = np.array(perp)
    perp = perp / np.linalg.norm(perp)

    p1 = a + width*perp
    p2 = a - width*perp

    return p1, p2

if __name__ == '__main__':
    center, inner, outer = make_track()

    # center, inner, outer = make_track(bumps=[(0.1, 0.5), (0.6, 0.9)])

    # center, inner, outer = make_track(bumps=[(0.5, 0.9)], sigma=0.5, bump_scale=25)

    # plt.scatter(center[:, 0], center[:, 1], s=1)
    plt.scatter(inner[:, 0], inner[:, 1], s=1)
    plt.scatter(outer[:, 0], outer[:, 1], s=1)
    plt.axis('equal')
    plt.show()

    # save the track
    # np.save('center.npy', center)
    # np.save('inner.npy', center)
    # np.save('outer.npy', center)