import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from matplotlib import pyplot as plt
import imutils
import numpy as np
import easyocr
import cv2
from lp_detection import lp_detection

class VideoThread(QThread):
    ImageUpdate = pyqtSignal(QImage, list, list, list)

    def __init__(self, ocr_type, frame_skip, cam = True, path = ""):
        super().__init__()

        self.isCamera = cam
        self.vidPath = path
        self.OCR_type = ocr_type
        self.paused = False
        self.frame_skip_nr = frame_skip
        self.count = 0

    def run(self):
        self.ThreadActive = True
        if self.isCamera == True:
            capture = cv2.VideoCapture(0)
        else:
            capture = cv2.VideoCapture(self.vidPath)

        self.frame_rate = capture.get(cv2.CAP_PROP_FPS)

        while self.ThreadActive:

            while self.paused:
                pass

            success, frame = capture.read()
            if success:
                image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                ConvertToQtFormat = QImage(image.data, image.shape[1], image.shape[0], QImage.Format_RGB888)
                pic = ConvertToQtFormat.scaled(1280, 720, Qt.KeepAspectRatio)

                if self.count == self.frame_skip_nr:
                    (cam_img_res, cam_number_res, conf_res, _) = lp_detection(image, self.OCR_type, video=True)
                    self.count = 0
                else:
                    cam_img_res = ["__fail__"]
                    cam_number_res = []
                    conf_res = [0]

                    self.count += 1

                self.ImageUpdate.emit(pic, cam_img_res, cam_number_res, conf_res)

                cv2.waitKey(int(1000/self.frame_rate))

        capture.release()

    def stop(self):
        self.ThreadActive = False
        self.quit()

    def setPause(self):
        self.paused = not self.paused

class VideoFootage(QWidget):
    Pause = pyqtSignal(bool)

    def __init__(self, ocr_type, frame_skip, camera=True, vidPath = ""):
        super(VideoFootage, self).__init__()

        self.is_pause = False

        self.currentFrameNr = 0
        self.frameCache = []

        self.setObjectName("VideoFootageWidget")
        self.setAttribute(Qt.WA_StyledBackground, True)
        self.setStyleSheet("QWidget#VideoFootageWidget{ \n"
        "background-color:qlineargradient(spread:pad, x1:0.945, y1:0.0681818, x2:0, y2:1, stop:0 rgba(68, 206, 206, 255), stop:1 rgba(175, 219, 220, 255));}")

        self.mainLayout = QGridLayout()

        self.title = QLabel()
        if camera==True:
            self.title.setText("Camera")
        else:
            self.title.setText("Video")
        self.title.setAlignment(Qt.AlignCenter)
        self.title.setFont(QFont("Segoe UI", 12))
        self.mainLayout.addWidget(self.title, 0, 15, 1, 11)

        self.FeedLabel = QLabel()
        self.FeedLabel.setMaximumWidth(1100)
        self.FeedLabel.setMaximumHeight(700)
        self.mainLayout.addWidget(self.FeedLabel, 1, 16, 8, 11)

        self.table = QTableWidget()
        self.table.setColumnCount(3)
        self.table.setRowCount(0)
        self.table.setHorizontalHeaderLabels(['Plate Number', 'Confidence', 'Option'])
        self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)

        self.mainLayout.addWidget(self.table, 1, 1, 1, 15)

        self.cancelBTN = QPushButton("Cancel")
        self.cancelBTN.clicked.connect(self.CancelFeed)
        self.cancelBTN.setFont(QFont("Segoe UI", 14))
        self.mainLayout.addWidget(self.cancelBTN, 10, 8, 1, 10)

        self.cancelBTN.setFixedWidth(600)
        self.cancelBTN.setFixedHeight(40)

        if camera==False:
            self.pauseBTN = QPushButton("Pause")
            self.pauseBTN.clicked.connect(self.pauseVideo)
            self.pauseBTN.setFont(QFont("Segoe UI", 14))
            self.mainLayout.addWidget(self.pauseBTN, 10, 20, 1, 10)

            self.pauseBTN.setFixedWidth(600)
            self.pauseBTN.setFixedHeight(40)

        self.setLayout(self.mainLayout)

        self.VideoThread = VideoThread(ocr_type, frame_skip, camera, vidPath)
        self.VideoThread.start()
        self.VideoThread.ImageUpdate.connect(self.updateScreen)

    @pyqtSlot(QImage, list, list, list)
    def updateScreen(self, image, cam_img_res, cam_number_res, conf_res):
        self.FeedLabel.setPixmap(QPixmap.fromImage(image))

        valid = 1

        if len(cam_number_res)>0 and cam_number_res!="__fail__":                  #=1; poate primi doar un numar
            ConvertToQtFormat = QImage(cam_img_res[0].data, cam_img_res[0].shape[1], cam_img_res[0].shape[0], QImage.Format_RGB888)
            pic = ConvertToQtFormat.scaled(1280, 720, Qt.KeepAspectRatio)
            self.FeedLabel.setPixmap(QPixmap.fromImage(pic))

            self.frameCache.append(cam_img_res[0])
            self.currentFrameNr = self.currentFrameNr + 1

            rowPosition = self.table.rowCount()

            for i in range(rowPosition):
                if cam_number_res[0] == self.table.item(i, 0).text():
                    valid = 0
                    break

            if valid == 1:
                self.table.insertRow(rowPosition)
                self.table.setItem(rowPosition, 0, QTableWidgetItem(cam_number_res[0]))
                if round(conf_res[0], 2) == 0:
                    self.table.setItem(rowPosition, 1, QTableWidgetItem("-"))
                else:
                    self.table.setItem(rowPosition, 1, QTableWidgetItem(str(round(conf_res[0], 2))+"%"))

                self.table.setItem(rowPosition, 2, QTableWidgetItem())

                self.saveButton =  QPushButton('Save frame', self)
                self.saveButton.clicked.connect(lambda ch, i=self.currentFrameNr-1: self.saveFrame(i))

                self.table.setCellWidget(rowPosition, 2, self.saveButton)

    def pauseVideo(self):
        self.is_pause = not self.is_pause
        if self.is_pause:
            self.pauseBTN.setText("Play")
        else:
            self.pauseBTN.setText("Pause")
        self.VideoThread.setPause()

    def saveFrame(self, i):
        if(self.title.text()=="Video" and not self.is_pause):
            self.pauseVideo()
        cv2.imwrite("vid/frame"+str(i)+".jpg", cv2.cvtColor(self.frameCache[i], cv2.COLOR_BGR2RGB))
        if  self.frameCache[i].shape[0] < 500:
            temp = cv2.resize(self.frameCache[i], (2*self.frameCache[i].shape[1], 2*self.frameCache[i].shape[0]), cv2.INTER_LINEAR)
        else:
            temp = self.frameCache[i]
        cv2.imshow("CAR", cv2.cvtColor(temp, cv2.COLOR_BGR2RGB))
        #cv2.imshow("CAR", cv2.cvtColor(self.frameCache[i], cv2.COLOR_BGR2RGB))
        cv2.waitKey(0)

    def CancelFeed(self):
        self.VideoThread.stop()
        stack.removeWidget(stack.currentWidget())

class ImageInput(QWidget):
    def __init__(self, path, ocr_type):
        super(ImageInput, self).__init__()

        self.setOCRType(ocr_type)
        self.setPath(path)
        self.image_step = 1

        self.setObjectName("ImageInputWidget")
        self.setAttribute(Qt.WA_StyledBackground, True)
        self.setStyleSheet("QWidget#ImageInputWidget{ \n"
        "background-color:qlineargradient(spread:pad, x1:0.945, y1:0.0681818, x2:0, y2:1, stop:0 rgba(68, 206, 206, 255), stop:1 rgba(175, 219, 220, 255));}")

        self.mainLayout = QGridLayout()
        self.mainLayout.setColumnStretch(0, 1)
        self.mainLayout.setColumnStretch(1, 1)
        self.mainLayout.setColumnStretch(2, 1)

        self.getResults()

        for i in range(len(self.nr_res)):
            rowPosition = self.table.rowCount()
            self.table.insertRow(rowPosition)
            self.table.setItem(rowPosition , 0, QTableWidgetItem(self.nr_res[i]))
            if round(self.conf_res[i], 2) == 0:
                self.table.setItem(rowPosition, 1, QTableWidgetItem("-"))
            else:
                self.table.setItem(rowPosition, 1, QTableWidgetItem(str(round(self.conf_res[i], 2))+"%"))

            self.table.setItem(rowPosition, 2, QTableWidgetItem())

            self.carButton = QPushButton('View car', self)
            self.carButton.clicked.connect(lambda ch, i=i: self.showCarImage(i))

            self.table.setCellWidget(rowPosition, 2, self.carButton)

        if len(self.nr_res)>0:
            self.mainLayout.addWidget(self.table, 1, 1, 1, 10)

        if len(self.nr_res)>0:
            self.combo_details = QComboBox()
            self.combo_details.setStyleSheet("selection-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(255, 178, 102, 255), stop:0.55 rgba(235, 148, 61, 255), stop:0.98 rgba(0, 0, 0, 255), stop:1 rgba(0, 0, 0, 0));\n"
    "background-color: rgb(185, 222, 227);")
            self.combo_details.addItem("1. Grayscale")
            self.combo_details.addItem("2. Blackhat")
            self.combo_details.addItem("3. Sobel Edge")
            self.combo_details.addItem("4. Sobel Edge + Closing")
            self.combo_details.addItem("5. Sobel Edge + Threshold")
            self.combo_details.addItem("6. Sobel Edge + Threshold + Erosion/Dilation")
            self.combo_details.addItem("7. Light + Threshold")
            self.combo_details.addItem("8. Applied Mask")
            self.combo_details.addItem("9. Final")
            self.combo_details.addItem("10.Region of interest")
            self.combo_details.activated[str].connect(self.set_image_step)
            self.mainLayout.addWidget(self.combo_details, 6, 2, 1, 1)

            self.row_nr = QSpinBox()
            self.row_nr.setMaximum(self.table.rowCount())
            self.row_nr.setMinimum(1)
            self.mainLayout.addWidget(self.row_nr, 5, 2, 1, 1)

            self.showBTN = QPushButton("Show step")
            self.showBTN.clicked.connect(self.showStepImage)
            self.showBTN.setFont(QFont("Segoe UI", 14))
            self.mainLayout.addWidget(self.showBTN, 11, 2, 1, 1)

        self.backBTN = QPushButton("Back to Menu")
        self.backBTN.clicked.connect(self.returnToMenu)
        self.backBTN.setFont(QFont("Segoe UI", 14))
        self.mainLayout.addWidget(self.backBTN, 11, 1, 1, 1)

        self.backBTN.setMaximumWidth(600)
        self.backBTN.setMinimumHeight(40)

        self.setLayout(self.mainLayout)

    def set_image_step(self, text):
        self.image_step = text.split('.')[0]

    def showStepImage(self):
        h, w = self.steps_img[self.row_nr.value()-1][int(self.image_step)-1].shape
        self.temp = self.steps_img[self.row_nr.value()-1][int(self.image_step)-1]

        if h < 500:
            scale = 2
        else:
            scale = 1.1

        new_width = int(scale * w)
        new_height = int(scale * h)
        new_res = (new_width, new_height)

        self.temp = cv2.resize(self.temp, new_res, interpolation=cv2.INTER_LINEAR)

        cv2.imshow("CAR", self.temp)
        cv2.waitKey(0)

    def showCarImage(self, ind):
        h, w, _ = self.img_res[ind].shape
        self.temp = self.img_res[ind]

        if h < 450:
            scale = 2
        elif h < 350:
            scale = 3
        elif h > 950:
            scale = 0.6
        else:
            scale = 1.1

        new_width = int(scale * w)
        new_height = int(scale * h)
        new_res = (new_width, new_height)

        self.temp = cv2.resize(self.temp, new_res, interpolation=cv2.INTER_LINEAR)

        cv2.imshow("CAR", self.temp)
        cv2.waitKey(0)

    def getResults(self):
        self.car_image = cv2.imread(self.imagePath)
        h, w, ch = self.car_image.shape
        bytesPerLine = ch * w

        self.original_img_label = QLabel()
        self.qt_image = cv2.cvtColor(self.car_image, cv2.COLOR_BGR2RGB)
        self.qt_image = QImage(self.qt_image.data, w, h, bytesPerLine, QImage.Format_RGB888)
        self.pic = self.qt_image.scaled(600, 400, Qt.KeepAspectRatio)
        self.original_img_label.setPixmap(QPixmap.fromImage(self.pic))
        self.mainLayout.addWidget(self.original_img_label, 1, 0, 1, 1)

        [self.img_res, self.nr_res, self.conf_res, self.steps_img] = lp_detection(self.car_image, self.OCR_type, video=False)

        if len(self.nr_res)==0:
            self.errorMessage = QLabel()
            self.errorMessage.setText("No license plate found!")
            self.errorMessage.setAlignment(Qt.AlignCenter)
            self.errorMessage.setFont(QFont("Segoe UI", 12))

            self.mainLayout.addWidget(self.errorMessage, 1, 1, 1, 1)
        else:
            self.table = QTableWidget()
            self.table.setColumnCount(3)
            self.table.setRowCount(0)
            self.table.setHorizontalHeaderLabels(['Plate Number', 'Confidence', 'Option'])
            self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)

    def setPath(self, path):
        self.imagePath = path

    def setOCRType(self, ocr_type):
        self.OCR_type = ocr_type

    def returnToMenu(self):
        stack.removeWidget(stack.currentWidget())

class HomePage(QMainWindow):
    def __init__(self):
        super(HomePage, self).__init__()

        self.ocr_type = "Tesseract"

        #Set Dimensions
        self.width = QDesktopWidget().screenGeometry(-1).width()
        self.height = QDesktopWidget().screenGeometry(-1).height()
        self.setGeometry(100, 100, self.width//2, self.height//2)
        self.setObjectName("MainWindow")

        self.setStyleSheet("QMainWindow#MainWindow{ \n"
        "background-color:qlineargradient(spread:pad, x1:0.945, y1:0.0681818, x2:0, y2:1, stop:0 rgba(68, 206, 206, 255), stop:1 rgba(175, 219, 220, 255));}")

        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        self.label = QLabel(self.central_widget)
        self.label.setGeometry(520, 10, 600, 70)
        self.label.setStyleSheet("font: 500 20pt \"Segoe UI\"; color: rgb(252, 255, 255);\n border-color: rgb(85, 0, 127);")
        self.label.setText("Automatic Number Plate Recognition")
        self.label.setAlignment(Qt.AlignCenter)

        self.imageInputButton = QPushButton("Insert an image", self.central_widget)
        self.imageInputButton.setStyleSheet("border-radius: 7px; \n font: 11pt \"Segoe UI\";  color: rgb(252, 255, 255);\n background-color: rgb(170, 96, 255); QPushButton::pressed{ background-color: rgb(0, 0, 255);}")
        #self.pushButton.setGeometry(QtCore.QRect(320, 130, 201, 61))
        self.imageInputButton.setGeometry(675, 200, 300, 100)
        self.imageInputButton.clicked.connect(self.getImage)

        self.videoButton = QPushButton("Select video", self.central_widget)
        #self.videoButton.setGeometry(320, 210, 201, 61)
        self.videoButton.setGeometry(675, 350, 300, 100)
        self.videoButton.setStyleSheet("border-radius: 7px;\n font: 11pt \"Segoe UI\";  color: rgb(252, 255, 255);\n background-color: rgb(170, 96, 255);")
        self.videoButton.clicked.connect(self.getVideo)

        self.cameraButton = QPushButton("Use Camera Footage", self.central_widget)
        self.cameraButton.setGeometry(675, 500, 300, 100)
        self.cameraButton.setStyleSheet("border-radius: 7px;\n font: 11pt \"Segoe UI\";  color: rgb(252, 255, 255);\n background-color: rgb(170, 96, 255);")
        self.cameraButton.clicked.connect(self.changeToCamera)

        self.label_ocr = QLabel(self.central_widget)
        self.label_ocr.setGeometry(175, 750, 200, 50)
        self.label_ocr.setText("Select Mode(OCR)")
        self.label_ocr.setStyleSheet("font: 11pt \"Segoe UI\";")
        self.label_ocr.setAlignment(Qt.AlignCenter)

        self.comboBox_ocr = QComboBox(self.central_widget)
        self.comboBox_ocr.setGeometry(100, 800, 350, 40)
        self.comboBox_ocr.setStyleSheet("selection-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(255, 178, 102, 255), stop:0.55 rgba(235, 148, 61, 255), stop:0.98 rgba(0, 0, 0, 255), stop:1 rgba(0, 0, 0, 0));\n"
"background-color: rgb(185, 222, 227);")
        self.comboBox_ocr.addItem("Fast (Tesseract)")
        self.comboBox_ocr.addItem("Slow (easyOCR)")
        self.comboBox_ocr.activated[str].connect(self.set_ocr)

        self.label_frame = QLabel("Frame skip:", self.central_widget)
        self.label_frame.setGeometry(1300, 800, 90, 30)
        self.label_frame.setStyleSheet("font: 11pt \"Segoe UI\";")
        self.spinBox = QSpinBox(self.central_widget)
        self.spinBox.setGeometry(1400, 802, 60, 30)
        self.spinBox.setMaximum(300)

    def set_ocr(self, text):
        text = text.split("(")[-1]
        self.ocr_type = text[:len(text)-1]

    def changeToCamera(self):
        self.frame_skip = self.spinBox.value()
        camera = VideoFootage(self.ocr_type, self.frame_skip)
        stack.addWidget(camera)
        stack.setCurrentWidget(camera)

    def getImage(self):
        fname = QFileDialog.getOpenFileName(self, 'Select an image', '', "Images (*.jpg; *.bmp; *.jpeg; *.png);;All Files (*)")
        imagePath = fname[0]

        if imagePath !="":
            img = ImageInput(imagePath, self.ocr_type)
            stack.addWidget(img)
            stack.setCurrentWidget(img)

    def getVideo(self):
        vname = QFileDialog.getOpenFileName(self, 'Select a video', '', "Video (*.mp4);;All Files (*)")
        videoPath = vname[0]

        if videoPath !="":
            self.frame_skip = self.spinBox.value()
            vid = VideoFootage(self.ocr_type, self.frame_skip, False, videoPath)
            stack.addWidget(vid)
            stack.setCurrentWidget(vid)

if __name__ == "__main__":
    App = QApplication(sys.argv)
    stack = QStackedWidget()

    home = HomePage()
    stack.addWidget(home)

    stack.setWindowTitle("Automatic Number Plate Recognition")

    stack.setFixedWidth(1600)
    stack.setFixedHeight(900)

    stack.show()

    App.exec_()
    App.quit()


#!/usr/bin/env python

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objects as go
from os.path import isfile, isdir, abspath, join as pjoin
from os import makedirs

import pandas as pd
import numpy as np
import argparse
import logging

from util import delimiter_dict
from verify_ports import get_ports
graphs_port= get_ports('graphs_port')

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
log= logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)

def plot_graph(region, NUM_STD=2):
    '''
    :param region:
    :param NUM_STD: acceptable range of standard deviation
    :return:
    '''

    L = len(subjects)
    val_mean = df[region].values.mean()
    val_std = df[region].values.std()
    # we need val_mean and val_std anyway so not using scipy.stats.zscore function
    zscores = np.array([round((y - val_mean) / val_std, 4) if val_std else 0 for y in df[region].values])
    inliers = abs(zscores) <= NUM_STD

    serial = np.arange(L)

    fig = go.Figure({
        'data': [
            # inliers
            dict(
                x=serial[inliers],
                y=df[region].values[inliers],
                text=[f'Sub: {id}, zscore: {z}' for id,z in zip(subjects[inliers],zscores[inliers])],
                mode='markers',
                name='inliers',
                marker={
                    'size': 15,
                    'opacity': 0.5,
                    'line': {'width': 0.5, 'color': 'white'},
                }
            ),
            # outliers
            dict(
                x=serial[~inliers],
                y=df[region].values[~inliers],
                text=[f'Sub: {id}, zscore: {z}' for id,z in zip(subjects[~inliers],zscores[~inliers])],
                mode='markers',
                name='outliers',
                marker={
                    'size': 15,
                    'opacity': 0.5,
                    'line': {'width': 0.5, 'color': 'white'},
                    'color': 'red'
                }
            ),
            # mean
            dict(
                x=serial,
                y=L * [val_mean],
                mode='lines',
                line={'color': 'black', 'width': 4},
                name='mean'
            ),
            # mean+ NUM*std
            dict(
                x=serial,
                y=L * [val_mean + NUM_STD* val_std],
                mode='lines',
                line={'dash': 'dash', 'color': 'green', 'width': 4},
                name=f'mean + {NUM_STD} x std'
            ),
            # mean- NUM_STD*std
            dict(
                x=serial,
                y=L * [val_mean - NUM_STD* val_std],
                mode='lines',
                line={'dash': 'dash', 'color': 'green', 'width': 4},
                name=f'mean - {NUM_STD} x std'
            )
        ],
        'layout': dict(
            xaxis={
                'title': 'Index of subjects'
            },
            yaxis={
                'title': region
            },
            margin={'l': 50, 'b': 40, 't': 30, 'r': 0},
            hovermode='closest',
            height=400
        )
    })

    # out_html = pjoin(outDir,f'{region}.html')
    # if not isfile(out_html):
    #     fig.write_html(out_html, include_plotlyjs='directory')

    return (fig, inliers, zscores)

if __name__ == '__main__':

    parser= argparse.ArgumentParser(
        description='Detect outliers in FreeSurfer statistics and display them in graphs')

    parser.add_argument('-i', '--input', required=True, help='a csv/tsv file containing region based statistics')
    parser.add_argument('-d', '--delimiter', default='comma', help='delimiter used between measures in the --input '
                                                                   '{comma,tab,space,semicolon}, default: %(default)s')
    parser.add_argument('-o', '--output', required=True, help='a directory where outlier analysis results are saved')
    parser.add_argument('-e', '--extent', type= float, default=2, help='values beyond mean \u00B1 e*STD are outliers, if e<5; '
                        'values beyond e\'th percentile are outliers, if e>70; default %(default)s')

    args= parser.parse_args()
    outDir= abspath(args.output)
    if not isdir(outDir):
        makedirs(outDir, exist_ok= True)

    # df = pd.read_csv('C://Users/tashr/Documents/asegstats_lh.csv')
    # df = pd.read_csv('C://Users/tashr/Documents/aparcstats_lh.csv')
    # outDir = 'C://Users/tashr/Documents/fs-stats-aparc/'

    df = pd.read_csv(abspath(args.input),sep=delimiter_dict[args.delimiter])
    regions = df.columns.values[1:]
    subjects = df[df.columns[0]].values

    # generate all figures
    df_inliers= df.copy()
    for column_name in regions:
        print(column_name)
        _, inliers, zscores= plot_graph(column_name, args.extent)

        # write outlier summary
        df_inliers[column_name] = zscores

    df_inliers.to_csv(pjoin(outDir, 'outliers.csv'), index=False)

    app.layout = html.Div([

        html.Div([
            dcc.Dropdown(
                id='region',
                options=[{'label': i, 'value': i} for i in regions],
                value=regions[0]
            )
        ],
            style={'width': '48%', 'display': 'inline-block'}),

        dcc.Graph(id='stat-graph'),

    ])

    @app.callback(
        Output('stat-graph', 'figure'),
        [Input('region', 'value')])
    def update_graph(region):

        fig, _, _ = plot_graph(region, args.extent)

        return fig

    app.run_server(debug=False, port= graphs_port, host= 'localhost')


from io import StringIO
from meresco.core import Observable
from seecr.test import SeecrTestCase, CallTrace
from weightless.core import be, compose
from lxml.etree import parse, _ElementStringResult, _ElementUnicodeResult, XML
from meresco.components import lxmltostring

from meresco.components import XmlPrintLxml, XmlParseLxml, FileParseLxml

class XmlPumpTest(SeecrTestCase):
    def setUp(self):
        SeecrTestCase.setUp(self)
        self.observer = CallTrace('Observer', ignoredAttributes=['start'])
        self.observable = be(
            (Observable(),
                (XmlParseLxml(fromKwarg='data', toKwarg='lxmlNode'),
                    (self.observer, )
                )
            )
        )

    def testParse(self):
        xmlString = """<tag><content>contents</content></tag>"""
        self.observable.do.add(identifier="id", partname="partName", data=xmlString)

        self.assertEqual(1, len(self.observer.calledMethods))
        self.assertEqual("add", self.observer.calledMethods[0].name)
        self.assertEqual("id", self.observer.calledMethods[0].kwargs['identifier'])
        self.assertEqual("partName", self.observer.calledMethods[0].kwargs['partname'])

        xmlNode = self.observer.calledMethods[0].kwargs['lxmlNode']
        self.assertEqualsLxml(XML(xmlString), xmlNode)

    def testParse2(self):
        xmlString = """<tag><content>contents</content></tag>"""
        self.observable.do.add(identifier="id", partname="partName", data=xmlString)
        self.observable.call.add(identifier="id", partname="partName", data=xmlString)
        self.observer.methods['add'] = lambda **kwargs: (x for x in [])
        list(compose(self.observable.all.add(identifier="id", partname="partName", data=xmlString)))
        list(compose(self.observable.any.add(identifier="id", partname="partName", data=xmlString)))

        self.assertEqual(4, len(self.observer.calledMethods))
        for i in range(4):
            xmlNode = self.observer.calledMethods[i].kwargs['lxmlNode']
            self.assertEqualsLxml(XML(xmlString), xmlNode)

    def testParseWithElementStringResult(self):
        xmlString = _ElementStringResult("""<tag><content>contents</content></tag>""", "utf-8")
        self.observable.do.add(identifier="id", partname="partName", data=xmlString)

        self.assertEqual(1, len(self.observer.calledMethods))
        self.assertEqual("add", self.observer.calledMethods[0].name)
        self.assertEqual("id", self.observer.calledMethods[0].kwargs['identifier'])
        self.assertEqual("partName", self.observer.calledMethods[0].kwargs['partname'])

        xmlNode = self.observer.calledMethods[0].kwargs['lxmlNode']
        rootTag = xmlNode.getroot()
        self.assertEqual('tag', rootTag.tag)
        self.assertEqual(['content'], [c.tag for c in rootTag.getchildren()])

    def testParseWithElementUnicodeResult(self):
        xmlString = _ElementUnicodeResult("""<tag><content>conténts</content></tag>""")
        self.observable.do.add(identifier="id", partname="partName", data=xmlString)

        xmlNode = self.observer.calledMethods[0].kwargs['lxmlNode']
        self.assertEqual(['conténts'], xmlNode.xpath('/tag/content/text()'))

    def testParseWithParseOptions(self):
        xmlString = """<tag xmlns:xyz="uri:xyz">
                <content xmlns:xyz="uri:xyz">contents</content>
            </tag>"""
        self.observable.do.add(identifier="id", partname="partName", data=xmlString)
        self.assertEqual(xmlString, lxmltostring(self.observer.calledMethods[0].kwargs['lxmlNode']))

        self.observable = be(
            (Observable(),
                (XmlParseLxml(fromKwarg='data', toKwarg='lxmlNode', parseOptions=dict(remove_blank_text=True, ns_clean=True)),
                    (self.observer,)
                )
            )
        )
        self.observable.do.add(identifier="id", partname="partName", data=xmlString)
        self.assertEqual("""<tag xmlns:xyz="uri:xyz"><content>contents</content></tag>""", lxmltostring(self.observer.calledMethods[1].kwargs['lxmlNode']))

    def testXmlPrintLxml(self):
        observable = Observable()
        xmlprintlxml = XmlPrintLxml(fromKwarg='lxmlNode', toKwarg="data")
        observer = CallTrace('observer', emptyGeneratorMethods=['someMessage'])
        xmlprintlxml.addObserver(observer)
        observable.addObserver(xmlprintlxml)
        list(compose(observable.all.someMessage(lxmlNode=parse(StringIO('“c')))))
        self.assertEqual(['someMessage'], observer.calledMethodNames())
        self.assertEqual(['data'], list(observer.calledMethods[0].kwargs.keys()))
        self.assertEqual('''
  “c

''', observer.calledMethods[0].kwargs['data'].decode())

    def testXmlPrintLxmlPrettyPrintFalse(self):
        observable = Observable()
        xmlprintlxml = XmlPrintLxml(fromKwarg='lxmlNode', toKwarg="data", pretty_print=False)
        observer = CallTrace('observer', emptyGeneratorMethods=['someMessage'])
        xmlprintlxml.addObserver(observer)
        observable.addObserver(xmlprintlxml)
        list(compose(observable.all.someMessage(lxmlNode=parse(StringIO('“c')))))
        self.assertEqual(['someMessage'], observer.calledMethodNames())
        self.assertEqual(['data'], list(observer.calledMethods[0].kwargs.keys()))
        self.assertEqual(b'''\xe2\x80\x9cc''', observer.calledMethods[0].kwargs['data'])

    def testTransparency(self):
        lxml = CallTrace('lxml')
        lxml2 = CallTrace('lxml2')
        observable = be(
            (Observable(),
                (XmlParseLxml(fromKwarg='data', toKwarg='lxmlNode'),
                    (XmlPrintLxml(fromKwarg='lxmlNode', toKwarg='data'),
                        (lxml, ),
                        (XmlParseLxml(fromKwarg='data', toKwarg='lxmlNode'),
                            (XmlPrintLxml(fromKwarg='lxmlNode', toKwarg='data'),
                                (lxml2,),
                            )
                        )
                    ),
                )
            )
        )

        observable.do.something(identifier='identifier', partname='partName', data='<?xml version="1.0"?>c')
        self.assertEqualsWS('c', lxml.calledMethods[0].kwargs['data'].decode())
        self.assertEqualsWS('c', lxml2.calledMethods[0].kwargs['data'].decode())

    def testMissingFromKwargDoesNothing(self):
        observer = CallTrace()
        observable = be(
            (Observable(),
                (XmlPrintLxml(fromKwarg='lxmlNode', toKwarg='data'),
                    (observer, )
                )
            )
        )

        observable.do.something('identifier', 'partname', parse(StringIO('')))
        self.assertEqual(1, len(observer.calledMethods))
        self.assertEqual("<class 'lxml.etree._ElementTree'>", str(type(observer.calledMethods[0].args[2])))

    def testFileParseLxml(self):
        observable = Observable()
        observer = CallTrace('observer')
        p = FileParseLxml(fromKwarg='filedata', toKwarg='lxmlNode')
        observable.addObserver(p)
        p.addObserver(observer)
        a = StringIO('aaa')
        observable.do.someMessage(filedata=a)
        lxmlA = observer.calledMethods[0].kwargs['lxmlNode']
        self.assertEqual('aaa', lxmltostring(lxmlA))

        with open(self.tempfile, 'w') as f:
            f.write('bbb')
        with open(self.tempfile) as b:
            observable.do.someMessage(filedata=b)
            lxmlB = observer.calledMethods[1].kwargs['lxmlNode']
            self.assertEqual('bbb', lxmltostring(lxmlB))

    def testRenameKwargOnConvert(self):
        observer = CallTrace()
        observable = be(
            (Observable(),
                (XmlPrintLxml(fromKwarg='lxmlNode', toKwarg='dataString'),
                    (observer,),
                )
            )
        )
        observable.do.something('identifier', 'partname', lxmlNode=parse(StringIO('<someXml/>')))
        self.assertEqual(r"something('identifier', 'partname', dataString=b'<someXml/>\n')", str(observer.calledMethods[0]))

        observable.do.something('identifier', 'partname', someKwarg=1)
        self.assertEqual("something('identifier', 'partname', someKwarg=1)", str(observer.calledMethods[1]))

    def testToKwargDefaultsToFromKwarg(self):
        observer = CallTrace()
        observable = be(
            (Observable(),
                (XmlPrintLxml(fromKwarg='data'),
                    (observer,),
                )
            )
        )
        observable.do.something('identifier', 'partname', data=parse(StringIO('<someXml/>')))
        self.assertEqual(r"something('identifier', 'partname', data=b'<someXml/>\n')", str(observer.calledMethods[0]))

    def testLxmltostring(self):
        from lxml.etree import tostring
        uri = "Baháma's"
        xml = """<root><subsub attribute="%s">%s</subsub></root>""" % (uri, uri)
        lxmlNode = parse(StringIO(xml))
        subnode = lxmlNode.xpath("sub")[0]
        self.assertEqual(b"""<subsub attribute="Bah\xc3\xa1ma's">Bah\xc3\xa1ma's</subsub>""", lxmltostring(subnode).encode('utf-8'))
        subsubnode = lxmlNode.xpath("sub/subsub")[0]
        self.assertEqual(b"""<subsub attribute="Baháma's">Bah\xc3\xa1ma's</subsub>""", tostring(subsubnode, encoding='UTF-8'))
        self.assertEqual(b"""<subsub attribute="Bah\xc3\xa1ma's">Bah\xc3\xa1ma's</subsub>""", lxmltostring(subsubnode).encode('utf-8'))

    def testLxmltostringFixes(self):
        from meresco.components.xmlpump import _fixLxmltostringRootElement

        self.assertEqual(b'<root><sub ...', _fixLxmltostringRootElement(b'<root><sub ...'))
        self.assertEqual(b'<root attrib="aap&noot"><sub ...',
                _fixLxmltostringRootElement(b'<root attrib="aap&noot"><sub ...'))
        self.assertEqual(b'<root attrib="aap€noot"><sub ...',
                _fixLxmltostringRootElement(b'<root attrib="aap€noot"><sub ...'))
        self.assertEqual('<root attrib="ĳs"><sub ...'.encode(),
                _fixLxmltostringRootElement(b'<root attrib="ĳs"><sub ...'))
        self.assertEqual('<root attrib="ĳs"><sub ...'.encode(),
                _fixLxmltostringRootElement(b'<root attrib="ĳs"><sub ...'))
        self.assertEqual('<root attrib="ĳs">...'.encode(),
                _fixLxmltostringRootElement(b'<root attrib="ĳs">...'))


s = "Hello world"

m = """

this is una
linea
multiple

"""

n = 5

print((s)+" Volvimo hacer Historia")
print(type(n))

## EN ESTA SECCION DE STRING NOS MUESTRA COMO ES LA RELACION DE LOS TIPOS DE DATOS Y AL REALIZAR EL IMPRESION, PODEMOS REALIZAR UNA  CONCATENACION


# -*- coding: utf-8 -*-
from . import cli, config
import click

shortcuts = ['i','t','w','l','d','a']
shortcuts_type = click.Choice(shortcuts)

@cli.command()
@click.option('-s', '--source', type=shortcuts_type, default='i')
@config.pass_config
def process(config, source):
    """
    process cards from one list to another.
    """
    lists = {
        'i': config.inbox,
        't': config.today,
        'w': config.this_week,
        'l': config.later,
        'd': config.done,
        'a': config.waiting,
    }

    source = lists[source]
    session = config.get_session()

    cards_resp = session.get('https://api.trello.com/1/lists/%s/cards?fields=name,labels,dateLastActivity' % source)
    assert cards_resp.ok

    cards = sorted(
        cards_resp.json(),
        key=lambda card: card['dateLastActivity']
    )
    for card in cards:
        click.clear()
        click.echo(card['name'].strip())
        click.echo('-' * len(card['name'].strip()))
        click.echo()

        if card['labels']:
            click.echo('Labels:')

            for label in sorted(card['labels'], key=lambda l: l['name']):

                # determine color
                fg = 'black'
                note = ''
                if label['color'] == 'orange':
                    fg = 'white'
                    bg = None
                    note = ' * orange'
                elif label['color'] == 'purple':
                    bg = 'magenta'
                else:
                    bg = label['color']

                click.echo(
                    click.style(label['name'], fg=fg, bg=bg, bold=True) + note
                )

            click.echo()

        destination = lists[click.prompt(
            'move to? {%s}' % ','.join(shortcuts),
            type=shortcuts_type
        )]

        resp = session.put(
            'https://api.trello.com/1/cards/%s' % card['id'],
            json={
                'idList': destination,
                'pos': 'bottom',
            }
        )
        assert resp.ok

    click.clear()


userin = int(input("Guess a number from 0-100\n"))

def game(userin):
    import random
    number = int(random.randint(0,101))
    holder1 = 0
    holder2 = 100
    max = 100
    min = 0
    while userin != number:
        if userin > number:
            while userin > number:
                print("Your number is too big\n")
                if userin > holder1:
                    max = userin
                    holder1 = userin
                userin = int(input("Try between {} - {}\n" .format(min+1, userin-1)))

        if userin < number:
            while userin < number:
                print("Your number is too small\n")
                if userin < holder2:
                    min = userin
                    holder2 = userin
                if userin > holder2:
                    if userin>min:
                        min = userin
                userin = int(input("Try between {} - {}\n" .format(userin+1, max-1)))
    else:
     print("Congrats thats the number!\n")
game(userin)
input("Press Enter to exit\n")


# https://leetcode.com/problems/minimum-number-of-refueling-stops/

from heapq import *

class Solution(object):
    def minRefuelStops(self, target, startFuel, stations):
        """
        :type target: int
        :type startFuel: int
        :type stations: List[List[int]]
        :rtype: int
        """
        heap = []
        res, i = 0, 0
        current_fuel = startFuel
        while current_fuel < target:
            while i < len(stations) and stations[i][0] <= current_fuel:
                heappush(heap, -stations[i][1])
                i += 1
            if not heap: return -1
            current_fuel += -heappop(heap)
            res += 1
        return res


# ver1
list01 = [0, 1]

def fibonacci_1(n: int) -> int:
    if n > 1:
        for i in range(2, n+1):
            list01.append(list01[i - 1] + list01[i - 2])
    return list01[-1]

if __name__ == '__main__':
    print(fibonacci_1(1000))

# ver2
dic = {1: 1, 2: 1}

def fibonacci_2(n):
    if n == 0:
        return 0
    if n not in dic:
        dic[n] = fibonacci_2(n - 1) + fibonacci_2(n - 2)
    return dic[n]

print(fibonacci_2(int(input())))


#!/usr/bin/python3 -u

# Note that running python with the `-u` flag is required on Windows,
# in order to ensure that stdin and stdout are opened in binary, rather
# than text, mode.

import json
import sys
import struct

class DatagramInterlocuter:

    class DataProto(DatagramProtocol):

        def __init__(self, interp_dg):
            DatagramProtocol.__init__(self)
            self.interp_dg = interp_dg

        def datagram_received(self, data, addr):
            print('recieved')
            self.interp_dg(data, addr)

    def __init__(self):
        self.transport: DatagramTransport = None
        self.protocol = None
        self.loop = asyncio.get_event_loop()
        self.addr: (str, int) = None
        self.process_fn = None
        #atexit.register(lambda: self.transport.close())
        print('setting up datagram transport')

    def connect(self, port):
        asyncio.ensure_future(self.connect_to(port))
        return self

    async def connect_to(self,
                port: int,
                host='127.0.0.1'):
        print('connecting datagram transport')
        self.addr = (host, port)
        if self.process_fn is None:
            raise Exception('Must use the `handles` method to provide a function for reacting to incoming messages')
        proto = partial(self.DataProto, self.process_fn)
        conn = self.loop.create_datagram_endpoint(
                    lambda: proto(),
                    local_addr=(host, port)
        )
        # print(listen)
        # self.transport, _ = \
        self.transport, self.protocol = await conn
        print(self.transport)
        print('connected')
        return True

    def send(self, data, addr=None):
        print('sending')
        self.transport.sendto(data,
                              addr=self.addr if addr is None
                                    else addr)

    def responds_with(self, receive_fn):
        self.process_fn = partial(receive_fn, self.send)
        return self

# Read a message from stdin and decode it.
async def get_message():
    raw_length = sys.stdin.buffer.read(4)
    if not raw_length:
        sys.exit(0)
    message_length = struct.unpack('i', raw_length)[0]
    message = sys.stdin.buffer.read(message_length)
    return json.loads(message)

# Encode a message for transmission, given its content.
async def encode_message(message_content):
    encoded_content :bytes =\
            json.dumps(message_content).encode('utf-8')
    encoded_length = struct.pack('i', len(encoded_content))
    return {'length': encoded_length, 'content': encoded_content}

# Send an encoded message to stdout.
async def send_message(encoded_message):
    sys.stdout.buffer.write(encoded_message['length'])
    sys.stdout.buffer.write(encoded_message['content'])
    sys.stdout.buffer.flush()

while True:
    message = get_message()
    if message == "ping":
        send_message(await encode_message("pong"))


from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
import django.db.utils
from speechdb.models import Metadata
from speechdb.models import Author, Work, Character, CharacterInstance
from speechdb.models import Speech, SpeechCluster, SpeechTag
import csv
import os
import re
import time
from django.core import serializers

def validate(s, choices, default=None, allow_none=False):
    '''Validate user input'''

    if s is not None:
        s = str(s).strip().lower()
        if len(s) == 0:
            s = None

    allowed = choices.values
    if allow_none:
        allowed.append(None)

    if s not in allowed:
        s = default.value

    return s

def addAuthors(file):
    '''Parse the authors list from a TSV file'''
    f = open(file)
    reader = csv.DictReader(f, delimiter='\t')

    for rec in reader:
        a = Author()
        a.id = int(rec.get('id').strip())
        a.name = rec.get('name').strip()
        a.wd = rec.get('wd').strip()
        a.urn = rec.get('urn').strip()
        a.save()

def addWorks(file):
    '''Parse the works list from a TSV file'''
    f = open(file)
    reader = csv.DictReader(f, delimiter='\t')

    for rec in reader:
        w = Work()
        w.id = int(rec.get('id').strip())
        auth_id = rec.get('author').strip()
        try:
            w.author = Author.objects.get(id=int(auth_id))
        except:
            print(f'Skipping work {w.id}: Can\'t parse author id "{auth_id}".')
            continue
        w.title = rec.get('title').strip()
        w.lang = rec.get('lang').strip()
        w.wd = rec.get('wd').strip()
        w.urn = rec.get('urn').strip()
        w.tlg = rec.get('tlg').strip()
        w.save()

def addChars(file):
    '''Parse the characters list from a TSV file'''
    f = open(file)
    reader = csv.DictReader(f, delimiter='\t')

    # a container for anonymous instances and alternate identities
    characters = {}
    alt_chars = {}
    anon_chars = {}

    for rec in reader:
        c = Character()

        # name
        c.name = rec.get('name').strip() or None
        if c.name is None:
            print(f'Character {c.id} has no name. Skipping')
            continue
        if c.name == 'self':
            continue
        if len(Character.objects.filter(name=c.name)) > 0:
            print(f'Adding duplicate char name {c.name}.')

        # wikidata id
        c.wd = rec.get('wd')
        if c.wd is not None:
            c.wd = c.wd.strip()

        # manto id
        c.manto = rec.get('manto')
        if c.manto is not None:
            c.manto = c.manto.strip()

        # topostext id
        c.tt = rec.get('topostext')
        if c.tt is not None:
            c.tt = c.tt.strip()

        # anonymous
        c.anon = (rec.get('anon') is not None) and (
                    len(rec.get('anon').strip()) > 0)
        # being
        c.being = validate(rec.get('being'), Character.CharacterBeing,
                    default=Character.CharacterBeing.MORTAL)
        # number
        c.number = validate(rec.get('number'), Character.CharacterNumber,
                    default=Character.CharacterNumber.INDIVIDUAL)
        # gender
        c.gender = validate(rec.get('gender'), Character.CharacterGender,
                    default=Character.CharacterGender.NA)

        # disguise
        c.disguise = rec.get('disguise')
        if c.disguise is not None:
            c.disguise = c.disguise.strip()
            if c.disguise == '':
                c.disguise = None
        c.same_as = rec.get('same_as').strip() or None
        c.notes = rec.get('notes').strip() or None

        # tags
        c.tags = {}
        for col in rec.keys():
            if col.startswith('tag_'):
                key = col[4:]
                vals = []
                for tag in rec.get(col).split(','):
                    tag = tag.strip()
                    if tag != '':
                        vals.append(tag)
                if len(vals) > 0:
                    c.tags[key] = vals

        # validation problems
        if c.being is None:
            print(f'Character {c} has no being')

        if c.name in characters or c.name in alt_chars or c.name in anon_chars:
            print(f'Multiple records for name {c.name}.')

        if c.same_as is not None:
            alt_chars[c.name] = c
        elif c.anon:
            anon_chars[c.name] = c
        else:
            characters[c.name] = c
            c.save()

    return characters, alt_chars, anon_chars

def addInst(name, speech, characters, alt_chars={}, anon_chars={}):
    '''get or create character instance'''

    # details of this instance
    instance_params = {
        'name': name,
        'context': speech.work.title,
    }

    # look for the name in characters list, alt ids, anonymous chars
    if name in characters:
        c = characters[name]
        instance_params['name'] = c.name
        instance_params['gender'] = c.gender
        instance_params['being'] = c.being
        instance_params['number'] = c.number
        instance_params['char'] = c
    elif name in alt_chars:
        c = alt_chars[name]
        instance_params['name'] = c.name
        instance_params['gender'] = c.gender
        instance_params['being'] = c.being
        instance_params['number'] = c.number
        instance_params['disguise'] = c.disguise
        instance_params['anon'] = c.anon
        try:
            instance_params['char'] = characters[c.same_as]
        except KeyError:
            print('Pseud {name} points to non-existent char {same_as}.'.format(
                    name=name, same_as=alt_chars[name].same_as))
    elif name in anon_chars:
        c = anon_chars[name]
        instance_params['name'] = c.name
        instance_params['gender'] = c.gender
        instance_params['being'] = c.being
        instance_params['number'] = c.number
        instance_params['anon'] = c.anon
        instance_params['tags'] = c.tags
    else:
        print(f'Failed to find character {name}.')
        return None

    #print(f'DEBUG: speech={speech}; params={instance_params}')
    inst, created = CharacterInstance.objects.get_or_create(**instance_params)

    return inst

def addSpeeches(file, characters, alt_chars={}, anon_chars={}):
    '''Parse the speeches list from a TSV file'''
    f = open(file)
    reader = csv.DictReader(f, delimiter='\t')

    skipped = []
    seq = 1

    for rec in reader:
        s = Speech()
        errs = []

        # seq
        s.seq = seq
        seq += 1

        # locus
        try:
            book_fi = rec.get('from_book').strip()
            assert book_fi
            book_fi += '.'
        except:
            book_fi = ''

        try:
            book_la = rec.get('to_book').strip()
            assert book_la
            book_la += '.'
        except:
            book_la = ''

        try:
            line_fi = rec.get('from_line').strip()
            assert line_fi
        except:
            errs.append('from_line')

        try:
            line_la = rec.get('to_line').strip()
            assert line_la
        except:
            errs.append('to_line')

        s.l_fi = book_fi + line_fi
        s.l_la = book_la + line_la

        # work
        work_id = rec.get('work_id').strip()
        try:
            work_id = int(work_id)
            s.work = Work.objects.get(id=work_id)
        except ValueError:
            work_id = 99
            errs.append('work')

        # cluster type
        try:
            s.type = rec.get('simple_cluster_type')[0].upper()
            assert s.type
        except:
            errs.append('simple_cluster_type')
            # temp value: speech should be deleted
            s.type='M'

        # cluster_id
        cluster_id = rec.get('cluster_id').strip()
        try:
            cluster_id = int(cluster_id)

            s.cluster, cluster_created = SpeechCluster.objects.get_or_create(id=cluster_id)
        except ValueError:
            errs.append('cluster_id')
            cluster_created = False

        # cluster part
        try:
            part = rec.get('cluster_part').strip()
            if 'or' in part:
                m = re.search('\d+', part)
                if m:
                    part = m.group(0)
            s.part = int(part)
        except:
            errs.append('part')
            # temp value: speech should be deleted
            s.part = 1

        # embeddedness
        try:
            s.level = int(rec.get('embedded_level').strip())
        except:
            errs.append('embedded_level')

        # speaker notes
        try:
            s.spkr_notes = rec.get('speaker_notes').strip() or None
        except AttributeError:
            s.spkr_notes = None

        # addressee notes
        try:
            s.addr_notes = rec.get('addressee_notes').strip() or None
        except AttributeError:
            s.addr_notes = None

        # general notes
        s.notes = rec.get('misc_notes').strip() or None

        # speech must be saved before adding character instances
        if len(errs) == 0:
            s.save()

            # speakers
            try:
                spkr_str = rec.get('speaker').strip()
                assert spkr_str != ''

                for name in spkr_str.split(' and '):
                    inst = addInst(name, s, characters=characters,
                            alt_chars=alt_chars, anon_chars=anon_chars)
                    if inst is not None:
                        s.spkr.add(inst)
                assert len(s.spkr.all()) > 0

            except:
                errs.append('speaker')

            # addressees
            try:
                addr_str = rec.get('addressee').strip()
                assert addr_str != ''

                for name in addr_str.split(' and '):
                    if name == 'self':
                        inst = s.spkr.first()
                    else:
                        inst = addInst(name, s, characters=characters,
                                alt_chars=alt_chars, anon_chars=anon_chars)
                    if inst is not None:
                        s.addr.add(inst)
                assert len(s.addr.all()) > 0

            except:
                errs.append('addressee')

            # speech type tags
            tag_notes = rec.get('long_speech_type').strip() or None
            tag_str = rec.get('short_speech_type').strip()
            for tag in tag_str.split(';'):
                tag = tag.strip().lower()
                doubt = tag.endswith('?')
                tag = tag.strip(' ?')
                if tag not in SpeechTag.TagType.values:
                    tag = SpeechTag.TagType.UNDEFINED
                t = SpeechTag(type=tag, speech=s, doubt=doubt, notes=tag_notes)
                t.save()

        else:
            skipped.append((reader.line_num, str(s), errs))
            if cluster_created:
                s.cluster.delete()

    if len(skipped) > 0:
        print(f'skipped {len(skipped)} rows:')
        for line_num, speech, errs in skipped:
            print(line_num, speech, errs)

class Command(BaseCommand):
    help = 'Check data integrity?'

    def add_arguments(self, parser):
        parser.add_argument('path', type=str)

    def handle(self, *args, **options):
        path = options['path']

        # authors
        auth_file = os.path.join(path, 'authors')
        self.stderr.write(f'Reading data from {auth_file}')
        addAuthors(auth_file)

        # works
        work_file = os.path.join(path, 'works')
        self.stderr.write(f'Reading data from {work_file}')
        addWorks(work_file)

        # characters
        char_file = os.path.join(path, 'characters')
        self.stderr.write(f'Reading data from {char_file}')
        characters, alt_chars, anon_chars = addChars(char_file)

        # speeches, clusters, and char instances
        speech_files = [os.path.join(path, f) for f in sorted(os.listdir(path))
                        if f.startswith('speeches')]
        for speech_file in speech_files:
            self.stderr.write(f'Reading data from {speech_file}')
            addSpeeches(speech_file, characters=characters, alt_chars=alt_chars,
                        anon_chars=anon_chars)

        # metadata
        Metadata(name='version', value='0.1').save()
        Metadata(name='date', value=time.strftime('%Y-%m-%d %H:%M:%S %z')).save()


import png
import random
import time

w = 3840
h = 2160
c = 256

pixels = []

start = time.time()

for y in range(h):  # rows
    pixels.append([])

    for x in range(w):  # cols
        color_red = random.randrange(c)
        color_green = random.randrange(c)
        color_blue = random.randrange(c)

        pixels[y].extend( (color_red,color_green,color_blue) )

with open('/tmp/random-image.png', 'wb') as fp:
    image_writer = png.Writer(w, h, greyscale=False)
    image_writer.write(fp, pixels)

print(f"Finished after {time.time() - start} seconds")


# encoding: utf-8

###########################################################################################################
#
#
#	File Format Plugin
#	Implementation for exporting fonts through the Export dialog
#
#	Read the docs:
#	https://github.com/schriftgestalt/GlyphsSDK/tree/master/Python%20Templates/File%20Format
#
#	For help on the use of Xcode:
#	https://github.com/schriftgestalt/GlyphsSDK/tree/master/Python%20Templates
#
#
###########################################################################################################

from __future__ import division, print_function, unicode_literals
import objc
from GlyphsApp import *
from GlyphsApp.plugins import *

# Preference key names
# Part of the example. You may delete them
unicodePref = 'com.test.csvexport.exportUnicode'
glyphWidthPref = 'com.test.csvexport.exportGlyphWidth'

class ____PluginClassName____(FileFormatPlugin):

	# Definitions of IBOutlets

	# The NSView object from the User Interface. Keep this here!
	dialog = objc.IBOutlet()

	# Example variables. You may delete them
	feedbackTextField = objc.IBOutlet()
	unicodeCheckBox = objc.IBOutlet()
	glyphWidthCheckbox = objc.IBOutlet()

	@objc.python_method
	def settings(self):
		self.name = Glyphs.localize({'en': u'My CSV Export', 'de': u'Mein CSV-Export'})
		self.icon = 'ExportIcon'
		self.toolbarPosition = 100

		# Load .nib dialog (with .extension)
		self.loadNib('IBdialog', __file__)

	@objc.python_method
	def start(self):

		# Init user preferences if not existent and set default value
		Glyphs.registerDefault(unicodePref, True)
		Glyphs.registerDefault(glyphWidthPref, True)

		# Set initial state of checkboxes according to user variables
		self.unicodeCheckBox.setState_(Glyphs.defaults[unicodePref])
		self.glyphWidthCheckbox.setState_(Glyphs.defaults[glyphWidthPref])

		# Update text field. You may delete them
		self.updateFeedBackTextField()

	# Example function. You may delete it
	@objc.IBAction
	def setExportUnicode_(self, sender):
		Glyphs.defaults[unicodePref] = bool(sender.intValue())
		self.updateFeedBackTextField()

	# Example function. You may delete it
	@objc.IBAction
	def setExportGlyphWidth_(self, sender):
		Glyphs.defaults[glyphWidthPref] = bool(sender.intValue())
		self.updateFeedBackTextField()

	# Example function. You may delete it
	@objc.python_method
	def updateFeedBackTextField(self):
		string = []
		if Glyphs.defaults[unicodePref]:
			string.append('Unicodes')
		if Glyphs.defaults[glyphWidthPref]:
			string.append('Glyph Width')
		self.feedbackTextField.setStringValue_(', '.join(string) if len(string) else 'Nothing')

	@objc.python_method
	def export(self, font):
		# Ask for export destination and write the file:
		title = "Choose export destination"
		proposedFilename = font.familyName
		fileTypes = ['csv']

		# Call dialog
		filepath = GetSaveFile(title, proposedFilename, fileTypes)

		if filepath:

			import csv

			with open(filepath, 'w') as csvfile:
				fieldnames = ['glyph_name', 'unicode', 'glyph_width']
				writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

				writer.writeheader()

				for g in font.glyphs:
					writeDict = {}
					writeDict['glyph_name'] = g.name

					if Glyphs.defaults[unicodePref] == True and g.unicode:
						writeDict['unicode'] = g.unicode

					if Glyphs.defaults[glyphWidthPref] == True and g.layers[0].width:
						writeDict['glyph_width'] = g.layers[0].width

					writer.writerow(writeDict)

			return (True, 'The export of "%s" was successful.' % (os.path.basename(filepath)))

		else:
			return (False, 'No file chosen')

	@objc.python_method
	def __file__(self):
		"""Please leave this method unchanged"""
		return __file__

Python Templates/File Format/dialog with xib/____PluginName____.glyphsFileFormat/Contents/Resources/plugin.py


from string import ascii_letters
from typing import Callable, Dict

from base.constants import AR_STR_UNSPECIFIED
from base.processors import BaseProcessor
from base.utils.processing_utils import normalize_multi_whitespaces

from hadith.src.websites.sunnah.items import SunnahItem
from hadith.src.websites.sunnah.models import BookModel, ChapterModel, HadithModel

class SunnahProcessor(BaseProcessor):
    TRANSLATE_TABLE = str.maketrans(
        ''.join(['', ' ', '“', '”']),
        ''.join([' ', ' ', '"', '"']),
    )

    def process(self, item: SunnahItem) -> SunnahItem:
        del item.identifier

        item.name = self.__process_dict_values(item.name, lambda text: self.__basic_processing(text))
        item.books = list(map(self.__process_book, item.books))

        return item

    def __process_book(self, book: BookModel) -> BookModel:
        book.name = self.__process_dict_values(book.name, lambda text: self.__basic_processing(text))
        book.chapters = list(map(self.__process_chapter, book.chapters))

        return book

    def __process_chapter(self, chapter: ChapterModel) -> ChapterModel:
        chapter.name = self.__process_dict_values(chapter.name, lambda text: self.__basic_processing(text))

        if not chapter.name['ar']:
            chapter.name['ar'] = AR_STR_UNSPECIFIED

        if not chapter.name['en']:
            chapter.name['en'] = AR_STR_UNSPECIFIED

        chapter.number = self.__process_dict_values(
            chapter.number,
            lambda text: text[1:-1] if text[0] == '(' and text[-1] == ')' else text,
        )
        chapter.number = self.__process_dict_values(chapter.number, lambda text: self.__basic_processing(text))
        chapter.hadiths = list(map(self.__process_hadith, chapter.hadiths))

        return chapter

    def __process_hadith(self, hadith: HadithModel) -> HadithModel:
        hadith.hadith_text = self.__process_dict_values(hadith.hadith_text, lambda text: self.__basic_processing(text))

        if not hadith.hadith_text['ar']:
            hadith.hadith_text['ar'] = AR_STR_UNSPECIFIED

        if not hadith.hadith_text['en']:
            hadith.hadith_text['en'] = AR_STR_UNSPECIFIED

        hadith.grades_text = list(
            map(
                lambda grade_text: self.__process_dict_values(grade_text, lambda text: self.__basic_processing(text)),
                hadith.grades_text,
            ),
        )
        hadith.english_narrator = self.__basic_processing(hadith.english_narrator)
        hadith.references = self.__process_dict_values(hadith.references, lambda text: self.__basic_processing(text))

        return hadith

    def __basic_processing(self, text: str) -> str:
        text = text.strip()

        if text and text[0] == ':':
            text = text[1:]

        if text and text[-1] == ':':
            text = text[:-1]

        text = text.translate(self.TRANSLATE_TABLE)

        if sum(character in ascii_letters for character in text) > len(text) * 0.25:
            text = text.replace(' \ufdfa ', ' peace be upon him ')
            text = text.replace('\ufdfa', 'peace be upon him')
        else:
            text = text.replace(' \ufdfa ', ' صلى الله عليه وسلم ')
            text = text.replace('\ufdfa', 'صلى الله عليه وسلم')

        text = normalize_multi_whitespaces(text).strip()

        return text

    def __process_dict_values(self, dictionary: Dict[str, str], function: Callable) -> Dict[str, str]:
        processed_dictionary = dict()

        for key in dictionary:
            processed_dictionary[key] = function(dictionary[key])

        return processed_dictionary


#-*-coding:utf-8-*-
import numpy as np
import xlrd
import pdb

__all__=['get_testcase']

def get_testcase(which=0):
    if which==2:
        maxmin=np.loadtxt('maxmin1000.dat',dtype='int32')
        p0=np.loadtxt('p01000.dat',dtype='int32')
        table=np.loadtxt('table1000.dat',dtype='int32')
        return maxmin[:,0],maxmin[:,1],table,p0
    elif which==1:
        node_min=np.loadtxt('node_min500.dat',dtype='int32')
        node_max=np.loadtxt('node_max500.dat',dtype='int32')
        p0=np.loadtxt('p0500.dat',dtype='int32')
        table=np.loadtxt('table500.dat',dtype='int32')
        return node_min,node_max,table,p0

    node_min=[10,5,-5,15,5,5,-5,-5,-5]
    node_max=[20,20,10,25,20,20,20,10,15]
    route_table=[[0,4,8],
            [0,3,6],
            [1,4,7],
            [2,5,8],
            [2,4,6],
            [0,1,2],
            [3,4,5],
            [6,7,8]]
    p0=[5,6,15,5,-15,8,4,-10]

    table=np.zeros([len(node_min),len(route_table)],dtype='int32')
    for i in xrange(len(route_table)):
        table[route_table[i],i]=1
    return node_min,node_max,table,p0

def _load_test_data(sheet=1):
    wb = xlrd.open_workbook("data2.xlsx")
    ws = wb.sheet_by_index(sheet)
    #pl=np.array([cell.value for cell in ws.row(1)[3:]])
    minmax=[cell.value.strip('[]').split(',') for cell in ws.col(1)[2:]]
    minval=np.array([int(val[0]) for val in minmax],dtype='int32')
    maxval=np.array([int(val[1]) for val in minmax],dtype='int32')
    data=np.array([[1 if col.value else 0 for col in ws.row(irow)[3:]] for irow in xrange(2,ws.nrows)],dtype='int32')
    data_val=np.array([[col.value if col.value else 0 for col in ws.row(irow)[3:]] for irow in xrange(2,ws.nrows)],dtype='int32')
    max_row=np.argmax(abs(data_val),axis=0)
    pl=data_val[max_row,np.arange(data_val.shape[1])]
    pdb.set_trace()
    return minval,maxcal,data,pl


import torch.utils.data as data
from imageio import imread
import numpy as np

def default_loader(root, path_imgs, path_depth):
    imgs = [imread(root/path) for path in path_imgs]
    depth = np.load(root/path_depth)
    return [imgs, depth]

class ListDataset(data.Dataset):
    def __init__(self, root, path_list, transform=None, target_transform=None,
                 co_transform=None, loader=default_loader):

        self.root = root
        self.path_list = path_list
        self.transform = transform
        self.target_transform = target_transform
        self.co_transform = co_transform
        self.loader = loader

    def __getitem__(self, index):
        inputs, target, displacement = self.path_list[index]
        inputs, target = self.loader(self.root, inputs, target)
        if self.co_transform is not None:
            inputs, target, displacement = self.co_transform(inputs, target, displacement)
        if self.transform is not None:
            inputs[0] = self.transform(inputs[0])
            inputs[1] = self.transform(inputs[1])
        if self.target_transform is not None:
            target = self.target_transform(target)

        return inputs, target, displacement

    def __len__(self):
        return len(self.path_list)


# Write a Python program to get the top three items in a shop. Go to the editor
a={'item1': 45.50, 'item2':35, 'item3': 41.30, 'item4':55, 'item5': 24}

b=list(a)
c=[]
i=0
while i<len(b):
    b.sort(reverse=True)
    x=b[i]
    c.append(x)
    d=c[:3]
    i+=1
print(i,":",d)

# for x, y in a.items():
#   print(x,":" ,y)

# thisdict = {
#   "brand": "Ford",
#   "model": "Mustang",
#   "year": 1964
# }
# mydict = thisdict.copy()
# print(mydict)

# thisdict = {
#   "brand": "Ford",
#   "model": "Mustang",
#   "year": 1964
# }
# mydict = dict(thisdict)
# print(mydict)


from bisect import bisect_left
from itertools import product

with open("day-22.txt") as f:
    lines = [line for line in f.read().rstrip().splitlines()]

trans = str.maketrans("xyz,.=", "      ")
ranges = []
xen, yen, zen = [], [], []
for line in lines:
    on_off, *cuboid = line.translate(trans).split()
    x0, x1, y0, y1, z0, z1 = map(int, cuboid)
    x1 += 1
    y1 += 1
    z1 += 1
    ranges.append((1 if on_off == "on" else 0, (x0, x1, y0, y1, z0, z1)))
    xen.extend([x0, x1])
    yen.extend([y0, y1])
    zen.extend([z0, z1])

xen.sort()
yen.sort()
zen.sort()

size = 2 * len(lines)
assert len(xen) == len(yen) == len(zen) == size

cubes = [[[0] * size for _ in range(size)] for _ in range(size)]
for zero_one, (x0, x1, y0, y1, z0, z1) in ranges:
    x0i = bisect_left(xen, x0)
    x1i = bisect_left(xen, x1)
    y0i = bisect_left(yen, y0)
    y1i = bisect_left(yen, y1)
    z0i = bisect_left(zen, z0)
    z1i = bisect_left(zen, z1)
    for x in range(x0i, x1i):
        for y in range(y0i, y1i):
            for z in range(z0i, z1i):
                cubes[x][y][z] = zero_one

ans = 0
for xi, yi, zi in product(range(size - 1), repeat=3):
    ans += (
        cubes[xi][yi][zi]
        * (xen[xi + 1] - xen[xi])
        * (yen[yi + 1] - yen[yi])
        * (zen[zi + 1] - zen[zi])
    )
print(ans)


import torch
from torch import nn
class LSTM_Net(nn.Module):
    def __init__(self, embedding, embedding_dim, hidden_dim, num_layers, dropout=0.5, fix_embedding=True):
        super(LSTM_Net, self).__init__()
        self.embedding = torch.nn.Embedding(embedding.size(0),embedding.size(1))
        self.embedding.weight = torch.nn.Parameter(embedding)
        self.embedding.weight.requires_grad = False if fix_embedding else True
        self.embedding_dim = embedding.size(1)
        self.hidden_dim = hidden_dim
        self.num_layers = num_layers
        self.dropout = dropout
        self.lstm = nn.LSTM(embedding_dim, hidden_dim, num_layers=num_layers, batch_first=True)
        self.classifier = nn.Sequential( nn.Dropout(dropout),
                                         nn.Linear(hidden_dim, 1),
                                         nn.Sigmoid() )
    def forward(self, inputs):
        inputs = self.embedding(inputs)
        x, _ = self.lstm(inputs, None)
        # x dimension (batch, seq_len, hidden_size)
        x = x[:, -1, :]
        x = self.classifier(x)
        return x


import copy
import math
import sys
from proofs_and_stress_calculation import buckling_proof
from proofs_and_stress_calculation import local_buckling
from cs_optimization_tool import cs_collector
from data_and_defaults import data
from data_and_defaults import defaults
from classes import proposed_stiffener
from classes import stiffeners_proposition
from assembly import add_stiffeners
from assembly import merge
sys.path.insert(0, './user_interface')
from output import printing
from deck_and_initial_cs import deck
from deck_and_initial_cs import initial_cs

#an optimizer that puts the stiffeners in place, such that the single plates inbetween each have the same total pressure
def opt_eqpressure():
    cs_collector.reset()
    b_sup = data.input_data["b_sup"]
    b_inf = data.input_data["b_inf"]
    h = data.input_data["h"]
    t_deck = data.input_data["t_deck"]
    t_values = defaults.t_range_opt
    i_along_values = defaults.I_range
    n_st_side_max = defaults.num_side_stiffeners_max
    n_st_bottom_max = defaults.num_bottom_stiffeners_max

    cs_fresh = initial_cs.create_initial_cs(b_sup, b_inf, h, 1, t_deck, 1)
    st_prop_deck = deck.deck(b_sup, True)
    n_st_deck = len(st_prop_deck.stiffeners)

    assert data.input_data.get("M_Ed") < 1, "Optimizer A does not work for positive bending moments"

    for t_side in t_values:
        print("888888888888888888888888888888888  SIDE T = ", t_side, "888888888888888888888888888888888")
        for t_bottom in t_values:
            print("888888888888888888888888888888888  BOTTOM T = ", t_bottom, "888888888888888888888888888888888")

            empty_cs = set_t_side(copy.deepcopy(cs_fresh), t_side)
            empty_cs = set_t_bottom(empty_cs, t_bottom)

            cs_temp = add_stiffeners.add_stiffener_set(copy.deepcopy(empty_cs), st_prop_deck, "a")
            cs_temp = buckling_proof.buckling_proof(copy.deepcopy(empty_cs))
            sigma_top_red = get_sigma_top_red(cs_temp)
            sigma_bottom_red = get_sigma_bottom_red(cs_temp)

            #the optimizer loop does not loop i_along, as this should be set optimally by the set functions
            n_st_side = 0
            while n_st_side <= n_st_side_max:
                print("\n888888888888888888888888888888888  ITERATION SIDE ", n_st_side, "888888888888888888888888888888888")

                if n_st_side == 0:
                    i_along_values_side = [1]
                else:
                    i_along_values_side = i_along_values
                for i_along_side in i_along_values_side:
                    print("\n&&&&&&&&&&&&&&&&&&&&&&&&& ITERATION I_ALONG_SIDE = ", str(i_along_side/10**5), " &&&&&&&&&&&&&&&&&&&&&&&&&&&")

                    n_st_bottom = 0
                    while n_st_bottom <= n_st_bottom_max:
                        print("\n888888888888888888888888888888888  ITERATION BOTTOM ", n_st_bottom, "888888888888888888888888888888888")

                        if n_st_bottom == 0:
                            i_along_values_bottom = [1]
                        else:
                            i_along_values_bottom = i_along_values
                        for i_along_bottom in i_along_values_bottom:
                            print("\n&&&&&&&&&&&&&&&&&&&&&&&&& ITERATION I_ALONG_BOTTOM = ", str(i_along_bottom/10**5), " &&&&&&&&&&&&&&&&&&&&&&&&&&&")

                            #do it twice; the stresses now are the ones calculated for the same amount of stiffeners (but different place (could do more))
                            for times in range(2):
                                st_prop_side = set_stiffeners_side(copy.deepcopy(empty_cs), n_st_deck, n_st_side, n_st_bottom, sigma_top_red, sigma_bottom_red, i_along_side)
                                st_prop_bottom = set_stiffeners_bottom(copy.deepcopy(empty_cs), n_st_deck, n_st_side, n_st_bottom, sigma_bottom_red, i_along_bottom)
                                st_prop = stiffeners_proposition.stiffeners_proposition()
                                st_prop.stiffeners = copy.deepcopy(st_prop_deck.stiffeners) + copy.deepcopy(st_prop_side.stiffeners) + copy.deepcopy(st_prop_bottom.stiffeners)
                                st_prop.stiffeners = sorted(st_prop.stiffeners, key = lambda st: st.st_number)

                                stiffened_cs = add_stiffeners.add_stiffener_set(copy.deepcopy(empty_cs), st_prop, "a")
                                assert stiffened_cs != True, "cs is bool True"
                                assert stiffened_cs != False, "cs is bool False"
                                stiffened_cs = buckling_proof.buckling_proof(copy.deepcopy(stiffened_cs))

                                #stresses at the top and bottom corner
                                sigma_top_red = get_sigma_top_red(stiffened_cs)
                                sigma_bottom_red = get_sigma_bottom_red(stiffened_cs)

                            if stiffened_cs.proven():
                                cs_collector.into_collector(stiffened_cs)

                        #terminate i_along_bottom
                        n_st_bottom += 1
                    #terminate n_st_bottom
                    #terminate else
                #terminate i_along _side
            #terminate n_st_side
                n_st_side += 1
        #terminate t bottom
    #terminate t_side
    printing.print_best()
    printing.print_best_proof()

def set_t_side(cs, t_side):
    for plate in cs.lines:
        if plate.code.pl_type == 0 and (plate.code.pl_position == 2 or plate.code.pl_position == 4):
            plate.t = t_side
    return cs

def set_t_bottom(cs, t_bottom):
    for plate in cs.lines:
        if plate.code.pl_type == 0 and plate.code.pl_position == 3:
            plate.t = t_bottom
    return cs

def set_stiffeners_side(cs, n_st_deck, amount, n_st_bottom, sigma_top_red, sigma_bottom_red, i_along_side):
    if amount == 0:
        propositions = stiffeners_proposition.stiffeners_proposition()
        return propositions
    else:
        #all tension?
        if sigma_top_red < 0 and sigma_bottom_red < 0:
            propositions = stiffeners_proposition.stiffeners_proposition()
            return propositions

        #where is the higher pressure
        if sigma_top_red > sigma_bottom_red:
            higher_top = True
            sigma_max = sigma_top_red
        else:
            higher_top = False
            sigma_max = sigma_bottom_red

        #the max stress and if all pressure than also the small one
        if sigma_top_red > 0 and sigma_bottom_red > 0:
            if higher_top == True:
                sigma_min = sigma_bottom_red
            else:
                sigma_min = sigma_top_red
        else:
            sigma_min = 0

        psi = min(sigma_top_red, sigma_bottom_red)/max(sigma_top_red, sigma_bottom_red)
        h = data.input_data.get("h")

        #h_c height that is under pressure length of whole triangle
        h_c = h / (1-psi)

        #h_min is the height under pressure that exceeds h
        #h_0 is the height under tension of h
        if h_c < h:
            h_min = 0
            h_0 = h - h_c
        else:
            h_min = h_c - h
            h_0 = 0

        #pressure gradient m
        m = sigma_max / h_c
        #eqpressure means all single plates get the same total force F
        F = (m*h_c**2/2 - m*h_min**2/2) / (2*amount + 1)

        #now to find the distances between the welding points
        distances = []
        i = 1
        sigma_i_before = sigma_min
        #distance is
        #from sigma_min to sigma_max find the distances using m and F
        while i <= 2*amount+1:
            #F = 1/2 * (sigma_before + sigma_before + m * distance_i) * distance_i
            #= = m*distance_i**2 + 2*sigma_before*distance_i -2*F
            distance_i = 1/(2*m) * ( (-2)*sigma_i_before + math.sqrt((2*sigma_i_before)**2 - 4*m*(-2*F)))
            #print("distance_i: "+str(distance_i))
            distances.append(distance_i)
            sigma_i_before = sigma_i_before + m*distance_i
            i += 1

        #sanity check
        #print("h_0", h_0)
        #print("+ sum(distances)", sum(distances))
        #print("= ", math.floor(h_0 + sum(distances)))
        #print("should be ", h)
        assert abs(h-(h_0 + sum(distances))) <= 5, "distances are wrong"

        #locations_abs are the centers between the welding points
        #the first is in distances[1]
        locations_abs = []
        b_sup_list = []
        i = 2
        locations_abs.append(h_0 + copy.deepcopy(distances[0]) + copy.deepcopy(distances[1])/2)
        b_sup_list.append(copy.deepcopy(distances[1]))
        locations_abs_last = copy.deepcopy(locations_abs[0])
        print("")
        print("widths_side: "+str(round(b_sup_list[0])))
        while i <= amount:
            locations_abs_i = locations_abs_last + distances[2*i-2]/2 + distances[2*i-2] + distances[2*i-1]/2
            locations_abs.append(locations_abs_i)
            locations_abs_last = copy.deepcopy(locations_abs_i)
            width_i = copy.deepcopy(distances[2*i-1])
            print("widths_side: "+str(round(width_i)))
            b_sup_list.append(width_i)
            i+=1

        print("")
        print("there are "+str(len(locations_abs))+" in locations_abs")

        #correct to relative height
        locations_side = []
        for locations_abs_i in locations_abs:
            locations_side.append(locations_abs_i / h)
            print("locations_side: "+str(locations_abs_i/h))

        i_alongs = [i_along_side]
        i = 2
        i_along_before = i_along_side
        #the i_alongs are scaled propotionally to the pressure gradient starting from i_along argument being the smallest
        while i <= amount:
            #2*i -1 is the width of the stiffener i
            i_along_next = i_along_before* (locations_abs[i-1] - h_0) / (locations_abs[i-2] - h_0)
            i_alongs.append(i_along_next)
            i_along_before = i_along_next
            i += 1

        #create the proposed_stiffeners
        #find the highest st number on the deck plate the bottom plate has no stiffener yet
        st_number_side1_max = 0
        for plate in cs.lines:
            if plate.code.pl_position == 1 and plate.code.st_number > st_number_side1_max:
                st_number_side1_max = plate.code.st_number

        propositions = stiffeners_proposition.stiffeners_proposition()

        if higher_top == True:

            #propositions are created from bottom to top
            for i in range(amount):
                proposition_right_i = proposed_stiffener.proposed_stiffener(2, n_st_deck + st_number_side1_max + amount - i, locations_side[i], i_alongs[i], b_sup_list[i])
                proposition_right_i.b_sup_corr = True
                propositions.add(proposition_right_i)
                proposition_left_i = proposed_stiffener.proposed_stiffener(4, n_st_deck + st_number_side1_max + n_st_bottom + amount + i +1, locations_side[i], i_alongs[i], b_sup_list[i])
                proposition_left_i.b_sup_corr = True
                propositions.add(proposition_left_i)
                i += 1
        else:
            for i in range(len(locations_side)):
                locations_side[i] = 1- locations_side[i]
            #propositions are created from top to bottom
            for i in range(amount):
                proposition_right_i = proposed_stiffener.proposed_stiffener(2, n_st_deck + st_number_side1_max + 1 + i, locations_side[i], i_alongs[i], b_sup_list[i])
                proposition_right_i.b_sup_corr = True
                propositions.add(proposition_right_i)
                proposition_left_i = proposed_stiffener.proposed_stiffener(4, n_st_deck + st_number_side1_max + n_st_bottom + 2*amount - i, locations_side[i], i_alongs[i], b_sup_list[i])
                proposition_left_i.b_sup_corr = True
                propositions.add(proposition_left_i)
                i += 1

        propositions.stiffeners = sorted(propositions.stiffeners, key = lambda st: st.st_number)

        return propositions

def set_stiffeners_bottom(cs, n_st_deck, n_st_side, amount, sigma_bottom_red, i_along_bottom):
    if amount == 0:
        propositions = stiffeners_proposition.stiffeners_proposition()
        return propositions
    else:
        cs_b_inf = data.input_data.get("b_inf")
        st_b_sup = data.input_data.get("b_inf")/(2*amount + 1)

        locations = []
        #where are the centers of the stiffeners
        #the location is the number of st_b_sup away from y = 0
        #1 st gives 0
        #2 st give -1, 1
        #3 st give -2, 0, 2 ...
        i = -amount + 1
        while i <= amount:
            locations.append(i)
            i += 2
        #change it to the convention of create_stiffener_global
        for l in range(amount):
            locations[l] = locations[l] * st_b_sup /cs_b_inf*2
            print("locations bottom: ", locations[l])
        #print("sum of widths", amount*st_b_sup)

        #create the proposed_stiffeners
        if st_b_sup < 100:
            i_along = 10**5
        elif st_b_sup < 300:
            i_along = 10**6
        elif st_b_sup < 500:
            i_along = 10**7
        else:
            i_along = 5*10**7
        st_number_side1_max = 0
        for plate in cs.lines:
            if plate.code.pl_position == 1 and plate.code.st_number > st_number_side1_max:
                st_number_side1_max = plate.code.st_number

        propositions = stiffeners_proposition.stiffeners_proposition()
        st_number = n_st_deck + st_number_side1_max + n_st_side + 1
        for location in locations:
            proposition = proposed_stiffener.proposed_stiffener(3,st_number, location, i_along, st_b_sup)
            proposition.b_sup_corr = True
            propositions.add(proposition)
            st_number += 1
        #correct the st_numbers of side 4
        for plate in cs.lines:
            if plate.code.pl_type == 1 and plate.code.pl_position == 4:
                plate.code.st_number += amount

        propositions.stiffeners = sorted(propositions.stiffeners, key = lambda st: st.st_number)

        return propositions

def get_sigma_top_red(cs):
    top_plate = cs.get_line(pl_position = 2, pl_type = 0)
    for plate in cs.lines:
        if plate.code.tpl_number <= top_plate.code.tpl_number and plate.code.pl_position == 2 and plate.code.pl_type == 0:
            top_plate = plate
    return top_plate.sigma_a_red

def get_sigma_bottom_red(cs):
    bottom_plate = copy.deepcopy(cs.get_line(pl_position = 2, pl_type = 0))
    for plate in cs.lines:
        if plate.code.tpl_number >= bottom_plate.code.tpl_number and plate.code.pl_position == 2 and plate.code.pl_type == 0:
            bottom_plate = copy.deepcopy(plate)
    return bottom_plate.sigma_b_red


from __future__ import annotations
from typing import List
from heapq import heappush, heappop

# https://leetcode.com/problems/trapping-rain-water-ii/discuss/1138028/Python3Visualization-BFS-Solution-With-Explanation
class Solution:
    def trapRainWater(self, heightMap: list[List[int]]) -> int:
        if not heightMap or not heightMap[0]:
            return 0

        m, n = len(heightMap), len(heightMap[0])
        if m < 3 or n < 3:
            return 0

        heap = []
        for i in range(m):
            for j in range(n):
                if i == 0 or i == m-1 or j == 0 or j == n-1:
                    heappush(heap, (heightMap[i][j], i, j))
                    heightMap[i][j] = -1

        level, ans = 0, 0

        while heap:
            # Notice heappop pops the lowest height
            height, x, y = heappop(heap)
            level = max(height, level)
            for i, j in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]:
                if 0 <= i < m and 0 <= j < n and heightMap[i][j] != -1:
                    heappush(heap, (heightMap[i][j], i, j))
                    if heightMap[i][j] < level:
                        ans += level - heightMap[i][j]
                    heightMap[i][j] = -1  # Set -1 if visited

        print(ans)
        return ans

test = Solution()
test.trapRainWater([[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]) # 4

test = Solution()
test.trapRainWater([[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]])
# 10


from detext.server.ml.models.mobilenet import MobileNet, preprocess

from PIL import Image

import torch
import torch.nn.functional as F

from detext.server.models import MathSymbol

from torchvision import datasets

from torch.utils.data import DataLoader

def get_class_name(item):
    return item.name

def run():
    class_table = MathSymbol
    classes = [
        get_class_name(cls_ent)
        for cls_ent in class_table.objects.all().order_by('timestamp')
    ]
    class_to_ix = {
        get_class_name(cls_ent): ix for ix, cls_ent in
        enumerate(class_table.objects.all().order_by('timestamp'))
    }
    print(class_to_ix)

    file_name = "test_augment.pth"

    model = MobileNet.from_file(file_name, test_time_dropout=False,
                                estimate_variane=True)
    model.eval().cuda()

    iters = 200

    full_dataset = datasets.ImageFolder("res/certain", preprocess)
    dataloader = DataLoader(full_dataset, batch_size=1, shuffle=False,
                            num_workers=4)

    for i, data in enumerate(dataloader):
        preds = torch.zeros((iters, 63))
        softmaxs = torch.zeros((iters, 63))
        maxs = torch.zeros(iters)
        variances = None

        inputs, labels = data

        print(labels)

        inputs = inputs.cuda()

        for j in range(iters):
            res = model(inputs)
            pred = res[0]
            var = res[1]
            pred, var = pred.detach().cpu(), var.detach().cpu()
            preds[j] = pred[0]
            maxs[j] = pred.argmax()
            softmaxs[j] = F.softmax(pred[0])
            variances = var[0]

        stds = softmaxs.std(dim=0)
        m = int(maxs[0].item())

        print(m)
        print(stds[m]/0.001)
        print(variances[m]/0.001)


"""
Some useful functions to manage file on the server
"""

import os, errno
import subprocess
import pandas as pd
import yaml
import time
import os
from shutil import copyfile

def archiveFile(path, fileName):
    """
    TimeStamp and archive the specified file
    """
    timestamp = time.strftime('%b-%d-%Y_%H%M', time.localtime())
    if(os.path.isfile(path + fileName)):
        newFileName = fileName + timestamp + '.h5'
        if(os.path.isfile(path + newFileName)):
            newFileName = fileName + '_2_' + timestamp + '.h5'
        copyfile(path + fileName, path + newFileName)
        print("File archived at: " + path + newFileName)
    else:
        print("No archive needed")
    return

def loadSettingsFromYamlFile(filePath):
    """
    Load settings from a yaml file specified by the filepath
    """
    with open(filePath, 'r') as f:
        settings = yaml.load(f)
    return settings

def store_df_in_named_file(df, name, downloadLocally = False):
    """
    Stores Pandas DataFrame df in h5 file with name "name"
    """

    silentremove(ensure_suffix(name, '.h5'))
    with pd.HDFStore(ensure_suffix(name, '.h5'), complevel=9,
                     complib='blosc') as store:
        store['df'] = df

    """
    df.to_csv(name + ".txt", sep = '\t', encoding = 'utf-16')
    """

    if downloadLocally:
        print("Downloading " + str(ensure_suffix(name, '.h5')))
        subprocess.call(["sz",ensure_suffix(name, '.h5')])

def get_df_from_named_file(name, df_name='df'):
    """
    Gets Pandas DataFrame name from h5 file with name "df_name"
    """

    with pd.HDFStore(ensure_suffix(name, '.h5')) as store:
        return store[df_name]

    """
    df = pd.read_csv(name + ".txt", sep = '\t', encoding = 'utf-16')
    """

def silentremove(filename):
    """
    Silently removes file. Usually h5 file.
    """
    try:
        os.remove(filename)
    except OSError as e:
        if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory
            raise # re-raise exception if a different error occured

def ensure_suffix(string, suffix):
    """
    Ensures that a file name "string" has a suffix "suffix".
    If it doesn't have it, the function adds suffix to the file name "string"
    """
    if string.endswith(suffix):
        return string
    else:
        return string + suffix


# используется для сортировки
from operator import itemgetter

class Lang:
    """Язык программирования"""
    def __init__(self, id, name, rating, tool_id):
        self.id = id
        self.name = name
        self.rating = rating
        self.tool_id = tool_id

class DevTool:
    """Средство разработки"""
    def __init__(self, id, name):
        self.id = id
        self.name = name

class LangDevTool:
    """
    'Средства разработки языков программирования' для реализации
    связи многие-ко-многим
    """
    def __init__(self, lang_id, tool_id):
        self.lang_id = lang_id
        self.tool_id = tool_id

# Средства разработки
devTools = [
    DevTool(1, 'Android Studio'),
    DevTool(2, 'IntelliJ IDEA'),
    DevTool(3, 'Visual Studio Code 2020'),
    DevTool(4, 'Visual Studio 2019'),
    DevTool(13, 'CLion'),
    DevTool(20, 'PyCharm'),
]

# Языки программирования
langs = [
    Lang(1, 'Java', 95.3, 1),
    Lang(2, 'JavaScript', 79.5, 3),
    Lang(5, 'C++', 87, 4),
    Lang(11, 'C#', 48.1, 4),
    Lang(19, 'Python', 100, 20),
    Lang(31, 'F#', 34.7, 4),
]

langs_devTools = [
    LangDevTool(1,1),
    LangDevTool(1,2),
    LangDevTool(2,3),
    LangDevTool(5,4),
    LangDevTool(5,13),
    LangDevTool(11,4),
    LangDevTool(19,3),
    LangDevTool(19,4),
    LangDevTool(19,20),
    LangDevTool(31,4),
]

def main():
    """Основная функция"""

    # Соединение данных один-ко-многим
    one_to_many = [(l.name, l.rating, t.name)
        for l in langs
        for t in devTools
        if l.tool_id==t.id]

    # Соединение данных многие-ко-многим
    many_to_many_temp = [(t.name, ldt.lang_id, ldt.tool_id)
        for t in devTools
        for ldt in langs_devTools
        if t.id==ldt.tool_id]

    many_to_many = [(l.name, l.rating, tool_name)
        for tool_name, lang_id, tool_id in many_to_many_temp
        for l in langs
        if l.id==lang_id]

    print('Задание D1')
    res1 = []
    for i in one_to_many:
        if i[0].endswith('#') ==True:
            res1.append(i[0:3:2])
    print(res1)

    print('\nЗадание D2')
    res_12_unsorted = []
    # Перебираем все средства разработки(инструменты)
    for t in devTools:
        # Список языков, поддерживаемых инструментом разработки
        t_langs = list(filter(lambda i: i[2]==t.name, one_to_many))
        if len(t_langs) > 0:
            # Находим средний рейтинг языков для каждого инструмента
            t_rating = [rating for _,rating,_ in t_langs]
            t_rating_sum = sum(t_rating)
            t_rating_count = len(t_rating)
            t_rating_average = t_rating_sum / t_rating_count
            res_12_unsorted.append((t.name, t_rating_average))

    # Сортировка по среднему рейтингу
    res_12 = sorted(res_12_unsorted, key=itemgetter(1), reverse=True)
    print(res_12)

    print('\nЗадание Д3')
    res3 = {}
    # Перебираем все средства разработки(инструменты)
    for t in devTools:
        #Выбираем инструменты, название которых начинается на букву V
        if t.name[0] == "V":
            t_langs = list(filter(lambda i: i[2] == t.name, many_to_many))
            # Только название языка
            o_langs_names = [x for x, _, _ in t_langs]
            # Добавляем результат в словарь
            # ключ - инструмент, значение - список языков
            res3[t.name] = o_langs_names
    print(res3)

if __name__ == '__main__':
    main()


"""
Source: https://leetcode.com/problems/validate-binary-search-tree/
Date: 2023/1/27
Skill:
Runtime: 44 ms, faster than 84.48%
Memory Usage: 16.2 MB, less than 99.34%
Time complexity:
Space complexity:
Constraints:
    The number of nodes in the tree is in the range [1, 10^4].
"""

import math
from typing import List, Optional
from collections import defaultdict, deque
from heapq import heapify, heappush, heappop, nsmallest

import heapq
import functools

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def isValidBST(self, root: Optional[TreeNode]) -> bool:

        cur, stack, prev = root, [], -math.inf
        while cur:
            stack.append(cur)
            cur = cur.left

        while stack:
            cur = stack.pop()
            if cur.val <= prev: return False
            prev = cur.val
            if cur.right:
                cur = cur.right
                while cur:
                    stack.append(cur)
                    cur = cur.left

        return True

0001~0500/0098. Validate Binary Search Tree/main2.py


import json
from http_get_request import *
import os

with open('data/lemmaId_set.json', 'r') as f:
    lemmaId_set = set(json.load(f))

if os.path.exists('data/kexue/') == False:
    os.mkdir('data/kexue/')

for i in lemmaId_set:
    print(i)
    time.sleep(0.5)
    # https://baike.sogou.com/kexue/d69917841985450255.htm
    r = http_get_request(f'https://baike.sogou.com/kexue/d{i}.htm')
    with open(f'running.htm', 'w') as f:
        f.write(r.text)
    with open(f'data/kexue/d{i}.htm', 'w') as f:
        f.write(r.text)


# import the module
import json
import requests
import logging
import Wallpaper
from tweepy.simpleAuth import simpleAuth

consumer_key = ""
consumer_secret = ""

access_token = ""
access_token_secret = ""

api = simpleAuth(consumer_key, consumer_secret, access_token, access_token_secret)

logger = logging.getLogger()
logging.basicConfig(level=logging.INFO)
logger.setLevel(logging.INFO)

# 외부 API 불러오기
def get_Cat():
    url = "https://api.thecatapi.com/v1/images/search"

    try:
        response = requests.get(url)
    except:
        logger.info("Error while calling API...")

    res = json.loads(response.text)
    print(res)
    print(res[0]["url"])
    return res[0]["url"]

# 마지막 트윗 정보 확인
def get_last_tweet(file):
    f = open(file, 'r')
    lastId = int(f.read().strip())
    f.close()
    return lastId

# 마지막 트윗 아이디 파일에 쓰기
def put_last_tweet(file, Id):
    f = open(file, 'w')
    f.write(str(Id))
    f.close()
    logger.info("Updated the file with the latest tweet Id")
    return

# 트위터 봇 자동 응답 기능
def respondToTweet(file='tweet_ID.txt'):
    last_id = get_last_tweet(file)
    mentions = api.mentions_timeline(since_id=last_id, tweet_mode='extended')
    if len(mentions) == 0:
        return

    new_id = 0
    logger.info("someone mentioned me...")

    for mention in reversed(mentions):
        logger.info(str(mention.id) + '-' + mention.full_text)
        new_id = mention.id
        print("id : ")
        print(new_id)

        # #cat이라는 키워드가 있을 시 아래 내용 수행
        if '#cat' in mention.full_text.lower():
            logger.info("Responding back with Cat to -{}".format(mention.id))
            try:
                tweet = get_Cat()
                Wallpaper.get_wallpaper(tweet)

                media = api.media_upload(filename="created_image.png")

                logger.info("liking and replying to tweet")

                api.create_favorite(mention.id)

                api.update_status('@' + mention.user.screen_name + " Here's your Cat",
                                  media_ids=[media.media_id])
            except:
                logger.info("Already replied to {}".format(mention.id))

    put_last_tweet(file, new_id)

if __name__ == "__main__":
    respondToTweet()


from paddle.io import Dataset, DataLoader
import os
import numpy as np
from PIL import Image, ImageOps
import random
import matplotlib.pyplot as plt

from config.init import OPT

# 处理图片数据：裁切、水平翻转、调整图片数据形状、归一化数据
def data_transform(img, resize_w, resize_h, load_size=286, pos=[0, 0, 256, 256], flip=True, is_image=True):
    if is_image:
        resized = img.resize((resize_w, resize_h), Image.BICUBIC)
    else:
        resized = img.resize((resize_w, resize_h), Image.NEAREST)
    croped = resized.crop((pos[0], pos[1], pos[2], pos[3]))
    fliped = ImageOps.mirror(croped) if flip else croped
    fliped = np.array(fliped) # transform to numpy array
    expanded = np.expand_dims(fliped, 2) if len(fliped.shape) < 3 else fliped
    transposed = np.transpose(expanded, (2, 0, 1)).astype('float32')
    if is_image:
        normalized = transposed / 255. * 2. - 1.
    else:
        normalized = transposed
    return normalized

# 定义CoCo数据集对象
class COCODateset(Dataset):
    def __init__(self, opt):
        super(COCODateset, self).__init__()
        inst_dir = opt.dataroot+'coco_stuff/train_inst/'
        _, _, inst_list = next(os.walk(inst_dir))
        self.inst_list = np.sort(inst_list)
        self.opt = opt

    def __getitem__(self, idx):
        ins = Image.open(self.opt.dataroot+'coco_stuff/train_inst/'+self.inst_list[idx])
        lab = Image.open(self.opt.dataroot+'coco_stuff/train_label/'+self.inst_list[idx])
        img = Image.open(self.opt.dataroot+'coco_stuff/train_img/'+self.inst_list[idx].replace(".png", ".jpg"))
        img = img.convert('RGB')

        w, h = img.size
        resize_w, resize_h = 0, 0
        if w < h:
            resize_w, resize_h = self.opt.load_size, int(h * self.opt.load_size / w)
        else:
            resize_w, resize_h = int(w * self.opt.load_size / h), self.opt.load_size
        left = random.randint(0, resize_w - self.opt.crop_size)
        top = random.randint(0, resize_h - self.opt.crop_size)
        flip = True if random.randint(0, 100) > 50 else False

        img = data_transform(img, resize_w, resize_h, load_size=self.opt.load_size,
            pos=[left, top, left + self.opt.crop_size, top + self.opt.crop_size], flip=flip, is_image=True)
        ins = data_transform(ins, resize_w, resize_h, load_size=self.opt.load_size,
            pos=[left, top, left + self.opt.crop_size, top + self.opt.crop_size], flip=flip, is_image=False)
        lab = data_transform(lab, resize_w, resize_h, load_size=self.opt.load_size,
            pos=[left, top, left + self.opt.crop_size, top + self.opt.crop_size], flip=flip, is_image=False)

        # 将label中的背景类别从255改为182
        mask = lab == 255
        nc = self.opt.label_nc + 1 if self.opt.contain_dontcare_label else self.opt.label_nc
        lab[mask] = nc - 1

        return img, ins, lab, self.inst_list[idx]

    def __len__(self):
        return len(self.inst_list)

if __name__ == '__main__':
    opt = OPT()
    opt.dataroot = '/home/aistudio/data/data96023/'
    # 定义图片loader
    cocods = COCODateset(opt)
    loader = DataLoader(cocods, shuffle=True, batch_size=1, drop_last=False, num_workers=1, use_shared_memory=False)
    for i, data in enumerate(loader):
        if i > 3 - 1:
            break
        img, ins, lab = data
        print('data shape:', img.shape, ins.shape, lab.shape)

        img = (np.transpose(img.numpy()[0], (1, 2, 0)) + 1.) / 2.
        ins = np.transpose(ins.numpy()[0], (1, 2, 0))[:, :, 0]
        lab = np.transpose(lab.numpy()[0], (1, 2, 0))[:, :, 0]

        plt.figure(figsize=(12,4),dpi=80)
        plt.subplot(1, 3, 1)
        plt.imshow(img)
        plt.subplot(1, 3, 2)
        plt.imshow(ins)
        plt.subplot(1, 3, 3)
        plt.imshow(lab)
        plt.show()