"""Statement parser for my consoles."""

__all__ = ["str2args", "StatementError"]

from dataclasses import dataclass

class StatementError(Exception):
    def __init__(self, statement, position, text):
        super().__init__(text)
        self.statement = statement
        self.position = position

    def explain(self):
        return f"{self.statement}\n{' '*self.position}^\n{str(self)}"

@dataclass
class _Flags:
    # This class exists so that I can set values from sub-method
    inside: bool = False  # inside argument
    kwarg: bool = False # parsing a key-value pair
    backslash: bool = False # found a backslash

def str2args(sargs):
    QUOTES = ('"', "'")
    args, kwargs = [], {}

    def new_arg():
        QBERT = "!)@(#*$&"
        part = sargs[bp+(1 if quoting else 0):i]
        # Removes single backslashes and replaces double backslashes with single backslashes (temporary operation required)
        part = part.replace("\\\\", QBERT).replace("\\", "").replace(QBERT, "\\")
        if flags.kwarg:
            kwargs[args.pop()] = part
            flags.kwarg = False
        else: args.append(part)
        flags.inside = False

    def error(text):
        return StatementError(sargs, i, text)

    def errorpart():
        return f"Error in position {i}, character '{ch}'"

    n = len(sargs)
    i = 0
    quote = None  # opening quotation mark: ' or "
    quoting = False
    expecting_space = False
    flags = _Flags()
    bp = None  # break point
    while True:
        if i == n:
            if quoting: raise error("Unclosed quotation")
            if flags.inside: new_arg()
            break
        ch = sargs[i]
        if expecting_space and ch != " ": raise error(f"{errorpart()}: expecting space")
        else: expecting_space = False

        if not quoting:
            if ch == " ":
                if flags.inside: new_arg()
            elif ch == "=":
                if flags.kwarg: raise error(f"{errorpart()}: repeated equal sign")
                if flags.inside: new_arg()
                flags.kwarg = True
            elif ch == "\\": raise error(f"{errorpart()}: backslash not allowed outside quotation marks")
            else:
                if not flags.inside:
                    flags.inside, bp = True, i
                    quoting = ch in QUOTES
                    if quoting: quote = ch
                else:
                    if ch in QUOTES: raise error(f"{errorpart()}: unexpected quotation mark")
        else:
            if flags.backslash:
                # just ignores next character
                flags.backslash = False
            else:
                if ch == quote:
                    new_arg()
                    flags.inside, quoting, expecting_space = False, False, True
                elif ch == "\\":
                    flags.backslash = True
        i += 1
    # print(f"{fg('purple_4a')+attr('bold')}str2args() is still in probation phase; therefore we'll print its results:\n<<{sargs}>>\nargs={args}\nkwargs={kwargs}{attr('reset')}\n")
    return args, kwargs


# pylint: disable=locally-disabled, missing-module-docstring, missing-class-docstring
# pylint: disable=locally-disabled, missing-function-docstring

import pytest

from illogical.expression.comparison.ne import Ne
from illogical.operand.collection import Collection
from illogical.operand.value import Value

@pytest.mark.parametrize(
    "left, right, expected",
    [
        # Same types
        (Value(1), Value(0), True),
        (Value(1), Value(1), False),
        (Value(1.1), Value(1.0), True),
        (Value(1.1), Value(1.1), False),
        (Value("1"), Value("2"), True),
        (Value("1"), Value("1"), False),
        (Value(True), Value(False), True),
        (Value(True), Value(True), False),
        # Diff types
        (Value(1), Value(1.1), True),
        (Value(1), Value("1"), True),
        (Value(1), Value(True), True),
        (Value(1.1), Value("1"), True),
        (Value(1.1), Value(True), True),
        (Value("1"), Value(True), True),
        # Collection
        (Collection([Value(1)]), Collection([Value(1)]), True),
        (Value(1), Collection([Value(1)]), True),
    ],
)
def test_evaluate(left, right, expected):
    assert Ne(left, right).evaluate({}) == expected

@pytest.mark.parametrize(
    "left, right, expected",
    [
        (Value(1), Value(2), "Ne(Value(1), Value(2))"),
    ],
)
def test___repr__(left, right, expected):
    assert repr(Ne(left, right)) == expected


from genericpath import exists
import cv2
import numpy as np
import json
import os
from datetime import datetime

def write_in_json(txt_file, read_txt, today):
    while  read_txt :
        lines  =  read_txt.readlines()

        if  not  lines:
            break

        chk_json_exist = os.path.isfile(txt_file)
        if chk_json_exist == False:
            data0 = {
                'file_name': txt_file,
                'AI_start_time': today,
                'AI_Object_Tracking': [

                ]
            }

        for  line  in  lines:
            print (line)
            ## call variable
            frame_id = line.split(',')[0]
            track_cls = line.split(',')[1]
            track_id = line.split(',')[2]
            x1 = line.split(',')[3]
            y1 = line.split(',')[4]
            x2 = line.split(',')[5]
            y2 = line.split(',')[6]
            score_ = line.split(',')[7]
            score = score_.split(' ')[0]

            ## write in json

today = datetime.now().strftime('%Y-%m-%d')
txt_file = os.path.join('C:/home/ims/yolov7/Bytetrack_yolov7/result/TBN4223133_1_20220613-155351_4s.txt')
json_file = os.path.join('C:/home/ims/yolov7/Bytetrack_yolov7/result/TBN4223133_1_20220613-155351_4s.json')
read_txt = open(txt_file, 'r', encoding='utf-8')

write_in_json(txt_file, read_txt, today)

    # chk json file
    # chk_json_exist = os.path.isfile(res_file)
    # if chk_json_exist == False:
    #     data0 = {
    #         'file_name': res_file,
    #         'AI_start_time': today,
    #         'AI_Object_Tracking': [

    #         ]
    #     }
    # else:
    #     with open(res_file, "r+") as f:
    #         data0 = json.loads(f.read())
    # data1 = {
    #             'frame': frame_id,
    #             'object': [
    #                 {
    #                     'track_cls': t_label,
    #                     'track_id': tid,
    #                     'score': t_score,
    #                     'x1': tlwh_0,
    #                     'y1': tlwh_1,
    #                     'x2': tlwh_2,
    #                     'y2': tlwh_3
    #                 }
    #             ]
    #         }

    # # with open(res_file, 'w', encoding='utf-8') as f:
    # data0['AI_Object_Tracking'].append(data1)

    # str_ = json.dumps(data0,
    #                 indent=4, sort_keys=False,
    #                 separators=(',', ': '), ensure_ascii=False)
    # write_json.write(str_)


import numpy as np
import torch

from rt_ddsp import processors

def test_output_is_correct() -> None:
    processor = processors.Add()
    x = torch.zeros((2, 3)) + 1.0
    y = torch.zeros((2, 3)) + 2.0

    output = processor(x, y)

    expected = np.zeros((2, 3), dtype=np.float32) + 3.0

    np.testing.assert_array_equal(expected, output.numpy())


from keras import layers
from keras import models
from keras import optimizers
from keras.preprocessing.image import ImageDataGenerator
import matplotlib as mpl
import matplotlib.pyplot as plt
import os

def multiple_choice():
    """Choose the right answers (one or more) from multiple choices.
    Note: if you think a is the right answer, return a;
            if your think a, b are the right answers, return a, b; ect.
    """
    # Here are 4 choices
    a = "Training accuracy increases over time and this is a problem."
    b = "Validation accuracy does not increase over time and this is a problem."
    c = "Training loss decreases over time and this is a problem."
    d = "Validation loss does not decrease over time and this is a problem."
    return b, d

def modified_cnn():
    """Return instance of keras.models.Sequential
    This is similar to build_cnn_architecture() in q1.py; however, you have to compile your model with
    a proper loss function and optimizer.
    """
    #######
    # b) 1. change Activation Function from 'sigmoid' to 'relu'
    model = models.Sequential()
    model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)))
    model.add(layers.MaxPooling2D((2, 2)))
    model.add(layers.Conv2D(64, (3, 3), activation='relu'))
    model.add(layers.MaxPooling2D((2, 2)))
    model.add(layers.Conv2D(128, (3, 3), activation='relu'))
    model.add(layers.MaxPooling2D((2, 2)))
    model.add(layers.Conv2D(128, (3, 3), activation='relu'))
    model.add(layers.MaxPooling2D((2, 2)))
    model.add(layers.Flatten())
    model.add(layers.Dense(512, activation='relu'))
    model.add(layers.Dense(4, activation='softmax'))
    #######
    return model

def test_multiple_choice():
    choice = multiple_choice()
    assert isinstance(choice, str) or isinstance(choice, tuple)
    print("\nPass.")

def test_modified_cnn():
    model = modified_cnn()
    assert isinstance(model, models.Sequential)
    if hasattr(model, "loss") and hasattr(model, "optimizer"):
        print("\nPass.")

def train():
    # data processing
    base_dir = '/userhome/34/zxzhao/assignment2/Datasets/cat_dog_car_bike/'
    train_dir = os.path.join(base_dir, 'train')
    val_dir = os.path.join(base_dir, 'val')
    test_dir = os.path.join(base_dir, 'test')

    train_datagen = ImageDataGenerator(rescale=1./255)
    test_datagen = ImageDataGenerator(rescale=1./255)

    train_generator = train_datagen.flow_from_directory(
        train_dir,
        target_size=(150, 150),
        batch_size=20,
        class_mode='categorical')

    validation_generator = test_datagen.flow_from_directory(
        val_dir,
        target_size=(150, 150),
        batch_size=20,
        class_mode='categorical')

    # create model
    model = modified_cnn()
    # b) 2. change Learning Rate from '0.1' to '1e-4'
    model.compile(loss = 'categorical_crossentropy',
                  optimizer = optimizers.RMSprop(lr=1e-4),
                  metrics=['acc'])

    # train
    history = model.fit_generator(
        train_generator,
        steps_per_epoch=100,
        epochs=10,
        validation_data=validation_generator,
        validation_steps=50)

    # plot
    acc = history.history['acc']
    val_acc = history.history['val_acc']
    loss = history.history['loss']
    val_loss = history.history['val_loss']

    epochs = range(1, len(acc) + 1)

    plt.plot(epochs, acc, 'bo', label='Training acc')
    plt.plot(epochs, val_acc, 'b', label='Validation acc')
    plt.title('Training and validation accuracy')
    plt.legend()
    plt.savefig('q2_acc.jpg')
    plt.figure()
    plt.plot(epochs, loss, 'bo', label='Training loss')
    plt.plot(epochs, val_loss, 'b', label='Validation loss')
    plt.title('Training and validation loss')
    plt.legend()

#     plt.show()
    plt.savefig('q2_loss.jpg')

if __name__ == '__main__':
    test_multiple_choice()
    test_modified_cnn()
    train()


import os
import numpy as np
import PIL.Image as Image
import torch
from torch.utils import data
import pdb
import random

def rotated_rect_with_max_area(w, h, angle):
    """
  Given a rectangle of size wxh that has been rotated by 'angle' (in
  radians), computes the width and height of the largest possible
  axis-aligned rectangle (maximal area) within the rotated rectangle.
  """
    if w <= 0 or h <= 0:
        return 0, 0

    width_is_longer = w >= h
    side_long, side_short = (w, h) if width_is_longer else (h, w)

    # since the solutions for angle, -angle and 180-angle are all the same,
    # if suffices to look at the first quadrant and the absolute values of sin,cos:
    sin_a, cos_a = abs(np.sin(angle)), abs(np.cos(angle))
    if side_short <= 2. * sin_a * cos_a * side_long or abs(sin_a - cos_a) < 1e-10:
        # half constrained case: two crop corners touch the longer side,
        #   the other two corners are on the mid-line parallel to the longer line
        x = 0.5 * side_short
        wr, hr = (x / sin_a, x / cos_a) if width_is_longer else (x / cos_a, x / sin_a)
    else:
        # fully constrained case: crop touches all 4 sides
        cos_2a = cos_a * cos_a - sin_a * sin_a
        wr, hr = (w * cos_a - h * sin_a) / cos_2a, (h * cos_a - w * sin_a) / cos_2a

    return wr, hr

class BaseFolder(data.Dataset):
    def __init__(self, root, crop=None, rotate=None, flip=False,
                 mean=None, std=None):
        super(BaseFolder, self).__init__()
        self.mean, self.std = mean, std
        self.flip = flip
        self.rotate = rotate
        self.crop = crop
        img_dir = os.path.join(root, 'images')
        gt_dir = os.path.join(root, 'masks')
        names = ['.'.join(name.split('.')[:-1]) for name in os.listdir(gt_dir)]
        self.img_filenames = [os.path.join(img_dir, name+'.jpg') for name in names]
        self.gt_filenames = [os.path.join(gt_dir, name+'.png') for name in names]
        self.names = names

    def random_crop(self, *images):
        images = list(images)
        sz = [img.size for img in images]
        sz = set(sz)
        assert(len(sz)==1)
        w, h = sz.pop()
        th, tw = int(self.crop*h), int(self.crop*w)
        if w == tw and h == th:
            return 0, 0, h, w
        i = random.randint(0, h - th)
        j = random.randint(0, w - tw)
        results = [img.crop((j, i, j + tw, i + th)) for img in images]
        return tuple(results)

    def random_flip(self, *images):
        if self.flip and random.randint(0, 1):
            images = list(images)
            results = [img.transpose(Image.FLIP_LEFT_RIGHT) for img in images]
            return tuple(results)
        else:
            return images

    def random_rotate(self, *images):
        images = list(images)
        sz = [img.size for img in images]
        sz = set(sz)
        assert(len(sz)==1)
        w, h = sz.pop()
        degree = random.randint(-1*self.rotate, self.rotate)
        images_r = [img.rotate(degree, expand=1) for img in images]
        w_b, h_b = images_r[0].size
        w_r, h_r = rotated_rect_with_max_area(w, h, np.radians(degree))
        ws = (w_b - w_r) / 2
        ws = max(ws, 0)
        hs = (h_b - h_r) / 2
        hs = max(hs, 0)
        we = ws + w_r
        he = hs + h_r
        we = min(we, w_b)
        he = min(he, h_b)
        results = [img.crop((ws, hs, we, he)) for img in images_r]
        return tuple(results)

    def __len__(self):
        return len(self.names)

class PriorFolder(BaseFolder):
    def __init__(self, root, prior_dir, size=256, crop=None, rotate=None, flip=False,
                 mean=None, std=None):
        super(PriorFolder, self).__init__(root, crop=crop, rotate=rotate, flip=flip, mean=mean, std=std)
        self.size = size
        self.pr_filenames = [os.path.join(prior_dir, name+'.png') for name in self.names]

    def __getitem__(self, index):
        # load image
        img_file = self.img_filenames[index]
        img = Image.open(img_file)
        gt_file = self.gt_filenames[index]
        name = self.names[index]
        gt = Image.open(gt_file)
        WW, HH = gt.size
        img = img.resize((WW, HH))
        pr_file = self.pr_filenames[index]
        pr = Image.open(pr_file)
        pr = pr.resize((WW, HH))
        if self.crop is not None:
            img, gt, pr = self.random_crop(img, gt, pr)
        if self.rotate is not None:
            img, gt, pr = self.random_rotate(img, gt, pr)
        if self.flip:
            img, gt, pr = self.random_flip(img, gt, pr)
        img, gt, pr = [_img.resize((self.size, self.size)) for _img in [img, gt, pr]]
        img = np.array(img, dtype=np.float64) / 255.0
        gt = np.array(gt, dtype=np.uint8)
        gt[gt != 0] = 1
        pr = np.array(pr, dtype=np.float64) / 255.0
        if len(img.shape) < 3:
            img = np.stack((img, img, img), 2)
        if img.shape[2] > 3:
            img = img[:, :, :3]
        if len(gt.shape) > 2:
            gt = gt[:, :, 0]
        if self.mean is not None:
            img -= self.mean
        if self.std is not None:
            img /= self.std
        img = img.transpose(2, 0, 1)
        img = torch.from_numpy(img).float()
        gt = torch.from_numpy(gt).float()
        pr = torch.from_numpy(pr).float()
        return img, gt, pr, name, WW, HH

class Folder(BaseFolder):
    def __init__(self, root, scales=[256], crop=None, rotate=None, flip=False,
                 mean=None, std=None):
        super(Folder, self).__init__(root, crop=crop, rotate=rotate, flip=flip, mean=mean, std=std)
        self.scales = scales

    def __getitem__(self, index):
        # load image
        img_file = self.img_filenames[index]
        img = Image.open(img_file)
        gt_file = self.gt_filenames[index]
        name = self.names[index]
        gt = Image.open(gt_file)
        WW, HH = gt.size
        img = img.resize((WW, HH))
        if self.crop is not None:
            img, gt = self.random_crop(img, gt)
        if self.rotate is not None:
            img, gt = self.random_rotate(img, gt)
        if self.flip:
            img, gt = self.random_flip(img, gt)
        max_size = max(self.scales)
        img = img.resize((max_size, max_size))
        gts = [gt.resize((s, s)) for s in self.scales]

        img = np.array(img, dtype=np.float64) / 255.0
        gts = [np.array(gt, dtype=np.uint8) for gt in gts]
        for gt in gts: gt[gt != 0] = 1
        if len(img.shape) < 3:
            img = np.stack((img, img, img), 2)
        if img.shape[2] > 3:
            img = img[:, :, :3]
        for i, gt in enumerate(gts):
            if len(gt.shape) > 2:
                gts[i] = gt[:, :, 0]
        if self.mean is not None:
            img -= self.mean
        if self.std is not None:
            img /= self.std
        img = img.transpose(2, 0, 1)
        img = torch.from_numpy(img).float()
        gts = [torch.from_numpy(gt).float() for gt in gts]
        return img, gts, name

def collate_more(data):
    images, gts, name = zip(*data)
    gts = list(map(list, zip(*gts)))

    images = torch.stack(images, 0)
    gts = [torch.stack(gt, 0) for gt in gts]

    return images, gts, name

if __name__ == "__main__":
    import matplotlib.pyplot as plt
    from datetime import datetime
    random.seed(datetime.now())
    sb = Folder('/home/zeng/data/datasets/saliency_Dataset/ECSSD',
                     crop=None, rotate=10, flip=True)
    img, gt, _ = sb.__getitem__(random.randint(0, 1000))
    img = img.numpy().transpose((1, 2, 0))
    plt.imshow(img)
    plt.show()
    plt.imshow(gt[0])
    plt.show()

    # sb = PriorFolder('/home/zeng/data/datasets/saliency_Dataset/ECSSD',
    #                  '/home/zeng/data/datasets/saliency_Dataset/results/ECSSD-Sal/SRM',
    #                  crop=None, rotate=None, flip=True, size=256)
    # img, gt, pr, _, _, _ = sb.__getitem__(0)
    # img = img.numpy().transpose((1, 2, 0))
    # plt.imshow(img)
    # plt.show()
    # plt.imshow(gt)
    # plt.show()
    # plt.imshow(pr)
    # plt.show()


import os
import csv

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

engine=create_engine("sqlite:///C:\\Users\\sysadmin\\Desktop\\Nishu\\sqlite3\\SQL\\mydb.db")
mydb=scoped_session(sessionmaker(bind=engine))

def main():
    f= open("flight.csv")
    reader =  csv .reader(f)
    for origin,destination,duration in reader:
        mydb.execute("insert into flights(origin,destination,duration) values (:origin,:destination,:duration)",
                     {"origin":origin , "destination":destination , "duration":duration})
        print(f"{origin} to {destination} takes {duration} minutes")
    mydb.commit()

if __name__=="__main__":
    main()


#!/usr/bin/env python3

# Losslessly autorotate JPEG images: a replacement for exifautotran
# which is no longer usable because of Debian Bug#947182.

from PIL import Image, ExifTags, ImageOps, __version__
from PIL import __version__ as PILversion
import sys

def autorotate(filename, outfile):
    """outfile may be the same as filename.
    """
    img = Image.open(filename)

    rotated = ImageOps.exif_transpose(img)

    rotated.save(outfile, exif=rotated.getexif())
    print("Saved to", outfile)

if __name__ == '__main__':
    pilversionparts = PILversion.split('.')
    if int(pilversionparts[0]) + float(pilversionparts[1]) / 10. < 7.2:
        print("PIL before 7.2 is buggy, bailing!")
        sys.exit(1)
    autorotate(sys.argv[1], "/tmp/rotated.jpg")


from django.urls import reverse
from django.shortcuts import redirect, render
from django.db.models import Q
from django.http import HttpResponseRedirect, HttpRequest
from django.conf import settings
from modules.serializers import OrderProducts

from modules.exceptions import *
from .reports import generate_report
from .forms import *
from .models import *

def get_shop_params():
    categories = ProductCategory.objects.all()
    params = {
        "categories": categories,
    }
    return params

@server_error_decorator
@is_staff_decorator
def index(request):
    with open(settings.PATH_LOG / f"api_view_logs.log", encoding="utf-8") as file:
        api_logs = file.read()
    with open(settings.PATH_LOG / f"orders_logs.log", encoding="utf-8") as file:
        order_logs = file.read()
    with open(settings.PATH_LOG / f"server_logs.log", encoding="utf-8") as file:
        server_logs = file.read()
    with open(settings.PATH_LOG / f"logs.log", encoding="utf-8") as file:
        logs = file.read()

    params = {
        "api_logs": api_logs,
        "order_logs": order_logs,
        "server_logs": server_logs,
        "logs": logs,
    }

    form = SearchForm()
    if "query" in request.GET:
        form = SearchForm(request.GET)
        if form.is_valid():
            cd = form.cleaned_data
            prod_results = Product.objects.filter(
                Q(name__icontains=cd["query"]) | Q(vendor__icontains=cd["query"])
            )
            prod_total_results = prod_results.count()

            news_results = News.objects.filter(
                Q(title__icontains=cd["query"]) | Q(news__icontains=cd["query"])
            )
            news_total_results = news_results.count()

            orders_results = Order.objects.filter(Q(id__icontains=cd["query"]))
            orders_total_results = orders_results.count()

            users_results = User.objects.filter(
                Q(username__icontains=cd["query"])
                | Q(first_name__icontains=cd["query"])
                | Q(last_name__icontains=cd["query"])
                | Q(email__icontains=cd["query"])
                | Q(id__icontains=cd["query"])
            )
            users_total_results = users_results.count()

            search_params = {
                "prod_results": prod_results,
                "prod_total_results": prod_total_results,
                "news_results": news_results,
                "news_total_results": news_total_results,
                "orders_results": orders_results,
                "orders_total_results": orders_total_results,
                "users_results": users_results,
                "users_total_results": users_total_results,
            }

            context = {
                **params,
                **search_params,
                "form": form,
                "cd": cd,
            }
            return render(request, "crm/index.html", context)

    context = {**params, "form": form}

    if str(request.GET.get("name")) != "None":
        context["name"] = str(request.GET.get("name"))
    return render(request, "crm/index.html", context)

@server_error_decorator
@is_staff_decorator
def news_edit(request, news_id):
    try:
        new_item = News.objects.get(pk=news_id)
    except News.DoesNotExist:
        message = "Такой новости не существует."
        return render(request, "dashboard/404.html", {"message": message})

    if request.method == "POST":
        form = NewsEdit(request.POST, request.FILES, instance=new_item)
        if form.is_valid():
            news_form = form.save(commit=False)
            news_form.pub_date = datetime.now()
            news_form.save()
            return HttpResponseRedirect(reverse("crm:news_list"))
    else:
        form = NewsEdit(instance=new_item)
    return render(
        request,
        "crm/news_edit.html",
        {
            "form": form,
            "new_item": new_item,
        },
    )

@server_error_decorator
@is_staff_decorator
def products_list(request):
    products = Product.objects.all().order_by("id")
    categories = ProductCategory.objects.all().order_by("id")
    filter_del = str(request.GET.get("deleted"))
    restore = str(request.GET.get("restored"))

    params = {
        "categories": categories,
    }

    form = SearchForm()
    if "query" in request.GET:
        form = SearchForm(request.GET)
        if form.is_valid():
            cd = form.cleaned_data
            products = Product.objects.filter(
                Q(name__icontains=cd["query"]) | Q(vendor__icontains=cd["query"])
            )

            context = {
                **params,
                "products": products,
                "form": form,
                "cd": cd,
            }
            return render(request, "crm/products_list.html", context)

    context = {
        **params,
        "products": products,
        "form": form,
    }

    if filter_del != "None":
        if isinstance(int(filter_del), int):
            product_to_delete = Product.objects.get(id=int(filter_del))
            product_to_delete.is_active = False
            product_to_delete.save()
            return render(request, "crm/products_list.html", context)

    if restore != "None":
        if isinstance(int(restore), int):
            product_to_restore = Product.objects.get(id=int(restore))
            product_to_restore.is_active = True
            product_to_restore.save()
            return render(request, "crm/products_list.html", context)

    return render(request, "crm/products_list.html", context)

@server_error_decorator
@is_staff_decorator
def product_edit(request, product_id):
    try:
        product_item = Product.objects.get(pk=product_id)
    except Product.DoesNotExist:
        message = "Такого продукта нет."
        return render(request, "dashboard/404.html", {"message": message})
    if request.method == "POST":
        form = ProductEdit(request.POST, request.FILES, instance=product_item)
        if form.is_valid():
            product_form = form.save(commit=False)
            product_form.save()
            return HttpResponseRedirect(reverse("crm:products_list"))
    else:
        form = ProductEdit(instance=product_item)
    return render(
        request,
        "crm/product_edit.html",
        {
            "form": form,
            "product_item": product_item,
        },
    )

@server_error_decorator
@is_staff_decorator
def create_news(request):
    profile = Profile.objects.get(client_id=request.user)
    assert isinstance(request, HttpRequest)
    form = NewsEdit(request.POST, request.FILES)
    if request.method == "POST":
        if form.is_valid():
            new_f = form.save(commit=False)
            new_f.pub_date = datetime.now()
            new_f.save()
            return redirect("crm:news_list")
        else:
            form = NewsEdit()
    return render(
        request,
        "crm/create_news.html",
        {
            "form": form,
            "profile": profile,
        },
    )

@server_error_decorator
@is_staff_decorator
def create_product(request):
    assert isinstance(request, HttpRequest)
    form = ProductEdit(request.POST, request.FILES)
    if request.method == "POST":
        if form.is_valid():
            new_f = form.save(commit=False)
            new_f.save()
            return redirect("crm:products_list")
        else:
            form = ProductEdit()
    return render(
        request,
        "crm/create_product.html",
        {
            "form": form,
        },
    )

@server_error_decorator
@is_staff_decorator
def news_list(request):
    news = News.objects.all().order_by("id")
    filter_del = str(request.GET.get("deleted"))
    restore = str(request.GET.get("restored"))

    form = SearchForm()
    if "query" in request.GET:
        form = SearchForm(request.GET)
        if form.is_valid():
            cd = form.cleaned_data
            news = News.objects.filter(
                Q(title__icontains=cd["query"]) | Q(news__icontains=cd["query"])
            )

            context = {
                # "profile": profile,
                "news": news,
                "form": form,
                "cd": cd,
            }
            return render(request, "crm/news_list.html", context)

    context = {
        "news": news,
        "form": form,
    }
    if filter_del != "None":
        if isinstance(int(filter_del), int):
            new_to_delete = News.objects.get(id=int(filter_del))
            new_to_delete.is_active = False
            new_to_delete.save()
            return render(request, "crm/news_list.html", context)

    if restore != "None":
        if isinstance(int(restore), int):
            new_to_restore = News.objects.get(id=int(restore))
            new_to_restore.is_active = True
            new_to_restore.save()
            return render(request, "crm/news_list.html", context)

    return render(request, "crm/news_list.html", context)

@server_error_decorator
@is_staff_decorator
def user_orders(request):
    users = User.objects.all()
    profiles = Profile.objects.all()
    orders_list = Order.objects.all().order_by("-id")
    # profile = Profile.objects.get(client_id=request.user)
    status1 = OrderStatus.objects.get(status_name="В сборке")
    status2 = OrderStatus.objects.get(status_name="В доставке")
    status3 = OrderStatus.objects.get(status_name="Доставлен")
    status4 = OrderStatus.objects.get(status_name="Отменен")

    statuses = {
        "status1": status1,
        "status2": status2,
        "status3": status3,
        "status4": status4,
    }

    form = SearchForm()
    if "query" in request.GET:
        form = SearchForm(request.GET)
        if form.is_valid():
            cd = form.cleaned_data

            users = User.objects.filter(
                Q(username__icontains=cd["query"])
                | Q(first_name__icontains=cd["query"])
                | Q(last_name__icontains=cd["query"])
                | Q(email__icontains=cd["query"])
                | Q(id__icontains=cd["query"])
            )

            search_params = {
                "users": users,
            }

            context = {
                "users": users,
                "profiles": profiles,
                # "profile": profile,
                "orders_list": orders_list,
                **statuses,
                **search_params,
                "form": form,
                "cd": cd,
            }
            return render(request, "crm/orders.html", context)

    context = {
        "users": users,
        "profiles": profiles,
        # "profile": profile,
        "orders_list": orders_list,
        **statuses,
        "form": form,
    }

    return render(request, "crm/orders.html", context)

@server_error_decorator
@is_staff_decorator
def user_order_edit(request, order_id):
    try:
        order = Order.objects.get(pk=order_id)
    except Order.DoesNotExist:
        message = "Такого заказа не существует."
        return render(request, "dashboard/404.html", {"message": message})

    if request.method == "POST":
        form = OrderEdit(request.POST, instance=order)
        if form.is_valid():
            order_form = form.save(commit=False)
            order_form.save()

            return HttpResponseRedirect(reverse("crm:orders"))
    else:
        form = OrderEdit(instance=order)

    serializer = OrderProducts(order, many=False)
    keys = serializer.data["product_list"].keys()
    get_keys = []
    amount = []
    for key in keys:
        get_keys.append(int(key))
        amount.append(int(serializer.data["product_list"].get(key)))
    order_products = Product.objects.filter(id__in=get_keys)

    profile = Profile.objects.get(client_id=request.user)
    title = order
    total = float(0)
    leng = int(0)
    for product in order_products:
        total += product.get_sale() * amount[leng]
        leng += 1
    context = {
        "form": form,
        "keys": keys,
        "amount": amount,
        "order_products": order_products,
        "title": title,
        "profile": profile,
        "order": order,
        "total": total,
    }
    return render(request, "crm/order_edit.html", context)

@server_error_decorator
@is_superuser_decorator
def user_permissions(request):
    profile = Profile.objects.get(client_id=request.user)
    users = User.objects.all().order_by("-is_staff")
    context = {
        "profile": profile,
        "users": users,
    }
    return render(request, "crm/user_permissions.html", context)

@server_error_decorator
@is_superuser_decorator
def make_user_client(user_id):
    target_user = User.objects.get(id=user_id)
    try:
        target_user.is_staff = False
        target_user.is_superuser = False
        target_user.save()
        return redirect("crm:permissions")
    except target_user.username == "igor":
        return redirect("crm:permissions")

@server_error_decorator
@is_superuser_decorator
def make_user_manager(user_id):
    target_user = User.objects.get(id=user_id)
    try:
        target_user.is_staff = True
        target_user.is_superuser = False
        target_user.save()
        return redirect("crm:permissions")
    except target_user.username == "igor":
        return redirect("crm:permissions")

@server_error_decorator
@is_superuser_decorator
def make_user_superuser(user_id):
    target_user = User.objects.get(id=user_id)
    try:
        target_user.is_staff = True
        target_user.is_superuser = True
        target_user.save()
        return redirect("crm:permissions")
    except target_user.username == "igor":
        return redirect("crm:permissions")

@server_error_decorator
def product_detail(request, product_id):
    reviews = Review.objects.order_by('-pub_date')
    try:
        product = Product.objects.get(pk=product_id, is_active=True)
    except Product.DoesNotExist:
        message = 'Такого товара не существует.'
        return render(request, 'dashboard/404.html', {'message': message})
    title = str(product.name)

    params = {
        'product': product,
        'title': title,
        'reviews': reviews,
    }

    context = {**get_shop_params(),
               **params}
    return render(request, 'crm/product_detail.html', context)

@server_error_decorator
def news_detail(request, news_id):
    try:
        new = News.objects.get(pk=news_id, is_active=True)
    except News.DoesNotExist:
        message = 'Такой новости не существует.'
        return render(request, 'dashboard/404.html', {'message': message})

    context = {
        'current_new': new,
    }
    if request.user.is_active:
        profile = Profile.objects.get(client_id=request.user)
        context['profile'] = profile
    return render(request, 'crm/news_detail.html', context)

@server_error_decorator
@is_staff_decorator
def support_list(request):
    get_r = str(request.GET.get("get_r"))
    read = str(request.GET.get("read"))
    cq = str(request.GET.get("current_question"))

    sup_list = Support.objects.all().order_by("-id")

    if get_r != "None":
        if isinstance(int(get_r), int):
            sup_list = Support.objects.filter(checked=get_r).order_by("-id")

    try:
        current_question = Support.objects.get(id=cq)
    except:
        current_question = sup_list.first()

    context = {
        "sup_list": sup_list,
        "current_question": current_question,
    }

    if read != "None":
        if isinstance(int(read), int):
            current_question.checked = True
            current_question.save()
            return render(request, "crm/support_list.html", context)
    return render(request, "crm/support_list.html", context)

@server_error_decorator
@is_staff_decorator
def templates(request):
    tid = str(request.GET.get("tid"))
    temp_list = Templates.objects.filter()
    context = {"temp_list": temp_list}
    if tid and tid.isnumeric():
        template = Templates.objects.get(id=int(tid))
        context["template"] = template
    return render(request, "crm/templates_list.html", context)

@server_error_decorator
@is_staff_decorator
def reports(request):
    if request.method == "POST":
        form = OrderPeriodForm(request.POST)
        if form.is_valid():
            orders = Order.objects.all().order_by("-date_created")
            generate_report(orders)
    else:
        form = OrderPeriodForm()

    context = {
        "form": form,
    }
    return render(request, "crm/reports.html", context)


import time
from rich import print
from rich.table import Table
from rich.box import SIMPLE

def display_ls(files):
    table = Table(show_header=True, header_style="bold blue", box=SIMPLE)
    table.add_column("Filename", style="dim", width=20)
    table.add_column("Owner", width=10)
    table.add_column("Permissions", width=10)
    table.add_column("Size", justify="right")
    for filename, (owner, perms, size) in files.items():
        table.add_row(filename, owner, perms, size)
    print(table)
    time.sleep(2)

def display_pwd(directory):
    print(f"[bold cyan]Current Directory:[/bold cyan] [green]{directory}[/green]")
    time.sleep(1)

# Dummy data for the example
current_directory = "/home/user"
files_before = {
    "file1.txt": ("user", "-rw-r--r--", "12 KB"),
    "file2.txt": ("user", "-rw-r--r--", "15 KB"),
    "file3.txt": ("user", "-rw-r--r--", "18 KB"),
    "file4.txt": ("user", "-rw-r--r--", "14 KB"),
    "file5.txt": ("user", "-rw-r--r--", "13 KB"),
    "file6.txt": ("user", "-rw-r--r--", "16 KB"),
    "file7.txt": ("user", "-rw-r--r--", "11 KB"),
    "project": ("user", "drwxr-xr-x", "[Dir]")
}
files_after = {
    "file3.txt": ("user", "-rw-r--r--", "18 KB"),
    "file4.txt": ("user", "-rw-r--r--", "14 KB"),
    "file6.txt": ("user", "-rw-r--r--", "16 KB"),
    "file7.txt": ("user", "-rw-r--r--", "11 KB"),
    "project": ("user", "drwxr-xr-x", "[Dir]"),
    "newfolder": ("user", "drwxr-xr-x", "[Dir]")
}

# Demonstrate the commands
print("[bold blue]Command:[/bold blue] [green]ls[/green]")
display_ls(files_before)

print("\n[bold blue]Command:[/bold blue] [green]mkdir newfolder[/green]")
print("[bold green]Folder 'newfolder' created.[/bold green]")
time.sleep(1)

print("\n[bold blue]Command:[/bold blue] [green]ls[/green]")
display_ls(files_after)

print("\n[bold blue]Command:[/bold blue] [green]cd newfolder[/green]")
current_directory += "/newfolder"
display_pwd(current_directory)

print("\n[bold blue]Command:[/bold blue] [green]cp ../file1.txt .[/green]")
print("[bold green]File 'file1.txt' copied to current directory.[/bold green]")
time.sleep(1)

print("\n[bold blue]Command:[/bold blue] [green]rm ../file1.txt ../file2.txt ../file5.txt[/green]")
print("[bold green]Files 'file1.txt', 'file2.txt', and 'file5.txt' removed.[/bold green]")
time.sleep(1)

print("\n[bold blue]Command:[/bold blue] [green]ls[/green]")
display_ls(files_after)

print("\n[bold blue]Command:[/bold blue] [green]pwd[/green]")
display_pwd(current_directory)


from airflow import DAG
from datetime import datetime
from src.hellooperator import HelloOperator

with DAG(dag_id = "04_customOperator",
         description = "using custom (base) operator",
         start_date = datetime(2023, 3, 24),
         schedule_interval = "@once"
) as dag:

    task = HelloOperator(task_id = "hello_with_custom_operator",
                         name = "KLYMers")

    task


from app import app
from app import db
from app.models import User, Project, Pomodoro
from sqlalchemy import desc
from datetime import datetime

@app.shell_context_processor
def make_shell_context():
    # adds the database and models to `flask shell` environment

    return {'db': db, 'User': User, 'Project': Project, 'Pomodoro': Pomodoro}

def update_db():
    # makes default timestamps. Bugfix
    projects = Project.query.filter_by().all()
    for p in projects:
        poms = Pomodoro.query.filter_by(project=p)
        latest_pom = poms.order_by(desc(Pomodoro.timestamp_end)).first()
        try:
            p.last_timestamp = latest_pom.timestamp_end
            db.session.add(p)
            db.session.commit()
        except:
            p.last_timestamp = datetime.utcnow()
            print (p.title, " no timestamp, so set to now")
            db.session.add(p)
            db.session.commit()
            pass

update_db()


import datetime, json

from flask import Blueprint, request, jsonify

from admin import admin_config
from backend import db, match_making, utility, slack_util
from backend.league_context import LeagueContext

playerboard_api = Blueprint('playerboard_api', __name__)

@playerboard_api.route('/submit-players', methods=['POST'])
def submit_players():
    players_and_groups = request.get_json().get("players")

    for group, players in players_and_groups.items():
        print(group, players)

        ensure_players_in_db(players)
        update_groupings(group, players)

    today = datetime.datetime.today()
    last_monday = today - datetime.timedelta(days=today.weekday())
    next_monday = (last_monday + datetime.timedelta(days=7)).date()

    league_name = admin_config.get_current_league()
    lctx = LeagueContext.load_from_db(league_name)
    # TODO use the config for sets needed
    match_making.create_matches_for_season(lctx, next_monday, 3, skip_weeks=[], include_byes=False)

    return "We did it boys"

@playerboard_api.route('/get-active-players', methods=['GET'])
def get_active_players():
    players = get_ranked_players()
    return jsonify(players)

@playerboard_api.route('/get-players-from-season', methods=['GET'])
def get_players_from_season():
    league_name = request.args.get("leagueName", default="", type=str)
    season = request.args.get("season", default=0, type=int)
    players = get_ranked_players(league_name, season)
    return jsonify(players)

@playerboard_api.route('/get-all-seasons', methods=['GET'])
def get_all_seasons():
    league_name = request.args.get("leagueName", default="", type=str)
    if not league_name:
        return jsonify([])
    all_seasons = db.get_all_seasons(league_name)
    return jsonify(all_seasons)

@playerboard_api.route('/inactivate-player', methods=['POST'])
def inactivate_player():
    league_name = request.get_json().get("leagueName")
    player_id = request.get_json().get("playerId")

    db.update_grouping(league_name, player_id, '')
    db.set_active(league_name, player_id, False)
    return "success"

@playerboard_api.route('/update-player-grouping-and-orders', methods=['POST'])
def update_player_grouping():
    data = request.get_json()
    league_name = data.get("leagueName")
    grouping = data.get("grouping")
    players = data.get("players")

    db.updating_grouping_and_orders(league_name, players, grouping)
    return "success"

@playerboard_api.route('/add-player', methods=['POST'])
def add_player():
    data = request.get_json()
    league_name = data.get("leagueName")
    player_name = data.get("playerName")
    grouping = data.get("grouping")
    lctx = LeagueContext.load_from_db(league_name)
    slack_id = slack_util.get_slack_id(lctx, player_name)
    if slack_id is None:
        return jsonify({'success': False, 'message': 'Could not find slack id for {}'.format(player_name)})
    try:
        db.add_player(league_name, slack_id, player_name, grouping)
        p = db.get_player_by_id(league_name, slack_id)
        return jsonify({'success': True, 'player': json.dumps(p, default=match_player_serializer)})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)})

@playerboard_api.route('/refresh-users', methods=['POST'])
def refresh_users():
    data = request.get_json()
    league_name = data.get("leagueName")
    lctx = LeagueContext.load_from_db(league_name)
    try:
        users_list = slack_util._get_users_list(lctx, True)
        return jsonify({'success': True, 'totalUsers': len(users_list), 'lastRan': slack_util.last_get_users_date})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)})

@playerboard_api.route('/slack-users-count', methods=['GET'])
def refresh_users_info():
    return jsonify({'success': True, 'totalUsers': len(slack_util.users_list), 'lastRan': slack_util.last_get_users_date})

@playerboard_api.route('/get-deactivated-players', methods=['GET'])
def get_deactivated_players():
    league_name = request.args.get("leagueName", default="", type=str)
    lctx = LeagueContext.load_from_db(league_name)
    return jsonify(slack_util.get_deactivated_slack_ids(lctx))

def ensure_players_in_db(players):
    league_name = admin_config.get_current_league()  # TODO pass league name in
    existing_players_dict = dict()
    existing_players = db.get_players(league_name)

    for existing_player in existing_players:
        existing_players_dict[existing_player.name] = existing_player

    players_to_add = []
    for player in players:
        if player['name'] not in existing_players_dict:
            print("FOUND ONE", player['name'])
            players_to_add.append(player)

    if len(players_to_add) == 0:
        return

    # TODO move this to slack util if we're gonna keep it
    lctx = LeagueContext.load_from_db(league_name)
    users = slack_util._get_users_list(lctx)
    user_map = {}
    for user in users:
        for player in players_to_add:
            if user['profile']['real_name'].startswith(player['name']) and not user['deleted']:
                user_map[player['name']] = user['id']
                db.add_player(league_name, user['id'], player['name'], player['group'])

def update_groupings(group, players):
    league_name = admin_config.get_current_league()
    existing = db.get_players(league_name)

    for player in players:
        for e in existing:
            if e.name == player['name']:
                if group == 'Trash':
                    db.update_grouping(league_name, e.slack_id, "")
                    db.set_active(league_name, e.slack_id, False)
                else:
                    db.update_grouping(league_name, e.slack_id, group)
                    db.set_active(league_name, e.slack_id, True)

def get_ranked_players(league_name=None, season=None):
    league_name = league_name or admin_config.get_current_league()
    if season is None:
        season = db.get_current_season(league_name)
    all_matches = db.get_matches_for_season(league_name, season)
    all_players = db.get_players(league_name)

    groups = sorted(list(set([m.grouping for m in all_matches])))
    return_players = []

    for group in groups:
        group_matches = [m for m in all_matches if m.grouping == group]

        players = utility.gather_scores(group_matches)

        for player in players:
            if player['player_id'] is None:
                continue

            name = [p.name for p in all_players if p.slack_id is not None and p.slack_id == player['player_id']][0]
            return_players.append(
                {
                    'name': name,
                    'slack_id': player['player_id'],
                    'sets_won': player['s_w'],
                    'sets_lost': player['s_l'],
                    'games_won': player['m_w'],
                    'games_lost': player['m_l'],
                    'group': group
                }
            )

    return return_players

def match_player_serializer(o):
    if isinstance(o, (datetime.date, datetime.datetime)):
        return o.isoformat()
    return o.__dict__


import pickle
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms

expFolderName = '/home/zhangzeqing/ur5_ws/src/ur_water_bucket/data'
fileName = '/bucket_targeted_amount_0.6_saved_trajs.pkl'
save_path = expFolderName+'/fig'

f = open(expFolderName+fileName,'rb')
data = pickle.load(f)
# print(data)
# print(data['loader_type'])

paths_xyz = data['loader_pos_trajs']
paths_theta = data['loader_rot_trajs']
num_path = np.shape(paths_xyz)[0]
num_traj = data['num_episodes']
path_length = data['episode_length']

# region
# for path_id in range(num_path):
#     fig = plt.figure(figsize = (10,10))
#     ax = plt.axes(projection='3d')

#     cur_path_xyz = paths_xyz[path_id,:,:]
#     # plot path
#     ax.plot3D(cur_path_xyz[:,0],cur_path_xyz[:,2],cur_path_xyz[:,1])
#     # start/goal
#     ax.scatter(cur_path_xyz[0,0],cur_path_xyz[0,2],cur_path_xyz[0,1], marker="o", color="red", s = 40,label="start")
#     ax.scatter(cur_path_xyz[-1,0],cur_path_xyz[-1,2],cur_path_xyz[-1,1], marker="x", color="red", s = 40,label="goal")

#     ax.set_title(f'{path_id}-th path')
#     # Set axes label
    # ax.axis('scaled')
    # ax.set_xlabel('x', labelpad=5)
    # ax.set_ylabel('y', labelpad=5)
    # ax.set_zlabel('z', labelpad=5)
    # ax.view_init(0 , 180)
#     plt.legend()
#     plt.show()
#     # plt.savefig(save_path+f'/{path_id}th_path' + '.png')
# endregion

width = 0.05
height = 0.025
position_x = .1
position_y = .4
# extent = [position_x, position_x+width, position_y, position_y+height] # left, right, bottom, top
init_color_matrix = [[1.,0.], [1.,0.]]

for path_id in range(num_path):
    fig = plt.figure(figsize = (10,10))
    ax = plt.axes()
    # ax = plt.axes(projection='3d')
    # ax.view_init(0 , 180)

    # path xyz R^{75*3}
    cur_path_xyz = paths_xyz[path_id,:,:]
    # theta (rad) R^{75*1}
    rot_traj = paths_theta[path_id,:,:]

    for i in range(path_length):
        # in Shiyu's frame
        # 3D plot path x,y,z
        # ax.plot3D(cur_path_xyz[i,0],cur_path_xyz[i,2],cur_path_xyz[i,1],'.')
        # 2D plot path y,z
        ax.plot(cur_path_xyz[i,2],cur_path_xyz[i,1],'.')

        # plot bucket model (rectangle)
        position_x = cur_path_xyz[i,2]
        position_y = cur_path_xyz[i,1]
        angle_deg = np.degrees(rot_traj[i,0])
        extent = [position_x, position_x+width, position_y-height/2, position_y+height/2] # left, right, bottom, top
        car_img = ax.imshow(init_color_matrix, cmap = plt.cm.Greens, interpolation = 'bicubic', extent=extent)
        trans_data = mtransforms.Affine2D().rotate_deg_around(position_x, position_y, angle_deg) + ax.transData
        car_img.set_transform(trans_data)

        # start/goal
        ax.scatter(cur_path_xyz[0,2],cur_path_xyz[0,1], marker="o", color="red", s = 40,label="start")
        ax.scatter(cur_path_xyz[-1,2],cur_path_xyz[-1,1], marker="x", color="red", s = 40,label="goal")

        ax.axis('scaled')
        ax.set_xlim([-0.2,0.3])
        ax.set_ylim([0.1,0.7])
        ax.set_xlabel('z', labelpad=5)
        ax.set_ylabel('y', labelpad=5)


from unittest import TestCase
from assetsstore.assets import FileAssets
import glob
import os
import logging

class AsssetsLocalTest(TestCase):

    def setUp(self):
        self.maxDiff = None
        logging.basicConfig(level=logging.INFO)

    def test_no_asset_store_set(self):
        os.environ["ASSET_STORE"] = ""
        with self.assertRaises(Exception) as context:
            FileAssets.get_asset()
        print(context.exception)
        self.assertTrue("There is no asset" in str(context.exception))

    def test_upload_and_download_from_local(self):
        # get set store
        os.environ["ASSET_STORE"] = "LocalFiles"

        os.environ["ASSET_ACCESS_KEY_ID"] = ""
        os.environ["ASSET_SECRET_ACCESS_KEY"] = ""
        os.environ["ASSET_LOCATION"] = "assetsstore/tests/results/remote/"
        os.environ["ASSET_REGION"] = ""

        os.environ["LOCAL_STORE"] = "assetsstore/tests/fixtures/"
        handler = FileAssets.get_asset()
        self.assertEqual("Uploaded", handler.put_file("test.txt"))

        os.environ["LOCAL_STORE"] = "assetsstore/tests/results/"
        handler = FileAssets.get_asset()
        self.assertEqual("Downloaded", handler.get_file("test.txt"))

        # get again to check if it exists
        self.assertEqual("Exists", handler.get_file("test.txt"))

        # delete remote file
        self.assertEqual("Deleted", handler.del_file("test.txt"))

        # delete local copy
        self.assertEqual("Deleted", handler.del_local_file("test.txt"))

    def tearDown(self):
        for file in glob.glob('results/*'):
            if '.gitkeep' not in file:
                os.remove(file)
        for file in glob.glob('results/remote/*'):
            if '.gitkeep' not in file:
                os.remove(file)


import tensorflow as tf
from utils import *
from AlexNet import Alexnet
import os
import h5py
from sklearn.metrics import confusion_matrix
from sklearn.metrics import precision_recall_curve
import matplotlib.pyplot as plt

save_dir = './checkpoints/'

def test(image_size=32,
         num_classes=2,
         num_channels=1):
    # load the test data
    os.environ["CUDA_VISIBLE_DEVICES"] = "2"
    X_train, Y_train, X_valid, Y_valid = load_data(dim=2,
                                                   normalize='unity_based',
                                                   one_hot=True)
    y_true = np.argmax(Y_valid, axis=1)

    # load the model
    model = Alexnet(num_classes, image_size, num_channels)
    model.inference().accuracy_func().loss_func().train_func().pred_func()

    saver = tf.train.Saver()
    save_path = os.path.join(save_dir, 'model_86.91_71')

    with tf.Session() as sess:
        saver.restore(sess, save_path)
        print("Model restored.")
        y_pred_prob, acc_test, loss_test = validation(sess, model, X_valid, Y_valid, 10, compute_prob=True)
        print("Test loss: {0:.2f}, Test accuracy: {1:.01%}"
              .format(loss_test, acc_test))

    y_pred = np.argmax(y_pred_prob, 1)
    print(confusion_matrix(y_true, y_pred))
    Precision, Recall, thresholds = precision_recall_curve(y_true, y_pred_prob[:, 1])

    # Plot Precision-Recall curve
    fig = plt.figure()
    ax1 = fig.add_subplot(1, 1, 1)
    plt.plot(Recall, Precision, lw=2, color='navy', label='Precision-Recall curve')
    ax1.set_xlabel('Recall', size=18)
    ax1.set_ylabel('Precision', size=18)
    ax1.tick_params(labelsize=18)
    plt.ylim([0.5, 1.05])
    plt.xlim([0.0, 1.0])
    plt.show()

    # Compute precision and recall
    precision_recall(y_true, y_pred)

    # save the results
    h5f = h5py.File('alexnet_2d_results.h5', 'w')
    h5f.create_dataset('Precision', data=Precision)
    h5f.create_dataset('Recall', data=Recall)
    h5f.create_dataset('y_pred_prob', data=y_pred_prob)
    h5f.create_dataset('thresholds', data=thresholds)
    h5f.create_dataset('y_pred', data=y_pred)
    h5f.create_dataset('y_true', data=y_true)
    h5f.close()

if __name__ == '__main__':
    test(image_size=32,
         num_classes=2,
         num_channels=1)


from typing import List

from poif.dataset.meta import MetaCollection
from poif.dataset.object.base import DataSetObject
from poif.dataset.operation.meta_provider.base import MetaProvider
from poif.typing import RelFilePath

class CocoMetaProvider(MetaProvider):
    def __init__(self, annotation_file: RelFilePath):
        super().__init__()
        self.annotation_file = annotation_file

    def provide_meta(self, objects: List[DataSetObject], old_meta: MetaCollection) -> MetaCollection:
        annotation_file = None
        for ds_object in objects:
            if ds_object.relative_path == self.annotation_file:
                annotation_file = ds_object

        if annotation_file is None:
            raise Exception("Annotation file not found in objects")

        annotation_data = annotation_file.get_parsed()

        category_mapping = {}
        for category in annotation_data["categories"]:
            category_mapping[category["id"]] = category["name"]

        old_meta.index_to_label = category_mapping
        return old_meta


#!/usr/bin/env python3

# ---------------------------------------------------------------------------------------
# This script lists AirFrance-KLM flights (including price) from an origin
# to a destination using provided date for outbound flight and return flight
#
# Author: Christophe Pauliat
#
# Prereq: register as a developer at https://docs.airfranceklm.com and get your api key
#
# API docs:
# - https://docs.airfranceklm.com/docs/read/opendata/offers/POST_availableoffers_v1
# - https://docs.airfranceklm.com/docs/read/opendata/offers/Errors_Code
#
# Versions:
#     2022-01-04: initial version
#     2022-01-11: Add option --csv
# ---------------------------------------------------------------------------------------

# ---------- imports
import requests
import json
import sys
import argparse
from datetime import datetime

# ---------- Variables
my_api_key          = "xxxxxxxxxxxx"     # register for free at https://docs.airfranceklm.com/docs/read/opendata/offers to get your API key
default_cabin       = "ECONOMY"          # Can contain ECONOMY or PREMIUM or BUSINESS or FIRST or ALL
default_airline     = "AF"               # AF or KL
lowest_price        = 9999
highest_price       = 0
decile1_max_price   = 0

# ---------- Colors for output
# see https://misc.flogisoft.com/bash/tip_colors_and_formatting to customize
COLOR_YELLOW = "\033[93m"
COLOR_RED    = "\033[91m"
COLOR_GREEN  = "\033[32m"
COLOR_NORMAL = "\033[39m"
COLOR_CYAN   = "\033[96m"
COLOR_BLUE   = "\033[94m"
COLOR_GREY   = "\033[90m"

COLOR_TITLE         = COLOR_GREEN
COLOR_DATA          = COLOR_BLUE
COLOR_ITINERARY     = COLOR_YELLOW
COLOR_PRICE1        = COLOR_RED
COLOR_PRICE2        = COLOR_CYAN
COLOR_LINKS         = COLOR_GREY
COLOR_LOWEST_PRICE  = COLOR_GREEN
COLOR_HIGHEST_PRICE = COLOR_RED
COLOR_DECILE1_PRICE = COLOR_YELLOW

# ---------- Functions

# ---- Disable colored output
def disable_colored_output():
  global COLOR_NORMAL
  global COLOR_TITLE
  global COLOR_DATA
  global COLOR_ITINERARY
  global COLOR_PRICE1
  global COLOR_PRICE2
  global COLOR_LINKS
  global COLOR_LOWEST_PRICE
  global COLOR_HIGHEST_PRICE
  global COLOR_DECILE1_PRICE

  COLOR_NORMAL        = ""
  COLOR_TITLE         = ""
  COLOR_DATA          = ""
  COLOR_ITINERARY     = ""
  COLOR_PRICE1        = ""
  COLOR_PRICE2        = ""
  COLOR_LINKS         = ""
  COLOR_LOWEST_PRICE  = ""
  COLOR_HIGHEST_PRICE = ""
  COLOR_DECILE1_PRICE = ""

# ---- Get data using REST APIs
def post_request(origin, destination, date_voyage_aller, date_voyage_retour, airline, cabin):
  url = "https://api.airfranceklm.com/opendata/offers/v1/available-offers/all"

  payload = json.dumps({
    "commercialCabins": [cabin],
    "passengerCount": {
      "ADT": 1,
      "CHD": 0,
      "INF": 0
    },
    "requestedConnections": [
      {
        "departureDate": date_voyage_aller,
        "origin": {
          "airport": {
            "code": origin
          }
        },
        "destination": {
          "airport": {
            "code": destination
          }
        }
      },
      {
        "departureDate": date_voyage_retour,
        "origin": {
          "airport": {
            "code": destination
          }
        },
        "destination": {
          "airport": {
            "code": origin
          }
        }
      }
    ]
  })

  headers = {
    'Content-Type': 'application/json',
    'Accept-Language': 'en-US',
    'AFKL-TRAVEL-Host': airline,
    'AFKL-TRAVEL-Country': 'FR',
    'api-key': my_api_key,
  }

  response = requests.request("POST", url, headers=headers, data=payload)
  mydict   = json.loads(response.text)
  return mydict

# ---- Save all data to file
def save_data_to_file(mydict, filename):
  with open(filename, 'w') as file:
    file.write(json.dumps(mydict, indent=4, sort_keys=False))

# ---- Load all data from file
def load_data_from_file(filename):
  with open(filename, 'r') as file:
    mydict = json.load(file)
  return mydict

# ---- Display taxes breakdown
def display_tax_breakdown(url):
  # print (url)
  # return

  payload = {}

  headers = {
    'Content-Type': 'application/json',
    'Accept-Language': 'en-US',
    'AFKL-TRAVEL-Host': 'AF',
    'AFKL-TRAVEL-Country': 'FR',
    'api-key': my_api_key,
  }

  response = requests.request("GET", url, headers=headers, data=payload)
  mydict   = json.loads(response.text)

  print (COLOR_NORMAL+f"---------- "+COLOR_ITINERARY+"taxes breakdown"+COLOR_NORMAL+" (total taxes = "+COLOR_PRICE2+f"{mydict['price']['totalTaxes']:7.2f}"+COLOR_NORMAL+")")
  taxes = mydict['price']['pricePerPassengerTypes'][0]['taxes']
  for tax in taxes:
    title = f"{tax['code']} ({tax['name']})"
    print (f"{title:54s} : {tax['amount']:7.2f}")
  try:
    yr_tax = mydict['price']['pricePerPassengerTypes'][0]['airTransportationSurcharges'][0]
    title = f"{yr_tax['code']} ({yr_tax['name']})"
    print (f"{title:54s} : {yr_tax['amount']:7.2f}")
  except:
    pass

# ---- Display all data in JSON format
def display_raw_data(mydict):
  print (json.dumps(mydict, indent=4, sort_keys=False))

# ---- Get lowest and highest prices
def get_lowest_and_highest_prices(mydict):
  global lowest_price
  global highest_price
  global decile1_max_price

  try:
    itineraries = mydict["itineraries"]
    for itinerary in itineraries:
      price       = itinerary["flightProducts"][0]["price"]["totalPrice"]
      if price < lowest_price:
        lowest_price = price
      if price > highest_price:
        highest_price = price
    decile1_max_price = lowest_price + (highest_price - lowest_price) / 10
  except:
    pass

# ---- Display only relevant data in formatted output
def display_formatted_data(mydict):
  num_iti = 0
  connection_max_segments = 0
  try:
    itineraries = mydict["itineraries"]

    # First, compute max number of segments for connection1 (outbound flights) and connection2 (return flights)
    for itinerary in itineraries:
      connections = itinerary["connections"]
      connection1 = connections[0]
      connection2 = connections[1]
      if len(connection1["segments"]) > connection_max_segments:
        connection_max_segments = len(connection1["segments"])
      if len(connection2["segments"]) > connection_max_segments:
        connection_max_segments = len(connection2["segments"])

    # Then display information
    for itinerary in itineraries:
      num_iti += 1
      price       = itinerary["flightProducts"][0]["price"]["totalPrice"]
      currency    = itinerary["flightProducts"][0]["price"]["currency"]
      connections = itinerary["connections"]

      print (COLOR_PRICE1+"======================================== "+COLOR_ITINERARY+f"Itinerary {num_iti}"+COLOR_NORMAL+" : Price = "+COLOR_PRICE1+f"{price:.2f} {currency}  ", end="")
      if price == lowest_price:
        print (COLOR_LOWEST_PRICE+" ======== LOWEST PRICE ========")
      elif price == highest_price:
        print (COLOR_HIGHEST_PRICE+" ======== HIGHEST PRICE ========")
      elif price <= decile1_max_price:
        print (COLOR_DECILE1_PRICE+" ======== 1st DECILE PRICE ========")
      else:
        print (COLOR_NORMAL)
      print (COLOR_NORMAL)

      num_con = 0
      for connection in connections:
        price_connection = itinerary["flightProducts"][0]["connections"][num_con]["price"]["totalPrice"]
        num_con += 1
        segments = connection["segments"]
        if num_con == 1 and len(segments) == 1:
          name_con = "Outbound flight : DIRECT"
        elif num_con == 1 and len(segments) > 1:
          name_con = "Outbound flights : WITH CONNECTION"
        elif num_con > 1 and len(segments) == 1:
          name_con = "Return flight : DIRECT"
        elif num_con > 1 and len(segments) > 1:
          name_con = "Return flights : WITH CONNECTION"

        connection_title = COLOR_NORMAL+"---------- "+COLOR_ITINERARY+f"{name_con:34s}"+COLOR_NORMAL+" : price = "+COLOR_PRICE2+f"{price_connection:7.2f} {currency:3s}"+COLOR_NORMAL
        # connection_title uses 67 characters so add 17 spaces to reach 84 characters
        print (f"{connection_title}{' ':17s}",end="")
        if connection_max_segments == 3:
          print (f"{' ':42s}",end="")
        print ("   ",end="")
      print ("")

      for connection in connections:
        segments = connection["segments"]
        for segment in segments:
          line1 = COLOR_TITLE+"Flight   : "+COLOR_DATA+f"{segment['marketingFlight']['carrier']['code']}{segment['marketingFlight']['number']}"
          # line1 uses 17 characters so add 25 spaces to reach 42 characters
          print (f"{line1}{' ':25s}",end="")
        # if less segments than connection_max_segments, add spaces for each missing segment
        for _ in range(connection_max_segments - len(segments)):
          print (f"{' ':42s}",end="")
        print (COLOR_LINKS+" | "+COLOR_NORMAL,end="")
      print ("")

      for connection in connections:
        segments = connection["segments"]
        for segment in segments:
          line2 = COLOR_TITLE+"Departure: "+COLOR_DATA+f"{segment['origin']['code']} at {segment['departureDateTime']}"
          # line2 uses 37 characters so add 5 spaces to reach 42 characters
          print (f"{line2}{' ':5s}",end="")
        # if less segments than connection_max_segments, add spaces for each missing segment
        for _ in range(connection_max_segments - len(segments)):
          print (f"{' ':42s}",end="")
        print (COLOR_LINKS+" | "+COLOR_NORMAL,end="")
      print ("")

      for connection in connections:
        segments = connection["segments"]
        for segment in segments:
          line3 = COLOR_TITLE+"Arrival  : "+COLOR_DATA+f"{segment['destination']['code']} at {segment['arrivalDateTime']}"
          # line3 uses 37 characters so add 5 spaces to reach 42 characters
          print (f"{line3}{' ':5s}",end="")
        # if less segments than connection_max_segments, add spaces for each missing segment
        for _ in range(connection_max_segments - len(segments)):
          print (f"{' ':42s}",end="")
        print (COLOR_LINKS+" | "+COLOR_NORMAL,end="")
      print ("")

      for connection in connections:
        segments = connection["segments"]
        for segment in segments:
          line4 = COLOR_TITLE+"Aircraft : "+COLOR_DATA+f"{segment['marketingFlight']['operatingFlight']['equipmentType']['name']:26s}"
          # line3 uses 37 characters so add 5 spaces to reach 42 characters
          print (f"{line4}{' ':5s}",end="")
        # if less segments than connection_max_segments, add spaces for each missing segment
        for _ in range(connection_max_segments - len(segments)):
          print (f"{' ':42s}",end="")
        print (COLOR_LINKS+" | "+COLOR_NORMAL,end="")
      print ("")

      # If requested, display links for cabin plans
      if args.cabin_plan:
        print ("")
        for connection in connections:
          segments = connection["segments"]
          for segment in segments:
            try:
              flight_number = f"{segment['marketingFlight']['carrier']['code']}{segment['marketingFlight']['number']}"
              link          = f"{segment['marketingFlight']['operatingFlight']['equipmentType']['_links']['information']['href']}"
              print (COLOR_TITLE+f"Cabin plan {flight_number}: "+COLOR_LINKS+f"{link}")
            except:
              pass

      print (COLOR_NORMAL)

      # If requested, display tax breakdown for the itinerary
      if args.tax_breakdown:
        offer_link = itinerary["flightProducts"][0]["_links"]["taxBreakdown"]["href"]
        display_tax_breakdown(offer_link)
        print (COLOR_NORMAL)

  except:
    # No flight available
    print ("No outbound or return flight available !")

# ---- Display minimal data
def display_minimal_data(mydict):
  num_iti = 0
  try:
    itineraries = mydict["itineraries"]
    for itinerary in itineraries:
      num_iti += 1
      price       = itinerary["flightProducts"][0]["price"]["totalPrice"]
      currency    = itinerary["flightProducts"][0]["price"]["currency"]
      connections = itinerary["connections"]

      if price == lowest_price:
        COLOR = COLOR_LOWEST_PRICE
      elif price == highest_price:
        COLOR = COLOR_HIGHEST_PRICE
      elif price <= decile1_max_price:
        COLOR = COLOR_DECILE1_PRICE
      else:
        COLOR = COLOR_NORMAL

      print (COLOR+f"Itinerary {num_iti:3d} : Price = {price:7.2f} {currency}      ",end="")
      num_con = 0
      for connection in connections:
        price_connection = itinerary["flightProducts"][0]["connections"][num_con]["price"]["totalPrice"]
        segments         = connection["segments"]
        connection_name  = segments[0]['departureDateTime']
        num_con += 1

        for segment in segments:
          connection_name = connection_name + "-" + segment['marketingFlight']['carrier']['code'] + segment['marketingFlight']['number']

        print (f"{connection_name:41s}: {price_connection:7.2f} {currency}      ", end="")

      if price == lowest_price:
        print ("LOWEST PRICE")
      elif price == highest_price:
        print ("HIGHEST PRICE")
      elif price <= decile1_max_price:
        print ("1st DECILE PRICE")
      else:
        print (COLOR_NORMAL)

  except:
    # No flight available
    print ("No outbound or return flight available !")

# ---- Display CSV data
def display_csv_data(mydict):
  current_date = datetime.today().strftime('%Y-%m-%d')
  try:
    itineraries = mydict["itineraries"]
    for itinerary in itineraries:
      itinerary_price = itinerary["flightProducts"][0]["price"]["totalPrice"]
      connections     = itinerary["connections"]

      itinerary_name = ""
      connection_name  = []
      connection_price = []
      num_con = 0
      for connection in connections:
        connection_price.append(itinerary["flightProducts"][0]["connections"][num_con]["price"]["totalPrice"])
        connection_array = []
        num_con += 1

        for segment in connection["segments"]:
          connection_array.append(segment['marketingFlight']['carrier']['code'] + segment['marketingFlight']['number'])

        connection_name.append("-".join(connection_array))

      itinerary_name = f"{connection_name[0]}___{connection_name[1]}"

      print (f"{current_date},{itinerary_name},{itinerary_price:.2f},{connection_name[0]},{connection_price[0]:.2f},{connection_name[1]},{connection_price[1]:.2f}")
  except:
    # No flight available
    print (f"{current_date},No flight")

# ========== Main

# ---- parse arguments
parser = argparse.ArgumentParser(description = "Get Flights offers from Air-France-KLM using REST APIs")
group1  = parser.add_mutually_exclusive_group()
group1.add_argument("-r", "--raw", help="displays raw formatted data (JSON)", action="store_true")
group1.add_argument("-s", "--short", help="displays minimal data (short)", action="store_true")
group1.add_argument("-c", "--csv", help="displays minimal data in CSV format", action="store_true")
group2  = parser.add_mutually_exclusive_group()
group2.add_argument("-lf", "--load_from", help="read data from file instead of API request")
group2.add_argument("-sf", "--save_to", help="write raw data to file")
parser.add_argument("-o", "--orig", help="origin airport (3 letters code).")
parser.add_argument("-d", "--dest", help="destination airport (3 letters code).")
parser.add_argument("-od", "--odate", help="date for outward flight (YYYY-MM-DD)")
parser.add_argument("-rd", "--rdate", help="date for return flight (YYYY-MM-DD)")
parser.add_argument("-al", "--airline", help=f"airline code (AF or KL). Default is {default_airline}.", choices=["AF","KL"])
parser.add_argument("-nc", "--nocolor", help="Disable colored output", action="store_true")
parser.add_argument("-tx", "--tax_breakdown", help="Display taxes breakdown", action="store_true")
parser.add_argument("-cp", "--cabin_plan", help="Display cabin plans links", action="store_true")
parser.add_argument("-cb", "--cabin", help=f"cabin (ECONOMY or PREMIUM or BUSINESS or FIRST). Default is {default_cabin}.", choices=["ECONOMY","PREMIUM","BUSINESS","FIRST"])
args = parser.parse_args()

if args.load_from and (args.orig or args.dest or args.odate or args.rdate):
  parser.error("-lf/--load_from cannot be used with -o/--orig, -d/--dest, -od/--odate or -rd/--rdate !")

if args.load_from == None and (args.orig == None or args.dest == None or args.odate == None or args.rdate == None):
  parser.error("Arguments -o/--orig, -d/--dest, -od/--odate and -rd/--rdate are mandatory if -lf/--load_form not provided !")

if args.nocolor:
  disable_colored_output()

# ---- get data from live API request or from saved file
if args.load_from:
  mydict = load_data_from_file(args.load_from)
else:
  if args.airline:
    airline = args.airline.upper()
  else:
    airline = default_airline
  if args.cabin:
    cabin = args.cabin.upper()
  else:
    cabin = default_cabin
  mydict = post_request(origin=args.orig.upper(), destination=args.dest.upper(), date_voyage_aller=args.odate, date_voyage_retour=args.rdate, airline=airline, cabin=cabin)
  if args.save_to:
    save_data_to_file(mydict, args.save_to)

# ---- display data with selected format
get_lowest_and_highest_prices(mydict)

if args.raw:
  display_raw_data(mydict)
elif args.short:
  display_minimal_data(mydict)
elif args.csv:
  display_csv_data(mydict)
else:
  display_formatted_data(mydict)

# ---- happy end
exit(0)


# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""Update_deployment_configs

Previously we had bad deployment config validation

Revision ID: 54e844ebfbc3
Revises: 3177d36ea270
Create Date: 2016-07-24 14:53:39.323105

"""

from alembic import op  # noqa
import sqlalchemy as sa  # noqa

from rally.common.db import sa_types
from rally import exceptions

# revision identifiers, used by Alembic.
revision = "54e844ebfbc3"
down_revision = "3177d36ea270"
branch_labels = None
depends_on = None

deployments_helper = sa.Table(
    "deployments",
    sa.MetaData(),
    sa.Column("id", sa.Integer, primary_key=True, autoincrement=True),
    sa.Column(
        "config",
        sa_types.MutableJSONEncodedDict,
        default={},
        nullable=False,
    )
)

def _check_user_entry(user):
    """Fixes wrong format of users."""
    if "tenant_name" in user:
        keys = set(user.keys())
        if keys == {"username", "password", "tenant_name",
                    "project_domain_name", "user_domain_name"}:
            if (user["user_domain_name"] == ""
                    and user["project_domain_name"] == ""):
                # it is credentials of keystone v2 and they were created
                # --fromenv
                del user["user_domain_name"]
                del user["project_domain_name"]
                return True
            else:
                # it looks like keystone v3 credentials
                user["project_name"] = user.pop("tenant_name")
                return True

def upgrade():
    connection = op.get_bind()
    for deployment in connection.execute(deployments_helper.select()):
        conf = deployment.config
        if conf["type"] != "ExistingCloud":
            continue

        should_update = False

        if _check_user_entry(conf["admin"]):
            should_update = True
        if "users" in conf:
            for user in conf["users"]:
                if _check_user_entry(user):
                    should_update = True

        if conf.get("endpoint_type") == "public":
            del conf["endpoint_type"]
            should_update = True

        if should_update:
            connection.execute(
                deployments_helper.update().where(
                    deployments_helper.c.id == deployment.id).values(
                    config=conf))

def downgrade():
    raise exceptions.DowngradeNotSupported()


import cv2
import numpy as np
import os
import matplotlib.pyplot as plt
from collections import Counter

dim = (300,300)
ChainCode = []
TamanhoSinal = []
tamanhoImagem = 8
contar = 0
imagemConta = 1
path = "./number1"

def recuperar(imagem, prox_ponto, valor):
    if valor==0:
        imagem[prox_ponto[0], prox_ponto[1]] = 255
        return (prox_ponto[0]-1, prox_ponto[1])

    elif valor==1:
        imagem[prox_ponto[0], prox_ponto[1]] = 255
        return (prox_ponto[0], prox_ponto[1]+1)

    elif valor==2:
        imagem[prox_ponto[0], prox_ponto[1]] = 255
        return (prox_ponto[0]+1, prox_ponto[1])

    elif valor==3:
        imagem[prox_ponto[0], prox_ponto[1]] = 255
        return (prox_ponto[0], prox_ponto[1]-1)

    else:
        return prox_ponto

def verifique(imagem, ponto, conectividade):
    global contar
    if conectividade == 4:
        if imagem[ponto[0]-1, ponto[1]] == 255:
            imagem[ponto[0]-1,ponto[1]] = 0
            ChainCode.append(0)
            TamanhoSinal.append(contar)
            contar += 1
            return (ponto[0]-1, ponto[1])
        elif imagem[ponto[0], ponto[1]+1] == 255:
                imagem[ponto[0],ponto[1]+1] = 0
                ChainCode.append(1)
                TamanhoSinal.append(contar)
                contar += 1
                return (ponto[0], ponto[1]+1)
        elif imagem[ponto[0]+1, ponto[1]] == 255:
                imagem[ponto[0]+1,ponto[1]] = 0
                ChainCode.append(2)
                TamanhoSinal.append(contar)
                contar += 1
                return (ponto[0]+1, ponto[1])
        elif imagem[ponto[0], ponto[1]-1] == 255:
                imagem[ponto[0],ponto[1]-1] = 0
                ChainCode.append(3)
                TamanhoSinal.append(contar)
                contar += 1
                return (ponto[0], ponto[1]-1)
        else:
            print('none')
    else:
        return ponto

def normalizaImagem(v):
    v = (v - v.min()) / (v.max() - v.min())
    resultado = (v * 255).astype(np.uint8)
    return resultado

for r, d, f in os.walk(path):
    tamanhoImagem = len(f)
    for filename in f:
        imagem = cv2.imread(os.path.join(path, filename))
        imagem = cv2.resize(imagem, dim, interpolation=cv2.INTER_AREA)
        imagemBin = 255 - imagem[:,:,0]

        novaImagem = np.zeros(np.shape(imagemBin))
        kernel = np.ones((3,3), np.uint8)
        novaImagem = normalizaImagem((imagemBin>100)*1)

        imCopy = np.copy(novaImagem)
        imPlot = np.zeros(np.shape(imagem))
        imPlot[:,:,0] = imPlot[:,:,1] = imPlot[:,:,2] = imCopy

        novaImagem = cv2.dilate(novaImagem, kernel, iterations=1) - novaImagem
        novaImagem = cv2.resize(novaImagem, dim, interpolation=cv2.INTER_AREA)

        #cv2.imshow('Imagem', novaImagem)
        #cv2.waitKey(0)

        max_xy = np.where(novaImagem == 255)
        #print (np.shape(novaImagem))

        novaImagemRGB = np.zeros(np.shape(imagem))
        novaImagemRGB[:,:,0] = novaImagemRGB[:,:,1] = novaImagemRGB[:,:,2] = novaImagem

        cv2.circle(novaImagemRGB, (max_xy[1][0], max_xy[0][0]), int(3), (0,0,255), 2)
        iniciarPonto = (max_xy[0][0], max_xy[1][0])
        ponto = verifique(novaImagem, iniciarPonto, 4)

        while(ponto!=iniciarPonto):
            cv2.circle(imPlot, (ponto[1], ponto[0]), int(3), (0,0,255), 6)
            cv2.imshow('Imagem', imPlot)
            cv2.waitKey(1)

            cv2.circle(imPlot, (ponto[1], ponto[0]), int(3), (0,255,255), 4)
            ponto = verifique(novaImagem, ponto, 4)

        res = dict(Counter( ChainCode ))
        imagem_retornada = np.zeros(np.shape(imPlot))
        ponto_in = (1, res[1])
        prox_ponto = ponto_in

        #imagemRetornada = np.zeros((int(res[0]*1.2), int((res[1]+res[3])*1.2) ))

        for valor in ChainCode:
            prox_ponto = recuperar(imagem_retornada, prox_ponto, valor)
            cv2.imshow('Imagem Retornada', imagem_retornada)
            cv2.waitKey(1)

        print(ChainCode)
        plt.subplot(tamanhoImagem, 1, imagemConta)
        plt.plot(ChainCode)
        imagemConta += 1
        ChainCode=[]
    plt.show()