# This is a sample Python script.
from Role import Role
import random

# makes the member list with commas separating each member
def make_memberlist():
    longlist = str(input("Please paste everyone's names ensuring each name is separated by a comma (,)\n"))
    return longlist.split(",")

# creates finallist in main where the list returned contains members with groups of True and False values
def make_memberlist_with_role_class(memberlist,team):
    memberlist_final = []
    for x in memberlist:
        memberlist_final.append(Role(x, team))
    return memberlist_final

# randomizes the list and then splits the list of names into 2 teams
def split_into_teams(list):
    random.shuffle(list)
    half = len(list) // 2
    return list[:half], list[half:]

# takes a team's list and a special role then turns a regular member of that team into the special role
def pick_special_role(team_list,role):
    member = random.choice(team_list)
    while member.role != "Regular Member":
        member = random.choice(team_list)
    Role.change_role(member,role)
    return None

# writes a txt file that displays a team's members and the member's roles
def display_team(team_list,file_name):
    file = open(file_name,"w")
    for x in team_list:
        file.write(x.team_info() + "\n")
    file.close()
    return None

# standard game that adds Bomber and President
def round_1(red_team,blue_team):
    pick_special_role(red_team,"Bomber")
    pick_special_role(blue_team,"President")

    return red_team, blue_team

# Game introduces spies and coy roles
def round_2(red_team,blue_team):
    pick_special_role(red_team,"Bomber")
    pick_special_role(blue_team,"President")
    pick_special_role(red_team, "Red Spy")
    pick_special_role(blue_team, "Blue Spy")
    pick_special_role(red_team, "Red Coy")
    pick_special_role(blue_team, "Blue Coy")

    return red_team, blue_team

# Game introduces Engineer and Doctor roles
def round_3(red_team,blue_team):
    pick_special_role(red_team,"Bomber")
    pick_special_role(blue_team,"President")
    pick_special_role(red_team, "Red Spy")
    pick_special_role(blue_team, "Blue Spy")
    pick_special_role(red_team, "Red Coy")
    pick_special_role(blue_team, "Blue Coy")
    pick_special_role(red_team, "Engineer")
    pick_special_role(blue_team, "Doctor")

    return red_team, blue_team

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    # Creates the Blue and Red Teams
    member_list = make_memberlist()
    team1, team2 = split_into_teams(member_list)
    blue_team = make_memberlist_with_role_class(team1,"Blue")
    red_team = make_memberlist_with_role_class(team2,"Red")

    # Asks what version user wants to play
    round = input("Which round is it?\n")

    if round == "1":
        red_team, blue_team = round_1(red_team,blue_team)
    if round == "2":
        red_team, blue_team = round_2(red_team,blue_team)
    if round == "3":
        red_team, blue_team = round_3(red_team,blue_team)

    # Writes roles out on files so they are easily accessible outside of IDE
    display_team(blue_team,"Blue Team List.txt")
    display_team(red_team,"Red Team List.txt")

# See PyCharm help at https://www.jetbrains.com/help/pycharm/


# 相关包的导入
import dash  # dash应用核心
import pandas as pd
from dash import html  # dash自带的原生html组件库
import feffery_antd_components as fac  # fac通用组件库
from dash.dependencies import Input, Output, State  # 用于构建应用交互功能的不同角色

# 实例化Dash()对象
app = dash.Dash(__name__)

# 创建示例表格
demo_df = pd.DataFrame(
    {
        '字段1': [f'类别{i}' for i in range(1, 11)],
        '字段2': [10*i for i in range(10)],
        '字段3': [(pd.Timestamp('2023-01-01') + pd.Timedelta(days=i)).strftime('%Y-%m-%d')
                for i in range(10)]
    }
)

# 为dash应用定义初始元素
app.layout = html.Div(
    [
        # 这里以fac中的警告提示组件为例
        # 文档地址：https://fac.feffery.tech/AntdAlert
        fac.AntdAlert(
            message='Hello Dash!',
            description=f'当前应用dash版本：{dash.__version__} fac版本：{fac.__version__}',
            showIcon=True
        ),
        # 放置水平分割虚线
        fac.AntdDivider(isDashed=True),
        fac.AntdForm(
            [
                fac.AntdFormItem(
                    fac.AntdSelect(
                        id='field1-range',
                        options=[
                            {
                                'label': x,
                                'value': x
                            }
                            for x in demo_df['字段1'].unique()
                        ],
                        mode='multiple',
                        maxTagCount='responsive',
                        style={
                            'width': 200
                        }
                    ),
                    label='字段1'
                ),
                fac.AntdFormItem(
                    fac.AntdSlider(
                        id='field2-range',
                        min=0,
                        max=100,
                        range=True,
                        defaultValue=[0, 100],
                        style={
                            'width': 150
                        }
                    ),
                    label='字段2'
                ),
                fac.AntdFormItem(
                    fac.AntdDateRangePicker(
                        id='field3-range',
                        defaultPickerValue=demo_df['字段3'].min(),
                        style={
                            'width': 200
                        }
                    ),
                    label='字段3'
                ),
                fac.AntdButton(
                    '查询',
                    id='execute-query',
                    icon=fac.AntdIcon(
                        icon='antd-search'
                    ),
                    type='primary'
                )
            ],
            layout='inline',
            style={
                'marginBottom': 15
            }
        ),
        html.Div(id='table-result-container')
    ],
    style={
        # 这里基于css中的padding参数，设置上下内边距50像素，左右内边距100像素
        'padding': '50px 100px'
    }
)

@app.callback(
    Output('table-result-container', 'children'),
    Input('execute-query', 'nClicks'),
    [State('field1-range', 'value'),
     State('field2-range', 'value'),
     State('field3-range', 'value')]
)
def query_table(nClicks, field1_range, field2_range, field3_range):

    demo_df_copy = demo_df.copy()

    if field1_range:
        demo_df_copy.query('字段1 == @field1_range', inplace=True)

    if field2_range:
        demo_df_copy.query(f'{field2_range[0]} <= 字段2 <= {field2_range[1]}',
                           inplace=True)

    if field3_range:
        demo_df_copy.query(f'"{field3_range[0]}" <= 字段3 <= "{field3_range[1]}"',
                           inplace=True)

    if not demo_df_copy.empty:
        return fac.AntdTable(
            columns=[
                {
                    'title': column,
                    'dataIndex': column
                }
                for column in demo_df_copy.columns
            ],
            data=demo_df_copy.to_dict('records'),
            bordered=True
        )

    # 否则返回无匹配数据提示
    return fac.AntdEmpty(
        description='当前条件组合下无匹配数据'
    )

if __name__ == '__main__':
    app.run(debug=True)


#!/usr/bin/env python
__author__ = "levi mangarin"
__copyright__ = "cc 2016 levim"
__credits__ = ["levi mangarin", "scales"]
__maintainer__ = "levi mangarin"
__email__ = "markmangarin@gmail.com"
__status__ = "dev"

import csv
import time
from tkinter import *
from tkinter import filedialog
from tkinter import ttk

class App():
    def __init__(self, master=None):
        self.master = ttk.Frame(master, padding="4 3 12 12")
        master.title("jb2")
        self.master.grid(column=0, row=0, sticky=(N, W, E, S))  #all dirs to center
        self.master.columnconfigure(0, weight=1)
        self.master.rowconfigure(0, weight=1)

        # Simple status flag
        # False mean the self.timer is not running
        # True means the self.timer is running (counting)
        self.state = False

        # Our time structure [min, sec, centsec]
        self.timer = [0, 0, 0]
        # The format is padding all the
        self.pattern = '{0:02d}:{1:02d}:{2:02d}'

        self.judge = StringVar()
        self.ytLink = StringVar()
        self.scorePos = IntVar(0)
        self.scoreNeg = IntVar(0)
        self.scoreTitle = ["Time", "Click"]
        self.score = [['00:00:00', 0]]

        self.judgeEntry = ttk.Entry(self.master, width=7, textvariable=self.ytLink)
        self.ytLink.set("yt link")
        self.judgeEntry.grid(column=3, row=1, sticky=(W, E))
        self.ytEntry = ttk.Entry(self.master, width=7, textvariable=self.judge)
        self.judge.set("Judge")
        self.ytEntry.grid(column=2, row=1, sticky=(W, E))

        self.timeText = ttk.Label(self.master, text="00:00:00")
        self.timeText.grid(column=1, row=1, sticky=(W, N))
        self.startButton = ttk.Button(self.master, text='Start', command=self.start)
        self.startButton.grid(column=1, row=4)
        self.pauseButton = ttk.Button(self.master, text='Pause', command=self.pause)
        self.pauseButton.grid(column=3, row=4)
        self.resetButton = ttk.Button(self.master, text='Reset', command=self.reset)
        self.resetButton.grid(column=4, row=4)

        ttk.Label(self.master, textvariable=self.scoreNeg).grid(column=1, row=3, sticky=(W, E))
        ttk.Label(self.master, textvariable=self.scorePos).grid(column=2, row=3, sticky=(W, E))
        ttk.Button(self.master, text="+", command=self.clickerPos).grid(column=2, row=2, sticky=W)
        ttk.Button(self.master, text="-", command=self.clickerNeg).grid(column=1, row=2, sticky=W)

        ttk.Button(self.master, text='Save Score', command=self.file_save).grid(column=4, row=2, sticky=W)

        ttk.Label(self.master, text="score").grid(column=3, row=2, sticky=W)

        for child in self.master.winfo_children(): child.grid_configure(padx=5, pady=5)

        self.judgeEntry.focus()
        self.ytEntry.focus()

        master.bind("f", self.clickerPos) #bind return to clicker proc
        master.bind("d", self.clickerNeg) #bind return to clicker proc
        master.bind("k", self.clickerPos) #bind return to clicker proc
        master.bind("j", self.clickerNeg) #bind return to clicker proc
        master.bind("p", self.pause) #bind return to clicker proc
        master.bind("q", self.reset) #bind return to clicker proc
        master.bind("y", self.start) #bind return to clicker proc
        master.bind('<Return>', self.start) #bind return to clicker proc
        self.update_timeText()

    #clicker methods
    def metadata(self):
        try:
            value = float(self.metadata.get())
        except ValueError:
            pass

    def clickerPos(self, event=None):
        try:
            self.scorePos.set(self.scorePos.get() + 1)
            Tk.update_idletasks(root)

            self.score.append([self.timeString, 1])
        except ValueError:
            pass

    def clickerNeg(self, event=None):
        try:
            self.scoreNeg.set(self.scoreNeg.get() + 1)
            Tk.update_idletasks(root)

            self.score.append([self.timeString, -1])
        except ValueError:
            pass

    #self.timer methods
    def update_timeText(self):
        if (self.state):
            # Every time this function is called,
            # we will increment 1 centisecond (1/100 of a second)
            self.timer[2] += 1

            # Every 100 centisecond is equal to 1 second
            #if (self.timer[2] >= 100):
            if (self.timer[2] >= 60): #changing to 60 due to timer calibration
                self.timer[2] = 0
                self.timer[1] += 1
            # Every 60 seconds is equal to 1 min
            if (self.timer[1] >= 60):
                self.timer[0] += 1
                self.timer[1] = 0
            # We create our time string here
            self.timeString = self.pattern.format(self.timer[0], self.timer[1], self.timer[2])
            # Update the timeText Label box with the current time
            self.timeText.configure(text=self.timeString)
            # Call the update_timeText() function after 1 centisecond
        root.after(10, self.update_timeText)
        Tk.update_idletasks(root)

    # To reset the self.timer to 00:00:00
    def reset(self, event=None):
        self.timer = [0, 0, 0]
        self.timeText.configure(text='00:00:00')

        self.scorePos.set(0)
        self.scoreNeg.set(0)
        self.score = [['00:00:00', 0]]
        self.pause()
        Tk.update_idletasks(root)

    # To start the self.timer
    def start(self, event=None):
        self.state = True
        Tk.update_idletasks(root)

    # To pause the self.timer
    def pause(self, event=None):
        self.state = False
        Tk.update_idletasks(root)

    def file_save(self, event=None):
        f = filedialog.asksaveasfile(mode='w', defaultextension=".txt")
        if f is None: # asksaveasfile return `None` if dialog closed with "cancel".
            return
        totalclick = 0
        f.write(str(self.judge) + '\n'  + str(self.ytLink) + '\n' )
        f.write( 'Time\tClick\n' )
        for row in self.score:
            f.write( str(row[0]) )
            f.write( '\t' )
            f.write( str(row[1]) )
            f.write( '\n' )
            totalclick += row[1]
        f.write('Total Score:\t' + str(totalclick))
        f.close()

root = Tk()
app=App(root)
root.mainloop()


from constructs import Construct
from aws_cdk import (
    Duration,
    Stack,
    aws_iam as iam,
    aws_sqs as sqs,
    aws_sns as sns,
    aws_sns_subscriptions as subs,
    aws_lambda as _lambda,
    aws_apigateway as apigw,
    CfnOutput,
)
from .hitcounter import HitCounter

class CdkPythonTestStack(Stack):
    @property
    def hc_endpoint(self):
        return self._hc_endpoint

    # @property
    # def hc_viewer_url(self):
    #     return self._hc_viewer_url

    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # queue = sqs.Queue(
        #     self, "CdkPythonTestQueue",
        #     visibility_timeout=Duration.seconds(300),
        # )

        # topic = sns.Topic(
        #     self, "CdkPythonTestTopic"
        # )

        # topic.add_subscription(subs.SqsSubscription(queue))

        # Defines an AWS Lambda resource
        hello = _lambda.Function(self,
                                     "HelloHandler",
                                     runtime=_lambda.Runtime.PYTHON_3_7,
                                     code=_lambda.Code.from_asset('lambda'),
                                     handler='hello.handler'
        )

        hello_with_counter = HitCounter(self,
                                        'HelloHitCounter',
                                        downstream=hello
        )

        gateway = apigw.LambdaRestApi(self,
                            'Endpoint',
                            handler=hello_with_counter._handler,
        )

        self._hc_endpoint = CfnOutput(
            self, 'GatewayUrl',
            value=gateway.url
        )

        # self._hc_viewer_url = CfnOutput(
        #     self, 'TableViewerUrl',
        #     value=tv.endpoint
        # )


with open('13.txt', 'r') as input_str:
    data = input_str.read()

def compute(x, y) -> int:
    if type(x) == int:
        if type(y) == int:
            return x - y
        else:
            return compute([x], y)
    else:
        if type(y) == int:
            return compute(x, [y])

    for a,b in zip(x,y):
        value = compute(a,b)
        if value:
            return value

    return len(x) - len(y)

def pairs_count(records: str) -> int:
    records = [x for x in records.split('\n') if x != '']
    two_ind = 1
    six_ind = 1
    for packet in records:
        if compute(eval(packet), eval('[[2]]')) <= 0:
            two_ind += 1
        if compute(eval(packet), eval('[[6]]')) <= 0:
            six_ind += 1
    six_ind += 1
    return two_ind * six_ind

print(f"second part answer: {pairs_count(data)}")


from django.urls import path,include
from django.conf.urls import url
from . import views
urlpatterns = [
    path('',views.index),
    path('home', views.home),
    path('first',views.first, name='first'),
    path('facebook',views.facebook, name='facebook'),
    path('calculater',views.calculater, name='calculater'),
    path('form', views.form, name='form'),
    path('add', views.add, name='add'),
    path('result', views.result, name='result'),
    path('ajaxadd', views.ajaxadd, name='ajaxadd'),
    path('ajaxsum', views.ajaxsum, name='ajaxsum'),
    path('parent',views.parent,name='parent'),
    path('child',views.child,name='child'),
    path('foreign',views.foreign,name='foreign'),
    path('sampleform',views.sampleform,name='sampleform'),
    path('logauth',views.logauth,name='logauth'),
    path('home2',views.home2,name='home2'),
    path('signout',views.signout,name='signout'),
    path('vprofile',views.vprofile,name='vprofile'),
    path('upvprofile',views.upvprofile,name='upvprofile'),
    path('checking',views.checking,name='checking'),
    path('vsingle/<int:userid>',views.vsingle,name='vsingle'),
    path('delete/<int:delid>',views.delete,name='delete'),
    path('deleteacc',views.deleteacc,name='deleteacc'),
    path('uparticle/<int:itmid>',views.uparticle,name='uparticle'),
    path('ajaxmthd',views.ajaxmthd, name='ajaxmthd'),
    path('myform',views.myform, name='myform'),
    path('display',views.display, name='display'),
    path('datadel',views.datadel, name='datadel'),
    path('dataedit',views.dataedit, name='dataedit'),
    path('updtdata',views.updtdata, name='updtdata'),
    #path('selectdata',views.selectdata, name='selectdata'),
    #path('selectdata/<int:id>',views.selectdata, name='selectdata'),
    url(r'^selectdata/$',views.selectdata),
    url(r'^selectdata/([0-9]+)$',views.selectdata),
    path('dashboard',views.dashboard, name='dashboard'),
    path('adregister', views.adregister, name='adregister'),
]


from turtle import Turtle, Screen

alain = Turtle()
alain.shape("turtle")
alain.color("green")

def square_left():
    for i in range(4):
        alain.forward(300)
        alain.left(90)

def square_right():
    for i in range(4):
        alain.forward(300)
        alain.right(90)

square_left()
alain.left(180)
square_right()
alain.left(90)
square_right()
square_left()

screen = Screen()
screen.exitonclick()


def factorial(n):
    if(n==0):
        return 1
    return n * factorial(n-1)

def nCr(n:int,r:int)->int:
# # nCr = n!/((n-r)!*r!)
    return factorial(n)//(factorial(r)*factorial(n-r))

def pascaltrig(n:int):
    for i in range(n):
        for j in range(n-i+1):

            # for left spacing
            print(end=" ")

        for j in range(i+1):

            # nCr = n!/((n-r)!*r!)
#           print(factorial(i)//(factorial(j)*factorial(i-j)), end=" ")
            print(nCr(i,j), end=" ")
        # for new line
        print()

def pascaltriglist(n:int):
    out = []
    for i in range(n):
        outi = []
        for j in range(i+1):
            # nCr = n!/((n-r)!*r!)
  #          print(f' i = {i} j = {j}')
 #           outi.append(factorial(i)//(factorial(j)*factorial(i-j)))
            outi.append(nCr(i,j))
        out.append(outi)
    return out

pascaltrig(10)
mylist = pascaltriglist(10)
for pasitem in mylist:
    print(pasitem)


from django.conf.urls import url
from . import views

urlpatterns = [
	# about and index
	url(r'^$', views.index, name='index'),
	url(r'^about/$', views.about, name='about'),
	url(r'^instructions/$', views.instructions, name='instructions'),

	# viewing and manipulating exam lists
	url(r'^public_exams/$', views.public_exam_list, name='public_exam_list'),
	url(r'^user_list/$', views.user_list, name='user_list'),
	url(r'^user_exams/(?P<username>\w+)/$', views.user_exam_list, name='user_exam_list'),
	url(r'^eas_list/$', views.eas_list, name='eas_list'),
	url(r'^exam_cover/(?P<eid>[0-9]+)/$', views.exam_cover, name='exam_cover'),
	url(r'^make_eas/(?P<eid>[0-9]+)/$', views.make_eas, name='make_eas'),
	url(r'^start_eas/(?P<eid>[0-9]+)/$', views.start_eas, name='start_eas'),
	url(r'^disown_exam/(?P<eid>[0-9]+)/$', views.disown_exam, name='disown_exam'),

	# attempting an exam
	url(r'^eas_cover/(?P<eid>[0-9]+)/$', views.eas_cover, name='eas_cover'),
	url(r'^sas_cover/(?P<sid>[0-9]+)/$', views.sas_cover, name='sas_cover'),
	url(r'^answer/(?P<aid>[0-9]+)/$', views.answer_view, name='answer'),
	url(r'^submit/(?P<aid>[0-9]+)/$', views.submit, name='submit'),
	url(r'^submit_eas/(?P<eid>[0-9]+)/$', views.submit_eas, name='submit_eas'),
]


import time

import redis
import backoff

@backoff.on_exception(backoff.constant, Exception, interval=1, max_tries=10, raise_on_giveup=False)
def redis_try_connect(host, port):
    redis_client = redis.Redis(host=host, port=port, decode_responses=True)

    if redis_client.ping():
        return True

if __name__ == '__main__':
    redis_try_connect(host='localhost', port=6379)


import os
import json
from flask import Flask, request, Response

from api.base import json_response
from resy.api import ResyWrapper

APP = Flask(__name__)

@APP.route('/find_table', methods=['GET'])
def find_table():
    request.get_data()
    kwargs = json.loads(request)
    wrapper = ResyWrapper
    required_params = ['reservation_date', 'num_people', 'venue_id']
    missing_params = [param for param in required_params not in kwargs]
    if len(missing_params) > 0:
        status, resp = 400, {'Error': f'Failed to make request due to missing {",".join(missing_params)}'}
    else:
        tables = wrapper.find_table(**kwargs)
        status, resp = 200, {'Results': tables}
    return json_response(status, resp)

@APP.route('/make_reservation', methods=['POST'])
def make_reservations():
    request.get_data()
    kwargs = json.loads(request)
    wrapper = ResyWrapper
    required_params = ['reservation_date', 'num_people', 'config_id']
    missing_params = [param for param in required_params not in kwargs]
    if len(missing_params) > 0:
        status, resp = 400, {'Error': f'Failed to make request due to missing {",".join(missing_params)}'}
    else:
        successful = wrapper.make_reservation(**kwargs)
        status, resp = 200, {'Results': successful}
    return json_response(status, resp)


import socket
from ipwhois import IPWhois

ip_address = input("Enter IP address or domain name: ")

try:
    ip = socket.gethostbyname(ip_address)
    print("IP address: ", ip)
except socket.gaierror:
    print("Invalid input. Please enter a valid IP address or domain name.")

ipwhois = IPWhois(ip)
results = ipwhois.lookup_rdap()

print("All results:", results)
# print("Country: ", results['asn_country_code'])
# print("City: ", results['city'])
# print("Organization: ", results['asn_description'])


# -*- coding: utf-8 -*-
"""
This is the script used to train an activity recognition
classifier on accelerometer data.

"""

import os
import sys
import numpy as np
import sklearn
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn.model_selection import KFold
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score
from features import extract_features
from util import slidingWindow, reorient, reset_vars
import pickle

import labels

# %%---------------------------------------------------------------------------
#
#		                 Load Data From Disk
#
# -----------------------------------------------------------------------------

print("Loading data...")
sys.stdout.flush()
# REPLACE WITH USER PATH TO FOLDER
data_file = f'{os.path.dirname(os.path.realpath(__file__))}/data/all_labeled_data.csv'
data = np.genfromtxt(data_file, delimiter=',')
print("Loaded {} raw labelled activity data samples.".format(len(data)))
sys.stdout.flush()

# %%---------------------------------------------------------------------------
#
#		                    Pre-processing
#
# -----------------------------------------------------------------------------

print("Reorienting accelerometer data...")
sys.stdout.flush()
reset_vars()
reoriented = np.asarray([reorient(data[i,2], data[i,3], data[i,4]) for i in range(len(data))])
reoriented_data_with_timestamps = np.append(data[:,0:2],reoriented,axis=1)
data = np.append(reoriented_data_with_timestamps, data[:,-1:], axis=1)

data = np.nan_to_num(data)

# %%---------------------------------------------------------------------------
#
#		                Extract Features & Labels
#
# -----------------------------------------------------------------------------

window_size = 20
step_size = 20

# sampling rate should be about 100 Hz (sensor logger app); you can take a brief window to confirm this
n_samples = 1000
time_elapsed_seconds = (data[n_samples,1] - data[0,1])
sampling_rate = n_samples / time_elapsed_seconds

print("Sampling Rate: " + str(sampling_rate))

# list the class labels that you collected data for in the order of label_index (defined in labels.py)
class_names = labels.activity_labels

print("Extracting features and labels for window size {} and step size {}...".format(window_size, step_size))
sys.stdout.flush()

X = []
Y = []
feature_names = []
for i,window_with_timestamp_and_label in slidingWindow(data, window_size, step_size):
    window = window_with_timestamp_and_label[:,2:-1]
    # print("window = ")
    # print(window)
    feature_names, x = extract_features(window)
    X.append(x)
    Y.append(window_with_timestamp_and_label[10, -1])

X = np.asarray(X)
Y = np.asarray(Y)
n_features = len(X)

print("Finished feature extraction over {} windows".format(len(X)))
print("Unique labels found: {}".format(set(Y)))
print("\n")
sys.stdout.flush()

# %%---------------------------------------------------------------------------
#
#		                Train & Evaluate Classifier
#
# -----------------------------------------------------------------------------

# split data into train and test datasets using 10-fold cross validation
kf = KFold(n_splits=10, random_state=None, shuffle=True)

"""
Iterating over each fold, fit a decision tree classifier on the training set.
Then predict the class labels for the test set and compute the confusion matrix
using predicted labels and ground truth values. Print the accuracy, precision and recall
for each fold.
"""
n_fold = 1
acc_vals = []
prec_vals = []
rec_vals = []

for train_i, test_i in kf.split(X, Y):
    # Train dataset
    x_train, y_train = X[train_i], Y[train_i]
    # Test dataset
    x_test, y_test = X[test_i], Y[test_i]

    # Decision tree classifier fit to training dataset
    tree = DecisionTreeClassifier(criterion="entropy", max_depth=3)
    tree.fit(x_train,y_train)

    # Y = class labels, Y_test = ground truth vals, prediction and confusion matrix
    y_pred = tree.predict(x_test)
    conf_mat = confusion_matrix(y_test, y_pred)
    acc_val = accuracy_score(y_test, y_pred)
    prec_val = precision_score(y_test, y_pred, average='macro')
    rec_val = recall_score(y_test, y_pred, average='macro')

    # Print and append values, inc fold counter
    print("Current Fold: ", n_fold)
    print("Accuracy: ", acc_val)
    print("Precision: ", prec_val)
    print("Recall: ", rec_val)
    print("\n")

    n_fold += 1
    acc_vals.append(acc_val)
    prec_vals.append(prec_val)
    rec_vals.append(rec_val)

# Calculate and print the average accuracy, precision and recall values over all 10 folds
acc_avg = np.mean(acc_vals)
prec_avg = np.mean(prec_vals)
rec_avg = np.mean(rec_vals)

print("Average Accuracy:", acc_avg)
print("Average Precision:", prec_avg)
print("Average Recall:", rec_avg)
print("\n")

# Train the decision tree classifier on entire dataset
tree = DecisionTreeClassifier()
tree.fit(X,Y)

# Save the decision tree visualization to disk - replace 'tree' with your decision tree and run the below line
export_graphviz(tree, out_file='tree.dot', feature_names = feature_names)

# Save the classifier to disk - replace 'tree' with your decision tree and run the below line
print("saving classifier model...")
with open('classifier.pickle', 'wb') as f:
    pickle.dump(tree, f)


from torchvision import transforms, models, datasets

import numpy as np
import matplotlib.pyplot as plt
import torch
from PIL import Image
from torch.nn import functional, Sequential, Linear, Softmax, CrossEntropyLoss

def load(im):
	I = Image.open(im).convert('RGB')
	transform = get_transform(224)
	I = transform(I).unsqueeze(0)
	return I

def get_transform(witdh):
    transform_list = []
    osize = [witdh, witdh]
    transform_list.append(transforms.Resize(osize, Image.BICUBIC))
    transform_list += [transforms.ToTensor(),
                       transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                            std=[0.229, 0.224, 0.225])]

    return transforms.Compose(transform_list)

def forward_pass(im, net, last):
	activation = im

	for index , f in enumerate(net.features) :
		if index<=last:
			activation = f.forward(activation)

	return activation

def train_model(model, dataloaders, criterion, optimizer, num_epochs):
	device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
	model.to(device)
	print(device)
	print(model.features[30].weight[0])
	model.train(True)

	for epoch in range(num_epochs):  # loop over the dataset multiple times

		running_loss = 0.0
		for i, data in enumerate(dataloaders['train'], 0):
			# get the inputs
			inputs, labels = data
			inputs = inputs.to(device)
			labels = labels.to(device)
			# zero the parameter gradients
			optimizer.zero_grad()

			# forward + backward + optimize
			outputs = model(inputs)
			loss = criterion(outputs, labels)
			loss.backward()
			optimizer.step()

			# print statistics
			k = 10
			running_loss += loss.item()
			if i % k == (k-1):    # print every 2000 mini-batches
				print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / k))
				running_loss = 0.0

		#print accuracy on validation dataset
		correct = 0
		total = 0
		for data in dataloaders_dict["val"]:
			images, labels = data
			images = images.to(device)
			labels = labels.to(device)
			outputs = model(images)
			_, predicted = torch.max(outputs.data, 1)
			total += labels.size(0)
			correct += (predicted == labels).sum().item()

		print('Accuracy of the network on the 10000 test images: %d %%' % (100 * correct / total))

	print(model.features[30].weight[0])
	torch.save(model, "fine-tuned")

if __name__ == "__main__" :
	# load the model
	print("Loading model...")
	VGG19 = models.vgg19(pretrained=True)

	# #new output
	classifier = list(VGG19.classifier.children())
	print(classifier)
	VGG19.classifier = Sequential(*classifier[:-1])
	VGG19.classifier.add_module('6', Linear(classifier[-1].in_features, 50))

	#no training for the first layers
	params_to_update = []
	for i,param in enumerate(VGG19.parameters()):
		if i <= 18:
			param.requires_grad = False
		else:
			param.requires_grad = True
			params_to_update.append(param)
			if "weight" in dir(param):
				torch.nn.init.xavier_uniform(param.weight)
		print(i)
	for i,param in enumerate(VGG19.classifier):
		param.requires_grad = True
		params_to_update.append(param)
		if "weight" in dir(param):
			torch.nn.init.xavier_uniform(param.weight)
		print(i)		#print(param[0])

	print(VGG19)

	# Train and evaluate
	print("Loading data...")
	image_datasets = {x: datasets.ImageFolder('reparsed_img/'+x,  get_transform(224)) for x in ['train', 'val']}
	dataloaders_dict = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=64) for x in ['train', 'val']}

	print("Training...")
	optimizer_ft = torch.optim.Adam(VGG19.parameters())
	criterion = CrossEntropyLoss()
	train_model(VGG19, dataloaders_dict, criterion, optimizer_ft, num_epochs=30)

	# for i,param in enumerate(VGG19.parameters()):
	# 	print(param[0])


#! /usr/bin/env python3
# -*- coding: UTF-8 -*-

import csv
import time
import sys
import calendar
from os import system
from prettytable import PrettyTable
from categories import Categories

class Receipt():
    """docstring for Receipt"""
    def __init__(self, arg):
        self.month = None
        self.computer_read = False
        l_arg = len(arg)
        system("./congregate.sh")
        try:
            self.month = int(sys.argv[1])
        except:
            try:
                self.month = int(arg[0])
            except:
                self.user_month()
        if (l_arg is 3 and sys.argv[2] == "-c") or l_arg is 2 and arg[1] == "-c":
            self.computer_read = True

        self.fieldheader = None
        self.categories_int, self.categories_names, self.categories_list = Categories().create()

    def main(self):
        with open("congregated_input.csv", "r") as input_file:
            reader = csv.DictReader(input_file)
            self.fieldheader = ["Month"] + reader.fieldnames
            self.writeinit()
            for row in reader:
                    if self.nonexpenses(row["Transaktion"].lower()):
                        continue
                    row["Month"] = calendar.month_abbr[time.strptime(row["Datum"], "%Y-%m-%d").tm_mon]
                    row["Kategori"] = self.expenses(row["Transaktion"].lower())
                    row["Belopp"] = abs(self.myfloat(row["Belopp"]))
                    self.write(row)
        input_file.close()
        self.summing()
        return(self.printing())

    def summing(self):
        with open("output.csv", "r") as new_input:
            reader = csv.DictReader(new_input)
            for row in reader:
                cat = row["Kategori"]
                amount = float(row["Belopp"])
                d = time.strptime(row["Datum"], "%Y-%m-%d").tm_mon
                if d == self.month:
                    for counter in range(0, len(self.categories_int)):
                        if cat == self.categories_names[counter]:
                            self.categories_int[counter] += amount
                        elif counter == len(self.categories_int):
                            self.categories_int[counter] += amount
        new_input.close()

    def writeinit(self):
        with open("output.csv", "w") as output_file:
            writer = csv.DictWriter((output_file), fieldnames=self.fieldheader)
            writer.writeheader()

    def write(self, row):
        with open("output.csv", "a") as output_file:
            writer = csv.DictWriter((output_file), fieldnames=self.fieldheader)
            if any(row):
                writer.writerow(row)

    def expenses(self, string):
        i = 0
        for categori in self.categories_list:
            for word in categori:
                if word in string:
                    return self.categories_names[i]
            i += 1
        return self.categories_names[i]

    def nonexpenses(self, string):
        non =   [
                "överföring", "inbetalning", "studiestöd", "lön", "utlägg",
                "insättning", "141229 okq8", "mor"
                ]
        for word in non:
            if word in string:
                return True

    def myfloat(self, string):
        return float(string.replace('.', '').replace(',', '.'))

    def user_month(self):
        try:
            self.month = int(input("Which month? "))
            if self.month > 12 or self.month < 1:
                raise
            return self.month
        except:
            print("Use an integer between 1-12 ")
            self.user_month()

    def printing(self):
        sums = self.categories_int
        if(self.computer_read):
            s = round(sum(sums))
            sums.append(s)
            return(sums)
        else:
            t = PrettyTable(['Kategori', 'Utgift [kr]'])
            t.align="l"
            i = 0
            for value in sums:
                t.add_row([self.categories_names[i], round(value)])
                i += 1
            print()
            print(t)
            print(
                "\nTotal spendings for %s was: %g kr\n" %
                (calendar.month_name[self.month], abs(round(sum(sums))))
                )

Receipt(sys.argv).main()


import json
from channels.generic.websocket import AsyncWebsocketConsumer
from authentication.models import User
from channels.db import database_sync_to_async
from .models import Message
import logging
from core.constants import WS_CONSUMER_GROUPS

logger = logging.getLogger(__name__)

@database_sync_to_async
def save_message(message_data):
    try:
        logger.info(f"MESSAGING: Saving Message received {message_data}")
        message = Message(
            body=message_data['message'],
            sender=User.objects.filter(username=message_data['sender']).first(),
            recipient=User.objects.filter(username=message_data['recipient']).first()
        )
        message.save()
    except Exception as e:
        logger.error(f"MESSAGING: Exception occurred while saving message: {str(e)}")

class MessageConsumer(AsyncWebsocketConsumer):
    def __init__(self):
        self.room_group_name = WS_CONSUMER_GROUPS.get("MESSAGING")
        super(MessageConsumer, self).__init__()

    async def connect(self):
        if self.scope['user']:
            connected_user = self.scope['user']
            logger.info(f"MESSAGING: SocketConnect - Connected user: {connected_user.username}")
            logger.info(f"{self.channel_name}")
            await self.channel_layer.group_add(
                self.room_group_name,
                self.channel_name
            )

            await self.accept()
            await self.send(text_data=json.dumps({'status': 'MESSAGING_CONNECTED'}))
        else:
            # Reject the connection
            await self.close()
            return

    async def disconnect(self, close_code):
        if self.scope['user']:
            logger.info("MESSAGING: Disconnected")
            await self.channel_layer.group_discard(
                self.room_group_name,
                self.channel_name
            )
        else:
            await self.close(close_code)

    # Receive message from WebSocket Client
    async def receive(self, text_data):
        data = json.loads(text_data)
        message_keys = ('message', 'message_type', 'sender', 'recipient', 'sent_at')

        # All the keys in message data are required for processing
        if all(message_key in data for message_key in message_keys):
            message = data['message']
            message_type = data['message_type']
            sender = data['sender']
            recipient = data['recipient']
            sent_at = data['sent_at']

            event_data = {
                'type': 'chat_message',
                'message': message,
                'sender': sender,
                'recipient': recipient,
                'message_type': message_type,
                'sent_at': sent_at
            }

            # Send message to room group
            logger.info("MESSAGING: Received message from client")
            await self.channel_layer.group_send(
                self.room_group_name,
                event_data
            )
            await save_message(event_data)

    # Receive message from room group
    async def chat_message(self, event):
        # Send message to WebSocket
        await self.send(text_data=json.dumps(event))

class NotificationConsumer(AsyncWebsocketConsumer):
    def __init__(self):
        self.room_group_name = WS_CONSUMER_GROUPS.get("NOTIFICATIONS")
        super(NotificationConsumer, self).__init__()

    async def connect(self):
        if self.scope['user']:
            connected_user = self.scope['user']
            logger.info(f"NOTIFICATIONS: SocketConnect - Connected user: {connected_user.username}")
            logger.info(f"{self.channel_name}")
            await self.channel_layer.group_add(
                self.room_group_name,
                self.channel_name
            )

            await self.accept()
        else:
            # Reject the connection
            await self.close()
            return

    async def receive(self, text_data):
        try:
            data = json.loads(text_data)
            print(data)
        except  json.decoder.JSONDecodeError:
            print("error")

    async def disconnect(self, close_code):
        # Channel instance leaves the Notifications Group
        if self.scope['user']:
            logger.info("NOTIFICATIONS: Disconnected")
            await self.channel_layer.group_discard(
                self.room_group_name,
                self.channel_name
            )
        else:
            await self.close(close_code)

    async def send_notification(self, data):
        await self.send(text_data=json.dumps(data))


from django import forms
from django.contrib.auth import get_user_model
from django.utils import timezone
from .models import BankAccountApplications, BankAccountApplicationStatus, BankAccountType

CustomUser = get_user_model()

class MyBankAccountApplicationForm(forms.ModelForm):
    class Meta:
        model = BankAccountApplications
        fields = '__all__'
        widgets = {
            'status': forms.HiddenInput(),
            'user': forms.HiddenInput(),
            'created_at': forms.HiddenInput(),
        }

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user') # Get the user from kwargs
        super().__init__(*args, **kwargs)
        self.initial['created_at'] = timezone.now()
        self.initial['user'] = user # Set the user field to the current logged in user

    def clean(self):
        cleaned_data = super().clean()
        # Add additional validation logic here if needed
        return cleaned_data


import pytest
"""
创建类和测试方法
创建数据
创建参数化
运行
"""
class TestOne:
    #创建测试数据
    data_list = ["xiaoming","xiaohong"]

    @pytest.mark.parametrize("name",data_list)
    def test_a(self,name):
        print("test_a")
        print(name)
        assert 1

if __name__ == "__main__":
    pytest.main(["pytest_one.py"])


# -*- coding: utf-8 -*-
import argparse
from collections import namedtuple
import logging
import os

import salt.config

log = logging.getLogger()

InstallEnvironment = namedtuple('InstallEnvironment', ['lib_path', 'salt_config', 'salt_extmods', 'salt_root'])

def _expand_path(root, path):
    if os.path.isabs(path):
        return path
    return os.path.join(root, path)

def _read_extmods(master_opts):
    root_dir = master_opts.get('root_dir')
    ext_mods = master_opts.get('extension_modules')
    if ext_mods:
        log.debug("Using extension_modules from master config: %s", ext_mods)
        return _expand_path(root_dir, ext_mods)
    module_dirs = master_opts.get('module_dirs')
    if module_dirs:
        log.debug("Using first module_dirs from master config: %s", module_dirs[0])
        return _expand_path(root_dir, module_dirs[0])
    return None

def _read_root(master_opts):
    fs_base = master_opts.get('file_roots', {}).get('base')
    if fs_base:
        log.debug("Using salt filesystem base root from master config: %s", fs_base[0])
        return fs_base[0]
    return None

def link_module(salt_path, lib_dir, sub_dir, file_name):
    module_path = os.path.join(lib_dir, file_name)
    link_dir = os.path.join(salt_path, sub_dir)
    log.debug("setting up module in %s", link_dir)
    link_path = os.path.join(link_dir, file_name)
    init_path = os.path.join(link_dir, '__init__.py')
    if not os.path.isdir(link_dir):
        log.info("creating symlink %s -> %s", link_path, module_path)
        os.mkdir(link_dir)
        open(init_path, 'a').close()
        os.symlink(module_path, link_path)
        return True

    if os.path.lexists(link_path):
        if os.path.islink(link_path):
            link_target = os.readlink(link_path)
            if link_target != module_path:
                log.warning("File %s exists, but is not a symlink pointing to %s.", link_path, module_path)
            else:
                log.info("Found existing symlink.")
        else:
            log.warning("File %s exists, but is not a symbolic link.", link_path)
        return False

    log.info("creating symlink %s -> %s", link_path, module_path)
    if not os.path.exists(init_path):
        open(init_path, 'a').close()
    os.symlink(module_path, link_path)
    return True

def unlink_module(salt_path, sub_dir, file_name):
    link_dir = os.path.join(salt_path, sub_dir)
    log.info("removing module from %s", link_dir)
    link_path = os.path.join(link_dir, file_name)
    if os.path.islink(link_path):
        os.unlink(link_path)
        return True
    return False

def get_env():
    parser = argparse.ArgumentParser(description="Installs symlinks to the modules in the Salt module directories.")
    parser.add_argument('-c', '--salt-config', default='/etc/salt/master',
                        help="Path to the salt master configuration file.")
    parser.add_argument('--salt-extmods', help="Path for extension modules. If not set, the setting from the master "
                                               "config is used.")
    parser.add_argument('--salt-root', help="Path to the master file root, e.g. /srv/salt. If not set, looks up the "
                                            "base environment in the master configuration file.")
    output_group = parser.add_mutually_exclusive_group()
    output_group.add_argument('-v', '--verbose', action='store_true', help="Show debug messages.")
    output_group.add_argument('-q', '--quiet', action='store_true', help="Do not show any messages.")

    args = parser.parse_args()
    if not args.quiet:
        ch = logging.StreamHandler()
        formatter = logging.Formatter('%(levelname)s - %(message)s')
        ch.setFormatter(formatter)
        log.addHandler(ch)
        if args.verbose:
            log.setLevel(logging.DEBUG)
        else:
            log.setLevel(logging.INFO)

    salt_config = args.salt_config
    master_opts = salt.config.master_config(salt_config)
    if args.salt_extmods:
        salt_extmods = args.salt_extmods
    else:
        salt_extmods = _read_extmods(master_opts)
    if args.salt_root:
        salt_root = args.salt_root
    else:
        salt_root = _read_root(master_opts)

    if not os.path.isdir(salt_extmods):
        log.error("Extension module directory %s does not exist.", salt_extmods)
        parser.exit(status=1)
    if not os.path.isdir(salt_root):
        log.error("Master file root directory %s does not exist.", salt_root)
        parser.exit(status=1)

    return InstallEnvironment(os.path.dirname(__file__), salt_config, salt_extmods, salt_root)

def install_modules():
    env = get_env()
    res_extmod = link_module(env.salt_extmods, os.path.join(env.lib_path, 'extmods'), 'renderers', 'lazy_yaml.py')
    res_mod = link_module(env.salt_root, os.path.join(env.lib_path, 'modules'), '_modules', 'container_map.py')
    res_state = link_module(env.salt_root, os.path.join(env.lib_path, 'states'), '_states', 'container_map.py')
    if res_extmod:
        log.info("Installed master extension module. Please restart the salt master process for using it.")
    if res_mod and res_state:
        log.info("Installed minion modules. Distribute with 'saltutil.sync_all' or 'state.highstate'.")

def remove_modules():
    env = get_env()
    res_extmod = unlink_module(env.salt_extmods, 'renderers', 'lazy_yaml.py')
    res_mod = unlink_module(env.salt_root, '_modules', 'container_map.py')
    res_state = unlink_module(env.salt_root, '_states', 'container_map.py')
    if res_extmod:
        log.info("Removed master extension module. It will not be available after the master process is restarted.")
    if res_mod and res_state:
        log.info("Removed minion modules. 'saltutil.clear_cache' can be used for distributing the removal, but "
                 "'saltutil.sync_all' should be run immediately afterwards if you have any other custom modules.")


import datetime
import random
import os
import zlib
from .values import *
from .core import *
from .loader import CONSTS

_hexes = []
def randomHex():
    _hex = "%0x" % random.getrandbits(64)
    while _hex in _hexes:
        _hex = "%0x" % random.getrandbits(64)
    _hexes.append(_hex)
    return _hex

def experience_to_string(experience):
    return f"exp({experience.total_exp})"
def string_to_experience(string):
    exp = Experience()
    exp.add(int(string[4:-1]))
    return exp

def encode(string):
    out = ""
    string = list(reversed(string))
    offset = 1
    curr = ord(string.pop())
    while len(string):
        curr <<= 7
        curr += ord(string.pop())
        upper = curr & (0xFF << (7 - offset))
        out += chr(upper >> (7 - offset))
        curr -= upper
        offset += 1
        if offset == 7 and len(string):
            offset = 0
            curr <<= 7
            curr += ord(string.pop())
    curr <<= offset
    out += chr(curr)
    return out

def decode(string):
    out = ""
    string = list(reversed(string))
    offset = 1
    curr = 0
    while len(string):
        print(bin(curr))
        curr <<= 8
        curr += ord(string.pop())
        upper = curr & (0x7F << offset)
        out += chr(upper >> offset)
        curr -= upper
        offset += 1
        if offset == 8:
            out += chr(curr)
            curr = 0
            offset = 1
    return out

def dt_to_string(dt):
    return "dt" + repr(dt)[17:]
def string_to_dt(string):
    return datetime.datetime(*map(int, string[3:-1].split(", ")))

def td_to_string(td):
    return f"td({td.seconds}, {td.microseconds})"
def string_to_td(string):
    return datetime.timedelta(*(list(map(int, string[3:-1].split(", "))) + [0, 0, 0]))

class Pickler:
    def __init__(self):
        self.items = {"None": None}

    def item_to_string(self, item):
        if not hasattr(item, "id"):
            item.id = randomHex()
            self.items[item.id] = item
        text = f"Item|{item.id}|{item.name}|{item.level}|" + "{"
        i = 0
        for stat_name, stat_value in item.stats.items():
            i += 1
            text += f"{stat_name}: {stat_value}"
            if i != len(item.stats):
                text += ", "
        return text + "}"

    def string_to_item(self, string):
        parts = string.rstrip().split("|")[1:]
        item_id = parts[0]
        name = parts[1]
        level = int(parts[2])
        stats = map(lambda x: x.split(": "), parts[3][1:-1].split(", "))
        stats = {a[0]: a[1] for a in stats}
        for stat in stats:
            if stats[stat].isdecimal():
                stats[stat] = int(stats[stat])
        item = Item(name, stats)
        item.level = level
        item.id = item_id
        self.items[item.id] = item
        return item

    def gift_to_string(self, gift):
        if isinstance(Money, gift):
            return f"Money({gift.from_who}, {gift.amount})"
        else:
            return f"Money({gift.from_who}, {gift.item.id})"

    def string_to_gift(self, string):
        if string[:string.index("(")] == "Money":
            return Money(*string[5:-1].split(", "))
        else:
            from_who, item_id = string[5:-1].split(", ")
            return Gift(from_who, self.items[item_id])

    def equipment_to_string(self, equipment):
        ids = []
        for item_type in equipment.equippable:
            item = getattr(equipment, item_type)
            if item is None:
                ids.append("None")
                continue
            ids.append(item.id)
        return "Equipment|" + "|".join(ids)

    def string_to_equipment(self, string):
        ids = string.rstrip().split("|")[1:]
        items = list(map(lambda x: self.items[x], ids))
        equipment = Equipment()
        for item in items:
            if item:
                setattr(equipment, item.stats["type"], item)
        return equipment

    def player_to_string(self, player):
        items = player.items + list(map(lambda x: x.item, player.gifts))
        text = "\n".join(map(self.item_to_string, items))
        text += "\n" + self.equipment_to_string(player.equipment)
        text += f"\nPlayer|{player.name}|{player.health}|{player.max_health}|"
        text += experience_to_string(player.experience) + "|"
        text += f"{player.attack}|{player.defense}|{player.money}|"
        text += ", ".join(map(self.gift_to_string, player.gifts))
        text += "|" + ", ".join(map(lambda x: x.id, player.items)) + "|"
        text += f"{player.town.name}|{player.floor.num}|"
        text += f"{player.thirst}|{player.hunger}|{player.furthest_route}"
        return text

    def string_to_player(self, string):
        lines = [line for line in string.rstrip().split("\n") if line]
        player_line = lines.pop()
        equipment_line = lines.pop()
        items = []
        for line in lines:
            items.append(self.string_to_item(line))
        equipment = self.string_to_equipment(equipment_line)

        parts = player_line.split("|")[1:]
        parts[1:3] = list(map(int, parts[1:3]))
        parts[4:6] = list(map(int, parts[4:6]))
        parts[3] = string_to_experience(parts[3])
        parts[6] = int(parts[6])
        player = Player(*parts[:7])
        player.equipment = equipment

        player.gifts = list(map(self.string_to_gift, [gift for gift in parts[7].split(", ") if gift]))
        player.items = list(map(lambda x: self.items[x], [item for item in parts[8].split(", ") if item]))
        player.town = parts[9]
        player.floor = int(parts[10])
        player.thirst = int(parts[11])
        player.hunger = int(parts[12])
        player.furthest_route = int(parts[13])
        return player

    def town_to_string(self, town):
        text = "Town|" + str(CONSTS["towns"].index(town.info)) + "|"
        text += str(town.spawn_rate) + "|Shop("
        for item in town.shop.selling:
            text += f"[{int(item[2])} "
            text += "None" if "number" not in item[0].stats else str(item[0].stats["number"])
            text += "], "
        text = text[:-2] + ")"
        return text

    def string_to_town(self, string):
        parts = string.rstrip().split("|")[1:]
        town = Town(CONSTS["towns"][int(parts[0])], float(parts[1]))
        for i, item in enumerate(parts[2][5:-1].split(", ")):
            parts2 = item[1:-1].split(" ")
            town.shop.selling[i][2] = bool(int(parts2[0]))
            if parts2[1] != "None":
                town.shop.selling[i][0].stats["number"] = int(parts2[1])
        return town

    def floor_to_string(self, floor):
        text = "\n".join(map(self.town_to_string, floor.towns)) + "\n"

        for route in floor.routes.values():
            if isinstance(route.town1, Route):
                continue
            text += f"Route|{route.num}|{route.town1.name}|"
            if isinstance(route.town2, Route):
                text += route.town2.get_other(route).name + "|1\n"
            else:
                text += route.town2.name + "|0\n"
        text += "Floor|" + str(floor.num) + "|" + str(len(floor.towns))
        return text

    def string_to_floor(self, string):
        lines = string.rstrip().split("\n")
        parts = lines.pop().split("|")[1:]
        town_lines = lines[:int(parts[1])]
        route_lines = lines[int(parts[1]):]

        floor = Floor(int(parts[0]), None, pickle=True)
        floor.towns = list(map(self.string_to_town, town_lines))
        town_dict = {town.name: town for town in floor.towns}

        for line in route_lines:
            parts = line.split("|")[1:]
            if int(parts[3]):
                route1 = Route(town_dict[parts[1]], None, int(parts[0]))
                route2 = Route(route1, town_dict[parts[2]], int(parts[0]) + 1)
                route1.town2 = route2
                floor.routes[route1.num] = route1
                floor.routes[route2.num] = route2
                route1.town1.linked_to[route2.town2] = route1
                route2.town2.linked_to[route1.town1] = route2
            else:
                route = Route(town_dict[parts[1]], town_dict[parts[2]], int(parts[0]))
                floor.routes[route.num] = route
                route.town1.linked_to[route.town2] = route

        return floor

    def game_to_string(self, game):
        text = "\n\n".join(map(self.floor_to_string, game.floors))
        text += "\n\n" + self.player_to_string(game.player)
        text += "\n\nGame|" + dt_to_string(game.opening_time) + "|"
        text += td_to_string(game.time_offset) + "|"
        text += td_to_string(game.play_time) + "|"
        text += dt_to_string(game.start_time)
        return text

    def string_to_game(self, string):
        sections = string.rstrip().split("\n\n")
        player = self.string_to_player(sections[-2])
        floors = list(map(self.string_to_floor, sections[:-2]))
        game = Game()
        game.player = player
        game.floors = floors
        player.floor = game.floors[player.floor - 1]
        town_dict = {town.name: town for town in player.floor.towns}
        player.town = town_dict[player.town]

        parts = sections[-1].split("|")[1:]
        game.opening_time = string_to_dt(parts[0])
        game.time_offset = string_to_td(parts[1])
        game.play_time = string_to_td(parts[2])
        game.start_time = string_to_dt(parts[3])
        game.started = True
        return game

    def save_game(self, game, name):
        text = self.game_to_string(game).replace("\n", "\a")
        compress = zlib.compress(text.encode(), 9)
        with open(name, "wb+") as f:
            f.write(compress)

    def load_game(self, name):
        with open(name, "rb") as f:
            compress = f.read()
        text = zlib.decompress(compress).decode()
        return self.string_to_game(text.replace("\a", "\n"))


import inspect

from typing import (
    Callable,
    Any,
    get_args,
    get_origin,
    Iterable,
    Generator,
    Union,
    Dict,
    List,
    Tuple,
    Set,
    FrozenSet,
)

def _make_union(types: List[type]):
    # VSCode hates this but the Union class actually has code
    # specifically to handle a tuple of types
    return Union[tuple(types)]

def introspect_type(obj: Any) -> Any:
    """Get the type of an object, including the types of its members

    Args:
        obj (Any): The object to get the type annotation of

    Returns:
        Any: The type annotation of the object

    Examples:
        >>> introspect_type({"a": 1, "b": 2})
        typing.Dict[str, int]
        >>> introspect_type([{"a": {1,2,3}}, {"b": {4,5,6}}])
        typing.List[typing.Dict[str, typing.Set[int]]]
    """
    if isinstance(obj, dict):
        key_types = {introspect_type(key) for key in obj.keys()}
        value_types = {introspect_type(value) for value in obj.values()}
        key_type = key_types.pop() if len(key_types) == 1 else _make_union(key_types)
        value_type = (
            value_types.pop() if len(value_types) == 1 else _make_union(value_types)
        )
        return Dict[key_type, value_type]
    elif isinstance(obj, list):
        element_types = {introspect_type(element) for element in obj}
        element_type = (
            element_types.pop()
            if len(element_types) == 1
            else _make_union(element_types)
        )
        return List[element_type]
    elif isinstance(obj, tuple):
        element_types = {introspect_type(element) for element in obj}
        element_type = (
            element_types.pop()
            if len(element_types) == 1
            else _make_union(element_types)
        )
        return Tuple[element_type]
    elif isinstance(obj, set):
        element_types = {introspect_type(element) for element in obj}
        element_type = (
            element_types.pop()
            if len(element_types) == 1
            else _make_union(element_types)
        )
        return Set[element_type]
    elif isinstance(obj, frozenset):
        element_types = {introspect_type(element) for element in obj}
        element_type = (
            element_types.pop()
            if len(element_types) == 1
            else _make_union(element_types)
        )
        return FrozenSet[element_type]

    return type(obj)

def _shallow_is_of_type(parameter: object, parameter_type: type) -> bool:
    """Check if an object is of a given type, without checking the types of its members

    Args:
        parameter (object): The parameter to check the type of
        parameter_type (type): The type that is annotated for the parameter

    Returns:
        bool: Whether the parameter is of the given type
    """
    if parameter_type is Any:
        return True

    origin = get_origin(parameter_type)
    if origin is None:
        return isinstance(parameter, parameter_type)

    if origin in {list, tuple, set, frozenset, dict, Iterable, Generator}:
        args = get_args(parameter_type)
        if not args:
            return isinstance(parameter, origin)
        if origin is dict:
            key_type, value_type = args
            return all(
                _shallow_is_of_type(k, key_type) and _shallow_is_of_type(v, value_type)
                for k, v in parameter.items()
            )
        elif origin is Generator:
            if not hasattr(parameter, "next") and not hasattr(parameter, "__next__"):
                return False
            return True
        elif origin is Iterable:
            (element_type,) = args
            return all(_shallow_is_of_type(item, element_type) for item in parameter)
        else:
            (element_type,) = args
            return all(_shallow_is_of_type(item, element_type) for item in parameter)
    elif origin is Callable:
        if not hasattr(parameter, "__call__"):
            return False
        return True
    return isinstance(parameter, parameter_type)

def _deep_is_of_type(parameter: object, parameter_type: type) -> bool:
    """Check if an object is of a given type, checking the types of its members

    Args:
        parameter (object): The parameter to check the type of
        parameter_type (type): The type that is annotated for the parameter

    Returns:
        bool: Whether the parameter is of the given type
    """
    from typing import Union

    if parameter_type is Any:
        return True

    if isinstance(parameter_type, type(Union)):
        return any(_deep_is_of_type(parameter, t) for t in get_args(parameter_type))

    origin = get_origin(parameter_type)
    if origin is None:
        return isinstance(parameter, parameter_type)

    args = get_args(parameter_type)

    if args:
        if origin is dict:
            key_type, value_type = args
            return all(
                _deep_is_of_type(k, key_type) and _deep_is_of_type(v, value_type)
                for k, v in parameter.items()
            )
        elif origin is Generator:
            if not hasattr(parameter, "next") and not hasattr(parameter, "__next__"):
                return False
            return True
        elif origin is Callable:
            if not hasattr(parameter, "__call__"):
                return False
            return True
        elif origin in {list, tuple, set, frozenset}:
            (element_type,) = args
            return all(_deep_is_of_type(item, element_type) for item in parameter)
        elif origin is Iterable:
            return (
                all(
                    _deep_is_of_type(item, get_args(parameter_type)[0])
                    for item in parameter
                )
                if isinstance(parameter, Iterable)
                else False
            )

    return isinstance(parameter, parameter_type)

def type_enforced(deep: bool = True):
    """Decorator that enforces the types of the arguments and return value of a function

    Args:
        deep (bool, optional): Whether or not the type checking should look at members of the type. Defaults to True.

    Raises:
        TypeError: An argument or return value does not match the annotations on the function

    Examples:
        >>> @type_enforced
        ... def test_func(a: int, b: str) -> str:
        ...     return str(a + int(b))
        ...
        >>> test_func(1, "2")
        "3"
        >>> test_func(1, 2)
        TypeError: Argument 'b' for function 'test_func' must be of type <class 'str'>, instead type <class 'int'> was passed
    """

    def decorator(func: Callable) -> Callable:
        """Decorator that enforces the types of the arguments and return value of a function

        Args:
            deep (bool, optional): Whether or not the type checking should look at members of the type. Defaults to True.

        Raises:
            TypeError: An argument or return value does not match the annotations on the function
        Returns:
            Callable: The function to enforce type checking on

        Examples:
            >>> @type_enforced
            ... def test_func(a: int, b: str) -> str:
            ...     return str(a + int(b))
            ...
            >>> test_func(1, "2")
            "3"
            >>> test_func(1, 2)
            TypeError: Argument 'b' for function 'test_func' must be of type <class 'str'>, instead type <class 'int'> was passed
            >>> test_func(1, "2.0")
            TypeError: Return value for function 'test_func' must be of type <class 'str'>, instead type <class 'float'> was returned
        """

        type_checker = _deep_is_of_type if deep else _shallow_is_of_type
        signature = inspect.signature(func)
        parameters = signature.parameters
        return_annotation = signature.return_annotation
        return_type = (
            return_annotation if return_annotation is not inspect._empty else None
        )

        def wrapper(*args, **kwargs):
            for i, (name, parameter) in enumerate(parameters.items()):
                if parameter.annotation is inspect._empty:
                    continue
                if i < len(args):
                    if not type_checker(args[i], parameter.annotation):
                        raise TypeError(
                            f"Argument '{name}' for function '{func.__name__}' must be of type {parameter.annotation}, instead type {introspect_type(args[i])} was passed"
                        )
                elif name in kwargs:
                    if not type_checker(kwargs[name], parameter.annotation):
                        raise TypeError(
                            f"Argument '{name}' for function '{func.__name__}' must be of type {parameter.annotation}, instead type {introspect_type(kwargs[name])} was passed"
                        )
            result = func(*args, **kwargs)

            if parameter.annotation is not inspect._empty and not type_checker(
                result, return_type
            ):
                raise TypeError(
                    f"Return value for function '{func.__name__}' must be of type {return_type}, instead type {introspect_type(result)} was returned"
                )
            return result

        return wrapper

    return decorator


import speech_recognition as sr

r = sr.Recognizer()
with sr.AudioFile('audiomass-output-10min.wav') as source:
    audio_data = r.record(source)

# Convert the audio data to text
text = r.recognize_google(audio_data,
                          language="id",
                          show_all=False)

# Print the text to the terminal
print(text)

# Save the recognized text as a text file
with open('recognized_text.txt', 'w') as file:
    file.write(text)

# Print a success message
print(f"Recognized text saved to recognized_text.txt")


from collections import Counter
class Solution:
    def commonChars(self, A: List[str]) -> List[str]:
        if len(A) == 1: return list(A[0])
        c = Counter(A[0])

        for i in range(1, len(A)):
            for ch in c.keys():
                if c[ch] > 0:
                    if A[i].count(ch) == 0:
                        c[ch] = 0
                        continue
                    if A[i].count(ch) < c[ch]: c[ch] = A[i].count(ch)
        ans = []
        for ch,n in c.items():
            for x in range(n): ans.append(str(ch))

        return ans


# 함수 내부에 불필요한 print문이 있는 경우 오답으로 처리가 됩니다.
def average(scores):
    sum = 0
    for i in scores:
        sum+=i
    return sum/len(scores)

# 아래의 코드를 수정하거나 새롭게 추가하지 않습니다.
########## 코드 변경 금지 ############
if __name__ == '__main__':
    scores = [80, 90, 85, 75]
    print(average(scores))    # 82.5


# Tutorials Web:
# https://pytorch.org/tutorials/beginner/blitz/neural_networks_tutorial.html#sphx-glr-beginner-blitz-neural-networks-tutorial-py

# 构建一个简单神经网络

# 卷积层输出计算式：
# N=(W−F+2P)/S+1
# N：输出大小
# W：输入大小
# F：卷积核大小
# P：填充值大小
# S：步长大小

import torch
import torch.nn as nn

class CNNNet(nn.Module):
    def __init__(self):
        # nn.Model的子类
        super(CNNNet, self).__init__()
        # Convolution Layers
        # nn.Conv2d(in_channels,out_channels,kernel)
        # Conv2d Out: (batch_size,depth,rows,cols)
        # Default: padding = 0, stride = 1
        self.conv1 = nn.Conv2d(1,6,5)
        self.conv2 = nn.Conv2d(6,16,5)
        # Full Connected Layers
        self.fc1 = nn.Linear(16*5*5,120)
        self.fc2 = nn.Linear(120,84)
        self.fc3 = nn.Linear(84,10)

    def forward(self, x):
        # Max Pooling (2,2)
        # 最大池化默认步长和窗口一致,n = (28-2)/2 + 1 =14
        # 1*32*32->[conv1]=6*28*28->[max_pool]=6*14*14
        x = torch.max_pool2d(torch.relu(self.conv1(x)),2)
        # Max Pooling (2,2)
        # 6*14*14->[conv2]=16*10*10->[max_pool]=16*5*5
        x = torch.max_pool2d(torch.relu(self.conv2(x)),2)
        # 全连接层的输入即为池化层的输出
        # 平铺，建立全连接层
        x = torch.flatten(x,1)
        x = torch.relu(self.fc1(x))
        x = torch.relu(self.fc2(x))
        # Softmax将张量的每个元素缩放到（0,1）区间且和为1,dim=1表示按行计算
        x = torch.softmax(self.fc3(x),dim=1)
        # x = self.fc3(x)

        return x

def CNN_train(dataset, label, net:CNNNet):
    # 训练程序
    optimizer = torch.optim.SGD(net.parameters(),lr=1e-2)
    epochs = 100
    for i in range(epochs):
        # 手动将梯度缓冲区设为0
        optimizer.zero_grad()
        output = net(dataset)
        # 定义LOSS
        criterion = nn.CrossEntropyLoss()
        loss = criterion(output,label)
        loss.backward()
        optimizer.step()
        print(f"Epoch: {i + 1}, Loss: {loss}")

if __name__ == "__main__":
    net0 = CNNNet()
    # 模拟输入一张图片(Dataset)
    input_sample = torch.randn(10, 1, 32, 32)
    input_label = torch.softmax(torch.rand(10,10),dim=1)
    # input_label = input_label.view(1,-1)
    CNN_train(input_sample,input_label,net0)


# Import OpenCV2 for image processing
import cv2
import picamera
import picamera.array
# Import numpy for matrices calculations
import numpy as np
import os;
import time;

userMap={};

# Set the font style
font = cv2.FONT_HERSHEY_SIMPLEX

# Initialize and start the video frame capture
camera = picamera.PiCamera();
stream =  picamera.array.PiRGBArray(camera);
camera.resolution = (320, 240);

def readUserRegister():
    registerFile = os.getcwd() + "/setup/register.txt";
    registerReadFile = open(registerFile, "r");
    for line in registerReadFile:
       iD,Name = line.split("-");
       userMap[int(iD)] = str(Name[:-1]);

def recognizeFace():

    # Create Local Binary Patterns Histograms for face recognization
    recognizer = cv2.face.LBPHFaceRecognizer_create();

    # Load the trained mode
    recognizer.read('trainer/trainer.yml')

    # Load prebuilt model for Frontal Face
    cascadePath = "haarcascade_frontalface_default.xml"

    # Create classifier from prebuilt model
    faceCascade = cv2.CascadeClassifier(cascadePath);
    # Loop
    while True:
        # Read the video frame
        camera.capture(stream, 'bgr', use_video_port=True);
        stream.truncate(0);
        # Convert the captured frame into grayscale
        gray = cv2.cvtColor(stream.array,cv2.COLOR_BGR2GRAY)

        # Get all face from the video frame
        faces = faceCascade.detectMultiScale(
            gray,
            scaleFactor=1.2,
            minNeighbors=5,
            minSize=(20, 20)
            );

        # For each face in faces
        for(x,y,w,h) in faces:

            # Create rectangle around the face
            cv2.rectangle(stream.array, (x,y), (x+w, y+h), (255,0,0), 2)

            # Recognize the face belongs to which ID
            Id, confidence = recognizer.predict(gray[y:y+h,x:x+w])
            try:
                Id = userMap[int(Id)];
                return str(Id);
            except:
                Id = "Unknown";

            # Put text describe who is in the picture
            cv2.rectangle(stream.array, (x,y), (x+w, y+h), (255,0,0), 2)
            cv2.putText(stream.array, str(Id), (x,y-40), font, 1, (255,255,255), 1)

        # Display the video frame with the bounded rectangle
        cv2.imshow('image',stream.array)

        # If 'q' is pressed, close program
        if cv2.waitKey(10) & 0xFF == ord('q'):
            break;
    return "Unknown";

def findUser():

    readUserRegister();
    userName = recognizeFace();
# Close all windows
    cv2.destroyAllWindows();
    return userName;


from datetime import timedelta

def Calculate_EMI(Loan_amount=None,Tenure=None,Interest_rate=None):
    try:
        tenure_months = Tenure * 12
        monthly_interest_rate = Interest_rate / (12 * 100)
        EMI_amount = (Loan_amount * monthly_interest_rate * (1 + monthly_interest_rate)**tenure_months) / ((1 + monthly_interest_rate)**tenure_months - 1)
        return EMI_amount

    except:
        return 'Invalid information'

def calculate_emi_schedule(EMI_amount=None,Loan_disbursement_date=None,Tenure=None):

    try:
        emi_schedule = []
        tenure_months = int(Tenure * 12)
        EMI_date = Loan_disbursement_date+timedelta(days=30)
        for i in range(1,tenure_months+1):

            emi_schedule.append({
                "installment_number" : i,
                "emi_amount": EMI_amount,
                "expected_date": EMI_date,
            })
            i += 1  # Assuming monthly installments
            EMI_date = EMI_date+timedelta(days=30)
        return emi_schedule
    except:
        return 'Invalid data'


import pytest

from pages.AccountPage import AccountPage
from pages.CustomerLoginPage import CustomerLoginPage
from pages.CustumerPage import CustomerPage
from pages.LoginPage import LoginPage
from pages.OpenAccountPage import OpenAccountPage

def pytest_addoption(parser):
    parser.addoption("--browser", default="firefox", help="Set browser")

@pytest.fixture()
def choose_browser(request):
    selected_browser = request.config.getoption("--browser").lower()
    yield selected_browser

@pytest.fixture()
def open_login(choose_browser):
    print('open page Bank Manager Login')
    login_page = LoginPage(browser=choose_browser)
    yield login_page
    print('Close Browser')
    login_page.close()

@pytest.fixture()
def create_customer(open_login):
    print('open-addCustomer')
    open_login.click_bank_manager()
    customer = CustomerPage(open_login.driver)
    yield customer

@pytest.fixture()
def create_account_customer(create_customer):
    print('Create customer')
    id_customer = create_customer.add_customer(name='Eduardo', lastName='Crepaldi', postalCode='12345678')
    create_customer.close_alert()
    print('open-account')
    account = OpenAccountPage(driver=create_customer.driver, full_name=create_customer.full_name)
    yield id_customer, account

@pytest.fixture()
def create_account_customer_complete(create_account_customer):
    id_customer, account = create_account_customer
    print('create-account')
    account.create_account("Dollar")
    account.close_alert()
    yield id_customer, account

@pytest.fixture()
def account_login(create_account_customer_complete):
    id_customer, account = create_account_customer_complete
    loginAccount = CustomerLoginPage(account.driver)
    loginAccount.login_account(account.full_name)
    account = AccountPage(account.driver)
    yield account


import numpy as np
import cv2
import dlib

def add_hat(img,hat_img):
    r,g,b,a = cv2.split(hat_img)
    rgb_hat = cv2.merge((r,g,b))

    cv2.imwrite("hat_alpha.jpg",a)

    predictor_path = "shape_predictor_5_face_landmarks.dat"
    predictor = dlib.shape_predictor(predictor_path)

    detector = dlib.get_frontal_face_detector()

    dets = detector(img, 1)

    if len(dets)>0:
        for d in dets:
            x,y,w,h = d.left(),d.top(), d.right()-d.left(), d.bottom()-d.top()
            shape = predictor(img, d)
            for point in shape.parts():
                cv2.circle(img,(point.x,point.y),3,color=(0,255,0))
            cv2.imshow("image",img)
            cv2.waitKey()
            point1 = shape.part(0)
            point2 = shape.part(2)

            eyes_center = ((point1.x+point2.x)//2,(point1.y+point2.y)//2)

            factor = 1.5
            resized_hat_h = int(round(rgb_hat.shape[0]*w/rgb_hat.shape[1]*factor))
            resized_hat_w = int(round(rgb_hat.shape[1]*w/rgb_hat.shape[1]*factor))

            if resized_hat_h > y:
                resized_hat_h = y-1

            resized_hat = cv2.resize(rgb_hat,(resized_hat_w,resized_hat_h))

            mask = cv2.resize(a,(resized_hat_w,resized_hat_h))
            mask_inv =  cv2.bitwise_not(mask)

            dh = 0
            dw = 0
            bg_roi = img[y+dh-resized_hat_h:y+dh,(eyes_center[0]-resized_hat_w//3):(eyes_center[0]+resized_hat_w//3*2)]

            bg_roi = bg_roi.astype(float)
            mask_inv = cv2.merge((mask_inv,mask_inv,mask_inv))
            alpha = mask_inv.astype(float)/255

            alpha = cv2.resize(alpha,(bg_roi.shape[1],bg_roi.shape[0]))
            bg = cv2.multiply(alpha, bg_roi)
            bg = bg.astype('uint8')

            cv2.imwrite("bg.jpg",bg)
            hat = cv2.bitwise_and(resized_hat,resized_hat,mask = mask)
            cv2.imwrite("hat.jpg",hat)

            hat = cv2.resize(hat,(bg_roi.shape[1],bg_roi.shape[0]))
            add_hat = cv2.add(bg,hat)
            img[y+dh-resized_hat_h:y+dh,(eyes_center[0]-resized_hat_w//3):(eyes_center[0]+resized_hat_w//3*2)] = add_hat

            return img

hat_img = cv2.imread("hat2.png",-1)
img = cv2.imread("test.jpg")
output = add_hat(img,hat_img)

cv2.imshow("output",output )
cv2.waitKey(0)
cv2.imwrite("output.jpg",output)

cv2.destroyAllWindows()


# -*- coding: utf-8 -*-
#4-15: axes 객체 생성하고, 속성 변경하여 그래프 완성
#4-14와 달리 axe 객체를 저장할 변수 생성, axe 객체 관련 함수 사용(plt 함수와 다름)
#

# 라이브러리 불러오기
import pandas as pd
import matplotlib.pyplot as plt

# matplotlib 한글 폰트 오류 문제 해결
from matplotlib import font_manager, rc
font_path = "./malgun.ttf"   #폰트파일의 위치
font_name = font_manager.FontProperties(fname=font_path).get_name()
rc('font', family=font_name)

# Excel 데이터를 데이터프레임 변환
df = pd.read_excel('시도별 전출입 인구수.xlsx', engine= 'openpyxl', header=0)

# 전출지별에서 누락값(NaN)을 앞 데이터로 채움 (엑셀 양식 병합 부분)
df = df.fillna(method='ffill')

# 서울에서 다른 지역으로 이동한 데이터만 추출하여 정리
mask = (df['전출지별'] == '서울특별시') & (df['전입지별'] != '서울특별시')
df_seoul = df[mask]
df_seoul = df_seoul.drop(['전출지별'], axis=1)
df_seoul.rename({'전입지별':'전입지'}, axis=1, inplace=True)
df_seoul.set_index('전입지', inplace=True)

# 서울에서 '충청남도','경상북도', '강원도', '전라남도'로 이동한 인구 데이터 값만 선택
col_years = list(map(str, range(1970, 2018)))
df_4 = df_seoul.loc[['충청남도','경상북도', '강원도', '전라남도'], col_years]
df_4 = df_4.transpose()

# 스타일 서식 지정
plt.style.use('ggplot')

# 데이터프레임의 인덱스를 정수형으로 변경 (x축 눈금 라벨 표시)
df_4.index = df_4.index.map(int)

#질문)  그래프 객체 생성 코드, sunplot추가 코드 없어도 되는지
#fig=plt.figure(figsize=(20,10)) --> line 46의 figsize설정이 이 코드와 동일한건지
#ax=fig.add_subplot(1,1,1) -->1개로 분할하는 경우이므로 굳이 subplot함수 이용하지 않고 바로 해당 axe객체에 plot 함수 이용하는 건지

# 면적 그래프 axe 객체 생성
ax = df_4.plot(kind='area', stacked=True, alpha=0.2, figsize=(20, 10))
print(type(ax))

# axe 객체 설정 변경
ax.set_title('서울 -> 타시도 인구 이동', size=30, color='brown', weight='bold')
ax.set_ylabel('이동 인구 수', size=20, color='blue')
ax.set_xlabel('기간', size=20, color='blue')
ax.legend(loc='best', fontsize=15)

plt.show()


def quicksort(a,i,j, key):
  if len(a)==1:
    return a
  if i<j:
    d = partition(a,i,j, key)
    quicksort(a,i,d-1, key)
    quicksort(a,d+1,j, key)

def partition(a,i,j, key):
  pivot = j
  j-=1
  while i<j:
    while str(getattr(a[i], key)).lower() < str(getattr(a[pivot], key)).lower():
      i+=1
    while str(getattr(a[j], key)).lower() > str(getattr(a[pivot], key)).lower():
      j-=1
    if i<j:
      a[i],a[j]=a[j],a[i]
  a[i],a[pivot]=a[pivot],a[i]
  return i

def qSort(books, key):
  quicksort(books, 0, len(books)-1, key)