#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 21 16:32:19 2021

@author: omartin
"""
import numpy as np
import scipy.interpolate as interp
import scipy.ndimage as scnd

def interpolateSupport(image,nRes,kind='spline'):

    # Define angular frequencies vectors
    nx,ny = image.shape

    if np.isscalar(nRes):
        mx = my = nRes
    else:
        mx = nRes[0]
        my = nRes[1]

    if kind == 'nearest':
        tmpReal = scnd.zoom(np.real(image),min([mx/nx,my/ny]),order=0)
        if np.any(np.iscomplex(image)):
            tmpImag = scnd.zoom(np.imag(image),min([mx/nx,my/ny]),order=0)
            return tmpReal + complex(0,1)*tmpImag
        else:
            return tmpReal
    else:

        # Initial frequencies grid
        if nx%2 == 0:
            uinit = np.linspace(-nx/2,nx/2-1,nx)*2/nx
        else:
            uinit = np.linspace(-np.floor(nx/2),np.floor(nx/2),nx)*2/nx
        if ny%2 == 0:
            vinit = np.linspace(-ny/2,ny/2-1,ny)*2/ny
        else:
            vinit = np.linspace(-np.floor(ny/2),np.floor(ny/2),ny)*2/ny

        # Interpolated frequencies grid
        if mx%2 == 0:
            unew = np.linspace(-mx/2,mx/2-1,mx)*2/mx
        else:
            unew = np.linspace(-np.floor(mx/2),np.floor(mx/2),mx)*2/mx
        if my%2 == 0:
            vnew = np.linspace(-my/2,my/2-1,my)*2/my
        else:
            vnew = np.linspace(-np.floor(my/2),np.floor(my/2),my)*2/my

        # Interpolation

        if kind == 'spline':
            # Surprinsingly v and u vectors must be shifted when using
            # RectBivariateSpline. See:https://github.com/scipy/scipy/issues/3164
            tmpReal = interp.fitpack2.RectBivariateSpline(vinit, uinit, np.real(image))
            tmpImag = interp.fitpack2.RectBivariateSpline(vinit, uinit, np.imag(image))
        else:
            tmpReal = interp.interp2d(uinit, vinit, np.real(image),kind=kind)
            tmpImag = interp.interp2d(uinit, vinit, np.imag(image),kind=kind)

        if np.any(np.iscomplex(image)):
            return tmpReal(unew,vnew) + complex(0,1)*tmpImag(unew,vnew)
        else:
            return tmpReal(unew,vnew)


import json

from firebase_admin.auth import AuthError

from dbcls.models import User, DataSet, UserRoleTypes
from .fixtures import client, users, data_sets, authorized_john, user_roles

HEADERS = {'Authorization': 'Bearer dummy-token'}

class TestMe:
    def test_get(self, client, users, user_roles, data_sets, authorized_john):
        with client:
            res = client.get('/api/v1/me', headers=HEADERS)
            assert res.status_code == 200
            assert res.get_json() == {
                'display_name': 'John Doe',
                'contact_uri': '',
                'roles': [UserRoleTypes.ADMIN.value],
            }

    def test_patch(self, client, users, user_roles, data_sets, authorized_john):
        with client:
            previous_display_name = authorized_john.display_name
            previous_contact_uri = authorized_john.contact_uri

            # 最大文字数を超えて変更
            data = json.dumps({'display_name': 'Jack' * 20, 'contact_uri': '12345' * 100})
            res = client.patch('/api/v1/me', data=data, headers=HEADERS, content_type='application/json')

            json_data = json.loads(data)
            assert res.status_code == 200
            assert res.get_json() == {
                'display_name': json_data['display_name'][:30],
                'contact_uri': json_data['contact_uri'][:255],
                'roles': [UserRoleTypes.ADMIN.value],
            }
            user = User.query.get(authorized_john.id)
            assert user.display_name != previous_display_name
            assert user.contact_uri != previous_contact_uri

            # 空文字にする
            previous_display_name = user.display_name
            previous_contact_uri = user.contact_uri
            data = json.dumps({'display_name': '', 'contact_uri': ''})
            res = client.patch('/api/v1/me', data=data, headers=HEADERS, content_type='application/json')

            assert res.status_code == 200
            assert res.get_json() == {
                'display_name': '',
                'contact_uri': '',
                'roles': [UserRoleTypes.ADMIN.value],
            }
            user = User.query.get(authorized_john.id)
            assert user.display_name != previous_display_name
            assert user.contact_uri != previous_contact_uri

    def test_patch_no_change(self, client, users, data_sets, authorized_john):
        with client:
            previous_display_name = authorized_john.display_name
            previous_contact_uri = authorized_john.contact_uri

            # 何も変更しない
            data = json.dumps({})
            res = client.patch('/api/v1/me', data=data, headers=HEADERS, content_type='application/json')

            json_data = json.loads(data)
            assert res.status_code == 200
            assert res.get_json() == {
                'display_name': previous_display_name,
                'contact_uri': previous_contact_uri,
                'roles': [],
            }
            user = User.query.get(authorized_john.id)
            assert user.display_name == previous_display_name
            assert user.contact_uri == previous_contact_uri

    def test_delete(self, client, users, data_sets, authorized_john):
        with client:
            # アカウント削除前
            previous_user_count = User.query.count()
            johns_data_set_query = DataSet.query.filter_by(user=authorized_john)
            assert johns_data_set_query.count() > 0
            res = client.get('/api/v1/me', headers=HEADERS)
            assert res.status_code == 200

            res = client.delete('/api/v1/me', headers=HEADERS)
            assert res.status_code == 204
            assert User.query.count() == previous_user_count - 1
            assert johns_data_set_query.count() == 0

            # 削除したので自分の情報は見れない
            res = client.get('/api/v1/me', headers=HEADERS)
            assert res.status_code == 401

class TestMyCustomToken:
    def test_get(self, client, users, data_sets, authorized_john, mocker):
        mocker.patch('firebase_admin.auth.get_user')
        custom_token_mock = mocker.Mock()
        custom_token_mock.decode.return_value = 'dummy_my_custom_token'
        mocker.patch('firebase_admin.auth.create_custom_token').return_value = custom_token_mock

        with client:
            res = client.get('/api/v1/me/custom_token', headers=HEADERS)
            assert res.status_code == 200
            assert res.get_json() == {'custom_token': 'dummy_my_custom_token'}

    def test_get_error(self, client, users, data_sets, authorized_john, mocker):
        get_user_mock = mocker.patch('firebase_admin.auth.get_user')
        get_user_mock.side_effect = AuthError(111, 'user not found on firebase')
        with client:
            res = client.get('/api/v1/me/custom_token', headers=HEADERS)
            assert res.status_code == 400
            assert res.get_json() == {'message': 'user not found on firebase'}

        get_user_mock.side_effect = ValueError('firebase uid is invalid')
        with client:
            res = client.get('/api/v1/me/custom_token', headers=HEADERS)
            assert res.status_code == 400
            assert res.get_json() == {'message': 'firebase uid is invalid'}


"""
Problem 024 : Lexicographical permutations

    A permutation is an ordered arrangement of objects.
    For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4.
    If all the permutations are listed numerically or alphabetically, we call it lexicographic order.
    The lexicographic permutations of 0, 1 and 2 are:

        012, 021, 102, 120, 201, 210

    What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?

        Solved in 556 ms.
"""

import time
from itertools import permutations

start = time.time_ns()

digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
s = ""

permutation_list = list(permutations(digits))
millionth = permutation_list[999999]
for digit in millionth:
    s += str(digit)
millionth = int(s)

end = time.time_ns()

print(__doc__)
print(f"Millionth lexicographic permutation of all digits is {millionth}, "
      f"found in {round((end - start)/ 1000000)} milliseconds.")


""" Test suite for the maltabar 'waitr' web API """

import unittest
import waitr
import json

API = '/api/v1'

class TestProbes(unittest.TestCase):

    def setUp(self):
        waitr.app.config['TESTING'] = True
        self.app = waitr.app.test_client()
        self.app.debug = True

    def test_get_probes(self):
        rv = self.app.get(API + '/probes')
        self.assertEqual(rv.status_code, 200, 'got: ' + rv.status)
        data = json.loads(rv.data)
        assert 'probes' in data

if __name__ == '__main__':
    unittest.main()


import os
import pickle

from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction
from rouge import Rouge

root_dir = os.path.abspath("..")

# считаем среднее значение метрики BLEU на тестовом датасете

def bleu_analysis(test_data, folder='mine-gen-func', root_dir=root_dir):
    smoothie = SmoothingFunction().method4
    scores = []

    with open(root_dir + "/reports/" + folder + "/test_generation", "rb") as fp:
        generated_list = pickle.load(fp)

    for num, item in enumerate(test_data):
        reference = item
        candidate = generated_list[num]
        scores.append(sentence_bleu([reference], candidate, smoothing_function=smoothie))

    with open(root_dir + "/reports/" + folder + "/test_generation_score", "wb") as fp:
        pickle.dump(scores, fp)
    return scores

def rogue_analysis(test_data, folder='mine-gen-func', root_dir=root_dir):
    rouge = Rouge()
    with open(root_dir + "/reports/" + folder + "/test_generation", "rb") as fp:
        generated_list = pickle.load(fp)

    rouge_score = rouge.get_scores(generated_list, test_data.tolist(), avg=True, ignore_empty=True)
    return rouge_score


from rest_framework import serializers

from ..models import Tag
from ..serializers import AvailableTagSerializer

class TagSerializer(serializers.ModelSerializer):
    tag = AvailableTagSerializer(read_only=True)

    class Meta:
        model = Tag
        fields = [
            "id",
            "tag",
            "created_at",
        ]

        lookup_field = "id"


from bottle import run, route, static_file, template

@route('/')
def index ():
    return template('index2')

@route('/staticf/<filename>')
def staticf(filename):
    l_fileName = filename
    print('In Method staticf')
    return(static_file(filename, root='./static_images'))

if __name__ == '__main__':
    run(debug=True, reloader=True)


from .equirectangular import Equirectangular
import bpy
from math import radians
from os.path import isfile

def transform_camera(camera: bpy.types.Object, distance, long, lat):
    """
    Set camera transformation
    Project position onto sphere of radius [distance] and align rotation
    :param camera: Camera to transform
    :param distance: Distance from centre point
    :param long: Longitudinal position
    :param lat: Latitudinal position
    """
    camera.location = Equirectangular.project_sphere((long, lat), False, distance)

    # rotate facing inwards, then apply lat & long
    rx, rz = 90 - lat, 180 + long
    camera.rotation_euler = (radians(rx), 0, radians(rz))

def create_pixel_sphere(radius, resolution):
    """
    Generate mesh with vertices for each projected pixel.
    Demonstrates position of each pixel.
    :param radius: Sphere radius
    :param resolution: Output image resolution
    """
    xR, yR = resolution

    # generate one vertex for each pixel
    verts = []
    for x in range(xR):
        for y in range(yR):
            v = Equirectangular.Pixel.project_sphere((x, y), resolution, radius)

            verts.append(v)

    name = f"Pixel Sphere ({xR}, {yR})"

    mesh = bpy.data.meshes.new(name)  # create mesh
    mesh.from_pydata(verts, [], [])
    obj = bpy.data.objects.new(name, mesh)  # create object; apply mesh

    bpy.context.scene.collection.objects.link(obj)  # place object in master collection
    bpy.context.view_layer.objects.active = obj  # make active object (?)
    obj.select_set(True)

def get_render_resolution(scene=None):
    if scene is None:
        scene = bpy.context.scene

    return scene.render.resolution_x, scene.render.resolution_y

def product(factors):
    result = 1
    for f in factors:
        result *= f
    return result

def iterate_flat(iterable, group_size):
    """
    Generator for iterating over [iterable] in groups of size [group_size]
    :param iterable: Target iterable
    :param group_size: Sub-group iteration size
    """
    if len(iterable) % group_size != 0:
        raise Exception("length of iterable must be divisible by four")

    for i in range(0, len(iterable), group_size):
        yield iterable[i: i + group_size]

class OutImage:
    @staticmethod
    def pixel_to_coord(pixel, res_width: int):
        """
        Convert pixel number to pixel coordinate
        :param pixel: Pixel number; start counting bottom left, go right
        :param res_width: x component of resolution
        :return: Pixel coordinates: zeroed bottom left
        """

        x = pixel % res_width
        y = pixel // res_width

        return x, y

    @staticmethod
    def coord_to_pixel(coord, res_width: int):
        """
        Convert pixel coordinate to pixel number
        :param coord: Pixel coordinates: zeroed bottom left
        :param res_width: x component of resolution
        :return: Pixel number; start counting bottom left, go right
        """
        x, y = coord

        return y * res_width + x

    @staticmethod
    def modify_filename(file_name):
        """
        Rename target file to ensure existing files are not overwritten
        """
        if not isfile(file_name):
            return file_name

        # does already exist
        count = 1
        while isfile(OutImage.insert_before_extension(file_name, count)):
            count += 1

        return OutImage.insert_before_extension(file_name, count)

    @staticmethod
    def insert_before_extension(filename: str, insert):
        """
        Insert string into filename before extension
        :param filename: target filename
        :param insert: string to be inserted
        """
        pos = filename.rfind('.')  # find extension dot position from right
        name, extension = filename[:pos], filename[pos:]
        return name + str(insert) + extension


from PIL import Image
import os
import cv2
import numpy as np
in_dir = '../Downloads/coloring_test/segmentation/test/final_test/'
#out_dir = '../Downloads/coloring_test/segmentation/train_d
out_dir = '../Downloads/coloring_test/segmentation/test/final_test_thick/'

imgs = list(sorted(os.listdir(os.path.join(in_dir))))
for filename in imgs:
    img = Image.open(in_dir  + filename).convert("RGB")
    name, ext = os.path.splitext (filename)
    #mask_name = name + '_tf.png'
    print(filename)

    #output = Image.open(out_dir+ mask_name).convert("RGB")
    output = Image.open(in_dir  + filename).convert("RGB")

    masking = output.load()

    (width,height) = img.size
    black = (0,0,0)
    yellow = (255,255,0)
    #output = img.load()
    for y in range(0,height-1):
        for x in range(0,width-1):
            r, g, b = img.getpixel((x,y))
            #print(str(x)+','+str(y))

            if r<5 and g < 5 and b< 5:
                masking[x,y] = black

                masking[x,y+1] = black
                masking[x+1,y] = black

                masking[x-1,y] = black
                masking[x,y-1] = black
    '''
    for x in range(0,width):
        masking[x,0] = (0,0,0)
        masking[x,1] = (0,0,0)
        masking[x,2] = (0,0,0)
        masking[x,3] = (0,0,0)
        masking[x,716] = (0,0,0)
        masking[x,719] = (0,0,0)
        masking[x,718] = (0,0,0)
        masking[x,717] = (0,0,0)
    '''

    output.save(out_dir + filename)


# Basics Requirements
import pathlib
import os
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State, ClientsideFunction
from dash.exceptions import PreventUpdate
#from .data.dataframes_ftr import get_df
from app import app
# from app import app, cache
from .data.dataframes import df_c, df_c2

# PLACE THE COMPONENTS IN THE LAYOUT
layout = html.Div(
    [
        dbc.Alert(
            [
                html.H3("Clustering Analysis", style={"color": "#F37126"}),
                html.P(
                    "You will find an analysis of how your clients relate to"
                    " each other based on their transaction behavior",
                    style={"color": "#8190A5", "font-weight": "bold"},
                ),
            ],
            style={"background-color": "#F8F6F6", "border": "0px"},
        ),
    ]
)

available_indicators = ['transaction_card_type',
                        'merchant_classification',
                        'category_hour',
                        'category_paymentmethod_franchise',
                        'category_response_code']

cluster_tab = dbc.Row(
    dbc.Col(
        [
            html.Div(
                [
                    html.P("Choose a category", className="choose_category"),
                ],
            ),
            dbc.Select(
                id="select",
                options=[{"label": i, "value": i} for i in available_indicators],
                value="transaction_card_type",
            ),
            dcc.Graph(id="indicator-graphic"),
        ],
        width={"size": 6, "offset": 3},
    )
)

@app.callback(
    dash.dependencies.Output("indicator-graphic", "figure"),
    [
        dash.dependencies.Input("select", "value"),
    ],
)
# @cache.memoize(timeout=120)
def update_graph(select):
    fig = go.Figure()
    fig.add_trace(
        go.Bar(
            x=df_c["{}".format(select)],
            y=(df_c[df_c['cluster_predicted']==0]).value_counts(),
            name="cluster 0",
            marker_color="tomato",
        )
    )
    fig.add_trace(
        go.Bar(
            x=df_c["{}".format(select)],
            y=(df_c[df_c['cluster_predicted']==1]).value_counts(),
            name="cluster 1",
            marker_color="slategray",
        )
    )
    fig.update_layout(title="Clusterization by {}".format(select),
                      xaxis=dict(title=df_c['{}'.format(select)].name,
                                 titlefont_size=16,
                                 tickfont_size=14,
                                ),
                      yaxis=dict(title='Number transactions',
                                 titlefont_size=16,
                                 tickfont_size=14,
                                ),
                      barmode='group',
                    )
    fig.update_xaxes(ticktext = [text for text in df_c2['{}'.format(select)].unique()],
                     tickvals = [val for val in df_c['{}'.format(select)].unique()])
    return fig


import re
from ariblib.aribstr import AribString
from typing import cast, Literal

class TSInformation:
    """ 録画 TS ファイル内に含まれる番組情報のユーティリティ """

    # 映像のコーデック
    # ref: https://github.com/Chinachu/Mirakurun/blob/master/src/Mirakurun/EPG.ts#L23-L27
    STREAM_CONTENT = {
        0x01: 'MPEG-2',
        0x05: 'H.264',
        0x09: 'H.265',
    }

    # 映像の解像度
    # ref: https://github.com/Chinachu/Mirakurun/blob/master/src/Mirakurun/EPG.ts#L29-L63
    COMPONENT_TYPE = {
        0x01: '480i',
        0x02: '480i',
        0x03: '480i',
        0x04: '480i',
        0x83: '4320p',
        0x91: '2160p',
        0x92: '2160p',
        0x93: '2160p',
        0x94: '2160p',
        0xA1: '480p',
        0xA2: '480p',
        0xA3: '480p',
        0xA4: '480p',
        0xB1: '1080i',
        0xB2: '1080i',
        0xB3: '1080i',
        0xB4: '1080i',
        0xC1: '720p',
        0xC2: '720p',
        0xC3: '720p',
        0xC4: '720p',
        0xD1: '240p',
        0xD2: '240p',
        0xD3: '240p',
        0xD4: '240p',
        0xE1: '1080p',
        0xE2: '1080p',
        0xE3: '1080p',
        0xE4: '1080p',
        0xF1: '180p',
        0xF2: '180p',
        0xF3: '180p',
        0xF4: '180p',
    }

    # formatString() で使用する変換マップ
    __format_string_translation_map: dict[int, str] | None = None
    __format_string_regex: re.Pattern[str] | None = None
    __format_string_regex_table: dict[str, str] | None = None

    @classmethod
    def __buildFormatStringTranslationMap(cls) -> None:
        """
        formatString() で使用する変換マップや正規表現を構築する
        一度のみ実行され、以降はキャッシュされる
        """

        # すでに構築済みの場合は何もしない
        if cls.__format_string_translation_map is not None and cls.__format_string_regex is not None:
            return

        # 全角英数を半角英数に置換
        # ref: https://github.com/ikegami-yukino/jaconv/blob/master/jaconv/conv_table.py
        zenkaku_table = '０１２３４５６７８９ＡＢＣＤＥＦＧＨＩＪＫＬＭＮＯＰＱＲＳＴＵＶＷＸＹＺａｂｃｄｅｆｇｈｉｊｋｌｍｎｏｐｑｒｓｔｕｖｗｘｙｚ'
        hankaku_table = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
        merged_table = dict(zip(list(zenkaku_table), list(hankaku_table)))

        # 全角記号を半角記号に置換
        symbol_zenkaku_table = '＂＃＄％＆＇（）＋，－．／：；＜＝＞［＼］＾＿｀｛｜｝　'
        symbol_hankaku_table = '"#$%&\'()+,-./:;<=>[\\]^_`{|} '
        merged_table.update(zip(list(symbol_zenkaku_table), list(symbol_hankaku_table)))
        merged_table.update({
            # 一部の半角記号を全角に置換
            # 主に見栄え的な問題（全角の方が字面が良い）
            '!': '！',
            '?': '？',
            '*': '＊',
            '~': '～',
            # シャープ → ハッシュ
            '♯': '#',
            # 波ダッシュ → 全角チルダ
            ## EDCB は ～ を全角チルダとして扱っているため、KonomiTV でもそのように統一する
            ## TODO: 番組検索を実装する際は検索文字列の波ダッシュを全角チルダに置換する下処理が必要
            ## ref: https://qiita.com/kasei-san/items/3ce2249f0a1c1af1cbd2
            '〜': '～',
        })

        # 番組表で使用される囲み文字の置換テーブル
        ## ref: https://note.nkmk.me/python-chr-ord-unicode-code-point/
        ## ref: https://github.com/l3tnun/EPGStation/blob/v2.6.17/src/util/StrUtil.ts#L7-L46
        ## ref: https://github.com/xtne6f/EDCB/blob/work-plus-s-230526/EpgDataCap3/EpgDataCap3/ARIB8CharDecode.cpp#L1324-L1614
        enclosed_characters_table = {
            '\U0001f14a': '[HV]',
            '\U0001f14c': '[SD]',
            '\U0001f13f': '[P]',
            '\U0001f146': '[W]',
            '\U0001f14b': '[MV]',
            '\U0001f210': '[手]',
            '\U0001f211': '[字]',
            '\U0001f212': '[双]',
            '\U0001f213': '[デ]',
            '\U0001f142': '[S]',
            '\U0001f214': '[二]',
            '\U0001f215': '[多]',
            '\U0001f216': '[解]',
            '\U0001f14d': '[SS]',
            '\U0001f131': '[B]',
            '\U0001f13d': '[N]',
            '\U0001f217': '[天]',
            '\U0001f218': '[交]',
            '\U0001f219': '[映]',
            '\U0001f21a': '[無]',
            '\U0001f21b': '[料]',
            '\U0001f21c': '[前]',
            '\U0001f21d': '[後]',
            '\U0001f21e': '[再]',
            '\U0001f21f': '[新]',
            '\U0001f220': '[初]',
            '\U0001f221': '[終]',
            '\U0001f222': '[生]',
            '\U0001f223': '[販]',
            '\U0001f224': '[声]',
            '\U0001f225': '[吹]',
            '\U0001f14e': '[PPV]',
            '\U0001f200': '[ほか]',
        }

        # Unicode の囲み文字を大かっこで囲った文字に置換する
        ## EDCB で EpgDataCap3_Unicode.dll を利用している場合や、Mirakurun 3.9.0-beta.24 以降など、
        ## 番組情報取得元から Unicode の囲み文字が送られてくる場合に対応するためのもの
        ## Unicode の囲み文字はサロゲートペアなどで扱いが難しい上に KonomiTV では囲み文字を CSS でハイライトしているため、Unicode にするメリットがない
        ## ref: https://note.nkmk.me/python-str-replace-translate-re-sub/
        merged_table.update(enclosed_characters_table)

        # 変換マップを構築し、クラス変数に格納
        cls.__format_string_translation_map = str.maketrans(merged_table)

        # 逆に代替の文字表現に置換された ARIB 外字を Unicode に置換するテーブル
        ## 主に EDCB (EpgDataCap3_Unicode.dll 不使用) 環境向けの処理
        ## EDCB は通常 Shift-JIS で表現できない文字をサロゲートペア範囲外の文字も含めてすべて代替の文字表現に変換するが、これはこれで見栄えが悪い
        ## そこで、サロゲートペアなしで表現できて、一般的な日本語フォントでグリフが用意されていて、
        ## かつ他の文字表現から明確に判別可能でそのままでは分かりづらい文字表現だけ Unicode に置換する
        ## ref: https://github.com/xtne6f/EDCB/blob/work-plus-s-230526/EpgDataCap3/EpgDataCap3/ARIB8CharDecode.cpp#L1324-L1614
        cls.__format_string_regex_table = {
            # '[・]': '⚿',  # グリフが用意されていないことが多い
            '(秘)': '㊙',
            'm^2': 'm²',
            'm^3': 'm³',
            'cm^2': 'cm²',
            'cm^3': 'cm³',
            'km^2': 'km²',
            '[社]': '㈳',
            '[財]': '㈶',
            '[有]': '㈲',
            '[株]': '㈱',
            '[代]': '㈹',
            # '(問)': '㉄',  # グリフが用意されていないことが多い
            '^2': '²',
            '^3': '³',
            # '(箏): '㉇',  # グリフが用意されていないことが多い
            '(〒)': '〶',
            '()()': '⚾',
        }

        # 正規表現を構築し、クラス変数に格納
        cls.__format_string_regex = re.compile("|".join(map(re.escape, cls.__format_string_regex_table.keys())))

    @classmethod
    def formatString(cls, string: str | AribString) -> str:
        """
        文字列に含まれる英数や記号を半角に置換し、一律な表現に整える

        Args:
            string (str | AribString): str あるいは AribString の文字列

        Returns:
            str: 置換した文字列
        """

        # AribString になっている事があるので明示的に str 型にキャストする
        result = str(string)

        # 変換マップを構築 (初回以降はキャッシュされる)
        cls.__buildFormatStringTranslationMap()
        assert cls.__format_string_translation_map is not None
        assert cls.__format_string_regex is not None
        assert cls.__format_string_regex_table is not None

        # 置換を実行
        result = result.translate(cls.__format_string_translation_map)
        result = cls.__format_string_regex.sub(lambda match: cast(dict[str, str], cls.__format_string_regex_table)[match.group(0)], result)

        # 置換した文字列を返す
        return result

    @staticmethod
    def getNetworkType(network_id: int) -> Literal['GR', 'BS', 'CS', 'CATV', 'SKY', 'STARDIGIO', 'OTHER']:
        """
        ネットワーク ID からネットワークの種別を取得する
        種別は GR (地デジ)・BS・CS・CATV・SKY (SPHD)・STARDIGIO (スターデジオ)・OTHER (不明なネットワーク ID のチャンネル) のいずれか

        Args:
            network_id (int): ネットワーク ID

        Returns:
            str: GR・BS・CS・CATV・SKY・STARDIGIO・OTHER のいずれか
        """

        # 以下は ARIB STD-B10 第2部 付録N より抜粋
        # https://web.archive.org/web/2if_/http://www.arib.or.jp/english/html/overview/doc/2-STD-B10v5_3.pdf#page=256

        # 地上デジタルテレビジョン放送 (network_id: 30848 ~ 32744)
        if network_id >= 0x7880 and network_id <= 0x7FE8:
            return 'GR'

        # BSデジタル放送
        if network_id == 0x0004:
            return 'BS'

        # 110度CSデジタル放送
        # CS1: 0x0006 (旧プラット・ワン系)
        # CS2: 0x0007 (旧スカイパーフェクTV!2系)
        if network_id == 0x0006 or network_id == 0x0007:
            return 'CS'

        # ケーブルテレビ (リマックス方式・トランスモジュレーション方式)
        # ケーブルテレビ独自のチャンネルのみで、地上波・BS の再送信は含まない
        # デジタル放送リマックス: 0xFFFE (HD・SD チャンネル (MPEG-2))
        # デジタル放送高度リマックス: 0xFFFA (ケーブル4Kチャンネル (H.264, H.265))
        # JC-HITSトランスモジュレーション: 0xFFFD (HD・SD チャンネル (MPEG-2))
        # 高度JC-HITSトランスモジュレーション: 0xFFF9 (ケーブル4Kチャンネル (H.264, H.265))
        if network_id == 0xFFFE or network_id == 0xFFFA or network_id == 0xFFFD or network_id == 0xFFF9:
            return 'CATV'

        # 124/128度CSデジタル放送
        # SPHD: 0x000A (スカパー！プレミアムサービス)
        # SPSD-SKY: 0x0003 (運用終了)
        if network_id == 0x000A or network_id == 0x0003:
            return 'SKY'

        # 124/128度CSデジタル放送
        # SPSD-PerfecTV: 0x0001 (スターデジオ)
        if network_id == 1:
            return 'STARDIGIO'

        # 不明なネットワーク ID のチャンネル
        return 'OTHER'

    @staticmethod
    def getISO639LanguageCodeName(iso639_language_code: str) -> str:
        """
        ISO639 形式の言語コードが示す言語の名称を取得する

        Args:
            iso639_code (str): ISO639 形式の言語コード

        Returns:
            str: ISO639 形式の言語コードが示す言語の名称
        """

        if iso639_language_code == 'jpn':
            return '日本語'
        elif iso639_language_code == 'eng':
            return '英語'
        elif iso639_language_code == 'deu':
            return 'ドイツ語'
        elif iso639_language_code == 'fra':
            return 'フランス語'
        elif iso639_language_code == 'ita':
            return 'イタリア語'
        elif iso639_language_code == 'rus':
            return 'ロシア語'
        elif iso639_language_code == 'zho':
            return '中国語'
        elif iso639_language_code == 'kor':
            return '韓国語'
        elif iso639_language_code == 'spa':
            return 'スペイン語'
        else:
            return 'その他の言語'


import os
from setuptools import setup, find_packages

with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
    README = readme.read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='django-reviewable',
    version='0.3.9.2',
    packages=find_packages(),
    include_package_data=True,
    url='https://github.com/jacobwindsor/django-reviewable',
    license='MIT License',
    author='Jacob Windsor',
    author_email='jacob.windsor@ymail.com',
    description='Simple, customizable reviews for any of your Django models',
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Framework :: Django :: 1.9',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3.5',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)


#-*- coding: utf-8 -*-
"""
verdi command show
"""
import click

from aiida_verdi import arguments, options

@click.command()
@arguments.node()
@arguments.comment_id(required=False)
@options.user()
@options.dry_run()
@options.non_interactive()
def show(node, comment_id, user, dry_run, non_interactive):
    """
    Show the comments (with COMMENT_ID) of a NODE in the database.
    """
    from aiida_verdi.utils.aiidadb import ensure_aiida_dbenv
    ensure_aiida_dbenv()
    from aiida.backends.utils import get_automatic_user

    user = get_automatic_user()

    all_comments = node.get_comments(pk=comment_id)

    if user:
        to_print = [i for i in all_comments if i['user__email'] == user.email]
        if not to_print:
            click.echo("Nothing found for user '{}'.".format(user))
            click.echo(
                "Valid users found for Node {} are: {}.".format(node.pk,
                                                                ", ".join(set(
                                                                    ["'" + i['user__email'] + "'" for i in
                                                                     all_comments]))))
    else:
        to_print = all_comments

    if comment_id > 0:
        to_print = [i for i in to_print if i['pk'] == comment_id]

    for i in to_print:
        click.echo("*"*58)
        click.echo("Comment of '{}' on {}".format(i['user__email'],
                                                  i['ctime'].strftime("%Y-%m-%d %H:%M")))
        click.echo("ID: {}. Last modified on {}".format(i['pk'],
                                                        i['mtime'].strftime("%Y-%m-%d %H:%M")))
        click.echo("")
        click.echo("{}".format(i['content']))
        click.echo("")

    # If there is nothing to print, print a message
    if not to_print:
        click.echo("No comment found.")


import bpy

from math import radians
from mathutils import Vector

def link_to_pivot(object, pivot):
    # Add 'Transform' constraint
    transform = object.constraints.new('TRANSFORM')
    transform.target = pivot
    transform.target_space = 'LOCAL'
    transform.owner_space = 'LOCAL'
    transform.map_from = 'SCALE'
    transform.from_min_y_scale = 0
    transform.from_max_y_scale = 100000
    transform.map_to = 'LOCATION'
    transform.map_to_z_from = 'Y'
    transform.to_max_z = 100000

    # Add 'Child of' constraint
    child_of = object.constraints.new('CHILD_OF')
    child_of.target = pivot
    child_of.use_scale_x = False
    child_of.use_scale_y = False
    child_of.use_scale_z = False

def create_light_controller(parent):
    # Create light pivot
    light_pivot = bpy.data.objects.new("Light Pivot", None)
    light_pivot.empty_display_type = 'SPHERE'
    light_pivot.location = parent.location
    light_pivot.rotation_euler = parent.rotation_euler.copy()
    light_pivot.scale = parent.scale * 0.8

    # Add 'Child of' constraint
    light_child_of = light_pivot.constraints.new('CHILD_OF')
    light_child_of.target = parent
    light_child_of.use_scale_x = False
    light_child_of.use_scale_y = False
    light_child_of.use_scale_z = False

    # Create light
    light_data = bpy.data.lights.new("Light", type="AREA")
    light = bpy.data.objects.new("Light", light_data)
    light.location = parent.location
    light.rotation_euler = parent.rotation_euler.copy()
    light.rotation_euler.rotate_axis('X', radians(90))
    light.scale = light_pivot.scale * 4

    link_to_pivot(light, light_pivot)

    # Lock transforms
    light.lock_location[0] = True
    light.lock_location[1] = True
    light.lock_location[2] = True
    light.lock_rotation[0] = True
    light.lock_rotation[1] = True
    light.lock_rotation[2] = True

    # Add to collection
    collection = bpy.data.collections.new("Light Controller")
    collection.objects.link(light_pivot)
    collection.objects.link(light)

    return collection, light, light_pivot

def create_camera_controller(location, radius):
    # Create camera pivot
    camera_pivot = bpy.data.objects.new("Camera Pivot", None)
    camera_pivot.empty_display_type = "SPHERE"
    camera_pivot.location = location
    camera_pivot.scale = Vector((radius, radius, radius))

    # Create camera
    camera_data = bpy.data.cameras.new(name="Camera")
    camera = bpy.data.objects.new("Camera", camera_data)
    camera.location = location
    camera.rotation_euler = (radians(90), 0, 0)

    link_to_pivot(camera, camera_pivot)

    # Lock camera transform
    camera.lock_location[0] = True
    camera.lock_location[1] = True
    camera.lock_location[2] = True
    camera.lock_rotation[0] = True
    camera.lock_rotation[1] = True
    camera.lock_rotation[2] = True
    camera.lock_scale[0] = True
    camera.lock_scale[1] = True
    camera.lock_scale[2] = True

    # Add to collection
    collection = bpy.data.collections.new("Camera Controller")
    collection.objects.link(camera)
    collection.objects.link(camera_pivot)

    # Return controller
    return collection, camera, camera_pivot

def vector_mean(vectors):
    total = Vector()
    for vector in vectors:
        total += vector
    return total / len(vectors)

def get_selection_center(context):
    selected_objects = context.selected_objects
    if selected_objects:
        return vector_mean([obj.location for obj in selected_objects])
    else:
        return context.scene.cursor.location.copy()

def get_selection_diameter(context, center):
    selected_objects = context.selected_objects

    if not selected_objects:
        return 1

    if len(selected_objects) == 1:
        if hasattr(selected_objects[0], "dimensions"):
            max_dimension = max(selected_objects[0].dimensions)
            return max(1, max_dimension)
        return 1

    distances = [(obj.location - center).magnitude for obj in selected_objects]
    max_distance = max(distances)
    return max_distance * 2


import joblib
import numpy as np
import json
import sys
import os

# Determine the absolute path to the current script's directory
script_dir = os.path.dirname(os.path.abspath(__file__))

# Load the trained model and scaler using the absolute paths
model_path = os.path.join(script_dir, 'housemodel.joblib')
scaler_path = os.path.join(script_dir, 'scaler.joblib')

model = joblib.load(model_path)
scaler = joblib.load(scaler_path)

# Extract input from command line arguments
try:
    data = json.loads(sys.argv[1])
    input_data = data['input']
except (IndexError, KeyError, json.JSONDecodeError):
    print(json.dumps({'error': 'Invalid input format'}))
    sys.exit(1)

# Define the expected features and their ranges
expected_features = ['medInc', 'houseAge', 'aveRooms', 'aveBedrms', 'population',
                     'aveOccup', 'latitude', 'longitude']
feature_ranges = [(0, 10), (0, 50), (0, 10), (0, 5), (0, 5000), (0, 10), (33, 42),
                  (-124, -114)]

# Validate the input data
if len(input_data) != len(expected_features):
    print(json.dumps({'error': 'Invalid input data'}))
    sys.exit(1)

for i in range(len(input_data)):
    # Convert input_data[i] to float before comparison
    try:
        value = float(input_data[i])
    except ValueError:
        print(json.dumps({'error': f'Invalid value for {expected_features[i]}'}))
        sys.exit(1)

    if not feature_ranges[i][0] <= value <= feature_ranges[i][1]:
        print(json.dumps({'error': f'Invalid value for {expected_features[i]}'}))
        sys.exit(1)

# Convert the input data, reshape, scale, and predict
input_data = np.array([float(i) for i in input_data]).reshape(1, -1)
input_data = scaler.transform(input_data)
prediction = model.predict(input_data)

# Get the feature importances
importances = model.feature_importances_

# Create the response payload
response = {
    'prediction': prediction.tolist(),
    'importances': importances.tolist()
}

# Print the response as JSON
print(json.dumps(response))


from tkinter import *
import sqlite3

root = Tk()
root.geometry('900x600')
root.title("Registration Form")

Fullname = StringVar()
Email = StringVar()
var = StringVar()
c = StringVar()
var1 = StringVar()
Address = StringVar()
Phonenumber = StringVar()
months = StringVar()
days = StringVar()
year = StringVar()

def database():
    name1 = Fullname.get()
    email = Email.get()
    phone = Phonenumber.get()
    address = Address.get()
    DOBDay = days.get()
    DOBMonth = months.get()
    DOBYear = year.get()
    gender = var.get()
    country = c.get()
    prog = var1.get()
    conn = sqlite3.connect('Form.db')
    with conn:
        cursor = conn.cursor()
    cursor.execute(
        'CREATE TABLE IF NOT EXISTS Student (Fullname TEXT,Email TEXT,Gender TEXT,country TEXT,Programming TEXT,'
        'Address TEXT,Phone TEXT,DOBDay TEXT,DOBMonth TEXT, DOBYear TEXT)')
    cursor.execute(
        'INSERT INTO Student (FullName,Email,Gender,country,Programming,Address,Phone, DOBDay, DOBMonth, '
        'DOBYear) VALUES(?,?,?,?,?,?,?,?,?,?)',
        (name1, email, gender, country, prog, address, phone, DOBDay, DOBMonth, DOBYear))
    conn.commit()

def dayss():
    dayss = list(range(1, 32))
    return dayss

def moonths():
    moonths = list(range(1, 13))
    return moonths

def yearr():
    yearr = list(range(1990, 2005))
    return yearr

label0 = Label(root, text="Registration Form", width=20, font=("bold", 20))
label0.place(x=290, y=53)

labela = Label(root, text="Address", width=20, font=("bold", 10))
labela.place(x=480, y=130)

entrya = Entry(root, textvar=Address, width=40)
entrya.place(x=640, y=130)

label1 = Label(root, text="Full Name", width=20, font=("bold", 10))
label1.place(x=80, y=130)

entry1 = Entry(root, textvar=Fullname, width=30)
entry1.place(x=240, y=130)

label2 = Label(root, text="Email", width=20, font=("bold", 10))
label2.place(x=68, y=180)

labelp = Label(root, text="Phone Number", width=20, font=("bold", 10))
labelp.place(x=480, y=180)

entryp = Entry(root, textvar=Phonenumber)
entryp.place(x=640, y=180)

entry2 = Entry(root, textvar=Email)
entry2.place(x=240, y=180)

label3 = Label(root, text="Gender", width=20, font=("bold", 10))
label3.place(x=70, y=230)

Radiobutton(root, text="Male", padx=5, variable=var, value="Male").place(x=235, y=230)
Radiobutton(root, text="Female", padx=20, variable=var, value="Female").place(x=290, y=230)

label4 = Label(root, text="country", width=20, font=("bold", 10))
label4.place(x=70, y=280)

list1 = ['Canada', 'India', 'UK', 'Nippal', 'Iceland', 'South Africa'];

droplist = OptionMenu(root, c, *list1)
droplist.config(width=25)
c.set('Select Your Country')
droplist.place(x=240, y=280)

label4 = Label(root, text="Language", width=20, font=("bold", 10))
label4.place(x=75, y=330)

list2 = ['C', 'C++', 'Java', 'Python']

droplist2 = OptionMenu(root, var1, *list2)
droplist2.config(width=25)
var1.set('Select Preffered Language')
droplist2.place(x=240, y=330)

labeldob = Label(root, text="Date Of Birth", width=20, font=("bold", 10))
labeldob.place(x=480, y=235)

days1 = dayss()
droplist3 = OptionMenu(root, days, *days1)
days.set("DD")
droplist3.place(x=640, y=230)

months1 = moonths()
droplist4 = OptionMenu(root, months, *months1)
months.set("MM")
droplist4.place(x=710, y=230)

year1 = yearr()
droplist5 = OptionMenu(root, year, *year1)
year.set("YYYY")
droplist5.place(x=790, y=230)

Button(root, text='Submit', width=20, bg='brown', fg='white', command=database).place(x=380, y=400)

root.mainloop()


import sqlite3
import os

root = os.path.dirname(__file__)
conn = sqlite3.connect(root + '/db/smarthome.db')

c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS sensors (id INTEGER PRIMARY KEY AUTOINCREMENT, sensor1 real, sensor2_value_t real, sensor2_value_h real, datetime string )')

class Sensors():
    def getLast(self):
        c.execute('SELECT round(sensor1, 2), round(sensor2_value_t, 2), round(sensor2_value_h, 2)  FROM sensors ORDER BY id DESC LIMIT 1')
        return c.fetchone()

    def getDay(self):
      sql =  "select "
      sql += "substr(datetime,12,4) || '0' as date, "
      sql += "round(min(sensor1), 2) as sensor1, "
      sql += "round(min(sensor2_value_t), 2) as sensor2_value_t "
      sql += "from sensors "
      sql += "where id in ( select id from sensors order by id desc limit 1440 ) "
      sql += "group by substr(datetime,1,15) || '0' "
      c.execute(sql)
      return c.fetchall()

    def InsertData(self, sensor1, sensor2_value_t, sensor2_value_h, datetime):
        c.execute("INSERT INTO sensors (sensor1, sensor2_value_t, sensor2_value_h, datetime)  VALUES ("+str(sensor1)+","+str(sensor2_value_t)+","+str(sensor2_value_h)+",'"+datetime+"')")
        conn.commit()

'''
from peewee import *

db = SqliteDatabase('/root/weatherstation/sensors.db')

class Sensors(Model):
    id = PrimaryKeyField()
    sensor1 = FloatField()
    datetime = DateTimeField()

    class Meta:
        database = db

    def getLast(self):
        return Sensors.select(Sensors.sensor1).order_by(Sensors.id.desc()).limit(1).get()

    def getDay(self):
        res= Sensors.select(
            fn.Substr(Sensors.datetime, 12, 4).concat('0').alias('date'),
            fn.round(fn.avg(Sensors.sensor1), 2).alias('sensor1')
            ).group_by('date').get()
        return [r[0] for r in res.fetchall()]

#        return Sensors.select(
#            fn.Substr(Sensors.datetime, 12, 4).concat('0').alias('date'),
#            fn.round(fn.avg(Sensors.sensor1), 2).alias('sensor1')
#            ).where(id in Sensors.select(Sensors.id).order_by(Sensors.id).desc().limit(1440).get()  ).group_by('date').get()

# Sensors.create_table()
# Sensors.insert(sensor1=10.5, datetime = datetime.today()).execute()
# print Sensors().getLast().sensor1
#print Sensors().getDay()

if __name__ == "__main__":
    try:
        print 'xxxxxxxxxxxxxxxxx'
        Sensors.create_table()
    except peewee.OperationalError:
        print "sensors table already exists!"

'''


import torch
import torch.nn as nn
import torch.nn.functional as F
import logging
import numpy as np

from .quant import conv3x3, conv1x1
from .layers import norm, actv
from torch.nn.modules.utils import _quadruple

# Prone-net: Point-wise and Reshape only Neural Network
class Prone(nn.Module):
    def __init__(self, out_channel, in_channel=3, stride=4, groups=1, kernel_size=3, force_fp=True, args=None, feature_stride=1, keepdim=True):
        super(Prone, self).__init__()
        self.stride = stride * 2
        self.in_channel = in_channel * self.stride * self.stride
        self.out_channel = out_channel * 4
        self.keepdim = keepdim
        self.conv = conv1x1(self.in_channel, self.out_channel, groups=groups, args=args, force_fp=force_fp)

        self.bn_before_restore = False
        if hasattr(args, 'keyword'):
            self.bn_before_restore = 'bn_before_restore' in args.keyword
        if self.bn_before_restore:
            self.bn = norm(self.out_channel, args)

    def forward(self, x):
        # padding zero when cannot just be divided
        B, C, H, W = x.shape
        if H % self.stride != 0:
            pad = (self.stride - (H % self.stride)) // 2
            x = F.pad(x, _quadruple(pad), mode="constant", value=0)

        B, C, H, W = x.shape
        #print(B, C, H, W, self.stride)
        # consider to employ the PixelShuffle layer instead
        x = x.reshape(B, C, H // self.stride, self.stride, W // self.stride, self.stride)
        x = x.transpose(4, 3).reshape(B, C, 1, H // self.stride, W // self.stride, self.stride * self.stride)
        x = x.transpose(2, 5).reshape(B, C * self.stride * self.stride, H // self.stride, W // self.stride)
        x = self.conv(x)
        if self.bn_before_restore:
            x = self.bn(x)

        if self.keepdim: # restore the channel dimension, however resolution might be altered
            B, C, H, W = x.shape
            x = x.reshape(B, C//4, 4, H, W, 1)
            x = x.transpose(2, 5).reshape(B, C//4, H, W, 2, 2)
            x = x.transpose(4, 3).reshape(B, C//4, H * 2, W * 2)
        return x

def qprone(in_channel, out_channel, stride=1, groups=1, padding=1, args=None, force_fp=False, feature_stride=1, kernel_size=3, keepdim=True):
    assert kernel_size in [3], "Only kernel size = 3 support"
    assert stride in [1, 2], "Stride must be 1 or 2"
    #assert groups in [1], "groups must be 1"
    return Prone(out_channel, in_channel, stride, groups, kernel_size, force_fp, args, feature_stride, keepdim)


from operator import attrgetter

from collections import OrderedDict
from oslo_log import log as logging

from asr1k_neutron_l3.common import utils
from asr1k_neutron_l3.models.netconf_yang.ny_base import NC_OPERATION, NyBase, execute_on_pair
from asr1k_neutron_l3.models.netconf_yang import xml_utils
from asr1k_neutron_l3.plugins.db import asr1k_db

LOG = logging.getLogger(__name__)

class L2Constants(object):
    INTERFACE = 'interface'
    PORT_CHANNEL = 'Port-channel'
    SERVICE = "service"
    SERVICE_INSTANCE = "instance"
    BD_SERVICE_INSTANCE = "service-instance"
    BD_SERVICE_INSTANCE_LIST = "service-instance-list"
    BD_SERVICE_INSTANCE_ID = "instance-id"

    ID = "id"
    NAME = "name"
    DESCRIPTION = "description"

    ETHERNET = "ethernet"
    ENCAPSULATION = 'encapsulation'
    BRIDGE_DOMAIN = "bridge-domain"
    BRIDGE_ID = "bridge-id"
    BRIDGE_DOMAIN_ID = "bridge-domain-id"
    BRIDGE_DOMAIN_BRIDGE_ID = "brd-id"
    DOT1Q = "dot1q"
    SECOND_DOT1Q = "second-dot1q"
    INGRESS = "ingress"
    TAG = "tag"
    POP = "pop"
    REWRITE = "rewrite"
    REWRITE_WAY = "way"
    REWRITE_MODE = "mode"

    MEMBER = "member"
    MEMBER_IFACE = "member-interface"
    MEMBER_BDVIF = "BD-VIF"

class BridgeDomain(NyBase):
    LIST_KEY = L2Constants.BRIDGE_DOMAIN
    ITEM_KEY = L2Constants.BRIDGE_DOMAIN_BRIDGE_ID

    ID_FILTER = """
        <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native">
            <bridge-domain>
                <brd-id xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-bridge-domain">
                    <bridge-domain-id>{id}</bridge-domain-id>
                </brd-id>
            </bridge-domain>
        </native>
    """

    GET_ALL_STUB = """
        <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native">
            <bridge-domain>
                <brd-id xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-bridge-domain">
                    <bridge-domain-id/>
                </brd-id>
            </bridge-domain>
        </native>
    """

    @classmethod
    def __parameters__(cls):
        return [
            {"key": "id", "yang-key": L2Constants.BRIDGE_DOMAIN_ID, "primary_key": True},
            {"key": "if_members", "type": [BDIfMember],
             "yang-path": L2Constants.MEMBER, "yang-key": L2Constants.MEMBER_IFACE, "default": []},
            {"key": "bdvif_members", "type": [BDVIFMember],
             "yang-path": L2Constants.MEMBER, "yang-key": L2Constants.MEMBER_BDVIF, "default": []},
            {"key": "has_complete_member_config", "default": False},
        ]

    @classmethod
    def get_for_bdvif(self, bdvif_name, context, partial=False):
        xpath_filter = "/native/bridge-domain/brd-id/member/BD-VIF[name='{}']".format(bdvif_name)
        bd = self._get(xpath_filter=xpath_filter, context=context)
        if bd is not None:
            if partial:
                return bd
            return bd._internal_get(context=context)

    def __init__(self, *args, **kwargs):
        super(BridgeDomain, self).__init__(*args, **kwargs)

        # data from the device might result in a single list with one None element
        # this should be fixed in NyBase.from_json(), but as this might impact other parts of the code
        # we just filter out the values for now
        if self.if_members == [None]:
            self.if_members = []
        if self.bdvif_members == [None]:
            self.bdvif_members = []

    def preflight(self, context):
        """Remove wrong interface membership for all BD-VIF members"""
        if not context.version_min_17_3:
            return

        # go through all non-deleted member interfaces
        for bdvif in self.bdvif_members:
            if bdvif.mark_deleted:
                continue
            LOG.debug("Host %s: preflight check for interface %s on in bridge %s",
                      context.host, bdvif.name, self.id)
            bridge = self.get_for_bdvif(bdvif.name, context, partial=True)

            # check if interface is in correct bridge
            if bridge is not None and bridge.id != self.id:
                LOG.warning("Host %s: found BD-VIF%s in wrong BD %s, should be in BD %s, "
                            "removing membership from BD %s",
                            context.host, bdvif.name, bridge.id, self.id, bridge.id)
                # should have only one result, but who knows what cisco will return
                for fb_bdvif in bridge.bdvif_members:
                    if fb_bdvif.name == bdvif.name:
                        # remove interface from wrong bridge
                        #  - don't call preflight, we don't need this check to run for the other bridge
                        #  - don't call internal validate (which will only execute if "something changed")
                        LOG.debug("Host %s: Deleting BD-VIF%s from BD %s", context.host, bdvif.name, bridge.id)
                        fb_bdvif.mark_deleted = True
                        bridge._update(context=context, method=NC_OPERATION.PATCH, preflight=False,
                                       internal_validate=False)
                        break
                else:
                    LOG.warning("Host %s: could not find BD_VIF%s as member of (wrong) bridge %s, skipping",
                                context.host, bdvif.name, bridge.id)

    def to_dict(self, context):
        bddef = OrderedDict()
        bddef[xml_utils.NS] = xml_utils.NS_CISCO_BRIDGE_DOMAIN
        bddef[L2Constants.BRIDGE_DOMAIN_ID] = self.id

        if context.version_min_17_3:
            if context.use_bdvif:
                bddef[L2Constants.MEMBER] = {
                    L2Constants.MEMBER_IFACE: [_m.to_dict(context)
                                               for _m in sorted(self.if_members,
                                                                key=lambda _x: _x.interface)],
                    L2Constants.MEMBER_BDVIF: [_m.to_dict(context)
                                               for _m in sorted(self.bdvif_members, key=attrgetter('name'))],
                }
                if self.has_complete_member_config:
                    bddef[L2Constants.MEMBER][xml_utils.OPERATION] = NC_OPERATION.PUT
            else:
                # This can be used for migrating back from new-style bridges, but might bring some problems
                # if the bridge was never used as a new-stlye bridge
                # bddef[L2Constants.MEMBER] = {xml_utils.OPERATION: NC_OPERATION.DELETE}
                pass

        return {L2Constants.BRIDGE_DOMAIN_BRIDGE_ID: bddef}

    def _diff(self, context, device_config):
        if context.use_bdvif and device_config and not self.has_complete_member_config:
            # we don't know all bd-vif members - the diff should represent if
            # the bd-vifs we know about are configured
            neutron_bdvif_names = [_m.name for _m in self.bdvif_members]
            for bdvif in list(device_config.bdvif_members):
                if bdvif.name not in neutron_bdvif_names:
                    device_config.bdvif_members.remove(bdvif)
        return super(BridgeDomain, self)._diff(context, device_config)

    def is_orphan(self, all_router_ids, all_segmentation_ids, all_bd_ids, context):
        return asr1k_db.MIN_DOT1Q <= int(self.id) <= asr1k_db.MAX_DOT1Q and \
            int(self.id) not in all_segmentation_ids

class BDIfMember(NyBase):
    """Normal interface as a member of a bridge-domain"""

    @classmethod
    def __parameters__(cls):
        return [
            {"key": "interface", "yang-key": L2Constants.INTERFACE},
            {"key": "service_instances", "yang-key": L2Constants.BD_SERVICE_INSTANCE_LIST, "default": [],
             "type": [BDIfMemberServiceInstance]},
            {"key": "mark_deleted", "default": False},
        ]

    def to_dict(self, context):
        result = {
            L2Constants.INTERFACE: self.interface,
        }

        if self.service_instances:
            service_instances = []
            for service_instance in sorted(self.service_instances, key=attrgetter('id')):
                service_instances.append(service_instance.to_dict(context))
            result[L2Constants.BD_SERVICE_INSTANCE_LIST] = service_instances

        if self.mark_deleted:
            result[xml_utils.OPERATION] = NC_OPERATION.REMOVE
        return result

class BDIfMemberServiceInstance(NyBase):
    """Represents a service instance id of a BDIfMember"""

    @classmethod
    def __parameters__(cls):
        return [
            {"key": "id", "yang-key": L2Constants.BD_SERVICE_INSTANCE_ID},
        ]

    def to_dict(self, context):
        return {
            L2Constants.BD_SERVICE_INSTANCE_ID: self.id,
        }

class BDVIFMember(NyBase):
    """BD-VIF as a member of a bridge-domain"""
    @classmethod
    def __parameters__(cls):
        return [
            {"key": "name"},
            {"key": "mark_deleted", "default": False},
        ]

    def to_dict(self, context):
        result = {
            L2Constants.NAME: self.name,
        }
        if self.mark_deleted:
            result[xml_utils.OPERATION] = NC_OPERATION.REMOVE

        return result

class ServiceInstance(NyBase):
    PORT_CHANNEL = 0
    ID_FILTER = """
          <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"
                  xmlns:ios-eth="http://cisco.com/ns/yang/Cisco-IOS-XE-ethernet">
            <interface>
              <Port-channel>
                <name>{port_channel}</name>
                <ios-eth:service>
                  <ios-eth:instance>
                    <id>{id}</id>
                  </ios-eth:instance>
                </ios-eth:service>
              </Port-channel>
            </interface>
          </native>
    """

    GET_ALL_STUB = """
          <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"
                  xmlns:ios-eth="http://cisco.com/ns/yang/Cisco-IOS-XE-ethernet">
            <interface>
              <Port-channel>
                <name>{port_channel}</name>
                <ios-eth:service>
                  <ios-eth:instance>
                    <ios-eth:id/>
                  </ios-eth:instance>
                </ios-eth:service>
              </Port-channel>
            </interface>
          </native>
    """

    LIST_KEY = L2Constants.SERVICE
    ITEM_KEY = L2Constants.SERVICE_INSTANCE

    @classmethod
    def __parameters__(cls):
        return [
            {"key": "port_channel", 'validate': False, 'primary_key': True},
            {"key": "id", "mandatory": True, 'default': 0},
            {"key": "description"},
            {"key": "bridge_domain", 'yang-path': 'bridge-domain', 'yang-key': 'bridge-id'},
            {"key": "dot1q", 'yang-path': 'encapsulation/dot1q', 'yang-key': 'id'},
            {"key": "second_dot1q", 'yang-path': 'encapsulation/dot1q', 'yang-key': 'second-dot1q'},
            {"key": "way", 'yang-path': 'rewrite/ingress/tag/pop'},
            {"key": "mode", 'yang-path': 'rewrite/ingress/tag/pop'}
        ]

    @classmethod
    def get_primary_filter(cls, **kwargs):
        return cls.ID_FILTER.format(id=kwargs.get('id'), port_channel=cls.PORT_CHANNEL)

    @classmethod
    def get_all_stub_filter(cls, context):
        return cls.GET_ALL_STUB.format(port_channel=cls.PORT_CHANNEL)

    @classmethod
    @execute_on_pair(return_raw=True)
    def get(cls, id, context):
        return super(ServiceInstance, cls)._get(id=id, port_channel=cls.PORT_CHANNEL, context=context)

    @classmethod
    @execute_on_pair(return_raw=True)
    def exists(cls, id, context):
        return super(ServiceInstance, cls)._exists(id=id, port_channel=cls.PORT_CHANNEL, context=context)

    @classmethod
    def remove_wrapper(cls, json, context):
        json = super(ServiceInstance, cls)._remove_base_wrapper(json, context)
        if json is None:
            return
        json = json.get(L2Constants.INTERFACE, json)
        json = json.get(L2Constants.PORT_CHANNEL, json)

        if isinstance(json, list):
            result = []
            for pc in json:
                if pc.get("name") == cls.PORT_CHANNEL:
                    service = pc.get(L2Constants.SERVICE, pc)
                    if not isinstance(service.get(L2Constants.SERVICE_INSTANCE, None), list):
                        if service.get(L2Constants.SERVICE_INSTANCE, None) is not None:
                            service[L2Constants.SERVICE_INSTANCE] = [service.get(L2Constants.SERVICE_INSTANCE)]
                    result.append(service)

            json = result
        else:
            json = json.get(L2Constants.SERVICE, json)
        return json

    def orphan_info(self):
        return {self.__class__.__name__: {'description': self.description, 'service_instance': self.id,
                                          'port_channel': self.PORT_CHANNEL, 'bridge_domain': self.bridge_domain}}

    def _wrapper_preamble(self, dict, context):
        result = {}
        dict[xml_utils.NS] = xml_utils.NS_CISCO_ETHERNET
        result[L2Constants.NAME] = self.PORT_CHANNEL
        result[self.LIST_KEY] = dict
        result = {L2Constants.PORT_CHANNEL: result}
        result = {L2Constants.INTERFACE: result}
        return result

    def __init__(self, **kwargs):
        kwargs['port_channel'] = self.PORT_CHANNEL
        super(ServiceInstance, self).__init__(**kwargs)

        if self.id == 'None' or self.id is None:
            self.id = -1

    def to_dict(self, context):
        dot1q = dict(OrderedDict())

        dot1q[L2Constants.ID] = [str(self.dot1q)]
        if self.second_dot1q is not None:
            dot1q[L2Constants.SECOND_DOT1Q] = [str(self.second_dot1q)]

        bridge_domain = OrderedDict()
        bridge_domain[L2Constants.BRIDGE_ID] = self.bridge_domain

        rewrite = OrderedDict()
        rewrite[L2Constants.INGRESS] = OrderedDict()

        rewrite[L2Constants.INGRESS][L2Constants.TAG] = OrderedDict()
        if self.way is not None and self.mode is not None:
            rewrite[L2Constants.INGRESS][L2Constants.TAG][L2Constants.POP] = OrderedDict()
            rewrite[L2Constants.INGRESS][L2Constants.TAG][L2Constants.POP][
                L2Constants.REWRITE_WAY] = self.way
            rewrite[L2Constants.INGRESS][L2Constants.TAG][L2Constants.POP][L2Constants.REWRITE_MODE] = self.mode

        instance = OrderedDict()
        instance[L2Constants.ID] = "{}".format(str(self.id))
        instance[L2Constants.ETHERNET] = ''
        if self.description is not None:
            instance[L2Constants.DESCRIPTION] = "{}".format(self.description)

        instance[L2Constants.ENCAPSULATION] = OrderedDict()
        instance[L2Constants.ENCAPSULATION][L2Constants.DOT1Q] = dot1q
        instance[L2Constants.REWRITE] = rewrite
        if not context.use_bdvif:
            instance[L2Constants.BRIDGE_DOMAIN] = bridge_domain

        result = OrderedDict()
        result[L2Constants.SERVICE_INSTANCE] = instance

        return dict(result)

    def to_delete_dict(self, context):
        instance = OrderedDict()
        instance[L2Constants.ID] = "{}".format(str(self.id))
        instance[L2Constants.ETHERNET] = ''

        result = OrderedDict()
        result[L2Constants.SERVICE_INSTANCE] = instance

        return dict(result)

    @execute_on_pair()
    def update(self, context):
        return super(ServiceInstance, self)._update(context=context, method=NC_OPERATION.PUT)

class ExternalInterface(ServiceInstance):
    PORT_CHANNEL = "1"

    def __init__(self, **kwargs):
        kwargs['bridge_domain'] = kwargs.get('id')
        kwargs['dot1q'] = kwargs.get('id')
        super(ExternalInterface, self).__init__(**kwargs)

    def is_orphan(self, all_router_ids, all_segmentation_ids, all_bd_ids, context):
        return asr1k_db.MIN_DOT1Q <= int(self.id) <= asr1k_db.MAX_DOT1Q and \
            int(self.id) not in all_segmentation_ids

class LoopbackExternalInterface(ServiceInstance):
    PORT_CHANNEL = "2"

    def __init__(self, **kwargs):
        kwargs['bridge_domain'] = kwargs.get('dot1q')
        kwargs['dot1q'] = kwargs.get('dot1q')
        super(LoopbackExternalInterface, self).__init__(**kwargs)

    def to_dict(self, context):
        if context.use_bdvif:
            return {}
        else:
            return super(LoopbackExternalInterface, self).to_dict(context)

    def is_orphan(self, all_router_ids, all_segmentation_ids, all_bd_ids, context):
        # KeepBDUpInterface is included here, as they share a port-channel
        return not context.use_bdvif and \
            (utils.to_bridge_domain(asr1k_db.MIN_SECOND_DOT1Q) <= int(self.id) <=
             utils.to_bridge_domain(asr1k_db.MAX_SECOND_DOT1Q) and
             int(self.id) not in all_bd_ids) or \
            context.use_bdvif and \
            (asr1k_db.MIN_DOT1Q <= int(self.id) <= asr1k_db.MAX_DOT1Q and
             int(self.id) not in all_segmentation_ids)

class LoopbackInternalInterface(ServiceInstance):
    PORT_CHANNEL = "3"

    def __init__(self, **kwargs):
        super(LoopbackInternalInterface, self).__init__(**kwargs)

    def to_dict(self, context):
        if context.use_bdvif:
            return {}
        else:
            return super(LoopbackInternalInterface, self).to_dict(context)

    def is_orphan(self, all_router_ids, all_segmentation_ids, all_bd_ids, context):
        return context.use_bdvif or \
            (utils.to_bridge_domain(asr1k_db.MIN_SECOND_DOT1Q) <= int(self.id) <=
             utils.to_bridge_domain(asr1k_db.MAX_SECOND_DOT1Q) and
             int(self.id) not in all_bd_ids)

class KeepBDUpInterface(ServiceInstance):
    PORT_CHANNEL = "2"

    def __init__(self, **kwargs):
        super(KeepBDUpInterface, self).__init__(**kwargs)

    def to_dict(self, context):
        if context.use_bdvif:
            return super(KeepBDUpInterface, self).to_dict(context)
        else:
            return {}

    def is_orphan(self, all_router_ids, all_segmentation_ids, all_bd_ids, context):
        raise NotImplementedError("This class' orphan check is handled by LoopbackExternalInterface")


import sys
sys.path.append("/home/ccjh/demo_git/sele_po_demo")
import unittest, time, HTMLTestRunner
from config.parameter import test_case_path, report_name
from src.common import send_mail

suite = unittest.defaultTestLoader.discover(start_dir = test_case_path, pattern='test*.py')

if __name__ =="__main__":
    report = report_name+"Report.html"
    fb = open(report, 'wb')
    runner = HTMLTestRunner.HTMLTestRunner(
        stream = fb,
        title = "test",
        description = "u know"
    )
    runner.run(suite)
    fb.close()
    time.sleep(10)
    email = send_mail.send_mail()
    email.sendReport()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from django.urls import reverse
from unittest import skip
from rest_framework import status
from mailservice.models import *

class MailHistoryApiTest(TestCase):
    def test_get_mail(self):
        url = reverse('mail')
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_get_mail_with_filter(self):
        url = reverse('mail')
        response = self.client.get(url, {'subject': 'hello'}, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

class MailSendingApiTest(TestCase):
    def test_create_account_null_body(self):
        url = reverse('mail')
        data = {}
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_create_account_invalid_email(self):
        url = reverse('mail')
        data = {
            "from_mail": "sender",
            "to_mail": "receiver"
        }
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    @skip("TODO: mock mail provider")
    def test_create_account_valid_body(self):
        url = reverse('mail')
        data = {
            "from_mail": "sender@mail.com",
            "to_mail": "receiver@mail.com"
        }
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(Mail.objects.count(), 1)


from matplotlib import pyplot as plt
import numpy as np

def difference_example(color, dpi, image_path, extension):
    np.random.seed(42)
    samples = [np.random.normal(n/30) for n in range(100)]

    plt.plot(samples, label="y", color=color)
    plt.plot(np.diff(samples, 1), color="black", linestyle="--", label=r"$\nabla$y", linewidth=0.9)
    plt.xlabel("Tempo")
    plt.ylabel("Magnitude")
    plt.title("Exemplo de uso de operador de diferenças")
    plt.legend()

    path=f"{image_path}.{extension}"
    plt.savefig(path, dpi=dpi, format=extension)

    plt.close()


"""Dataset generator implementation"""
from typing import Tuple

import gin
import numpy as np

from src.constants import FEATURES_NUMBER

@gin.configurable()
def get_dataset(
        n_samples: int,
        train_test_split: float,
        seed: int
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
    np.random.seed(seed)
    x = np.random.random(size=(n_samples, FEATURES_NUMBER))
    y = 10 * x[:, 0] * (x[:, 0] + 5 * x[:, 1]) - 1/100 * x[:, 2]

    split = int(n_samples * train_test_split)
    return x[:split, :], y[:split], x[split:, :], y[split:]


# 通过盒形图可视化不同卧室个数对应的房屋价格的分布
# 通过双变量图观察卫生间个数与房屋价格的关系
# 通过热图可视化变量间的关系

# 如果有多个画图 运行程序时 每个图的show（）不能少 不然容易最后都画到一张图上面

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

data_path = 'C:\\Users\\shine小小昱\\Desktop\\house_data.csv'
save_path = 'C:\\Users\\shine小小昱\\Desktop\\'

def collect_data():
    """
    载入csv数据至pandas
    :return: 所有数据df
    """
    f       = open(data_path, encoding='utf-8')      # 中文文件名或中文路径必须这么打开
    data_df = pd.read_csv(f, header=0)               # 可只读取需要的列
    return data_df

def inspect_data(data_df):
    """
    审查数据
    :param data_df: 所有数据df
    :return:
    """
    print('数据预览：')
    print(data_df.head(10))

    print('数据基本信息：')
    print(data_df.info())

    print('数据内容统计：')
    print(data_df.describe())

def process_data(data_df):
    """
    处理数据，去除空值
    :param data_df: 所有数据df
    :return: 去除空值后的数据
    """
    cln_data_df = data_df.dropna()
    print('原始数据有{}行记录，处理后的数据有{}行记录'.format(data_df.shape[0], cln_data_df.shape[0]))

    return cln_data_df

def analyze_by_box(df):
    """
    通过盒形图可视化不同卧室个数对应的房屋价格的分布
    :param df: 数据
    :return:
    """

    sns.boxplot(data=df, x="bedrooms", y='price')
    plt.title('Price Analysis by Bedroom')
    plt.savefig(save_path + '卧室房价盒型图.png')
    plt.show()

def analyze_dual_variables(df):
    """
    通过双变量图观察卫生间个数与房屋价格的关系
    :param df: 数据
    :return:
    """

    sns.jointplot(data=df, x='bathrooms', y='price')  # 这种画图不能加标题 不然会混乱乱
    plt.savefig(save_path + '房价卫生间变量关系.png')
    plt.show()

def analyze_variables_relationships(df):
    """
    通过热图可视化变量间的关系（基于皮尔逊相关系数：-1 到 0 到 1 ，体现正负相关强度）
    :param df:
    :return:
    """
    corr_df = df.corr()   # df对象本身具有相关性计算方法 可添加参数更改相关性计算公式 默认计算皮尔逊相关系数
    sns.heatmap(corr_df, annot=True)  # 传入相关性结果数组 调用注释 显示所有变量的两两相关性
    plt.title("Houses' Attributions Relationships")
    plt.savefig(save_path + '房价变量相关性热图.png')
    plt.show()

if __name__ == '__main__':
    all_data_df = collect_data()
    inspect_data(all_data_df)
    proc_data_arr = process_data(all_data_df)
    analyze_by_box(proc_data_arr)
    analyze_dual_variables(proc_data_arr)
    analyze_variables_relationships(proc_data_arr)


import os
import logging

import pickle
import numpy as np
import torch

from torch.utils.data import Dataset, DataLoader

class CIFAR10Data(Dataset):
    def __init__(self, images, labels, transform=None):
        self.images = images
        self.labels = labels
        self.transform = transform

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

    def __getitem__(self, index):
        label = torch.tensor(self.labels[index], dtype=torch.long)
        image = self.images[index].astype('uint8')
        if self.transform:
            image = self.transform(image)
        return image, label

def load_CIFAR_batch(filename):
    with open(filename, "rb") as f:
        datadict = pickle.load(f, encoding="latin1")
        X = datadict["data"]
        Y = datadict["labels"]
        X = X.reshape(10000, 3, 32, 32).transpose(0, 2, 3, 1).astype("int")
        Y = np.array(Y)
        return X, Y

def load_CIFAR10(ROOT):
    """ load all of cifar batches (1-5 + test)"""
    xs = []
    ys = []
    for b in range(1, 6):
        f = os.path.join(ROOT, "data_batch_%d" % (b,))
        X, Y = load_CIFAR_batch(f)
        xs.append(X)
        ys.append(Y)
    Xtr = np.concatenate(xs)
    Ytr = np.concatenate(ys)
    del X, Y
    Xte, Yte = load_CIFAR_batch(os.path.join(ROOT, "test_batch"))
    return {
        "X_train": Xtr,
        "y_train": Ytr,
        "X_test": Xte,
        "y_test": Yte,
    }

def count_parameters(model):
    return sum(p.numel() for p in model.parameters() if p.requires_grad)


from django.contrib import admin
from app.models import User, Club, Book, Chat, Message, FriendRequest, Post, Meeting

# Register your models here.

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    """Configuration of the admin interface for users."""

    list_display = [
        'username', 'first_name', 'last_name', 'email', 'location', 'id'
    ]

@admin.register(Club)
class ClubAdmin(admin.ModelAdmin):
    """Configuration of the admin interface for users."""

    list_display = [
        'name', 'description', 'visibility', 'public'
    ]

@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    """Configuration of the admin interface for users."""

    list_display = [
        'ISBN', 'title', 'author', 'publisher'
    ]

admin.site.register(Chat)
admin.site.register(Message)

@admin.register(FriendRequest)
class FriendRequest(admin.ModelAdmin):
    list_display = [
        'sender', 'receiver', 'created_at'
    ]

@admin.register(Post)
class Post(admin.ModelAdmin):
    list_display = [
        "title", "content", "created_at"
    ]
@admin.register(Meeting)
class Meeting(admin.ModelAdmin):
    list_display = [
        "name", "club", "book", "time"
    ]


from django.db import models
from django.contrib.auth.models import User
from cloudinary.models import CloudinaryField
from django.utils.text import slugify
from django.utils import timezone

class Post(models.Model):
    """
    Model for user posts
    """
    title = models.CharField(
        max_length=200,
        verbose_name="Title",
        )
    slug = models.SlugField(
        max_length=200,
        unique=True
        )
    author = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="post_posts"
    )
    content = models.TextField(
        blank=True,
        null=True,
    )
    featured_image = CloudinaryField(
        'image',
        default='placeholder'
        )
    created_on = models.DateTimeField(
        auto_now_add=True
        )
    updated_on = models.DateTimeField(
        auto_now=True
        )
    likes = models.ManyToManyField(
        User,
        related_name='post_likes',
        blank=True,
        )

    #following code taken from Kim Bergstroem's PP4
    def save(self, *args, **kwargs):
            if not self.slug:
                # Generate a slug based on the username and post title
                base_slug = slugify(self.title)
                timestamp = timezone.now().strftime('%Y%m%d%H%M%S')
                unique_slug = f"{base_slug}-{timestamp}"
                self.slug = unique_slug

            return super().save(*args, **kwargs)

    class Meta:
        ordering = ["-created_on"]

    def __str__(self):
        return self.title

    def number_of_likes(self):
        return self.likes.count()

class Comment(models.Model):
    """
    Model for comments
    """

    post = models.ForeignKey(
        Post,
        on_delete=models.CASCADE,
        related_name="comments"
        )
    name = models.CharField(
        blank=True,
        null=True,
        max_length=80
        )
    author = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="post_comment"
        )
    body = models.TextField()
    created_on = models.DateTimeField(
        auto_now_add=True
    )
    approved = models.BooleanField(default=True)

    class Meta:
        ordering = ["created_on"]

    def __str__(self):
        """
        Returns string for comment
        """
        return f"Comment {self.body} by {self.name}"


"""
It must start with a # symbol
It can have 3 or 6 digits
Each digit is in the range of 0 to F (1,2,3,4,5,6,7,8,9,0,A,B,C,D,E and F)
A - F letters can be lower case (a,b,c,d,e and f are also valid digits)
"""
import re

def solution():
    pattern = re.compile("(#[0-9abcdefABCDEF]{3,6})")
    pattern_begin = re.compile("{$")
    pattern_end = re.compile("}$")
    # Comment lines object when you finish testing
    lines = []
    begin_end = ""
    n = int(input())
    for _ in range(n):
        tmp = input()
        begin_match = pattern_begin.search(tmp)
        end_match = pattern_end.search(tmp)
        if (begin_end == "" or begin_end == "}") and begin_match:
            begin_end = "{"
        elif begin_end == "{" and end_match == None:
                groups = pattern.finditer(tmp)
                for match in groups:
                    # If you finish testing the code comment the next line
                    lines.append(match.group(0))
                    # If you finish testing uncomment the next line
                    # print(match.group(0))
        elif begin_end == "{" and end_match:
            begin_end = "}"
    # Comment the next line when you finish testing
    return lines

import pytest

monkeypatch = pytest.MonkeyPatch()

def test_one():
    inputs = iter([
        "11",
        "#BED",
        "{",
        "    color: #FfFdF8; background-color:#aef;",
        "    font-size: 123px;",
        "    background: -webkit-linear-gradient(top, #f9f9f9, #fff);",
        "}",
        "#Cab",
        "{",
        "    background-color: #ABC;",
        "    border: 2px dashed #fff;",
        "}",
    ])
    results = [
        "#FfFdF8",
        "#aef",
        "#f9f9f9",
        "#fff",
        "#ABC",
        "#fff",
    ]
    monkeypatch.setattr("builtins.input", lambda: next(inputs))
    output = solution()
    monkeypatch.undo()
    assert output == results

def test_two():
    inputs = iter([
        "24",
        ".custom-file-input::-webkit-file-upload-button {",
        "visibility: hidden;",
        "}",
        ".custom-file-input::before {",
        "content: 'Select some files';",
        "display: inline-block;",
        "background: -webkit-linear-gradient(top, #f9f9f9, #e3e3e3);",
        "border: 1px solid #999;",
        "border-radius: 3px;",
        "padding: 5px 8px;",
        "outline: none;",
        "white-space: nowrap;",
        "-webkit-user-select: none;",
        "cursor: pointer;",
        "text-shadow: 1px 1px #fff;",
        "font-weight: 700;",
        "font-size: 10pt;",
        "}",
        ".custom-file-input:hover::before {",
        "border-color: black;",
        "}",
        ".custom-file-input:active::before {",
        "background: -webkit-linear-gradient(top, #e3e3e3, #f9f9f9);",
        "}",
    ])
    results = [
        "#f9f9f9",
        "#e3e3e3",
        "#999",
        "#fff",
        "#e3e3e3",
        "#f9f9f9",
    ]
    monkeypatch.setattr("builtins.input", lambda: next(inputs))
    output = solution()
    monkeypatch.undo()
    assert output == results

if __name__ == "__main__":
    solution()


import dataclasses
from enum import Enum
from pathlib import Path

from pydantic import BaseModel, Field
from pydantic.dataclasses import dataclass

@dataclass
class OutPaths:
    source: Path = dataclasses.field(
        metadata=dict(
            description="The output directory for source files",
        )
    )
    header: Path = dataclasses.field(
        metadata=dict(
            description="The output directory for header files",
        )
    )

class IdentifierStyle(BaseModel):
    class Case(str, Enum):
        none = 'none'
        camel = 'camelCase'
        pascal = 'PascalCase'
        snake = 'snake_case'
        kebab = 'kebab-case'
        train = 'TRAIN_CASE'

    style: Case
    prefix: str = Field(
        default=None,
        description="Prefix that is added to the beginning of the identifier"
    )


from django import forms

from msbdev.models import ContactForm

class ContactFormForm(forms.ModelForm):
    class Meta:
        model = ContactForm
        fields = ['email', 'note']
        widgets = {
            'email': forms.EmailInput(attrs={'class': 'form-control form-control-sm',
                                             'placeholder': 'Your email address'}),
            'note': forms.Textarea(attrs={'class': 'form-control form-control-sm', 'rows': '2',
                                          'placeholder': 'Leave a note'}),
        }


import cv2

haarcascade_frontalface = cv2.CascadeClassifier('./Faces/haarcascade_frontalface_default.xml')

photo = cv2.imread('./Faces/photo2.jpg', cv2.IMREAD_UNCHANGED)

photoGray = cv2.cvtColor(photo,cv2.COLOR_BGR2GRAY)

faces = haarcascade_frontalface.detectMultiScale(photoGray,
scaleFactor=1.05,
minNeighbors=5)

for x,y,w,h in faces:
    cv2.rectangle(photo, (x,y), (x+w,y+h), (0,255,0),3)

cv2.imshow('photo', photo)
cv2.waitKey(0)
cv2.destroyAllWindows()


from keras.applications.vgg16 import VGG16, preprocess_input
# from keras.applications.vgg19 import VGG19, preprocess_input
from keras.applications.xception import Xception, preprocess_input
# from keras.applications.resnet50 import ResNet50, preprocess_input
from keras.applications.inception_v3 import InceptionV3, preprocess_input
from keras import applications
from keras.preprocessing import image
from keras.models import Model
from keras.models import model_from_json
import logging
# other imports
from sklearn.preprocessing import LabelEncoder
import numpy as np
import glob
import h5py
import os
import json
import pickle as cPickle
import datetime
import time

from sklearn.metrics import accuracy_score
# organize imports
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix

logging.basicConfig(level=logging.DEBUG)

logger.debug("Load Config file")

with open('conf/config.json') as f:
	config=json.load(f)

logger.debug("Load Model parameters")
img_width, img_height = config["size"],config["size"]
train_data_dir = config["test"]
validation_data_dir = config["val"]
batch_size = config["batch_size"]
epochs = config["epochs"]
vgg_output=config["vgg"]
inception_output=config["inception"]
xception_output=config["xception"]

# Load moedels
logger.debug("Load VGG Model")
model_vgg = applications.VGG16(weights='imagenet',include_top=False, input_shape = (img_width, img_height, 3))
logger.debug("Load Inception Model")
model_inception = applications.InceptionV3(weights='imagenet',include_top=False, input_shape = (img_width, img_height, 3))
logger.debug("Load Xception Model")
model_xception =applications.Xception(weights='imagenet',include_top=False, input_shape = (img_width, img_height, 3))

# Define Feature extractor
logger.debug("Define Feature extractors")
feat_ext_vgg=Model(input=model_vgg.input, output=model_vgg.get_layer(vgg_output).output)
feat_ext_inception=Model(input=model_inception.input, output=model_inception.get_layer(inception_output).output)
feat_ext_xception=Model(input=model_xception.input, output=model_xception.get_layer(xception_output).output)

if os.path.isdir(train_data_dir) :
	# path to training dataset
	logger.debug("Load Training Dataset")
	train_labels = os.listdir()
else:
	logger.debug("Training Directory not found")
	raise FileNotFoundError('Training Directory not found')

# variables to hold inception features and labels
inception_features = []
inception_test_features = []

# variables to hold vgg features and labels
vgg_features = []
vgg_test_features = []

# variables to hold vgg features and labels
sq_features = []
sq_test_features = []

labels   = []
test_labels =[]

image_size=(img_width, img_height)
# loop over all the labels in the folder
logger.debug("Loop over all the labels in the train folder")
for label in train_labels:
	cur_path = train_data_dir + "/" + label
	print(cur_path)
	for image_path in glob.glob(cur_path + "/*.jpg"):
		img = image.load_img(image_path, target_size=image_size)
		x = image.img_to_array(img)
		x = np.expand_dims(x, axis=0)
		x = preprocess_input(x)
		feature = feat_ext_inception.predict(x)
		flat = feature.flatten()
		inception_features.append(flat)
		feature = feat_ext_vgg.predict(x)
		flat = feature.flatten()
		vgg_features.append(flat)
		feature = feat_ext_xception.predict(x)
		flat = feature.flatten()
		x_features.append(flat)
		labels.append(label)

# loop over all the labels in the folder
logger.debug("Loop over all the labels in the validation folder")
for label in train_labels:
	cur_path = validation_data_dir + "/" + label
	for image_path in glob.glob(cur_path + "/*.jpg"):
		img = image.load_img(image_path, target_size=image_size)
		x = image.img_to_array(img)
		x = np.expand_dims(x, axis=0)
		x = preprocess_input(x)
		feature = feat_ext_inception.predict(x)
		flat = feature.flatten()
		inception_test_features.append(flat)
		feature = feat_ext_vgg.predict(x)
		flat = feature.flatten()
		vgg_test_features.append(flat)
		feature = feat_ext_xception.predict(x)
		flat = feature.flatten()
		x_test_features.append(flat)
		test_labels.append(label)

# encode the labels using LabelEncoder
logger.debug("Encode the labels using LabelEncoder")
targetNames = np.unique(labels)
le = LabelEncoder()
le_labels = le.fit_transform(labels)
test_labels=le.transform(test_labels)

logger.debug("Concatenate Features ")
features = np.concatenate( [np.asarray(vgg_features), np.asarray(inception_features), np.asarray(x_features)], axis=1 )
test_features = np.concatenate( [np.asarray(vgg_test_features), np.asarray(inception_test_features),np.asarray(x_test_features)], axis=1)
seed=config["seed"]

# use logistic regression as the model
print("[INFO] creating Logistic Regression...")
logger.debug("Creating Logistic Regression ")
clf = LogisticRegression(random_state=seed)
clf.fit(features, le_labels)
# evaluate the model of test data
logger.debug("Evaluate the model of test data")
preds = clf.predict(test_features)
print(classification_report(le.inverse_transform(preds),le.inverse_transform(test_labels)))
print("Accuracy :",accuracy_score(le.inverse_transform(preds),le.inverse_transform(test_labels)))
logger.debug(classification_report(le.inverse_transform(preds),le.inverse_transform(test_labels)))
logger.debug("Accuracy :",accuracy_score(le.inverse_transform(preds),le.inverse_transform(test_labels)))

# Xgboost
import xgboost as xgb

# Prepare the inputs for the model
train_X = np.asmatrix(features)
test_X = np.asmatrix(test_features)
#train_y = train_df['Survived']

# You can experiment with many other options here, using the same .fit() and .predict()
# methods; see http://scikit-learn.org
# This example uses the current build of XGBoost, from https://github.com/dmlc/xgboost
print("[INFO] creating XGBoost...")
logger.debug("Creating XGBoost")
gbm = xgb.XGBClassifier(max_depth=3, n_estimators=300, learning_rate=0.05).fit(train_X, le_labels)
preds = gbm.predict(test_X)

print(classification_report(le.inverse_transform(preds),le.inverse_transform(test_labels)))
print("Accuracy :",accuracy_score(le.inverse_transform(preds),le.inverse_transform(test_labels)))
logger.debug(classification_report(le.inverse_transform(preds),le.inverse_transform(test_labels)))
logger.debug("Accuracy :",accuracy_score(le.inverse_transform(preds),le.inverse_transform(test_labels)))

if config["pca"]:
	# Apply PCA
	logger.debug("Apply PCA")
	from sklearn.decomposition import PCA
	logger.debug("Concatenate Test and Train feature set")
	X=np.concatenate( [features,test_features], axis=0 )
	logger.debug("Create PCA with {} of principal components".format(config["n_components"]))
	pca = PCA(n_components=config["n_components"])
	pca.fit(X)

	train_x = pca.transform(features)
	test_x = pca.transform(test_features)

	# Apply Logistic Regression with PCA
	print("[INFO] creating Logistic Regression with PCA...")
	logger.debug("Creating Logistic Regression with PCA")
	clf = LogisticRegression(random_state=seed)
	clf.fit(train_x, le_labels)

	# evaluate the model of test data
	preds = clf.predict(test_x)
	print(classification_report(le.inverse_transform(preds),le.inverse_transform(test_labels)))
	print("Accuracy :",accuracy_score(le.inverse_transform(preds),le.inverse_transform(test_labels)))
	logger.debug(classification_report(le.inverse_transform(preds),le.inverse_transform(test_labels)))
	logger.debug("Accuracy :",accuracy_score(le.inverse_transform(preds),le.inverse_transform(test_labels)))
	# Apply Xgboost with PCA
	# Prepare the inputs for the model
	train_X = np.asmatrix(train_x)
	test_X = np.asmatrix(test_x)

	# You can experiment with many other options here, using the same .fit() and .predict()
	# methods; see http://scikit-learn.org
	# This example uses the current build of XGBoost, from https://github.com/dmlc/xgboost
	print("[INFO] creating XGBoost with PCA...")
	logger.debug("Creating XGBoost with PCA")
	gbm = xgb.XGBClassifier(max_depth=config["xgb_max_dept"], n_estimators=config["xgb_n_estimator"], \
					learning_rate=config["xgb_learning_rate"]).fit(train_X, le_labels)
	preds = gbm.predict(test_X)

	print(classification_report(le.inverse_transform(preds),le.inverse_transform(test_labels)))
	print("Accuracy :",accuracy_score(le.inverse_transform(preds),le.inverse_transform(test_labels)))
	logger.debug(classification_report(le.inverse_transform(preds),le.inverse_transform(test_labels)))
	logger.debug("Accuracy :",accuracy_score(le.inverse_transform(preds),le.inverse_transform(test_labels)))


import torch
import torch.nn as nn
from torchsummary import summary

class Conv3x3(nn.Module):
    def __init__(self, inp_dim, out_dim):
        super().__init__()
        self.conv = nn.Conv2d(inp_dim, out_dim, 3, 1, 1)
        self.relu = nn.ReLU(inplace=True)

    def forward(self, x):
        x = self.conv(x)
        x = self.relu(x)
        return x

class HandSegNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.layer1 = nn.Sequential(
            Conv3x3(3, 64),
            Conv3x3(64, 64),
            nn.MaxPool2d(4, 2, 1)
        )
        self.layer2 = nn.Sequential(
            Conv3x3(64, 128),
            Conv3x3(128, 128),
            nn.MaxPool2d(4, 2, 1)
        )
        self.layer3 = nn.Sequential(
            Conv3x3(128, 256),
            Conv3x3(256, 256),
            Conv3x3(256, 256),
            Conv3x3(256, 256),
            nn.MaxPool2d(4, 2, 1)
        )
        self.layer4 = nn.Sequential(
            Conv3x3(256, 512),
            Conv3x3(512, 512),
            Conv3x3(512, 512),
            Conv3x3(512, 512),
            Conv3x3(512, 512),
            nn.Conv2d(512, 2, 1),
            nn.Upsample(size=(256, 256), mode='bilinear', align_corners=True)
        )

    def forward(self, x):
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)
        return x

if __name__ == '__main__':
    device = torch.device('cuda')
    net = HandSegNet().to(device)
    summary(net, (3, 256, 256))
    x = torch.randn((1, 3, 256, 256)).to(device)
    out = net(x)
    print(out.shape)


"""
=================================
Gaussian Mixture Model Ellipsoids
=================================

Plot the confidence ellipsoids of a mixture of two Gaussians
obtained with Expectation Maximisation (``GaussianMixture`` class) and
Variational Inference (``BayesianGaussianMixture`` class models with
a Dirichlet process prior).

Both models have access to five components with which to fit the data. Note
that the Expectation Maximisation model will necessarily use all five
components while the Variational Inference model will effectively only use as
many as are needed for a good fit. Here we can see that the Expectation
Maximisation model splits some components arbitrarily, because it is trying to
fit too many components, while the Dirichlet Process model adapts it number of
state automatically.

This example doesn't show it, as we're in a low-dimensional space, but
another advantage of the Dirichlet process model is that it can fit
full covariance matrices effectively even when there are less examples
per cluster than there are dimensions in the data, due to
regularization properties of the inference algorithm.

"""

import itertools

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from scipy import linalg

from sklearn import mixture

color_iter = itertools.cycle(["navy", "c", "cornflowerblue", "gold", "darkorange"])

def plot_results(X, Y_, means, covariances, index, title):
    splot = plt.subplot(2, 1, 1 + index)
    for i, (mean, covar, color) in enumerate(zip(means, covariances, color_iter)):
        v, w = linalg.eigh(covar)
        v = 2.0 * np.sqrt(2.0) * np.sqrt(v)
        u = w[0] / linalg.norm(w[0])
        # as the DP will not use every component it has access to
        # unless it needs it, we shouldn't plot the redundant
        # components.
        if not np.any(Y_ == i):
            continue
        plt.scatter(X[Y_ == i, 0], X[Y_ == i, 1], 0.8, color=color)

        # Plot an ellipse to show the Gaussian component
        angle = np.arctan(u[1] / u[0])
        angle = 180.0 * angle / np.pi  # convert to degrees
        ell = mpl.patches.Ellipse(mean, v[0], v[1], angle=180.0 + angle, color=color)
        ell.set_clip_box(splot.bbox)
        ell.set_alpha(0.5)
        splot.add_artist(ell)

    plt.xlim(-9.0, 5.0)
    plt.ylim(-3.0, 6.0)
    plt.xticks(())
    plt.yticks(())
    plt.title(title)

# Number of samples per component
n_samples = 500

# Generate random sample, two components
np.random.seed(0)
C = np.array([[0.0, -0.1], [1.7, 0.4]])
X = np.r_[
    np.dot(np.random.randn(n_samples, 2), C),
    0.7 * np.random.randn(n_samples, 2) + np.array([-6, 3]),
]

# Fit a Gaussian mixture with EM using five components
gmm = mixture.GaussianMixture(n_components=5, covariance_type="full").fit(X)
plot_results(X, gmm.predict(X), gmm.means_, gmm.covariances_, 0, "Gaussian Mixture")

# Fit a Dirichlet process Gaussian mixture using five components
dpgmm = mixture.BayesianGaussianMixture(n_components=5, covariance_type="full").fit(X)
plot_results(
    X,
    dpgmm.predict(X),
    dpgmm.means_,
    dpgmm.covariances_,
    1,
    "Bayesian Gaussian Mixture with a Dirichlet process prior",
)

plt.show()


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

import wx,shutil,os,time,threading

def zipDir(dirPath,outPath):
    t = time.strftime('%Y%m%d%H%M%S',time.localtime())
    if os.path.isdir(dirPath) and os.path.isdir(outPath):
        name = os.path.join(outPath,t)
        shutil.make_archive(name,'zip',dirPath)

class Backup(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(500, 180))
        self.pnl = wx.Panel(self)

        self.makeMenu()
        self.makePannel()

        self.SetMaxSize((500,180))
        self.Center()
        self.Show()

    def makePannel(self):

        font = wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.NORMAL)

        hboxBackPath = wx.BoxSizer(wx.HORIZONTAL)
        hboxTargetPath = wx.BoxSizer(wx.HORIZONTAL)
        hboxTime = wx.BoxSizer(wx.HORIZONTAL)
        hboxButton = wx.BoxSizer(wx.HORIZONTAL)
        vBox = wx.BoxSizer(wx.VERTICAL)

        backupPathTxt = wx.StaticText(self.pnl, label=u"备份路径:", size=(100, 30))
        backupPathTxt.SetFont(font)
        self.backupPathT = wx.TextCtrl(self.pnl, wx.ID_ANY, style=wx.TE_READONLY)
        button1 = wx.Button(self.pnl, -1, label="...", size=(30, 28))
        self.Bind(wx.EVT_BUTTON,self.chooseBackPath,button1)
        hboxBackPath.Add(backupPathTxt, proportion=2, flag=wx.LEFT, border=2)
        hboxBackPath.Add(self.backupPathT, proportion=8, flag=wx.LEFT, border=10)
        hboxBackPath.Add(button1, proportion=0, flag=wx.LEFT, border=2)

        targetPathTxt = wx.StaticText(self.pnl, label=u"目标路径:", size=(100, 30))
        targetPathTxt.SetFont(font)
        self.targetPathT = wx.TextCtrl(self.pnl, wx.ID_ANY, style=wx.TE_READONLY)
        button2 = wx.Button(self.pnl, -1, label="...", size=(30, 28))
        self.Bind(wx.EVT_BUTTON, self.chooseTargetPath, button2)
        hboxTargetPath.Add(targetPathTxt, proportion=2, flag=wx.LEFT, border=2)
        hboxTargetPath.Add(self.targetPathT, proportion=8, flag=wx.LEFT, border=10)
        hboxTargetPath.Add(button2, proportion=0, flag=wx.LEFT, border=2)

        timePathTxt = wx.StaticText(self.pnl, label=u"间隔时间(min):", size=(150, 30))
        timePathTxt.SetFont(font)
        self.timePathT = wx.TextCtrl(self.pnl, wx.ID_ANY)
        hboxTime.Add(timePathTxt, proportion=2, flag=wx.LEFT, border=2)
        hboxTime.Add(self.timePathT, proportion=4, flag=wx.LEFT, border=2)

        self.buttonStart = wx.Button(self.pnl, -1, label="开始备份", size=(70, 50))
        buttonExit = wx.Button(self.pnl, -1, label="结束退出", size=(70, 50))
        self.Bind(wx.EVT_BUTTON, self.OnQuit, buttonExit)
        self.Bind(wx.EVT_BUTTON, self.start, self.buttonStart)
        hboxButton.Add(self.buttonStart, proportion=0, flag=wx.RIGHT, border=2)
        hboxButton.Add(buttonExit, proportion=0, flag=wx.RIGHT, border=2)

        vBox.Add(hboxBackPath,proportion=1, flag=wx.LEFT, border=2)
        vBox.Add(hboxTargetPath,proportion=1, flag=wx.LEFT, border=2)
        vBox.Add(hboxTime,proportion=1, flag=wx.LEFT, border=2)
        vBox.Add(hboxButton, proportion=1, flag=wx.LEFT, border=2)

        self.SetSizer(vBox)

    def makeMenu(self):
        menuBar = wx.MenuBar()
        exitMenu = wx.Menu()
        fitem = exitMenu.Append(wx.ID_EXIT, "Quit", "Quit Applications")
        self.Bind(wx.EVT_MENU, self.OnQuit, fitem)
        menuBar.Append(exitMenu,"&quit")

        self.SetMenuBar(menuBar)

    def OnQuit(self, e):
        self.Close()

    def chooseBackPath(self,event):
        dlg = wx.DirDialog(self,u"选择文件夹",style=wx.DEFAULT_DIALOG_STYLE)
        if dlg.ShowModal() == wx.ID_OK:
            self.backupPathT.SetValue(dlg.GetPath())
        dlg.Destroy()

    def chooseTargetPath(self,event):
        dlg = wx.DirDialog(self,u"选择文件夹",style=wx.DEFAULT_DIALOG_STYLE)
        if dlg.ShowModal() == wx.ID_OK:
            self.targetPathT.SetValue(dlg.GetPath())
        dlg.Destroy()

    def vaildate(self):
        back = self.backupPathT.GetValue()
        target = self.targetPathT.GetValue()
        time:str = self.timePathT.GetValue()
        if len(back)==0 or len(target)==0 or len(time)==0:
            msg = wx.MessageDialog(None,u'填写信息不全，请重新填写！',u'警告',wx.OK)
            msg.ShowModal()
            return False
        if not time.isdigit():
            msg = wx.MessageDialog(None, u'时间格式不正确，请重新填写', u'警告', wx.OK)
            msg.ShowModal()
            return False
        return True

    def zipfile(self):
        if self.vaildate():
            zipDir(self.backupPathT.GetValue(),self.targetPathT.GetValue())
            t = threading.Timer(int(self.timePathT.GetValue())*60,self.zipfile)
            t.start()

    def start(self,event):
        if self.vaildate():
            self.buttonStart.Enable(False)
            self.zipfile()

if __name__ == '__main__':
    app = wx.App()
    Backup(None, -1, '备份文件')
    app.MainLoop()