from django import forms
from django.contrib.auth.models import User
from django.forms import Textarea, TextInput, NullBooleanSelect, Select, HiddenInput
from consorcios.models import *
from .models import *
from contabilidad.models import *
from django.db.models import Q
from django_afip.models import PointOfSales
from admincu.forms import FormControl

from django.db.models import Max

class ingresoForm(FormControl, forms.ModelForm):
	class Meta:
		model = Ingreso
		fields = [
			'nombre', 'prorrateo',
			'prioritario', 'cuenta_contable'
		]
		labels = {
			'nombre': "Nombre del ingreso",
			'prioritario': "Tiene prioridad de cobro?",
			'prorrateo': "Prorratea por m2?",
		}
		widgets = {
			'prorrateo': NullBooleanSelect(),
			'prioritario': NullBooleanSelect(),
		}

	def __init__(self, consorcio=None, *args, **kwargs):
		self.consorcio = consorcio
		super().__init__(*args, **kwargs)
		if not self.consorcio.superficie:
			self.fields.pop('prorrateo')
		self.fields['cuenta_contable'].queryset = Plan.objects.get(consorcio=consorcio).cuentas.filter(
				nivel=4,
				).order_by('numero')
		if self.instance.primario:
			self.fields.pop('cuenta_contable')

class gastoForm(FormControl, forms.ModelForm):
	class Meta:
		model = Gasto
		fields = [
			'nombre', 'cuenta_contable'
		]
		labels = {
			'nombre': "Nombre del tipo de gasto",
		}

	def __init__(self, consorcio=None, *args, **kwargs):
		self.consorcio = consorcio
		super().__init__(*args, **kwargs)
		self.fields['cuenta_contable'].queryset = Plan.objects.get(consorcio=consorcio).cuentas.filter(nivel=4).all().order_by('numero')

class cajaForm(FormControl, forms.ModelForm):
	class Meta:
		model = Caja
		fields = ['nombre', 'entidad', 'saldo', 'fecha', 'cuenta_contable']

		labels = {
			'saldo' : "Saldo trasladable",
			'fecha': "Fecha del saldo",
		}

	def __init__(self, consorcio=None, *args, **kwargs):
		self.consorcio = consorcio
		super().__init__(*args, **kwargs)
		self.fields['cuenta_contable'].queryset = Plan.objects.get(consorcio=consorcio).cuentas.filter(nivel=4).filter(
				Q(numero__range=[111000,113000]) |
				Q(numero__range=[211000,221000])
				).order_by('numero')
		if self.instance.primario:
			self.fields.pop('entidad')
			self.fields.pop('cuenta_contable')

class dominioForm(FormControl, forms.ModelForm):
	class Meta:
		model = Dominio
		fields = [
			'propietario', 'socio',
			'numero', 'identificacion',
			'superficie_total', 'superficie_cubierta',
			'domicilio_calle', 'domicilio_numero',
			'domicilio_piso', 'domicilio_oficina',
			'domicilio_sector', 'domicilio_torre',
			'domicilio_manzana', 'domicilio_parcela',
			'domicilio_catastro', 'padre',
			]

		labels = {
			'domicilio_catastro': "Catastro / Matricula",
			'socio': "Ocupante",
			'identificacion': 'Identificacion (ocupante)',
			'padre': 'Unifica con',
			'domicilio_manzana': 'Domicilio manzana / modulo',
		}

	def __init__(self, consorcio=None, *args, **kwargs):
		self.consorcio = consorcio
		super().__init__(*args, **kwargs)
		socios = Socio.objects.filter(consorcio=consorcio)
		self.fields['socio'].queryset = socios
		self.fields['propietario'].queryset = socios
		self.fields['padre'].queryset = Dominio.objects.filter(consorcio=consorcio, padre__isnull=True)
		self.fields['padre'].label_from_instance = self.label_from_instance

	def label_from_instance(self, obj):
		return "{} - {}".format(obj.socio, obj.nombre)

	def clean_superficie_total(self):
		superficie_total = self.cleaned_data['superficie_total']
		ingresos = Ingreso.objects.filter(consorcio=self.consorcio)
		prorrateo_superficie = []
		for ingreso in ingresos:
			if ingreso.prorrateo:
				prorrateo_superficie.append(ingreso)
		if prorrateo_superficie and not superficie_total:
			raise forms.ValidationError("Este campo es obligatorio.")
		return superficie_total

class socioForm(FormControl, forms.ModelForm):
	class Meta:
		model = Socio
		fields = [
			'nombre', 'apellido','numero_asociado','tipo_asociado',
			'fecha_alta',  'tipo_documento',
			'numero_documento','fecha_nacimiento',
			'es_extranjero', 'domicilio', 'localidad',
			'provincia', 'telefono','profesion',
			'mail',   'notificaciones'
			]
		labels = {
			'numero_asociado' : "Numero de asociado",
			'fecha_nacimiento': "Fecha de nacimiento",
			'es_extranjero': 'Es extranjero?',
			'tipo_documento': 'Tipo de Documento',
			'numero_documento': 'Numero de Documento',
			'tipo_asociado':'Tipo de asociado',
			'fecha_alta': 'Fecha de alta',
			'notificaciones': 'Recibe notificaciones?'
		}
		widgets = {
			'notificaciones': NullBooleanSelect(),
			'es_extranjero': NullBooleanSelect(),
			'numero_documento': TextInput(attrs={'type': 'number', 'min': '0', 'step':'1', 'required':True}),

		}

	def __init__(self, consorcio=None, *args, **kwargs):
		self.consorcio = consorcio
		super().__init__(*args, **kwargs)
		self.fields['numero_asociado'].initial = Socio.objects.aggregate(Max('numero_asociado'))['numero_asociado__max']+1
		self.fields['tipo_asociado'].queryset = Tipo_asociado.objects.filter(consorcio=consorcio, baja__isnull=True)
		self.fields['tipo_documento'].required = True
		self.fields['numero_documento'].required = True
		self.fields['fecha_alta'].required = True
		self.fields['tipo_asociado'].required = True
		self.fields['numero_asociado'].required = True
		self.fields['nombre'].required = True

	def clean_numero_asociado(self):
		numero_asociado = self.cleaned_data['numero_asociado']
		socios_del_club = Socio.objects.filter(consorcio=self.consorcio)
		if self.instance:
			socios_del_club = socios_del_club.exclude(pk=self.instance.pk)
		n_asocs = []
		for s in socios_del_club:
			n_asocs.append(s.numero_asociado)
		if numero_asociado in n_asocs:
			raise forms.ValidationError("ya existe un asociado con el numero indicado")
		return numero_asociado

	def clean_numero_documento(self):
		numero_documento = self.cleaned_data['numero_documento']
		socios_del_club = Socio.objects.filter(consorcio=self.consorcio)
		if self.instance:
   			socios_del_club = socios_del_club.exclude(pk=self.instance.pk)
		documentos = []
		for s in socios_del_club:
			documentos.append(s.numero_documento)
		if numero_documento in documentos:
			raise forms.ValidationError("ya existe un asociado con el numero de documento indicado")
		return numero_documento

class acreedorForm(FormControl, forms.ModelForm):
	class Meta:
		model = Acreedor
		fields = [
			'nombre','tipo', 'tipo_documento',
			'numero_documento', 'genera',
			'cuenta_contable',
			]
		labels = {
			'tipo': 'Tipo de Gasto',
			'tipo_documento': 'Tipo de documento',
			'genera': 'Genera retenciones?',
			'numero_documento': 'Numero de documento',
		}
		widgets = {
			'numero_documento': TextInput(attrs={'type': 'number', 'min': '0', 'step':'1', 'required':True})
		}

	def __init__(self, consorcio=None, *args, **kwargs):
		self.consorcio = consorcio
		super().__init__(*args, **kwargs)
		self.fields['tipo'].queryset = Gasto.objects.filter(consorcio=consorcio)
		self.fields['cuenta_contable'].queryset = Plan.objects.get(consorcio=consorcio).cuentas.filter(nivel=4).filter(
				numero__range=[210000,299999]
				).order_by('numero')
		self.fields['tipo_documento'].required = True
		if self.instance.primario:
			self.fields.pop('nombre')
			self.fields.pop('tipo_documento')
			self.fields.pop('numero_documento')
			self.fields.pop('cuenta_contable')
			self.fields.pop('genera')

class interesForm(FormControl, forms.ModelForm):
	class Meta:
		model = Accesorio
		fields = [
			'nombre', 'ingreso',
			'plazo', 'tipo',
			'reconocimiento',
			'monto', 'base_calculo',
			'cuenta_contable'
		]
		labels = {
			'nombre': "Titulo del interes",
			'plazo': "Plazo en dias",
			'tipo': "Tipo de calculo",
			'monto': "Valor de calculo",
			'base_calculo': "Base de calculo",
		}
		help_texts = {
			"plazo":"Dias desde la fecha de facturacion para que opere el vencimiento y empiece a correr el interes",
		}

	def __init__(self, consorcio=None, *args, **kwargs):
		self.consorcio = consorcio
		super().__init__(*args, **kwargs)
		self.fields['cuenta_contable'].queryset = Plan.objects.get(consorcio=consorcio).cuentas.filter(
				nivel=4,
				numero__gte=400000,
				numero__lt=500000,
				).order_by('numero')
		self.fields['ingreso'].queryset = Ingreso.objects.filter(consorcio=consorcio)
		for field in iter(self.fields):
			self.fields[field].required = True

class descuentoForm(FormControl, forms.ModelForm):
	class Meta:
		model = Accesorio
		fields = [
				'nombre','ingreso',
				'plazo',
				'tipo', 'monto',
				'cuenta_contable'
			]
		labels = {
			'nombre': "Titulo del descuento",
			'plazo': "Plazo en dias",
			'tipo': "Tipo de calculo",
			'monto': "Valor de calculo",
		}
		help_texts = {
			"plazo":"Dias de gracia desde la fecha de facturacion",
		}

	def __init__(self, consorcio=None, *args, **kwargs):
		self.consorcio = consorcio
		super().__init__(*args, **kwargs)
		self.fields['cuenta_contable'].queryset = Plan.objects.get(consorcio=consorcio).cuentas.filter(
				nivel=4,
				numero__gte=400000,
				).order_by('numero')
		self.fields['ingreso'].queryset = Ingreso.objects.filter(consorcio=consorcio)
		for field in iter(self.fields):
			self.fields[field].required = True

class bonificacionForm(FormControl, forms.ModelForm):
	class Meta:
		model = Accesorio
		fields = [
				'nombre','ingreso',
				'tipo', 'monto',
				'cuenta_contable'
			]
		labels = {
			'nombre': "Titulo de la bonificacion",
			'tipo': "Tipo de calculo",
			'monto': "Valor de calculo",
		}

	def __init__(self, consorcio=None, *args, **kwargs):
		self.consorcio = consorcio
		super().__init__(*args, **kwargs)
		self.fields['cuenta_contable'].queryset = Plan.objects.get(consorcio=consorcio).cuentas.filter(
				nivel=4,
				numero__gte=400000,
				).order_by('numero')
		self.fields['ingreso'].queryset = Ingreso.objects.filter(consorcio=consorcio)
		for field in iter(self.fields):
			self.fields[field].required = True

class grupoForm(FormControl, forms.ModelForm):
	class Meta:
		model = Tipo_asociado
		fields = ['nombre', 'descripcion']

	def __init__(self, consorcio=None, *args, **kwargs):
		self.consorcio = consorcio
		super().__init__(*args, **kwargs)
		self.fields['nombre'].required = True
		#self.fields['dominios'].queryset = Dominio.objects.filter(consorcio=consorcio)

class servicioForm(FormControl, forms.ModelForm):
	class Meta:
		model = Socio
		fields = ['nombre_servicio_mutual','nombre', 'descripcion' ]
		labels = {
			'nombre':"Nombre del grupo de asociados que reciben el servicio",
			'descripcion': "Descripcion del servicio",
			'nombre_servicio_mutual': "Nombre del servicio mutual",
		}

	def __init__(self, consorcio=None, *args, **kwargs):
		self.consorcio = consorcio
		super().__init__(*args, **kwargs)

		self.fields['nombre_servicio_mutual'].required = True
		self.fields['nombre'].required = True

class hiddenForm(forms.ModelForm):

	class Meta:
		model = Accesorio
		fields = ['finalizacion']

		widgets = {
			'finalizacion': HiddenInput(),
		}


#####################################################################################
# Example program for the ADS1115_mPy module
#
# This program shows how to use the Auto Range function of the AD1115_mPy module.
#
# Further information can be found on (currently only for the Arduino version):
# https://wolles-elektronikkiste.de/ads1115 (German)
# https://wolles-elektronikkiste.de/en/ads1115-a-d-converter-with-amplifier (English)
#
#####################################################################################

from machine import I2C
from time import sleep
from ADS1115 import *

ADS1115_ADDRESS = 0x48

i2c = I2C(0)
adc = ADS1115(ADS1115_ADDRESS, i2c=i2c)

#     Set the voltage range of the ADC to adjust the gain:
#     Please note that you must not apply more than VDD + 0.3V to the input pins!
#     ADS1115_RANGE_6144  ->  +/- 6144 mV
#     ADS1115_RANGE_4096  ->  +/- 4096 mV
#     ADS1115_RANGE_2048  ->  +/- 2048 mV (default)
#     ADS1115_RANGE_1024  ->  +/- 1024 mV
#     ADS1115_RANGE_0512  ->  +/- 512 mV
#     ADS1115_RANGE_0256  ->  +/- 256 mV
adc.setVoltageRange_mV(ADS1115_RANGE_6144)

#     Set the inputs to be compared:
#     ADS1115_COMP_0_1    ->  compares 0 with 1 (default)
#     ADS1115_COMP_0_3    ->  compares 0 with 3
#     ADS1115_COMP_1_3    ->  compares 1 with 3
#     ADS1115_COMP_2_3    ->  compares 2 with 3
#     ADS1115_COMP_0_GND  ->  compares 0 with GND
#     ADS1115_COMP_1_GND  ->  compares 1 with GND
#     ADS1115_COMP_2_GND  ->  compares 2 with GND
#     ADS1115_COMP_3_GND  ->  compares 3 with GND
adc.setCompareChannels(ADS1115_COMP_0_GND)

#     Set number of conversions after which the alert pin will assert
#     - or you can disable the alert:
#     ADS1115_ASSERT_AFTER_1  -> after 1 conversion
#     ADS1115_ASSERT_AFTER_2  -> after 2 conversions
#     ADS1115_ASSERT_AFTER_4  -> after 4 conversions
#     ADS1115_DISABLE_ALERT   -> disable comparator / alert pin (default)
# adc.setAlertPinMode(ADS1115_ASSERT_AFTER_1)

#     Set the conversion rate in SPS (samples per second)
#     Options should be self-explaining:
#     ADS1115_8_SPS
#     ADS1115_16_SPS
#     ADS1115_32_SPS
#     ADS1115_64_SPS
#     ADS1115_128_SPS (default)
#     ADS1115_250_SPS
#     ADS1115_475_SPS
#     ADS1115_860_SPS
adc.setConvRate(ADS1115_128_SPS)

#     Set continuous or single shot mode:
#     ADS1115_CONTINUOUS  ->  continuous mode
#     ADS1115_SINGLE     ->  single shot mode (default)
adc.setMeasureMode(ADS1115_CONTINUOUS)

#     Choose maximum limit or maximum and minimum alert limit (window) in volts - alert pin will
#     assert when measured values are beyond the maximum limit or outside the window
#     Upper limit first: setAlertLimit_V(MODE, maximum, minimum)
#     In max limit mode the minimum value is the limit where the alert pin assertion will be
#     be cleared (if not latched).
#     ADS1115_MAX_LIMIT
#     ADS1115_WINDOW
# adc.setAlertModeAndLimit_V(ADS1115_MAX_LIMIT, 3.0, 1.5)

#     Enable or disable latch. If latch is enabled the alert pin will assert until the
#     conversion register is read (getResult functions). If disabled the alert pin assertion
#     will be cleared with next value within limits.
#     ADS1115_LATCH_DISABLED (default)
#     ADS1115_LATCH_ENABLED
# adc.setAlertLatch(ADS1115_LATCH_ENABLED)

#     Sets the alert pin polarity if active:
#     ADS1115_ACT_LOW  ->  active low (default)
#     ADS1115_ACT_HIGH ->  active high
# adc.setAlertPol(ADS1115_ACT_LOW)

#     With this function the alert pin will assert, when a conversion is ready.
#     In order to deactivate, use the setAlertLimit_V function
# adc.setAlertPinToConversionReady()

#     Enable or disable permanent automatic range selection mode. If enabled, the range will
#     change if the measured values are outside of 30-80% of the maximum value of the current
#     range.
#     !!! Use EITHER this function once OR setAutoRange() whenever needed (see below) !!!
adc.setPermanentAutoRangeMode(True)

def readChannel(channel):
    adc.setCompareChannels(channel)

#     setAutoRange() switches to the highest range (+/- 6144 mV), measures the current
#     voltage and then switches to the lowest range where the current value is still
#     below 80% of the maximum value of the range. The function is only suitable if you
#     expect stable or slowly changing voltages. setAutoRange needs roughly the time you
#     would need for three conversions.
#     If the ADS115 is in single shot mode, setAutoRange() will switch into continuous
#     mode to measure a value and switch back again.
#     !!! Use EITHER this function whenever needed OR setPermanentAutoRangeMode(true) once !!!
    #adc.setAutoRange()

    voltage = adc.getResult_V()
    voltRange = adc.getVoltageRange_mV() # this is just to show that the range is changing with changing voltages
    print("Range: +/-", voltRange, "[mV], Voltage [V]: {:<4.2f}".format(voltage))

print("ADS1115 Example Sketch - Continuous Mode with Auto Range")
print("")

while True:
    print("Channel 0 -", end=" ")
    readChannel(ADS1115_COMP_0_GND)

    print("Channel 1 -", end=" ")
    readChannel(ADS1115_COMP_1_GND)

    print("Channel 2 -", end=" ")
    readChannel(ADS1115_COMP_2_GND)

    print("Channel 3 -", end=" ")
    readChannel(ADS1115_COMP_3_GND)

    print("-------------------------------")
    sleep(2)


import numpy as np
from petsc4py import PETSc

USE_MONITORS = True
N = 2

def residual_function(snes, x, residual):
    '''
    :param petsc4py.PETSc.SNES snes:
    :param petsc4py.PETSc.Vec x:
    :param petsc4py.PETSc.Vec f:
        Residual vector
    '''
    # Get X array information
    x = np.array(x)
    # Compute the problem
    y = np.array([
        x[1] - np.log10(x[0]),
        x[0] + x[1] - 1.0,
    ])
    # Copy the solution back to the PETSc' residual vector
    residual[:] = y

snes = PETSc.SNES().create()
r = PETSc.Vec().createSeq(N)  # residual vector
x = PETSc.Vec().createSeq(N)  # solution vector
b = PETSc.Vec().createSeq(N)  # right-hand side
snes.setFunction(residual_function, r)

if USE_MONITORS:
    def _solver_monitor(snes, its, fnorm):
        print('[NonLinear Solver] %s Residual function norm %s' % (its, fnorm,))
    snes.setMonitor(_solver_monitor)
    def _linear_solver_monitor(snes, its, fnorm):
        print('[Linear Solver] %s Residual function norm %s' % (its, fnorm,))
    snes.ksp.setMonitor(_linear_solver_monitor)

# Setup the Jacobian structure using DMShell
# from scipy.sparse.csr import csr_matrix
# dm = PETSc.DMShell().create()
# j_structure = csr_matrix(np.ones(shape=(N,N)))
# csr = (j_structure.indptr, j_structure.indices, j_structure.data)
# jac = PETSc.Mat().createAIJWithArrays(j_structure.shape, csr)
# dm.setMatrix(jac)
# snes.setDM(dm)

# Setup the Jacobian structure using DMDA
dmda = PETSc.DMDA().create([N], dof=1, stencil_width=2, stencil_type='star')
snes.setDM(dmda)

# Setup the initial guess
initial_guess = 7.0 * np.ones(shape=(N))
x.setArray(initial_guess)
# Setup the B vector
b.set(0)
snes.solve(b, x)
solution = np.array(x)

assert np.allclose(solution, [1.0, 0.0], atol=1e-6)


import heapq
import sys
sys.stdin = open('input.txt', 'r')

N, K = map(int, input().split())
board = [list(map(int, input().split())) for _ in range(N)]

for k in range(N):
    for i in range(N):
        if i == k:
            continue
        for j in range(N):
            if j == i or j == k:
                continue
            board[i][j] = min(board[i][j], board[i][k] + board[k][j])

queue = []
heapq.heappush(queue, (0, K, [False]*N))

while queue:
    val, idx, visit = heapq.heappop(queue)
    visit[idx] = True

    flag = True
    for nxt in range(N):
        if visit[nxt] is False:
            heapq.heappush(queue, (val+board[idx][nxt], nxt, visit[:]))
            flag = False
    if flag:
        print(val)
        break


from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from main import main_account_screen

class CashierView:
    def __init__(self):

        # main_account_screen()
        self.window = Toplevel(main_account_screen())
        # master self.window size
        self.window.geometry("700x600")
        self.window.title("10K")
        color = "#FAF733"
        self.window.resizable(width=FALSE, height=FALSE)
        self.window.configure(bg=color)
        # main_account_screen()

        # top_frame = Frame(self.window, bg=color, width=700, height=20)
        # top_frame.pack(side=TOP)
        # california lebel in top frame
        title_label = Label(self.window, text="10K Akorno Limited (Cashier's View)",fg="blue", font=("Comic Sans MC", 17), bg=color,
                            pady=10)
        # left frame
        # left_frame = Frame(self.window, bg=color, width=600, height=450)
        # left_frame.place(x=10, y=50)
        title_label.pack(side=TOP)

        # #bottom frame for buttons
        # bottom_frame = Frame(self.window, bg=color, height=130, width=705)
        # bottom_frame.place(x=10, y=660)

        label = Label(self.window, text="Today's Menu", font= ("Comic Sans MC","15"),  bg="black", fg="white")
        label.place(x=0, y=0)

        # checkbuttons for FOOD in self.window
        self.banku = IntVar()
        banku = Checkbutton(self.window, text="Banku", variable=self.banku, font="Helvetica 12 bold italic", bg=color)

        banku.place(x=0, y=40)

        self.fried_rice = IntVar()
        fried_rice = Checkbutton(self.window, text="Fried Rice", variable=self.fried_rice, font="Helvetica 12 bold italic",
                           bg=color)

        fried_rice.place(x=0, y=90)
        self.stir_fry = IntVar()
        stir_fry = Checkbutton(self.window, text="Stir Fry", variable=self.stir_fry, font="Helvetica 12 bold italic",
                           bg=color)
        stir_fry.place(x=0, y=140)

        self.beans = IntVar()
        beans = Checkbutton(self.window, text="Beans and Plaintain", variable=self.beans, font="Helvetica 12 bold italic",
                           bg=color)

        beans.place(x=0, y=190)

        self.indomie = IntVar()
        indomie = Checkbutton(self.window, text="Indomie", variable=self.indomie, font="Helvetica 12 bold italic",
                           bg=color)

        indomie.place(x=0, y=240)

        total_btn = Button(self.window,text = "TOTAL",command=lambda:self.calc_total())
        total_btn.place(x=0, y=290)

        # optionmenu widget for dropdown of quantity place with food in self.window
        global list_menu
        list_menu = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
        self.drop_op_1 = StringVar()
        self.drop_op_1.set(list_menu[0])
        drop1 = OptionMenu(self.window, self.drop_op_1, *list_menu)

        self.drop_op_2 = StringVar()
        self.drop_op_2.set(list_menu[0])
        drop2 = OptionMenu(self.window, self.drop_op_2, *list_menu)

        self.drop_op_3 = StringVar()
        self.drop_op_3.set(list_menu[0])
        drop3 = OptionMenu(self.window, self.drop_op_3, *list_menu)

        self.drop_op_4 = StringVar()
        self.drop_op_4.set(list_menu[0])
        drop4 = OptionMenu(self.window, self.drop_op_4, *list_menu)

        self.drop_op_5 = StringVar()
        self.drop_op_5.set(list_menu[0])
        drop5 = OptionMenu(self.window, self.drop_op_5, *list_menu)

        drop1.place(x=180, y=40)
        drop2.place(x=180, y=90)
        drop3.place(x=180, y=140)
        drop4.place(x=180, y=190)
        drop5.place(x=180, y=240)

        # sizes optionmenu in self.window
        self.s1 = StringVar()
        self.s1.set("size")
        list_menu2 = ["half-portion", "full-portion"]
        size_opt1 = OptionMenu(self.window, self.s1, *list_menu2)
        size_opt1.place(x=270, y=40)
        self.s2 = StringVar()
        self.s2.set("size")
        size_opt2 = OptionMenu(self.window, self.s2, *list_menu2)
        size_opt2.place(x=270, y=90)
        self.s3 = StringVar()
        self.s3.set("size")
        size_opt3 = OptionMenu(self.window, self.s3, *list_menu2)
        size_opt3.place(x=270, y=140)
        self.s4 = StringVar()
        self.s4.set("size")
        size_opt4 = OptionMenu(self.window, self.s4, *list_menu2)
        size_opt4.place(x=270, y=190)
        self.s5 = StringVar()
        self.s5.set("size")
        size_opt5 = OptionMenu(self.window, self.s5, *list_menu2)
        size_opt5.place(x=270, y=240)

    global item_quantity_price
    item_quantity_price = []

    def error_handling(self, msg):
        if msg == "error!":
            messagebox.showerror("Error", "No Digits to compute!")
        elif msg == "division by zero!":
            messagebox.showerror("Error", "You can not divide a digit by zero!")

    # back end and logic
    def calc_total(self):

        # Set initial result to 0
        self.total_food= 0
        banku_result = 0
        fried_rice_result = 0
        indomie_result = 0
        beans_res = 0
        stir_fry_result = 0

        try:
            # for food 1
            if self.banku.get() == 1:
                if self.s1.get() == "full-portion":
                    banku_result = int(self.drop_op_1.get()) * 300   # option 1 in dropdown menu
                    p1_t = ("banku", str(self.drop_op_1.get()), "300")
                    item_quantity_price.append(p1_t)
                elif self.s1.get() == "half-portion":
                    banku_result = int(self.drop_op_1.get()) * 200
                    p1_t = ("banku", str(self.drop_op_1.get()), "200")
                    item_quantity_price.append(p1_t)
                else:
                    banku_result = int(self.drop_op_1.get()) * 150
                    p1_t = ("banku", str(self.drop_op_1.get()), "150")
                    item_quantity_price.append(p1_t)
                # item_quantity_price.append(p1_t)
            else:
                banku_result = 0

            # for food 2
            if self.fried_rice.get() == 1:
                if self.s2.get() == "full-portion":
                    fried_rice_result = int(self.drop_op_2.get()) * 300 #option 2 in dropdown menu
                    p2_t = ("Fried Rice and Chicken", str(self.drop_op_2.get()), "300")
                    item_quantity_price.append(p2_t)
                elif self.s2.get() == "half-portion":
                    fried_rice_result = int(self.drop_op_2.get()) * 200
                    p2_t = ("Fried Rice and Chicken", str(self.drop_op_2.get()), "200")
                    item_quantity_price.append(p2_t)
                else:
                    fried_rice_result = int(self.drop_op_2.get()) * 150
                    p2_t = ("Fried Rice and Chicken", str(self.drop_op_2.get()), "150")
                    item_quantity_price.append(p2_t)
                # item_quantity_price.append(p2_t)
            else:
                fried_rice_result = 0

            # for food 3
            if self.stir_fry.get() == 1:
                if self.s3.get() == "full-portion":
                    stir_fry_result = int(self.drop_op_3.get()) * 300  #option 3 in dropdown menu
                    p3_t = ("Stir Fry", str(self.drop_op_3.get()), "300")
                    item_quantity_price.append(p3_t)
                elif self.s3.get() == "half-portion":
                    stir_fry_result = int(self.drop_op_3.get()) * 200
                    p3_t = ("Stir Fry", str(self.drop_op_3.get()), "200")
                    item_quantity_price.append(p3_t)
                else:
                    stir_fry_result = int(self.drop_op_3.get()) * 150
                    p3_t = ("Stir Fry", str(self.drop_op_3.get()), "150")
                    item_quantity_price.append(p3_t)
                # item_quantity_price.append(p3_t)
            else:
                stir_fry_result = 0

            # for food 4
            if self.beans.get() == 1:
                if self.s4.get() == "full-portion":
                    beans_res = int(self.drop_op_4.get()) * 300   # option 4 in dropdown menu
                    p4_t = ("Beans and Plaintain", str(self.drop_op_1.get()), "300")
                    item_quantity_price.append(p4_t)
                elif self.s4.get() == "half-portion":
                    beans_res = int(self.drop_op_4.get()) * 200
                    p4_t = ("Beans and Plaintain", str(self.drop_op_4.get()), "200")
                    item_quantity_price.append(p4_t)
                else:
                    beans_res = int(self.drop_op_4.get()) * 150
                    p4_t = ("Beans and Plaintain", str(self.drop_op_4.get()), "150")
                    item_quantity_price.append(p4_t)
                # item_quantity_price.append(p4_t)
            else:
                beans_res = 0

            # for food 5
            if self.indomie.get() == 1:
                if self.s5.get() == "full-portion":
                    indomie_result = int(self.drop_op_5.get()) * 300  # option 5 in dropdown menu
                    p5_t = ("Indomie", str(self.drop_op_5.get()), "300")
                    item_quantity_price.append(p5_t)
                elif self.s5.get() == "half-portion":
                    indomie_result = int(self.drop_op_5.get()) * 200
                    p5_t = ("Indomie", str(self.drop_op_5.get()), "200")
                    item_quantity_price.append(p5_t)
                else:
                    indomie_result = int(self.drop_op_5.get()) * 150
                    p5_t = ("Indomie", str(self.drop_op_5.get()), "150")
                    item_quantity_price.append(p5_t)
                # item_quantity_price.append(p5_t)
            else:
                indomie_result = 0

        except:
            raise NameError

        self.total_food = (
                        banku_result + fried_rice_result + stir_fry_result + indomie_result +  beans_res)

        print(self.total_food)

        total = Label(self.window,text=self.total_food, bg="brown", font=("verdana", 20)).pack()
        total.place(x=0, y=300)

    def printvalue(self):
        self.calc_total

    def reset_sales(self):

        try:
            self.banku.set(0)
            self.fried_rice.set(0)
            self.stir_fry.set(0)
            self.beans.set(0)
            self.indomie.set(0)

            self.drop_op_1.set(list_menu[0])
            self.drop_op_2.set(list_menu[0])
            self.drop_op_3.set(list_menu[0])
            self.drop_op_4.set(list_menu[0])
            self.drop_op_5.set(list_menu[0])

            self.s1.set("size")
            self.s2.set("size")
            self.s3.set("size")
            self.s4.set("size")
            self.s5.set("size")

            # Reset checklist btns to 0
            self.d_ch_banku.set(0)
            self.d_ch_bt_2.set(0)
            self.d_ch_bt_3.set(0)
            self.d_ch_bt_4.set(0)
            self.d_ch_bt_5.set(0)

            self.drop_op_d_1.set(list_menu[0])
            self.drop_op_d_2.set(list_menu[0])
            self.drop_op_d_3.set(list_menu[0])
            self.drop_op_d_4.set(list_menu[0])
            self.drop_op_d_5.set(list_menu[0])

            self.s_ch_banku.set(0)
            self.s_ch_bt_2.set(0)
            self.s_ch_bt_3.set(0)
            self.s_ch_bt_4.set(0)
            self.s_ch_bt_5.set(0)

            global total_food
            self.total_food = 0
            global item_quantity_price
            item_quantity_price.clear()
            self.total_x_e.delete(0, END)

            self.receipt_made.delete("1.0", END)
            messagebox.showinfo("Next Customer!", "Serve the next customer please!")
        except NameError:
            messagebox.showerror("error nothing to clear")

if __name__=='__main__':
    self.window = Tk()

    root = CashierView(self.window)
    self.window.mainloop()


import requests
from bs4 import BeautifulSoup

class nameToUid(object):
    def __init__(self, cookies):
        self.cookies = cookies

    def transfer(self, name):
        search_url = 'https://weibo.cn/search/user/?keyword={}'.format(name)
        response = requests.post(search_url, cookies=self.cookies)
        soup = BeautifulSoup(response.content, 'html.parser')
        url = ''
        for tr in soup.find_all('table'):
            for td in tr.find_all('a'):
                username =  td.get_text().strip()
                if username.lower() == name.lower():
                    url = td.get('href').split('?')[0]
                    break
        return url


'''
Author: Alexandre Borgmann
Date: 4/4/2020
URI Online Judge | 1113 Crescente e Decrescente

Leia uma quantidade indeterminada de duplas de valores inteiros X e Y.
Escreva para cada X e Y uma mensagem que indique se estes valores foram digitados em ordem crescente ou decrescente.
Entrada
A entrada contém vários casos de teste.
Cada caso contém dois valores inteiros X e Y.
A leitura deve ser encerrada ao ser fornecido valores iguais para X e Y.
Saída
Para cada caso de teste imprima “Crescente”, caso os valores tenham sido digitados na ordem crescente, caso contrário imprima a mensagem “Decrescente”.

Exemplo de Entrada
5 4
7 2
3 8
2 2
Exemplo de Saída
Decrescente
Decrescente
Crescente
'''
while True:
    linha = input("")
    campos = linha.split()

    x = int(campos[0])
    y = int(campos[1])
    if(x==y):
        break
    if(x>y):
        print("Decrescente")
    elif y>x:
        print("Crescente")


"""
maximum size subarray sum equals to k
Given an array nums and a target value k, find the maximum length of a
subarray that sums to k. If there isn't one, return 0 instead.
https://discuss.leetcode.com/topic/33259/o-n-super-clean-9-line-java-solution-with-hashmap
https://discuss.leetcode.com/topic/33331/clean-python-solution-one-pass
"""

def max_subarray_sumk(nums, k):
	if not nums:
		return 0
	map = {}
	sum, max = 0, 0
	for i, val in enumerate(nums):
		sum += val
		if sum == k:
			max = i+1
		elif sum-k in map:
			max = max(max, i-map.get(sum-k))
		if not map.get(sum):
			map[sum] = i
	return max


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

from __future__ import print_function
import codecs
import re
import sys
import xml.etree.ElementTree as ET

# Default transliteration framework.
# Uses ICU-like syntax of transliteration rules.

# TODO: 13-Dec-2016
# 1. Remove testing from this file.
# 2. Complete conversion into classes.
# 3. Determine how to use any transliteration rules from upload.

# Take a transliteration rule with phases.
# Extract shortcuts such as "$nondigits = [^\u1040-\u1049];
# clauses "\u107B > \u1039 \u1018 ;
# Separate the phases with "::Null;
# For each phase,
#   for each clause in phrase,
#     replace with result in all cases

# Globals
allPhases = None
debug_output = False

class Rule():
  # Stores one rule of a phase, including substitution information
  def __init__(self, pattern, substitution,
               context = None,
               after_context=None,
               before_reposition=None,
               after_reposition=None,
               id=0):
    self.id = id
    self.pattern = pattern
    self.re_pattern = re.compile(pattern, re.UNICODE)
    self.subst = substitution
    self.context = context
    self.after_context = after_context
    self.before_reposition = before_reposition
    self.after_reposition = after_reposition
    #? Store info on repositioning cursor

class Phase():
  # one phase of the transliteration spec
  def __init__(self, id=0):
    self.rules = []     # Old tuples
    self.RuleList = []  # Rule objects
    self.phase_id = id

  def fillRules(self, rulelist):
    global debug_output

    # set up pattern and subst value for each rule
    parts_splitter = re.compile('>|→')
    rule_pattern = re.compile(
      '(?P<context>[^\}]*)(?P<context_mark>\}?)(?P<after_context>[^>|→]*)\
[>→](?P<before_reposition>[^|]*)(?P<reposition_mark>\|?)(?P<after_reposition>[^;]*)'\
'(?P<final_semicolon>;?)(?P<comment>#?.*)')

    index = 0
    for rule1 in rulelist:
      # TODO: handle reposition with unescaped '|'
      resposition = rule1.find('|')
      # TODO: handle context with unescaped '{'
      context = rule1.find('}')

      # Extract parts for context, matching, and output with respositioning
      test_match = rule_pattern.match(rule1)
      context = None
      before_context = None
      after_context = None
      before_reposition = None
      after_reposition = None
      if test_match:
        groups = test_match.groupdict()
        if groups['reposition_mark']:
          after_reposition = re.sub(' ', '', uStringsFixPlaceholder(groups['after_reposition']))
        before_reposition = re.sub(' ', '', uStringsFixPlaceholder(groups['before_reposition']))
        if groups['context_mark']:
          after_context = re.sub(' ', '', uStringsFixPlaceholder(groups['after_context']))
        context = re.sub(' ', '', uStringsFixPlaceholder(groups['context']))

      rule1 = rule1.strip()
      rule = re.sub('\n', '', rule1)
      # Remove comment lines.
      # TODO: remove final semicolon
      if rule and rule[0] != '#':
        # TODO: Use matched results instead of simple split
        parts = parts_splitter.split(rule)
        pattern = re.sub(' ', '', parts[0]) # but don't remove quoted space
        try:
          subst = re.sub(' ', '', uStringsFixPlaceholder(parts[1]))
          newPair = (pattern, subst)
          self.rules.append(newPair)
          self.RuleList.append(Rule(pattern, subst,
                                    context=context,
                                    after_context=after_context,
                                    before_reposition=before_reposition,
                                    after_reposition=after_reposition,
                                    id=index))  # Rule objects
        except IndexError as e:
          print('Error e = %s. Phase %s, %d rule = %s' % (e, self.phase_id, index, rule1))
          print('  Rule = >>%s<< %d' % (rule, len(rule)))
          break
        except:
          e = sys.exc_info()[0]
          print('!! Error e = %s. Phase %s, %d rule = %s' % (e, self.phase_id, index, rule1))
          print('  Rule = >>%s<< %d characters' % (rule, len(rule)))
          break
      index += 1

  def getRules(self):
    # Old style rules
    return self.rules

  def getRuleList(self):
    # List of rule objects
    return self.RuleList

  def apply(self, intext):
    # takes each rule (pattern, substitute), applying to intext
    for rule in self.rules:
      result = re.sub(rule[0], rule[1], intext)
      intext = result
    return result

def extractShortcuts(ruleString):
  # Shortcuts are clauses of the form "$id = re;  What about a literal ";?
  # also remove comment lines and blank lines
  shorcutPattern = '(\$\w+)\s*=\s*([^;]*)'
  matches = re.findall(shorcutPattern, ruleString)

  shortcuts = {}
  for m in matches:
    shortcuts[m[0]] = m[1]

  # Remove shortcuts and comments from input.
  shorcutPattern = '\$(\w+)\s*=\s*([^;]*);\n'
  commentPattern = '#[^\n]*\n+'
  stripped = re.sub(shorcutPattern, '', ruleString)
  smaller = re.sub(commentPattern, "", stripped)
  return (shortcuts, smaller)

def expandShortcuts(shortcuts, inlist):
  newlist = inlist
  if shortcuts:
    for key, value in shortcuts.items():
      key = re.sub('\$', '\$', key)
      sublist = re.sub(key, value, newlist)
      newlist = sublist
  return newlist

def splitPhases(ruleString):
  phases = ruleString.split('::Null;')
  return phases

def testZawgyiConvert():
  z1 = 'ဘယ္'
  u1 = ConvertZawgyiToUnicode(z1)

def ConvertZawgyiToUnicode(ztext):
  # Run the phases over the data.
  out1 = ztext

  for phase in phases:
    # Apply each regular expression with global replacement;
    rules = phases.rules
    for rule in rules:
      # apply
      continue

def uStringsFixPlaceholder(string):
  return re.sub(u'\$(\d)', subBackSlash, string) # Fix the replacement patterns

def uStringsToText(string):
  pattern = r'\\u[0-9A-Fa-f]{4}'
  result = re.sub(pattern, decodeHexU, string)
  return re.sub(u'\$(\d)', subBackSlash, result) # Fix the replacement patterns

def uStringToHex(string):
  result = ''
  for c in string:
    result += '%4s ' % hex(ord(c))
  return result

def subBackSlash(pattern):
  return '\\' + pattern.group(0)[1:]

def decodeHexU(uhexcode):
  # Convert \uhhhh in input hex code match to Unicode character
  text = uhexcode.group(0)[2:]
  return unichr(int(text, 16)).encode('utf-8')

class Transliterate():
  # Accepting a set of rules, create a transliterator with phases,
  # ready to apply them.

  def __init__(self, raw_rules, description='Default conversion'):
    # Get the short cuts.

    self.description = description
    # Convert Unicode escapes to characters
    self.raw_rules = raw_rules  #.decode('unicode-escape')

    (self.shortcuts, self.reduced) = extractShortcuts(self.raw_rules)
    # Expand short cuts.
    self.expanded = expandShortcuts(self.shortcuts, self.reduced)

    self.phaseStrings = splitPhases(self.expanded)

    # Create the phase objects
    self.phaseList = []
    index = 0
    for phase in self.phaseStrings:
      self.phaseList.append(Phase(index))
      rule_lines = phase.split('\n')
      phase_rules = []
      for r in rule_lines:
        # TODO: Handle lines with semicolon as left side of rule
        rule_parts = r.rsplit(';', 1)
        if rule_parts[0]:
          phase_rules.append(rule_parts[0])
        # Omit empty lines
      self.phaseList[index].fillRules(phase_rules)
      index += 1

    # Range of current string, for passing information to substFunction.
    self.start = 0
    self.limit = 0

  def printSummary(self):
    # Print the statistics
    print('%4d raw rules' % len(self.raw_rules))
    print('%4d shortcuts ' % len(self.shortcuts))
    print('%4d reduced ' % len(self.reduced))
    print('%4d phaseStrings ' % len(self.phaseStrings))
    print('%4d phaseList ' % len(self.phaseList))
    index = 0
    for phase in self.phaseList:
      print('  %3d rules in phase %2d' % (len(self.phaseList[index].rules), index))
      index += 1

  def getSummary(self):
    # Print the statistics
    result = {
      'raw rules': len(self.raw_rules),
      'shortcuts': len(self.shortcuts),
      'reduced': len(self.reduced),
      'phaseStrings': self.phaseStrings,
      'phaseList': len(self.phaseList)
    }
    return result

  def substFunction(matchObj):
    return 'UNFINISHED'

  def applyPhase(self, index, instring,  debug):
    # It should do:
    #  a. Find rule that matches from the start
    #  b. if a match, substitute text and move start as required
    # until start >= limit

    # For each rule, apply to instring.
    self.start = 0
    self.limit = len(instring) - 1
    ruleList = self.phaseList[index].RuleList

    currentString = instring
    matchObj = True
    while self.start <= self.limit:
      # Look for a rule that matches
      ruleIndex = 0
      matchObj = None
      self.limit = len(currentString) - 1

      foundRule = None
      for rule in ruleList:
        # Try to match each rule at the current start point.
        re_pattern = rule.re_pattern

        try:
          # look at the current position.
          matchObj = re_pattern.match(currentString[self.start:])
          # matchObj = re.match(rule.pattern, currentString[self.start:])
        except TypeError as e:
          print('***** TypeError EXCEPTION %s in phase %s, rule %s: %s -> %s' % (e,
            index, ruleIndex, uStringToHex(rule.pattern), uStringToHex(rule.subst)))
        except:
          e = sys.exc_info()[0]
          print('***** EXCEPTION %s in phase %s, rule %s: %s -> %s' % (e,
            index, ruleIndex, uStringToHex(rule.pattern), uStringToHex(rule.subst)))

        if matchObj:
          # Do just one substitution!
          foundRule = True

          # Size of last part of old string after the replacement
          cSize = len(currentString) - matchObj.end(0) - self.start  # Last part of old string not matched
          if not rule.before_reposition:
            substitution = rule.after_reposition
          else:
            # TODO: Handle case of before and after substitutions.
            substitution = rule.subst
          if not substitution:
            substitution = ''
          try:
            outstring = re.sub(rule.pattern, substitution, currentString[self.start:], 1)
          except TypeError as e:
            outstring = '&*&*& %s &*&*&' % substitution
          # Try to advance start.
          newString = currentString[0:self.start] + outstring
          self.limit = len(newString) - 1

          # Figure out the new start and limit.
          # New: don't advance if all the text is after the reposition mark.
          if not rule.before_reposition:
            self.start = self.start  # Unchanged
          else:
            # TODO: Find size of substitution of before_context
            self.start = self.limit - cSize + 1
          currentString = newString
          break
        ruleIndex += 1

      # Rule loop complete
      if not foundRule:
        # Increment position since no rule matched
        self.start += 1

    return currentString

  def transliterate(self, instring, debug=None):
    # Apply each phase to the incoming string or string list.

    if type(instring) == list:
      # Repeat on each list item.
      return [self.transliterate(item, debug) for item in instring]

    if type(instring) != bytes and type(instring) != str:
      return 'Error: type = %s. String or Unicode required' % type(instring)

    for phaseIndex in range(len(self.phaseList)):
      outstring = self.applyPhase(phaseIndex, instring, debug)
      instring = outstring

    # ?? .decode('unicode-escape')
    return outstring

# Derived class that takes an XML file from CLDR and create a transliterator from it
class TranslitXML(Transliterate):
  def __init__(self, file_path):
    self.path = file_path
    self.tree = None
    self.root = None
    self.rules_text = None
    self.transforms = None
    self.openFile()
    self.parseXmlTree()

    super(TranslitXML, self).__init__(self.rules_text)

    return

  def openFile(self):
    self.tree = ET.parse(self.path)
    self.root = self.tree.getroot()
    return

  def parseXmlTree(self):
    if self.root:
      # Look for the rules and get into proper shape
      self.transforms = self.root.find('transforms')
      self.transform = self.transforms.find('transform')
      text = self.transform.find('tRule').text
      #text = text.encode('unicode-escape')
      in_str = text.encode('unicode-escape')  # bytes with all chars escaped (the original escapes have the backslash escaped)
      in_str = in_str.replace(b'\\\\u', b'\\u')  # unescape the \
      text = in_str.decode('unicode-escape')
    self.rules_text = text
      # self.rules_text = self.transform.find('tRule').text.decode( 'unicode-escape' )
    return


import sys
import heapq

''' 다익스트라 최단 경로 알고리즘
양수 가중치가 있는 (= 간선의 w가 서로 다른) 그래프에서
시작 노드로부터 다른 모든 노드 까지의 최단 거리를 구하는 알고리즘
=> 한 번 반복할 때마다 노드 하나의 최단 경로가 확정되는 성질 (배낭)

1. 모든 노드까지의 거리는 무한대
2. 시작 노드 start까지의 거리는 0
=> 최솟값 선택을 반복 => 힙 자료형 사용
반 | 3. 힙에서 거리가 최소인 노드를 꺼냄 => 거리 확정
복 | 4. 그 노드로부터 인접한 노드들의 거리를 갱신
'''

M, N = map(int, sys.stdin.readline().strip().split())
board = [list(map(int, sys.stdin.readline().strip()))
        for _ in range(N)]
dis = [[10**9] * M for _ in range(N)]

def dijkstra(start_y, start_x):
    dis[start_y][start_x] = 0
    h = [(start_y, start_x, dis[start_y][start_x])]

    while h:
        y, x, distance = heapq.heappop(h)

        if distance > dis[y][x]:
            continue

        for dy, dx in [(1,0),(-1,0),(0,1),(0,-1)]:
            if 0<=y+dy<N and 0<=x+dx<M:
                if dis[y+dy][x+dx] > distance+board[y+dy][x+dx]:
                    heapq.heappush(h, (y+dy, x+dx, distance+board[y+dy][x+dx]))
                    dis[y+dy][x+dx] = distance+board[y+dy][x+dx]

dijkstra(0,0)
print(dis[N-1][M-1])


#coding=utf-8
	#################################################################################################
	#												#
	#	Bu dosyada tüm modellerde kullanacağımız ortak işlem, parametre ve fonksiyonları	#
	#	Ortakislemler sınıfında tanımlıyoruz. Diğer model sınıflarına bu sınıfı miras		#
	#	alma yoluyla aktarıyoruz.								#
	#						M. Mutlu YAPICI  -  11.08.2018			#
	#												#
	#################################################################################################

import numpy as np
import time
import scipy
from keras.preprocessing.image import array_to_img, img_to_array, load_img
from modules.dataPreprocess import BinaryResimYukle, PILResimYukle, ResmiYenidenBoyutlandir, ResimSinirlariniBelirle,YeniResimSinirlariniBelirle, CokluImg2Array, CokluCrop, PILResmiYenidenBoyutlandir, ImzaVeritabaniniYukle,ImzaVeritabaniniYukleSIAMES, VeritabaniniDosyayaKaydetHDF5, VeritabaniniDosyadanYukle, VeritabaniniDosyayaKaydet,IzgaraOzniteligi

from keras.applications.imagenet_utils import decode_predictions
from keras.applications.imagenet_utils import preprocess_input

#### Aşağıda Dogrulama Yöntemlerinde elde edilecek doğrulama verilerini nesne halinde göndermek için
class DogrulamaElemanlari:
	def __init__(self, DG, YN, FAR, FRR, TPR, FPR,F1,RECALL,PRECISION,TNR,AER):
		self.DogruSayisi = DG
		self.YanlisSayisi = YN
		self.F1_score=F1
		self.FAR = FAR
		self.FRR = FRR
		self.TPR = TPR
		self.FPR = FPR
		self.RECALL=RECALL
		self.PRECISION=PRECISION
		self.TNR=TNR
		self.AER=AER

class Ortakislemler:
	def __init__(self):
		self.batch_zaman_fark =0
		self.batc_oncekizaman=0

	def veriYukle(self,durum='rastgele',kisi_sayisi=1, resimEn = 500,resimBoy=500,modelSecimi='Normal'):
		"""
		#kisi_sayisi=1
		gercekImzaSayisi=(24*kisi_sayisi)
		sahteImzaSayisi = (30*kisi_sayisi)
		EKGIS=(15*kisi_sayisi) #Eğitimde Kullanılacak Gerçek İmza Sayısı
		EKSIS=(15*kisi_sayisi) #Eğitimde Kullanılacak Sahte İmza Sayısı
		TKGIS=gercekImzaSayisi-EKGIS #Testte Kullanılacak Gerçek İmza Sayısı
		TKSIS=sahteImzaSayisi-EKSIS #Testte Kullanılacak Sahte İmza Sayısı
		"""
		#gercekImzaSayisi = (318 * kisi_sayisi)
		#sahteImzaSayisi = (388 * kisi_sayisi)
		veriGercek=24
		veriSahte=30
		gercekImzaSayisi = (veriGercek * kisi_sayisi)
		sahteImzaSayisi = (veriSahte * kisi_sayisi)
		EKGIS = (15 * kisi_sayisi)  # Eğitimde Kullanılacak Gerçek İmza Sayısı
		EKSIS = (15 * kisi_sayisi)  # Eğitimde Kullanılacak Sahte İmza Sayısı
		TKGIS = gercekImzaSayisi - EKGIS  # Testte Kullanılacak Gerçek İmza Sayısı
		TKSIS = sahteImzaSayisi - EKSIS  # Testte Kullanılacak Sahte İmza Sayısı

		## Resim boyutları yükseklik ve en
		#resimBoy, resimEn = 500, 500

		#Verileri Yükleyelim
		if(modelSecimi=='Normal'): ### 	EĞER NORMAL MODELE GÖRE YAPACAKSAK EEĞİTİM VERİLERİ SAHTE VE GERÇEK KARIŞIK GELSİN

			#GVeri=ImzaVeritabaniniYukle("firmasSINTESISmanuscritas","c-*.jpg", resimEn, resimBoy, gercekImzaSayisi, 1, 10, 255,  True, 255, True)
			##Gerçek verileri Dosyaya Kaydedelim
		#Yüksek veri boyutunda bu dosya tipine kayıt başarısız	VeritabaniniDosyayaKaydet("GVerimmm_"+str(kisi_sayisi), GVeri[0], False)#VeritabaniniDosyayaKaydet(dosyaAdi, veri, ekranaYaz=False):
		#	veriSekli = (gercekImzaSayisi, resimBoy, resimEn, 1)
		#	VeritabaniniDosyayaKaydetHDF5("GVeri_" + str(kisi_sayisi) + ".hdf5", GVeri[0], veriSekli)  ##VeritabaniniDosyayaKaydetHDF5(dosyaAdi, veri, veriSekli):
		#	print("#####################################    GERÇEK VERİLER BİTTİ SAHTELERİ YÜKLEYELİM    ####################################")

			#SVeri=ImzaVeritabaniniYukle("firmasSINTESISmanuscritas","cf*.jpg", resimEn, resimBoy, sahteImzaSayisi, 1, 10, 255,  True, 255, True)
		#	sveriSekli = (sahteImzaSayisi, resimBoy, resimEn, 1)
		#	VeritabaniniDosyayaKaydetHDF5("SVeri_" + str(kisi_sayisi) + ".hdf5", SVeri[0],sveriSekli)  ##VeritabaniniDosyayaKaydetHDF5(dosyaAdi, veri, veriSekli):
		#Yüksek veri boyutunda bu dosya tipine kayıt başarısız	VeritabaniniDosyayaKaydet("SVeri_" + str(kisi_sayisi), SVeri, False)  # VeritabaniniDosyayaKaydet(dosyaAdi, veri, ekranaYaz=False):

		#ImzaVeritabaniniYukle(kokDizin, dosyaAdi, yeniEn, yeniBoy, yuklenecekResimSayisi=0, dizinDerinligi=0,tolerans=0, arkaRenk=255, orjinallikKorunsunMu=False, arkaRenk2=255, ekranaYaz=False):
			##GPDS VERİTABANI
			#GVeri = ImzaVeritabaniniYukle("firmasSINTESISmanuscritas/751", "c-*.jpg", resimEn, resimBoy, gercekImzaSayisi, 0, 10, 255, True, 255,  True)
			#SVeri = ImzaVeritabaniniYukle("firmasSINTESISmanuscritas/751", "cf*.jpg", resimEn, resimBoy, sahteImzaSayisi, 0, 10, 255, True, 255,  True)

			##MCYT VERİTABANI
			#GVeri = ImzaVeritabaniniYukle("MCYT/0098", "*v*.bmp", resimEn, resimBoy, gercekImzaSayisi, 0, 10, 255, True, 255, True)
			#SVeri = ImzaVeritabaniniYukle("MCYT/0098", "*f*.bmp", resimEn, resimBoy,sahteImzaSayisi, 0, 10, 255, True, 255, True)

			##BİZİM YARATTIĞIMIZ HOCALALRIN VERİTABANI
			GVeri = ImzaVeritabaniniYukle("e_bu_fake/renkli/NT", "c-*.jpg", resimEn, resimBoy, gercekImzaSayisi, 0, 10, 255, True, 255, True)
			SVeri = ImzaVeritabaniniYukle("e_bu_fake/renkli/NT", "cf*.jpg", resimEn, resimBoy, sahteImzaSayisi, 0, 10, 255, True, 255, True)

			X_train, Y_train, X_test, Y_test = [[], []], [], [[], []], []
			if(durum=='rastgele'):
				#Eğer Verileri Rastgele Oluşturacaksak
				#nGVeri=np.asarray(GVeri)
				#nSVeri=np.asarray(SVeri)

				print('RASTGELE   ----------------> '+str(kisi_sayisi))
				#GERCEK ve SAHTE Verilerin İndekslerini Oluşturalım
				Gind=list(range(0,(gercekImzaSayisi)))
				Sind = list(range(0,(sahteImzaSayisi)))

				# GERCEK ve SAHTE Verilerin İndekslerini  SUFFLE İle Karıştıralım Böylece RANDOM Gelmiş Olacaklar
				np.random.shuffle(Gind)
				np.random.shuffle(Sind)

				#Gerçek Eğitim Verilerini Aldık Rastgele
				for a in range(EKGIS):
					inn=Gind.pop(0)
					X_train[0].append(GVeri[0][inn])#X_train in 0 ında verileri (resimler) 1 inde gerçek mi sahtemi oldukları var
					X_train[1].append([1, 0])  # Gerçek veriler 1 0
					Y_train.append([1, 0])#Gerçek veriler 1 0

				#Sahtelerden de rastgele Eğitim verielerini alalım
				for a in range(EKSIS):
					inn=Sind.pop(0)
					X_train[0].append(SVeri[0][inn])#X_train in 0 ında verileri (resimler) 1 inde gerçek mi sahtemi oldukları var
					X_train[1].append([0, 1])  # Sahte veriler 0 1
					Y_train.append([0,1])#Sahte veriler 0 1

				#ŞİMDİDE TEST VERİLERİNİ ALALIM TEST VERİLERİ EĞİTİMDEN ARTA KALANLAR OLACAK
				for a in range(TKGIS):
					inn = Gind.pop(0)
					X_test[0].append(GVeri[0][inn])  # X_test in 0 ında verileri (resimler) 1 inde gerçek mi sahtemi oldukları var
					X_test[1].append([1, 0])  # Gerçek veriler 1 0
					Y_test.append([1, 0])  # Gerçek veriler 1 0

				for a in range(TKSIS):
					inn = Sind.pop(0)
					X_test[0].append(SVeri[0][inn])  # X_train in 0 ında verileri (resimler) 1 inde gerçek mi sahtemi oldukları var
					X_test[1].append([0, 1])  # Sahte veriler 0 1
					Y_test.append([0, 1])  # Sahte veriler 0 1
			else:
				##X_train X_test Y_train Y_test Verilerini Yaratalım: Senaryoya göre 24 tane geçek verinin ilk 15 i eğitim de on 9 u testte kullanılacak ve yine Sahte verilerinin Son 15 i eğitimde ilk 15 i de testte kullanılacak.
				GercekX_trn=GVeri[0][0:EKGIS]
				GercekX_trn=np.asarray(GercekX_trn)
				GercekX_trn.shape
				SahteX_trn=SVeri[0][TKSIS:]
				SahteX_trn=np.asarray(SahteX_trn)
				SahteX_trn.shape
				X_train=np.concatenate((GercekX_trn,SahteX_trn),axis=0)
				X_train.shape

				GercekX_test=GVeri[0][EKGIS:]
				GercekX_test=np.asarray(GercekX_test)
				GercekX_test.shape
				SahteX_test=SVeri[0][0:TKSIS]
				SahteX_test=np.asarray(SahteX_test)
				SahteX_test.shape
				X_test=np.concatenate((GercekX_test,SahteX_test),axis=0)
				X_test.shape

				GercekY_trn=GVeri[1][0:EKGIS]
				GercekY_trn=np.asarray(GercekY_trn)
				GercekY_trn.shape
				SahteY_trn=SVeri[1][TKSIS:]
				SahteY_trn=np.asarray(SahteY_trn)
				SahteY_trn.shape
				Y_train=np.concatenate((GercekY_trn,SahteY_trn),axis=0)
				Y_train.shape

				GercekY_test=GVeri[1][EKGIS:]
				GercekY_test=np.asarray(GercekY_test)
				GercekY_test.shape
				SahteY_test=SVeri[1][0:TKSIS]
				SahteY_test=np.asarray(SahteY_test)
				SahteY_test.shape
				Y_test=np.concatenate((GercekY_test,SahteY_test),axis=0)
				Y_test.shape
			return [GVeri, SVeri, X_train, X_test, Y_train, Y_test, resimBoy, resimEn]
		elif(modelSecimi=='SIAMES'): ###	EĞER MODEL SEÇİMİ SIAMES İSE OZMAN EĞİTİM VE TEST VERİLERİNİ SAHTE VE GERÇEK DİYE GRUP HALİNDE GÖNDERELİM
			# ImzaVeritabaniniYukleSIAMES(kokDizin, dosyaAdi, yeniEn, yeniBoy, yuklenecekResimSayisi=0, dizinDerinligi=0,tolerans=0, arkaRenk=255, orjinallikKorunsunMu=False, arkaRenk2=255, ekranaYaz=False):
			TVeri = ImzaVeritabaniniYukleSIAMES("firmasSINTESISmanuscritas", "*.jpg", resimEn, resimBoy, (54 * kisi_sayisi), 1, 10, 255, True, 255, True) ## tüm veriler
			egitim_grubu=[[],[]] ### Eğitim grubunda sahteler ve gerçekler kişi bazlı ayrılacak
			test_grubu=[[],[]] ### Test grubunda sahteler ve gerçekler kişi bazlı ayrılacak

			EKGIS = 15
			EKSIS = 15
			TKGIS = 9
			TKSIS = 15
			#### Her Bireyden Eğitime İmza Alalım
			for k in range(kisi_sayisi):
				####her kişiden eğitime 15 gerçek 15 sahte alalım
				egitim_grubu[0].append([]) #### Eğitim Grubunun Gerçeğine Yeni Kişi Ekledik
				egitim_grubu[1].append([])  #### Eğitim Grubunun Sahtesine Yeni Kişi Ekledik
				test_grubu[0].append([])  #### Test Grubunun Gerçeğine Yeni Kişi Ekledik
				test_grubu[1].append([])  #### Test Grubunun Sahtesine Yeni Kişi Ekledik

				#Rastgele seçelim
				# GERCEK ve SAHTE Verilerin İndekslerini Oluşturalım
				Gind = list(range(0, (24)))
				Sind = list(range(0, (30)))

				# GERCEK ve SAHTE Verilerin İndekslerini  SUFFLE İle Karıştıralım Böylece RANDOM Gelmiş Olacaklar
				np.random.shuffle(Gind)
				np.random.shuffle(Sind)

				for a in range(EKGIS): ###kişiye ait Eğitimde kullanılacak gerçek imzalar
					inn=Gind.pop(0)
					egitim_grubu[0][k].append(TVeri[k][0][inn])

				for a in range(TKGIS): ###kişiye ait Testte kullanılacak Kalan gerçek imzalar
					inn=Gind.pop(0)
					test_grubu[0][k].append(TVeri[k][0][inn])

				for a in range(EKSIS):  ###kişiye ait Eğitimde kullanılacak SAHTE imzalar
					inn = Sind.pop(0)
					egitim_grubu[1][k].append(TVeri[k][1][inn])

				for a in range(TKSIS):  ###kişiye ait Testte kullanılacak Kalan SAHTE imzalar
					inn = Sind.pop(0)
					test_grubu[1][k].append(TVeri[k][1][inn])

			return [TVeri, egitim_grubu, test_grubu, resimBoy, resimEn]
############ VERİ YÜKLEME BURAYAAAAAAAAAAAA KADAR ################

################ 	RASTGELE VERİ, ÜRETME ########################
#///SİAMES İÇİN GRUPLAR HALİNDE VERİ ÜRETİYOR
	def gen_random_batchSIAMES(self,tumVeri, kisiSayisi, kisiBasiOrnekimza, anchor='Resim'):
		A_verisi, B_verisi, Anchor, cikti = [], [], [], []
		tumKisiIndeksleri = list(range(len(tumVeri[0])))  ### Gelen veri grubunda bulunan kişilerin indexleri

		for i in range(kisiSayisi):  ####her bir kişiden A ve B için veri alacağız Burada A gerçek (Positive) B sahte (Negative)
			kisiInd = np.random.choice((tumKisiIndeksleri))  ## tüm kişiler içerisinden rastgele birini seçelim
			tumImzaInd = list(range(len(tumVeri[0][0])))  ### kişinin tüm gerçek imzalarının indisleri
			for j in range(kisiBasiOrnekimza):  #### tüm imzalar arasından imza sayısı kadar seçeceğiz
				imzaInd = np.random.choice((tumImzaInd))  ## tüm imzaların içerisinden rastgele birini seçelim
				A_verisi += [tumVeri[0][kisiInd][imzaInd]]  ### Gerçek imza tamam şimdi birde sahtesini seçelim
				B_verisi += [tumVeri[1][kisiInd][imzaInd]]  ### birde sahtesini seçelim
				imzaInd = np.random.choice((tumImzaInd))  ## tüm imzaların içerisinden rastgele birini tekrar seçelim çünkü bunu ANCHOR seçmede kullanacağım
				Anchor += [tumVeri[0][kisiInd][imzaInd]]
				cikti += [kisiInd]  ### imza hangi kişiye ait

		return np.stack(A_verisi, 0), np.stack(B_verisi, 0), np.stack(Anchor, 0), np.stack(cikti, 0)

#n///////////////NORMAL VERİLER İÇİN RASTGELE VERİ ÜRETELİM

	def get_random_batches(self,tumVeriX,tumVeriY,verisayisi,ayri=False):
		uretilenX, uretilenY = [],[]
		print("ACEBA YENI EPOCH GECTIMI")
		while 1:
			tumVeriIndeksleri = list(range(tumVeriX.shape[0]))  ### Gelen veri grubunda bulunan indexleri alalım
			np.random.shuffle(tumVeriIndeksleri)### tüm indisleri karıştırdık
			#print("Veri Şekli = "+str(tumVeriX.shape))
			#print(tumVeriIndeksleri)
			for i in range(verisayisi):  ####veriSayisi kadar veriyi gönderelim
				Ind = tumVeriIndeksleri[i]  ## tüm veriler içerisinden rastgele birini seçelim
				#print("IND =>>>>>>>>>>>>>>><  " + str(Ind))
				uretilenX+=[tumVeriX[Ind]]
				uretilenY += [tumVeriY[Ind]]

			self.batch_zaman_fark = time.time() - self.batc_oncekizaman
			self.batc_oncekizaman = time.time()
			print("ZAMAN FARKI = ",self.batch_zaman_fark," ---> ",uretilenX.__len__())
			if(ayri==True):
				return  (np.stack(uretilenX, 0), np.stack(uretilenY, 0))
			else:
				yield (np.stack(uretilenX, 0), np.stack(uretilenY, 0))
			uretilenX, uretilenY = [], []

# n///////////////TENSORFLOWDA NORMAL VERİLER İÇİN RASTGELE VERİ ÜRETELİM
## TENSORFLOWDA Veriler Veri ve Etiket olarak ayrı ayrı ve veriler tek boyutlu dizi halinde gidiyor
	def get_random_batchesTensorFlow(self, tumVeriX, tumVeriY, verisayisi):
		uretilenX, uretilenY = [], []
		while 1:
			tumVeriIndeksleri = list(range(tumVeriX.shape[0]))  ### Gelen veri grubunda bulunan indexleri alalım
			np.random.shuffle(tumVeriIndeksleri)  ### tüm indisleri karıştırdık
			# print("Veri Şekli = "+str(tumVeriX.shape))
			# print(tumVeriIndeksleri)
			for i in range(verisayisi):  ####veriSayisi kadar veriyi gönderelim
				Ind = tumVeriIndeksleri[i]  ## tüm veriler içerisinden rastgele birini seçelim
				# print("IND =>>>>>>>>>>>>>>><  " + str(Ind))

				#### Resmi tensorflow için tek boyutlu diziye çevirelim
				yeniVeri=tumVeriX[Ind].reshape(1,-1)
				uretilenX += [yeniVeri]
				uretilenY += [tumVeriY[Ind]]

			return (np.stack(uretilenX, 0), np.stack(uretilenY, 0))
			uretilenX, uretilenY = [], []

# n///////////////GAN VERİLER İÇİN RASTGELE VERİ ÜRETELİM
		## burada aynı tür resme ait orjinal boyut ve küçültülmüş örnekler dönecek
	def get_random_batchesGAN(tumVeriX, verisayisi,kucultme_orani):
		orjinal, kucuk = [], []
		h, w = tumVeriX[0].shape[0],tumVeriX[0].shape[1]
		kucuk_boy, kucuk_en = int(h / kucultme_orani), int(w / kucultme_orani)
		tumVeriIndeksleri = list(range(len(tumVeriX)))  ### Gelen veri grubunda bulunan indexleri alalım
		np.random.shuffle(tumVeriIndeksleri)  ### tüm indisleri karıştırdık

##### Veri Çoğaltmak için başka bir yol deniyorum aynı özelliklerde başka resim gönderelim
		tumVeriIndeksleri_EK = list(range(len(tumVeriX)))  ### Gelen veri grubunda bulunan indexleri alalım
		np.random.shuffle(tumVeriIndeksleri_EK)  ### tüm indisleri karıştırdık

		for i in range(verisayisi):  ####veriSayisi kadar veriyi gönderelim
			Ind1 = tumVeriIndeksleri[i]  ## tüm veriler içerisinden rastgele birini seçelim
			#a=array_to_img(tumVeriX[Ind]).convert('RGB')
			a=array_to_img(tumVeriX[Ind1])
			orjinal += [img_to_array(a)]##resimGREY di üç kanal lazım o nedenle önce RGB donusturddum sonra tekrar arraye
			#kucuk += [np.reshape(scipy.misc.imresize(a, (kucuk_en, kucuk_boy)),(kucuk_en, kucuk_boy,3))]

			Ind = tumVeriIndeksleri_EK[i]
			while True:#aynı veri olmasın diye
				if (Ind1 !=Ind):
					break
				np.random.shuffle(tumVeriIndeksleri_EK)  ### tüm indisleri karıştırdık
				Ind = tumVeriIndeksleri_EK[0]  ## tüm veriler içerisinden rastgele birini seçelim

			#a=array_to_img(tumVeriX[Ind]).convert('RGB')
			a=array_to_img(tumVeriX[Ind])
			kucuk += [img_to_array(a)]##resimGREY di üç kanal lazım o nedenle önce RGB donusturddum sonra tekrar arraye

		orjinal = np.array(orjinal) / 127.5 - 1.
		kucuk = np.array(kucuk) / 127.5 - 1.

		return np.stack(orjinal, 0), np.stack(kucuk, 0)

###########################################################################

	#dizi verisi halinde gelen Gri resimleri Renkli ye çevirme Sadece 1 kanaldan 3 kanal yapacağız
	def Gray2RGB(self,resimler):
		yeniRGB = []
		for i in range(resimler.__len__()):  ####veriSayisi kadar veriyi gönderelim
			a = array_to_img(resimler[i]).convert('RGB')
			yeniRGB += [img_to_array(a)]  ##resimGREY di üç kanal lazım o nedenle önce RGB donusturddum sonra tekrar arraye

		return  yeniRGB

################3	DOĞRULAMA YÇNTEMLERİ ############################################
	# False_reject_rate(FRR) = FN / (TP + FN) = FN / P = 1 - TPR
	# False_accept_rate(FAR) = C / (C + D) = FP / (FP + TN) = FPR
	# True_positive_rate(TPR) = A / (A + B) = TP / (TP + FN) = TP / P
	# False_positive_rate(FPR) = fallout = C / (C + D) = FP / (FP + TN) = FAR = 1 - SPC
# False Positive, False Negative, True Positive, True Negative, Dogru, Yanlış
	#testVerisi shape = 120, 300,300, 1 gibi
	# eğer CallBack True ise model.fit içerisinden callback ile çağırılıyordur bunedenle return değeri true olacak değilse object olacak
	def dogtulamaYontemleri(self,model,XtestVerisi,YtestVerisi,CallBack=False,DenseMi=False):
		self.model=model
		self.XtestVerisi=XtestVerisi
		self.YtestVerisi=YtestVerisi

		self.FP = 0.
		self.FN = 0.
		self.TP = 0.
		self.TN = 0.
		self.DG = 0
		self.YN = 0
		self.F1=0
		self.Precision=0
		self.Recall=0
		self.AER=0
		self.FRR =0
		self.FAR =0
		self.TPR =0
		self.FPR =0
		self.TNR =0

		if (DenseMi == False):
			self.p = self.model.predict(self.XtestVerisi, verbose=1)[0]
		else:
			self.p = self.model.predict(self.XtestVerisi, verbose=1)

		for i in range(self.YtestVerisi.shape[0]):
			if (self.YtestVerisi[i][0] == 1):  # eğer imza GERÇEKSE
				if (self.p[i][0] > self.p[i][1]):  # Eğer İmzaya Gerçek Demişsek
					self.TP += 1
					self.DG += 1
				elif (self.p[i][0] < self.p[i][1]):  # Eğer İmzaya Sahte Demişsek
					self.FN += 1
					self.YN += 1
			elif (self.YtestVerisi[i][0] == 0):  # eğer imza SAHTEYSE
				if (self.p[i][0] > self.p[i][1]):  # Eğer İmzaya Gerçek Demişsek
					self.FP += 1
					self.YN += 1
				elif (self.p[i][0] < self.p[i][1]):  # Eğer İmzaya Sahte Demişsek
					self.TN += 1
					self.DG += 1

	# False_reject_rate(FRR) = FN / (TP + FN) = FN / P = 1 - TPR
		if(self.FN.__float__()>0):
			self.FRR = self.FN.__float__() / (self.TP.__float__() + self.FN.__float__())

	# False_accept_rate(FAR) = C / (C + D) = FP / (FP + TN) = FPR
		if (self.FP.__float__() > 0):
			self.FAR = self.FP.__float__() / (self.FP.__float__() + self.TN.__float__())

	# True_positive_rate(TPR) = A / (A + B) = TP / (TP + FN) = TP / P
		if (self.TP.__float__() > 0):
			self.TPR = self.TP.__float__() / (self.TP.__float__() + self.FN.__float__())

	# False_positive_rate(FPR) = fallout = C / (C + D) = FP / (FP + TN) = FAR = 1 - SPC
		if (self.FP.__float__() > 0):
			self.FPR = self.FP.__float__() / (self.FP.__float__() + self.TN.__float__())

	# True Negative Rate (TNR) = Specifity =  TN / (FP + TN) = FAR = 1 - SPC
		if (self.TN.__float__() > 0):
			self.TNR = self.TN.__float__() / (self.FP.__float__() + self.TN.__float__())

	# F1 SCORU
		if (self.TP.__float__() > 0):
			self.F1 =2*self.TP.__float__()  / (2*self.TP.__float__()  + self.FP.__float__()  +self.FN.__float__())

	#recall rcl= TP/(TP+FN)
		if (self.TP.__float__() > 0):
			self.Recall=self.TP.__float__()  / (self.TP.__float__()  +self.FN.__float__())

	#precision Precision=TP/(TP+FP)
		if (self.TP.__float__() > 0):
			self.Precision=self.TP.__float__() / (self.TP.__float__() + self.FP.__float__())

	#Average Error Rate AER = (FAR + FRR) / 2
		self.AER = (self.FAR.__float__()  +self.FRR.__float__())/2

		print("Precision "+str(self.Precision)+" \nRecall "+str(self.Recall)+" \nF1 "+str(self.F1) )
		print("FRR " + str(self.FRR) + " \nFAR " + str(self.FAR) + " \nFPR " + str(self.FPR))
		print( "FP = "+str(self.FP.__float__())+" TP = " +str(self.TP.__float__())+"\nFN = "+str(self.FN.__float__())+" TN = " +str(self.TN.__float__()))

		#print("TP "+str(self.TP)+" \nTN "+str(self.TN)+" \nFP "+str(self.FP)+" \nFN "+str(self.FN) )

		f = DogrulamaElemanlari(self.DG,self.YN, self.FAR,self.FRR,self.TPR,self.FPR,self.F1,self.Recall,self.Precision,self.TNR ,self.AER )
		if(CallBack==True):
			return
		else:
			return f

###########################################################################

	### Gelen resmin Gerçek mi Sahtemi olduğunu gönderiyor, Test Edebilmek için Gerçek imza verilerinin olduğu resim dizisi GVeri yi göndermemiz gerekiyor
	def resimTuru(self,resim, GVeriler):
		indeks = -1
		bo = False
		for i in GVeriler[0]:
			n = i / 255.
			indeks+=1
			bo = np.allclose(resim, n)
			if (bo == True):
				print(indeks, " Verisi Gerçek")
				break

		if (bo == False):
			print(indeks, " Verisi Sahte")
		return [indeks,bo]

	def tahmin(x,model):
		x = np.expand_dims(x, axis=0)   #Verinin şeklini 210,300,1 den 1, 210,300,1 a çevirmek için
		return model.predict(x)

	### EĞİTİĞİMİZ MODELİ DAHA SONRA KULLANMAK İÇİN DOSYAYA KAYDEDELİM ###
	def EgitimVerileriniKaydet(yol,model):
		model.save(yol)
		print("Modele Ait Eğitim Verileri "+yol+" Dosyasına Kaydedildi")

	##########		VERİLERİ MATPLOTLIB KUTUPHANESİ İLE GÖRSELLEŞTİRME	#############
	"""Modeli, Test verilerini, ekrana bastırılacak resim sayısını en boy oranlarını gönderdiğimizde 2 sınıfa göre gerçek mi sahtemi olduğunu ve doğru mu yanlışmı tahmin ettiğimizi buluyor"""
import math as math
def GorselTahmin(modelim,X_testler,Y_testler,TSay = 2,en=30,boy=30,DenseMi=False):
	global axi
	label = ['Gerçek', 'Sahte']
	####PREDICTIONDA İKİ FARKLI SONUÇ VAR MODLİN DENSENET OLMASINA GÖRE
	if (DenseMi == False):
		p = modelim.predict(X_testler, verbose=1)[0]
	else:
		p = modelim.predict(X_testler, verbose=1)

	satir, sutun=1,2
	if(TSay>1):
		sutun=(int)(math.ceil(math.sqrt(TSay)))
		satir =(int)(math.sqrt(TSay))

	fgr, ax = plt.subplots(satir,sutun, figsize=(en, boy))

	left = 0
	bottom = 0

	#Gelen Verielrden Rastgele Alalım
	m = np.arange(X_testler.shape[0])
	np.random.shuffle(m)

	for i, axi in enumerate(ax.flat):
		if(i<TSay):
			img=X_testler[m[i]].astype(np.float32) #veriyi plot ile yazmak için tipini float32 yapmalı
			img=img[:,:,0] #veriyi plot ile yazmak için boyutu [224 224 1] den [224 244] yapmalı
			axi.imshow(np.squeeze(img), cmap='binary')
			# ek=unicode(str(label[(int)(Y_testler[m[i]][1])]), 'utf-8')##python 2.x
			#ek = str(label[(int)(Y_testler[m[i]][1])]).encode('utf-8')  ##python 3.x
			ek=str(label[(int)(Y_testler[m[i]][1])])
			print('---------------------------------------- '+ek)
			axi.set_title(ek+' -> '+ str(m[i]),fontsize=12,color="blue", fontweight='bold')
			metin=""
			for n in range(2):
				metin+=(' |'+ (u'\u2589' * int(p[m[i], n] * 10)) + ' ' + label[n] + ' {:.5f}%'.format(p[m[i], n] * 100)+'\n'  )

			print('---------------------------------------- ' + metin)

			renk = "red"
			if(((p[m[i], 0] > p[m[i], 1]) and ((Y_testler[m[i]][0])==1)) or ((p[m[i], 0] < p[m[i], 1]) and ((Y_testler[m[i]][0])==0))):
				renk="green"##Eğer bilirsek bar rengi yeşiş bilemezsek kırmızı olsun

			axi.text(left, bottom,metin,fontsize=9,color=renk,
					horizontalalignment='left',
					verticalalignment='bottom',
					transform=axi.transAxes)
			#axi.set_xlabel(metin)
			#axi.set_ylabel('vvvvvvvv')
			axi.set(xticks=[], yticks=[])
	plt.show()


import argparse
import sys
from client import UDPClient

if __name__ == '__main__':
    # arguments
    parser = argparse.ArgumentParser(
        usage="%(prog)s [OPTION]...",
        description="Run a client to send ping and receive pong as well as calculate rtt.",
    )
    parser.add_argument(
        "-ip",
        "--server_ip",
        help=('Set the IP address that the client will connect. Default is 127.0.0.1.'),
        action='store',
        default='127.0.0.1',
    )
    parser.add_argument(
        "-port",
        "--server_port",
        help=('Set the port that the client will connect. Default is 3000.'),
        action='store',
        default=3000,
    )
    parser.add_argument(
        "-l",
        "--logger",
        help='Save all client output in log file.',
        action='store_true',
    )
    parser.add_argument(
        "-c",
        "--csv",
        help='Save all packet data in a csv file.',
        action='store_true',
    )
    parser.add_argument(
        "-t",
        "--timeout",
        help=('Set how long to wait for a client to receive a ' 'response before receiving a timeout, in seconds.'),
        action='store',
        default=10,
    )
    parser.add_argument(
        "-p",
        "--packets",
        help=('Number of packets to send.'),
        action='store',
        default=10,
    )
    args = parser.parse_args()

    # stdout change
    if args.logger:
        previous = sys.stdout
        sys.stdout = open('client_log.txt', 'w', encoding='utf8')

    client = UDPClient(
        server_ip=args.server_ip,
        server_port=int(args.server_port),
        timeout=int(args.timeout),
        number_of_packets=int(args.packets),
        save_csv=args.csv,
    )
    client.run()

    # revert stdout change
    if args.logger:
        sys.stdout.close()
        sys.stdout = previous


f = open('day-7/input.txt', 'r')

dirs = {}
subdirs = {}
path = "/"

def count_sizes(path):
  result = dirs[path]
  for subdir in subdirs[path]:
    if subdir in dirs:
      result += count_sizes(subdir)
  return result

for line in f:
  if '$' in line:
    if '$ cd ..' in line:
        path = "/".join(path.split('/')[:-2]) + "/"
    elif '$ cd /' in line:
        path = "/"
    elif '$ cd' in line:
        path += line.split('$ cd ')[1].strip() + "/"
    if path not in dirs:
        dirs[path] = 0
        subdirs[path] = []
  else:
    if 'dir' in line:
        subdirs[path].append(path + line.split('dir ')[1].strip() + "/")
    else:
        dirs[path] += int(line.split(' ')[0].strip())

count = 0
for dir in dirs:
  if count_sizes(dir) <= 100000:
    count += count_sizes(dir)

print(count)


import threading

class ThreadingQueue:

    def __init__(self):
        self.queue = []
        self.empty = threading.Semaphore(10)
        self.full = threading.Semaphore(0)
        self.lock = threading.Lock()

    def enqueue(self,item):
        self.empty.acquire()
        self.lock.acquire()
        self.queue.append(item)
        self.lock.release()
        self.full.release()

    def dequeue(self):
        self.full.acquire()
        self.lock.acquire()
        val = self.queue.pop(0)
        self.lock.release()
        self.empty.release()
        return val


t=int(input())
for i in range(t):
    x = [int(x) for x in input().split()]
    ar= list([int(x) for x in input().split()])

    li=[]
    for i in range(x[1],0,-1):
        li.append(i)

    # ind=[index for index, value in enumerate(ar) if value == x[1]]
    # print(ind)

    # for q in range(ar.index(x[1])):
    def removeElements(li,ar):
        for i in range(len(ar) - len(li) + 1):
            for j in range(len(li)):
                if ar[i + j] != li[j]:
                    break
            else:
                return True
        return False

    if(removeElements(li,ar)==True):
        temp=0
        temp=temp+1
    print(temp)


import functools
from testcase import Document
from testcase import DocumentTranslationTest
from preparer import DocumentTranslationPreparer, DocumentTranslationClientPreparer as _DocumentTranslationClientPreparer
from azure.core.exceptions import HttpResponseError
from azure.ai.translation.document import DocumentTranslationClient, DocumentTranslationInput, TranslationTarget
DocumentTranslationClientPreparer = functools.partial(_DocumentTranslationClientPreparer, DocumentTranslationClient)

class TestCancelTranslation(DocumentTranslationTest):

    @DocumentTranslationPreparer()
    @DocumentTranslationClientPreparer()
    def test_cancel_translation(self, client):
        '''
            some notes (test sporadically failing):
            1. use a large number of translations
                - because when running tests the translations sometimes finishes with status 'Succeeded'
                  before we call the 'cancel' endpoint!
            2. wait sometime after calling 'cancel' and before calling 'get status'
                - in order for the cancel status to propagate
        '''
        # submit translation operation
        docs_count = 8 # large number of docs
        poller = self._begin_and_validate_translation_with_multiple_docs(client, docs_count, wait=False)

        # cancel translation
        client.cancel_translation(poller.id)

        # wait for propagation
        wait_time = 15  # for 'canceled' status to propagate, if test failed, increase this value!
        self.wait(duration=wait_time)

        # check translation status
        translation_details = client.get_translation_status(poller.id)
        self._validate_translations(translation_details, status="Canceled", total=docs_count)
        try:
            poller.wait()
        except HttpResponseError:
            pass  # expected if the operation was already in a terminal state.


from tool.get_session import GetSession

class ApiNoticeOne:
    def api_notice_one(self, url, id):
        session = GetSession().get_session()
        params = {'action': 'getone',
                  'id': id
                  }
        return session.get(url, params=params)


""" pytests for file API endpoints """

import pytest
from app import app
import json
import time
import uuid

from app.services import file_service

FILE_NAME = 'test_file_endpoints'
APPLICATION_TYPE = 'application/json'
HEADERS = {
    'Content-Type': APPLICATION_TYPE,
    'Accept': APPLICATION_TYPE
}
DATA = {
    'sessionId': str(FILE_NAME)
}

@pytest.fixture(scope="module")
def client():
    app.config['TESTING'] = True
    return app.test_client()

def setup_module(client):
    f = open('tests/titanic.csv', 'r')
    f.filename = FILE_NAME
    f.content_type = 'application/CSV'
    file_service.upload_file(f, FILE_NAME)
    f.close()

def test_file_upload(client):
    # arrange
    file_location = 'tests/titanic.csv'
    data = {
        'sessionId': str(FILE_NAME),
        'file': (open(file_location, 'rb'), FILE_NAME)
    }
    url = 'api/data/upload'

    # act
    resp = client.post(url, data=data, headers=HEADERS,
                       follow_redirects=True, content_type='multipart/form-data')

    # assert
    resp_json = json.loads(resp.json)
    nunique = resp_json['nunique']
    assert nunique is not None
    assert resp.status_code == 200

def test_create_unique_session(client):
    # arrange
    url = 'api/session/create'

    # act
    resp = client.post(url, headers=HEADERS, follow_redirects=True)
    uuid_response = resp.json

    # assert
    try:
        uuid_obj = uuid.UUID(uuid_response, version=4)
    except ValueError:
        return False

    is_uuid_valid = str(uuid_obj) == uuid_response

    assert is_uuid_valid
    assert resp.status_code == 200