#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 25 21:24:35 2019

@author: behrense
"""

from netCDF4 import Dataset
import matplotlib.pyplot as plt
import numpy as np
import  cmocean

def initial_conditions(din,ratio=1.005):
    rn15std=0.0036765
    tmp=ratio*rn15std*din/(1+ratio*rn15std)
    return tmp

def delta(C,C15):
    rn15std=0.0036765
    tmp=(C15/(C-C15)/rn15std-1)*1000

    return tmp

# both euqations verified

d1=Dataset('DIN.nc')
lon=d1.variables['nav_lon'][:]
lat=d1.variables['nav_lat'][:]
DIN=d1.variables['DIN'][:]
d3=Dataset('tmask.nc')
tmask=d3.variables['tmaskutil'][:]

#%% create initial conditions for tracer concentrations as per MEDUSA code

PHN=np.zeros(DIN.shape)
PHN[:14,:,:]=0.1 # over the frist 200 m else 0
PHD=PHN.copy()+.2
ZMI=PHN.copy()+.5
ZME=PHN.copy()+.7
DET=PHN.copy()+.25

PHN_N15=initial_conditions(PHN,1.005)
PHD_N15=initial_conditions(PHD,1.005)
ZMI_N15=initial_conditions(ZMI,1.005)
ZME_N15=initial_conditions(ZME,1.005)
DIN_N15=initial_conditions(DIN,1.005)
DET_N15=initial_conditions(DET,1.005)

#%%  initial tracer concentrations next time step to 0
PHN_next=np.zeros(PHN.shape)
PHD_next=np.zeros(PHN.shape)
ZMI_next=np.zeros(PHN.shape)
ZME_next=np.zeros(PHN.shape)
DIN_next=np.zeros(PHN.shape)
DET_next=np.zeros(PHN.shape)

PHN_N15_next=np.zeros(PHN.shape)
PHD_N15_next=np.zeros(PHN.shape)
ZMI_N15_next=np.zeros(PHN.shape)
ZME_N15_next=np.zeros(PHN.shape)
DIN_N15_next=np.zeros(PHN.shape)
DET_N15_next=np.zeros(PHN.shape)

#%% check that things are ok ratios are 5 permil
plt.close('all')
fig = plt.figure(figsize=(15,10))
ax1 = fig.add_subplot(231)
plt.pcolormesh(np.where(tmask[0,:,:]==0,1,delta(PHN[0,0,:,:],PHN_N15[0,0,:,:])),vmin=4.7,vmax=5.4)
plt.colorbar()
plt.text(10,10,'PHN',color='white')
ax1 = fig.add_subplot(232)
plt.pcolormesh(np.where(tmask[0,:,:]==0,1,delta(PHD[0,0,:,:],PHD_N15[0,0,:,:])),vmin=4.7,vmax=5.4)
plt.colorbar()
plt.text(10,10,'PHD',color='white')
ax1 = fig.add_subplot(233)
plt.pcolormesh(np.where(tmask[0,:,:]==0,1,delta(ZMI[0,0,:,:],ZMI_N15[0,0,:,:])),vmin=4.7,vmax=5.4)
plt.colorbar()
plt.text(10,10,'ZMI',color='white')
ax1 = fig.add_subplot(234)
plt.pcolormesh(np.where(tmask[0,:,:]==0,1,delta(ZME[0,0,:,:],ZME_N15[0,0,:,:])),vmin=4.7,vmax=5.4)
plt.colorbar()
plt.text(10,10,'ZME',color='white')
ax1 = fig.add_subplot(235)
plt.pcolormesh(np.where(tmask[0,:,:]==0,1,delta(DIN[0,0,:,:],DIN_N15[0,0,:,:])),vmin=4.7,vmax=5.4)
plt.colorbar()
plt.text(10,10,'DIN',color='white')
ax1 = fig.add_subplot(236)
plt.pcolormesh(np.where(tmask[0,:,:]==0,1,delta(DET[0,0,:,:],DET_N15[0,0,:,:])),vmin=4.7,vmax=5.4)
plt.colorbar()
plt.text(10,10,'DET',color='white')

plt.savefig('Initial_surface_concentration.png',dpi=200,pading=.1,bbox_inches='tight')

#%% code as similar to Fortran

def calculate_ratios():
    global fprn,zphn,fprd,zphd
    global DIN,DIN_N15,PHN,PHN_N15,PHD,PHD_N15,ZMI,ZMI_N15,ZME,ZME_N15
    global rn15std
    global un,rdin,bassimphn,fcassimphn,bassimphd,fcassimphd,rtdin15,rtphnn15,rtphdn15
    global rtzmin15,rtzmen15,rtdetrn15,rmi,bmiexcr,fcmiexcr,rme,bmeexcr,fcmeexcr

    eps_assim = 0.
    eps_excr= 0.

    rmin=0.000000001
    dmin=0.000001
    rmax=0.999999999
    rdt=40*60

    #keep code as similar to Fortran so we can copy across

    zdim=0
    tdim=0

    for jj in range(fprn.shape[0]):
        for ji in range(fprn.shape[1]):
              #uno3 = npp*dtbio/biono3
              un[jj,ji]=(fprn[jj,ji] * zphn[jj,ji] + fprd[jj,ji] * zphd[jj,ji]) * rdt /max(DIN[tdim,zdim,jj,ji],dmin)

              un[jj,ji] = min(un[jj,ji], rmax)
              un[jj,ji] = max(un[jj,ji], rmin)
              #rno3 = biodin15/(biono3-biodin15)
              rdin[jj,ji] = DIN_N15[tdim,zdim,jj,ji]/(max(DIN[tdim,zdim,jj,ji]-DIN_N15[tdim,zdim,jj,ji],dmin))
              rdin[jj,ji] = min(rdin[jj,ji],2*rn15std)
              rdin[jj,ji] = max(rdin[jj,ji],rn15std/2)
              #print(rdin[0,0])
              #bassim = rno3 + eps_assim*(1-uno3)/uno3*log(1-uno3)*rno3/1000.
              bassimphn[jj,ji]=rdin[jj,ji]+rdin[jj,ji]*eps_assim*(1-un[jj,ji])/un[jj,ji]*np.log(1-un[jj,ji])/1000.
              fcassimphn[jj,ji]=bassimphn[jj,ji]/(1+bassimphn[jj,ji])
              #print(fcassimphn[0,0])
              #bassim = rno3 + eps_assim*(1-uno3)/uno3*log(1-uno3)*rno3/1000.
              bassimphd[jj,ji]=rdin[jj,ji]+rdin[jj,ji]*eps_assim*(1-un[jj,ji])/un[jj,ji]*np.log(1-un[jj,ji])/1000.
              fcassimphd[jj,ji]=bassimphd[jj,ji]/(1+bassimphd[jj,ji])
              #rtdin15 = biodin15/biono3
              rtdin15[jj,ji] = DIN_N15[tdim,zdim,jj,ji] /max(DIN[tdim,zdim,jj,ji],rmin)
              rtdin15[jj,ji] = min(rtdin15[jj,ji],2*rn15std/(1+rn15std))
              rtdin15[jj,ji] = max(rtdin15[jj,ji],rn15std/(1+rn15std)/2.)
              #rtphytn15 = biophytn15/biophyt
              rtphnn15[jj,ji] = PHN_N15[tdim,zdim,jj,ji] /max(PHN[tdim,zdim,jj,ji],rmin)
              rtphdn15[jj,ji] = PHD_N15[tdim,zdim,jj,ji] /max(PHD[tdim,zdim,jj,ji],rmin)
              rtphnn15[jj,ji] = min(rtphnn15[jj,ji],2.*rn15std/(1+rn15std))
              rtphnn15[jj,ji] = max(rtphnn15[jj,ji],rn15std/(1+rn15std)/2.)
              rtphdn15[jj,ji] = min(rtphdn15[jj,ji],2.*rn15std/(1+rn15std))
              rtphdn15[jj,ji] = max(rtphdn15[jj,ji],rn15std/(1+rn15std)/2.)
              #rtzoopn15 = biozoopn15/biozoop
              rtzmin15[jj,ji] = ZMI_N15[tdim,zdim,jj,ji] /max(ZMI[tdim,zdim,jj,ji],rmin)
              rtzmen15[jj,ji] = ZME_N15[tdim,zdim,jj,ji] /max(ZME[tdim,zdim,jj,ji],rmin)
              rtzmin15[jj,ji] = min(rtzmin15[jj,ji],2.*rn15std/(1+rn15std))
              rtzmin15[jj,ji] = max(rtzmin15[jj,ji],rn15std/(1+rn15std)/2.)
              rtzmen15[jj,ji] = min(rtzmen15[jj,ji],2.*rn15std/(1+rn15std))
              rtzmen15[jj,ji] = max(rtzmen15[jj,ji],rn15std/(1+rn15std)/2.)
              #rtdetrn15 = biodetrn15/biodetr
              rtdetrn15[jj,ji] = DET_N15[tdim,zdim,jj,ji] /max(DET[tdim,zdim,jj,ji],rmin)
              rtdetrn15[jj,ji] = min(rtdetrn15[jj,ji],2.*rn15std/(1+rn15std))
              rtdetrn15[jj,ji] = max(rtdetrn15[jj,ji],rn15std/(1+rn15std)/2.)
              #rzoop = biozoopn15/(biozoop-biozoopn15)
              rmi[jj,ji] = ZMI_N15[tdim,zdim,jj,ji] /max(ZMI[tdim,zdim,jj,ji]-ZMI_N15[tdim,zdim,jj,ji],rmin)
              rmi[jj,ji] = min(rmi[jj,ji], 2.*rn15std)
              rmi[jj,ji] = max(rmi[jj,ji], rn15std/2.)
              #bexcr = rzoop - eps_excr*rzoop/1000.
              bmiexcr[jj,ji] = rmi[jj,ji] - eps_excr*rmi[jj,ji]/1000.
              fcmiexcr[jj,ji] = bmiexcr[jj,ji]/(1+bmiexcr[jj,ji])
              #rzoop = biozoopn15/(biozoop-biozoopn15)
              rme[jj,ji] = ZME_N15[tdim,zdim,jj,ji] /max(ZME[tdim,zdim,jj,ji]-ZME_N15[tdim,zdim,jj,ji],rmin)
              rme[jj,ji] = min(rme[jj,ji], 2.*rn15std)
              rme[jj,ji] = max(rme[jj,ji], rn15std/2.)
              #bexcr = rzoop - eps_excr*rzoop/1000.
              bmeexcr[jj,ji] = rme[jj,ji] - eps_excr*rme[jj,ji]/1000.
              fcmeexcr[jj,ji] = bmeexcr[jj,ji]/(1+bmeexcr[jj,ji])

    return

#%%

def calc_growth():

        global fprn,fgmipn,fgmid
        global fstarmi,fmith,ficmi,ficmin15
        xphi=.2
        xthetapn=6.625
        xbetan=0.77
        xthetazmi=5.625
        xbetac=0.64
        xkc=0.80
        xthetazme=5.625
        xthetapd=6.625

        finmi=np.zeros(fprn.shape)
        finme=np.zeros(fprn.shape)
        ficmi=np.zeros(fprn.shape)
        finmin15=np.zeros(fprn.shape)
        finmen15=np.zeros(fprn.shape)
        ficmin15=np.zeros(fprn.shape)
        fmigrow=np.zeros(fprn.shape)
        fmigrown15=np.zeros(fprn.shape)
        ficme=np.zeros(fprn.shape)
        fgmidc=np.zeros(fprn.shape)+.01
        fgmedc=np.zeros(fprn.shape)+.1
        ficmen15=np.zeros(fprn.shape)
        fmegrow=np.zeros(fprn.shape)
        fmegrown15=np.zeros(fprn.shape)

        for jj in range(fprn.shape[0]): #loop j

            for ji in range(fprn.shape[1]): # loop i

               finmi[jj,ji]  = (1.0 - xphi) * (fgmipn[jj,ji]+ fgmid[jj,ji])
               ficmi[jj,ji]  = (1.0 - xphi) * ((xthetapn * fgmipn[jj,ji]) + fgmidc[jj,ji])
               finmin15[jj,ji]  = (1.0 - xphi) * (rtphnn15[jj,ji]*fgmipn[jj,ji]+ rtdetrn15[jj,ji]*fgmid[jj,ji])
               ficmin15[jj,ji]  = (1.0 - xphi) * rtphnn15[jj,ji]*((xthetapn * fgmipn[jj,ji]) +  fgmidc[jj,ji])

               fstarmi = (xbetan * xthetazmi) / (xbetac * xkc)
               fmith = (ficmi[jj,ji]/ (finmi[jj,ji]+ finmi[jj,ji]))

               if (fmith >= fstarmi):
                  fmigrow[jj,ji]= xbetan * finmi[jj,ji]
                  fmiexcr[jj,ji]= 0.0
                  fmigrown15[jj,ji]= xbetan * finmin15[jj,ji]

               else:
                  fmigrow[jj,ji]= (xbetac * xkc * ficmi[jj,ji]) / xthetazmi
                  fmiexcr[jj,ji]= ficmi[jj,ji]* ((xbetan / (fmith + fmith)) - ((xbetac * xkc) / xthetazmi))
                  fmigrown15[jj,ji]= (xbetac * xkc * ficmin15[jj,ji]) / xthetazmi

               finme[jj,ji]   = (1.0 - xphi) \
                   *(fgmepn[jj,ji] + fgmepd[jj,ji] \
                   +fgmezmi[jj,ji] + fgmed[jj,ji])
               ficme[jj,ji]   = (1.0 - xphi) *\
                                ((xthetapn * fgmepn[jj,ji]) +\
                                (xthetapd * fgmepd[jj,ji]) +\
                                (xthetazmi * fgmezmi[jj,ji]) + fgmedc[jj,ji])

               finmen15[jj,ji]   = (1.0 - xphi) *\
                                (rtphnn15[jj,ji]*fgmepn[jj,ji] + rtphdn15[jj,ji]*fgmepd[jj,ji] +\
                                rtzmin15[jj,ji]*fgmezmi[jj,ji] + rtdetrn15[jj,ji]*fgmed[jj,ji])
               total=(xthetapn  * fgmepn[jj,ji]) + (xthetapd * fgmepd[jj,ji]) + (xthetazmi * fgmezmi[jj,ji]) + fgmedc[jj,ji]
               frac1=(xthetapn  * fgmepn[jj,ji]+1/3* fgmedc[jj,ji])/total
               frac2=(xthetapd  * fgmepd[jj,ji]+1/3* fgmedc[jj,ji])/total
               frac3=(xthetazmi * fgmezmi[jj,ji]+1/3* fgmedc[jj,ji])/total

               ficmen15[jj,ji]   = (1.0 - xphi) *\
                                 (frac1*rtphnn15[jj,ji]+frac2*rtphdn15[jj,ji]+frac3*rtzmin15[jj,ji])*((xthetapn * fgmepn[jj,ji]) +\
                                 (xthetapd * fgmepd[jj,ji]) + \
                                 (xthetazmi * fgmezmi[jj,ji]) + fgmedc[jj,ji])

               fstarme        = (xbetan * xthetazme) / (xbetac * xkc)

               fmeth   = (ficme[jj,ji] / (finme[jj,ji] + finme[jj,ji]))
               if (fmeth >= fstarme):
                  fmegrow[jj,ji] = xbetan * finme[jj,ji]
                  fmeexcr[jj,ji] = 0.0
                  fmegrown15[jj,ji] = xbetan * finmen15[jj,ji]
               else:
                  fmegrow[jj,ji] = (xbetac * xkc * ficme[jj,ji]) / xthetazme
                  fmeexcr[jj,ji] = ficme[jj,ji] * ((xbetan / (fmeth + fmeth)) -  ((xbetac * xkc) / xthetazme))
                  fmegrown15[jj,ji] = (xbetac * xkc * ficmen15[jj,ji]) / xthetazme

        return finmi,finme,fmigrow,fmigrown15,fmegrow,fmegrown15

#%%

def compute_fluxes():
    global fprn,zphn,fprd,zphd
    global DIN,DIN_N15,PHN,PHN_N15,PHD,PHD_N15,ZMI,ZMI_N15,ZME,ZME_N15
    global PHN_N15_flux,PHD_N15_flux,ZMI_N15_flux,ZME_N15_flux,DET_N15_flux,DIN_N15_flux
    global rn15std
    global un,rdin,bassimphn,fcassimphn,bassimphd,fcassimphn,rtdin15,rtphnn15,rtphdn15
    global rtzmin15,rtzmen15,rtdetrn15,rmi,bmiexcr,fcmiexcr,rme,bmeexcr,fcmeexcr,fmiexcr,fmeexcr,freminn
    global PHN_flux,PHD_flux,ZMI_flux,ZME_flux,DET_flux,DIN_flux

    finmi,finme,fmigrow,fmigrown15,fmegrow,fmegrown15=calc_growth()

    fn_cons_n15=np.zeros(fprn.shape)
    fn_prod_n15=np.zeros(fprn.shape)
    fn_cons=np.zeros(fprn.shape)
    fn_prod=np.zeros(fprn.shape)
    b0=1
    xfdfrac1=0.333
    xfdfrac2=1
    xbetan=0.77
    xphi=.2

    for jj in range(fprn.shape[0]): #loop j
        for ji in range(fprn.shape[1]): # loop i
               PHN_flux[jj,ji] = b0 * ( fprn[jj,ji] * zphn[jj,ji] \
                                     - fdpn[jj,ji] \
                                     - fdpn2[jj,ji] \
                                     - fgmipn[jj,ji] \
                                     - fgmepn[jj,ji] )

               PHD_flux[jj,ji] = b0 * ( fprd[jj,ji] * zphd[jj,ji] \
                                      - fdpd[jj,ji] \
                                      - fdpd2[jj,ji] \
                                      - fgmepd[jj,ji])

               ZMI_flux[jj,ji] = b0 * (fmigrow[jj,ji] \
                                   - fgmezmi[jj,ji] \
                                   - fdzmi[jj,ji]\
                                   - fdzmi2[jj,ji])

               ZME_flux[jj,ji] = b0 * (fmegrow[jj,ji]            \
                                    - fdzme[jj,ji] \
                                    - fdzme2[jj,ji])

               DET_flux[jj,ji] = b0 * (fdpn[jj,ji] \
                                    +  (1.0 - xfdfrac1) * fdpd[jj,ji] \
                                    + fdzmi[jj,ji]                    \
                                    + (1.0 - xfdfrac2) *fdzme[jj,ji] \
                                    + ((1.0 - xbetan) *  (finmi[jj,ji] + finme[jj,ji])) \
                                    - fgmid[jj,ji]                   \
                                    - fgmed[jj,ji]                   \
                                    - fdd[jj,ji]                     \
                                    + fslowgain[jj,ji] - fslowloss[jj,ji]             \
                                    - (f_sbenin_n[jj,ji] / fse3t[jj,ji])           \
                                    + ffast2slown[jj,ji] )

               fn_cons[jj,ji] = -(fprn[jj,ji] * zphn[jj,ji])\
                                 -(fprd[jj,ji] * zphd[jj,ji])

               fn_prod[jj,ji] =(xphi * (fgmipn[jj,ji] + fgmid[jj,ji])) \
                            + (xphi * (fgmepn[jj,ji]   \
                                    + fgmepd[jj,ji]    \
                                    + fgmezmi[jj,ji]   \
                                    + fgmed[jj,ji]))  \
                                    + fmiexcr[jj,ji]                           \
                                    + fmeexcr[jj,ji]                           \
                                    + fdd[jj,ji]              \
                                    + freminn[jj,ji]                           \
                                    + fdpn2[jj,ji]             \
                                    + fdpd2[jj,ji]             \
                                    + fdzmi2[jj,ji]            \
                                    + fdzme2[jj,ji]

               DIN_flux[jj,ji] = b0 * ( fn_prod[jj,ji] + fn_cons[jj,ji] )

               PHN_N15_flux[jj,ji] = b0 * ( fcassimphn[jj,ji]*fprn[jj,ji] * zphn[jj,ji] \
                                     - rtphnn15[jj,ji]*fdpn[jj,ji] \
                                     - rtphnn15[jj,ji]*fdpn2[jj,ji] \
                                     - rtphnn15[jj,ji]*fgmipn[jj,ji] \
                                     - rtphnn15[jj,ji]*fgmepn[jj,ji] )

               PHD_N15_flux[jj,ji] = b0 * ( fcassimphd[jj,ji]*fprd[jj,ji] * zphd[jj,ji] \
                                      - rtphdn15[jj,ji]*fdpd[jj,ji] \
                                      - rtphdn15[jj,ji]* fdpd2[jj,ji] \
                                      - rtphdn15[jj,ji]*fgmepd[jj,ji])

               ZMI_N15_flux[jj,ji] = b0 * (fmigrown15[jj,ji] \
                                   - rtzmin15[jj,ji]*fgmezmi[jj,ji] \
                                   - rtzmin15[jj,ji]*fdzmi[jj,ji]\
                                   - rtzmin15[jj,ji]*fdzmi2[jj,ji])

               ZME_N15_flux[jj,ji] = b0 * (fmegrown15[jj,ji]            \
                                    - rtzmen15[jj,ji]*fdzme[jj,ji] \
                                    - rtzmen15[jj,ji]*fdzme2[jj,ji])

               DET_N15_flux[jj,ji] = b0 * (rtphnn15[jj,ji]*fdpn[jj,ji] \
                                    +  (1.0 - xfdfrac1) *rtphdn15[jj,ji]* fdpd[jj,ji] \
                                    + rtzmin15[jj,ji]*fdzmi[jj,ji]                    \
                                    + (1.0 - xfdfrac2) * rtzmen15[jj,ji]*fdzme[jj,ji] \
                                    + ((1.0 - xbetan) *  (rtzmin15[jj,ji]*finmi[jj,ji] + rtzmen15[jj,ji]*finme[jj,ji])) \
                                    - rtdetrn15[jj,ji]*fgmid[jj,ji]                   \
                                    - rtdetrn15[jj,ji]*fgmed[jj,ji]                   \
                                    - rtdetrn15[jj,ji]*fdd[jj,ji]                     \
                                    + rtdetrn15[jj,ji]*(fslowgain[jj,ji] - fslowloss[jj,ji])             \
                                    - (rtdetrn15[jj,ji]*f_sbenin_n[jj,ji] / fse3t[jj,ji])           \
                                    + rtdetrn15[jj,ji]*ffast2slown[jj,ji] )

               fn_cons_n15[jj,ji] = -(fcassimphn[jj,ji]*fprn[jj,ji] * zphn[jj,ji])\
                                      -(fcassimphd[jj,ji]*fprd[jj,ji] * zphd[jj,ji])

               fn_prod_n15[jj,ji] =(xphi * (rtphnn15[jj,ji]*fgmipn[jj,ji] + rtdetrn15[jj,ji]*fgmid[jj,ji])) \
                           + (xphi * (rtphnn15[jj,ji]*fgmepn[jj,ji]   \
                                   + rtphdn15[jj,ji]*fgmepd[jj,ji]    \
                                   + rtzmin15[jj,ji]*fgmezmi[jj,ji]   \
                                   + rtdetrn15[jj,ji]*fgmed[jj,ji]))  \
                                   + rtzmin15[jj,ji]*fmiexcr[jj,ji]                           \
                                   + rtzmen15[jj,ji]*fmeexcr[jj,ji]                           \
                                   + rtdetrn15[jj,ji]*fdd[jj,ji]              \
                                   + (rtphdn15[jj,ji]+rtzmen15[jj,ji])/2*freminn[jj,ji]                           \
                                   + rtphnn15[jj,ji]*fdpn2[jj,ji]             \
                                   + rtphdn15[jj,ji]*fdpd2[jj,ji]             \
                                   + rtzmin15[jj,ji]*fdzmi2[jj,ji]            \
                                   + rtzmen15[jj,ji]*fdzme2[jj,ji]

               DIN_N15_flux[jj,ji] = b0 * ( fn_prod_n15[jj,ji] + fn_cons_n15[jj,ji] )
    return

def compute_new_concentrations():
    dayinsec=86400.
    global DIN_next,DET_next,PHN_next,PHD_next,ZMI_next,ZME_next
    global DIN_N15_next,DET_N15_next,PHN_N15_next,PHD_N15_next,ZMI_N15_next,ZME_N15_next
    DIN_next[0,0,:,:]=DIN[0,0,:,:]+DIN_flux/dayinsec
    DET_next[0,0,:,:]=DET[0,0,:,:]+DET_flux/dayinsec
    PHN_next[0,0,:,:]=PHN[0,0,:,:]+PHN_flux/dayinsec
    PHD_next[0,0,:,:]=PHD[0,0,:,:]+PHD_flux/dayinsec
    ZMI_next[0,0,:,:]=ZMI[0,0,:,:]+ZMI_flux/dayinsec
    ZME_next[0,0,:,:]=ZME[0,0,:,:]+ZME_flux/dayinsec
    DIN_N15_next[0,0,:,:]=DIN_N15[0,0,:,:]+DIN_N15_flux/dayinsec
    DET_N15_next[0,0,:,:]=DET_N15[0,0,:,:]+DET_N15_flux/dayinsec
    PHN_N15_next[0,0,:,:]=PHN_N15[0,0,:,:]+PHN_N15_flux/dayinsec
    PHD_N15_next[0,0,:,:]=PHD_N15[0,0,:,:]+PHD_N15_flux/dayinsec
    ZMI_N15_next[0,0,:,:]=ZMI_N15[0,0,:,:]+ZMI_N15_flux/dayinsec
    ZME_N15_next[0,0,:,:]=ZME_N15[0,0,:,:]+ZME_N15_flux/dayinsec
    return

#%% define fluxes for the computation of tracer fluxes and assign some random values
rn15std=0.0036765
fprn=np.zeros((DIN.shape[2],DIN.shape[3]))+.5   #production phyt non-diatoms
zphn=np.zeros(fprn.shape)+.2   #non-diatom concentraion
zphd=np.zeros(fprn.shape)+.2   #diatom concentraion
fprd=np.zeros(fprn.shape)+.5   #production phyt diatoms

fdpn=np.zeros(fprn.shape)+1   #loss term
fdpn2=np.zeros(fprn.shape)+2  #loss term 2
fgmipn=np.zeros(fprn.shape)+1  #eaten by zmi
fgmepn=np.zeros(fprn.shape)+1  #eaten by zme

fdpd=np.zeros(fprn.shape)+.2 #loss term
fdpd2=np.zeros(fprn.shape)+.3 #loss term2
fgmepd=np.zeros(fprn.shape)+.5 #eaten by zme

fmigrown15=np.zeros(fprn.shape)+.05 #grow term
fgmezmi=np.zeros(fprn.shape)+.15 #eaten by zme
fdzmi=np.zeros(fprn.shape)+.25 #loss term
fdzmi2=np.zeros(fprn.shape)+.35 #loss term2

fmegrown15=np.zeros(fprn.shape)+.15  #grow term
fdzme=np.zeros(fprn.shape)+.25 #loss term
fdzme2=np.zeros(fprn.shape)+.35 #loss term2

fgmid=np.zeros(fprn.shape)+.3 # grazing zmi on det
fgmed=np.zeros(fprn.shape)+.2 # grazing zme on det
fdd=np.zeros(fprn.shape)+.22  #remin.
fslowgain=np.zeros(fprn.shape)+.1 #sinking
fslowloss=np.zeros(fprn.shape)+.1 #sinking
f_sbenin_n=np.zeros(fprn.shape)+.1 #sinking
fse3t=np.zeros(fprn.shape)+.1 #sinking
ffast2slown=np.zeros(fprn.shape)+.1 #sinking

fmiexcr=np.zeros(fprn.shape)+.1 #excr
fmeexcr=np.zeros(fprn.shape)+.2
freminn=np.zeros(fprn.shape)+.2

bmiexcr=np.zeros(fprn.shape)
bmeexcr=np.zeros(fprn.shape)
#%% initialise N15 ratio fields
un=np.zeros(fprn.shape)
bassimphn=np.zeros(fprn.shape)
bassimphd=np.zeros(fprn.shape)
rdin=np.zeros(fprn.shape)
fcassimphd=np.zeros(fprn.shape)
fcassimphn=np.zeros(fprn.shape)
rtdin15=np.zeros(fprn.shape)
rtphnn15=np.zeros(fprn.shape)
rtphdn15=np.zeros(fprn.shape)
rtzmin15=np.zeros(fprn.shape)
rtzmen15=np.zeros(fprn.shape)
rtdetrn15=np.zeros(fprn.shape)
fcmiexcr=np.zeros(fprn.shape)
fcmeexcr=np.zeros(fprn.shape)
rmi=np.zeros(fprn.shape)
rme=np.zeros(fprn.shape)
#%% define tracer fluxes and set zeros
PHN_flux=np.zeros(fprn.shape)  #phyto non-diatom
PHD_flux=np.zeros(fprn.shape)  #phyto diatom
ZMI_flux=np.zeros(fprn.shape)  #zoo micro
ZME_flux=np.zeros(fprn.shape)  #zoo meso
DET_flux=np.zeros(fprn.shape)  #detritus
DIN_flux=np.zeros(fprn.shape)  #DIN

PHN_N15_flux=np.zeros(fprn.shape)
PHD_N15_flux=np.zeros(fprn.shape)
ZMI_N15_flux=np.zeros(fprn.shape)
ZME_N15_flux=np.zeros(fprn.shape)
DET_N15_flux=np.zeros(fprn.shape)
DIN_N15_flux=np.zeros(fprn.shape)
#%% model run
calculate_ratios()
compute_fluxes()
compute_new_concentrations()

#%% delta ratio after update

plt.close('all')
fig = plt.figure(figsize=(15,10))
ax1 = fig.add_subplot(231)
plt.pcolormesh(np.where(tmask[0,:,:]==0,1,delta(PHN_next[0,0,:,:],PHN_N15_next[0,0,:,:])),vmin=4.7,vmax=5.4)
plt.colorbar()
plt.text(10,10,'PHN',color='white')
ax1 = fig.add_subplot(232)
plt.pcolormesh(np.where(tmask[0,:,:]==0,1,delta(PHD_next[0,0,:,:],PHD_N15_next[0,0,:,:])),vmin=4.7,vmax=5.4)
plt.colorbar()
plt.text(10,10,'PHD',color='white')
ax1 = fig.add_subplot(233)
plt.pcolormesh(np.where(tmask[0,:,:]==0,1,delta(ZMI_next[0,0,:,:],ZMI_N15_next[0,0,:,:])),vmin=4.7,vmax=5.4)
plt.colorbar()
plt.text(10,10,'ZMI',color='white')
ax1 = fig.add_subplot(234)
plt.pcolormesh(np.where(tmask[0,:,:]==0,1,delta(ZME_next[0,0,:,:],ZME_N15_next[0,0,:,:])),vmin=4.7,vmax=5.4)
plt.colorbar()
plt.text(10,10,'ZME',color='white')
ax1 = fig.add_subplot(235)
plt.pcolormesh(np.where(tmask[0,:,:]==0,1,delta(DIN_next[0,0,:,:],DIN_N15_next[0,0,:,:])),vmin=4.7,vmax=5.4)
plt.colorbar()
plt.text(10,10,'DIN',color='white')
ax1 = fig.add_subplot(236)
plt.pcolormesh(np.where(tmask[0,:,:]==0,1,delta(DET_next[0,0,:,:],DET_N15_next[0,0,:,:])),vmin=4.7,vmax=5.4)
plt.colorbar()
plt.text(10,10,'DET',color='white')

plt.savefig('Updated_surface_concentration.png',dpi=200,pading=.1,bbox_inches='tight')

#%%
plt.close('all')
fig = plt.figure(figsize=(15,10))
ax1 = fig.add_subplot(231)
plt.pcolormesh(np.where(tmask[0,:,:]==0,np.NaN,delta(PHN_next[0,0,:,:],PHN_N15_next[0,0,:,:])-delta(PHN[0,0,:,:],PHN_N15[0,0,:,:])),vmin=-0.00001,vmax=0.00001,cmap='cmo.balance')
plt.colorbar()
plt.text(10,10,'PHN',color='white')
ax1 = fig.add_subplot(232)
plt.pcolormesh(np.where(tmask[0,:,:]==0,np.NaN,delta(PHD_next[0,0,:,:],PHD_N15_next[0,0,:,:])-delta(PHD[0,0,:,:],PHD_N15[0,0,:,:])),vmin=-0.00001,vmax=0.00001,cmap='cmo.balance')
plt.colorbar()
plt.text(10,10,'PHD',color='white')
ax1 = fig.add_subplot(233)
plt.pcolormesh(np.where(tmask[0,:,:]==0,np.NaN,delta(ZMI_next[0,0,:,:],ZMI_N15_next[0,0,:,:])-delta(ZMI[0,0,:,:],ZMI_N15[0,0,:,:])),vmin=-0.00001,vmax=0.00001,cmap='cmo.balance')
plt.colorbar()
plt.text(10,10,'ZMI',color='white')
ax1 = fig.add_subplot(234)
plt.pcolormesh(np.where(tmask[0,:,:]==0,np.NaN,delta(ZME_next[0,0,:,:],ZME_N15_next[0,0,:,:])-delta(ZME[0,0,:,:],ZME_N15[0,0,:,:])),vmin=-0.00001,vmax=0.00001,cmap='cmo.balance')
plt.colorbar()
plt.text(10,10,'ZME',color='white')
ax1 = fig.add_subplot(235)
plt.pcolormesh(np.where(tmask[0,:,:]==0,np.NaN,delta(DIN_next[0,0,:,:],DIN_N15_next[0,0,:,:])-delta(DIN[0,0,:,:],DIN_N15[0,0,:,:])),vmin=-0.00001,vmax=0.00001,cmap='cmo.balance')
plt.colorbar()
plt.text(10,10,'DIN',color='white')
ax1 = fig.add_subplot(236)
plt.pcolormesh(np.where(tmask[0,:,:]==0,np.NaN,delta(DET_next[0,0,:,:],DET_N15_next[0,0,:,:])-delta(DET[0,0,:,:],DET_N15[0,0,:,:])),vmin=-0.00001,vmax=0.00001,cmap='cmo.balance')
plt.colorbar()
plt.text(10,10,'DET',color='white')

plt.savefig('Updated_surface_concentration_difference.png',dpi=200,pading=.1,bbox_inches='tight')

#%%% test for PHN according to Chris with eps=0 the delta should not change

# rdt=3
# rmin=0.1
# aa=np.zeros(fprn.shape)
# for jj in range(fprn.shape[0]): #loop j
#     for ji in range(fprn.shape[1]): # loop i
#         #un[jj,ji]=max(DIN[0,0,jj,ji],rmin)
#         un[jj,ji]=(fprn[jj,ji] * zphn[jj,ji] + fprd[jj,ji] * zphd[jj,ji]) * rdt /max(DIN[0,0,jj,ji],rmin)

plt.close('all')
fig = plt.figure(figsize=(15,10))
ax1 = fig.add_subplot(111)
plt.pcolormesh(fcassimphn)
plt.colorbar()


"""
This code is supported by the website: https://www.guanjihuan.com
The newest version of this code is on the web page: https://www.guanjihuan.com/archives/17937
"""

from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
import datetime

year = datetime.datetime.now().year
month = datetime.datetime.now().month
day = datetime.datetime.now().day

# 获取链接

# 由于没有模拟登录知乎，因此只能爬取到最新的两篇文章
authors = ["https://www.zhihu.com/people/guanjihuan/posts"]  # Guan

match_href = []
for i0 in range(len(authors)):
    start_link = authors[i0]
    html = urlopen(start_link).read().decode('utf-8')  # 打开网页
    soup = BeautifulSoup(html, features='lxml') # 放入soup中
    all_a_tag = soup.find_all('a', href=True)  # 获取超链接标签
    for a_tag in all_a_tag:
        href = a_tag['href']  # 超链接字符串
        if re.search('//zhuanlan.zhihu.com/p/', href) and not re.search('edit', href): # 文章的链接
            if re.search('https:', href)==None:  # 如果链接不是完整的，那么补充完整
                href = 'https:'+ href
            if href not in match_href:
                match_href.append(href)

# 对链接进行排序
numbers = []
match_href_new = []
for href in match_href:
    numbers.append(int(href[29:]))
numbers.sort(reverse = True)
for n in numbers:
    match_href_new.append('https://zhuanlan.zhihu.com/p/'+str(n))

# 获取内容并写入文件
f = open('zhihu.html', 'w', encoding='UTF-8')
f.write('<meta charset="utf-8">')

f.write('
'+str(year)+'.'+str(month).rjust(2,'0')+'.'+str(day).rjust(2,'0')+' 已更新
')
for href in match_href_new:
    try:
        html = urlopen(href).read().decode('utf-8')   # 打开文章链接
        soup = BeautifulSoup(html, features='lxml') # 放入soup中
        title = soup.title   # 文章标题
        f.write('
')
        f.write(str(title.get_text()[:-5]))
        f.write('  ')
        author = soup.find("span", {"class": "UserLink AuthorInfo-name"})
        f.write(str(author.get_text()+'  '))
        post_time = soup.find("div", {"class" : "ContentItem-time"})
        f.write(str(post_time.get_text()[4:-6])+'
')
    except:
        pass
f.close()


from Collum_generation import CG
from matplotlib import pyplot as plt
import time

class Results():
    def __init__(self,show=False,save=True,max_time=3600):
        self.show = show
        self.save = save

        start_time = time.time()
        self.model = CG()
        self.run_time = time.time()-start_time
        print(f"\nruntime: {round(self.run_time,3)} seconds")

        self.print_stats()
        self.plot_graph()

    def timestep2day(self,timestep):
        '''converts the time step into a string with hour and day number for plotting'''
        tmp = []
        for t in timestep:
            time = t * 4
            h = int(time % 24)
            d = int((time - h) / 24 + 1)
            if h != 0:
                tmp.append(f"{h}h")
            else:
                tmp.append(f"{h}h\nDay {d}")
        return tmp

    def plot_graph(self):
        '''plots and saves the graph that represents the model'''
        c_code = {"AC_1": (1, 0, 0),
                  "AC_2": (0, 0, 1)}
        results = self.model.decision_variable_dict

        plt.figure(figsize=[11,4])
        plt.xticks(range(25),self.timestep2day(range(25)))
        idx2ref = [""] * 6
        for airport_ref, airport in self.model.TSN.data.airport_dict.items():
            idx2ref[airport["index"] - 1] = airport_ref
        plt.yticks(range(7)[1:], idx2ref)

        request_plot_dict = {}
        # for every z_p_r
        for p, zp in results["z"].items():
            for r, zpr in zp.items():
                if type(zpr) != int:
                    path = self.model.path_dict["request paths"][r][p]
                    for arc in path.arcs:
                        a = arc.ref
                        if arc.type != "NS":
                            if self.model.TSN.data.request_dict[r]["airport_D"] != arc.origin_airport:
                                weight = self.model.TSN.data.request_dict[r]["weight"] * zpr.X
                            else:
                                weight = 0
                            try:
                                request_plot_dict[a] += weight
                            except:
                                request_plot_dict[a] = weight
                            t = [arc.origin_timestep,arc.destination_timestep]
                            n = [self.model.TSN.data.airport_dict[arc.origin_airport]["index"] , self.model.TSN.data.airport_dict[arc.destination_airport]["index"]]
                            plt.plot(t, n, linewidth=request_plot_dict[a] / 10, color=(0.3, 0.3, 0.3),zorder = 2)
                        else:
                            if zpr.X:
                                # plt.plot(arc.origin_timestep, self.model.TSN.data.airport_dict[arc.origin_airport]["index"], 'ro')
                                plt.plot([arc.origin_timestep, arc.destination_timestep],
                                         [self.model.TSN.data.airport_dict[arc.origin_airport]["index"],
                                         self.model.TSN.data.airport_dict[arc.destination_airport]["index"]],
                                         color=(0, 0.8, 0), marker='o',markersize=2, linestyle='dashed', linewidth=1, zorder=1)

        for r in self.model.master.getVars():
            if r.X != 0:
                if r.varName[0] in ["x", "y"]:
                    # print(r.varName,r.X)
                    arc_name = r.varName[16:].split("->")
                    t = [0, 0]
                    n = [0, 0]
                    plane = arc_name[1].split("-")[-1]
                    for i in range(2):
                        t[i] = int(arc_name[i].split("-")[0])
                        n[i] = int(self.model.TSN.data.airport_dict[arc_name[i].split("-")[1]]["index"])
                    plt.plot(t, n, color=c_code[plane], linestyle=":",zorder=3)

        if self.save:
            file_name = "Results_model_4"
            plt.savefig(f"{file_name}.png")
            print(f"saved figure to '{file_name}.png'")
        if self.show:
            plt.show()

    def print_stats(self):
        '''prints the stats of the model'''
        # =========================================================== Generate data
        # -> Arc used (non-NS)
        total_arc_used = 0
        f_arc_used = 0
        g_arc_used = 0

        # -> NS arcs used
        NS_arc_used = 0
        # -> Packages handled
        packages_handled = []
        packages_not_handled = []
        packages_not_handled_penalty = 0

        results = self.model.decision_variable_dict

        for p, zp in results["z"].items():
            for r, zpr in zp.items():
                if type(zpr) != int:
                    path = self.model.path_dict["request paths"][r][p]

                    for arc in path.arcs:
                        if arc.type == "NS":
                            NS_arc_used += 1 * zpr.X

                        # elif arc.type == "Ground":
                        #     g_arc_used += 1
                        #
                        # elif arc.type == "Flight":
                        #     f_arc_used += 1

        # ... per request
        for r, request in self.model.TSN.data.request_dict.items():
            # ... find Pns
            for p, path in self.model.path_dict["request paths"][r].items():
                if path.type == "NS":

                    PCr = request["penalty"]  # MU/ton
                    Wr = request["weight"] # ton
                    if type(self.model.decision_variable_dict["z"][p][r]) != int:
                        packages_not_handled_penalty += PCr * Wr * self.model.decision_variable_dict["z"][p][r].x

        total_arc_used += f_arc_used + g_arc_used

        # print(f"- Nb. arcs used: {total_arc_used}")
        # print(f"   > Flight arcs: {f_arc_used}")
        # print(f"   > Ground arcs: {g_arc_used}")

        print(f"- Nb. NS arcs used: {NS_arc_used}")
        print(f"- Nb. packages handled: {115-NS_arc_used}")
        print(f"- Nb. packages not handled: {NS_arc_used}")
        print(f"- Total packages not handled penalty: {packages_not_handled_penalty}")

if __name__ == '__main__':
    Results(show=False,save=True,max_time=3600)


import torch
from torch.autograd import Variable
import numpy as np
import pdb, os, argparse
from skimage import io
from tqdm import tqdm
from model.VSOD_model import RGBDVSODModel
from data import get_loader

def LOG(logfile, output):
    with open(logfile, 'a') as f:
        f.write(output)

def eval_data(opt, test_loader, ckpt_name, is_ResNet=True, ckpt_path=None):
    model = RGBDVSODModel(opt, isTrain=False, is_ResNet=is_ResNet)
    if is_ResNet:
        model.load_state_dict(torch.load(ckpt_path + 'model.pth.' + str(ckpt_name)))
    else:
        model.load_state_dict(torch.load(ckpt_path + 'model.pth.' + str(ckpt_name)))

    cuda = torch.cuda.is_available()
    if cuda:
        model.cuda()
    model.eval()

    if is_ResNet:
        save_path = os.path.join('./results/Resnet/')
    else:
        save_path = os.path.join('./results/VGG/')
    if not os.path.exists(save_path):
        os.makedirs(save_path)

    logfile = os.path.join('./', 'result.txt')

    print('Evaluating dataset:')
    avg_mae, img_num = 0.0, 0.0
    for i, pack in enumerate(tqdm(test_loader), start=1):
        images, gts, depths, name = pack
        images = Variable(images)
        gts = Variable(gts)
        depths = Variable(depths)
        if cuda:
            images = images.cuda()
            gts = gts.cuda()
            depths = depths.cuda()

        _, _, res = model(images, depths)

        res = res.sigmoid().data.cpu().numpy().squeeze()
        res = (res - res.min()) / (res.max() - res.min() + 1e-8)

        os.makedirs(save_path+name[1][0],exist_ok=True)
        io.imsave(os.path.join(save_path+name[1][0], name[0][0]), np.uint8(res * 255))

        '''Evaluate MAE'''
        gt = gts.data.cpu().numpy().squeeze()
        mea = np.abs(res - gt).mean()
        if mea == mea:  # for Nan
            avg_mae += mea
            img_num += 1.0
    avg_mae /= img_num
    print('[MAE] The current evaluation metric is: {:.4f} mae.'.format(avg_mae))
    LOG(logfile, 'model.pth.{} CKPT with {:.4f} mae.\n'.format(str(ckpt_name), avg_mae))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--testsize', type=int, default=320, help='testing size')
    parser.add_argument('--baseline_mode', type=bool, default=False, help='whether apply baseline mode or not')
    parser.add_argument('--sample_rate', type=int, default=3, help='sample rate')
    parser.add_argument('--stm_queue_size', type=int, default=3, help='stm queue size')
    parser.add_argument('--is_ResNet', type=bool, default=True, help='VGG or ResNet backbone')
    parser.add_argument('--win_size', type=int, default=-1, help='if not given, mem size + 1')
    cfg = parser.parse_args()

    if cfg.win_size == -1:
        cfg.win_size = cfg.stm_queue_size + 1
    interval = [cfg.win_size - 1, 0]
    assert (len(interval) == 2 and interval[0] >= 0 and interval[1] >= 0)

    videos_ROOT = "Your_DViSal_dataset_path/"
    ckpt_path = 'Your_ckpt_save_path/'

    ckpt_name = 'best'       # specify ckpt name, 'best'+.pth
    test_name = 'test_all'   # specify testset, e.g., test_DET, test_track3D

    test_loader = get_loader(videos_ROOT, batchsize=1, trainsize=cfg.testsize, shuffle=False, pin_memory=False,
                             subset=test_name, augmentation=False, interval=interval, sample_rate=cfg.sample_rate)
    eval_data(cfg, test_loader, ckpt_name, is_ResNet=cfg.is_ResNet, ckpt_path= ckpt_path)


from mta_api import MtaApi
from print_dash import PrintDash
import json
from tabulate import tabulate
import time
import sys
import itertools
from datetime import date
from datetime import datetime

from colorama import Fore, Back, Style

from weather import Weather

# print(Fore.RED + 'some red text')
# print(Back.GREEN + 'and with a green background')
# print(Style.DIM + 'and in dim text')
# print(Style.RESET_ALL)
# print('back to normal now')

use_local = False

train_getter = MtaApi()
print_dash = PrintDash()
weather = Weather()
colors = Fore.BLACK + Back.WHITE

spinner = itertools.cycle(["-", "/", "|", "\\"])
busy = True

def sleep_spinner():
    i = 0
    while i < 60:
        sys.stdout.write(next(spinner))  # write the next character
        sys.stdout.flush()  # flush stdout buffer (actual character display)
        sys.stdout.write("\b")  # erase the last written char
        time.sleep(1)
        i += 1

while True:
    sys.stdout.flush()
    t = time.localtime()
    today = date.today()
    current_time = datetime.now().time()
    hours = current_time.hour
    minutes = current_time.minute
    current_time_in_minutes = hours * 60 + minutes

    if current_time_in_minutes > int(weather.get_sunrise()) and current_time_in_minutes < int(weather.get_sunset()):
        colors = Fore.BLACK + Back.WHITE
    else:
        colors = Fore.WHITE + Back.BLACK
    train_board = train_getter.get_trains(use_local)

    x = 0
    while x < 10:
        print(colors + "\n")
        x += 1
    current_time = time.strftime("%I:%M %p")
    current_date = today.strftime("%m / %d / %Y")
    print(colors + current_time + "  |  " + current_date)
    print(colors + weather.get_weather_printout())
    print(
        colors
        + "\n"
        + tabulate(print_dash.format_trains_to_table(train_board), tablefmt="plain")
    )
    # time.sleep(60)
    sleep_spinner()


import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from router.route import router
from config.env import *

app = FastAPI(
    redoc_url=False
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=os.getenv('CORS_ALLOW_ORIGINS'),
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
async def root():
    return {
        "Hello": "Welcome to the Spending API",
        "Github": "https://github.com/Paulo-Lopes-Estevao/expensecontrol",
        "Documentation Swegger": "https://fast-hamlet-77449.herokuapp.com/docs"
        }
app.include_router(router)

if __name__ == '__main__':
    uvicorn.run(app, host='0.0.0.0', port=os.getenv("PORT"))


import sys
from collections import deque
from copy import deepcopy
input = sys.stdin.readline

N = int(input())
candy = [list(input().rstrip()) for _ in range(N)]
u = [[1] * N for _ in range(N)]
dy = [-1, 0, 1, 0]
dx = [0, 1, 0, -1]

qu = deque()
for y in range(N):
    for x in range(N):
        if u [y][x]:
            for i in range(4):
                r, c = y + dy[i], x + dx[i]
                if r < 0 or r >= N or c < 0 or c >= N: continue
                if candy[y][x] == candy[r][c]: continue
                qu.append((y, x, r, c))
                u[y][x] = u[r][c] = 0

ans = 0
while qu:
    if ans == N: break
    n_candy = deepcopy(candy)
    y, x, r, c = qu.popleft()
    n_candy[y][x], n_candy[r][c] = n_candy[r][c], n_candy[y][x]

    ret1 = ret2 = 0
    for i in range(N):
        cnt1 = [1, 1]
        cnt2 = [1, 1]
        for j in range(1, N):
            if n_candy[i][j-1] == n_candy[i][j]:
                cnt1[0] += 1
            if n_candy[i][j-1] != n_candy[i][j] or j == N - 1:
                cnt1[1] = max(cnt1[0], cnt1[1])
                cnt1[0] = 1

            if n_candy[j-1][i] == n_candy[j][i]:
                cnt2[0] += 1
            if n_candy[j-1][i] != n_candy[j][i] or j == N - 1:
                cnt2[1] = max(cnt2[0], cnt2[1])
                cnt2[0] = 1

        ret1 = max(ret1, cnt1[1])
        ret2 = max(ret2, cnt2[1])

    ans = max(ret1, ret2, ans)

print(ans)


import numpy as np

class GlobalRoutePlannerDAO(object):  # DAO, data access object?
    """
    This class is the data access layer for fetching data
    from the carla server instance for GlobalRoutePlanner
    """

    def __init__(self, wmap, sampling_resolution):  # from interpolate in route_manipulation GlobalRoutePlannerDAO(world.get_map(), hop_resolution)  # hop_resolution=1.0
        """
        Constructor method.

            :param wmap: carla.world object
            :param sampling_resolution: sampling distance between waypoints
        """
        self._sampling_resolution = sampling_resolution
        self._wmap = wmap

    def get_topology(self):
        """
        Accessor for topology.
        This function retrieves topology from the server as a list of
        road segments as pairs of waypoint objects, and processes the
        topology into a list of dictionary objects.

            :return topology: list of dictionary objects with the following attributes
                entry   -   waypoint of entry point of road segment
                entryxyz-   (x,y,z) of entry point of road segment
                exit    -   waypoint of exit point of road segment
                exitxyz -   (x,y,z) of exit point of road segment
                path    -   list of waypoints separated by 1m from entry
                            to exit
        """
        topology = []
        # Retrieving waypoints to construct a detailed topology
        for segment in self._wmap.get_topology():  #of the whole map

            '''
            Carla world getter method
            get_topology(self)
            Returns a list of tuples describing a minimal graph of the topology of the OpenDRIVE file.
            The tuples contain pairs of waypoints located either at the point a road begins or ends.
            The first one is the origin and the second one represents another road end that can be reached.
            This graph can be loaded into NetworkX to work with.
            Output could look like this: [(w0, w1), (w0, w2), (w1, w3), (w2, w3), (w0, w4)].
            Return: list(tuple(carla.Waypoint, carla.Waypoint))
            '''

            wp1, wp2 = segment[0], segment[1]
            l1, l2 = wp1.transform.location, wp2.transform.location
            # Rounding off to avoid floating point imprecision
            x1, y1, z1, x2, y2, z2 = np.round([l1.x, l1.y, l1.z, l2.x, l2.y, l2.z], 0)
            wp1.transform.location, wp2.transform.location = l1, l2
            seg_dict = dict()
            seg_dict['entry'], seg_dict['exit'] = wp1, wp2
            seg_dict['entryxyz'], seg_dict['exitxyz'] = (x1, y1, z1), (x2, y2, z2)
            seg_dict['path'] = []
            endloc = wp2.transform.location
            if wp1.transform.location.distance(endloc) > self._sampling_resolution:
                w = wp1.next(self._sampling_resolution)[0]
                while w.transform.location.distance(endloc) > self._sampling_resolution:  # while loop :3
                    seg_dict['path'].append(w)
                    w = w.next(self._sampling_resolution)[0]
            else:
                seg_dict['path'].append(wp1.next(self._sampling_resolution)[0])
            topology.append(seg_dict)

        #for segs in topology:
        #    for key in segs.keys():
        #        print(key)

        '''
        These were the keys printed
        entry
        exit
        entryxyz
        exitxyz
        path
        '''

        #for segs in topology:
        #    for key, value in segs.items():
        #        print(f"{key} has these values {value}")

        '''
       The first dictionay segs in topology had the following keys and their corresponding values
        entry has these values Waypoint(Transform(Location(x=52.700909, y=187.576401, z=0.000000), Rotation(pitch=360.000000, yaw=-179.973694, roll=0.000000)))
        exit has these values Waypoint(Transform(Location(x=34.700912, y=187.568146, z=0.000000), Rotation(pitch=360.000000, yaw=180.026260, roll=0.000000)))
        entryxyz has these values (53.0, 188.0, 0.0)
        exitxyz has these values (35.0, 188.0, 0.0)
        path has these values [<carla.libcarla.Waypoint object at 0x000002032A20AB10>, <carla.libcarla.Waypoint object at 0x000002032A20ABD0>,
        <carla.libcarla.Waypoint object at 0x000002032A20AC30>, <carla.libcarla.Waypoint object at 0x000002032A20AC90>,
        <carla.libcarla.Waypoint object at 0x000002032A20ACF0>, <carla.libcarla.Waypoint object at 0x000002032A20AD50>,
        <carla.libcarla.Waypoint object at 0x000002032A20ADB0>, <carla.libcarla.Waypoint object at 0x000002032A20AE10>,
        <carla.libcarla.Waypoint object at 0x000002032A20AE70>, <carla.libcarla.Waypoint object at 0x000002032A20AED0>,
         <carla.libcarla.Waypoint object at 0x000002032A20AF30>, <carla.libcarla.Waypoint object at 0x000002032A20AF90>,
          <carla.libcarla.Waypoint object at 0x000002032A20B030>, <carla.libcarla.Waypoint object at 0x000002032A20B090>,
           <carla.libcarla.Waypoint object at 0x000002032A20B0F0>, <carla.libcarla.Waypoint object at 0x000002032A20B150>,
            <carla.libcarla.Waypoint object at 0x000002032A20B1B0>]
        '''

        return topology  # a lot of seg_dic in topology. These seg_dic have entries, exits and paths for those particular entry-exit
        #returns a densely populated list of dictionaries that have entry exit and a waypoint path between them

    def get_waypoint(self, location):
        """
        The method returns waypoint at given location

            :param location: vehicle location
            :return waypoint: generated waypoint close to location
        """
        waypoint = self._wmap.get_waypoint(location)
        return waypoint

    def get_resolution(self):
        """ Accessor for self._sampling_resolution """
        return self._sampling_resolution


from itertools import groupby
import sys

class Entry(object):
    __slots__ = ("when", "who", "what")

    def __init__(self, when, who, what):
        self.when = when
        self.who = who
        self.what = what

    def __repr__(self):
        return "when={self.when}, who={self.who}, what={self.what})".format(self=self)

class Item(object):
    __slots__ = ("duration", "who")

    def __init__(self, duration, who):
        self.duration = duration
        self.who = who

    def __repr__(self):
        return "when={self.duration}, who={self.who})".format(self=self)

def load():
    def make(line):
        parts = line.split(',')
        return Entry(int(parts[0].strip()), parts[1].strip(), parts[2].strip())

    with open(input_file, "r") as f:
        return [make(line) for line in f]

def save(items):
    with open(output_file, "w") as f:
        f.write("duration, who")
        for item in items:
            f.write("\n{0}, {1}".format(item.duration, item.who))

def work():
    entries = load()

    keys = []
    groups = []
    entries = sorted(entries, key=lambda x: x.who)
    for k, g in groupby(entries, key=lambda x: x.who):
        groups.append(list(g))
        keys.append(k)

    items = []

    for i in range(0, len(keys)):
        g = groups[i]
        ordered = list(sorted(g, key=lambda x: x.when))

        start = 0
        duration = 0

        for entry in ordered:
            if entry.what == "login":
                start = entry.when
            elif entry.what == "logout":
                duration += entry.when - start

        items.append(Item(duration, keys[i]))

    items = sorted(items, key=lambda x: x.duration, reverse=True)

    save(items)

input_file = sys.argv[1]
output_file = "out.txt"

if len(sys.argv) > 2:
    output_file = sys.argv[2]

work()


from odoo.exceptions import UserError
from odoo.tests import Form, common

class TestGovPurchaseAgreement(common.TransactionCase):
    def setUp(self):
        super().setUp()
        self.pr_model = self.env["purchase.requisition"]
        self.po_model = self.env["purchase.order"]
        self.partner1 = self.env.ref("base.res_partner_1")
        self.product1 = self.env.ref("product.product_product_7")
        self.agreement = self.env.ref("agreement.market1")
        self.agreement2 = self.env.ref("agreement.market2")

    def _create_pr(self, po_type, qty, unit_price):
        pr = self.pr_model.create(
            {
                "user_id": self.env.ref("base.user_root").id,
                "type_id": self.env.ref("purchase_requisition.type_multi").id,
                "po_type": po_type,
                "line_ids": [
                    (
                        0,
                        0,
                        {
                            "product_id": self.product1.id,
                            "product_qty": qty,
                            "product_uom_id": self.product1.uom_po_id.id,
                            "price_unit": unit_price,
                        },
                    )
                ],
            }
        )
        return pr

    def _create_purchase(self, pr=False):
        Purchase = self.env["purchase.order"]
        view_id = "purchase.purchase_order_form"
        with Form(Purchase, view=view_id) as po:
            po.partner_id = self.partner1
            po.requisition_id = pr
        purchase = po.save()
        return purchase

    def test_01_po_agreement(self):
        """Test process agreement with purchase"""
        pr = self._create_pr("agreement", 1, 100.0)
        pr.action_in_progress()
        purchase = self._create_purchase(pr)
        # No agreement. can't confirm
        self.assertEqual(len(purchase.agreement_ids.ids), 0)
        with self.assertRaises(UserError):
            purchase.button_confirm()
        self.assertFalse(self.agreement.purchase_order_id)
        # Test partner difference on purchase and agreement
        with self.assertRaises(UserError):
            self.agreement.purchase_order_id = purchase.id
        # Test change purchase in agreement, partner will change following purchase
        old_partner = self.agreement.partner_id
        with Form(self.agreement) as ag:
            ag.purchase_order_id = purchase
        ag.save()
        self.assertNotEqual(self.agreement.partner_id, old_partner)
        self.assertEqual(self.agreement.partner_id, self.partner1)
        # check agreement on purchase
        self.assertEqual(purchase.agreement_count, 1)
        action = purchase.action_view_agreement()
        self.assertEqual(action["res_id"], self.agreement.id)
        # Add duplicate purchase into new agreement
        with Form(self.agreement2) as ag:
            ag.purchase_order_id = purchase
        ag.save()
        self.assertEqual(purchase.agreement_count, 2)
        action = purchase.action_view_agreement()
        self.assertEqual(action["domain"][0][2], purchase.agreement_ids.ids)
        # Test inverse, it should be not change
        self.assertFalse(self.agreement.invoice_plan_ids)
        self.assertFalse(purchase.invoice_plan_ids)
        self.agreement._inverse_invoice_plan_ids()
        self.assertFalse(self.agreement.invoice_plan_ids)
        self.assertFalse(purchase.invoice_plan_ids)
        # _inverse_invoice_plan_ids
        purchase.button_confirm()


"""URL patterns."""

from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views

urlpatterns = [
    url(r'^login/$', auth_views.login, name='login', kwargs={'template_name': 'flasharray/login.html'}),
    url(r'^logout/$', auth_views.logout, name='logout', kwargs={'next_page': '/'}),
    url(r'home.html', views.index, name='home'),
    url(r'logs.html', views.logs, name='logs'),
    url(r'^create_array', views.FlashArrayCreate.as_view(), name='create_array'),
    url(r'^delete_array/(?P<pk>[\w-]+)$', views.FlashArrayDelete.as_view(), name='delete_array'),
    url(r'^update_array/(?P<pk>[\w-]+)$', views.FlashArrayUpdate.as_view(), name='update_array'),
]


from lib.binance import getCandles
from lib.order import buyWithQt, sellWithQt, borrowAndBuy, borrowAndSell
from lib.manager import get_asset
import time

class CryptoGenerator:
    def __init__(self, symbol, action_func, side="SHORT", leverage=5, slr=0.01, tpr=0.01, init_quote=10):
        if side == "LONG":
            self.side = side
        else:
            self.side = "SHORT"
        self.candles_1m = getCandles(symbol, "15m")
        self.symbol = symbol
        self.position_on = False
        self.stop_loss = 0
        self.take_profit = 0
        self.leverage = leverage
        self.initial_quote = init_quote  * self.leverage
        self.action_func = action_func
        self.posQt = 0
        self.slr = slr
        self.tpr = tpr

    def updateCandles(self):
        if (time.time() * 1000) >= int(self.candles_1m[-1][0] + (60000*15)):
            candles_1m = getCandles(self.symbol, "15m", int(self.candles_1m[-1][0] + (60000*15)))
            if len(candles_1m) > 0:
                if len(candles_1m) == 500:
                    self.candles_1m = candles_1m
                else:
                    self.candles_1m = self.candles_1m[len(candles_1m):] + candles_1m
            return True
        else:
            return False

    def longPosition(self):
        response = borrowAndBuy(self.symbol, self.leverage)
        print(response)
        if "executedQty" in response:
            self.posQt = response["executedQty"]
            self.stop_loss = self.candles_1m[-1][4] - (self.candles_1m[-1][4] * self.slr)
            self.take_profit = self.candles_1m[-1][4] + (self.candles_1m[-1][4] * self.tpr)
            self.position_on = self.candles_1m[-1][4]
        return response

    def shortPosition(self):
        response = borrowAndSell(self.symbol, self.leverage)
        print(response)
        if "executedQty" in response:
            self.posQt = response["executedQty"]
            self.stop_loss = self.candles_1m[-1][4] + (self.candles_1m[-1][4] * self.slr)
            self.take_profit = self.candles_1m[-1][4] - (self.candles_1m[-1][4] * self.tpr)
            self.position_on = self.candles_1m[-1][4]
        return response

    def stopLoss(self):
        if self.side == "LONG":
            response = sellWithQt(self.symbol, self.posQt)
            if "orderId" in response:
                self.position_on = False
            return response
        else:
            response = buyWithQt(self.symbol, (float(self.posQt) * self.candles_1m[-1][4]))
            if "orderId" in response:
                self.position_on = False
            return response

    def takeProfit(self):
        if self.side == "LONG":
            if (float(self.posQt) * self.candles_1m[-1][4]) > self.initial_quote:
                response = sellWithQt(self.symbol, (self.initial_quote / self.candles_1m[-1][4]))
                if "orderId" in response:
                    self.position_on = False
                return response
            else:
                response = sellWithQt(self.symbol, self.posQt)
                if "orderId" in response:
                    self.position_on = False
                return response
        else:
            if (float(self.posQt) * self.candles_1m[-1][4]) > self.initial_quote:
                response = buyWithQt(self.symbol, (float(self.posQt) * self.position_on))
                if "orderId" in response:
                    self.position_on = False
                return response
            else:
                response = buyWithQt(self.symbol, (float(self.posQt) * self.candles_1m[-1][4]))
                if "orderId" in response:
                    self.position_on = False
                return response
    def run(self):
        print("Running the bot")
        while True:
            if self.updateCandles():
                if self.action_func(self.candles_1m) and not self.position_on:
                    if self.side == "LONG":
                        self.longPosition()
                    else:
                        self.shortPosition()
                elif self.position_on and self.side == "LONG":
                    if self.candles_1m[-1][4] >= self.take_profit:
                        self.takeProfit()
                    elif self.candles_1m[-1][4] <= self.stop_loss:
                        self.stopLoss()
                elif self.position_on and self.side == "SHORT":
                    if self.candles_1m[-1][4] <= self.take_profit:
                        self.takeProfit()
                    elif self.candles_1m[-1][4] >= self.stop_loss:
                        self.stopLoss()
            time.sleep(5)

##### SELL RESPONSE #####
#{
#    'symbol': 'BNBUSDT',
#    'orderId': 4302657985,
#    'clientOrderId': 'default_425adfe35c784685ab0f3605ad6a',
#    'transactTime': 1661965359352,
#    'price': '0',
#    'origQty': '0.044',
#    'executedQty': '0.044',
#    'cummulativeQuoteQty': '12.3728',
#    'status': 'FILLED',
#    'timeInForce': 'GTC',
#    'type': 'MARKET',
#    'side': 'SELL',
#    'fills': [{'price': '281.2', 'qty': '0.044', 'commission': '0.0123728', 'commissionAsset': 'USDT'}],
#    'isIsolated': True
#}

##### BUY RESPONSE #####
#{
#    'symbol': 'BNBUSDT',
#    'orderId': 4302660806,
#    'clientOrderId': 'default_900a8fc98c8e4da8901e7e5bd60a',
#    'transactTime': 1661965480980,
#    'price': '0',
#    'origQty': '0.044',
#    'executedQty': '0.044',
#    'cummulativeQuoteQty': '12.364',
#    'status': 'FILLED',
#    'timeInForce': 'GTC',
#    'type': 'MARKET',
#    'side': 'BUY',
#    'fills': [{'price': '281', 'qty': '0.044', 'commission': '0.000033', 'commissionAsset': 'BNB'}],
#    'isIsolated': True
#}


#!/usr/bin/python3

""" this a python3 script that prints a message """

import sys

def main():

    """ prints out a message using write """

    message = "and that piece of art is useful - Dora Korpar, 2015-10-19"

    sys.stderr.write(message + "\n")

if __name__ == "__main__":
    main()
    sys.exit(1)


class Solution:
    def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
        maxi = max(candies)
        n = len(candies)
        a = []
        for i in range(n):
            check = candies[i] + extraCandies
            #print(check)
            a.append(check >= maxi)
            #print(a)
            check = 0
        return a


from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import numpy as np
import struct
import matplotlib.pyplot as plt
import matplotlib.animation as animation

filepath = "/home/rsa/TMP/TramaTemporal.tmp"
filepathM = "/home/rsa/Resultados/RegistroContinuo/UCUE01_220712-230954.dat"

#********************************************************************************
#Variables y parametros
#********************************************************************************
#Lectura del archivo binario:
tramaSize = 2506
valCH1 = 0
valCH2 = 0
valCH3 = 0
xData = [0 for i in range(4)]
yData = [0 for i in range(4)]
zData = [0 for i in range(4)]

#Parametros del grafico:
x_len = 120         # Number of points to display
y1_range = [-2, 2]  # Range of possible Y values to display
y2_range = [-2, 2]
y3_range = [8, 12]
# Crea la figura y los subplots
plt.style.use('dark_background')
fig = plt.figure()
ax1 = fig.add_subplot(3, 1, 1)
ax2 = fig.add_subplot(3, 1, 2)
ax3 = fig.add_subplot(3, 1, 3)
#Establece los limistes del eje X
xs = list(range(0, 120))
ys1 = [0] * x_len
ys2 = [0] * x_len
ys3 = [0] * x_len
#Establece los limites del eje Y
ax1.set_ylim(y1_range)
ax2.set_ylim(y2_range)
ax3.set_ylim(y3_range)
#Establece los colores de fondo de los subplots
ax1.set_facecolor('#181c1fff')
ax2.set_facecolor('#181c1fff')
ax3.set_facecolor('#181c1fff')
#Establece el estilo del grid
ax1.grid(linestyle='-',linewidth=0.2)
ax2.grid(linestyle='-',linewidth=0.2)
ax3.grid(linestyle='-',linewidth=0.2)
#Establece las marcas del eje X
plt.setp(ax1.get_xticklabels(), visible=False)     #Borra las marcar del plot x1
plt.setp(ax2.get_xticklabels(), visible=False)     #Borra las marcar del plot x2
ax3.set_xticks([0,20,40,60,80,100,120])     #Selecciona las marcas de los puntos extremos y mitad del eje X
ax3.set_xticklabels([-60,'','',-30,'','',0])     #Remplaza las marcas seleccionadas por los valores 0, 30 y 60
ax1.tick_params(labelsize=9,labelcolor='gray')
ax2.tick_params(labelsize=9,labelcolor='gray')
ax3.tick_params(labelsize=9,labelcolor='gray')
#Establece las etiquetas de los ejes X y Y
ax1.set_ylabel('CH1')
ax2.set_ylabel('CH2')
ax3.set_ylabel('CH3')
ax3.set_xlabel('Tiempo [seg]')
# Create a blank line. We will update the line in animate
line1, = ax1.plot(xs, ys1, color='#5bd15eff')
line2, = ax2.plot(xs, ys2, color='#5bd15eff')
line3, = ax3.plot(xs, ys3, color='#5bd15eff')

#********************************************************************************

#********************************************************************************
#Metodo para leer el archivo de texto y extraer los valores de los 3 ejes:
#********************************************************************************
def LeerArchivo():

    #variables globales
    global valCH1
    global valCH2
    global valCH3

    #print("imprimiendo...")

    # Abre el archivo para lectura de binarios "rb"
    objFile = open(filepath, "rb")
    tramaDatos = np.fromfile(objFile, np.int8, tramaSize)

    # Extrae los datos de aceleracion de los 3 ejes:
    for i in range(0, 3):
        xData[i] = tramaDatos[i + 1]
        yData[i] = tramaDatos[i + 4]
        zData[i] = tramaDatos[i + 7]

    #Calculo aceleracion eje x:
    xValue = ((xData[0]<<12)&0xFF000)+((xData[1]<<4)&0xFF0)+((xData[2]>>4)&0xF)
	 #Apply two complement
    if (xValue >= 0x80000):
        xValue = xValue & 0x7FFFF
        xValue = -1*(((~xValue)+1)& 0x7FFFF)

    valCH1 = xValue * (9.8/pow(2,18))

    #Calculo aceleracion eje y:
    yValue = ((yData[0]<<12)&0xFF000)+((yData[1]<<4)&0xFF0)+((yData[2]>>4)&0xF)
	 #Apply two complement
    if (yValue >= 0x80000):
        yValue = yValue & 0x7FFFF
        yValue = -1*(((~yValue)+1)& 0x7FFFF)

    valCH2 = yValue * (9.8/pow(2,18))

    #Calculo aceleracion eje z:
    zValue = ((zData[0]<<12)&0xFF000)+((zData[1]<<4)&0xFF0)+((zData[2]>>4)&0xF)
	 #Apply two complement
    if (zValue >= 0x80000):
        zValue = zValue & 0x7FFFF
        zValue = -1*(((~zValue)+1)& 0x7FFFF)

    valCH3 = zValue * (9.8/pow(2,18))

    #Imprime la hora y fecha recuperada de la trama de datos
    #print("Datos de la trama:")
    print("|%02d:%02d:%02d %02d/%02d/%02d|" % (tramaDatos[tramaSize-3], tramaDatos[tramaSize-2],  tramaDatos[tramaSize-1], tramaDatos[tramaSize-6], tramaDatos[tramaSize-5], tramaDatos[tramaSize-4]))
	#Imprime los datos de aceleracion:
    print("|X: %2.8f Y: %2.8f Z: %2.8f|" % (valCH1, valCH2, valCH3))

    #print("%f   %f   %f" % (valCH1, valCH2, valCH3))

    # Al final cierra el archivo de lectura
    objFile.close()

#********************************************************************************

#********************************************************************************
#Metodo que se llama periodicamente desde FuncAnimation
#********************************************************************************
def animate(i):

    global xs
    global ys1
    global ys2
    global ys3

    # Actualiza la medicion de los canales CH1, CH2 y CH3
    medCH1 = valCH1
    medCH2 = valCH2
    medCH3 = valCH3

    # Add x and y to lists
    ys1.append(medCH1)
    ys2.append(medCH2)
    ys3.append(medCH3)

    # Limit y list to set number of items
    ys1 = ys1[-x_len:]
    ys2 = ys2[-x_len:]
    ys3 = ys3[-x_len:]

    line1.set_data(xs,ys1)
    line2.set_data(xs,ys2)
    line3.set_data(xs,ys3)

    return line1,line2,line3

#********************************************************************************

#********************************************************************************
#Clase para monitorizar cambios en los archivos:
#********************************************************************************
class MyEventHandler(FileSystemEventHandler):
    def on_modified(self, event):
        #print(event.src_path, "modificado.")
        LeerArchivo()

#********************************************************************************

#********************************************************************************
#Main
#********************************************************************************
observer = Observer()
observer.schedule(MyEventHandler(), filepathM, recursive=False)
observer.start()

# Set up plot to call animate() function periodically
#ani = animation.FuncAnimation(fig, animate, fargs=(ys1, ys2, ys3, ), interval=500, blit=True)
ani = animation.FuncAnimation(fig, animate, interval=500, blit=True)
plt.show()

try:
    while observer.is_alive():
        observer.join(1)
        print("hola")
except KeyboardInterrupt:
    observer.stop()
observer.join()

#********************************************************************************


import numpy as np

import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.autograd as autograd

from multiprocessing_env import SubprocVecEnv
from minipacman import MiniPacman

import matplotlib.pyplot as plt

from tqdm import tqdm

#USE_CUDA = torch.cuda.is_available()
#Variable = lambda *args, **kwargs: autograd.Variable(*args, **kwargs).cuda() if USE_CUDA else autograd.Variable(*args, **kwargs)

class OnPolicy(nn.Module):
    def __init__(self):
        super(OnPolicy, self).__init__()

    def forward(self, x):
        raise NotImplementedError

    def act(self, x, deterministic=False):
        logit, value = self.forward(x)
        probs = F.softmax(logit)

        if deterministic:
            action = probs.max(1)[1]
        else:
            action = probs.multinomial(1)

        return action

    def evaluate_actions(self, x, action):
        logit, value = self.forward(x)

        probs     = F.softmax(logit)
        log_probs = F.log_softmax(logit)

        action_log_probs = log_probs.gather(1, action)
        entropy = -(probs * log_probs).sum(1).mean()

        return logit, action_log_probs, value, entropy

class ActorCritic(OnPolicy):
    def __init__(self, in_shape, num_actions):
        super(ActorCritic, self).__init__()

        self.in_shape = in_shape

        self.features = nn.Sequential(
            nn.Conv2d(in_shape[0], 16, kernel_size=3, stride=1),
            nn.ReLU(),
            nn.Conv2d(16, 16, kernel_size=3, stride=2),
            nn.ReLU(),
        )

        self.fc = nn.Sequential(
            nn.Linear(self.feature_size(), 256),
            nn.ReLU(),
        )

        self.critic  = nn.Linear(256, 1)
        self.actor   = nn.Linear(256, num_actions)

    def forward(self, x):
        x = self.features(x)
        x = x.view(x.size(0), -1)
        x = self.fc(x)
        logit = self.actor(x)
        value = self.critic(x)
        return logit, value

    def feature_size(self):
        return self.features(autograd.Variable(torch.zeros(1, *self.in_shape))).view(1, -1).size(1)

# @ikostrikov style

class RolloutStorage(object):
    def __init__(self, num_steps, num_envs, state_shape):
        self.num_steps = num_steps
        self.num_envs  = num_envs
        self.states  = torch.zeros(num_steps + 1, num_envs, *state_shape)
        self.rewards = torch.zeros(num_steps,     num_envs, 1)
        self.masks   = torch.ones(num_steps  + 1, num_envs, 1)
        self.actions = torch.zeros(num_steps,     num_envs, 1).long()
        #self.use_cuda = False

    def cuda(self):
        #self.use_cuda  = True
        self.states    = self.states.cuda()
        self.rewards   = self.rewards.cuda()
        self.masks     = self.masks.cuda()
        self.actions   = self.actions.cuda()

    def insert(self, step, state, action, reward, mask):
        self.states[step + 1].copy_(state)
        self.actions[step].copy_(action)
        self.rewards[step].copy_(reward)
        self.masks[step + 1].copy_(mask)

    def after_update(self):
        self.states[0].copy_(self.states[-1])
        self.masks[0].copy_(self.masks[-1])

    def compute_returns(self, next_value, gamma):
        returns   = torch.zeros(self.num_steps + 1, self.num_envs, 1)
        #if self.use_cuda:
        #    returns = returns.cuda()
        returns[-1] = next_value
        for step in reversed(range(self.num_steps)):
            returns[step] = returns[step + 1] * gamma * self.masks[step + 1] + self.rewards[step]
        return returns[:-1]

def main():
    mode = "regular"
    num_envs = 16

    def make_env():
        def _thunk():
            env = MiniPacman(mode, 1000)
            return env

        return _thunk

    envs = [make_env() for i in range(num_envs)]
    envs = SubprocVecEnv(envs)

    state_shape = envs.observation_space.shape

    #a2c hyperparams:
    gamma = 0.99
    entropy_coef = 0.01
    value_loss_coef = 0.5
    max_grad_norm = 0.5
    num_steps = 5
    num_frames = int(10e3)

    #rmsprop hyperparams:
    lr    = 7e-4
    eps   = 1e-5
    alpha = 0.99

    #Init a2c and rmsprop
    actor_critic = ActorCritic(envs.observation_space.shape, envs.action_space.n)
    optimizer = optim.RMSprop(actor_critic.parameters(), lr, eps=eps, alpha=alpha)

    #if USE_CUDA:
    #    actor_critic = actor_critic.cuda()

    rollout = RolloutStorage(num_steps, num_envs, envs.observation_space.shape)
    #rollout.cuda()

    all_rewards = []
    all_losses  = []

    state = envs.reset()
    state = torch.FloatTensor(np.float32(state))

    rollout.states[0].copy_(state)

    episode_rewards = torch.zeros(num_envs, 1)
    final_rewards   = torch.zeros(num_envs, 1)

    for i_update in tqdm(range(num_frames)):

        for step in range(num_steps):
            action = actor_critic.act(autograd.Variable(state))

            next_state, reward, done, _ = envs.step(action.squeeze(1).cpu().data.numpy())

            reward = torch.FloatTensor(reward).unsqueeze(1)
            episode_rewards += reward
            masks = torch.FloatTensor(1-np.array(done)).unsqueeze(1)
            final_rewards *= masks
            final_rewards += (1-masks) * episode_rewards
            episode_rewards *= masks

            #if USE_CUDA:
            #    masks = masks.cuda()

            state = torch.FloatTensor(np.float32(next_state))
            rollout.insert(step, state, action.data, reward, masks)

        _, next_value = actor_critic(autograd.Variable(rollout.states[-1], volatile=True))
        next_value = next_value.data

        returns = rollout.compute_returns(next_value, gamma)

        logit, action_log_probs, values, entropy = actor_critic.evaluate_actions(
            autograd.Variable(rollout.states[:-1]).view(-1, *state_shape),
            autograd.Variable(rollout.actions).view(-1, 1)
        )

        values = values.view(num_steps, num_envs, 1)
        action_log_probs = action_log_probs.view(num_steps, num_envs, 1)
        advantages = autograd.Variable(returns) - values

        value_loss = advantages.pow(2).mean()
        action_loss = -(autograd.Variable(advantages.data) * action_log_probs).mean()

        optimizer.zero_grad()
        loss = value_loss * value_loss_coef + action_loss - entropy * entropy_coef
        loss.backward()
        nn.utils.clip_grad_norm(actor_critic.parameters(), max_grad_norm)
        optimizer.step()

        if i_update % num_frames == 0:
            all_rewards.append(final_rewards.mean())
            all_losses.append(loss.item())

            #clear_output(True)
            plt.figure(figsize=(20,5))
            plt.subplot(131)
            plt.title('epoch %s. reward: %s' % (i_update, np.mean(all_rewards[-10:])))
            plt.plot(all_rewards)
            plt.subplot(132)
            plt.title('loss %s' % all_losses[-1])
            plt.plot(all_losses)
            plt.show()

        rollout.after_update()

    torch.save(actor_critic.state_dict(), "actor_critic_" + mode)

    import time

    def displayImage(image, step, reward):
        #clear_output(True)
        s = "step: " + str(step) + " reward: " + str(reward)
        plt.figure(figsize=(10,3))
        plt.title(s)
        plt.imshow(image)
        plt.show()
        time.sleep(0.1)

    env = MiniPacman(mode, 1000)

    done = False
    state = env.reset()
    total_reward = 0
    step   = 1

    while not done:
        current_state = torch.FloatTensor(state).unsqueeze(0)
        #if USE_CUDA:
        #    current_state = current_state.cuda()

        action = actor_critic.act(autograd.Variable(current_state))

        next_state, reward, done, _ = env.step(action.data[0, 0])
        total_reward += reward
        state = next_state

        image = torch.FloatTensor(state).permute(1, 2, 0).cpu().numpy()
        displayImage(image, step, total_reward)
        step += 1

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
import scrapy
from ..items import MovieprojectItem

## 先使用scrapy，再使用scrapy_redis

class MovieSpider(scrapy.Spider):
    name = 'movie'  ## redis保存的文件夹名字叫movie
    allowed_domains = ['www.dy2018.com']
    start_urls = ['https://www.dy2018.com/0/']

    def parse(self, response):

        tables = response.xpath('//table[@class="tbspan"]') ## 直接找tabl
        for t in tables:
            item = MovieprojectItem()

            ##获取电影名
            ## 电影介绍
            title =  t.xpath('.//tr[2]//a[2]/text()').extract()[0]
            info = ''.join(t.xpath('.//tr[4]//p/text()').extract()).replace('\u3000','') ## 列表直接平成字符串
            # info =  info.replace('\u3000','') ##info.replace('\u3000','')##  \u3000代表中文空格
            item['title'] = title
            item['info'] = info
            yield item


# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import

import argparse
import sys
import os

import matplotlib.pyplot as plt
import pylab
import matplotlib.image as mpimg
import numpy as np
import shutil
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

reload(sys)
sys.setdefaultencoding("utf-8")

CN_CHARSET = None
CN_T_CHARSET = None
JP_CHARSET = None
KR_CHARSET = None

input_args = ['--dst_font_dir','/DataA/Harric/ChineseCharacterExp/CASIA_Dataset/Sources/64_FoundContentPrototypeTtfOtfs/Simplified/',
              '--single_img_dir', '/DataA/Harric/ChineseCharacterExp/CASIA_Dataset/PrintedData_64Fonts/'
              ]

parser = argparse.ArgumentParser(description='Convert font to images')

parser.add_argument('--dst_font_dir', dest='dst_font_dir', required=True, help='path of the target font dir')
parser.add_argument('--char_size', dest='char_size', type=int, default=150, help='character size')
parser.add_argument('--canvas_size', dest='canvas_size', type=int, default=256, help='canvas size')
parser.add_argument('--x_offset', dest='x_offset', type=int, default=20, help='x offset')
parser.add_argument('--y_offset', dest='y_offset', type=int, default=20, help='y_offset')
parser.add_argument('--single_img_dir', dest='single_img_dir', required=True,help='directory to save paired imgs')

args = parser.parse_args(input_args)

def draw_example(ch, dst_font, canvas_size, x_offset, y_offset):
    def draw_single_char(ch, font, canvas_size, x_offset, y_offset):
        img = Image.new("RGB", (canvas_size, canvas_size), (255, 255, 255))
        draw = ImageDraw.Draw(img)

        try:
            draw.text((x_offset, y_offset), ch, (0, 0, 0), font=font)
        except IOError:
            img_output = np.zeros(shape=[256, 256, 3])
            img_output = Image.fromarray(np.uint8(img_output))
            return img_output

        img_matrix = np.asarray(img)[:, :, 0]
        zero_indices = np.where(img_matrix == 0)
        exceed = 'NONE'

        if np.min(img_matrix) == np.max(img_matrix) or (0 not in img_matrix):
            img_output = np.zeros(shape=[256,256,3])
            img_output = Image.fromarray(np.uint8(img_output))
        else:
            up_p = np.min(zero_indices[0])
            down_p = np.max(zero_indices[0])
            left_p = np.min(zero_indices[1])
            right_p = np.max(zero_indices[1])

            up_down = down_p - up_p
            right_left = right_p - left_p
            if up_down > right_left:
                character_size = up_down
                if not character_size % 2 == 0:
                    character_size = character_size + 1
                    down_p = down_p + 1
                right_left_avg = (right_p + left_p) / 2
                right_p = right_left_avg + int(character_size / 2)
                left_p = right_left_avg - int(character_size / 2)
                if left_p < 0:
                    exceed = 'LEFT'
                    exceed_pixels = np.abs(left_p)
                    left_p = 0
                if right_p > 255:
                    exceed = 'RIGHT'
                    exceed_pixels = right_p - 255
                    right_p = 255

            else:
                character_size = right_left
                if not character_size % 2 == 0:
                    character_size = character_size + 1
                    right_p = right_p + 1

                up_down_avg = (up_p + down_p) / 2
                down_p = up_down_avg + int(character_size / 2)
                up_p = up_down_avg - int(character_size / 2)
                if up_p < 0:
                    exceed = 'UP'
                    exceed_pixels = np.abs(up_p)
                    up_p = 0
                if down_p > 255:
                    exceed = 'DOWN'
                    exceed_pixels = down_p - 255
                    down_p = 255

            img_matrix_cut = img_matrix[up_p:down_p, left_p:right_p]

            if not exceed=='NONE':
                if exceed=='LEFT':
                    added_pixels = np.ones([img_matrix_cut.shape[0],exceed_pixels]) * 255
                    img_matrix_cut = np.concatenate([added_pixels, img_matrix_cut], axis=1)
                elif exceed=='RIGHT':
                    added_pixels = np.ones([img_matrix_cut.shape[0], exceed_pixels]) * 255
                    img_matrix_cut = np.concatenate([img_matrix_cut,added_pixels], axis=1)
                elif exceed=='UP':
                    added_pixels = np.ones([exceed_pixels, img_matrix_cut.shape[1]]) * 255
                    img_matrix_cut = np.concatenate([added_pixels, img_matrix_cut], axis=0)
                elif exceed=='DOWN':
                    added_pixels = np.ones([exceed_pixels, img_matrix_cut.shape[1]]) * 255
                    img_matrix_cut = np.concatenate([img_matrix_cut, added_pixels], axis=0)

            img_matrix_cut = np.tile(np.reshape(img_matrix_cut,
                                                [img_matrix_cut.shape[0], img_matrix_cut.shape[1], 1]),
                                     [1, 1, 3])
            img_cut = Image.fromarray(np.uint8(img_matrix_cut))
            img_resize = img_cut.resize((150, 150), Image.ANTIALIAS)
            img_output = Image.new("RGB", (256, 256), (255, 255, 255))
            img_output.paste(img_resize, (52, 52))

        return img_output

    dst_img = draw_single_char(ch, dst_font, canvas_size, x_offset, y_offset)

    invalid_img = (np.max(dst_img) == np.min(dst_img))

    return dst_img,invalid_img

def font2img(charset,
             character_label_list,
             dst,
             char_size,
             canvas_size,
             x_offset,
             y_offset,
             single_save_dir,
             font_label='0'):
    dst_font = ImageFont.truetype(dst, size=char_size)

    if not os.path.exists(single_save_dir):
        os.makedirs(single_save_dir)

    count = 0
    valid_counter = 0
    invalid_counter = 0

    for c in charset:

        if count == len(charset):
            break

        single_256, invalid_img = draw_example(c, dst_font, canvas_size, x_offset, y_offset)
        if single_256 and (not invalid_img):
            single_64 = single_256.resize((64, 64), Image.ANTIALIAS)
            single_64.save(os.path.join(single_save_dir, "%09d_%s_%s.png" % (count, character_label_list[count], font_label)))
            valid_counter+=1
        else:
            invalid_counter+=1

        count += 1
    return valid_counter, invalid_counter

def get_chars_set_from_level1_2(path,level):
    """
    Expect a text file that each line is a char
    """
    chars = list()
    character_id_1_counter=0
    character_id_2_counter=0
    character_list=list()
    with open(path) as f:
        for line in f:

            line = u"%s" % line
            char_counter=0
            for char in line:

                current_char = line[char_counter]
                chars.append(current_char)

                if level==1:
                    character_id_1 = str(character_id_1_counter + 16 + 160)
                    character_id_2 = str(character_id_2_counter + 1 + 160)
                    character_id = character_id_1 + character_id_2

                    character_id_2_counter += 1
                    if character_id_2_counter == 94:
                        character_id_2_counter = 0
                        character_id_1_counter += 1
                elif level==2:
                    character_id_1 = str(character_id_1_counter + 56 + 160)
                    character_id_2 = str(character_id_2_counter + 1 + 160)
                    character_id = character_id_1 + character_id_2

                    character_id_2_counter += 1
                    if character_id_2_counter == 94:
                        character_id_2_counter = 0
                        character_id_1_counter += 1

                character_list.append(character_id)
                char_counter+=1
    return chars,character_list

def find_file_list( path,train_mark):
    file_list=list()
    counter=0

    dir_list=os.listdir(path)
    dir_list.sort()

    for dir in dir_list:
        current_full_path=os.path.join(path,dir)
        files = [f for f in os.listdir(current_full_path) if os.path.isfile(os.path.join(current_full_path, f))]
        files.sort()
        for fn in files:
            if fn.find('.jpg') != -1:
                file_list.append(os.path.join(current_full_path,fn))
                counter = counter + 1

    return file_list

if __name__ == "__main__":

    dir_serach_list=args.dst_font_dir.split(",")

    dst_file_list=[]
    for current_dir in dir_serach_list:
        for root, dirs, files in os.walk(current_dir):
            for name in files:

                file_path = (os.path.join(root, name))
                file_extension = os.path.splitext(file_path)[1]

                if file_extension == '.TTF' or file_extension == '.OTF' or file_extension == '.ttf' or file_extension == '.otf':
                    dst_file_list.append(os.path.join(root, name))

    dst_file_list.sort()

    charset_level1_smp, character_label_level1_smp = get_chars_set_from_level1_2(path='../charset/GB2312_Level1_Simplified.txt',level=1)
    charset_level2_smp, character_label_level2_smp = get_chars_set_from_level1_2(path='../charset/GB2312_Level2_Simplified.txt',level=2)
    charset_level1_trd, character_label_level1_trd = get_chars_set_from_level1_2(path='../charset/GB2312_Level1_Traditional.txt', level=1)
    charset_level2_trd, character_label_level2_trd = get_chars_set_from_level1_2(path='../charset/GB2312_Level2_Traditional.txt', level=2)

    if os.path.exists(args.single_img_dir):
        shutil.rmtree(args.single_img_dir)
    os.makedirs(args.single_img_dir)

    font_counter=0
    print("###########################################################################")
    for dst_file in dst_file_list:

        file_name=dst_file.split('/')
        file_name=file_name[len(file_name)-1]
        font_label=file_name.split('_')
        font_label=str(font_label[0])

        current_dir_smp = os.path.join(args.single_img_dir,'Simplified')
        current_dir_trd = os.path.join(args.single_img_dir, 'Traditional')

        current_save_dir_l1_smp = os.path.join(current_dir_smp,'GB2312_L1')
        current_save_dir_l2_smp = os.path.join(current_dir_smp, 'GB2312_L2')
        current_save_dir_l1_smp = os.path.join(current_save_dir_l1_smp, font_label)
        current_save_dir_l2_smp = os.path.join(current_save_dir_l2_smp, font_label)

        current_save_dir_l1_trd = os.path.join(current_dir_trd, 'GB2312_L1')
        current_save_dir_l2_trd = os.path.join(current_dir_trd, 'GB2312_L2')
        current_save_dir_l1_trd = os.path.join(current_save_dir_l1_trd, font_label)
        current_save_dir_l2_trd = os.path.join(current_save_dir_l2_trd, font_label)

        valid_l1_smp, invalid_l1_smp = \
            font2img(charset=charset_level1_smp,
                     character_label_list=character_label_level1_smp, dst=dst_file,
                     char_size=args.char_size,canvas_size=args.canvas_size,
                     x_offset=args.x_offset, y_offset=args.y_offset,
                     single_save_dir=current_save_dir_l1_smp,
                     font_label=font_label)
        valid_l2_smp, invalid_l2_smp = \
            font2img(charset=charset_level2_smp,
                     character_label_list=character_label_level2_smp,
                     dst=dst_file,
                     char_size=args.char_size,canvas_size=args.canvas_size,
                     x_offset=args.x_offset, y_offset=args.y_offset,
                     single_save_dir=current_save_dir_l2_smp,
                     font_label=font_label)

        valid_l1_trd, invalid_l1_trd = \
            font2img(charset=charset_level1_trd,
                     character_label_list=character_label_level1_trd, dst=dst_file,
                     char_size=args.char_size, canvas_size=args.canvas_size,
                     x_offset=args.x_offset, y_offset=args.y_offset,
                     single_save_dir=current_save_dir_l1_trd,
                     font_label=font_label)
        valid_l2_trd, invalid_l2_trd = \
            font2img(charset=charset_level2_trd,
                     character_label_list=character_label_level2_trd,
                     dst=dst_file,
                     char_size=args.char_size, canvas_size=args.canvas_size,
                     x_offset=args.x_offset, y_offset=args.y_offset,
                     single_save_dir=current_save_dir_l2_trd,
                     font_label=font_label)

        font_counter=font_counter+1

        dst_file_name = dst_file.split("/")[-1]
        print("%s, Processing Font-->Pict:%d/%d with FontLabel:%s"
              % (dst_file_name, font_counter, len(dst_file_list), font_label))

        print("ValidL1_Smp:%04d,InvalidL1_Smp:%04d; ValidL2_Smp:%04d,InvalidL2_Smp:%04d;"
              % (valid_l1_smp, invalid_l1_smp, valid_l2_smp, invalid_l2_smp))
        print("ValidL1_Trd:%04d,InvalidL1_Trd:%04d; ValidL2_Trd:%04d,InvalidL2_Trd:%04d;"
              % (valid_l1_trd, invalid_l1_trd, valid_l2_trd, invalid_l2_trd))
        print("###########################################################################")


# def imprimir_mensaje():
#     print("Menaje especial: ")
#     print('Estoy aprendiendo a usar funciones')

# imprimir_mensaje()
# imprimir_mensaje()

# def conversacion(mensaje):
#     print('hola')
#     print('Como estas')
#     print('Elegiste la opcion ' + str(mensaje))
#     print('Adios')

# opcion = int(input('Elige una ocpion (1,2,3): '))

# if opcion == 1:
#     conversacion(opcion)
# elif opcion == 2:
#     conversacion(opcion)
# elif opcion ==3:
#     conversacion(opcion)
# else:
#     print('Escribe la opcion correcta')

from re import S

def suma(a,b):
    print('Se suma dos numero')
    resultado = a +b
    return resultado

sumatoria =  suma(1,4)

print("Resultado "+ str(sumatoria))


class OrderLineModel:

    def __init__(self, id, product, order, amount, total_price):
        """OrderLineModel constructor

        Args:
            id (int): database id
            product (int): product id
            order (int): order id
            amount (int):
            total_price (int): in cents
        """
        self.id = id
        self.product = product
        self.order = order
        self.amount = amount
        self.total_price = total_price


from functools import reduce
from itertools import product
from operator import mul
from typing import Tuple

import numpy as np

from utils import read_file

def parse_input(input_path: str):
    steps = []
    for line in read_file(input_path):
        sign = int(line.startswith("on"))
        ranges = []
        range_strs = line.split(" ")[1].split(",")

        for range_str in range_strs:
            range = list(map(int, range_str.split("=")[1].split("..")))

            # Account for range boundaries to prevent one-off errors
            range[1] += 1
            ranges.append(tuple(range))
        steps.append((sign, tuple(ranges)))
    return steps

def solve_1(steps):
    states = np.zeros((101, 101, 101))
    for step in steps:
        sign, [range_x, range_y, range_z] = step
        states[
            range_x[0] + 50 : range_x[1] + 50,
            range_y[0] + 50 : range_y[1] + 50,
            range_z[0] + 50 : range_z[1] + 50,
        ] = sign

    return np.sum(states)

class Cuboid:
    axes = range(3)

    def __init__(self, boundaries: Tuple[Tuple[int]]):
        self.boundaries = boundaries

    def size(self):
        return reduce(mul, (boundary[1] - boundary[0] for boundary in self.boundaries))

    def overlap(self, other: "Cuboid"):
        return all(
            self.boundaries[idx][0] <= other.boundaries[idx][1] - 1
            and self.boundaries[idx][1] - 1 >= other.boundaries[idx][0]
            for idx in self.axes
        )

def get_non_overlapping(cuboid1: Cuboid, cuboid2: Cuboid):
    """Subtract cuboid2 from cuboid1"""

    boundaries = []
    for axis_id in range(3):
        c1_bounds, c2_bounds = cuboid1.boundaries[axis_id], cuboid2.boundaries[axis_id]
        points = list(c1_bounds)

        if c2_bounds[0] >= c1_bounds[0]:
            points.append(c2_bounds[0])
        if c2_bounds[1] <= c1_bounds[1]:
            points.append(c2_bounds[1])

        points = [
            tuple(sorted(points)[idx : idx + 2]) for idx in range(len(points) - 1)
        ]
        boundaries.append(points)

    subcuboids = product(*boundaries)

    # Take out overlapping ones
    non_overlapping_subcuboids = []
    for c in subcuboids:
        subcuboid = Cuboid(c)
        if not cuboid2.overlap(subcuboid):
            non_overlapping_subcuboids.append(subcuboid)

    return non_overlapping_subcuboids

def solve_2(steps):
    cuboids = []

    for step in steps:
        sign, boundaries = step
        new_cuboids, new_cub = [], Cuboid(boundaries)

        for old_cub in cuboids:
            # Detect and remove overlapping area
            if old_cub.overlap(new_cub):
                # Only keep non-overlapping areas of old cuboid
                non_overlapping_subcubs = get_non_overlapping(old_cub, new_cub)
                new_cuboids.extend(non_overlapping_subcubs)
            else:
                new_cuboids.append(old_cub)
        if sign == 1:
            new_cuboids.append(new_cub)
        cuboids = new_cuboids

    return sum(cuboid.size() for cuboid in cuboids)

if __name__ == "__main__":
    sample1_input = parse_input("data/day_22/sample1.txt")
    sample2_input = parse_input("data/day_22/sample2.txt")
    sample3_input = parse_input("data/day_22/sample3.txt")
    real_input = parse_input("data/day_22/input.txt")

    # Part 1
    assert solve_1(sample1_input) == 39
    assert solve_1(sample2_input) == 590784
    assert solve_1(real_input) == 551693

    # Part 2
    assert solve_2(sample3_input) == 2758514936282235
    assert solve_2(real_input) == 1165737675582132


def fobonacci(numero):
    var1=1
    fibonacci=0
    var2=0
    y=0
    lis=[]
    for x in range (30):
        fibonacci=var1+fibonacci
        var2=var1
        var2=fibonacci
        fibonacci=var2
        lis.append(fibonacci)
    for l in range (30):
        if lis[l]==numero:
            aux_3=1
            return aux_3
    for b in range(30):
        if lis[b]!=numero:
            aux_3=0
            return aux_3
numero=int(input("El numero= "))
print("Es 1 si esta dentro de los primeros 30 fibonacci y 0 si no lo es")
print(fobonacci(numero))

Python/Taller de  funciones/Ejercicio 5.py


from pair_sum import TwoPairSum
from tkinter import *
from tkinter import messagebox

def search_pairs():
    input_box = input_entry.get().strip()
    try:
        # Convert it into integer
        int_input = int(input_box)
        two_pair_sum = TwoPairSum(input_number=int_input)
        pair_result_dict = two_pair_sum.two_sum_hashing()
        if not bool(pair_result_dict):
            messagebox.showinfo(title="Oops", message="No Pair of names in the input data")
        else:
            two_pair_sum.print_name(pair_result_dict)
            messagebox.showinfo(title="Congrats!", message="result.txt file is save in your root directory")
    except ValueError:
        messagebox.showerror(title="Oops", message="Please enter a valid integer")

# ---------------------------- UI SETUP ------------------------------- #
window = Tk()
window.title("Pair Sum Search")
window.config(padx=50, pady=50)

canvas = Canvas(width=200, height=200)
title_label = Label(text="Pair Sum List App", font=("Helvetica", 14))
title_label.grid(row=0, column=0, columnspan=2)

description_label = Label(text="App to find list of pairs of a given list url, \n please enter a integer in the "
                               "field below")
description_label.grid(row=1, column=0, columnspan=2, pady=(5, 0))

input_label = Label(text="Enter a value:")
input_label.grid(row=2, column=0)

input_entry = Entry(width=17)
input_entry.grid(row=2, column=1, columnspan=2)
input_entry.insert(0, "139")

search_button = Button(text="Search Pairs", width=36, command=search_pairs)
search_button.grid(row=3, column=0, columnspan=2, pady=(5, 0))

blank_label = Label(text="")
blank_label.grid(row=4, column=0)

rights_label = Label(text="Diego Cabulo Dev", font=("Helvetica", 8, "italic"))
rights_label.grid(row=5, column=0, columnspan=2)

window.mainloop()


from flask import Flask, jsonify, request, Response
import requests
import re
import json

app = Flask(__name__)
proxyList = list()
proxyNow = 0
api = "https://service.narvii.com/api/v1"

@app.route('/')
def index():
    return '''  <title>403 Forbidden</title>

403 Forbidden

			'''

@app.route('/<path:path>', methods=["GET", "POST", "DELETE"])
def catch_all(path):
    global proxyNow
    if request.method == 'POST':
        result = requests.post(f"{api}/{path}", headers=request.headers, data=request.data, proxies=proxyList[proxyNow])
        if proxyNow < len(proxyList): proxyNow+=1
        else: proxyNow = 0
    elif request.method == 'GET':
        result = requests.get(f"{api}/{path}", headers=request.headers, proxies=proxyList[proxyNow])
        if proxyNow < len(proxyList): proxyNow+=1
        else: proxyNow = 0
    elif request.method == 'DELETE':
        result = requests.delete(f"{api}/{path}", headers=request.headers, proxies=proxyList[proxyNow])
        if proxyNow < len(proxyList): proxyNow+=1
        else: proxyNow = 0
    return Response(result.text, result.status_code, mimetype='application/json')

if __name__ == '__main__':
    with open("proxies.txt", "r") as file:
        for line in file:
            proxyList.append({"https": line.strip()})
    print(f" * Loaded {len(proxyList)} proxies!")
    app.run(host='0.0.0.0', port=55535, debug=True)


# -*- coding: utf-8 -*-
import os
from setuptools import setup, find_packages, Extension

install_reqs = [
    'hexrd',
    'fabio>=0.11',
    'matplotlib',
    'Pillow',
    'pyside6',
    'pyyaml',
    'silx',
]

setup(
    name='hexrdgui',
    use_scm_version=True,
    setup_requires=['setuptools-scm'],
    description='',
    long_description='',
    author='Kitware, Inc.',
    author_email='kitware@kitware.com',
    url='https://github.com/hexrd/hexrdgui',
    license='BSD',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.10',
        'Programming Language :: Python :: 3.11',
    ],
    packages=find_packages(),
    package_data={'hexrdgui': ['resources/**/*']},
    python_requires='>=3.10',
    install_requires=install_reqs,
    entry_points={
        'gui_scripts': [
            'hexrdgui = hexrdgui.main:main'
        ]
    }
)


# from openpyxl import Workbook
# client_database = Workbook()
# wb = client_database.active()
def spreadsheet_writer():
    """This functions checks the row and column by itself and writed the data."""
    with open("data_randc.txt", "r") as f:
        dat = f.read()
        print(type(dat))
i = 0
while True:
    v = input()
    if v.lower() == "q":
        print(i)
        break
    else:
        v = int(v)
        i = i + v
spreadsheet_writer()


import csv
with open ('ex2-text.csv',encoding="utf-8") as file1 :
    csvReader=csv.reader(file1)
    lineCount=0
    file2=open('ex2-employees.txt','w')
    file3=open('ex2-locations.txt','w')
    for row in csvReader:
        if lineCount==0:
            file2.write(f'Column names: {row[0]}, {row[1]}\n')
            file3.write(f'Column names: {row[0]}, {row[3]}\n')
            lineCount+=1;
        else:
            file2.write(f'{row[0]}, {row[1]}\n')
            file3.write(f'{row[0]}, {row[3]}\n')
            lineCount+=1