import pandas as pd
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
import plotly.express as px

df = pd.read_csv("https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DS0321EN-SkillsNetwork/datasets/spacex_launch_dash.csv")

max_payload = df['Payload Mass (kg)'].max()
min_payload = df['Payload Mass (kg)'].min()

def filter_payload_range(df, min_val, max_val):
    return df[(df['Payload Mass (kg)'] > min_val) & (df['Payload Mass (kg)'] < max_val)]

app = dash.Dash(__name__)

app.layout = html.Div(children = [
    html.H1('SpaceX Launch Records Dashboard',
            style = {'textAlign': 'center',
                     'color': '#503D36',
                     'font-size': 40}),
    dcc.Dropdown(
        id='site-dropdown',
        options=[
            {'label': "All Sites", 'value': 'ALL'},
            {'label': 'CCAFS LC-40', 'value': 'CCAFS LC-40'},
            {'label': 'VAFB SLC-4E', 'value': 'VAFB SLC-4E'},
            {'label': 'KSC LC-39A', 'value': 'KSC LC-39A'},
            {'label': 'CCAFS SLC-40', 'value': 'CCAFS SLC-40'}
            ],
        value = 'ALL',
        placeholder = "Select a location...",
        searchable = True
        ),

    dcc.Graph(id='success-pie-chart'),

    dcc.RangeSlider(id='payload-slider',
                    min = 0, max=10000, step=100,
                    marks = {0: '0',
                             2500: '2500',
                             5000: '5000',
                             7500: '7500',
                             10000: '10000'},
                    value = [min_payload, max_payload]),
    dcc.Graph(id='success-payload-scatter')
    ])

@app.callback(
    Output(component_id='success-pie-chart', component_property='figure'),
    Input(component_id='site-dropdown', component_property='value')
    )
def get_pie_chart(site):
    filtered_df = df[df['Mission Outcome'] == 'Success']
    if site == 'ALL':
        fig = px.pie(df,
                     names=df['Launch Site'],
                     values=df['class'],
                     title = 'All Sites')
        return fig
    else:
        site_df = df[df['Launch Site'] == site]
        fig = px.pie(site_df,
                     names=site_df['class'],
                     title = site)
        return fig

@app.callback(
    Output(component_id='success-payload-scatter', component_property='figure'),
    Input(component_id='site-dropdown', component_property='value'),
    Input(component_id='payload-slider', component_property='value')
    )
def get_payload_scatter(site, payload_range):
    if site == 'ALL':
        filtered_df = filter_payload_range(df, payload_range[0], payload_range[1])
        fig = px.scatter(filtered_df,
                         x = 'Payload Mass (kg)',
                         y = 'class',
                         color = 'Booster Version Category',
                         title = "Correlation between Payload and Success for all sites")
        return fig
    else:
        site_df = df[df['Launch Site'] == site]
        filtered_df = filter_payload_range(site_df, payload_range[0], payload_range[1])
        print(filtered_df.head())
        fig = px.scatter(filtered_df,
                         x = 'Payload Mass (kg)',
                         y = 'class',
                         color = 'Booster Version Category',
                         title = "Correlation between payload and success for {}".format(site))
        return fig

if __name__ == '__main__':
    app.run_server(debug=True)


#! /usr/bin/env python3

import configparser as CP
import os
import rospkg
import glob
import rospy
import os
import sys

import networkx as nx
from datetime import datetime
import subprocess
from art import *

start_time  = datetime.now()
no_of_bots = [1,3,6,9,12,15]
# no_of_bots = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
algos = ['iot_communication_network']
graphs = ['pipeline1','pipeline2','pipeline3']
iot_device_ranges = [1000]
dir_name = rospkg.RosPack().get_path('mrpp_sumo')
no_of_runs = 1
deploy_tag = 'graph'
# rospy.init_node('config_simulate')
for graph_name in graphs:
    graph_path = dir_name +'/graph_ml/'+ graph_name + '.graphml'
    graph_net = nx.read_graphml(graph_path)
    for run_id in range(no_of_runs):
        for algo_name in algos:
            how_many_iterations = 1
            if 'iot' in algo_name:
                how_many_iterations = len(iot_device_ranges)
            for idx in range(how_many_iterations):
                device_range = iot_device_ranges[idx]
                path = '{}/scripts/algorithms/partition_based_patrolling/deployment_results/{}/on_{}/{}m_range/'.format(dir_name,graph_name,deploy_tag,device_range)
                for filename in os.listdir(path):
                    no_of_base_stations = int(filename.split('_')[0])
                    for no_agents in no_of_bots:
                        sim_dir = '{}/post_process/{}/on_{}/{}m_range/{}_base_stations/{}_agents/run_{}/'.format(dir_name,graph_name,deploy_tag,device_range,no_of_base_stations,no_agents,run_id)
                        if not os.path.exists(sim_dir):
                            run_start_time = datetime.now()
                            init_locations = " ".join(list(graph_net.nodes())[0:no_agents])
                            os.system("xterm -e roscore & sleep 3")
                            rospy.set_param('/init_locations',init_locations)
                            rospy.set_param('/use_sim_time',True)
                            rospy.set_param('/gui',False)
                            rospy.set_param('/graph',graph_name)
                            rospy.set_param('/init_bots',no_agents)
                            rospy.set_param('done',False)
                            rospy.set_param('/sim_length',30000)
                            rospy.set_param('/algo_name',algo_name)
                            rospy.set_param('/no_of_deads',0)
                            rospy.set_param('/run_id',run_id)
                            rospy.set_param('/random_string','test')
                            rospy.set_param('/deploy_tag',deploy_tag)
                            rospy.set_param('/no_of_base_stations',no_of_base_stations)

                            if 'iot' in algo_name: rospy.set_param('/iot_device_range',iot_device_ranges[idx])
                            for name in rospy.get_param_names()[4:]:
                                print(name,':',rospy.get_param(name))

                            # subprocess.call(['terminator', '--layout', 'grid', '-x', cmd1, '-x', cmd2, '-x', cmd3])
                            os.system("xterm -e rosrun mrpp_sumo sumo_wrapper.py & sleep 3")
                            os.system("xterm -e rosrun mrpp_sumo "+ algo_name +".py & sleep 3")
                            os.system("xterm -e rosrun mrpp_sumo command_center.py")
                            os.system("sleep 10")
                            # os.system("killall xterm & sleep 3")

                            run_end_time = datetime.now()
                            print('Algorithm took', run_end_time-run_start_time)
                            print('─' * 100,'\n')

end_time  = datetime.now()
print('\n','StartTime:',start_time, '|EndTime:',end_time,'|Total Time taken:',end_time-start_time)
tprint("Please run  post_data_process.py script!!")


import pandas as pd
import numpy as np
import sklearn
import joblib
from sklearn.linear_model import LinearRegression
from flask import Flask,render_template,request

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')
@app.route('/predict',methods=['GET','POST'])
def predict():
    if request.method =='POST':
        print(request.form.get('Années'))
        print(request.form.get('Kilométrage'))
        print(request.form.get('Le nombre de chevaux'))

        try:
            var_1=float(request.form['Années'])
            var_2=float(request.form['Kilométrage'])
            var_3=float(request.form['Le nombre de chevaux'])
            pred_args=[var_1,var_2,var_3]
            pred_arr=np.array(pred_args)
            preds=pred_arr.reshape(1,-1)
            model=open("linear_regression_model.pkl","rb")
            lr_model=joblib.load(model)
            model_prediction=lr_model.predict(preds)
            model_prediction=round(float(model_prediction),2)
        except ValueError:
            return render_template('Erreur.html')
    return render_template('predict.html',prediction=model_prediction)

if __name__ == '__main__':
    app.run(debug=True)


import logging

from aws_gate.constants import (
    AWS_DEFAULT_PROFILE,
    AWS_DEFAULT_REGION,
    DEFAULT_OS_USER,
    DEFAULT_SSH_PORT,
    DEFAULT_KEY_ALGORITHM,
    DEFAULT_KEY_SIZE,
)
from aws_gate.decorators import (
    plugin_version,
    plugin_required,
    valid_aws_profile,
    valid_aws_region,
)
from aws_gate.query import query_instance
from aws_gate.session_common import BaseSession
from aws_gate.ssh_common import SshKey, SshKeyUploader
from aws_gate.utils import (
    get_aws_client,
    get_aws_resource,
    fetch_instance_details_from_config,
    get_instance_details,
)

logger = logging.getLogger(__name__)

class SshProxySession(BaseSession):
    def __init__(
        self,
        instance_id,
        ssm=None,
        region_name=AWS_DEFAULT_REGION,
        profile_name=AWS_DEFAULT_PROFILE,
        port=DEFAULT_SSH_PORT,
        user=DEFAULT_OS_USER,
    ):
        self._instance_id = instance_id
        self._region_name = region_name
        self._profile_name = profile_name if profile_name is not None else ""
        self._ssm = ssm
        self._port = port
        self._user = user

        self._session_parameters = {
            "Target": self._instance_id,
            "DocumentName": "AWS-StartSSHSession",
            "Parameters": {"portNumber": [str(self._port)]},
        }

@plugin_required
@plugin_version("1.1.23.0")
@valid_aws_profile
@valid_aws_region
def ssh_proxy(
    config,
    instance_name,
    user=DEFAULT_OS_USER,
    port=DEFAULT_SSH_PORT,
    key_type=DEFAULT_KEY_ALGORITHM,
    key_size=DEFAULT_KEY_SIZE,
    profile_name=AWS_DEFAULT_PROFILE,
    region_name=AWS_DEFAULT_REGION,
):
    instance, profile, region = fetch_instance_details_from_config(
        config, instance_name, profile_name, region_name
    )

    ssm = get_aws_client("ssm", region_name=region, profile_name=profile)
    ec2 = get_aws_resource("ec2", region_name=region, profile_name=profile)
    ec2_ic = get_aws_client(
        "ec2-instance-connect", region_name=region, profile_name=profile
    )

    instance_id = query_instance(name=instance, ec2=ec2)
    if instance_id is None:
        raise ValueError(f"No instance could be found for name: {instance}")

    az = get_instance_details(instance_id=instance_id, ec2=ec2)["availability_zone"]

    logger.info(
        "Opening SSH proxy session on instance %s (%s) via profile %s",
        instance_id,
        region,
        profile,
    )
    with SshKey(key_type=key_type, key_size=key_size) as ssh_key:
        with SshKeyUploader(
            instance_id=instance_id, az=az, user=user, ssh_key=ssh_key, ec2_ic=ec2_ic
        ):
            with SshProxySession(
                instance_id,
                region_name=region,
                profile_name=profile,
                ssm=ssm,
                port=port,
                user=user,
            ) as ssh_proxy_session:
                ssh_proxy_session.open()


from django.shortcuts import get_object_or_404, render
from .models import Comentarios, Cursos
from .forms import ComentarioContactoForm, CursosForm

# Create your views here.
def cursos(request):
    cursos=Cursos.objects.all()
    return render(request,"cursos/cursos.html",{'cursos':cursos})

def cursosComentario(request):
    return render(request,"cursos/contacto.html")

def comentarios(request):
    comentarios=Comentarios.objects.all()
    return render(request,'cursos/consultarComentarios.html',{'comentarios':comentarios})

def guardarComentario(request):
    if request.method == 'POST':
        form = ComentarioContactoForm(request.POST)
        if form.is_valid(): #si los datos recibidos son correctos
            form.save() #Inserta
            comentarios=Comentarios.objects.all()
            return render(request,'cursos/consultarComentarios.html',{'comentarios':comentarios})
    form = ComentarioContactoForm()
    #Si algo sale mal se reenvian al formulario losdatos ingresados
    return render(request,'cursos/contacto.html',{'form':form})

def eliminarComentarioContacto(request,idcomentario, confirmacion='cursos/confirmarEliminarCom.html'):
    comentario = get_object_or_404(Comentarios, idcomentario=idcomentario)
    if request.method == 'POST':
        comentario.delete()
        comentarios=Comentarios.objects.all()
        return render(request,'cursos/consultarComentarios.html',{'comentarios':comentarios})
    return render(request, confirmacion,{'object':comentario})

def editarComentarioContacto(request,idcomentario):
    comentario = get_object_or_404(Comentarios, idcomentario=idcomentario)
    form = ComentarioContactoForm(request.POST, instance=comentario)
    if form.is_valid():
        form.save()
        comentarios=Comentarios.objects.all()
        return render(request,"cursos/consultarComentarios.html",{'comentarios':comentarios})

    return render(request,'cursos/editarComentario.html',{'comentario':comentario})

def eliminarCurso(request,idcurso, confirmacion='cursos/confirmarEliminarCurso.html'):
    curso = get_object_or_404(Cursos, idcurso=idcurso)
    if request.method == 'POST':
        curso.delete()
        cursos=Cursos.objects.all()
        return render(request,'cursos/cursos.html',{'cursos':cursos})
    return render(request, confirmacion,{'object':curso})

def editarCurso(request,idcurso):
    curso = get_object_or_404(Cursos, idcurso=idcurso)
    form = CursosForm(request.POST, instance=curso)
    if form.is_valid():
        form.save()
        cursos=Cursos.objects.all()
        return render(request,"cursos/cursos.html",{'cursos':cursos})

    return render(request,'cursos/editarCursos.html',{'curso':curso})


import sys

from PyQt5 import QtCore, QtGui
from PyQt5 import QtWidgets
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem, QWidget, QPushButton, QVBoxLayout, QHBoxLayout, \
    QLabel, QMessageBox, QHeaderView
from qt_material import apply_stylesheet

from ui.custom_widgets.styled_widgets import StyledEdit

from utils.settings_handler import AppSettings

ru_text_to_key = {'й': 1049, 'ц': 1062, 'у': 1059, 'к': 1050, 'е': 1045, 'н': 1053, 'г': 1043,
                  'ш': 1064, 'щ': 1065, 'з': 1047, 'х': 1061, 'ъ': 1066, 'ф': 1060, 'ы': 1067, 'в': 1042, 'а': 1040,
                  'п': 1055, 'р': 1056, 'о': 1054, 'л': 1051, 'д': 1044, 'ж': 1046, 'э': 1069, 'я': 1071, 'ч': 1063,
                  'с': 1057, 'м': 1052, 'и': 1048, 'т': 1058, 'ь': 1068, 'б': 1041, 'ю': 1070}

eng_text_to_key = {'q': 81, 'w': 87, 'e': 69, 'r': 82, 't': 84, 'y': 89, 'u': 85, 'i': 73, 'o': 79,
                   'p': 80, '[': 91, ']': 93, 'a': 65, 's': 83, 'd': 68, 'f': 70, 'g': 71, 'h': 72, 'j': 74, 'k': 75,
                   'l': 76, ';': 59, "'": 39, 'z': 90, 'x': 88, 'c': 67, 'v': 86, 'b': 66, 'n': 78, 'm': 77, ',': 44,
                   '.': 46}

ru_to_eng = {k: v for k, v in zip(ru_text_to_key.keys(), eng_text_to_key.keys())}

def show_message(title, text):
    msgbox = QMessageBox()
    msgbox.setIcon(QMessageBox.Information)
    msgbox.setText(text)
    msgbox.setWindowTitle(title)
    msgbox.exec()

class ShortCutEdit(StyledEdit):
    def __init__(self, theme):
        super(ShortCutEdit, self).__init__(theme=theme)
        self.keymap = {}
        for key, value in vars(QtCore.Qt).items():
            if isinstance(value, QtCore.Qt.Key):
                self.keymap[value] = key.partition('_')[2]

        self.modmap = {
            QtCore.Qt.ControlModifier: self.keymap[QtCore.Qt.Key_Control],
            QtCore.Qt.AltModifier: self.keymap[QtCore.Qt.Key_Alt],
            QtCore.Qt.ShiftModifier: self.keymap[QtCore.Qt.Key_Shift]
        }

        self.command = None
        self.ru_text_to_key = {}
        self.eng_text_to_key = {}

    def keyevent_to_string(self, event, convert_ru_to_eng=False):
        sequence = []
        modifiers = []
        for modifier, cmd in self.modmap.items():
            if event.modifiers() & modifier:
                cmd_converted = self.convert_shortcut_to_pyqt(cmd)
                sequence.append(cmd_converted)
                modifiers.append(cmd_converted)

        key = self.keymap.get(event.key(), event.text())
        key = self.convert_shortcut_to_pyqt(key)

        e_key = None
        if key not in sequence:
            if key.lower() in ru_text_to_key and convert_ru_to_eng:
                ru_key = key.lower()
                eng_key = ru_to_eng[ru_key]
                sequence.append(eng_key.upper())
                e_key = eng_text_to_key[eng_key]
            else:
                sequence.append(key)
                e_key = event.key()

        appearance = '+'.join(sequence)
        self.command = {'appearance': appearance, 'key': e_key, 'modifiers': modifiers}
        return appearance

    def convert_shortcut_to_pyqt(self, sc):

        maps = {'Control': 'Ctrl', 'Period': '.', 'Comma': ',', 'Minus': '-', 'Equal': '+', 'Plus': '+',
                'BraceLeft': '[', 'BraceRight': ']', 'PageUp': 'PgUp', 'PageDown': 'PgDown',
                'Slash': '/', 'Apostrophe': "'", 'Semicolon': ";"}
        for k, v in maps.items():
            if k in sc:
                sc = sc.replace(k, v)

        return sc

    def append_to_ru(self, text, key):
        ru_letters = set('Ё!"№;%:?*()_+йцукенгшщзхъфывапролджэячсмитьбю.')
        if text in ru_letters and text not in self.ru_text_to_key:
            self.ru_text_to_key[text] = key

    def append_to_eng(self, text, key):
        eng_letters = set("~!@#$%^&*()_+qwertyuiop[]asdfghjkl;'zxcvbnm,./")
        if text in eng_letters and text not in self.eng_text_to_key:
            self.eng_text_to_key[text] = key

    def keyPressEvent(self, e: QtGui.QKeyEvent) -> None:
        self.setText(self.keyevent_to_string(e, convert_ru_to_eng=True))

    def get_command(self):
        return self.command

class ShortCutInputDialog(QWidget):

    def __init__(self, parent, title_name, question_name, placeholder="", min_width=300):
        super().__init__(parent)
        self.setWindowTitle(f"{title_name}")
        self.setWindowFlag(QtCore.Qt.Tool)

        self.settings = AppSettings()
        self.lang = self.settings.read_lang()

        self.label = QLabel(f"{question_name}")
        self.edit = ShortCutEdit(theme=self.settings.read_theme())
        self.edit.setPlaceholderText(placeholder)

        btnLayout = QVBoxLayout()

        self.okBtn = QPushButton('Ввести' if self.lang == 'RU' else "OK", self)

        btnLayout.addWidget(self.okBtn)

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.label)
        self.mainLayout.addWidget(self.edit)
        self.mainLayout.addLayout(btnLayout)
        self.setLayout(self.mainLayout)
        self.setMinimumWidth(min_width)

    def getText(self):
        return self.edit.text()

    def getCommand(self):
        return self.edit.get_command()

class ShortCutsTable(QTableWidget):

    def __init__(self, parent=None, lang='RU', min_width=400, shortcuts=None):
        super(ShortCutsTable, self).__init__(parent)

        if shortcuts:
            self.setColumnCount(3)
            self.setRowCount(len(shortcuts))
            if lang == 'RU':
                self.setHorizontalHeaderLabels(['Key', 'Имя команды', 'Горячие\nклавиши'])
            else:
                self.setHorizontalHeaderLabels(['Key', 'Command', 'Shortcut'])
            self.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
            row = 0
            for k in shortcuts:
                self.setItem(row, 0, QTableWidgetItem(k))
                name_item = QTableWidgetItem(shortcuts[k]['name_ru'])
                name_item.setFlags(name_item.flags() & ~QtCore.Qt.ItemIsEditable)
                self.setItem(row, 1, name_item)
                appearance_item = QTableWidgetItem(shortcuts[k]['appearance'])
                appearance_item.setFlags(appearance_item.flags() & ~QtCore.Qt.ItemIsEditable)
                self.setItem(row, 2, appearance_item)
                row += 1

            self.setMinimumWidth(min_width)
            self.setColumnHidden(0, True)

class ShortCutsEditor(QWidget):

    def __init__(self, parent=None, on_ok_act=None, width_percent=0.5, height_percent=0.6):
        super(ShortCutsEditor, self).__init__(parent)

        self.settings = AppSettings()
        self.lang = self.settings.read_lang()
        self.icon_folder = self.settings.get_icon_folder()

        self.setWindowTitle("Настройки горячих клавиш" if self.lang == 'RU' else 'Shortcuts Settings')
        self.setWindowIcon(QIcon(self.icon_folder + "/keyboard.png"))
        self.setWindowFlag(QtCore.Qt.Window)

        self.shortcuts = self.settings.read_shortcuts()

        self.create_actions()
        self.create_toolbar()
        self.table = ShortCutsTable(lang=self.lang, shortcuts=self.shortcuts)

        mainlayout = QVBoxLayout()

        self.tablelay = QVBoxLayout()
        self.tablelay.addLayout(self.toolbar)
        self.tablelay.addWidget(self.table)

        buttons_lay = QHBoxLayout()
        ok_button = QPushButton('Применить' if self.lang == 'RU' else 'Apply')
        ok_button.clicked.connect(self.on_ok)
        if on_ok_act:
            ok_button.clicked.connect(on_ok_act)

        cancel_button = QPushButton('Отменить' if self.lang == 'RU' else 'Cancel')
        cancel_button.clicked.connect(self.hide)

        reset_all_button = QPushButton(" Вернуть к исходным" if self.lang == 'RU' else ' Reset')
        # reset_all_button.setIcon(QIcon(self.icon_folder + "/circle.png"))
        reset_all_button.clicked.connect(self.on_reset_all)

        buttons_lay.addWidget(ok_button)
        buttons_lay.addWidget(cancel_button)
        buttons_lay.addWidget(reset_all_button)

        mainlayout.addLayout(self.tablelay)

        mainlayout.addLayout(buttons_lay)

        self.setLayout(mainlayout)
        size, pos = self.settings.read_size_pos_settings()
        self.setMinimumWidth(int(size.width()*width_percent))
        self.setMinimumHeight(int(size.height()*height_percent))

    def on_ok(self):
        self.settings.write_shortcuts(self.shortcuts)
        self.hide()

    def create_actions(self):
        self.edit = QPushButton(" Правка" if self.lang == 'RU' else ' Edit')
        self.edit.setIcon(QIcon(self.icon_folder + "/edit.png"))
        self.edit.clicked.connect(self.on_edit)

        self.reset = QPushButton(" Удалить" if self.lang == 'RU' else ' Clear')
        self.reset.setIcon(QIcon(self.icon_folder + "/clear.png"))
        self.reset.clicked.connect(self.on_reset)

    def create_toolbar(self):
        self.toolbar = QHBoxLayout()
        self.toolbar.addWidget(self.edit, stretch=1)
        self.toolbar.addWidget(self.reset, stretch=1)

    def on_reset(self):
        self.edit_row = self.table.currentRow()
        if self.edit_row == -1:
            return
        k = self.table.item(self.edit_row, 0).text()
        shortcut_apperance = self.shortcuts[k]['appearance']
        if shortcut_apperance:
            self.shortcuts[k]['appearance'] = ""
            self.shortcuts[k]['modifier'] = None
            self.shortcuts[k]['shortcut_key_ru'] = None,
            self.shortcuts[k]['shortcut_key_eng'] = None
        appearance_item = self.table.item(self.edit_row, 2)
        appearance_item.setText(self.shortcuts[k]['appearance'])

    def on_reset_all(self):
        self.settings.reset_shortcuts()
        self.shortcuts = self.settings.read_shortcuts()
        self.table.close()
        self.table = ShortCutsTable(lang=self.lang, shortcuts=self.shortcuts)
        self.tablelay.addWidget(self.table)
        self.update()

    def on_edit(self):
        self.edit_row = self.table.currentRow()
        if self.edit_row == -1:
            return
        self.selected_k = self.table.item(self.edit_row, 0).text()
        cmd = self.table.item(self.edit_row, 1).text()
        shortcut_apperance = self.shortcuts[self.selected_k]['appearance']

        self.input_dialog = ShortCutInputDialog(self,
                                                title_name=f"Редактирование комманды {cmd}" if self.lang == 'RU' else f"Edit shortcut {cmd}",
                                                question_name="Введите новую комманду:" if self.lang == 'RU' else "Enter new shortcut:",
                                                placeholder=shortcut_apperance, min_width=400)
        self.input_dialog.okBtn.clicked.connect(self.on_edit_shortcut_ok)
        self.input_dialog.show()
        self.input_dialog.edit.setFocus()

    def check_shortcut(self, sc, selected_key):

        for k in self.shortcuts:
            if self.shortcuts[k]['appearance'] == sc['appearance']:
                if k != selected_key:
                    return False
        return True

    def on_edit_shortcut_ok(self):
        shortcut_command = self.input_dialog.getCommand()  # {'appearance': appearance, 'key': e_key, 'modifiers': modifiers}

        if not shortcut_command:
            if self.lang == 'RU':
                text = f"Введите команду для {self.table.item(self.edit_row, 1).text()}"
                title = "Не задана команда"
            else:
                text = f"Please input shortcut for {self.table.item(self.edit_row, 1).text()}"
                title = "Shortcut is empty"
            show_message(title, text)
            return
        if not self.check_shortcut(shortcut_command, self.selected_k):
            if self.lang == 'RU':
                text = "Команда уже занята"
                title = "Не верно задана команда"
            else:
                text = f"This shortcut is set"
                title = "Wrong shortcut"
            show_message(title, text)
            return

        appearance_item = self.table.item(self.edit_row, 2)
        k = self.table.item(self.edit_row, 0).text()
        shortcut_key = shortcut_command['key']
        ru_key_to_text = {k: v for v, k in ru_text_to_key.items()}

        if shortcut_key in ru_key_to_text:
            # Перевести RU -> ENG
            text = shortcut_command['appearance']
            modifiers = None
            if '+' in text:
                text_splitted = text.split('+')
                modifiers = text_splitted[:-1]
                symbol_big = text_splitted[-1]

                symbol_low = symbol_big.lower()
                eng_text = ru_to_eng.get(symbol_low, symbol_low)

                self.shortcuts[k]['appearance'] = '+'.join(modifiers) + '+' + eng_text.upper()

            else:

                symbol_low = text.lower()
                eng_text = ru_to_eng.get(symbol_low, symbol_low)
                self.shortcuts[k]['appearance'] = eng_text.upper()

            eng_shortcut_key = eng_text_to_key.get(eng_text, shortcut_key)
            self.shortcuts[k]['shortcut_key_eng'] = eng_shortcut_key
            self.shortcuts[k]['shortcut_key_ru'] = shortcut_key
            self.shortcuts[k]['modifier'] = modifiers

        else:
            text = shortcut_command['appearance']
            modifiers = None
            if '+' in text:
                text_splitted = text.split('+')
                modifiers = text_splitted[:-1]
                text = text_splitted[-1]
                self.shortcuts[k]['appearance'] = '+'.join(modifiers) + '+' + text
                text = text.lower()

            else:
                self.shortcuts[k]['appearance'] = text
                text = text.lower()

            eng_to_ru = {k: v for v, k in ru_to_eng.items()}
            if text in eng_to_ru:
                ru_text = eng_to_ru[text]
                ru_shortcut_key = ru_text_to_key.get(ru_text, shortcut_key)
                self.shortcuts[k]['shortcut_key_ru'] = ru_shortcut_key
            else:
                self.shortcuts[k]['shortcut_key_ru'] = shortcut_key
            self.shortcuts[k]['shortcut_key_eng'] = shortcut_key
            self.shortcuts[k]['modifier'] = modifiers

        appearance_item.setText(self.shortcuts[k]['appearance'])
        self.input_dialog.close()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)

    apply_stylesheet(app, theme='dark_blue.xml', invert_secondary=False)

    w = ShortCutsEditor()
    w.show()
    sys.exit(app.exec_())


import pandas as pd
import numpy as np
import pickle
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from scipy.spatial import distance
import pdb

# imports for standard font size
font = {'family' : 'normal',
        'weight' : 'normal',
        'size'   : 16}
import matplotlib
matplotlib.rc('font', **font)

def scaled_df(df):
    ''' returns a pandas dataframe with data scaled by StandardScaler
    requires: sklearn StandardScaler()
    input: pandas df
    output: pandas df
    '''
    scaler = StandardScaler()
    scaler.fit(df)
    scaled_df = scaler.transform(df)
    return scaled_df

def ranked_zip(labels, values, abs_vals=True):
    if abs_vals:
        zipped = zip(labels, abs(values))
    else:
        zipped = zip(labels, values)
    return sorted(zipped, key=lambda x: x[1], reverse=True)

def ranked_components_plot_ax(labels, values, title, ax, color, abs_vals=True):
    ''' pca components plot, ranked by highest loading

    inputs: labels: (list or pandas.core.indexes.base.Index)
            values: (numpy array)
            title: (string)
            ax: (matplotlib axis)
            abs_vals: flag, use absolute value or not'''

    # sort components by value
    if abs_vals:
        zipped = zip(labels, abs(values))
    else:
        zipped = zip(labels, values)
    srted = sorted(zipped, key=lambda x: x[1], reverse=True)

    # labels, values
    arr = np.array(srted)
    labels = arr[:,0]
    vals = arr[:,1]
    vals = vals.astype(float)
    # indices
    idx = np.arange(len(vals))
    idx = np.flip(idx, axis=0)

    # plot
    ax.barh(idx, vals, color=color)
    ax.set_yticks(idx)
    ax.set_yticklabels(labels)
    ax.set_title(title)

def kmeans_labeled(df, n_clusters):
    ''' fit kmeans clustering to dataframe, return dataframe and
    fitted estimator'''
    kmm = KMeans(n_clusters = n_clusters)
    kmm.fit(df)
    labeled_df = df.copy()
    labeled_df['cluster'] = kmm.labels_
    return labeled_df, kmm

def intra_cluster_distance_manual(X, labels, label_dict):
    ''' calculates euclidean distance norm for manually labeled clusters
        in two dimensions (e.g. pc1, pc2)

    inputs:
    X: np array, shape (n_obs, 2)
    labels: np array, shape (n_obs,), vals = integer labels
    label_dict: dictionary mapping integer to string labels

    output:
    print: label, norm
    '''
    label_vals = np.unique(labels) # unique labeled values
    classes = []
    for val in label_vals:
        # subset of data with same label
        X_sub = X[labels == val]
        # find center
        C = np.array([X_sub[:,0].mean(), X_sub[:,1].mean()])
        # compute euclidean distance norm
        D = distance.cdist(X_sub, C.reshape(-1,1).T, 'euclidean')
        norm = np.sqrt(np.sum(D**2))
        classes.append((val, norm))

    # apply correct labels
    for item in classes:
        label = label_dict[item[0]]
        print('{}: euclidean distance norm = {:0.3f}'.format(label, item[1]))

def pca_scatter_plot_2dim(X_reduced, labels, label_dict):
    plt.scatter(X_reduced[:,0], X_reduced[:,1], marker='o', c=labels)
    #plt.legend(['type1', 'type2', 'type3'])
    plt.xlabel('PC 1')
    plt.ylabel('PC 2')
    cbar = plt.colorbar(ticks=[0, 1, 2])
    cbar.ax.set_yticklabels([label_dict[1], label_dict[2], label_dict[3]])
    plt.tight_layout()
    plt.show()

if __name__=='__main__':
    # read df from pickle
    species_df = pickle.load(open('pkl/species_df.pkl', 'rb'))
    phenotype = species_df.pop('Phenotype')

    # scale data
    X_scaled = scaled_df(species_df)

    # pca
    n_components = 2
    pca = PCA(n_components)
    pca.fit(X_scaled)
    X_reduced = pca.transform(X_scaled)
    comps = pca.components_
    print('PCA: {} components'.format(n_components))

    # explained variance ratio
    ratio = pca.explained_variance_ratio_
    print('explained variance ratio = {:0.2f} : {:0.2f}'.format(ratio[0], ratio[1]))

    # components sorted by feature loadings
    pc1_ranked = ranked_zip(species_df.columns, comps[0,:], abs_vals=True)
    pc2_ranked = ranked_zip(species_df.columns, comps[1,:], abs_vals=True)

    # component loading plots
    pcs = {'pc1': comps[0,:],
            'pc2': comps[1,:]}

    fig, ax = plt.subplots(1,2)
    idx_axes = [0,1]
    colors = ['b','g']
    for pc, idx_ax, c in zip(pcs, idx_axes, colors):
        ranked_components_plot_ax(species_df.columns, pcs[pc], pc, ax[idx_ax], c, abs_vals=True)
    plt.tight_layout()
    plt.show()

    # principal component scatter plot
    num_to_label = {1: 'C3', 2: 'constitutive', 3: 'facultative'}
    labels = phenotype.values
    pca_scatter_plot_2dim(X_reduced, labels, num_to_label)

    # intra-cluster distance for manually labeled clusters
    print('\n')
    intra_cluster_distance_manual(X_reduced, labels, num_to_label)

    # clustering on pca dimension-reduced data
    print('\n')
    kmm = KMeans(n_clusters = 3)
    kmm.fit(X_reduced)
    labels = kmm.labels_
    centers = kmm.cluster_centers_

    # intra-cluster variance
    X_labeled = np.concatenate((X_reduced, labels.reshape(-1,1)), axis=1) # concat labels
    X_sorted = X_labeled[X_labeled[:,2].argsort()] # sort by labels

    arrays = []
    for i in range(max(labels) + 1):
        X = X_labeled[X_labeled[:,2] == i]
        X = X[:,0:2] # remove labels
        C = centers[i,:] #pc1, pc2 coordinates of cluster centers
        # np euclidean norm
        dist = np.linalg.norm(X-C, ord=2) # euclidean norm
        # scipy euclidean norm
        D = distance.cdist(X, C.reshape(-1,1).T, 'euclidean')
        norm = np.sqrt(np.sum(D**2))
        #dist = distance.euclidean(X[:,], C)
        arrays.append((X, C, norm))
        print('cluster {}'.format(i))
        print('np.linalg.norm: {:0.3f}'.format(dist))
        print('euclidean norm: {:0.3f}\n'.format(norm))

    # plot pca-reduced clusters
    colors = ['b','g','r']
    i = 0
    for X, C, norm in arrays:
        plt.scatter(X[:,0], X[:,1], c=colors[i], s=10)
        plt.scatter(C[0], C[1], c=colors[i], s=40, marker='+')
        i += 1
    plt.xlabel('PC1')
    plt.ylabel('PC2')
    plt.legend(['type1', 'type2', 'type3'])
    plt.show()


# https://leetcode.cn/problems/integer-break/
# 给定一个正整数 n ，将其拆分为 k 个 正整数 的和（ k >= 2 ），并使这些整数的乘积最大化。
# 返回 你可以获得的最大乘积 。
# 输入: n = 2
# 输出: 1
# 解释: 2 = 1 + 1, 1 × 1 = 1。
class Solution:
    def integerBreak(self, n: int) -> int:
        dp = [0 for _ in range(n + 1)]
        for i in range(1, n):  # nums
            for j in range(i, n + 1):  # target
                dp[j] = max(dp[j], dp[j - i] * i, (j - i) * i)
        return dp[n]

if __name__ == '__main__':
    res = Solution()
    print(res.integerBreak(4))

贪心&动态规划/343. 整数拆分.py


import sys
sys.stdin = open('5525_input.txt', 'r')

N = int(input()) # P에서 OI의 반복 횟수
M = int(input()) # S의 길이
S = input()

cnt = 0
i = 0
while i < M:
    if S[i] == 'I':
        k = 0 # I 뒤의 OI의 반복횟수
        while True:
            ni = i + 1 + 2*k
            if S[ni:ni+2] == 'OI':
                k += 1
            else:
                break
        if k and k >= N:
            cnt += (k-N) + 1
        i += 2 * k + 1
    else:
        i += 1
print(cnt)


import math

import srli.engine.mln.base

DEFAULT_MAX_TRIES = 3
DEFAULT_NOISE = 0.05
LOG_MOD = 50
FLIP_MULTIPLIER = 2

class NativeMLN(srli.engine.mln.base.BaseMLN):
    """
    A basic implementation of MLNs with inference using MaxWalkSat.
    If unspecified, the number of flips defaults to FLIP_MULTIPLIER x the number of unobserved atoms (similar to Tuffy).
    """

    def __init__(self, relations, rules, **kwargs):
        super().__init__(relations, rules, **kwargs)

    def reason(self, ground_rules, atoms, max_flips = None, max_tries = DEFAULT_MAX_TRIES, noise = DEFAULT_NOISE, **kwargs):
        atom_rule_map = self._map_atoms(ground_rules)

        if (max_flips is None):
            max_flips = FLIP_MULTIPLIER * len(atom_rule_map)

        best_atom_values = None
        best_total_loss = None
        best_attempt = None

        for attempt in range(1, max_tries + 1):
            atom_values, total_loss = self._inference_attempt(attempt, max_flips, noise, ground_rules, atoms, atom_rule_map)
            if (best_total_loss is None or total_loss < best_total_loss):
                best_total_loss = total_loss
                best_atom_values = atom_values
                best_attempt = attempt

            if (math.isclose(total_loss, 0.0)):
                break

        print("MLN Inference Complete - Best Attempt: %d, Loss: %f." % (best_attempt, best_total_loss))

        return best_atom_values

    def _inference_attempt(self, attempt, max_flips, noise, ground_rules, atoms, atom_rule_map):
        atom_values = {}
        for atom_index in atom_rule_map:
            atom_values[atom_index] = self._get_initial_atom_value(atoms[atom_index]['relation'])

        total_loss = 0.0
        for ground_rule in ground_rules:
            total_loss += ground_rule.loss(atom_values)

        print("MLN Inference - Attempt: %d, Iteration 0, Loss: %f, Max Flips: %d." % (attempt, total_loss, max_flips))

        flip = 1
        for flip in range(1, max_flips + 1):
            if (math.isclose(total_loss, 0.0)):
                print("Full satisfaction found.")
                break

            # Pick a random unsatisfied ground rule.
            ground_rule_index = None
            while (ground_rule_index is None or math.isclose(ground_rules[ground_rule_index].loss(atom_values), 0.0)):
                ground_rule_index = self._rng.randint(0, len(ground_rules) - 1)

            # Flip a coin.
            # On heads, flip a random atom in the ground rule.
            # On tails, flip the atom that leads to the most satisfaction.
            if (self._rng.random() < noise):
                flip_atom_index = self._rng.choice(ground_rules[ground_rule_index].atoms)
                atom_values[flip_atom_index] = 1.0 - atom_values[flip_atom_index]
            else:
                flip_atom_index = None
                flip_atom_loss = None

                # Compute the possible loss for flipping each atom.
                for atom_index in ground_rules[ground_rule_index].atoms:
                    old_atom_loss = 0.0
                    for ground_rule_index in atom_rule_map[atom_index]:
                        old_atom_loss += ground_rules[ground_rule_index].loss(atom_values)

                    new_atom_loss = 0.0
                    atom_values[atom_index] = 1.0 - atom_values[atom_index]
                    for ground_rule_index in atom_rule_map[atom_index]:
                        new_atom_loss += ground_rules[ground_rule_index].loss(atom_values)
                    atom_values[atom_index] = 1.0 - atom_values[atom_index]

                    flip_delta = old_atom_loss - new_atom_loss
                    if (flip_atom_index is None or flip_delta > flip_atom_loss):
                        flip_atom_loss = flip_delta
                        flip_atom_index = atom_index

                atom_values[flip_atom_index] = 1.0 - atom_values[flip_atom_index]

            total_loss = 0.0
            for ground_rule in ground_rules:
                total_loss += ground_rule.loss(atom_values)

            if (flip % LOG_MOD == 0):
                print("MLN Inference - Attempt: %d, Iteration %d, Loss: %f." % (attempt, flip, total_loss))

        print("MLN Inference Attempt Complete - Attempt: %d, Iteration %d, Loss: %f." % (attempt, flip, total_loss))

        return atom_values, total_loss

    def _map_atoms(self, ground_rules):
        atom_rule_map = {}

        for ground_rule_index in range(len(ground_rules)):
            for atom_index in ground_rules[ground_rule_index].atoms:
                if (atom_index not in atom_rule_map):
                    atom_rule_map[atom_index] = []
                atom_rule_map[atom_index].append(ground_rule_index)

        return atom_rule_map


def convert_to_seconds(time):
    time = map(int, time.split(":"))
    result = 0
    for t, sec in zip(time, [3600, 60, 1]):
        result += t * sec
    return result

def seconds_to_time(seconds):
    s = seconds % 60
    seconds //= 60
    m = seconds % 60
    seconds //= 60
    h = seconds
    return '{:02d}:{:02d}:{:02d}'.format(h, m, s)

def solution(play_time, adv_time, logs):
    play_sec = convert_to_seconds(play_time)
    adv_sec = convert_to_seconds(adv_time)

    played = [0 for _ in range(360001)]
    for log in logs:
        log = log.split("-")
        start = convert_to_seconds(log[0])
        played[start] += 1
        played[convert_to_seconds(log[1])] -= 1

    for idx in range(1, play_sec + 1):
        played[idx] += played[idx - 1]
    for idx in range(1, play_sec + 1):
        played[idx] += played[idx - 1]

    max_time = 0
    max_sum_played = played[adv_sec]
    for start_time in range(1, play_sec+1):
        end_time = start_time + adv_sec if start_time + adv_sec < play_sec else play_sec
        sum_played = played[end_time] - played[start_time]
        if max_sum_played < sum_played:
            max_sum_played = sum_played
            max_time = start_time+1

    return seconds_to_time(max_time)

play_time = "99:59:59"
adv_time = "25:00:00"
logs = ["69:59:59-89:59:59", "01:00:00-21:00:00",
        "79:59:59-99:59:59", "11:00:00-31:00:00"]
print(solution(play_time, adv_time, logs))


class CompteBancaire:
    def __init__(self, numeroCompte, nom, solde):
        self.numeroCompte = numeroCompte
        self.nom = nom
        self.solde = solde

    def Versement(self, montantVerse):
        if montantVerse<0 :
            print("montant incohérent")
        else :
            self.solde += montantVerse
            print(f"Versement bien pris en compte, nouveau solde : {self.solde}")
        return self

    def Retrait(self, montantRetire):
        if montantRetire<0 :
            print("montant incohérent")
        else :
            self.solde -= montantRetire
            print(f"Retrait bien pris en compte, nouveau solde : {self.solde}")

    def Agios(self):
        self.solde = self.solde * 0.95
        print("On s'est bien servi merci")

    def Afficher(self):
        print(f"""
        Num compte : {self.numeroCompte}
        Nom : {self.nom}
        Solde : {self.solde}
        """)

cb = CompteBancaire('FR123', 'Joe', 100)
cb.Versement(10).Versement(20)
cb.Retrait(20)
cb.Agios()
cb.Afficher()

3. Object-oriented programming/2. Exos online/compteBancaire.py


import pandas as pd

df = pd.read_csv('./Data/data.csv')
#
# print(df.to_string())

# mydataset = {
#     'cars': ["BMW", "Tesla", "NIO"],
#     'passings': [3, 7, 2]
# }
# myvar = pd.DataFrame(mydataset)
# print(myvar)

# Series: A Pandas Series is like a column in a table. It is a one-dimensional array holding data of any type.
a = [1, 7, 2]
serieVar = pd.Series(a)
print(serieVar)
# labels: If nothing else is specified, the values are labeled with their index number. First value has index 0, second value has index 1 etc.
# This label can be used to access a specified value.
print(serieVar[0])
# Create Labels
serieVar2 = pd.Series(a, index = ['x', 'y', 'z'])
print(serieVar2)
print(serieVar2['y'])
# Key value Objects as Series
calories = {"day1": 420, "day2": 380, "day3": 390}
serieVar3 = pd.Series(calories)
print(serieVar3)
serieVar4 = pd.Series(calories, index=['day1', 'day2'])
print(serieVar4)

# DataFrames: Data sets in Pandas are usually multi-dimensional tables, called DataFrames. whole table
data = {
  "calories": [420, 380, 390],
  "duration": [50, 40, 45]
}
# load data into a DataFrame object
dataFrameVar = pd.DataFrame(data)
print(dataFrameVar)
# locate Row: Pandas use the loc attribute to return one or more specified row(s)
print(dataFrameVar.loc[0])
# use a list of indexes:
print(dataFrameVar.loc[[0, 1]])
# named index
dataFrameVar2 = pd.DataFrame(data, index = ['day1', 'day2', 'day3'])
print(dataFrameVar2)
print(dataFrameVar2.loc['day2'])

# Json
dataFrameVar3 = pd.read_json('./Data/data.json')
print(dataFrameVar3.to_string())

# JSON objects have the same format as Python dictionaries
dataJson = {
  "Duration":{
    "0":60,
    "1":60,
    "2":60,
    "3":45,
    "4":45,
    "5":60
  },
  "Pulse":{
    "0":110,
    "1":117,
    "2":103,
    "3":109,
    "4":117,
    "5":102
  },
  "Maxpulse":{
    "0":130,
    "1":145,
    "2":135,
    "3":175,
    "4":148,
    "5":127
  },
  "Calories":{
    "0":409,
    "1":479,
    "2":340,
    "3":282,
    "4":406,
    "5":300
  }
}

dataFrameVar4 = pd.DataFrame(dataJson)
print(dataFrameVar4)

# View Data
print(df.head(10))
print(df.head())
print(df.tail())
print(df.info())


# coding=utf-8

from rest_framework.response import Response

from console.common.console_api_view import ConsoleApiView
from console.common.utils import console_response, now_to_timestamp
from console.common.payload import Payload

from .helper import *

class DescribeDashboardCabinetLoad(ConsoleApiView):
    """
    获取机柜负载
    """

    def post(self, request, *args, **kwargs):
        format = 'real_time'
        poolname = 'all'

        urlparams = ['owner', 'itemname', 'format', 'poolname']

        cpu_util_itemname = 'cpu_util'
        mem_util_itemname = 'mem_util'
        disk_total_and_usage_itemname = 'disk_total_and_usage'
        logger.debug("aaa %s", request.data)

        payload = Payload(
            request=request,
            action='MonitorFinancialServer',
            owner=request.owner,
            format=format,
            num=request.data.get("data").get("num", None),
            poolname=poolname,
        )

        resp = describe_dashboard_cabinet_loads(payload.dumps(), urlparams, cpu_util_itemname, mem_util_itemname,
                                                disk_total_and_usage_itemname)

        return Response(console_response(total_count=len(resp), ret_set=resp, timestamp=now_to_timestamp()))

class DescribeDashboardCabinetUse(ConsoleApiView):
    """
    获取机柜使用率
    """

    def post(self, request, *args, **kwargs):
        resp = describe_dashboard_cabinet_use(request.owner)
        return Response(console_response(total_count=len(resp), ret_set=resp, timestamp=now_to_timestamp()))

class DescribeDashboardOverview(ConsoleApiView):
    """
    总览接口整合
    """
    def post(self, request, *args, **kwargs):
        resp = dashboardoverview()
        return Response(console_response(code=0, ret_set=resp, total_count=len(resp)))


import os
from math import radians

import numpy as NP

import aster
from ..Helpers.UniteAster import UniteAster
from ..Messages import UTMESS, MasquerAlarme, RetablirAlarme

from ..Cata.Syntax import _F
from ..Commands import (CREA_CHAMP, CREA_RESU, CREA_TABLE, LIRE_MAILLAGE,
                        MODI_REPERE, PROJ_CHAMP, RECU_TABLE)
from ..Helpers.LogicalUnit import FileAccess, LogicalUnitFile
from .Fracture.post_endo_fiss_utils import (NoMaximaError,
                                            ThresholdTooHighError,
                                            conv_smoothing1D,
                                            conv_smoothing_arc,
                                            crackOpeningStrong, crea_mail_lin,
                                            crea_sd_mail, euler_angles,
                                            findExtr, unitVector, versDirMoy)
from .macr_lign_coupe_ops import crea_mail_lig_coup

def cherche_trajet(self, NOM_CMP, NOM_CHAM, dRECHERCHE, __ENDO, __mail, typeChampTrajet, infoPlan, inst):

    # --------------------------------------------------
    # IMPORT OF ASTER COMMANDS
    #

    # --------------------------------------------------
    # MESH AND MESH PROPERTIES
    #
    coorIni1 = infoPlan[0]
    coorIni2 = infoPlan[1]
    dnor = infoPlan[2]
    dplan1 = infoPlan[3]
    dplan2 = infoPlan[4]

    dime = __mail.sdj.DIME.get()[5]

    # ---------------------------------
    # SEARCH PARAMETERS
    #
    lort = dRECHERCHE['LONG_ORTH']
    nbPoints = dRECHERCHE['NB_POINT']
    lreg = dRECHERCHE['LONG_REG']
    seuil = dRECHERCHE['BORNE_MIN']
    alpha = dRECHERCHE['ANGL_MAX']
    pas = dRECHERCHE['PAS']
    pas0 = lreg
    if pas0 < dRECHERCHE['PAS']:
        pas0 = dRECHERCHE['PAS']

    # --------------------------------------------------------------
    # RESTRICTION OF THE FIELD ON THE SELECTED ELEMENT GROUP
    #  ("__ENDOGM" = ENDO Groupe de Mailles)
    #   AND CONSTRUCTION OF THE WORKING "RESULT" CONCEPT
    #
    motclefs1 = {}
    motclefs1['MAILLAGE'] = __mail

    if 'GROUP_MA' in list(dRECHERCHE.keys()):
        groupma = dRECHERCHE['GROUP_MA']
        __ENDOGM = CREA_CHAMP(OPERATION='ASSE',
                              TYPE_CHAM=typeChampTrajet,
                              ASSE=_F(CHAM_GD=__ENDO,
                                      GROUP_MA=groupma,
                                      NOM_CMP=NOM_CMP,
                                      ),
                              **motclefs1)
    else:
        __ENDOGM = __ENDO

    __resu = CREA_RESU(OPERATION='AFFE',
                       TYPE_RESU='EVOL_NOLI',
                       NOM_CHAM=NOM_CHAM,
                       AFFE=(_F(CHAM_GD=__ENDO,
                                INST=inst),),)

    # --------------------------------------------------
    # BOOT OF THE CRACK SEARCH PROCEDURE
    #
    methodeProj = 'COLLOCATION'
    Coortot = __mail.sdj.COORDO.VALE.get()
    Xtot = Coortot[coorIni1:len(Coortot):3]
    Ytot = Coortot[coorIni2:len(Coortot):3]
    Endono = __ENDOGM.EXTR_COMP(NOM_CMP, [], 1)
    Endo = Endono.valeurs
    Noeybar = Endono.noeud
    idxNoeud = NP.array(Noeybar) - 1
    Coorx = NP.take(Xtot, idxNoeud)
    Coory = NP.take(Ytot, idxNoeud)
    coorIni3 = int(NP.nonzero(dnor)[0])
    NormTot = Coortot[coorIni3:len(Coortot):3]
    CoorNor = NP.take(NormTot, idxNoeud)
    zCoupe = CoorNor[
        0]  # On dit que dans la coupe tous les valeurs sont constants
    idxmax = NP.argmax(Endo)
    xmax = Coorx[idxmax]
    ymax = Coory[idxmax]
    endomax = Endo[idxmax]

    Endono2 = __ENDO.EXTR_COMP(NOM_CMP, [], 1)

    # First crack path point
    PtMax = xmax * dplan1 + ymax * dplan2 + zCoupe * dnor
    CoxAmo = NP.array([PtMax[0]])
    CoyAmo = NP.array([PtMax[1]])
    CozAmo = NP.array([PtMax[2]])
    EndoAmo = NP.array([endomax], float)

    # Creation of a circle and projection of the field on it
    lignes = []
    groups = []
    arcs = []
    pt2 = (xmax + pas) * dplan1 + ymax * dplan2 + zCoupe * dnor
    pt3 = (xmax - pas) * dplan1 + ymax * dplan2 + zCoupe * dnor
    arcs.append((pt2, PtMax, nbPoints, 180., dnor))
    arcs.append((pt3, PtMax, nbPoints, 180., dnor))

    resu_mail0, arcgma0, angles0, nbno0 = crea_mail_lig_coup(
        dime, lignes, groups, arcs)
    __MAI = crea_sd_mail(self, os.linesep.join(resu_mail0))

    motclefs2 = {}
    motclefs2['MAILLAGE_1'] = __mail
    motclefs2['MAILLAGE_2'] = __MAI
    nbPrec = NP.finfo(NP.float).precision
    distMax = 10. ** (-nbPrec + 2)

    __YBARPR = PROJ_CHAMP(METHODE=methodeProj,
                          RESULTAT=__resu,
                          DISTANCE_MAX=distMax,
                          TYPE_CHAM='NOEU',
                          NOM_CHAM=NOM_CHAM,
                          NUME_ORDRE=1,
                          **motclefs2)

    __YBARCH = CREA_CHAMP(TYPE_CHAM=typeChampTrajet,
                          OPERATION='EXTR',
                          NOM_CHAM=NOM_CHAM,
                          RESULTAT=__YBARPR,
                          NUME_ORDRE=1, )

    dx0 = __YBARCH.EXTR_COMP(NOM_CMP, [], 1)

    # "NonVide" : list of the circle nodes
    #   with associated values, i.e. inside the material
    # "idxpred" : connections between the two half-circles
    NonVide = NP.array(list(dx0.noeud))
    idxpred1 = NP.where(NonVide == 2 * nbPoints - 1)[0]
    idxpred2 = NP.where(NonVide == nbPoints)[0]

    EndoOrth = dx0.valeurs
    Coor0 = __MAI.sdj.COORDO.VALE.get()
    CoorxOrth = NP.array(Coor0[coorIni1:len(Coor0):3], float)
    CooryOrth = NP.array(Coor0[coorIni2:len(Coor0):3], float)

    # We eliminate nodes without field values
    CoorxOrth = NP.take(CoorxOrth, NonVide - 1)
    CooryOrth = NP.take(CooryOrth, NonVide - 1)
    CoorxOrth = NP.delete(CoorxOrth, idxpred1)
    CoorxOrth = NP.delete(CoorxOrth, idxpred2)
    CooryOrth = NP.delete(CooryOrth, idxpred1)
    CooryOrth = NP.delete(CooryOrth, idxpred2)
    EndoOrth = NP.delete(EndoOrth, idxpred1)
    EndoOrth = NP.delete(EndoOrth, idxpred2)

    # Smoothing of the field on the circle
    # EndoReg = conv_smoothing_arc_old(pas,CoorxOrth, CooryOrth,EndoOrth)
    EndoReg = conv_smoothing_arc(lreg, CoorxOrth, CooryOrth, EndoOrth)

    # Second crack path point
    idxmax = NP.argmax(EndoReg)
    endomax = EndoOrth[idxmax]
    cox = CoorxOrth[idxmax]
    coy = CooryOrth[idxmax]
    PtMax = cox * dplan1 + coy * dplan2 + zCoupe * dnor
    CoxAmo = NP.append(CoxAmo, PtMax[0])
    CoyAmo = NP.append(CoyAmo, PtMax[1])
    CozAmo = NP.append(CozAmo, PtMax[2])
    EndoAmo = NP.append(CozAmo, endomax)

    # Creation of a search vector
    CoxLast = NP.array([CoxAmo[1], CoxAmo[0]])
    CoyLast = NP.array([CoyAmo[1], CoyAmo[0]])
    CozLast = NP.array([CozAmo[1], CozAmo[0]])

    VersAvan = NP.array(
        [CoxLast[1] - CoxLast[0], CoyLast[1] - CoyLast[0], CozLast[1] - CozLast[0]])
    VersAvan = unitVector(VersAvan)

    PStart = NP.array([CoxLast[0], CoyLast[0], CozLast[0]])
    Ppred = PStart + pas * VersAvan
    VersNorm = unitVector(NP.cross(VersAvan, dnor))
    PPlus = Ppred + (lort / 2.) * VersNorm
    PMoin = Ppred - (lort / 2.) * VersNorm

    # Creation of an orthogonal profile and projection on it
    lignes = []
    groups = []
    arcs = []
    lignes = []
    lignes.append((PMoin.tolist(), Ppred.tolist(), nbPoints))
    lignes.append((Ppred.tolist(), PPlus.tolist(), nbPoints))

    resu_mail0, arcgma0, angles0, nbno0 = crea_mail_lig_coup(
        dime, lignes, groups, arcs)
    __MAI = crea_sd_mail(self, os.linesep.join(resu_mail0))

    motclefs2 = {}
    motclefs2['MAILLAGE_1'] = __mail
    motclefs2['MAILLAGE_2'] = __MAI

    __YBARPR = PROJ_CHAMP(METHODE='COLLOCATION',
                          RESULTAT=__resu,
                          DISTANCE_MAX=distMax,
                          TYPE_CHAM='NOEU',
                          NOM_CHAM=NOM_CHAM,
                          NUME_ORDRE=1,
                          **motclefs2)

    __YBARCH = CREA_CHAMP(TYPE_CHAM=typeChampTrajet,
                          OPERATION='EXTR',
                          NOM_CHAM=NOM_CHAM,
                          RESULTAT=__YBARPR,
                          NUME_ORDRE=1,)

    dx0 = __YBARCH.EXTR_COMP(NOM_CMP, [], 1)

    #  Search for the prediction point among the projected points
    #   and elimination of doubled point in the middle
    NonVide = NP.array(list(dx0.noeud))
    idxpred = NP.where(NonVide == nbPoints)[0]
    EndoOrth = dx0.valeurs

    Coor0 = __MAI.sdj.COORDO.VALE.get()
    CoorxOrth = NP.array(Coor0[coorIni1:len(Coor0):3], float)
    CooryOrth = NP.array(Coor0[coorIni2:len(Coor0):3], float)
    CoorxOrth = NP.take(CoorxOrth, NonVide - 1)
    CooryOrth = NP.take(CooryOrth, NonVide - 1)
    CoorxOrth = NP.delete(CoorxOrth, idxpred)
    CooryOrth = NP.delete(CooryOrth, idxpred)
    EndoOrth = NP.delete(EndoOrth, idxpred)
    EndoReg = conv_smoothing1D(lreg, CoorxOrth, CooryOrth, EndoOrth)

    # Refined coordinates of the first crack path point
    idxmax = NP.argmax(EndoReg)
    endomax = EndoOrth[idxmax]
    cox = CoorxOrth[idxmax]
    coy = CooryOrth[idxmax]
    PtMax = cox * dplan1 + coy * dplan2 + zCoupe * dnor
    CoxAmo[0] = PtMax[0]
    CoyAmo[0] = PtMax[1]
    CozAmo[0] = PtMax[2]
    EndoAmo[0] = endomax

    # --------------------------------------------------
    #  BEGIN OF THE CRACK PATH SEARCH
    #
    # Definition of two search directions
    VersAvn1 = NP.array(
        [CoxAmo[1] - CoxAmo[0], CoyAmo[1] - CoyAmo[0], CozAmo[1] - CozAmo[0]])
    VersAvn1 = unitVector(VersAvn1)
    VersAvn2 = -VersAvn1

    # Initialisation of the ridge vectors
    CoxCrete1 = NP.array([CoxAmo[1]])
    CoyCrete1 = NP.array([CoyAmo[1]])
    CozCrete1 = NP.array([CozAmo[1]])
    EndoCrete1 = NP.array([EndoAmo[1]])

    CoxCrete = NP.array([CoxAmo[0]])
    CoyCrete = NP.array([CoyAmo[0]])
    CozCrete = NP.array([CozAmo[0]])
    EndoCrete = NP.array([EndoAmo[0]])

    # ----
    # Loop on the crack path points
    #     Loop variables :
    #        dirRech   --> search direction index (1 or 2)
    #        condSort  --> loop exit condition
    #
    dirRech = 1
    i = 0
    condSort = seuil * 1.1
    while (condSort > seuil or dirRech == 1):
        i = i + 1
        # Definition of ths search vector
        if i == 1:
            if dirRech == 1:
                VersAvan = VersAvn1
            else:
                VersAvan = VersAvn2
        else:
            if dirRech == 1:
                CoxLast = NP.array([CoxCrete1[-2], CoxCrete1[-1]])
                CoyLast = NP.array([CoyCrete1[-2], CoyCrete1[-1]])
                CozLast = NP.array([CozCrete1[-2], CozCrete1[-1]])
            else:
                CoxLast = NP.array([CoxCrete[-2], CoxCrete[-1]])
                CoyLast = NP.array([CoyCrete[-2], CoyCrete[-1]])
                CozLast = NP.array([CozCrete[-2], CozCrete[-1]])
            VersAvan = NP.array(
                [CoxLast[1] - CoxLast[0], CoyLast[1] - CoyLast[0], CozLast[1] - CozLast[0]])
            VersAvan = unitVector(VersAvan)

        if dirRech == 1:
            PStart = NP.array([CoxCrete1[-1], CoyCrete1[-1], CozCrete1[-1]])
        else:
            PStart = NP.array([CoxCrete[-1], CoyCrete[-1], CozCrete[-1]])

        # Definition of the prediction point
        Ppred = PStart + pas * VersAvan
        VersNorm = unitVector(NP.cross(VersAvan, dnor))
        PPlus = Ppred + (lort / 2.) * VersNorm
        PMoin = Ppred - (lort / 2.) * VersNorm

        # Creation of the orthogonal profile
        lignes = []
        groups = []
        arcs = []
        lignes.append((PMoin.tolist(), Ppred.tolist(), nbPoints))
        lignes.append((Ppred.tolist(), PPlus.tolist(), nbPoints))

        resu_mail0, arcgma0, angles0, nbno0 = crea_mail_lig_coup(
            dime, lignes, groups, arcs)
        __MAI = crea_sd_mail(self, os.linesep.join(resu_mail0))

        motclefs2 = {}
        motclefs2['MAILLAGE_1'] = __mail
        motclefs2['MAILLAGE_2'] = __MAI
        try:
            # we try to project, except the case of no points "in the material"
            __YBARPR = PROJ_CHAMP(METHODE='COLLOCATION',
                                  RESULTAT=__resu,
                                  DISTANCE_MAX=distMax,
                                  TYPE_CHAM='NOEU',
                                  NOM_CHAM=NOM_CHAM,
                                  NUME_ORDRE=1,
                                  **motclefs2)

        except E_Exception.error as e:
            # All points outside the material
            if (e.id_message != 'CALCULEL3_97'):
                if dirRech == 1:
                    dirRech = 2
                    i = 0
                else:
                    condSort = seuil * 0.1

        else:
            __YBARCH = CREA_CHAMP(TYPE_CHAM=typeChampTrajet,
                                  OPERATION='EXTR',
                                  NOM_CHAM=NOM_CHAM,
                                  RESULTAT=__YBARPR,
                                  NUME_ORDRE=1,)

            dx0 = __YBARCH.EXTR_COMP(NOM_CMP, [], 1)
            NonVide = NP.array(list(dx0.noeud))

            # Search of the prediction point among projected points
            idxpred = NP.where(NonVide == nbPoints)[0]

            # Prediction point outside material
            if len(idxpred) == 0:
                if dirRech == 1:
                    dirRech = 2
                    i = 0
                    continue
                else:
                    condSort = seuil * 0.1
                    break

            EndoOrth = dx0.valeurs
            Coor0 = __MAI.sdj.COORDO.VALE.get()
            CoorxOrth = NP.array(Coor0[coorIni1:len(Coor0):3], float)
            CooryOrth = NP.array(Coor0[coorIni2:len(Coor0):3], float)
            CoorxOrth = NP.take(CoorxOrth, NonVide - 1)
            CooryOrth = NP.take(CooryOrth, NonVide - 1)
            CoorxOrth = NP.delete(CoorxOrth, idxpred)
            CooryOrth = NP.delete(CooryOrth, idxpred)
            EndoOrth = NP.delete(EndoOrth, idxpred)

            # Smoothing of the projected field on the orthogonal profile
            # EndoReg  = conv_smoothing1D(lreg/3, CoorxOrth,
            # CooryOrth,EndoOrth)
            EndoReg = conv_smoothing1D(lreg, CoorxOrth, CooryOrth, EndoOrth)

            # New crack path point!
            idxmax = NP.argmax(EndoReg)
            endomax = EndoOrth[idxmax]
            cox = CoorxOrth[idxmax]
            coy = CooryOrth[idxmax]
            PtMax = cox * dplan1 + coy * dplan2 + zCoupe * dnor
            condSort = endomax
            # We controle that the point is inside the maximum accepted angle "ANGL_MAX"
            #    otherwise we stop the search in "dirRech" direction

            if round(alpha) != 180.:
                alphar = radians(alpha)
                blim = pas * NP.tan(alphar / 2.)
                btest = ((PtMax[0] - Ppred[0]) ** 2. + (
                    PtMax[1] - Ppred[1]) ** 2. + (PtMax[2] - Ppred[2]) ** 2.) ** 0.5
                if btest > blim:
                    if dirRech == 1:
                        dirRech = 2
                        i = 0
                        condSort = seuil * 1.1
                        continue
                    else:
                        condSort = seuil * 0.1
                        break

            if dirRech == 1:
                if condSort >= seuil:
                    CoxCrete1 = NP.append(CoxCrete1, [PtMax[0]])
                    CoyCrete1 = NP.append(CoyCrete1, [PtMax[1]])
                    CozCrete1 = NP.append(CozCrete1, [PtMax[2]])
                    EndoCrete1 = NP.append(EndoCrete1, [endomax])
                else:
                    dirRech = 2
                    condSort = seuil * 1.1
                    i = 0
            else:
                if condSort >= seuil:
                    cox = NP.append(cox, [2, 6])
                    CoxCrete = NP.append(CoxCrete, [PtMax[0]])
                    CoyCrete = NP.append(CoyCrete, [PtMax[1]])
                    CozCrete = NP.append(CozCrete, [PtMax[2]])
                    EndoCrete = NP.append(EndoCrete, [endomax])
                else:
                    pass

    CoxCrete1 = CoxCrete1.tolist()
    CoxCrete = CoxCrete.tolist()
    CoyCrete1 = CoyCrete1.tolist()
    CoyCrete = CoyCrete.tolist()
    CozCrete1 = CozCrete1.tolist()
    CozCrete = CozCrete.tolist()
    EndoCrete1 = EndoCrete1.tolist()
    EndoCrete = EndoCrete.tolist()
    CoxCrete.reverse()
    CoyCrete.reverse()
    CozCrete.reverse()
    EndoCrete.reverse()
    CoxCrete.extend(CoxCrete1)
    CoyCrete.extend(CoyCrete1)
    CozCrete.extend(CozCrete1)
    EndoCrete.extend(EndoCrete1)

    nbNoeud = len(CoxCrete)
    Connex = []
    for idxNo in range(nbNoeud - 1):
        no1 = idxNo + 1
        no2 = idxNo + 2
        ma = (no1, no2)
        Connex.append(ma)

    return CoxCrete, CoyCrete, CozCrete, EndoCrete, Connex

def calcul_ouverture(self, NOM_CHAM, NOM_CMP, dRECHERCHE, __RESUIN, __mail, infoPlan, inst, CoxCrete, CoyCrete, CozCrete, dime, strong_flag):

    # --------------------------------------------------
    # IMPORT DES COMMANDES ASTER
    #

    # ---------------------------
    # DEVELOPER PARAMETERS
    #
    if strong_flag == True:
        # for the "strong" method, give here necessary parameters :
        #   caracteristic- and orthogonal line lengths
        #   default values : those used for crack path search
        lortOuv = dRECHERCHE['LONG_ORTH']

    # ---------------------------
    # PARAMETRES DE LA RECHERCHE
    #
    nbPoints = dRECHERCHE['NB_POINT']
    lortOuv = dRECHERCHE['LONG_ORTH']
    endoMin = dRECHERCHE['BORNE_MAX']
    champEndo = NOM_CHAM
    cmpEndo = NOM_CMP

    if (champEndo == 'DEPL'):
        typechampEndo = 'NOEU_DEPL_R'
    else:
        typechampEndo = 'NOEU' + '_' + NOM_CHAM[0:4] + '_R'
        if (champEndo == 'VARI_NOEU'):
            typechampEndo = 'NOEU_VAR2_R'

    # ---------------------------
    #  2D AND MESH PARAMETERS
    #
    #__mail   = modelisa['MAILLAGE']
    #__modtot = modelisa['MODELE']
    coorIni1 = infoPlan[0]
    coorIni2 = infoPlan[1]
    dnor = infoPlan[2]

    (lst_tanPoi, lst_normPoi) = versDirMoy(CoxCrete, CoyCrete, CozCrete, dnor)

    motclefs = {}
    ChampsResu = __RESUIN.LIST_CHAMPS()

    methodeProj = 'COLLOCATION'
    methodeProjVI = 'COLLOCATION'
    composante = 'DY'
    champ = 'DEPL'
    typeChamp = 'NOEU_DEPL_R'
    motclefs['MODI_CHAM'] = [_F(NOM_CHAM='DEPL',
                                NOM_CMP=('DX', 'DY',),
                                TYPE_CHAM = 'VECT_2D',),
                             ]

    nbPrec = NP.finfo(NP.float).precision
    distMax = 10. ** (-nbPrec + 2)

    if strong_flag == True:
        composante = 'EPYY'
        champ = 'EPSI_NOEU'
        typeChamp = 'NOEU_EPSI_R'
        motclefs['MODI_CHAM'] = [_F(NOM_CHAM=champ,
                                    NOM_CMP=(
                                    'EPXX', 'EPYY', 'EPZZ', 'EPXY',),
                                    TYPE_CHAM = 'TENS_2D',), ]

    # ---------------------
    # LOOP CRACK PATH POINTS
    #     "lstOuvFiss" : list of crack openings on the crack path
    #     "lstErr"     : list on errors for each crack opening ("STRONG" method)

    lstOuvFiss = []
    lstErr = []
    for idxPoi in range(len(CoxCrete)):
        # Creation of the mesh and model on the considered orthogonal profile
        PtCrete = NP.array(
            [CoxCrete[idxPoi], CoyCrete[idxPoi], CozCrete[idxPoi]])
        PGort = PtCrete + (lortOuv / 2.) * lst_normPoi[idxPoi]
        PDort = PtCrete - (lortOuv / 2.) * lst_normPoi[idxPoi]
        lignort = []
        groups0 = []
        arcs0 = []
        lignort.append((PGort, PtCrete, nbPoints))
        lignort.append((PtCrete, PDort, nbPoints))

        resu_mail0, arcgma0, angles0, nbno0 = crea_mail_lig_coup(
            dime, lignort, groups0, arcs0)
        __MAI = crea_sd_mail(self, os.linesep.join(resu_mail0))

        CoorTotOrtho = __MAI.sdj.COORDO.VALE.get()
        XtotOrtho = NP.array(CoorTotOrtho[coorIni1:len(CoorTotOrtho):3])
        YtotOrtho = NP.array(CoorTotOrtho[coorIni2:len(CoorTotOrtho):3])

        # Rotation of the diplacement or strain field on the crack reference
        # system
        vec_tan = lst_tanPoi[idxPoi]
        vec_nor = lst_normPoi[idxPoi]
        M = NP.concatenate(([vec_tan], [vec_nor], [dnor]), axis=0)
        M = NP.transpose(M)

        (alpha, beta, gamma) = euler_angles(M)
        __RESROT = MODI_REPERE(RESULTAT=__RESUIN,
                               INST=inst,
                               REPERE='UTILISATEUR',
                               AFFE=_F(
                               ANGL_NAUT=(alpha, beta, gamma),
                               TOUT='OUI',
                               ),
                               **motclefs)

        # Projection of displ. or strain field on the orthogonal profile
        #    and extraction of this field from the result concept
        motclefs2 = {}
        motclefs2['MAILLAGE_1'] = __mail
        motclefs2['MAILLAGE_2'] = __MAI
        except1 = 'False'
        except2 = 'False'
        try:
            __OUVEPR = PROJ_CHAMP(METHODE=methodeProj,
                                  RESULTAT=__RESROT,
                                  DISTANCE_MAX=distMax,
                                  NOM_CHAM=champ,
                                  INST=inst,
                                  **motclefs2)
        except:
            lstOuvFiss.append('-')
            except1 = 'True'

        else:

            __OUVECH = CREA_CHAMP(TYPE_CHAM=typeChamp,
                                  OPERATION='EXTR',
                                  NOM_CHAM=champ,
                                  RESULTAT=__OUVEPR,
                                  INST=inst,)

            # Retrieving to Python objects the strain or displacement field values
            #    on the orthogonal profile, and the orthogonal mesh.
            ChampOrthoCH = __OUVECH.EXTR_COMP(composante, [], 1)
            ChampOrtho = ChampOrthoCH.valeurs
            NonVide = NP.array(list(ChampOrthoCH.noeud))
            idxCentre = NP.where(NonVide == nbPoints)[0]
            XtotOrtho1 = NP.take(XtotOrtho, NonVide - 1)
            YtotOrtho1 = NP.take(YtotOrtho, NonVide - 1)
            XtotOrtho1 = NP.delete(XtotOrtho1, idxCentre)
            YtotOrtho1 = NP.delete(YtotOrtho1, idxCentre)
            ChampOrtho = NP.delete(ChampOrtho, idxCentre)

        if strong_flag == False:
            try:
        # Projection of the damage field on the orthogonal profile
        #    and extraction of this field from the result concept
                __ENDOPR = PROJ_CHAMP(METHODE=methodeProjVI,
                                      RESULTAT=__RESUIN,
                                      DISTANCE_MAX=distMax,
                                      NOM_CHAM=champEndo,
                                      INST=inst,
                                      **motclefs2)
            except:
                if except1:
                    pass
                else:
                    lstOuvFiss.append('-')
                    except2 = 'True'
            else:

                __ENDOCH = CREA_CHAMP(TYPE_CHAM=typechampEndo,
                                      OPERATION='EXTR',
                                      NOM_CHAM=champEndo,
                                      RESULTAT=__ENDOPR,
                                      INST=inst,)

                EndoOrthoCH = __ENDOCH.EXTR_COMP(cmpEndo, [], 1)
                EndoOrtho = EndoOrthoCH.valeurs
                NonVide = NP.array(list(EndoOrthoCH.noeud))
                idxCentre = NP.where(NonVide == nbPoints)[0]
                XtotOrtho2 = NP.take(XtotOrtho, NonVide - 1)
                YtotOrtho2 = NP.take(YtotOrtho, NonVide - 1)
                XtotOrtho2 = NP.delete(XtotOrtho2, idxCentre)
                YtotOrtho2 = NP.delete(YtotOrtho2, idxCentre)
                EndoOrtho = NP.delete(EndoOrtho, idxCentre)

            # -----Extraction de l'ouverture de fissure / erreur ---------
            #
                try:
                    idxG, idxD = findExtr(EndoOrtho, endoMin, idxCentre)
                except (ThresholdTooHighError, NoMaximaError):
                    if except1 or except2:
                        pass
                    else:
                        lstOuvFiss.append('-')
                else:
                    ouvFiss = float(abs(ChampOrtho[idxD] - ChampOrtho[idxG]))
                    lstOuvFiss.append(ouvFiss)
        else:  # methode strong
            ouvFiss, errOuv = crackOpeningStrong(
                lortOuv, XtotOrtho, XtotOrtho, ChampOrtho)
            lstOuvFiss.append(ouvFiss)
            lstErr.append(errOuv)

    if strong_flag == False:
        return lstOuvFiss
    else:  # methode strong
        return lstOuvFiss, lstErr

def post_endo_fiss_ops(self,
                       TABLE,
                       NOM_CMP,
                       NOM_CHAM,
                       RECHERCHE,
                       OUVERTURE=None,
                       CHAM_GD=None,
                       **args):

    # --------------------------------------------------
    # DEVELOPER OPTIONS
    #
    # "strong_flag" must be set to True if computing crack opening with the "strong" method
    strong_flag = False

    MasquerAlarme('CALCULEL5_48')
    MasquerAlarme('ALGORITH12_43')
    MasquerAlarme('CALCULEL2_12')
    MasquerAlarme('CALCULEL5_7')

    # --------------------------------------------------
    # IMPORT OF ASTER COMMANDS
    #

    # --------------------------------------------------
    #  INPUT PARAMETERS
    #
    l_dRECHERCHE = []
    for recherche in RECHERCHE:
        dRECHERCHE = recherche.cree_dict_valeurs(recherche.mc_liste)
        for i in list(dRECHERCHE.keys()):
            if dRECHERCHE[i] is None:
                del dRECHERCHE[i]
        l_dRECHERCHE.append(dRECHERCHE)

    # --------------------------------------------------
    # INPUT PARAMETERS, MESH AND MODEL
    #
    motscles = {}

    for dRECHERCHE in l_dRECHERCHE:
        if (OUVERTURE == 'OUI') and ('BORNE_MAX' not in list(dRECHERCHE.keys())):
            UTMESS('F', 'POST0_44')

    if CHAM_GD is not None:
        build = 'champ'
        __ENDO = CHAM_GD
        inst = 1.
        motscles['INST'] = inst

        __mail = __ENDO.getMesh()

    else:
        build = 'resu'
        __RESUIN = args['RESULTAT']
        dicVarAcc = __RESUIN.LIST_VARI_ACCES()
        if args.get('NUME_ORDRE') is not None:
            nume_ordre = args.get('NUME_ORDRE')
            if nume_ordre not in dicVarAcc['NUME_ORDRE']:
                UTMESS('F', 'POST0_41')
            else:
                inst = (dicVarAcc['INST'])[nume_ordre]
            motscles['NUME_ORDRE'] = nume_ordre
        else:
            inst = args.get('INST')
            motscles['INST'] = inst
            nume_ordre = None
            for champ_inst_index, champ_inst in enumerate(dicVarAcc['INST']):
                if round(champ_inst, 12) == round(inst, 12):
                    nume_ordre = dicVarAcc['NUME_ORDRE'][champ_inst_index]
                    break
            if nume_ordre is None:
                UTMESS('F', 'POST0_41')

        # Maillage pour projections
        model = __RESUIN.getModel()
        if model is None:
            __mail = __RESUIN.getMesh()
        else:
            __mail = __RESUIN.getModel().getMesh()

    dime = __mail.sdj.DIME.get()[5]

    # --------------------------------------------------
    # CONTROLS ON THE INPUT FIELDS
    #
    if build == 'resu':
        ChampsResu = __RESUIN.LIST_CHAMPS()
        lstChampsResu = list(ChampsResu.keys())
        if (NOM_CHAM not in lstChampsResu):
            UTMESS('F', 'POST0_42')
        elif (nume_ordre not in ChampsResu[NOM_CHAM]):
            UTMESS('F', 'POST0_41')
        else:
            pass

    if build == 'champ' and OUVERTURE == 'OUI':
        UTMESS('F', 'POST0_43')

    if ('NOEU' in NOM_CHAM) or (NOM_CHAM == 'DEPL'):
        typeChampTrajet = 'NOEU' + '_' + NOM_CHAM[0:4] + '_R'
        if NOM_CHAM == 'VARI_NOEU':
            typeChampTrajet = 'NOEU_VAR2_R'
    else:
        UTMESS('F', 'POST0_35')

    # --------------------------------------------------
    # QUANTITIES FOR THE 2D PROCEDURE
    #
    __TABG = RECU_TABLE(CO=__mail,
                        NOM_TABLE='CARA_GEOM',)

    xmin = __TABG['X_MIN', 1]
    xmax = __TABG['X_MAX', 1]
    ymin = __TABG['Y_MIN', 1]
    ymax = __TABG['Y_MAX', 1]
    zmin = __TABG['Z_MIN', 1]
    zmax = __TABG['Z_MAX', 1]

    nbPrec = NP.finfo(NP.float).precision
    delta_x = NP.round(xmax - xmin, nbPrec)
    delta_y = NP.round(ymax - ymin, nbPrec)
    delta_z = NP.round(zmax - zmin, nbPrec)

    Ddim = [delta_x, delta_y, delta_z]
    delta_min = min(Ddim)
    if NP.round(delta_min, nbPrec - 2) != 0.:
        UTMESS('F', 'POST0_34')
    else:
        idx_plan = Ddim.index(delta_min)

    # PLAN == 'XY' :
    if idx_plan == 2:
        coorIni1 = 0
        coorIni2 = 1
        dnor = NP.array([0., 0., 1.], float)
        dplan1 = NP.array([1., 0., 0.], float)
        dplan2 = NP.array([0., 1., 0.], float)
    # PLAN == 'XZ':
    elif idx_plan == 1:
        coorIni1 = 0
        coorIni2 = 2
        dnor = NP.array([0., 1., 0.], float)
        dplan1 = NP.array([1., 0., 0.], float)
        dplan2 = NP.array([0., 0., 1.], float)
    # PLAN == 'YZ':
    else:
        coorIni1 = 1
        coorIni2 = 2
        dnor = NP.array([1., 0., 0.], float)
        dplan1 = NP.array([0., 1., 0.], float)
        dplan2 = NP.array([0., 0., 1.], float)

    infoPlan = (coorIni1, coorIni2, dnor, dplan1, dplan2)

    # --------------------------------------------------
    # FIELD FOR CRACK PATH SEARCH
    #
    if build == 'resu':
        __ENDO = CREA_CHAMP(TYPE_CHAM=typeChampTrajet,
                            OPERATION='EXTR',
                            RESULTAT=__RESUIN,
                            NOM_CHAM=NOM_CHAM,
                            **motscles)

    # --------------------------------------------------
    # LOOP ON THE FPZs (INSTANCES OF KEYWORD "RECHERCHE")
    #
    XcreteTot = []
    YcreteTot = []
    ZcreteTot = []
    ConnTot = []
    EndocreteTot = []
    lstFissure = []
    lstOuverture = []
    lstErreur = []
    lstNomFiss = []

    for idxRech in range(len(l_dRECHERCHE)):

        dRECHERCHE = l_dRECHERCHE[idxRech]

        (CoxCrete, CoyCrete, CozCrete, EndoCrete, Connex) = cherche_trajet(
            self, NOM_CMP, NOM_CHAM, dRECHERCHE, __ENDO, __mail, typeChampTrajet, infoPlan, inst)
        if OUVERTURE == 'OUI':
            if strong_flag == False:
                lstOuvFiss = calcul_ouverture(
                    self, NOM_CHAM, NOM_CMP, dRECHERCHE, __RESUIN, __mail, infoPlan, inst, CoxCrete, CoyCrete, CozCrete, dime, strong_flag)
            else:
                lstOuvFiss, lstErr = calcul_ouverture(
                    self, NOM_CHAM, NOM_CMP, dRECHERCHE, __RESUIN, __mail, infoPlan, inst, nume_ordre, CoxCrete, CoyCrete, CozCrete, dime, strong_flag)
        XcreteTot.append(CoxCrete)
        YcreteTot.append(CoyCrete)
        ZcreteTot.append(CozCrete)
        EndocreteTot.append(EndoCrete)
        ConnTot.append(Connex)
        if 'GROUP_MA' in list(dRECHERCHE.keys()):
            nomFissure = dRECHERCHE['GROUP_MA']
        else:
            nomFissure = 'FISS' + str(idxRech + 1)
        lstFissure = lstFissure + ([nomFissure] * len(CoxCrete))
        lstNomFiss.append(nomFissure)

        if OUVERTURE == 'OUI':
            if '-' in lstOuvFiss:
                UTMESS('A', 'POST0_33', nomFissure)
            lstOuverture.append(lstOuvFiss)
            if strong_flag == True:
                lstErreur.append(lstErr)

    lstX = []
    lstY = []
    lstZ = []
    lstEndo = []
    if OUVERTURE == 'OUI':
        lstO = []
        if strong_flag == True:
            lstE = []

    for i in range(len(XcreteTot)):
        lstX = lstX + XcreteTot[i]
        lstY = lstY + YcreteTot[i]
        lstZ = lstZ + ZcreteTot[i]
        lstEndo = lstEndo + EndocreteTot[i]
        if OUVERTURE == 'OUI':
            lstO = lstO + lstOuverture[i]
            if strong_flag == True:
                lstE = lstE + lstErreur[i]

  # -----------------------------------------------------
  # CREATION OF A TABLE TO STOCK CRACK PATH COORDINATES
  #   AND CRACK OPENING
  #
    if OUVERTURE == 'NON':
        tabRes = CREA_TABLE(LISTE=(
            _F(PARA='FISSURE', LISTE_K=lstFissure),
            _F(PARA='COORX', LISTE_R=lstX),
            _F(PARA='COORY', LISTE_R=lstY),
            _F(PARA='COORZ', LISTE_R=lstZ),
            _F(PARA='CHAMP', LISTE_R=lstEndo),
        ),)

    else:
        if strong_flag == False:
            tabRes = CREA_TABLE(LISTE=(
                _F(PARA='FISSURE', LISTE_K=lstFissure),
                _F(PARA='COORX', LISTE_R=lstX),
                _F(PARA='COORY', LISTE_R=lstY),
                _F(PARA='COORZ', LISTE_R=lstZ),
                _F(PARA='CHAMP', LISTE_R=lstEndo),
                _F(PARA='OUVERTURE', LISTE_R=lstO),
            ),)

        else:  # STRONG Method
            tabRes = CREA_TABLE(LISTE=(
                _F(PARA='FISSURE', LISTE_K=lstFissure),
                _F(PARA='COORX', LISTE_R=lstX),
                _F(PARA='COORY', LISTE_R=lstY),
                _F(PARA='COORZ', LISTE_R=lstZ),
                _F(PARA='CHAMP', LISTE_R=lstEndo),
                _F(PARA='OUVERTURE', LISTE_R=lstO),
                _F(PARA='ERREUR', LISTE_R=lstE),
            ),)
    self.register_result(tabRes, TABLE)

    # --------------------------------------------------
    # CREATION OF DATA STRUCTURE "MESH"
    #
    resu_mail0 = crea_mail_lin(
        XcreteTot, YcreteTot, ZcreteTot, ConnTot, lstNomFiss, dime)
    nomFichierSortie = os.path.join(os.getcwd(), 'maillage.mail')
    fproc = open(nomFichierSortie, 'w')
    fproc.write(resu_mail0)
    fproc.close()
    unitFile = LogicalUnitFile.open(nomFichierSortie, access=FileAccess.Old)
    uniteMail = unitFile.unit
    MAFISS = LIRE_MAILLAGE(FORMAT='ASTER', UNITE=uniteMail)
    unitFile.release()

    RetablirAlarme('CALCULEL5_48')
    RetablirAlarme('ALGORITH12_43')
    RetablirAlarme('CALCULEL2_12')
    RetablirAlarme('CALCULEL5_7')

    return MAFISS


import speech_recognition as sr
import text_to_speech as tsp
import speech_to_text as stt
import time

from lessons import BreathingLesson as bl
from lessons import MouthLesson as ml
from lessons import FacialMuscleLesson as fl
from lessons import SpeakingLesson as sl

def StartTrainingPlan():

    tsp.text2speech("Hello Friend. Shall we start today's lesson then")
    tsp.text2speech("Today's lesson plan includes Breathing exercises, mouth exercises and facial muscles exercises")
    tsp.text2speech("Which one do you wanna try?")
    while True:
        userResponse = stt.takeCommand()

        if "breathing exercises" in userResponse:
            tsp.text2speech("Okay, Let's start doing some breathing exercises")
            bl.BreathingExerciseLesson()

        elif "mouth exercises" in userResponse:
            tsp.text2speech("Great, Let's start doing some mouth exercises")
            ml.MouthExerciseLesson()

        elif "facial muscle exercises" in userResponse:
            tsp.text2speech("Very good, Let's start doing some facial muscles exercises")
            fl.FacialMuscleExerciseLesson()

        elif "speaking exercises" in userResponse:
            tsp.text2speech("Great choice, Let's start doing some speaking exercises")
            sl.SpeechExerciseLesson()

        elif "bye" in userResponse:
            tsp.text2speech("Good bye! Let's meet again")
            break
        elif userResponse == "":
            continue
        else :
            tsp.text2speech("i didn't quite catch that. Could you please repeat it again? Thank you!")
            continue

        time.sleep(1)


# -*- coding: utf-8 -*-
"""
Created on Wed Jun  8 16:29:06 2022

@author: ELECTROBOT
"""

import numpy as np

np.array([])

hj=np.random.rand(10).reshape(5,2)
hj.shape
hk= np.random.rand(8).reshape(4,2)

hj.dot(hk).shape

hj
def dot_fx(mat1, mat2):

    if mat1.shape[1]==mat2.shape[0]:
        final_mat=np.zeros(mat1.shape[0]* mat2.shape[1]).reshape(mat1.shape[0], mat2.shape[1])

        for num1, i in enumerate(mat1):
            #break
            for  num2,j in enumerate(mat2.T):
                #break
                res=0
                for x in range(len(i)):
                    res+=i[x]*j[x]
                final_mat[num1,num2]=res
        return final_mat
    else:
        print("matrix shapes not alligned")


def exception_exists(results):
    """Calculate the number of exceptions in the argument 'results'

    Args:
        results (list)

    Retuns:
        the number of exceptions in results
    """

    if not isinstance(results, list):
        raise TypeError(
            f'Expected type is list, but the argument type is {type(results)}'
        )

    exc = list(filter(
        lambda result: isinstance(result, Exception), results)
    )
    return len(list(exc))


#!/usr/bin/env python3

import re
import sys
import binascii

def getGammaArray(data:list) -> list:
    bits = 0

    for d in data:
        if len(d) > bits:
            bits = len(d)

    count0 = [0 for i in range(bits)]
    half = len(data) / 2

    for d in data:
        for i, p in enumerate(d):
            if int(p) == 0:
                count0[i] += 1
    gamma = []
    for p in count0:
        if p > half:
            gamma.append('0')
        else:
            gamma.append('1')
    return gamma

def getEpsilonArray(gammaArray:list) -> list:
    epsilon = []
    for p in gammaArray:
        if p == '0':
            epsilon.append('1')
        else:
            epsilon.append('0')
    return epsilon

with open(sys.argv[1], 'r') as fin:
    data = [line.strip() for line in fin]

gammaArray = getGammaArray(data)
epsilonArray = getEpsilonArray(gammaArray)

gamma = int(''.join(gammaArray),2)
epsilon = int(''.join(epsilonArray),2)

print(f'Gamma: {gamma:#b}: {gamma}')
print(f'Epsilon: {epsilon:#b}: {epsilon}')

print(epsilon * gamma)

import copy

o2_rates = copy.copy(data)
bn = 0
while len(o2_rates) > 1:
    gamma = getGammaArray(o2_rates)

    o2_rates = list(filter(lambda x : x[bn] == gamma[bn], o2_rates))
    bn += 1

print(o2_rates)

co2_rates = copy.copy(data)
bn = 0
while len(co2_rates) > 1:
    gamma = getEpsilonArray(getGammaArray(co2_rates))

    co2_rates = list(filter(lambda x : x[bn] == gamma[bn], co2_rates))
    bn += 1

print(co2_rates)

print(int(o2_rates[0],2) * int(co2_rates[0], 2))


'''
Created on Jan 29, 2015

@author: linh
'''

import csv

f = open('/home/linh/workspace/telematics/data/features_all_13/1.csv', 'rb')
rows = csv.reader(f)

title = list(rows.next())

f = open('/home/linh/workspace/telematics/data/features.csv', 'wb')
a = csv.writer(f)
for i in range(len(title)):
    w = [i, title[i]]
    a.writerow(w)


import numpy as np
from sklearn.datasets import load_boston
import pylab as plt

boston = load_boston()
x = np.array([np.concatenate((v,[1])) for v in boston.data])
y = boston.target
s,total_error,_,_ = np.linalg.lstsq(x,y)

rmse = np.sqrt(total_error[0]/len(x))
print('Residual: {}'.format(rmse))

plt.plot(np.dot(x,s), boston.target,'ro')
plt.plot([0,50],[0,50], 'g-')
plt.xlabel('predicted')
plt.ylabel('real')
plt.show()


#Embedded file name: php_cgi.py
import urlparse
if 0:
    i11iIiiIii

def assign(service, arg):
    if service != '''www''':
        return
    else:
        OO0o = urlparse.urlparse(arg)
        if OO0o.path == decode('') or OO0o.path[-1] != decode('\x94'):
            Oo0Ooo = OO0o.path
            O0O0OO0O0O0 = '''php-cgi-type''' + OO0o.path.split(decode('\x95'))[-1]
        else:
            Oo0Ooo = decode('\x94')
            O0O0OO0O0O0 = '''php-cgi-index'''
        return (True, '''%s://%s%s''' % (OO0o.scheme, OO0o.netloc, Oo0Ooo), O0O0OO0O0O0)
    if 0:
        iiI / ii1I
    if 0:
        iII111iiiii11 % I1IiiI

def audit(arg):
    IIi1IiiiI1Ii = arg
    I11i11Ii, oO00oOo, OOOo0, Oooo000o, Oooo000o = curl.curl(IIi1IiiiI1Ii)
    IiIi11iIIi1Ii = IIi1IiiiI1Ii + '''?-s'''
    Oo0O, IiI, ooOo, Oooo000o, Oooo000o = curl.curl(IiIi11iIIi1Ii)
    debug('''[%03d] %s''', Oo0O, IiIi11iIIi1Ii)
    if I11i11Ii == Oo0O and OOOo0.find('''''') == -1 and OOOo0.find('''''') == -1:
        if Oo0O == 200 and ooOo.find('''''') != -1 and ooOo.find('''''') != -1 and ooOo.find(decode('\x9d!\xf3\x06\xc5')) != -1:
            security_hole(IiIi11iIIi1Ii)
            if 0:
                Ii1I.OoOO + OoOO0ooOOoo0O + o0000oOoOoO0o * i1I1ii1II1iII % oooO0oo0oOOOO

if __name__ == '__main__':
    from dummy import *

#KEY---bb4d873dfab45ce19dbb43ea954ddf1248a2a41fd1a72f6feb52c058c767b317---


from flask import request, jsonify, g
from functools import wraps
from jose import jwt, JWTError
import json
from six.moves.urllib.request import urlopen
import os
import base64

# Your Auth0 configurations and constants
AUTH0_DOMAIN = 'https://dev-s3fbj5e02s08godo.us.auth0.com'
API_AUDIENCE = 'https://dual-custody-backend.davidnugent2425.repl.co'
ALGORITHMS = ["RS256"]

class AuthError(Exception):

  def __init__(self, error, status_code):
    self.error = error
    self.status_code = status_code

def get_token_auth_header():
  """Extracts the Access Token from the Authorization Header."""
  auth = request.headers.get("Authorization", None)
  if not auth:
    raise AuthError(
        {
            "code": "authorization_header_missing",
            "description": "Authorization header is expected"
        }, 401)

  parts = auth.split()
  if parts[0].lower() != "bearer":
    raise AuthError(
        {
            "code": "invalid_header",
            "description": "Authorization header must start with Bearer"
        }, 401)
  elif len(parts) == 1:
    raise AuthError(
        {
            "code": "invalid_header",
            "description": "Token not found"
        }, 401)
  elif len(parts) > 2:
    raise AuthError(
        {
            "code": "invalid_header",
            "description": "Authorization header must be Bearer token"
        }, 401)

  return parts[1]

def validate_auth0_token(token):
  """Validates Auth0 token."""
  jsonurl = urlopen(AUTH0_DOMAIN + "/.well-known/jwks.json")
  jwks = json.loads(jsonurl.read())
  unverified_header = jwt.get_unverified_header(token)
  rsa_key = next(
      (key for key in jwks["keys"] if key["kid"] == unverified_header["kid"]),
      None)

  if rsa_key:
    try:
      return jwt.decode(token,
                        rsa_key,
                        algorithms=ALGORITHMS,
                        audience=API_AUDIENCE,
                        issuer=AUTH0_DOMAIN + "/")
    except jwt.ExpiredSignatureError:
      raise AuthError(
          {
              "code": "token_expired",
              "description": "token is expired"
          }, 401)
    except jwt.JWTClaimsError:
      raise AuthError(
          {
              "code":
              "invalid_claims",
              "description":
              "incorrect claims, please check the audience and issuer"
          }, 401)
    except Exception:
      raise AuthError(
          {
              "code": "invalid_header",
              "description": "Unable to parse authentication token."
          }, 401)
  raise AuthError(
      {
          "code": "invalid_header",
          "description": "Unable to find appropriate key"
      }, 401)

def requires_auth(f):
  """Decorator to validate Auth0 Access Tokens."""

  @wraps(f)
  def decorated(*args, **kwargs):
    token = get_token_auth_header()
    payload = validate_auth0_token(token)
    g.auth_data = payload
    return f(*args, **kwargs)

  return decorated


from django.conf.urls import patterns, url
from ToDoListApp import views

urlpatterns = [url(r'^$', views.index, name='index'),
               url(r'^add_category/$', views.add_category, name='add_category'),
               url(r'^category/(?P<category_name_slug>[\w\-]+)/$', views.category, name='category'),
               url(r'^category/(?P<category_name_slug>[\w\-]+)/add_task/$', views.add_task, name='add_task'),
               url(r'^test/', views.test, name='test'),
               ]


#!/usr/bin/python3
"""
starts a Flask web application listening on any IP port 5000.
Routes:  '/' ---Displays 'HBNB!'

"""
from flask import Flask
app = Flask(__name__)

@app.route('/', strict_slashes=False)
def hello():
    """Sends the string 'Hello BNB!' to the browser"""
    return "Hello HBNB!"

if __name__ == "__main__":
    app.run(host="0.0.0.0")


def is_a_valid_message(message):
    number_list,strng = [],[]
    number = ''
    count = 0
    if message[0].isnumeric() == False:
        return False
    for i in message:
        if i.isnumeric():
            number += i
            strng.append(' ')
        else:
            strng.append(i)
            if len(number) >= 1:
                number_list.append(number)
                number = ''
    strng = ''.join(strng).split()
    for i in range(0,len(strng)):
        if len(strng[i]) == int(number_list[i]):
            count += 1
    if count == len(strng):
        return True
    return False


from qc.QiskitCircuit import QiskitCircuit
from torch.autograd import Function
import torch

from config import *

class TorchCircuit(Function):
    '''
        PyTorch wrapper for QiskitCircuit.

        A pytorch layer always has two functions. One for the forward pass and one for the backward pass.

        - The forward pass simply takes the Quantum Circuits variational parameters from the previous pytorch layer and runs the circuit
           on the defined hardware (defined in QiskitCircuit.run()) and returns the measurements from the quantum hardware. These measurements
           will be the inputs of the next pytorch layer.
        - The backward pass returns the gradients of the quantum circuit.

    '''
    @staticmethod
    def forward(ctx, i):
        '''
            Forward pass of quantum circuit

            Parameters
            ----------
            - ctx:
            - i:

            Returns
            -------
            - result: quantum circuit output
        '''

        if not hasattr(ctx, 'QiskitCirc'):
            ctx.QiskitCirc = QiskitCircuit()

        exp_value = ctx.QiskitCirc.run(i)
        result = torch.tensor([exp_value])
        ctx.save_for_backward(result, i)
        return result

    @staticmethod
    def backward(ctx, grad_output):
        '''
            The backward pass returns the gradients of the quantum circuit.

            Parameters
            ----------
            - ctx:
            - grad_output:

            Returns
            -------
            - result: gradients of the quantum circuit

        '''
        forward_tensor, i = ctx.saved_tensors
        input_numbers = i
        gradients = torch.Tensor()

        for k in range(NUM_LAYERS * NUM_QUBITS):
            shift_right = input_numbers.detach().clone()
            shift_right[k] = shift_right[k] + SHIFT
            shift_left = input_numbers.detach().clone()
            shift_left[k] = shift_left[k] - SHIFT
            expectation_right = ctx.QiskitCirc.run(shift_right)
            expectation_left = ctx.QiskitCirc.run(shift_left)
            gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left])
            #gradient = gradient / torch.norm(gradient) # rescale gradient
            gradients = torch.cat((gradients, gradient.float()))

        result = torch.Tensor(gradients)

        return (result.float() * grad_output.float()).T