from flask import render_template, flash, redirect, session, url_for, current_app, request, make_response
from flask_admin.contrib.sqla import ModelView
from flask_login import current_user, login_user, login_required
from flask_principal import Identity, AnonymousIdentity,identity_changed
from datetime import datetime
from werkzeug.urls import url_parse
from app import app, db,admin_permission
from .models import User,Post,UserRole,Comment,Tag,posts_tags
from .forms import LoginForm,RegistrationForm,PasswordForm,EditProfileForm,PostForm,CommentForm
from sqlalchemy import func
import os,random
from flask_login import logout_user
from flask_admin import Admin,AdminIndexView,expose

class MyAdminIndexView(AdminIndexView):
    def is_accessible(self):
        return admin_permission

    def inaccessible_callback(self, name, **kwargs):
        flash("You have no authority to access this page!")
        if current_user.is_authenticated:
             app.logger.warning('"%s"is try to access the admin page',current_user.username)
             return redirect(url_for('index', next=request.url))
        else:
            app.logger.warning('Anonymous usr tried to access the background')
            return redirect(url_for('index', next=request.url))

    @expose('/')
    def index(self):
        # Get URL for the test view method
        user = User.query.count()
        posts = Post.query.count()
        tags = Tag.query.count()
        comments = Comment.query.count()
        return self.render('admin/welcom.html',
                           users=user,
                           posts=posts,
                           tags=tags,
                           comments=comments,
                           url = '/admin')

admin = Admin(app,template_mode='bootstrap3',
                  index_view=MyAdminIndexView())

class MyViewAll(ModelView):
    def after_model_delete(self, model):
        app.logger.info('Admin "%s" deleted the "%s"',current_user.username, model)

    def after_model_change(self, form, model, is_create):
        app.logger.info('Admin "%s" updated the "%s"', current_user.username, model)

class MyView(MyViewAll):
    column_exclude_list = ('password_hash')
    form_excluded_columns = ('posts', 'comments')

class MyViewpost(MyViewAll):
    form_excluded_columns = ('comments')
    page_size = 6

admin.add_view(MyView(User, db.session))
admin.add_view(MyViewpost(Post, db.session))
admin.add_view(MyViewAll(Comment, db.session))
admin.add_view(MyViewAll(Tag, db.session))

@app.route('/')
@app.route('/index<int:page>')
def index(page=1):
    if current_user.is_anonymous:
        posts = Post.query.order_by(
            Post.timestamp.desc()
        ).paginate(page,3,False)
        recent, top_tags = sidebar_data()

        return render_template('base/index.html',
                               posts=posts,
                               recent=recent,
                               top_tags=top_tags)
    else:
        role = UserRole.query.filter_by(user_id = current_user.id).first()
        posts = Post.query.order_by(
            Post.timestamp.desc()
        ).paginate(page,3,False)
        recent, top_tags = sidebar_data()

        return render_template('base/index.html',
                               posts=posts,
                               recent=recent,
                               top_tags=top_tags,
                               role=role)

@app.route('/login',methods=['GET','POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    # Check the form data
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            # log information
            app.logger.info('"%s" logged in failed', form.username.data)
            return redirect(url_for('login'))
        identity_changed.send(current_app._get_current_object(), identity=Identity(user.id))
        login_user(user, remember=form.remember_me.data)

        #log information
        app.logger.info('"%s" logged in successfully', user.username)

        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('index')
        return redirect(next_page)
    return render_template('user/login.html',title='Login',form=form)

@app.route('/logout')
def logout():
    try:
        # log information
        app.logger.info('"%s" logged out successfully', current_user.username)
        logout_user()
        # Remove session keys set by Flask-Principal
        for key in ('identity.name', 'identity.auth_type'):
            session.pop(key, None)
        # Tell Flask-Principal the user is anonymous
        identity_changed.send(current_app._get_current_object(),
                              identity=AnonymousIdentity())
        return redirect(url_for('index'))
    except Exception as e:
        # log information
        app.logger.info('"%s" logged out failed', current_user.username)
        flash("Logout failed")
        redirect(url_for('index'))

@app.route('/cookies')
def privacy():
    return render_template('base/privacy.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    # Justify the identity of user
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(username=form.username.data,email=form.email.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        userrole = UserRole(user_id=user.id)
        userrole.role_id = 2
        db.session.add(userrole)
        db.session.commit()
        flash('Welcome to join us!')
        # log information
        app.logger.info('"%s" registered successfully', user.username)
        return redirect(url_for('login'))
    return render_template('user/register.html', title='register', form=form)

@app.route('/user/password',methods=['GET','POST'])
@login_required
def security():
    form = PasswordForm()
    if form.validate_on_submit():
        if not current_user.check_password(form.password.data):
            flash('The original password is wrong')
            # log information
            app.logger.info('"%s" changed password failed', current_user.username)
            return redirect(url_for('security'))
        else:
            current_user.set_password(form.passwordnew.data)
            db.session.commit()
            flash('Success! Please login again')
            # log information
            app.logger.info('%s changed password', current_user.username)
            return redirect(url_for('logout'))
    return render_template('user/pawedit.html', title='password_edit',
                           form=form)

@app.route('/user/<username>')
def user(username):
    user = User.query.filter_by(username=username).first_or_404()
    userid = user.id
    posts = Post.query.order_by(
        Post.timestamp.desc()
    ).filter_by(user_id=userid)
    return render_template('user/user.html',user=user,posts=posts)

@app.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
    form = EditProfileForm()
    if form.validate_on_submit():
        current_user.username = form.username.data
        current_user.about_me = form.about_me.data
        db.session.commit()
        flash('Your profile has changed!')

        # log information
        app.logger.info('"%s" has edited profile', current_user.username)

        return redirect(url_for('user', username=current_user.username))
    elif request.method == 'GET':
        form.username.data = current_user.username
        form.about_me.data = current_user.about_me
    return render_template('user/edit_profile.html', title='Profile Editor',
                           form=form)

@app.route('/new_post', methods=['GET', 'POST'])
@login_required
def new_post():
    """View function for new_port."""
    form = PostForm()
    if form.validate_on_submit():
        new_post = Post(title=form.title.data)
        new_post.body = form.body.data
        new_post.timestamp = datetime.now()
        new_post.user_id = current_user.id
        new_post.tags.name = form.tags.data
        print("wow")
        for t in form.tags.data:
            tag = Tag.query.get(t)
            new_post.tags.append(tag)
            print(2)
        db.session.add(new_post)
        db.session.commit()
        flash("Create succss!")
        # log information
        app.logger.info('"%s" has post a new post "%s"', current_user.username,new_post.title)
        return redirect(url_for('index'))

    return render_template('post/new_post.html',
                           form=form)

@app.route('/edit/<id>', methods=['GET', 'POST'])
def edit_post(id):
    """View function for edit_post."""
    post = Post.query.get_or_404(id)
    form = PostForm()

    if post.author.id != current_user.id:
        # log information
        app.logger.warning('"%s" tried to edit post "%s" with no authority', current_user.username, post.title)
        flash ("You have no authority to edit")
        return redirect(url_for('index'))

    if form.validate_on_submit():
        post.title = form.title.data
        post.body = form.body.data
        post.tags.name = form.tags.data
        post.timestamp = datetime.now()
        for t  in form.tags.data:
            tag = Tag.query.get(t)
            post.tags.append(tag)

        # Update the post
        db.session.add(post)
        db.session.commit()
        # log information
        app.logger.info('"%s" has deleted post "%s"', current_user.username, post.title)
        return redirect(url_for('post', post_id=post.id))

    form.title.data = post.title
    form.body.data = post.body

    return render_template('post/edit_post .html', form=form, post=post)

@app.route('/delete_post/<id>', methods=['GET'])
def delete_post(id):
    post = Post.query.get(id)
    db.session.delete(post)
    db.session.commit()
    flash("Delete succss!")
    # log information
    app.logger.info('"%s" has deleted post "%s"', current_user.username, post.title)
    return redirect(url_for("user",username=current_user.username))

def sidebar_data():
    """Set the sidebar function."""
    # Get post of recent
    recent = db.session.query(Post).order_by(
            Post.timestamp.desc()
        ).limit(5).all()

    # Get the tags and sort by count of posts.
    top_tags = db.session.query(
            Tag, func.count(posts_tags.c.post_id).label('total')
        ).join(
            posts_tags
        ).group_by(Tag).order_by('total DESC').limit(5).all()
    return recent, top_tags

@app.route('/post/<post_id>', methods=('GET', 'POST'))
def post(post_id):
    """View function for post page"""
    # Form object: `Comment`
    form = CommentForm()
    # form.validate_on_submit() will be true and return the
    # data object to form instance from user enter,
    # when the HTTP request is POST
    if form.validate_on_submit():
        new_comment = Comment(user_id = current_user.id)
        new_comment.text = form.text.data
        new_comment.date = datetime.now()
        new_comment.post_id = post_id
        db.session.add(new_comment)
        db.session.commit()
        # log information
        app.logger.info('"%s" has commented on post "%s"', current_user.username, new_comment.posts.title)

    post = Post.query.get_or_404(post_id)
    tags = post.tags
    comments = post.comments.order_by(Comment.date.desc()).all()
    recent, top_tags = sidebar_data()

    return render_template('post/post.html',
                               post=post,
                               tags=tags,
                               comments=comments,
                               form=form,
                               recent=recent,
                               top_tags=top_tags)

@app.route('/tag/<string:tag_name>')
def tag(tag_name):
    """View function for tag page"""

    tag = Tag.query.filter_by(name=tag_name).first_or_404()
    posts = tag.posts.order_by(Post.timestamp.desc()).all()
    recent, top_tags = sidebar_data()

    return render_template('post/tags.html',
                           tag=tag,
                           posts=posts,
                           recent=recent,
                           top_tags=top_tags)

def gen_rnd_filename():
    filename_prefix = datetime.now().strftime('%Y%m%d%H%M%S')
    return '%s%s' % (filename_prefix, str(random.randrange(1000, 10000)))

@app.route('/ckupload/', methods=['POST', 'OPTIONS'])
def ckupload():
    """CKEditor file upload"""
    error = ''
    url = ''
    callback = request.args.get("CKEditorFuncNum")

    if request.method == 'POST' and 'upload' in request.files:
        fileobj = request.files['upload']
        fname, fext = os.path.splitext(fileobj.filename)
        rnd_name = '%s%s' % (gen_rnd_filename(), fext)

        filepath = os.path.join(app.static_folder, 'upload', rnd_name)

        # 检查路径是否存在，不存在则创建
        dirname = os.path.dirname(filepath)
        if not os.path.exists(dirname):
            try:
                os.makedirs(dirname)
            except:
                error = 'ERROR_CREATE_DIR'
        elif not os.access(dirname, os.W_OK):
            error = 'ERROR_DIR_NOT_WRITEABLE'

        if not error:
            fileobj.save(filepath)
            url = url_for('static', filename='%s/%s' % ('upload', rnd_name))
            print(url)
    else:
        error = 'post error'

    res = """<script type="text/javascript">
  window.parent.CKEDITOR.tools.callFunction(%s, '%s', '%s');
</script>""" % (callback, url, error)

    response = make_response(res)
    response.headers["Content-Type"] = "text/html"
    return response


import pytest
import requests
import json
import random
from faker import Faker
import userApi_helpers as helper

baseUrl = "https://dev.playground.alexcook.dev/"

def test_getAllUsers():
    url = baseUrl + "api/users"
    response = helper.getUsers(url)
    status_code = response.status_code
    assert status_code == 200

def test_createAndDeleteUser():

    # Create test data
    fake = Faker()
    firstname = fake.first_name()
    lastname = fake.last_name()
    age = random.randint(10,80)
    address = fake.address()
    url = baseUrl + "api/users"

    # Create user
    response = helper.createUser(url, firstname, lastname, age, address)
    status_code = response.status_code
    assert status_code == 200
    result = response.json()
    userId = result.get('userId')

    # Validate data
    url = url + "/" + str(userId)
    response2 = helper.getUsers(url)
    status_code2 = response2.status_code
    assert status_code2 == 200
    result2 = response2.json()
    userIdResult = result2.get('userId')
    firstnameResult = result2.get('firstName')
    lastnameResult = result2.get('lastName')
    ageResult = result2.get('age')
    addressResult = result2.get('address')

    assert userId == userIdResult
    assert firstname == firstnameResult
    assert lastname == lastnameResult
    assert age == ageResult
    assert address == addressResult

    # Delete User
    responseDelete = helper.deleteUser(url)
    deleteStatusCode = responseDelete.status_code
    assert deleteStatusCode == 200

    # Validate Delete
    responseValidate = helper.getUsers(url)
    validateStatusCode = responseValidate.status_code
    assert validateStatusCode == 404

# def test_updateUser():
#     create user
#     update user
#     validate
#     delete user


from .models import UserProfile
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.contrib.auth import get_user_model
from cart.models import Cart

User = get_user_model()

@receiver(post_delete, sender=UserProfile)
def deleteProfile(instance, **kwargs):
    instance.user.delete()

@receiver(post_save, sender=User)
def createProfile(instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

@receiver(post_delete, sender=Cart)
def cartCreate(instance, **kwargs):
    instance.profile.delete()

@receiver(post_save, sender=UserProfile)
def createCart(instance,  created, **kwargs):
    if created:
        Cart.objects.create(profile=instance)


from kwippyproject.kwippy.models.quip import Quip
from django import template
from django.shortcuts import get_object_or_404
from django.template import Node, NodeList, Template, Context, Variable
import pdb, re, string
from kwippy.views.main import ireplace
from django.conf import settings

register = template.Library()

def do_formatquery(parser, token):
    bits = list(token.split_contents())
    nodelist = NodeList()
    return FormatQueryNode(bits[1],bits[2])

def formatquery(parser, token):
    return do_formatquery(parser, token)

class FormatQueryNode(Node):
    def __init__(self, var1, var2):
        self.var1 = Variable(var1)
        self.var2 = Variable(var2)
    def __repr__(self):
        return "<FormatQueryNode>"

    def render(self, context):
        try:
            val1 = self.var1.resolve(context)
        except VariableDoesNotExist:
            val1 = None
        try:
            val2 = self.var2.resolve(context)
        except VariableDoesNotExist:
            val2 = None
        query = val1
        text = val2
        replacement = ''+query+''
        data_object = ireplace(text,query,replacement)
        return data_object

register.tag('formatquery',do_formatquery)


from graphics import Rectangle, Circle, Polygon, Text, GraphWin, Point, Line
from time import sleep
"""
Name: Angie-Bui
lab4.py

Problem: This program utilizes the graphics library and loop to make a greeting card.
It has an arrow shooting through the heart using time.sleep.

Certification of Authenticity:
I certify that this assignment is entirely my own work.
"""
def greeting_card():
    width = 700
    height = 700

    win = GraphWin("Greeting Card", width,height)
    win.setCoords(0,0,10,10)
    win.setBackground("Pink")

    left_circle = Circle(Point(4,7), 1)
    left_circle.setFill("Red")
    left_circle.setOutline("Red")

    right_circle = Circle(Point(5.5, 7), 1)
    right_circle.setFill("Red")
    right_circle.setOutline("Red")

    tri_bot = Polygon(Point(3,7),Point(6.5,7), Point(4.6,3.5))
    tri_bot.setFill("Red")
    tri_bot.setOutline("Red")

    writing = Text(Point(5,2),"Happy Valentine's Day!")
    writing.setSize(30)

    left_circle.draw(win)
    right_circle.draw(win)
    tri_bot.draw(win)
    writing.draw(win)

    arrow = Line(Point(0, 0), Point(2, 2))
    arrow.setWidth(4)
    arrow.setArrow("last")
    arrow.draw(win)

    for i in range(5):
        arrow.move(2,3)
        sleep(0.5)

    close_msg = Text(Point(5, 1), "Click anywhere to close.")
    close_msg.setSize(20)
    close_msg.draw(win)

    win.getMouse()
    win.close()
greeting_card()


####################
#   Board Class    #
####################
# Properties of Board class (accessed with Board.propertyName)
#   Matrix - 2D Array (Numpy.Array) with state of current board.

import numpy as np

# global variables to change row count and col count
# used global variables to avoid magic numbers
ROW_COUNT = 6
COL_COUNT = 7

class Board:
    """
        This class represents the actual Board of the game

        matrix- double sub-scripted list containing description of the current game State with 0 = blank, 1 = playerOne, and 2 = playerTwo
    """
    # The connect-4 puzzle board representation
    def __init__(self, matrix=None, depth=0):
        """
            Create the board object

        Paramaters: matrix - numpy 2D matrix representing the board state.

        Returns: Creates board, returns nothing
        """
        if matrix is None:
            self.matrix = np.zeros((ROW_COUNT,COL_COUNT))
        else:
            self.matrix = matrix

        if depth == 0:
            self.depth = 0
        else:
            self.depth = depth

        for index, element in np.ndenumerate(self.matrix):
            # confirm that the matrix all contains valid values
            if element != 0 and element != 1 and element != 2:

                raise ValueError("Invalid Matrix!")

    def isValidMove(self,point):
        """
            Params: point (tuple) - containing valid (row,col) position on board

            Returns: True/False, True = matrix[row][col] is 0, False = matrix[row][col] == 1 | 2
        """
        # Set point to first tuple in *point args
        row,col = point

        # Verify that the index of point actually exists in the matrix
        try:
            self.matrix[row][col]
        except (ValueError, IndexError):
            return False

        # Since we know the point exists, check it's value
        # Since the move is valid as long as the column is not completly filled up, we can assume row = 0
        if self.matrix[0][col] == 0:
            return True

        return False

    def makeMove(self,point,playerValue):
        """
            Params:     point (tuple) - containing valid (row,col) position on board
                        player (int) - value of player for board (1 or 2) - used for coloring pieces

            Returns:    Board (Board) - representing the new state of the game after the move
                        Returns None if no move can be made
        """
        # Set point to first tuple in *point args
        row,col = point

        # If move is invalid, return None
        if not self.isValidMove(point):
            return None

        # Verify the player number is valid
        if playerValue != 1 and playerValue != 2:
            return ValueError("Invalid playerValue!")

        # Since the playerValue and point is valid, make the move
        self.matrix[row][col] = playerValue
        self.depth += 1
        return self

    # A function to provide a string representation of the board
    def __str__(self):
        # s will be used to hold everything we are returning, and will be returned at the end
        s = '\n'

        # String with "-" characters sized according to board size to serve as horizontal bar
        bar = ''
        # + (ROW_COUNT*4) since for each row there are 4 characters added (" | "), etc
        for i in range (COL_COUNT + (ROW_COUNT*4)):
            bar += "-"
        bar += '\n'

        # Similar to bar, but used to box in the top and bottom of game board
        border = ''
        for i in range (COL_COUNT + (ROW_COUNT*4)):
            border += "="
        border += '\n'

        # Draw Row Numbers
        # String to hold entire Row #'s section seperaetly'
        colNums = "Col Index's\n" + bar +  '|| '

        # Add row index values to colNums string, formatted properly
        for i in range (COL_COUNT):
            if i == 0:
                colNums += str(i)
            else:
                colNums += " | " + str(i)
        colNums += " ||     (Row Index's)\n"

        # Add colNums and bar strings to s, so that they will be returned
        s += colNums + bar

        # Iterate matrix and add formatted strings to s
        s += '\n'
        for row in range(ROW_COUNT):
            s += "|| "
            for col in range(COL_COUNT):
                if col == 0:
                    s += str(int(self.matrix[row][col]))
                else:
                    s += " | " + str(int(self.matrix[row][col]))
            s += ' ||       [' + str(row) + "]\n\n"
        return s + '\n\n'


import jieba
import numpy as np
import paddle
from paddlenlp.data import Vocab

def convert_example(example, tokenizer, is_test=False):
    """
    jieba 分词，转换id
    """

    input_ids = tokenizer.encode(example["text"])
    valid_length = np.array(len(input_ids), dtype='int64')
    input_ids = np.array(input_ids, dtype='int64')

    if not is_test:
        label = np.array(example["label"], dtype="int64")
        return input_ids, valid_length, label
    else:
        return input_ids, valid_length

def create_dataloader(dataset,
                      trans_fn=None,
                      mode='train',
                      batch_size=1,
                      use_gpu=False,
                      pad_token_id=0,
                      batchify_fn=None):
    """
    Creats dataloader.

    Args:
        dataset(obj:`paddle.io.Dataset`): Dataset instance.
        trans_fn(obj:`callable`, optional, defaults to `None`): function to convert a data sample to input ids, etc.
        mode(obj:`str`, optional, defaults to obj:`train`): If mode is 'train', it will shuffle the dataset randomly.
        batch_size(obj:`int`, optional, defaults to 1): The sample number of a mini-batch.
        use_gpu(obj:`bool`, optional, defaults to obj:`False`): Whether to use gpu to run.
        pad_token_id(obj:`int`, optional, defaults to 0): The pad token index.
        batchify_fn(obj:`callable`, optional, defaults to `None`): function to generate mini-batch data by merging
            the sample list, None for only stack each fields of sample in axis
            0(same as :attr::`np.stack(..., axis=0)`).

    Returns:
        dataloader(obj:`paddle.io.DataLoader`): The dataloader which generates batches.
    """
    if trans_fn:
        dataset = dataset.apply(trans_fn, lazy=True)

    if mode == 'train' and use_gpu:
        sampler = paddle.io.DistributedBatchSampler(
            dataset=dataset, batch_size=batch_size, shuffle=True)
    else:
        shuffle = True if mode == 'train' else False
        sampler = paddle.io.BatchSampler(
            dataset=dataset, batch_size=batch_size, shuffle=shuffle)
    dataloader = paddle.io.DataLoader(
        dataset,
        batch_sampler=sampler,
        return_list=True,
        collate_fn=batchify_fn)
    return dataloader


import openpyxl
import decimal
from openpyxl import load_workbook
import re
import datetime
import tools

# wb = load_workbook('datatypes.xlsx')
# print(f'"{wb.active["A1"]}的数据类型为{type(wb.active["A1"].value)}')
# print(f'"{wb.active["A2"]}的数据类型为{type(wb.active["A2"].value)}')
# print(f'"{wb.active["A3"]}的数据类型为{type(wb.active["A3"].value)}')
# print(f'"{wb.active["A4"]}的数据类型为{type(wb.active["A4"].value)}')
def main():
    # print(transfer_to_decimal('100.'))
    # print(transfer_to_decimal('100.1'))
    # print(transfer_to_decimal('100.11'))
    # print(transfer_to_decimal('100.113'))
    # print(transfer_to_decimal('-100.115'))
    num_decimal = decimal.Decimal('0')
    wb = load_workbook('amount.xlsx')
    for i in range(3, 61):
        num_decimal += tools.transfer_to_decimal(wb.active['C' + str(i)].value)
    print(num_decimal)
    num_float = 0
    for i in range(3, 61):
        num_float += float(wb.active['C' + str(i)].value)
    print(num_float)

if __name__ == '__main__':
    # main()
    # get_datatype()
    # get_sumifs()
    data = [9223372036854775807,123.45,'12345',"字符串",datetime.datetime(1733,5,27,19),'=A1+A2']
    for j in range(1,len(data)+1):
        tools.save_to_excel('a',j,data[j-1])
    # save_to_excel()


import librosa
import numpy as np
import tensorflow as tf
import gradio as gr

# File Paths
model_path = "sound_emotion_rec_model"
categories = ['angry', 'disgust', 'fear', 'happy', 'neutral', 'ps', 'sad']
model = tf.keras.models.load_model(model_path)

# loading the files
def extract_mfcc(audio_path, duration=3, offset=0.5, n_mfcc=40):
    # loading the data
    y, sr = librosa.load(audio_path, duration=duration, offset=offset)

    # extracting the voice feature
    mfcc = np.mean(librosa.feature.mfcc(y=y, sr=sr, n_mfcc=n_mfcc).T, axis=0)

    return mfcc

def prepare_data(audio_path):

  # extracting the features
  features = extract_mfcc(audio_path)

  # adjusting the shape
  features = [x for x in features]
  features = np.array(features)
  features = np.expand_dims(features, -1)

  return features

def clsf(audio_path):

  # extracting the features
  features = prepare_data(audio_path)

  # batching the data
  sample = np.expand_dims(features, axis=0)

  # predicting
  preds = model.predict(sample)[0]

  # results
  confidences = {categories[i]:np.round(float(preds[i]), 3) for i in range(len(categories))}

  return confidences

def pre_processor(audio_path):

  # load the audio file
  x, sample_rate = librosa.load(audio_path)

  # feature extracting (mfccs is an aduio feature)
  mfccs = np.mean(librosa.feature.mfcc(y=x, sr=sample_rate, n_mfcc=40).T, axis=0)
  feature = mfccs

  return feature

# GUI Component
gui_params = {
    "fn":clsf,
    "inputs":gr.Audio(source="upload", type="filepath"),
    "outputs" : "label",
    #live=True,
    "examples" : "examples"

}
demo = gr.Interface(**gui_params)

# Launching the demo
if __name__ == "__main__":
    demo.launch()


from pathlib import Path

from cltl.dialogue_evaluation.graph_evaluation import GraphEvaluator

SCENARIO_FOLDER = './data/3cf7c0b8-f69d-45e8-b804-cb6aca3a044d/'
RDF_FOLDER = SCENARIO_FOLDER + f'rdf/'

#SCENARIO_FOLDER='./data/emissor'
#RDF_FOLDER ='d0fc872d-8199-46a2-94e1-aa739bc9ed7c/'

evaluator = GraphEvaluator()

evaluator.evaluate_conversation(Path(SCENARIO_FOLDER), Path(RDF_FOLDER),
                                metrics_to_plot=['GROUP A - Average degree', 'GROUP A - Sparseness'])


class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n)]
        self.rank = [0] * n

    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return False
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
        return True

def kruskal(n, edges):
    uf = UnionFind(n)
    ans = 0
    for x, y in edges:
        if not uf.unite(x, y):
            ans += 1
    return ans

# 無向グラフのエッジリスト
# edges = [(0, 1), (1, 2), (2, 3), (3, 0), (2, 4)]

n, m = map(int, input().split())
a = [0]*m
b = [0]*m
edges = []

for i in range(m):
  a, b = map(int, input().split())
  edges.append((a-1, b-1))
# print(edges)
print(kruskal(n, edges)) # => 2


import pygame as pg
from board import board
from tkinter import *
from tkinter import messagebox
from draw_window import *
from draw_flag import draw_flag

def main():
    pg.init()
    pg.mixer.init()

    res = (400, 480)
    mute = False

    surface = pg.image.load('flag_icon.png')
    mine_surface = pg.image.load('mine_icon.jpg')
    pg.display.set_icon(surface)

    level_surface = pg.image.load('level_icon.jpg')
    mute_surface = pg.image.load('mute2_icon.png')
    sound_surface = pg.image.load('sound2_icon.png')
    settings_surface = pg.image.load('settings_icon.png')

    color = (255, 255, 102)
    color_light = (170, 170, 170)
    color_light2 = (220, 220, 220)
    color_dark = (100, 100, 100)
    main_text_color = (153, 204, 255)

    screen = pg.display.set_mode(res)

    pg.display.set_caption('Majnsviper')

    width = screen.get_width()
    height = screen.get_height()

    size = 500

    smallfont = pg.font.SysFont('Corbel', 35)
    #smallfont = pg.font.SysFont('times-bold', 35)

    main_text = smallfont.render('Majnsviper', True, main_text_color)

    text1 = smallfont.render('Quit', True, color)
    text2 = smallfont.render('Start', True, color)

    selection1 = smallfont.render('Small', True, color)
    selection2 = smallfont.render('Normal', True, color)
    selection3 = smallfont.render('Large', True, color)

    text3 = smallfont.render('Mode', True, color)

    is_mode_selected = False

    brojac_1 = 1

    if mute == False:
        pg.mixer.music.load('Wii_music.mp3')
        pg.mixer.music.play(-1)

    while True:
        game = board()
        game.mute = mute
        screen = pg.display.set_mode(res)
        blockSize = 60

        for ev in pg.event.get():

            if ev.type == pg.QUIT:
                pg.quit()

            if ev.type == pg.MOUSEBUTTONUP:
                if width / 2 - 70 <= mouse[0] <= width / 2 + 70 and height / 2 - 80 <= mouse[1] <= height / 2 - 40:
                    pg.mixer.music.stop()
                    game.set_blocksize_and_size(blockSize, size)
                    while main_f(brojac_1, game) == 0:
                        pass

                    pg.display.set_icon(surface)
                    pg.display.set_caption('Majnsviper')

                    mute = game.mute
                    blockSize = game.blocksize
                    pg.mixer.music.load('Wii_music.mp3')
                    game.set_number_of_mines()
                    game.set_blocksize_and_size(blockSize, size)
                    if mute == False:
                        pg.mixer.music.play(-1)

                elif width / 2 - 70 <= mouse[0] <= width / 2 + 70 and height / 2 - 20 <= mouse[1] <= height / 2 + 20:
                    pg.quit()
                    return

                elif is_mode_selected and width / 2 - 70 <= mouse[0] <= width / 2 + 70 and height / 2 + 80 <= mouse[
                    1] <= height / 2 + 120:
                    pg.mixer.music.stop()
                    blockSize = 60
                    game.set_blocksize_and_size(blockSize, size)
                    while main_f(brojac_1, game) == 0:
                        pass

                    pg.display.set_icon(surface)
                    pg.display.set_caption('Majnsviper')

                    mute = game.mute
                    blockSize = game.blocksize
                    game.set_number_of_mines()
                    game.set_blocksize_and_size(blockSize, size)
                    pg.mixer.music.load('Wii_music.mp3')
                    if mute == False:
                        pg.mixer.music.play(-1)

                elif is_mode_selected and width / 2 - 70 <= mouse[0] <= width / 2 + 70 and height / 2 + 120 <= mouse[
                    1] <= height / 2 + 160:
                    pg.mixer.music.stop()
                    blockSize = 30
                    game.set_blocksize_and_size(blockSize, size)
                    while main_f(brojac_1, game) == 0:
                        pass

                    pg.display.set_icon(surface)
                    pg.display.set_caption('Majnsviper')

                    mute = game.mute
                    blockSize = game.blocksize
                    game.set_number_of_mines()
                    game.set_blocksize_and_size(blockSize, size)
                    pg.mixer.music.load('Wii_music.mp3')
                    if mute == False:
                        pg.mixer.music.play(-1)

                elif is_mode_selected and width / 2 - 70 <= mouse[0] <= width / 2 + 70 and height / 2 + 160 <= mouse[
                    1] <= height / 2 + 200:
                    pg.mixer.music.stop()
                    blockSize = 20
                    game.set_blocksize_and_size(blockSize, size)
                    while main_f(brojac_1, game) == 0:
                        pass

                    pg.display.set_icon(surface)
                    pg.display.set_caption('Majnsviper')

                    mute = game.mute
                    blockSize = game.blocksize
                    game.set_number_of_mines()
                    game.set_blocksize_and_size(blockSize, size)
                    pg.mixer.music.load('Wii_music.mp3')
                    if mute == False:
                        pg.mixer.music.play(-1)

                elif width - 60 <= mouse[0] <= width - 20 and height - 60 <= mouse[1] <= height - 20:
                    mute = not mute
                    if mute == True:
                        pg.mixer.music.stop()
                    else:
                        pg.mixer.music.play(-1)

                elif width - 105 <= mouse[0] <= width - 65 and height - 60 <= mouse[1] <= height - 20:
                    settings_window = pg.display.set_mode((width, height))
                    pg.display.set_caption('Settings')
                    pg.display.set_icon(settings_surface)

                    run = True

                    while run:
                        settings_window.fill(color)
                        pg.display.update()
                        for event in pg.event.get():
                            if event.type == pg.QUIT:
                                run = False

                    pg.display.set_icon(surface)
                    pg.display.set_caption('Majnsviper')

        # fills the screen with a color
        screen.fill(color)

        # stores the (x,y) coordinates into
        # the variable as a tuple
        mouse = pg.mouse.get_pos()

        # if mouse is hovered on a button it
        # changes to lighter shade

        pg.draw.rect(screen, color_dark, [width / 2 - 70, height / 2 - 20, 140, 40])
        pg.draw.rect(screen, color_dark, [width / 2 - 70, height / 2 - 80, 140, 40])
        pg.draw.rect(screen, color_dark, [width / 2 - 70, height / 2 + 40, 140, 40])

        flag_img = pg.transform.scale(surface, (40, 40))
        mine_img = pg.transform.scale(mine_surface, (40, 40))
        level_icon = pg.transform.scale(level_surface, (40, 40))
        sound_icon = pg.transform.scale(sound_surface, (40, 40))
        mute_icon = pg.transform.scale(mute_surface, (40, 40))
        settings_icon = pg.transform.scale(settings_surface, (40, 40))

        screen.blit(flag_img, (width / 2 - 130, height / 2 - 80))
        screen.blit(mine_img, (width / 2 - 130, height / 2 - 20))
        screen.blit(level_icon, (width / 2 - 130, height / 2 + 40))
        if mute == False:
            screen.blit(mute_icon, (width - 60, height - 60))
        else:
            screen.blit(sound_icon, (width - 60, height - 60))
        screen.blit(settings_icon, (width - 105, height - 60))

        if width / 2 - 70 <= mouse[0] <= width / 2 + 70 and height / 2 - 20 <= mouse[1] <= height / 2 + 20:
            is_mode_selected = False
            pg.draw.rect(screen, color_light, [width / 2 - 70, height / 2 - 20, 140, 40])

        elif width / 2 - 70 <= mouse[0] <= width / 2 + 70 and height / 2 - 80 <= mouse[1] <= height / 2 - 40:
            is_mode_selected = False
            pg.draw.rect(screen, color_light, [width / 2 - 70, height / 2 - 80, 140, 40])

        elif width / 2 - 70 <= mouse[0] <= width / 2 + 70 and height / 2 + 40 <= mouse[1] <= height / 2 + 80:
            is_mode_selected = True
            pg.draw.rect(screen, color_light, [width / 2 - 70, height / 2 + 40, 140, 40])
            pg.draw.rect(screen, color_dark, [width / 2 - 70, height / 2 + 80, 140, 40])
            pg.draw.rect(screen, color_dark, [width / 2 - 70, height / 2 + 120, 140, 40])
            pg.draw.rect(screen, color_dark, [width / 2 - 70, height / 2 + 160, 140, 40])

        elif is_mode_selected and width / 2 - 70 <= mouse[0] <= width / 2 + 70 and height / 2 + 80 <= mouse[
            1] <= height / 2 + 120:
            pg.draw.rect(screen, color_light, [width / 2 - 70, height / 2 + 80, 140, 40])
            pg.draw.rect(screen, color_dark, [width / 2 - 70, height / 2 + 120, 140, 40])
            pg.draw.rect(screen, color_dark, [width / 2 - 70, height / 2 + 160, 140, 40])

        elif is_mode_selected and width / 2 - 70 <= mouse[0] <= width / 2 + 70 and height / 2 + 120 <= mouse[
            1] <= height / 2 + 160:
            pg.draw.rect(screen, color_dark, [width / 2 - 70, height / 2 + 80, 140, 40])
            pg.draw.rect(screen, color_light, [width / 2 - 70, height / 2 + 120, 140, 40])
            pg.draw.rect(screen, color_dark, [width / 2 - 70, height / 2 + 160, 140, 40])

        elif is_mode_selected and width / 2 - 70 <= mouse[0] <= width / 2 + 70 and height / 2 + 160 <= mouse[
            1] <= height / 2 + 200:
            pg.draw.rect(screen, color_dark, [width / 2 - 70, height / 2 + 80, 140, 40])
            pg.draw.rect(screen, color_dark, [width / 2 - 70, height / 2 + 120, 140, 40])
            pg.draw.rect(screen, color_light, [width / 2 - 70, height / 2 + 160, 140, 40])

        else:
            is_mode_selected = False

        if is_mode_selected:
            pg.draw.rect(screen, color_light2, [width / 2 - 70, height / 2 + 40, 140, 40])
            screen.blit(selection1, (width / 2 - 40, height / 2 + 80))
            screen.blit(selection2, (width / 2 - 50, height / 2 + 120))
            screen.blit(selection3, (width / 2 - 40, height / 2 + 160))

        # superimposing the text onto our button
        screen.blit(text1, (width / 2 - 30, height / 2 - 18))
        screen.blit(text2, (width / 2 - 30, height / 2 - 78))
        screen.blit(text3, (width / 2 - 40, height / 2 + 43))
        pg.draw.rect(screen, color_dark, [width / 2 - 77, height / 2 - 180, 160, 40])
        screen.blit(main_text, (width / 2 - 75, height / 2 - 180))

        # updates the frames of the game
        pg.display.update()

def main_f(brojac_1, game):
    gray1 = (155, 155, 155)
    gray2 = (202, 207, 202)
    gray2 = (224,224,224)
    black = (16,16,16)
    brown = (102, 102, 51)
    green = (0, 102, 0)
    tirkizna = (0, 155, 155)
    white = (255, 255, 255)
    red = (255, 25, 0)
    blue = (0, 102, 255)
    light_green = (153, 255, 204)
    yellow = (255, 255, 102)
    test_color = (0, 50, 70)

    background_color = test_color

    font = pg.font.Font('freesansbold.ttf', 32)
    caption = "MyMineSweeper"
    icon = 'mine_icon.jpg'
    icon_surface = pg.image.load(icon)

    # flag_count_img = pg.image.load('flag_icon.png')

    mute_icon_image = pg.image.load('mute2_icon.png')
    mute_icon_image = pg.transform.scale(mute_icon_image, (40, 40))

    sound_icon_image = pg.image.load('sound2_icon.png')
    sound_icon_image = pg.transform.scale(sound_icon_image, (40, 40))

    if game.mute == False:
        sound_or_mute_image = mute_icon_image
    else:
        sound_or_mute_image = sound_icon_image

    width = game.size
    height = game.size

    window = pg.display.set_mode((width, height + 40))
    pg.display.set_caption(caption)
    pg.display.set_icon(icon_surface)

    run = True

    counter_of_moves_played = 0

    while run:
        if game.num_of_free_squares == 0:
            if game.blocksize == 60:
                if game.mute == False:
                    pg.mixer.music.load('Win_music_1.mp3')
                    pg.mixer.music.play(1)
                Tk().wm_withdraw()  # to hide the main window
                messagebox.showinfo('Yeah', 'You won!')
                # animation for win
            elif game.blocksize == 30:
                if game.mute == False:
                    pg.mixer.music.load('Win_music_2.mp3')
                    pg.mixer.music.play(1)
                Tk().wm_withdraw()  # to hide the main window
                messagebox.showinfo('Yeah', 'You won!')
                # animation for win
            elif game.blocksize == 15:
                if game.mute == False:
                    pg.mixer.music.load('Win_music_3.mp3')
                    pg.mixer.music.play(1)
                Tk().wm_withdraw()  # to hide the main window
                messagebox.showinfo('Yeah', 'You won!')
                # animation for win
            game.__init__()
            return 0

        for event in pg.event.get():
            if event.type == pg.MOUSEBUTTONUP:
                if (event.button == 1):
                    pos = pg.mouse.get_pos()
                    if 450 <= pos[0] <= 490 and height - 5 <= pos[1] <= height + 35:
                        if game.mute == True:
                            game.mute = False
                            sound_or_mute_image = mute_icon_image
                        else:
                            game.mute = True
                            sound_or_mute_image = sound_icon_image

                    if game.num_of_moves_played == 0:
                        mem_x = -1
                        mem_y = -1
                        x = 0
                        y = 0
                        for i in range(10, game.size - 10, game.blocksize):
                            y = y % game.num_of_rows

                            for j in range(10, game.size - 10, game.blocksize):
                                x = x % game.num_of_rows

                                rect = pg.Rect(i, j, game.blocksize, game.blocksize)
                                pg.draw.rect(window, (50, 100, 200), rect, 2)

                                if 0 < pos[0] - i < game.blocksize and 0 < pos[1] - j < game.blocksize:
                                    mem_x = x
                                    mem_y = y
                                x = x + 1

                            y = y + 1

                        if mem_x != -1 and mem_y != -1:
                            game.generate_new_array_with_free_starting_square(mem_x, mem_y)
                            game.num_of_moves_played = 1

                    info = draw_window(pos, True, brojac_1, window, game, background_color)
                    if info == 1:
                        game.__init__()
                        return 0
                elif event.button == 3 and game.num_of_flags_remaining >= 0 and game.num_of_moves_played != 0:
                    pos = pg.mouse.get_pos()
                    draw_flag(window, pos, game)
                brojac_1 = 0
            elif event.type == pg.QUIT:
                return 1
            else:
                info = draw_window(0, False, brojac_1, window, game, background_color)
                if info == 1:
                    game.__init__()
                    return 0
                brojac_1 = 0

        flag_count_text_1 = font.render(": ", True, white, black)
        flag_count_text = font.render(str(game.num_of_flags_remaining), True, white, black)
        flag_count_text_1 = pg.transform.scale(flag_count_text_1, (28, 21))
        flag_count_text = pg.transform.scale(flag_count_text, (38, 30))
        window.fill((0, 0, 0), (42, height, 110, 40))
        window.blit(flag_count_text_1, (43, height + 4))
        window.blit(flag_count_text, (60, height + 1))
        window.blit(sound_or_mute_image, (450, height - 5))

    pg.quit()

#start of program
main()


# spisok="Это давно установ,ленный факт,,   --   что!! читателей будет отвлекаться на     удобчтмое сдержние страницы."

spisok = input("Введите предложение")
lst_1 = spisok.split(" ")
print(lst_1)
# убираю знаки препинания
cnt = 0
for i in lst_1:
    if not i.isalpha():
        spisok_1 = list(i)
        for j in spisok_1:
            if not j.isalpha():
                for k in range(spisok_1.count(j)):
                    spisok_1.remove(j)
        lst_1.pop(cnt)
        lst_1.insert(cnt, "".join(spisok_1))
    cnt += 1

# убираю пустые строки
for i in range(lst_1.count("")):
    lst_1.remove("")

# Сортировка
lst_1.sort()

# Таблица
print("_" * 43)
print(f'|{"Слово":^30}|{"Индекс":^10}|')
print("-" * 43)

for i in range(len(lst_1)):
    print(f'|{lst_1[i]:^30}|{i:^10}|')

print("-" * 43)
print(f'|{"К-во слов":^30}|{len(lst_1):^10}|')
print("-" * 43)


"""api URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.conf import settings
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth.models import *
from rest_framework import routers, serializers, viewsets, permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from apiapp import views

schema_view = get_schema_view(
    openapi.Info(
        title='podo api',
        default_version='v4',
        description='api for podo ios',
        terms_of_service='https://www.ourapp.com/policies/terms/',
        contact=openapi.Contact(email=''),
        license=openapi.License(name='...'),
    ),
    public=True,
    permission_classes=(permissions.AllowAny,),
)

urlpatterns = [

    path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
    path('', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
    path('admin/', admin.site.urls),

    path('signup/',views.signup, name = 'signup'),
    path('addwallet/<int:id>/',views.integrate_phantom_wallet, name = 'integrate_phantom_wallet'),
    path('signin/',views.signin, name = 'signin'),
    path('signout/',views.signout, name = 'signout'),

#    path('article_list',views.article_list, name = 'article_list'),
#    path('article_detail/<int:pk>',views.article_detail, name = 'article_detail'),
#    path('article_create',views.article_create, name = 'article_create'),
#    path('article_update/<int:pk>',views.article_update, name = 'article_update'),
#    path('article_delete/<int:pk>',views.article_delete, name = 'article_delete'),
#    path('question_list',views.question_list, name = 'question_list'),
#    path('question_detail/<int:pk>',views.question_detail, name = 'question_detail'),
#    path('question_create',views.question_create, name = 'question_create'),
#    path('question_update/<int:pk>',views.question_update, name = 'question_update'),
#    path('question_delete/<int:pk>',views.question_delete, name = 'question_delete'),
#    path('comment_list',views.comment_list, name = 'comment_list'),
#    path('comment_detail/<int:pk>',views.comment_detail, name = 'comment_detail'),
#    path('comment_create',views.comment_create, name = 'comment_create'),
#    path('comment_update/<int:pk>',views.comment_update, name = 'comment_update'),
#    path('comment_delete/<int:pk>',views.comment_delete, name = 'comment_delete'),
#    path('<int:pk>/answer_detail',views.answer_detail, name = 'answer_detail'),
#    path('<int:pk>/answer_create',views.answer_create, name = 'answer_create'),
#    path('<int:pk>/answer_update',views.answer_update, name = 'answer_update'),
#    path('<int:pk>/answer_delete',views.answer_delete, name = 'answer_delete'),
#    path('<int:pk>/answer_choose',views.answer_choose, name='answer_choose'),

]


from numpy import *
import operator

def createDataSet():
    group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
    labels = ['A','A','B','B']
    return group, labels

def classify0(inX, dataSet, labels, k):
    #距离计算
    dataSetSize = dataSet.shape[0]
    # tile函数作用是按照某个方向复制元素，第一个参数是行，第二个参数是列
    # 这里在行方向复了inX向量dataSetSize次，在列方向复制了1次
    diffMat = tile(inX, (dataSetSize,1)) - dataSet  #计算目标点向量差值
    #对向量中每个数据求平方
    sqDiffMat = diffMat**2                          #差值做平方
    sqDistances = sqDiffMat.sum(axis=1)             #求和
    distances = sqDistances**0.5                    #开方

    #返回distances中元素从小到大排序后的索引值
    sortedDistIndicies = distances.argsort()
    classCount = {}
    #选择距离最小的k个点
    for i in range(k):
        #取出前k个元素的类别
        voteIlabel = labels[sortedDistIndicies[i]]
        #计算类别出现次数，get()方法返回指定键的值，如果值不在字典中返回默认值
        classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1

    #排序
    sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0] [0]

#解析文本记录
def file2matrix(filename):
    #打开文件
    fr = open(filename)
    #读取文件所有内容
    arrayOLines = fr.readlines()
    #得到文件行数
    numberOfLines = len(arrayOLines)
    #返回Numpy矩阵，有numberOfLine行，3列
    returnMat = zeros((numberOfLines,3))
    #返回分类标签向量
    classLabelVector = []
    #行索引
    index = 0
    for line in arrayOLines:
        #对每行数据进行格式化，strip(rm)方法，当rm为空时，默认删除空白
        line = line.strip()
        #使用split()将字符串进行切片
        listFromLine = line.split('\t')
        #取出数据的前三列，放入NumPy矩阵中
        returnMat[index,:] = listFromLine[0:3]
        classLabelVector.append(int(listFromLine[-1]))
        index += 1
    return returnMat,classLabelVector


from cmpTree import *

class Sort:
	def __init__(self, n):
		self.arr = []
		self.n = n
		self.tree = Tree(n)
		self.i = 0
		self.node = self.tree.root
		self.side = None
		self.indexes = [i for i in range(n)]

	def setArr(self, arr, i):
		self.arr = arr
		self.i = i
		self.node = None
		self.indexes = [i for i in range(self.n)]

	def isLess(self, i, j):
		tree = self.tree
		a, b = self.indexes[i], self.indexes[j]
		self.node = tree.appendCmpNode(a, b, self.node, self.side)
		left = self.arr[i] < self.arr[j]
		self.side = left
		return left

	def swap(self, i, j):
		tmp = self.arr[i]
		self.arr[i] = self.arr[j]
		self.arr[j] = tmp
		tmp = self.indexes[i]
		self.indexes[i] = self.indexes[j]
		self.indexes[j] = tmp

	def realSort(self):
		return

	def sort(self):
		self.realSort()
		allStr = "".join(map(str, self.indexes))
		node = Node(allStr)
		self.tree.appendNode(node, self.node, self.side)

	def createCmpTree(self):
		l = len(self.tree.lArrs)
		for i in range(l):
			arr = self.tree.lArrs[i][:]
			self.setArr(arr, i)
			self.sort()

	def printTree(self):
		self.tree.printTree()


from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from .views import (
    HomeView,
    AboutView,
    ProjectsView,
    ProjectsDetailView,
    ContactView
)

app_name = 'portapp'

urlpatterns = [
    path('', HomeView.as_view(), name='home'),
    path('about/', AboutView.as_view(), name='about'),
    path('projects/', ProjectsView.as_view(), name='projects'),
    path('projects/detail/<int:pk>/', ProjectsDetailView.as_view(), name='projects'),
    path('contact/', ContactView.as_view(), name='contact'),
]

urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


from _collections import deque
n, m, k = map(int, input().split())
maps=[list(map(int, input().split())) for _ in range(n)]

# 우, 하, 좌, 상(시계방향)
direction = [(0,1),(1,0),(0,-1),(-1,0)]
# 우, 하, 좌, 상로 옮길 때 주사위 위치
dice_dir = [(2,4,1,3,0,5), (3,5,2,1,4,0),(4,2,0,3,1,5),(5,3,2,0,4,1)]
dice=[6,1,3,5,4,2]

now_dice_location = (0,0)

def bfs(x,y,num):
    visited = [[False] * m for _ in range(n)]
    count=1
    q=deque()
    q.append((x,y))
    visited[x][y] = True
    while q:
        x,y=q.popleft()
        for i in range(4):
            nx,ny=x+direction[i][0], y+direction[i][1]
            if nx < 0 or nx > n - 1 or ny < 0 or ny > m - 1:
                continue
            if maps[nx][ny] == num and visited[nx][ny]==False:
                visited[nx][ny] = True
                q.append((nx,ny))
                count+=1
    return count

def next_dice_list(dir,dice_dir,dice):
    # dice_dir = [(2, 4, 1, 3, 0, 5), (3, 5, 2, 1, 4, 0), (4, 2, 0, 3, 1, 5), (5, 3, 2, 0, 4, 1)]
    # dice = [6, 1, 3, 5, 4, 2]
    new_dice = [0] * 6
    for i in range(6):
        new_dice[i] = dice[dice_dir[dir][i]]

    return new_dice

def next_dir(dir,clock_dir):
    # 한줄로
    # dir = (dir+clock_dir)%4 # 4로 나누면 나머지는 0,1,2,3이므로(시계방향)
    # 반시계 dir += clock_dir if d==-1 : d=3
    dir+=clock_dir
    if dir>3:
        dir=0
    elif dir<0:
        dir=3
    return dir

def rotate_180(dir):
    # 한줄로
    #dir = (dir+2)%4 # 서로 반대 방향은 2씩 차이남. 3을 넘어가면 %4로 해주어 0,1,2,3으로 나오도록!

    if dir == 0:
        dir=2
    elif dir == 2:
        dir = 0
    elif dir == 1:
        dir = 3
    elif dir == 3:
        dir=1
    return dir
dir = 0
score=0
x,y=0,0
for _ in range(k):
    nx,ny=x+direction[dir][0],y+direction[dir][1] #이동
    # 이동 후 주사위 위치
    if nx < 0 or nx > n - 1 or ny < 0 or ny > m - 1:
        dir = rotate_180(dir)
        nx, ny = x + direction[dir][0], y + direction[dir][1]

    score += bfs(nx,ny,maps[nx][ny])*maps[nx][ny]
    dice = next_dice_list(dir, dice_dir, dice)

    if dice[0]> maps[nx][ny]:
        dir = next_dir(dir, 1) # 방향 전환
    elif dice[0]< maps[nx][ny]:
        dir = next_dir(dir, -1)
    elif dice[0] == maps[nx][ny]:
        dir=dir
    x,y=nx,ny
print(score)


'''Given an non-empty list find the largest element in list'''
l1=[10,5,29,8]
l2=[30,30,20]
l3=[4]

# we can use the built-in function max(l)
# but we have to write our custom function to get the largest element in the list
# approach - 1
def getmax(l):
    for i in l:
        for j in l:
            if j>i:
                break
            else:
                return i
print(getmax(l2))
# time complexity for the above function will be: big o of n-square -- example: list sorted in increasing order
# in this we will run the loop one time, two time...n times i.e. n(n+1) times

# optmising the code to make the time complexity linear
# time complexity for the following code will be theta-n as we are comparing each element once only
def getmax(l):
    if not l:
        return None
    else:
        res=l[0]
        for i in range(1,len(l)):
            if l[i]>res:
                res=l[i]
        return res


import requests

# -*- coding: utf-8 -*-
import os

from aiohttp import ClientError
from fastapi import FastAPI, File, UploadFile

# image_chatgpt

from clarifai_grpc.channel.clarifai_channel import ClarifaiChannel
from clarifai_grpc.grpc.api import resources_pb2, service_pb2, service_pb2_grpc
from clarifai_grpc.grpc.api.status import status_code_pb2

import openai

import dotenv
import os

# ipynb 실행용
# import nbformat
# from nbconvert import PythonExporter
# from nbconvert.preprocessors import ExecutePreprocessor
import boto3

from pydantic import BaseModel

from typing import List, Optional

import requests

import secrets

from pydub import AudioSegment

app = FastAPI()

dotenv.load_dotenv()

OPENAI_YOUR_KEY = os.getenv("CHATGPT_API_KEY")
openai.api_key = OPENAI_YOUR_KEY

client_s3 = boto3.client(
    's3',
    aws_access_key_id=os.getenv("CREDENTIALS_ACCESS_KEY"),
    aws_secret_access_key=os.getenv("CREDENTIALS_SECRET_KEY")
)

class Audio(BaseModel):
    audioName: List[str]

class ImageURLRequest(BaseModel):
    images: List[str]
    voiceUrl: Optional[str] = None

def TTS(voice_id, result):

    CHUNK_SIZE = 1024
    if voice_id:
        elevenlabs_url = "https://api.elevenlabs.io/v1/text-to-speech/" + voice_id
    else:
        elevenlabs_url = "https://api.elevenlabs.io/v1/text-to-speech/1Y8VEQXMwbo4IxJO2JKy"

    headers = {
        "Accept": "audio/mpeg",
        "Content-Type": "application/json",
        "xi-api-key": os.getenv("ELEVENLABS_API_KEY")
    }

    elevenlabs_data = {
        "text": result,
        "model_id": "eleven_multilingual_v2",
        "voice_settings": {
            "stability": 0.6,
            "similarity_boost": 1,
            "style": 0,
            "use_speaker_boost": 'false'
        }
    }

    name = secrets.token_hex(nbytes=16)

    response = requests.post(elevenlabs_url, json=elevenlabs_data, headers=headers)
    with open("./audio/" + name + ".mp3", 'wb') as f:
        for chunk in response.iter_content(chunk_size=CHUNK_SIZE):
            if chunk:
                f.write(chunk)
    return name

def add(id, file):
    url = "https://api.elevenlabs.io/v1/voices/add"

    headers = {
    "Accept": "application/json",
    "xi-api-key": os.getenv("ELEVENLABS_API_KEY")
    }

    data = {
        'name': id
    }
    files = {
        ('files', (file, open(file, 'rb'), 'audio/mpeg'))
    }
    response = requests.post(url, headers=headers, data=data, files=files)
    return response

def delete(voice_id):

    headers = {
    "Accept": "application/json",
    "xi-api-key": os.getenv("ELEVENLABS_API_KEY")
        }
    url = "https://api.elevenlabs.io/v1/voices/" + voice_id
    response = requests.delete(url, headers=headers)
    return response

@app.post("/ai/text")
def ipynb(imageRequest: ImageURLRequest):
    print("요청 들어옴")
    fileName = []

    PAT = os.getenv("CLARIFAI_API_KEY")
    USER_ID = 'clarifai'
    APP_ID = 'main'
    MODEL_ID = 'general-image-recognition'
    MODEL_VERSION_ID = 'aa7f35c01e0642fda5cf400f543e7c40'

    print(imageRequest.images)

    result = ""
    # 매개변수 전달
    for image in imageRequest.images:

        IMAGE_URL = image

        message = ""

        channel = ClarifaiChannel.get_grpc_channel()
        stub = service_pb2_grpc.V2Stub(channel)

        metadata = (('authorization', 'Key ' + PAT),)

        userDataObject = resources_pb2.UserAppIDSet(user_id=USER_ID, app_id=APP_ID)

        post_model_outputs_response = stub.PostModelOutputs(
            service_pb2.PostModelOutputsRequest(
                user_app_id=userDataObject,
                model_id=MODEL_ID,
                version_id=MODEL_VERSION_ID,
                inputs=[
                    resources_pb2.Input(
                        data=resources_pb2.Data(
                            image=resources_pb2.Image(
                                url=IMAGE_URL
                            )
                        )
                    )
                ]
            ),
            metadata=metadata
        )

        if post_model_outputs_response.status.code != status_code_pb2.SUCCESS:
            print(post_model_outputs_response.status)
            raise Exception("Post model outputs failed, status: " + post_model_outputs_response.status.description)

        output = post_model_outputs_response.outputs[0]

        print("Predicted concepts:")
        for concept in output.data.concepts:
            print("%s %.2f" % (concept.name, concept.value))
            message += concept.name + " " + str(concept.value) + "\n"

        MODEL = "gpt-3.5-turbo"
        USER_INPUT_MSG = message

        response = openai.ChatCompletion.create(
            model=MODEL,
            messages=[
                {"role": "system",
                 "content": "존댓말로 작성해. 셰익스피어처럼 표현해줘. 나래이션의 스크립트가 필요해. 그 문단은 이 20개의 단어로 구성되어야 해. 꼭 이 단어를 전부 사용할 필요는 없어. 감성적인 표현이 주가 되어야 해. 한국어로 작성하도록 해."},
                {"role": "user", "content": USER_INPUT_MSG},
                {"role": "user", "content": "300글자 이상 500글자 이하가 되도록 문단을 작성해."},
                {"role": "assistant", "content": "네. 글자수는 300글자 이상 500글자 이하가 되도록 문단을 작성하도록 하겠습니다."},
                {"role": "user", "content": "시스템 메시지를 다시 언급하지 마. 반드시 존댓말로 작성하도록 해."},
                {"role": "assistant", "content": "반드시 존댓말로 작성해 드릴게요."},
                # {"role": "assistant", "content": "Who's there?"},
            ],
            temperature=0.7,
            max_tokens=1000  # 최대 토큰 수를 설정하여 답변의 길이를 제어합니다.
        )

        # response['choices'][0]['message']['content']

        result += f"{response['choices'][0]['message']['content']} "

    print(result)

    voiceUrl = imageRequest.voiceUrl

    # 저장할 로컬 폴더 경로
    output_folder = "./voice"

    # 폴더가 없다면 생성
    os.makedirs(output_folder, exist_ok=True)

    input_voice = None

    # URL에서 음성 파일 다운로드
    if voiceUrl != None :
        response = requests.get(voiceUrl)

        if response.status_code == 200:
            # 파일 이름 추출 (URL에서 마지막 슬래시 뒤의 부분을 사용)
            file_name = voiceUrl.split("/")[-1]

            # 로컬에 파일 저장
            with open(os.path.join(output_folder, file_name), "wb") as file:
                file.write(response.content)
            print(f"{file_name}을(를) 다운로드하여 {output_folder}에 저장했습니다.")

            # input_voice 변수에 저장한 음성 파일의 경로를 할당
            input_voice = os.path.join(output_folder, file_name)
            print(f"input_voice 변수에 음성 파일 경로를 할당했습니다: {input_voice}")
        else:
            print("파일을 다운로드할 수 없습니다. 상태 코드:", response.status_code)

    new_voice_id = ""
    if input_voice:
        new_voice_id = add("custom", input_voice).json()["voice_id"]
    print(new_voice_id)
    name = TTS(f"{new_voice_id}", result)
    if input_voice:
        delete(f"{new_voice_id}")

    makeBackGroundMusic(name)
    fileName.append(name + ".mp3")

    return {"audios": saveAudioAtS3(fileName)}

def saveAudioAtS3(audio):
    audioUrl = []

    try:
        for a in audio:
            client_s3.upload_file(
                "./audio/" + a,
                os.getenv("S3_BUCKET"),
                "audio/" + a,
                ExtraArgs={'ContentType': 'audio/mp3'}
            )

            # 로컬에 저장되어있는 음성파일 삭제
            os.remove("./audio/" + a)

            audioUrl.append(os.getenv("S3_URL") + "/" + a)

        return audioUrl
    except ClientError as e:
        print(f'Credential error => {e}')
    except Exception as e:
        print(f"Another error => {e}")

def makeBackGroundMusic(name):
    # 배경 음악 파일 로드
    background_music = AudioSegment.from_mp3("./audio/back.mp3")

    # 원본 mp3 파일 로드
    original_audio = AudioSegment.from_mp3("./audio/" + name + ".mp3") - 5

    # 로컬에 있는 mp3 파일 삭제
    os.remove("./audio/" + name + ".mp3")

    # 배경 음악과 원본 오디오 합치기
    output_audio = background_music.overlay(original_audio, position=10000)

    # 결과를 새 파일로 저장
    output_audio.export("./audio/" + name + ".mp3", format="mp3")

    print("배경 음악이 추가된 오디오를 저장했습니다.")


import pickle, random
import os.path
#Funckja przyjmuje dane klienta i tworzy pliczek z nazwą numeru konta
def create_account(imie, nazwisko, pesel, nr_konta, saldo):
    dane_konta = {"imie": imie, "nazwisko": nazwisko, "pesel": pesel, "saldo": saldo}
    plik_konta = open(f"{nr_konta}.pkl", "wb")
    pickle.dump(dane_konta, plik_konta)
    plik_konta.close()
    plik_konta = open(f"{nr_konta}.pkl", "rb")
    output = pickle.load(plik_konta)
    print(output)
    plik_konta.close()

def register(imie, nazwisko, pesel, saldo):
    numer_klienta = random.randint(10000, 100000)
    while os.path.isfile(f"{numer_klienta}.pkl"):
        numer_klienta = random.randint(10000, 100000)

    create_account(imie, nazwisko, pesel, numer_klienta, saldo)
    print(numer_klienta)
# testowe wywołanie
register(imie = "Szymon", nazwisko = "Jankowski", pesel = 1010101, saldo = 10)


import tkinter as tk
from PIL import Image, ImageTk

win = tk.Tk()
Pic_path = "img5.jpg"
im = Image.open(Pic_path)  # 读取图片
tkImage_list = []

depth = 3
width, height = im.size

def cut_image(Pic):  # 分割图片
    global tkImage_list
    w = int(width/depth)
    h = int(height/depth)
    for i in range(depth):
        for j in range(depth):
            box = (w*j, h*i, w*(j+1), h*(i+1))  # 需要切割的矩形区域
            image = Pic.crop(box)
            tkImage_list.append(ImageTk.PhotoImage(image))
            label = tk.Label(win, image=tkImage_list[i*depth + j])
            """
            Tk.photoImage()显示图片时，
            当把包含该函数放在自定义函数里时，不能正常显示，移出函数又可正常显示，
            所以想到可能是变量不是全局性的缘故，改为全局变量后果然可正常显示
            """
            label.grid(row=i, column=j)
            """ 布局 https://blog.csdn.net/qq_37503890/article/details/90264864"""

if __name__ == '__main__':
    cut_image(im)
    win.mainloop()


import sys
import logging
import wandb
import torch
import os
sys.path.insert(0,os.getcwd())

import yaml
from utils.functions import setup_logger

import argparse
from tqdm import tqdm
from pytorch_lightning import seed_everything

from dataset.transformer_dataset import ClickbaitDataModule
from model.gan import GAN, build_gan_optimizer, gan_save_model
from model.transformer import TransformerForSequenceClassification, \
                              build_transformer_optimizer,\
                              transformer_save_model

from train.transformer_train_epoch import transformer_train_epoch, transformer_validate_model
from train.gan_train_epoch import gan_train_epoch, gan_validate_model
import pdb

logger = logging.getLogger()

def main(config_file: str):
    with open(config_file,'r') as f:
            config = yaml.safe_load(f)

    if not os.path.exists(config['output_path']):
        os.makedirs(config['output_path'])

    setup_logger(logger,config['output_path'])

    best_dev_f1, best_epoch = 0,0
    seed_everything(42)

    # run = wandb.init(project="banbait",entity='colab-team',config=config)
    run = wandb.init(project="banbait",config=config)
    config = wandb.config
    model_type = config.model_type
    ratio = getattr(config, 'ratio',100)
    main_dataset = ClickbaitDataModule(model_name_or_path = config.model_name_or_path,
                                       label_list = config.label_list, batch_size = int(config.batch_size),
                                       data_folder = config.data_dir,
                                       data_column= config.data_column,
                                       label_column= config.label_column,
                                       model_type = model_type,
                                       tokenizer_class = config.tokenizer_class,
                                       ratio = ratio)
    config.num_train_examples = len(main_dataset.train_examples)
    if model_type == 'gan':
      clickbaitmodel = GAN(
          model_name_or_path = config.model_name_or_path,
          num_hidden_layers_g=config.num_hidden_layers_g,
          num_hidden_layers_d=config.num_hidden_layers_d,
          out_dropout_rate = config.out_dropout_rate,
          label_list = config.label_list)
      optimizers = build_gan_optimizer(clickbaitmodel, config)
      train_epoch = gan_train_epoch
      validate_model = gan_validate_model
      save_model = gan_save_model
    elif model_type == 'transformer':
        clickbaitmodel = TransformerForSequenceClassification(model_name_or_path=config.model_name_or_path,
                                                              num_classes=len(config.label_list))
        optimizers = build_transformer_optimizer(clickbaitmodel,config)
        train_epoch = transformer_train_epoch
        validate_model = transformer_validate_model
        save_model = transformer_save_model

    for epoch in tqdm(range(config.epochs)):
        validation_metrics = train_epoch(clickbaitmodel,main_dataset, optimizers,config,epoch+1)
        dev_f1 = validation_metrics['dev/epoch_f1']
        save_best_model = False
        if epoch==0:
          best_dev_f1 = dev_f1
          save_best_model = True

        elif dev_f1>best_dev_f1:
          best_dev_f1 = dev_f1
          save_best_model = True
          best_epoch= epoch

        if save_best_model:
          save_model(os.path.join(config.output_path,f'{model_type}.pt'),clickbaitmodel,optimizers)
          save_best_model = False

    test_metrics = validate_model(clickbaitmodel,main_dataset.test_dataloader(),
                                  config,epoch,'test')
    run.summary['best_dev_f1'] = best_dev_f1
    run.summary['test_f1'] = test_metrics['test/epoch_f1']
    test_f1 = run.summary['test_f1']
    run.summary['best epoch based on dev F1 score'] = best_epoch

    logger.info('Best Epoch based on dev F1 score %s:',best_epoch)
    model_artifact = wandb.Artifact(
          f"{model_type}_{test_f1:.3f}", type=f'{model_type}',
          description=f"{model_type}-test f1 clickbait:{test_f1}",
          metadata=dict(config))
    PATH=os.path.join(config.output_path,f'{model_type}.pt')
    model_artifact.add_file(PATH)
    run.log_artifact(model_artifact)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="inference the model output.")
    parser.add_argument("--config",type=str,required=True,metavar='PATH',help='The model inference config file location')
    args = parser.parse_args()
    main(args.config)


"""
给定链表 head 和两个整数 m 和 n. 遍历该链表并按照如下方式删除节点:
    开始时以头节点作为当前节点.
    保留以当前节点开始的前 m 个节点.
    删除接下来的 n 个节点.
    重复步骤 2 和 3, 直到到达链表结尾.
在删除了指定结点之后, 返回修改过后的链表的头节点.

    示例 1:
        输入: head = [1,2,3,4,5,6,7,8,9,10,11,12,13], m = 2, n = 3
        输出: [1,2,6,7,11,12]
        解析: 保留前(m = 2)个结点,  也就是以黑色节点表示的从链表头结点开始的结点(1 ->2).
            删除接下来的(n = 3)个结点(3 -> 4 -> 5), 在图中以红色结点表示.
            继续相同的操作, 直到链表的末尾.
            返回删除结点之后的链表的头结点.
"""

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

    def add(self, val):
        new_node = self.__class__(val)
        self.next = new_node
        return new_node

    def __str__(self):
        output = []
        root = self
        while root:
            output.append(root.val)
            root = root.next
        return "->".join(map(str, output))

class Solution:
    def deleteNodes(self, head: ListNode, m: int, n: int) -> ListNode:
        return self.answer_1(head, m, n)

    def answer_1(self, head, m, n):
        curr = head
        last = head

        while curr:
            p, q = m, n
            while p and curr:
                last = curr
                curr = curr.next
                p -= 1

            while q and curr:
                curr = curr.next
                q -= 1
            last.next = curr
        return head


import tkinter as tk
from tkinter import ttk, font

from src.connection.database import get_entity
from src.edit.edit_template import EditTemplate
from src.item.item import Item
from src.methods import get_text_data, popup_showinfo
from styles import BUTTON_BACKGROUND_COLOR2, WHITE_COLOR

class EditItem(EditTemplate):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        widgets = kwargs['widgets']
        buttons = kwargs['buttons']

        self.font = font.Font(size=11)

        self.types_ = ('Armor', 'Weapon')

        self.entity: Item

        # --- Attributes ---
        self.name = tk.StringVar(value=self.entity.name)
        self.type_ = tk.StringVar(value=self.types_[self.entity.type - 1])
        self.reduction = tk.StringVar(value=self.entity.reduction)
        self.damage = tk.StringVar(value=self.entity.damage)
        self.range_ = tk.StringVar(value=self.entity.range)
        self.health = tk.StringVar(value=self.entity.health)
        self.area = tk.StringVar(value=self.entity.area)

        # --- Widgets ---
        self.effects_entry = tk.Text()
        self.description_entry = tk.Text()

        self.set_widgets(widgets)
        if buttons is not None:
            self.set_buttons(buttons)

    def set_widgets(self, widgets) -> None:
        name_label = ttk.Label(
            widgets,
            text="Name"
        )
        name_label.grid(row=0, column=0, sticky="EW")

        name_entry = ttk.Entry(
            widgets,
            textvariable=self.name,
            width=60
        )
        name_entry.grid(row=0, column=1, sticky="EW")

        # --- Type ---

        type_label = ttk.Label(
            widgets,
            text="Type"
        )
        type_label.grid(row=1, column=0, sticky="EW")

        type_entry = ttk.Combobox(
            widgets,
            textvariable=self.type_,
            values=self.types_,
            exportselection=False,
            state="readonly"
        )
        type_entry.grid(row=1, column=1, sticky="EW")

        # --- Reduction ---

        reduction_label = ttk.Label(
            widgets,
            text="Reduction"
        )
        reduction_label.grid(row=2, column=0, sticky="EW")

        reduction_entry = ttk.Entry(
            widgets,
            textvariable=self.reduction,
            width=60
        )
        reduction_entry.grid(row=2, column=1, sticky="EW")

        # --- Damage ---

        damage_label = ttk.Label(
            widgets,
            text="Damage"
        )
        damage_label.grid(row=3, column=0, sticky="EW")

        damage_entry = ttk.Entry(
            widgets,
            textvariable=self.damage,
            width=60
        )
        damage_entry.grid(row=3, column=1, sticky="EW")

        # --- Range ---

        range_label = ttk.Label(
            widgets,
            text="Range"
        )
        range_label.grid(row=4, column=0, sticky="EW")

        range_entry = ttk.Entry(
            widgets,
            textvariable=self.range_,
            width=60
        )
        range_entry.grid(row=4, column=1, sticky="EW")

        # --- Health ---

        health_label = ttk.Label(
            widgets,
            text="Health"
        )
        health_label.grid(row=5, column=0, sticky="EW")

        health_entry = ttk.Entry(
            widgets,
            textvariable=self.health,
            width=60
        )
        health_entry.grid(row=5, column=1, sticky="EW")

        # --- Area ---

        area_label = ttk.Label(
            widgets,
            text="Area"
        )
        area_label.grid(row=6, column=0, sticky="EW")

        area_entry = ttk.Entry(
            widgets,
            textvariable=self.area,
            width=60
        )
        area_entry.grid(row=6, column=1, sticky="EW")

        # --- Effects ---

        effects_label = ttk.Label(
            widgets,
            text="Effects"
        )
        effects_label.grid(row=7, column=0, sticky="EW")

        self.effects_entry = tk.Text(
            widgets,
            width=1,
            height=15,
            background=BUTTON_BACKGROUND_COLOR2,
            foreground=WHITE_COLOR
        )
        self.effects_entry.grid(row=7, column=1, sticky="EW")

        effects_scroll = ttk.Scrollbar(
            widgets,
            orient="vertical",
            command=self.effects_entry.yview
        )
        effects_scroll.grid(row=7, column=2, sticky="ns")

        self.effects_entry["yscrollcommand"] = effects_scroll.set

        self.effects_entry.insert(tk.END, self.entity.effects)

        # --- Description ---

        description_label = ttk.Label(
            widgets,
            text="Description"
        )
        description_label.grid(row=8, column=0, sticky="EW")

        self.description_entry = tk.Text(
            widgets,
            width=1,
            height=5,
            background=BUTTON_BACKGROUND_COLOR2,
            foreground=WHITE_COLOR
        )
        self.description_entry.grid(row=8, column=1, sticky="EW")

        description_scroll = ttk.Scrollbar(
            widgets,
            orient="vertical",
            command=self.description_entry.yview
        )
        description_scroll.grid(row=8, column=2, sticky="ns")

        self.description_entry["yscrollcommand"] = description_scroll.set

        self.description_entry.insert(tk.END, self.entity.description)

    def set_buttons(self, buttons) -> None:
        self.search_result = get_entity(self.entity.name, self.search_type)

        separator = ttk.Separator(
            buttons
        )
        separator.grid(row=0, columnspan=1)

        save_button = ttk.Button(
            buttons,
            text='  Save',
            command=lambda: self.save(edit=self.edit),
            style='DarkButton.TButton',
            image=self.save_icon,
            compound=tk.LEFT,
            cursor='hand2'
        )
        save_button.grid(row=1)

        back_button = ttk.Button(
            buttons,
            text='  Back',
            command=lambda: self.back(
                self.go_parent,
                name=self.search_name,
                entity=self.search_result,
                type_=self.search_type,
                search_parent_name=self.search_parent_name,
                parent_name=self.parent_name,
                parent_type=self.parent_type,
                is_edit=True
            ),
            style='DarkButton.TButton',
            image=self.back_icon,
            compound=tk.LEFT,
            cursor='hand2'
        )
        back_button.grid(row=2)

    def edit(self) -> None:
        type_dict = {'Armor': 1, 'Weapon': 2}

        name = self.name.get()
        type_ = type_dict[self.type_.get()]
        reduction = self.reduction.get()
        damage = self.damage.get()
        range_ = self.range_.get()
        health = self.health.get()
        area = self.area.get()
        effects = get_text_data(self.effects_entry)
        description = get_text_data(self.description_entry)

        item = Item(
            id=self.entity.id,
            name=name,
            type_=type_,
            reduction=reduction,
            damage=damage,
            range_=range_,
            health=health,
            area=area,
            effects=effects,
            description=description
        )

        update_item = item.update_item()

        self.search_result = get_entity(name, self.search_type)

        if update_item:
            self.back(
                self.go_parent,
                name=self.search_name,
                entity=self.search_result,
                type_=self.search_type,
                search_parent_name=self.search_parent_name,
                parent_name=self.parent_name,
                parent_type=self.parent_type,
                is_edit=True
            )
        else:
            popup_showinfo('Something went wrong, try again!')


# coding=utf-8
import os
import logging

# 第一步，创建一个logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)  # Log等级总开关

# 第二步，创建一个handler，用于写入日志文件
path = '../log'
folder = os.path.exists(path)
if not folder:  # 判断是否存在文件夹如果不存在则创建为文件夹
    os.makedirs(path)
    print('创建' + path)
else:
    print('文件夹存在')

log_name = path + '/log.log'
fh = logging.FileHandler(log_name, mode='w')
fh.setLevel(logging.DEBUG)  # 输出到file的log等级的开关

# 第三步，再创建一个handler，用于输出到控制台
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING)  # 输出到console的log等级的开关

# 第四步，定义handler的输出格式
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)
ch.setFormatter(formatter)

# 第五步，将logger添加到handler里面
logger.addHandler(fh)
logger.addHandler(ch)

# 日志
logger.debug('this is a logger debug message')
logger.info('this is a logger info message')
logger.warning('this is a logger warning message')
logger.error('this is a logger error message')
logger.critical('this is a logger critical message')


from datetime import date
import numpy as np
import matplotlib.pyplot as plt

import ihm.console as ihm
import utilitaires.earth as earth
from utilitaires.carte import (dessine_fondcarte, parametrage_carte,
                               mercator)
from utilitaires.fonctions import saisie_aeroport

class Avion(object):
    def __init__(self, id_avion, compagnie, config, aeroport, date_livraison, date_derniere_revision,
                 etat, latitude_deg=None, longitude_deg=None, vols=None):
        """
        Constructeur de la classe avion

        :param id_avion: identifiant avion
        :param compagnie: compagnie qui possède l'avion
        :param config: configuration de l'avion
        :param aeroport: aeroport ou il se situe actuellement
        :param date_livraison: date de livraison de l'avion
        :param date_derniere_revision: derniere date de revision de l'avion
        :param etat: donne l'etat de l'avion, si il est en vol, au sol, non utilisable
        :param latitude_deg: la latitude en degres de la position de l'avion
        :param longitude_deg: la longitude en degres de la position de l'avion
        :param vols: vols assures par l'avion
        """
        self._id                     = id_avion
        self._compagnie              = compagnie
        self._config                 = config
        self._date_livraison         = date_livraison
        self._date_derniere_revision = date_derniere_revision
        self._etat                   = etat
        self._aeroport               = aeroport
        if latitude_deg == '' or latitude_deg is None:
            latitude_deg   = aeroport.latitude_deg
        self._latitude_deg = latitude_deg
        if longitude_deg == '' or longitude_deg is None:
            longitude_deg   = aeroport.longitude_deg
        self._longitude_deg = longitude_deg
        if vols is None:
            vols   = []
        self._vols = vols

    @property
    def id(self):
        return self._id

    @property
    def compagnie(self):
        return self._compagnie

    @property
    def config(self):
        return self._config

    @property
    def date_livraison(self):
        return self._date_livraison

    @property
    def date_derniere_revision(self):
        return self._date_derniere_revision

    @property
    def etat(self):
        return self._etat

    @property
    def aeroport(self):
        return self._aeroport

    @property
    def latitude_deg(self):
        return self._latitude_deg

    @property
    def longitude_deg(self):
        return self._longitude_deg

    @property
    def vols(self):
        return self._vols

    @property
    def age(self):
        """
        Méthode permettant de determiner l'age de l'avion

        :return: l'age de l'avion
        """

        when           = self._date_livraison
        on             = date.today()
        was_earlier    = (on.month, on.day) < (when.month, when.day)
        nb_annees      = on.year - when.year - was_earlier
        dernier_anniv  = date(when.year + nb_annees, when.month, when.day)
        prochain_anniv = date(when.year + nb_annees + 1, when.month, when.day)
        jours_ecoules  = (on - dernier_anniv).days
        duree_annee    = (prochain_anniv - dernier_anniv).days
        ratio          = jours_ecoules/duree_annee
        return "{:.1f}".format(nb_annees + ratio)

    @date_derniere_revision.setter
    def date_derniere_revision(self, valeur):
        self._date_derniere_revision = valeur

    def __str__(self):
        txt = "{} - Id : {} - {} - Config {} : {}F/{}C/{}P/{}Y ({} pax) - " \
               "Age : {} ans (1er vol : {}, revision : {}) - {}"\
              .format(self._compagnie.id_code_iata, self._id,
                      self._config.type_avion, self._config.nom,
                      self._config.nb_places_premiere,
                      self._config.nb_places_business,
                      self._config.nb_places_eco_plus,
                      self._config.nb_places_eco,
                      self._config.nb_total_places,
                      self.age, self._date_livraison,
                      self._date_derniere_revision,
                      self._etat)
        if self.aeroport is not None:
            txt += " - à {}".format(self.aeroport)
        return txt

    def afficher_carte(self, show=True, annot=True):
        """
        Methode qui permet d'afficher la carte du monde avec l'avion

        :param show: booleen qui permet de choisir s'il faut montrer la carte ou non
        :param annot: booleen qui permet de choisir si on veut afficher les annotations ou non
        :return: None
        """

        # Ajout du fond de carte (si la carte ne fait pas partie d'une composition)
        if show:
            dessine_fondcarte()

        # Coordonnees de l'aeroport
        list_coords = np.zeros((1, 2))
        print(self._latitude_deg, self._longitude_deg)
        list_coords[0, 0] = float(self._latitude_deg)
        list_coords[0, 1] = float(self._longitude_deg)
        # Transfo en Mercator
        xs0, ys0 = mercator(list_coords, earth.E, 0, 0, earth.A)
        # Ajout points a la carte
        plt.plot(xs0, ys0, 'b.')

        # Parametrage de la carte
        parametrage_carte()

        # Ajout de tags avec les codes des aeroports
        if annot:
            fig = plt.gcf()
            ax = fig.add_subplot(111)
            ax.annotate('{0:s}'.format(self.id), xy=(xs0, ys0), xytext=(4, -4), \
                        fontsize=6, textcoords='offset points')

        # Affichage
        if show:
            plt.title("Carte de l'avion {0:s}".format(self._id))
            plt.show()
        return

    def afficher_vols(self):
        """
        Methode qui permet d'afficher les vols assures par l'avion

        :return: None
        """

        ihm.afficher("Il y a {} vol(s)".format(len(self._vols)))
        ihm.afficher_paginer(self._vols, "Vols", pas=10)
        return

    def deplacer_vers_aeroport(self, aeroports):
        """
        Methode qui permet de deplacer (instantanement...) l'avion vers un aeroport

        :param aeroports: liste de tous les aeroports
        :return:
        """

        old_aero = self._aeroport
        aero = saisie_aeroport("aéroport de destination", aeroports)
        self._aeroport = aero
        self._latitude_deg = aero.latitude_deg
        self._longitude_deg = aero.longitude_deg
        if old_aero is not None or old_aero != '':
            old_aero.avions.remove(self)
        aero.avions.append(self)
        return


import collections
N, K = map(int, input().split())

def solution(N, K):
    deque = collections.deque([i for i in range(1, N + 1)])
    result = []
    while deque:
        for _ in range(K-1):
            deque.append(deque.popleft())
        result.append(deque.popleft())

    print(f"<{', '.join(map(str,result))}>")

solution(N, K)

백준/Silver/1158. 요세푸스 문제/요세푸스 문제.py


from .helpers import validates

"""test_env_and_yaml_same_name
"""
from os import listdir
from os import path

VERSION = "1.0.0"

@validates("R-38474", "R-81725", "R-53433")
def test_env_and_yaml_same_name(template_dir):
    """
    Check that all environment template filenames are identical to an
    associated Heat template filenames. Log the result of the check and add the
    filename of any environment file that is badly named.
    """
    files = listdir(template_dir)
    env_files = [f for f in files if path.splitext(f)[-1] == ".env"]
    yaml_files = [f for f in files if path.splitext(f)[-1] in [".yml", ".yaml"]]
    unmatched = []
    for filename in env_files:
        basename = path.splitext(filename)[0]
        if basename + ".yaml" not in yaml_files and basename + ".yml" not in yaml_files:
            unmatched.append(filename)
    assert not unmatched, "files with no corresponding .y[a]ml %s" % unmatched


import datetime
import json

import fujian
# import lychee
from abjad import lilypondfiletools

_RENDER_LILYPOND_PDF = False

def get_show_abjad(session):
    '''
    Returns the show_abjad() function.
    '''
    def show_abjad(abj_obj):
        '''
        A Fujian-specific replacement for Abjad's show() method that connects to Lychee.
        '''
        lilypondfile = lilypondfiletools.LilyPondFile.new(abj_obj)
        session.run_workflow(dtype='lilypond', doc=format(lilypondfile))

    return show_abjad

def _process_signal(ws_handler, signal, session, tempdirs):
    '''
    Do whatever is required for a signal incoming via WebSocket.

    :param str signal: The encoded signal data (currently JSON object).
    :param session: The :class:`InteractiveSession` to use.
    :param dict tempdirs: The dictionary of temporary directories.
    '''
    global _RENDER_LILYPOND_PDF
    signal = json.loads(signal)

    if signal['type'] == 'fujian.RENDER_LILYPOND_PDF':
        try:
            _RENDER_LILYPOND_PDF = True
            session.registrar.register('lilypond', 'Fujian bridge')
            session.run_outbound(views_info=signal.get('payload', {}).get('sectID', ''))
        finally:
            _RENDER_LILYPOND_PDF = False
            session.registrar.unregister('lilypond', 'Fujian bridge')

    elif signal['type'] == 'fujian.REGISTER_OUTBOUND_FORMAT':
        session.registrar.register(
            signal['payload']['dtype'],
            signal['payload']['who'],
            signal['payload']['runNow'],
        )

    elif signal['type'] == 'fujian.UNREGISTER_OUTBOUND_FORMAT':
        session.registrar.unregister(
            signal['payload']['dtype'],
            signal['payload']['who'],
        )

    elif signal['type'] == 'fujian.SET_REPO_DIR':
        session.set_repo_dir(
            signal['payload']['repoDir'],
            signal['payload']['runOutbound'],
        )

    elif signal['type'] == 'fujian.GET_SECTION_BY_ID':
        if signal['payload'].get('revision'):
            session.run_outbound(
                views_info=signal['payload']['viewsInfo'],
                revision=signal['payload']['revision'],
            )
        else:
            session.run_outbound(
                views_info=signal['payload']['viewsInfo'],
            )

    elif signal['type'] == 'fujian.SUBMIT_LILYPOND':
        session.run_workflow(
            dtype='LilyPond',
            doc=signal['payload']['doc'],
            sect_id=signal['payload']['sectID'],
        )

    elif signal['type'] == 'fujian.SAVE_TEXT_EDITOR':
        action = {
            'is_fsa': True,
            'type': 'fujian.SAVE_COMPLETED',
            'payload': {
                'key': signal['payload']['key'],
                'sectID': signal['payload']['sectID'],
            },
        }
        try:
            session.save_text_editor(
                sect_id=signal['payload']['sectID'],
                dtype=signal['payload']['key'],
                doc=signal['payload']['value'],
            )
        except Exception:
            action['error'] = True
        finally:
            ws_handler.write_message(json.dumps(action))

    else:
        raise RuntimeError('Fujian received an unknown signal from Julius')

def process_signal(ws_handler, signal, session, tempdirs):
    '''
    Do whatever is required for a signal incoming via WebSocket.

    :param str signal: The encoded signal data (currently JSON object).
    :param session: The :class:`InteractiveSession` to use.
    :param dict tempdirs: The dictionary of temporary directories.
    '''
    try:
        _process_signal(ws_handler, signal, session, tempdirs)
    except Exception as exc:
        redux_action = {
            'is_fsa': True,
            'type': 'meta.types.WRITE_STDERR',
            'payload': 'Exception: {0}\n'.format(exc),
        }
        ws_handler.write_message(json.dumps(redux_action))

def conversion_finished(instance, dtype, document, placement, **kwargs):
    '''
    Converts the Lychee "outbound.CONVERSION_FINISHED" signal to a Redux action for Julius.
    '''
    if dtype == 'document':
        serialized_sections = json.dumps(
            document.get('sections', {}),
            separators=(',', ':'),
            sort_keys=True,
        )

        # Only dispatch this action if the sections have changed.
        # If we dispatch UPDATED_SECTIONS when the sections were not changed, then most of the
        # stores will empty themselves and we lose all the Redux state.
        if instance._sections != serialized_sections:
            first_redux_action = {
                'is_fsa': True,
                'type': 'document.types.WILL_UPDATE_SECTIONS',
                'meta': {
                    'dtype': dtype,
                    'placement': placement,
                },
                'payload': document.get('sections', {}),
            }
            instance.write_message(json.dumps(first_redux_action))

            second_redux_action = {'is_fsa': True, 'type': 'document.types.UPDATED_SECTIONS'}
            instance.write_message(json.dumps(second_redux_action))

            instance._sections = serialized_sections

    else:
        redux_action = {
            'is_fsa': True,
            'type': 'document.types.UPDATE_SECTION_DATA',
            'meta': {
                'dtype': dtype,
                'placement': placement,
            },
            'payload': document,
        }
        instance.write_message(json.dumps(redux_action))

        if dtype == 'lilypond' and _RENDER_LILYPOND_PDF:
            pdf_path = fujian.lilypond.render_lilypond_pdf(document, kwargs['tempdirs'])
            redux_action = {
                'is_fsa': True,
                'type': 'lilypond.types.UPDATE_PDF',
                'payload': pdf_path,
                'meta': placement,
            }
            instance.write_message(json.dumps(redux_action))

def conversion_errored(instance, msg=None, **kwargs):
    '''
    Converts the "outbound.ERROR" signal to a Redux action for Julius.
    '''
    if msg:
        message = 'Error during outbound conversion: {0}'.format(msg)
    else:
        message = 'Error during outbound conversion.'

    instance.write_message(json.dumps({
        'is_fsa': True,
        'type': 'meta.types.WRITE_STDERR',
        'payload': message,
    }))

def log_message(instance, level=None, logger=None, message=None, status=None, time=None, **kwargs):
    '''
    Converts the "LOG_MESSAGE" signal for use by Julius (not a Redux action).
    '''
    if status != 'success':
        formatted_time = datetime.datetime.utcfromtimestamp(float(time)).time().isoformat()
        message = '{time} {level} ({logger}): {message}\n'.format(
            level=level, logger=logger, message=message, status=status, time=formatted_time,
        )
        instance.write_message(json.dumps({
            'is_fsa': True,
            'type': 'meta.types.WRITE_STDERR',
            'payload': message,
        }))

SIGNAL_TO_HANDLER = {
    'LOG_MESSAGE': log_message,
    'outbound.CONVERSION_FINISHED': conversion_finished,
    'outbound.ERROR': conversion_errored,
}