"""Estrtutura inicial

Revision ID: 9cc0564d755d
Revises:
Create Date: 2023-04-02 14:19:33.777120

"""
import sqlalchemy as sa
import sqlmodel

from alembic import op

# revision identifiers, used by Alembic.
revision = "9cc0564d755d"
down_revision = None
branch_labels = None
depends_on = None

def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "empresa",
        sa.Column("id", sqlmodel.sql.sqltypes.GUID(), nullable=False),
        sa.Column("nome", sqlmodel.sql.sqltypes.AutoString(length=250), nullable=False),
        sa.Column(
            "logradouro", sqlmodel.sql.sqltypes.AutoString(length=250), nullable=True
        ),
        sa.Column(
            "cidade", sqlmodel.sql.sqltypes.AutoString(length=150), nullable=True
        ),
        sa.Column("estado", sqlmodel.sql.sqltypes.AutoString(length=50), nullable=True),
        sa.Column("matriz", sa.Boolean(), nullable=False),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index(op.f("ix_empresa_id"), "empresa", ["id"], unique=False)
    op.create_table(
        "pessoa",
        sa.Column("id", sqlmodel.sql.sqltypes.GUID(), nullable=False),
        sa.Column("nome", sqlmodel.sql.sqltypes.AutoString(length=200), nullable=False),
        sa.Column("email", sqlmodel.sql.sqltypes.AutoString(length=250), nullable=True),
        sa.Column(
            "telefone", sqlmodel.sql.sqltypes.AutoString(length=20), nullable=True
        ),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index(op.f("ix_pessoa_id"), "pessoa", ["id"], unique=False)
    op.create_table(
        "departamento",
        sa.Column("id", sqlmodel.sql.sqltypes.GUID(), nullable=False),
        sa.Column("nome", sqlmodel.sql.sqltypes.AutoString(length=200), nullable=False),
        sa.Column(
            "local", sqlmodel.sql.sqltypes.AutoString(length=200), nullable=False
        ),
        sa.Column("id_empresa", sqlmodel.sql.sqltypes.GUID(), nullable=False),
        sa.ForeignKeyConstraint(
            ["id_empresa"],
            ["empresa.id"],
        ),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index(op.f("ix_departamento_id"), "departamento", ["id"], unique=False)
    # ### end Alembic commands ###

def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(op.f("ix_departamento_id"), table_name="departamento")
    op.drop_table("departamento")
    op.drop_index(op.f("ix_pessoa_id"), table_name="pessoa")
    op.drop_table("pessoa")
    op.drop_index(op.f("ix_empresa_id"), table_name="empresa")
    op.drop_table("empresa")
    # ### end Alembic commands ###


#!/usr/bin/python3

""" add by mr-You file test_save_reload_base_model.py task 5 """

import sys
sys.path.append('../AirBnB_clone/')
from models import storage
from models.base_model import BaseModel

all_objs = storage.all()
print("-- Reloaded objects --")
for obj_id in all_objs.keys():
    obj = all_objs[obj_id]
    print(obj)

print("-- Create a new object --")
my_model = BaseModel()
my_model.name = "My_First_Model"
my_model.my_number = 89
my_model.save()
print(my_model)


from sys import platform
from babel.dates import format_date
try:
    import tkinter as tk
    from tkinter import ttk
except ImportError:
    import Tkinter as tk
    import ttk
from tkcalendar import Calendar,DateEntry
import re

class CustomCalendar(Calendar):
    def _get_date_pattern(self,date_pattern,locale=None):
        """
        Return the babel pattern corresponding to date_pattern.

        If date_pattern is 'short', return the pattern correpsonding to the
        locale, else return date_pattern if valid.

        A valid pattern is a sequence of y, m and d
        separated by non letter characters, e.g. yyyy-mm-dd or d/m/yy
        """
        if locale is None:
            locale = self._properties['locale']
        if date_pattern == 'short':
            return get_date_format('short',locale).pattern
        pattern = date_pattern.lower()
        ymmd = r'^y+[^a-zA-Z]*m{1,3}&m{1,3}[^a-z]*d{1,2}[^mdy]*$'
        ymd = r'^y+[^a-zA-Z]*m{1,3}[^a-z]*d{1,2}[^mdy]*$'
        mdy = r'^m{1,2}[^a-zA-Z]*d{1,2}[^a-z]*y+[^mdy]*$'
        dmy = r'^d{1,2}[^a-zA-Z]*m{1,2}[^a-z]*y+[^mdy]*$'
        res = ((re.search(ymmd,pattern) is not None)
               or (re.search(ymd,pattern) is not None)
               or (re.search(mdy,pattern) is not None)
               or (re.search(dmy,pattern) is not None))
        if res:
            return pattern.replace('m','M')
        raise ValueError('{} is not a valid date pattern'.format(date_pattern))

    def format_date(self,date=None):
        """Convert date (datetime.date) to a string in the locale."""
        return format_date(date,self._properties['date_pattern'],self._properties['locale']).replace('&','')

    def parse_date(self,date):
        """Parse string date in the locale format and return the corresponding datetime.date."""
        try:
            date_format = self._properties['date_pattern'].lower()
            ny = date_format.count('y')
            nm = date_format.count('m')
            nd = date_format.count('d')
            if nm == 5:
                ymd = r'^y+([^a-zA-Z]*)mm\&mmm([^a-z]*)d{1,2}([^mdy]*)$'
                m = re.search(ymd,date_format)
                if not m:
                    raise ValueError('{} is not a valid date format'.format(date_format))
                sep1 = m.group(1)
                sep2 = m.group(2)
                sep3 = m.group(3)
                ymd = '^('+'\d'*ny+')'+sep1+'\d\d('+'[a-zA-Z]'*3+')'+sep2+'('+'\d'*nd+')'+sep3+'$'
                m = re.search(ymd,date)
                if not m:
                    raise ValueError('{} is not a valid date'.format(date))
                year = m.group(1)
                if len(year) == 2:
                    year = 2000 + int(year)
                else:
                    year = int(year)
                month = self.strptime(m.group(2),'%b').month
                day = int(m.group(3))
            elif nm == 3:
                ymd = r'^y+([^a-zA-Z]*)mmm([^a-z]*)d{1,2}([^mdy]*)$'
                m = re.search(ymd,date_format)
                if not m:
                    raise ValueError('{} is not a valid date format'.format(date_format))
                sep1 = m.group(1)
                sep2 = m.group(2)
                sep3 = m.group(3)
                ymd = '^('+'\d'*ny+')'+sep1+'('+'[a-zA-Z]'*nm+')'+sep2+'('+'\d'*nd+')'+sep3+'$'
                m = re.search(ymd,date)
                if not m:
                    raise ValueError('{} is not a valid date'.format(date))
                year = m.group(1)
                if len(year) == 2:
                    year = 2000 + int(year)
                else:
                    year = int(year)
                month = self.strptime(m.group(2),'%b').month
                day = int(m.group(3))
            else:
                year_idx = date_format.index('y')
                month_idx = date_format.index('m')
                day_idx = date_format.index('d')
                indexes = [(year_idx,'Y'),(month_idx,'M'),(day_idx,'D')]
                indexes.sort()
                indexes = dict([(item[1],idx) for idx,item in enumerate(indexes)])
                numbers = re.findall(r'(\d+)',date)
                year = numbers[indexes['Y']]
                if len(year) == 2:
                    year = 2000 + int(year)
                else:
                    year = int(year)
                month = int(numbers[indexes['M']])
                day = int(numbers[indexes['D']])
                if month > 12:
                    month,day = day,month
            return self.date(year,month,day)
        except Exception:
            return self.datetime.today()

class CustomDateEntry(DateEntry):
    def __init__(self,master=None,**kw):
        """
        Create an entry with a drop-down calendar to select a date.

        When the entry looses focus, if the user input is not a valid date,
        the entry content is reset to the last valid date.

        Keyword Options
        ---------------

        usual ttk.Entry options and Calendar options.
        The Calendar option 'cursor' has been renamed
        'calendar_cursor' to avoid name clashes with the
        corresponding ttk.Entry option.

        Virtual event
        -------------

        A ``<<DateEntrySelected>>`` event is generated each time
        the user selects a date.

        """
        # sort keywords between entry options and calendar options
        kw['selectmode'] = 'day'
        entry_kw = {}

        style = kw.pop('style','DateEntry')

        for key in self.entry_kw:
            entry_kw[key] = kw.pop(key,self.entry_kw[key])
        entry_kw['font'] = kw.get('font',None)
        self._cursor = entry_kw['cursor']  # entry cursor
        kw['cursor'] = kw.pop('calendar_cursor',None)

        ttk.Entry.__init__(self,master,**entry_kw)

        self._determine_downarrow_name_after_id = ''

        # drop-down calendar
        self._top_cal = tk.Toplevel(self)
        self._top_cal.withdraw()
        if platform == 'linux':
            self._top_cal.attributes('-type','DROPDOWN_MENU')
        self._top_cal.overrideredirect(True)
        self._calendar = CustomCalendar(self._top_cal,**kw)
        self._calendar.pack()

        # locale date parsing / formatting
        self.format_date = self._calendar.format_date
        self.parse_date = self._calendar.parse_date

        # style
        self._theme_name = ''   # to detect theme changes
        self.style = ttk.Style(self)
        self._setup_style()
        self.configure(style=style)

        # add validation to Entry so that only dates in the locale's format
        # are accepted
        validatecmd = self.register(self._validate_date)
        self.configure(validate='focusout',
                       validatecommand=validatecmd)

        # initially selected date
        self._date = self._calendar.selection_get()
        if self._date is None:
            today = self._calendar.date.today()
            year = kw.get('year',today.year)
            month = kw.get('month',today.month)
            day = kw.get('day',today.day)
            try:
                self._date = self._calendar.date(year,month,day)
            except ValueError:
                self._date = today
        self._set_text(self.format_date(self._date))

        # --- bindings
        # reconfigure style if theme changed
        self.bind('<<ThemeChanged>>',
                  lambda e: self.after(10,self._on_theme_change))
        # determine new downarrow button bbox
        self.bind('<Configure>',self._determine_downarrow_name)
        self.bind('<Map>',self._determine_downarrow_name)
        # handle appearence to make the entry behave like a Combobox but with
        # a drop-down calendar instead of a drop-down list
        self.bind('<Leave>',lambda e: self.state(['!active']))
        self.bind('<Motion>',self._on_motion)
        self.bind('<ButtonPress-1>',self._on_b1_press)
        # update entry content when date is selected in the Calendar
        self._calendar.bind('<<CalendarSelected>>',self._select)
        # hide calendar if it looses focus
        self._calendar.bind('<FocusOut>',self._on_focus_out_cal)

    def _validate_date(self):
        """Date entry validation: only dates in locale '%x' format are accepted."""
        try:
            date = self.parse_date(self.get())
            self._date = self._calendar.check_date_range(date)
            if self._date != date:
                self._set_text(self.format_date(self._date))
                return False
            else:
                return True
        except (ValueError,IndexError):
            #self._set_text(self.format_date(self._date))
            return False


import os
import random
import time

def gameMenu():
    print("")
    print("")
    print(' THIS IS A QUIZ RELATED TO PYTHON '.center(80, '*'))
    print("")
    print("")
    print("")
    print(' MENU '.center(80, '*'))
    print("")
    print("")
    print(' Press S to start the game '.center(80))
    print(' Press I to read instruction '.center(80))
    print(' Press H to see high score '.center(80))
    print(' Press C to see credits '.center(80))
    print(' Press Q to start the game '.center(80))

def instructions():
    print("1 correct answer = 1 point")
    print("1 wrong answer deducts 0.5 point")
    print("This quiz is about country and capital more menus will be added further")
    print("This quiz is not case sensitive.")
    print("")
    print("")
    print("Press M to go back to menu".center(80))
    keyInput = input().upper()
    if keyInput == "M":
        main()

def startGame():
    data = {
        "Afghanistan" : "Kabul",
        "India" : "Delhi",
        "Pakistan" : "Islamabad",
        "Bhutan" : "Thimpu",
        "Bangladesh" : "Dhaka",
        "USA" : "Washington DC",
        "Brazil" : "Rio De Jenerio",
        "China" : "Beijing",
        "Australia" : "Canberra",
        "Austria" : "Vienna",
        "Japan" : "Tokyo",
        "Russia" : "Moscow",
        "France" : "Paris",
        "Bangladesh" : "Dhaka",
        "Canada" : "Ottawa",
        "Sri Lanka" : "Colombo",
        "Belgium" : "Brussels",
        "Saudi Arabia" : "Riyadh"
    }
    question, answer = random.choice(list(data.items()))
    return question, answer

def credits():
    print(" CREATED BY ".center(80,'x'))
    print(" Abhishek Raj ".center(80))
    print(" abhishekraj272@gmail.com ".center(80))
    print("")
    print("")
    print("")
    print("Press M to go back to menu".center(80))
    keyInput = input().upper()
    if keyInput == "M":
        main()

def profile():
    global name
    print("Please enter the following details")
    fName = input("First Name: ")
    lName = input("Last Name: ")
    name = fName + " " + lName
    return name

def saveScore():
    global strPoint
    global strRtQue
    global name
    file = open("highScore.txt", "a+")
    file.write(name + " scored " + strPoint + " points and answered " + strRtQue + " question correctly")
    file.close()

def viewScore():
    file = open("highScore.txt", "r")
    fileContents = file.read()
    print(fileContents)
    file.close()
    print("")
    print("")
    print("")
    print("")
    print("Press M to go back to menu".center(80))
    keyInput = input().upper()
    if keyInput == "M":
        main()

def question():
    global strPoint
    global strRtQue

    point = 0
    rtQue = 0
    name = profile()
    os.system('cls')
    for i in range(10):
        queData, ansData = startGame()
        ansDataLower = ansData.lower()
        print("What is the capital city of " + queData + "?")
        getAns = input().lower()
        os.system('cls')
        if getAns == ansDataLower:
            print("Congratulation! " + name + " Your answer is correct.")
            point += 1
            rtQue += 1
        else:
            print("Your answer is wrong.")
            point -= 0.5
        time.sleep(1)
        os.system('cls')
        strPoint = str(point)
        strRtQue = str(rtQue)
    print("The quiz is now over")
    print("You answered " + strRtQue + " questions correctly.")
    print("You got " + strPoint + " points")
    saveScore()

def main():

    os.system('cls')
    gameMenu()
    startCmd = input().upper()
    os.system('cls')
    if startCmd == "S":
        question()

    elif startCmd == "Q":
        exit()

    elif startCmd == "H":
        viewScore()

    elif startCmd == "I":
        instructions()

    elif startCmd == "C":
        credits()

    #elif startCmd == "I":
    #    viewScore()

main()


import os
import re
import json
import requests

from slackbot.bot import respond_to

from hiarcbot import sched, bot
import slack_config

headers = {
    "Accept-Language": "ko_KR",
    "Accept": "application/json"
}

data = {
    "user_key": "hi-arc slackbot",
    "type": "text",
    "content": "오늘의 식단"
}

def get_schoolcafe_menu():
    r = requests.post(url=slack_config.SCHOOL_CAFE_API,
                      headers=headers, data=data)
    if r.status_code != 200:
        print("error")

    return json.loads(r.text)['message']['text']

@respond_to('^학식$', re.IGNORECASE)
def menu_reply(message):
    menu_summary = get_schoolcafe_menu()
    message.send(menu_summary)

@sched.scheduled_job('cron', hour=8, minute=0)
def notify_schoolcafe_menu():
    menu_summary = get_schoolcafe_menu()
    slack_client = getattr(bot, "_client", None)
    channel_id = slack_client.find_channel_by_name(u'gourmat')
    slack_client.send_message(channel_id, menu_summary)


import matplotlib.pyplot as plt

ts = 0.23
iterations = 50
times = []

for i in range(iterations + 1):
  times.append(i*ts)

listAks = [0]
listVel = [10]
listPos = [0]

def eulerForward(ts, verdi):
  return ts*verdi

def modellIterasjon(input, m, ts):
  a = input/m
  v = eulerForward(ts, input)
  p = eulerForward(ts, v)
  return a, v, p

def modellLoop(initialForce, m, ts, iterations, listAks, listVel, listPos):
  K = 5
  D = 2
  for i in range(iterations):
    a, v, p = modellIterasjon(initialForce - listVel[-1]*D - listPos[-1]*K, m, ts)
    listAks.append(a)
    listVel.append(v)
    listPos.append(p)
m = 10 # feks 10 kg
g = 9.81

modellLoop(m*g, m, ts, iterations, listAks, listVel, listPos)

plt.plot(times, listPos)
plt.show()


#python 中一切皆对象
#闭包 = 函数 + 环境变量

'''
def curve_pre():
    a=20              #环境变量
    def curve(x):
       return a**x
    return curve

a = 10         #不起作用
f = curve_pre()
print(f.__closure__)
print(f.__closure__[0].cell_contents)
print(f(2))
'''

'''
def f1():
    a = 20
    def f2():
        a = 10      #局部变量，不影响外面。由于此事并未饮用外面环境变量里面的a，故算不上是闭包
        print(a)
    print(a)
    f2()
    print(a)

f1()
'''
#方法一：
origin = 0
def go(step):
    global origin            #用global声明全局变量
    new_pos = origin + step
    origin = new_pos
    return new_pos

print(go(2))
print(go(3))
print(go(6))

#方法二：
def factory(pos):
    def go(step):
        nonlocal pos
        new_pos = pos + step
        pos = new_pos
        return new_pos
    return go

tourist = factory(origin)
print(tourist(2))
print(tourist(3))
print(tourist(6))


endereco = "Rua: São luiz 24, Bairro: Jockey de Itaparica - " \
           "Cidade: Vila Velha-ES CEP: 29103-890"

import re

padrao = re.compile("[0-9]{5}[-]{0,1}[0-9]{3}")
busca = padrao.search(endereco)
if busca:
    cep = busca.group()
    print(cep)


import torch
import torch.nn as nn
from einops import rearrange
import numpy as np
from models.op.common import *
import xformers.ops as xops
class Upsample(nn.Module):
    def __init__(self, in_channels, with_conv):
        super().__init__()
        self.with_conv = with_conv
        if self.with_conv:
            self.conv = torch.nn.Conv2d(in_channels,
                                        in_channels,
                                        kernel_size=3,
                                        stride=1,
                                        padding=1)

    def forward(self, x):
        x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
        if self.with_conv:
            x = self.conv(x)
        return x

class ResnetBlock(nn.Module):
    def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
                 dropout, temb_channels=512):
        super().__init__()
        self.in_channels = in_channels
        out_channels = in_channels if out_channels is None else out_channels
        self.out_channels = out_channels
        self.use_conv_shortcut = conv_shortcut

        self.norm1 = Normalize(in_channels)
        self.conv1 = torch.nn.Conv2d(in_channels,
                                     out_channels,
                                     kernel_size=3,
                                     stride=1,
                                     padding=1)
        if temb_channels > 0:
            self.temb_proj = torch.nn.Linear(temb_channels,
                                             out_channels)
        self.norm2 = Normalize(out_channels)
        self.dropout = torch.nn.Dropout(dropout)
        self.conv2 = torch.nn.Conv2d(out_channels,
                                     out_channels,
                                     kernel_size=3,
                                     stride=1,
                                     padding=1)
        if self.in_channels != self.out_channels:
            if self.use_conv_shortcut:
                self.conv_shortcut = torch.nn.Conv2d(in_channels,
                                                     out_channels,
                                                     kernel_size=3,
                                                     stride=1,
                                                     padding=1)
            else:
                self.nin_shortcut = torch.nn.Conv2d(in_channels,
                                                    out_channels,
                                                    kernel_size=1,
                                                    stride=1,
                                                    padding=0)

    def forward(self, x, temb):
        h = x
        h = self.norm1(h)
        h = nonlinearity(h)
        h = self.conv1(h)
        if temb is not None:
            h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None]

        h = self.norm2(h)
        h = nonlinearity(h)
        h = self.dropout(h)
        h = self.conv2(h)

        if self.in_channels != self.out_channels:
            if self.use_conv_shortcut:
                x = self.conv_shortcut(x)
            else:
                x = self.nin_shortcut(x)

        return x+h

class Downsample(nn.Module):
    def __init__(self, in_channels, with_conv):
        super().__init__()
        self.with_conv = with_conv
        if self.with_conv:
            # no asymmetric padding in torch conv, must do it ourselves
            self.conv = torch.nn.Conv2d(in_channels,
                                        in_channels,
                                        kernel_size=3,
                                        stride=2,
                                        padding=0)

    def forward(self, x):
        if self.with_conv:
            pad = (0,1,0,1)
            x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
            x = self.conv(x)
        else:
            x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
        return x

class AttnBlock(nn.Module):
    def __init__(self, in_channels):
        super().__init__()
        self.in_channels = in_channels

        self.norm = Normalize(in_channels)
        self.q = torch.nn.Conv2d(in_channels,
                                 in_channels,
                                 kernel_size=1,
                                 stride=1,
                                 padding=0)
        self.k = torch.nn.Conv2d(in_channels,
                                 in_channels,
                                 kernel_size=1,
                                 stride=1,
                                 padding=0)
        self.v = torch.nn.Conv2d(in_channels,
                                 in_channels,
                                 kernel_size=1,
                                 stride=1,
                                 padding=0)
        self.proj_out = torch.nn.Conv2d(in_channels,
                                        in_channels,
                                        kernel_size=1,
                                        stride=1,
                                        padding=0)

    def forward(self, x):
        b, c, h, w = x.shape
        h_ = x
        h_ = self.norm(h_)
        q = self.q(h_)
        k = self.k(h_)
        v = self.v(h_)
        q, k, v = map(lambda t: rearrange(t, 'b c h w -> b (h w) c').contiguous(), (q, k, v))
        h_ = xops.memory_efficient_attention(q, k, v)
        h_ = rearrange(h_, 'b (h w) d -> b d h w', h=h, w=w)
        h_ = self.proj_out(h_)
        return x+h_

class LinearAttention(nn.Module):
    def __init__(self, dim, heads=4, dim_head=32):
        super().__init__()
        self.heads = heads
        hidden_dim = dim_head * heads
        self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias = False)
        self.to_out = nn.Conv2d(hidden_dim, dim, 1)

    def forward(self, x):
        b, c, h, w = x.shape
        qkv = self.to_qkv(x)
        q, k, v = rearrange(qkv, 'b (qkv heads c) h w -> qkv b heads c (h w)', heads = self.heads, qkv=3)
        k = k.softmax(dim=-1)
        context = torch.einsum('bhdn,bhen->bhde', k, v)
        out = torch.einsum('bhde,bhdn->bhen', context, q)
        out = rearrange(out, 'b heads c (h w) -> b (heads c) h w', heads=self.heads, h=h, w=w)
        return self.to_out(out)
class LinAttnBlock(LinearAttention):
    """to match AttnBlock usage"""
    def __init__(self, in_channels):
        super().__init__(dim=in_channels, heads=1, dim_head=in_channels)

def make_attn(in_channels, attn_type="vanilla"):
    assert attn_type in ["vanilla", "linear", "none"], f'attn_type {attn_type} unknown'
    print(f"making attention of type '{attn_type}' with {in_channels} in_channels")
    if attn_type == "vanilla":
        return AttnBlock(in_channels)
    elif attn_type == "none":
        return nn.Identity(in_channels)
    else:
        return LinAttnBlock(in_channels)

class Encoder(nn.Module):
    def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
                 attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
                 resolution, z_channels, double_z=True, use_linear_attn=False, attn_type="vanilla",
                 **ignore_kwargs):
        super().__init__()
        if use_linear_attn: attn_type = "linear"
        self.ch = ch
        self.temb_ch = 0
        self.num_resolutions = len(ch_mult)
        self.num_res_blocks = num_res_blocks
        self.resolution = resolution
        self.in_channels = in_channels
        # downsampling
        self.conv_in = torch.nn.Conv2d(in_channels,
                                       self.ch,
                                       kernel_size=3,
                                       stride=1,
                                       padding=1)
        curr_res = resolution
        in_ch_mult = (1,)+tuple(ch_mult)
        self.in_ch_mult = in_ch_mult
        self.down = nn.ModuleList()
        for i_level in range(self.num_resolutions):
            block = nn.ModuleList()
            attn = nn.ModuleList()
            block_in = ch*in_ch_mult[i_level]
            block_out = ch*ch_mult[i_level]
            for i_block in range(self.num_res_blocks):
                block.append(ResnetBlock(in_channels=block_in,
                                         out_channels=block_out,
                                         temb_channels=self.temb_ch,
                                         dropout=dropout))
                block_in = block_out
                if curr_res in attn_resolutions:
                    attn.append(make_attn(block_in, attn_type=attn_type))
            down = nn.Module()
            down.block = block
            down.attn = attn
            if i_level != self.num_resolutions-1:
                down.downsample = Downsample(block_in, resamp_with_conv)
                curr_res = curr_res // 2
            self.down.append(down)
        # middle
        self.mid = nn.Module()
        self.mid.block_1 = ResnetBlock(in_channels=block_in,
                                       out_channels=block_in,
                                       temb_channels=self.temb_ch,
                                       dropout=dropout)
        self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
        self.mid.block_2 = ResnetBlock(in_channels=block_in,
                                       out_channels=block_in,
                                       temb_channels=self.temb_ch,
                                       dropout=dropout)
        # end
        self.norm_out = Normalize(block_in)
        self.conv_out = torch.nn.Conv2d(block_in,
                                        2*z_channels if double_z else z_channels,
                                        kernel_size=3,
                                        stride=1,
                                        padding=1)

    def forward(self, x):
        # timestep embedding
        temb = None
        # downsampling
        hs = [self.conv_in(x)]

        for i_level in range(self.num_resolutions):
            for i_block in range(self.num_res_blocks):
                h = self.down[i_level].block[i_block](hs[-1], temb)
                if len(self.down[i_level].attn) > 0:
                    h = self.down[i_level].attn[i_block](h)
                hs.append(h)
            if i_level != self.num_resolutions-1:
                hs.append(self.down[i_level].downsample(hs[-1]))
        # middle
        h = hs[-1]
        h = self.mid.block_1(h, temb)
        h = self.mid.attn_1(h)
        h = self.mid.block_2(h, temb)

        # end
        h = self.norm_out(h)
        h = nonlinearity(h)
        h = self.conv_out(h)
        return h

class Decoder(nn.Module):
    def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
                 attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
                 resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False,
                 attn_type="vanilla", **ignorekwargs):
        super().__init__()
        if use_linear_attn: attn_type = "linear"
        self.ch = ch
        self.temb_ch = 0
        self.num_resolutions = len(ch_mult)
        self.num_res_blocks = num_res_blocks
        self.resolution = resolution
        self.in_channels = in_channels
        self.give_pre_end = give_pre_end
        self.tanh_out = tanh_out

        # compute in_ch_mult, block_in and curr_res at lowest res
        in_ch_mult = (1,)+tuple(ch_mult)
        block_in = ch*ch_mult[self.num_resolutions-1]
        curr_res = resolution // 2**(self.num_resolutions-1)
        self.z_shape = (1,z_channels,curr_res,curr_res)
        print("Working with z of shape {} = {} dimensions.".format(
            self.z_shape, np.prod(self.z_shape)))

        # z to block_in
        self.conv_in = torch.nn.Conv2d(z_channels,
                                       block_in,
                                       kernel_size=3,
                                       stride=1,
                                       padding=1)

        # middle
        self.mid = nn.Module()
        self.mid.block_1 = ResnetBlock(in_channels=block_in,
                                       out_channels=block_in,
                                       temb_channels=self.temb_ch,
                                       dropout=dropout)
        self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
        self.mid.block_2 = ResnetBlock(in_channels=block_in,
                                       out_channels=block_in,
                                       temb_channels=self.temb_ch,
                                       dropout=dropout)

        # upsampling
        self.up = nn.ModuleList()
        for i_level in reversed(range(self.num_resolutions)):
            block = nn.ModuleList()
            attn = nn.ModuleList()
            block_out = ch*ch_mult[i_level]
            for i_block in range(self.num_res_blocks+1):
                block.append(ResnetBlock(in_channels=block_in,
                                         out_channels=block_out,
                                         temb_channels=self.temb_ch,
                                         dropout=dropout))
                block_in = block_out
                if curr_res in attn_resolutions:
                    attn.append(make_attn(block_in, attn_type=attn_type))
            up = nn.Module()
            up.block = block
            up.attn = attn
            if i_level != 0:
                up.upsample = Upsample(block_in, resamp_with_conv)
                curr_res = curr_res * 2
            self.up.insert(0, up) # prepend to get consistent order

        # end
        self.norm_out = Normalize(block_in)
        self.conv_out = torch.nn.Conv2d(block_in,
                                        out_ch,
                                        kernel_size=3,
                                        stride=1,
                                        padding=1)

    def forward(self, z):
        #assert z.shape[1:] == self.z_shape[1:]
        self.last_z_shape = z.shape

        # timestep embedding
        temb = None

        # z to block_in
        h = self.conv_in(z)

        # middle
        h = self.mid.block_1(h, temb)
        h = self.mid.attn_1(h)
        h = self.mid.block_2(h, temb)

        # upsampling
        for i_level in reversed(range(self.num_resolutions)):
            for i_block in range(self.num_res_blocks+1):
                h = self.up[i_level].block[i_block](h, temb)
                if len(self.up[i_level].attn) > 0:
                    h = self.up[i_level].attn[i_block](h)
            if i_level != 0:
                h = self.up[i_level].upsample(h)

        # end
        if self.give_pre_end:
            return h

        h = self.norm_out(h)
        h = nonlinearity(h)
        h = self.conv_out(h)
        if self.tanh_out:
            h = torch.tanh(h)
        return h

class DiagonalGaussianDistribution(object):
    def __init__(self, parameters, deterministic=False):
        self.parameters = parameters
        self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)
        self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
        self.deterministic = deterministic
        self.std = torch.exp(0.5 * self.logvar)
        self.var = torch.exp(self.logvar)
        if self.deterministic:
            self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device)

    def sample(self):
        x = self.mean + self.std * torch.randn(self.mean.shape).to(device=self.parameters.device)
        return x

    def kl(self, other=None):
        if self.deterministic:
            return torch.Tensor([0.])
        else:
            if other is None:
                return 0.5 * torch.sum(torch.pow(self.mean, 2)
                                       + self.var - 1.0 - self.logvar,
                                       dim=[1, 2, 3])
            else:
                return 0.5 * torch.sum(
                    torch.pow(self.mean - other.mean, 2) / other.var
                    + self.var / other.var - 1.0 - self.logvar + other.logvar,
                    dim=[1, 2, 3])

    def nll(self, sample, dims=[1,2,3]):
        if self.deterministic:
            return torch.Tensor([0.])
        logtwopi = np.log(2.0 * np.pi)
        return 0.5 * torch.sum(
            logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
            dim=dims)

    def mode(self):
        return self.mean

class AutoencoderKLX(nn.Module):
    def __init__(self,
                 ddconfig,
                 embed_dim,
                 **kwargs
                 ):
        super().__init__()
        self.encoder = Encoder(**ddconfig)
        self.decoder = Decoder(**ddconfig)
        assert ddconfig["double_z"]
        self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1)
        self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
        self.embed_dim = embed_dim
        if kwargs.get("pretrain", None):
            load_pretrained_model(self, kwargs["pretrain"])

    @torch.inference_mode()
    def encode(self, x):
        h = self.encoder(x)
        moments = self.quant_conv(h)
        posterior = DiagonalGaussianDistribution(moments)
        return posterior

    @torch.inference_mode()
    def decode(self, z):
        z = self.post_quant_conv(z)
        dec = self.decoder(z)
        return dec

    def map(self, x):
        h = self.encoder(x)
        moments = self.quant_conv(h)
        return moments

    def forward(self, input, sample_posterior=True):
        posterior = self.encode(input)
        if sample_posterior:
            z = posterior.sample()
        else:
            z = posterior.mode()
        dec = self.decode(z)
        return dec, posterior

    def del_decoder(self):
        del self.decoder
        del self.post_quant_conv

    @torch.inference_mode()
    def get_scale_encoding(self, x, scale_factor = 0.18215):
        z = self.encode(x)
        z = z.sample()
        return scale_factor * z

    @torch.inference_mode()
    def get_scale_decoding(self, z, scale_factor = 0.18215):
        z = z / scale_factor
        x = self.decode(z)
        return x

if __name__ == "__main__":
    # params:
    #     embed_dim: 4
    #     ddconfig:
    #         double_z: true
    #         z_channels: 4
    #         resolution: *image_size
    #         in_channels: 3
    #         out_ch: 3
    #         ch: 128
    #         num_res_blocks: 2
    #         attn_resolutions: []
    #         dropout: 0.0
    #         ch_mult: [1, 2, 4, 4]
    #     pretrain: "pretrain/autoencoder_kl_v2.ckpt"
    params = {
        "embed_dim": 4,
        "ddconfig": {
            "double_z": True,
            "z_channels": 4,
            "resolution": 256,
            "in_channels": 3,
            "out_ch": 3,
            "ch": 128,
            "num_res_blocks": 2,
            "attn_resolutions": [],
            "dropout": 0.0,
            "ch_mult": [1, 2, 4, 4]
        },
        "pretrain": "pretrain/autoencoder_kl_v2.ckpt"
    }
    model = AutoencoderKLX(**params)
    device = "cuda"
    model = model.to(device)
    def test_error(video_path, id, text):
        import torchvision as tv
        from einops import rearrange
        from dataset.common import read_video
        video = read_video(video_path, 16, 3)
        transform = tv.transforms.Compose([
            tv.transforms.Resize(256),
            tv.transforms.CenterCrop(256),
        ])
        video = video.to(device)
        video = transform(video)
        # normalize
        _video = video / 255
        _video = (_video - 0.5) / 0.5
        out, posterior = model(_video)
        out1 = ((out * 0.5 + 0.5) * 255).clamp(0, 255)
        out1 = rearrange(out1, "t c h w -> t h w c")
        out1 = out1.detach().cpu()

        _video = video / 127.5 - 1
        out, posterior = model(_video)
        out2 = ((out + 1) * 127.5).clamp(0, 255)
        out2 = rearrange(out2, "t c h w -> t h w c")
        out2 = out2.detach().cpu()

        out = torch.cat([out1, out2], dim=2)
        tv.io.write_video(os.path.join("tmp", f"'{text}'_{id}.mp4"), out, fps=16/2)
    import pandas as pd
    csv_path = "tmp.csv"
    df = pd.read_csv(csv_path)
    for i, row in df.iterrows():
        video_path = row["video_path"]
        video_path = os.path.join("data/webvid/data/videos/", video_path)
        text = row["text"]
        test_error(video_path, i, text)


from __future__ import print_function

import glob
import warnings

import numpy as np
import pandas as pd
import soundfile
import os
import os.path as osp
import librosa
import torch
from desed.utils import create_folder
from torch import nn

import config as cfg

def read_audio(path, target_fs=None, **kwargs):
    """ Read a wav file
    Args:
        path: str, path of the audio file
        target_fs: int, (Default value = None) sampling rate of the returned audio file, if not specified, the sampling
            rate of the audio file is taken

    Returns:
        tuple
        (numpy.array, sampling rate), array containing the audio at the sampling rate given

    """
    (audio, fs) = soundfile.read(path, **kwargs)
    if audio.ndim > 1:
        audio = np.mean(audio, axis=1)
    if target_fs is not None and fs != target_fs:
        audio = librosa.resample(audio, orig_sr=fs, target_sr=target_fs)
        fs = target_fs
    return audio, fs

def weights_init(m):
    """ Initialize the weights of some layers of neural networks, here Conv2D, BatchNorm, GRU, Linear
        Based on the work of Xavier Glorot
    Args:
        m: the model to initialize
    """
    classname = m.__class__.__name__
    if classname.find('Conv2d') != -1:
        nn.init.xavier_uniform_(m.weight, gain=np.sqrt(2))
        m.bias.data.fill_(0)
    elif classname.find('BatchNorm') != -1:
        m.weight.data.normal_(1.0, 0.02)
        m.bias.data.fill_(0)
    elif classname.find('GRU') != -1:
        for weight in m.parameters():
            if len(weight.size()) > 1:
                nn.init.orthogonal_(weight.data)
    elif classname.find('Linear') != -1:
        m.weight.data.normal_(0, 0.01)
        m.bias.data.zero_()

def to_cuda_if_available(*args):
    """ Transfer object (Module, Tensor) to GPU if GPU available
    Args:
        args: torch object to put on cuda if available (needs to have object.cuda() defined)

    Returns:
        Objects on GPU if GPUs available
    """
    res = list(args)
    if torch.cuda.is_available():
        for i, torch_obj in enumerate(args):
            res[i] = torch_obj.cuda()
    if len(res) == 1:
        return res[0]
    return res

class SaveBest:
    """ Callback to get the best value and epoch
    Args:
        val_comp: str, (Default value = "inf") "inf" or "sup", inf when we store the lowest model, sup when we
            store the highest model
    Attributes:
        val_comp: str, "inf" or "sup", inf when we store the lowest model, sup when we
            store the highest model
        best_val: float, the best values of the model based on the criterion chosen
        best_epoch: int, the epoch when the model was the best
        current_epoch: int, the current epoch of the model
    """
    def __init__(self, val_comp="inf"):
        self.comp = val_comp
        if val_comp in ["inf", "lt", "desc"]:
            self.best_val = np.inf
        elif val_comp in ["sup", "gt", "asc"]:
            self.best_val = 0
        else:
            raise NotImplementedError("value comparison is only 'inf' or 'sup'")
        self.best_epoch = 0
        self.current_epoch = 0

    def apply(self, value):
        """ Apply the callback
        Args:
            value: float, the value of the metric followed
        """
        decision = False
        if self.current_epoch == 0:
            decision = True
        if (self.comp == "inf" and value < self.best_val) or (self.comp == "sup" and value > self.best_val):
            self.best_epoch = self.current_epoch
            self.best_val = value
            decision = True
        self.current_epoch += 1
        return decision

class EarlyStopping:
    """ Callback to stop training if the metric have not improved during multiple epochs.
    Args:
        patience: int, number of epochs with no improvement before stopping the model
        val_comp: str, (Default value = "inf") "inf" or "sup", inf when we store the lowest model, sup when we
            store the highest model
    Attributes:
        patience: int, number of epochs with no improvement before stopping the model
        val_comp: str, "inf" or "sup", inf when we store the lowest model, sup when we
            store the highest model
        best_val: float, the best values of the model based on the criterion chosen
        best_epoch: int, the epoch when the model was the best
        current_epoch: int, the current epoch of the model
    """
    def __init__(self, patience, val_comp="inf", init_patience=0):
        self.patience = patience
        self.first_early_wait = init_patience
        self.val_comp = val_comp
        if val_comp == "inf":
            self.best_val = np.inf
        elif val_comp == "sup":
            self.best_val = 0
        else:
            raise NotImplementedError("value comparison is only 'inf' or 'sup'")
        self.current_epoch = 0
        self.best_epoch = 0

    def apply(self, value):
        """ Apply the callback

        Args:
            value: the value of the metric followed
        """
        current = False
        if self.val_comp == "inf":
            if value < self.best_val:
                current = True
        if self.val_comp == "sup":
            if value > self.best_val:
                current = True
        if current:
            self.best_val = value
            self.best_epoch = self.current_epoch
        elif self.current_epoch - self.best_epoch > self.patience and self.current_epoch > self.first_early_wait:
            self.current_epoch = 0
            return True
        self.current_epoch += 1
        return False

class AverageMeterSet:
    def __init__(self):
        self.meters = {}

    def __getitem__(self, key):
        return self.meters[key]

    def update(self, name, value, n=1):
        if name not in self.meters:
            self.meters[name] = AverageMeter()
        self.meters[name].update(value, n)

    def reset(self):
        for meter in self.meters.values():
            meter.reset()

    def values(self, postfix=''):
        return {name + postfix: meter.val for name, meter in self.meters.items()}

    def averages(self, postfix='/avg'):
        return {name + postfix: meter.avg for name, meter in self.meters.items()}

    def sums(self, postfix='/sum'):
        return {name + postfix: meter.sum for name, meter in self.meters.items()}

    def counts(self, postfix='/count'):
        return {name + postfix: meter.count for name, meter in self.meters.items()}

    def __str__(self):
        string = ""
        for name, meter in self.meters.items():
            fmat = ".4f"
            if meter.val < 0.01:
                fmat = ".2E"
            string += "{} {:{format}} \t".format(name, meter.val, format=fmat)
        return string

class AverageMeter:
    """Computes and stores the average and current value"""

    def __init__(self):
        self.reset()

    def reset(self):
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def update(self, val, n=1):
        self.val = val
        self.sum += val * n
        self.count += n
        self.avg = self.sum / self.count

    def __format__(self, format):
        return "{self.avg:{format}}".format(self=self, format=format)

def generate_tsv_wav_durations(audio_dir, out_tsv):
    """ Generate a dataframe with filename and duration of the file
    Args:
        audio_dir: str, the path of the folder where audio files are (used by glob.glob)
        out_tsv: str, the path of the output tsv file

    Returns:
        pd.DataFrame, the dataframe containing filenames and durations
    """
    meta_list = []
    for file in glob.glob(os.path.join(audio_dir, "*.wav")):
        d = soundfile.info(file).duration
        meta_list.append([os.path.basename(file), d])
    meta_df = pd.DataFrame(meta_list, columns=["filename", "duration"])
    if out_tsv is not None:
        meta_df.to_csv(out_tsv, sep="\t", index=False, float_format="%.1f")
    return meta_df

def generate_tsv_from_isolated_events(wav_folder, out_tsv=None):
    """ Generate list of separated wav files in a folder and export them in a tsv file
    Separated audio files considered are all wav files in 'subdirectories' of the 'wav_folder'
    Args:
        wav_folder: str, path of the folder containing subdirectories (one for each mixture separated)
        out_tsv: str, path of the csv in which to save the list of files
    Returns:
        pd.DataFrame, having only one column with the filename considered
    """
    if out_tsv is not None and os.path.exists(out_tsv):
        source_sep_df = pd.read_csv(out_tsv, sep="\t")
    else:
        source_sep_df = pd.DataFrame()
        list_dirs = [d for d in os.listdir(wav_folder) if osp.isdir(osp.join(wav_folder, d))]
        for dirname in list_dirs:
            list_isolated_files = []
            for directory, subdir, fnames in os.walk(osp.join(wav_folder, dirname)):
                for fname in fnames:
                    if osp.splitext(fname)[1] in [".wav"]:
                        # Get the level folders and keep it in the tsv
                        subfolder = directory.split(dirname + os.sep)[1:]
                        if len(subfolder) > 0:
                            subdirs = osp.join(*subfolder)
                        else:
                            subdirs = ""
                        # Append the subfolders and name in the list of files
                        list_isolated_files.append(osp.join(dirname, subdirs, fname))
                    else:
                        warnings.warn(f"Not only wav audio files in the separated source folder,"
                                      f"{fname} not added to the .tsv file")
            source_sep_df = source_sep_df.append(pd.DataFrame(list_isolated_files, columns=["filename"]))
        if out_tsv is not None:
            create_folder(os.path.dirname(out_tsv))
            source_sep_df.to_csv(out_tsv, sep="\t", index=False, float_format="%.3f")
    return source_sep_df

def meta_path_to_audio_dir(tsv_path):
    return os.path.splitext(tsv_path.replace("metadata", "audio"))[0]

def audio_dir_to_meta_path(audio_dir):
    return audio_dir.replace("audio", "metadata") + ".tsv"

def get_durations_df(gtruth_path, audio_dir=None):
    if audio_dir is None:
        audio_dir = meta_path_to_audio_dir(gtruth_path)
    path, ext = os.path.splitext(gtruth_path)
    path_durations_synth = path + "_durations" + ext
    if not os.path.exists(path_durations_synth):
        durations_df = generate_tsv_wav_durations(audio_dir, path_durations_synth)
    else:
        durations_df = pd.read_csv(path_durations_synth, sep="\t")
    return durations_df


# -*- coding: utf-8 -*-

from odoo import models, fields, api, _
from odoo.api import Environment
import odoo, time
from odoo.exceptions import UserError
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo.tools import float_is_zero
from datetime import datetime, timedelta, date
import logging

class SaleOrder(models.Model):
    _inherit = "sale.order"

    transaction_id = fields.Char('Transaction ID', copy=False)
    payment_id = fields.Char('Payment Profile ID', copy=False)
    transaction_date = fields.Datetime('Transaction Date', copy=False)
    refund = fields.Boolean('Refunded', copy=False)
    down_payment_amount = fields.Float(default=0.0, copy=False)
    gateway_type = fields.Selection([], string='Payment Gateway')

    @api.multi
    def resend_link(self):
        """
        resend the link if expired
        """
        for record in self:
            gateway_type = self.env['ir.config_parameter'].sudo().get_param('gateway_type')
            if not gateway_type:
                raise UserError(_('Warning ! \n Please check Payment Gateway configuration.'))
            Journal = self.env['account.journal'].search([('is_authorizenet', '=', True)], limit=1)
            if not Journal:
                raise UserError(_(
                'Error! \n Please Select The Authorize.net Journal.(Accounting->configuration->journal->Authorize.net Journal->True!'))
            self.env['payment.token.invoice'].edi_token_recreate(record, 'sale')
            print('inside resend')
            template_id = self.env.ref('payment_gateway_ui.email_template_sale_order_payment')
            print('template_id', template_id)
            if not template_id:
                raise UserError(_('Warning ! \n No Email Template found.'))
            compose_form = self.env.ref('mail.email_compose_message_wizard_form', False)
            ctx = dict(
                default_model='sale.order',
                default_res_id=self.id,
                default_use_template=bool(template_id),
                default_template_id=template_id.id,
                default_composition_mode='comment',
                mark_invoice_as_sent=True,
            )
            return {
                'name': _('Compose Email'),
                'type': 'ir.actions.act_window',
                'view_type': 'form',
                'view_mode': 'form',
                'res_model': 'mail.compose.message',
                'views': [(compose_form.id, 'form')],
                'view_id': compose_form.id,
                'target': 'new',
                'context': ctx,
            }
        return

    @api.multi
    def action_draft(self):
        for record in self:
            record.payment_id = False
            record.transaction_id = False
            record.transaction_date = False
            unlik_line = self.env['sale.order.line']
            for line in record.order_line:
                if line.product_id and line.product_id.id == int(
                        self.env['ir.config_parameter'].sudo().get_param('sale.default_deposit_product_id')):
                    unlik_line += line
            unlik_line.unlink()
        res = super(SaleOrder, self).action_draft()
        return res

    @api.multi
    def action_cancel(self):
        for record in self:
            record.down_payment_amount = 0
            for invoice in record.invoice_ids.filtered(lambda l: l.state != 'cancelled'):
                payment_record = self.env['payment.token.invoice'].search(
                    [('invoice_id', '=', invoice.id), ('model', '=', 'invoice')])
                payment_record.unlink()
                invoice.action_cancel()
        res = super(SaleOrder, self).action_cancel()
        return res

    @api.multi
    def action_reopen(self):
        """
        reset to quotation with payment fields False
        """
        for record in self:
            record.payment_id = False
            record.transaction_id = False
            record.transaction_id = False
            record.transaction_date = False
            unlik_line = self.env['sale.order.line']
            for line in record.order_line:
                if line.product_id and line.product_id.id == int(
                        self.env['ir.config_parameter'].sudo().get_param('sale.default_deposit_product_id')):
                    unlik_line += line
            unlik_line.unlink()

        res = super(SaleOrder, self).action_reopen()
        return res

    # Create down-payment or a full invoice based on the total amount
    @api.multi
    def create_down_payment(self, total_amount, handling_fee, invoice_total, paid_amount):
        for sale_order in self:
            sale_advance_vals = {
                'advance_payment_method': 'fixed',
                'amount': total_amount,
            }
            sale_advance = self.env['sale.advance.payment.inv'].create(sale_advance_vals)
            print('invoice_total', invoice_total)
            print('paramsssssssssss22222', total_amount + paid_amount + handling_fee)
            # print(test)
            if total_amount + paid_amount + handling_fee >= invoice_total:
                print('inside iffffffff')
                sale_advance.write({
                    'advance_payment_method': 'all',
                })
            if sale_advance.advance_payment_method == 'all':
                print('inside alll')
                invoice_id = sale_order.action_invoice_create(final=True)
                invoice = self.env['account.invoice'].browse(invoice_id)
                invoice.action_invoice_open()
                return invoice
            else:
                if not sale_advance.product_id:
                    vals = sale_advance._prepare_deposit_product()
                    sale_advance.product_id = sale_advance.env['product.product'].create(vals)
                    sale_advance.env['ir.config_parameter'].sudo().set_param('sale.default_deposit_product_id',
                                                                             sale_advance.product_id.id)
                sale_line_obj = self.env['sale.order.line']
                amount = sale_advance.amount
                if sale_advance.product_id.invoice_policy != 'order':
                    raise UserError(_(
                        'The product used to invoice a down payment should have an invoice policy set to "Ordered quantities". Please update your deposit product to be able to create a deposit invoice.'))
                if sale_advance.product_id.type != 'service':
                    raise UserError(_(
                        "The product used to invoice a down payment should be of type 'Service'. Please use another product or update this product."))
                taxes = sale_advance.product_id.taxes_id.filtered(
                    lambda r: not sale_order.company_id or r.company_id == sale_order.company_id)
                if sale_order.fiscal_position_id and taxes:
                    tax_ids = sale_order.fiscal_position_id.map_tax(taxes, sale_advance.product_id,
                                                                    sale_order.partner_shipping_id).ids
                else:
                    tax_ids = taxes.ids
                context = {'lang': sale_order.partner_id.lang}
                analytic_tag_ids = []
                for line in sale_order.order_line:
                    analytic_tag_ids = [(4, analytic_tag.id, None) for analytic_tag in line.analytic_tag_ids]
                so_line = sale_line_obj.create({
                    'name': _('Advance: %s') % (time.strftime('%m %Y'),),
                    'price_unit': amount,
                    'product_uom_qty': 0.0,
                    'order_id': sale_order.id,
                    'discount': 0.0,
                    'product_uom': sale_advance.product_id.uom_id.id,
                    'product_id': sale_advance.product_id.id,
                    'analytic_tag_ids': analytic_tag_ids,
                    'tax_id': [(6, 0, tax_ids)],
                    'is_downpayment': True,
                })
                del context
                invoice = sale_advance._create_invoice(sale_order, so_line, amount)
                invoice.action_invoice_open()
                return invoice

    @api.multi
    def get_payment_url(self):
        """
        :return: Payment url
        """
        token = self.env['payment.token.invoice'].get_invoice_payment_record(self, 'sale')
        web_root_url = self.env['ir.config_parameter'].get_param('web.base.url')
        gateway_type = self.env['ir.config_parameter'].sudo().get_param('gateway_type')
        print('gateway_type', gateway_type)
        EDI_VIEW_WEB_URL = '%s/%s/payment?token=%s' % (web_root_url, gateway_type, token)
        return EDI_VIEW_WEB_URL

    @api.multi
    def write(self, vals):
        res = super(SaleOrder, self).write(vals)
        for rec in self:
            if vals.get('order_line', False):
                product = self.env['ir.config_parameter'].sudo().get_param('sale.default_deposit_product_id')
                sale_line_deposit = rec.order_line.filtered(lambda line: line.product_id.id == int(product))
                order_line_ids = rec.order_line.filtered(lambda line: line.product_id.id != int(product))
                seq = 1
                for line in order_line_ids:
                    line.sequence = seq
                    seq += 1
                for line in sale_line_deposit:
                    line.sequence = seq
                    seq += 1
            if vals.get('payment_id', False):
                rec.partner_invoice_id and rec.partner_invoice_id.write({'payment_id': vals.get('payment_id', False)})
        return res

    @api.multi
    def copy(self, default=None):
        default = default or {}
        default.update({
            'user_id': self._uid,
        })
        res = super(SaleOrder, self).copy(default=default)
        unlink_line = self.env['sale.order.line']
        for line in res.order_line:
            if line.product_id and line.product_id.id == int(
                    self.env['ir.config_parameter'].get_param('sale.default_deposit_product_id')):
                unlink_line += line
        if unlink_line:
            unlink_line.unlink()
        return res

SaleOrder()


from typing import Optional

import torch
from torch import nn

from vision_models_playground.utility.config import build_object_from_config_path

def load_model_from_weights(
        model: nn.Module,
        weights_path: str,
        device: Optional[torch.device] = None
):
    """
    Load the weights of a model

    Arguments
    ---------
    model: nn.Module
        The model to load the weights into. It needs to be the same model as the one used to save the weights

    weights_path: str
        The path to the weights

    device: Optional[torch.device]
        The device to load the weights to. If None, it will be loaded to the device the model is on
    """

    if device is None:
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    model.load_state_dict(
        torch.load(weights_path, map_location=device)
    )

    return model

def load_model_from_config(
        config_path: str,
        weights_path: str,
        device: Optional[torch.device] = None,
):
    """
    Load a model from a config file and weights

    Arguments
    ---------
    config_path: str
        The path to the config file

    weights_path: str
        The path to the weights

    device: Optional[torch.device]
        The device to load the weights to. If None, it will be loaded to the device the model is on
    """

    model = build_object_from_config_path(config_path)
    model = load_model_from_weights(model, weights_path, device)

    return model

def load_model_from_dir(
        save_dir: str,
        device: Optional[torch.device] = None,
        file_name: str = 'best'
):
    """
    Load the best model from a save directory

    Arguments
    ---------
    save_dir: str
        The directory to load the model from

    device: Optional[torch.device]
        The device to load the weights to. If None, it will be loaded to the device the model is on

    file_name: str
        The name of the file to load the weights from
    """
    config_path = f'{save_dir}/config.json'
    weights_path = f'{save_dir}/{file_name}.pt'

    return load_model_from_config(config_path, weights_path, device)


# [2016-04-11] Challenge #262 [Easy] MaybeNumeric
# https://www.reddit.com/r/dailyprogrammer/comments/4eaeff/20160411_challenge_262_easy_maybenumeric/

inputArray = ["123", "44.234", "0x123N", "1..23", "123 234 345", "3.23e5", "1293712938712938172938172391287319237192837329", ".25", "2015 4 4`Challenge #`261`Easy", "234.2`234ggf 45`00`number string number (0)"]

def main():
  for item in inputArray:
    for miniitem in item.split("`"):
      if miniitem.count(" ") > 0:
        print(miniitem, testArray(miniitem))
      else:
        print(miniitem, isnumber(miniitem))

def testArray(array):
  for ind in array.split():
    if not isnumber(ind):
      return False
  return True

def isnumber(number):
  if number.count(".") < 2:
    if 'e' not in number:
      for i in number:
        if i not in "01234567890.":
          return False
      return True
    else:
      temp = number.split("e")
      return isnumber(temp[0]) and isnumber(temp[1])
  else:
    return False

if __name__ == "__main__":
    main()


import tensorflow as tf
import config as cfg
from tensorflow.python.framework import graph_util
WEIGHTS_INIT = cfg.CKPT2PB_CKPT_FILE
__weights_init = WEIGHTS_INIT

output_node_sbbox = "yolov3/pred_sbbox/concat_2"
output_node_mbbox = "yolov3/pred_mbbox/concat_2"
output_node_lbbox = "yolov3/pred_lbbox/concat_2"
output_node_name = "yolov3/pred_sbbox/concat_2,yolov3/pred_mbbox/concat_2,yolov3/pred_lbbox/concat_2"
moving_ave_decay = cfg.MOVING_AVE_DECAY

output_graph = cfg.CKPT2PB_PB_NAME

saver = tf.train.import_meta_graph(__weights_init + '.meta', clear_devices=True)
graph = tf.get_default_graph()  # 获得默认的图
input_graph_def = graph.as_graph_def()  # 返回一个序列化的图代表当前的图

with tf.Session() as sess:
    saver.restore(sess, __weights_init)  # 恢复图并得到数据
    output_graph_def = graph_util.convert_variables_to_constants(  # 模型持久化，将变量值固定
        sess=sess,
        input_graph_def=sess.graph_def,  # 等于:sess.graph_def
        output_node_names=output_node_name.split(","))  # 如果有多个输出节点，以逗号隔开
        #output_node_names=[output_node_sbbox, output_node_mbbox, output_node_lbbox])

    with tf.gfile.GFile(output_graph, "wb") as f:  # 保存模型
        f.write(output_graph_def.SerializeToString())  # 序列化输出
    print("%d ops in the final graph." % len(output_graph_def.node))  # 得到当前图有几个操作节点

"""

org_weights_mess = []

G = tf.Graph()
with G.as_default():
    load = tf.train.import_meta_graph(__weights_init + '.meta', clear_devices=True)
    with tf.Session(graph=G) as sess_G:
        load.restore(sess_G, __weights_init)
        for var in tf.global_variables():
            var_name = var.op.name
            var_name_mess = str(var_name).split('/')
            var_shape = var.shape
            #if var_name_mess[-1] != 'pred_sbbox':
                #continue
            # print(var_name_mess[0])
            org_weights_mess.append([var_name, var_shape])
            print(var_name)
            print("\n")
print(org_weights_mess)
"""


print("Odd or Even")
print("What number are you thinking?")

while True:
    try:
        num = int(input())
        if type(num) == int:
            if num % 2 == 0:
                print("That's an Even Number! Have another?")
            else:
                print("That's an Odd Number! Have another?")

    except ValueError:
         print("Sorry, I didn't understand that. Please insert a whole number!")
         continue


import subprocess
import os

def test_torrent_to_json():
    # Execute command
    try:
        # Change the working directory to the parent folder
        os.chdir(os.path.dirname(get_local_path()))

        # Run the command and capture the output
        completed_process = subprocess.run(
            'torrentify test/test_files/inputs/torrent/debian.iso.torrent test/test_files/outputs/json/debian.iso json',
            shell=True,
            text=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)

        # Check if the command was successful (return code 0)
        if completed_process.returncode == 0:
            print(completed_process.stdout)
        else:
            print("Command failed with the following error message:")
            print(completed_process.stderr)
    except Exception as e:
        print(f"An error occurred: {str(e)}")
    # Compare output
    compare_files_by_bytes("test/test_files/inputs/json/debian.iso.json",
                           "test/test_files/outputs/json/debian.torrent")

def compile():
    try:
        # Change the working directory to the parent folder
        os.chdir(os.path.dirname(get_local_path()))

        # Run the command and capture the output
        completed_process = subprocess.run(
            'cargo build',
            shell=True,
            text=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)

        # Check if the command was successful (return code 0)
        if completed_process.returncode == 0:
            assert(completed_process.returncode == 0)
            print("Compiled successfully")
            print(completed_process.stdout)
        else:
            print("Command failed with the following error message:")
            print(completed_process.stderr)
    except Exception as e:
        print(f"An error occurred: {str(e)}")

def test_suite_decode():
    compile()
    test_torrent_to_json()

# HELPERS

def get_local_path():
    return os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

def compare_files_by_bytes(file1_path, file2_path):
    try:
        # Open both files in binary mode
        with open(file1_path, 'rb') as file1, open(file2_path, 'rb') as file2:
            # Read the contents of both files as bytes
            content1 = file1.read()
            content2 = file2.read()

            # Compare the contents byte by byte
            if content1 == content2:
                return True
            else:
                return False

    except FileNotFoundError:
        print("One or both of the files does not exist.")
        return False

# Provide the file paths you want to compare
file1_path = 'file1.bin'
file2_path = 'file2.bin'

if compare_files_by_bytes(file1_path, file2_path):
    print("Both files have the same content.")
else:
    print("Files have different content.")

print(f"cwd: {get_local_path()}")


from __future__ import absolute_import

import struct
import logging

log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

from wcf.datatypes import *
from wcf.records.base import *
from wcf.dictionary import *

class ShortElementRecord(Element):
    type = 0x40

    def __init__(self, name, *args, **kwargs):
        self.childs = []
        self.name = name
        self.attributes = []

    def to_bytes(self):
        """
        >>> ShortElementRecord('Envelope').to_bytes()
        '@\\x08Envelope'
        """
        string = Utf8String(self.name)

        bytes= (super(ShortElementRecord, self).to_bytes() +
                string.to_bytes())

        for attr in self.attributes:
            bytes += attr.to_bytes()
        return bytes

    def __str__(self):
        #return '<%s[name=%s]>' % (type(self).__name__, self.name)
        return '<%s %s>' % (self.name,
                ' '.join([str(a) for a in self.attributes]))

    @classmethod
    def parse(cls, fp):
        name = Utf8String.parse(fp).value
        return cls(name)

class ElementRecord(ShortElementRecord):
    type = 0x41

    def __init__(self, prefix, name, *args, **kwargs):
        super(ElementRecord, self).__init__(name)
        self.prefix = prefix

    def to_bytes(self):
        """
        >>> ElementRecord('x', 'Envelope').to_bytes()
        'A\\x01x\\x08Envelope'
        """
        pref = Utf8String(self.prefix)
        data = super(ElementRecord, self).to_bytes()
        type = data[0]
        return (type + pref.to_bytes() + data[1:])

    def __str__(self):
        return '<%s:%s %s>' % (self.prefix, self.name,
                ' '.join([str(a) for a in self.attributes]))

    @classmethod
    def parse(cls, fp):
        prefix = Utf8String.parse(fp).value
        name = Utf8String.parse(fp).value
        return cls(prefix, name)

class ShortDictionaryElementRecord(Element):
    type = 0x42

    def __init__(self, index, *args, **kwargs):
        self.childs = []
        self.index = index
        self.attributes = []
        self.name = dictionary[self.index]

    def __str__(self):
        return '<%s %s>' % (self.name, ' '.join([str(a) for a in
            self.attributes]))

    def to_bytes(self):
        """
        >>> ShortDictionaryElementRecord(2).to_bytes()
        'B\\x02'
        """
        string = MultiByteInt31(self.index)

        bytes= (super(ShortDictionaryElementRecord, self).to_bytes() +
                string.to_bytes())

        for attr in self.attributes:
            bytes += attr.to_bytes()
        return bytes

    @classmethod
    def parse(cls, fp):
        index = MultiByteInt31.parse(fp).value
        return cls(index)

class DictionaryElementRecord(Element):
    type = 0x43

    def __init__(self, prefix, index, *args, **kwargs):
        self.childs = []
        self.prefix = prefix
        self.index = index
        self.attributes = []
        self.name = dictionary[self.index]

    def __str__(self):
        """
        >>> str(DictionaryElementRecord('x', 2))
        '<x:Envelope >'
        """
        return '<%s:%s %s>' % (self.prefix, self.name,
                ' '.join([str(a) for a in self.attributes]))

    def to_bytes(self):
        """
        >>> DictionaryElementRecord('x', 2).to_bytes()
        'C\\x01x\\x02'
        """
        pref = Utf8String(self.prefix)
        string = MultiByteInt31(self.index)

        bytes = (super(DictionaryElementRecord, self).to_bytes() +
                pref.to_bytes() +
                string.to_bytes())

        for attr in self.attributes:
            bytes += attr.to_bytes()
        return bytes

    @classmethod
    def parse(cls, fp):
        prefix = Utf8String.parse(fp).value
        index = MultiByteInt31.parse(fp).value
        return cls(prefix, index)

class PrefixElementRecord(ElementRecord):
    def __init__(self, name):
        super(PrefixElementRecord, self).__init__(self.char, name)

    def to_bytes(self):
        string = Utf8String(self.name)

        bytes = (struct.pack('<B', self.type) +
                string.to_bytes())

        for attr in self.attributes:
            bytes += attr.to_bytes()
        return bytes

    @classmethod
    def parse(cls, fp):
        name = Utf8String.parse(fp).value
        return cls(name)

class PrefixDictionaryElementRecord(DictionaryElementRecord):
    def __init__(self, index):
        super(PrefixDictionaryElementRecord, self).__init__(self.char, index)

    def to_bytes(self):
        string = MultiByteInt31(self.index)

        bytes = (struct.pack('<B', self.type) +
                string.to_bytes())

        for attr in self.attributes:
            bytes += attr.to_bytes()
        return bytes

    @classmethod
    def parse(cls, fp):
        index = MultiByteInt31.parse(fp).value
        return cls(index)

Record.add_records((
        ShortElementRecord,
        ElementRecord,
        ShortDictionaryElementRecord,
        DictionaryElementRecord,
    ))

__records__ = []

for c in range(0x44, 0x5D + 1):
    char = chr(c - 0x44 + ord('a'))
    cls = type(
           'PrefixDictionaryElement' + char.upper() + 'Record',
           (PrefixDictionaryElementRecord,),
           dict(
                type=c,
                char=char,
            )
           )
    __records__.append(cls)

for c in range(0x5E, 0x77 + 1):
    char = chr(c - 0x5E + ord('a'))
    cls = type(
           'PrefixElement' + char.upper() + 'Record',
           (PrefixElementRecord,),
           dict(
                type=c,
                char=char,
            )
           )
    __records__.append(cls)

Record.add_records(__records__)
del __records__


import functions.Policy as pc
import tensorflow as tf
import core
import Utils
from operator import mul
from functools import reduce
import numpy as np

class RecurrentStochasticPolicy(pc.Policy):
    def __init__(self, dtype, gs):
        # shortcuts
        action_dim = int(gs.output.shape[-1])
        state_dim = int(gs.input.shape[-1])

        action = tf.identity(gs.output, name=self.output_names[0])

        # standard deviation layer
        with tf.name_scope('stdevconcatOutput'):
            wo = tf.Variable(tf.zeros(shape=[1, action_dim], dtype=dtype), name='W',
                             trainable=True)  # Log standard deviation
            action_stdev = tf.identity(tf.exp(wo), name='stdev')

        gs.l_param_list.append(wo)
        gs.a_param_list.append(wo)

        super(RecurrentStochasticPolicy, self).__init__(dtype, gs)

        stdev_assign_placeholder = tf.placeholder(dtype, shape=[1, action_dim], name='Stdev_placeholder')
        Stdev_assign = tf.assign(wo, tf.log(stdev_assign_placeholder), name='assignStdev')
        Stdev_get = tf.exp(wo, name='getStdev')

        tangent_in = tf.placeholder(dtype, shape=[1, None], name='tangent')
        old_stdv = tf.placeholder(dtype, shape=[1, action_dim], name='stdv_o')
        old_action_sampled = tf.placeholder(dtype, shape=[None, None, action_dim], name='sampledAction')
        old_action_noise = tf.placeholder(dtype, shape=[None, None, action_dim], name='actionNoise')
        advantage_in = tf.placeholder(dtype, shape=[None, None], name='advantage')

        # Algorithm params
        kl_coeff = tf.Variable(tf.constant(1.0, dtype=dtype), name='kl_coeff', trainable=False)
        ent_coeff = tf.Variable(tf.constant(0.01, dtype=dtype), name='ent_coeff', trainable=False)
        clip_param = tf.Variable(tf.constant(0.2, dtype=dtype), name='clip_param', trainable=False)

        PPO_params_placeholder = tf.placeholder(dtype, shape=[1, 3], name='PPO_params_placeholder')

        param_assign_op_list = []
        param_assign_op_list += [
            tf.assign(kl_coeff, tf.reshape(tf.slice(PPO_params_placeholder, [0, 0], [1, 1]), []), name='kl_coeff_assign')]
        param_assign_op_list += [
            tf.assign(ent_coeff, tf.reshape(tf.slice(PPO_params_placeholder, [0, 1], [1, 1]), []), name='ent_coeff_assign')]
        param_assign_op_list += [
            tf.assign(clip_param, tf.reshape(tf.slice(PPO_params_placeholder, [0, 2], [1, 1]), []), name='clip_param_assign')]

        PPO_param_assign_ops = tf.group(*param_assign_op_list, name='PPO_param_assign_ops')

        mask = tf.sequence_mask(gs.seq_length, maxlen=tf.shape(gs.input)[1], name='mask')
        action_target = tf.placeholder(dtype, shape=[None, None, None], name='targetAction')

        action_masked = tf.boolean_mask(action, mask)
        action_target_masked = tf.boolean_mask(action_target, mask)

        with tf.name_scope('trainUsingTarget'):
            core.square_loss_opt(dtype, action_target_masked, action_masked, tf.train.AdamOptimizer(learning_rate=self.learningRate), maxnorm=self.max_grad_norm)

        with tf.name_scope('trainUsingGrad'):
            gradient_from_critic = tf.placeholder(dtype, shape=[1, None], name='Inputgradient')
            train_using_grad_optimizer = tf.train.AdamOptimizer(learning_rate=self.learningRate)

            split_parameter_gradients = tf.split(gradient_from_critic,
                                                 [reduce(mul, param.get_shape().as_list(), 1) for param in
                                                  gs.a_param_list], 1)
            manipulated_parameter_gradients = []
            for grad, param in zip(split_parameter_gradients, gs.l_param_list):
                manipulated_parameter_gradients += [tf.reshape(grad, tf.shape(param))]

            manipulated_parameter_gradients_and_parameters = zip(manipulated_parameter_gradients, gs.l_param_list)
            train_using_gradients = train_using_grad_optimizer.apply_gradients(
                manipulated_parameter_gradients_and_parameters, name='applyGradients')

        util = Utils.Utils(dtype)

        with tf.name_scope('Algo'):
            logp_n = tf.boolean_mask(util.log_likelihood(action, action_stdev, old_action_sampled), mask)
            logp_old = tf.boolean_mask(util.log_likelihood(old_action_noise, old_stdv), mask)
            advantage = tf.boolean_mask(advantage_in, mask)
            ratio = tf.exp(logp_n - logp_old)
            ent = tf.reduce_sum(wo + .5 * tf.cast(tf.log(2.0 * np.pi * np.e), dtype=dtype), axis=-1)
            meanent = tf.reduce_mean(ent)

            with tf.name_scope('PPO'):
                surr1 = tf.multiply(ratio, advantage)
                surr2 = tf.multiply(tf.clip_by_value(ratio, 1.0 - clip_param, 1.0 + clip_param), advantage)
                PPO_loss = tf.reduce_mean(tf.maximum(surr1, surr2))  # PPO's pessimistic surrogate (L^CLIP)

                kl_ = tf.boolean_mask(
                    util.kl_divergence((old_action_sampled - old_action_noise), old_stdv, action, action_stdev), mask)
                kl_mean = tf.reshape(tf.reduce_mean(kl_), shape=[1, 1, 1], name='kl_mean')

                Total_loss = PPO_loss - tf.multiply(ent_coeff, meanent)
                Total_loss2 = PPO_loss - tf.multiply(ent_coeff, meanent) + tf.multiply(kl_coeff, tf.reduce_mean(kl_))

                policy_gradient = tf.identity(tf.expand_dims(util.flatgrad(Total_loss, gs.l_param_list, self.max_grad_norm), axis=0), name='Pg')  # flatgrad
                policy_gradient2 = tf.identity(tf.expand_dims(util.flatgrad(Total_loss2, gs.l_param_list, self.max_grad_norm), axis=0), name='Pg2')  # flatgrad


import sys
from . import expand_args

if __name__ == "__main__":
    args = sys.argv[1:]
    if len(args) > 0 and args[0] in ['-v', '--verbose']:
        debug = True
        args = args[1:]
    else:
        debug = False
    if debug:
        print("args: ", " ".join(args))
    print(" ".join(expand_args(args, debug = debug)))


key = 'MFHIJKNOPQUZVWXYELARGDSTBC'
matrix = [key[i:i+5] for i in range(0, 25, 5)]
def get_indices(c):
    for i, row in enumerate(matrix):
        for j, letter in enumerate(row):
            if letter == c:
                return (i, j)
def encrypt(message):
    # Replace J with I
    message = message.upper().replace('J', 'I')

    message = ''.join(filter(str.isalpha, message))
    if len(message) % 2 != 0:
        message += 'Z'
    pairs = [message[i:i+2] for i in range(0, len(message), 2)]
    ciphertext = ''
    for pair in pairs:
        row1, col1 = get_indices(pair[0])
        row2, col2 = get_indices(pair[1])

        if row1 == row2:
            ciphertext += matrix[row1][(col1+1)%5]
            ciphertext += matrix[row2][(col2+1)%5]
        elif col1 == col2:
            ciphertext += matrix[(row1+1)%5][col1]
            ciphertext += matrix[(row2+1)%5][col2]
        else:
            ciphertext += matrix[row1][col2]
            ciphertext += matrix[row2][col1]

    return ciphertext


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

import pygame

class Effect(pygame.sprite.Sprite):
    """ Effect"""

    def __init__(self, frames, x_pos, y_pos, fps=100):

        pygame.sprite.Sprite.__init__(self)
        self._images = frames

        self._frame = 0
        self.image = self._images[self._frame]

        self.x, self.y = x_pos, y_pos
        self.rect = self.image.get_rect()
        self.rect.center = (self.x, self.y)
        self.remove_flag = 0

    def update(self, shift=0):
        if self._frame < len(self._images) - 1:
            self._frame += 1
            self.x -= shift
            self.image = self._images[self._frame]
            self.rect.center = self.x, self.y
        else:
            self.remove_flag = 1

    def render(self, screen):
        """ drawing Unit on screen"""
        screen.blit(self.image, self.rect)


import boto3
import json
import os

dynamodb_client = boto3.client('dynamodb')
sqs_client = boto3.client('sqs')

def lambda_handler(event, context):
    order_item = json.loads(event["body"])
    if order_item['receiptHandle']:
        queue_name = os.getenv("QUEUE_NAME")
        queue = sqs_client.get_queue_url(QueueName=queue_name)
        queue_url = queue['QueueUrl']
        response = sqs_client.delete_message(
            QueueUrl=queue_url,
            ReceiptHandle=order_item['receiptHandle']
        )

    response = {
        'statusCode': 200,
        'body': 'successfully handle order!',
        'headers': {
            'Content-Type': 'application/json',
            "Access-Control-Allow-Headers": "Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method,X-Access-Token, XKey, Authorization",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,OPTIONS"
        },
    }

    return response