from imutils import face_utils
import numpy as np
import dlib
import cv2
import sys
import binascii
import struct
from PIL import Image, ImageDraw
import scipy
import scipy.misc
import scipy.cluster
from sys import argv
import matplotlib.pyplot as plt

def apply_lipstick(img, rgb):
    if(len(a)):
        name, (i, j)=a[0]
        points= []

        for (x, y) in shape[i:j]:
            points.append([x,y])
        points= np.reshape(points, (-1, 1, 2))
        cv2.fillPoly(img, [points], rgb, 8)

    return img, points

def get_dominant_colour(img_path):
    try:
        NUM_CLUSTERS = 5
        im = Image.open(img_path)
        #im = im.resize((150, 150))      # optional, to reduce time
        ar = np.asarray(im)
        shape = ar.shape
        ar = ar.reshape(scipy.product(shape[:2]), shape[2]).astype(float)
        codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS)
        vecs, dist = scipy.cluster.vq.vq(ar, codes)         # assign codes
        counts, bins = scipy.histogram(vecs, len(codes))    # count occurrences
        index_max = scipy.argmax(counts)                    # find most frequent
        peak = codes[index_max]
        colour = binascii.hexlify(bytearray(int(c) for c in peak)).decode('ascii')
        r = int(peak[0])
        g = int(peak[1])
        b = int(peak[2])
        bgr = (b, g, r)
        return bgr
    except:
        pass
    return (-1,-1,-1)

# define our function for preparing mask
def prepare_mask(polygon, image):
    """Returns binary mask based on input polygon presented as list of coordinates of vertices
    Params:
        polygon (list) - coordinates of polygon's vertices. Ex: [(x1,y1),(x2,y2),...] or [x1,y1,x2,y2,...]
        image (numpy array) - original image. Will be used to create mask of the same size. Shape (H, W, C).
    Output:
        mask (numpy array) - boolean mask. Shape (H, W).
    """
    # create an "empty" pre-mask with the same size as original image
    width = image.shape[1]
    height = image.shape[0]
    mask = Image.new('L', (width, height), 0)
    # Draw your mask based on polygon
    ImageDraw.Draw(mask).polygon(polygon, outline=1, fill=1)
    # Covert to np array
    mask = np.array(mask).astype(bool)
    return mask

def compute_histogram(mask, image):
    """Returns histogram for image region defined by mask for each channel
    Params:
        image (numpy array) - original image. Shape (H, W, C).
        mask (numpy array) - boolean mask. Shape (H, W).
    Output:
        list of tuples, each tuple (each channel) contains 2 arrays: first - computed histogram, the second - bins.

    """
    # Apply binary mask to your array, you will get array with shape (N, C)
    region = image[mask]

    red = np.histogram(region[..., 0].ravel(), bins=256, range=[0, 256])
    green = np.histogram(region[..., 1].ravel(), bins=256, range=[0, 256])
    blue = np.histogram(region[..., 2].ravel(), bins=256, range=[0, 256])

    return [red, green, blue]

def plot_histogram(histograms):
    """Plots histogram computed for each channel.
    Params:
        histogram (list of tuples) - [(red_ch_hist, bins), (green_ch_hist, bins), (green_ch_hist, bins)]
    """

    colors = ['r', 'g', 'b']
    for hist, ch in zip(histograms, colors):
        plt.bar(hist[1][:256], hist[0], color=ch)

Model_PATH =Model_PATH = "C:\\Vivekanandan\\ServiceTransformation\\Web\DigitalAssurance\\Content\\ImageComparison\\shape_predictor_68_face_landmarks.dat"

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(Model_PATH)

#imgPath = r"D:\Solutions\VTO\3.jpg"
#outputFolder = r"D:\Solutions\VTO\Output"
#paletteImages = "D:\\Solutions\\ImageProcessing\\Comparison\\Test1\\LakmAbsoluteArganOilLipColor_BurntBrown.jpg,D:\\Solutions\\ImageProcessing\\Comparison\\Test1\\LakmAbsoluteArganOilLipColor_CrimsonSilk.jpg"
#outputFolder = outputFolder + '\\'

#imgPath = argv[1]
#outputFolder = argv[2]
#paletteImages = argv[3]
#outputFolder = outputFolder + '\\'

imgPath = r"D:\Solutions\VTO\2.jpg"
imgOutputPath = r"D:\Solutions\VTO\2_out.jpg"
imgOutputPath2 = r"D:\Solutions\VTO\2_out_transparency.jpg"
paletteImages = "D:\\Solutions\\ImageProcessing\\Comparison\\Test1\\LakmAbsoluteArganOilLipColor_BurntBrown.jpg,D:\\Solutions\\ImageProcessing\\Comparison\\Test1\\LakmAbsoluteArganOilLipColor_CrimsonSilk.jpg"
imgOutputPath3 = r"D:\Solutions\VTO\2_out_mask.jpg"

img = cv2.imread(imgPath)
overlay = img.copy()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
rects = detector(gray, 1)
# loop over the face detections
a=[]
for (i, rect) in enumerate(rects):
    shape = predictor(gray, rect)
    shape = face_utils.shape_to_np(shape)
    a=list(face_utils.FACIAL_LANDMARKS_IDXS.items())

paletteImageList = paletteImages.split(',')
index =1

height = overlay.shape[0]
width = overlay.shape[1]

empty_mask = np.zeros((height, width), dtype=np.uint8)

for paletteImage in paletteImageList:
    #imgOutPath = outputFolder + str(index) + '.jpg'
    bgr = get_dominant_colour(paletteImage)
    print(bgr)
    applied_lips, lips_polygon = apply_lipstick(img,bgr)
    cv2.imwrite(imgOutputPath,applied_lips)

    cv2.fillPoly(empty_mask, lips_polygon, (255))
    res = cv2.bitwise_and(overlay,overlay,mask = empty_mask)

    rect = cv2.boundingRect(lips_polygon) # returns (x,y,w,h) of the rect
    cropped = res[rect[1]: rect[1] + rect[3], rect[0]: rect[0] + rect[2]]

    #bg = np.ones_like(cropped, np.uint8)*255
    #cv2.bitwise_not(bg,bg, mask=empty_mask)
    #dst2 = bg+ res

    mask = prepare_mask(lips_polygon,overlay)
    cv2.imwrite(imgOutputPath3,cropped)

    histograms = compute_histogram(mask, overlay)

    # Let's plot our test results
    plt.figure(figsize=(10, 10))

    plt.subplot(221)
    plt.imshow(overlay)
    plt.title('Image')

    plt.subplot(222)
    plt.imshow(mask, cmap='gray')
    plt.title('Mask')

    plt.subplot(223)
    plot_histogram(histograms)
    plt.title('Histogram')

    plt.show()

    alpha = 0.4  # Transparency factor.
    # Following line overlays transparent rectangle over the image
    image_new = cv2.addWeighted(overlay, alpha, applied_lips, 1 - alpha, 0)
    cv2.imwrite(imgOutputPath2,image_new)
    index = index +1
    break


import unittest
import numpy as np
from shapely.geometry import Polygon

from mtoolkit.workflow import Context
from mtoolkit.jobs import read_eq_catalog, read_source_model, \
create_catalog_matrix, gardner_knopoff, stepp, _check_polygon, \
processing_workflow_setup_gen
from mtoolkit.utils import get_data_path, DATA_DIR

class JobsTestCase(unittest.TestCase):

    def setUp(self):
        self.context = Context(get_data_path(
            'config.yml', DATA_DIR))
        self.eq_catalog_filename = get_data_path(
            'ISC_small_data.csv', DATA_DIR)
        self.smodel_filename = get_data_path(
            'area_source_model.xml', DATA_DIR)

    def test_read_eq_catalog(self):
        self.context.config['eq_catalog_file'] = self.eq_catalog_filename
        expected_first_eq_entry = {'eventID': 1, 'Agency': 'AAA', 'month': 1,
                'depthError': 0.5, 'second': 13.0, 'SemiMajor90': 2.43,
                'year': 2000, 'ErrorStrike': 298.0, 'timeError': 0.02,
                'sigmamb': '', 'latitude': 44.368, 'sigmaMw': 0.355,
                'sigmaMs': '', 'Mw': 1.71, 'Ms': '',
                'Identifier': 20000102034913, 'day': 2, 'minute': 49,
                'hour': 3, 'mb': '', 'SemiMinor90': 1.01, 'longitude': 7.282,
                'depth': 9.3, 'ML': 1.7, 'sigmaML': 0.1}

        read_eq_catalog(self.context)

        self.assertEqual(10, len(self.context.eq_catalog))
        self.assertEqual(expected_first_eq_entry,
                self.context.eq_catalog[0])

    def test_read_smodel(self):
        self.context.config['source_model_file'] = self.smodel_filename
        expected_first_sm_definition = \
            {'id_as': 'src_1',
             'area_boundary':
               [132.93, 42.85, 134.86,
                41.82, 129.73, 38.38,
                128.15, 40.35],
             'rupture_rate_model': [
               {'max_magnitude': 8.0,
                'a_value_cumulative':
                    3.1612436654341836,
                'name': 'truncated_guten_richter',
                'min_magnitude': 5.0,
                'b_value': 0.7318999871612379},
             {'name': 'focal_mechanism',
              'nodal_planes': [
                {'strike': 0.0,
                 'rake': 0.0,
                 'dip': 90.0,
                 'id': 0},
                {'strike': 12.0,
                 'rake': 0.0,
                 'dip': 40.0,
                 'id': 1}],
              'id': 'smi:fm1/0'}],
             'tectonic_region':
                'Active Shallow Crust',
             'id_sm': 'sm1',
             'rupture_depth_distribution': {
                'depth': [15.0],
                'magnitude': [5.0],
                'name': 'rupture_depth_distrib'},
             'hypocentral_depth': 15.0,
             'type': 'area_source',
             'name': 'Source 8.CH.3'}

        read_source_model(self.context)
        self.assertEqual(2, len(self.context.sm_definitions))
        self.assertEqual(expected_first_sm_definition,
                self.context.sm_definitions[0])

    def test_a_bad_polygon_raises_exception(self):
        polygon = Polygon([(1, 1), (1, 2), (2, 1), (2, 2)])

        self.assertRaises(RuntimeError, _check_polygon, polygon)

    def test_processing_workflow_setup(self):
        self.context.config['apply_processing_steps'] = True

        eq_internal_point = [2000, 1, 2, -0.25, 0.25]
        eq_side_point = [2000, 1, 2, -0.5, 0.25]
        eq_external_point = [2000, 1, 2, 0.5, 0.25]
        eq_events = np.array([eq_internal_point,
                eq_side_point, eq_external_point])
        self.context.vmain_shock = eq_events

        sm = {'area_boundary':
            [-0.5, 0.0, -0.5, 0.5, 0.0, 0.5, 0.0, 0.0]}
        self.context.sm_definitions = [sm]

        first_sm, filtered_eq_sm = \
            processing_workflow_setup_gen(self.context).next()

        expected_eq_events = np.array([eq_internal_point])

        self.assertTrue(np.array_equal(expected_eq_events, filtered_eq_sm))
        self.assertEqual(sm, first_sm)

    def test_gardner_knopoff(self):

        self.context.config['eq_catalog_file'] = get_data_path(
            'declustering_input_test.csv', DATA_DIR)
        self.context.config['GardnerKnopoff']['time_dist_windows'] = \
                'GardnerKnopoff'
        self.context.config['GardnerKnopoff']['foreshock_time_window'] = 0.5

        read_eq_catalog(self.context)
        create_catalog_matrix(self.context)

        expected_vmain_shock = np.delete(
            self.context.catalog_matrix, [4, 10, 19], 0)

        expected_vcl = np.array([0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0,
            0, 0, 0, 0, 6])

        expected_flag_vector = np.array([0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0,
            0, 0, 0, 0, 0, 0, 1])

        gardner_knopoff(self.context)

        self.assertTrue(np.array_equal(expected_vmain_shock,
                self.context.catalog_matrix))
        self.assertTrue(np.array_equal(expected_vcl, self.context.vcl))
        self.assertTrue(np.array_equal(expected_flag_vector,
                self.context.flag_vector))

    def test_parameters_gardner_knopoff(self):

        self.context.config['eq_catalog_file'] = get_data_path(
            'declustering_input_test.csv', DATA_DIR)
        self.context.config['GardnerKnopoff']['time_dist_windows'] = \
                'GardnerKnopoff'
        self.context.config['GardnerKnopoff']['foreshock_time_window'] = 0.5

        read_eq_catalog(self.context)
        create_catalog_matrix(self.context)

        def mock(data, time_dist_windows, foreshock_time_window):
            self.assertEquals("GardnerKnopoff", time_dist_windows)
            self.assertEquals(0.5, foreshock_time_window)
            return None, None, None

        self.context.map_sc['gardner_knopoff'] = mock
        gardner_knopoff(self.context)

    def test_stepp(self):
        self.context.config['eq_catalog_file'] = get_data_path(
            'completeness_input_test.csv', DATA_DIR)

        self.context.config['Stepp']['time_window'] = 5
        self.context.config['Stepp']['magnitude_windows'] = 0.1
        self.context.config['Stepp']['sensitivity'] = 0.2
        self.context.config['Stepp']['increment_lock'] = True

        read_eq_catalog(self.context)
        create_catalog_matrix(self.context)

        filtered_eq_events = np.array([
                    [4.0, 1994.], [4.1, 1994.], [4.2, 1994.],
                    [4.3, 1994.], [4.4, 1994.], [4.5, 1964.],
                    [4.6, 1964.], [4.7, 1964.], [4.8, 1964.],
                    [4.9, 1964.], [5.0, 1964.], [5.1, 1964.],
                    [5.2, 1964.], [5.3, 1964.], [5.4, 1964.],
                    [5.5, 1919.], [5.6, 1919.], [5.7, 1919.],
                    [5.8, 1919.], [5.9, 1919.], [6.0, 1919.],
                    [6.1, 1919.], [6.2, 1919.], [6.3, 1919.],
                    [6.4, 1919.], [6.5, 1919.], [6.6, 1919.],
                    [6.7, 1919.], [6.8, 1919.], [6.9, 1919.],
                    [7.0, 1919.], [7.1, 1919.], [7.2, 1919.],
                    [7.3, 1919.]])

        stepp(self.context)
        self.assertTrue(np.allclose(filtered_eq_events,
                self.context.completeness_table))

        gardner_knopoff(self.context)
        stepp(self.context)
        self.assertTrue(np.allclose(filtered_eq_events,
                self.context.completeness_table))

    def test_parameters_stepp(self):
        self.context.config['eq_catalog_file'] = get_data_path(
            'completeness_input_test.csv', DATA_DIR)

        self.context.config['Stepp']['time_window'] = 5
        self.context.config['Stepp']['magnitude_windows'] = 0.1
        self.context.config['Stepp']['sensitivity'] = 0.2
        self.context.config['Stepp']['increment_lock'] = True

        read_eq_catalog(self.context)
        create_catalog_matrix(self.context)

        def mock(year, mw, magnitude_windows, time_window, sensitivity, iloc):
            self.assertEqual(time_window, 5)
            self.assertEqual(magnitude_windows, 0.1)
            self.assertEqual(sensitivity, 0.2)
            self.assertTrue(iloc)

        self.context.map_sc['stepp'] = mock
        stepp(self.context)


import sys
from PyQt5 import QtWidgets, QtCore, QtGui, Qt

POINTER_TOOL = "pointer"
MOVE_TOOL = "move"
ROTATE_TOOL = "rotate"
RESET_TOOL = "reset"
ZOOM_TOOL = "zoom"

# Various cursors for tools
CURSORS = {POINTER_TOOL: Qt.Qt.ArrowCursor,
           MOVE_TOOL: Qt.Qt.SizeAllCursor,
           ROTATE_TOOL: Qt.Qt.OpenHandCursor,
          }

class EditToolBar(QtWidgets.QToolBar):

    toolClickSgl = QtCore.pyqtSignal(str)

    def __init__(self):

        super(EditToolBar, self).__init__('Edit')

        self.toolButtonGroup = QtWidgets.QButtonGroup()

        self.undoTool = QtWidgets.QAction(QtGui.QIcon(':undo'), '&Undo')

        self.resetViewTool = QtWidgets.QAction(QtGui.QIcon(':square'), '&Reset View')
        self.resetViewTool.triggered.connect(self._clickReset)

        self.pointerTool = QtWidgets.QToolButton()
        self.pointerTool.setIcon(QtGui.QIcon(':navigation-2'))
        self.pointerTool.setCheckable(True)
        self.pointerTool.setToolTip('Pointer')
        self.pointerTool.clicked.connect(self._clickPointer)
        self.toolButtonGroup.addButton(self.pointerTool)

        self.moveTool = QtWidgets.QToolButton()
        self.moveTool.setIcon(QtGui.QIcon(':move'))
        self.moveTool.setCheckable(True)
        self.moveTool.setToolTip('Move')
        self.moveTool.clicked.connect(self._clickMove)
        self.toolButtonGroup.addButton(self.moveTool)

        self.rotateTool = QtWidgets.QToolButton()
        self.rotateTool.setIcon(QtGui.QIcon(':sync'))
        self.rotateTool.setCheckable(True)
        self.rotateTool.setToolTip('Rotate')
        self.rotateTool.clicked.connect(self._clickRotate)
        self.toolButtonGroup.addButton(self.rotateTool)

        self.zoomInTool = QtWidgets.QAction(QtGui.QIcon(':maximize'), '&Zoom In')
        self.zoomOutTool = QtWidgets.QAction(QtGui.QIcon(':minimize'), '&Zoom Out')

        self.addAction(self.undoTool)
        self.addAction(self.resetViewTool)

        self.addWidget(self.pointerTool)
        self.addWidget(self.moveTool)
        self.addWidget(self.rotateTool)
        self.addAction(self.zoomInTool)
        self.addAction(self.zoomOutTool)

    def _clickMove(self, event):
        if self.moveTool.isChecked():
            self.toolClickSgl.emit(MOVE_TOOL)

    def _clickRotate(self, event):
        if self.rotateTool.isChecked():
            self.toolClickSgl.emit(ROTATE_TOOL)

    def _clickPointer(self, event):
        if self.pointerTool.isChecked():
            self.toolClickSgl.emit(POINTER_TOOL)

    def _clickReset(self, event):
        # No need to verify checked status, since this isn't a tool
        self.toolClickSgl.emit(RESET_TOOL)


import cv2
import winsound
import tkinter as tk
from tkinter import messagebox
from threading import Thread
from tkinter import ttk
from PIL import Image, ImageTk
import math
from openpyxl import Workbook
from datetime import datetime

# Global variable to track dark mode state
dark_mode = False

# Global variable for animation
angle = 0

# Global variable for Excel workbook and sheet
workbook = Workbook()
sheet = workbook.active

# Function to toggle dark mode
def toggle_dark_mode():
    global dark_mode
    dark_mode = not dark_mode
    update_theme()

# Function to update the GUI theme based on dark mode state
def update_theme():
    bg_color = "#333" if dark_mode else "white"
    fg_color = "white" if dark_mode else "black"
    button_bg = "#4CAF50" if dark_mode else "green"

    root.configure(bg=bg_color)
    title_label.configure(bg=bg_color, fg=fg_color)
    image_label.configure(bg=bg_color)
    start_button.configure(bg=button_bg, fg=fg_color)
    team_label.configure(fg=fg_color, bg=bg_color)

# Function to update the animation
def update_animation():
    global angle
    if motion_detection_running:
        angle += 2  # Rotate by 2 degrees
        if angle >= 360:
            angle = 0
        rotated_logo = original_logo.rotate(angle)
        animated_logo = ImageTk.PhotoImage(rotated_logo)
        image_label.config(image=animated_logo)
        image_label.image = animated_logo
    root.after(50, update_animation)  # Call update_animation every 50ms

# Function to start motion detection
def start_motion_detection():
    global motion_detection_running
    if not motion_detection_running:
        messagebox.showinfo("Motion Detection", "Motion detection is starting.")
        motion_detection_running = True
        Thread(target=motion_detection).start()

# Your provided motion detection code
def motion_detection():
    cam = cv2.VideoCapture(0)
    while cam.isOpened():
        ret, frame = cam.read()
        ret, frame1 = cam.read()
        diff = cv2.absdiff(frame, frame1)
        grey = cv2.cvtColor(diff, cv2.COLOR_RGB2GRAY)
        blur = cv2.GaussianBlur(grey, (5, 5), 0)
        _, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)
        dilation = cv2.dilate(thresh, None, iterations=3)
        contour, _ = cv2.findContours(dilation, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        for c in contour:
            if cv2.contourArea(c) < 5000:
                continue
            x, y, w, h = cv2.boundingRect(c)
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 138), 2)
            winsound.Beep(1000, 200)

        if cv2.waitKey(10) == ord('a'):
            break
        cv2.imshow("Motion Detection", frame)

        # Save motion detection data to Excel
        save_motion_data()

    cam.release()
    cv2.destroyAllWindows()
    motion_detection_running = False

# Function to save motion detection data to Excel
def save_motion_data():
    global sheet
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    sheet.append([timestamp, "Motion Detected"])
    workbook.save("motion_detection_data.xlsx")

# Create the tkinter window
root = tk.Tk()
root.title("Security Camera with Frame Detection Powered by AI")
root.configure(bg='white')  # Set default background color

# Load and display an image/logo
original_logo = Image.open("C://Users//Hp//PycharmProjects//python-security camera//sscam.jpg")  # Replace "logo.png" with your image file
original_logo = original_logo.resize((150, 150), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(original_logo)
image_label = tk.Label(root, image=photo)
image_label.image = photo
image_label.pack(pady=20)

# Create a label for the project title
title_label = tk.Label(root, text="Security Camera with Frame Detection Powered by AI", font=("Arial", 16, "bold"),
                       fg="black", bg="white")
title_label.pack(pady=10)

# Create a Start button (centered)
start_button = tk.Button(root, text="Start", command=start_motion_detection, font=("Arial", 12, "bold"), bg="green",
                         fg="white", padx=20, pady=10)
start_button.pack(pady=20)

# Create a label for the team members
team_label = tk.Label(root, text="Team Members:\nAbhi Success, Pranav Mehta, Piyush Kumar, Harshit Soni, Fahim-ul-haq",
                      font=("Arial", 12), fg="black", bg="white")
team_label.pack(pady=10)

# Create a dark mode toggle button
dark_mode_button = tk.Button(root, text="Toggle Dark Mode", command=toggle_dark_mode, font=("Arial", 10, "bold"),
                             bg="gray", fg="white", padx=10, pady=5)
dark_mode_button.pack()

# Initialize motion detection state
motion_detection_running = False

# Start the tkinter main loop
root.geometry("600x500")  # Set the window size
update_theme()  # Initialize theme based on dark mode state
update_animation()  # Start the animation
root.mainloop()


#!/usr/bin/env python

import psycopg2
import psycopg2.extras

import re

DANY_VERSION_STRING = "2.2.4"
DANY_FUNC_VERSION_STRING = "2_2_4"

def multiple_replace(text, adict):
    """
    From the the python cookbook. adict's keys should be the patterns
    to match and their values should be the replacements.
    """
    rx = re.compile("|".join(map(re.escape, adict)))
    def one_xlat(match):
        return adict[match.group(0)]
    return rx.sub(one_xlat, text)

class DanyException(Exception):
    pass

class DanCursor(psycopg2.extras.DictCursor):

    def execute(self, *args, **kwargs):
        try:
            super(DanCursor, self).execute(*args, **kwargs)
        except:
            raise DanyException("NOPE")

    def get_nodes(self):
        qry = """
        select no_id as node_id,
               no_active as active,
               no_comment as comment
        from sl_node
        ;
        """
        self.execute(qry)
        for row in self:
            yield row

    def get_paths(self):
        qry = """
        select pa_server as server,
               pa_client as client,
               pa_conninfo as conninfo,
               pa_connretry as connretry
        from sl_path
        ;
        """
        self.execute(qry)
        for row in self:
            yield row

    def get_listens(self):
        qry = """
        select li_origin as origin_id,
               li_provider as provider_id,
               li_receiver as receiver_id
        from sl_listen
        ;
        """
        self.execute(qry)
        for row in self:
            yield row

    def get_set(self, set_id):
        qry = """
        select set_id as id,
               set_origin as origin,
               set_comment as comment
        from sl_set
        where set_id = %(set_id)s
        ;
        """
        d = {
            "set_id": set_id,
        }
        self.execute(qry, d)
        row = self.fetchone()
        return row

    def get_sets(self):
        qry = """
        select set_id,
               set_origin as origin_id,
               set_comment as comment
        from sl_set
        ;
        """
        self.execute(qry)
        for row in self:
            yield row

    def check_subscription_exists(self, set_id, receiver_id, provider_id):
        qry = """
        select exists (select 1
                       from sl_subscribe
                       where sub_set = %(set_id)s
                         and sub_receiver = %(receiver_id)s
                         and sub_active = true
                         and sub_provider != %(provider_id)s) as sub_exists
        ;
        """
        d = {
            "set_id": set_id,
            "receiver_id": receiver_id,
            "provider_id": provider_id,
        }
        self.execute(qry, d)
        row = self.fetchone()
        return row["sub_exists"]

    def get_subscriptions(self):
        qry = """
        select sub_set as set_id,
               sub_provider as provider_id,
               sub_receiver as receiver_id,
               sub_forward as forward,
               sub_active as active
        from sl_subscribe
        ;
        """
        self.execute(qry)
        for row in self:
            yield row

    def get_max_seqno_by_origin(self):
        qry = """
        select ev_origin as origin_id,
               max(ev_seqno) as max_seqno
        from sl_event
        group by ev_origin
        ;
        """
        self.execute(qry)
        for row in self:
            yield row

    def set_seqno_value(self, name, value):
        qry = """
        select setval(%(sequence)s, %(value)s);
        """
        d = {
            "name": name,
            "value": value,
        }
        self.execute(qry, d)

    def insert_confirmation(self, origin_id, receiver_id, seqno):
        qry = """
        insert into sl_confirm
        (
          con_origin,
          con_received,
          con_seqno,
          con_timestamp
        )
        values
        (
          %(origin_id)s,
          %(received_id)s,
          %(seqno)s,
          current_timestamp
        )
        ;
        """
        d = {
            "origin": origin_id,
            "received": receiver_id,
            "seqno": seqno,
        }
        self.execute(qry, d)

    def initializeLocalNode(self, node_id, comment):
        qry = """
        select initializeLocalNode(%(node_id)s, %(comment)s);
        """
        d = {
            "node_id": node_id,
            "comment": comment,
        }
        self.execute(qry, d)

    def storeNode(self, node_id, comment):
        qry = """
        select storeNode_int(%(node_id)s, %(comment)s);
        """
        d = {
            "node_id": node_id,
            "comment": comment,
        }
        self.execute(qry, d)

    def enableNode(self, node_id):
        qry = """
        select enableNode_int(%(node_id)s);
        """
        d = {
            "node_id": node_id,
        }
        self.execute(qry, d)

    def storePath(self, server_id, client_id, conninfo, connretry):
        qry = """
        select storePath_int(%(server_id)s,
                             %(client_id)s,
                             %(conninfo)s,
                             %(connretry)s)
        ;
        """
        d = {
            "server_id": server_id,
            "client_id": client_id,
            "conninfo": conninfo,
            "connretry": connretry,
        }
        self.execute(qry, d)

    def storeListen(self, origin_id, provider_id, receiver_id):
        qry = """
        select storeListen_int(%(origin_id)s,
                               %(provider_id)s,
                               %(receiver_id)s)
        ;
        """
        d = {
            "origin_id": origin_id,
            "provider_id": provider_id,
            "receiver_id": receiver_id,
        }
        self.execute(qry, d)

    def storeSet(self, set_id, origin_id, comment):
        qry = """
        select storeSet_int(%(set_id)s,
                            %(origin_id)s,
                            %(comment)s)
        ;
        """
        d = {
            "set_id": set_id,
            "origin_id": origin_id,
            "comment": comment,
        }
        self.execute(qry, d)

    def subscribeSet(self, set_id, provider_id, receiver_id, forward, active):
        qry = """
        select subscribeSet_int(%(set_id)s,
                                %(provider_id)s,
                                %(receiver_id)s,
                                %(forward)s,
                                %(active)s)
        ;
        """
        d = {
            "set_id": set_id,
            "provider_id": provider_id,
            "receiver_id": receiver_id,
            "forward": forward,
            "active": active,
        }
        self.execute(qry, d)

    def enableSubscription(self, set_id, provider_id, receiver_id):
        qry = """
        select enableSubscription_int(%(set_id)s,
                                      %(provider_id)s,
                                      %(receiver_id)s)
        ;
        """
        d = {
            "set_id": set_id,
            "provider_id": provider_id,
            "receiver_id": receiver_id,
        }
        self.execute(qry, d)

    def reshapeSubscription(self, set_id, provider_id, receiver_id):
        qry = """
        select reshapeSubscription(%(set_id)s,
                                   %(provider_id)s,
                                   %(receiver_id)s)
        ;
        """
        d = {
            "set_id": set_id,
            "provider_id": provider_id,
            "receiver_id": receiver_id,
        }
        self.execute(qry, d)

    def determineIdxnameUnique(self, fqdn, key):
        qry = """
        select determineIdxnameUnique(%(fqdn)s, %(key)s) as idxname;
        """
        d = {
            "fqdn": fqdn,
            "key": key,
        }
        self.execute(qry, d)
        row = self.fetchone()
        return row["idxname"]

    def setAddTable(self, set_id, table_id, fqdn, idxname, comment):
        qry = """
        select setAddTable(%(set_id)s,
                           %(table_id)s,
                           %(fqdn)s,
                           %(idxname)s,
                           %(comment)s)
        ;
        """
        d = {
            "set_id": set_id,
            "table_id": table_id,
            "fqdn": fqdn,
            "idxname": idxname,
            "comment": comment,
        }
        self.execute(qry, d)

    def createEvent(self, schema, event):
        qry = """
        select createEvent(%(schema)s, %(event)s);
        """
        d = {
            "schema": schema,
            "event": event,
        }
        self.execute(qry, d)

    def acquire_event_lock(self):
        self.execute("lock table sl_event_lock;")

    def acquire_config_lock(self):
        self.execute("lock table sl_config_lock;")

class Node(object):

    def __init__(self, node_id, conninfo, comment=None):

        self.node_id = node_id
        self.conninfo = conninfo
        self.comment = comment

    def connect(self, schema):
        if isinstance(self.conninfo, basestring):
            conn = psycopg2.connect(self.conninfo, cursor_factory=DanCursor)
        elif isinstance(self.conninfo, dict):
            conn = psycopg2.connect(cursor_factory=DanCursor, **self.conninfo)
        else:
            raise DanyException("Bad conninfo: {0}".format(self.conninfo))
        level = psycopg2.extensions.ISOLATION_LEVEL_REPEATABLE_READ
        conn.set_isolation_level(level)
        cur = conn.cursor()
        cur.execute("set search_path = %s;", (schema,))
        return conn

    def __eq__(self, other):
        return self.node_id == other.node_id

class Cluster(object):

    def __init__(self, cluster_id, name, comment=None):
        """
        Define a slony cluster.
        """

        self.cluster_id = cluster_id
        self.name = name
        self.comment = comment

class Set(object):

    def __init__(self, set_id, comment="An exciting replication set"):
        self.set_id = set_id
        self.comment = comment

class Table(object):

    def __init__(self, table_id, name, schema="public", key=None, comment=None):
        self.table_id = table_id
        self.name = name
        self.schema = schema
        self.key = key
        self.comment = comment

    @property
    def fqdn(self):
        return "{0}.{1}".format(self.schema, self.name)

class AdminConnections(object):

    def __init__(self, schema):
        self.schema = schema
        self.connections = {}

    def __getitem__(self, node):

        if node not in self.connections:
            conn = node.connect(self.schema)
            self.connections[node] = conn

        return self.connections[node]

    def lookup_id(self, node_id):

        for node in self.connections:
            if node.node_id == node_id:
                return self.connections[node]

        raise DanyException("No connection info for node {0}".format(node_id))

    def __iter__(self):
        return iter(self.connections)

class Dan(object):

    def __init__(self, cluster, nodes):
        self.cluster = cluster
        self.schema = "_{0}".format(cluster.name)
        self.nodes = nodes
        self.connections = AdminConnections(self.schema)

    def _load_script(self, cur, fname):

        sql = None
        with open(fname) as f:
            d = {
                "@CLUSTERNAME@": self.cluster.name,
                "@MODULEVERSION@": DANY_VERSION_STRING,
                "@NAMESPACE@": self.schema,
                "@FUNCVERSION@": DANY_FUNC_VERSION_STRING,
            }
            sql = multiple_replace(f.read(), d)
        if sql is not None:
            cur.execute(sql)
        else:
            raise DanyException("Couldn't load {0}".format(fname))

    def _load_base(self, cur, node):
        # Maybe one day the schema name will be bound properly here :/
        cur.execute("create schema %s;" % (self.schema,))
        self._load_script(cur, "slony1_base.2.2.4.sql")
        self._load_script(cur, "slony1_base.v84.2.2.4.sql")
        self._load_script(cur, "slony1_funcs.2.2.4.sql")
        self._load_script(cur, "slony1_funcs.v84.2.2.4.sql")

    def _lookup_origin_helper(self, set_id, cur):

        row = cur.get_set(set_id)

        if row is None:
            return None

        return row["origin"]

    def _lookup_origin(self, set_id, cur=None):

        origin_id = None

        msg = "Cannot determine set origin for set {0}".format(set_id)

        if cur is None:

            for node in self.connections:
                cur = self.connections[node].cursor()
                origin_id = self._lookup_origin_helper(set_id, cur)
                if origin_id is not None:
                    return origin_id

            # We made it through all the connections and didn't find
            # the origin
            raise DanyException(msg)

        else:

            origin_id = self._lookup_origin_helper(set_id, cur)

            if origin_id is None:
                raise DanyException(msg)

            return origin_id

    def init_cluster(self, origin):

        conn = self.connections[origin]
        cur = conn.cursor()

        self._load_base(cur, origin)

        cur.acquire_event_lock()
        cur.acquire_config_lock()
        cur.initializeLocalNode(origin.node_id, origin.comment)
        cur.enableNode(origin.node_id)

        conn.commit()

    def store_node(self, node, event_node):

        if node == event_node:
            msg = "ev_origin for store_node cannot be the new node"
            raise DanyException(msg)

        conn_node = self.connections[node]
        cur_node = conn_node.cursor()

        self._load_base(cur_node, node)

        cur_node.acquire_event_lock()
        cur_node.acquire_config_lock()

        cur_node.initializeLocalNode(node.node_id, node.comment)
        cur_node.enableNode(node.node_id)

        conn_event_node = self.connections[event_node]
        cur_event_node = conn_event_node.cursor()

        # Copy sl_node entries from event node to the node being stored
        for row in cur_event_node.get_nodes():
            cur_node.storeNode(row["node_id"], row["comment"])
            if row["active"]:
                cur_node.enableNode(row["node_id"])

        # Copy sl_path entries from event node to the node being stored
        for row in cur_event_node.get_paths():
            cur_node.storePath(row["server_id"],
                               row["client_id"],
                               row["conninfo"],
                               row["connretry"])

        # Copy sl_listen entries from event node to the node being stored
        for row in cur_event_node.get_listens():
            cur_node.storeListen(row["origin_id"],
                                 row["provider_id"],
                                 row["receiver_id"])

        # Copy sl_set
        for row in cur_event_node.get_sets():
            cur_node.storeSet(row["set_id"], row["origin_id"], row["comment"])

        # Copy sl_subscribe
        for row in cur_event_node.get_subscriptions():

            # Every subscription here starts as inactive
            cur_node.subscribeSet(row["set_id"],
                                  row["provider_id"],
                                  row["receiver_id"],
                                  row["forward"],
                                  False)

            # Then, if the subscription is supposed to be active,
            # enable it
            if row["active"]:
                cur_node.enableSubscription(row["set_id"],
                                            row["provider_id"],
                                            row["receiver_id"])

        # For nodes that aren't this new node, mark the new node as
        # having confirmed every event up until now (to mark us as up
        # to speed). I'm not sure how we could have yet generated a
        # noticeable event that the event node would then kick back
        # for us here, but if we did then our event sequence gets
        # kicked up to that value.
        for row in cur_event_node.get_max_seqno_by_origin():
            if node.node_id == row["origin_id"]:
                cur_node.set_seqno_val("sl_event_seq", row["max_seqno"])
            else:
                cur_node.insert_confirmation(row["ev_origin"],
                                             node.node_id,
                                             row["max_ev_seqno"])

        # Now register the new node in the event node. If auto-wait is
        # enabled, this should wait for confirmation.
        cur_event_node.storeNode(node.node_id, node.comment)
        cur_event_node.enableNode(node.node_id)

        conn_node.commit()
        conn_event_node.commit()

    def store_path(self, server, client, conninfo, connretry=10):

        conn = self.connections[client]
        cur = conn.cursor()

        cur.acquire_event_lock()
        cur.acquire_config_lock()

        cur.storePath(server.node_id, client.node_id, conninfo, connretry)

        conn.commit()

    def create_set(self, set_, origin):

        conn = self.connections[origin]
        cur = conn.cursor()

        cur.acquire_event_lock()
        cur.acquire_config_lock()

        cur.storeSet(set_.set_id, origin.node_id, set_.comment)

        conn.commit()

    def set_add_table(self, set_, tables):
        """
        Add each of the provided tables to the given replication set.
        """
        origin_id = self._lookup_origin(set_.set_id)
        conn_origin = self.connections.lookup_id(origin_id)
        cur_origin = conn_origin.cursor()

        cur_origin.acquire_event_lock()
        cur_origin.createEvent(self.schema, "SYNC")

        # wait for that sync

        # Obtain a lock on sl_event_lock. It must be obtained before
        # calling setAddTable()
        cur_origin.acquire_event_lock()
        cur_origin.acquire_config_lock()

        for table in tables:
            idxname = cur_origin.determineIdxnameUnique(table.fqdn, table.key)
            cur_origin.acquire_config_lock()
            cur_origin.setAddTable(set_.set_id,
                                   table.table_id,
                                   table.fqdn,
                                   idxname,
                                   table.comment)

        conn_origin.commit()

    def subscribe_set(self, set_, provider, receiver,
                      forward=True, omitcopy=True):

        conn_provider = self.connections[provider]
        cur_provider = conn_provider.cursor()

        # Check if this node already subscribes to this set via a node
        # that's NOT the proposed provider. If so we will need to
        # reshape it later.
        reshape = cur_provider.check_subscription_exists(set_.set_id,
                                                         receiver.node_id,
                                                         provider.node_id)

        # Now look up the set's definition to find the origin node
        origin_id = self._lookup_origin(set_.set_id, cur_provider)
        conn_origin = self.connections.lookup_id(origin_id)
        cur_origin = conn_origin.cursor()

        cur_origin.acquire_event_lock()
        cur_origin.acquire_config_lock()

        cur_origin.subscribeSet(set_.set_id,
                                provider.node_id,
                                receiver.node_id,
                                forward,
                                omitcopy)

        if reshape:
            conn_receiver = self.connections[receiver]
            cur_receiver = conn_receiver.cursor()

            cur_receiver.acquire_config_lock()
            cur_receiver.reshapeSubscription(set_.set_id,
                                             provider.node_id,
                                             receiver.node_id)

            conn_receiver.commit()

        conn_provider.commit()
        conn_origin.commit()

    def sync(self, node):
        conn = self.connections[node]
        cur = conn.cursor()
        cur.acquire_event_lock()
        cur.createEvent(self.schema, "SYNC")
        conn.commit()


# coding=utf-8
from django import template
import traceback

register = template.Library()

@register.filter
def selectgender(value):
	"""格式化为是/否
	:param value:M/F，
	:return: 男/女
	"""

	absent = {"M": u'男', "F": u'女'}
	try:
		if value:
			return absent[value]
		return ""
	except:
		traceback.print_exc()


from functools import cache
from _tabltypes import set_attributes

"""Motzkin triangle, coefficients of Motzkin polynomials.

[0] 1
[1] 1, 0
[2] 1, 0,  1
[3] 1, 0,  3, 0
[4] 1, 0,  6, 0,   2
[5] 1, 0, 10, 0,  10, 0
[6] 1, 0, 15, 0,  30, 0,   5
[7] 1, 0, 21, 0,  70, 0,  35, 0
[8] 1, 0, 28, 0, 140, 0, 140, 0,  14
[9] 1, 0, 36, 0, 252, 0, 420, 0, 126, 0
"""

@cache
def motzkin(n: int) -> list[int]:

    if n == 0: return [1]
    if n == 1: return [1, 0]

    l = 0 if n % 2 else (motzkin(n - 2)[n - 2] * 2 * (n - 1)) // (n // 2 + 1)
    row = motzkin(n - 1) + [l]
    for k in range(2, n, 2):
        row[k] = (n * row[k]) // (n - k)
    return row

@set_attributes(
    motzkin,
    "Motzkin",
    ['A359364'],
    False)
def Motzkin(n: int, k: int) -> int:
    return motzkin(n)[k]

if __name__ == "__main__":
    from _tabltest import TablTest

    TablTest(Motzkin)

''' Alternative:
from Binomial import Binomial
@cache
def motzkin(n: int) -> list[int]:
    def Catalan(n: int) -> int:
        return Binomial(2 * n, n) // (n + 1)

    return [Binomial(n, k) * Catalan(k // 2) if k % 2 == 0 else 0 for k in range(n + 1)]
'''


from sympy import *
import cantera as ct
print('Runnning Cantera version: ' + ct.__version__)

# matplotlib notebook
import matplotlib.pyplot as plt

# determine the density of gas at the inlet
# # Load in the cti mech file
gas = ct.Solution('../mechanisms/gri30.yaml')

# Define inlet density
inletTemperature = 300  # Kelvin
inletPressure = 101325  # Pascals
inletYi = {'O2': 1.0}
gas.TPY = inletTemperature, inletPressure, inletYi
inletDensity = gas.density

# define the geometry
yo = 0.0;
yh = 0.0254
dia = (yh - yo)
yc = (yo + yh) * 0.5
depth = 0.0254
inletMassFlowKgMin = 0.192 #kg/min
inletMassFlow = inletMassFlowKgMin/60.0

# setup symbols
y = Symbol('y')
f = Symbol('f')
m = Symbol('m')

# compute the mass flux function
# for laminar (https://www.kau.edu.sa/Files/0057863/Subjects/Chapter%208.pdf 8-17)
# velocityProfile = f*(1-((y-yc)**2)/((dia**2)/4))
# for turbulent
velocityProfile = f*(1-sqrt((y-yc)**2)/(dia/2))**(1/7)

# for turblent flow
massFluxProfile = velocityProfile * inletDensity

# Perform a simple 1D integration (assume that z dimension is one)
massFlow = integrate(massFluxProfile, (y, yo, yh))*depth

# Solver for f
conserved = Eq(massFlow, m)
fSolution = solve(conserved, f)[0]
print("VelocityFactor: ", fSolution)
print("VelocityFactor for ", inletMassFlow, " kg/s is ",  fSolution.subs(m, inletMassFlow))

#
# Plot the velocity
fSolution = fSolution.subs(m,inletMassFlow)
velocityProfile = velocityProfile.subs(f,fSolution)
plot(velocityProfile, (y, yo, yh))


import math

import torch
import torch.nn as nn
import torch.nn.functional as F

class Phase(nn.Module):
    """See `this page <https://sp-nitech.github.io/sptk/latest/main/phase.html>`_
    for details.

    Parameters
    ----------
    fft_length : int >= 2 [scalar]
        Number of FFT bins, :math:`L`.

    unwrap : bool [scalar]
        If True, perform phase unwrapping.

    """

    def __init__(self, fft_length, unwrap=False):
        super(Phase, self).__init__()

        self.fft_length = fft_length
        self.unwrap = unwrap

        assert 2 <= self.fft_length

    def forward(self, b, a=None):
        """Compute phase spectrum.

        Parameters
        ----------
        b : Tensor [shape=(..., M+1)]
            Numerator coefficients.

        a : Tensor [shape=(..., N+1)]
            Denominator coefficients.

        Returns
        -------
        p : Tensor [shape=(..., L/2+1)]
            Phase spectrum [:math:`\\pi` rad].

        Examples
        --------
        >>> x = diffsptk.ramp(3)
        >>> phase = diffsptk.Phase(8)
        >>> p = phase(x)
        >>> p
        tensor([ 0.0000, -0.5907,  0.7500, -0.1687,  1.0000])

        """
        B = torch.fft.rfft(b, n=self.fft_length)

        if a is None:
            p = torch.atan2(B.imag, B.real)
        else:
            K, a = torch.split(a, [1, a.size(-1) - 1], dim=-1)
            a = F.pad(a, (1, 0), value=1)
            A = torch.fft.rfft(a, n=self.fft_length)
            p = torch.atan2(
                B.imag * A.real - B.real * A.imag, B.real * A.real + B.imag * A.imag
            )

        # Convert to cycle [-1, 1].
        p /= math.pi

        if self.unwrap:
            diff = p[..., 1:] - p[..., :-1]
            bias = (-2 * (1 < diff)) + (2 * (diff < -1))
            s = torch.cumsum(bias, dim=-1)
            p[..., 1:] = p[..., 1:] + s

        return p


""" A collection of classes and functions to reproject data.

Todo:
    * Rewrite using cartopy
    * Can some of this be merged with :any:`~evac.utils.gis_tools`?
    * These classes need to be put in their own file.
    * Long term, we probably need a new directory, 'geog' or 'reproj',
        which deals with reprojection, and gathers a lot of functions
        and classes that are scattered around evac.
    * Rewrite without any WEM imports.
"""
import os
import pdb

from scipy.interpolate import griddata
from mpl_toolkits.basemap import Basemap
import numpy as N

from evac.datafiles.wrfout import WRFOut
from evac.datafiles.hrrr import HRRR

class VerifGrid:
    """
    The verification grid should be inside the 1 km domain.

    Roughly 5 km res?

    W is the 1 km WRFOut instance
    """
    def __init__(self,W,nx,ny,xy1D=True):
        self.proj = 'lcc'
        # These are urcrnrlon etc
        self.Nlim = W.kwargs['urcrnrlat']
        self.Elim = W.kwargs['urcrnrlon']
        self.Slim = W.kwargs['llcrnrlat']
        self.Wlim = W.kwargs['llcrnrlon']

        self.nx = nx
        self.ny = ny
        self.cen_lat = W.kwargs['lat_0']
        self.cen_lon = W.kwargs['lon_0']
        self.tlat1 = W.kwargs['lat_1']
        self.tlat2 = W.kwargs['lat_2']

        self.m, self.lons, self.lats, self.xx, self.yy = create_new_grid(Nlim=self.Nlim,
                        Elim=self.Elim,Slim=self.Slim,Wlim=self.Wlim,nx=self.nx,ny=self.ny,proj=self.proj,
                        tlat1=self.tlat1,tlat2=self.tlat2,cen_lat=self.cen_lat,cen_lon=self.cen_lon)
        # if xy1D:
            # self.xx = self.xx[0,:]
            # self.yy = self.yy[:,0]

        # Aliases
        self.lat_0 = self.cen_lat
        self.lon_0 = self.cen_lon
        return

class WRF_native_grid:
    def __init__(self,fpath,resolution='i',xy1D=True):
        """Generates a basemap object for a WRF file's domain.

        """
        # keyword arguments to basemap generation
        self.kwargs = {'resolution':resolution}

        self.load_wrfout(fpath)
        self.load_attrs()
        self.load_corners()
        self.generate_basemap()

        if xy1D:
            self.xx = self.xx[0,:]
            self.yy = self.yy[:,0]

        self.combine_scopes()

    def load_wrfout(self,fpath):
        self.W = WRFOut(fpath)
        return

    def load_attrs(self,):
        self.kwargs['lat_0'] = self.W.nc.CEN_LAT
        self.kwargs['lon_0'] = self.W.nc.CEN_LON
        self.kwargs['lat_1'] = self.W.nc.TRUELAT1
        self.kwargs['lat_2'] = self.W.nc.TRUELAT2

    def load_corners(self):
        self.kwargs['llcrnrlon'] = self.W.lons[0,0]
        self.kwargs['llcrnrlat'] = self.W.lats[0,0]
        self.kwargs['urcrnrlon'] = self.W.lons[-1,-1]
        self.kwargs['urcrnrlat'] = self.W.lats[-1,-1]

    def generate_basemap(self):
        self.m = Basemap(projection='lcc',**self.kwargs)
        self.lons, self.lats, self.xx, self.yy = self.m.makegrid(
                        self.W.lons.shape[1],self.W.lons.shape[0],returnxy=True)

    def combine_scopes(self):
        """
        Put kwargs dictionary into self's namespace
        """
        self.__dict__ = dict(self.__dict__,**self.kwargs)

        # Alias of domain limits
        self.Wlim = self.llcrnrlon
        self.Slim = self.llcrnrlat
        self.Nlim = self.urcrnrlat
        self.Elim = self.urcrnrlon

class HRRR_native_grid(WRF_native_grid):
    """AS WRF_native_grid, but with some info about operational HRRR.
    """
    def __init__(self,fpath):
        super(HRRR_native_grid,self).__init__(fpath)

    def load_wrfout(self,fpath):
        """Over-riden from parent.
        """
        self.W = HRRR(fpath)

    def load_attrs(self,):
        """Over-riden from parent.

        TODO: get rid of this and just load from HRRR object.
        """
        self.kwargs['lat_0'] = 38.5
        self.kwargs['lon_0'] = -97.5
        self.kwargs['lat_1'] = 38.5
        self.kwargs['lat_2'] = 38.5

def create_new_grid(Nlim=None,Elim=None,Slim=None,Wlim=None,proj='merc',
                    lat_ts=None,resolution='i',nx=None,ny=None,
                    tlat1=30.0,tlat2=60.0,cen_lat=None,cen_lon=None,
                    lats=None,lons=None,dx=None):
                    # lllon=None,lllat=None,urlat=None,urlon=None):
    """Create new domain for interpolating to, for instance.

    The following are mandatory arguments for mercator ('merc'):
    Nlim,Elim,Slim,Wlim = lat/lon/lat/lon limits for north/east/south/west respectively
    lat_ts = latitude of true scale?
    nx,ny = number of points in the x/y direction respectively
    """
    if proj == 'merc':
        if nx is None:
            assert dx
        if None in (Nlim,Elim,Slim,Wlim,lat_ts):
            print("Check non-optional arguments.")
            raise Exception
        m = Basemap(projection=proj,llcrnrlat=Slim,llcrnrlon=Wlim,
                    urcrnrlat=Nlim,urcrnrlon=Elim,lat_ts=lat_ts,resolution=resolution)
        if dx:
            # llcrnr
            xW, yS = m(Wlim, Slim)
            # urcrnr
            xE, yN = m(Elim, Nlim)

            # km difference in x (lon) direction
            xdiff_km = abs(xE-xW)/1000
            # and in y (lat) direction
            ydiff_km = abs(yS-yN)/1000

            # nx needed to give dx requested
            nx = int(N.floor(xdiff_km/dx))
            # assume dx=dy
            ny = int(N.floor(ydiff_km/dx))

    elif proj == 'lcc':
        # if None in (tlat1,tlat2,cen_lat,cen_lon,lllon,lllat,urlon,urlat,nx,ny):
        if None in (tlat1,tlat2,cen_lat,cen_lon,Nlim,Elim,Slim,Wlim,nx,ny):
            print("Check non-optional arguments.")
            raise Exception
        m = Basemap(projection='lcc',lat_1=tlat1,lat_2=tlat2,lat_0=cen_lat,
                            lon_0=cen_lon,llcrnrlon=Wlim,llcrnrlat=Slim,
                            urcrnrlon=Elim,urcrnrlat=Nlim,resolution='h')

    lons, lats, xx, yy = m.makegrid(nx,ny,returnxy=True)
    # pdb.set_trace()
    return m, lons, lats, xx, yy

def create_WRFgrid(f):
    """Constructs an instance of WRF_native_grid to return the vitals.

    f   -   absolute path to wrfout file.
    """
    W = WRF_native_grid(f)
    xx = W.xx
    yy = W.yy
    lons = W.lons
    lats = W.lats
    m = W.m
    return xx,yy,lats,lons,m

def reproject(data_orig,xx_orig=False,yy_orig=False,lats_orig=False,lons_orig=False,newgrid=False,
                    xx_new=False,yy_new=False,method='linear',debug=False):
    """
    data_orig               -   N.ndarray of original data (2D?)
    xx_orig,yy_orig         -   x-/y-axis indices of original data straight out a m(lons,lats)
    lats_orig,lons_orig     -   lats/lons of original data (shape?)
    newgrid                 -   basemap class classobject
    """
    # xx_new,yy_new = newgrid(lons_orig,lats_orig)
    # pdb.set_trace()
    assert len(xx_orig.shape) == 2
    if len(xx_new.shape) == 1:
        xx_new_dim = len(xx_new)
        yy_new_dim = len(yy_new)
        # mx,my = N.meshgrid(xx_new,yy_new)
        my, mx = N.meshgrid(yy_new,xx_new)
    elif len(xx_new.shape)== 2:
        xx_new_dim = len(xx_new[:,0])
        # xx_new_dim = len(xx_new[0,:])
        yy_new_dim = len(yy_new[0,:])
        # yy_new_dim = len(yy_new[:,0])
        mx,my = xx_new, yy_new
    else:
        raise Exception("Dimensions of xx_new and yy_new are too large.")

    # data_new = griddata((xx_orig.flat,yy_orig.flat),data_orig.flat,(xx_new.flat,
        # yy_new.flat)).reshape(xx_new_dim,yy_new_dim)
    # pdb.set_trace()
    if debug:
        print("Starting reprojection...")

    if type(xx_orig) == N.ma.core.MaskedArray:
        xx_orig = xx_orig.data
    if type(yy_orig) == N.ma.core.MaskedArray:
        yy_orig = yy_orig.data
    if type(data_orig) == N.ma.core.MaskedArray:
        data_orig = data_orig.data
    if type(mx) == N.ma.core.MaskedArray:
        mx = mx.data
    if type(my) == N.ma.core.MaskedArray:
        my = my.data

    data_new = griddata((xx_orig.flat,yy_orig.flat),
                            data_orig.flat,(mx.flat,my.flat),
                            method=method).reshape(xx_new_dim,yy_new_dim)
                        # (mx.flat,my.flat),method=method)
    if debug:
        print("Completed reprojection.")
    return data_new


import sys
import os
import subprocess
from threading import Thread
import json
import sublime
import sublime_plugin
import time
import re
import ftplib
import platform
#Libreria para sftp desde Linux(Ubuntu)
from .src.Configuration import Configuration
from .src.Connection import Connection
from .src.ProgressBar import ProgressBarCommand as ProgressBar, ShowProgressBarCommand
from .src.extras import get_list_servers, sortFiles, createFile, readFile, Debug, getTmpName, getPath
import datetime
import shutil

def plugin_loaded():
	# Se crea el directorio del plugin
	user_path = os.path.join(sublime.packages_path(), 'User')
	Configuration.mysftp_path = os.path.join(user_path, 'MySFTP')
	if not os.path.exists(Configuration.mysftp_path): os.makedirs(Configuration.mysftp_path)

	# Se crea el directorio para los archivos temporales
	Configuration.tmp_path = os.path.join(Configuration.mysftp_path, 'tmp')
	if os.path.exists(Configuration.tmp_path):
		shutil.rmtree(Configuration.tmp_path)

	if not os.path.exists(Configuration.tmp_path): os.makedirs(Configuration.tmp_path)

	# Se crea directorio para los archivos de configuración de servidores
	Configuration.servers_path = os.path.join(Configuration.mysftp_path, 'servers')
	if not os.path.exists(Configuration.servers_path): os.makedirs(Configuration.servers_path)

	# Se crea directorio para psftp
	Configuration.psftp_path = os.path.join(Configuration.mysftp_path, 'psftp')
	if not os.path.exists(Configuration.psftp_path): os.makedirs(Configuration.psftp_path)

	Configuration.package_path = os.path.join(sublime.packages_path(), 'MySFTP')

	Debug.debug_file = os.path.join(Configuration.mysftp_path, '.debug')

	MySftp.settings = sublime.load_settings("MySFTP.sublime-settings")
	Debug.settings = MySftp.settings
	# create custome file settings
	if not os.path.exists(os.path.join(user_path, 'MySFTP.sublime-settings')):
		json_settings = {
			'debug_mode': MySftp.settings.get('debug_mode') or False,
			'debug_console': MySftp.settings.get('debug_console') or False,
			'check_if_write': MySftp.settings.get('check_if_write') or False
		}
		createFile(os.path.join(user_path, 'MySFTP.sublime-settings'), json.dumps(json_settings, indent='\t'))
	Debug.print("DEBUG_MODE: ", str(MySftp.settings.get('debug_mode')))
	Debug.print("DEBUG_CONSOLE: ", str(MySftp.settings.get('debug_console')))
	Debug.print("CHECK_IF_WRITE: ", str(MySftp.settings.get('check_if_write')))

	# Movemos los archivos de configuración servidores de la versión anterior al directorio servers
	for file in os.listdir( user_path ):
		full_name_file = os.path.join(user_path, file)
		if os.path.isfile(full_name_file):
			filename, file_extension = os.path.splitext(file)
			if file_extension != ".json":
				continue
			file_content = readFile( full_name_file )
			obj_match = re.findall(r"nick|type|host|remote_path|password|port|user", file_content)
			if obj_match != None and len(obj_match) == 7:
				shutil.move( full_name_file, os.path.join(Configuration.servers_path, file) )

	createFile(os.path.join(Configuration.mysftp_path, '.debug'))

class MySftp(sublime_plugin.TextCommand):
	listServers = []
	optionsFiles = ["> Cambiar de Servidor", "> Regresar", "> Editar","> Renombrar","> Cambiar Permisos","> Eliminar"]
	optionsFolders = ["> Cambiar de Servidor", "> Subir nivel","> Nuevo Archivo","> Nueva Carpeta","> Renombrar","> Cambiar Permisos","> Eliminar"]

	settings = None

	def run(self, edit):
		archivos = get_list_servers(Configuration.servers_path)
		self.view.window().run_command("show_servers", {"args" : archivos});

	@staticmethod
	def isWorking():
		try:
			if ShowProgressBarCommand.loading:
				raise Exception("threading isAlive")
		except Exception as e:
			sublime.message_dialog("Hay una operación en proceso, espere a que esta termine para continuar.")
			raise e

	@staticmethod
	def checkResponse(self, response, show_status = True):
		if not show_status:
			return True
		if response.find('Could not resolve hostname') != -1 or response.find('No route to host') != -1 or response.find('Network is unreachable') != -1 or response.find('Connection refused') != -1:
			ProgressBar.showError(self)
			ProgressBar.showMessage(self, 'Imposible conectar con el servidor, no se pudo resolver: {}.\n'.format(Configuration.host))
			return False
		elif response.find('Permission denied') != -1 or response.find('Could not create file') != -1:
			ProgressBar.showErrorPermissions(self)
			return False
		elif response.find('Usuario o password incorrectos') != -1 or response.find('Login incorrect') != -1:
			ProgressBar.showErrorCredentials(self)
			return False
		elif response.find('TimeOutExpired') != -1:
			ProgressBar.showErrorTimeOutExpired(self)
		elif response.find('o such file or directory') != -1:
			ProgressBar.showErrorNoSuchFileOrDirectory(self)
		elif response.find('PermissionError: [WinError 32]') != -1:
			ProgressBar.showError(self)
		elif response.find('No se puede establecer una conexión ya que el equipo de destino denegó expresamente') != -1:
			ProgressBar.showConnectionRefuse(self)
			return False
		else:
			ProgressBar.showSuccess(self)
		return True

class SyncFiles(sublime_plugin.WindowCommand):
	def run(self, comando):
		file = os.path.basename(self.window.active_view().file_name())

		if comando == "put_sftp":
			self.window.run_command("save");
			return

		Configuration.setConfig(os.path.join(Configuration.tmp_path, os.path.splitext(file)[0] + ".config"))
		if Configuration.flag_config != True:
			return

		if ProgressBar.createPanelOutput == False:
			ProgressBar.initConnection(self)
		self.window.run_command("get_sftp",{"file" : file, "flag" : True})

	def is_visible(self):
		return False if os.path.dirname(self.window.active_view().file_name()) != Configuration.tmp_path else True

class showServers(sublime_plugin.WindowCommand):
	def run(self, args):
		MySftp.isWorking();
		MySftp.listServers = args
		MySftp.listServers.insert(0, "Nuevo servidor.")
		quick_list = [option for option in MySftp.listServers]
		self.quick_list = quick_list
		self.window.show_quick_panel(quick_list,self.on_done,0)

	def on_done(self, index):
		if index == 0:
			self.window.run_command('new_server')
		elif index > 0:
			previous_config = Configuration( json.loads(Configuration.getJsonConfig()) )
			Configuration.setConfig(os.path.join(Configuration.servers_path, MySftp.listServers[index] + ".json"))
			if not Configuration.flag_config:
				return
			if previous_config.host == '' or previous_config.usuario == '' or previous_config.host != Configuration.host or previous_config.usuario != Configuration.usuario or previous_config.puerto != Configuration.puerto:
				ProgressBar.initConnection(self)

			t1 = Thread(target=self.listado)
			t1.start()

	def listado(self):
		self.window.run_command("show_ls");

class showLs(sublime_plugin.WindowCommand):

	list_files = None
	files_hiddens = None

	def run(self):
		MySftp.isWorking();
		ProgressBar.showList(self)
		t1 = Thread(target=self.requestListFiles)
		t1.start()

	def requestListFiles(self):
		response = showLs.getListFiles(self, True)
		if showLs.list_files != None and response != False:
			self.Options = ["Directorio: " + Configuration.currentPath] + MySftp.optionsFolders + showLs.list_files
			quick_list = [option for option in self.Options]
			self.quick_list = quick_list
			self.window.show_quick_panel(quick_list, lambda id : self.on_done(id), 0)

	def on_done(self, index):
		if index > 7:
			if showLs.list_files[index - 8][-1:] == '/':
				Configuration.currentPath = getPath(Configuration.currentPath, showLs.list_files[index - 8])
				self.window.run_command("show_ls");
			elif showLs.list_files[index - 8][-2:] == '->':
				# no such file or directory
				tmp_current_path = Configuration.currentPath
				Configuration.currentPath = getPath(Configuration.currentPath, showLs.list_files[index - 8][:-2])
				list_files_old = showLs.list_files
				salida = showLs.getListFiles(self)
				showLs.list_files = list_files_old
				if salida != False and salida.find("no such file or directory") != -1:
					Configuration.currentPath = tmp_current_path;
					self.Options = [ "Archivo: " + showLs.list_files[index - 8][:-2] ] + MySftp.optionsFiles
					quick_list = [option for option in self.Options]
					self.quick_list = quick_list
					self.window.show_quick_panel(quick_list, lambda id : self.file_selected(id, showLs.list_files[index - 8][:-2]), 0)
				else:
					Configuration.currentPath = tmp_current_pathn;
					Configuration.currentPath = getPath(Configuration.currentPath, showLs.list_files[index - 8][:-2])
					self.window.run_command("show_ls");
			else:
				self.Options = [ "Archivo: " + showLs.list_files[index - 8] ] + MySftp.optionsFiles
				quick_list = [option for option in self.Options]
				self.quick_list = quick_list
				self.window.show_quick_panel(quick_list, lambda id : self.file_selected(id, showLs.list_files[index - 8]), 0)
		elif index == 2: # Up Level
			Configuration.currentPath = getPath(Configuration.currentPath, '../')
			self.window.run_command("show_ls");
		else:
			commams_folders = [['my_sftp', {}], ['show_ls', {}], ['new_file_sftp', {}], ['new_dir_sftp', {}],
								['rename_sftp', {"path" : os.path.basename(Configuration.currentPath), 'is_folder': True}], ['chmod_sftp', {"path" : os.path.basename(Configuration.currentPath), 'is_file': False}],
								['remove_sftp', {"path" : os.path.basename(Configuration.currentPath), "is_file" : False}]]
			if index > 0:
				self.window.run_command( commams_folders[index - 1][0], commams_folders[index - 1][1] )

	def file_selected(self, index, file):
		commams_files = [['my_sftp', {}], ['show_ls', {}], ['get_sftp', {"file" : file}],
						['rename_sftp', {"path" : file}], ['chmod_sftp', {"path" : file}],
						['remove_sftp', {"path" : file, "is_file" : True}]]
		if index == 2:
			self.Options = ["Directorio: " + Configuration.currentPath] + MySftp.optionsFolders + showLs.list_files
			quick_list = [option for option in self.Options]
			self.quick_list = quick_list
			self.window.show_quick_panel(quick_list, lambda id : self.on_done(id), 0)
		if index != 2 and index > 0:
			self.window.run_command( commams_files[index - 1][0], commams_files[index - 1][1] )

	@staticmethod
	def getListFiles(self, show_status_connection = False):
		salida = Connection.ls()
		if show_status_connection:
			if MySftp.checkResponse(self, salida, show_status_connection) != True: return False
		lista = salida.strip("\n").split("\n")
		listas = sortFiles(lista)
		showLs.list_files = listas[0]
		showLs.files_hiddens = listas[1]
		return salida

class ChmodSftp(sublime_plugin.WindowCommand):

	def run(self, path, is_file = True):
		self.window.show_input_panel("Permisos:", "", lambda permisos: self.chmod(permisos, path, is_file), None, None)

	def chmod(self, permisos, path, is_file = True):
		if re.match("[1-7]{3}", permisos) != None:
			burbuja = Configuration.currentPath
			if not is_file:
				Configuration.currentPath = os.path.dirname(Configuration.currentPath)

			ProgressBar.showChmod(self, getPath(Configuration.currentPath, path))
			t1 = Thread(target=self.hilo, args=[permisos, path, burbuja])
			t1.start()
		else:
			sublime.message_dialog("La sintaxis para definir permisos no es valida.")

	def hilo(self, permisos, path, burbuja):
		salida = Connection.chmod(path, permisos)
		Configuration.currentPath = burbuja
		if MySftp.checkResponse(self, salida) != True:
			return

class removeSftp(sublime_plugin.TextCommand):

	def run(self, edit, path, is_file = True):
		burbuja = Configuration.currentPath
		if is_file == False:
			Configuration.currentPath = os.path.dirname(Configuration.currentPath)

		if path.find('.mysftp') == -1: # No lo encuentra
			ProgressBar.showDelete(self, getPath(Configuration.currentPath, path))

		t1 = Thread(target=self.hilo, args=[edit, path, is_file, burbuja])
		t1.start()

	def hilo(self, edit, path, is_file, burbuja):
		salida = Connection.rm(path, is_file)
		if path.find('.mysftp') == -1 and MySftp.checkResponse(self, salida) != True:
			Configuration.currentPath = burbuja
			return

class getSftp(sublime_plugin.TextCommand):

	def run(self, edit, file, flag = False):
		MySftp.isWorking();
		t1 = Thread(target=self.hilo, args=[edit, file, flag])
		t1.start()

	def hilo(self, edit, file, flag = False):
		ProgressBar.showDownload(self, getPath(Configuration.currentPath, file), file)

		if MySftp.settings.get('check_if_write') and "\n".join(showLs.files_hiddens).find( getTmpName(file) ) != -1: # Validamos que exista el archivo
			salida = Connection.get(getTmpName(file), os.path.join(Configuration.tmp_path, getTmpName(file)))
			if os.path.exists(os.path.join(Configuration.tmp_path, getTmpName(file))):
				nick_current_use = readFile(os.path.join(Configuration.tmp_path, getTmpName(file))).strip()
				os.remove(os.path.join(Configuration.tmp_path, getTmpName(file)))
				if nick_current_use != Configuration.nick:
					if not sublime.ok_cancel_dialog("El usuario " + nick_current_use + " esta usando actualmente el archivo, Deseas continuar con la descarga?."):
						Debug.print('Se manda a cancelar.')
						ProgressBar.showCancel(self)
						return

		if os.path.exists(os.path.join(Configuration.tmp_path, file)) and self.view.window().find_open_file(os.path.join(Configuration.tmp_path, file)) and flag == False:
			sublime.message_dialog("Ya existe un archivo con el mismo nombre, cierre primero para poder continuar editando otro archivo con el mismo nombre.")
			return

		salida = Connection.get(file, os.path.join(Configuration.tmp_path, file))
		time.sleep(0.02) # Esperamos que se termine de descargar el contenido
		if MySftp.checkResponse(self, salida) != True: return

		# Hay que poner los stops en los progressbar
		if os.path.exists(os.path.join(Configuration.tmp_path, file)):
			#ProgressBar.showSuccess(self)
			createFile(os.path.join(Configuration.tmp_path, os.path.splitext(file)[0] + ".path"), Configuration.currentPath)
			createFile(os.path.join(Configuration.tmp_path, os.path.splitext(file)[0] + ".config"), Configuration.getJsonConfig())
			vista = self.view.window().open_file(os.path.join(Configuration.tmp_path, file))
			t2 = Thread(target=self.hilo2, args=[file])
			t2.start()
		else:
			pass
			#ProgressBar.showError(self)

	def hilo2(self, file):
		createFile(os.path.join(Configuration.tmp_path, getTmpName(file)), Configuration.nick)
		salida = Connection.put(os.path.join(Configuration.tmp_path, getTmpName(file)), getTmpName(os.path.basename(file)))
		time.sleep(0.02)
		if os.path.exists(os.path.join(Configuration.tmp_path, getTmpName(file))):
			os.remove(os.path.join(Configuration.tmp_path, getTmpName(file)))

class MySftpEvent(sublime_plugin.EventListener):
	def on_post_save(self, view):
		ruta = view.file_name()
		if ruta != None and os.path.dirname(ruta) == Configuration.tmp_path:
			view.run_command("put_sftp", {"file" : view.file_name(), "flag" : False })
		else:
			Debug.print("este archivo no es valido para el package.")

	def on_close(self, view):
		ruta = view.file_name()
		if ruta != None and os.path.dirname(ruta) == Configuration.tmp_path and view.is_dirty() == False:
			view.run_command("remove_sftp", {"path" : getTmpName( os.path.basename(ruta) ), "is_file" : True})
			t1 = Thread(target=self.closeFile, args=[view, ruta])
			t1.start()

	def closeFile(self, view, ruta):
		if os.path.exists(ruta):
			os.remove(ruta)
		if os.path.exists( getTmpName(os.path.splitext(ruta)[0]) ):
			os.remove( getTmpName(os.path.splitext(ruta)[0]) )
		os.remove(os.path.splitext(ruta)[0] + ".path")
		os.remove(os.path.splitext(ruta)[0] + ".config")

class putSftp(sublime_plugin.TextCommand):

	def run(self, edit, file , flag):
		MySftp.isWorking();

		ruta = file.replace('.mysftp', "") if flag == True else file

		if os.path.dirname(ruta) != Configuration.tmp_path:
			return

		path_put = Configuration.currentPath
		old_path = Configuration.currentPath

		if flag == False:
			path_put = readFile(os.path.splitext(ruta)[0] + ".path")
			json_file = json.loads( readFile(os.path.splitext(ruta)[0] + ".config") )
			if Configuration.host == '' or Configuration.usuario == '' or Configuration.password == '' or Configuration.host != json_file[0]["host"] or Configuration.usuario != json_file[0]["user"] or Configuration.password != json_file[0]["password"]:
				Configuration.setConfig(os.path.splitext(ruta)[0] + ".config")
				if Configuration.flag_config != True:
					return
				ProgressBar.initConnection(self)
		Configuration.currentPath = path_put
		t1 = Thread(target=self.hilo1, args=[edit, ruta, flag, old_path])
		t1.start()

	def hilo1(self, edit, ruta, flag, old_path):
		if flag == False:
			ProgressBar.showUpload(self, os.path.basename(ruta), getPath(Configuration.currentPath, os.path.basename(ruta)))

		if MySftp.settings.get('check_if_write'):
			salida = Connection.get(getTmpName(ruta), os.path.join(Configuration.tmp_path, getTmpName(ruta)))
			if os.path.exists( os.path.join(Configuration.tmp_path, getTmpName(ruta)) ):#Validamos que exista el archivo
				nick_current_use = readFile(os.path.join(Configuration.tmp_path, getTmpName(ruta))).strip()
				if Configuration.nick != nick_current_use and flag == False:
					if not sublime.ok_cancel_dialog("El usuario " + nick_current_use + " esta usando actualmente el archivo, Deseas subir tus cambios?."):
						ProgressBar.showCancel(self)
						return

		createFile(os.path.join(Configuration.tmp_path, getTmpName(ruta)), Configuration.nick)

		if flag == False:
			t2 = Thread(target=self.hilo2, args=[edit, ruta, flag, old_path])
			t2.start()

	def hilo2(self, edit, ruta, flag, old_path):
		salida = Connection.put(ruta, os.path.basename(ruta))
		if 'nick_current_use' in locals():
			if Configuration.nick != nick_current_use:
				os.remove(os.path.join(Configuration.tmp_path, getTmpName(ruta)))
		if not flag:
			if MySftp.checkResponse(self, salida) != True: return

		t3 = Thread(target=self.hilo3, args=[edit, ruta, old_path])
		t3.start()

	def hilo3(self, edit, ruta, old_path):
		salida = Connection.put(os.path.join(Configuration.tmp_path, getTmpName(ruta)), getTmpName(ruta))
		Configuration.currentPath = old_path
		time.sleep(0.02)
		if os.path.exists(os.path.join(Configuration.tmp_path, getTmpName(ruta))):
			os.remove(os.path.join(Configuration.tmp_path, getTmpName(ruta)))

class newFileSftp(sublime_plugin.WindowCommand):
	def run(self):
		t1 = Thread(target=self.getListFiles)
		t1.start()
		time.sleep(0.16)
		self.window.show_input_panel("Nombre del archivo:", "", self.createFile, None, None)

	def createFile(self,name_file):
		# Validamos el nombre de archivo
		name_file = name_file.strip();
		if re.match("^[\w\-. ]+$", name_file):
			# Revisamos que no exista el archivo en remoto
			if name_file in showLs.list_files:
				sublime.message_dialog("Ya existe un archivo con el nombre: " + name_file + " en: " + Configuration.currentPath)
				return
			if os.path.isfile(os.path.join(Configuration.tmp_path, name_file)):
				sublime.message_dialog("Se encuentra editando un archivo con el mismo nombre, se recomienda cerrarlo primero.")
			else:
				local_file = os.path.join(Configuration.tmp_path, name_file)
				createFile(local_file)
				createFile(os.path.join(Configuration.tmp_path, os.path.splitext(name_file)[0] + ".path"), Configuration.currentPath)
				createFile(os.path.join(Configuration.tmp_path, os.path.splitext(name_file)[0] + ".config"), Configuration.getJsonConfig())
				ProgressBar.showMakeFile(self, getPath(Configuration.currentPath, name_file))
				t2 = Thread(target=self.hilo, args=[local_file])
				t2.start()
		else:
			sublime.message_dialog("Nombre de archivo no valido")

	def hilo(self, local_file):
		salida = Connection.put(local_file, os.path.basename(local_file))
		tmp_name = os.path.join(Configuration.tmp_path, getTmpName(os.path.basename(local_file)))
		createFile(tmp_name, Configuration.nick)
		Connection.put(tmp_name, os.path.basename(tmp_name))
		time.sleep(0.08)
		os.remove(tmp_name)
		if MySftp.checkResponse(self, salida) == True:
			self.window.open_file(local_file)

	def getListFiles(self):
		showLs.getListFiles(self)

class newDirSftp(sublime_plugin.WindowCommand):
	def run(self):
		t1 = Thread(target=self.getListFiles)
		t1.start()
		time.sleep(0.16)
		self.window.show_input_panel("Nombre del directorio:", "", self.createDir, None, None)

	def createDir(self, name_dir):
		name_dir = name_dir.strip();
		if re.match("^[\w\-. ]+$", name_dir):
			# Revisamos que no exista el archivo en remoto
			if (name_dir + '/') in showLs.list_files:
				sublime.message_dialog("Ya existe un directorio con el nombre: " + name_dir + " en: " + Configuration.currentPath)
				return
			t2 = Thread(target=self.hilo, args=[name_dir])
			t2.start()

	def hilo(self, name_dir):
		ProgressBar.showMakeDir(self, getPath(Configuration.currentPath, name_dir ))
		salida = Connection.mkdir(name_dir)
		if MySftp.checkResponse(self, salida) != True: return
		Configuration.currentPath = getPath(Configuration.currentPath, name_dir)
		self.window.run_command("show_ls");

	def getListFiles(self):
		showLs.getListFiles(self)

class ServerManager(sublime_plugin.WindowCommand):
	def run(self, action):
		MySftp.listServers = get_list_servers(Configuration.servers_path)
		quick_list = [option for option in MySftp.listServers]
		self.quick_list = quick_list
		self.window.show_quick_panel(quick_list,lambda id : self.on_done(id, action),0)

	def on_done(self, index, action):
		if index >= 0:
			if action == 'edit':
				self.window.open_file(os.path.join(Configuration.servers_path, MySftp.listServers[index] + ".json"))
			elif action == 'remove':
				os.remove(os.path.join(Configuration.servers_path, MySftp.listServers[index] + ".json"))

class NewServer(sublime_plugin.WindowCommand):
	def run(self):
		vista = self.window.new_file()
		vista.run_command('insert_snippet', {"name": "Packages/MySFTP/server.sublime-snippet" })
		vista.set_syntax_file("JSON.sublime-syntax")
		vista.set_name('server.json')
		vista.settings().set('default_dir', Configuration.servers_path)

class renameSftp(sublime_plugin.WindowCommand):
	def run(self, path, is_folder = False):
		self.window.show_input_panel("Nombre Nuevo:", path, lambda name:self.rename(path, name, is_folder), None, None)

	def rename(self, current_name, new_name, is_folder = False):
		ProgressBar.showRename(self, current_name, new_name)
		t1 = Thread(target=self.hilo, args=[current_name, new_name, is_folder])
		t1.start()

	def hilo(self, current_name, new_name, is_folder = False):
		burbuja = Configuration.currentPath
		if is_folder:
			Configuration.currentPath = os.path.dirname(Configuration.currentPath)

		salida = Connection.mv(current_name, new_name)

		if MySftp.checkResponse(self, salida) != True:
			if is_folder:
				Configuration.currentPath = burbuja
			return
		else:
			if is_folder:
				Configuration.currentPath = getPath(Configuration.currentPath, new_name)

class SideBar(sublime_plugin.WindowCommand):
	def run(self, paths = []):
		###self.window.run_command("progress_bar", {"msg" : "\nCargando "})
		ProgressBar.showDownload(self)
		t1 = Thread(target=self.testLoad)
		t1.start()

	def testLoad(self):
		# self.window.run_command("progress_bar", {"msg" : "", "start_loading": True, "stop_loading": False})
		time.sleep(2)
		# self.window.run_command("progress_bar", {"msg" : "success", "start_loading": False, "stop_loading": True})
		ProgressBar.showSuccess(self)

	def is_visible(self, paths = ''):
		return True

	def is_enabled(self, paths = ''):
		Debug.print("$path", paths)
		return True


import torch
from torch import nn
import torch.nn.functional as F
from torchvision import models
from torch.nn.utils.spectral_norm import spectral_norm
# from spatial_correlation_sampler import spatial_correlation_sample
from .resample2d import Resample2d
import torchvision.utils as vutils

class Discriminator(nn.Module):
    def __init__(self, input_dim=3, dim=64, n_layers=3,
                norm='none', activ='lrelu', pad_type='reflect', use_sn=True):
        super(Discriminator, self).__init__()

        self.model = nn.ModuleList()
        self.model.append(Conv2dBlock(input_dim,dim,4,2,1,'none',activ,pad_type,use_sn=use_sn))
        dim_in = dim
        for i in range(n_layers - 1):
            dim_out = min(dim*8, dim_in*2)
            self.model.append(DownsampleResBlock(dim_in,dim_out,'none',activ,pad_type,use_sn))
            dim_in = dim_out

        self.model.append(Conv2dBlock(dim_in,1,1,1,activation='none',use_bias=False, use_sn=use_sn))
        self.model = nn.Sequential(*self.model)

    def forward(self, x):
        return self.model(x)

class MultiDiscriminator(nn.Module):
    def __init__(self, **parameter_dic):
        super(MultiDiscriminator, self).__init__()
        self.model_1 = Discriminator(**parameter_dic)
        self.down = nn.AvgPool2d(3, stride=2, padding=[1, 1], count_include_pad=False)
        self.model_2 = Discriminator(**parameter_dic)

    def forward(self, x):
        pre1 = self.model_1(x)
        pre2 = self.model_2(self.down(x))
        return [pre1, pre2]

class StructureGen(nn.Module):
    def __init__(self, input_dim=3, dim=64, n_res=4, activ='relu',
                 norm='in', pad_type='reflect', use_sn=True):
        super(StructureGen, self).__init__()

        self.down_sample=nn.ModuleList()
        self.up_sample=nn.ModuleList()
        self.content_param=nn.ModuleList()

        self.input_layer = Conv2dBlock(input_dim*2+1, dim, 7, 1, 3, norm, activ, pad_type, use_sn=use_sn)
        self.down_sample += [nn.Sequential(
            Conv2dBlock(dim, 2*dim, 4, 2, 1, norm, activ, pad_type, use_sn=use_sn),
            Conv2dBlock(2*dim, 2*dim, 5, 1, 2, norm, activ, pad_type, use_sn=use_sn))]

        self.down_sample += [nn.Sequential(
            Conv2dBlock(2*dim, 4*dim, 4, 2, 1,norm, activ, pad_type, use_sn=use_sn),
            Conv2dBlock(4*dim, 4*dim, 5, 1, 2,norm, activ, pad_type, use_sn=use_sn))]

        self.down_sample += [nn.Sequential(
            Conv2dBlock(4*dim, 8*dim, 4, 2, 1,norm, activ, pad_type, use_sn=use_sn))]
        dim = 8*dim
        # content decoder
        self.up_sample += [(nn.Sequential(
            ResBlocks(n_res, dim, norm, activ, pad_type=pad_type),
            nn.Upsample(scale_factor=2),
            Conv2dBlock(dim, dim // 2, 5, 1, 2, norm, activ, pad_type, use_sn=use_sn)) )]

        self.up_sample += [(nn.Sequential(
            ResBlocks(n_res, dim//2, norm, activ, pad_type=pad_type),
            nn.Upsample(scale_factor=2),
            Conv2dBlock(dim//2, dim//4, 5, 1, 2,norm, activ, pad_type, use_sn=use_sn)) )]

        self.up_sample += [(nn.Sequential(
            ResBlocks(n_res, dim//4, norm, activ, pad_type=pad_type),
            nn.Upsample(scale_factor=2),
            Conv2dBlock(dim//4, dim//8, 5, 1, 2,norm, activ, pad_type, use_sn=use_sn)) )]

        self.content_param += [Conv2dBlock(dim//2, dim//2, 5, 1, 2, norm, activ, pad_type)]
        self.content_param += [Conv2dBlock(dim//4, dim//4, 5, 1, 2, norm, activ, pad_type)]
        self.content_param += [Conv2dBlock(dim//8, dim//8, 5, 1, 2, norm, activ, pad_type)]

        self.image_net = Get_image(dim//8, input_dim)

    def forward(self, inputs):
        x0 = self.input_layer(inputs)
        x1 = self.down_sample[0](x0)
        x2 = self.down_sample[1](x1)
        x3 = self.down_sample[2](x2)

        u1 = self.up_sample[0](x3) + self.content_param[0](x2)
        u2 = self.up_sample[1](u1) + self.content_param[1](x1)
        u3 = self.up_sample[2](u2) + self.content_param[2](x0)

        images_out = self.image_net(u3)
        return images_out

class FlowGen(nn.Module):
    def __init__(self, input_dim=3, dim=64, n_res=2, activ='relu',
                norm_flow='ln', norm_conv='in', pad_type='reflect', use_sn=True):
        super(FlowGen, self).__init__()

        self.flow_column = FlowColumn(input_dim, dim, n_res, activ,
                                      norm_flow, pad_type, use_sn)
        self.conv_column = ConvColumn(input_dim, dim, n_res, activ,
                                      norm_conv, pad_type, use_sn)

    def forward(self, inputs):
        flow_map = self.flow_column(inputs)
        images_out = self.conv_column(inputs, flow_map)
        return images_out, flow_map

class ConvColumn(nn.Module):
    def __init__(self, input_dim=3, dim=64, n_res=2, activ='lrelu',
                 norm='ln', pad_type='reflect', use_sn=True):
        super(ConvColumn, self).__init__()

        self.down_sample  = nn.ModuleList()
        self.up_sample    = nn.ModuleList()

        self.down_sample += [nn.Sequential(
                            Conv2dBlock(input_dim*2+1, dim//2, 7, 1, 3, norm, activ, pad_type, use_sn=use_sn),
                            Conv2dBlock(dim//2, dim,   4, 2, 1, norm, activ, pad_type, use_sn=use_sn),
                            Conv2dBlock(dim,    dim,   5, 1, 2, norm, activ, pad_type, use_sn=use_sn),
                            Conv2dBlock(dim,    2*dim, 4, 2, 1, norm, activ, pad_type, use_sn=use_sn),
                            Conv2dBlock(2*dim,  2*dim, 5, 1, 2, norm, activ, pad_type, use_sn=use_sn))]

        self.down_sample += [nn.Sequential(
                            Conv2dBlock(2*dim,  4*dim, 5, 1, 2, norm, activ, pad_type, use_sn=use_sn),
                            Conv2dBlock(4*dim,  8*dim, 4, 2, 1, norm, activ, pad_type, use_sn=use_sn))]
        dim = 8*dim

        # content decoder
        self.up_sample   += [(nn.Sequential(
                             ResBlocks(n_res, dim, norm, activ, pad_type=pad_type),
                             nn.Upsample(scale_factor=2),
                             Conv2dBlock(dim, dim//2, 5, 1, 2, norm, activ, pad_type, use_sn=use_sn)) )]

        self.up_sample   += [(nn.Sequential(
                            Conv2dBlock(dim, dim//2, 5, 1, 2,norm, activ, pad_type, use_sn=use_sn),
                            ResBlocks(n_res, dim//2, norm, activ, pad_type=pad_type),
                            nn.Upsample(scale_factor=2),
                            Conv2dBlock(dim//2, dim//4, 5, 1, 2,norm, activ, pad_type, use_sn=use_sn),

                            ResBlocks(n_res, dim//4, norm, activ, pad_type=pad_type),
                            nn.Upsample(scale_factor=2),
                            Conv2dBlock(dim//4, dim//8, 5, 1, 2,norm, activ, pad_type, use_sn=use_sn),
                            Get_image(dim//8, input_dim)) )]

        self.resample16 = Resample2d(16, 1, sigma=4)
        self.resample4  = Resample2d(4,  1, sigma=2)

    def forward(self, inputs, flow_maps):
        x1 = self.down_sample[0](inputs)
        x2 = self.down_sample[1](x1)
        flow_fea = self.resample_image(x1, flow_maps)

        u1 = torch.cat((self.up_sample[0](x2), flow_fea), 1)
        images_out = self.up_sample[1](u1)
        return images_out

    def resample_image(self, img, flow):
        output16 = self.resample16(img, flow)
        output4  = self.resample4 (img, flow)
        outputs = torch.cat((output16,output4), 1)
        return outputs

class FlowColumn(nn.Module):
    def __init__(self, input_dim=3, dim=64, n_res=2, activ='lrelu',
                 norm='in', pad_type='reflect', use_sn=True):
        super(FlowColumn, self).__init__()

        self.down_sample_flow  = nn.ModuleList()
        self.up_sample_flow    = nn.ModuleList()

        self.down_sample_flow.append( nn.Sequential(
                                    Conv2dBlock(input_dim*2+1, dim//2, 7, 1, 3, norm, activ, pad_type, use_sn=use_sn),
                                    Conv2dBlock(dim//2, dim, 4, 2, 1, norm, activ, pad_type, use_sn=use_sn),
                                    Conv2dBlock(   dim, dim, 5, 1, 2, norm, activ, pad_type, use_sn=use_sn)))
        self.down_sample_flow.append( nn.Sequential(
                                    Conv2dBlock(  dim, 2*dim, 4, 2, 1, norm, activ, pad_type, use_sn=use_sn),
                                    Conv2dBlock(2*dim, 2*dim, 5, 1, 2, norm, activ, pad_type, use_sn=use_sn)))
        self.down_sample_flow.append(nn.Sequential(
                                    Conv2dBlock(2*dim, 4*dim, 4, 2, 1, norm, activ, pad_type, use_sn=use_sn),
                                    Conv2dBlock(4*dim, 4*dim, 5, 1, 2, norm, activ, pad_type, use_sn=use_sn)))
        self.down_sample_flow.append(nn.Sequential(
                                    Conv2dBlock(4*dim, 8*dim, 4, 2, 1, norm, activ, pad_type, use_sn=use_sn),
                                    Conv2dBlock(8*dim, 8*dim, 5, 1, 2, norm, activ, pad_type, use_sn=use_sn)))
        dim = 8*dim

        # content decoder
        self.up_sample_flow.append(nn.Sequential(
                                    ResBlocks(n_res, dim, norm, activ, pad_type=pad_type),
                                    TransConv2dBlock(dim, dim//2, 6, 2, 2, norm=norm, activation=activ) ))

        self.up_sample_flow.append(nn.Sequential(
                                    Conv2dBlock(dim, dim//2, 5, 1, 2, norm, activ, pad_type, use_sn=use_sn),
                                    ResBlocks(n_res, dim//2, norm, activ, pad_type=pad_type),
                                    TransConv2dBlock(dim//2, dim//4, 6, 2, 2, norm=norm, activation=activ) ))

        self.location = nn.Sequential(
                                    Conv2dBlock(dim//2, dim//8, 5, 1, 2, norm, activ, pad_type, use_sn=use_sn),
                                    Conv2dBlock(dim//8, 2, 3, 1, 1, norm='none', activation='none', pad_type=pad_type, use_bias=False) )

    def forward(self, inputs):
        f_x1 = self.down_sample_flow[0](inputs)
        f_x2 = self.down_sample_flow[1](f_x1)
        f_x3 = self.down_sample_flow[2](f_x2)
        f_x4 = self.down_sample_flow[3](f_x3)

        f_u1 = torch.cat((self.up_sample_flow[0](f_x4), f_x3), 1)
        f_u2 = torch.cat((self.up_sample_flow[1](f_u1), f_x2), 1)
        flow_map = self.location(f_u2)
        return flow_map

##################################################################################
# Basic Blocks
##################################################################################
class Get_image(nn.Module):
    def __init__(self, input_dim, output_dim, activation='tanh'):
        super(Get_image, self).__init__()
        self.conv = Conv2dBlock(input_dim, output_dim, kernel_size=3, stride=1,
                     padding=1, pad_type='reflect', activation=activation)
    def forward(self, x):
        return self.conv(x)

class ResBlocks(nn.Module):
    def __init__(self, num_blocks, dim, norm='in', activation='relu', pad_type='zero', use_sn=False):
        super(ResBlocks, self).__init__()
        self.model = []
        for i in range(num_blocks):
            self.model += [ResBlock(dim, norm=norm, activation=activation, pad_type=pad_type, use_sn=use_sn)]
        self.model = nn.Sequential(*self.model)

    def forward(self, x):
        return self.model(x)

class ResBlock(nn.Module):
    def __init__(self, dim, norm='in', activation='relu', pad_type='zero', use_sn=False):
        super(ResBlock, self).__init__()

        model = []
        model += [Conv2dBlock(dim ,dim, 3, 1, 1, norm=norm, activation=activation, pad_type=pad_type, use_sn=use_sn)]
        model += [Conv2dBlock(dim ,dim, 3, 1, 1, norm=norm, activation='none', pad_type=pad_type, use_sn=use_sn)]
        self.model = nn.Sequential(*model)

    def forward(self, x):
        residual = x
        out = self.model(x)
        out += residual
        return out

class DilationBlock(nn.Module):
    def __init__(self, dim, norm='in', activation='relu', pad_type='zero'):
        super(DilationBlock, self).__init__()

        model = []
        model += [Conv2dBlock(dim ,dim, 3, 1, 2, norm=norm, activation=activation, pad_type=pad_type, dilation=2)]
        model += [Conv2dBlock(dim ,dim, 3, 1, 4, norm=norm, activation=activation, pad_type=pad_type, dilation=4)]
        model += [Conv2dBlock(dim ,dim, 3, 1, 8, norm=norm, activation=activation, pad_type=pad_type, dilation=8)]
        self.model = nn.Sequential(*model)

    def forward(self, x):
        out = self.model(x)
        return out

class Conv2dBlock(nn.Module):
    def __init__(self, input_dim ,output_dim, kernel_size, stride,
                 padding=0, norm='none', activation='relu', pad_type='zero', dilation=1,
                 use_bias=True, use_sn=False):
        super(Conv2dBlock, self).__init__()
        self.use_bias = use_bias
        # initialize padding
        if pad_type == 'reflect':
            self.pad = nn.ReflectionPad2d(padding)
        elif pad_type == 'replicate':
            self.pad = nn.ReplicationPad2d(padding)
        elif pad_type == 'zero':
            self.pad = nn.ZeroPad2d(padding)
        else:
            assert 0, "Unsupported padding type: {}".format(pad_type)

        # initialize normalization
        norm_dim = output_dim
        if norm == 'bn':
            self.norm = nn.BatchNorm2d(norm_dim)
        elif norm == 'in':
            self.norm = nn.InstanceNorm2d(norm_dim)
        elif norm == 'ln':
            self.norm = LayerNorm(norm_dim)
        elif norm == 'adain':
            self.norm = AdaptiveInstanceNorm2d(norm_dim)
        elif norm == 'none':
            self.norm = None
        else:
            assert 0, "Unsupported normalization: {}".format(norm)

        # initialize activation
        if activation == 'relu':
            self.activation = nn.ReLU(inplace=True)
        elif activation == 'lrelu':
            self.activation = nn.LeakyReLU(0.2, inplace=True)
        elif activation == 'prelu':
            self.activation = nn.PReLU()
        elif activation == 'selu':
            self.activation = nn.SELU(inplace=True)
        elif activation == 'tanh':
            self.activation = nn.Tanh()
        elif activation == 'sigmoid':
            self.activation = nn.Sigmoid()
        elif activation == 'none':
            self.activation = None
        else:
            assert 0, "Unsupported activation: {}".format(activation)

        # initialize convolution
        if use_sn:
            self.conv = spectral_norm(nn.Conv2d(input_dim, output_dim, kernel_size, stride, bias=self.use_bias, dilation=dilation))
        else:
            self.conv = nn.Conv2d(input_dim, output_dim, kernel_size, stride, bias=self.use_bias, dilation=dilation)

    def forward(self, x):
        x = self.conv(self.pad(x))
        if self.norm:
            x = self.norm(x)
        if self.activation:
            x = self.activation(x)
        return x

class TransConv2dBlock(nn.Module):
    def __init__(self, input_dim ,output_dim, kernel_size, stride,
                 padding=0, norm='none', activation='relu'):
        super(TransConv2dBlock, self).__init__()
        self.use_bias = True

        # initialize normalization
        norm_dim = output_dim
        if norm == 'bn':
            self.norm = nn.BatchNorm2d(norm_dim)
        elif norm == 'in':
            self.norm = nn.InstanceNorm2d(norm_dim)
        elif norm == 'in_affine':
            self.norm = nn.InstanceNorm2d(norm_dim, affine=True)
        elif norm == 'ln':
            self.norm = LayerNorm(norm_dim)
        elif norm == 'adain':
            self.norm = AdaptiveInstanceNorm2d(norm_dim)
        elif norm == 'none':
            self.norm = None
        else:
            assert 0, "Unsupported normalization: {}".format(norm)

        # initialize activation
        if activation == 'relu':
            self.activation = nn.ReLU(inplace=True)
        elif activation == 'lrelu':
            self.activation = nn.LeakyReLU(0.2, inplace=True)
        elif activation == 'prelu':
            self.activation = nn.PReLU()
        elif activation == 'selu':
            self.activation = nn.SELU(inplace=True)
        elif activation == 'tanh':
            self.activation = nn.Tanh()
        elif activation == 'sigmoid':
            self.activation = nn.Sigmoid()
        elif activation == 'none':
            self.activation = None
        else:
            assert 0, "Unsupported activation: {}".format(activation)

        # initialize convolution
        self.transConv = nn.ConvTranspose2d(input_dim, output_dim, kernel_size, stride, padding, bias=self.use_bias)

    def forward(self, x):
        x = self.transConv(x)
        if self.norm:
            x = self.norm(x)
        if self.activation:
            x = self.activation(x)
        return x

class AdaptiveInstanceNorm2d(nn.Module):
    def __init__(self, num_features, eps=1e-5, momentum=0.1):
        super(AdaptiveInstanceNorm2d, self).__init__()
        self.num_features = num_features
        self.eps = eps
        self.momentum = momentum
        # weight and bias are dynamically assigned
        self.weight = None
        self.bias = None
        # just dummy buffers, not used
        self.register_buffer('running_mean', torch.zeros(num_features))
        self.register_buffer('running_var', torch.ones(num_features))

    def forward(self, x):
        assert self.weight is not None and self.bias is not None, "Please assign weight and bias before calling AdaIN!"
        b, c = x.size(0), x.size(1)
        running_mean = self.running_mean.repeat(b)
        running_var = self.running_var.repeat(b)

        # Apply instance norm
        x_reshaped = x.contiguous().view(1, b * c, *x.size()[2:])

        out = F.batch_norm(
            x_reshaped, running_mean, running_var, self.weight, self.bias,
            True, self.momentum, self.eps)

        return out.view(b, c, *x.size()[2:])

    def __repr__(self):
        return self.__class__.__name__ + '(' + str(self.num_features) + ')'

class LayerNorm(nn.Module):
    def __init__(self, n_out, eps=1e-5, affine=True):
        super(LayerNorm, self).__init__()
        self.n_out = n_out
        self.affine = affine

        if self.affine:
          self.weight = nn.Parameter(torch.ones(n_out, 1, 1))
          self.bias = nn.Parameter(torch.zeros(n_out, 1, 1))

    def forward(self, x):
        normalized_shape = x.size()[1:]
        if self.affine:
          return F.layer_norm(x, normalized_shape, self.weight.expand(normalized_shape), self.bias.expand(normalized_shape))
        else:
          return F.layer_norm(x, normalized_shape)

class DownsampleResBlock(nn.Module):
    def __init__(self, input_dim, output_dim, norm='in', activation='relu', pad_type='zero', use_sn=False):
        super(DownsampleResBlock, self).__init__()
        self.conv_1 = nn.ModuleList()
        self.conv_2 = nn.ModuleList()

        self.conv_1.append(Conv2dBlock(input_dim,input_dim,3,1,1,'none',activation,pad_type,use_sn=use_sn))
        self.conv_1.append(Conv2dBlock(input_dim,output_dim,3,1,1,'none',activation,pad_type,use_sn=use_sn))
        self.conv_1.append(nn.AvgPool2d(kernel_size=2, stride=2))
        self.conv_1 = nn.Sequential(*self.conv_1)

        self.conv_2.append(nn.AvgPool2d(kernel_size=2, stride=2))
        self.conv_2.append(Conv2dBlock(input_dim,output_dim,1,1,0,'none',activation,pad_type,use_sn=use_sn))
        self.conv_2 = nn.Sequential(*self.conv_2)

    def forward(self, x):
        out = self.conv_1(x) + self.conv_2(x)
        return out


from flask import Flask
from keras.preprocessing import image
import numpy as np
from app.main.predict import predict
import json
from flask import request
import os
app = Flask(__name__)
upload_folder = './app/photos'
if os.path.exists(upload_folder):
    pass
else:
    os.mkdir(upload_folder)
@app.route('/',methods=['GET','POST'])
def index():
    upload_file = request.files('file')
    file_name = upload_file.filename
    upload_file.save(os.path.join(upload_folder,file_name))
    img = image.load_img(os.path.join(upload_folder,file_name), target_size=(224, 224))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = x / 255.0
    result = predict(x,model_path='./app/model/mobilenet_my_finetune_model_ep15_d3_lr0.0001.h5')
    return json.dumps(result)
if __name__== "__main__":
    app.run(host='0.0.0.0',port=5000)