import requests
import time
from datetime import date, datetime
import vk

def start_program():
    # спрашиваем у пользователя ник или id аккаунта, записываем в параметры запроса
    account = input('Введите id аккаунта или ник: ')
    try:
        vk.params['user_id'] = int(account)
    except ValueError:
        print("введен ник")
        vk.params['screen_name'] = account

    user_info = vk.get_user_info()
    user_id = user_info['id']
    users = vk.search_users(user_info)
    result = vk.compare_groups(users)
    top10_users = vk.find_top10(result)
    top10_users_with_photos = vk.find_top3_photos(top10_users)
    final_list = vk.create_output_file(top10_users_with_photos)
    vk.write_output_file(final_list)

if __name__ == '__main__':
    start_program()


# Matrix class in Python
epsilon = 1e-6
def correct_float_error(f):
    # Takes a float and rounds to integer if it is close enough
    if abs(f - round(f)) < epsilon:
        return round(f)
    else:
        return f

class Matrix:
    def __init__(self, rows, cols):
        self.rows = rows
        self.cols = cols
        self.data = [[0 for i in range(cols)] for j in range(rows)]

    def __add__(self, other):
        if self.rows != other.rows or self.cols != other.cols:
            raise Exception("Matrices must have the same dimensions")
        result = Matrix(self.rows, self.cols)
        for i in range(self.rows):
            for j in range(self.cols):
                result.data[i][j] = self.data[i][j] + other.data[i][j]
        return result

    def __sub__(self, other):
        if self.rows != other.rows or self.cols != other.cols:
            raise Exception("Matrices must have the same dimensions")
        result = Matrix(self.rows, self.cols)
        for i in range(self.rows):
            for j in range(self.cols):
                result.data[i][j] = self.data[i][j] - other.data[i][j]
        return result

    def __mul__(self, other):
        if self.cols != other.rows:
            raise Exception("Matrices must have the same dimensions")
        result = Matrix(self.rows, other.cols)
        for i in range(self.rows):
            for j in range(other.cols):
                for k in range(self.cols):
                    result.data[i][j] += self.data[i][k] * other.data[k][j]
        return result

    def __truediv__(self, other):
        if self.rows != other.rows or self.cols != other.cols:
            raise Exception("Matrices must have the same dimensions")
        result = Matrix(self.rows, self.cols)
        for i in range(self.rows):
            for j in range(self.cols):
                result.data[i][j] = self.data[i][j] / other.data[i][j]
        return result

    def __pow__(self, other):
        if self.rows != self.cols:
            raise Exception("Matrix must be square")
        result = Matrix(self.rows, self.cols)
        for i in range(self.rows):
            for j in range(self.cols):
                result.data[i][j] = self.data[i][j] ** other
        return result

    def __mod__(self, other):
        if self.rows != self.cols:
            raise Exception("Matrix must be square")
        result = Matrix(self.rows, self.cols)
        for i in range(self.rows):
            for j in range(self.cols):
                result.data[i][j] = self.data[i][j] % other
        return result

    def __eq__(self, other):
        if self.rows != other.rows or self.cols != other.cols:
            return False
        for i in range(self.rows):
            for j in range(self.cols):
                if self.data[i][j] != other.data[i][j]:
                    return False
        return True

    def __ne__(self, other):
        return not self == other

    def __getitem__(self, key):
        return self.data[key]

    def __setitem__(self, key, value):
        self.data[key] = value

    def __len__(self):
        return self.rows

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

    def get(self, row, col):
        return self.data[row][col]

    def set(self, row, col, value):
        self.data[row][col] = value

    def transpose(self):
        result = Matrix(self.cols, self.rows)
        for i in range(self.rows):
            for j in range(self.cols):
                result.data[j][i] = self.data[i][j]
        return result

    def map(self, func):
        for i in range(self.rows):
            for j in range(self.cols):
                self.data[i][j] = func(self.data[i][j])

    def copy(self):
        result = Matrix(self.rows, self.cols)
        for i in range(self.rows):
            for j in range(self.cols):
                result.data[i][j] = self.data[i][j]
        return result

    def randomize(self):
        import random
        for i in range(self.rows):
            for j in range(self.cols):
                self.data[i][j] = random.random()

    def print(self):
        # Create a lines list with num columns + 2 slots
        lines = ["" for i in range(self.cols + 2)]
        lines[0] = "┌\t"
        for i in range(self.cols):
            lines[0] += "\t"
        lines[0] += "┐"
        for i in range(self.rows):
            lines[i+1] = "│"
            for j in range(self.cols):
                lines[i+1] += "\t" + str(correct_float_error(self.data[i][j]))
            lines[i+1] += "\t│"
        lines[self.rows+1] = "└\t"
        for i in range(self.cols):
            lines[self.rows+1] += "\t"
        lines[self.rows+1] += "┘"
        return "\n".join(lines)

    def setData(self, data):
        self.data = data

    def __str__(self):
        return self.print()

    def __repr__(self):
        return self.print()


import data_tools
import pandas as pd

def description_to_df():
    def first_index_of_detail(detail):
        """
        Should be use the wipe out the start of details like '1. we do stuff' or '2- another stuff'
        :return: index in detail where we should start slicing
        """
        def find_index_end_of_seif_number():
            has_seen_non_space = False
            for i, char in enumerate(detail[:-1]):
                if char != ' ':
                    has_seen_non_space = True
                if has_seen_non_space and (char == '-' or char == '.' or char == ' ') and \
                        (ord('9') < ord(detail[i+1]) or ord(detail[i+1]) < ord('0')):
                    return i + 1
            return None
        ind_end_seif = find_index_end_of_seif_number()
        if ind_end_seif is None:
            return 0
        prev_was_revah = False
        for val in detail[:ind_end_seif]:
            if prev_was_revah and ord('א') <= ord(val) <= ord('ת'):
                return 0
            if val == ' ':
                prev_was_revah = True
            else:
                prev_was_revah = False
        return ind_end_seif

    db = data_tools.get_db()
    details = data_tools.get_vals(db, ['PL_NUMBER', 'PL_NAME', 'main_details_from_mavat'])
    details = [data_tools.tup_to_readable_tup(tup) for tup in details]
    split_tups = []
    for tup in details:
        if tup[2] is None:
            continue
        split_details = tup[2].split('<br>')
        for detail in split_details:
            sliced_detail = detail[first_index_of_detail(detail):]
            stripped_detail = sliced_detail.strip()
            if stripped_detail == '':
                continue
            tup_to_insert = (tup[0], tup[1], stripped_detail)
            split_tups.append(tup_to_insert)
    return pd.DataFrame(split_tups, columns=['PL_NUMBER', 'PL_NAME', 'detail'])

def n_relationship(df, n):
    counters_dict = {}
    for i, row in df.iterrows():
        words = [word.strip() for word in row['detail'].split(' ') if word != '']
        for j in range(0, len(words) - (n - 1)):
            n_words = tuple(words[j:j+n])   # because list is not hashable
            if n_words not in counters_dict:
                counters_dict[n_words] = 0
            counters_dict[n_words] += 1
    return counters_dict

if __name__ == '__main__':
    # This will save all the n-relations from 1 to 11 (not included 11)
    df = description_to_df()
    writer = pd.ExcelWriter('../relations.xlsx', engine='xlsxwriter')
    df.to_excel(writer, sheet_name='original_data')
    for n in range(1, 11):
        relations = sorted(n_relationship(df, n).items(), key=lambda item: item[1], reverse=True)
        relations = [tup for tup in relations if tup[1] > 1]  # don't take combos that do not repeat
        df_n_relation = pd.DataFrame([key + (value,) for key, value in relations],
                                     columns=['word {}'.format(i) for i in range(0, n)] + ['frequency'])
        sheet_name = 'single_words' if n == 1 else '{}_size_relations'.format(n)
        df_n_relation.to_excel(writer, sheet_name=sheet_name)
    writer.save()


from warnings import warn

from django.contrib.gis.db.backends.base.operations import BaseSpatialOperations
from django.db import connections, DEFAULT_DB_ALIAS

class NoIssueGIS(Warning):
    pass

def determine_gissiness():
    try:
        from django.contrib.gis.db.models.fields import PointField
    except ImportError:  # pragma: no cover
        warn(
            "Could not import the PointField class; Issue GIS features are not enabled.",
            NoIssueGIS
        )
        return False

    connection = connections[DEFAULT_DB_ALIAS]

    if not isinstance(connection.ops, BaseSpatialOperations):  # pragma: no cover
        warn(
            f"The default connection {connection!r} is not GIS-enabled; Issue GIS features are not enabled.",
            NoIssueGIS
        )
        return False

    return True


from functools import lru_cache
from app.celery import celery_app
from app.tasks.get_timetable import request_shedule
from celery.result import GroupResult
from core.config import config
from fastapi import APIRouter, Depends, HTTPException, Response
from fastapi.responses import ORJSONResponse

router = APIRouter(
    prefix="/wakeparks",
    tags=["items"],
)

@lru_cache()
def get_items():
    return list(config.SHEDULE_ITEMS.keys())

@router.get("/", response_class=ORJSONResponse)
def items(items: list = Depends(get_items)):
    return items

@router.get("/{item_id}", response_class=ORJSONResponse, status_code=202)
def get_item(item_id: str, date: str | None = None):
    if item_id not in config.SHEDULE_ITEMS:
        raise HTTPException(status_code=404)

    task = request_shedule(item_id, date)

    return {"task_id": task.id}

@router.get("/tasks/{task_id}", response_class=ORJSONResponse)
def get_status(task_id: str, response: Response):
    task_result = GroupResult.restore(task_id, app=celery_app)

    if task_result is None:
        raise HTTPException(status_code=404)
    if task_result.ready():
        result_data = task_result.get()
        return result_data

    response.status_code = 202
    return {"task_id": task_id}


import sys
import json

from scipy.spatial.distance import cosine
from sklearn.metrics import roc_auc_score, precision_recall_curve
import numpy as np

from nyan.embedder import Embedder

def read_jsonl(path):
    with open(path) as r:
        return [json.loads(line) for line in r]

markup_path = sys.argv[1]
docs_path = sys.argv[2]
model_path = sys.argv[3]

markup = read_jsonl(markup_path)
docs = read_jsonl(docs_path)
docs = {doc["url"]: doc for doc in docs}

embedder = Embedder(model_path)
y_pred = []
y_true = []
for record in markup:
    result = record["result"]
    if result == "trash":
        continue
    url1 = record["url1"]
    url2 = record["url2"]
    doc1 = docs[url1]
    doc2 = docs[url2]
    embeddings = embedder([doc1["text"], doc2["text"]])
    distance = cosine(embeddings[0], embeddings[1])
    y_pred.append(distance)
    label = 1 - int(result == "ok")
    y_true.append(label)

print("AUC:", roc_auc_score(y_true, y_pred))
precision, recall, thresholds = precision_recall_curve(y_true, y_pred)
f1_scores = 2 * recall * precision / (recall + precision)
threshold = thresholds[np.argmax(f1_scores)]
f1 = max(f1_scores)
print('Best threshold: ', threshold)
print("F1: ", f1)


s1 = ''.join(input().split(' '))
s2 = ''.join(input().split(' '))
d = dict()
flag = 'NO'
for i in s2:
    if i in d:
        d[i] += 1
    else:
        d[i] = 1
for i in s1:
    if i in d:
        d[i] -= 1
        if d[i] == 0:
            d.pop(i)
    if len(d) == 0:
        flag = 'YES'
        break
print(flag, end='')


from typing import TYPE_CHECKING, Any, Dict
from pydantic import ConstrainedDecimal
from pydantic.types import ConstrainedNumberMeta
from udantic.fields.utils import is_float

if TYPE_CHECKING:
    FieldPercent = dict
else:

    class _FieldPercent(ConstrainedDecimal):
        """
        FieldPrice can be:
            - int, float based 1
            - str, folloing format works:
                - int or float as str, based 1
                - symbol % ended with int or float as str based 0.01
        """
        @classmethod
        def __get_validators__(cls) -> 'CallableGenerator':
            # one or more validators may be yielded which will be called in the
            # order to validate the input, each validator will receive as an input
            # the value returned from the previous validator
            yield cls.validate
            return ConstrainedDecimal.__get_validators__()

        @classmethod
        def validate(cls, t: Any):
            if isinstance(t, ConstrainedDecimal) or \
                isinstance(t, int) or isinstance(t, float):
                return cls(t)
            if not isinstance(t, str):
                raise TypeError(f"{t} can't be treated as Percent")
            pstr = str(t).strip()
            if is_float(pstr):
                return cls(float(pstr))
            elif pstr[-1] == "%" and is_float(pstr[0:-2]):
                return cls(float(pstr[0:-1]) * 0.01)
            else:
                raise TypeError(f"{t} unkown format of Percent")

        def __repr__(self):
            return f'{type(self)}({super().__repr__()})'

    class FieldPercent(type):
        def __new__(cls, *,
                    gt: ConstrainedDecimal = None,  ge: ConstrainedDecimal = None,
                    lt: ConstrainedDecimal = None, le: ConstrainedDecimal = None,
                    max_digits: int = None, decimal_places: int = None):
            namespace = dict(
                gt=gt, ge=ge, lt=lt, le=le, max_digits=max_digits, decimal_places=decimal_places
            )
            return type('PercentValue', (_FieldPercent,), namespace)


class Singleton1(object):
    _instance = None
    _is_first_inst = False

    def __new__(cls, name):
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self, name):
        if not self._is_first_inst:
            self.__name = name
            Singleton1._is_first_inst = True

    @property
    def name(self):
        return self.__name

if __name__ == '__main__':
    tony = Singleton1('Tony')
    karry = Singleton1('Karry')
    print(tony.name, karry.name)
    print(f'id(tony):{id(tony)}, id(karry):{id(karry)}')
    print('tony==karry:', tony == karry)


n = int(input())
a = [int(i) for i in input().split()]
two = 0
four = 0
for i in range(n):
    if a[i] % 4 == 0:
        four += 1
    elif a[i] % 2 == 0:
        two += 1
if n == 2:
    ans = 'Yes' if 1 <= four or two == n else 'No'
elif n == 3:
    ans = 'Yes' if 1 <= four or two == n else 'No'
else:
    ans = 'Yes' if (2 <= four and (n-four*2 <= two or (n-4)//2 <= four-2)) or (four == 1 and n-2 <= two) or two == n else 'No'
print(ans)


# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.

# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

from ansible.errors import AnsibleError, AnsibleParserError
from ansible.playbook.attribute import Attribute, FieldAttribute
#from ansible.utils.display import deprecated

class Become:

    # Privlege escalation
    _become              = FieldAttribute(isa='bool', default=False)
    _become_method       = FieldAttribute(isa='string')
    _become_user         = FieldAttribute(isa='string')
    _become_pass         = FieldAttribute(isa='string')

    def __init__(self):
        return super(Become, self).__init__()

    def _detect_privilege_escalation_conflict(self, ds):

        # Fail out if user specifies conflicting privelege escalations
        has_become = 'become' in ds or 'become_user'in ds
        has_sudo   = 'sudo' in ds or 'sudo_user' in ds
        has_su     = 'su' in ds or 'su_user' in ds

        if has_become:
            msg = 'The become params ("become", "become_user") and'
            if has_sudo:
                raise errors.AnsibleParserError('%s sudo params ("sudo", "sudo_user") cannot be used together' % msg)
            elif has_su:
                raise errors.AnsibleParserError('%s su params ("su", "su_user") cannot be used together' % msg)
        elif has_sudo and has_su:
            raise errors.AnsibleParserError('sudo params ("sudo", "sudo_user") and su params ("su", "su_user") cannot be used together')

    def _munge_become(self, ds):

        self._detect_privilege_escalation_conflict(ds)

        # Setting user implies setting become/sudo/su to true
        if 'become_user' in ds and not ds.get('become', False):
            ds['become'] = True

        # Privilege escalation, backwards compatibility for sudo/su
        if 'sudo' in ds or 'sudo_user' in ds:
            ds['become_method'] = 'sudo'
            if 'sudo' in ds:
                ds['become'] = ds['sudo']
                del ds['sudo']
            else:
                ds['become'] = True
            if 'sudo_user' in ds:
                ds['become_user'] = ds['sudo_user']
                del ds['sudo_user']

            #deprecated("Instead of sudo/sudo_user, use become/become_user and set become_method to 'sudo' (default)")

        elif 'su' in ds or 'su_user' in ds:
            ds['become_method'] = 'su'
            if 'su' in ds:
                ds['become'] = ds['su']
                del ds['su']
            else:
                ds['become'] = True
            if 'su_user' in ds:
                ds['become_user'] = ds['su_user']
                del ds['su_user']

            #deprecated("Instead of su/su_user, use become/become_user and set become_method to 'su' (default is sudo)")

        return ds


import json
import requests
from django.shortcuts import render,reverse
from django.views.decorators.csrf import csrf_exempt
from django.http import *
from web.forms.file import FileFolderModelForm, FileModelForm
from django.http import JsonResponse
from web.models import *
from utils.tencent.cos import *

def file(request, project_id):
    '''文件列表'''
    # 区分父级目录
    parent_object = None
    folder_id = request.GET.get('folder', "")
    if folder_id.isdecimal():
        parent_object = FileRepository.objects.filter(id=int(folder_id), file_type=2,
                                                      project=request.saas.project).first()
    # 查看页面`
    if request.method == 'GET':
        # 导航条
        breadcrumb_list = []
        parent = parent_object
        while parent:
            breadcrumb_list.insert(0, {'id': parent.id, 'name': parent.name})
            parent = parent.parent

        # 当前目录下的所有文件 $ 文件夹获取到即可
        queryset = FileRepository.objects.filter(project=request.saas.project)
        if parent_object:
            # 进入了某个目录
            file_object_list = queryset.filter(parent=parent_object).order_by('-file_type')  # 倒序,文件夹在上文件在下
        else:
            # 根目录
            file_object_list = queryset.filter(parent__isnull=True).order_by('-file_type')
        form = FileFolderModelForm(request, parent_object)
        context = {
            'form': form,
            "file_object_list": file_object_list,
            "breadcrumb_list": breadcrumb_list,
            'folder_object': parent_object
        }
        return render(request, 'file.html', context)
    # 文件夹添加 & 修改
    fid = request.POST.get('fid', '')
    edit_object = None
    if fid.isdecimal():
        # 修改
        edit_object = FileRepository.objects.filter(id=int(fid), file_type=2,
                                                    project=request.saas.project).first()
    if edit_object:
        form = FileFolderModelForm(request, parent_object, data=request.POST, instance=edit_object)
    else:
        form = FileFolderModelForm(request, parent_object, data=request.POST)
    if form.is_valid():
        form.instance.project = request.saas.project
        form.instance.file_type = 2
        form.instance.update_user = request.saas.user
        form.instance.parent = parent_object
        form.save()
        return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': form.errors})

def file_delete(request, project_id):
    """删除文件"""
    fid = request.GET.get('fid')
    # 删除数据库文件和文件夹(级联删除)
    delete_object = FileRepository.objects.filter(id=fid, project=request.saas.project).first()
    if delete_object.file_type == 1:
        # 删除文件(数据库文件/cos文件),并且把空间还回去
        # 删除文件,将容量还回去
        request.saas.project.use_space -= delete_object.file_size
        request.saas.project.save()
        # 去cos中删除文件
        delete_file(request.saas.project.bucket, request.saas.project.region, delete_object.key)
        delete_object.delete()
        return JsonResponse({'status': True})
    else:
        # 删除文件夹(找到文件夹下面的所有文件,删除并且把空间还回去)
        total_size = 0
        key_list = []
        folder_list = [delete_object, ]
        for folder in folder_list:
            child_list = FileRepository.objects.filter(project=request.saas.project, parent=folder).order_by(
                '-file_type')
            for child in child_list:
                if child.file_type == 2:
                    folder_list.append(child)
                else:
                    # 文件大小汇总
                    total_size += child.file_type

                    # 删除文件
                    key_list.append({"Key": child.key})

        # cos 批量删除文件
        if key_list:
            delete_file_list(request.saas.project.bucket, request.saas.project.region, key_list)
        # 归还容量
        if total_size:
            request.saas.project.use_space -= total_size
            request.saas.project.save()

        delete_object.delete()
        return JsonResponse({'status': True})

@csrf_exempt
def cos_credential(request, project_id):
    '''获取上传临时凭证'''
    per_file_limit = request.saas.price_policy.per_file_size * 1024 * 1024  # 限制 单个文件
    total_file_limit = request.saas.price_policy.per_file_size * 1024 * 1024 * 1024  # 限制   单个项目
    file_list = json.loads(request.body.decode('utf-8'))
    total_size = 0
    # 单个容量限制
    for item in file_list:
        # 文件字节大小 item['size]=B  单文件限制大小 M
        if item['size'] > per_file_limit:
            # 超出限制
            msg = '单文件超出限制(最大{}M),文件:{},请升级套餐'.format(request.saas.price_policy.per_file_size, item['name'])
            return JsonResponse({'status': False, 'error': msg})
    # 总容量限制
    # request.saas.price_policy.project_space #项目允许使用的空间
    # request.saas.project.use_space #项目已使用的空间
    if request.saas.project.use_space + total_size > total_file_limit:
        # 超出限制
        return JsonResponse({'status': False, 'error': '容量超过限制,请升级套餐'})
    data_dict = credential(request.saas.project.bucket, request.saas.project.region)

    return JsonResponse({'status': True, 'data': data_dict})

@csrf_exempt
def file_post(request, project_id):
    """ 已上传成功的文件写入到数据 """
    """
    name: fileName,
    key: key,
    file_size: fileSize,
    parent: CURRENT_FOLDER_ID,
    # etag: data.ETag,
    file_path: data.Location
    """

    # 根据key再去cos获取文件Etag和"db7c0d83e50474f934fd4ddf059406e5"

    print(request.POST)
    # 把获取到的数据写入数据库即可
    form = FileModelForm(request, data=request.POST)
    if form.is_valid():
        # 校验通过,写入数据库
        # form.instance.file_type = 1
        # form._update_user = request.saas.user
        data_dict = form.cleaned_data
        data_dict.pop('etag')
        data_dict.update({'project': request.saas.project, 'file_type': 1, 'update_user': request.saas.user})
        instance = FileRepository.objects.create(**data_dict)
        #项目的已使用空间
        request.saas.project.use_space += data_dict['file_size']
        request.saas.project.save()

        result = {
            'id': instance.id,
            'name': instance.name,
            'file_size': instance.file_size,
            'username': instance.update_user.name,
            'datetime': instance.update_datetime.strftime('%Y年-%m月-%d日 %H:%M'),
            # 'file_type':instance.get_file_type_display()
            'download_url':reverse('file_download',kwargs = {'project_id':project_id,'file_id':instance.id})
        }
        return JsonResponse({'status': True, 'data': result})
    return JsonResponse({'status': False, 'data': '文件错误'})

def file_download(request, project_id,file_id):
    '''下载文件'''
    file_object = FileRepository.objects.filter(id=file_id, project_id=project_id).first()
    res = requests.get(file_object.file_path)

    # 文件分块处理（适用于大文件）     @孙歆尧
    data = res.iter_content()

    # 设置content_type=application/octet-stream 用于提示下载框        @孙歆尧
    response = HttpResponse(data, content_type="application/octet-stream")
    from django.utils.encoding import escape_uri_path

    # 设置响应头：中文件文件名转义      @王洋
    response['Content-Disposition'] = "attachment; filename={};".format(escape_uri_path(file_object.name))
    return response


#! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/9/20 21:02
# @Author  : toby
# @File    : 39.协程-事件循环set_task_factory方法.py
# @Software: PyCharm
# @Desc:
import asyncio

def custom_task_factory(loop, coro):
    task = asyncio.Task(coro, loop=loop)
    task.my_custom_attribute = "This is a custom attribute"
    return task

async def my_coroutine():
    await asyncio.sleep(1)

async def main():
    loop = asyncio.get_event_loop()

    # 设置自定义任务工厂
    loop.set_task_factory(custom_task_factory)

    # 创建协程任务
    task = asyncio.create_task(my_coroutine())
    await task

    # 访问自定义属性
    print(task.my_custom_attribute)

asyncio.run(main())


from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.urls import reverse
from django.utils import timezone

from .models import Todoitem

def index(request, **kwargs):
    context = {
        'list_header': 'Anything!',
        'comp_header': 'Look On Your Works',
        'todos': Todoitem.objects.filter(completion_status=False),
        'done_todos': Todoitem.objects.filter(completion_status=True),
    }
    return render(request, 'todo/index.html', context)

def new_todo(request, **kwargs):
    todo_txt = request.POST['todo_txt']
    todo = Todoitem(body=todo_txt, completion_status=False)
    todo.save()
    return HttpResponseRedirect(reverse('todo:index'))

def complete_todo(request):
    todo_id = request.POST['todo_id']
    item = get_object_or_404(Todoitem, pk=todo_id)
    item.completion_status = True
    item.complete_date = timezone.now()
    item.save()
    return HttpResponseRedirect(reverse('todo:index'))


# Code Release for ICLR-22 work
# 'Differentiable Gradient Sampling for Learning Implicit 3D Scene Reconstructions from a Single Image'
# Any question please contact Shizhan Zhu: zhshzhutah2@gmail.com
# Released on 04/25/2022.

# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.

# Borrowed and developed from: https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/util/html.py
# This tool does not care about functional / non-functional
from ..np_ext.np_image_io_v1 import gifWrite
from ..py_ext.misc_v1 import mkdir_full
import dominate
from dominate.tags import *
import os
import skimage.io as io
import numpy as np
import shutil

class HTML:
    def __init__(self, web_dir, title, reflesh=0):

        if os.path.isdir(web_dir):
            shutil.rmtree(web_dir)
        mkdir_full(web_dir + 'images/')

        self.title = title
        self.web_dir = web_dir
        self.img_dir = os.path.join(self.web_dir, 'images')

        self.doc = dominate.document(title=title)
        if reflesh > 0:
            with self.doc.head:
                meta(http_equiv="reflesh", content=str(reflesh))

    def get_image_dir(self):
        return self.img_dir

    def add_header(self, str):
        with self.doc:
            h3(str)

    def add_header_h4(self, str):
        with self.doc:
            h4(str)

    def add_header_h5(self, str):
        with self.doc:
            h5(str)

    def add_text(self, s):
        with self.doc:
            p(s)

    def add_table(self, border=1):
        self.t = table(border=border, style="table-layout: fixed;")
        self.doc.add(self.t)

    def add_images(self, ims, txts, links, width=400):
        self.add_table()
        with self.t:
            with tr():
                for im, txt, link in zip(ims, txts, links):
                    with td(style="word-wrap: break-word;", halign="center", valign="top"):
                        with p():
                            with a(im):  # zhuzhu
                                br()
                                img(style="width:%dpx" % width, src=link)
                            br()
                            if not(txt is None):
                                p(txt)

    def save(self):
        html_file = '%s/index.html' % self.web_dir
        f = open(html_file, 'wt')
        f.write(self.doc.render())
        f.close()

def storeImagesAndReturnLinks(str_store, str_link, strs_imgs, imgsContents):
    links = []
    assert len(strs_imgs) == len(imgsContents)
    for i in range(len(strs_imgs)):
        if len(imgsContents[i].shape) in [2, 3]:  # It is png
            if len(imgsContents[i].shape) == 2:
                assert imgsContents[i].shape[0] > 5
                assert imgsContents[i].shape[1] > 5
            if 'float32' in str(imgsContents[i].dtype):
                tmp = imgsContents[i].copy()
                tmp[tmp < 0] = 0.
                tmp[tmp > 1] = 1.
                tmp = (tmp * 255.).astype(np.uint8)
                io.imsave(str_store + strs_imgs[i] + '.png', tmp)
            else:
                io.imsave(str_store + strs_imgs[i] + '.png', imgsContents[i])
            links.append(str_link + strs_imgs[i] + '.png')
        elif len(imgsContents[i].shape) == 4:  # It is gif
            gifWrite(str_store + strs_imgs[i] + '.gif', imgsContents[i])
            links.append(str_link + strs_imgs[i] + '.gif')
        else:
            raise ValueError('Shape of imgsContents[i] is wierd %s' % str(imgsContents[i].shape))

    return links

class HTMLStepperAbstract(object):
    def __init__(self, logDir, singleHtmlSteps, htmlName):  # consider to use htmlName to represent different experiments.
        # Static member
        assert os.path.isdir(logDir)
        if not logDir.endswith('/'):
            logDir += '/'
        self.logDir = logDir
        self.htmlName = htmlName
        self.singleHtmlSteps = singleHtmlSteps

        # dynamics
        self.htmlStepCount = float('inf')
        self.currentFileID = None
        self.html = None

    def _printLossTotal(self, loss):
        raise NotImplementedError

    def _printLossEach(self, loss, j):
        raise NotImplementedError

    def step2(self, summary0=None, txt0=None, brInds=(0, ), headerMessage=None, subMessage=None):
        assert brInds[0] == 0
        if txt0 is not None:
            assert len(summary0) == len(txt0)
        if self.htmlStepCount >= self.singleHtmlSteps:  # reset
            assert os.path.isdir(self.logDir)
            mkdir_full(self.logDir + 'html_' + self.htmlName + '/')
            tmp = [int(x[5:]) for x in os.listdir(self.logDir + 'html_' + self.htmlName + '/') if x.startswith('html_')]
            if tmp:  # safe if  # tmp is a non-empty set
                maxHtmlFileID = max(tmp)
            else:  # tmp is an empty set
                maxHtmlFileID = -1
            self.currentFileID = maxHtmlFileID + 1
            self.html = HTML(self.logDir + 'html_' + self.htmlName + '/' + 'html_%06d/' % self.currentFileID,
                             self.htmlName)  # zhuzhu
            self.htmlStepCount = 0

        if headerMessage is not None:
            self.html.add_header(headerMessage)
        if subMessage is not None:
            self.html.add_header_h4(subMessage)
        if summary0 is not None:
            links = storeImagesAndReturnLinks(
                self.logDir + 'html_' + self.htmlName + '/html_%06d/images/%s_%06d_%06d_' %
                    (self.currentFileID, self.htmlName, self.currentFileID, self.htmlStepCount),
                'images/%s_%06d_%06d_' %
                    (self.htmlName, self.currentFileID, self.htmlStepCount),
                list(summary0.keys()),
                list(summary0.values()),
            )
            for o in range(len(brInds)):
                head = brInds[o]
                if head >= len(summary0):
                    break
                if o == len(brInds) - 1 or brInds[o + 1] >= len(summary0):
                    tail = len(summary0)
                else:
                    tail = brInds[o + 1]
                if txt0 is None:
                    self.html.add_images(
                        list(summary0.keys())[head:tail],
                        [None for _ in range(head, tail)], links[head:tail])
                else:
                    self.html.add_images(
                        list(summary0.keys())[head:tail],
                        [txt0[i] for i in range(head, tail)], links[head:tail])
        self.html.save()
        self.htmlStepCount += 1

    def step(self, iterCount, losses, visual, txts=None, brInds=(0, )):  # functional, but file system changed  # losses can be OrderedDict as in here, or also a TreeLog
        assert brInds[0] == 0
        if txts is not None:
            assert len(visual.summary) == len(txts[0])
        if self.htmlStepCount >= self.singleHtmlSteps:  # reset
            assert os.path.isdir(self.logDir)
            mkdir_full(self.logDir + 'html_' + self.htmlName + '/')
            tmp = [int(x[5:]) for x in os.listdir(self.logDir + 'html_' + self.htmlName + '/') if x.startswith('html_')]
            if tmp:  # safe if  # tmp is a non-empty set
                maxHtmlFileID = max(tmp)
            else:  # tmp is an empty set
                maxHtmlFileID = -1
            self.currentFileID = maxHtmlFileID + 1
            self.html = HTML(self.logDir + 'html_' + self.htmlName + '/' + 'html_%06d/' % self.currentFileID, self.htmlName)  # zhuzhu
            self.htmlStepCount = 0

        self.html.add_header('Iter %d %s' % (iterCount, self.htmlName))  # zhuzhu
        self._printLossTotal(losses)

        for j in range(visual.m):
            links = storeImagesAndReturnLinks(
                self.logDir + 'html_' + self.htmlName + '/html_%06d/images/%s_%08d_%06d_%02d_%02d_%08d_%08d_' % \
                    (self.currentFileID, self.htmlName, iterCount, self.currentFileID, j, visual.datasetID[j], visual.index[j], visual.insideBatchIndex[j]),  # zhuzhu
                'images/%s_%08d_%06d_%02d_%02d_%08d_%08d_' % (self.htmlName, iterCount, self.currentFileID, j, visual.datasetID[j], visual.index[j], visual.insideBatchIndex[j]),  # zhuzhu
                list(visual.summary.keys()),
                [x[j] for x in visual.summary.values()],
            )
            self.html.add_header('Iter = %d, Dataset = %s, SampleID = %d, InsideBatchID %d' % \
                                 (iterCount, visual.dataset[j], visual.index[j], visual.insideBatchIndex[j]))
            self._printLossEach(losses, visual.insideBatchIndex[j])
            for o in range(len(brInds)):
                head = brInds[o]
                if head >= len(visual.summary):
                    break
                if o == len(brInds) - 1 or brInds[o + 1] >= len(visual.summary):
                    tail = len(visual.summary)
                else:
                    tail = brInds[o + 1]
                if txts is None:
                    self.html.add_images(list(visual.summary.keys())[head:tail], [None for _ in range(head, tail)], links[head:tail])
                else:
                    self.html.add_images(list(visual.summary.keys())[head:tail], [txts[j][i] for i in range(head, tail)], links[head:tail])
            # self.html.add_images(visual.summary.keys(), [None for _ in visual.summary.keys()], links)
        self.html.save()
        self.htmlStepCount += 1

class HTMLStepper(HTMLStepperAbstract):
    pass

# Do more class extension directly in your code!

class HTMLStepperODTotal(HTMLStepperAbstract):
    # Override
    def _printLossTotal(self, loss_od):
        st = ''
        for k in loss_od.keys():
            assert type(loss_od[k]) is float
            st += ' %s: %.5f,' % (k, loss_od[k])
        self.html.add_header_h4(st)

    # Override
    def _printLossEach(self, loss_od, j):
        pass

class HTMLStepperNoPrinting(HTMLStepperAbstract):
    # Override
    def _printLossTotal(self, loss_none):
        pass

    # Override
    def _printLossEach(self, loss_none, j):
        pass

class HTMLStepperTreeLog(HTMLStepperAbstract):  # dedicated to our framework
    # Notes for __init__(logDir, singleHtmlSteps, htmlName): htmlName in here should be something like 'G_%s_%s_%s_%s' % (P, D, S, R)

    # Override
    def _printLossTotal(self, treeLog):
        for t in treeLog.keys():
            treeLog[t].print_stack(2, self.html.add_header_h4)

    # Override
    def _printLossEach(self, treeLog, j):
        for t in treeLog.keys():
            treeLog[t].print_stack(4, self.html.add_text, j)

if __name__ == '__main__':
    html = HTML('./', 'test_html')
    html.add_header('hello world')

    ims = []
    txts = []
    links = []
    for n in range(1, 5):
        ims.append('image_%d.png' % n)
        txts.append('text_%d' % n)
        # links.append('image_%d.png' % n)  # zhuzhu
        links.append('/home/zhusz/link/play/html/image_%d.png' % n)
    html.add_images(ims, txts, links)

    ims = []
    txts = []
    links = []
    for n in range(1, 5):
        ims.append('image_%d.png' % n)
        txts.append('text_%d' % n)
        # links.append('image_%d.png' % n)  # zhuzhu
        links.append('/home/zhusz/link/play/html/image_%d.png' % n)
    html.add_images(ims, txts, links)
    html.save()


# -*- coding: utf-8 -*-
"""
Created on Wed Feb  5 04:41:35 2020

@author: halfar
"""
from numba import jit
from numpy import *
import matplotlib.pyplot as plt
import time

# papa = zeros((20,20), dtype = bool)

# print(papa[1,1])
# papa[2:7, 3] = True
# print(papa)

# plt.imshow(papa, cmap='hot', interpolation='nearest')

# @jit
def testi():

    papa = zeros((10000,10000))

    for i in range(papa.shape[0]):

        for j in range(papa.shape[1]):

            papa[i,j]  += i+j

    return papa

# @jit
def kaka():

    lala = []
    pau = 1000000

    for i in range(pau):

        lala.append(i**2)

    return lala

start_time = time.time()
tata = testi()
print ("did take ", time.time() - start_time, "s to run")

start_time = time.time()
papa = testi()
print ("did take ", time.time() - start_time, "s to run")

start_time = time.time()
tata = kaka()
print ("did take ", time.time() - start_time, "s to run")

start_time = time.time()
papa = kaka()
print ("did take ", time.time() - start_time, "s to run")


import json
import pprint
import urllib
from PIL import Image, ImageDraw, ImageFilter, ImageOps
import discord
import requests
from discord.ext import commands
from discord.ext.commands import bot

class Acciones(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    def respuestaMensaje(accion):
        global url
        apikey = "Z20FPG65VAWS"
        lmt = 1
        r = requests.get(
            "https://api.tenor.com/v1/random?q=%s&key=%s&limit=%s" % (accion, apikey, lmt))

        if r.status_code == 200:
            pp = pprint.PrettyPrinter(indent=4)
            gif = json.loads(r.content)
            for i in range(len(gif['results'])):
                url = gif['results'][i]['media'][0]['gif']['url']

    @commands.command(name='hug',
                      brief='Abraza a tu compaÃ±ero uwu')
    async def hug(self, ctx, user):
        """Abraza a tu compaÃ±ero uwu."""
        embed = discord.Embed(colour=discord.Colour(0x9013fe))
        Acciones.respuestaMensaje("hug")
        embed.set_image(url=url)
        try:
            embed.add_field(name="â€Ž", value=f"""**<@!{ctx.author.id}>** abrazÃ³ a **{user}**. uwu""")
        except discord.ext.commands.errors.MissingRequiredArgument:
            embed.add_field(name="â€Ž", value=f"""**<@!{ctx.author.id}>** se abrazÃ³ a sÃ mismo, esto es un poco triste...""")

        await ctx.send(embed=embed)

    @commands.command(name='hostia',
                      brief='Dale una hostia a alguien xd')
    async def hostia(self, ctx, user):
        """Dale una hostia a alguien xd"""
        embed = discord.Embed(colour=discord.Colour(0x9013fe))
        Acciones.respuestaMensaje("slap")
        embed.set_image(url=url)
        try:
            embed.add_field(name="â€Ž", value=f"""**<@!{ctx.author.id}>** le diÃ³ una hostia a **{user}**. ðŸ˜ˆ""")
        except discord.ext.commands.errors.MissingRequiredArgument:
            embed.add_field(name="â€Ž", value=f"""**<@!{ctx.author.id}>** se diÃ³ una hostia a sÃ mismo... Â¿EstÃ¡s bien?""")

        await ctx.send(embed=embed)

    @commands.command(name='kill',
                      brief='Literalmente mata a alguien xddd')
    async def kill(self, ctx, user):
        """Literalmente mata a alguien xddd"""
        embed = discord.Embed(colour=discord.Colour(0x9013fe))
        print(user)
        print(ctx.author.id)
        try:
            if user != ("<@741962880097845340>" and "<@!741962880097845340>") :
                embed.add_field(name="â€Ž", value=f"""**<@!{ctx.author.id}>** puto matÃ³ a **{user}**. ðŸ˜Žâœ¨""")
                Acciones.respuestaMensaje("kill you")
                embed.set_image(url=url)
                await ctx.send(embed=embed)
            else:
                async with ctx.channel.typing():
                    bg = Image.open('cogs/img/CallAnAmbulance....png').convert("RGBA")
                    width, height = bg.size
                    userIcon = ctx.author.avatar_url
                    img_data = requests.get(userIcon).content
                    with open('cogs/img/userIcon.png', 'wb') as handler:
                        handler.write(img_data)
                    userIcon = Image.open('cogs/img/userIcon.png').convert("RGBA")
                    mask = Image.open("cogs/img/circuloMask.png").convert("L")
                    userIcon = userIcon.resize((100, 100), Image.ANTIALIAS)
                    userIcon = ImageOps.fit(userIcon, mask.size, centering=(0.5, 0.5))
                    userIcon.putalpha(mask)
                    userIcon = userIcon.resize((100, 100), Image.ANTIALIAS)

                    text_img = Image.new('RGBA', (width, height), (0, 0, 0, 0))
                    text_img.paste(bg, (0, 0))
                    text_img.paste(userIcon, (90, -5), mask=userIcon)
                    text_img.save("cogs/img/killDyson.png", format="png")
                    file = discord.File("cogs/img/killDyson.png", filename="image.png")
                    embed.set_image(url="attachment://image.png")
                    embed.add_field(name="â€Ž", value="...")
                    await ctx.send(file=file, embed=embed)

        except discord.ext.commands.errors.MissingRequiredArgument:
            embed.add_field(name="â€Ž", value=f"""**<@!{ctx.author.id}>** se puto matÃ³. ðŸ˜Žâœ¨""")
            Acciones.respuestaMensaje("kms")
            embed.set_image(url=url)
            await ctx.send(embed=embed)

    @commands.command(name='kiko',
                      brief='Te puto matas. Momento xd.')
    async def kiko(self, ctx):
        """Te puto matas. Momento xd."""
        embed = discord.Embed(colour=discord.Colour(0x9013fe))
        embed.add_field(name="â€Ž", value=f"""**<@!{ctx.author.id}>** se puto matÃ³. ðŸ˜Žâœ¨""")
        Acciones.respuestaMensaje("kms")
        embed.set_image(url=url)
        await ctx.send(embed=embed)

    @commands.command(name='cry',
                      brief='WAAAH WAAAH',
                      alias="llorar")
    async def cry(self, ctx):
        """WAAAH WAAAH"""
        embed = discord.Embed(colour=discord.Colour(0x9013fe))
        embed.add_field(name="â€Ž", value=f"""**<@!{ctx.author.id}>** se puso a llorar. ðŸ˜""")
        Acciones.respuestaMensaje("cry")
        embed.set_image(url=url)
        await ctx.send(embed=embed)

    @commands.command(name='cat',
                      brief='Miau xd',
                      alias="gato")
    async def cat(self, ctx):
        """WAAAH WAAAH"""
        embed = discord.Embed(colour=discord.Colour(0x9013fe))
        embed.add_field(name="â€Ž", value=f"""**<@!{ctx.author.id}>** ahora tiene un gatito. ðŸ˜¼""")
        Acciones.respuestaMensaje("cat")
        embed.set_image(url=url)
        await ctx.send(embed=embed)

    @commands.command(name='heal',
                      brief='Curas a quien quieras.')
    async def heal(self, ctx, user):
        """Curas a quien quieras"""
        embed = discord.Embed(colour=discord.Colour(0x9013fe))

        try:
            embed.add_field(name="â€Ž", value=f"""**<@!{ctx.author.id}>** curÃ³ a **{user}** ðŸ’‰""")
            Acciones.respuestaMensaje("heal")
        except discord.ext.commands.errors.MissingRequiredArgument:
            embed.add_field(name="â€Ž", value=f"""**<@!{ctx.author.id}>** se curÃ³ ðŸ’‰""")
            Acciones.respuestaMensaje("heal")

        embed.set_image(url=url)
        await ctx.send(embed=embed)

    @commands.command(name='horny',
                      brief='Mandas a la horny jail a alguien horny.')
    async def horny(self, ctx, user):
        """Mandas a la horny jail a alguien horny."""
        embed = discord.Embed(colour=discord.Colour(0x9013fe))

        try:
            embed.add_field(name="â€Ž", value=f"""**<@!{ctx.author.id}>** mandÃ³ a **{user}** a la Horny Jail""")
        except discord.ext.commands.errors.MissingRequiredArgument:
            embed.add_field(name="â€Ž", value=f"""**<@!{ctx.author.id}>** estÃ¡ horny. Tened cuidado :0""")

        embed.set_image(url="https://media1.tenor.com/images/062ed2c1ab2756d774367ef0f8a1f53b/tenor.gif?itemid=17582752")
        await ctx.send(embed=embed)

    @commands.command(name='bonk',
                      brief='bonk.')
    async def bonk(self, ctx, user):
        """bonk."""
        actionUser = ctx.message.content.replace("d.bonk ", "")
        embed = discord.Embed(colour=discord.Colour(0x9013fe))
        embed.add_field(name="â€Ž", value=f"""Bonk a  **{actionUser}** de parte de **<@!{ctx.author.id}>**""")
        embed.set_image(
            url="https://media1.tenor.com/images/ae34b2d6cbac150bfddf05133a0d8337/tenor.gif?itemid=14889944")
        await ctx.send(embed=embed)
        #bonk.

def setup(bot):
    bot.add_cog(Acciones(bot))


# Import Libraries #
import argparse
import torch
from collections import OrderedDict
from os.path import isdir
from torch import nn
from torch import optim
from torchvision import datasets, transforms, models

# Define function that parses arguments to run from the command line, all arguments are optional
def arg_parser():
    parser = argparse.ArgumentParser(description="Image Classifier Settings")

    # define architecture from the model
    parser.add_argument('--arch',
                        type=str)

    # define checkpoint directory
    parser.add_argument('--save_dir',
                        type=str)

    parser.add_argument('--learningrate',
                        type=float)

    parser.add_argument('--hidden_units',
                        type=int)

    parser.add_argument('--epochs',
                        type=int)

    parser.add_argument('--gpu',
                        action="store_true")

    # Parse arguments
    args = parser.parse_args()
    return args

# define function training data transformer
def traindata_transformer(train_dir):
   # Define transformation
   train_transforms = transforms.Compose([transforms.RandomRotation(30),
                                          transforms.RandomResizedCrop(224),
                                          transforms.RandomHorizontalFlip(),
                                          transforms.ToTensor(),
                                          transforms.Normalize([0.485, 0.456, 0.406],
                                                               [0.229, 0.224, 0.225])])
    # Load the Data
   train_image_datasets = datasets.ImageFolder(train_dir, transform=train_transforms)
   return train_image_datasets

#define function valid data transformer
def validdata_transformer(valid_dir):
    valid_transforms = transforms.Compose([transforms.Resize(256),
                                           transforms.CenterCrop(224),
                                           transforms.ToTensor(),
                                           transforms.Normalize([0.485, 0.456, 0.406],
                                                                [0.229, 0.224, 0.225])])

    valid_image_datasets = datasets.ImageFolder(valid_dir, transform=valid_transforms)
    return valid_image_datasets

# define fucntion test data transformer
def testdata_transformer(test_dir):
   test_transforms = transforms.Compose([transforms.Resize(256),
                                         transforms.CenterCrop(224),
                                         transforms.ToTensor(),
                                         transforms.Normalize([0.485, 0.456, 0.406],
                                                              [0.229, 0.224, 0.225])])
    # Load the Data
   test_image_datasets = datasets.ImageFolder(test_dir, transform=test_transforms)
   return test_image_datasets

# define function to load data
def data_loader(data, train=True):
    if train:
        loader = torch.utils.data.DataLoader(data, batch_size=64, shuffle=True)
    else:
        loader = torch.utils.data.DataLoader(data, batch_size=64)
    return loader

# Define function to check available device
def check_device(gpucpu):
    if not gpucpu:
        return torch.device("cpu")

    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

    return device

# define pretrained model alexnet
def pretrained_model(architecture = 'alexnet'):

    if type(architecture) == type(None):
        model = models.alexnet (pretrained = True)
        model.name = 'alexnet'
    else:
        exec("model = models.{}(pretrained=True)".format(architecture))
        model.name = architecture

    for param in model.parameters():
        param.requires_grad = False
    return model

# define function model classifer
def model_classifier(model, hidden_units):

    if type(hidden_units) == type(None):
        hidden_units = 4096

    # Define the model classifier uwing sequential with OrderedDict
    classifier = nn.Sequential(OrderedDict([
                          ('linear1', nn.Linear(9216, hidden_units)),
                          ('relu1', nn.ReLU()),
                          ('drop1', nn.Dropout(p=0.5)),
                          ('linear2', nn.Linear(hidden_units, 2048)),
                          ('output1', nn.LogSoftmax(dim=1))
                          ]))

    return classifier

# define validation of model function
def modelvalidation(model, valid_loader, criterion, device):
    model.to(device)

    valid_loss = 0
    accuracy = 0
    for inputs, labels in valid_loader:

        inputs, labels = inputs.to(device), labels.to(device)
        output = model.forward(inputs)
        valid_loss += criterion(output, labels).item()

        ps = torch.exp(output)
        equality = (labels.data == ps.max(dim=1)[1])
        accuracy += equality.type(torch.FloatTensor).mean()

    return valid_loss, accuracy

# define training of model
def modeltrainer(model, train_loader, valid_loader, device, criterion, optimizer, epochs, print_every, steps):

    if type(epochs) == type(None):
        epochs = 5

    print("Training process started")

    for e in range(epochs):
        running_loss = 0
        model.train()
        accuracy_train = 0

        for ii, (inputs, labels) in enumerate(train_loader):
            steps += 1

            inputs, labels = inputs.to(device), labels.to(device)

            optimizer.zero_grad()

            # Forward and backward pass
            outputs = model.forward(inputs)
            loss = criterion(outputs, labels)
            loss.backward()
            optimizer.step()

            running_loss += loss.item()
            ps_train = torch.exp(outputs).data
            equality_train = (labels.data == ps_train.max(1)[1])
            accuracy_train += equality_train.type_as(torch.FloatTensor()).mean()

            if steps % print_every == 0:
                model.eval()

                with torch.no_grad():
                    valid_loss, accuracy = modelvalidation(model, valid_loader, criterion, device)

                print("Epoch: {}/{} |".format(e+1, epochs),
                  "Training Loss: {:.4f}..".format(running_loss/print_every),
                  "Validation Loss: {:.4f}..".format(valid_loss/len(valid_loader)),
                  "Training Accuracy: {:.4f}".format(accuracy_train/len(train_loader)),
                  "Validation Accuracy: {:.4f}".format(accuracy/len(valid_loader)))

                running_loss = 0
                model.train()

    return model

# define validate model accuracy rate
def validatemodel(model, test_loader, device):

    # Do validation on the test set
    correct = 0
    total = 0
    with torch.no_grad():
        model.eval()
        for data in test_loader:
            images, labels = data
            images, labels = images.to(device), labels.to(device)
            outputs = model(images)
            _, predicted = torch.max(outputs.data, 1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()

    print('Accuracy: %d%%' % (100 * correct/total))

# define function to save checkpoint
def dircheckpoint(model, train_data):

    # Create `class_to_idx` attribute in model
    model.class_to_idx = train_data.class_to_idx

    # Create checkpoint dictionary
    checkpoint = {'classifier': model.classifier,
    'class_to_idx': model.class_to_idx,
    'state_dict': model.state_dict()}

    # Save checkpoint
    torch.save(checkpoint, 'savedcheckpoint.pth')

def main():

    # Get Keyword Args for Training
    args = arg_parser()

    # define directory
    data_dir = 'flowers'
    train_dir = data_dir + '/train'
    valid_dir = data_dir + '/valid'
    test_dir = data_dir + '/test'

    #transform data
    train_data = traindata_transformer(train_dir)
    valid_data = validdata_transformer(valid_dir)
    test_data = testdata_transformer(test_dir)

    #load data
    train_loader = data_loader(train_data)
    valid_loader = data_loader(valid_data, train=False)
    test_loader = data_loader(test_data, train=False)

    # call pretrained model function
    model = pretrained_model(architecture=args.arch)

    # Call classifier function
    model.classifier = model_classifier(model,
                                        hidden_units=args.hidden_units)

    # Check for device
    device = check_device(gpucpu=args.gpu)

    # Send model to device
    model.to(device)

    # Assign learning rate
    if type(args.learningrate) == type(None):
        learningrate = 0.001
    else: learningrate = args.learningrate

    # Define loss and optimizer
    criterion = nn.NLLLoss()
    optimizer = optim.Adam(model.classifier.parameters(), lr=learningrate)

    # Define number of passes and print loss every batch of 50 images
    print_every = 50
    steps = 0

    trained_model = modeltrainer(model, train_loader, valid_loader, device, criterion, optimizer, args.epochs, print_every, steps)

    print("Training process completed")

    # call validate model function
    validatemodel(trained_model, test_loader, device)

    # call save checkpoint function
    dircheckpoint(trained_model, train_data)

# Run Program
if __name__ == '__main__': main()


from darkflow.net.build import TFNet
import cv2
import os
import json

options = {"model":"./cfg/yolo.cfg","load": "./yolo.weights", "threshold": 0.25,"gpu":1}
tfnet = TFNet(options)

def car_detection(input_image,output_image):

  filename = os.path.basename(input_image)
  output_dict = {"filename":filename,
                 "label":0,
                 "width":0,
                 "height":0,
                 "num_of_points":0}

  imgcv = cv2.imread('%s' % input_image)

  output_dict["height"] = imgcv.shape[0]
  output_dict["width"] = imgcv.shape[1]

  result = tfnet.return_predict(imgcv)

  #result = tfnet.return_predict(frame)

  num_of_points = 0
  kigou = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

  for item in result:
    tlx = item['topleft']['x']
    tly = item['topleft']['y']
    brx = item['bottomright']['x']
    bry = item['bottomright']['y']
    label = item['label']
    conf = item['confidence']

    center_x = int(tlx + (brx - tlx)/2)
    center_y = int(tly + (bry - tly)/2)

    if label == 'car' or label == 'bus' or label == 'truck':
      num_of_points += 1

      newdict = {"%s" % kigou[num_of_points-1]:{"x":center_x,"y":center_y}}
      output_dict["num_of_points"] = num_of_points
      output_dict.update(newdict)

      cv2.rectangle(imgcv, (tlx, tly), (brx, bry), (0,0,255), 5)
      text = label + " " + ('%.2f' % conf)
      cv2.rectangle(imgcv, (tlx, tly - 15), (tlx + 100, tly + 5), (0,0,255), -1)
      cv2.putText(imgcv, text, (tlx, tly), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,0), 1)
      cv2.circle(imgcv, (center_x, center_y), 15, (255, 255, 0), -1)
    else:
      pass

  cv2.imwrite('%s' % output_image, imgcv)

  f = open('./images_testing/images_testing.json','a')
  f.write(',\n')
  json.dump(output_dict, f, indent=2, separators=(',',':'))
  f.close()

  print('%s' % output_image)
  #print(output_dict)

def resize(input_image,output_image):
  imgcv = cv2.imread('%s' % input_image)
  #hight = imgcv.shape[0]
  #width = imgcv.shape[1]

  image_resized = cv2.resize(imgcv, (1080, 1440))
  cv2.imwrite('%s' % output_image, image_resized)

  print('%s' % output_image)

if __name__ == '__main__':
  car_detection('./image04.jpg','./output/04/output01.jpg')


# << 뮤직카우의 곡별 정보 크롤링 코드 >>
# 작성자 : 정예원
#
# 코드설명
# [[ 뮤직카우 정보란에 '1,2차 옥션결과' 와 '저작권 정보' 를 모으는 코드 입니다 ]]
# 1. 곡 페이지 링크, 1,2 차 옥션 결과 , 공표일자, 저작권료 지분  을 크롤링 합니다.
# 2. 크롤링된 데이터는 musicInfo 명의 콜렉션으로 디비에 저장됩니다.
# 3. 한번 크롤링된 데이터는 변동되지 않으므로 다시 크롤링 할 필요가 없기 때문에,
#    musicCowData에 있는, 그러나 musicInfo에 없는 곡들에 대해서만 크롤링을 합니다.
# 4. musicInfo 에 저장되는 song_title과 song_artist는 따로 split 을 거치지 않은 뮤직카우 에 등록된 곡명과 가수명 입니다.
# 5. 크롤링 완료 후 다시 코드를 돌리면 "이미 musicInfo에 모든 데이터가 들어있습니다" 메시지를 print 합니다.
#
# 코드 수행시간 : 5분

import requests
import re
from bs4 import BeautifulSoup
from pymongo import MongoClient
import numpy as np

def musicInfoCrawler(col1, col4):
    musicInfoSongNumListCurrent = col4.find({}, {'num': {"$slice": [1, 1]}})  # 현재 musicInfoData 디비에 있는 곡 번호 리스트
    musicCowSongNumListCurrent = col1.find({}, {'num': {"$slice": [1, 1]}})
    # 현재 musicCowData <-> musicInfoData 디비 비교했을 때, "musicCowData에 있는, 그러나 musicInfo에 없는 곡"들을 정확히 찾아내기 위해
    # 정확히 지금 현재 시점에서 musicCowData 에 있는 곡들을 다시 한번 탐색하여 self.musicCowSongNumCurrent 변수에 할당.

    songList = []  # musicCowData에 있는, 그러나 musicInfo에 없는 곡
    for x in musicCowSongNumListCurrent:
        songList.append(x['num'])
    for x in musicInfoSongNumListCurrent:
        if x['num'] in songList:
            songList.remove(x['num'])

    if len(songList) == 0:
        print("이미 musicInfo에 모든 데이터가 들어있습니다")
    else:
        for x in songList:
            page = "https://www.musicow.com/song/{0}?tab=info".format(x)
            url = requests.get(page)
            html = url.text
            soup = BeautifulSoup(html, 'html.parser')

            song_title = str(soup.select('div.song_header > div.song_header--bar.song_header--bar_1 > div.song_header--title.txt_ellipsis > strong'))
            song_title = re.sub('\<.+?>|\[|\]', '', song_title, 0).replace('&', '&').strip()

            #print("{0}번 곡 확인 중".format(x))

            crawl_link(x, col4, soup, page, song_title)

        print("========= << 곡 information 크롤링을 마쳤습니다 >> ========== ")

def crawl_link(x, col4, soup, page, song_title):
    print("{0}번 곡 뮤직카우 크롤링 시작".format(x))

    song_artist = str(soup.select('div.card_body > div > dl > dd:nth-child(4)'))
    song_artist = re.sub('\<.+?>|\[|\'|\]', '', song_artist, 0).replace('&', '&').strip()

    auc_date_1 = str(soup.select('div:nth-child(1) > h2 > small'))
    auc_date_1 = re.sub('\<.+?>|\[|\'|\]', '', auc_date_1, 0).strip()
    auc_date_1_start = auc_date_1.split('~')[0].strip()
    auc_date_1_end = auc_date_1.split('~')[1].strip()

    auc_stock_1 = str(soup.select('div.card_body > div > div:nth-child(1) > dl > dd:nth-child(2)'))
    auc_stock_1 = re.sub('\<.+?>|\[|\'|\]|\,', '', auc_stock_1, 0).replace('주','').strip()
    auc_price_1 = str(soup.select('div.card_body > div > div:nth-child(1) > dl > dd:nth-child(8)'))
    auc_price_1 = re.sub('\<.+?>|\[|\'|\]|\,', '', auc_price_1, 0).replace('캐쉬','').strip()

    auc_date_2 = str(soup.select('div:nth-child(2) > h2 > small'))
    auc_date_2 = re.sub('\<.+?>|\[|\'|\]', '', auc_date_2, 0).strip()
    if auc_date_2[0:-1] == '':
        # None 말고 NaN과 0 이라는 값 넣은 이유는 string과 int로 type 통일하기 위해서
        auc_date_2_start = np.nan; auc_date_2_end = np.nan
        auc_stock_2 = np.nan; auc_price_2 = np.nan
    else:
        auc_date_2_start = auc_date_2.split('~')[0].strip()
        auc_date_2_end = auc_date_2.split('~')[1].strip()

    auc_stock_2 = str(soup.select('div.card_body > div > div:nth-child(2) > dl > dd:nth-child(2)'))
    auc_stock_2 = re.sub('\<.+?>|\[|\'|\]|\,', '', auc_stock_2, 0).replace('주','').strip()
    auc_price_2 = str(soup.select('div.card_body > div > div:nth-child(2) > dl > dd:nth-child(8)'))
    auc_price_2 = re.sub('\<.+?>|\[|\'|\]|\,', '', auc_price_2, 0).replace('캐쉬','').strip()

    song_release_date = str(soup.select('div.card_body > div > dl > dd:nth-child(2)'))
    song_release_date = re.sub('\<.+?>|\[|\'|\]', '', song_release_date, 0).strip()

    # stock_num 앞뒤 공백 제거 후 숫자만 추출
    stock_num = str(soup.select('div.lst_copy_info dd p')).split('2차적')[0]
    stock_num = re.sub('\<.+?>|\[|\'|\]|\t|\n|\,', '', stock_num, 0).replace('1/','').strip()

    print("{0}번 곡 DB 입력 중".format(x))

    list_music = {
        'num': x,
        'song_title': song_title,
        'song_artist': song_artist,
        'page': page,
        'auc1_info': {
            'auc_start_date': auc_date_1_start, 'auc_end_date': auc_date_1_end,
            'auc_stock': auc_stock_1, 'auc_price': auc_price_1},
        'auc2_info': {
            'auc_start_date': auc_date_2_start, 'auc_end_date': auc_date_2_end,
            'auc_stock': auc_stock_2, 'auc_price': auc_price_2},
        'song_release_date': song_release_date,
        'stock_num': stock_num
    }

    col4.insert_one(list_music).inserted_id


# lst=[1,2,3,5,6,7,12,23,22,34,56,'khan','ali','anything']
# for i in lst:
#     if i> 6:
#         print(i)
    # else:
    #     print('not found')

# while(True):
#     x=int(input("enter number\n"))
#     if x>100:
#         print("congrate u put grater value then 100\n")
#         break
#     else:
#         print("try again grater value then 100\n")
#         continue

no=20
guess=1
while(guess<=5):

    print("enter number for guessing..")
    x = int(input(""))
    if x<no:
        print(f"the {x} is to small\n")
    elif x>no:
        print(f"you enter {x}is to large ")

    else:
        print(f"you select right number is {x} ")
        print(f"u guess in {guess} time\n you win")
        break
    print(5-guess,"number of gusses left")
    guess+=1

else:
    if guess>5:
        print("ggame is ove")


distance = float(input('What is the distance?  '))
unit = input('What is the starting unit?  ')
unit2 = input('What unit do you want to convert to?  ')

if unit == 'ft':
    result = distance * 0.3048
elif unit == 'mi':
    result = distance * 1609.34
elif unit == 'm':
    result = distance
elif unit == 'km':
    result = distance * 1000
elif unit == 'yard':
    result = distance * 0.9144
elif unit == 'inch':
    result = distance * 0.0254

print(result)

if unit2 == 'ft':
    print(result/0.3048)
elif unit2 == 'mi':
    print(result/1609.34)
elif unit2 == 'm':
    print(result)
elif unit2 == 'km':
    print(result/1000)
elif unit2 == 'yard':
    print(result/0.9144)
elif unit2 == 'inch':
    print(result/0.0254)


""" Rolling a random die 6,000,000 times """

# Importing required library

import random

# Initializing the frequency counters

freq_1 = 0

freq_2 = 0

freq_3 = 0

freq_4 = 0

freq_5 = 0

freq_6 = 0

#6,000,000 die rolls

for roll in range(6000000):

    face = random.randrange(1 , 7)

    if face == 1:

        freq_1 += 1

    elif face == 2:

        freq_2 += 1

    elif  face == 3:

        freq_3 += 1

    elif face == 4:

        freq_4 += 1

    elif  face == 5:

        freq_5 += 1

    else:
        freq_6 += 1

print(f"Face{'Frequency':>13}")
print(f'{1:>4}{freq_1:>13}')
print(f'{2:>4}{freq_2:>13}')
print(f'{3:>4}{freq_3:>13}')
print(f'{4:>4}{freq_4:>13}')
print(f'{5:>4}{freq_5:>13}')
print(f'{6:>4}{freq_6:>13}')


class Character():
    def __init__(self, x, y, speed_x, speed_y, name):
        self.name = name
        self.x = x
        self.y = y
        self.speed_x = 0
        self.speed_y = 0

    def move(self):
        self.x += self.speed_x
        self.y += self.speed_y
        if self.x > 512 - 64:
            self.x = 512 - 64
        if self.x < 32:
            self.x = 32
        if self.y > 480 - 64:
            self.y = 480 - 64
        if self.y < 32:
            self.y = 32


import datamanage
import datetime

if __name__=='__main__':
    dm = datamanage.datamanage(startdate=(datetime.datetime.today()-datetime.timedelta(5)).strftime('%Y%m%d'))
    dm.getstocksdaily()
    dm.getbasicdaily()
    dm.getindexdaily()
    dm.getadjfactor()
    dm.getfundsdaily()


# Base class for consumer entities
from random import random
from numpy.random import normal
import accounts

class Consumer:
    def __init__(self, env):
        self.env = env

        self.abnormal_size  = False
        self.desire         = normal(self.env.mean_desire, self.env.std_desire)
        self.num_shoes_want = 1 if random() < self.env.desire_threshold else 2
        self.money          = normal(self.env.average_mean_money, self.env.average_std_money)
        self.identity       = "average"
        self.has_loyalty    = random() < self.env.average_prob_loyal
        self.shoes_acquired = 0
        self.influence      = 0
        self.proxy          = self.desire
        self.got_shoes      = False
        self.prob_loyal     = self.env.average_prob_loyal
        self.main_account   = accounts.Account(self)
        self.fake_accounts  = [accounts.Account(self)] if self.num_shoes_want > 1 else []

        self.authorized_fake_accounts = []

    def buy_shoes(self, cap):
        self._buy_shoes(min(cap, self.num_shoes_want - self.shoes_acquired, self.env.num_shoes))
        if self.shoes_acquired > 0 : self.got_shoes = True

    def reset(self):
        self.shoes_acquired = 0

    def _buy_shoes(self, num_to_buy):
        self.env.num_shoes = self.env.num_shoes - num_to_buy
        self.shoes_acquired += num_to_buy

class AverageConsumer(Consumer):
    pass

class AbnormalConsumer(Consumer):
    def __init__(self, env):
        Consumer.__init__(self, env)
        self.abnormal_size = True
        self.identity      = "abnormal"

class SpecialConsumer(Consumer):
    def __init__(self, env):
        Consumer.__init__(self, env)
        self.num_shoes_want = 2
        self.identity       = "special"

    def buy_shoes(self, cap):
        # special consumer will not buy 1 pair, only 2 pairs
        if self.env.num_shoes >= 2 and cap > 1 and self.shoes_acquired < 2:
            self._buy_shoes(2)
            self.got_shoes = True

class WealthyConsumer(Consumer):
    def __init__(self, env):
        Consumer.__init__(self, env)
        self.money          = normal(self.env.rich_mean_money, self.env.rich_std_money)
        self.has_loyalty    = random() < self.env.rich_prob_loyal
        self.identity       = "wealthy"
        self.influence      = 0.5
        self.fake_accounts  = [accounts.Account(self)]  # wealthy always have at least one fake account
        self.proxy          = self.proxy + 0.1

        if self.num_shoes_want > 1:
            self.fake_accounts.append(accounts.Account(self))

    def buy_shoes(self, cap):
        self._buy_shoes(min(cap, self.num_shoes_want + 1 - self.shoes_acquired, self.env.num_shoes))
        if self.shoes_acquired > 0 : self.got_shoes = True

class InfluencerConsumer(AverageConsumer):
    def __init__(self, env):
        AverageConsumer.__init__(self, env)
        self.identity                 = "influencer"
        self.num_shoes_want           = 1
        self.main_account.has_loyalty = False    # to simplify invite only mechanism
        self.influence                = 1
        self.fake_accounts            = []       # influencers do not create fake accounts
        self.influence                = 0.5

class ResellerConsumer(Consumer):
    def __init__(self, env):
        Consumer.__init__(self, env)
        self.desire         = 0
        self.proxy          = normal(self.env.mean_desire, self.env.std_desire)
        self.num_shoes_want = 100
        self.money          = 100000
        self.has_loyalty    = random() < self.env.reseller_prob_loyal
        self.identity       = "reseller"
        self.influence      = 0.5
        self.authenticated_fakes = [accounts.Account(self) for _ in range(7)]     # 20 fake accounts total
        self.fake_accounts = self.authorized_fake_accounts + [accounts.Account(self) for _ in range(13)]


from copy import copy
import sys
import threading
import wx

import Conversion

class VirtualListCtrl(wx.ListCtrl):
    def __init__(self, cols, dataFunc, parent, customDataToStringFuncs=[], rowIdCol=None, allowSort=True, defaultSortCol='', defaultSortDirection='ASC', id=-1,
                 pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.LC_REPORT | wx.LC_VIRTUAL | wx.LC_VRULES | wx.CLIP_CHILDREN, **kwargs):
        wx.ListCtrl.__init__(self, parent, id, pos, size, style, **kwargs)
        """
        cols:
            [(*columnName*, *dataKeyword*, *dataType*, *columnWidth*), ...]
        """
        self.dataFunc = dataFunc

        #get a copy of the converter dicts
        self.dataToStringFuncs = copy(Conversion.dataToStringFuncs)

        #add custom funcs
        for funcTup in customDataToStringFuncs:
            if not funcTup[0] in self.dataToStringFuncs:
                self.dataToStringFuncs[funcTup[0]]=funcTup[1]

        #image stuff
        self.imageList, self.images = self._createColSortImages()
        self.SetImageList(self.imageList, wx.IMAGE_LIST_SMALL)

        #columns
        self.rowIdCol = rowIdCol
        self.defaultSortCol = defaultSortCol
        self.defaultSortDirection = defaultSortDirection
        self.allowSort = allowSort

        self.colDefaults = cols #default column data (size and so on)
        self._initColumns(cols) #sets class vars!

        #lock
        self.lock = threading.RLock() #guess...

        #events
        if self.allowSort:
            self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick, self) #sort on col click
        self.Bind(wx.EVT_LIST_COL_RIGHT_CLICK, self.OnColRightClick, self) #display options on right click on col
        self.Bind(wx.EVT_LIST_COL_END_DRAG, self.OnColResize, self) #update the size info for the resized column

        #tell ListCtrl how many items we currently have
        self.SetItemCount(0)

    ##internal functions - images

    def _createColSortImages(self):
        imageList = wx.ImageList(15, 15, mask=True)
        images = {}
        for imageName, imageIdent in (('arrowUp', wx.ART_GO_UP), ('arrowDown', wx.ART_GO_DOWN)):
            #add one image to the list
            orgImg = wx.ArtProvider_GetBitmap(imageIdent, wx.ART_OTHER, (14,14)).ConvertToImage()
            if (not isinstance(orgImg, type(wx.NullBitmap))) and sys.platform[:5] == 'linux' and orgImg.HasAlpha():
                #looks ok, init empty new image
                newImg = wx.EmptyImage(15, 15, clear=True)
                newImg.InitAlpha()
                for x in xrange(0, 15):
                    for y in xrange(0, 15):
                        newImg.SetAlpha(x, y, 0)

                #copy original image into new one
                newImg.Paste(orgImg.GetSubImage((1,0,12,12)), 1, 2)
                if orgImg.HasAlpha():
                    for x in xrange(0, 12):
                        for y in xrange(0, 12):
                            newImg.SetAlpha(x+1, y+2, orgImg.GetAlpha(x+1, y))

            else:
                #this looks borked (Windows?), draw bitmap from scratch
                orgImg = wx.EmptyBitmap(15, 15)
                memDc = wx.MemoryDC()
                memDc.SelectObject(orgImg)

                #draw background
                memDc.SetPen(wx.Pen('WHITE', 1))
                memDc.SetBrush(wx.Brush('WHITE', wx.SOLID))
                memDc.DrawRectangle(0, 0, 15, 15)

                #draw triangle
                memDc.SetPen(wx.Pen('BLACK', 1))
                memDc.SetBrush(wx.Brush('BLACK', wx.SOLID))
                if imageIdent is wx.ART_GO_UP:
                    memDc.DrawPolygon(((3,11), (11,11), (7,3)))
                elif imageIdent is wx.ART_GO_DOWN:
                    memDc.DrawPolygon(((3,3), (11,3), (7,11)))

                memDc.SelectObject(wx.NullBitmap)

                #convert to image, apply alpha
                newImg = orgImg.ConvertToImage()
                newImg.InitAlpha()
                for x in xrange(0, 15):
                    for y in xrange(0, 15):
                        if newImg.GetGreen(x, y) == 0:
                            #black
                            newImg.SetAlpha(x, y, 95)
                        else:
                            #white
                            newImg.SetAlpha(x, y, 0)

            #finally convert back to bitmap and store in dict
            images[imageName] = imageList.Add(newImg.ConvertToBitmap())

        return imageList, images

    def _applyColSortImages(self, sortColumn, sortDirection):
        self.ClearColumnImage(self.sortColumn)
        if sortDirection == 'ASC':
            self.SetColumnImage(sortColumn, self.images['arrowDown'])
        else:
            self.SetColumnImage(sortColumn, self.images['arrowUp'])

    ##internal functions - columns

    def _createColumnInfo(self, cols):
        #cols = [(*columnName*, *dataKeyword*, *dataType*, *columnWidth*, *active*), ...]

        colInfo = {}   #columns info stuff
        colMapper = [] #maps a column name to a position

        #build up mapper and info dict
        place = 0
        while place < len(cols):
            #process one col
            colSet = cols[place]
            colInfo[colSet[0]] = {'dataKeyword':colSet[1],
                                  'dataType':colSet[2],
                                  'columnWidth':colSet[3]}
            if colSet[4]:
                #active column
                colMapper.append(colSet[0])
            place += 1
        return colInfo, colMapper

    def _applyColumnInfo(self, colInfo, colMapper):
        #create the 'real' (=gui) columns
        for i in xrange(0, len(colMapper)):
            colName = colMapper[i]
            self.InsertColumn(i, colName)
            self.SetColumnWidth(i, colInfo[colName]['columnWidth'])

    def _createColumns(self, colInfo, colMapper):
        #create the columns itself
        self._applyColumnInfo(colInfo, colMapper)

        #set class vars
        self.colInfo = colInfo            #column info
        self.colMapper = colMapper        #maps a column name to a position
        self.colNum = len(self.colMapper) #number of columns
        self.colData = dict(((colName, []) for colName in self.colInfo)) #row data, per column one list

    def _initColumns(self, cols):
        #initialises everything columns related
        colInfo, colMapper = self._createColumnInfo(cols)
        self._createColumns(colInfo, colMapper)

        #index of the column, which is used for sorting
        if self.defaultSortCol in colMapper:
            self.sortColumn = colMapper.index(self.defaultSortCol)
        else:
            self.sortColumn = 0
        self.sortDirection = self.defaultSortDirection #sort direction, either ASC or DESC
        self._applyColSortImages(self.sortColumn, self.sortDirection)

    def _resetColumns(self):
        #reset everything back to the defaults
        self.DeleteAllColumns()                                         #remove all existing columns
        colInfo, colMapper = self._createColumnInfo(self.colDefaults)   #build the needed vars out of the defaults
        self._createColumns(colInfo, colMapper)                         #create new columns according to these default

        #index of the column, which is used for sorting
        if self.defaultSortCol in colMapper:
            self.sortColumn = colMapper.index(self.defaultSortCol)
        else:
            self.sortColumn = 0
        self.sortDirection = self.defaultSortDirection #sort direction, either ASC or DESC
        self._applyColSortImages(self.sortColumn, self.sortDirection)
        self.dataUpdate() #refill the columns

    ##internal functions - data

    def _dataUpdate(self, data):
        oldDataAmount = len(self.colData[self.colMapper[0]])

        #remember selected rows if possible
        if self.rowIdCol is not None:
            rowIdColData = self.colData[self.rowIdCol]
            selectedRows = self._getSelectedRows()
            selectedRowIds = [rowIdColData[rowIdx] for rowIdx in selectedRows if rowIdx < len(rowIdColData)]
            for rowIdx in selectedRows:
                self.Select(rowIdx, on=0)

        #create sort list
        colName = self.colMapper[self.sortColumn]
        dataKeyword = self.colInfo[colName]['dataKeyword']
        if type(dataKeyword)==str:
            #single item
            sortList = (row[dataKeyword] for row in data)
        else:
            #multiple items
            sortList = []
            for row in data:
                sortList.append([row[singleDataKeyword] for singleDataKeyword in dataKeyword])

        #add row index
        sortList = map(lambda tup: (tup[1], tup[0]), enumerate(sortList))

        #sort the list
        sortList.sort(reverse=(self.sortDirection == 'DESC'))

        #create new data list
        for colName in self.colData.keys():
            #fill one column
            colDataKeyword = self.colInfo[colName]['dataKeyword']
            if type(colDataKeyword)==str:
                #only a single data item
                self.colData[colName] = [data[rowNum][colDataKeyword] for rowData, rowNum in sortList]

            else:
                #multiple data items
                colData = []
                for rowData, rowNum in sortList:
                    colData.append([data[rowNum][singleDataKeyword] for singleDataKeyword in colDataKeyword])
                self.colData[colName] = colData

        #set new item length if rows got added or removed
        newDataAmount = len(sortList)
        if newDataAmount != oldDataAmount:
            self.SetItemCount(newDataAmount)

        #restore row selection if possible
        if self.rowIdCol is not None:
            rowIdColData = self.colData[self.rowIdCol]
            selectedRows = [rowIdColData.index(rowId) for rowId in selectedRowIds if rowId in rowIdColData]
            for rowIdx in sorted(selectedRows):
                self.Select(rowIdx, on=1)

        #refresh currently displayed items
        firstDisplayedRow = self.GetTopItem()
        lastDisplayedRow = min(firstDisplayedRow + self.GetCountPerPage(), newDataAmount)
        self.RefreshItems(firstDisplayedRow, lastDisplayedRow)

        #windows is a bit strange and requires this call (the "RefreshItems" call should do the same ...)
        if sys.platform[:3] == 'win':
            if newDataAmount >= oldDataAmount:
                self.Refresh(False)
            else:
                self.Refresh(True)

    ##internal functions - columns

    def _disableCol(self, colName):
        if self.colNum > 1 and not (self.allowSort == False and self.defaultSortCol == colName):
            #ok to disable column, its not the last one
            colPos = self.colMapper.index(colName)
            del self.colMapper[colPos]
            self.colNum -= 1
            self.DeleteColumn(colPos)

            #clean the whole sorting stuff up
            if self.sortColumn == colPos:
                #we deleted the row which is used for sorting, default back to the first col
                self.sortColumn = 0
                self.sortDirection = 'ASC'
                self._applyColSortImages(self.sortColumn, self.sortDirection)

            elif self.sortColumn > colPos:
                #we sort depending on a column which is after the deleted column
                self.sortColumn -= 1

        self.Refresh()

    def _enableCol(self, colName, colPos):
        if colPos is None:
            colPos = self.colNum

        #add col
        self.InsertColumn(colPos, colName)
        self.SetColumnWidth(colPos, self.colInfo[colName]['columnWidth'])
        self.colMapper.insert(colPos, colName)
        self.colNum += 1

        #cleanup sorting
        if self.sortColumn >= colPos:
            #we added a row before or at the position of the sorting column
            self.sortColumn += 1

        self.dataUpdate()

    def _moveCol(self, colName, direction):
        colPos = self.colMapper.index(colName)
        if (colPos + direction) >= 0 and (colPos + direction) < self.colNum:
            self.DeleteColumn(colPos)
            self.InsertColumn(colPos + direction, colName)
            self.SetColumnWidth(colPos + direction, self.colInfo[colName]['columnWidth'])
            del self.colMapper[colPos]
            self.colMapper.insert(colPos + direction, colName)

            #clean the whole sorting stuff up
            if direction < 0 and self.sortColumn < colPos and self.sortColumn >= colPos+direction:
                self.sortColumn += 1

            elif direction > 0 and self.sortColumn > colPos and self.sortColumn <= colPos+direction:
                self.sortColumn -= 1

            elif self.sortColumn == colPos:
                self.sortColumn += direction

            self._applyColSortImages(self.sortColumn, self.sortDirection)

        self.dataUpdate()

    ##internal functions - events

    def _onColClick(self, event):
        clickedCol = event.GetColumn()
        if not clickedCol == self.sortColumn:
            #use another column for sorting stuff
            self._applyColSortImages(clickedCol, 'ASC')
            self.sortColumn = clickedCol
            self.sortDirection = 'ASC'
        else:
            #just reverse sorting order
            if self.sortDirection == 'ASC':
                self._applyColSortImages(self.sortColumn, 'DESC')
                self.sortDirection = 'DESC'
            else:
                self._applyColSortImages(self.sortColumn, 'ASC')
                self.sortDirection = 'ASC'

        self.dataUpdate()

    def _onColRightClick(self, event):
        cols = []
        for colName in self.colData.iterkeys():
            active = (colName in self.colMapper)
            cols.append((colName, active))
        cols.sort()

        clickedCol = event.GetColumn()
        if clickedCol == -1:
            merk = ColumnSelectionPopup(cols, self, None, None, None)
        else:
            merk = ColumnSelectionPopup(cols, self, self.colMapper[clickedCol], clickedCol, len(self.colMapper))
        self.PopupMenu(merk)

    def _onColResize(self, event):
        resizedColNum = event.GetColumn()
        resizedColName = self.colMapper[resizedColNum]
        newSize = self.GetColumnWidth(resizedColNum)
        self.colInfo[resizedColName]['columnWidth'] = newSize

    ##internal functions - other

    def _getRowCount(self):
        return len(self.colData[self.colMapper[0]])

    def _getRawData(self, colName, rowIndex):
        return self.colData[colName][rowIndex]

    def _getSelectedRows(self):
        selectedRows = []
        selected = self.GetFirstSelected()
        while not selected==-1:
            selectedRows.append(selected)
            selected = self.GetNextSelected(selected)
        return selectedRows

    ##external functions - data

    def getRawData(self, colName, rowIndex):
        self.lock.acquire()
        data = self._getRawData(colName, rowIndex)
        self.lock.release()
        return data

    def getSelectedRows(self):
        self.lock.acquire()
        rows = self._getSelectedRows()
        self.lock.release()
        return rows

    def clear(self):
        self.lock.acquire()
        self._dataUpdate([])
        self.lock.release()

    def dataUpdate(self):
        self.lock.acquire()
        data = self.dataFunc()
        self._dataUpdate(data)
        self.lock.release()

    ##external functions - columns

    def disableCol(self, colName):
        self.lock.acquire()
        self._disableCol(colName)
        self.lock.release()

    def enableCol(self, colName, colPos=None):
        self.lock.acquire()
        self._enableCol(colName, colPos)
        self.lock.release()

    def moveCol(self, colName, direction):
        self.lock.acquire()
        self._moveCol(colName, direction)
        self.lock.release()

    def resetCols(self):
        self.lock.acquire()
        self._resetColumns()
        self.lock.release()

    ##external functions - events

    def OnColClick(self, event):
        self.lock.acquire()
        self._onColClick(event)
        self.lock.release()

    def OnColRightClick(self, event):
        self.lock.acquire()
        self._onColRightClick(event)
        self.lock.release()

    def OnColResize(self, event):
        self.lock.acquire()
        self._onColResize(event)
        self.lock.release()

    def OnGetItemText(self, rowIndex, columnIndex):
        self.lock.acquire()
        if columnIndex >= self.colNum or rowIndex >= len(self.colData[self.colMapper[0]]):
            data = ''
        else:
            colName = self.colMapper[columnIndex]
            data = self.colData[colName][rowIndex]
            if data is None:
                data = ''
            else:
                data = self.dataToStringFuncs[self.colInfo[colName]['dataType']](data)
        self.lock.release()
        return data

class ColumnSelectionPopup(wx.Menu):
    def __init__(self, cols, parentDiag, clickedCol, clickedColNum, maxColNum, *args, **kwargs):
        wx.Menu.__init__(self, *args, **kwargs)
        #static
        self.parentDiag = parentDiag
        self.clickedCol = clickedCol
        self.clickedColNum = clickedColNum
        self.maxColNum = maxColNum

        id = wx.NewId()
        self.Append(id, 'Reset to defaults', 'Restore the default column ordering and size')
        self.Bind(wx.EVT_MENU, self.OnColumnReset, id=id)
        self.AppendSeparator()

        if clickedCol is not None:
            #move funcs
            id = wx.NewId()
            self.Append(id, 'Move to left', 'Moves column one step to the left')
            self.Bind(wx.EVT_MENU, self.OnMoveToLeft, id=id)

            id = wx.NewId()
            self.Append(id, 'Move x steps', 'Moves column x steps')
            self.Bind(wx.EVT_MENU, self.OnMoveToX, id=id)

            id = wx.NewId()
            self.Append(id, 'Move to right', 'Moves column one step to the right')
            self.Bind(wx.EVT_MENU, self.OnMoveToRight, id=id)

            self.AppendSeparator()

        #enable/disable columns
        self.idMapper = {}
        for tup in cols:
            id = wx.NewId()
            m = self.AppendCheckItem(id, tup[0], 'Activates or deactivates this column')
            #m.SetCheckable(True)
            if tup[1]==True:
                m.Toggle()
            self.idMapper[id]=tup[0]

            #event
            self.Bind(wx.EVT_MENU, self.OnClick, id=id)

    def OnClick(self, event):
        colName = self.idMapper[event.GetId()]
        if event.IsChecked() == True:
            if self.clickedColNum is not None:
                self.parentDiag.enableCol(colName, colPos=self.clickedColNum + 1)
            else:
                self.parentDiag.enableCol(colName, colPos=None)
        else:
            self.parentDiag.disableCol(colName)
        #event.Skip(False)

    def OnMoveToLeft(self, event):
        self.parentDiag.moveCol(self.clickedCol, -1)

    def OnMoveToX(self, event):
        min = self.clickedColNum * -1
        max = self.maxColNum - self.clickedColNum - 1
        diag = wx.NumberEntryDialog(self.parentDiag, 'How many steps should the column be moved?', 'Steps (left = -, right = +):', 'Move Column', 0, min, max)
        if diag.ShowModal() == wx.ID_OK:
            self.parentDiag.moveCol(self.clickedCol, diag.GetValue())

    def OnMoveToRight(self, event):
        self.parentDiag.moveCol(self.clickedCol, 1)

    def OnColumnReset(self, event):
        self.parentDiag.resetCols()

class PersistentVirtualListCtrl(VirtualListCtrl):
    def __init__(self, persister, persistPrefix, updateFunc, currentVersion, cols, dataFunc, parent, customDataToStringFuncs=[], rowIdCol=None, allowSort=True, defaultSortCol='', defaultSortDirection='ASC',
                 id=-1, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.LC_REPORT | wx.LC_VIRTUAL | wx.LC_VRULES, **kwargs):
        self.persister = persister
        self.persistKey = persistPrefix + 'columnInfo'
        self.updateFunc = updateFunc
        self.currentVersion = currentVersion

        VirtualListCtrl.__init__(self, cols, dataFunc, parent, customDataToStringFuncs, rowIdCol, allowSort=allowSort, defaultSortCol=defaultSortCol, defaultSortDirection=defaultSortDirection, id=id, pos=pos, size=size, style=style, **kwargs)

    ##internal funcs - persisting

    def _initColumns(self, cols):
        #initialises everything columns related
        persColData = self.persister.get(self.persistKey, None)
        if persColData is None:
            #nothing persisted exists
            colInfo, colMapper = self._createColumnInfo(cols)
            self.sortDirection = self.defaultSortDirection
            if self.defaultSortCol in colMapper:
                self.sortColumn = colMapper.index(self.defaultSortCol)
            else:
                self.sortColumn = 0
        else:
            #managed to get persisted data, update
            persColData = self.updateFunc(persColData, self.currentVersion)

            #restore
            colInfo = persColData['colInfo']
            colMapper = persColData['colMapper']
            self.sortColumn = persColData['sortColumn']
            self.sortDirection = persColData['sortDirection']

            #check for new and changed cols
            for colSet in cols:
                if colSet[0] not in colInfo:
                    #new, add it
                    colInfo[colSet[0]] = {'dataKeyword':colSet[1],
                                          'dataType':colSet[2],
                                          'columnWidth':colSet[3]}

                else:
                    #old, update dataKeyword and dataType in case anything changed
                    colInfo[colSet[0]]['dataKeyword'] = colSet[1]
                    colInfo[colSet[0]]['dataType'] = colSet[2]

        self._createColumns(colInfo, colMapper)
        self._applyColSortImages(self.sortColumn, self.sortDirection)

    def _persist(self):
        persColData = {'colInfo':self.colInfo,
                       'colMapper':self.colMapper,
                       'sortColumn':self.sortColumn,
                       'sortDirection':self.sortDirection,
                       'version':self.currentVersion}
        self.persister.store(self.persistKey, persColData)

    ##internal funcs - other

    def _resetColumns(self):
        VirtualListCtrl._resetColumns(self)
        self._persist()

    def _onColClick(self, event):
        VirtualListCtrl._onColClick(self, event)
        self._persist()

    def _onColResize(self, event):
        VirtualListCtrl._onColResize(self, event)
        self._persist()

    def _disableCol(self, colName):
        VirtualListCtrl._disableCol(self, colName)
        self._persist()

    def _enableCol(self, colName, colPos):
        VirtualListCtrl._enableCol(self, colName, colPos)
        self._persist()

    def _moveCol(self, colName, direction):
        VirtualListCtrl._moveCol(self, colName, direction)
        self._persist()


def makeIntList(list):
    count = 0;
    while (count < len(list)):
        list[count] = int(list[count]);
        count += 1;
    return list;
def soldiersMedal(list,count):
    judge=True;
    i=0;
    while(i<len(list)):
        j=i+1;
        while(j<len(list)):
            if(list[i]==list[j]):
                list[j]+=1;
                count+=1;
                judge=False;
            j+=1;
        i+=1;
    if(judge):
        return count;
    else:
        return soldiersMedal(list,count);

Total=int(input());
list=str(input());
list=makeIntList(list.split(" "));
print(soldiersMedal(list,0));