from itertools import chain

from django.core.paginator import Paginator
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.models import User
from django.urls import reverse
from django.contrib import messages
from django.db.models import Q

from criticizes.forms import TicketForm, ReviewForm, UserFollowsForm
from criticizes.models import UserFollows, Ticket, Review

# ------ Création d'un ticket (demande de critique), page tickets.html ------
@login_required
def ticket_view(request):
    """Permet la création d'un ticket."""
    if request.method == "POST":
        form = TicketForm(request.POST, request.FILES)
        if form.is_valid():
            # print(form.cleaned_data)
            # print(request.user)
            ticket = form.save(commit=False)
            ticket.user = request.user
            ticket.save()
            return HttpResponseRedirect(reverse('criticizes:flux'))

    else:
        form = TicketForm()

    return render(request, "criticizes/tickets.html", {"form": form})

# ------ Modification du ticket, page ticket_update.html ------
@login_required
def update_ticket_view(request, ticket_pk):
    """Permet la modification d'un ticket."""

    if ticket_pk != "":
        ticket_needing_update = get_object_or_404(Ticket, id=ticket_pk)

    if request.method == "POST":
        form = TicketForm(request.POST, request.FILES)
        if form.is_valid():
            new_datas = form.cleaned_data
            form.save(commit=False)
            ticket_needing_update.title = new_datas.get("title")
            ticket_needing_update.description = new_datas.get("description")
            if new_datas.get("image"):
                ticket_needing_update.image = new_datas.get("image")
            ticket_needing_update.user = request.user
            ticket_needing_update.save()

            return HttpResponseRedirect(reverse('criticizes:flux'))
    else:
        form = TicketForm(initial={"title": ticket_needing_update.title,
                                   "description": ticket_needing_update.description,
                                   "image": ticket_needing_update.image})

    context = {
        "form": form, "initial_image": ticket_needing_update.image.url,
    }

    return render(request, "criticizes/tickets_update.html", context)

# ------ Suppression d'un ticket, page ticket_confirm_delete.html ------
def confirmation_delete_ticket(request, ticket_pk=""):
    """Affiche un message de confirmation de suppression du ticket."""
    previous_page = request.META.get('HTTP_REFERER', '/')

    # Recherche de la ligne correspondante à la PK dans la BD
    ticket_for_deletion = get_object_or_404(Ticket, id=ticket_pk)

    return render(request, "criticizes/ticket_confirm_delete.html",
                  {"ticket": ticket_for_deletion, 'previous_page': previous_page})

def delete_ticket(request, ticket_pk=""):
    """Supprime le ticket dans le table Ticket par la suppression de la PK de
    l'enregistrement."""

    ticket_for_deletion = get_object_or_404(Ticket, id=ticket_pk)
    ticket_for_deletion.delete()

    return HttpResponseRedirect(reverse('criticizes:flux'))

# ------ Création de la review(en réponse à un ticket), page criticism.html ------
@login_required
def review_view(request, ticket_pk=""):
    """Permet la création d'une critique en réponse au ticket affiché."""
    ticket_needing_answer = get_object_or_404(Ticket, id=ticket_pk)
    # print(ticket_needing_answer)
    # Affiche le formulaire de réponse (notation)
    # Solution selon TH Udemy
    if request.method == "POST":
        form = ReviewForm(request.POST)
        if form.is_valid():
            # print(form.cleaned_data)
            review = form.save(commit=False)
            review.ticket = ticket_needing_answer
            review.user = request.user
            review.save()

            return HttpResponseRedirect(reverse('criticizes:flux'))
    else:
        form = ReviewForm()

    context = {
        "ticket_needing_answer": ticket_needing_answer,
        "form": form,
    }

    return render(request, "criticizes/criticism.html", context)

# ------ Modification de la review, page criticism_update.html ------
@login_required
def update_review_view(request, review_pk=""):
    """Permet la modification d'une critique."""
    if review_pk != "":
        # Récupère la review concernée
        review_needing_update = get_object_or_404(Review, id=review_pk)
        # Récupère la clé du ticket associé
        ticket_linked = review_needing_update.ticket.pk
        # Récupère le ticket concerné pour affichage
        ticket_needing_answer = get_object_or_404(Ticket, id=ticket_linked)

    # Affiche le formulaire de réponse (notation)
    # Solution selon TH Udemy
    if request.method == "POST":
        form = ReviewForm(request.POST)
        if form.is_valid():
            new_datas = form.cleaned_data
            form.save(commit=False)
            review_needing_update.headline = new_datas.get("headline")
            review_needing_update.rating = new_datas.get("rating")
            review_needing_update.body = new_datas.get("body")
            review_needing_update.save()

            return HttpResponseRedirect(reverse('criticizes:flux'))
    else:
        form = ReviewForm(initial={"headline": review_needing_update.headline,
                                   "rating": review_needing_update.rating,
                                   "body": review_needing_update.body})

    context = {
        "ticket_needing_answer": ticket_needing_answer,
        "form": form,
    }

    return render(request, "criticizes/criticism_update.html", context)

# ------ Création d'une critique, review(sans réponse à un ticket),
# page criticism_direct.html ------
@login_required
def review_direct_view(request):
    """Permet la création d'une critique en direct sans réponse à un ticket."""
    # Intègre les deux formulaires

    review_form = ReviewForm()
    ticket_form = TicketForm()

    # Affiche le formulaire de création du ticket
    if request.method == "POST":
        ticket_form = TicketForm(request.POST, request.FILES)
        review_form = ReviewForm(request.POST)
        if ticket_form.is_valid() and review_form.is_valid():
            ticket_datas = ticket_form.cleaned_data
            ticket = ticket_form.save(commit=False)
            ticket.user = request.user
            ticket.save()
            ticket_recorded = Ticket.objects.last()
            review = review_form.save(commit=False)
            review.ticket = ticket_recorded
            review.user = request.user
            review.save()

            return HttpResponseRedirect(reverse('criticizes:flux'))

    else:
        ticket_form = TicketForm()
        review_form = ReviewForm()

    context = {
        "ticket_form": ticket_form,
        "review_form": review_form,
    }

    return render(request, "criticizes/criticism_direct.html", context)

# ------ Suppression d'une critique, page review_confirm_delete.html ------
def confirmation_delete_review(request, review_pk=""):
    """Affiche un message de confirmation de suppression de la critique."""

    # renverra la page précédente
    previous_page = request.META.get('HTTP_REFERER', '/')

    # Recherche de la ligne correspondante à la PK dans la BD
    review_for_deletion = get_object_or_404(Review, id=review_pk)

    return render(request, "criticizes/criticism_confirm_delete.html",
                  {"review": review_for_deletion, 'previous_page': previous_page})

def delete_review(request, review_pk=""):
    """Supprime la critique dans le table Review par la suppression de la PK de
    l'enregistrement."""

    review_for_deletion = get_object_or_404(Review, id=review_pk)
    review_for_deletion.delete()

    return HttpResponseRedirect(reverse('criticizes:flux'))

# ------ Suivi d'un utilisateur, page followers.html ------
@login_required
def user_follow_view(request):
    """Affiche un champ de texte pour y indiquer le nom de l'utilisateur à
    suivre, ainsi que les abonnements et les abonnés sur la page
    followers.html."""
    # Pour alimenter abonnements et abonnés (sections 2 et 3)
    pk_connected_user = request.user.pk
    followed_by_user = request.user.following.all()
    user_followed_by = UserFollows.objects.filter(followed_user=pk_connected_user)

    # Pour afficher la saisie de l'utilisateurs à suivre (section 1)
    if request.method == "POST":
        form = UserFollowsForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            # print(data)
            # print(request.user)
            follower = User.objects.get(username=request.user)
            followed = User.objects.get(username=data.get('searched_user_name'))
            # recherche des enregistrement qui ont pour user follower
            datas_followers_models = UserFollows.objects.filter(user=follower)
            # si parmi ces lignes, followed = followed_user, alors print
            for data in datas_followers_models:
                if data.followed_user.pk == followed.pk:
                    # source https://docs.djangoproject.com/fr/3.2/ref/contrib/messages/
                    messages.add_message(request, messages.INFO, "L'utilisateur est déjà suivi.")
                    # pour éviter le popup "ressoumètre le formulaire"
                    return HttpResponseRedirect(request.path)
                elif followed == follower:
                    messages.add_message(request, messages.INFO, "Vous ne pouvez pas vous suivre.")
                    # pour éviter le popup "ressoumètre le formulaire"
                    return HttpResponseRedirect(request.path)

                else:
                    relation = UserFollows(user=follower, followed_user=followed)

            relation.save()

    else:
        form = UserFollowsForm()

    template = 'criticizes/followers.html'
    context = {"form": form, 'followed_by_user': followed_by_user,
               'user_followed_by': user_followed_by}
    return render(request, template, context)

def delete_subscription(request):
    """Supprime l'abonnement dans le table UserFollows par la suppression de la
    PK de l'enregistrement collecté depuis la page html et de la donnée issue
    de def list_followers."""
    pk_in_database = request.POST.get('primary_key_of_subscription')
    # Recherche de la ligne correspondante à la PK dans la BD
    recording_in_UserFollows = UserFollows.objects.get(pk=pk_in_database)
    # suppression dans la BD
    recording_in_UserFollows.delete()
    return redirect('criticizes:user_follow')

# ------ page flux.html ------
@login_required
def flux_ticket_review(request):
    # User connecté :
    pk_connected_user = request.user.pk
    # Utilisateurs suivis par le user connecté :
    followed_by_user = request.user.following.all()
    # Création d'une liste avec les PK des utilisateurs suivis
    users_followed = []
    for i in followed_by_user:
        users_followed.append(i.followed_user.pk)

    # Combinaison des deux filtres, tickets de User et de ceux des utilisateurs suivis
    tickets = Ticket.objects.filter(Q(user=pk_connected_user) | Q(user__in=users_followed))
    # J'isole les tickets de l'utilisateur connecté pour pouvoir les récupérer dans les critiques
    # dans le cas où une personne non suivie par l'utilisateur y a répondu
    tickets_from_user_connected = []
    tickets_2 = Ticket.objects.filter(user=pk_connected_user)
    for t in tickets_2:
        tickets_from_user_connected.append(t.pk)
    # Combinaisons des filtres dans les critiques
    reviews = Review.objects.filter(Q(user=pk_connected_user) | Q(user__in=users_followed) |
                                    Q(ticket__in=tickets_from_user_connected))

    # création d'une liste des tickets ayant reçus une critique.
    # cette liste est utilisée dans ticket_snippet.html pour n'afficher le bouton
    # "créer une critique" que pour les tickets qui ne sont pas dedans
    tickets_followed = []
    for ticket in reviews:
        tickets_followed.append(ticket.ticket.pk)

    tickets_and_reviews = sorted(chain(tickets, reviews),
                                 key=lambda instance: instance.time_created, reverse=True)

    paginator = Paginator(tickets_and_reviews, 6)
    page = request.GET.get('page')

    page_obj = paginator.get_page(page)

    template = 'criticizes/flux.html'
    context = {'page_obj': page_obj, 'tickets_followed': tickets_followed}

    return render(request, template, context=context)

# ------ page posts.html ------
@login_required
def posts_ticket_review(request):
    tickets = Ticket.objects.filter(user=request.user)
    reviews = Review.objects.filter(user=request.user)

    tickets_and_reviews = sorted(chain(tickets, reviews),
                                 key=lambda instance: instance.time_created, reverse=True)

    paginator = Paginator(tickets_and_reviews, 6)
    page = request.GET.get('page')

    page_obj = paginator.get_page(page)

    template = 'criticizes/posts.html'
    context = {'page_obj': page_obj}
    return render(request, template, context=context)


# -*- coding:utf-8 -*-
a = list('abcdefghijklmnopqrstuvwxyz')
S = list(input())
b = list(set(S))
for tmp in b:
    a.pop(a.index(tmp))
if len(a) == 0:
    print("None")
else:
    print(a.pop(0))


from __future__ import annotations

from enum import Enum
from typing import List

from range_typed_integers import u16, u8, u32, i32

from skytemple_files.common.i18n_util import _
from skytemple_files.common.util import (
    AutoString,
    write_u32,
    read_i32,
    read_u8,
    write_i32,
    read_u16,
    write_u16,
    read_u32,
    write_u8,
)
from skytemple_files.data.anim import (
    GENERAL_DATA_SIZE,
    MOVE_DATA_SIZE,
    TRAP_DATA_SIZE,
    ITEM_DATA_SIZE,
    SPECIAL_MOVE_DATA_SIZE,
)

class AnimPointType(Enum):
    HEAD = 0x00, _("Head")
    LEFT_HAND = 0x01, _("Left Hand")
    RIGHT_HAND = 0x02, _("Right Hand")
    CENTER = 0x03, _("Center")
    NONE = 0xFF, _("None")

    def __new__(cls, *args, **kwargs):  # type: ignore
        obj = object.__new__(cls)
        obj._value_ = args[0]
        return obj

    # ignore the first param since it's already set by __new__
    def __init__(self, _: int, description: str):
        self.description = description

class AnimType(Enum):
    INVALID = 0x00, _("Invalid")
    WAN_FILE0 = 0x01, _("WAN File 0")
    WAN_FILE1 = 0x02, _("WAN File 1")
    WAN_OTHER = 0x03, _("WAN")
    WAT = 0x04, _("WAT")
    SCREEN = 0x05, _("Screen")
    WBA = 0x06, _("WBA")

    def __new__(cls, *args, **kwargs):  # type: ignore
        obj = object.__new__(cls)
        obj._value_ = args[0]
        return obj

    # ignore the first param since it's already set by __new__
    def __init__(self, _: int, description: str):
        self.description = description

class TrapAnim(AutoString):
    anim: u16

    def __init__(self, data: bytes):
        self.anim = read_u16(data, 0)

    def to_bytes(self):
        data = bytearray(TRAP_DATA_SIZE)
        write_u16(data, self.anim, 0)
        return data

class ItemAnim(AutoString):
    anim1: u16
    anim2: u16

    def __init__(self, data: bytes):
        self.anim1 = read_u16(data, 0)
        self.anim2 = read_u16(data, 2)

    def to_bytes(self):
        data = bytearray(ITEM_DATA_SIZE)
        write_u16(data, self.anim1, 0)
        write_u16(data, self.anim2, 2)
        return data

class MoveAnim(AutoString):
    anim1: u16
    anim2: u16
    anim3: u16
    anim4: u16
    dir: int
    flag1: bool
    flag2: bool
    flag3: bool
    flag4: bool
    speed: u32
    animation: u8
    point: AnimPointType
    sfx: u16
    spec_entries: u16
    spec_start: u16

    def __init__(self, data: bytes):
        self.anim1 = read_u16(data, 0)
        self.anim2 = read_u16(data, 2)
        self.anim3 = read_u16(data, 4)
        self.anim4 = read_u16(data, 6)
        flags = read_u32(data, 8)
        self.dir = flags & 0x7
        self.flag1 = bool(flags & 0x8)
        self.flag2 = bool(flags & 0x10)
        self.flag3 = bool(flags & 0x20)
        self.flag4 = bool(flags & 0x40)
        self.speed = read_u32(data, 12)
        self.animation = read_u8(data, 16)
        self.point = AnimPointType(read_u8(data, 17))  # type: ignore
        self.sfx = read_u16(data, 18)
        self.spec_entries = read_u16(data, 20)
        self.spec_start = read_u16(data, 22)

    def to_bytes(self):
        data = bytearray(MOVE_DATA_SIZE)
        write_u16(data, self.anim1, 0)
        write_u16(data, self.anim2, 2)
        write_u16(data, self.anim3, 4)
        write_u16(data, self.anim4, 6)
        flags = (
            self.dir
            | (int(self.flag1) << 3)
            | (int(self.flag2) << 4)
            | (int(self.flag3) << 5)
            | (int(self.flag4) << 6)
        )
        write_u32(data, u32(flags), 8)
        write_u32(data, self.speed, 12)
        write_u8(data, self.animation, 16)
        write_u8(data, self.point.value, 17)
        write_u16(data, self.sfx, 18)
        write_u16(data, self.spec_entries, 20)
        write_u16(data, self.spec_start, 22)
        return data

class GeneralAnim(AutoString):
    anim_type: AnimType
    anim_file: u32
    unk1: u32
    unk2: u32
    sfx: i32
    unk3: u32
    u8: bool
    point: AnimPointType
    unk5: bool
    loop: bool

    def __init__(self, data: bytes):
        self.anim_type = AnimType(read_u32(data, 0))  # type: ignore
        self.anim_file = read_u32(data, 4)
        self.unk1 = read_u32(data, 8)
        self.unk2 = read_u32(data, 12)
        self.sfx = read_i32(data, 16)
        self.unk3 = read_u32(data, 20)
        self.unk4 = bool(read_u8(data, 24))
        self.point = AnimPointType(read_u8(data, 25))  # type: ignore
        self.unk5 = bool(read_u8(data, 26))
        self.loop = bool(read_u8(data, 27))

    def to_bytes(self):
        data = bytearray(GENERAL_DATA_SIZE)
        write_u32(data, self.anim_type.value, 0)
        write_u32(data, self.anim_file, 4)
        write_u32(data, self.unk1, 8)
        write_u32(data, self.unk2, 12)
        write_i32(data, self.sfx, 16)
        write_u32(data, self.unk3, 20)
        write_u8(data, u8(int(self.unk4)), 24)
        write_u8(data, self.point.value, 25)
        write_u8(data, u8(int(self.unk5)), 26)
        write_u8(data, u8(int(self.loop)), 27)
        return data

class SpecMoveAnim(AutoString):
    pkmn_id: u16
    animation: u8
    point: AnimPointType
    sfx: u16

    def __init__(self, data: bytes):
        self.pkmn_id = read_u16(data, 0)
        self.animation = read_u8(data, 2)
        self.point = AnimPointType(read_u8(data, 3))  # type: ignore
        self.sfx = read_u16(data, 4)

    def to_bytes(self):
        data = bytearray(SPECIAL_MOVE_DATA_SIZE)
        write_u16(data, self.pkmn_id, 0)
        write_u8(data, self.animation, 2)
        write_u8(data, self.point.value, 3)
        write_u16(data, self.sfx, 4)
        return data

class Anim(AutoString):
    trap_table: List[TrapAnim]
    item_table: List[ItemAnim]
    move_table: List[MoveAnim]
    general_table: List[GeneralAnim]
    special_move_table: List[SpecMoveAnim]

    def __init__(self, data: bytes):
        if not isinstance(data, memoryview):
            data = memoryview(data)
        trap_table_ptr = read_u32(data, 0)
        item_table_ptr = read_u32(data, 4)
        move_table_ptr = read_u32(data, 8)
        general_table_ptr = read_u32(data, 12)
        special_move_table_ptr = read_u32(data, 16)

        self.trap_table = []
        for x in range(trap_table_ptr, item_table_ptr, TRAP_DATA_SIZE):
            self.trap_table.append(TrapAnim(data[x : x + TRAP_DATA_SIZE]))
        self.item_table = []
        for x in range(item_table_ptr, move_table_ptr, ITEM_DATA_SIZE):
            self.item_table.append(ItemAnim(data[x : x + ITEM_DATA_SIZE]))
        self.move_table = []
        for x in range(move_table_ptr, general_table_ptr, MOVE_DATA_SIZE):
            self.move_table.append(MoveAnim(data[x : x + MOVE_DATA_SIZE]))
        self.general_table = []
        for x in range(general_table_ptr, special_move_table_ptr, GENERAL_DATA_SIZE):
            self.general_table.append(GeneralAnim(data[x : x + GENERAL_DATA_SIZE]))
        self.special_move_table = []
        for x in range(special_move_table_ptr, len(data), SPECIAL_MOVE_DATA_SIZE):
            self.special_move_table.append(
                SpecMoveAnim(data[x : x + SPECIAL_MOVE_DATA_SIZE])
            )

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Anim):
            return False
        return (
            self.trap_table == other.trap_table
            and self.item_table == other.item_table
            and self.move_table == other.move_table
            and self.general_table == other.general_table
            and self.special_move_table == other.special_move_table
        )


#evaluation of postfix expression
class Evaluate:
    def __init__(self):
        self.stack = []

    def isDigit(self, digit):
        if ord(digit) >= 48 and ord(digit) <= 57:
            return 1
        else:
            return 0

    def evaluatepostfix(self, exp):
        for i in range(len(exp)):
            if self.isDigit(exp[i]):
                self.stack.append(exp[i])
            elif exp[i] == " ":
                pass
            else:
                op2 = self.stack.pop()
                op1 = self.stack.pop()
                op = str(eval(op1 + exp[i] + op2))
                self.stack.append(op)

        return self.stack.pop()
        #or return self.stack[-1]

if __name__ == "__main__":

    exp = input("Enter postfix expression to evaluate : ")
    ev = Evaluate()
    print(ev.evaluatepostfix(exp))


import matplotlib.pyplot as plt
import json
import numpy as np

folder_name = "50k_pure_hervor"
f = open(f'../_data_archive/instances/{folder_name}/training_stats.txt', 'r')

text = f.read()[1:-1].split('][')
chaser_avg = []
hervor_avg = []

print(len(text))

for x in text:
    sp = x.split('},{')
    hervor = json.loads(sp[0] + "}")
    chaser = json.loads("{" + sp[1])
    hervor_avg.append(hervor["avg_fitness"])
    chaser_avg.append(chaser["avg_fitness"])

window = 100
average = []
for ind in range(len(hervor_avg) - window + 1):
    average.append(np.average(hervor_avg[ind:ind+window]))

plt.plot(range(len(hervor_avg)), hervor_avg)
plt.plot(range(len(hervor_avg) - window + 1), average)
plt.title("Hervor average fitness")
plt.show()

window = 100
average = []
for ind in range(len(chaser_avg) - window + 1):
    average.append(np.average(chaser_avg[ind:ind+window]))

plt.plot(range(len(chaser_avg)), chaser_avg)
plt.plot(range(len(chaser_avg) - window + 1), average)
plt.title("Chaser average fitness")
plt.show()


import sys
import Get_size_type
"""
__m512i _mm512_i32extgather_epi32 (__m512i index, void const * mv, _MM_UPCONV_EPI32_ENUM conv, int scale, int hint)

__m512 _mm512_i32extgather_ps (__m512i index, void const * mv, _MM_UPCONV_PS_ENUM conv, int scale, int hint)

__m512d _mm512_i32loextgather_pd (__m512i index, void const * mv, _MM_UPCONV_PD_ENUM conv, int scale, int hint)

"""

AVX512_index_type={'MPI_FLOAT': '__m512i', 'MPI_INT': '__m512i', 'MPI_DOUBLE': '__m256i'}
AVX512_type={'MPI_FLOAT': '__m512', 'MPI_INT': '__m512i', 'MPI_DOUBLE': '__m512d'}
AVX512_to_C={'MPI_FLOAT': 'ps', 'MPI_INT': 'epi32', 'MPI_DOUBLE': 'pd'}
AVX512_UPCONV={'MPI_FLOAT': '_MM_UPCONV_PS_NONE', 'MPI_INT': '_MM_UPCONV_EPI32_NONE', 'MPI_DOUBLE': '_MM_UPCONV_PD_NONE'}

class AVX512_gather(object):
    def __init__(self, offsets, MPI_TYPE):
        self.offsets = offsets
        self.MPI_TYPE = MPI_TYPE

init_vars = """
    // Scale need to be 4 for float , 8 for double
    %(512_INDEX)s index;
    %(512_TYPE)s gathered_vector;
"""

gather_ins = """
    //index  =  _mm512_loadu_si512(offsets+%(NUMBER_OF_GATHER)s*%(ELEM_IN_VEC)s);
    //gathered_vector = _mm512_i32extgather_%(512_TO_C)s( index, src, %(512_UPCONV)s, 4, 0 );
    for(i=0;i<%(NUMBER_OF_GATHER)s;i++){
        index = _mm512_loadu_si512(offsets+i*%(ELEM_IN_VEC)s);
        //gathered_vector = _mm512_i32extgather_%(512_TO_C)s( index, src, %(512_UPCONV)s, 4, 0 );
        gathered_vector = _mm512_i32gather_%(512_TO_C)s( index, src, 4);
        _mm512_store_%(512_TO_C)s(dst,gathered_vector);
        dst += %(ELEM_IN_VEC)s;
     }
"""

scatter_ins = """
    for(i=0;i<%(NUMBER_OF_GATHER)s;i++){
        index = _mm512_loadu_si512(offsets+i*%(ELEM_IN_VEC)s);
        gathered_vector = _mm512_load_epi32(src)
        //_mm512_store_%(512_TO_C)s(src,gathered_vector);
        _mm512_mask_i32scatter_epi32 (dst, index, gathered_vector, 4);
       dst += %(ELEM_IN_VEC)s;
    }
"""

double_gather_ins = """
    for(i=0;i<%(NUMBER_OF_GATHER)s;i++){
    index = _mm256_loadu_si256(offsets+i*%(ELEM_IN_VEC)s);
    //index = _mm256_loadu_si256(offsets+%(NUMBER_OF_GATHER)s*%(ELEM_IN_VEC)s);
    gathered_vector = _mm512_i32gather_%(512_TO_C)s( index, src, 8);
    _mm512_store_%(512_TO_C)s(dst,gathered_vector);
    dst += %(ELEM_IN_VEC)s;}
"""

def print_init_vars(MPI_TYPE,elem_in_vector,number_of_gather):
    params = {
        '512_TYPE'       : str(AVX512_type[MPI_TYPE]),
        '512_INDEX'      :str(AVX512_index_type[MPI_TYPE]),
        }
    print (init_vars% params)

def print_gather(MPI_TYPE,elem_in_vector,number_of_gather):
    params = {
        '512_TYPE'       : str(AVX512_type[MPI_TYPE]),
        '512_TO_C'       : str(AVX512_to_C[MPI_TYPE]),
        '512_UPCONV'     : str(AVX512_UPCONV[MPI_TYPE]),
        'ELEM_IN_VEC'    : int(elem_in_vector),
        'NUMBER_OF_GATHER' : int(number_of_gather),
        '512_INDEX'      :str(AVX512_index_type[MPI_TYPE]),
        }
    if MPI_TYPE == 'MPI_DOUBLE':
        print (double_gather_ins% params)
    else:
        print (gather_ins% params)

gather_pack = """
void gather_pack(uint32_t cnt, uint32_t *offsets, void *_src, void *_dst){
    int i = 0;
    %(GET_TYPE)s* src = (%(GET_TYPE)s*)_src;
    %(GET_TYPE)s* dst = (%(GET_TYPE)s*)_dst;
"""
def print_gather_pack(MPI_TYPE):
    params = {
            'GET_TYPE'       : str(Get_size_type.get_type(MPI_TYPE)),
            }
    print (gather_pack % params)

def gen_gather_code(offsets, MPI_TYPE, elem_in_vector):

    print_gather_pack(MPI_TYPE)
    print_init_vars(MPI_TYPE,elem_in_vector, 0)
    #for number_of_gather in range (0, len(offsets)/elem_in_vector):
    #    print_gather(MPI_TYPE,elem_in_vector,number_of_gather)
    print_gather(MPI_TYPE,elem_in_vector,len(offsets)/elem_in_vector)
    print ("}")


#!/usr/bin/env python

import os
from distutils.core import setup

import repython

def read(filename):
    return open(os.path.join(os.path.dirname(__file__), filename)).read()

setup(name='repython',
    version=repython.__version__,
    description='Tool to restart commands based on filesystem changes',
    author='Reinis Ivanovs',
    author_email='dabas@untu.ms',
    url='https://github.com/slikts/repython',
    packages=['repython'],
    keywords='cli restart inotify monitor',
    license='BSD',
    long_description=read('README.md'),
    # http://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: POSIX',
        'Programming Language :: Python',
        'Topic :: Software Development',
        'Topic :: Utilities',
    ],
    install_requires=['pyinotify', 'twiggy'],
)


from __future__ import print_function
import os
import tensorflow as tf
import numpy as np
import ccnn as NETwork
import datetime
from sklearn.metrics import average_precision_score
import data_manager
import test as evaluation

"""
You must set batch_size=1 firstly
"""

# Model Hyperparameters
tf.flags.DEFINE_string('filter_sizes', '3,4,5', 'Comma-separated filter sizes default: (3,4,5)')
tf.flags.DEFINE_integer('pattern_num', 5, 'No. of patterns for each relation (default: 10)')
tf.flags.DEFINE_float('l2_reg_omega', 0.001, 'l2_regularizer weight (default: 0.0005)')

# Eval Parameters
tf.flags.DEFINE_string('checkpoint_dir', '../../runs/bag/', 'Checkpoint directory from training run')
tf.flags.DEFINE_string('model', 'model-5', "Model dir for evaluation, default: (model)")
tf.flags.DEFINE_boolean("use_types", True, "Use entity types (default: True")

# Misc Parameters
tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement")
tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices")

FLAGS = tf.flags.FLAGS
FLAGS._parse_flags()
print("\nParameters:")
for attr, value in sorted(FLAGS.__flags.items()):
    print("{}={}".format(attr.upper(), value))
print("")

def main(_):
    """
    main function
    """
    dataset = data_manager.DataManager()
    model_dir = '../../runs/bag/{}'.format(FLAGS.model)

    time_str = datetime.datetime.now().isoformat()
    print('{}: start test'.format(time_str))

    print('reading wordembedding')
    wordembedding = np.load('../../data/bag_data/vec.npy')

    settings = NETwork.Settings()
    settings.vocab_size = len(wordembedding)
    settings.filter_sizes = list(map(int, FLAGS.filter_sizes.split(',')))
    settings.pattern_num = FLAGS.pattern_num
    settings.l2_reg_omega = FLAGS.l2_reg_omega

    #checkpoint_file = tf.train.latest_checkpoint(FLAGS.checkpoint_dir + FLAGS.model + '/checkpoints/')
    checkpoint_file = FLAGS.checkpoint_dir + FLAGS.model + '/model-best'
    graph = tf.Graph()
    with graph.as_default():
        gpu_options = tf.GPUOptions(allow_growth=True)
        session_conf = tf.ConfigProto(
            allow_soft_placement=FLAGS.allow_soft_placement,
            log_device_placement=FLAGS.log_device_placement,
            gpu_options=gpu_options)
        sess = tf.Session(config=session_conf)
        with sess.as_default():
            # Load the saved meta graph and restore variables
            time_str = datetime.datetime.now().isoformat()
            print('{}: construct network...'.format(time_str))
            # saver = tf.train.import_meta_graph('{}.meta'.format(checkpoint_file))
            # saver.restore(sess, checkpoint_file)
            network = NETwork.CNN(word_embeddings=dataset.wordembedding, settings=settings, is_training=False, is_evaluating=True, use_types=FLAGS.use_types)
            saver = tf.train.Saver()
            time_str = datetime.datetime.now().isoformat()
            print('{}: restore checkpoint file: {}'.format(time_str, checkpoint_file))
            saver.restore(sess, checkpoint_file)

            # test one entity relation mentions
            time_str = datetime.datetime.now().isoformat()
            print('{}: testing...'.format(time_str))

            def eval_step(test_word, test_pos1, test_pos2, test_type, test_y):
                num_batches_per_epoch = int((len(test_y)-1)/settings.batch_size) + 1
                for batch_num in range(num_batches_per_epoch):
                    start_index = batch_num * settings.batch_size
                    end_index = min((batch_num+1)*settings.batch_size, len(test_y))
                    if (end_index - start_index) != settings.batch_size:
                        start_index = end_index - settings.batch_size

                    word_batch = test_word[start_index: end_index]
                    pos1_batch = test_pos1[start_index: end_index]
                    pos2_batch = test_pos2[start_index: end_index]
                    type_batch = test_type[start_index: end_index]
                    y_batch = test_y[start_index: end_index]

                    attentions = eval_op(word_batch, pos1_batch, pos2_batch, type_batch, y_batch)
                    print(attentions)

            def eval_op(word_batch, pos1_batch, pos2_batch, type_batch, y_batch):
                """
                evaluate a batch
                """
                total_word = []
                total_pos1 = []
                total_pos2 = []
                total_type = []
                total_shape_batch = []
                total_num = 0

                for i in range(len(word_batch)):
                    total_shape_batch.append(total_num)
                    total_num += len(word_batch[i])

                    for j in range(len(word_batch[i])):
                        total_word.append(word_batch[i][j])
                        total_pos1.append(pos1_batch[i][j])
                        total_pos2.append(pos2_batch[i][j])
                        total_type.append(type_batch[i][j])

                # Here total_word and y_batch are not equal, total_word[total_shape[i]:total_shape[i+1]] is related to y_batch[i]
                total_shape_batch.append(total_num)

                total_shape_batch = np.array(total_shape_batch)
                total_word = np.array(total_word)
                total_pos1 = np.array(total_pos1)
                total_pos2 = np.array(total_pos2)
                total_type = np.array(total_type)

                feed_dict = {
                    network.input_word: total_word,
                    network.input_pos1: total_pos1,
                    network.input_pos2: total_pos2,
                    network.input_type: total_type,
                    #self.network.input_y: y_batch,
                    network.total_shape: total_shape_batch,
                    network.dropout_keep_prob: 1.0
                }

                attentions = sess.run([network.attention], feed_dict)

                return attentions

            eval_step(dataset.test_word, dataset.test_pos1, dataset.test_pos2, dataset.test_type, dataset.test_y)

if __name__ == '__main__':
    tf.app.run()


import pygetwindow as pg
import time as t

from ReconhecerObjetos import ReconhecerCelular
from CaptacaoImagensNegativas import ImportarImagens

def ProcuraAbasNaoPermitidas(abas, termo):
    for elements in abas:
        if(termo) in elements:
            if(elements != None):
                elemento_encontrado = elements
                return elemento_encontrado
                break
            else:
                return False
                break

def FechaAbasNaoPermitidas(Google, Firefox, Edge, VisualStudio):
    if(Google != None):
        Google = Google.upper()
        abaCorreta = pg.getWindowsWithTitle(Google)[0]
        if (abaCorreta.title != ''):
            abaCorreta.close()
    if(Firefox != None):
        Firefox = Firefox.upper()
        abaCorreta = pg.getWindowsWithTitle(Firefox)[0]
        if (abaCorreta.title != ''):
            abaCorreta.close()
    if(Edge != None):
        Edge = Edge.upper()
        abaCorreta = pg.getWindowsWithTitle(Edge)[0]
        if (abaCorreta.title != ''):
            abaCorreta.close()

    if(VisualStudio != None):
        VisualStudio = VisualStudio.upper()
        abaCorreta = pg.getWindowsWithTitle(VisualStudio)[0]
        if (abaCorreta.title != ''):
            abaCorreta.close()

def countdown(num_of_secs):
    while num_of_secs:
        AbasAbertas = pg.getAllTitles()
        Google = ProcuraAbasNaoPermitidas(AbasAbertas, 'Google')
        Firefox = ProcuraAbasNaoPermitidas(AbasAbertas, 'Firefox')
        Edge = ProcuraAbasNaoPermitidas(AbasAbertas, 'Edge')
        VisualStudio = ProcuraAbasNaoPermitidas(AbasAbertas, 'Visual Studio')

        FechaAbasNaoPermitidas(Google, Firefox, Edge, VisualStudio)

        m, s = divmod(num_of_secs, 60)
        min_sec_format = '{:02d}:{:02d}'.format(m, s)
        print(min_sec_format)
        t.sleep(1)
        num_of_secs -= 1

    print('O Tempo Acabou')
    return False

if __name__ == '__main__':
    countdown(3920)
    #ImportarImagens()


# -*- coding: utf-8 -*-
"""
Created on Tue Oct 11 20:04:47 2022

@author: turtl_4
"""

from tkinter import *

root = Tk()
root.title("ASCII Converter With Encrpt")

root.geometry("400x400")
root.configure(background = "light blue")

input_word = Entry(root)
input_word.place(relx=0.5, rely=0.4, anchor=CENTER)

label_output = Label(root, text = "ASCII value : ", bg = 'light green', fg = 'black')
label_encrpt = Label(root)

def convert_code():
    input_text = input_word.get()
    label_output["text"]  = ""

    for letter in input_text :
        label_output["text"] += str(ord(letter)) + " "
        ASCII = int(ord(letter))
        encrpt = ASCII - 1
        label_encrpt["text"] += str(chr(encrpt))

btn = Button(root,text = "Display the ASCII Code and Encrypted value", command = convert_code,bg = 'gold', fg = 'black')
btn.place(relx=0.5, rely=0.5, anchor=CENTER)

label_output.place(relx=0.5, rely=0.6, anchor=CENTER)
label_encrpt.place(relx=0.5, rely=0.7, anchor=CENTER)

root.mainloop()


'''

设置单元格的字体和颜色
'''

import sys,math
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt, QStringListModel
from qtpy import QtCore

class CellFontAndColor(QWidget):
    def __init__(self):
        super(CellFontAndColor, self).__init__()
        self.initUI()

    def initUI(self):
        self.resize(430, 230)
        self.setWindowTitle("PlaceControlInCell例子")

        layout=QHBoxLayout()
        tableWidget = QTableWidget()
        tableWidget.setRowCount(4)
        tableWidget.setColumnCount(3)

        layout.addWidget(tableWidget)
        tableWidget.setHorizontalHeaderLabels(['姓名', '性别', '体重（kg）'])
        newItem = QTableWidgetItem('小明')
        newItem.setFont(QFont('Times',14,QFont.Black))
        newItem.setForeground(QBrush(QColor(255,0,0)))
        tableWidget.setItem(0, 0, newItem)

        newItem = QTableWidgetItem('小明2')
        #newItem.setFont(QFont('Times', 14, QFont.Black))
        newItem.setForeground(QBrush(QColor(255, 255, 0)))
        newItem.setBackground(QBrush(QColor(0, 0, 255)))
        tableWidget.setItem(0, 1, newItem)

        newItem = QTableWidgetItem('160')
        newItem.setFont(QFont('Times', 20, QFont.Black))
        newItem.setForeground(QBrush(QColor(0, 0, 255)))
        tableWidget.setItem(0, 2, newItem)

        self.setLayout(layout)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = CellFontAndColor()
    main.show()

    sys.exit(app.exec_())


from django.urls import path
from . import views

urlpatterns = [
	path('', views.store, name="store"),
	path('cart/', views.cart, name="cart"),
	path('checkout/', views.checkout, name="checkout"),
	path('update_item/', views.updateItem, name="update_item"),
	path('process_order/', views.processOrder, name="process_order"),

	path('accounts/signup', views.signup, name="signup"),

	# chat
	# path('home/', views.home, name='home'),
    # path('<str:room>/', views.room, name='room'),
    # path('checkview', views.checkview, name='checkview'),
    # path('send', views.send, name='send'),
    # path('getMessages/<str:room>/', views.getMessages, name='getMessages'),
]


import math

from user.models import *
from shomobay_shomiti_detector.models import *
from django.conf import settings

def HMModel(participant):
    # print()
    # print("in reweight------------------------------------------->>")

    # should contain 1 object for each adjacent participant
    subs = Submission.objects.filter(status=1, level=participant.curr_level - 1, participant__batch=participant.batch)

    # print()
    # print()
    update_list_weights = []
    update_list_max_weights = []
    if not subs:
        participant.max_weight = 0
    for sub in subs:
        if sub.participant.user == participant.user:
            continue
        diff = (participant.last_successful_submission_time - sub.time).total_seconds()
        try:
            prev_weight1 = DetectorGraph.objects.get(participant1=participant, participant2=sub.participant)
            prev_weight2 = DetectorGraph.objects.get(participant1=sub.participant, participant2=participant)
        except DetectorGraph.DoesNotExist:
            # starting value of weight
            prev_weight1 = DetectorGraph.objects.create(participant1=participant, participant2=sub.participant,
                                                        weight=settings.START_PROB)
            prev_weight2 = DetectorGraph.objects.create(participant1=sub.participant, participant2=participant,
                                                        weight=settings.START_PROB)

        # print("prev_weight ", prev_weight1.weight, prev_weight2.weight)

        # HMM
        new_weight = updateProbabilityForOneTimeStep(prev_weight1.weight)
        new_weight = reweighProbabilityBasedOnEvidence(new_weight, diff)

        prev_weight1.weight = new_weight
        prev_weight2.weight = new_weight

        update_list_weights.append(prev_weight1)
        update_list_weights.append(prev_weight2)

        # update max_weights
        if participant.max_weight < new_weight:
            participant.max_weight = new_weight

        if sub.participant.max_weight <= new_weight:
            sub.participant.max_weight = new_weight
            update_list_max_weights.append(sub.participant)

        # print(participant, sub.participant, diff, new_weight)

    update_list_max_weights.append(participant)
    DetectorGraph.objects.bulk_update(update_list_weights, ['weight'])
    Participant.objects.bulk_update(update_list_max_weights, ['max_weight'])
    # print("out reweight------------------------------------------->>")
    # print()

def EMISSION1(time_diff):
    """
        time_diff in seconds
    """
    time_diff = time_diff / settings.SPREAD
    mean = settings.MEAN
    dev = settings.DEVIATION

    e_pow = -pow(math.log(time_diff, math.e) - mean, 2) / (2 * pow(dev, 2))
    p = pow(math.e, e_pow) * settings.SCALE

    return p

def EMISSION0(time_diff):
    return settings.EMISSION00 if EMISSION1(time_diff) > 0.5 else settings.EMISSION01

def updateProbabilityForOneTimeStep(B):
    """
    TRANSITION00 = 0.8     # -cheat(t+1)|-cheat(t)
    TRANSITION01 = 0.1     # -cheat(t+1)|+cheat(t)
    TRANSITION10 = 0.2     # +cheat(t+1)|-cheat(t)
    TRANSITION11 = 0.9     # +cheat(t+1)|+cheat(t)
    """
    return B * settings.TRANSITION11 + (1 - B) * settings.TRANSITION10

def reweighProbabilityBasedOnEvidence(B, evd):
    new_B = B * EMISSION1(evd)
    new_B_ = (1 - B) * EMISSION0(evd)

    return new_B / (new_B + new_B_)


n1=int(input("Enter first integer: "))
n2=int(input("Enter second integer: "))
UCLN=1
k=2
if n1 < 0 or n2<0:
    print('Xin hay nhap so nguyen duong')
    n1 = int(input("Enter first integer: "))
    n2 = int(input("Enter second integer: "))

    if n1==0 and n2==0:
        print('Loi Chia 0')
    elif n1==0 and n2 != 0:
        print('So chia lon nhat cua %d va %d la: %d '%(n1,n2,n2))
    elif n2 == 0 and n1 != 0:
        print('So chia lon nhat cua %d va %d la: %d '% (n1, n2, n1))

    elif n1 != n2 and n1>0 and n2>0:

        while k<=n1 and k<=n2:
            if n1%k==0 and n2%k==0:
                UCLN=k
            k+=1
        print("So Chia lon nhat cua hai so tren la: ", UCLN)


from dbclasses import DBConnection
from ozonattributes import Attribute
from ozonproduct import OzonNDSValue, OzonProduct
import requests
import json
from typing import List
import logging

REQUEST_LIMIT = 1000
PRODUCT_LIST_URI = 'https://api-seller.ozon.ru/v2/product/list'
UPLOAD_PRODUCT_URI = 'https://api-seller.ozon.ru/v2/product/import'
DELETE_PRODUCTS_URI = 'https://api-seller.ozon.ru/v2/products/delete'
ARCHIVE_PRODUCTS_URI = 'https://api-seller.ozon.ru/v1/product/archive'
UPDATE_CHARACTERISTICS_URI = 'https://api-seller.ozon.ru/v1/product/attributes/update'
GET_ATTRIBUTES_URI = 'https://api-seller.ozon.ru/v3/products/info/attributes'
UPDATE_OFFER_IDS_URI = 'https://api-seller.ozon.ru/v1/product/update/offer-id'

class OzonApi():
    def __init__(self, client_id, api_key) -> None:
        self.client_id = client_id
        self.api_key = api_key
        self.headers = {
            'Client-Id': client_id,
            'Api-Key': api_key
        }
        self.verifier = DBConnection().init_verifier()

    def get_all_products(self, _filter={}):
        json_data = {
            'limit': REQUEST_LIMIT,
            'filter': _filter,
        }
        items = []
        last_id = None
        while True:
            r = requests.post(PRODUCT_LIST_URI,
                              headers=self.headers,
                              json=json_data if last_id is None else {**json_data, 'last_id': last_id})
            if r.status_code != 200:
                logging.error(r.status_code, r.text)
                return None

            parsed = json.loads(r.text)
            items += parsed['result']['items']
            if len(items) >= parsed['result']['total']:
                break
        return items

    def get_archived_products(self):
        return self.get_all_products({
            'visibility': 'ARCHIVED'
        })

    def get_products_attribs(self, offer_ids):
        json_data = {
            'limit': REQUEST_LIMIT,
            'filter': {
                'offer_id': offer_ids
            }
        }
        req = requests.post(GET_ATTRIBUTES_URI,
                            headers=self.headers,
                            json=json_data)

        if req.status_code != 200:
            logging.error(req.status_code, req.text)
            return

        return json.loads(req.text)['result']

    def update_attributes(self, offer_ids, attributes):
        attributes_json = [self._form_attrib_request(attrib)
                           for attrib in attributes]
        json_data = {
            'items': [{
                'offer_id': offer_id,
                'attributes': attributes_json
            } for offer_id in offer_ids]
        }
        req = requests.post(UPDATE_CHARACTERISTICS_URI,
                            headers=self.headers,
                            json=json_data)
        if req.status_code != 200:
            logging.error(req.status_code, req.text)

    def update_offer_ids(self, update_offer_ids):
        req = requests.post(UPDATE_OFFER_IDS_URI,
                            headers=self.headers,
                            json={
                                'update_offer_id': update_offer_ids
                            })
        if req.status_code != 200:
            logging.error(req.status_code, req.text)

    def upload_products(self, products: List[OzonProduct]):
        json_data = {
            'items': []
        }
        for product in products:
            json_data['items'].append(self._form_creation_request(product))
        r = requests.post(UPLOAD_PRODUCT_URI,
                          headers=self.headers,
                          json=json_data)
        if r.status_code != 200:
            logging.error(r.status_code, r.text)
        return r.status_code

    def _form_creation_request(self, product: OzonProduct):
        return {
            'offer_id': product.info.offer_id,
            'category_id': product.info.category_id,
            'currency_code': 'RUB',
            'images': product.media.images,
            'name': product.info.name,
            'dimension_unit': product.dimensions.dimension_unit.value,
            'depth': product.dimensions.depth,
            'height': product.dimensions.height,
            'width': product.dimensions.width,
            'price': str(product.price.price),
            'old_price': str(product.price.old_price),
            'vat': OzonNDSValue.ZERO.value,
            'weight': product.weight.weight,
            'weight_unit': product.weight.weight_unit.value,
            'attributes': [self._form_attrib_request(attrib) for attrib in product.attributes]
        }

    def _form_attrib_request(self, attrib: Attribute):
        d = {
            'complex_id': 0,
            'id': attrib._id,
            'values': []
        }
        if type(attrib.value) != list:
            d['values'] = [self._form_attrib_value_request(
                attrib.value, attrib._id)]
        else:
            d['values'] = [self._form_attrib_value_request(
                val, attrib._id) for val in attrib.value]
        return d

    def _form_attrib_value_request(self, attrib_value, attrib_id):
        return {
            'dictionary_value_id': self.verifier._get_value_id(attrib_id, attrib_value),
            'value': str(attrib_value)
        }

    def archive(self, what_to_archive):
        products = [p for p in self.get_all_products() if what_to_archive(p)]
        product_chunks = [products[x:x+100]
                          for x in range(0, len(products), 100)]
        for chunk in product_chunks:
            json_data = {
                'product_id': [p['product_id'] for p in chunk]
            }
            req = requests.post(ARCHIVE_PRODUCTS_URI,
                                headers=self.headers,
                                json=json_data)
            if req.status_code != 200:
                logging.error(req.status_code, req.text)

    def delete(self, what_to_delete):
        products = [p for p in self.get_all_products() if what_to_delete(p)]
        product_chunks = [products[x:x+100]
                          for x in range(0, len(products), 100)]
        for chunk in product_chunks:
            json_data = {
                'product_id': [p['product_id'] for p in chunk]
            }
            req = requests.post(DELETE_PRODUCTS_URI,
                                headers=self.headers,
                                json=json_data)
            if req.status_code != 200:
                logging.error(req.status_code, req.text)


class Graph:
    def __init__(self):
        self.vertex = {}

    def addEdge(self, fromVertex, toVertex):
        if fromVertex in self.vertex.keys():
            self.vertex[fromVertex].append(toVertex)
        else:
            self.vertex[fromVertex] = [toVertex]

    def printGraph(self):
        for i in self.vertex:
            print(i, '->', ' -> '.join([str(j) for j in self.vertex[i]]))

    def DFS(self, startVetex, graph):
        visited = set()
        path = []
        stack = [startVetex]

        while stack:
            p = stack.pop()
            if p not in visited:
                visited.add(p)
                path.append(p)
                stack.extend(reversed(graph[p]))
                print(p, stack, visited)
        return path

if __name__ == '__main__':

    al = Graph()
    al.addEdge(0, 1)
    al.addEdge(0, 4)
    al.addEdge(4, 1)
    al.addEdge(4, 3)
    al.addEdge(1, 0)
    al.addEdge(1, 4)
    al.addEdge(1, 3)
    al.addEdge(1, 2)
    al.addEdge(2, 3)
    al.addEdge(3, 4)
    al.printGraph()
    # graph1 = {1: [2, 3], 2: [1, 4], 3: [1, 6, 7], 4: [2, 5], 5: [4, 6], 6: [3, 5], 7: [3]}


import streamlit as st
from formula import *
import math
from st_keyup import st_keyup

def convert_to_num(*args):
    try:
        return [int(i) for i in args]
    except ValueError:
        return [0 for i in args]

def format_output(value: int):
    try:
        return "{:,}".format(int(value))
    except ValueError:
        return ''

hide_menu_style = """
        <style>
        #MainMenu {visibility: hidden;}
        </style>
        """
st.markdown(hide_menu_style, unsafe_allow_html=True)
st.title('Расчет цены ипотеки')
res = 0
tax = 13  # подоходный налог
form = st.selectbox('Есть первоначальный взнос?', options=['Не выбрано', 'Да', 'Нет'], )

if form == 'Нет':
    buy = st_keyup(label=f'Первоначальная цена квартиры в руб: ')
    st.write(format_output(buy))

    sell = st_keyup('Цена при продаже на руки продавцу в руб (полностью)')
    st.write(format_output(sell))

    fee = st.number_input('Первоначальный взнос (%)', min_value=0, value=20)

    res = formula_without_entry_fee(*convert_to_num(sell, buy, tax, fee))

    st.subheader('Стоимость квартиры в ипотеку с занижением:')
    if res == 0:
        st.text('Сначала введите все данные')
    else:
        st.title('{:,}'.format(round(res, 2)).replace(',', ' ') + ' руб')

if form == 'Да':
    in_arms = st_keyup('Стоимость на руки продавцу в руб (полностью)')
    st.write(format_output(in_arms))

    dkp_seller = st_keyup('Стоимость в ДКП в руб (полностью)')
    st.write(format_output(dkp_seller))

    initial = st_keyup('Первоначальная цена квартиры в руб (полностью)')
    st.write(format_output(initial))

    bank = st.number_input('Банковский процент (%)', min_value=15)

    in_arms, dkp_seller, initial = convert_to_num(in_arms, dkp_seller, initial)
    res = round(math.ceil(formula_with_entry_fee(in_arms, dkp_seller, initial)))
    if res == 0:
        st.text('Сначала введите все данные')
    else:
        st.subheader('Стоимость квартиры в ипотеку с завышением:')
        st.subheader('{:,}'.format(res).replace(',', ' ') + ' руб')

        st.subheader('Первоначальный взнос: ')
        st.subheader('{:,}'.format(math.ceil(res * bank / 100)).replace(',', ' ') + ' руб')

        st.subheader('Сумма налога: ')
        st.subheader('{:,}'.format(math.ceil((res - initial) * 0.13)).replace(',', ' ') + ' руб ')
        st.text('Из них компенсирует продавец: ' + '{:,}'.format(math.ceil((dkp_seller - initial) * 0.13)))

        st.subheader('Покупатель компенсирует: ')
        st.subheader('{:,}'.format(math.ceil((res - initial) * 0.13 - (dkp_seller - initial) * 0.13)))


import flask
from flask import request,jsonify,render_template
import Module.poop as poop
import pickle

# buffer variables
# are meant to be declared here, we will share the stuffs
# with botogram bot!

primary_Gasbuffer = []
primary_LDRbuffer = []
usageCounter = []
#Std query format /update?valGas=100.00&valLDR=1015" 404 -

app = flask.Flask(__name__)
app.config["DEBUG"] = True

@app.route('/',methods = ['GET'])
def home_main():
    return "
Yaaay! this is basic website, it literally does nothing
"

@app.route('/update',methods=['GET'])
def Call_message():
    if 'valGas' in request.args:
        valGas = request.args['valGas']
        if 'valLDR' in request.args:
            valLDR = request.args['valLDR']
            if 'valPC' in request.args:
                valPC = request.args['valPC']

                print(valGas+" "+valLDR+" "+valPC)
                primary_Gasbuffer.append(valGas)
                primary_LDRbuffer.append(valLDR)
                usageCounter.append(valPC)

                gasBuffer = "file_gas"
                gas_object = open(gasBuffer, 'wb')
                ldrBuffer = "file_ldr"
                ldr_object = open(ldrBuffer, 'wb')
                pcBuffer = "file_pc"
                pc_object = open(pcBuffer, 'wb')
                #Stuffs ^
                pickle.dump(primary_Gasbuffer,gas_object)
                pickle.dump(primary_LDRbuffer,ldr_object)
                pickle.dump(usageCounter,pc_object)
                gas_object.close()
                ldr_object.close()
                pc_object.close()
                return ""
    else:
        return " "

app.run(host='0.0.0.0')


# python 体重转换器

weight = float(input("请输入你的体重："))
unit = input("你的体重是公斤还是磅？（kg/lb）").upper()

if unit == 'KG':
    weight *= 2.2
    new_unit = '磅'
elif unit == 'LB':
    weight /= 2.2
    new_unit = '公斤'
else:
    print('单位不正确')
    exit()

print(f'你的体重是 {round(weight)} {new_unit}')


import csv

import Manager
import binascii

class LoggerManager(Manager.Manager):

    def __init__(self, name=None ):
        super(LoggerManager, self).__init__()
        self._recording = False

        if name is None:
            self._recording = False
        else:
            self.new_file(name)
            self.recording = True

    @property
    def recording(self):
        return self._recording

    @recording.setter
    def recording(self, value):
        self._recording = value

    def start_recording(self):
        """
        Start recording
        :return:
        """
        self.recording = True

    def stop_recording(self):
        """
        stop recording
        :return: None
        """
        self.recording = False

    def new_file(self, name):
        """
        Create a new file to record the sensor data too
        :param name:
        :return:
        """
        if self.recording:
            """
            Throw an error if in the middle of recording
            """
            RuntimeError("IN THE MIDDLE OF RECORDING")
            return
        self._name = name + ".csv"
        with open(self._name, "a") as f:
            writer = csv.writer(f, delimiter=",")

    def update(self, packet):
        """
        write values the the CSV file
        :type sensors: dict
        """

        if self.recording:

            data = packet

            with open(self._name, "a") as f:
                writer = csv.writer(f, delimiter=",")
                writer.writerow(data)


# 368page
# 고정점 : 수열의 원소 중 그 값이 인덱스와 동일한 원소

# 강의 시작 전 풀이 시작
import sys

def binary_search(lst, start, end):
    if start == end and lst[start] != start:
        return -1

    mid = (start + end) // 2

    if lst[mid] == mid:
        return mid
    elif lst[mid] > mid:
        return binary_search(lst, start, mid-1)
    else:
        return binary_search(lst, mid+1, end)

N = int(sys.stdin.readline())
input_data = list(map(int, sys.stdin.readline().split()))
print(binary_search(input_data, 0, N-1))
# 강의 시작 전 풀이 끝

'''
입력:
5
-15 -6 1 3 7
출력 : 3
'''
'''
입력 :
7
-15 -4 2 8 9 13 15
출력 : 2
'''
'''
입력 :
7
-15 -4 3 8 9 13 15
출력 : -1
'''

이코테_Q28_고정점찾기.py


import pygame as pygame
import sys, random
from pygame.locals import *

pygame.init()

colors = {
    "background":[250,227,217],
    "ball":[255,182,185],
    "paddle":[187,222,214]
}
#게임 플레이에 주축이 되는 변수들 정의
WINDOW_WIDTH = 600
WINDOW_HEIGHT = 600
windowSize = [WINDOW_WIDTH,WINDOW_HEIGHT] #창 크기 설정
screen = pygame.display.set_mode(windowSize) #screen 생성
FPS = 60

FPSclock = pygame.time.Clock()
Running = True
pygame.display.set_caption("One Man Ping Pong")
class Ball:
    def __init__(self, x, y, radius, Spd):
        self.x = x
        self.y = y
        self.radius = radius
        self.XSpd = Spd
        self.YSpd = Spd
        self.WallColli = 0
    def draw(self):
        pygame.draw.circle(screen, colors["ball"], (self.x, self.y), self.radius)
        self.x += self.XSpd
        self.y += self.YSpd
    def collisionCheck(self):
        pygame.draw.circle(screen, (255,255,255), (75,75), self.radius)
        pygame.draw.circle(screen, (255,255,255), (75,125), self.radius)
        pygame.draw.circle(screen, (255,255,255), (50,100), self.radius)
        pygame.draw.circle(screen, (255,255,255), (100,100), self.radius)
        if(self.x + self.radius >= WINDOW_WIDTH or self.x - self.radius <= 0): #벽 충돌 이벤트
            self.XSpd *= -1
            self.WallColli += 1
        elif(self.y + self.radius >= WINDOW_HEIGHT or self.y - self.radius <= 0): #벽 충돌 이벤트
            self.YSpd *= -1
            self.WallColli += 1
        elif(self.x >= PaddleTOP.x - PaddleTOP.length/2 and self.x <= PaddleTOP.x + PaddleTOP.length/2): #상단 패들과 충돌 검사
            pygame.draw.circle(screen, (255,0,0), (75,75), self.radius)
            if(self.y - self.radius <= PaddleTOP.y + PaddleTOP.thickness/2):
                pygame.draw.circle(screen, (0,0,255), (75,75), self.radius)
                self.YSpd *= -1
                self.WallColli += 1
        elif(self.x >= PaddleBOTTOM.x - PaddleBOTTOM.length/2 and self.x <= PaddleBOTTOM.x + PaddleBOTTOM.length/2): #하단 패들과 충돌 검사
            pygame.draw.circle(screen, (255,0,0), (75,125), self.radius)
            if(self.y + self.radius >= PaddleBOTTOM.y - PaddleBOTTOM.thickness/2):
                pygame.draw.circle(screen, (0,0,255), (75,125), self.radius)
                self.YSpd *= -1
                self.WallColli += 1
        elif(self.y >= PaddleLEFT.y - PaddleLEFT.length/2 and self.y <= PaddleLEFT.y + PaddleLEFT.length/2): #왼쪽 패들과 충돌 검사
            pygame.draw.circle(screen, (255,0,0), (50,100), self.radius)
            if(self.x - self.radius <= PaddleLEFT.x + PaddleLEFT.thickness/2):
                pygame.draw.circle(screen, (0,0,255), (50,100), self.radius)
                self.XSpd *= -1
                self.WallColli += 1
        elif(self.y >= PaddleRIGHT.y - PaddleRIGHT.length/2 and self.y <= PaddleRIGHT.y + PaddleRIGHT.length/2): #오른쪽 패들과 충돌 검사
            pygame.draw.circle(screen, (255,0,0), (50,100), self.radius)
            if(self.x + self.radius >= PaddleRIGHT.x - PaddleRIGHT.thickness/2):
                pygame.draw.circle(screen, (0,0,255), (50,100), self.radius)
                self.XSpd *= -1
                self.WallColli += 1

class Paddle:
    def __init__(self, x, y, length, thickness):
        self.x = x
        self.y = y
        self.length = length
        self.thickness = thickness
    def drawTOP(self):
        self.x = mousex
        pygame.draw.line(screen, colors["paddle"],[self.x-(self.length/2),self.y],[self.x+(self.length/2),self.y],self.thickness)
    def drawBOTTOM(self):
        self.x = WINDOW_WIDTH-mousex
        pygame.draw.line(screen, colors["paddle"],[self.x-(self.length/2),self.y],[self.x+(self.length/2),self.y],self.thickness)
    def drawLEFT(self):
        self.y = mousey
        pygame.draw.line(screen, colors["paddle"],[self.x,self.y-(self.length/2)],[self.x,self.y+(self.length/2)],self.thickness)
    def drawRIGHT(self):
        self.y = WINDOW_HEIGHT-mousey
        pygame.draw.line(screen, colors["paddle"],[self.x,self.y-(self.length/2)],[self.x,self.y+(self.length/2)],self.thickness)

Ball = Ball(random.randrange(10,WINDOW_WIDTH-10),random.randrange(10,WINDOW_HEIGHT-10),10,4) #게임공
PaddleTOP = Paddle(random.randrange(0,WINDOW_WIDTH),30,100,14) #위쪽 패들
PaddleBOTTOM = Paddle(random.randrange(0,WINDOW_WIDTH),WINDOW_HEIGHT-30,100,14) #아랫쪽 패들
PaddleLEFT = Paddle(30,random.randrange(0,WINDOW_HEIGHT),100,14) #왼쪽 패들
PaddleRIGHT = Paddle(WINDOW_WIDTH-30,random.randrange(0,WINDOW_HEIGHT),100,14) #오른쪽 패들
mousex = 0
mousey = 0

while True:
    screen.fill(colors["background"])
    PaddleTOP.drawTOP()
    PaddleBOTTOM.drawBOTTOM()
    PaddleLEFT.drawLEFT()
    PaddleRIGHT.drawRIGHT()
    Ball.draw()
    Ball.collisionCheck()

    for event in pygame.event.get():
        if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE): #esc또는 X를 눌렀을 때 게임 종료
            pygame.quit()
            sys.exit()

    mousex,mousey = pygame.mouse.get_pos()
    print("("+str(mousex)+","+str(mousey)+") Wall Collision : "+str(Ball.WallColli)) # 마우스 위치 Logging
    pygame.draw.circle(screen, (255,0,0), (mousex, mousey), 5) #마우스 위치 표시
    pygame.display.flip()
    FPSclock.tick(FPS)


#QUESTIONS:
#the scale radius of the subhalos is the same as the scale radius of the halos
#do I center on the halo or instead on the main subhalo?
#check halos.is_resolved(). What happens when no intersection is found?

import os
import sys
import glob
import gzip
import argparse

import numpy as np

import dmprofile
from dmprofile.src.halos import Halos
from dmprofile.src import plot
from dmprofile.src.utilities import rho_crit, intersect
from dmprofile.src.move import centering_com, centering_mbp
from dmprofile.src.parser import add_args
from dmprofile.src.utilities import write_to_file as wf

FLAGS, _ = add_args(argparse.ArgumentParser())
print("Parsed arguments:")
for k,v in FLAGS.__dict__.items():
    print('{}: {}'.format(k,v))

st = FLAGS.sim_types
addition = ''
ss = FLAGS.sim_sizes[0]
if ss=='128': additon='.hdf5'
path_first = ['/fred/oz071/aduffy/Smaug/'+st[i]+'_L010N0'+ss+'/data' for i in range(len(st))]
redshift_dict = {5: '103', 6: '080', 7: '065', 8: '054', 9: '045'}
rshift = redshift_dict[FLAGS.redshift]
path1 = [os.path.join(path_first[i], 'subhalos_'+rshift+'/subhalo_'+rshift) for i in range(len(st))]
path2 = [os.path.join(path_first[i], 'snapshot_'+rshift+'/snap_'+rshift+addition) for i in range(len(st))]

h = [Halos(path1[i], min_size=FLAGS.sim_min_particle_number) for i in range(len(st))]
N = [h[i].get_number_halos() for i in range(len(st))]

for isim in range(len(st)):
    c, M200, M200_shape, res, rel, s = ([] for i in range(6))
    for i in range(N[isim]):
        print("SIM", st[isim], "  HALO:", i)
        with centering_com(h[isim].get_halo(i), r=h[isim]._get_r200(i)):
            print(h[isim].get_halo(i))
            isres = h[isim].is_resolved(i, sub_idx=0)
            isrel = h[isim].is_relaxed(i, sub_idx=0)
            relax_tmp = h[isim].concentration_200(idx=i, sub_idx=0)
            s_tmp = h[isim].get_shape(i, 0)
            if s_tmp!=-1 and isres!=-1 and relax_tmp!=-1 and isrel!=-1:
                M200.append(h[isim].get_mass200(i))
                res.append(isres)
                rel.append(isrel)
                c.append(relax_tmp)
                M200_shape.append(np.log10(h[isim].get_mass200(i)))
                s.append(s_tmp)
    wf('data3/Concentration_'+st[isim]+'_'+str(FLAGS.sim_min_particle_number)+
       '_'+ss+'_redshift'+str(FLAGS.redshift)+'.txt', c, M200, res, rel)
    wf('data3/Shape_'+st[isim]+'_'+str(FLAGS.sim_min_particle_number)+
       '_'+ss+'_redshift'+str(FLAGS.redshift)+'.txt', s, M200_shape, mode='shape')


#coding:utf-8
## https://zhuanlan.zhihu.com/p/38006693
import sklearn
import sklearn.datasets
import numpy as np

def sigmoid(input_sum):
    output = 1.0/(1 + np.exp(-input_sum))
    return output, input_sum

def sigmoid_back(derror_wrt_output, input_sum):
    output = 1.0/(1 + np.exp(-input_sum))
    doutput_wrt_dinput = output * (1 - output)
    derror_wrt_dinput = derror_wrt_output * doutput_wrt_dinput
    return derror_wrt_dinput

def activated(activation_choose, input):
    if activation_choose == 'sigmoid':
        return sigmoid(input)

    return sigmoid(input)

class NeuralNetwork:
    def __init__(self, layers_structure, print_cost=False):
        self.layers_structure = layers_structure
        self.layers_num = len(layers_structure)

        self.param_layers_num = self.layers_num - 1

        self.learning_rate = 0.0618
        self.num_iterations = 2000
        self.x = None
        self.y = None
        self.w = dict()
        self.b = dict()
        self.costs = []
        self.print_cost = print_cost

        self.init_w_b()

    def init_w_b(self):
        np.random.seed(3)

        for l in range(1, self.layers_num):
            self.w["w" + str(l)] = np.random.randn(self.layers_structure[l], self.layers_structure[l-1])/np.sqrt(self.layers_structure[l-1])
            self.b["b" + str(l)] = np.zeros((self.layers_structure[l], 1))

        return self.w, self.b

    def set_learning_rate(self, learning_rate):
        self.learning_rate = learning_rate

    def set_num_iterations(self, num_iterations):
        self.num_iterations = num_iterations

    def set_xy(self, input, label):
        self.x = input
        self.y = label

    def layer_activation_forward(self, x, w, b, activation_choose):
        input_sum = np.dot(w,x) + b
        output, _ = activated(activation_choose, input_sum)
        return output, (x, w, b, input_sum)

    def forward_propagation(self, x):
        caches = []
        output_prev = x
        L = self.param_layers_num
        for l in range(1,L):
            input_cur = output_prev
            output_prev, cache = self.layer_activation_forward(input_cur, self.w["w" + str(l)], self.b["b" + str(l)], "sigmoid")
            caches.append(cache)

        output, cache = self.layer_activation_forward(output_prev, self.w["w" + str(L)], self.b["b" + str(L)], "sigmoid")
        caches.append(cache)

        return output, caches

    def compute_error(self, output):
        m = self.y.shape[1]
        error = np.sum(0.5 * (self.y - output) ** 2) / m
        error = np.squeeze(error)

        return error

    def layer_activation_backward(self, derror_wrt_output, cur_cache):
        input, w, b, input_sum = cur_cache
        output_prev = input
        m = output_prev.shape[1]

        derror_wrt_dinput = sigmoid_back(derror_wrt_output, input_sum)
        derror_wrt_dw = np.dot(derror_wrt_dinput, output_prev.T) / m

        derror_wrt_db = np.sum(derror_wrt_dinput, axis=1, keepdims=True)/m

        derror_wrt_output_prev = np.dot(w.T, derror_wrt_dinput)

        return derror_wrt_output_prev, derror_wrt_dw, derror_wrt_db

    def back_propagation(self, output, caches):

        """
        函数:
            神经网络的反向传播
        输入:
            output：神经网络输
            caches：所有网络层（输入层不算）的缓存参数信息  [(x, w, b, input_sum), ...]
        返回:
            grads: 返回当前迭代的梯度信息
        """

        grads = {}
        L = self.param_layers_num #
        output = output.reshape(output.shape)  # 把输出层输出输出重构成和期望输出一样的结构

        expected_output = self.y

        # 见式(5.8)
        #derror_wrt_output = -(expected_output - output)

        # 交叉熵作为误差函数
        derror_wrt_output = - (np.divide(expected_output, output) - np.divide(1 - expected_output, 1 - output))

        # 反向传播：输出层 -> 隐藏层，得到梯度：见式(5.8), (5.13), (5.15)
        current_cache = caches[L - 1] # 取最后一层,即输出层的参数信息
        grads["derror_wrt_output" + str(L)], grads["derror_wrt_dw" + str(L)], grads["derror_wrt_db" + str(L)] = \
            self.layer_activation_backward(derror_wrt_output, current_cache)

        # 反向传播：隐藏层 -> 隐藏层，得到梯度：见式 (5.28)的(Σδ·w), (5.28), (5.32)
        for l in reversed(range(L - 1)):
            current_cache = caches[l]
            derror_wrt_output_prev_temp, derror_wrt_dw_temp, derror_wrt_db_temp = \
                self.layer_activation_backward(grads["derror_wrt_output" + str(l + 2)], current_cache)

            grads["derror_wrt_output" + str(l + 1)] = derror_wrt_output_prev_temp
            grads["derror_wrt_dw" + str(l + 1)] = derror_wrt_dw_temp
            grads["derror_wrt_db" + str(l + 1)] = derror_wrt_db_temp

        return grads

    def update_w_and_b(self, grads):
        """
        函数:
            根据梯度信息更新w，b
        输入:
            grads：当前迭代的梯度信息
        返回:

        """

        # 权值w和偏置b的更新，见式:（5.16),(5.18)
        for l in range(self.param_layers_num):
            self.w["w" + str(l + 1)] = self.w["w" + str(l + 1)] - self.learning_rate * grads["derror_wrt_dw" + str(l + 1)]
            self.b["b" + str(l + 1)] = self.b["b" + str(l + 1)] - self.learning_rate * grads["derror_wrt_db" + str(l + 1)]

    def training_module(self):
        np.random.seed(5)
        for i in range(0 ,self.num_iterations):
            output, caches = self.forward_propagation(self.x)
            cost = self.compute_error(output)
            grads = self.back_propagation(output, caches)
            self.update_w_and_b(grads)
            #当次迭代结束，打印误差信息
            if self.print_cost and i % 1000 == 0:
                print ("Cost after iteration %i: %f" % (i, cost))
            if self.print_cost and i % 1000 == 0:
                self.costs.append(cost)

        return self.w, self.b

if __name__ == "__main__":
    # 60个点，noise噪声系数越大噪声越大，两种点
    xy, colors = sklearn.datasets.make_moons(60, noise=1.0)
    # 输出层2个神经元，[1,0] [0,1]为两个类别
    y = []
    for c in colors:
        if c == 1:
            y.append([0,1])
        else:
            y.append([1,0])
    y = np.array(y).T
    # import pdb
    # pdb.set_trace()

    hidden_layer_neuron_num_list = [1,2,4,10,20,50]

    #for i, hidden_layer_neuron_num in enumerate(hidden_layer_neuron_num_list):
    nn = NeuralNetwork([2, 4, 2], True)
    print(nn)
    nn.set_xy(xy.T, y)
    nn.set_num_iterations(30000)
    nn.set_learning_rate(0.1)
    w, b = nn.training_module()
    print("%i iter w:", w)
    print("%i iter b:", b)


### https://github.com/mahakal001/reinforcement-learning/tree/master/cartpole-dqn

import torch
from torch import nn
import copy
from collections import deque
import random

class DQN_Agent:

    def __init__(self, seed, layer_sizes, lr, sync_freq, exp_replay_size):
        torch.manual_seed(seed)
        self.q_net = self.build_nn(layer_sizes).to(device)
        self.target_net = copy.deepcopy(self.q_net).to(device)

        self.loss_fn = torch.nn.MSELoss()
        self.optimizer = torch.optim.Adam(self.q_net.parameters(), lr=lr)

        self.network_sync_freq = sync_freq
        self.network_sync_counter = 0
        self.gamma = torch.tensor(0.95).float().to(device)
        self.experience_replay = deque(maxlen=exp_replay_size)
        return

    def build_nn(self, layer_sizes):
        assert len(layer_sizes) > 1
        layers = []
        for index in range(len(layer_sizes) - 1):
            linear = nn.Linear(layer_sizes[index], layer_sizes[index + 1])
            act = nn.Tanh() if index < len(layer_sizes) - 2 else nn.Identity()
            layers += (linear, act)
        return nn.Sequential(*layers)

    def load_pretrained_model(self, model_path):
        self.q_net.load_state_dict(torch.load(model_path))

    def save_trained_model(self, model_path="cartpole-dqn.pth"):
        torch.save(self.q_net.state_dict(), model_path)

    def get_action(self, state, action_space_len, epsilon):
        # We do not require gradient at this point, because this function will be used either
        # during experience collection or during inference
        with torch.no_grad():
            Qp = self.q_net(torch.from_numpy(state).float().to(device))
        Q, A = torch.max(Qp, axis=0)
        A = A if torch.rand(1, ).item() > epsilon else torch.randint(0, action_space_len, (1,))
        return A

    def get_q_next(self, state):
        with torch.no_grad():
            qp = self.target_net(state)
        q, _ = torch.max(qp, axis=1)
        return q

    def collect_experience(self, experience):
        self.experience_replay.append(experience)
        return

    def sample_from_experience(self, sample_size):
        if len(self.experience_replay) < sample_size:
            sample_size = len(self.experience_replay)
        sample = random.sample(self.experience_replay, sample_size)
        s = torch.tensor([exp[0] for exp in sample]).float()
        a = torch.tensor([exp[1] for exp in sample]).float()
        rn = torch.tensor([exp[2] for exp in sample]).float()
        sn = torch.tensor([exp[3] for exp in sample]).float()
        return s, a, rn, sn

    def train(self, batch_size):
        s, a, rn, sn = self.sample_from_experience(sample_size=batch_size)
        if self.network_sync_counter == self.network_sync_freq:
            self.target_net.load_state_dict(self.q_net.state_dict())
            self.network_sync_counter = 0

        # predict expected return of current state using main network
        qp = self.q_net(s.to(device))
        pred_return, _ = torch.max(qp, axis=1)

        # get target return using target network
        q_next = self.get_q_next(sn.to(device))
        target_return = rn.to(device) + self.gamma * q_next

        loss = self.loss_fn(pred_return, target_return)
        self.optimizer.zero_grad()
        loss.backward(retain_graph=True)
        self.optimizer.step()

        self.network_sync_counter += 1
        return loss.item()

import gym
from tqdm import tqdm
import time

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

def train():
    env = gym.make('CartPole-v0')
    input_dim = env.observation_space.shape[0]
    output_dim = env.action_space.n
    exp_replay_size = 256
    agent = DQN_Agent(seed=1423, layer_sizes=[input_dim, 64, output_dim], lr=1e-3, sync_freq=5,
                      exp_replay_size=exp_replay_size)

    # Main training loop
    losses_list, reward_list, episode_len_list, epsilon_list = [], [], [], []
    episodes = 10000
    epsilon = 1

    # initialize experience replay
    index = 0
    for i in range(exp_replay_size):
        obs = env.reset()
        done = False
        while not done:
            A = agent.get_action(obs, env.action_space.n, epsilon=1)
            obs_next, reward, done, _ = env.step(A.item())
            agent.collect_experience([obs, A.item(), reward, obs_next])
            obs = obs_next
            index += 1
            if index > exp_replay_size:
                break

    index = 128
    for i in tqdm(range(episodes)):
        obs, done, losses, ep_len, rew = env.reset(), False, 0, 0, 0
        while not done:
            ep_len += 1
            A = agent.get_action(obs, env.action_space.n, epsilon)
            obs_next, reward, done, _ = env.step(A.item())
            agent.collect_experience([obs, A.item(), reward, obs_next])

            obs = obs_next
            rew += reward
            index += 1

            if index > 128:
                index = 0
                for j in range(4):
                    loss = agent.train(batch_size=16)
                    losses += loss
        if epsilon > 0.05:
            epsilon -= (1 / 5000)

        losses_list.append(losses / ep_len), reward_list.append(rew)
        episode_len_list.append(ep_len), epsilon_list.append(epsilon)

    print("Saving trained model")
    agent.save_trained_model("cartpole-dqn.pth")

def test():

    env = gym.make('CartPole-v0')
    # env = gym.wrappers.Monitor(env, "record_dir", force='True')

    input_dim = env.observation_space.shape[0]
    output_dim = env.action_space.n
    exp_replay_size = 256
    agent = DQN_Agent(seed=1423, layer_sizes=[input_dim, 64, output_dim], lr=1e-3, sync_freq=5,
                      exp_replay_size=exp_replay_size)
    agent.load_pretrained_model("cartpole-dqn.pth")

    reward_arr = []
    for i in tqdm(range(100)):
        obs, done, rew = env.reset(), False, 0
        while not done:
            A = agent.get_action(obs, env.action_space.n, epsilon=0)
            obs, reward, done, info = env.step(A.item())
            rew += reward
            time.sleep(0.01)
            env.render()

        reward_arr.append(rew)
    print("average reward per episode :", sum(reward_arr) / len(reward_arr))

if __name__ == '__main__':
    # train()
    test()


import os
import numpy as np
import pandas as pd
from sklearn.metrics import log_loss, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, MinMaxScaler
import random
from deepctr.models import DeepFM,FLEN
from tensorflow.keras.callbacks import EarlyStopping,ModelCheckpoint
from deepctr.feature_column import SparseFeat, DenseFeat, get_feature_names
import pickle
from tqdm import tqdm_notebook
from collections import Counter

data_dir = '../data/离线实验_0923/'
os.makedirs(data_dir,exist_ok=True)

student_metadata =  pd.read_csv('../data/public_data/metadata/student_metadata_task_1_2.csv')
question_metadata =  pd.read_csv('../data/public_data/metadata/question_metadata_task_1_2.csv')
answer_metadata =  pd.read_csv('../data/public_data/metadata/answer_metadata_task_1_2.csv')
subject_metadata =  pd.read_csv('../data/public_data/metadata/subject_metadata.csv')

subject_metadata.index = subject_metadata['SubjectId']
subject_metadata.fillna(0,inplace=True)
subject_metadata['ParentId'] = subject_metadata['ParentId'].apply(int)

def add_date_feature(df, col):
    df[col].fillna("0000-08-01 00:00:00.000", inplace=True)
    df['{}_Split'.format(col)] = df[col].apply(
        lambda x: x.split()[0].split('-'))
    df['{}_Year'.format(col)] = df['{}_Split'.format(col)
                                   ].apply(lambda x: int(x[0]))
    df['{}_Month'.format(col)] = df['{}_Split'.format(col)
                                    ].apply(lambda x: int(x[1]))
    df['{}_Year_Month'.format(col)] = df.apply(lambda x:
                                               '{}_{}'.format(
                                                   x['{}_Year'.format(col)],
                                                   x['{}_Month'.format(col)]), axis=1)
    return df

question_metadata['SubjectId'] = question_metadata['SubjectId'].apply(eval)
question_metadata['subject_num'] = question_metadata['SubjectId'].apply(len)

que_to_subject = dict(zip(question_metadata['QuestionId'],question_metadata['SubjectId']))

n = 10
que_feature_map = {}
for que_id,subject_list in que_to_subject.items():
    feature_list = []
    feature_list = subject_list+[-1]*n
    que_feature_map[que_id] = feature_list[:n]

def add_subject_col(df,n=8):
    tmp = df['QuestionId'].map(que_feature_map)
    tmp = pd.DataFrame(np.array(tmp.tolist()),columns=["subject_{}".format(i) for i in range(1,n+1)])
    df = pd.concat([tmp,df],axis=1)
    return df

student_metadata['PremiumPupil'].fillna(2,inplace=True)
student_metadata = add_date_feature(student_metadata,'DateOfBirth')

answer_metadata = add_date_feature(answer_metadata,'DateAnswered')

df_all_train = pd.read_csv('../data/public_data/train_data/train_task_1_2.csv')
## 用户能力预估
question_difficulty_dict = df_all_train.groupby('QuestionId')['IsCorrect'].agg(lambda x:x.mean()).to_dict()
user_ability_dict = df_all_train.groupby('UserId')['IsCorrect'].agg(lambda x:x.mean()).to_dict()

user_history_ability_dict = pickle.load(open('../data/离线实验/user_history_ability_dict.pkl','rb'))
user_history_subject_ability_dict = pickle.load(open('../data/离线实验/user_history_subject_ability_dict.pkl','rb'))

QuestionId2SubjectId = dict(zip(question_metadata['QuestionId'],question_metadata['SubjectId']))
len(QuestionId2SubjectId)

# 获取历史的能力
def get_history_ability_list(df):
    history_ability_list = []
    for ym,UserId in tqdm_notebook(zip(df['DateAnswered_YearMonth'],df['UserId'])):
        history_ability = user_history_ability_dict.get(ym, {}).get(UserId, 0.5)
        history_ability_list.append(history_ability)
    return history_ability_list
# 获取历史知识点的能力
def add_history_subject_ability_list(df,n = 10):
    history_ability_list = []
    for ym, UserId, QuestionId in tqdm_notebook(zip(df['DateAnswered_YearMonth'], df['UserId'], df['QuestionId'])):
        feature_list = []
        for i,SubjectId in enumerate(QuestionId2SubjectId[QuestionId],1):
            value = user_history_subject_ability_dict.get(
                ym, {}).get((UserId,SubjectId), 0.5)
            feature_list.append(value)
        feature_list = feature_list+[0.5]*n
        history_ability_list.append(feature_list[:n])
    tmp = pd.DataFrame(np.array(history_ability_list), columns=[
                       "history_subject_ability_{}".format(i) for i in range(1, n+1)])
    df = pd.concat([tmp,df],axis=1)
    return df

def merge_df(df_path, pkl_path):
    df = pd.read_csv(df_path)
    df = df.merge(answer_metadata, how='left')
    df_add_student_info = df.merge(student_metadata, how='left')
    df_add_subejct = add_subject_col(df_add_student_info, n=10)
    df_add_subejct['question_difficulty'] = df_add_subejct['QuestionId'].map(
        question_difficulty_dict)
    df_add_subejct['user_ability'] = df_add_subejct['UserId'].map(
        user_ability_dict)
    df_add_subejct['DateAnswered_YearMonth'] = df_add_subejct['DateAnswered_Year']*100+df_add_subejct['DateAnswered_Month']
    # 增加history_ability
    df_add_subejct['history_ability'] = get_history_ability_list(
        df_add_subejct)
    df_add_subejct = add_history_subject_ability_list(df_add_subejct,n=10)
    with open(pkl_path, 'wb') as f:
        pickle.dump(df_add_subejct, f)
    return df_add_subejct

# 获取lbe_dict

def get_lbe_dict(df, features):
    df[features] = df[features].fillna('-1', )
    lbe_dict = {}
    for feat in features:
        df[feat] = df[feat].apply(int)
        lbe = LabelEncoder()
        lbe.fit(df[feat])
        lbe_dict[feat] = lbe
    return lbe_dict

def encode_df(df, lbe_dict, feature_names):
    random.seed(0)
    for feat in tqdm_notebook(feature_names):
        df[feat] = df[feat].fillna('-1', )
        lbe = lbe_dict[feat]
        df[feat] = df[feat].apply(int)
        lbe_class_dict = dict(zip(lbe.classes_, lbe.classes_))
        df[feat] = df[feat].map(lambda s: random.choice(
            lbe.classes_) if s not in lbe_class_dict else s)
        df[feat] = lbe.transform(df[feat])
    return df

answer_features = ['GroupId', 'QuizId', 'SchemeOfWorkId','DateAnswered_Year', 'DateAnswered_Month','Confidence']
feature_names = ['subject_1', 'subject_2', 'subject_3', 'subject_4', 'subject_5',
                 'subject_6', 'subject_7', 'subject_8', 'subject_9', 'subject_10',
                 'QuestionId', 'UserId', 'Gender', 'PremiumPupil',
                 'DateOfBirth_Year', 'DateOfBirth_Month','DateAnswered_YearMonth']+answer_features

df_path = '../data/public_data/train_data/train_task_1_2.csv'
pkl_path = os.path.join(data_dir,'raw_train.pkl')
pkl_encode_path = os.path.join(data_dir,'raw_train_encode.pkl')

df = merge_df(df_path,pkl_path)

df['DateAnswered_YearMonth'] = df['DateAnswered_Year']*100+df['DateAnswered_Month']

user_history_ability_dict = {}
for ym in tqdm_notebook(df['DateAnswered_YearMonth'].unique()):
    df_ym = df[df['DateAnswered_YearMonth']<ym].copy()
    if df_ym.shape[0]==0:
        continue
    user_history_ability = df_ym.groupby('UserId')['IsCorrect'].mean().to_dict()
    user_history_ability_dict[ym] = user_history_ability

with open('../data/离线实验/user_history_ability_dict.pkl','wb') as f:
    pickle.dump(user_history_ability_dict,f)

def get_history_ability_list(df):
    history_ability_list = []
    for ym,UserId in tqdm_notebook(zip(df['DateAnswered_YearMonth'],df['UserId'])):
        history_ability = user_history_ability_dict.get(ym, {}).get(UserId, 0.5)
        history_ability_list.append(history_ability)
    return history_ability_list

df['history_ability'] = get_history_ability_list(df)

question_metadata =  pd.read_csv('../data/public_data/metadata/question_metadata_task_1_2.csv')
question_metadata['SubjectId'] = question_metadata['SubjectId'].apply(eval)
question_metadata['subject_num'] = question_metadata['SubjectId'].apply(len)

QuestionId2SubjectId = dict(zip(question_metadata['QuestionId'],question_metadata['SubjectId']))
len(QuestionId2SubjectId)

new_list = []
for _,row in question_metadata.iterrows():
    for SubjectId in row['SubjectId']:
        new_list.append({"SubjectId":SubjectId,"QuestionId":row['QuestionId']})

question_metadata_flatten = pd.DataFrame(new_list)

df_raw_add_subject = df_raw[['QuestionId', 'UserId', 'IsCorrect',
                             'DateAnswered_YearMonth']].merge(question_metadata_flatten)

user_history_subject_ability_dict = {}
for ym in tqdm_notebook(df_raw_add_subject['DateAnswered_YearMonth'].unique()):
    df_ym = df_raw_add_subject[df_raw_add_subject['DateAnswered_YearMonth']<ym].copy()
    if df_ym.shape[0]==0:
        continue
    user_history_subject_ability = df_ym.groupby(['UserId','SubjectId'])['IsCorrect'].mean().to_dict()
    user_history_subject_ability_dict[ym] = user_history_subject_ability

with open('../data/离线实验/user_history_subject_ability_dict.pkl','wb') as f:
    pickle.dump(user_history_subject_ability_dict,f)

def add_history_subject_ability_list(df,n = 10):
    history_ability_list = []
    for ym, UserId, QuestionId in tqdm_notebook(zip(df['DateAnswered_YearMonth'], df['UserId'], df['QuestionId'])):
        feature_list = []
        for i,SubjectId in enumerate(QuestionId2SubjectId[QuestionId],1):
            value = user_history_subject_ability_dict.get(
                ym, {}).get((UserId,SubjectId), 0.5)
            feature_list.append(value)
        feature_list = feature_list+[0.5]*n
        history_ability_list.append(feature_list[:n])
    tmp = pd.DataFrame(np.array(history_ability_list), columns=[
                       "history_subject_ability_{}".format(i) for i in range(1, n+1)])
    df = pd.concat([tmp,df],axis=1)
    return df

df_tmp = add_history_subject_ability_list(df_raw[:20000])


import pandas as pd
import numpy as np
import math
import os.path

DAYS_COUNT = {4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 26}
PER_STATE_DATA_PATH = './data/daily_report_per_states/'
KEPT_FIELDS = ["Confirmed", "Deaths", "Recovered", "Active", "FIPS", "Incident_Rate", "People_Tested",
               "People_Hospitalized", "Mortality_Rate", "UID", "ISO3", "Testing_Rate", "Hospitalization_Rate"]

def file_exists(path):
    if(os.path.isfile(path)):
        return True
    return False

def reset_all_state_files():
    states_file = PER_STATE_DATA_PATH + 'states/states.csv'
    states = pd.read_csv(states_file, engine="python")
    for index, row in states.iterrows():
        state = row.loc['State']
        path = PER_STATE_DATA_PATH + state + ".csv"
        if(not file_exists(path)):
            open(path, "x")
        file = open(path, "w")
        file.truncate()
        init_row = "Date"
        for field in KEPT_FIELDS:
            init_row += "," + field
        init_row += "\n"
        file.write(init_row)

def day_str(date):
    if (date < 10):
        return "0" + str(date)
    return str(date)

# partition input data by state

def partition_state(data, date):
    for index, row in data.iterrows():
        state_csv_file = PER_STATE_DATA_PATH + \
            row.loc["Province_State"] + ".csv"
        if (not file_exists(state_csv_file)):
            continue
        csv_row = date
        for field in row.values[5:]:
            if (isinstance(field, str)):
                csv_row = csv_row + ',' + field
            elif (math.isnan(field)):
                csv_row = csv_row + ','
            else:
                csv_row = csv_row + ',' + str(field)
        csv_row = csv_row + "\n"
        with open(state_csv_file, 'a') as fd:
            fd.write(csv_row)
        # append csv files

def main():
    reset_all_state_files()

    for month in DAYS_COUNT:
        for day in range(1, DAYS_COUNT[month]+1):
            date = "0" + str(month) + "-" + day_str(day)
            filename = date + "-2020.csv"
            file_path = './data/daily_report/' + filename
            if(not file_exists(file_path)):
                continue
            daily_report_data = pd.read_csv(file_path, engine="python")
            partition_state(daily_report_data, date)
            # add methods here

if __name__ == "__main__":
    main()


if __name__ == '__main__':
    import gensim
    from gensim import corpora
    from gensim.models import LdaModel
    import jieba
    import os

    # 加载停用词
    stop_words = set()
    with open("stopwordlist.txt", "r", encoding="utf-8") as file:
        for line in file:
            stop_words.add(line.strip())

    # 分词函数
    def tokenize(text):
        words = jieba.cut(text)
        return [word for word in words if word not in stop_words]

    # 读取文本文件
    def read_documents(directory):
        documents = []
        for filename in os.listdir(directory):
            with open(os.path.join(directory, filename), "r", encoding="utf-8") as file:
                text = file.read()
                documents.append(tokenize(text))
        return documents

    # 从文件夹中读取文档
    document_directory = "/Users/wei/PycharmProjects/wordfreq/documents"
    documents = read_documents(document_directory)

    # 创建词典和文档-词频矩阵
    dictionary = corpora.Dictionary(documents)
    corpus = [dictionary.doc2bow(doc) for doc in documents]

    # 训练LDA模型
    num_topics = 5  # 指定主题数量
    lda_model = LdaModel(corpus, num_topics=num_topics, id2word=dictionary, passes=15)

    # 打印每个主题的词语分布
    topics = lda_model.print_topics(num_topics=num_topics, num_words=10)
    for topic in topics:
        print(topic)


from panda3d.core import Point3

from direct.actor.Actor import Actor
from direct.distributed.DistributedNode import DistributedNode
from direct.distributed.ClockDelta import globalClockDelta
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.fsm.ClassicFSM import ClassicFSM
from direct.fsm.State import State
from direct.interval.IntervalGlobal import LerpPosInterval, LerpColorScaleInterval, Sequence, Parallel, Wait, Func

import ButterflyGlobals
import random

class DistributedButterfly(DistributedNode):
    notify = directNotify.newCategory('DistributedButterfly')

    def __init__(self, cr):
        DistributedNode.__init__(self, cr)
        self.wingType = None
        self.hood = None
        self.butterfly = None
        self.shadow = None
        self.flyTrack = None
        self.fsm = ClassicFSM('DBF', [State('off', self.enterOff, self.exitOff),
                                      State('sit', self.enterSit, self.exitSit),
                                      State('fly', self.enterFly, self.exitFly)],
                              'off', 'off')
        self.fsm.enterInitialState()

    def setWingType(self, wingType):
        self.wingType = wingType

    def setHood(self, hood):
        self.hood = hood

    def setState(self, state, fromLoc, toLoc, timestamp = None):
        if timestamp is not None:
            ts = globalClockDelta.localElapsedTime(timestamp)
        else:
            ts = 0.0

        self.fsm.request(ButterflyGlobals.StateIdx2State[state], [fromLoc, toLoc, ts])

    def enterOff(self):
        pass

    def exitOff(self):
        pass

    def enterSit(self, fromLoc, toLoc, ts = 0.0):
        self.butterfly.loop('land')
        spot = ButterflyGlobals.Spots[self.hood][toLoc]
        self.setPos(spot)
        self.shadow.setColorScale(0, 0, 0, 1)
        self.shadow.show()

    def exitSit(self):
        self.butterfly.stop()

    def enterFly(self, fromLoc, toLoc, ts = 0.0):
        endLoc = ButterflyGlobals.Spots[self.hood][toLoc]
        startLoc = ButterflyGlobals.Spots[self.hood][fromLoc]
        distance = (endLoc - startLoc).length()
        time = distance / ButterflyGlobals.Speed

        mp = Point3((endLoc.getX() + startLoc.getX()) / 2.0,
                    (endLoc.getY() + startLoc.getY()) / 2.0,
                    (endLoc.getZ() + startLoc.getZ()) / 2.0)
        mp.setZ(mp.getZ() + random.uniform(10.0, 20.0))

        self.setPos(startLoc)
        self.headsUp(endLoc)
        self.setH(self.getH() - 180)

        self.flyTrack = Parallel(
            LerpColorScaleInterval(self.shadow, 1.0, (0, 0, 0, 0), (0, 0, 0, 1)),
            Sequence(LerpPosInterval(self, time / 2.0, mp, startLoc, blendType = 'easeIn'),
                     LerpPosInterval(self, time / 2.0, endLoc, mp, blendType = 'easeOut')),
            Sequence(Func(self.butterfly.loop, 'flutter'),
                     Wait(time - (time / 4.0)),
                     Func(self.butterfly.loop, 'glide'),
                     Wait(time / 4.0),
                     Func(self.butterfly.loop, 'land'))
        )
        self.flyTrack.start(ts)

    def exitFly(self):
        self.stopFlyTrack()

    def stopFlyTrack(self):
        if self.flyTrack:
            self.flyTrack.finish()
        self.flyTrack = None

    def generate(self):
        self.butterfly = Actor('phase_4/models/props/SZ_butterfly-mod.bam', {'flutter': 'phase_4/models/props/SZ_butterfly-flutter.bam',
                                                                             'glide': 'phase_4/models/props/SZ_butterfly-glide.bam',
                                                                             'land': 'phase_4/models/props/SZ_butterfly-land.bam'})
        self.butterfly.reparentTo(self)
        self.shadow = loader.loadModel("phase_3/models/props/drop_shadow.bam")
        self.shadow.setBillboardAxis(2)
        self.shadow.setColor(0, 0, 0, 0.5, 1)
        self.shadow.setScale(0.08)
        self.shadow.reparentTo(self)
        DistributedNode.generate(self)

    def announceGenerate(self):
        DistributedNode.announceGenerate(self)

        for wingType in range(1, 7):
            if wingType != self.wingType:
                self.butterfly.find("**/wings_" + str(wingType)).removeNode()

        self.reparentTo(render)

    def disable(self):
        self.fsm.requestFinalState()
        self.stopFlyTrack()
        if self.shadow:
            self.shadow.removeNode()
        self.shadow = None
        if self.butterfly:
            self.butterfly.cleanup()
            self.butterfly.removeNode()
        self.butterfly = None
        self.hood = None
        self.wingType = None
        self.fsm = None
        DistributedNode.disable(self)


import pykka
from slack_utils import wrapper
from collections import namedtuple
import requests
from dateutil import parser
import json

def get_color(predicate):
    return "good" if predicate else "danger"

def act(url):
    try:
        response = requests.get(url)
        raw_content = response.content.decode('utf-8')
        live_report = json.loads(raw_content, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))

        wrapper.print("", title="{0} - {1}".format(live_report.ServiceName, live_report.Version), color="good",
                      fallback="Service status")

        wrapper.print("", title="RabbitMq", color=get_color(live_report.IsRabbitMqAlive), fallback="Rabbit status")
        wrapper.print("", title="Database", color=get_color(live_report.IsDatabaseAlive),
                      fallback="Database status")

        for transmission in live_report.TransmissionStatistics:
            date = parser.parse(transmission.TransmissionsDate)
            title = "Transmission for: {0}".format(date.strftime("%Y-%B-%d"))
            text = "Published {0} messages, failed {1}. \n Consumed {2} message, failed {3}".format(
                transmission.SuccedPublishedMessage, transmission.FailedToPublishedMessage,
                transmission.ConsumedMessage, transmission.FailedToConsumeMessage)
            wrapper.print("", text=text, title=title, fallback="title")
    except:
        wrapper.print("", title="Service is on url {0} is unavailable".format(url), color="danger")

class ServiceStatusActor(pykka.ThreadingActor):
    def on_receive(self, message):
        message_content = message.get("text", None)

        if message_content == "!status":
            act("http://localhost:5000")


T = int(input())

for t in range(1, T + 1):
    N = int(input())
    money = [50000, 10000, 5000, 1000, 500, 100, 50, 10]
    rest = N    # divmod 함수에 첫 입력값 할당 후 반복하기 위해 N을 rest에 대입
    print(f'#{t}')
    for m in money:         # quotient == 몫
        quotient, rest = divmod(rest, m)          # 큰 수를 할 때 빠름
        # quotient, rest = (rest // m, rest % m)      # 작은 수를 할 때 빠름
        print(quotient, end=' ')
    print()