# https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
import collections
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def levelOrderBottomUp(root):
    if not root:
        return None
    dq = collections.deque()
    dq.append(root)
    res = []
    while dq:
        level = []
        for _ in range(len(dq)):
            node = dq.popleft()
            if node.left:
                dq.append(node.left)
            if node.right:
                dq.append(node.right)
            level.append(node.val)
        res.append(level)
    return reversed(res)


from rest_framework.decorators import action
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST, HTTP_201_CREATED
from rest_framework.viewsets import GenericViewSet

from orders.serializers import OrderSerializer
from orders.services import get_customer_orders, get_customer_order, create_new_order

class OrdersViewSet(GenericViewSet, ListModelMixin, RetrieveModelMixin):
    serializer_class = OrderSerializer

    def list(self, request, *args, **kwargs):
        data = self.get_queryset()
        serialized_data = self.get_serializer(data, many=True).data
        return Response(status=HTTP_200_OK, data=serialized_data)

    def retrieve(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk')
        data = get_customer_order(order_id=pk, customer_id=request.user.customer.id)
        serialized_data = self.get_serializer(data).data
        return Response(status=HTTP_200_OK, data=serialized_data)

    def get_queryset(self):
        return get_customer_orders(self.request.user.customer.id)

    @action(methods=['POST'], detail=False, url_path='create-order')
    def create_order(self, request):
        try:
            customer_id, cart_id, delivery_type, address = request.user.customer.id, request.data.get(
                'cart_id'), request.data.get('delivery_type'), request.data.get('address')
            create_new_order(customer_id=customer_id, cart_id=cart_id, delivery_type=delivery_type, address=address)
            return Response(status=HTTP_201_CREATED)
        except ValueError as e:
            return Response(status=HTTP_400_BAD_REQUEST, data={'error': str(e)})


import numpy as np
import sys
import os
import pickle, gzip
from scipy.special import expit

emotionLabels = pickle.load(gzip.open('LabelNumMap.pickle.gz', 'rb'), encoding='latin1')

fileidx = pickle.load(gzip.open('testIdx.pickle.gz', 'rb'), encoding='latin1')

feature_mat = pickle.load(gzip.open('testfeature.pickle.gz', 'rb'), encoding='latin1')

_, indices = pickle.load(gzip.open('test.pickle.gz', 'rb'), encoding='latin1')

W, U = pickle.load(gzip.open('ELMWeights.pickle.gz', 'rb'), encoding='latin1')

segnum = indices.max()

utterFeatList = []

for i in range(segnum + 1):
    frames = feature_mat[indices == i, :]
    # change the way of computing energy using the new energy file
    if frames.size != 0:
        feat1 = np.amax(frames, axis=0)
        feat2 = np.amin(frames, axis=0)
        feat3 = np.mean(frames, axis=0)
        feat4 = np.mean(frames > 0.2, axis=0)
        utter_feat = np.hstack([feat1, feat2, feat3, feat4])
        utterFeatList.append(utter_feat)
    utterFeats = np.vstack(utterFeatList)

H = expit(W.T.dot(utterFeats.T))
Predicts = H.T.dot(U)

results = np.argmax(Predicts, axis= 1)
inv_map = {v: k for k, v in emotionLabels.items()}

text_file = open("Results.txt", "w")
for i in range(segnum + 1):
    text_file.write("%s  %s\n" % (fileidx[i], inv_map[results[i]]))
text_file.close()


"""
* 이진 트리 직렬화 & 역직렬화
이진 트리를 배열로 직렬화하고, 반대로 역직렬화하는 기능을 구현하라.
즉 다음과 같은 트리는 [1, 2, 3, null, null, 4, 5] 형태로 직렬화할 수 있을 것이다.
     1
   /   \
  2     3
 / \   / \
      4   5
"""

# Definition for a binary tree node.
import collections
from typing import List

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def serialize(self, root: TreeNode) -> str:
        queue = collections.deque([root])
        result = ['#']

        while queue:
            node = queue.popleft()
            if node:
                queue.append(node.left)
                queue.append(node.right)

                result.append(str(node.val))
            else:
                result.append('#')
        return ' '.join(result)

    def deserialize(self, data: str):
        nodes = data.split(' ')

        root = TreeNode(int(nodes[1]))
        queue = collections.deque([root])

        index = 2
        # 빠른 런너처럼 자식 노드 결과를 먼저 확인 후 큐 삽입
        while queue:
            node = queue.popleft()
            if nodes[index] != '#':
                node.left = TreeNode(int(nodes[index]))
                queue.append(node.left)
            index += 1

            if nodes[index] != '#':
                node.right = TreeNode(int(nodes[index]))
                queue.append(node.right)
            index += 1
        return root

if __name__ == '__main__':
    print(Solution().serialize(TreeNode(1, TreeNode(2), TreeNode(3, TreeNode(4), TreeNode(5)))))
    d_tree = Solution().deserialize('# 1 2 3 # # 4 5 # # # #')
    print(Solution().serialize(d_tree))


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models
import datetime
from django.utils.timezone import utc

class Migration(migrations.Migration):

    dependencies = [
        ('UTD', '0012_auto_20160417_1213'),
    ]

    operations = [
        migrations.AddField(
            model_name='playlist',
            name='last_update',
            field=models.DateField(default=datetime.datetime(2016, 4, 17, 12, 46, 51, 864268, tzinfo=utc)),
        ),
        migrations.AlterField(
            model_name='playlist',
            name='song',
            field=models.ManyToManyField(to='UTD.Song', blank=True),
        ),
    ]


from __future__ import annotations

import datetime
import re
from typing import TYPE_CHECKING, Optional

import parsedatetime as pdt
from dateutil.relativedelta import relativedelta
from discord.ext import commands

from .formats import human_join, plural

# Monkey patch mins and secs into the units
units = pdt.pdtLocales["en_US"].units
units["minutes"].append("mins")
units["seconds"].append("secs")

if TYPE_CHECKING:
    from typing_extensions import Self

class ShortTime:
    compiled = re.compile(
        """
           (?:(?P<years>[0-9])(?:years?|y))?                      # e.g. 2y
           (?:(?P<months>[0-9]{1,2})(?:months?|mon?))?            # e.g. 2months
           (?:(?P<weeks>[0-9]{1,4})(?:weeks?|w))?                 # e.g. 10w
           (?:(?P<days>[0-9]{1,5})(?:days?|d))?                   # e.g. 14d
           (?:(?P<hours>[0-9]{1,5})(?:hours?|hr?s?))?             # e.g. 12h
           (?:(?P<minutes>[0-9]{1,5})(?:minutes?|m(?:ins?)?))?    # e.g. 10m
           (?:(?P<seconds>[0-9]{1,5})(?:seconds?|s(?:ecs?)?))?    # e.g. 15s
        """,
        re.VERBOSE,
    )

    discord_fmt = re.compile(r"<t:(?P<ts>[0-9]+)(?:\:?[RFfDdTt])?>")

    dt: datetime.datetime

    def __init__(
        self,
        argument: str,
        *,
        now: Optional[datetime.datetime] = None,
        tzinfo: datetime.tzinfo = datetime.timezone.utc,
    ):
        match = self.compiled.fullmatch(argument)
        if match is None or not match.group(0):
            match = self.discord_fmt.fullmatch(argument)
            if match is not None:
                self.dt = datetime.datetime.fromtimestamp(
                    int(match.group("ts")), tz=datetime.timezone.utc
                )
                if tzinfo is not datetime.timezone.utc:
                    self.dt = self.dt.astimezone(tzinfo)
                return
            else:
                raise commands.BadArgument("invalid time provided")

        data = {k: int(v) for k, v in match.groupdict(default=0).items()}
        now = now or datetime.datetime.now(datetime.timezone.utc)
        self.dt = now + relativedelta(**data)  # type: ignore
        if tzinfo is not datetime.timezone.utc:
            self.dt = self.dt.astimezone(tzinfo)

    @classmethod
    async def convert(cls, ctx: commands.Context, argument: str) -> Self:
        tzinfo = datetime.timezone.utc
        reminder = ctx.bot.reminder
        if reminder is not None:
            tzinfo = await reminder.get_tzinfo(ctx.author.id)
        return cls(argument, now=ctx.message.created_at, tzinfo=tzinfo)

class HumanTime:
    calendar = pdt.Calendar(version=pdt.VERSION_CONTEXT_STYLE)

    def __init__(
        self,
        argument: str,
        *,
        now: Optional[datetime.datetime] = None,
        tzinfo: datetime.tzinfo = datetime.timezone.utc,
    ):
        now = now or datetime.datetime.now(tzinfo)
        dt, status = self.calendar.parseDT(argument, sourceTime=now, tzinfo=None)
        if not status.hasDateOrTime:  # type: ignore # keep an eye out
            raise commands.BadArgument(
                'invalid time provided, try e.g. "tomorrow" or "3 days"'
            )

        if not status.hasTime:  # type: ignore
            # replace it with the current time
            dt = dt.replace(
                hour=now.hour,
                minute=now.minute,
                second=now.second,
                microsecond=now.microsecond,
            )

        self.dt: datetime.datetime = dt.replace(tzinfo=tzinfo)
        if now.tzinfo is None:
            now = now.replace(tzinfo=datetime.timezone.utc)
        self._past: bool = self.dt < now

    @classmethod
    async def convert(cls, ctx: commands.Context, argument: str) -> Self:
        tzinfo = datetime.timezone.utc
        reminder = ctx.bot.reminder
        if reminder is not None:
            tzinfo = await reminder.get_tzinfo(ctx.author.id)
        return cls(argument, now=ctx.message.created_at, tzinfo=tzinfo)

class Time(HumanTime):
    def __init__(
        self,
        argument: str,
        *,
        now: Optional[datetime.datetime] = None,
        tzinfo: datetime.tzinfo = datetime.timezone.utc,
    ):
        try:
            o = ShortTime(argument, now=now, tzinfo=tzinfo)
        except Exception:
            super().__init__(argument, now=now, tzinfo=tzinfo)
        else:
            self.dt = o.dt
            self._past = False

def human_timedelta(
    dt: datetime.datetime,
    *,
    source: Optional[datetime.datetime] = None,
    accuracy: Optional[int] = 3,
    brief: bool = False,
    suffix: bool = True,
) -> str:
    now = source or datetime.datetime.now(datetime.timezone.utc)
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=datetime.timezone.utc)

    if now.tzinfo is None:
        now = now.replace(tzinfo=datetime.timezone.utc)

    # Microsecond free zone
    now = now.replace(microsecond=0)
    dt = dt.replace(microsecond=0)

    # This implementation uses relativedelta instead of the much more obvious
    # divmod approach with seconds because the seconds approach is not entirely
    # accurate once you go over 1 week in terms of accuracy since you have to
    # hardcode a month as 30 or 31 days.
    # A query like "11 months" can be interpreted as "!1 months and 6 days"
    if dt > now:
        delta = relativedelta(dt, now)
        output_suffix = ""
    else:
        delta = relativedelta(now, dt)
        output_suffix = " ago" if suffix else ""

    attrs = [
        ("year", "y"),
        ("month", "mo"),
        ("day", "d"),
        ("hour", "h"),
        ("minute", "m"),
        ("second", "s"),
    ]

    output = []
    for attr, brief_attr in attrs:
        elem = getattr(delta, attr + "s")
        if not elem:
            continue

        if attr == "day":
            weeks = delta.weeks
            if weeks:
                elem -= weeks * 7
                if not brief:
                    output.append(format(plural(weeks), "week"))
                else:
                    output.append(f"{weeks}w")

        if elem <= 0:
            continue

        if brief:
            output.append(f"{elem}{brief_attr}")
        else:
            output.append(format(plural(elem), attr))

    if accuracy is not None:
        output = output[:accuracy]

    if len(output) == 0:
        return "now"
    else:
        if not brief:
            return human_join(output, final="and") + output_suffix
        else:
            return " ".join(output) + output_suffix


# ##### BEGIN GPL LICENSE BLOCK #####
#
#  This program is free software; you can redistribute it and / or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2
#  of the License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software Foundation,
#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110 - 1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
#

# LOAD MODUL #
import bpy
from bpy import *
from bpy.props import *
from .. icons.icons import load_icons

def draw_biped_ui(self, context, layout):
        tp_props = context.window_manager.tp_props_resurface

        icons = load_icons()

        col = layout.column(1)

        if not tp_props.display_skin:

            box = col.box().column(1)

            row = box.row(1)
            row.prop(tp_props, "display_skin", text="", icon="TRIA_RIGHT", emboss = False)
            row.label("BipedSkin")

            button_skin_human = icons.get("icon_skin_human")
            row.operator("tp_ops.add_skin_human",text="", icon_value=button_skin_human.icon_id)

            button_skin_animal = icons.get("icon_skin_animal")
            row.operator("tp_ops.add_skin_animal",text="", icon_value=button_skin_animal.icon_id)

            #button_skin_empty = icons.get("icon_skin_empty")
            #row.operator("tp_ops.add_skin_empty",text="", icon_value=button_skin_empty.icon_id)
            row.operator("tp_ops.add_skin_empty",text="", icon ="MOD_SKIN")

        else:

            box = col.box().column(1)

            row = box.row(1)
            row.prop(tp_props, "display_skin", text="", icon="TRIA_DOWN", emboss = False)
            row.label("BipedSkin")

            box.separator()

            split = box.split()

            row.scale_y = 1.2
            row = box.row(1)

            row.operator("tp_ops.add_skin_empty",text="Vertex", icon ="MOD_SKIN")

            button_skin_human = icons.get("icon_skin_human")
            row.operator("tp_ops.add_skin_human",text="Human", icon_value=button_skin_human.icon_id)

            button_skin_animal = icons.get("icon_skin_animal")
            row.operator("tp_ops.add_skin_animal",text="Animal", icon_value=button_skin_animal.icon_id)

            box.separator()

            obj = context.active_object
            if obj:

                mo_types = []
                append = mo_types.append

                for mo in context.active_object.modifiers:

                    if mo.type == "SKIN":# and bpy.context.object.mode == "EDIT":
                        append(mo.type)
                        #box.label(mo.name)

                        box.separator()

                        row = box.row()

                        ob = context.object
                        for mod in [m for m in ob.modifiers if m.type == 'MIRROR']:
                            row.prop(bpy.context.active_object.modifiers[mod.name], "show_viewport", text="Mirror")

                        for mod in [m for m in ob.modifiers if m.type == 'SUBSURF']:
                            row.prop(bpy.context.active_object.modifiers[mod.name], "show_viewport", text="SubSurf")

                        box.separator()

                        row = box.row()
                        row.operator("object.skin_armature_create", text="Create Armature")
                        row.operator("mesh.customdata_skin_add")

                        box.separator()

                        row = box.row(align=True)
                        row.prop(mo, "branch_smoothing")
                        row.prop(mo, "use_smooth_shade")

                        split = box.split()

                        col = split.column()
                        col.label(text="Selected Vertices:")

                        sub = col.column(align=True)
                        sub.operator("object.skin_root_mark", text="Mark Root")
                        sub.operator("object.skin_radii_equalize", text="Equalize Radii")
                        sub.operator("object.skin_loose_mark_clear", text="Mark Loose").action = 'MARK'
                        sub.operator("object.skin_loose_mark_clear", text="Clear Loose").action = 'CLEAR'

                        col = split.column()
                        col.label(text="Symmetry Axes:")
                        col.prop(mo, "use_x_symmetry")
                        col.prop(mo, "use_y_symmetry")
                        col.prop(mo, "use_z_symmetry")

                        box.separator()


import torch
from torch.autograd import Variable
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from .base import Base

class LSTM(Base):
    def __init__(
        self, num_input_dims=41, num_lstm_units=100, num_lstm_layers=2, num_out_dims=4
    ):
        super(LSTM, self).__init__()
        self.num_input_dims = num_input_dims
        self.num_lstm_units = num_lstm_units
        self.num_lstm_layers = num_lstm_layers
        self.num_out_dims = num_out_dims
        # build actual NN
        self.__build_model()

    def __build_model(self):
        # self.brnn = nn.LSTM(
        #     input_size=input_dims,
        #     hidden_size=lstm_dims,
        #     num_lstm_layers=2,
        #     bias=True,
        #     batch_first=True,
        #     bidirectional=True,
        # )
        self.lstm = torch.nn.LSTM(
            input_size=self.num_input_dims,
            hidden_size=self.num_lstm_units,
            num_layers=self.num_lstm_layers,
            batch_first=True,
        )
        self.fc1 = torch.nn.Linear(
            in_features=self.num_lstm_units, out_features=self.num_out_dims
        )
        self.act1 = torch.nn.Tanh()
        # self.fc2 = nn.Linear(in_features=512, out_features=256)
        # self.act2 = nn.Tanh()
        # self.fc3 = nn.Linear(in_features=256, out_features=self.num_out_dims)
        # self.act3 = nn.Tanh()

    def init_hidden(self, batch_size):
        # the weights are of the form (num_lstm_layers, batch_size, num_lstm_units)
        hidden_a = torch.randn(self.num_lstm_layers, batch_size, self.num_lstm_units)
        hidden_b = torch.randn(self.num_lstm_layers, batch_size, self.num_lstm_units)

        hidden_a = Variable(hidden_a)
        hidden_b = Variable(hidden_b)

        return (hidden_a, hidden_b)

    def forward(self, input, lengths):
        self.hidden = self.init_hidden(len(lengths))
        # [Batch, 41, Max_length] -> [Batch, Max_length, 41]
        output = input.transpose(1, 2)

        # [Batch, Max_length, embedding_dim] -> [Batch, Max_length, num_lstm_units]
        # pack_padded_sequence so that padded items in the sequence won't be shown to the LSTM
        output = pack_padded_sequence(output, lengths, batch_first=True)
        # now run through LSTM
        output, self.hidden = self.lstm(output, self.hidden)

        # undo the packing operation
        output, _ = pad_packed_sequence(output, batch_first=True)

        # Project to target space
        # [Batch, Max_length, num_lstm_units] -> [Batch * Max_length, num_lstm_units]
        output = output.contiguous().view(-1, self.num_lstm_units)

        # Run through linear and activation layers
        output = self.fc1(output)
        output = self.act1(output)

        # [Batch * Max_length, num_lstm_units] -> [Batch, num_out_dims, Max_length]
        output = output.view(-1, lengths[0], self.num_out_dims)
        output = output.transpose(1, 2)

        return output


# 散点图1
from pyecharts import Scatter
v1 = [10,20,30,40,50,60]
v2 = [10,20,30,40,50,60]

scatter =Scatter("散点图示例")
scatter.add("A",v1,v2)
scatter.add("B",v1[::-1],v2) #v1[::-1] 倒序

scatter.render("scatter01.html")

# 散点图2
v1 = [10,20,30,40,50,60]
v2 = [10,20,30,40,50,60]

scatter =Scatter("散点图示例")
scatter.add("A",v1,v2)
scatter.add("B",v1[::-1],v2,
is_visualmap =True,visual_type ="size",
visual_range_size=[20,80])#散点可见

scatter.render("scatter02.html")


from test_loader.sentryDataset import *
from test_loader.rgbdDataset import *
from test_loader.rgbDataset import *
from test_loader.dataset import FrameDataset
from test_loader.visualizer import Viualizer
import torch
import argparse

def main(args):
    if args.seed is not None:
        np.random.seed(args.seed)
        torch.manual_seed(args.seed)
        torch.backends.cudnn.benchmark = True
    else:
        torch.backends.cudnn.benchmark = True

    dataset = args.dataset
    dataroot = args.root

    if dataset == "sentry":
        base = sentryDataset(os.path.join(dataroot, dataset), worldgrid_shape=[449, 800])
        train_set =  FrameDataset(base, grid_reduce=4, img_reduce=4, train_ratio=args.train_ratio, train=True)
        test_set =  FrameDataset(base, grid_reduce=4, img_reduce=4, train_ratio=args.train_ratio, train=False)
    if dataset == "rgb" or "rgbd":
        base = rgbDataset(os.path.join(dataroot, dataset))
        train_set = FrameDataset(base, train_ratio=args.train_ratio, train=True)
        test_set = FrameDataset(base, train_ratio=args.train_ratio, train=False)
    if dataset == "rgbd":
        base = rgbdDataset(os.path.join(dataroot, dataset))
        train_set = FrameDataset(base, train_ratio=args.train_ratio, train=True)
        test_set = FrameDataset(base, train_ratio=args.train_ratio, train=False)

    # normalize = T.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
    #
    # train_trans = T.Compose([T.ToTensor(), normalize])
    # test_trans = T.Compose([T.ToTensor(), normalize])

    train_loader = torch.utils.data.DataLoader(train_set, batch_size=args.batch_size, shuffle=True,num_workers=args.num_workers, pin_memory=True, drop_last=True)
    test_loader = torch.utils.data.DataLoader(test_set, batch_size=args.batch_size, shuffle=True,num_workers=args.num_workers, pin_memory=True, drop_last=True)

    for batch_idx, data in enumerate(train_loader):
        imgs, depth = data
        break

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Dataloader API')
    parser.add_argument('-d', '--dataset', type=str, default='rgbd', choices=['sentry', 'rgb', 'rgbd'])
    parser.add_argument('-p', '--root', type=str, default="/home/dzc/Data/3in1")
    parser.add_argument('-s', '--seed', type=int, default=7)
    parser.add_argument('-t', '--train_ratio', type=int, default=0.01)
    parser.add_argument('-b', '--batch_size', type=int, default=1)
    parser.add_argument('-w', '--num_workers', type=int, default=8)
    args = parser.parse_args()
    # main(args)

    vis = Viualizer("/home/dzc/Data/3in1", "sentry")
    vis.visualize(10)
    pass


import json
import numpy as np

import cv2
import os
from nltk.metrics.distance import jaccard_distance
import concurrent.futures
# construc

import datetime
import re

from flask import render_template
import os
from flask import (Blueprint,
                   render_template,
                   redirect, url_for)

from flask import (Flask,
                   request,
                   redirect,
                   session,
                   send_file)

import pytesseract
import pymysql
from transformers import (
    TrOCRProcessor,
    VisionEncoderDecoderModel,
)
# import requests
from PIL import Image
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")
# Path of your tesseract executable
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files (x86)\Tesseract-OCR\tesseract.exe'
app = Flask(__name__, template_folder='template')

#------------------------------------------------------------------#

def tessaract():
    cheque= cv2.imread("static/result-img/Cheque No.jpg")
    account = cv2.imread("static/result-img/Account Holder Name.jpg")

    iban = cv2.imread("static/result-img/IBAN.jpg")
    logo = cv2.imread("static/result-img/logo.jpg")

    #convert the image to gray scale
    config = ('-l eng --oem 3 --psm 11')
    if cheque is not None:
        cheque_gray = cv2.cvtColor(cheque, cv2.COLOR_BGR2GRAY)
        cheque_text = pytesseract.image_to_string(cheque_gray, config=config)
    else:
        cheque_text= ""
    if account is not None:
        account_gray = cv2.cvtColor(account, cv2.COLOR_BGR2GRAY)
        account_text = pytesseract.image_to_string(account_gray, config=config)
    else:
        account_text= ""
    # amount_gray = cv2.cvtColor(amount, cv2.COLOR_BGR2GRAY)
    # date_gray = cv2.cvtColor(date, cv2.COLOR_BGR2GRAY)
    if iban is not None:
        iban_gray = cv2.cvtColor(iban, cv2.COLOR_BGR2GRAY)
        iban_text = pytesseract.image_to_string(iban_gray, config=config)
    else:
        iban_text= ""
    if logo is not None:
        logo_gray = cv2.cvtColor(logo, cv2.COLOR_BGR2GRAY)
        logo_text = pytesseract.image_to_string(logo_gray, config=config)
        #only take alphabets from logo_text
        logo_text = re.sub('[^A-Za-z]+', '', logo_text)
    else:
        logo_text= ""

    cheque_text = re.sub('[^0-9]', '', cheque_text)
    with open('sample.txt', 'r') as f:
        bank_name =f.read().split()
    for i in bank_name:
        bank= 1 - jaccard_distance(set(logo_text), set(i))
        print(bank)
        if bank > 0.3:
            logo_text = i
            print(bank)
            print(logo_text)
    return cheque_text, account_text, iban_text, logo_text

#------------------------------------------------------------------#

def pay():
    img_1 = Image.open("static/result-img/Pay.jpg").convert("RGB")
    pixel_values_1 = processor(img_1, return_tensors="pt").pixel_values
    generated_ids_1 = model.generate(pixel_values_1)
    generated_text_1 = processor.batch_decode(generated_ids_1, skip_special_tokens=True)[0]
    return generated_text_1

#------------------------------------------------------------------#

def date():
    img_2 = Image.open("static/result-img/date.jpg").convert("RGB")
    pixel_values_2 = processor(img_2, return_tensors="pt").pixel_values
    generated_ids_2 = model.generate(pixel_values_2)
    generated_text_2 = processor.batch_decode(generated_ids_2, skip_special_tokens=True)[0]
    #only digit will be extracted from the date
    date_text = re.sub('[^0-9]', '', generated_text_2)
    #spilit the date into day, month and year
    day = date_text[0:2]
    month = date_text[2:4]
    year = date_text[4:8]
    #convert the date into dd/mm/yyyy format
    date_text = day + "-" + month + "-" + year
    return date_text

#------------------------------------------------------------------#

def amount():
    img_3= Image.open("static/result-img/Amount.jpg").convert("RGB")
    pixel_values_3 = processor(img_3, return_tensors="pt").pixel_values
    generated_ids_3 = model.generate(pixel_values_3)
    generated_text_3 = processor.batch_decode(generated_ids_3, skip_special_tokens=True)[0]
    #only digit will be extracted from the amount
    amount_text = re.sub('[^0-9]', '', generated_text_3)
    return amount_text

#------------------------------------------------------------------#

@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template('index.html')

#------------------------------------------------------------------#

@app.route('/text', methods=['GET', 'POST'])
def text():
    if request.method=='POST':
        conn = pymysql.connect(db='cheque', user='root', passwd='', host='localhost')
        cur = conn.cursor()

        ct = str("static/result/")+str("Signature")+str(datetime.datetime.now())+str(".jpg")
        account_name = request.form['account_name']
        amount = request.form['amount']
        cheque_no = request.form['cheque_no']
        date = request.form['date']
        iban = request.form['iban']
        bank_name = request.form['bank_name']
        pay= request.form['pay']
        # print(account_name,amount,cheque_no,date,iban,bank_name,pay)
        cur.execute("INSERT INTO cheque_classfication (account_name,amount,cheque_no,date,iban,bank_name,pay,signature) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",(account_name,amount,cheque_no,date,iban,bank_name,pay,ct))
        conn.commit()
        cur.close()
        conn.close()

    return render_template('text.html')

#------------------------------------------------------------------#

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    # call the main function from file.py
    if request.method == 'POST':
        f = request.files['file1']
        #save the file with different name
        #delete all the file in the folder
        for filename in os.listdir('static/upload-img'):
            os.remove('static/upload-img/'+filename)
        for filename in os.listdir('static/result-img'):
            os.remove('static/result-img/'+filename)
        f.save(os.path.join('static/upload-img/', f.filename))
        # return render_template('index.html', filename=f.filename)
        # pass the image to the main function
        labelsPath = "yolo/obj.names"
        LABELS = open(labelsPath).read().strip().split("\n")
        # initialize a list of colors to represent each possible class label
        np.random.seed(42)
        COLORS = np.random.randint(0, 255, size=(len(LABELS), 3),
            dtype="uint8")

        weightsPath ="yolo/yolov4-custom_best.weights"
        configPath = "yolo/yolov4-custom.cfg"

        net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)
        ln = net.getLayerNames()
        ln = [ln[i - 1] for i in net.getUnconnectedOutLayers()]

        im=[]
        # read the image
        frame = cv2.imread("static/upload-img/"+f.filename)

        Num = 0

        (H, W) = frame.shape[:2]

        blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416), swapRB=True)
        net.setInput(blob)
        layerOutputs = net.forward(ln)
        boxes = []
        confidences = []
        classIDs = []
        confidence_threshold = 0.5
        overlapping_threshold = 0.6

        for output in layerOutputs:
            for detection in output:
                scores = detection[5:]
                classID = np.argmax(scores)
                confidence = scores[classID]
                if confidence > confidence_threshold:
                    # Scale the bboxes back to the original image size
                    box = detection[0:4] * np.array([W, H, W, H])
                    (centerX, centerY, width, height) = box.astype("int")
                    x = int(centerX - (width / 2))
                    y = int(centerY - (height / 2))
                    boxes.append([x, y, int(width), int(height)])
                    confidences.append(float(confidence))
                    classIDs.append(classID)

        # Remove overlapping bounding boxes and boundig boxes
        bboxes = cv2.dnn.NMSBoxes(
            boxes, confidences, confidence_threshold, overlapping_threshold)
        if len(bboxes) > 0:
            for i in bboxes.flatten():
                box = boxes[i]
                x = box[0]
                y = box[1]
                w = box[2]
                h = box[3]

                crop_image = frame[y:y+h, x:x+w]

                try:
                    if LABELS[classIDs[i]] == "A-C name":

                        cv2.imwrite("static/result-img/"+"Account Holder name"+".jpg", crop_image)
                        # continue
                    elif LABELS[classIDs[i]] == "Amount":
                        #convert the image to gray scale
                        # crop_image = cv2.cvtColor(crop_image, cv2.COLOR_BGR2GRAY)
                        cv2.imwrite("static/result-img/"+"Amount"+".jpg", crop_image)
                        # continue
                    elif LABELS[classIDs[i]] == "Logo":
                        cv2.imwrite("static/result-img/"+"logo"+".jpg", crop_image)
                        # continue
                    elif LABELS[classIDs[i]] == "Cheque No":
                        cv2.imwrite("static/result-img/"+"Cheque No"+".jpg", crop_image)
                        # continue
                    elif LABELS[classIDs[i]] == "Date":
                        # crop_image = cv2.cvtColor(crop_image, cv2.COLOR_BGR2GRAY)
                        cv2.imwrite("static/result-img/"+"Date"+".jpg", crop_image)
                        # continue
                    elif LABELS[classIDs[i]] == "IBAN":
                        cv2.imwrite("static/result-img/"+"IBAN"+".jpg", crop_image)
                        # continue
                    elif LABELS[classIDs[i]] == "Signature":
                        ct = datetime.datetime.now()
                        cv2.imwrite("static/result-img/"+"Signature"+".jpg", crop_image)

                        # continue
                    elif LABELS[classIDs[i]] == "Pay":
                        crop_image = cv2.cvtColor(crop_image, cv2.COLOR_BGR2GRAY)
                        cv2.imwrite("static/result-img/"+"Pay"+".jpg",crop_image)
                    elif (LABELS[classIDs[i]]) == "MICR":
                        cv2.imwrite("static/result-img/"+"MICR"+".jpg",frame[y:y+h, x:x+w])
                    #     # continue
                        # continue

                    else:
                        continue
                except:
                    print("Sorry! NO FRAME ACCESSED!")

                Num = Num + 1
        # extraction()

        cheque= cv2.imread("static/result-img/Cheque No.jpg")
        account = cv2.imread("static/result-img/Account Holder Name.jpg")
        # amount = cv2.imread("static/result-img/Amount.jpg")
        # date = cv2.imread("static/result-img/Date.jpg")
        iban = cv2.imread("static/result-img/IBAN.jpg")
        logo = cv2.imread("static/result-img/logo.jpg")
        # pay= cv2.imread("static/result-img/Pay.jpg")
        #preprocess the image
        #convert the image to gray scale
        config = ('-l eng --oem 3 --psm 11')
        if cheque is not None:
            cheque_gray = cv2.cvtColor(cheque, cv2.COLOR_BGR2GRAY)
            cheque_text = pytesseract.image_to_string(cheque_gray, config=config)
        else:
            cheque_text= ""
        if account is not None:
            account_gray = cv2.cvtColor(account, cv2.COLOR_BGR2GRAY)
            account_text = pytesseract.image_to_string(account_gray, config=config)
        else:
            account_text= ""
        # amount_gray = cv2.cvtColor(amount, cv2.COLOR_BGR2GRAY)
        # date_gray = cv2.cvtColor(date, cv2.COLOR_BGR2GRAY)
        if iban is not None:
            iban_gray = cv2.cvtColor(iban, cv2.COLOR_BGR2GRAY)
            iban_text = pytesseract.image_to_string(iban_gray, config=config)
        else:
            iban_text= ""
        if logo is not None:
            logo_gray = cv2.cvtColor(logo, cv2.COLOR_BGR2GRAY)
            logo_text = pytesseract.image_to_string(logo_gray, config=config)
            #only take alphabets from logo_text
            logo_text = re.sub('[^A-Za-z]+', '', logo_text)
        else:
            logo_text= ""

        cheque_text = re.sub('[^0-9]', '', cheque_text)
        with open('sample.txt', 'r') as f:
            bank_name =f.read().split()
        for i in bank_name:
            bank= 1 - jaccard_distance(set(logo_text), set(i))
            print(bank)
            if bank > 0.3:
                logo_text = i
                print(bank)
                print(logo_text)

        #run the extraction function on a thread
        with concurrent.futures.ThreadPoolExecutor() as executor:
                future = executor.submit(date)
                future_1 = executor.submit(pay)
                future_2 = executor.submit(amount)
                future_3 = executor.submit(tessaract)
                return_value = future_3.result()
                cheque_text, account_text, iban_text, logo_text=return_value
                date_text = future.result()
                pay_text = future_1.result()
                amount_text = future_2.result()

        return render_template('text.html',cheque_text=cheque_text, account_text=account_text, amount_text=amount_text, date_text=date_text, iban_text=iban_text, logo_text=logo_text, pay_text=pay_text)

#------------------------------------------------------------------#

if __name__ == '__main__':

    app.run(debug=True)


from flask import Blueprint
from flask import request, jsonify

import client
from apiauth import require_apikey

personsroute = Blueprint('persons', __name__)

persons = client.db.collection('persons')

@personsroute.route('/persons', methods=['POST'])
@require_apikey
def createperson():

	try:
		id = request.json['id']
		persons.document(id).set(request.json)
		return jsonify({"success": True}), 200
	except Exception as e:
		return f"An Error Occurred: {e}"

@personsroute.route('/persons', methods=['GET'])
@require_apikey
def readperson():

	try:
		all_persons = [doc.to_dict() for doc in persons.stream()]
		jsonresult = jsonify({"persons" : all_persons}), 200
		return jsonresult
	except Exception as e:
		return f"An Error Occurred: {e}"

@personsroute.route('/persons/<id>', methods=['GET'])
@require_apikey
def readoneperson(id):

	try:
		person = persons.document(id).get()
		return jsonify(person.to_dict()), 200
	except Exception as e:
		return f"An Error Occurred: {e}"

@personsroute.route('/persons/<id>', methods=['PUT'])
@require_apikey
def updateperson(id):

	try:
		id = request.json['id']
		persons.document(id).update(request.json)
		return jsonify({"success": True}), 200
	except Exception as e:
		return f"An Error Occurred: {e}"

@personsroute.route('/persons/<id>', methods=['DELETE'])
@require_apikey
def deleteperson(id):

	try:
		persons.document(id).delete()
		return jsonify({"success": True}), 200
	except Exception as e:
		return f"An Error Occurred: {e}"


# coding: utf-8
"""
Base classes and helper functions of various types that are used with different parsers.
"""
# region imports

from bs4 import BeautifulSoup
from bs4.element import ResultSet, Tag
from glob import glob
from kwhelp.decorator import DecFuncEnum, RequireArgs, RuleCheckAllKw
from kwhelp import rules
from pathlib import Path
from typing import List,Union
from .common.constants import URL_SPLIT as URL_SPLIT, APP_ROOT as APP_ROOT
from .common.config import APP_CONFIG as APP_CONFIG
from .common.util import Util as Util, str_clean
from .web.response_obj import ResponseObj
# endregion imports

# region Writer/parser base
class WriteBase(object):
    def __init__(self, **kwargs):
        pass

    def _mkdirp(self, dest_dir):
        Util.mkdirp(dest_dir=dest_dir)

    def _get_project_path(self) -> Path:
        return Path(__file__).parent.parent

    def _get_template_path(self) -> Path:
        project_path = self._get_project_path()
        return project_path.joinpath('template')

    def _get_template_files(self) -> List[str]:
        p = self._get_template_path()
        pattern = str(p) + '/_*.py'
        files = glob(pattern, recursive=False)
        return files

class ParserBase(object):
    @RequireArgs('url', ftype=DecFuncEnum.METHOD)
    @RuleCheckAllKw(arg_info={"url": 0, "sort": 1, "cache": 1, "replace_dual_colon": 1},
                    rules=[rules.RuleStrNotNullEmptyWs, rules.RuleBool],
                    ftype=DecFuncEnum.METHOD)
    def __init__(self, **kwargs):
        self._allow_cache: bool = kwargs.get('cache', True)
        self._indent = '    '
        self._url = kwargs.get('url', '')
        self._raw = ''
        self._sort = kwargs.get('sort', True)
        self._replace_dual_colon = kwargs.get('replace_dual_colon', True)
        self._title_full = None
        self._response_obj = None

    # region internal Non specific methods
    def _get_number(self, input: str) -> Union[str, int, float]:
        if not input:
            return ''
        try:
            return int(input)
        except ValueError:
            pass
        try:
            return int(input, 16)
        except ValueError:
            pass
        try:
            return float(input)
        except ValueError:
            pass
        return input
    # endregion internal Non specific methods

    # region request
    def get_request_text(self, url: str) -> str:
        if self._response_obj is None:
            if self.allow_cache:
                self._response_obj = ResponseObj(url=url)
            else:
                self._response_obj = ResponseObj(url=url, cache_seconds=0)
        return self._response_obj.raw_html

    # endregion request

    # region raw html

    def get_raw_html(self) -> str:
        if not self._url:
            return ''
        if not self._raw:
            self._raw = self.get_request_text(self.url)
        return self._raw

    # endregion raw html

    # region Info
    def _get_full_name(self, soup: BeautifulSoup) -> str:
        """
        Gets full name from nav bar

        Returns:
            str: such as com.sun.star.awt.AdjustmentEvent
        """
        if self._title_full is None:
            nav = soup.find('div', id='nav-path')
            els = nav.find_all('a', class_='el')
            text = ''
            for i, el in enumerate(els):
                if i > 0:
                    text += '.'
                text += el.text.strip()
            # text = nav.text.replace('\n', '.').strip()
            self._title_full = Util.get_clean_classname(text)
        return self._title_full

    def _get_name(self, soup: BeautifulSoup):
        full = self._get_full_name(soup=soup)
        parts = full.split('.')
        return parts[len(parts) - 1]

    def _get_desc(self, soup: BeautifulSoup) -> List[str]:
        lines = []
        contents = soup.find('div', class_='contents')
        if not contents:
            return lines
        block = contents.find('div', class_='textblock')
        if not block:
            return lines
        soup_lines: ResultSet = block.find_all('p')
        if not soup_lines:
            return lines
        for i, ln in enumerate(soup_lines):
            s = ln.text.strip().replace('::', '.')
            if i > 0:
                lines.append("")
            lines.append(s)
        since = self._get_since(block=block)
        if len(since) > 0:
            lines.append('')
            lines.extend(since)
        # result = "\n".join(lines)
        return lines

    def _get_since(self, block: Tag) -> List[str]:
        result = []
        since = block.find('dl', class_='section since')
        if since:
            s = since.find('dd').text.strip()
            result.append("**Since**")
            result.append("")
            result.append(self._indent + s)
        return result
    # endregion Info

    # region Tidy
    def _clean_str(self, input: str) -> str:
        """
        Cleans and encodes string for template replacemnt
        """
        return str_clean(input=input, replace_dual=self._replace_dual_colon)

    # endregion Tidy

    # region Data
    def _get_memitems(self, soup: BeautifulSoup) -> ResultSet:
        return soup.find_all('div', class_='memitem')

    # endregion Data

    # region util
    def camel_to_snake(self, name: str) -> str:
        """
        Converts Camel case to snake clase

        Args:
            name (str): Camel name

        Returns:
            str: snake case
        """
        return Util.camel_to_snake(name)

    # endregion util

    # region Properties

    @property
    def sort(self) -> bool:
        """Specifies sort

            :getter: Gets sort value.
            :setter: Sets sort value.
        """
        return self._sort

    @sort.setter
    def sort(self, value: bool):
        self._sort = value

    @property
    def url(self) -> str:
        """Specifies url

            :getter: Gets url value.
            :setter: Sets url value.
        """
        return self._url

    @url.setter
    def url(self, value: str):
        self._url = value

    @property
    def allow_cache(self) -> bool:
        """Specifies allow_cache

            :getter: Gets allow_cache value.
            :setter: Sets allow_cache value.
        """
        return self._allow_cache

    @allow_cache.setter
    def allow_cache(self, value: bool):
        self._allow_cache = value
    # endregion Properties

# endregion Writer/parser base


import json

from flask import Blueprint, request, jsonify
import requests as r

lines_app = Blueprint('lines', __name__)
LIST_URL = 'http://127.0.0.1:8000/api/lines/'
DETAIL_URL = LIST_URL + '{}/'

@lines_app.route('', methods=['GET'])
def list():
    req = r.get(LIST_URL, headers=request.headers)
    data = req.json()
    return jsonify(data)

# @lines_app.route('/<int:line_id>/', methods=['GET'])
@lines_app.route('/<int:line_id>', methods=['GET'])
def detail(line_id):
    req = r.get(DETAIL_URL.format(line_id), headers={'authorization': request.headers['authorization']})
    data = req.json()
    return jsonify(data)

@lines_app.route('/', methods=['POST'])
def new_line():
    data = request.json
    req = r.post(LIST_URL, data=json.dumps(data), headers={'content-type': 'application/json', 'authorization': request.headers['authorization']})
    data = req.json()
    return jsonify(data), 201

# @lines_app.route('/<int:line_id>/', methods=['PUT'])
@lines_app.route('/<int:line_id>', methods=['PUT'])
def update_line(line_id):
    data = request.json
    data.pop('id')
    data.pop('calls_to_center')
    data.pop('date_joined')
    req = r.get(DETAIL_URL.format(line_id), headers={'authorization': request.headers['authorization']})
    db_line = req.json()
    db_line.update(data)
    req = r.put(DETAIL_URL.format(line_id), data=json.dumps(db_line), headers={'content-type': 'application/json', 'authorization': request.headers['authorization']})
    data = req.json()
    return jsonify(data)

# @lines_app.route('/<int:line_id>/', methods=['DELETE'])
@lines_app.route('/<int:line_id>', methods=['DELETE'])
def delete_line(line_id):
    r.delete(DETAIL_URL.format(line_id), headers=request.headers)
    return '', 204


import io
import sys

_INPUT = """\
6
AtCoder
Aa
atcoder
Perfect
"""

sys.stdin = io.StringIO(_INPUT)
case_no=int(input())
for __ in range(case_no):
  S=input()
  c,s=0,0
  for i in range(len(S)):
    if S[i].upper()==S[i]:
      c=1
    if S[i].lower()==S[i]:
      s=1
  if c==1 and s==1 and len(set(S))==len(S):
    print('Yes')
  else: print('No')


from secrets import randbelow
from time import time
import numpy as np
from matplotlib import pyplot as plt
import cv2

# ======================== INPUT IMAGE ========================
def input_img(image_name: str):
    # Retorna as dimencoes da imagem e um objeto que é a sua imagem(img)
    image = cv2.imread(image_name)
    print("Dimensões da imagem: " + str(image.shape))
    altura, largura, canais = image.shape
    print(f'Largura: {largura}')
    print(f'Altura: {altura}')
    print(f'Canais de cores: {canais}')
    return image, altura, largura, canais

# ======================== SHOW IMAGE ========================
def show_image(image):
    # Mostra Uma imagem
    my_dpi = 96
    plt.figure(figsize=(15/1087*1200, 15/1087*1200), dpi=my_dpi, frameon = False)
    plt.axis('off')
    plt.imshow(image)
    #plt.savefig('ada_file.jpg', format="jpg", dpi=my_dpi, bbox_inches='tight', pad_inches=0)
    plt.show()

# ======================== IMAGE BUILDER ========================
def image_builder(altura: int, largura: int, canais: int, intarray: list):
    # Retorna uma imagem com o conteudo intarray
    return np.ndarray(shape=(altura, largura, canais), dtype=int, buffer=np.array(list(intarray)))

# ======================== CRIPTOGRAFAR IMAGEM ========================
def criptografar(image, altura: int, largura: int, canais: int, operacao: str):
    # ^ XOR
    # & AND
    # | OR
    t = time()
    op = {
        'AND': lambda a, b: a & b,
        'OR': lambda a, b: a | b,
        'XOR': lambda a, b: a ^ b
    }
    ENC = []
    PWD = []
    for y in range(0, altura):
        for x in range(0, largura):
            for z in range(canais):
                mini_chave = randbelow(256)  # 8 bits -> 2**8 = 256
                PWD.append(mini_chave)
                ENC.append(op[operacao](int(image[y][x][z]), mini_chave))

    print('Tempo de criptografia:', time() - t, 'sec')

    return ENC


from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path
import os
from flask_login import LoginManager
#from celery import Celery

db = SQLAlchemy()
DB_NAME = "database.db"
ALLOWED_EXTENSIONS = {'fastq'}

def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'hjshjhdjahdfgdsfdss kjshkjdhjs'
    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
    UPLOAD_FOLDER  ='./uploads'
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
    db.init_app(app)

    #app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
    #app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'
    #celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
    #celery.conf.update(app.config)

    from .views import views
    from .auth import auth

    app.register_blueprint(views, url_prefix='/')
    app.register_blueprint(auth, url_prefix='/')

    from .models import User, Upload

    with app.app_context():
        db.create_all()

    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(id):
        return User.query.get(int(id))

    return app

def create_database(app):
    if not path.exists('website/' + DB_NAME):
        db.create_all(app=app)
        print('База данных создана')


#Windows
# #! python3
#Mac
  #! /usr/bin/env python3
#Linux
# #! /usr/bin/python3

# backupToZip.py - フォルダ全体を連番付きZIPファイルにコピーする
# Usage:
# python backupToZip.py

import zipfile, os

def backup_to_zip(folder):
#	print('Input folder : ' + folder)
	# フォルダ全体をZIPファイルにバックアップする
	folder = os.path.abspath(folder)	# folderを絶対パスにする

#	print('Absolute folder path : ' + folder)
#	print('basename : ' + os.path.basename(folder))
	# 既存のファイル名からファイル名の連番を決める
	number = 1
	while True:
		zip_filename = os.path.basename(folder) + '_' + str(number) + '.zip'
		if not os.path.exists(zip_filename):
			break
		number = number + 1

	# ZIPファイルを作成する
	print('Creating {}...'.format(zip_filename))
	backup_zip = zipfile.ZipFile(zip_filename, 'w')

	# フォルダのツリーを渡り歩いてその中のファイルを圧縮する
	# os.walkを使えば、そのフォルダのファイルリストが入手できる（以下では、filenames）
	for foldername, subfolders, filenames in os.walk(folder):
		print('Adding files in {}...'.format(foldername))
		# 現在のフォルダをZIPファイルに追加する
		backup_zip.write(foldername)
		# 現在のフォルダの中の全ファイルをZIPファイルに追加する
		for filename in filenames:
			new_base = os.path.basename(folder) + '_'
			if filename.startswith(new_base) and filename.endswith('.zip'):
				continue		# バックアップ用ZIPファイル（foldername_**.zip）はバックアップしない
			backup_zip.write(os.path.join(foldername, filename))
	backup_zip.close()
	print('Done')

cur_dir = os.getcwd()
backup_to_zip(cur_dir)


import sys, argparse
import youtube_dl

# Coded by Suleiman Alothman @sulealothman

parser = argparse.ArgumentParser(
	description="Script name : Download-Youtube, Ver. : 0.1, Author : SuleAlOthman",
	usage=""" Example #1 : python3 download-youtube.py -l https://www.youtube.com/watch?v=XXXXXXXXXXX \r\n
	Example #2 : python3 download-youtube.py -f links.txt \r\n
	Example #3 : python3 download-youtube.py -f links.txt -e mp4 \r\n""")
parser.add_argument('-f', '--file',type=str,help='Text file for links')
parser.add_argument('-l', '--link',type=str,help='Video Url')
parser.add_argument('-e', '--extension',nargs='?',default="mp3",type=str,help='extension file : mp3 or mp4')
args = parser.parse_args()

def youtubeDownload(url,ext="mp3"):
	if ext == "mp3":
		ydl_opts = {
			'format': 'bestaudio/best',
			'postprocessors': [{
				'key' : 'FFmpegExtractAudio',
				'preferredcodec': 'mp3',
				'preferredquality': '192',
				}],
		}
	else:
		ydl_opts = {
			'format' : 'bestvideo',
			'postprocessors' : [{
				'key' : 'FFmpegVideoConvertor',
				'preferedformat' : 'mp4',
				}]
		}

	with youtube_dl.YoutubeDL(ydl_opts) as ydl:
		ydl.download([url])

if __name__ == "__main__":

	if(args.file != None):
		path = args.file
		try:
			linksFile = open(path, "r")
			for link in linksFile:
				try:
					youtubeDownload(link, args.extension.strip())
				except:
					print(link + " : is incorrupt")
		except:
			print("Not found the file")
		print("\r\n- #   Finished downloading ..")
		sys.exit()
	elif(args.link != None):
		url = args.link
		try:
			youtubeDownload(url, args.extension.strip())
		except:
			print(url + " incurrept link")
	else:
		url = input("Enter youtube url : ")
		try:
			youtubeDownload(url, args.extension.strip())
		except:
			print(url + "incurrept link")

print("\r\n- #   Finished downloading ..")


import logging
import os

import numpy as np
import tensorflow as tf
# pylint: disable=E0611,E0401
import tensorflow.keras.backend as K
# pylint: disable=E0611,E0401
from tensorflow.keras import layers, regularizers
# pylint: disable=E0611,E0401
from tensorflow.keras.layers import (
    BatchNormalization,
    Conv2D,
    Dense,
    Dropout,
    Input,
    Lambda,
    Reshape,
)
# pylint: disable=E0611,E0401
from tensorflow.keras.models import Model
# pylint: disable=E0611,E0401
from tensorflow.keras.optimizers import Adam

from deep_speaker.constants import NUM_FBANKS, SAMPLE_RATE, NUM_FRAMES
from deep_speaker.triplet_loss import deep_speaker_loss

logger = logging.getLogger(__name__)

@tf.function
def tf_normalize(data, ndims, eps=0, adjusted=False):
    data = tf.convert_to_tensor(data, name='data')

    reduce_dims = [-i - 1 for i in range(ndims)]
    # pylint: disable=E1123,E1120
    data = tf.cast(data, dtype=tf.dtypes.float32)
    data_num = tf.reduce_prod(data.shape[-ndims:])
    data_mean = tf.reduce_mean(data, axis=reduce_dims, keepdims=True)

    # Apply a minimum normalization that protects us against uniform images.
    stddev = tf.math.reduce_std(data, axis=reduce_dims, keepdims=True)
    adjusted_stddev = stddev
    if adjusted:
        min_stddev = tf.math.rsqrt(tf.cast(data_num, tf.dtypes.float32))
        eps = tf.maximum(eps, min_stddev)
    if eps > 0:
        adjusted_stddev = tf.maximum(adjusted_stddev, eps)

    return (data - data_mean) / adjusted_stddev

@tf.function
def tf_fbank(samples):
    """
    Compute Mel-filterbank energy features from an audio signal.
    See python_speech_features.fbank
    """
    frame_length = int(0.025 * SAMPLE_RATE)
    frame_step = int(0.01 * SAMPLE_RATE)
    fft_length = 512
    fft_bins = fft_length // 2 + 1

    pre_emphasis = samples[:, 1:] - 0.97 * samples[:, :-1]

    # Original implementation from python_speech_features
    # frames = tf.expand_dims(sigproc.framesig(preemphasis[0], frame_length,
    # frame_step, winfunc=lambda x: np.ones((x,))), 0)
    # powspec = sigproc.powspec(frames, fft_length)

    # Tensorflow impl #1, using manually-split frames and rfft
    # spec = tf.abs(tf.signal.rfft(frames, [fft_length]))
    # powspec = tf.square(spec) / fft_length

    # Tensorflow impl #2, using stft to handle framing automatically
    # (There is a one-off mismatch on the number of frames on the resulting tensor, but I guess this is ok)
    spec = tf.abs(tf.signal.stft(pre_emphasis, frame_length, frame_step, fft_length, window_fn=tf.ones))
    powspec = tf.square(spec) / fft_length

    # Matrix to transform spectrum to mel-frequencies

    # Original implementation from python_speech_features
    # linear_to_mel_weight_matrix = get_filterbanks(NUM_FBANKS, fft_length,
    # SAMPLE_RATE, 0, SAMPLE_RATE/2).astype(np.float32).T

    linear_to_mel_weight_matrix = tf.signal.linear_to_mel_weight_matrix(
        num_mel_bins=NUM_FBANKS,
        num_spectrogram_bins=fft_bins,
        sample_rate=SAMPLE_RATE,
        lower_edge_hertz=0,
        upper_edge_hertz=SAMPLE_RATE / 2,
    )

    feat = tf.matmul(powspec, linear_to_mel_weight_matrix)
    # feat = tf.where(feat == 0, np.finfo(np.float32).eps, feat)
    return feat

class DeepSpeakerModel:

    # I thought it was 3 but maybe energy is added at a 4th dimension.
    # would be better to have 4 dimensions:
    # MFCC, DIFF(MFCC), DIFF(DIFF(MFCC)), ENERGIES (probably tiled across the frequency domain).
    # this seems to help match the parameter counts.
    def __init__(
            self,
            batch_input_shape=(None, NUM_FRAMES, NUM_FBANKS, 1),
            include_softmax=False,
            num_speakers_softmax=None,
            pcm_input=False
    ):
        if pcm_input:
            batch_input_shape = None
        self.include_softmax = include_softmax
        if self.include_softmax:
            assert num_speakers_softmax > 0
        self.clipped_relu_count = 0

        # http://cs231n.github.io/convolutional-networks/
        # conv weights
        # #params = ks * ks * nb_filters * num_channels_input

        # Conv128-s
        # 5*5*128*128/2+128
        # ks*ks*nb_filters*channels/strides+bias(=nb_filters)

        # take 100 ms -> 4 frames.
        # if signal is 3 seconds, then take 100ms per 100ms and average out this network.
        # 8*8 = 64 features.

        # used to share all the layers across the inputs

        # num_frames = K.shape() - do it dynamically after.

        if pcm_input:
            batch_input_shape = batch_input_shape or (None, None)  # Batch-size, num-samples
            inputs = Input(batch_shape=batch_input_shape, name='raw_inputs')
            x = inputs
            x = Lambda(tf_fbank)(x)
            x = Lambda(lambda x_: tf_normalize(x_, 1, 1e-12))(x)
            x = Lambda(lambda x_: tf.expand_dims(x_, axis=-1))(x)
        else:
            batch_input_shape = batch_input_shape or (None, None, NUM_FBANKS, 1)
            inputs = Input(batch_shape=batch_input_shape, name='input')
            x = inputs

        x = self.cnn_component(x)

        x = Reshape((-1, 2048))(x)
        # Temporal average layer. axis=1 is time.
        x = Lambda(lambda y: K.mean(y, axis=1), name='average')(x)
        if include_softmax:
            logger.info('Including a Dropout layer to reduce overfitting.')
            # used for softmax because the dataset we pre-train on might be too small. easy to overfit.
            x = Dropout(0.5)(x)
        x = Dense(512, name='affine')(x)
        if include_softmax:
            # Those weights are just when we train on softmax.
            x = Dense(num_speakers_softmax, activation='softmax')(x)
        else:
            # Does not contain any weights.
            x = Lambda(lambda y: K.l2_normalize(y, axis=1), name='ln')(x)
        self.m = Model(inputs, x, name='ResCNN')

    def keras_model(self):
        return self.m

    def get_weights(self):
        w = self.m.get_weights()
        if self.include_softmax:
            w.pop()  # last 2 are the W_softmax and b_softmax.
            w.pop()
        return w

    def clipped_relu(self, inputs):
        relu = Lambda(lambda y: K.minimum(K.maximum(y, 0), 20), name=f'clipped_relu_{self.clipped_relu_count}')(inputs)
        self.clipped_relu_count += 1
        return relu

    def identity_block(self, input_tensor, kernel_size, filters, stage, block):
        conv_name_base = f'res{stage}_{block}_branch'

        x = Conv2D(filters,
                   kernel_size=kernel_size,
                   strides=1,
                   activation=None,
                   padding='same',
                   kernel_initializer='glorot_uniform',
                   kernel_regularizer=regularizers.l2(l=0.0001),
                   name=conv_name_base + '_2a')(input_tensor)
        x = BatchNormalization(name=conv_name_base + '_2a_bn')(x)
        x = self.clipped_relu(x)

        x = Conv2D(
            filters,
            kernel_size=kernel_size,
            strides=1,
            activation=None,
            padding='same',
            kernel_initializer='glorot_uniform',
            kernel_regularizer=regularizers.l2(l=0.0001),
            name=conv_name_base + '_2b',
        )(x)
        x = BatchNormalization(name=conv_name_base + '_2b_bn')(x)

        x = self.clipped_relu(x)

        x = layers.add([x, input_tensor])
        x = self.clipped_relu(x)
        return x

    def conv_and_res_block(self, inp, filters, stage):
        conv_name = 'conv{}-s'.format(filters)
        # TODO: why kernel_regularizer?
        o = Conv2D(filters,
                   kernel_size=5,
                   strides=2,
                   activation=None,
                   padding='same',
                   kernel_initializer='glorot_uniform',
                   kernel_regularizer=regularizers.l2(l=0.0001), name=conv_name)(inp)
        o = BatchNormalization(name=conv_name + '_bn')(o)
        o = self.clipped_relu(o)
        for i in range(3):
            o = self.identity_block(o, kernel_size=3, filters=filters, stage=stage, block=i)
        return o

    def cnn_component(self, inp):
        x = self.conv_and_res_block(inp, 64, stage=1)
        x = self.conv_and_res_block(x, 128, stage=2)
        x = self.conv_and_res_block(x, 256, stage=3)
        x = self.conv_and_res_block(x, 512, stage=4)
        return x

    def set_weights(self, w):
        for layer, layer_w in zip(self.m.layers, w):
            layer.set_weights(layer_w)
            logger.info(f'Setting weights for [{layer.name}]...')

def main():
    # Looks correct to me.
    # I have 37K but paper reports 41K. which is not too far.
    dsm = DeepSpeakerModel()
    dsm.m.summary()

    # I suspect num frames to be 32.
    # Then fbank=64, then total would be 32*64 = 2048.
    # plot_model(dsm.m, to_file='model.png', dpi=300, show_shapes=True, expand_nested=True)

def _train():
    # x = np.random.uniform(size=(6, 32, 64, 4))  # 6 is multiple of 3.
    # y_softmax = np.random.uniform(size=(6, 100))
    # dsm = DeepSpeakerModel(batch_input_shape=(None, 32, 64, 4), include_softmax=True, num_speakers_softmax=100)
    # dsm.m.compile(optimizer=Adam(lr=0.01), loss='categorical_crossentropy')
    # print(dsm.m.predict(x).shape)
    # print(dsm.m.evaluate(x, y_softmax))
    # w = dsm.get_weights()
    dsm = DeepSpeakerModel(batch_input_shape=(None, 32, 64, 4), include_softmax=False)
    # dsm.m.set_weights(w)
    dsm.m.compile(optimizer=Adam(lr=0.01), loss=deep_speaker_loss)

    # it works!!!!!!!!!!!!!!!!!!!!
    # unit_batch_size = 20
    # anchor = np.ones(shape=(unit_batch_size, 32, 64, 4))
    # positive = np.array(anchor)
    # negative = np.ones(shape=(unit_batch_size, 32, 64, 4)) * (-1)
    # batch = np.vstack((anchor, positive, negative))
    # x = batch
    # y = np.zeros(shape=(len(batch), 512))  # not important.
    # print('Starting to fit...')
    # while True:
    #     print(dsm.m.train_on_batch(x, y))

    # should not work... and it does not work!
    unit_batch_size = 20
    negative = np.ones(shape=(unit_batch_size, 32, 64, 4)) * (-1)
    batch = np.vstack((negative, negative, negative))
    x = batch
    y = np.zeros(shape=(len(batch), 512))  # not important.
    print('Starting to fit...')
    while True:
        print(dsm.m.train_on_batch(x, y))

def _test_checkpoint_compatibility():
    dsm = DeepSpeakerModel(batch_input_shape=(None, 32, 64, 4), include_softmax=True, num_speakers_softmax=10)
    dsm.m.save_weights('test.h5')
    dsm = DeepSpeakerModel(batch_input_shape=(None, 32, 64, 4), include_softmax=False)
    dsm.m.load_weights('test.h5', by_name=True)
    os.remove('test.h5')

if __name__ == '__main__':
    _test_checkpoint_compatibility()


from settings import *
import random
import pygame
def invert(a):
    k = ''
    for i in range(len(a)):
        if a[i] == "1":
            k += "1"
        else:
            k += '0'
    return k
def transcript(a):
    k = ''
    for i in range(len(a)):
        if a[i] == "True":
            k += "1"
        else:
            k += "0"
    return k

def start_point_generate(n, m):
    return (0,0)

def finish_point_generate(start, n, m):
    #конец лабиринта"
    return n - 1 - start[0], m - 1 - start[1]
def transition_choice(x, y, rm):
    #Выбор пути"
    choice_list = []
    if x > 0:
        if not rm[x - 1][y]:
            choice_list.append((x - 1, y))
    if x < len(rm) - 1:
        if not rm[x + 1][y]:
            choice_list.append((x + 1, y))
    if y > 0:
        if not rm[x][y - 1]:
            choice_list.append((x, y - 1))
    if y < len(rm[0]) - 1:
        if not rm[x][y + 1]:
            choice_list.append((x, y + 1))
    if choice_list:
        nx, ny = random.choice(choice_list)
        if x == nx:
            if ny > y:
                tx, ty = x * 2, ny * 2 - 1
            else:
                tx, ty = x * 2, ny * 2 + 1
        else:
            if nx > x:
                tx, ty = nx * 2 - 1, y * 2
            else:
                tx, ty = nx * 2 + 1, y * 2
        return nx, ny, tx, ty
    else:
        return -1, -1, -1, -1

def create_labyrinth(n = 5, m = 5):
    "Генерация лабиринта"
    reach_matrix = []
    for i in range(n):  # создаём матрицу достижимости ячеек
        reach_matrix.append([])
        for j in range(m):
            reach_matrix[i].append(False)
    transition_matrix = []
    for i in range(n * 2 - 1):  # заполнение матрицы переходов
        transition_matrix.append([])
        for j in range(m * 2 - 1):
            if i % 2 == 0 and j % 2 == 0:
                transition_matrix[i].append(True)
            else:
                transition_matrix[i].append(False)
    start = start_point_generate(n, m)
    finish = finish_point_generate(start, n, m)
    list_transition = [start]
    x, y = start
    reach_matrix[x][y] = True
    x, y, tx, ty = transition_choice(x, y, reach_matrix)
    for i in range(1, m * n):
        while not (x >= 0 and y >= 0):
            x, y = list_transition[-1]
            list_transition.pop()
            x, y, tx, ty = transition_choice(x, y, reach_matrix)
        reach_matrix[x][y] = True
        list_transition.append((x, y))
        transition_matrix[tx][ty] = True
        x, y, tx, ty = transition_choice(x, y, reach_matrix)
    return transition_matrix, start, finish  # возвращаем матрицу проходов,начальную и конечную точку
nn = 13
mm = nn -1

mapp = list(create_labyrinth(nn, mm))

startpos = mapp[-2]
endpos = mapp[-1]
mapp.pop()
mapp.pop()
s = mapp[0]
MAPP = []
for i in range(len(s)):
    stroka = s[i]
    k = ""
    for j in range(len(stroka)):
        if stroka[j] == True:
            k += "0"
        else:
            k += "1"
    MAPP.append(k)
boardedmap = ["1"*(nn*2-1)]
for i in range(mm * 2 + 1):
    boardedmap.append("1"+MAPP[i] + "1")
boardedmap.append("1"*(nn*2-1))
#текстовая карта прямоугольников на карте
text_map = boardedmap

game_map = set()
mini_map = set()
collision_walls = []

for i, row in enumerate(text_map):
    for j, obst in enumerate(row) :
        if obst == '1':
            game_map.add((j * PIX, i * PIX))
            mini_map.add((j * MINIMAP_PIX, i * MINIMAP_PIX))
            collision_walls.append(pygame.Rect(j * PIX, i * PIX, PIX, PIX))
print(endpos)


import json
import os
import PyPDF2

from braces.views import AjaxResponseMixin, JSONResponseMixin
from django.conf import settings
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.shortcuts import redirect, render, get_object_or_404
from django.views.generic import View, TemplateView
# from django.views.generic.edit import CreateView
from wand.image import Image

from maps.forms import BookForm, MapAttributeForm, PartForm
from maps.models import MapAttribute, ImagePart, Part, PartFile, Motorcycle

class HomeView(TemplateView):
    template_name = "home.html"

class ImageMapView(View):
    # template_name = "index.htm"

    def get(self, request, *args, **kwargs):
        map_attrs = MapAttribute.objects.all()
        ctx = {
            'map_attrs': map_attrs,
        }
        return render(request, "index.htm", ctx)

    def post(self, request, *args, **kwargs):

        image_coords = request.POST['img_coords'].replace('\n', '')
        list_shp_coords = image_coords.split('\r')

        for shape_cord in list_shp_coords:
            if shape_cord.startswith('shape'):
                print(shape_cord.replace("shape- ", ""))
            else:
                print(shape_cord.replace("coords- ", ""))

        return render(request, "index.htm", {})

class UploadBook(View):

    def get(self, request, *args, **kwargs):
        form = BookForm()
        images = PartFile.objects.all()

        ctx = {
            "form": form,
            "images": images,
        }
        return render(request, "maps/show_images.html", ctx)

    def post(self, request, *args, **kwargs):

        form = BookForm(request.POST, request.FILES)
        if form.is_valid():
            book = form.save()

            full_filepath = os.path.join(settings.MEDIA_ROOT, "books", str(book.pk))
            full_filepath_jpg = os.path.join(full_filepath, "jpg")

            os.makedirs(full_filepath_jpg, exist_ok=True)

            # TODO: move to celery task
            inputpdf = PyPDF2.PdfFileReader(open(book.file.file.name, "rb"))

            # Separate pdf pages
            for i in range(inputpdf.numPages):
                # TODO: rewrite with in-memory files
                output = PyPDF2.PdfFileWriter()
                output.addPage(inputpdf.getPage(i))
                file_write = os.path.join(full_filepath, "%s-%s.pdf" % (str(book.pk), i))
                media_url = os.path.join("books", str(book.pk), "jpg", "%s-%s.jpg" % (str(book.pk), i + 1))
                with open(file_write, "wb") as outputStream:
                    output.write(outputStream)
                # Converting one page into JPG
                img_path = os.path.join(full_filepath_jpg, "%s-%s.jpg" % (str(book.pk), i + 1))
                with Image(filename=file_write+"[0]", resolution=600) as img:
                    img.save(filename=img_path)
                    image_part = ImagePart.objects.create(part_file=book, page=i+1)
                    image_part.image.name = media_url
                    image_part.save()

                try:
                    os.remove(file_write)
                except OSError:
                    pass

            return redirect(reverse('upload_book'))
        else:
            messages.error(request, "Form is invalid")

        images = PartFile.objects.all()
        ctx = {
            "form": form,
            "images": images,
        }
        return render(request, "maps/show_images.html", ctx)

class AddPartsView(View):

    def get(self, request, *args, **kwargs):

        pk = kwargs['id']
        image = PartFile.objects.get(pk=pk)
        parts = Part.objects.all()

        form_part = PartForm()
        ctx = {
            "image": image,
            "parts": parts,
            "form_part": form_part,
        }
        return render(request, "maps/add_parts.html", ctx)

    def post(self, request, *args, **kwargs):

        pk = kwargs['id']
        img = request.POST.get('image')
        parts = request.POST.getlist('parts[]')
        form_part = PartForm(request.POST)

        if parts:
            imgs = PartFile.objects.get(pk=img)
            for part in parts:
                img_part = Part.objects.get(pk=part)
                image_part = ImagePart(image=imgs, part=img_part)
                image_part.save()

        elif form_part.is_valid():
            form_part.save()
        else:
            messages.error(request, "Form is Invaid")

        return redirect(reverse('add_part', kwargs={'id': pk}))

class MapCreate(View):

    def get(self, request, *args, **kwargs):

        form = MapAttributeForm()
        map_attrs = MapAttribute.objects.all()

        ctx = {
            "form": form,
            "map_attrs": map_attrs,
        }
        return render(request, "maps/mapattribute_form.html", ctx)

    def post(self, request, *args, **kwargs):

        form = MapAttributeForm(request.POST)
        map_attrs = MapAttribute.objects.all()

        ctx = {
            "form": form,
            "map_attrs": map_attrs,
        }
        if form.is_valid():
            form.save()
            return render(request, "maps/mapattribute_form.html", ctx)
        else:
            messages.error(request, "Form is Invaid")

        return redirect(reverse('map_create'))

# class PartCreate(CreateView):
#     model = Part
#     fields = ['part']
#     success_url = '/images/'

class BookPageView(JSONResponseMixin, AjaxResponseMixin, View):
    def process_pages(self, book_id, page_id):
        image = ImagePart.objects.filter(part_file__pk=book_id, page=page_id).first()
        prev = ImagePart.objects.filter(part_file__pk=book_id, page=page_id-1).first()
        next_ = ImagePart.objects.filter(part_file__pk=book_id, page=page_id+1).first()
        res = {'image': image, 'page': page_id, 'next': None, 'prev': None}
        if prev:
            res['prev'] = prev
        if next_:
            res['next'] = next_
        return res

    def get(self, request, *args, **kwargs):
        book = PartFile.objects.get(pk=kwargs['book_id'])
        page_id = int(kwargs.get('page_id', 1))
        ctx = {'book': book}
        ctx.update(self.process_pages(kwargs['book_id'], page_id=page_id))

        return render(request, "maps/book.html", ctx)

    def post_ajax(self, request, *args, **kwargs):
        res = self.process_pages(kwargs.get('book_id'), int(kwargs.get('page_id')))
        ctx = {
            'image': res['image'].image.url,
            'prev': res['prev'].image.url if res['prev'] else None,
            'next': res['next'].image.url if res['next'] else None,
            'page': res['page']
        }
        return HttpResponse(json.dumps(ctx), content_type="application/json")

class MotorcycleView(View):
    def get(self, request, *args, **kwargs):
        moto = get_object_or_404(Motorcycle, pk=kwargs['moto_id'])
        ctx = {"motorcycle": moto}
        return render(request, "maps/motorcycle.html", ctx)


from discord.ext import commands
import discord
import random
import gifs
import main

@commands.command(
    brief=f"{main.prefix}hug nickogólnydiscorda - przytulasz wybranego użytkownika gifem"
  )
async def hug(ctx, user: discord.Member):

    embed = discord.Embed(
        title = "",
        description = f"{ctx.author.mention} przytula {user.mention}!",
      #mention to oznaczenie/ping
        color = ctx.author.color
    )

    randomgif = random.choice(gifs.hug)
    embed.set_image(url = randomgif)
    await ctx.send(embed = embed)

async def setup(bot):
  bot.add_command(hug)


import pandas
import datetime

import config
import database

def get_key_1(date, common_key, payment_amount, status):
    key = list()
    for i in range(len(date)):
        key_temp = '_'.join([str(date[i].date()), str(common_key[i]), str(float(payment_amount[i])), str(status[i])])
        key.append(key_temp)
    return key

def get_key_2(date, common_key, status):
    key = list()
    for i in range(len(date)):
        key_temp = '_'.join([str(date[i].date()), str(common_key[i]), str(status[i])])
        key.append(key_temp)
    return key

def read_kaspi(file_name):
    file_path = config.attachment_dir + '/' + file_name
    file = pandas.read_excel(file_path, skiprows=0, skipfooter=0)
    date = file['Дата транзакции']
    order_id = file['Номер бронирования']
    payment_amount_temp = file['Сумма']
    payment_type = config.kaspi_name
    payment_reference = file['Номер Транзакции']
    status = list()
    payment_amount = list()
    for payment_sum in payment_amount_temp:
        temp = float(payment_sum)
        payment_amount.append(abs(temp))
        if temp > 0:
            status.append(config.status_payment)
        else:
            status.append(config.status_refund)
    key_1 = get_key_1(date, order_id, payment_amount, status)
    key_2 = get_key_2(date, order_id, status)
    return date, order_id, payment_amount, payment_type, payment_reference, status, key_1, key_2
def read_rps(file_name):
    file_path = config.attachment_dir + '/' + file_name
    file = pandas.read_excel(file_path, skiprows=1, skipfooter=1)
    date = file['Дата']
    order_id = file['Номер брони']
    payment_amount = file['Сумма платежа']
    payment_type = config.rps_name
    payment_reference = file['# Кассовой операции']
    status_temp = file['Код результата']
    status = list()
    succeed = list()
    for code in status_temp:
        if int(code) == 0:
            status.append(config.status_payment)
        else:
            status.append(config.status_refund)
        succeed.append('1')
    key_1 = get_key_1(date, order_id, payment_amount, status)
    key_2 = get_key_2(date, order_id, status)
    return date, order_id, payment_amount, payment_type, payment_reference, status, key_1, key_2
def read_processing(file_name):
    file_path = config.attachment_dir + '/' + file_name
    file = pandas.read_excel(file_path, skiprows=4, skipfooter=0)
    date = file['AlmDate']
    order_id = file['Order ID']
    payment_amount = file['Tran_amoun']
    payment_type = config.processing_name
    payment_reference = file['RRN(Bank)']
    types = file['Type']
    succeed = file['Resp']
    for i in range(len(succeed)):
        if succeed[i] == 'Decline':
            payment_amount.at[i] = 0

    status = list()
    for type in types:
        if str(type) == 'A':
            status.append(config.status_payment)
        elif str(type) == 'F':
            status.append(config.status_refund)

    key_1 = get_key_1(date, order_id, payment_amount, status)
    key_2 = get_key_2(date, order_id, status)
    return date, order_id, payment_amount, payment_type, payment_reference, status, key_1, key_2
def read_qazkom(file_name):
    file_path = config.attachment_dir + '/' + file_name
    file = pandas.read_html(file_path)
    # concatenate all the tables that contain needed information
    total_table = list()
    tables = file[4:]
    for table in tables:
        names = table.iloc[0].values.tolist()
        table = pandas.DataFrame.from_records(data=table.values[1:], columns=names)
        total_table.append(table)
    file = pandas.concat(total_table, ignore_index=True)
    date = file['Post Date']
    date = pandas.to_datetime(date)
    order_id = file['A Code']
    payment_amount_temp = file['Settl.Amount']
    payment_type = config.qazkom_name
    payment_reference = file['Ret Ref Number']
    status = list()
    succeed = list()
    payment_amount = list()
    for payment_sum in payment_amount_temp:
        temp = float(payment_sum)
        payment_amount.append(abs(temp))
        if temp > 0:
            status.append(config.status_payment)
        else:
            status.append(config.status_refund)
        succeed.append('1')
    key_1 = get_key_1(date, order_id, payment_amount, status)
    key_2 = get_key_2(date, order_id, status)
    return date, order_id, payment_amount, payment_type, payment_reference, status, key_1, key_2

def files_into_database(file_names):
    for file_name in file_names:
        payment_type = ''

        # kaspi
        if file_name.count(config.kaspi_name) != 0:
            date, order_id, payment_amount, payment_type, payment_reference, status, key_1, key_2 = read_kaspi(file_name)
        # rps
        if file_name.count(config.rps_name) != 0:
            date, order_id, payment_amount, payment_type, payment_reference, status, key_1, key_2 = read_rps(file_name)
        # processing
        if file_name.count(config.processing_name) != 0:
            date, order_id, payment_amount, payment_type, payment_reference, status, key_1, key_2 = read_processing(file_name)
        # qazkom
        if file_name.count(config.qazkom_name) != 0:
            date, order_id, payment_amount, payment_type, payment_reference, status, key_2, key_2 = read_qazkom(file_name)

        if payment_type:
            date_created = datetime.datetime.now()
            database.update_payment_trans_table(date, date_created, order_id, payment_amount,
                   payment_type, payment_reference, status, key_1, key_2)


import rospy
import serial
import string
import math
import sys

#from time import time
from sensor_msgs.msg import Imu
from tf.transformations import quaternion_from_euler
from dynamic_reconfigure.server import Server
from razor_imu_9dof.cfg import imuConfig

PAUSE_LOGGING       =  b' '    #  Space - Pause SD/UART logging
DISABLE_TIME        =  b't'    #  Disable time log (milliseconds)
DISABLE_COMPASS     =  b'm'    #  Disable Compass
ENABLE_QUAT         =  b'Q'
ENABLE_EULER        =  b'E'

# Covariance estimation:
ORIENT_COVARIANCE = [
0.005 , 0 , 0,
0, 0.005, 0,
0, 0, 0.005
]

ANGL_VEL_COVARIANCE = [
0.02, 0 , 0,
0 , 0.02, 0,
0 , 0 , 0.02
]

LIN_ACCEL_COVARIANCE = [
0.04 , 0 , 0,
0 , 0.04, 0,
0 , 0 , 0.04
]

imu_yaw_calibration = 0.
# Callback for dynamic reconfigure requests
def reconfig_callback(config, level):
    global imu_yaw_calibration
    rospy.loginfo("""Reconfigure request for yaw_calibration: %d""" %(config['yaw_calibration']))
    imu_yaw_calibration = config['yaw_calibration']
    rospy.loginfo("Set imu_yaw_calibration to %d" % (imu_yaw_calibration))
    return config

# ####################### ROS SET UP #########################
rospy.init_node("razor_node")
srv = Server(imuConfig, reconfig_callback)     # define dynamic_reconfigure callback
pub = rospy.Publisher('imu', Imu, queue_size=1) #We only care about the most recent measurement, i.e. queue_size=1

# ################### SERIAL PORT SET UP ######################
default_port='/dev/ttyACM1'
# Check your COM port and baud rate
rospy.loginfo("Opening %s...", default_port)
try:
    ser = serial.Serial(port=default_port, baudrate=115200, timeout=1)
except serial.serialutil.SerialException:
    rospy.logerr("IMU not found at port "+port + ". Did you specify the correct port in the launch file?")
    #exit
    sys.exit(0)

# ################### INIT & CALIBRATION ######################

#accelerometer
accel_x_min = rospy.get_param('~accel_x_min', -250.0)
accel_x_max = rospy.get_param('~accel_x_max', 250.0)
accel_y_min = rospy.get_param('~accel_y_min', -250.0)
accel_y_max = rospy.get_param('~accel_y_max', 250.0)
accel_z_min = rospy.get_param('~accel_z_min', -250.0)
accel_z_max = rospy.get_param('~accel_z_max', 250.0)
# gyroscope
gyro_average_offset_x = rospy.get_param('~gyro_average_offset_x', 0.0)
gyro_average_offset_y = rospy.get_param('~gyro_average_offset_y', 0.0)
gyro_average_offset_z = rospy.get_param('~gyro_average_offset_z', 0.0)
# magnetometer
magn_x_min = rospy.get_param('~magn_x_min', -600.0)
magn_x_max = rospy.get_param('~magn_x_max', 600.0)
magn_y_min = rospy.get_param('~magn_y_min', -600.0)
magn_y_max = rospy.get_param('~magn_y_max', 600.0)
magn_z_min = rospy.get_param('~magn_z_min', -600.0)
magn_z_max = rospy.get_param('~magn_z_max', 600.0)

calibration_magn_use_extended = rospy.get_param('~calibration_magn_use_extended', False)
magn_ellipsoid_center = rospy.get_param('~magn_ellipsoid_center', [0, 0, 0])
magn_ellipsoid_transform = rospy.get_param('~magn_ellipsoid_transform', [[0, 0, 0], [0, 0, 0], [0, 0, 0]])
imu_yaw_calibration = rospy.get_param('~imu_yaw_calibration', 0.0)

#@TODO : Calibration

roll=0
pitch=0
yaw=0
seq=0
degrees2rad = math.pi/180.0

rospy.loginfo("Giving the razor IMU board 3 seconds to boot...")
rospy.sleep(3) # Sleep for 5 seconds to wait for the board to boot

#################################
### IMU Board Configuration #####
#################################
ser.write(DISABLE_TIME)
ser.write(DISABLE_COMPASS)
ser.write(ENABLE_EULER)
ser.write(ENABLE_QUAT)

imuMsg = Imu()
# Orientation covariance estimation
imuMsg.orientation_covariance = ORIENT_COVARIANCE
imuMsg.angular_velocity_covariance = ANGL_VEL_COVARIANCE
imuMsg.linear_acceleration_covariance = LIN_ACCEL_COVARIANCE

# @TODO : bug when disable and enable TIME

sample = ser.readline()
print("IMU Format:<accelX>, <accelY>, <accelZ>, <gyroX>, <gyroY>, <gyroZ>, <quatW>, <quatX>, <quatY>, <quatZ>, <pitch>, <roll>, <yaw>")
print("Sample Data: " +  sample)

while not rospy.is_shutdown():
    line = ser.readline()
    measurement = string.split(line,",")    # Fields split
    if len(measurement) > 2:
#@TODO: CORRECT IMU MEASUREMENT
# Unceted/Kalman filter? robot_localization package

        # Followed REP-103 ROS
        # http://www.ros.org/reps/rep-0103.html

	# Linear Acceleration
        imuMsg.linear_acceleration.x = float(measurement[0])
        imuMsg.linear_acceleration.y = float(measurement[1])
        imuMsg.linear_acceleration.z = -float(measurement[2])   # Gravity force should pull down

        # Angular Velocity
        imuMsg.angular_velocity.x = float(measurement[3])
        imuMsg.angular_velocity.y = float(measurement[4])
        imuMsg.angular_velocity.z = float(measurement[5])

        # Euler angle
        pitch = float(measurement[9])*degrees2rad
        roll  = float(measurement[10])*degrees2rad
        yaw   = float(measurement[11])*degrees2rad

        # Quaterion
        imuMsg.orientation.w = float(measurement[6])
        imuMsg.orientation.x = float(measurement[7])
        imuMsg.orientation.y = float(measurement[8])
        imuMsg.orientation.z = float(measurement[9])

# 	q = quaternion_from_euler(yaw, pitch, roll, 'rzyx')
#        imuMsg.orientation.w = q[0]
#        imuMsg.orientation.x = q[1]
#        imuMsg.orientation.y = q[2]
#        imuMsg.orientation.z = q[3]
        imuMsg.header.stamp= rospy.Time.now()
        imuMsg.header.frame_id = 'base_imu_link'
        imuMsg.header.seq = seq
        seq = seq + 1
        pub.publish(imuMsg)

ser.close()


import boto3
import logging
import traceback

logging.getLogger('botocore').setLevel(logging.CRITICAL)

from pathlib import Path
from botocore.config import Config
from botocore.exceptions import ClientError

from config.settings import B2_APPKEY_RW, B2_BUCKET_IMAGES, B2_ENDPOINT, B2_KEYID_RW

# Return a boto3 resource object for B2 service
def get_b2_resource(endpoint, key_id, application_key):
    return boto3.resource(service_name='s3',
                        endpoint_url=endpoint,     # Backblaze endpoint
                        aws_access_key_id=key_id,  # Backblaze keyID
                        aws_secret_access_key=application_key,  # Backblaze applicationKey
                        config=Config(signature_version='s3v4'))

def get_b2_client(endpoint, keyID, applicationKey):
        b2_client = boto3.client(service_name='s3',
                                 endpoint_url=endpoint,                # Backblaze endpoint
                                 aws_access_key_id=keyID,              # Backblaze keyID
                                 aws_secret_access_key=applicationKey) # Backblaze applicationKey
        return b2_client

def get_client():
    return get_b2_client(B2_ENDPOINT, B2_KEYID_RW, B2_APPKEY_RW)

def get_image_bucket():
    return get_b2_resource(B2_ENDPOINT, B2_KEYID_RW, B2_APPKEY_RW).Bucket(B2_BUCKET_IMAGES)

def upload_image(fileobj, file_name, extra_args=None):
    get_image_bucket().upload_fileobj(
        fileobj,
        file_name,
        ExtraArgs=extra_args
    )

# Upload specified file into the specified bucket
def upload_file(b2, fileobj, bucket, b2_path, extra_args=None):
    b2.Bucket(bucket).upload_fileobj(
        fileobj,
        b2_path,
        ExtraArgs=extra_args
    )

def download_file(b2, bucket, directory, local_name, key_name):
    file_path = directory + '/' + local_name
    try:
        b2.Bucket(bucket).download_file(key_name, file_path)
    except ClientError as ce:
        print('error', ce)

if __name__=='__main__':
    import os
    import environ
    from pathlib import Path
    # Build paths inside the project like this: BASE_DIR / 'subdir'.
    BASE_DIR = Path(__file__).resolve().parent.parent
    # Take environment variables from .env file
    env = environ.Env()
    environ.Env.read_env(os.path.join(BASE_DIR, '.env'))

    # # Possible override of settings to test
    # B2_KEYID_RW=''
    # B2_APPKEY_RW=''
    # B2_ENDPOINT=''
    # B2_BUCKET_IMAGES=''

    b2 = get_b2_resource(B2_ENDPOINT, B2_KEYID_RW, B2_APPKEY_RW)
    c = get_b2_client(B2_ENDPOINT, B2_KEYID_RW, B2_APPKEY_RW)

    import IPython
    IPython.embed()


from collections import Counter

file = open('06.txt', 'r')
init_states = [int(s) for s in file.readlines()[0].split(',')]

def num_fish(days):
    fish = Counter(init_states)

    for i in range(days):
        fish[(i+7) % 9] += fish[i % 9]
    return sum(fish.values())

print(f'DAY 6 | PART 1: {num_fish(80)}')
print(f'DAY 6 | PART 2: {num_fish(256)}')


import os
from sklearn.metrics import accuracy_score
from tqdm import tqdm

import torch
from torchvision import datasets, transforms
from dataset import TrainDataset
from torch.optim.lr_scheduler import MultiStepLR
import os
import nni
from nni.compression.pytorch.pruning import AutoCompressPruner, FPGMPruner
from nni.compression.pytorch.utils import count_flops_params
from nni.compression.pytorch import ModelSpeedup
from torchvision.models.mobilenetv2 import *
from torchvision.models.mobilenetv3 import *
from lenet import LeNet
import pandas as pd

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

COLOR = 'G'
SIZE = 32
PATH = "D:\HUST\CH-Motor_Research\Testbench data\Data_augument\IMF1"

train_set = TrainDataset(PATH, COLOR, SIZE, 'train')
train_loader = torch.utils.data.DataLoader(train_set, batch_size=128, shuffle=True)
test_set = TrainDataset(PATH, COLOR, SIZE, 'test')
test_loader = torch.utils.data.DataLoader(test_set, batch_size=128, shuffle=True)

criterion = torch.nn.CrossEntropyLoss()

epoch = 0

def trainer(model, optimizer, criterion):
    print('[LOG]: trainer')
    global epoch
    model.train()
    total_loss = 0
    total_size = 0
    for data, target in tqdm(iterable=train_loader, desc='Total Epoch {}'.format(epoch)):
        data, target = data.to(device), target.to(device)
        optimizer.zero_grad()
        output = model(data)
        loss = criterion(output, target)
        total_loss += loss.item()*data.size(0)
        loss.backward()
        optimizer.step()
        total_size += data.size(0)
    epoch = epoch + 1
    return total_loss/total_size

def finetuner(model):
    print('[LOG]: finetuner')
    optimizer = torch.optim.SGD(model.parameters(), lr=0.002, momentum=0.9, weight_decay=5e-4)
    criterion = torch.nn.CrossEntropyLoss()
    for i in range(10):
        trainer(model, optimizer, criterion)

def evaluator(model):
    print('[LOG]: evaluator')
    model.eval()
    correct = 0
    with torch.no_grad():
        for data, target in tqdm(iterable=test_loader, desc='Test'):
            data, target = data.to(device), target.to(device)
            output = model(data)
            pred = output.argmax(dim=1, keepdim=True)
            correct += pred.eq(target.view_as(pred)).sum().item()
    acc = 100 * correct / len(test_loader.dataset)
    print('Accuracy: {}%\n'.format(acc))
    return acc

if __name__ == '__main__':
    model = mobilenet_v3_small(n_class=10, width_mult=0.05).to(device)

    model.load_state_dict(torch.load('D:\HUST\CH-Motor_Research\Code\IBFD_MobileNetV3_AutoCompress\epochs\\22061012\epoch_22061012_78.pth'))
    config_list = [{'op_types': ['Linear', 'Conv2d'], 'total_sparsity': 0.1}]

    # make sure you have used nni.trace to wrap the optimizer class before initialize
    traced_optimizer = nni.trace(torch.optim.SGD)(model.parameters(), lr=0.002, momentum=0.9, weight_decay=5e-4)
    admm_params = {
        'trainer': trainer,
        'traced_optimizer': traced_optimizer,
        'criterion': criterion,
        'iterations': 5,
        'training_epochs': 5
    }
    sa_params = {
        'evaluator': evaluator
    }
    pruner = AutoCompressPruner(model, config_list, 1, admm_params, sa_params, keep_intermediate_result=True)
    print('[LOG]: compress')
    pruner.compress()
    _, model, masks, _, _ = pruner.get_best_result()
    evaluator(model)