"""
This is a script to convert curve info in other formats to NRML, v0.5.

It is being modified on a needs basis.

"""

import csv
import numpy

import xlrd
from hazimp.misc import csv2dict

FLOOD_HOUSE_FABRIC = 'structural_domestic_flood_2012'
FLOOD_HOUSE_CONTENTS = 'contents_domestic_flood_2012'
LOSS_CAT_FABRIC = 'structural_loss_ratio'
LOSS_CAT_CONTENTS = 'contents_loss_ratio'
FLOOD_IMT = 'water depth above ground floor (m)'

def xml_write_variable(xml_h, name, value):
    """
    Add a variable name and value to an xml file.

    :param xml_h: A handle to the xml file.
    :param name: The name of the variable.
    :param value: The value of the variable.
    """
    xml_h.write('%s="' % name)
    try:
        xml_h.write(value)
    except TypeError:
        if numpy.isnan(value):
            # This is what we need for blank string values.
            # Probably not universal though.
            xml_h.write('')
        else:
            # to rethrow error
            xml_h.write(value)
    xml_h.write('" ')

def write_nrml_top(xml_h, vulnerability_set_id, asset_category, loss_category):
    """
    Write the top section of an nrml file.

    :param xml_h: A handle to the xml file.
    :param vulnerability_set_id: String name of the vulnerability set.
    :param asset_category: String name of the assert category.
    :param loss_category: String name of the loss category.
    :param imt: String name of the intensity measure type.
    :param imls: 1D vector of the intensity measure values (x-axis) of the
                 vuln curve.
    """

    intro = """<?xml version='1.0' encoding='utf-8'?>
<nrml xmlns="http://openquake.org/xmlns/nrml/0.5"
      xmlns:gml="http://www.opengis.net/gml">

    <vulnerabilityModel """
    xml_h.write(intro)
    xml_write_variable(xml_h, "id", vulnerability_set_id)
    xml_write_variable(xml_h, "assetCategory", asset_category)
    xml_write_variable(xml_h, "lossCategory", loss_category)
    xml_h.write('>\n')

def write_nrml_curve(xml_h, vulnerability_function_id, imls: list, imt: str,
                     loss_ratio, coef_var):
    """
    Write the curve info of an nrml file.

    :param xml_h: A handle to the xml file.
    :param vulnerability_function_id: String name of the vuln function.
    :param imls: 1D vector of the intensity measure values (x-axis) of the
                 vuln curve.
    :param imt: intensity measure type
    :param loss_ratio: 1D vector of the loss ratio values (y-axis) of the
                 vuln curve.
    :param coef_var: 1D vector of the coefficient of variation values (y-axis)
                     of the vuln curve.
    """
    xml_h.write("<vulnerabilityFunction ")
    xml_write_variable(xml_h, "id",
                       vulnerability_function_id)
    xml_h.write('')
    xml_h.write('dist="LN">\n  <imls ')
    xml_write_variable(xml_h, "imt", imt)
    xml_h.write('>')
    for iml in imls:
        if numpy.isnan(iml):
            continue
        xml_h.write(str(iml) + ' ')
    xml_h.write('</imls>\n')
    xml_h.write('<meanLRs>')
    xml_h.write(loss_ratio)
    xml_h.write('</meanLRs>\n')
    xml_h.write('<covLRs>')
    xml_h.write(coef_var)
    xml_h.write('</covLRs>\n')
    xml_h.write('</vulnerabilityFunction>\n\n')

def write_nrml_close(xml_h):
    """
    Write the final section of an nrml file and close it.

    :param xml_h: A handle to the xml file.
    """
    xml_h.write('</vulnerabilityModel>\n')
    xml_h.write('</nrml>\n')

def csv_curve2nrml(csv_filename, xml_filename):
    """
    Read in a csv hazard curve file and convert it to an NRML file.

    :param csv_filename: The csv file to be read.
    :param xml_filename: The NRML file to be written.
    """
    # Read the file twice.
    # Once for the non-per-curve info and then
    # for the per curve info.

    csv_dict = csv2dict(csv_filename)
    vulnerability_set_id = csv_dict['vulnerabilitySetID'][0]
    try:
        asset_category = csv_dict['assetCategory'][0]
    except IndexError:
        # Assume asset_category is empty
        asset_category = ''
    loss_category = csv_dict['lossCategory'][0]
    imls = [v for v in csv_dict['IML'] if not v == '']

    # open the csv file to read the rows
    reader = csv.DictReader(open(csv_filename, 'r'))
    with open(xml_filename, 'w') as xml_h:
        write_nrml_top(xml_h, vulnerability_set_id, asset_category,
                       loss_category)

        # Loop over the csv file info
        for row in reader:
            row = {k.strip(): v.strip() for k, v in list(row.items())}
            if row['Alpha'] == 'N/A':
                # This row has no model
                continue
            coef_var = ''
            loss_ratio = ''
            for iml in imls:
                if numpy.isnan(iml):
                    continue
                loss_ratio += str(row[str(int(iml))]) + ' '
                coef_var += str((float(row['Alpha'])/float(row['Beta']))) + ' '
            write_nrml_curve(xml_h, row['vulnerabilityFunctionID'],
                             imls, csv_dict['IMT'][0],
                             loss_ratio, coef_var)

        write_nrml_close(xml_h)

def validate_excel_curve_data(excel_file):
    """
    Check that the titles and the water depths do not change
    from sheet to sheet.
    The first 2 rows are titles.
    The first coulmn is the water depth.

    :param excel_file: The excel file to validate.
    """

    default = None
    valid = True
    titles = {}
    wb = xlrd.open_workbook(excel_file)
    for s in wb.sheets():
        title = []
        # The first 3 rows should be titles that are the same,
        # except for the 2nd value on the 1st row.
        for row in [0, 1, 2]:
            values = []
            for col in range(s.ncols):
                val = s.cell(row, col).value

                # This is just for visualising.
                try:
                    val = str(val)
                except TypeError:
                    pass

                values.append(val)
            title.append(values)
        # Remove the  2nd value on the 1st row.
        del title[0][1]
        titles[s.name] = title
        default = title

    if default is None:
        valid = False
    else:
        # Check that all sheets have the same title info
        for title in list(titles.values()):
            if not title == default:
                print(("title", title))
                print(("default", default))
                valid = False
                break

    return valid and check_identical_depths(wb)

def check_identical_depths(wb):
    """
    Check that the depth values are the same for all workbooks.
    Check that the first colum, starting at the 4th row, is identical.

    :param wb: The excel workbook xlrd object.
    """

    valid = True
    default = None
    depths = {}
    for s in wb.sheets():
        values = []
        for row in range(3, s.nrows):
            col = 0
            val = s.cell(row, col).value
            values.append(val)
        depths[s.name] = values
        default = values

    if default is None:
        valid = False
    else:
        # Check that all sheets have the same title info
        for depth in list(depths.values()):
            if not depth == default:
                print(("depth", depth))
                print(("default", default))
                valid = False
                break

    return valid

def read_excel_curve_data(excel_file):
    """
    Read in the excel file info.  Specific, undocumented format.

    :param excel_file: The excel workbook.
    """
    wb = xlrd.open_workbook(excel_file)
    a_sheet = wb.sheets()[0]

    # Get a list of the depths
    depths = []
    for row in range(3, a_sheet.nrows):
        col = 0
        val = a_sheet.cell(row, col).value
        depths.append(val)
    fabric_vuln_curves, contents_vuln_curves = read_excel_worksheet(wb)

    return depths, fabric_vuln_curves, contents_vuln_curves

def read_excel_worksheet(wb):
    """
    Read an excel worksheet

    :param wb: The excel workbook xlrd object.
    """
    fabric_vuln_curves = {}  # the keys are curve names.
    contents_vuln_curves = {}  # the keys are curve names.

    for s in wb.sheets():
        di_block = []
        for row in range(3, s.nrows):
            values = []
            for col in range(s.ncols):
                values.append(s.cell(row, col).value)
            di_block.append(values)
        # Get individual curves from the curve block.
        # Convert the curves into an array
        di_array = numpy.asarray(di_block)
        insure = {"INSURED": 0, "UNINSURED": 4}
        for key in insure:
            # Read in the structure type
            # The 2nd value on the 1st row.
            curve_id_base = s.cell(0, 1).value.split()[0] + '_' + key
            fabric_vuln_curves[curve_id_base] = di_array[:, 1 + insure[key]]
            tag_offset = {'_SAVE': 2, '_NOACTION': 3, '_EXPOSE': 4}
            for tag in tag_offset:
                curve_id = curve_id_base + tag
                contents_vuln_curves[curve_id] = di_array[:, tag_offset[tag]
                                                          + insure[key]]
    return fabric_vuln_curves, contents_vuln_curves

def excel_curve2nrml(contents_filename, fabric_filename, xls_filename):
    """
    Read in an excel flood curve file and convert it to an NRML file.

    The excel file format is specific and best understood by looking
    at the file flood_2012_test.xlsx.

    :param contents_filename: The contents NRML file to be created.
    :param fabric_filename: The fabric NRML file to be created.
    :param xls_filename: The excel file that is the basis of the NRML files.
    """

    validate_excel_curve_data(xls_filename)

    depths, fabric_vuln_curves, contents_vuln_curves = read_excel_curve_data(
        xls_filename)
    curve_info = [{'curves': fabric_vuln_curves,
                   'set_id': FLOOD_HOUSE_FABRIC,
                   'asset': '',
                   'loss_category': LOSS_CAT_FABRIC,
                   'file_name': fabric_filename},
                  {'curves': contents_vuln_curves,
                   'set_id': FLOOD_HOUSE_CONTENTS,
                   'asset': '',
                   'loss_category': LOSS_CAT_CONTENTS,
                   'file_name': contents_filename}]

    for set_id in curve_info:

        with open(set_id['file_name'], 'w') as xml_h:
            write_nrml_top(
                xml_h,
                set_id['set_id'],
                set_id['asset'],
                set_id['loss_category']
            )

            # Loop over the csv file info
            for curve_dic_key in set_id['curves']:
                curve_values = set_id['curves'][curve_dic_key]
                coef_var = ''
                loss_ratio = ''
                # creating the coef_var vector
                for iml in curve_values:
                    loss_ratio += str(iml) + ' '
                    coef_var += '0 '
                write_nrml_curve(xml_h, curve_dic_key, depths, FLOOD_IMT,
                                 loss_ratio, coef_var)

            write_nrml_close(xml_h)

# -----------------------------------------------------------
if __name__ == "__main__":

    import os
    import argparse
    parser = argparse.ArgumentParser(
        description="Convert curve data to NRML format"
        )

    parser.add_argument("-i", "--input", required=True,
                help="Input curve file (either Excel or csv)")
    parser.add_argument("-o", "--output", help="Output file name")
    parser.add_argument("-f", "--format", choices=['csv', 'xlsx'],
                help="File format (inferred from input file if not given)")

    args = parser.parse_args()

    input_file = args.input
    base, ext = os.path.splitext(input_file)

    if args.output:
        output_file = args.output
    else:
        output_file = f"{base}.xml"

    if args.format:
        informat = args.format
    else:
        if ext=='.csv':
            informat = 'csv'
        elif ext.strip('.') in ['xls', 'xlsx']:
            informat = 'xlsx'
        else:
            print("Not sure what the file format is")
            print("Use the -f option to specify")

    if informat == 'csv':
        csv_curve2nrml(input_file, output_file)
    elif informat == 'xlsx':
        output_contents_file = f"{base}_contents.xml"
        output_fabric_file = f"{base}_fabric.xml"
        excel_curve2nrml(output_contents_file, output_fabric_file, input_file)


import logging
import re
from datetime import datetime
from typing import Optional

import pandas as pd
from bs4 import BeautifulSoup, Tag

from scraping_netkeiba import url

class Horse:
    def __init__(self, horse_id: str, html: str):
        self.__horse_id: str = horse_id
        self.__soup: BeautifulSoup = BeautifulSoup(html, "html.parser")
        self.__horse_title: Tag = self.__soup.select_one("div.horse_title")
        self.__profile_table: Tag = self.__soup.select_one("table.db_prof_table")
        self.validate()

    def name(self) -> str:
        return self.__horse_title.select_one("h1").text

    def eng_name(self) -> str:
        return self.__horse_title.select_one("p.eng_name").text

    def gender(self) -> str:
        horse_title_sentence: str = self.__horse_title.select_one("p.txt_01").text
        return re.match(r"^.*([牡牝セ]).*$", horse_title_sentence).group(1)

    def birth_date(self) -> datetime.date:
        birth_date_tag: Tag = self.__profile_table.find(
            "th", string="生年月日"
        ).parent.find("td")
        return datetime.strptime(birth_date_tag.text, "%Y年%m月%d日").date()

    def trainer_id(self) -> str:
        trainer_tag: Tag = (
            self.__profile_table.find("th", string="調教師").parent.find("td").find("a")
        )
        return url.trainer_pattern().match(trainer_tag.get("href")).group(1)

    def owner_id(self) -> str:
        owner_tag: Tag = (
            self.__profile_table.find("th", string="馬主").parent.find("td").find("a")
        )
        return url.owner_pattern().match(owner_tag.get("href")).group(1)

    def breeder_id(self) -> str:
        breeder_tag: Tag = (
            self.__profile_table.find("th", string="生産者").parent.find("td").find("a")
        )
        return url.breeder_pattern().match(breeder_tag.get("href")).group(1)

    def as_dataframe(self) -> pd.DataFrame:
        try:
            return pd.DataFrame.from_dict(
                {
                    "horse_id": [self.__horse_id],
                    "name": [self.name()],
                    "eng_name": [self.eng_name()],
                    "gender": [self.gender()],
                    "birth_date": [self.birth_date()],
                    "trainer_id": [self.trainer_id()],
                    "owner_id": [self.owner_id()],
                    "breeder_id": [self.breeder_id()],
                }
            )
        except Exception as e:
            logging.warning(f"An error occurred while scraping Horse: {e}")

    def validate(self):
        top: Optional[Tag] = self.__soup.find(
            "a", href=url.horse_pattern().match, attrs={"class": "active"}
        )
        if top is None:
            raise Exception("Active horse url is not found")

        top_href: str = top.get("href")
        horse_id: str = url.horse_pattern().match(top_href).group(1)
        if self.__horse_id != horse_id:
            raise Exception(
                f'Invalid horse id: expected "{self.__horse_id}", got "{horse_id}"'
            )


import streamlit as st
import joblib
import pandas as pd

# loading the trained model
model = joblib.load('XGBClassifier.pkl')

st.title('XGBoost Classifier')

feature1 = st.sidebar.slider('feature1', 10.59, 21.18, 13.0)
feature2 = st.sidebar.slider('feature2', 12.41, 17.25, 13.0)
feature3 = st.sidebar.slider('feature3', 0.8081,0.9183,  0.9)
feature4 = st.sidebar.slider('feature4', 4.899, 6.675, 4.9)
feature5 = st.sidebar.slider('feature5', 2.63, 4.033, 3.0)
feature6 = st.sidebar.slider('feature6',0.7651, 8.456, 3.0)
feature7 = st.sidebar.slider('feature7', 4.519, 6.55, 5.0)

df = pd.DataFrame({'0': feature1, '1': feature2, '2': feature3, '3': feature4, '4': feature5, '5': feature6, '6': feature7}, index=[0])

model_prediction = model.predict(df)

st.header('Prediction')
st.write(df, model)
prediction = pd.DataFrame({'Prediction': model_prediction})
st.write(prediction)


import csv
import logging
from contextlib import closing
from copy import deepcopy

import matplotlib
# Numpy
import numpy as np
from matplotlib.backends.backend_qt5agg import \
    FigureCanvasQTAgg as FigureCanvas
# Plotting functions and hooks for GUI
from matplotlib.figure import Figure
from matplotlib.widgets import MultiCursor
# GUI functionality
from PyQt5.QtCore import QCoreApplication, Qt
from PyQt5.QtGui import QIntValidator, QKeySequence
from PyQt5.QtWidgets import QFileDialog, QShortcut
from PyQt5.uic import loadUiType

from icecream import ic

# Local modules
# import satkit.io as satkit_io
from satkit.data_structures import RecordingSession
from satkit.configuration import gui_params
from satkit.gui import BoundaryAnimator, ReplaceDialog
from satkit.plot.plot import plot_density
from satkit.plot import (Normalisation, plot_satgrid_tier, plot_spectrogram,
                         plot_timeseries, plot_wav)
from satkit.save_and_load import (
    save_recordings, save_recording_session, load_recording_session)
from satkit.ui_callbacks import UiCallbacks

# Load the GUI layout generated with QtDesigner.
Ui_MainWindow, QMainWindow = loadUiType('satkit/gui/qt_annotator.ui')

_qt_annotator_logger = logging.getLogger('satkit.qt_annotator')

def setup_qtannotator_ui_callbacks():

    UiCallbacks.register_overwrite_confirmation_callback(
        ReplaceDialog.confirm_overwrite)

class PdQtAnnotator(QMainWindow, Ui_MainWindow):
    """
    Qt_Annotator_Window is a GUI class for annotating PD curves.

    The annotator works with PD curves and allows
    selection of a single points (labelled as pdOnset in the saved file).
    The GUI also displays the waveform, and if TextGrids
    are provided, the acoustic segment boundaries.
    """

    default_categories = ['Stable', 'Hesitation', 'Chaos', 'No data',
                          'Not set']

    default_tongue_positions = ['High', 'Low', 'Other / Not visible']

    def __init__(self, recording_session: RecordingSession, args,
                 xlim=(-0.25, 1.5),
                 categories=None, pickle_filename=None):
        super().__init__()
        self.setupUi(self)

        setup_qtannotator_ui_callbacks()

        self.recording_session = recording_session
        self.recordings = recording_session.recordings
        self.index = 0
        self.max_index = len(self.recordings)

        self.commandlineargs = args
        self.display_tongue = args.displayTongue

        if categories is None:
            self.categories = PdQtAnnotator.default_categories
        else:
            self.categories = categories
        self.tongue_positions = PdQtAnnotator.default_tongue_positions
        self._add_annotations()

        self.pickle_filename = pickle_filename

        #
        # Menu actions and shortcuts
        #
        self.close_window_shortcut = QShortcut(
            QKeySequence(self.tr("Ctrl+W", "File|Quit")), self)
        self.close_window_shortcut.activated.connect(self.quit)

        self.export_figure_shortcut = QShortcut(QKeySequence(
            self.tr("Ctrl+E", "File|Export figure...")), self)
        self.export_figure_shortcut.activated.connect(self.export_figure)

        self.actionOpen.triggered.connect(self.open)
        self.actionSaveAll.triggered.connect(self.save_all)
        # self.actionSaveToPickle.triggered.connect(self.save_to_pickle)
        self.action_export_figure.triggered.connect(self.export_figure)

        self.actionNext.triggered.connect(self.next)
        self.actionPrevious.triggered.connect(self.prev)

        self.actionNext_Frame.triggered.connect(self.next_frame)
        self.actionPrevious_Frame.triggered.connect(self.previous_frame)

        self.actionQuit.triggered.connect(self.quit)

        #
        # GUI buttons
        #
        self.nextButton.clicked.connect(self.next)
        self.prevButton.clicked.connect(self.prev)
        self.saveButton.clicked.connect(self.save_all)
        self.exportButton.clicked.connect(self.export)

        go_validator = QIntValidator(1, self.max_index + 1, self)
        self.goLineEdit.setValidator(go_validator)
        self.goButton.clicked.connect(self.go_to_recording)

        # TODO: add recording list to the display and highlight current
        # recording

        # self.categoryRB_1.toggled.connect(self.pd_category_cb)
        # self.categoryRB_2.toggled.connect(self.pd_category_cb)
        # self.categoryRB_3.toggled.connect(self.pd_category_cb)
        # self.categoryRB_4.toggled.connect(self.pd_category_cb)
        # self.categoryRB_5.toggled.connect(self.pd_category_cb)

        self.positionRB_1.toggled.connect(self.tongue_position_cb)
        self.positionRB_2.toggled.connect(self.tongue_position_cb)
        self.positionRB_3.toggled.connect(self.tongue_position_cb)

        self.figure = Figure()
        self.canvas = FigureCanvas(self.figure)
        self.mplWindowVerticalLayout.addWidget(self.canvas)
        self.data_axes = []
        self.tier_axes = []

        self.shift_is_held = False
        # self.cid_key_press = self.figure.canvas.mpl_connect('key_press_event', self.on_key_press)
        # self.cid_key_release = self.figure.canvas.mpl_connect('key_release_event', self.on_key_release)

        matplotlib.rcParams.update(
            {'font.size': gui_params['default font size']})

        self.xlim = xlim

        # TODO this should be based on the plotted modalities, not on a random
        # choice from depths of time. It is a good idea though: Setting ylim
        # over the whole data rather than on recording.
        max_pds = np.zeros(len(self.recordings))
        for i, recording in enumerate(self.recordings):
            if 'PD l1 on RawUltrasound' in recording.modalities:
                max_pds[i] = np.max(recording.modalities
                                    ['PD l1 on RawUltrasound'].data[10:])
        self.ylim = (-50, np.max(max_pds)*1.05)

        height_ratios = [gui_params['data/tier height ratios']["data"],
                         gui_params['data/tier height ratios']["tier"]]
        self.main_grid_spec = self.figure.add_gridspec(
            nrows=2,
            ncols=1,
            hspace=0,
            wspace=0,
            height_ratios=height_ratios)

        nro_data_modalities = gui_params['number of data axes']
        self.data_grid_spec = self.main_grid_spec[0].subgridspec(
            nro_data_modalities, 1, hspace=0, wspace=0)
        self.data_axes.append(self.figure.add_subplot(self.data_grid_spec[0]))
        for i in range(1, nro_data_modalities):
            self.data_axes.append(
                self.figure.add_subplot(
                    self.data_grid_spec[i],
                    sharex=self.data_axes[0]))

        self.ultra_fig = Figure()
        self.ultra_canvas = FigureCanvas(self.ultra_fig)
        self.verticalLayout_6.addWidget(self.ultra_canvas)
        self.ultra_axes = self.ultra_fig.add_axes([0, 0, 1, 1])

        if not self.current.excluded:
            self.draw_plots()

        self.figure.align_ylabels()

        self.multicursor = None

        self.show()
        self.ultra_canvas.draw()

    @property
    def current(self):
        """Current recording index."""
        return self.recordings[self.index]

    @property
    def default_annotations(self):
        """List default annotations and their default values as a dict."""
        return {
            'pdCategory': self.categories[-1],
            'tonguePosition': self.tongue_positions[-1],
            'selected_time': -1.0,
            'selection_index': -1,
        }

    def _add_annotations(self):
        """Add the annotations."""
        for recording in self.recordings:
            if recording.annotations:
                recording.annotations = dict(
                    list(self.default_annotations.items()) +
                    list(recording.annotations.items()))
            else:
                recording.annotations = deepcopy(self.default_annotations)

    def _get_title(self):
        """
        Private helper function for generating the title.
        """
        text = 'Recording: ' + str(self.index+1) + '/' + str(self.max_index)
        text += ', prompt: ' + self.current.meta_data.prompt
        return text

    def _get_long_title(self):
        """
        Private helper function for generating a longer title for a figure.
        """
        text = 'Recording: ' + str(self.index+1) + '/' + str(self.max_index)
        text += ', Speaker: ' + str(self.current.meta_data.participant_id)
        text += ', prompt: ' + self.current.meta_data.prompt
        return text

    def clear_axes(self):
        """Clear data axes of this annotator."""
        for axes in self.data_axes:
            axes.cla()

    def update(self):
        """
        Updates the graphs but not the buttons.
        """
        self.clear_axes()
        if self.current.excluded:
            pass

        self.draw_plots()
        self.multicursor = MultiCursor(
            self.canvas,
            axes=self.data_axes+self.tier_axes,
            color='deepskyblue', linestyle="--", lw=1)
        self.figure.canvas.draw()

        if self.display_tongue:
            _qt_annotator_logger.debug("Drawing ultra frame in update")
            self.draw_ultra_frame()

    def update_ui(self):
        """
        Updates parts of the UI outwith the graphs.
        """
        # self.pdCategoryRB.set_active(self.current.annotations['pdCategory'])
        # if self.categoryRB_1.text() == self.current.annotations['pdCategory']:
        #     self.categoryRB_1.setChecked(True)
        # if self.categoryRB_2.text() == self.current.annotations['pdCategory']:
        #     self.categoryRB_2.setChecked(True)
        # if self.categoryRB_3.text() == self.current.annotations['pdCategory']:
        #     self.categoryRB_3.setChecked(True)
        # if self.categoryRB_4.text() == self.current.annotations['pdCategory']:
        #     self.categoryRB_4.setChecked(True)
        # if self.categoryRB_5.text() == self.current.annotations['pdCategory']:
        #     self.categoryRB_5.setChecked(True)

        # TODO: highlight current recording

        if self.positionRB_1.text() == self.current.annotations['tonguePosition']:
            self.positionRB_1.setChecked(True)
        if self.positionRB_2.text() == self.current.annotations['tonguePosition']:
            self.positionRB_2.setChecked(True)
        if self.positionRB_3.text() == self.current.annotations['tonguePosition']:
            self.positionRB_3.setChecked(True)

        self.goLineEdit.setText(str(self.index + 1))

    def draw_plots(self):
        """
        Updates title and graphs. Called by self.update().
        """
        self.data_axes[0].set_title(self._get_title())
        self.data_axes[0].set_title(self._get_long_title())

        for axes in self.tier_axes:
            axes.remove()
        self.tier_axes = []
        if self.current.satgrid:
            nro_tiers = len(self.current.satgrid)
            self.tier_grid_spec = self.main_grid_spec[1].subgridspec(
                nro_tiers, 1, hspace=0, wspace=0)
            for i, tier in enumerate(self.current.textgrid):
                axes = self.figure.add_subplot(self.tier_grid_spec[i],
                                               sharex=self.data_axes[0])
                axes.set_yticks([])
                self.tier_axes.append(axes)

        for axes in self.data_axes:
            axes.xaxis.set_tick_params(bottom=False, labelbottom=False)

        for axes in self.tier_axes[:-1]:
            axes.xaxis.set_tick_params(bottom=False, labelbottom=False)

        # self.tier_axes[-1].xaxis.set_tick_params(labelbottom=True)
        # ticks = self.tier_axes[-1].xaxis.set_tick_params(bottom=True, labelbottom=True)

        audio = self.current.modalities['MonoAudio']
        stimulus_onset = audio.go_signal
        wav = audio.data
        wav_time = (audio.timevector - stimulus_onset)

        # l0 = self.current.modalities['PD l0 on RawUltrasound']
        # l0_01 = self.current.modalities['PD l0.01 on RawUltrasound']
        # l0_1 = self.current.modalities['PD l0.1 on RawUltrasound']
        # l0_5 = self.current.modalities['PD l0.5 on RawUltrasound']

        l1 = self.current.modalities['PD l1 on RawUltrasound']
        # l1_top = self.current.modalities['PD l1 top on RawUltrasound']
        # l1_bottom = self.current.modalities['PD l1 bottom on RawUltrasound']

        # l2 = self.current.modalities['PD l2 on RawUltrasound']
        # l4 = self.current.modalities['PD l4 on RawUltrasound']
        # l2_top = self.current.modalities['PD l2 top on RawUltrasound']
        # l2_bottom = self.current.modalities['PD l2 bottom on RawUltrasound']

        # l10 = self.current.modalities['PD l10 on RawUltrasound']
        # linf = self.current.modalities['PD l_inf on RawUltrasound']

        # frequencies = self.current.modalities['PD d on RawUltrasound']

        # l2_interpolated = self.current.modalities['Interpolated PD l2 on RawUltrasound']
        # l2_interpolated_top = self.current.modalities['Interpolated PD l2 top on RawUltrasound']
        # l2_interpolated_bottom = self.current.modalities['Interpolated PD l2 bottom on RawUltrasound']
        ultra_time = l1.timevector - stimulus_onset

        # l2_size = len(self.current.modalities['RawUltrasound'].data[0,:,:])
        # half = int(self.current.modalities['RawUltrasound'].data.shape[1]/2)
        # l2_top_size = len(self.current.modalities['RawUltrasound'].data[0,:half,:])
        # l2_bottom_size = len(self.current.modalities['RawUltrasound'].data[0,half:,:])

        # image = self.current.modalities['RawUltrasound'].interpolated_image(100)
        # nonzero = np.nonzero(image==255)
        # l2_interp_size = image.size-len(nonzero[0])
        # half = int(image.shape[0]/2)
        # nonzero_top = np.nonzero(image[:half,:]==255)
        # l2_interp_size_top = image[:half,:].size -len(nonzero_top[0])
        # nonzero_bottom = np.nonzero(image[half:,:]==255)
        # l2_interp_size_bottom = image[half:,:].size-len(nonzero_bottom[0])

        # self.xlim = [ultra_time[0] - 0.05, ultra_time[-1]+0.05]

        # self.pd_boundaries = plot_pd(
        # self.ax1, pd.data['pd'],
        # ultra_time, self.xlim, textgrid, stimulus_onset,
        # picker=PdQtAnnotator.line_xdirection_picker)
        # plot_wav(self.ax3, wav, wav_time, self.xlim,
        #          textgrid, stimulus_onset,
        #          picker=PdQtAnnotator.line_xdirection_picker)
        ylim = None
        if 'auto x' in gui_params and gui_params['auto x']:
            # TODO: find the minimum and maximum timestamp of all the modalities
            # being plotted. this can be really done only after plotting is
            # controlled by config instead of manual code
            self.xlim = (
                np.min([np.min(wav_time), np.min(ultra_time)]),
                np.max([np.max(wav_time), np.max(ultra_time)])
            )
        elif 'xlim' in gui_params:
            self.xlim = gui_params['xlim']
        else:
            self.xlim = (-.25, 1.5)

        # plot_density(self.data_axes[0], frequencies.data)

        # raw_l0 = plot_timeseries(self.data_axes[0], l0.data,
        #     ultra_time, self.xlim, ylim, color='black', linestyle='--',
        #     normalise=Normalisation('PEAK AND BOTTOM'))
        # raw_l0_01 = plot_timeseries(self.data_axes[0], l0_01.data,
        #     ultra_time, self.xlim, ylim, color='black',
        #     normalise=Normalisation('PEAK AND BOTTOM'))
        # raw_l0_1 = plot_timeseries(self.data_axes[0], l0_1.data,
        #     ultra_time, self.xlim, ylim, color='dimgrey',
        #     normalise=Normalisation('PEAK AND BOTTOM'))
        # raw_l0_5 = plot_timeseries(self.data_axes[0], l0_5.data,
        #     ultra_time, self.xlim, ylim, color='grey',
        #     normalise=Normalisation('PEAK AND BOTTOM'))
        raw_l1 = plot_timeseries(
            self.data_axes[0],
            l1.data, ultra_time, self.xlim, ylim, color='yellowgreen',
            normalise=Normalisation('PEAK AND BOTTOM'),
            find_peaks=False)
        # raw_l1_bottom = plot_timeseries(self.data_axes[0], l1_bottom.data,
        #     ultra_time, self.xlim, ylim, color='gray', linestyle=':',
        #     normalise=Normalisation('PEAK AND BOTTOM'))
        # raw_l1_top = plot_timeseries(self.data_axes[0], l1_top.data,
        #     ultra_time, self.xlim, ylim, color='blue', linestyle=':',
        #     normalise=Normalisation('PEAK AND BOTTOM'))
        # raw_top = plot_timeseries(self.data_axes[0], l2_top.data,
        #     ultra_time, self.xlim, ylim, color='black',
        #     normalise=Normalisation('PEAK'))
        self.data_axes[0].set_ylabel("Pixel difference (PD)")
        # self.data_axes[0].legend(
        #     (
        #         #raw_l0, raw_l0_01,
        #         # raw_l0_1, raw_l0_5,
        #         raw_l1, raw_l1_bottom, raw_l1_top
        #     ),
        #     # , interp, interp_top, interp_bottom),
        #     (
        #         # 'l0', 'l0.01',
        #         # 'l0.1', 'l0.5',
        #         'l1 whole', 'l1 bottom', 'l1 top'
        #     ),
        #     #, 'Interpolated', 'Interpolated top', 'Interpolated bottom'),
        #     loc='upper right')

        # raw_l1 = plot_timeseries(self.data_axes[1], l1.data,
        #     ultra_time, self.xlim, ylim, color='gray', linestyle=':',
        #     normalise=Normalisation('PEAK AND BOTTOM'))
        # raw_l1_bottom = plot_timeseries(self.data_axes[1], l1_bottom.data,
        #     ultra_time, self.xlim, ylim, color='black',
        #     normalise=Normalisation('PEAK AND BOTTOM'), find_peaks=True)
        # raw_l2 = plot_timeseries(self.data_axes[1], l2.data,
        #     ultra_time, self.xlim, ylim, color='yellowgreen',
        #     normalise=Normalisation('PEAK AND BOTTOM'))
        # raw_l4 = plot_timeseries(self.data_axes[1], l4.data,
        #     ultra_time, self.xlim, ylim, color='saddlebrown',
        #     normalise=Normalisation('PEAK AND BOTTOM'))
        # raw_l10 = plot_timeseries(self.data_axes[1], l10.data,
        #     ultra_time, self.xlim, ylim, color='saddlebrown', linestyle='--',
        #     normalise=Normalisation('PEAK AND BOTTOM'))
        # raw_linf = plot_timeseries(self.data_axes[1], linf.data,
        #     ultra_time, self.xlim, ylim, color='saddlebrown', linestyle=':',
        #     normalise=Normalisation('PEAK AND BOTTOM'))
        # self.data_axes[1].set_ylabel("Peaks from\nbottom of image")

        # interp = plot_timeseries(self.data_axes[1], l2_interpolated.data,
        #     ultra_time, self.xlim, ylim, color='black', linestyle="--", peak_normalise=True)
        # interp_top = plot_timeseries(self.data_axes[1], l2_interpolated_top.data,
        #     ultra_time, self.xlim, ylim, color='lime', linestyle="--", peak_normalise=True)
        # interp_bottom = plot_timeseries(self.data_axes[1], l2_interpolated_bottom.data,
        #     ultra_time, self.xlim, ylim, color='orange', linestyle="--", peak_normalise=True)
        # self.data_axes[1].set_ylabel("Peak normalised PD")

        # self.data_axes[0].legend(
        #     (raw, raw_top, raw_bottom),
        #     ('Raw', 'Raw upper', 'Raw lower'),
        #     loc='upper right')
        # self.data_axes[1].legend(
        #     (
        #         #raw_l0, raw_l0_01,
        #         # raw_l0_1, raw_l0_5,
        #         raw_l1, raw_l1_bottom
        #     ),
        #     # , interp, interp_top, interp_bottom),
        #     (
        #         # 'l0', 'l0.01',
        #         # 'l0.1', 'l0.5',
        #         'l1 whole', 'l1 bottom'
        #     ),
        #     #, 'Interpolated', 'Interpolated top', 'Interpolated bottom'),
        #     loc='upper right')

        # self.ylim = None
        # plot_timeseries(self.data_axes[1], l2.data/l2_size,
        #     ultra_time, self.xlim, self.ylim)
        # plot_timeseries(self.data_axes[1], l2_top.data/l2_top_size,
        #     ultra_time, self.xlim, self.ylim, color='green')
        # plot_timeseries(self.data_axes[1], l2_bottom.data/l2_bottom_size,
        #     ultra_time, self.xlim, self.ylim, color='red')
        # self.data_axes[1].set_ylabel("Pixel normalised PD")

        # plot_timeseries(self.data_axes[2], l2_interpolated.data/l2_interp_size,
        #     ultra_time, self.xlim, self.ylim, color='black', linestyle="--")
        # plot_timeseries(self.data_axes[2], l2_interpolated_top.data/l2_interp_size_top,
        #     ultra_time, self.xlim, self.ylim, color='lime', linestyle="--")
        # plot_timeseries(self.data_axes[2], l2_interpolated_bottom.data/l2_interp_size_bottom,
        #     ultra_time, self.xlim, self.ylim, color='orange', linestyle="--")
        # self.data_axes[2].set_ylabel("Pixel normalised PD")

        plot_wav(self.data_axes[2], wav, wav_time, self.xlim)
        plot_spectrogram(self.data_axes[1],
                         waveform=wav,
                         ylim=(0, 10500),
                         sampling_frequency=audio.sampling_rate,
                         xtent_on_x=[wav_time[0], wav_time[-1]])

        # TODO: the sync is out with this one, but plotting a pd spectrum is still a good idea.
        # plot_spectrogram(self.data_axes[2],
        #                 waveform=l2.data,
        #                 ylim=(0,40),
        #                 sampling_frequency=l2.sampling_rate,
        #                 xtent_on_x=[-1.5812581, 1]) #,
        #                 # xtent_on_x=[ultra_time[0], ultra_time[-1]]) #,

        segment_line = None
        self.animators = []
        for (name, tier), axis in zip(self.current.satgrid.items(), self.tier_axes, strict=True):
            boundaries_by_axis = []
            boundary_set, segment_line = plot_satgrid_tier(
                axis, tier, time_offset=stimulus_onset, text_y=.5)
            boundaries_by_axis.append(boundary_set)
            axis.set_ylabel(
                name, rotation=0, horizontalalignment="right",
                verticalalignment="center")
            axis.set_xlim(self.xlim)
            if name in gui_params["pervasive tiers"]:
                for axis in self.data_axes:
                    boundary_set = plot_satgrid_tier(
                        axis, tier, time_offset=stimulus_onset,
                        draw_text=False)[0]
                    boundaries_by_axis.append(boundary_set)

            # Change rows to be individual boundaries instead of axis. This
            # makes it possible to create animators for each boundary as
            # represented by multiple lines on different axes.
            boundaries_by_boundary = list(map(list, zip(*boundaries_by_axis)))

            for boundaries, interval in zip(
                    boundaries_by_boundary, tier, strict=True):
                animator = BoundaryAnimator(
                    self, boundaries, interval, stimulus_onset)
                animator.connect()
                self.animators.append(animator)
        if self.tier_axes:
            self.tier_axes[-1].set_xlabel("Time (s), go-signal at 0 s.")

        self.figure.tight_layout()

        if self.current.annotations['selected_time'] > -1:
            for axes in self.data_axes[:-1]:
                axes.axvline(x=self.current.annotations['selected_time'],
                             linestyle=':', color="deepskyblue", lw=1)
            self.data_axes[-1].axvline(x=self.current.annotations
                                       ['selected_time'],
                                       linestyle=':', color="white", lw=1)
            for axes in self.tier_axes:
                axes.axvline(x=self.current.annotations['selected_time'],
                             linestyle=':', color="deepskyblue", lw=1)

        # if self.display_tongue:
        #     _qt_annotator_logger.debug("Drawing ultra frame in plots")
        #     self.draw_ultra_frame()

    def draw_ultra_frame(self):
        """
        Display an already interpolated ultrasound frame.
        """
        if (self.current.excluded or
                self.current.annotations['selection_index'] == -1):
            self.ultra_axes.clear()
        elif self.current.annotations['selection_index']:
            index = self.current.annotations['selection_index']
            image = self.current.modalities['RawUltrasound'].interpolated_image(
                index)
            self.ultra_axes.imshow(image, interpolation='nearest', cmap='gray')
        self.ultra_canvas.draw()

    def draw_raw_ultra_frame(self):
        """
        Interpolate and display a raw ultrasound frame.
        """
        if self.current.annotations['selection_index']:
            ind = self.current.annotations['selection_index']
            array = self.current.modalities['RawUltrasound'].data[ind, :, :]
        else:
            array = self.current.modalities['RawUltrasound'].data[1, :, :]
        array = np.transpose(array)
        array = np.flip(array, 0).copy()
        array = array.astype(np.int8)
        self.ultra_axes.imshow(array, interpolation='nearest', cmap='gray')
        self.ultra_canvas.draw()

    def next(self):
        """
        Callback function for the Next button.
        Increases cursor index, updates the view.
        """
        if self.index < self.max_index-1:
            # TODO: wrap in a data modalities accessor
            if 'RawUltrasound' in self.current.modalities:
                self.current.modalities['RawUltrasound'].data = None
            self.index += 1
            self.update()
            self.update_ui()

    def _update_pd_onset(self):
        audio = self.current.modalities['MonoAudio']
        stimulus_onset = audio.go_signal

        if 'PD l1 on RawUltrasound' in self.current.modalities:
            pd_metrics = self.current.modalities['PD l1 on RawUltrasound']
            ultra_time = pd_metrics.timevector - stimulus_onset
            self.current.annotations['selected_time'] = ultra_time[self.
                                                                   current.annotations['selection_index']]

    def next_frame(self):
        """
        Move the data cursor to the next frame.
        """
        if (self.current.annotations['selection_index'] > -1 and
            'PD l1 on RawUltrasound' in self.current.modalities and
                self.current.annotations['selection_index'] < self.current.modalities['PD l1 on RawUltrasound'].data.size):

            self.current.annotations['selection_index'] += 1
            _qt_annotator_logger.debug(
                "next frame: %d" %
                (self.current.annotations['selection_index']))
            self._update_pd_onset()
            self.update()
            self.update_ui()

    def previous_frame(self):
        """
        Move the data cursor to the previous frame.
        """
        if self.current.annotations['selection_index'] > 0:
            self.current.annotations['selection_index'] -= 1
            _qt_annotator_logger.debug(
                "previous frame: %d" %
                (self.current.annotations['selection_index']))
            self._update_pd_onset()
            self.update()
            self.update_ui()

    def prev(self):
        """
        Callback function for the Previous button.
        Decreases cursor index, updates the view.
        """
        if self.index > 0:
            # TODO: wrap in a data modalities accessor
            self.current.modalities['RawUltrasound'].data = None
            self.index -= 1
            self.update()
            self.update_ui()

    def go_to_recording(self):
        """
        Go to a recording specified in the goLineEdit text input field.
        """
        self.current.modalities['RawUltrasound'].data = None
        self.index = int(self.goLineEdit.text())-1
        self.update()
        self.update_ui()

    def quit(self):
        """
        Quit the app.
        """
        QCoreApplication.quit()

    def open(self):
        """
        Open either SATKIT saved data or import new data.
        """
        directory = QFileDialog.getExistingDirectory(
            self, caption="Open directory", directory='.')
        if directory:
            self.recording_session = load_recording_session(
                directory=directory)
            self.recordings = self.recording_session.recordings
            self.index = 0
            self.max_index = len(self.recordings)
            self._add_annotations()
            self.update()

    def open_file(self):
        """
        Open either SATKIT saved data or import new data.
        """
        filename = QFileDialog.getOpenFileName(
            self, caption="Open file", directory='.',
            filter="SATKIT files (*.satkit_meta)")
        print(
            f"Don't yet know how to open a file even though I know the name is {filename}.")

    def save_all(self):
        """
        Save derived modalities and annotations.
        """
        # TODO 1.0: write a call back for asking for overwrite confirmation.
        save_recording_session(self.recording_session)

    def save_to_pickle(self):
        """
        Save the recordings into a pickle file.
        """
        if not self.pickle_filename:
            (self.pickle_filename, _) = QFileDialog.getSaveFileName(
                self, 'Save file', directory='.', filter="Pickle files (*.pickle)")
        if self.pickle_filename:
            _qt_annotator_logger.info(
                "Pickling is currently disabled. Did NOT write file {file}.",
                file=self.pickle_filename)
            # satkit_io.save2pickle(
            #     self.recordings,
            #     self.pickle_filename)
            # _qt_annotator_logger.info(
            #     "Wrote data to file {file}.", file = self.pickle_filename)

    def save_textgrid(self):
        """
        Save the recordings.
        """
        if not self.current._textgrid_path:
            (self.current._textgrid_path, _) = QFileDialog.getSaveFileName(
                self, 'Save file', directory='.', filter="TextGrid files (*.TextGrid)")
        if self.current._textgrid_path and self.current.satgrid:
            with open(self.current._textgrid_path, 'w') as outfile:
                outfile.write(self.current.satgrid.format_long())
            _qt_annotator_logger.info(
                "Wrote TextGrid to file %s.", str(self.current._textgrid_path))

    def export_figure(self):
        """
        Callback method to export the current figure in any supported format.

        Opens a filedialog to ask for the filename. Save format is determined by
        file extension.
        """
        (filename, _) = QFileDialog.getSaveFileName(
            self, 'Export figure', directory='.')
        self.figure.savefig(filename, bbox_inches='tight', pad_inches=0.05)

    def export(self):
        """
        Export annotations and some other meta data.
        """
        (filename, _) = QFileDialog.getSaveFileName(
            self, 'Save file', directory='.', filter="CSV files (*.csv)")

        if not filename:
            return

        vowels = ['a', 'A', 'e', 'E', 'i', 'I',
                  'o', 'O', 'u', '@', "@`", 'OI', 'V']
        fieldnames = ['basename', 'date_and_time', 'prompt', 'C1', 'C1_dur',
                      'word_dur', 'first_sound',
                      'first_sound_type', 'first_sound_dur', 'AAI']
        fieldnames.extend(self.default_annotations.keys())
        csv.register_dialect('tabseparated', delimiter='\t',
                             quoting=csv.QUOTE_NONE)

        with closing(open(filename, 'w', encoding='utf-8')) as csvfile:
            writer = csv.DictWriter(csvfile, fieldnames, extrasaction='ignore',
                                    dialect='tabseparated')

            writer.writeheader()
            for recording in self.recordings:
                annotations = recording.annotations.copy()
                annotations['basename'] = recording.basename
                annotations['date_and_time'] = recording.meta_data.time_of_recording
                annotations['prompt'] = recording.meta_data.prompt
                annotations['word'] = recording.meta_data.prompt.split()[0]

                word_dur = -1.0
                acoustic_onset = -1.0
                if 'word' in recording.textgrid:
                    for interval in recording.textgrid['word']:
                        # change this to access the phonemeDict and
                        # check for included words, then search for
                        # phonemes based on the same
                        if interval.text == "":
                            continue

                        # Before 1.0: check if there is a duration to use here. and maybe make this
                        # more intelligent by selecting purposefully the last non-empty first and
                        # taking the duration?
                        word_dur = interval.dur
                        stimulus_onset = recording.modalities['MonoAudio'].go_signal
                        acoustic_onset = interval.xmin - stimulus_onset
                        break
                    annotations['word_dur'] = word_dur
                else:
                    annotations['word_dur'] = -1.0

                if acoustic_onset < 0 or annotations['selected_time'] < 0:
                    aai = -1.0
                else:
                    aai = acoustic_onset - annotations['selected_time']
                annotations['AAI'] = aai

                first_sound_dur = -1.0
                first_sound = ""
                if 'segment' in recording.textgrid:
                    for interval in recording.textgrid['segment']:
                        if interval.text and interval.text != 'beep':
                            first_sound_dur = interval.dur
                            first_sound = interval.text
                            break
                annotations['first_sound_dur'] = first_sound_dur
                annotations['first_sound'] = first_sound
                if first_sound in vowels:
                    annotations['first_sound_type'] = 'V'
                else:
                    annotations['first_sound_type'] = 'C'

                annotations['C1'] = recording.meta_data.prompt[0]
                writer.writerow(annotations)
            _qt_annotator_logger.info(
                'Wrote onset data in file %s.' % (filename))

    def pd_category_cb(self):
        """
        Callback funtion for the RadioButton for catogorising
        the PD curve.
        """
        radio_button = self.sender()
        if radio_button.isChecked():
            self.current.annotations['pdCategory'] = radio_button.text()

    def tongue_position_cb(self):
        """
        Callback funtion for the RadioButton for catogorising
        the PD curve.
        """
        radio_button = self.sender()
        if radio_button.isChecked():
            self.current.annotations['tonguePosition'] = radio_button.text()

    def onpick(self, event):
        """
        Callback for handling time selection on events.
        """
        if not event.xdata:
            self.current.annotations['selected_time'] = -1
            self.current.annotations['selection_index'] = -1
            self.update()
            return

        subplot = 0
        for i, axes in enumerate(self.data_axes):
            if axes == event.inaxes:
                subplot = i+1
                break

        _qt_annotator_logger.debug("Inside onpick - subplot: %d, x=%f" % (
            subplot, event.xdata))

        # if subplot == 1:
        #     self.current.annotations['selected_time'] = event.pickx

        audio = self.current.modalities['MonoAudio']
        stimulus_onset = audio.go_signal

        timevector = self.current.modalities['PD l1 on RawUltrasound'].timevector
        distances = np.abs(timevector - stimulus_onset - event.xdata)
        self.current.annotations['selection_index'] = np.argmin(distances)
        self.current.annotations['selected_time'] = event.xdata

        _qt_annotator_logger.debug(
            "Inside onpick - subplot: %d, index=%d, x=%f" %
            (subplot, self.current.annotations['selection_index'],
             self.current.annotations['selected_time']))

        self.update()

    def resizeEvent(self, event):
        """Handle window being resized."""
        self.update()
        QMainWindow.resizeEvent(self, event)

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Shift:
            self.shift_is_held = True
        if event.key() == Qt.Key_I:
            gui_params['auto x'] = False
            if self.current.annotations['selection_index'] >= 0:
                center = self.current.annotations['selected_time']
            else:
                center = (self.xlim[0] + self.xlim[1])/2.0
            length = (self.xlim[1] - self.xlim[0])*.25
            self.xlim = (center-length, center+length)
            # TODO: create a way of storing this that isn't
            if 'xlim' in gui_params:
                gui_params['xlim'] = self.xlim
            self.update()
        elif event.key() == Qt.Key_O:
            gui_params['auto x'] = False
            center = (self.xlim[0] + self.xlim[1])/2.0
            length = (self.xlim[1] - self.xlim[0])
            self.xlim = (center-length, center+length)
            if 'xlim' in gui_params:
                gui_params['xlim'] = self.xlim
            self.update()
        elif event.key() == Qt.Key_A:
            gui_params['auto x'] = True
            self.update()
        # else:
        #     print(event.key())

    def keyReleaseEvent(self, event):
        if event.key() == Qt.Key_Shift:
            self.shift_is_held = False
        # else:
        #     print(event.key)


from django.contrib import admin
from django.urls import path
from user import views
urlpatterns = [
     path('admindashboard/',views.admin,name="admindashboard"),
     path('updatecustomer/<int:id>',views.updatecustomer,name="update"),
     path('deletecustomer/<int:id>',views.deletecustomer,name="delete"),
     path('addtransaction/<int:id>',views.addtransaction,name="addtransaction"),
     path('customer_transactions/',views.customer_transactionlist,name="customer_txn_list"),
     # path('transaction/<int:id>',views.transaction,name="transaction"),

]


"""Evaluation metrics to measure log probabilities for language modeling."""

from __future__ import annotations

from dataclasses import dataclass

import numpy as np

from explainaboard.metrics.metric import (
    Metric,
    MetricConfig,
    MetricStats,
    SimpleMetricStats,
)
from explainaboard.serialization import common_registry
from explainaboard.utils.typing_utils import narrow

@dataclass
@common_registry.register("LogProbConfig")
class LogProbConfig(MetricConfig):
    """Configuration for LogProb metrics.

    Args:
        ppl: Whether to exponente the log prob into perplexity.
    """

    ppl: bool = False

    def to_metric(self) -> Metric:
        """See MetricConfig.to_metric."""
        return LogProb(self)

class LogProb(Metric):
    """Calculate the log probability or perplexity."""

    def is_simple_average(self, stats: MetricStats):
        """See Metric.is_simple_average."""
        return stats.num_statistics() == 1

    def calc_stats_from_data(self, true_data: list, pred_data: list) -> MetricStats:
        """See Metric.calc_stats_from_data.

        Takes in a list of floats (token-level), or list of lists of floats (sentence
        level) and either one float for each or float+length rows
        """
        if len(pred_data) == 0 or isinstance(pred_data[0], float):
            return SimpleMetricStats(np.array(pred_data))
        elif isinstance(pred_data[0], list):
            return SimpleMetricStats(np.array([[sum(x), len(x)] for x in pred_data]))
        else:
            t = type(pred_data[0])
            raise ValueError(f"Invalid type of pred_data for calc_stats_from_data {t}")

    def _calc_metric_from_aggregate(self, agg_stats: np.ndarray) -> np.ndarray:
        """See Metric.calc_metric_from_aggregate."""
        is_batched = agg_stats.ndim != 1
        if not is_batched:
            agg_stats = agg_stats.reshape((1, agg_stats.shape[0]))
        config = narrow(LogProbConfig, self.config)
        val = (
            agg_stats[:, 0]
            if agg_stats.size == 1
            else agg_stats[:, 0] / agg_stats[:, 1]
        )
        if config.ppl:
            val = np.exp(-val)
        if not is_batched:
            val = val[0]
        return val


import logging

from ..widgets import (
    ImageWidget,
)
from .managed_window import ManagedWindow

log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())

class ManagedImageWindow(ManagedWindow):
    """
    Display experiment output with an :class:`~pymeasure.display.widgets.image_widget.ImageWidget`
    class.

    :param procedure_class: procedure class describing the experiment (see
        :class:`~pymeasure.experiment.procedure.Procedure`)
    :param x_axis: the data-column for the x-axis of the plot, cannot be changed afterwards for
        the image-plot
    :param y_axis: the data-column for the y-axis of the plot, cannot be changed afterwards for
        the image-plot
    :param z_axis: the initial data-column for the z-axis of the plot, can be changed afterwards
    :param \\**kwargs: optional keyword arguments that will be passed to
        :class:`~pymeasure.display.windows.managed_image_window.ManagedWindow`

    """

    def __init__(self, procedure_class, x_axis, y_axis, z_axis=None, **kwargs):
        self.z_axis = z_axis
        self.image_widget = ImageWidget(
            "Image", procedure_class.DATA_COLUMNS, x_axis, y_axis, z_axis)

        if "widget_list" not in kwargs:
            kwargs["widget_list"] = ()
        kwargs["widget_list"] = kwargs["widget_list"] + (self.image_widget,)

        super().__init__(procedure_class, x_axis=x_axis, y_axis=y_axis, **kwargs)


import os
import tempfile
from kubernetes import client, config, watch
from kubernetes.utils import create_from_yaml

APPLY_YAML_DATA =  os.getenv('APPLY_YAML_DATA',
'''
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: istio-gateways-role
  namespace: {namespace}
rules:
- apiGroups:
  - networking.istio.io
  resources:
  - gateways
  verbs:
  - get
  - list
  - create
  - update
  - delete
  - patch
  - watch
''')
# Configs can be set in Configuration class directly or using helper utility
config.load_incluster_config()

v1 = client.CoreV1Api()

while True:
    try:
        w = watch.Watch()
        for event in w.stream(v1.list_namespace, _request_timeout=60):
            if event['type'] == "MODIFIED":
                print("Event: %s %s" % (event['type'], event['object'].metadata.name))
                tmp_data = APPLY_YAML_DATA.replace('{namespace}', event['object'].metadata.name)
                with tempfile.NamedTemporaryFile(dir='/tmp') as tmpfile:
                    tmp_file = tmpfile.name
                    tmpfile.close()
                print(tmp_file)
                f = open(tmp_file, "a")
                f.write(tmp_data)
                f.close()
                clientapi = client.ApiClient()
                create_from_yaml(clientapi, tmp_file, namespace=event['object'].metadata.name)
                os.remove(tmp_file)
    except Exception as e:
        print(e)


import requests
import json

divOrbCount = float(input("Divine Orb Calculator\nHow many Divine Orbs do you want to convert to Chaos Orbs?\n").replace(",", "."))

values = requests.get("https://poe.ninja/api/data/currencyoverview?league=Kalandra&type=Currency").text
valuesJson = json.loads(values)
# print(valuesJson["lines"][0])
for i in valuesJson["lines"]:
    if i["detailsId"] == "divine-orb":
        divOrbValue = i["receive"]["value"]
print(f"That's {round((divOrbValue)*(divOrbCount))} Chaos Orbs")
input("Press any key to exit...")


import torch
import numpy as np
def compute_cmvn_epoch(opt, train_loader, enhance_model, feat_model):
    enhance_model.eval()
    feat_model.eval()
    torch.set_grad_enabled(False)
    ##print(enhance_model.state_dict())
    enhance_cmvn_file = os.path.join(opt.exp_path, 'enhance_cmvn.npy')
    for i, (data) in enumerate(train_loader, start=0):
        utt_ids, spk_ids, clean_inputs, clean_log_inputs, mix_inputs, mix_log_inputs, cos_angles, targets, input_sizes, target_sizes = data
        enhance_out = enhance_model(mix_inputs, mix_log_inputs, input_sizes)
        enhance_cmvn = feat_model.compute_cmvn(enhance_out, input_sizes)
        if enhance_cmvn is not None:
            np.save(enhance_cmvn_file, enhance_cmvn)
            print('save enhance_cmvn to {}'.format(enhance_cmvn_file))
            break
    enhance_cmvn = torch.FloatTensor(enhance_cmvn)
    enhance_model.train()
    feat_model.train()
    torch.set_grad_enabled(True)
    return enhance_cmvn


import pygame
import sys
import obd

# Initialize Pygame
pygame.init()

# Screen dimensions
WIDTH, HEIGHT = 800, 600

# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)

# Create the screen
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Race Car Dashboard")

# Font setup
font = pygame.font.Font(None, 40)

# OBD-II connection setup
connection = obd.OBD()  # This initializes the OBD-II connection using default settings

# Function to read OBD-II data
def get_obd_data():
    try:
        rpm_response = connection.query(obd.commands.RPM)
        coolant_temp_response = connection.query(obd.commands.COOLANT_TEMP)
        dtc_response = connection.query(obd.commands.GET_DTC)

        rpm = rpm_response.value.magnitude if rpm_response.value else 0
        coolant_temp = coolant_temp_response.value.magnitude if coolant_temp_response.value else 0

        if dtc_response and not dtc_response.is_null():
            dtc_codes = [dtc.code for dtc in dtc_response]
        else:
            dtc_codes = []

        return rpm, coolant_temp, dtc_codes
    except Exception as e:
        print("Error reading OBD-II data:", e)
        return 0, 0, []

# Function to clear DTC
def clear_dtc():
    try:
        connection.query(obd.commands.CLEAR_DTC)
    except Exception as e:
        print("Error clearing DTC:", e)

def draw_text(text, x, y, color=WHITE):
    text_surface = font.render(text, True, color)
    screen.blit(text_surface, (x, y))

def main():
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_x, mouse_y = pygame.mouse.get_pos()
                read_dtc_button = pygame.Rect(WIDTH - 200, 50, 150, 50)
                clear_dtc_button = pygame.Rect(WIDTH - 200, HEIGHT - 100, 150, 50)

                if read_dtc_button.collidepoint(mouse_x, mouse_y):
                    # Code to read DTC here
                    rpm, coolant_temp, dtc_codes = get_obd_data()
                    print("Read DTC:", dtc_codes)
                elif clear_dtc_button.collidepoint(mouse_x, mouse_y):
                    # Code to clear DTC here
                    clear_dtc()
                    print("DTCs cleared")

        # Clear the screen
        screen.fill(BLACK)

        # Draw race car elements
        pygame.draw.rect(screen, RED, (10, 10, WIDTH - 20, HEIGHT - 20), 5)
        pygame.draw.rect(screen, RED, (30, 30, WIDTH - 60, HEIGHT - 60), 5)
        pygame.draw.line(screen, YELLOW, (WIDTH // 2, 30), (WIDTH // 2, HEIGHT - 30), 5)

        # Display car data
        rpm, coolant_temp, dtc_codes = get_obd_data()  # Get OBD-II data

        draw_text(f"RPM: {rpm}", 50, 50)
        draw_text(f"Coolant Temp: {coolant_temp}°C", 50, HEIGHT - 100)

        dtc_x, dtc_y = WIDTH // 2 + 50, 50
        for code in dtc_codes:
            draw_text(f"DTC: {code}", dtc_x, dtc_y)
            dtc_y += 40

        # Draw buttons
        pygame.draw.rect(screen, YELLOW, (WIDTH - 200, 50, 150, 50))
        pygame.draw.rect(screen, YELLOW, (WIDTH - 200, HEIGHT - 100, 150, 50))

        draw_text("Read DTC", WIDTH - 190, 60, BLACK)
        draw_text("Clear DTC", WIDTH - 190, HEIGHT - 90, BLACK)

        # Update the display
        pygame.display.flip()

if __name__ == "__main__":
    main()


from __future__ import print_function

from future import standard_library

from CONSTANT import TUMBLR_CLIENT_SECRET, TUMBLR_CLIENT_ID, TUMBLR_REDIRECT_URL
from SocialMedia.SocialMedia import SocialMedia
from SocialMedia.Tumblr.TumblrAuth import get_authorization_url, get_access_token_from_url

standard_library.install_aliases()
import pytumblr

# HTML and MD are supported by Tumblr

class Tumblr(SocialMedia):
    request_token_url = 'http://www.tumblr.com/oauth/request_token'
    authorize_url = 'http://www.tumblr.com/oauth/authorize'
    access_token_url = 'http://www.tumblr.com/oauth/access_token'

    # TODO Make all extra function parameters same
    def __init__(self, client_id, client_secret, oauth_token, oauth_token_secret):
        self.client_id = client_id
        self.client_secret = client_secret
        self.oauth_token = oauth_token
        self.oauth_token_secret = oauth_token_secret

        self.post_id = None
        self.blog_name = None

        self.tumblr_api = pytumblr.TumblrRestClient(
            self.client_id,
            self.client_secret,
            self.oauth_token,
            self.oauth_token_secret
        )

    def publish_update(self, message, blog_name="", title=""):
        self.post_id = self.tumblr_api.create_text(blog_name,
                                                   state="published",
                                                   slug="testing-text-posts",
                                                   title=title,
                                                   body=message)
        self.blog_name = blog_name

        print("Tumblr Post ID:", self.post_id)
        post_url = self.get_link_latest_post()
        print('Tumblr Post URL:', post_url)

    def publish_update_with_attachment(self, body="", title="", url="", blog_name=""):
        self.post_id = self.tumblr_api.create_link(blog_name, title=title, url=url,
                                                   description=body)
        self.blog_name = blog_name

        print("Tumblr Post ID:", self.post_id)

        post_url = self.get_link_latest_post()
        print('Tumblr Post URL:', post_url)

    def publish_update_with_image_attachment(self, caption="", image_links=None,
                                             tags=None, blog_name="",
                                             format="markdown",
                                             state="published"):
        # https://github.com/tumblr/pytumblr#creating-a-photo-post
        # image_links here is a list of all the images to be posted
        self.blog_name = blog_name

        if tags is None:
            tags = [""]
        self.post_id = self.tumblr_api.create_photo(blog_name,
                                                    state=state, tags=tags, format=format,
                                                    data=image_links,
                                                    caption=caption)
        print("Tumblr Post ID:", self.post_id)

        post_url = self.get_link_latest_post()
        print('Tumblr Post URL:', post_url)

    def get_link_latest_post(self, post_id=None):
        try:
            if post_id is None:
                post_id = str(self.post_id['id'])
                post_url = 'https://' + self.blog_name + '.tumblr.com/post/' + post_id
                return post_url
        except (TypeError, KeyError) as e:
            print(e)
            return ""

    def get_profile_name(self):
        user = self.tumblr_api.info()['user']
        return user['name']

if __name__ == '__main__':
    url, res_key, res_sec = get_authorization_url(TUMBLR_CLIENT_ID,
                                                  TUMBLR_CLIENT_SECRET,
                                                  TUMBLR_REDIRECT_URL)
    print(url)
    tokens = get_access_token_from_url(TUMBLR_CLIENT_ID, TUMBLR_CLIENT_SECRET,
                                       res_key, res_sec,
                                       input('Allow then paste the full redirect URL here:\n'),
                                       callback_url=TUMBLR_REDIRECT_URL)
    tumblr = Tumblr(
        tokens['consumer_key'],
        tokens['consumer_secret'],
        tokens['oauth_token'],
        tokens['oauth_token_secret'],
    )

    # Post Status working
    tumblr.publish_update(
        message="""###Body Title""",
        title="Tit1le",
        blog_name='pymultiposter1')

    # Post Image working
    tumblr.publish_update_with_image_attachment(
        caption="""###Body Title""",
        image_links=["temp1.png", "temp3.png"],
        blog_name='pymultiposter1')

    # Post Link
    tumblr.publish_update_with_attachment(body="""###Body Title""",
                                          title="#Tile",
                                          url="www.googlel.com",
                                          blog_name="pymultiposter1")


import sys

import tensorflow as tf

from utils import residual_block, downsample_block

# Declaring exception names:
class ConfigurationException(Exception): pass
class IncompleteFeedDict(Exception): pass

# Main class
class resnet(object):
    '''Define a network model and run training

    U resnet implementation
    '''
    def __init__(self, params):
        '''initialization

        Requires a list of parameters as python dictionary

        Arguments:
            params {dict} -- Network parameters

        Raises:
            ConfigurationException -- Missing a required parameter
        '''
        required_params =[
            'MINIBATCH_SIZE',
            'SAVE_ITERATION',
            'NUM_LABELS',
            'N_INITIAL_FILTERS',
            'BATCH_NORMALIZATION',
            'NETWORK_DEPTH',
            'RESIDUAL_BLOCKS_PER_LAYER',
            'LOGDIR',
            'BASE_LEARNING_RATE',
            'TRAINING',
            'RESTORE',
            'TRAINING_ITERATIONS',
        ]

        for param in required_params:
            if param not in params:
                raise ConfigurationException("Missing parameter "+ str(param))

        self._params = params

    def construct_network(self, dims):
        '''Build the network model

        Initializes the tensorflow model according to the parameters
        '''

        tf.reset_default_graph()

        # Initialize the input layers:
        self._input_image  = tf.placeholder(tf.float32, dims, name="input_image")
        self._input_labels = tf.placeholder(tf.int64,
            [dims[0], self._params['NUM_LABELS']], name="input_image")

        logits = self._build_network(self._input_image)

        self._softmax = tf.nn.softmax(logits)
        self._predicted_labels = tf.argmax(logits, axis=-1)

        # Keep a list of trainable variables for minibatching:
        with tf.variable_scope('gradient_accumulation'):
            self._accum_vars = [tf.Variable(tv.initialized_value(),
                                trainable=False) for tv in tf.trainable_variables()]

        # Accuracy calculations:
        with tf.name_scope('accuracy'):
            self._total_accuracy   = tf.reduce_mean(tf.cast(
                tf.equal(self._predicted_labels,
                         tf.argmax(self._input_labels, axis=-1)), tf.float32))

            # Add the accuracies to the summary:
            tf.summary.scalar("Total_Accuracy", self._total_accuracy)

        # Loss calculations:
        with tf.name_scope('cross_entropy'):

            # Unreduced loss, shape [BATCH, L, W]
            losses = tf.nn.softmax_cross_entropy_with_logits(
                labels=self._input_labels, logits=logits)

            self._loss = tf.reduce_mean(losses)

            # Add the loss to the summary:
            tf.summary.scalar("Total_Loss", self._loss)

        # Optimizer:
        with tf.name_scope("training"):
            self._global_step = tf.Variable(0, dtype=tf.int32,
                trainable=False, name='global_step')
            if self._params['BASE_LEARNING_RATE'] <= 0:
                opt = tf.train.AdamOptimizer()
            else:
                opt = tf.train.AdamOptimizer(self._params['BASE_LEARNING_RATE'])

            # Variables for minibatching:
            self._zero_gradients =  [tv.assign(tf.zeros_like(tv)) for tv in self._accum_vars]
            self._accum_gradients = [self._accum_vars[i].assign_add(gv[0]) for
                                     i, gv in enumerate(opt.compute_gradients(self._loss))]
            self._apply_gradients = opt.apply_gradients(zip(self._accum_vars, tf.trainable_variables()),
                global_step = self._global_step)

        # Merge the summaries:
        self._merged_summary = tf.summary.merge_all()

    def apply_gradients(self,sess):

        return sess.run( [self._apply_gradients], feed_dict = {})

    def feed_dict(self, images, labels, weights=None):
        '''Build the feed dict

        Take input images, labels and (optionally) weights and match
        to the correct feed dict tensorrs

        Arguments:
            images {numpy.ndarray} -- Image array, [BATCH, L, W, F]
            labels {numpy.ndarray} -- Label array, [BATCH, L, W, F]

        Keyword Arguments:
            weights {numpy.ndarray} -- (Optional) input weights, same shape as labels (default: {None})

        Returns:
            [dict] -- Feed dictionary for a tf session run call

        Raises:
            IncompleteFeedDict -- If weights are requested in the configuration but not provided.
        '''
        fd = dict()
        fd.update({self._input_image : images})
        if labels is not None:
            fd.update({self._input_labels : labels})

        return fd

    def losses():
        pass

    def make_summary(self, sess, input_data, input_label, input_weight=None):
        fd = self.feed_dict(images  = input_data,
                            labels  = input_label,
                            weights = input_weight)
        return sess.run(self._merged_summary, feed_dict=fd)

    def zero_gradients(self, sess):
        sess.run(self._zero_gradients)

    def accum_gradients(self, sess, input_data, input_label, input_weight=None):

        feed_dict = self.feed_dict(images  = input_data,
                                   labels  = input_label,
                                   weights = input_weight)

        ops = [self._accum_gradients]
        doc = ['']
        # classification
        ops += [self._loss, self._total_accuracy]
        doc += ['loss', 'acc. all']

        return sess.run(ops, feed_dict = feed_dict ), doc

    def run_test(self,sess, input_data, input_label, input_weight=None):
        feed_dict = self.feed_dict(images   = input_data,
                                   labels  = input_label,
                                   weights = input_weight)

        ops = [self._loss, self._total_accuracy,]
        doc = ['loss', 'acc. all']

        return sess.run(ops, feed_dict = feed_dict ), doc

    def inference(self,sess,input_data,input_label=None):

        feed_dict = self.feed_dict(images=input_data, input_label=input_label)

        ops = [self._softmax]
        if input_label is not None:
          ops.append(self._accuracy_allpix)
          ops.append(self._accuracy_nonzero)

        return sess.run( ops, feed_dict = feed_dict )

    def global_step(self, sess):
        return sess.run(self._global_step)

    def _build_network(self, input_placeholder):

        x = input_placeholder
        # Initial convolution to get to the correct number of filters:
        x = tf.layers.conv3d(x, self._params['N_INITIAL_FILTERS'],
                             kernel_size=[5, 5, 5],
                             strides=[1, 1, 1],
                             padding='same',
                             use_bias=False,
                             trainable=self._params['TRAINING'],
                             name="Conv2DInitial",
                             reuse=None)

        # ReLU:
        x = tf.nn.relu(x)

        # Begin the process of residual blocks and downsampling:
        for i in xrange(self._params['NETWORK_DEPTH']):

            for j in xrange(self._params['RESIDUAL_BLOCKS_PER_LAYER']):
                x = residual_block(x, self._params['TRAINING'],
                                   batch_norm=self._params['BATCH_NORMALIZATION'],
                                   name="resblock_down_{0}_{1}".format(i, j))

            x = downsample_block(x, self._params['TRAINING'],
                                batch_norm=self._params['BATCH_NORMALIZATION'],
                                name="downsample_{0}".format(i))

        # At the bottom, do another residual block:
        for j in xrange(self._params['RESIDUAL_BLOCKS_PER_LAYER']):
            x = residual_block(x, self._params['TRAINING'],
                batch_norm=self._params['BATCH_NORMALIZATION'],
                name="deepest_block_{0}".format(j))

        # At this point, we ought to have a network that has the same shape as the initial input, but with more filters.
        # We can use a bottleneck to map it onto the right dimensions:
        x = tf.layers.conv3d(x,
                             self._params['NUM_LABELS'],
                             kernel_size=[1, 1, 1],
                             strides=[1, 1, 1],
                             padding='same',
                             activation=None,
                             use_bias=False,
                             trainable=self._params['TRAINING'],
                             name="BottleneckConv2D",)

        # Apply global average pooling to each filter to get the values for signal/bkg

        # For global average pooling, need to get the shape of the input:
        shape = (x.shape[1], x.shape[2], x.shape[3])

        x = tf.nn.pool(x,
                       window_shape=shape,
                       pooling_type="AVG",
                       padding="VALID",
                       dilation_rate=None,
                       strides=None,
                       name="GlobalAveragePool",
                       data_format=None)

        # Reshape to remove empty dimensions:
        x = tf.reshape(x, [tf.shape(x)[0], self._params['NUM_LABELS']],
                     name="global_pooling_reshape")

        # The final activation is softmax across the pixels.  It gets applied in the loss function
#         x = tf.nn.softmax(x)
        return x


from minio import Minio
from minio.error import S3Error
from config import Config
import io

class MinioClass:
    def __init__(self):
        try:
            self.config = Config('minio_config.cfg')
            self.client = Minio(endpoint=self.config['socket'],
                                access_key=self.config['access_key'],
                                secret_key=self.config['secret_key'],
                                secure=False)
        except S3Error as e:
            print("minio error occurred: ", e)
        except Exception as e:
            print("unexpected error: ", e)

    def __del__(self):
        print('minio connection closed')

    def add_file(self, name: str, title: str, content, c_type):
        file_io_object = io.StringIO(content)
        b_content = file_io_object.read().encode('latin-1')
        try:
            result = self.client.put_object(bucket_name=name,
                                            object_name=title,
                                            data=io.BytesIO(b_content),
                                            length=len(b_content),
                                            content_type=c_type)
        except S3Error as e:
            print("minio error occurred: ", e)
        except Exception as e:
            print("unexpected error: ", e)

    def get_files_list(self, name: str):
        list_of_titles = []
        try:
            file_list = self.client.list_objects(bucket_name=name)
            for file in file_list:
                list_of_titles.append(file.object_name)
            return list_of_titles
        except S3Error as e:
            print("minio error occurred: ", e)
        except Exception as e:
            print("unexpected error: ", e)

    def get_file(self, name: str, title: str):
        try:
            if(name == 'articles'):
                file = f'http://127.0.0.1:9000/articles/{title}'
            else:
                file = f'http://127.0.0.1:9000/permissions/{title}'
            return file
        except S3Error as e:
            print("minio error occurred: ", e)
        except Exception as e:
            print("unexpected error: ", e)

    def remove_file(self, name:str, title:str):
        try:
            result = self.client.remove_object(bucket_name=name, object_name=title)
        except S3Error as e:
            print("minio error occurred: ", e)
        except Exception as e:
            print("unexpected error: ", e)


from django.utils.translation import gettext_lazy as _

#: A list of Argentinean provinces and autonomous cities as `choices` in a
#: formfield. From http://www.argentina.gov.ar/argentina/portal/paginas.dhtml?pagina=425
PROVINCE_CHOICES = (
    ('B', _('Buenos Aires')),
    ('K', _('Catamarca')),
    ('H', _('Chaco')),
    ('U', _('Chubut')),
    ('C', _('Ciudad Autónoma de Buenos Aires')),
    ('X', _('Córdoba')),
    ('W', _('Corrientes')),
    ('E', _('Entre Ríos')),
    ('P', _('Formosa')),
    ('Y', _('Jujuy')),
    ('L', _('La Pampa')),
    ('F', _('La Rioja')),
    ('M', _('Mendoza')),
    ('N', _('Misiones')),
    ('Q', _('Neuquén')),
    ('R', _('Río Negro')),
    ('A', _('Salta')),
    ('J', _('San Juan')),
    ('D', _('San Luis')),
    ('Z', _('Santa Cruz')),
    ('S', _('Santa Fe')),
    ('G', _('Santiago del Estero')),
    ('V', _('Tierra del Fuego, Antártida e Islas del Atlántico Sur')),
    ('T', _('Tucumán')),
)


from crawler.general import get_page_content
from functools import reduce
from crawler.models import *

def get_paragraph(url):
  try:
    content = get_page_content(url)[1]
    for blockquote in content.find_all('blockquote'):
      blockquote.decompose()
    content = content.find_all('article', attrs={'class':'post-content'})[0].find_all('p')
    content[0] = content[0].get_text()
    return reduce(lambda x, y: x + y.get_text(), content).replace('\n', '.')
  except:
    return 'fail: ' + url


# 221003
# 프로그래머스 10815번 숫자 카드
# 분류: 집합과 맵
# 난이도: 실버 5
# https://www.acmicpc.net/problem/10815
# 한줄 평: ㅈ밥

import sys
from collections import defaultdict
read = sys.stdin.readline

n = int(read())
sang = defaultdict(int)
for i in map(int, read().split()):
    sang[i] = 1

m = int(read())
res = []
for me in map(int, read().split()):
    tmp = 1 if sang[me] else 0
    res.append(tmp)
print(*res)


# Prototype 1
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.formula.api as smf
import pandas as pd
from scipy.optimize import curve_fit

rng = np.random.default_rng(seed = 313)
x = sort(np.linspace(0, 1, num = 100))
u = rng.uniform(-1, 1, 100)
y1 = 2 + 3 * x + u
y2 = np.exp(3 * x ** 2) + u

func = lambda x, a, b: np.exp(a * x ** b)

param1 = curve_fit(func, x, y1)[0]
param2 = curve_fit(func, x, y2)[0]

def rsq(x, y):
    params = curve_fit(func, x, y)[0]
    lower = np.mean((np.mean(y) - y) ** 2)
    upper = np.mean((func(x, params[0], params[1]) - y) ** 2)
    return 1 - upper / lower

plt.scatter(x, y1)
plt.plot(x, func(x, param1[0], param1[1]), color = "black")
plt.show()

plt.scatter(x, y2)
plt.plot(x, func(x, param2[0], param2[1]), color = "black")
plt.show()

rsq(x, y1)
rsq(x, y2)

def nls_plotter(y, x, func):
    params = curve_fit(func, x, y)[0]
    lower = np.mean((np.mean(y) - y) ** 2)
    upper = np.mean((func(x, *params) - y) ** 2)
    plt.scatter(x, y)
    plt.plot(x, func(x, *params), color = "black")
    plt.show()
    return {"rsq": 1 - upper / lower, "params" : params}

nls_plotter(y2, x, lambda x, a, b, c: a * x ** 2 + b * x ** c)

extras/2021 Fall EBA3500 Data Analysis and Programming/notes/lecture2/notes5.py


from django.test import TestCase
from django.urls import reverse
from ..models import Product

class TestProductsView(TestCase):
    def test_all_products_view(self):
        """
        Test for status code 200 response and correct
        template rendered when getting the products page.
        """
        response = self.client.get("/products/")
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "products/products.html")

    def test_get_product_detail_view(self):
        """
        Test for status code 200 response and correct
        template rendered when getting an individual
        product_detail page.
        """
        p = Product.objects.create(price=0.00)
        p.save()
        response = self.client.get(reverse(("product_detail"), args=(p.id,)))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "products/product_detail.html")


import os

from configparser import ConfigParser

def read_api_config():
    conn = ConfigParser()
    file_path = os.getcwd() + "\\config.ini"
    if not os.path.exists(file_path):
        raise FileNotFoundError("配置文件不存在")

    conn.read(file_path, encoding="utf-8")

    use = conn.get('api', 'use')
    url = conn.get('api', use)
    access_token = conn.get('api', 'access_token')

    return url, access_token

def read_grasp_setting():
    conn = ConfigParser()
    file_path = os.getcwd() + "\\config.ini"
    if not os.path.exists(file_path):
        raise FileNotFoundError("配置文件不存在")

    conn.read(file_path, encoding="utf-8")

    window_title = conn.get('grasp_setting', 'window_title')
    left = conn.get('grasp_setting', 'left')
    top = conn.get('grasp_setting', 'top')
    right = conn.get('grasp_setting', 'right')
    bottom = conn.get('grasp_setting', 'bottom')
    return window_title, float(left), float(top), float(right), float(bottom)


from flask import Flask
from flask_restful import Api, Resource

# instantiate the app
app = Flask(__name__)

api = Api(app)

# set config
app.config.from_object('project.config.DevelopmentConfig')

class UserPing(Resource):

    def get(self):
        return {
            'status': 'success',
            'message': 'pong!'
        }

api.add_resource(UserPing, '/users/ping')