"""
Leer una cadena de caracteres e imprimirla centrada en pantalla. Suponer que la misma tiene 80 columnas.
"""

ANCHO_PANTALLA = 80

def centrar(cadena):
    espacios = (ANCHO_PANTALLA - len(cadena)) // 2
    espacios = " " * espacios
    return espacios + cadena + espacios

if __name__ == "__main__":
    print(centrar(input("Ingrese una cadena para imprirla centrada:\n")))


import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QSizePolicy, QMessageBox, QWidget, QPushButton, QLabel, QHBoxLayout, QVBoxLayout, QGroupBox, QSlider, QLineEdit
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from neuron import Neuron_HR as Neuron

class CentralWidget(QWidget):
    def __init__(self, parent=None):
        super(CentralWidget, self).__init__(parent)
        self.initUI()

    def initUI(self):
        self.glaph = PlotCanvas(None, width=5, height=4)
        navi = NavigationToolbar(self.glaph, self)

        # glaph
        layout_glaph = QVBoxLayout()
        layout_glaph.addWidget(self.glaph)
        layout_glaph.addWidget(navi)

        # HR model palm range
        self.a_max = 3
        self.a_min = -1
        self.b_max = 5
        self.b_min = 1
        self.c_max = 3
        self.c_min = 1
        self.d_max = 10
        self.d_min = 1
        self.r_max = 0.1
        self.r_min = 0.001
        self.s_max = 5
        self.s_min = 1
        self.xr_max = 3
        self.xr_min = -3
        self.i_max = 10
        self.i_min = -10
        self.gcmp_max = 20
        self.gcmp_min = 0
        self.delay_max = 150
        self.delay_min = 0

        self.slider_min = 1
        self.slider_max = 100

        # HR model palameter
        layout1_2 = QHBoxLayout()
        layout1 = QVBoxLayout()
        self.slider1 = QSlider(Qt.Horizontal)
        self.slider1.setRange(self.slider_min, self.slider_max)
        self.slider1.setValue(int(self.glaph.a - self.a_min) /
                              (self.a_max - self.a_min)*self.slider_max)
        self.label1 = QLabel('a :')
        layout1_2.addWidget(self.label1)
        layout1_2.addWidget(self.slider1)
        self.textbox1 = QLineEdit()
        self.textbox1.setText(str(self.glaph.a))
        layout1.addWidget(self.textbox1)
        layout1.addLayout(layout1_2)

        layout2_2 = QHBoxLayout()
        layout2 = QVBoxLayout()
        self.slider2 = QSlider(Qt.Horizontal)
        self.slider2.setRange(self.slider_min, self.slider_max)
        self.slider2.setValue(int(self.glaph.b - self.b_min) /
                              (self.b_max - self.b_min)*self.slider_max)
        self.label2 = QLabel('b :')
        layout2_2.addWidget(self.label2)
        layout2_2.addWidget(self.slider2)
        self.textbox2 = QLineEdit()
        self.textbox2.setText(str(self.glaph.b))
        layout2.addWidget(self.textbox2)
        layout2.addLayout(layout2_2)

        layout3_2 = QHBoxLayout()
        layout3 = QVBoxLayout()
        self.slider3 = QSlider(Qt.Horizontal)
        self.slider3.setRange(self.slider_min, self.slider_max)
        self.slider3.setValue(int(self.glaph.c - self.c_min) /
                              (self.c_max - self.c_min)*self.slider_max)
        self.label3 = QLabel('c :')
        layout3_2.addWidget(self.label3)
        layout3_2.addWidget(self.slider3)
        self.textbox3 = QLineEdit()
        self.textbox3.setText(str(self.glaph.c))
        layout3.addWidget(self.textbox3)
        layout3.addLayout(layout3_2)

        layout4_2 = QHBoxLayout()
        layout4 = QVBoxLayout()
        self.slider4 = QSlider(Qt.Horizontal)
        self.slider4.setRange(self.slider_min, self.slider_max)
        self.slider4.setValue(int(self.glaph.d - self.d_min) /
                              (self.d_max - self.d_min)*self.slider_max)
        self.label4 = QLabel('d :')
        layout4_2.addWidget(self.label4)
        layout4_2.addWidget(self.slider4)
        self.textbox4 = QLineEdit()
        self.textbox4.setText(str(self.glaph.d))
        layout4.addWidget(self.textbox4)
        layout4.addLayout(layout4_2)

        layout5_2 = QHBoxLayout()
        layout5 = QVBoxLayout()
        self.slider5 = QSlider(Qt.Horizontal)
        self.slider5.setRange(self.slider_min, self.slider_max)
        self.slider5.setValue(int(self.glaph.r - self.r_min) /
                              (self.r_max - self.r_min)*self.slider_max)
        self.label5 = QLabel('r :')
        layout5_2.addWidget(self.label5)
        layout5_2.addWidget(self.slider5)
        self.textbox5 = QLineEdit()
        self.textbox5.setText(str(self.glaph.r))
        layout5.addWidget(self.textbox5)
        layout5.addLayout(layout5_2)

        layout6_2 = QHBoxLayout()
        layout6 = QVBoxLayout()
        self.slider6 = QSlider(Qt.Horizontal)
        self.slider6.setRange(self.slider_min, self.slider_max)
        self.slider6.setValue(int(self.glaph.s - self.s_min) /
                              (self.s_max - self.s_min)*self.slider_max)
        self.label6 = QLabel('s :')
        layout6_2.addWidget(self.label6)
        layout6_2.addWidget(self.slider6)
        self.textbox6 = QLineEdit()
        self.textbox6.setText(str(self.glaph.s))
        layout6.addWidget(self.textbox6)
        layout6.addLayout(layout6_2)

        layout7_2 = QHBoxLayout()
        layout7 = QVBoxLayout()
        self.slider7 = QSlider(Qt.Horizontal)
        self.label7 = QLabel('xr :')
        self.slider7.setRange(self.slider_min, self.slider_max)
        self.slider7.setValue(int(self.glaph.xr - self.xr_min) /
                              (self.xr_max - self.xr_min)*self.slider_max)
        layout7_2.addWidget(self.label7)
        layout7_2.addWidget(self.slider7)
        self.textbox7 = QLineEdit()
        self.textbox7.setText(str(self.glaph.xr))
        layout7.addWidget(self.textbox7)
        layout7.addLayout(layout7_2)

        layout8_2 = QHBoxLayout()
        layout8 = QVBoxLayout()
        self.slider8 = QSlider(Qt.Horizontal)
        self.slider8.setRange(self.slider_min, self.slider_max)
        self.slider8.setValue(int(self.glaph.i - self.i_min) /
                              (self.i_max - self.i_min)*self.slider_max)
        self.label8 = QLabel('I :')
        layout8_2.addWidget(self.label8)
        layout8_2.addWidget(self.slider8)
        self.textbox8 = QLineEdit()
        self.textbox8.setText(str(self.glaph.i))
        layout8.addWidget(self.textbox8)
        layout8.addLayout(layout8_2)

        layout9_2 = QHBoxLayout()
        layout9 = QVBoxLayout()
        self.slider9 = QSlider(Qt.Horizontal)
        self.slider9.setRange(self.slider_min, self.slider_max)
        self.slider9.setValue(int(self.glaph.gcmp - self.gcmp_min) /
                              (self.gcmp_max - self.gcmp_min)*self.slider_max)
        self.label9 = QLabel('gcmp :')
        layout9_2.addWidget(self.label9)
        layout9_2.addWidget(self.slider9)
        self.textbox9 = QLineEdit()
        self.textbox9.setText(str(self.glaph.gcmp))
        layout9.addWidget(self.textbox9)
        layout9.addLayout(layout9_2)

        layout10_2 = QHBoxLayout()
        layout10 = QVBoxLayout()
        self.slider10 = QSlider(Qt.Horizontal)
        self.slider10.setRange(self.slider_min, self.slider_max)
        self.slider10.setValue(int(self.glaph.delay - self.delay_min) /
                              (self.delay_max - self.delay_min)*self.slider_max)
        self.label10 = QLabel('delay :')
        layout10_2.addWidget(self.label10)
        layout10_2.addWidget(self.slider10)
        self.textbox10 = QLineEdit()
        self.textbox10.setText(str(self.glaph.delay))
        layout10.addWidget(self.textbox10)
        layout10.addLayout(layout10_2)

        layout_palm = QVBoxLayout()
        layout_palm.addLayout(layout1)
        layout_palm.addLayout(layout2)
        layout_palm.addLayout(layout3)
        layout_palm.addLayout(layout4)
        layout_palm.addLayout(layout5)
        layout_palm.addLayout(layout6)
        layout_palm.addLayout(layout7)
        layout_palm.addLayout(layout8)
        layout_palm.addLayout(layout9)
        layout_palm.addLayout(layout10)

        groupBox1 = QGroupBox("palm")
        groupBox2 = QGroupBox("glaph")
        sizePolicy1 = groupBox1.sizePolicy()
        sizePolicy2 = groupBox2.sizePolicy()
        sizePolicy1.setHorizontalStretch(2)
        sizePolicy2.setHorizontalStretch(7)
        groupBox1.setSizePolicy(sizePolicy1)
        groupBox2.setSizePolicy(sizePolicy2)
        groupBox1.setLayout(layout_palm)
        groupBox2.setLayout(layout_glaph)

        layout_main = QHBoxLayout()
        layout_main.addWidget(groupBox1)
        layout_main.addWidget(groupBox2)
        self.setLayout(layout_main)

        # signal
        self.textbox1.textChanged.connect(self.text1_changed)
        self.textbox2.textChanged.connect(self.text2_changed)
        self.textbox3.textChanged.connect(self.text3_changed)
        self.textbox4.textChanged.connect(self.text4_changed)
        self.textbox5.textChanged.connect(self.text5_changed)
        self.textbox6.textChanged.connect(self.text6_changed)
        self.textbox7.textChanged.connect(self.text7_changed)
        self.textbox8.textChanged.connect(self.text8_changed)
        self.textbox9.textChanged.connect(self.text9_changed)
        self.textbox10.textChanged.connect(self.text10_changed)
        self.slider1.valueChanged.connect(self.slider1_changed)
        self.slider2.valueChanged.connect(self.slider2_changed)
        self.slider3.valueChanged.connect(self.slider3_changed)
        self.slider4.valueChanged.connect(self.slider4_changed)
        self.slider5.valueChanged.connect(self.slider5_changed)
        self.slider6.valueChanged.connect(self.slider6_changed)
        self.slider7.valueChanged.connect(self.slider7_changed)
        self.slider8.valueChanged.connect(self.slider8_changed)
        self.slider9.valueChanged.connect(self.slider9_changed)
        self.slider10.valueChanged.connect(self.slider10_changed)

    # slot
    def text1_changed(self):
        if self.textbox1.text() is "":
            self.glaph.replot_a(float(self.glaph.tmp_a))
        else:
            self.glaph.replot_a(float(self.textbox1.text()))

    def text2_changed(self):
        if self.textbox2.text() is "":
            self.glaph.replot_b(float(self.glaph.tmp_b))
        else:
            self.glaph.replot_b(float(self.textbox2.text()))

    def text3_changed(self):
        if self.textbox3.text() is "":
            self.glaph.replot_c(float(self.glaph.tmp_c))
        else:
            self.glaph.replot_c(float(self.textbox3.text()))

    def text4_changed(self):
        if self.textbox4.text() is "":
            self.glaph.replot_d(float(self.glaph.tmp_d))
        else:
            self.glaph.replot_d(float(self.textbox4.text()))

    def text5_changed(self):
        if self.textbox5.text() is "":
            self.glaph.replot_r(float(self.glaph.tmp_r))
        else:
            self.glaph.replot_r(float(self.textbox5.text()))

    def text6_changed(self):
        if self.textbox6.text() is "":
            self.glaph.replot_s(float(self.glaph.tmp_s))
        else:
            self.glaph.replot_s(float(self.textbox6.text()))

    def text7_changed(self):
        if self.textbox7.text() is "":
            self.glaph.replot_xr(float(self.glaph.tmp_xr))
        else:
            self.glaph.replot_xr(float(self.textbox7.text()))

    def text8_changed(self):
        if self.textbox8.text() is "":
            self.glaph.replot_i(float(self.glaph.tmp_i))
        else:
            self.glaph.replot_i(float(self.textbox8.text()))

    def text9_changed(self):
        if self.textbox9.text() is "":
            self.glaph.replot_gcmp(float(self.glaph.tmp_gcmp))
        else:
            self.glaph.replot_gcmp(float(self.textbox9.text()))

    def text10_changed(self):
        if self.textbox10.text() is "":
            self.glaph.replot_delay(float(self.glaph.tmp_delay))
        else:
            self.glaph.replot_delay(float(self.textbox10.text()))

    def slider1_changed(self):
        self.s1palm = round((self.slider1.value()/self.slider_max) *
                             (self.a_max-self.a_min)+self.a_min, 3)
        self.textbox1.setText(str(self.s1palm))

    def slider2_changed(self):
        self.s2palm = str((self.slider2.value()/self.slider_max) *
                          (self.b_max-self.b_min)+self.b_min)
        self.textbox2.setText(self.s2palm)

    def slider3_changed(self):
        self.s3palm = str((self.slider3.value()/self.slider_max) *
                          (self.c_max-self.c_min)+self.c_min)
        self.textbox3.setText(self.s3palm)

    def slider4_changed(self):
        self.s4palm = str((self.slider4.value()/self.slider_max) *
                          (self.d_max-self.d_min)+self.d_min)
        self.textbox4.setText(self.s4palm)

    def slider5_changed(self):
        self.s5palm = str((self.slider5.value()/self.slider_max) *
                          (self.r_max-self.r_min)+self.r_min)
        self.textbox5.setText(self.s5palm)

    def slider6_changed(self):
        self.s6palm = str((self.slider6.value()/self.slider_max) *
                          (self.s_max-self.s_min)+self.s_min)
        self.textbox6.setText(self.s6palm)

    def slider7_changed(self):
        self.s7palm = str((self.slider7.value()/self.slider_max) *
                          (self.xr_max-self.xr_min)+self.xr_min)
        self.textbox7.setText(self.s7palm)

    def slider8_changed(self):
        self.s8palm = str((self.slider8.value()/self.slider_max) *
                          (self.i_max-self.i_min)+self.i_min)
        self.textbox8.setText(self.s8palm)

    def slider9_changed(self):
        self.s9palm = str((self.slider9.value()/self.slider_max) *
                          (self.gcmp_max-self.gcmp_min)+self.gcmp_min)
        self.textbox9.setText(self.s9palm)

    def slider10_changed(self):
        self.s10palm = str((self.slider10.value()/self.slider_max) *
                           (self.delay_max-self.delay_min)+self.delay_min)
        self.textbox10.setText(self.s10palm)

class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()
        self.left = 100
        self.top = 100
        self.title = 'Hindmarsh-Rose model - simulater'
        self.width = 1280
        self.height = 1024
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.setCentralWidget(CentralWidget(self))

class PlotCanvas(FigureCanvas):

    def __init__(self, parent=None, width=10, height=8, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                                   QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)
        self.plot_init()

    def plot_init(self):
        self.dt = 0.05
        self.t = np.arange(0, 10000, self.dt)
        self.steps = len(self.t)
        self.x = -1.6 * np.ones(self.steps)
        self.y = 0 * np.ones(self.steps)
        self.z = 0 * np.ones(self.steps)
        self.m = 0 * np.ones(self.steps)
        self.h = 0 * np.ones(self.steps)
        self.ica = 0 * np.ones(self.steps)

        self.a = 1
        self.b = 3.3
        self.c = 1
        self.d = 5
        self.r = 0.01
        self.s = 4
        self.i = 0
        self.xr = -2.5
        self.gcmp = 0
        self.delay = 0

        self.ax = self.figure.add_subplot(211)
        self.ax.set_title('N0')
        plt.title('Hindmarsh-Rose model')
        self.ax2 = self.figure.add_subplot(212)

        self.tmp_a = self.a
        self.tmp_b = self.b
        self.tmp_c = self.c
        self.tmp_d = self.d
        self.tmp_r = self.r
        self.tmp_s = self.s
        self.tmp_xr = self.xr
        self.tmp_i = self.i
        self.tmp_gcmp = self.gcmp
        self.tmp_delay = self.delay

        self.plot(self.a, self.b, self.c, self.d, self.r, self.s, self.xr,
                  self.i, self.gcmp, self.delay)

    def replot_a(self, a):
        self.line.remove()
        self.line2.remove()
        self.tmp_a = a
        self.plot(self.tmp_a, self.b, self.c, self.d, self.r, self.s, self.xr,
                  self.i, self.gcmp, self.delay)

    def replot_b(self, b):
        self.line.remove()
        self.line2.remove()
        self.tmp_b = b
        self.plot(self.a, self.tmp_b, self.c, self.d, self.r, self.s, self.xr,
                  self.i, self.gcmp, self.delay)

    def replot_c(self, c):
        self.line.remove()
        self.line2.remove()
        self.tmp_c = c
        self.plot(self.a, self.b, self.tmp_c, self.d, self.r, self.s, self.xr,
                  self.i, self.gcmp, self.delay)

    def replot_d(self, d):
        self.line.remove()
        self.line2.remove()
        self.tmp_d = d
        self.plot(self.a, self.b, self.c, self.tmp_d, self.r, self.s, self.xr,
                  self.i, self.gcmp, self.delay)

    def replot_r(self, r):
        self.line.remove()
        self.line2.remove()

        self.tmp_r = r
        self.plot(self.a, self.b, self.c, self.d, self.tmp_r, self.s, self.xr,
                  self.i, self.gcmp, self.delay)

    def replot_s(self, s):
        self.line.remove()
        self.line2.remove()

        self.tmp_s = s
        self.plot(self.a, self.b, self.c, self.d, self.r, self.tmp_s, self.xr,
                  self.i, self.gcmp, self.delay)

    def replot_xr(self, xr):
        self.line.remove()
        self.line2.remove()

        self.tmp_xr = xr
        self.plot(self.a, self.b, self.c, self.d, self.r, self.s, self.tmp_xr,
                  self.i, self.gcmp, self.delay)

    def replot_i(self, i):
        self.line.remove()
        self.line2.remove()

        self.tmp_i = i
        self.plot(self.a, self.b, self.c, self.d, self.r, self.s, self.xr,
                  self.tmp_i, self.gcmp, self.delay)

    def replot_gcmp(self, gcmp):
        self.line.remove()
        self.line2.remove()

        self.tmp_gcmp = gcmp
        self.plot(self.a, self.b, self.c, self.d, self.r, self.s, self.xr,
                  self.i, self.tmp_gcmp, self.delay)

    def replot_delay(self, delay):
        self.line.remove()
        self.line2.remove()

        self.tmp_delay = delay
        self.plot(self.a, self.b, self.c, self.d, self.r, self.s, self.xr,
                  self.i, self.gcmp, self.tmp_delay)

    def plot(self, a, b, c, d, r, s, xr, i, gcmp, delay):
        self.a = a
        self.b = b
        self.c = c
        self.d = d
        self.r = r
        self.s = s
        self.xr = xr
        self.i = i
        self.gcmp = gcmp
        self.delay = delay
        self.n = 0
        self.iext = np.zeros(self.steps)
        for j in range(int(500/self.dt), int(2000/self.dt)):
            self.iext[j] = i

        for i in range(0, self.steps-1):
            """
            if self.x[i] > self.delay:
                self.k1x = (self.y[i] - self.a * self.x[i]**3 + self.b * self.x[i]**2 -
                        self.z[i] + self.i + self.n + 10)
                print("kashikoma")
            else:
                self.k1x = (self.y[i] - self.a * self.x[i]**3 + self.b * self.x[i]**2 -
                            self.z[i] + self.i + self.n)
            """
            self.ica[i] = (self.m[i]**2)*self.h[i]
            self.k1x = (self.y[i] - self.a * self.x[i]**3 + self.b * self.x[i]**2 -
                        self.z[i] + self.iext[i] + self.gcmp * self.ica[i] +
                        self.n)

            self.k1y = (self.c - self.d * self.x[i]**2 - self.y[i])
            self.k1z = (self.r * (self.s * (self.x[i] - self.xr) - self.z[i]))

            self.m_inf = 1/(1 + np.exp(-(self.x[i]+1.5)/0.25))
            self.h_inf = 1/(1 + np.exp(-(self.x[i]+2.3)/0.17))
            self.t_m = 0.612 + (1/(np.exp(-(self.x[i]+4)/0.5)+np.exp((self.x[i]+0.42)/0.5)))*20
            if self.x[i] > -2.1:
                self.t_h = 28 + (np.exp(-(self.x[i]+0.6)/0.26))*20
            else:
                self.t_h = (np.exp((self.x[i]+15)/2.2))*20

            self.dm = -1*(self.m[i] -self.m_inf)/self.t_m
            self.dh = -1*(self.h[i] -self.h_inf)/self.t_h
            self.dn = -0.5*self.n +np.random.randn() *self.delay

            self.x[i+1] = self.x[i] + self.k1x * self.dt
            self.y[i+1] = self.y[i] + self.k1y * self.dt
            self.z[i+1] = self.z[i] + self.k1z * self.dt
            self.m[i+1] = self.m[i] + self.dm * self.dt
            self.h[i+1] = self.h[i] + self.dh * self.dt
            self.n += (self.dn * self.dt)

        self.line, = self.ax.plot(self.t, self.x)
        self.line2, = self.ax2.plot(self.t, self.ica)

        self.draw()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mw = MainWindow()
    mw.show()
    sys.exit(app.exec_())


# By Websten from forums
#
# Given your birthday and the current date, calculate your age in days.
# Account for leap days.
#
# Assume that the birthday and current date are correct dates (and no
# time travel).

def isLeap(year):
    if year % 4 != 0:
        return False
    elif year % 100 != 0:
        return True
    elif year % 400 != 0:
        return False
    else:
        return True

def daysBetweenDates(year1, month1, day1, year2, month2, day2):
    daysinMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

    days, leap = 0, 0

    print (days)
    # calculate leap days

    if year1 == year2:
        if ((month1 == 2 and day1 == 29) or (month2 == 2 and day2 == 29)):
            if isLeap(year1) is True:
                leap = 1
        elif (month1 < 3 and month2 > 2):
            if isLeap(year1) is True:
                leap = 1
    else:
        for i in range (year1, year2 + 1):
            print (i)
            if (i == year2 and year2 > year1):
                if month2 > 2:
                    if isLeap(year2) is True:
                        leap = leap + 1
            elif i == year1:
                if month1 < 3:
                    if isLeap(year1) is True:
                        leap = leap + 1
            elif isLeap(i) is True:
                leap = leap + 1

    print ("days=", days)
    print ("leap=", leap)
    print ("sum(daysinMonth[month1:month2])=", sum(daysinMonth[month1:month2]))
    print ("(daysinMonth[month1]-day1)=", (daysinMonth[month1]-day1))
    print ("sum(daysinMonth[:month2])=", sum(daysinMonth[:month2-1]))
    print ("month2=",month2)

    if year2 < year1:
        print("Date 2 cannot be earlier than Date 1")
    elif year1 == year2:        # start and end same year
        days = leap + sum(daysinMonth[month1+1:month2]) + (daysinMonth[month1]-day1) + day2
    elif year1 == year2 - 1:    # start and end in consecutive years
        days = leap + sum(daysinMonth[month1+1:]) + (daysinMonth[month1]-day1) + sum(daysinMonth[:month2]) + day2
    else:                       # start and end with full years between
        days = leap + (365 * (year2 - year1 - 1)) + sum(daysinMonth[month1+1:]) + (daysinMonth[month1]-day1) + sum(daysinMonth[:month2]) + day2

    print("total=",days)

    print("Between ", month1, "/", day1, "/", year1, " and ", month2, "/", day2, "/", year2, " there are ", days,
          " days.")

    return days

# #Test routine: leapyear
#
# def test():
#     test_cases = [(2000, True),
#                   (2001, False)]
#     for (args, answer) in test_cases:
#         result = isLeap(args)
#         if result != answer:
#             print("Test with data:", args, "failed")
#         else:
#             print("Test case passed!")
#
# test()

# Test routine: days between dates

def test():
    test_cases = [((2012,1,1,2012,2,28), 58),
                  ((2012,1,1,2012,3,1), 60),
                  ((2011,6,30,2012,6,30), 366),
                  ((2011,1,1,2012,8,8), 585 ),
                  ((1900,1,1,1999,12,31), 36523)]
    for (args, answer) in test_cases:
        result = daysBetweenDates(*args)
        if result != answer:
            print("Test with data:", args, "failed")
        else:
            print("Test case passed!")

test()


import os
# os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras import layers
import torch
from torch import nn
import onnx
from onnx2keras import onnx_to_keras
import numpy as np
import tensorflow_addons as tfa
import time
from PIL import Image
import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
from natsort import natsorted

randin = torch.randn(1, 3, 256, 256)
randin_numpy = randin.numpy()
randin_numpy = randin_numpy.transpose(0, 2, 3, 1)
print(randin_numpy.shape)

class ReflectPad(tf.keras.layers.Layer):
    def __init__(self, pads, test_c_order = False):
        super(ReflectPad, self).__init__()
        self.pads = pads
        if test_c_order == False:
            self.op = [[0, 0], [0, 0], [pads[2], pads[6]], [pads[3], pads[7]]]
        else:
            self.op = [[0, 0], [pads[2], pads[6]], [pads[3], pads[7]], [0, 0]]

    def call(self, inputs):
        x = tf.pad(inputs, self.op, 'REFLECT')
        return x

    def get_config(self):
        config = super().get_config().copy()
        config.update({
            'pads': self.pads
        })
        return config

class SimpleModel(nn.Module):
    def __init__(self):
        super(SimpleModel, self).__init__()
        self.t0 = torch.nn.ReflectionPad2d((3,3,3,3))
        self.t1 = nn.Conv2d(3, 16, kernel_size=(7, 7), stride=(1, 1))
        self.t2 = nn.InstanceNorm2d(16, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)
        self.t3 = nn.ReLU(inplace=True)
        self.t4 = nn.Conv2d(16, 64, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))
        self.t5 = nn.InstanceNorm2d(32, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)
        self.t6 = nn.ReLU(inplace=True)
        self.t7 = nn.Conv2d(64, 64, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))
        self.t8 = nn.InstanceNorm2d(32, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)
        self.t9 = nn.ReLU(inplace=True)
        self.t10 = torch.nn.ReflectionPad2d((1,1,1,1))
        self.t11 = nn.Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(0, 0), groups=64)
        self.t12 = nn.InstanceNorm2d(64, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)
        self.t13 = nn.ConvTranspose2d(64, 32, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), output_padding = (1, 1))
        self.t14 = nn.InstanceNorm2d(32, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)
        self.t15 = nn.ReLU(inplace=True)
        self.t16 = nn.ConvTranspose2d(32, 16, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), output_padding = (1, 1))
        self.t17 = nn.InstanceNorm2d(16, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)
        self.t18= nn.ReLU(inplace=True)
        self.t19 = torch.nn.ReflectionPad2d((3,3,3,3))
        self.t20 = nn.Conv2d(16, 3, kernel_size=(7, 7), stride=(1, 1), padding=(0, 0))

    def forward(self, input):
        x = self.t0(input)
        x = self.t1(x)
        x = self.t2(x)
        x = self.t3(x)
        x = self.t4(x)
        x = self.t5(x)
        x = self.t6(x)
        x = self.t7(x)
        x = self.t8(x)
        x_add = self.t9(x)
        x = self.t10(x_add)
        x = self.t11(x)
        x = self.t12(x)
        x = x + x_add
        x = self.t13(x)
        return x

def get_torch():
    x = SimpleModel().cuda()
    x.eval()
    return x

def get_onnx(torch_model):
    input_name = ["input"]
    output_name = ["output"]
    torch.onnx.export(torch_model, randin.cuda(), "test_convert.onnx", verbose = True, input_names = input_name, output_names = output_name)

def get_keras(dynamic_input = False):
    onnx_model = onnx.load("/home/fico/DeepL/Gans/Mobile_Cyclegan/vangogh2photo_fixed.onnx")
    # Call the converter (input - is the main model input name, can be different for your model)
    k_model = onnx_to_keras(onnx_model, ['input'], test_c_order = True, dynamic_input = dynamic_input)

    # if dynamic_input == True:
    #     model_config = k_model.get_config()
    #     print(model_config['layers'][0])

    print(k_model.summary())

    return k_model

def get_keras_model_weights():
    model = Sequential()
    model.add(tf.keras.Input(shape=(256, 256, 3), batch_size = 1))
    model.add(ReflectPad([0, 0, 3, 3, 0, 0, 3, 3], test_c_order = True))
    model.add(layers.Conv2D(16, (7, 7), strides = (1,1)))
    model.add(tfa.layers.InstanceNormalization(axis=3,
                                            epsilon=.00009,
                                            center=False,
                                            scale=False))
    for layer in model.layers:
        if "conv" in layer.get_config()["name"]:
            print(layer.get_config()["name"], np.shape(layer.get_weights()[0]))
            return model

def data_loader():
    total_imgs = natsorted(os.listdir("/media/fico/Data/Kaggle/monet2photo/testB"))
    trans = transforms.Compose([
                               transforms.Resize(256, 256),
                               transforms.ToTensor(),
                               transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),])
    count = 0
    for x in total_imgs:
        print(count)
        count += 1
        img_loc = os.path.join("/media/fico/Data/Kaggle/monet2photo/testB", x)
        image = Image.open(img_loc).convert("RGB")
        tensor_image = trans(image)
        image = tensor_image.numpy()
        image = np.expand_dims(image, axis=0)
        image = image.transpose(0,2,3,1)
        yield [image]
        if count == 10:
            break

    # for x, y in enumerate(data_load):
    #     y = y.numpy()
    #     y = y.transpose(0,2,3, 1)
    #     yield [y]

def tflite_conversion(keras_model):
    try:
        converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
        converter.experimental_new_converter = True

        converter.optimizations = [tf.lite.Optimize.DEFAULT]
        # converter.target_spec.supported_types = [tf.float16]
        # converter.optimizations = [tf.lite.Optimize.DEFAULT]
        # converter.representative_dataset = data_loader

        tflite_model = converter.convert()
    except:
        print("Dead")

    # Save the model.
    with open('vangogh_float32.tflite', 'wb') as f:
      f.write(tflite_model)

def test_tflite():
    interpreter = tf.lite.Interpreter(model_path="test_convert.tflite", num_threads = 4)
    input_details = interpreter.get_input_details()
    interpreter.resize_tensor_input(input_details[0]['index'], (1, 300, 300, 3))
    interpreter.allocate_tensors()

    input_details = interpreter.get_input_details()
    output_details = interpreter.get_output_details()

    # Test the model on random input data.
    im = Image.open("/media/fico/Data/Kaggle/k.jpg")
    im = transforms.Resize((300, 300))(im)
    # im = transforms.RandomCrop(256)(im)
    im.show()

    im = np.array(im, dtype = np.float32)
    im = im.transpose(2,0,1)
    im = (im  - 127.5) / 127.5
    im = np.expand_dims(im, axis=0)
    im = im.transpose(0, 2, 3, 1)
    input_shape = input_details[0]['shape']

    interpreter.set_tensor(input_details[0]['index'], im)
    start = time.time()
    interpreter.invoke()
    print(time.time()-start)
    interpreter.set_tensor(input_details[0]['index'], im)
    start = time.time()
    interpreter.invoke()
    print(time.time()-start)

    # The function `get_tensor()` returns a copy of the tensor data.
    # Use `tensor()` in order to get a pointer to the tensor.
    output_data = interpreter.get_tensor(output_details[0]['index'])
    print(output_data.shape)
    # x = output_data.numpy()
    x = output_data.transpose(0,3,1,2)

    x = torch.from_numpy(x)

    # x = x.cpu()
    old_min = -1
    old_max = 1
    old_range = old_max - old_min
    new_range = 1 - 0
    x = (((x - old_min)*new_range)/ old_range) + 0
    # x = x.permute(0,2,3,1)
    x = x.squeeze()
    im = transforms.ToPILImage()(x)
    print(im.size)
    im.show()

def main():
    # torch_model = get_torch()
    # get_onnx(torch_model)

    keras_model = get_keras(dynamic_input = True)
#
    # torch_out = torch_model(randin.cuda())
    # torch_out = torch_out.cpu().detach().numpy()
    # keras_out = keras_model(randin_numpy)
    # torch_out = torch_out.transpose(0, 2, 3, 1)
    # print(np.max(torch_out - keras_out))

    # keras_premade = get_keras_model_weights()

    tflite_conversion(keras_model)
    test_tflite()
    # data_loader()

if __name__ == "__main__":
    main()


#
# Copyright (C) 2015 ETH Zurich and University of Bologna
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the BSD license.  See the LICENSE file for details.
#
# Authors: Germain Haugou (germain.haugou@gmail.com)
#

import configs.pulp.PulpConfigCommon as pulpConfig

class FulmineConfig(pulpConfig.Config):

  versions = {
    'apb_soc'    : 1,
    'mchan'      : 5,
    'udma'       : 1,
    'eventUnit'  : 1,
    'or1k'       : 5,
    'soc'        : 4,
    'hwce'       : 3,
    'icache_ctrl': 1,
  }

  imaps = {
    'udma0'   : 10,
    'udma1'   : 11,
    'udma2'   : 12,
    'udma3'   : 13,
    'udma4'   : 14,
    'udma5'   : 15,
    'udma6'   : 16,
    'udma7'   : 17,
  }

  properties = {
    'hasUart'       : 1
  }

  nbCluster = 1

  soc_peripherals_base = 0x1A100000

  soc_apb_base = soc_peripherals_base + 0x3000

  def __init__(self, decorators):
    super(FulmineConfig, self).__init__(decorators=decorators)

    self.soc = pulpConfig.Soc_v4(self)

    self.clusters = []

    for cid in range(0, self.nbCluster):
      cluster = pulpConfig.Cluster_v4(self)
      self.clusters.append(cluster)


from lab4_ import db

student = db['student']
teacher = db['teacher']
course = db['course']

print('向学生表中插入一条数据：')
s_d = {
    'info:SID': '201600301111',
    'info:NAME': '张三',
    'info:SEX': '男',
    'info:CLASS': '2016'
}
student.put(s_d['info:SID'], s_d)
print('学生表数据插入成功')

print('向课程表中插入一条数据：')
c_d = {
    'info:CID': '666666',
    'info:NAME': '中学物理'
}
course.put(c_d['info:CID'], c_d)
print('课程表数据插入成功')

print('向教师表中插入多条数据：')
t_d = [
    {
        'info:TID': '666666',
        'info:NAME': '张三',
        'info:DNAME': '软件学院'
    },
    {
        'info:TID': '777777',
        'info:AGE': '54',
        'info:NAME': '李四'
    }
]
for one in t_d:
    teacher.put(one['info:TID'], one)
print('教师表数据插入成功')


from vgg16_spectral_channel import VGG16
from keras.applications.inception_v3 import InceptionV3
from keras.preprocessing.image import load_img,img_to_array,array_to_img
from keras.applications.resnet50 import preprocess_input, decode_predictions
from keras import backend as K
import tensorflow as tf
import numpy as np
import scipy

def deprocess_image(x):
    # Util function to convert a tensor into a valid image.
    # if K.image_data_format() == 'channels_first':
    #     print('channels first')
    x = x.reshape((3, x.shape[2], x.shape[3]))
    x = x.transpose((1, 2, 0))
    x = x[:, :, ::-1]
    # else:
    #     #print('channels last')
    #     x = x[:, :, :, ::-1]
    #     x = x.reshape((x.shape[1], x.shape[2], 3))
    print('shape',np.shape(x))
    x[:, :, 0] += 123.68
    x[:, :, 1] += 116.779
    x[:, :, 2] += 103.939
    print(np.max(x))
    print(np.min(x))

    x = np.clip(x, 0, 255).astype('uint8')
    return x

def gradient_descent(x, iterations, step, min_loss=None):
    for i in range(iterations):
        outs = fetch_loss_and_grads([x])
        loss_value, grad_values=outs[0],outs[1]
        if min_loss is not None and loss_value >= min_loss:
            return x,i
            break
        print('..Loss value at', i, ':', loss_value)
        # print('grad')
        # print(grad_values)
        x += step * grad_values

    return x,iterations

def save_img(img, fname):
    pil_img = deprocess_image(np.copy(img))
    scipy.misc.imsave(fname, pil_img)

# img_path = 'dataset/img/'
# origin = load_img(img_path, target_size=(224, 224))
# a=img_to_array(origin)
# #b=array_to_img(a)
# #scipy.misc.imsave('result/origin.jpeg',b)
#
# a[:, :, 0] -= 123.68
# a[:, :, 1] -= 116.779
# a[:, :, 2] -= 103.939
#
# a=a[:,:,::-1]
# a=np.expand_dims(a,axis=0)

# f_origin = np.fft.fft2(a)

step=1e-2
iterations=1000
min_loss=0.99
model = VGG16(weights='imagenet',include_top=True)

Input=model.input
preds=model.output
for i in range(14,1000):
    print('img:--- ',i)
    img_path = '../../dataset/image/' + str(i) + '.png'
    origin = load_img(img_path, target_size=(224, 224))
    a = img_to_array(origin)
    # b=array_to_img(a)
    # scipy.misc.imsave('result/origin.jpeg',b)

    a[:, :, 0] -= 123.68
    a[:, :, 1] -= 116.779
    a[:, :, 2] -= 103.939

    a = a[:, :, ::-1]
    a = np.expand_dims(a, axis=0)
    a=a.transpose(0,3,1,2)
    print('shape',np.shape(a))
    f_origin = np.fft.fft2(a)
    # for j in range(1000):
    f=f_origin.copy()
    j=0
    loss=preds[0][j]
    grads=K.gradients(loss,Input)[0]
    grads/=K.mean(grads)
    outputs=[loss,grads]
    fetch_loss_and_grads = K.function([Input], outputs)
    f,nums = gradient_descent(f,iterations=iterations,step=step,min_loss=min_loss)
    if nums<iterations:
        img=np.real(np.fft.ifft2(f))
        print('class: ',j)
        save_img(img, fname='../../result/channel/'+str(i)+'.png')


# -*- coding: utf-8 -*-
"""tree edit distance and related structures"""

import collections

try:
    import numpy as np
    zeros = np.zeros
except ImportError:
    def py_zeros(dim, pytype):
        """2D int matrix, initialized at 0"""
        assert len(dim) == 2
        return [[pytype() for _ in range(dim[1])]
                for _ in range(dim[0])]
    zeros = py_zeros

class Node(object):
    """A simple node object that can be used to construct trees"""
    __slots__ = ["label", "parent", "children", "_id"]

    def __init__(self, parent, label=u"\u25A9"):
        if parent is not None:
            assert isinstance(parent, Node)
            parent.children.append(self)
        self.label = label
        self.children = list()
        self.parent = parent

    @staticmethod
    def get_children(node):
        """get the children list of the node"""
        return node.children

    @staticmethod
    def get_label(node):
        """get label of the node"""
        return node.label

    def __eq__(self, other):
        if other is not None:
            return False
        if not isinstance(other, Node):
            raise TypeError("Must compare against type Node")
        return self.label == other.label

    def __ne__(self, other):
        return not self.__eq__(other)

    def __repr__(self):
        return self.__str__()

    def __str__(self, prefix="", is_tail=True):
        """see http://stackoverflow.com/questions/4965335"""
        result = prefix + (
            "└── " if is_tail else "├── ") + str(self.label) + "\n"
        for index in range(0, len(self.children)-1):
            result += self.children[index].__str__(
                prefix + ("    " if is_tail else "│   "), False)
        if len(self.children) >= 1:
            result += self.children[-1].__str__(
                prefix + ("    " if is_tail else "│   "), True)
        return result

    def append(self, other_node):
        """add the other_node and the end of the node's children list"""
        assert isinstance(other_node, Node)
        self.children.append(other_node)

class AnnotatedTree(object):
    """Annotated tree used for tree edit distance calculation"""
    def __init__(self, root, get_children, size=0):
        self.get_children = get_children

        def setid(n, _id):
            setattr(n, "_id", _id)
            return n
        self.size = size

        self.root = root
        self.nodes = list()  # a pre-order enumeration of the nodes in the tree
        self.lmds = list()  # left most descendents
        self.keyroots = None
        # k and k' are nodes specified in the pre-order enumeration.
        # keyroots = {k | there exists no k'>k such that lmd(k) == lmd(k')}

        stack = list()
        pstack = list()
        stack.append((root, collections.deque()))
        j = 0
        while len(stack) > 0:
            n, anc = stack.pop()
            setid(n, j)
            for c in self.get_children(n):
                a = collections.deque(anc)
                a.appendleft(n._id)
                stack.append((c, a))
            pstack.append((n, anc))
            j += 1
        lmds = dict()
        keyroots = dict()
        i = 0
        while len(pstack) > 0:
            n, anc = pstack.pop()
            self.nodes.append(n)
            if not self.get_children(n):
                lmd = i
                for a in anc:
                    if a not in lmds:
                        lmds[a] = i
                    else:
                        break
            else:
                try:
                    lmd = lmds[n._id]
                except:
                    import pdb
                    pdb.set_trace()
            self.lmds.append(lmd)
            keyroots[lmd] = i
            i += 1
        self.keyroots = sorted(keyroots.values())

    def __str__(self):
        return self.root.__str__()

    def __repr__(self):
        return self.__str__()

    def __len__(self):
        """returns number of nodes in the tree (excluding the root)"""
        return self.size

def is_valid_dot_bracket(dot_bracket):
    """tests Vienna dot-bracket for illegal structure (or symbol)"""
    counter = 0
    for i in dot_bracket:
        if i == '(':
            counter += 1
        elif i == ')':
            counter -= 1
        elif i != '.':  # illegal symbol
            return False
        if counter < 0:  # unbalanced structure
            return False
    if counter != 0:
        return False  # unbalanced structure
    return True

def dot_bracket_to_tree(dot_bracket):
    """creates a base pair tree from the Vienna dot bracket"""
    assert is_valid_dot_bracket(dot_bracket), "invalid dot-bracket"
    root = Node(None)
    position = root
    size = 0
    for c in dot_bracket:
        if c == '(':
            child = Node(position)
            position = child
            size += 1
        elif c == ')':
            position = position.parent
        else:
            continue
    return AnnotatedTree(root, Node.get_children, size)

def treedist(i, j, A, B, Almds, Blmds, Anodes, Bnodes, treedists,
             max_sub_match, update,
             insert_cost=lambda x: 1, remove_cost=lambda x: 1):

    m = i - Almds[i] + 2
    n = j - Blmds[j] + 2
    fd = zeros((m, n), int)

    ioff = Almds[i] - 1
    joff = Blmds[j] - 1

    for x in range(1, m):  # δ(l(i1)..i, θ) = δ(l(1i)..1-1, θ) + γ(v → λ)
        fd[x][0] = fd[x-1][0] + remove_cost(Anodes[x-1])
    for y in range(1, n):  # δ(θ, l(j1)..j) = δ(θ, l(j1)..j-1) + γ(λ → w)
        fd[0][y] = fd[0][y-1] + insert_cost(Bnodes[y-1])

    for x in range(1, m):  # the plus one is for the range impl
        for y in range(1, n):
            # check if x and y are ancestors of i and j
            if Almds[i] == Almds[x+ioff] and Blmds[j] == Blmds[y+joff]:
                # | δ(l(i1)..i-1, l(j1)..j) + γ(v → λ)
                # δ(F1, F2) = min-+ δ(l(i1)..i , l(j1)..j-1) + γ(λ → w)
                # | δ(l(i1)..i-1, l(j1)..j-1) + γ(v → w)
                fd[x][y] = min(
                    fd[x-1][y] + remove_cost(Anodes[x+ioff]),
                    fd[x][y-1] + insert_cost(Bnodes[y+joff]),
                    fd[x-1][y-1]  # no update cost
                )
                treedists[x+ioff][y+joff] = fd[x][y]
            else:
                # | δ(l(i1)..i-1, l(j1)..j) + γ(v → λ)
                # δ(F1, F2) = min-+ δ(l(i1)..i , l(j1)..j-1) + γ(λ → w)
                # | δ(l(i1)..l(i)-1, l(j1)..l(j)-1)
                # | + treedist(i1,j1)
                p = Almds[x+ioff]-1-ioff
                q = Blmds[y+joff]-1-joff
                fd[x][y] = min(
                    fd[x-1][y] + remove_cost(Anodes[x+ioff]),
                    fd[x][y-1] + insert_cost(Bnodes[y+joff]),
                    fd[p][q] + treedists[x+ioff][y+joff])
    if update:
       #  print("updating")
        max_sub_match[0] = min(max_sub_match[0], min(fd[-1]))
    # print("m = {0}, n = {1}, \n {2} \n".format(i, j, fd))

def unlabeled_distance(A, B):
    """Computes the unlabeled tree indel distance between trees A and B
    the computation for the maximum submatching tree is also performed"""
    assert(isinstance(A, AnnotatedTree))
    assert(isinstance(B, AnnotatedTree))
    if(len(A) < len(B)):  # symmetrize
        A, B = B, A
    treedists = zeros((len(A.nodes), len(B.nodes)), int)
    max_sub_match = [float('inf')]
    max_tree_left = len(A)
    Almds = A.lmds
    Blmds = B.lmds
    Anodes = A.nodes
    Bnodes = B.nodes
    # print(max_tree_left)
    for i in A.keyroots:
        for j in B.keyroots:
            if (i == max_tree_left):
                treedist(i, j, A, B, Almds, Blmds, Anodes, Bnodes, treedists, max_sub_match, True)
            else:
                treedist(i, j, A, B, Almds, Blmds, Anodes, Bnodes, treedists, max_sub_match, False)

    # print("\n" + str(treedists) + "\n")
    return (treedists[-1][-1])

__all__ = ['Node',
           'AnnotatedTree',
           'is_valid_dot_bracket',
           'dot_bracket_to_tree',
           'unlabeled_distance',
           'treedist']


'''
File                : proc.py

Start Date        : 20040522

Description        :
  This is an Eddie data collector.  It collects process information on
  an OpenBSD system.

  The following statistics are currently collected and made available to
  directives that request it (e.g., PROC):

  TODO...

$Id: proc.py 895 2007-12-09 07:18:02Z chris $
'''

__version__ = '$Revision: 895 $'

__copyright__ = 'Copyright (c) Chris Miles 2004-2005'

__author__ = 'Chris Miles; John McInnes'

__license__ = '''
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
'''

# Python modules
import string

# Eddie modules
from eddietool.common import datacollect, log, utils

# List of interpreters - default empty
interpreters = []

class procList(datacollect.DataCollect):
    """Class procList, holds a list of running processes and related information.
    """

    def __init__(self):
        apply( datacollect.DataCollect.__init__, (self,) )

    ##################################################################
    # Public, thread-safe, methods

    def procExists(self, procname):
        """Search the process list and return the number of occurrences
        of procname.
        """

        proclist = self.getList( 'proclist' )   # safely get copy of process list

        count = 0               # count number of occurrences of 'procname'
        for i in proclist:
            command = string.split(i.comm, '/')[-1]
            if command == procname or i.procname == procname:
                count = count + 1

        return count

    def pidExists(self, pid):
        """Return true (1) if a process with 'pid' exists,
        or false (0) otherwise.
        """

        prochash = self.getHash( 'datahash' )   # safely get copy of process dict

        try:
            prochash[pid]
            return 1
        except KeyError:
            return 0

    def __getitem__(self, name):
        """Overload '[]' to return corresponding process object for given
        process name.
        """

        processes = self.getHash( 'nameHash' )  # safely get copy of process name dictionary

        try:
            r = processes[name]
        except KeyError:
            r = None            # no such process called 'name'

        return r

    def allprocs(self):
        """Return dictionary of all processes (which are dictionaries of each
        process' details).
        """

        processes = self.getHash( 'nameHash' )  # safely get copy of process name dictionary

        allprocs = {}

        for p in processes.keys():
            allprocs[p] = processes[p].procinfo()

        return allprocs

    ##################################################################
    # Private methods.  No thread safety if not using public methods.

    def collectData(self):
        """Collect process list.
        """

        self.data.datahash = {}                # dict of processes keyed by pid
        self.data.proclist = []                # list of processes
        self.data.nameHash = {}                # dict of processes keyed by process name

        # gather data from "ps"
        rawList = utils.safe_popen('ps -o ppid,nice,ruid,rgid,gid -auxww', 'r')
        rawList.readline()                # skip header

        for line in rawList.readlines():
            p = proc(line)
            self.data.proclist.append(p)
            self.data.datahash[p.pid] = p
            self.data.nameHash[p.procname] = p

        utils.safe_pclose( rawList )

        log.log( "<proc>procList.collectData(): new proc list created", 7 )

class proc:
    """Class proc : holds information about a single process.
    """

    def __init__(self, rawline):

        fields = string.split(rawline)

        # fields as defined from "ps -o ppid,nice,ruid,rgid,gid -auxww"
        self.ppid =        int(fields[ 0])        # parent process id
        self.nice =        fields[ 1]        # nice value
        self.ruid =        fields[ 2]        # real user id
        self.rgid =        fields[ 3]        # real group id
        self.gid =        fields[ 4]        # group id
        self.uid =        fields[ 5]        # username or uid
        self.pid =        int(fields[ 6])        # pid
        self.pcpu =        float(fields[ 7])        # cpu
        self.pmem =        float(fields[ 8])        # mem
        self.sz =        int(fields[ 9])        # size
        self.rsz =        int(fields[10])        # resident size
        self.tty =        fields[11]        # terminal
        self.s =        fields[12]        # state
        self.stime =        fields[13]        # start time
        self.time =        fields[14]        # cpu time
        self.comdname =        fields[15]        # process name (no arguments)
        self.comm =        fields[15]        # process name (no arguments)
        self.comd =        string.join(fields[16:], " ")        # command with all its arguments as a string
        lastfield = 15

        # Actual 'command' name with no path or interpreter - Eddie will mainly use this
        self.procname = string.split(self.comdname, '/')[-1]
        if self.procname in interpreters:
            # this command is an interpreter (eg: 'perl', 'python', etc)
            # let's set procname to the name of the script (if there is a script)
            if len(fields) > lastfield + 1:
                i = lastfield + 1
                self.procname = string.split(fields[i], '/')[-1]
                # ignore arguments (strings starting with '-')
                try:
                    while self.procname[0] == '-':
                        i = i + 1
                        self.procname = string.split(fields[i], '/')[-1]
                except IndexError:
                    # can't determine procname.....
                    self.procname = ''

    def timeconv(self,str):
        """Convert something vaguely in the format [dd-]hh:mm:ss.ms into
        something usable - ie pure seconds.
        """

        s=0
        t=string.split(str,"-")
        if len(t)>1:
            s=s+86400*int(t[0])
            str=t[1]
        else:
            str=t[0]
        t=string.split(str,":")
        s=s+float(t[-1])
        s=s+60*int(t[-2])
        if len(t)==3:
            s=s+3600*int(t[0])
            return s

    def __str__(self):
        # display process details (OLD, doesn't show many details)
        c = string.ljust(self.procname, 20)
        u = string.ljust(self.comm, 20)
        t = string.ljust(self.time, 10)

        return( '%s\t%s\t%s\t%s\t%s\t%s' % (self.pid, u, c, t, self.pcpu, self.s) )

    def procinfo(self):
        """Return process details as a dictionary.
        """

        info = {}
        for k in ('ppid', 'nice', 'ruid', 'rgid', 'uid', 'pid', 'gid', 'pcpu', 'pmem', 'sz', 'vsz:sz', 'rsz', 'rss:rsz', 'tty', 's', 'stime', 'time', 'comdname', 'comd', 'comm:comd', 'procname'):
            ks = k.split(':', 2)
            ks.append(ks[0])
            info[ks[0]] = eval("self.%s" % (ks[1]))

        return info

##
## END - proc.py
##


class file():
    # print the decode text in the file(message.txt)
    @staticmethod
    def outputinfile(message):
        f=open("D:\Python project\encryption-app-using-python-master/message.txt",'w')
        f.write(message)
        f.close()
    # take input from the file for preview
    @staticmethod
    def datafromfile(choice=1):
        if choice==2:
            address="D:\Python project\encryption-app-using-python-master/message.txt"
        elif choice==1:
            address="D:\Python project\encryption-app-using-python-master/cipher.txt"
        f=open(address,"r")
        chiper_text=f.readline().replace("\n","")
        f.close()
        return chiper_text
    #take input from file to decrypt
    @staticmethod
    def datafromfile2(address):
        f=open(address,"r")
        chiper_text=f.readline().replace("\n","")
        f.close()
        return chiper_text

     # display the encode text in file(chiper.txt)
    @staticmethod
    def displayfile(chiper):
        f=open("D:\Python project\encryption-app-using-python-master/cipher.txt",'w')
        f.write(chiper)
        f.close()

class raps_file(file):
    # display the encode text in file(chiper.txt)
    @staticmethod
    def displayfile(chiper,key_list,key_list2):
        f=open("D:\Python project\encryption-app-using-python-master/cipher.txt",'w')
        f.write(chiper+"\n")
        for i in range(len(key_list)):
            f.write(str(key_list[i])+"\t"+str(key_list2[i])+"\t")
        f.close()

    # take input from the file
    @staticmethod
    def datafromfile(address):
        key_list,key_list2=[],[]
        f=open(address,'r')
        chiper=f.readline().replace("\n","")
        keys=f.readline().split()
        for i in range(len(keys)):
            if i%2==0:
                key_list.append(int(keys[i]))
            else:
                key_list2.append(int(keys[i]))

        return chiper,key_list,key_list2

class playfair_file(file):
    pass

class caesar_file(file):
    pass


import ujson as json
from scrapper.file.utils import smart_open
from scrapper.commander import Commander

class Pluck(Commander):
    scriptname = 'js.pluck'

    @classmethod
    def setup_parser(cls, parser):
        parser.add_argument('input', nargs='?')
        parser.add_argument('--field', nargs='+', dest='fields')

    @classmethod
    def initialize(cls, opts):
        return cls(opts.input, opts.fields)

    def __init__(self, ifname, fields):
        self.ifname = ifname
        self.fields = fields

    def run(self):
        with smart_open(self.ifname) as f:
            for line in f:
                obj = json.loads(line)
                value = None
                for field in self.fields:
                    value = obj.get(field)
                    obj = value
                    if not value:
                        break
                if value:
                    print(json.dumps(value))


"""Defines URL patterns for vendordb."""

from django.urls import path

from . import views

app_name = 'vendordb'
urlpatterns = [
    # Home page
    path('', views.index, name='index'),

    # Page that shows all vendors
    path('vendors/', views.vendors, name='vendors'),

    # Detail page for a single vendor
    path('vendors/<int:vendor_id>/', views.vendor, name='vendor'),

    # Page for adding a new vendor
    path('new_vendor/', views.new_vendor, name='new_vendor'),
]


import torch
import numpy as np

class NSGP(torch.nn.Module):
    def __init__(self, X, y, num_inducing_points=5, X_bar=None,
                 jitter=10**-8, random_state=None, local_noise=True, local_std=True):
        super().__init__()

        assert len(
            X.shape) == 2, "X is expected to have shape (n, m) but has shape "+str(X.shape)
        assert len(
            y.shape) == 2, "y is expected to have shape (n, 1) but has shape "+str(y.shape)
        assert y.shape[1] == 1, "y is expected to have shape (n, 1) but has shape "+str(
            y.shape)

        self.X = X
        self.y = y
        self.X_bar = X_bar

        self.N = self.X.shape[0]
        self.input_dim = self.X.shape[1]

        self.num_inducing_points = self.X_bar.shape[0]
        self.jitter = jitter
        self.local_noise = local_noise
        self.local_std = local_std
        self.random_state = random_state

        # Local params
        self.local_gp_ls = self.param((self.input_dim,))
        self.local_gp_std = self.param((self.input_dim,))
        if not self.local_std:
            self.local_gp_std.requires_grad = False
        self.local_gp_noise_std = self.param((self.input_dim,))
        if not self.local_noise:
            self.local_gp_noise_std.requires_grad = False
        self.local_ls = self.param(
            (self.num_inducing_points, self.input_dim))

        # Global params
        self.global_gp_std = self.param((1,))
        self.global_gp_noise_std = self.param((1,))

        # Other params to be used
        # self.eye_num_inducing_points = torch.eye(self.num_inducing_points, dtype=self.X.dtype)
        # self.eye_N = torch.eye(self.N)
        self.pi = torch.tensor(np.pi)

        # Initialize model parameters
        self.initialize_params()

    def param(self, shape, requires_grad=True):
        return torch.nn.Parameter(torch.empty(shape, dtype=self.X.dtype), requires_grad=requires_grad)

    def initialize_params(self):
        if self.random_state == None:
            self.random_state = int(torch.rand(1)*1000)
        torch.manual_seed(self.random_state)
        for param in self.parameters():
            torch.nn.init.normal_(param, mean=0.0, std=1.0)

    def LocalKernel(self, x1, x2, dim):  # kernel of local gp (GP_l)
        dist = torch.square(x1 - x2.T)
        scaled_dist = dist/self.local_gp_ls[dim]**2

        return self.local_gp_std[dim]**2 * torch.exp(-0.5*scaled_dist)

    def get_LS(self, X):  # Infer lengthscales for train_X (self.X)
        l_list = []
        if self.training:
            B = []
        for dim in range(self.input_dim):
            k = self.LocalKernel(
                self.X_bar[:, dim, None], self.X_bar[:, dim, None], dim)

            # Diagonal Solution from https://stackoverflow.com/a/48170846/13330701
            dk = k.diagonal()
            dk += self.local_gp_noise_std[dim]**2
            c = torch.linalg.cholesky(k)
            alpha = torch.cholesky_solve(
                torch.log(torch.abs(self.local_ls[:, dim, None])), c)
            k_star = self.LocalKernel(
                X[:, dim, None], self.X_bar[:, dim, None], dim)
            l = torch.exp(k_star@alpha)
            l_list.append(l)

            if self.training:
                k_star = self.LocalKernel(
                    X[:, dim, None], self.X_bar[:, dim, None], dim)
                k_star_star = self.LocalKernel(
                    X[:, dim, None], X[:, dim, None], dim)

                chol = torch.linalg.cholesky(k)
                v = torch.cholesky_solve(k_star.T, chol)

                k_post = k_star_star - k_star@v
                dk_post = k_post.diagonal()
                dk_post += self.jitter
                post_chol = torch.linalg.cholesky(k_post)
                B.append(torch.log(post_chol.diagonal()))

        if self.training:
            return l_list, B
        else:
            return l_list

    def GlobalKernel(self, X1, X2):  # global GP (GP_y)
        if self.training:
            l, B = self.get_LS(X1)
            l = torch.cat(l, dim=1)
            l1 = l[:, None, :]
            l2 = l[None, :, :]
        else:
            l1 = torch.cat(self.get_LS(X1), dim=1)[:, None, :]
            l2 = torch.cat(self.get_LS(X2), dim=1)[None, :, :]

        lsq = torch.square(l1) + torch.square(l2)
        suffix = torch.sqrt(2 * l1 * l2 / lsq).prod(axis=2)
        dist = torch.square(X1[:, None, :] - X2[None, :, :])
        scaled_dist = dist/lsq
        K = self.global_gp_std**2 * \
            suffix * torch.exp(-scaled_dist.sum(dim=2))

        if self.training:
            return K, B
        else:
            return K

    def nlml(self):
        K, B = self.GlobalKernel(self.X, self.X)

        dK = K.diagonal()
        dK += self.global_gp_noise_std**2
        L = torch.linalg.cholesky(K)
        alpha = torch.cholesky_solve(self.y, L)
        A = 0.5*(self.y.T@alpha + torch.sum(torch.log(L.diagonal())) +
                 self.N * torch.log(2*self.pi))[0, 0]
        B = torch.sum(torch.cat(B)) + 0.5*(self.num_inducing_points *
                                           self.input_dim*torch.log(2*self.pi))
        return A+B

    def predict(self, X_new):  # Predict at new locations
        K = self.GlobalKernel(self.X, self.X)
        K_star = self.GlobalKernel(X_new, self.X)
        K_star_star = self.GlobalKernel(X_new, X_new)

        dK = K.diagonal()
        dK += self.global_gp_noise_std**2
        L = torch.linalg.cholesky(K)
        alpha = torch.cholesky_solve(self.y, L)

        pred_mean = K_star@alpha

        v = torch.cholesky_solve(K_star.T, L)
        pred_var = K_star_star - K_star@v

        dpred_var = pred_var.diagonal()
        dpred_var += self.global_gp_noise_std**2
        return pred_mean, pred_var


"""
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes.

Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.

If no such second minimum value exists, output -1 instead.

Example 1:
Input:
    2
   / \
  2   5
     / \
    5   7

Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.
Example 2:
Input:
    2
   / \
  2   2

Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.
"""

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

from itertools import chain

class Solution(object):
    def findSecondMinimumValue(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        # BFS
        if not root:
            return -1
        nodes = [root]
        val = root.val
        found_min = None
        while nodes:
            non_vals = [node.val for node in nodes if node.val != val]
            if non_vals:
                if found_min is None:
                    found_min = min(non_vals)
                else:
                    found_min = min(found_min, min(non_vals))
            nodes_nxt = list(chain.from_iterable((node.left, node.right) for node in nodes if node.left is not None))
            nodes = nodes_nxt
        if found_min is not None:
            return found_min
        else:
            return -1


#!/usr/bin/python3

import sys

temp_str = input("Enter Celsius temp: ")
c = float(temp_str)
f = ((9 * c) / 5 ) + 32

print("{0:.1f} C is {1:.1f} F".format(c,f))


from oauthlib import oauth2

from pulsar.apps.http import Auth

from .binder import API

__all__ = ['oauth2', 'OAuth2', 'OAuth2API']

class OAuth2(Auth):
    '''Construct a new OAuth 2 authorisation object.

        :param client_id: Client id obtained during registration
        :param client: :class:`oauthlib.oauth2.Client` to be used. Default is
                       WebApplicationClient which is useful for any
                       hosted application but not mobile or desktop.
        :param token: Token dictionary, must include access_token
                      and token_type.
    '''
    def __init__(self, client_id=None, client=None, **kwargs):
        self._client = client or oauth2.WebApplicationClient(client_id,
                                                             **kwargs)

    def __call__(self, response):
        request = response.request
        full_url = request.full_url
        url, headers, body = self._client.add_token(
            full_url,
            http_method=request.method,
            body=request.data,
            headers=request.headers)
        if url != full_url:
            request.full_url = url
        return response

class OAuth2API(API):
    WEB_AUTH_URL = None

    def setup(self, client_id=None, client_secret=None, client_scope=None,
              **params):
        self.client_id = client_id
        self.client_secret = client_secret
        self.client_scope = client_scope

    def web_oauth(self, request):
        '''Return the absolute uri for web authentication.

        Uses the :attr:`WEB_AUTH_URL` attribute as the base url.
        '''
        redirect_uri = self.build_uri(request.absolute_uri(), self.name,
                                      'callback')
        sessions = request.app.extensions['sessions']
        client = oauth2.WebApplicationClient(self.client_id)
        state = sessions.get_or_create_csrf_token(request)
        return client.prepare_request_uri(self.WEB_AUTH_URL,
                                          scope=self.client_scope,
                                          redirect_uri=redirect_uri,
                                          state=state)


import numpy

def qsort(li, first, length, count):

	if length - first < 2: return
	count[0] += length - first - 1 # counting comparisons

	pivot, l_len, r_len = li[length-1], 0, 0
	swap(li, first, length-1)

	i = first + 1
	while i < length:
		if   li[i] > pivot:
			r_len += 1
		elif li[i] < pivot:
			l_len += 1
			swap(li, i, first+l_len)

		i += 1

	swap(li, first, first+l_len) # placing pivot in its right place
	qsort(li, first, first+l_len, count)
	qsort(li, first+l_len+1, length, count)

def swap(li, a_i, b_i): li[a_i], li[b_i] = li[b_i], li[a_i]

# SOURCE_FILE = "tiny.txt"
SOURCE_FILE = "QuickSort.txt"

li = numpy.loadtxt(fname = SOURCE_FILE, dtype=int).tolist()
# li = [10,2,3,22,33,7,4,1,2]
# li = [2,3,1]

count = [0] # mutable reference

# print 'li: ', li
qsort(li, 0, len(li), count)
# print 'sorted: ', li
print('comparisons: ', count[0])


"""Humans class which represents those not infected."""

from random import randint
from Enums.SimulatorEntities import simulatorEntity
from Moveable import moveable

class human(moveable):
    """
    Humans.

    Will aimlessly wander around the area until:
    * If a zombie seen, will become paniced and run
    * If caught by a Zombie will fight and either kill or become infected
    * If infected will become a Zombie
    """

    moveableType = simulatorEntity.Human
    panicTimer = 0

    def look(self, area, direction):
        """Look some squares infront and react accordingly."""
        infront = area.checkWhatsInfront(self.xPos, self.yPos, direction, 5)

        if infront == simulatorEntity.Zombie:
            self.panicTimer = 20
            self.movementSpeed = self.baseMovementSpeed/4
        elif infront == simulatorEntity.PanicedHuman:
            self.panicTimer = 10
            self.movementSpeed = self.baseMovementSpeed/4

        if self.panicTimer > 0:
            self.panicTimer -= 1
            if self.panicTimer == 0:
                self.movementSpeed = self.baseMovementSpeed

        return

    def isPaniced(self):
        """Is this human paniced."""
        return self.movementSpeed != self.baseMovementSpeed

    def __init__(self, canvas, area):
        """Start-up."""
        super(moveable, self).__init__()
        super(human, self).__init__()

        self.canvas = canvas

        while True:
            xCoord = randint(0, 250)
            yCoord = randint(0, 250)
            if area.checkCoordinatesOnMap(xCoord, yCoord)\
                    == simulatorEntity.EmptySquare:
                self.xPos = xCoord
                self.yPos = yCoord
                area.humanPositions.add((self.xPos, self.yPos))
                break

        self.id = self.canvas.create_line(self.xPos,
                                          self.yPos,
                                          self.xPos + 1,
                                          self.yPos,
                                          fill="Green")


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

import pywikibot, re, sys, argparse

import blib
from blib import getparam, rmparam, msg, errandmsg, site, tname, pname

import lalib

pages_to_delete = []

def delete_term(index, term, expected_head_templates, save, verbose):
  notes = []

  def pagemsg(txt):
    msg("Page %s %s: %s" % (index, term, txt))
  page = pywikibot.Page(site, term)
  if not page.exists():
    pagemsg("Skipping form value %s, page doesn't exist" % term)
    return

  text = str(page.text)

  retval = lalib.find_latin_section(text, pagemsg)
  if retval is None:
    return

  sections, j, secbody, sectail, has_non_latin = retval

  subsections = re.split("(^==+[^=\n]+==+\n)", secbody, 0, re.M)
  saw_lemma_in_etym = False
  saw_wrong_lemma_in_etym = False
  saw_head = False
  infl_template = None
  saw_bad_template = False
  for k in range(2, len(subsections), 2):
    parsed = blib.parse_text(subsections[k])
    for t in parsed.filter_templates():
      tn = tname(t)
      if tn in expected_head_templates:
        saw_head = True
      elif tn in ["inflection of", "rfdef", "la-IPA"]:
        pass
      else:
        pagemsg("WARNING: Saw unrecognized template in subsection #%s %s: %s" % (
          k // 2, subsections[k - 1].strip(), str(t)))
        saw_bad_template = True

  delete = False
  if saw_head:
    if saw_bad_template:
      pagemsg("WARNING: Would delete but saw unrecognized template, not deleting")
    else:
      delete = True

  if not delete:
    return

  if "==Etymology" in sections[j]:
    pagemsg("WARNING: Found Etymology subsection, don't know how to handle")
    return
  if "==Pronunciation " in sections[j]:
    pagemsg("WARNING: Found Pronunciation N subsection, don't know how to handle")
    return

  #### Now, we can maybe delete the whole section or page

  if subsections[0].strip():
    pagemsg("WARNING: Whole Latin section deletable except that there's text above all subsections: <%s>" % subsections[0].strip())
    return
  if "[[Category:" in sectail:
    pagemsg("WARNING: Whole Latin section deletable except that there's a category at the end: <%s>" % sectail.strip())
    return
  if not has_non_latin:
    # Can delete the whole page, but check for non-blank section 0
    cleaned_sec0 = re.sub("^\{\{also\|.*?\}\}\n", "", sections[0])
    if cleaned_sec0.strip():
      pagemsg("WARNING: Whole page deletable except that there's text above all sections: <%s>" % cleaned_sec0.strip())
      return
    pagetitle = str(page.title())
    pagemsg("Page %s should be deleted" % pagetitle)
    pages_to_delete.append(pagetitle)
    return
  del sections[j]
  del sections[j-1]
  notes.append("removed Latin section for bad term")
  if j > len(sections):
    # We deleted the last section, remove the separator at the end of the
    # previous section.
    sections[-1] = re.sub(r"\n+--+\n*\Z", "", sections[-1])
  text = "".join(sections)

  return text, notes

parser = blib.create_argparser("Delete bad Latin terms", include_pagefile=True)
parser.add_argument('--headtemp', required=True, help="Name(s) of expected headword template(s).")
parser.add_argument('--output-pages-to-delete', help="File to write pages to delete.")
args = parser.parse_args()
start, end = blib.parse_start_end(args.start, args.end)

headtemp = blib.split_utf8_arg(args.headtemp)

def process_page(page, index, parsed):
  return delete_term(index, page, headtemp)

blib.do_pagefile_cats_refs(args, start, end, process_page, edit=True)

msg("The following pages need to be deleted:")
for page in pages_to_delete:
  msg(page)
if args.output_pages_to_delete:
  with open(args.output_pages_to_delete, "w", encoding="utf-8") as fp:
    for page in pages_to_delete:
      print(page, file=fp)


import json
from functools import wraps

from app import sio, redis, pubsub
from app.models import Player
from app.rules import * #NOQA

players = {}

def get_player(fn):
    @wraps(fn)
    def inner(*args, **kwargs):
        """ Replace first argument with a Player instance. """
        sid, data = args

        if sid in players:
            player = players[sid]
        else:
            player = Player(sid)
            players[sid] = player

        args = (player, data)

        return fn(*args, **kwargs)
    return inner

@sio.on('connect')
def connect(sid, environ):
    """ Add new clients to room 'clients'. """
    sio.enter_room(sid, 'clients')
    redis.publish('player:connect', json.dumps({'sid': sid}))

@sio.on('disconnect')
def disconnect(sid):
    """ Remove client from room 'clients' when he disconnects . """
    redis.publish('player:disconnect', json.dumps({'sid': sid}))
    sio.leave_room(sid, 'clients')

@sio.on('position')
def message(sid, data):
    """ Set player to given coordinates. """
    redis.publish('player:move', json.dumps({
        'sid': sid,
        'x': data['data']['long'],
        'y': data['data']['lat']
    }))

@sio.on('placeBomb')
def place_bomb(sid, data):
    """ Set bomb to given coordinates. """
    redis.publish('player:plant_bomb', json.dumps({
        'sid': sid,
        'x': data['data']['lat'],
        'y': data['data']['long']
    }))


import json
import logging
import os
import sys
import time

import click

from autoseq.pipeline.liqbio import LiqBioPipeline
from autoseq.util.clinseq_barcode import extract_clinseq_barcodes, convert_barcodes_to_sampledict, validate_clinseq_barcodes
from autoseq.util.path import mkdir
from autoseq.aws_utils.get_files import Awscli

@click.command()
@click.option('--step', required=True, help="Tool name to run the step")
#@click.argument('sample', type=click.File('r'))
@click.option('--sample', required=True, help="sample json file")
@click.pass_context
def liqbio(ctx, step, sample ):

    logging.info("Starting Liquid Biopsy pipeline")
    logging.info("Setting up required files for Liquid Biopsy pipeline")

    #get required files from s3 for this step to run
    aws_cli = ctx.obj['awscli']
    #get sample file from s3 and create directory if does not existsa
    logging.info("Copy the files required for liqbio  pipeline from s3")

    aws_cli.check_and_create_dir(os.path.dirname(sample))
    aws_cli.get_s3files(sample)
    aws_cli.set_fastq_files(sample)
    logging.info("Getting required files for current step {} from s3".format(step))
    aws_cli.get_files_for_current_step(step)

    print('done......')

    logging.info("Running Liquid Biopsy pipeline")
    logging.info("Sample is {}".format(sample))

    logging.debug("Reading sample config from {}".format(sample))
    sampledata = json.load(open(sample,'r'))

    if ctx.obj['jobdb']:
        mkdir(os.path.dirname(ctx.obj['jobdb']))

    ctx.obj['pipeline'] = LiqBioPipeline(sampledata=sampledata,
                                        refdata=ctx.obj['refdata'],
                                        job_params=ctx.obj['job_params'],
                                        outdir=ctx.obj['outdir'],
                                         libdir=ctx.obj['libdir'],
                                         maxcores=ctx.obj['cores'],
                                         runner=ctx.obj['runner'],
                                         jobdb=ctx.obj['jobdb'],
                                         dot_file=ctx.obj['dot_file'],
                                         umi=ctx.obj['umi'],
                                         scratch=ctx.obj['scratch'],
                                         )

    step_status = ctx.obj['pipeline'].runaws(step)
    if not step_status:
        logging.info("No Step configured with step name: " + step + ' check step_to_run dict to fix error')
        sys.exit(400)

    # start main analysis
    logging.info("Get All the inputs files required for pipeline to run.......")
    #print(  ctx.obj['pipeline'].get_outputs() )
    required_files = {}
    for j in ctx.obj['pipeline']._get_ordered_jobs():
        for varname in j.__dict__:
            obj = j.__dict__[varname]
            if varname.startswith('input'):
                print(obj)
                aws_cli.get_s3files(obj)

    #ctx.obj['pipeline'].check_sampledata()
    ctx.obj['pipeline'].start()
    logging.info("Waiting for pipeline to finish.")
    while ctx.obj['pipeline'].is_alive():
        logging.debug("Waiting for LiqBioPipeline")
        time.sleep(5)

    # return_code from run_pipeline() will be != 0 if the pipeline fails
    sys.exit(ctx.obj['pipeline'].exitcode)
    #sys.exit(ctx.obj['pipeline'].exitcode)

@click.command()
@click.option('--outdir', required=True, help="directory to write config files")
@click.argument('barcodes-filename', type=str)
@click.pass_context
def liqbio_prepare(ctx, outdir, barcodes_filename):
    logging.info("Extracting clinseq barcodes from input file: " + barcodes_filename)
    clinseq_barcodes = extract_clinseq_barcodes(barcodes_filename)

    logging.info("Validating all clinseq barcodes.")
    validate_clinseq_barcodes(clinseq_barcodes)

    logging.info("Generating sample dictionary from the input clinseq barcode strings.")
    sample_dict = convert_barcodes_to_sampledict(clinseq_barcodes)
    for sdid in sample_dict:
        fn = "{}/{}.json".format(outdir, sdid)
        with open(fn, 'w') as f:
            json.dump(sample_dict[sdid], f, sort_keys=True, indent=4)


import argparse
import logging
from soa import app, settings, models, housekeeping, tracks

if settings.is_dev:
    log = logging.getLogger("soa")
    log.setLevel(logging.DEBUG)
    log.addHandler(logging.StreamHandler())

parser = argparse.ArgumentParser()
parser.add_argument("--port", default=8000, type=int)
parser.add_argument("--tracks-dir", default="tracks", type=str)
parser.add_argument("--housekeeping", default=None, type=str)
args = parser.parse_args()

if args.housekeeping:
    housekeeping.handle(args)
else:
    tracks.core.load_tracks()
    kwargs = {
        "port": args.port,
        "host": "0.0.0.0",
    }
    if settings.is_dev:
        kwargs.update(dict(debug=True, reloader=False))
    kwargs["server"] = "gevent"
    app.run(**kwargs)


from keras.models import load_model
from tensorflow import lite

def keras_to_tflite(input_keras_model_file, output_tflite_file):
    keras_model = load_model(input_keras_model_file)
    input_names = get_input_names(keras_model)
    output_names = get_output_names(keras_model)
    print("input names:", input_names, " shapes:", keras_model.input_shape)
    print("output names:", output_names, " shapes:", keras_model.output_shape)
    converter = lite.TFLiteConverter.from_keras_model_file(model_file=input_keras_model_file,
                                                           input_arrays=input_names,
                                                           output_arrays=output_names)
    model = converter.convert()
    file = open(output_tflite_file, "wb")
    file.write(model)
    print("save tflite file to: ", output_tflite_file)

def get_output_names(keras_model):
    outputs = keras_model.outputs
    output_names = []
    for _output in outputs:
        output_names.append(_output.name[:-2])
    return output_names

def get_input_names(keras_model):
    inputs = keras_model.inputs
    input_names = []
    for _input in inputs:
        input_names.append(_input.name[:-2])
    return input_names

def main():
    keras_model_file = "./model_data/yolov3.h5"
    tflite_model_file = "./model_data/yolov3.tflite"
    keras_to_tflite(keras_model_file, tflite_model_file)

if __name__ == '__main__':
    main()


import os
import json
import hashlib

MAP_DIR = './map_base'
PROTOCOL_DIR = './protocol'

def list_files(dir):
    return [f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir, f))]

def convert_to_unix_line_endings_and_hash(dir, files):
    hashes = {}
    for file in files:
        path = os.path.join(dir, file)
        with open(path, 'rb') as fh:
            data = fh.read().replace(b'\r\n', b'\n')
        hashes[file] = hashlib.sha256(data).hexdigest()
        with open(path, 'wb') as fh:
            fh.write(data)

    return hashes

manifest = {
    'maps': convert_to_unix_line_endings_and_hash(MAP_DIR, list_files(MAP_DIR)),
    'protocol': convert_to_unix_line_endings_and_hash(PROTOCOL_DIR, list_files(PROTOCOL_DIR)),
}

with open('manifest.json', 'w') as fh:
    fh.write(json.dumps(manifest).replace(' ', ''))


# -*- coding: utf-8 -*-
"""
@author: Karthick
"""

import random
import numpy as np
import math

def find_max(pta):
    """
    function to find the amx pta : tie breaking using random
    input: pta(list) probability of each arm
    output : chosen_arm (number)
    action: chosing the best arm with random tie breaking
    """
    winner = np.argwhere(pta==np.amax(pta)).reshape(-1)
    winner = int(random.choice(winner))
    return winner

class Thompson:
    def __init__(self, n_arms):
        self.n_arms = n_arms
        self.numbers_of_success = [0] * n_arms
        self.numbers_of_failure = [0] * n_arms
        self.rewards = []
        self.chosen_arms = []
        return

    def action(self, context = False):
        self.max_random = 0
        self.chosen_arm = 0
        for i in range(0, self.n_arms):
            random_beta = random.betavariate(self.numbers_of_success[i] + 1, self.numbers_of_failure[i] + 1)
            if random_beta >self.max_random:
                self.max_random = random_beta
                self.chosen_arm = i
        self.chosen_arms.append(self.chosen_arm)
        return self.chosen_arm

    def update(self, reward):
        reward = int(reward)
        self.rewards.append(reward)
        if reward == 10 or reward == 5:
            self.numbers_of_success[self.chosen_arm] = self.numbers_of_success[self.chosen_arm] + 1
        else:
            self.numbers_of_failure[self.chosen_arm] = self.numbers_of_failure[self.chosen_arm] + 1

class eGreedy:
    def __init__(self, n_arms, epsilon):
        """
        Implemented one of the famous and simple techniques of eGreedy for online learning
        Inputs : n_arms, epsilon (number(int),number(float))
        output: None
        Action: creates and initiates arms, number of times arms being used
        """
        self.n_arms =n_arms
        self.epsilon = epsilon # eploration probability
        self.counts = np.zeros(n_arms, dtype=int)
        self.values = np.zeros(n_arms, dtype=float)
        self.chosen_arms = []
        self.rewards = []
        return

    def action(self, context=False):
        """
        actions :Choosen the most observed arm from the past for probability 1-epsilon else choosen randomly
        input : None
        output : choosen arm (number)
        """
        z = np.random.random()
        if z > self.epsilon:
            # Pick the best arm
            chosen_arm = find_max(self.values)
            self.chosen_arms.append(chosen_arm)
            return chosen_arm
        # Randomly pick any arm with prob 1 / len(self.counts)
        chosen_arm = np.random.randint(0, self.n_arms)
        self.chosen_arms.append(chosen_arm)
        return chosen_arm

    def update(self, reward):
        """
        input : reward (number)
        output : None
        """
        reward = int(reward)
        self.rewards.append(reward)
        # Increment chosen arm's count by one
        self.counts[self.chosen_arms[-1]] += 1
        n = self.counts[self.chosen_arms[-1]]
        # Recompute the estimated value of chosen arm using new reward
        value = self.values[self.chosen_arms[-1]]
        new_value = value * ((n - 1) / n) + reward / n
        self.values[self.chosen_arms[-1]] = new_value

class UCB:
    """
    Upper Confidence Bound (UCB) multi-armed bandit
    Arguments
    =========
    narms : int
        number of arms
    rho : float
        positive real explore-exploit parameter
    """
    def __init__(self, n_arms, rho = 2, q0 = np.inf):
        self.n_arms =n_arms
        self.rho = rho
        self.q0 = q0
        self.numbers_of_selections = [0] * n_arms
        self.avg_list = [q0 for i in range(n_arms)]
        self.q_list = [q0 for i in range(n_arms)]
        self.sums_of_rewards = [0] * n_arms
        self.chosen_arms = []
        self.rewards = []
        #self.max_upper_bound = 0
        #self.upper_bound = [0] * n_arms
        #self.average_reward = [0] * n_arms
        #self.chosen_arm = 0
        self.n_users = 0
        #self.avg_reward = 0
        return

    def action(self):
        self.n_users = self.n_users + 1
        values = self.q_list
        next_arm_list = []
        for index, value in enumerate(values):
            if value==max(values):
                next_arm_list.append(index)
        next_arm = int(np.random.choice(next_arm_list))
        self.chosen_arms.append(next_arm)
        return next_arm

    def update(self,reward):
        reward = int(reward)
        self.rewards.append(reward)
        index = self.chosen_arms[-1]
        average = self.avg_list[index]
        if average == np.inf:
            average = 0
        self.numbers_of_selections[index] = self.numbers_of_selections[index] + 1
        current = self.numbers_of_selections[index]
        # update the average value with previous weighted average value + new reward
        self.avg_list[index] = (average * (current - 1) + reward) / current
        self.rewards.append(reward)
        self.numbers_of_selections[index] = self.numbers_of_selections[index] + 1
        self.sums_of_rewards[index] = self.sums_of_rewards[index] + reward
        # update extimate Q value of each chosen arm
        for i in range(self.n_arms):
            mean = self.avg_list[i]
            if mean != np.inf:  # update Q value for the arms that have been explored
                self.q_list[i] = mean + np.sqrt((self.rho * np.log(self.n_users)) / self.numbers_of_selections[i])

Karthick - Assignment 2/sampling_algorithm.py


# Leetcode 153. Find Minimum in Rotated Sorted Array

# Time Complexity :  O(log n) where n is the size of the array

# Space Complexity : O(1)

# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No

# Approach: Condition: If both the neighbours are greater than the current then its the min.
# When the array is split at the mid atleast one side is unsorted and the target is on the unsorted side.
# If the left side is sorted then search on right side and vice versa

# Your code here along with comments explaining your approach

class Solution:

    def minSearch(self, nums, low, high) -> int:
        while low <= high:
            mid = low + ((high-low)//2)

            # if mid points to the 0th index or the element BEFORE mid is greater than mid
            # and if mid points to the last index or the element AFTER mid is greater than mid
            if ((mid == 0 or nums[mid-1] > nums[mid]) and (mid == len(nums)-1 or nums[mid+1] > nums[mid])):
                return nums[mid]
            # Check if the array is sorted if yes then move to the other side
            if nums[mid] < nums[high]:
                high = mid - 1
            else:
                low = mid+1
        return -1

    def findMin(self, nums: List[int]) -> int:
        low = 0
        high = len(nums)-1

        return self.minSearch(nums, low, high)


from cloudshell.cli.command_template.command_template_executor import CommandTemplateExecutor

from cloudshell.traffic.teravm.cli import ctrl_command_templates

class TeraVMStartTestsFlow(object):
    def __init__(self, cli_handler):
        """

        :param traffic.teravm.cli.ctrl_handler.TeraVMControllerCliHandler cli_handler:
        """
        self._cli_handler = cli_handler

    def execute(self, test_group_name, user):
        """

        :param str test_group_name:
        :param str user:
        :return:
        """
        with self._cli_handler.get_cli_service(self._cli_handler.cli_mode) as session:
            command = CommandTemplateExecutor(cli_service=session,
                                              command_template=ctrl_command_templates.START_TEST_GROUP)

            return command.execute_command(test_group_name=test_group_name, user=user)


import sys
from JackAnalyzer import analyze
from CodeWriter import encode

if __name__ == '__main__':

    root_dir = ''
    try:
        root_dir = sys.argv[1]
    except IndexError:
        print("No input file name")
        exit()

    xml_data, file_names = analyze(root_dir)

    for i in range(len(xml_data)):
        source_code = encode(xml_data[i])
        with open(file_names[i].replace('.jack', '.vm'), 'w') as f:
            f.write(source_code)


import json

import walrus

from mindsdb.integrations.base import StreamIntegration
import mindsdb.interfaces.storage.db as db
from mindsdb_streams import RedisStream, StreamController, StreamLearningController

class RedisConnectionChecker:
    def __init__(self, **params):
        self.connection_info = params['connection']

    def check_connection(self):
        if isinstance(self.connection_info, str):
            self.connection_info = json.loads(self.connection_info)
        try:
            client = walrus.Database(**self.connection_info)
            client.dbsize()
        except Exception:
            return False
        else:
            return True

class Redis(StreamIntegration, RedisConnectionChecker):
    def __init__(self, config, name, db_info):
        self.connection_info = db_info['connection']

        # Back compatibility with initial API version
        self.control_stream = db_info.get('control_stream') or db_info.get('stream') or None
        if 'advanced' in db_info:
            self.connection_info['advanced'] = db_info['advanced']

        StreamIntegration.__init__(
            self,
            config,
            name,
            control_stream=RedisStream(self.control_stream, self.connection_info) if self.control_stream else None
        )

    def _make_stream(self, s: db.Stream):
        if s.learning_params and s.learning_threshold:
            learning_params = json.loads(s.learning_params) if isinstance(s.learning_params, str) else s.learning_params
            return StreamLearningController(
                    s.name,
                    s.predictor,
                    learning_params,
                    s.learning_threshold,
                    stream_in=RedisStream(s.stream_in, self.connection_info),
                    stream_out=RedisStream(s.stream_out, self.connection_info),
                    in_thread=True
                )

        return StreamController(
            s.name,
            s.predictor,
            stream_in=RedisStream(s.stream_in, self.connection_info),
            stream_out=RedisStream(s.stream_out, self.connection_info),
            stream_anomaly=RedisStream(s.anomaly_stream, self.connection_info) if s.anomaly_stream is not None else None,
            in_thread=True
        )


import sqlite3 as dEntry

class CreateDB:
    def __init__(self):
        self.con = dEntry.connect('dataRecords.db')
        self.cur = self.con.cursor()
        self.createTable(self.con)
        print(self.con)

    def createTable(self, con):
        try:
            self.cur.execute("""CREATE TABLE IF NOT EXISTS RECORDS
                     (stock, time, quantity, type, price)""")
        except Exception as e:
            print(e)