import sys

def dfs(i, visited, dpth, graph):
    ans = 0
    if dpth == 4:
        return 1
    else:
        visited[i] = True
        for next in graph[i]:
            if not visited[next]:
                visited[next] = True
                ans += dfs(next, visited, dpth + 1, graph)
                # 주의 --> 방문 현황 갱신 필요
                visited[next] = False
        return ans

n, m = map(int, sys.stdin.readline().split())
graph = [[] for _ in range(n)]

for i in range(m):
    n1, n2 = map(int, sys.stdin.readline().split())
    graph[n1].append(n2)
    graph[n2].append(n1)

answer = 0
for i in range(n):
    visited = [False for _ in range(n)]
    if dfs(i, visited, 0, graph) > 0:
        answer = 1
        break

print(answer)


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Try to change the value of alpha
def mf_sgd(R, K=64, alpha=1e-4, beta=1e-2, iterations=50):
    """
    :param R: user-item rating matrix
    :param K: number of latent dimensions
    :param alpha: learning rate
    :param beta: regularization parameter
    """
    num_users, num_items = R.shape

    # Initialize user and item latent feature matrice
    P = np.random.normal(scale=1. / K, size=(num_users, K))
    Q = np.random.normal(scale=1. / K, size=(num_items, K))

    # Initialize the biases
    b_u = np.zeros(num_users)
    b_i = np.zeros(num_items)
    b = np.mean(R[np.where(R != 0)])

    # Create a list of training samples
    samples = [
        (i, j, R[i, j])
        for i in range(num_users)
        for j in range(num_items)
        if R[i, j] > 0
    ]

    # Perform stochastic gradient descent for number of iterations
    training_loss = []

    for iters in range(iterations):
        np.random.shuffle(samples)

# My code start
        loss = 0
# My code end

        for i, j, r in samples:
            """
            TODO:
            In this for-loop scope,
            you need to (1)update "b_u"(vector of rating bias for users) and "b_i"(vector of rating bias for items)
            and (2)update user and item latent feature matrices "P", "Q"
            """

# My code start
            # Comment out pred = 0
            # pred = 0

            # Calculate prediction and error
            hat_r = b + b_u[i] + b_i[j] + np.dot(P[i, :], Q[j, :])
            d_ij = r - hat_r

            # Calculate gradients
            gradient_b_u = -d_ij + (beta * b_u[i])
            gradient_b_i = -d_ij + (beta * b_i[j])
            gradient_P = -d_ij * Q[j, :] + (beta * P[i, :])
            gradient_Q = -d_ij * P[i, :] + (beta * Q[j, :])

            # Update all variables
            b_u[i] -= alpha * gradient_b_u
            b_i[j] -= alpha * gradient_b_i
            P[i, :] -= alpha * gradient_P
            Q[j, :] -= alpha * gradient_Q

            # Calculate loss
            loss += ((r - b - b_u[i] - b_i[j] - np.dot(P[i, :], Q[j, :])) ** 2)

        # Calculate loss
        loss /= len(samples)
        loss = loss ** 0.5

        temp = [iters, loss]
        training_loss.append(temp)

    pred = np.dot(P, Q.transpose())
# My code end

    return pred, b, b_u, b_i, training_loss

def plot_training_loss(training_loss):
    x = [x for x, y in training_loss]
    y = [y for x, y in training_loss]
    plt.figure(figsize=(16, 4))
    plt.plot(x, y)
    plt.xticks(x, x)
    plt.xlabel("Iterations")
    plt.ylabel("Root Mean Square Error")
    plt.grid(axis="y")
    plt.savefig("training_loss.png")
    plt.show()

if __name__ == "__main__":
    data = pd.read_csv('ratings.csv')
    table = pd.pivot_table(data, values='rating', index='userId', columns='movieId', fill_value=0)
    R = table.values

    pred, b, b_u, b_i, loss = mf_sgd(R,iterations=50)
    print("P x Q:")
    print(pred)
    print("Global bias:")
    print(b)
    print("User bias:")
    print(b_u)
    print("Item bias:")
    print(b_i)
    plot_training_loss(loss)


from IPython.display import display
import os
import wfdb
import numpy as np
from tqdm import tqdm
import cnibp.preprocessing.utils.signal_utils as su

'''
find_available_data(root_path)

< input >
    root_path : folder path containing person
< output >
    ABPBVP_list : list of people that have both channel; BVP, ABP
'''

def find_available_data(root_path):
    print('\n***MIMICdataset.find_available_data() called***')
    print(root_path)
    person_list = []
    for (path, dirs, files) in os.walk(root_path):
        for d in dirs:
            if len(d) == 3:
                person_list.append(d)

    available_list = []
    for person in person_list:
        channel_cnt = 0
        p = root_path + person
        for (path, dirs, files) in os.walk(p):
            for file in files:
                if file.split('.')[-1] == 'abp' or file.split('.')[-1] == 'ple':
                    channel_cnt += 1
                    if channel_cnt == 2:
                        available_list.append(person)
                        continue
    available_list = sorted(available_list)
    return available_list

'''
def find_idx(path)

< input >
    path : data path
< output >
    channel : index list of ABP, BVP
    flag : 2=[ABP, BVP], 1 = missing either of two
'''

def find_idx(path):
    record = wfdb.rdrecord(path)
    ABP_channel = [i for i in range(len(record.sig_name)) if (record.sig_name[i] == 'ABP')]
    PPG_channel = [i for i in range(len(record.sig_name)) if (record.sig_name[i] == 'PLETH')]
    # print('channel :', len(channel))
    # flag = len(channel)
    return ABP_channel, PPG_channel

'''
def read_record(path, sampfrom=0, sampto=None)

< input >
    path : data path
    sampfrom : starting point of slice
    sampto : end point of slice
< output >
    record : record of [ABP, BVP] channel

wfdb.io.rdrecord()
Read a WFDB record and return the signal and record descriptors
as attributes in a Record or MultiRecord object.
'''

''' 바로 return.p_signal 하도록 변경 '''

# TODO -> Record.init_value를 추가로 return 해주는데, 뒤에 함수들 전부 수정
def read_record(path, sampfrom=0, sampto=None):
    # channel = ['ABP', 'PLETH']
    ABP_channel, PPG_channel = find_idx(path)
    ABP_record = wfdb.rdrecord(path, channels=ABP_channel, sampfrom=sampfrom, sampto=sampto)
    PPG_record = wfdb.rdrecord(path, channels=PPG_channel, sampfrom=sampfrom, sampto=sampto)
    # wfdb.plot_wfdb(record=record, title='Record from PhysioNet MIMIC Dataset')
    # display(ABP_record.__dict__)
    return ABP_record.p_signal, PPG_record.p_signal

def data_aggregator(model_name, read_path, chunk_size, samp_rate):
    print('MIMIC-I dataset selected')
    available_list = find_available_data(read_path)
    print('Number of total ICU patient :', len(available_list))
    print(' >>', available_list)
    total_data = np.empty((1, 2))
    total_cnt = 0
    print('Number of selected ICU patient :', len(available_list))
    used_file_cnt = 0
    # TODO ''' use total data after solving the problem of get_diastolic() '''
    for a in available_list[:1]:
        p = read_path + a
        for (path, dirs, files) in os.walk(p):
            for file in tqdm(files):
                if (len(file.split('/')[-1]) == 12) and (file.split('.')[-1] == 'hea'):
                    data_path = (p + '/' + file).strip('.hea')
                    used_file_cnt += 1
                    total_data = np.append(total_data, read_record(data_path), axis=0)

    sig_total = total_data[1:]
    # for reshaping in signal_utils
    relength = (len(sig_total) // chunk_size) * chunk_size
    sig_total = sig_total[:relength]
    print('np.shape(sig_total) :', np.shape(sig_total))

    abp, ple, dsm = su.signal_slicing(model_name, sig_total, chunk_size, samp_rate, fft=True)
    return ple, abp, dsm


# -*- coding: utf-8 -*-

# Faça um Programa que leia 4 notas, mostre as notas e a média na tela.

print("======================================================")

notas = []
media = 0

for i in range(4):
	notas.append(float(input("Digite a nota " + str(i + 1)+ ": ")))
for i in range(len(notas)):
	media += notas[i]
media /= len(notas)
print("Media: %.1f" % media)

print("======================================================")


import datetime
from collections import namedtuple

import openPLM.plmapp.models as models
from openPLM.plmapp.units import DEFAULT_UNIT
from openPLM.plmapp.controllers.plmobject import PLMObjectController
from openPLM.plmapp.controllers.base import get_controller

Child = namedtuple("Child", "level link")
Parent = namedtuple("Parent", "level link")

class PartController(PLMObjectController):
    u"""
    Controller for :class:`.Part`.

    This controller adds methods to manage Parent-Child links between two
    Parts.
    """

    def check_add_child(self, child):
        """
        Checks if *child"* can be added to *self*.
        If *child* can not be added, an exception is raised.

        :param child: child to be added
        :type child: :class:`.Part`

        :raises: :exc:`ValueError` if *child* is already a child or a parent.
        :raises: :exc:`.PermissionError` if :attr:`_user` is not the owner of
            :attr:`object`.
        """
        self.check_permission("owner")
        self.check_editable()
        if not child.is_part:
            raise TypeError("Can not add child: not a Part")
        # check if child is not a parent
        if child.id == self.object.id:
            raise ValueError("Can not add child: child is current object")
        get_controller(child.type)(child, self._user).check_readable()
        parents = (p.link.parent.pk for p in self.get_parents(-1))
        if child.pk in parents:
            raise ValueError("Can not add child %s to %s, it is a parent" %
                                (child, self.object))
        link = self.parentchildlink_parent.filter(child=child, end_time=None)
        if link:
            raise ValueError("Can not add child, %s is already a child of %s" %
                                (child, self.object))

    def can_add_child(self, child):
        """
        Returns True if *child* can be added to *self*.
        """

        can_add = False
        try:
            self.check_add_child(child)
            can_add = True
        except StandardError:
            pass
        return can_add

    def add_child(self, child, quantity, order, unit=DEFAULT_UNIT, **extension_data):
        """
        Adds *child* to *self*.

        :param child: added child
        :type child: :class:`.Part`
        :param quantity: amount of *child*
        :type quantity: positive float
        :param order: order
        :type order: positive int
        :param unit: a valid unit

        :raises: :exc:`ValueError` if *child* is already a child or a parent.
        :raises: :exc:`ValueError` if *quantity* or *order* are negative.
        :raises: :exc:`.PermissionError` if :attr:`_user` is not the owner of
            :attr:`object`.
        :raises: :exc:`.PermissionError` if :attr:`object` is not editable.
        """

        if isinstance(child, PLMObjectController):
            child = child.object
        self.check_add_child(child)
        # check if child is not already a direct child
        if child.pk in (c.link.child.pk for c in self.get_children(1)):
            raise ValueError("%s is already a child of %s" % (child, self.object))
        if order < 0 or quantity < 0:
            raise ValueError("Quantity or order is negative")
        # data are valid : create the link
        link = models.ParentChildLink()
        link.parent = self.object
        link.child = child
        link.quantity = quantity
        link.order = order
        link.unit = unit
        link.save()
        # handle plces
        for PCLE in models.get_PCLEs(self.object):
            name = PCLE._meta.module_name
            if name in extension_data and PCLE.one_per_link():
                ext = PCLE(link=link, **extension_data[name])
                ext.save()
        # records creation in history
        self._save_histo(link.ACTION_NAME,
                         "parent : %s\nchild : %s" % (self.object, child))

    def delete_child(self, child):
        u"""
        Deletes *child* from current children and records this action in the
        history.

        .. note::
            The link is not destroyed: its end_time is set to now.

        :raises: :exc:`.PermissionError` if :attr:`_user` is not the owner of
            :attr:`object`.
        :raises: :exc:`.PermissionError` if :attr:`object` is not editable.
        """

        self.check_permission("owner")
        self.check_editable()
        if isinstance(child, PLMObjectController):
            child = child.object
        link = self.parentchildlink_parent.get(child=child, end_time=None)
        link.end_time = datetime.datetime.today()
        link.save()
        self._save_histo("Delete - %s" % link.ACTION_NAME, "child : %s" % child)

    def modify_child(self, child, new_quantity, new_order, new_unit,
            **extension_data):
        """
        Modifies information about *child*.

        :param child: added child
        :type child: :class:`.Part`
        :param new_quantity: amount of *child*
        :type new_quantity: positive float
        :param new_order: order
        :type new_order: positive int

        :raises: :exc:`.PermissionError` if :attr:`_user` is not the owner of
            :attr:`object`.
        :raises: :exc:`.PermissionError` if :attr:`object` is not editable.
        """

        self.check_permission("owner")
        self.check_editable()
        if isinstance(child, PLMObjectController):
            child = child.object
        if new_order < 0 or new_quantity < 0:
            raise ValueError("Quantity or order is negative")
        link = models.ParentChildLink.objects.get(parent=self.object,
                                                  child=child, end_time=None)
        original_extension_data = link.get_extension_data()

        if (link.quantity == new_quantity and link.order == new_order and
            link.unit == new_unit and original_extension_data == extension_data):
            # do not make an update if it is useless
            return
        link.end_time = datetime.datetime.today()
        link.save()
        # make a new link
        link2, extensions = link.clone(quantity=new_quantity, order=new_order,
                       unit=new_unit, end_time=None, extension_data=extension_data)
        details = ""
        if link.quantity != new_quantity:
            details += "quantity changes from %f to %f\n" % (link.quantity, new_quantity)
        if link.order != new_order:
            details += "order changes from %d to %d" % (link.order, new_order)
        if link.unit != new_unit:
            details += "unit changes from %s to %s" % (link.unit, new_unit)

        # TODO: details of extension changes

        self._save_histo("Modify - %s" % link.ACTION_NAME, details)
        link2.save(force_insert=True)
        # save cloned extensions
        for ext in extensions:
            ext.link = link2
            ext.save(force_insert=True)
        # add new extensions
        for PCLE in models.get_PCLEs(self.object):
            name = PCLE._meta.module_name
            if (name in extension_data and name not in original_extension_data
                and PCLE.one_per_link()):
                ext = PCLE(link=link2, **extension_data[name])
                ext.save()

    def get_children(self, max_level=1, current_level=1, date=None):
        """
        Returns a list of all children at time *date*.

        :rtype: list of :class:`Child`
        """

        if max_level != -1 and current_level > max_level:
            return []
        if not date:
            links = self.parentchildlink_parent.filter(end_time__exact=None)
        else:
            links = self.parentchildlink_parent.filter(ctime__lt=date).exclude(end_time__lt=date)
        res = []
        for link in links.order_by("order", "child__reference"):
            res.append(Child(current_level, link))
            pc = PartController(link.child, self._user)
            res.extend(pc.get_children(max_level, current_level + 1, date))
        return res

    def get_parents(self, max_level=1, current_level=1, date=None):
        """
        Returns a list of all parents at time *date*.

        :rtype: list of :class:`Parent`
        """

        if max_level != -1 and current_level > max_level:
            return []
        if not date:
            links = self.parentchildlink_child.filter(end_time__exact=None)
        else:
            links = self.parentchildlink_child.filter(ctime__lt=date).exclude(end_time__lt=date)
        res = []
        for link in links:
            res.append(Parent(current_level, link))
            pc = PartController(link.parent, self._user)
            res.extend(pc.get_parents(max_level, current_level + 1, date))
        return res

    def update_children(self, formset):
        u"""
        Updates children informations with data from *formset*

        :param formset:
        :type formset: a modelfactory_formset of
                        :class:`~plmapp.forms.ModifyChildForm`

        :raises: :exc:`.PermissionError` if :attr:`_user` is not the owner of
            :attr:`object`.
        :raises: :exc:`.PermissionError` if :attr:`object` is not editable.
        """

        self.check_permission("owner")
        self.check_editable()
        if formset.is_valid():
            for form in formset.forms:
                parent = form.cleaned_data["parent"]
                if parent.pk != self.object.pk:
                    raise ValueError("Bad parent %s (%s expected)" % (parent, self.object))
                delete = form.cleaned_data["delete"]
                child = form.cleaned_data["child"]
                if delete:
                    self.delete_child(child)
                else:
                    quantity = form.cleaned_data["quantity"]
                    order = form.cleaned_data["order"]
                    unit = form.cleaned_data["unit"]
                    self.modify_child(child, quantity, order, unit,
                            **form.extensions)

    def revise(self, new_revision):
        # same as PLMObjectController + add children
        new_controller = super(PartController, self).revise(new_revision)
        for level, link in self.get_children(1):
            link.clone(save=True, parent=new_controller.object)
        return new_controller

    def attach_to_document(self, document):
        """
        Links *document* (a :class:`.Document`) with
        :attr:`~PLMObjectController.object`.

        :raises: :exc:`.PermissionError` if :attr:`_user` is not the owner of
            :attr:`object`.
        """

        self.check_attach_document(document)
        if isinstance(document, PLMObjectController):
            document = document.object
        self.documentpartlink_part.create(document=document)
        self._save_histo(models.DocumentPartLink.ACTION_NAME,
                         "Part : %s - Document : %s" % (self.object, document))

    def detach_document(self, document):
        """
        Delete link between *document* (a :class:`.Document`)
        and :attr:`~PLMObjectController.object`.

        :raises: :exc:`.PermissionError` if :attr:`_user` is not the owner of
            :attr:`object`.
        """

        self.check_permission("owner")
        if isinstance(document, PLMObjectController):
            document = document.object
        link = self.documentpartlink_part.get(document=document)
        link.delete()
        self._save_histo(models.DocumentPartLink.ACTION_NAME + " - delete",
                         "Part : %s - Document : %s" % (self.object, document))

    def get_attached_documents(self):
        """
        Returns all :class:`.Document` attached to
        :attr:`~PLMObjectController.object`.
        """
        return self.documentpartlink_part.all()

    def is_document_attached(self, document):
        """
        Returns True if *document* is attached to the current part.
        """

        if isinstance(document, PLMObjectController):
            document = document.object
        return bool(self.documentpartlink_part.filter(document=document))

    def check_attach_document(self, document):
        self.check_permission("owner")
        if not hasattr(document, "is_document") or not document.is_document:
            raise TypeError("%s is not a document" % document)

        if isinstance(document, PLMObjectController):
            document.check_readable()
            document = document.object
        else:
            get_controller(document.type)(document, self._user).check_readable()
        if self.is_document_attached(document):
            raise ValueError("Document is already attached.")

    def can_attach_document(self, document):
        """
        Returns True if *document* can be attached to the current part.
        """
        can_attach = False
        try:
            self.check_attach_document(document)
            can_attach = True
        except StandardError:
            pass
        return can_attach

    def update_doc_cad(self, formset):
        u"""
        Updates doc_cad informations with data from *formset*

        :param formset:
        :type formset: a modelfactory_formset of
                        :class:`~plmapp.forms.ModifyChildForm`

        :raises: :exc:`.PermissionError` if :attr:`_user` is not the owner of
            :attr:`object`.
        """

        self.check_permission("owner")
        if formset.is_valid():
            for form in formset.forms:
                part = form.cleaned_data["part"]
                if part.pk != self.object.pk:
                    raise ValueError("Bad part %s (%s expected)" % (part, self.object))
                delete = form.cleaned_data["delete"]
                document = form.cleaned_data["document"]
                if delete:
                    self.detach_document(document)


'''
Probably not O(n) time and O(1) space quite yet
But an attempt at a solution:
time: O(n)
space: also O(n)

So if 1 exist, answer is not 1
if all the number have no gap, answer is max + 1
if there is a gap somewhere in the answer, answer is the gap of the smallest numbers

'''

import sys

def firstSmallestPositive(nums):
    num_dict = {} #the numbers, and the number that is supposed to be right after it
    #also keep track of max
    max_num = -1
    found_one = False
    for n in nums:
        #keep track of max
        if n > max_num:
            max_num = n
        #ignore negative
        if n >= 0 and n not in num_dict:
            num_dict[n] = n + 1
        if n == 1:
            found_one = True
    #no found 1
    if found_one == False:
        return 1
    min_gap = sys.maxsize
    for v in  num_dict.values():
        if v not in num_dict and v < min_gap:
            min_gap = v-1 #add the key in
    if min_gap == sys.maxsize:
        return max_num + 1
    return min_gap + 1
    #check if there is 1. if no 1, return 1
    #then from num_dict's values, check if it exist. If not, keep it
    #but when keeping, only keep the minimum one
    #if no gap, return max+1

assert firstSmallestPositive([3, 4, -1, 1]) == 2
assert firstSmallestPositive([1, 2, 0]) == 3
assert firstSmallestPositive([7,8,9,11,12]) == 1


class Solution:
    def isCompleteTree(self, root: TreeNode) -> bool:
        '''
        Full tree: The tree is left leaning. Meaning that all the nodes
        have left node before they have a right node. Otherwise it's invalid.
        When we encounter a None node, we can't encounter any other node afteewards
        '''
        q = [root]
        hasNone = False

        while q:
            node = q.pop(0)
            if not node:
                hasNone = True

            if hasNone and node:
                return False

            if node:
                q.append(node.left)
                q.append(node.right)

        return True


#delentry
#args: none
#deletes an entry

from . import classes
from . import globalvar
import sys

def delentry(args):
    #The codes used for selecting which entry to delete
    #is taken straight out of viewentry
    src = 0
    cate = 0

    #Deciding whether the entry the user wants to look up is under a source or cate
    while True:
        inp = input('Source or category (src/cate/q) ')
        if inp == 'src':
            src = 1
            break
        elif inp == 'cate':
            cate = 1
            break
        elif inp == 'q':
            print('Cancelling operation...')
            sys.exit(1)
        else:
            print('Invalid input.')

    if src == 1:
        #Picking a source to look under
        #Is copied straight from newentry.py
        print('Sources: {0}'.format(globalvar.listStrSource))
        while True:
            source = input('Enter a source, or type \'q\' to quit: ')
            if source == 'q':
                print('Cancelling operation...')
                sys.exit(1)
            try:
                globalvar.masterSource[source]
                break
            except KeyError:
                print('Source not found. Please try again.')
        #Picking an entry to display
        globalvar.masterSource[source].display()
        while True:
            num = input('Enter the ID of the entry, or type \'q\' to quit: ')
            if num == 'q':
                print('Cancelling operation...')
                sys.exit(1)
            elif int(num) > len(globalvar.masterSource[source].spendEntryList) or int(num) < 1:
                print('Invalid ID number. Please try again.')
            else:
                break
        #removing the entry from corresponding sources and cate
        targetEntry = globalvar.masterSource[source].spendEntryList[int(num) - 1]
        globalvar.masterSource[source].removeEntry(targetEntry)
        print('Entry removed from source {}'.format(source))
        for i in targetEntry.category:
            globalvar.masterCate[i].removeEntry(targetEntry)
            print('Entry removed from cate {}'.format(i))

    if cate == 1:
        #Picking a source to look under
        #Is copied straight from newentry.py
        print('Categories: {0}'.format(globalvar.listStrCate))
        while True:
            cate = input('Enter a category, or type \'q\' to quit: ')
            if cate == 'q':
                print('Cancelling operation...')
                sys.exit(1)
            try:
                globalvar.masterCate[cate]
                break
            except KeyError:
                print('Source not found. Please try again.')
        #Picking an entry to display
        globalvar.masterCate[cate].display()
        while True:
            num = int(input('Enter the ID of the entry, or type \'q\' to quit: '))
            if num == 'q':
                print('Cancelling operation...')
                sys.exit(1)
            elif int(num) > len(globalvar.masterCate[cate].spendEntryList) or int(num) < 1:
                print('Invalid ID number. Please try again.')
            else:
                break
        #removing the entry from corresponding sources and cate
        targetEntry = globalvar.masterCate[cate].spendEntryList[int(num) - 1]
        globalvar.masterCate[cate].removeEntry(targetEntry)
        print('Entry removed from cate {}'.format(cate))
        globalvar.masterSource[targetEntry.source].removeEntry(targetEntry)
        print('Entry removed from source {}'.format(targetEntry.source))


import numpy as np
import copy
import os

ROOT_DIR = '/home/ych/Downloads/UCRArchive_2018/'
TS_NAME = 'Yoga'

def read_data():
    root_dir, ts_name = ROOT_DIR, TS_NAME
    ts_dir = os.path.join(root_dir, ts_name)

    data_train = np.loadtxt(os.path.join(ts_dir, ts_name + '_TRAIN.tsv'), delimiter='\t')
    data_test = np.loadtxt(os.path.join(ts_dir, ts_name + '_TEST.tsv'), delimiter='\t')

    label_train = np.array(data_train[:, 0], np.float32)
    label_test = np.array(data_test[:, 0], np.float32)

    input_train = np.array(data_train[:, 1:], np.float32)
    input_test = np.array(data_test[:, 1:], np.float32)

    return input_train, label_train, input_test, label_test

def redefine_category(label):
    category2real = {}
    real2category = {}
    label = np.sort(np.unique(label))
    class_num = len(label)
    for k in range(class_num):
        category2real[k] = label[k]
        real2category[label[k]] = k
    return category2real, real2category

def transform_category(label, real2category):
    transformed_label = copy.deepcopy(label)
    for k in range(len(label)):
        transformed_label[k] = real2category[label[k]]
    return transformed_label

if __name__ == '__main__':
    x_train, y_train, x_test, y_test = read_data()
    category2real, real2category = redefine_category(y_train)
    transformed_label = transform_category(y_train, real2category)

    # print(np.any(np.isnan(x_train)))
    # print(np.any(np.isnan(y_train)))
    # print(np.any(np.isnan(x_test)))
    # print(np.any(np.isnan(y_test)))


# import decimal variable type from the library
from decimal import Decimal as d

# declare balance ammount
balance = d(2000)
# print balance ammount on the console
print("Bank account balance: ", balance, "€")
# ask the user for the ammount of euros and cents to be added on the balance
user_input_euros = d(input("How many euros will be added to the balance?: "))
user_input_cents = d(input("How many cents will be added to the balance?: "))
# convert user_input_cents from euros to cents
user_input_cents = user_input_cents / 100
# calculate the total of both numbers
total_added_ammount = user_input_euros + user_input_cents
# add the ammount into the total balance ammount
balance = balance + total_added_ammount
# print out the total balance ammount
print("Bank account balance: ", balance, "€")

Tehtävät/L07 Tietotyypit ja muuttujat/Tehtävä05.py


"""
dp[i] : 1,2,3을 이용해서 i를 나타낼 수 있는 경우의 수의 합

예를 들면

4를 만드는 방법은

1을 만드는 경우의 수 + 2를 만드는 경우의 수 + 3을 만드는 경우의 수의 합이다.

1을 만드는 경우의 수가 k 개 있으면 이 수가 4가 되려면 1에 3을 더해주면 4가 된다.

즉 1을 만드는 방법의 경우의 수눈 4를 만드는 경우의 수에 사용된다.

"""
import sys
sys.setrecursionlimit(10000000)

tc = int(input())

def calc_dp(i):
    if dp[i] is None:
        dp[i] = calc_dp(i-3) + calc_dp(i-2) + calc_dp(i-1)

    return dp[i]

for _ in range(tc):
    n = int(input())
    dp = [None for x in range(n + 1)]
    dp[0] = 1
    dp[1] = 1
    if n >= 2:
        dp[2] = 2
    if n >= 3:
        dp[3] = 4
    if n > 3:
        print(calc_dp(n))
    else:
        print(dp[n])

"""
# bottom-up method

TC = int(input())  # TC를 받는다

for x in range(TC):  # TC만큼 반복
    n = int(input())  # 정수 n 입력

    dp = [1, 2, 4]  # 기본적으로 설정된 값, 손으로 구했다.

    if n <= 3:  # 3이하면 패스
        pass
    else:
        for i in range(3, n):  # 3보다 클 경우
            result = dp[i - 3] + dp[i - 2] + dp[i - 1]  # 계속 호출해서 반복
            dp.append(result)  # dp를 채워나아간다.
    print(dp[n - 1])  # 0번부터 리스트는 시작이니까 1개 빼준다.
"""


#################################
# Your name: Nathan Bloch
#################################

# Please import and use stuff only from the packages numpy, sklearn, matplotlib
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.datasets import make_blobs

"""
Q4.1 skeleton.

Please use the provided functions signature for the SVM implementation.
Feel free to add functions and other code, and submit this file with the name svm.py
"""

# generate points in 2D
# return training_data, training_labels, validation_data, validation_labels
def get_points():
    X, y = make_blobs(n_samples=120, centers=2, random_state=0, cluster_std=0.88)
    return X[:80], y[:80], X[80:], y[80:]

def create_plot(X, y, clf):
    plt.clf()

    # plot the data points
    plt.scatter(X[:, 0], X[:, 1], c=y, s=30, cmap=plt.cm.PiYG)

    # plot the decision function
    ax = plt.gca()
    xlim = ax.get_xlim()
    ylim = ax.get_ylim()

    # create grid to evaluate model
    xx = np.linspace(xlim[0] - 2, xlim[1] + 2, 30)
    yy = np.linspace(ylim[0] - 2, ylim[1] + 2, 30)
    YY, XX = np.meshgrid(yy, xx)
    xy = np.vstack([XX.ravel(), YY.ravel()]).T
    Z = clf.decision_function(xy).reshape(XX.shape)

    # plot decision boundary and margins
    ax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5,
               linestyles=['--', '-', '--'])

def train_three_kernels(X_train, y_train, X_val, y_val):
    """
    Returns: np.ndarray of shape (3,2):
        A two dimensional array of size 3 that contains the number of support vectors for each class(2) in the three kernels.
    """
    linear_clf = svm.SVC(kernel='linear', C=1000)
    linear_clf.fit(X_train, y_train)

    quadratic_clf = svm.SVC(kernel='poly', C=1000, degree=2)
    quadratic_clf.fit(X_train, y_train)

    rbf_clf = svm.SVC(C=1000)
    rbf_clf.fit(X_train, y_train)

    create_plot(X_train, y_train, rbf_clf)
    # plt.show()

    create_plot(X_train, y_train, quadratic_clf)
    # plt.show()

    create_plot(X_train, y_train, linear_clf)
    # plt.show()

    return np.array([linear_clf.n_support_, quadratic_clf.n_support_, rbf_clf.n_support_])

def linear_accuracy_per_C(X_train, y_train, X_val, y_val):
    """
        Returns: np.ndarray of shape (11,) :
                    An array that contains the accuracy of the resulting model on the VALIDATION set.
    """
    valid_accuracy = np.zeros(11)
    train_accuracy = np.zeros(11)
    C = [pow(10, i) for i in range(-5, 6)]
    for i in range(11):
        clf = svm.SVC(kernel='linear', C = C[i])
        clf.fit(X_train, y_train)
        valid_accuracy[i] = calc_accuracy(X_val, y_val, clf)
        train_accuracy[i] = calc_accuracy(X_train, y_train, clf)

    valid_line, = plt.plot(C, valid_accuracy)
    train_line, = plt.plot(C, train_accuracy)
    plt.xscale('log')
    plt.legend((valid_line, train_line), ('Validation Set', 'Train Set'))
    # plt.show()

    return valid_accuracy

def rbf_accuracy_per_gamma(X_train, y_train, X_val, y_val):
    """
        Returns: np.ndarray of shape (11,) :
                    An array that contains the accuracy of the resulting model on the VALIDATION set.
    """
    valid_accuracy = np.zeros(11)
    train_accuracy = np.zeros(11)
    gammas = [pow(10, i) for i in range(-5, 6)]
    for i in range(11):
        clf = svm.SVC(C = 10, gamma=gammas[i])
        clf.fit(X_train, y_train)
        valid_accuracy[i] = calc_accuracy(X_val, y_val, clf)
        train_accuracy[i] = calc_accuracy(X_train, y_train, clf)

    valid_line, = plt.plot(gammas, valid_accuracy)
    train_line, = plt.plot(gammas, train_accuracy)
    plt.xscale('log')
    plt.legend((valid_line, train_line), ('Validation Set', 'Train Set'))
    # plt.show()

    return valid_accuracy

#====================================  HELPER FUNCTION  =========================================

def calc_accuracy(X_data, Y_data, clf):
    true = 0
    predictions = clf.predict(X_data)
    for i in range(X_data.shape[0]):
        if(predictions[i] == Y_data[i]):
            true += 1

    return true / X_data.shape[0]

# train_data, train_labels, validation_data, validation_labels = get_points();

# 1(a)
# sv = train_three_kernels(train_data, train_labels, validation_data, validation_labels)
# print("# of SVs in linear model:", sum(sv[0]));
# print("# of SVs in quaratic model:", sum(sv[1]));
# print("# of SVs in RBF model:", sum(sv[2]));

# 1(b)
# linear_accuracy_per_C(train_data, train_labels, validation_data, validation_labels)

# 1(c)
# rbf_accuracy_per_gamma(train_data, train_labels, validation_data, validation_labels)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Compatibility tools for various data structure inputs
"""
from six.moves import range
import numpy as np
import pandas as pd

# upstream this is in discrete_model._numpy_to_dummies
def numpy_to_dummies(endog):
    from sm2.tools import tools
    if endog.dtype.kind in ['S', 'O']:
        endog_dummies, ynames = tools.categorical(endog, drop=True,
                                                  dictnames=True)
    elif endog.ndim == 2:
        endog_dummies = endog
        ynames = range(endog.shape[1])
    else:
        endog_dummies, ynames = tools.categorical(endog, drop=True,
                                                  dictnames=True)
    return endog_dummies, ynames

# upstream this is in discrete_model._pandas_to_dummies
def pandas_to_dummies(endog):
    if endog.ndim == 2:
        if endog.shape[1] == 1:
            yname = endog.columns[0]
            endog_dummies = pd.get_dummies(endog.iloc[:, 0])
        else:  # series
            yname = 'y'
            endog_dummies = endog
    else:
        yname = endog.name
        endog_dummies = pd.get_dummies(endog)
    ynames = endog_dummies.columns.tolist()

    return endog_dummies, ynames, yname

# upstream this is discrete_margins._get_const_index
def get_const_index(exog):
    """
    Returns a boolean array of non-constant column indices in exog and
    an scalar array of where the constant is or None
    """
    effects_idx = exog.var(0) != 0
    if np.any(~effects_idx):
        const_idx = np.where(~effects_idx)[0]
    else:
        const_idx = None
    return effects_idx, const_idx

# upstream this is discrete_margins._isdummy
def isdummy(X):
    """
    Given an array X, returns the column indices for the dummy variables.

    Parameters
    ----------
    X : array-like
        A 1d or 2d array of numbers

    Examples
    --------
    >>> X = np.random.randint(0, 2, size=(15, 5)).astype(float)
    >>> X[:, 1:3] = np.random.randn(15, 2)
    >>> ind = _isdummy(X)
    >>> ind
    array([0, 3, 4])
    """
    X = np.asarray(X)
    if X.ndim > 1:
        ind = np.zeros(X.shape[1]).astype(bool)
    max = (np.max(X, axis=0) == 1)
    min = (np.min(X, axis=0) == 0)
    remainder = np.all(X % 1. == 0, axis=0)
    ind = min & max & remainder
    if X.ndim == 1:
        ind = np.asarray([ind])
    return np.where(ind)[0]

# upstream this is discrete_margins._get_dummy_index
def get_dummy_index(X, const_idx):
    dummy_ind = isdummy(X)
    dummy = True

    if dummy_ind.size == 0:  # don't waste your time
        dummy = False
        dummy_ind = None  # this gets passed to stand err func
    return dummy_ind, dummy

# upstream this is discrete_margins._iscount
def iscount(X):
    """
    Given an array X, returns the column indices for count variables.

    Parameters
    ----------
    X : array-like
        A 1d or 2d array of numbers

    Examples
    --------
    >>> X = np.random.randint(0, 10, size=(15, 5)).astype(float)
    >>> X[:, 1:3] = np.random.randn(15, 2)
    >>> ind = _iscount(X)
    >>> ind
    array([0, 3, 4])
    """
    X = np.asarray(X)
    remainder = np.logical_and(np.logical_and(np.all(X % 1. == 0, axis=0),
                               X.var(0) != 0), np.all(X >= 0, axis=0))
    dummy = isdummy(X)
    remainder = np.where(remainder)[0].tolist()
    for idx in dummy:
        remainder.remove(idx)
    return np.array(remainder)

def get_count_index(X, const_idx):
    count_ind = iscount(X)
    count = True

    if count_ind.size == 0:  # don't waste your time
        count = False
        count_ind = None  # for stand err func
    return count_ind, count

def _check_period_index(x, freq="M"):  # pragma: no cover
    raise NotImplementedError("_check_period_index not ported from upstream, "
                              "as it is only used in tsaplots, "
                              "which is not (yet) ported")

def is_data_frame(obj):
    return isinstance(obj, pd.DataFrame)

def is_design_matrix(obj):
    from patsy import DesignMatrix
    return isinstance(obj, DesignMatrix)

def is_structured_ndarray(obj):
    return isinstance(obj, np.ndarray) and obj.dtype.names is not None

def interpret_data(data, colnames=None, rownames=None):
    """
    Convert passed data structure to form required by estimation classes

    Parameters
    ----------
    data : ndarray-like
    colnames : sequence or None
        May be part of data structure
    rownames : sequence or None

    Returns
    -------
    (values, colnames, rownames) : (homogeneous ndarray, list)
    """
    if isinstance(data, np.ndarray):
        if _is_structured_ndarray(data):
            if colnames is None:
                colnames = data.dtype.names
            values = struct_to_ndarray(data)
        else:
            values = data

        if colnames is None:
            colnames = ['Y_%d' % i for i in range(values.shape[1])]
    elif is_data_frame(data):
        # XXX: hack
        data = data.dropna()
        values = data.values
        colnames = data.columns
        rownames = data.index
    else:  # pragma: no cover
        raise TypeError('Cannot handle input type {typ}'
                        .format(typ=type(data).__name__))

    if not isinstance(colnames, list):
        colnames = list(colnames)

    # sanity check
    if len(colnames) != values.shape[1]:
        raise ValueError('length of colnames does not match number '
                         'of columns in data')  # pragma: no cover

    if rownames is not None and len(rownames) != len(values):
        raise ValueError('length of rownames does not match number '
                         'of rows in data')  # pragma: no cover

    return values, colnames, rownames

def struct_to_ndarray(arr):
    return arr.view((float, len(arr.dtype.names)), type=np.ndarray)

def is_using_ndarray_type(endog, exog):
    return (type(endog) is np.ndarray and
            (type(exog) is np.ndarray or exog is None))

def is_using_ndarray(endog, exog):
    return (isinstance(endog, np.ndarray) and
            (isinstance(exog, np.ndarray) or exog is None))

def is_using_pandas(endog, exog):
    klasses = (pd.Series, pd.DataFrame, pd.Panel)
    # from sm2.compat.pandas import data_klasses as klasses
    return (isinstance(endog, klasses) or isinstance(exog, klasses))

def _is_array_like(endog, exog):  # pragma: no cover
    raise NotImplementedError("_is_array_like not ported from upstream, "
                              "as it is only used in iolib.foreign, "
                              "which is itself not ported.")

def is_using_patsy(endog, exog):
    # we get this when a structured array is passed through a formula
    return (is_design_matrix(endog) and
            (is_design_matrix(exog) or exog is None))

def is_recarray(data):
    """
    Returns true if data is a recarray
    """
    return isinstance(data, np.core.recarray)

# aliases for backward compatibility
_is_structured_ndarray = is_structured_ndarray
_is_recarray = is_recarray
_is_using_patsy = is_using_patsy
_is_using_pandas = is_using_pandas
_is_using_ndarray = is_using_ndarray
_is_using_ndarray_type = is_using_ndarray_type


import csv
import boto3

with open('new_user_credentials.csv', 'r') as input:
    next(input)
    reader = csv.reader(input)
    for line in reader:
        access_key_id = line[2]
        secret_access_key = line[3]

photo = 'train.jpg'

# Creates a client of the rekognition API
client = boto3.client('rekognition',
                      aws_access_key_id=access_key_id,
                      aws_secret_access_key=secret_access_key)

with open(photo, 'rb') as source_image:
    source_bytes = source_image.read()

response = client.detect_labels(Image={'Bytes': source_bytes},
                                MaxLabels=10)

person = 'mercelis.jpg'

with open(person, 'rb') as source_image:
    source_bytes = source_image.read()

personResponse = client.detect_faces(Image={'Bytes': source_bytes},
                                     Attributes=['ALL'])

print("Train response: ", response)
print("Person response: ", personResponse)


#!/usr/bin/env python3
# @Date    : 2021-12-21
# @Author  : Bright Li (brt2@qq.com)
# @Link    : https://gitee.com/brt2
# @Version : 0.1.5

import os
import re
import datetime
import glob
from collections import defaultdict

from .md_parser import MarkdownParser, NullMarkdownFile
# from .util.imgfmt import png2jpg, resize

# def png2jpg_for_md(path_png):
#     """ 验证png转换后体积明显缩小，
#         否则添加前缀，避免修改后再次上传时重复进行格式转换 """
#     new_file_prefix="keepng_"
#     if os.path.basename(path_png).startswith(new_file_prefix):
#         return path_png

#     path_jpg = png2jpg(path_png, 85)
#     if path_jpg == path_png:
#         path_jpg = os.path.join(os.path.dirname(path_png),
#            new_file_prefix + os.path.basename(path_png))
#         os.rename(path_png, path_jpg)
#     return path_jpg

class MarkdownFormatter(MarkdownParser):

    def format(self, resize_imgs=False):
        # self._update_categories()

        if not self.check_list["find_TOC"]:
            toc_index = self.check_list["index_H2"]
            if toc_index is None:
                toc_index = 0
            self.insert_text(toc_index, "[TOC]\n\n---\n\n")

        if self.check_list["index_H1"]:
            self.pop_text(self.check_list["index_H1"])

        self.update_serial_num()
        self.update_description()
        self.update_meta()  # Front Matter

        # # 图像处理
        # if self.get_images("http") and input("是否尝试下载超链接图片？[Y/n]: ").lower() != "n":
        #     # self.unlock_text()
        #     self.download_img()

        # # 默认启用 png -> jpg
        # self.convert_png2jpg()

        # # 对于高分辨率图像进行压缩
        # if resize_imgs:
        #     self.resize_high_resolution()

        # # 判断下载图像的size，执行resize或压缩
        # self.compress_bigimg()

    def _make_front_matter(self):
        def list_as_str(data: list):
            # str(data) -> 单引号，不符合markdown标准
            return "[\"" + "\",\"".join(data) + "\"]" if data else "[]"

        self.metadata["date"] = str(datetime.date.today())

        # date数据由于使用eval()反序列化，故必须使用""作为字符串
        str_md_info = """<!--
+++
title       = "{}"
description = "{}"
date        = "{}"
tags        = {}
categories  = {}
series      = {}
keywords    = {}
weight      = {}
toc         = true
draft       = false
+++ -->
""".format(self.metadata['title'], self.metadata['description'], self.metadata['date'],
    list_as_str(self.metadata.get('tags')), list_as_str(self.metadata.get('categories')),
    list_as_str(self.metadata.get('series')), list_as_str(self.metadata.get('keywords')),
    self.metadata['weight'])
        return str_md_info

    def update_meta(self):
        meta_line = self._make_front_matter()
        if self.meta_range[0] is not None:
        # def _remove_old_meta(self):
            __text_lines = self.get_text()
            meta_start, meta_end = self.meta_range
            if meta_start is not None:
                self.set_text(__text_lines[:meta_start] + __text_lines[meta_end +1:])

        # def _insert_meta(self):
            self.insert_text(0, meta_line)
            self.meta_range = [None, None]
        else:
            self.modify_text(0, meta_line)

    def update_serial_num(self):
        """ 使用3级序号：1.2.4. xxx """
        x, y, z = 0, 0, 0
        def get_serial():
            serial_num = ""
            for i in [x, y, z]:
                if i:
                    # print("__", serial_num, type(i))
                    serial_num += "{}.".format(i)
                else:
                    break
            return serial_num

        pattern_headline = re.compile(r"(#+) +(\d+\.\S*)? *(.*)")

        def update_line(line):
            serial_num = get_serial()
            # if self.check_list["has_serial_num"]:
            #     prefix, _, text = line.split(maxsplit=2)
            # else:
            #     prefix, text = line.split(maxsplit=1)
            prefix, _, text = re.match(pattern_headline, line).groups()
            return "{} {} {}".format(prefix, serial_num, text)

        self.head2 = []
        for index, line in enumerate(self.get_text()):
            if line.startswith("## "):
                x += 1
                y,z = 0,0

                new_line = update_line(line)
                self.modify_text(index, new_line)
                # h2 = re.match(pattern_headline, line).groups()[2]
                _, h2 = new_line.split(maxsplit=1)
                self.head2.append(h2)
            elif line.startswith("### "):
                y += 1
                z = 0
                self.modify_text(index, update_line(line))
            elif line.startswith("#### "):
                z += 1
                self.modify_text(index, update_line(line))

    def update_description(self):
        if not self.metadata['description']:
            self.metadata['description'] = "; ".join(self.head2)

    def download_img(self):
        from util.imgfmt import download_src

        dict_images = self.get_images("http")
        # 生成图像目录
        dir_img, _ = os.path.splitext(self.file_path)
        if not os.path.exists(dir_img):
            os.makedirs(dir_img)
        self.process_images(dict_images, lambda url: os.path.relpath(download_src(url, dir_img),
                                                            os.path.dirname(self.file_path)))

    def convert_png2jpg(self):
        dict_images = self.get_images("png")
        self.process_images(dict_images, lambda path_png: os.path.relpath(png2jpg_for_md(path_png),
                                                            os.path.dirname(self.file_path)))
        # 删除原png文件
        # for path_img in dict_images.values():
        #     os.remove(path_img)

    def compress_jpg(self):
        pass

    def compress_bigimg(self):
        pass

    # def resize_high_resolution(self, save_as_jpg=True):
    #     dict_images_png = self.get_images("png")
    #     dict_images_jpg = self.get_images("jpg")
    #     callback = lambda url: resize(url, ratio=0.6, min_size=10240,
    #                                   max_shape=[680,680], save_as_jpg=save_as_jpg)
    #     self.process_images({**dict_images_png, **dict_images_jpg}, callback)

#####################################################################

def getopt():
    import argparse

    parser = argparse.ArgumentParser("格式化mkdocs文档", description="")
    parser.add_argument("-p", "--path", action="store", help="解析文件路径，可以是文件或目录")
    return parser.parse_args()

def format_one_doc(fmt, path_file):
    fmt.load_file(path_file)
    fmt.format(resize_imgs=False)

def format_dir(fmt, path_dir):
    list_files = glob.glob("{}/**/*.md" % path_dir, recursive=True)

    err_files = defaultdict(list)
    for path_file in list_files:
        try:
            format_one_doc(fmt, path_file)
        except NullMarkdownFile:
            err_files["NullMarkdownFile"].append(path_file)

    if err_files:
        for key, list_files in err_files.items():
            print(">> 错误文件类型【{}】" % key)
            print("   文件列表： {}" % list_files)

def format_anything(fmt, path):
    if os.path.isdir(path):
        format_dir(fmt, path)
    else:
        format_one_doc(fmt, path)

if __name__ == "__main__":
    args = getopt()
    fmt = MarkdownFormatter()

    if args.path:
        format_anything(fmt, args.path)
    else:
        path = input("\n请输入待处理文件path(支持直接拖拽): ")
        while True:
            path = path.strip().strip('"')
            if os.path.exists(path):
                format_anything(fmt, path)
                fmt.overwrite()
            else:
                print("Error: File [{}] NOT found." % path)

            path = input("继续输入path，按[Q]退出: ")
            if path.lower() == "q":
                break


"""mouse.py defines the following functions:

click() -- calls left mouse click
hold() -- presses and holds left mouse button
release() -- releases left mouse button

rightclick() -- calls right mouse click
righthold() -- calls right mouse hold
rightrelease() -- calls right mouse release

middleclick() -- calls middle mouse click
middleclick() -- calls middle mouse hold
middlerelease() -- calls middle mouse release

move(x,y) -- moves mouse to x/y coordinates (in pixels)
getpos() -- returns mouse x/y coordinates (in pixels)
slide(x,y) -- slides mouse to x/y coodinates (in pixels)
              also supports optional speed='slow', speed='fast'
"""
from ctypes import*
from ctypes.wintypes import *
from time import sleep
import time

__all__ = ['click', 'hold', 'release', 'rightclick', 'righthold', 'rightrelease', 'middleclick', 'middleclick', 'middlerelease', 'move', 'slide', 'getpos']

# START SENDINPUT TYPE DECLARATIONS
PUL = POINTER(c_ulong)

class KeyBdInput(Structure):
    _fields_ = [("wVk", c_ushort),
             ("wScan", c_ushort),
             ("dwFlags", c_ulong),
             ("time", c_ulong),
             ("dwExtraInfo", PUL)]

class HardwareInput(Structure):
    _fields_ = [("uMsg", c_ulong),
             ("wParamL", c_short),
             ("wParamH", c_ushort)]

class MouseInput(Structure):
    _fields_ = [("dx", c_long),
             ("dy", c_long),
             ("mouseData", c_ulong),
             ("dwFlags", c_ulong),
             ("time",c_ulong),
             ("dwExtraInfo", PUL)]

class Input_I(Union):
    _fields_ = [("ki", KeyBdInput),
              ("mi", MouseInput),
              ("hi", HardwareInput)]

class Input(Structure):
    _fields_ = [("type", c_ulong),
             ("ii", Input_I)]

class POINT(Structure):
    _fields_ = [("x", c_ulong),
             ("y", c_ulong)]
# END SENDINPUT TYPE DECLARATIONS

LEFTDOWN   = 0x00000002
LEFTUP     = 0x00000004
MIDDLEDOWN = 0x00000020
MIDDLEUP   = 0x00000040
MOVE       = 0x00000001
ABSOLUTE   = 0x00008000
RIGHTDOWN  = 0x00000008
RIGHTUP    = 0x00000010

FInputs = Input * 2
extra = c_ulong(0)

click = Input_I()
click.mi = MouseInput(0, 0, 0, 2, 0, pointer(extra))
release = Input_I()
release.mi = MouseInput(0, 0, 0, 4, 0, pointer(extra))

x = FInputs( (0, click), (0, release) )
#user32.SendInput(2, pointer(x), sizeof(x[0])) CLICK & RELEASE

x2 = FInputs( (0, click) )
#user32.SendInput(2, pointer(x2), sizeof(x2[0])) CLICK & HOLD

x3 = FInputs( (0, release) )
#user32.SendInput(2, pointer(x3), sizeof(x3[0])) RELEASE HOLD

def move(x,y):
    windll.user32.SetCursorPos(x,y)

def getpos():
    global pt
    pt = POINT()
    windll.user32.GetCursorPos(byref(pt))
    return pt.x, pt.y

def slide(a,b,speed=0):
    while True:
        if speed == 'slow':
            sleep(0.005)
            Tspeed = 2
        if speed == 'fast':
            sleep(0.001)
            Tspeed = 5
        if speed == 0:
            sleep(0.001)
            Tspeed = 3

        x = getpos()[0]
        y = getpos()[1]
        if abs(x-a) < 5:
            if abs(y-b) < 5:
                break

        if a < x:
            x -= Tspeed
        if a > x:
            x += Tspeed
        if b < y:
            y -= Tspeed
        if b > y:
            y += Tspeed
        move(x,y)

#uses sendinput to do the clicks
def click():
    windll.user32.SendInput(2,pointer(x),sizeof(x[0]))

def hold():
    windll.user32.SendInput(2, pointer(x2), sizeof(x2[0]))

def release():
    windll.user32.SendInput(2, pointer(x3), sizeof(x3[0]))

def mousebutton(clickButton,releaseButton,delay=0,release=True):
    """Simulates a mouse button. Button can be left, right or middle click in up or down state.
    By default it clicks the button and immediately releases it. If release is false it will skip letting go of the button and
    hold it."""

    windll.user32.mouse_event(clickButton,0,0,0,0)
    if release==True:
        time.sleep(delay)
        windll.user32.mouse_event(releaseButton,0,0,0,0)

def leftclick(delay=0,release=True):
    mousebutton(LEFTDOWN,LEFTUP,delay, release)

def leftrelease():
    mousebutton(LEFTUP,LEFTUP,release=False)

def rightclick(delay=0,release=True):
    mousebutton(RIGHTDOWN,RIGHTUP,delay,release)

def rightrelease():
    mousebutton(RIGHTUP,RIGHTUP,release=False)

def middleclick(delay=0,release=True):
    mousebutton(MIDDLEDOWN,MIDDLEUP,release)

def middlerelease():
    mousebutton(MIDDLEUP,MIDDLEUP,release=False)

if __name__ == '__main__':
    move(10,1)


from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings

from beerspider.spiders.beers import (
    beyondbeer,
    bierdeluxe,
    bierkaufen,
    bierlinie,
    biermarket,
    bierothek,
    bierpost,
    bierselect,
    craftbeershop,
    hiergibtsbier,
    holycraft,
    meibier,
    ratsherrn,
)
from beerspider.spiders.beers.beertasting_manual import BeertastingManualSpider
from beerspider.spiders.beers.bierlinie_manual import BierlinieManualSpider
from beerspider.spiders.beers.meibier_manual import MeibierManuelSpider

# from beerspider.spiders.beers.flaschenpost_manual import FlaschenpostManualSpider

if __name__ == "__main__":
    beertasting_spider = BeertastingManualSpider(
        scrape_headless=True, scrape_from_germany=True
    )
    beertasting_spider.parse_urls()
    beertasting_spider.export_results()

    bierlinie_spider = BierlinieManualSpider(scrape_headless=True)
    bierlinie_spider.parse_urls()
    bierlinie_spider.export_results()

    meibier_spider = MeibierManuelSpider(scrape_headless=True)
    meibier_spider.parse_urls()
    meibier_spider.export_results()

    # flaschenpost_spider = FlaschenpostManualSpider(scrape_headless=True)
    # flaschenpost_spider.parse_urls()
    # flaschenpost_spider.export_results()

    settings = get_project_settings()
    process = CrawlerProcess(settings)
    process.crawl(beyondbeer.BeyondBeerSpider)
    # process.crawl(bierdeluxe.BierDeluxeSpider)
    process.crawl(bierkaufen.BierKaufenSpider)
    # process.crawl(bierlinie.BierlineSpider)
    process.crawl(biermarket.BiermarketSpider)
    process.crawl(bierothek.BierothekSpider)
    process.crawl(bierpost.BierPostSpider)
    process.crawl(bierselect.BierSelectSpider)
    process.crawl(craftbeershop.CraftbeerShopSpider)
    process.crawl(hiergibtsbier.HiergibtsbierSpider)
    process.crawl(holycraft.HolyCraftSpider)
    # process.crawl(meibier.MeibierSpider)
    process.crawl(ratsherrn.RatsherrnSpider)
    process.start()


import requests

from timer import timer

URL = 'https://httpbin.org/uuid'

def fetch(web, url):
    with web.get(url) as response:
        print(response.json()['uuid'])

@timer(1, 1)
def main():
    with requests.Session() as web:
        for i in range(100):
            fetch(web, URL)


'''
Write a script that takes a string from the user and creates a list of tuples with each word.
For example:

input = "hello world"
result_list = [('h', 'e', 'l', 'l', 'o'), ('w', 'o', 'r', 'l', 'd')]

'''

str = input("Write a string: ")
str = str.split(" ")

nlist = []
for word in str:
    l = list(word)
    l = tuple(l)
    nlist.append(l)
print(nlist)


# Author: Madhur Gupta
# Github: github.com/guptamadhur
# Project: Hacker Rank Practice Python

if __name__ == '__main__':
    (_, A) = (int(input()),set(map(int, input().split())))
    B = int(input())
    for _ in range(B):
        (command, newSet) = (input().split()[0],set(map(int, input().split())))
        getattr(A, command)(newSet)

    print (sum(A))


import uuid
from json import dumps, loads

from boto3 import client
from syndicate.commons.log_helper import get_logger
from syndicate.connection.helper import apply_methods_decorator, retry

_LOG = get_logger('syndicate.connection.sns_connection')

@apply_methods_decorator(retry)
class SNSConnection(object):
    def __init__(self, region=None, aws_access_key_id=None,
                 aws_secret_access_key=None, aws_session_token=None):
        self.client = client('sns', region,
                             aws_access_key_id=aws_access_key_id,
                             aws_secret_access_key=aws_secret_access_key,
                             aws_session_token=aws_session_token)
        _LOG.debug('Opened new SNS connection.')

    def create_topic(self, name):
        """ Crete SNS topic and return topic arn.

        :type name: str
        """
        return self.client.create_topic(Name=name)['TopicArn']

    def subscribe(self, endpoint, topic_name, protocol):
        """
        :param protocol:
            http -- delivery of JSON-encoded message via HTTP POST
            https -- delivery of JSON-encoded message via HTTPS POST
            email -- delivery of message via SMTP
            email-json -- delivery of JSON-encoded message via SMTP
            sms -- delivery of message via SMS
            sqs -- delivery of JSON-encoded message to an Amazon SQS queue
            application -- delivery of JSON-encoded message to an EndpointArn
                           for a mobile app and device.
            lambda -- delivery of JSON message to an AWS Lambda function
        :type protocol: str
        :type topic_name: str
        :param endpoint:
            http protocol, the endpoint is an URL beginning with "http://"
            https protocol, the endpoint is a URL beginning with "https://"
            email protocol, the endpoint is an email address
            email-json protocol, the endpoint is an email address
            sms protocol, the endpoint is a phone number of an SMS-enabled
                device
            sqs protocol, the endpoint is the ARN of an Amazon SQS queue
            application protocol, the endpoint is the EndpointArn of a mobile
                app and device.
            lambda protocol, the endpoint is the ARN of an AWS Lambda function
        :type endpoint: str
        """
        topic_arn = self.get_topic_arn(topic_name)
        if topic_arn is None:
            raise AssertionError(
                'Topic does not exist: {0}.'.format(topic_name))
        self.client.subscribe(TopicArn=topic_arn,
                              Protocol=protocol,
                              Endpoint=endpoint)
        return topic_arn

    def get_topic_arn(self, name):
        """ Get topic arn by name.

        :type name: str
        """
        topics = self.get_topics()
        for each in topics:
            if name == each['TopicArn'].split(':')[-1]:
                return each['TopicArn']

    def get_platform_application(self, name):
        """ Get application arn by name.

        :type name: str
        """
        applications = self.get_platform_applications()
        for each in applications:
            resolved_item = each['PlatformApplicationArn'].split(':')[-1]
            if name == resolved_item.split('/')[-1]:
                return each['PlatformApplicationArn']

    def is_user_subscribed(self, endpoint, topic_name):
        topic_arn = self.get_topic_arn(topic_name)
        subscriptions = self.client.list_subscriptions_by_topic(
            TopicArn=topic_arn)['Subscriptions']
        for each in subscriptions:
            if endpoint == each['Endpoint']:
                return True

    def publish_message(self, topic_name, message):
        topic_arn = self.get_topic_arn(topic_name)
        return self.client.publish(
            TargetArn=topic_arn,
            Message=message,
            MessageAttributes={
                'string': {
                    'DataType': 'String',
                    'StringValue': ' '
                }
            }
        )

    def get_topics(self):
        """ Get all topics."""
        topics = []
        response = self.client.list_topics()
        topics.extend(response.get('Topics'))
        token = response.get('NextToken')
        while token:
            response = self.client.list_topics(NextToken=token)
            topics.extend(response.get('Topics'))
            token = response.get('NextToken')
        return topics

    def get_platform_applications(self):
        """ Get all platform applications."""
        applications = []
        response = self.client.list_platform_applications()
        applications.extend(response.get('PlatformApplications'))
        token = response.get('NextToken')
        while token:
            response = self.client.list_platform_applications(NextToken=token)
            applications.extend(response.get('PlatformApplications'))
            token = response.get('NextToken')
        return applications

    def remove_topic_by_arn(self, topic_arn):
        """ Remove topic by arn.

        :type topic_arn: str
        """
        self.client.delete_topic(TopicArn=topic_arn)

    def remove_topic_by_name(self, topic_name):
        """ Remove topic by arn.

        :type topic_name: str
        """
        arn = self.get_topic_arn(topic_name)
        if arn:
            self.client.delete_topic(TopicArn=arn)

    def set_topic_attribute(self, topic_arn, attr_name, attr_value):
        self.client.set_topic_attributes(
            TopicArn=topic_arn,
            AttributeName=attr_name,
            AttributeValue=attr_value
        )

    def allow_service_invoke(self, topic_arn, service):
        existing_attr = self.get_topic_attributes(topic_arn)
        existing_policy = existing_attr['Attributes']['Policy']
        existing_policy_dict = loads(existing_policy)
        policy = {
            "Sid": str(uuid.uuid1()),
            "Effect": "Allow",
            "Principal":
                {
                    "Service": "{0}".format(service)
                },
            "Action": "sns:Publish",
            "Resource": "{0}".format(topic_arn)
        }
        existing_policy_dict['Statement'].append(policy)
        self.set_topic_attribute(topic_arn, 'Policy',
                                 dumps(existing_policy_dict))

    def get_topic_attributes(self, topic_arn):
        return self.client.get_topic_attributes(
            TopicArn=topic_arn
        )

    def get_platform_application_attributes(self, application_arn):
        return self.client.get_platform_application_attributes(
            PlatformApplicationArn=application_arn
        )

    def add_account_permission(self, topic_arn, account_id, action, label):
        if isinstance(account_id, str):
            account_id = [account_id]
        if not isinstance(account_id, list):
            raise AssertionError('Incorrect account id {0}'.format(account_id))

        if isinstance(action, str):
            action = [action]
        if not isinstance(action, list):
            raise AssertionError('Incorrect action {0}'.format(action))

        self.client.add_permission(TopicArn=topic_arn, Label=label,
                                   AWSAccountId=account_id,
                                   ActionName=action)

    def revoke_account_permission(self, topic_arn, label):
        self.client.remove_permission(TopicArn=topic_arn, Label=label)

    def list_subscriptions_by_topic(self, topic_arn):
        subscriptions = []
        response = self.client.list_subscriptions_by_topic(TopicArn=topic_arn)
        subscriptions.extend(response.get('Subscriptions'))
        token = response.get('NextToken')
        while token:
            response = self.client.list_subscriptions_by_topic(
                TopicArn=topic_arn, NextToken=token)
            subscriptions.extend(response.get('Subscriptions'))
            token = response.get('NextToken')

        return subscriptions

    def unsubscribe(self, subscription_arn):
        self.client.unsubscribe(SubscriptionArn=subscription_arn)

    def create_platform_endpoint(self, platform_application_arn, token):
        response = self.client.create_platform_endpoint(
            PlatformApplicationArn=platform_application_arn,
            Token=token
        )
        return response.get('EndpointArn')

    def create_platform_application(self, name, platform, attributes):
        response = self.client.create_platform_application(
            Name=name, Platform=platform, Attributes=attributes)
        return response.get('PlatformApplicationArn')

    def remove_application_by_arn(self, application_arn):
        """ Remove application by arn.

        :type application_arn: str
        """
        self.client.delete_platform_application(
            PlatformApplicationArn=application_arn)


from PyAsoka.Connections.AConnector import AConnector

class ConnectorsManager:
    def __init__(self):
        self.all = []

    def add(self, connector: AConnector):
        self.all.append(connector)

    def remove(self, value):
        if isinstance(value, AConnector):
            try:
                self.all.remove(value)
            except Exception as e:
                Log.warning(f"Ошибка удаления коннектора (id = {value._id_}) из менеджера. Коннектор не найден.")

        elif isinstance(value, int):
            id = value
            for c in self.all:
                if c._id_ == id:
                    self.all.remove(c)
                    return
            Log.warning(f"Ошибка удаления коннектора (id = {id}) из менеджера. Коннектор не найден.")

        else:
            raise Exception('Broken type of "value" in ConnectorsManager.remove(value)')

    def find(self, id):
        for c in self.all:
            if c._id_ == id:
                return c
        return None

class ConnectorsProcessManager(ConnectorsManager):
    def add(self, connector: AConnector):
        super(ConnectorsProcessManager, self).add(connector)
        from PyAsoka.Processing.AProcess import AProcess, ProcessMessage, Headers
        AProcess.current_process.core.channel.send(ProcessMessage(Headers.CONNECTOR_ADDED, (connector._id_._id_, connector._id_.__unique_name__)))

    def remove(self, value):
        super(ConnectorsProcessManager, self).remove(value)
        from PyAsoka.Processing.AProcess import AProcess, ProcessMessage, Headers
        id = None
        if isinstance(value, AConnector):
            id = value._id_
        elif isinstance(value, int):
            id = value
        AProcess.current_process.core.channel.send(ProcessMessage(Headers.CONNECTOR_REMOVED, (id.__id__, id.__unique_name__)))

class ConnectorsCoreManager(ConnectorsManager):
    def add(self, connector: AConnector):
        super(ConnectorsCoreManager, self).add(connector)
        from PyAsoka.Core.ACore import ACore
        from PyAsoka.Processing.AProcess import ProcessCutaway
        ACore.current_process.multi_connectors.add(connector._id_, ProcessCutaway(ACore.current_process.name, None))

    def remove(self, value):
        super(ConnectorsCoreManager, self).remove(value)
        from PyAsoka.Core.ACore import ACore
        from PyAsoka.Processing.AProcess import ProcessCutaway
        id = None
        if isinstance(value, AConnector):
            id = value._id_
        elif isinstance(value, int):
            id = value
        ACore.current_process.multi_connectors.add(id, ProcessCutaway(ACore.current_process.name, None))


from .solvers import DefaultSolver
import itertools

N = 25

class Solver(DefaultSolver):
    @staticmethod
    def process_input(lines):
        return list(map(int, lines))

    @staticmethod
    def part_1(data):
        return get_bad_num(data)

    @staticmethod
    def part_2(data):
        target = get_bad_num(data)

        result = get_summing_nums(data, target)
        if result:
            start, end = result
            nums = data[start:end]
            return min(nums) + max(nums)

        return None

def get_summing_nums(data, target):
    total = 0
    j = 0
    for i in range(len(data)):
        while total < target:
            j += 1
            total += data[j - 1]
        if total == target:
            return i, j
        total -= data[i]
    return None

def get_bad_num(data):
    for idx in range(N, len(data)):
        prev_set = set(data[idx - N : idx])
        if not get_matching_set(prev_set, 2, data[idx]):
            return data[idx]
    return None

def get_matching_set(number_set, count, _sum):
    for tpl in itertools.combinations(number_set, count):
        if sum(tpl) == _sum:
            return tpl
    return None


import numpy as np

a = np.array([2, 4])
b = np.array([3, 1])

cross_ab = np.cross(a, b)

area = np.linalg.norm(cross_ab)

tra_area = area / 2

print("tra area vlaue: ", tra_area)


'''
Napiš funkci, která pro argumentem zadané číslo n vytvoří a vrátí slovník,
kde jako klíče budou čísla od jedné do n a jako hodnoty k nim jejich
druhé mocniny. Například:

>>> mocniny(4)
{1: 1, 2: 4, 3: 9, 4: 16}

'''

def squares(number):
    d = {}
    for i in range(1,number):
        d[i] = i * i

    return d

print(squares(9))


import pandas as pd
from sklearn.linear_model import LinearRegression

df = pd.read_csv('carprices.csv')

# prepare data
dummies = (pd.get_dummies(df['Car Model']).astype(int))

df = pd.concat([df,dummies],axis=1)

df = df.drop(['Car Model','Mercedez Benz C class'],axis=1)
print(df)

X = df.drop('Sell Price($)',axis=1).values
y = df['Sell Price($)'].values

# train
model = LinearRegression()
model.fit(X,y)

# predict
print(model.predict([[45000,4,0,0]]))
print(model.predict([[86000,7,0,1]]))
print(model.score(X,y))

v5 - Dummy Variables & One Hot Encoding/exercise.py


import re

def parseKeySequence(keyseq):
    """ Parse the key sequence string and return a Keystroke() list.
        Returns None when parsing failed.
    """
    keystrokes = []
    while len(keyseq) > 0:
        if keyseq[0] == '\\': # escape next character
            keystr = keyseq[0:2]
            keyseq = keyseq[2:]
        else:
            match = re.match(r"^<([^>]+)>", keyseq)
            if match: # found a non-displayable key (e.g. "<C-x>")
                keystr = match.group(1) # string inside <>
                keyseq = keyseq[len(match.group(0)):] # remove <...>
            else:
                keystr = keyseq[0] # the leading character
                keyseq = keyseq[1:] # remove the leading character
        if ' ' in keystr: # no space allowed in key sequence
            return None
        try:
            keystroke = Keystroke(keystr)
            keystrokes.append(keystroke)
        except:
            return None
    return keystrokes

class Keystroke(object):

    def __init__(self, keystr):
        ctrl = False
        meta = False
        shift = False
        # parse modifier
        while True:
            # match "C-" or "S-" or "M-" at the beginning of the string
            match = re.match(r"^([CcSsMm])-", keystr)
            if match:
                modifier = match.group(1).upper() # normalize to upper case
                if modifier == "C":
                    ctrl = True
                elif modifier == "S":
                    shift = True
                elif modifier == "M":
                    meta = True
                keystr = keystr[len(match.group(0)):] # remove the modifier
            else: # no more modifiers
                break
        self.key = keystr.lower() # keys are normalized to upper case
        self.ctrl = ctrl
        self.meta = meta
        self.shift = shift

    def __eq__(self, other):
        return self.key == other.key \
            and self.ctrl == other.ctrl \
            and self.meta == other.meta \
            and self.shift == other.shift

    def __hash__(self):
        return hash((self.key, self.ctrl, self.meta, self.shift))

    def __str__(self):
        kstr = ""
        if self.ctrl:
            kstr += "C-"
        if self.shift:
            kstr += "S-"
        if self.meta:
            kstr += "M-"
        kstr += self.key
        return kstr

    def __repr__(self):
        return "Keystroke(%s)" % str(self)

class ActionNode(object):

    def __init__(self):
        self.children = None

    def setAction(self, callback, *args):
        self.action = callback
        self.args = args

    def hasAction(self):
        return self.action != None

    def fire(self):
        if self.action:
            self.action(*self.args)

    def createChild(self, keystroke):
        if not self.children:
            self.children = dict()
        child = ActionNode()
        self.children[keystroke] = child
        return child

    def getChild(self, keystroke):
        if self.children:
            return self.children.get(keystroke, None)
        else:
            return None

    def hasChild(self):
        return self.children != None

class ShortcutMapper(object):

    def __init__(self):
        self.rootNode = ActionNode()
        self.queue = []

    def getNode(self, keystrokes, create):
        """ Get the node mapped to keystrokes. """
        assert(type(keystrokes) == list)
        node = self.rootNode
        for key in keystrokes:
            assert(type(key) == Keystroke)
            child = node.getChild(key)
            if child == None:
                if create:
                    child = node.createChild(key)
                else:
                    return None
            node = child
        return node

    def bind(self, keystrokes, callback, *args):
        node = self.getNode(keystrokes, create=True)
        node.setAction(callback, *args)

    def unbind(self, keystrokes):
        raise Exception("unbind() not implemented")

    def pressKey(self, keystroke):
        assert(type(keystroke) == Keystroke)
        self.queue.append(keystroke)
        node = self.getNode(self.queue, create=False)
        if node:
            if not node.hasChild(): # leaf node
                node.fire()
                self.resetState()
        else: # undefined mapping
            self.resetState()
            return False
        return True

    def resetState(self):
        self.queue[:] = [] # clear python list in place

    def clearAll(self):
        """ remove all shortcuts """
        # throw away old root node
        self.rootNode = ActionNode()

    def queuedKeys(self):
        return self.queue[:] # copy


count_of_sentences = int(input())
key_word = input()

list_of_sentences = []
list_of_key_word_sentences = []

for count in range(1, count_of_sentences + 1):
    current_sentence = input()
    list_of_sentences.append(current_sentence)
    if key_word in current_sentence:
        list_of_key_word_sentences.append(current_sentence)

print(list_of_sentences)
print(list_of_key_word_sentences)


#!/usr/bin/python

class LoadConfig:

  list = []

  def loadconfig(self):
    tmplist = []
    f = open("./config/config.txt","r")
    for counter, data in enumerate(f.readlines()):
      data = data.split('=')
      tmplist.append([])
      key = data[0]
      key = key.replace('\n', '')
      key = key.replace('\n', '')
      value = data[1]
      value = value.replace('\n', '')
      value = value.replace(' ', '')
      tmplist[counter] = [key,value]
    f.close()
    self.list = tmplist

  def getconfig(self, key):
    for value in self.list:
      if value[0].replace(' ', '') in key:
        return value[1]


# Crie um programa onde o usuário digite uma expressão qualquer que use parênteses.
# Seu aplicativo deverá analisar se a expressão passada está com os parênteses abertos e fechados na ordem correta.
analysis = []
expression = str(input('Digite a expressão matemática: '))
for caractere in expression:
    if caractere == '(':
        analysis.append('(')
    elif caractere == ')':
        if len(analysis) > 0:
            analysis.pop()
        else:
            analysis.append(')')
            break
if len(analysis) == 0:
    print('Expressão válida!')
else:
    print('Expressão inválida!')


import numpy, pandas, sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt, mpld3

PRICE = 0.00001667
WORKLOAD = 100000

try:
    data = pandas.read_csv('data.csv')
    data = data.sort_values(by=['MemorySize'])
    data['cost100k'] = data.apply(lambda row: ((WORKLOAD * row.BilledDuration)/1000) * (row.MemorySize / 1024) * PRICE, axis=1)
    data.round(2).sort_values(by=['cost100k']).to_csv('totalcost-100000.csv')
    # print(data)
except Exception as error:
    print('Error:', error)


from asyncio.futures import Future
import logging
from os import getpid
from random import randint
from time import time
from typing import Callable, Iterable
from bacpypes.apdu import (
    ConfirmedRequestSequence,
    SubscribeCOVRequest,
)
from bacpypes.core import deferred
from bacpypes.iocb import IOCB, IOController
from bacpypes.pdu import Address
from bacpypes.primitivedata import ObjectIdentifier
from bacpypes.task import OneShotTask
from fastapi.exceptions import HTTPException

_logger = logging.getLogger(__name__)

class _BaseRecurringTask(OneShotTask):
    def __init__(self, interval: int | None, offset: float | None = None) \
            -> None:
        self.interval = interval
        self.offset = offset
        self.cancelled = False
        super().__init__()
        _logger.debug("Init %r", self)

    def install_task(self, when: float | None = None,
                     delta: float | None = None) -> None:
        if self.cancelled:
            return
        offset = self.offset if self.offset is not None else 0
        super().install_task(when=time() + offset)

    def process_task(self) -> None:
        _logger.debug("Pocess task %r", self)
        if self.interval and not self.cancelled:
            super().install_task(delta=self.interval)

    def cancel_task(self) -> None:
        _logger.debug("Canceled task %r", self)
        self.cancelled = True

class _BaseIOTask(_BaseRecurringTask):
    def __init__(self, io_controller: IOController, interval: int,
                 offset: float | None = None,
                 callback: Callable[[IOCB], None] | None = None) -> None:
        if offset is None:
            offset = randint(0, interval * 1000 - 1) / 1000.0
        self.io_controller = io_controller
        self.callback = callback
        super().__init__(interval, offset)

    def _add_callback(self, iocb: IOCB) -> None:
        if self.callback is not None:
            iocb.add_callback(self.callback)

    def process_task(self) -> None:
        super().process_task()
        for request in self._build_requests():
            iocb = IOCB(request)
            self._add_callback(iocb)
            deferred(self.io_controller.request_io, iocb)

    def _build_requests(self) -> Iterable[ConfirmedRequestSequence]:
        raise NotImplementedError()

class SubscribeCOVTask(_BaseIOTask):
    def __init__(self, io_controller: IOController, address: Address,
                 object_identifier: ObjectIdentifier, cov_lifetime: int,
                 future: Future[bool]) \
            -> None:
        self.address = address
        self.object_identifier = object_identifier
        self.lifetime = cov_lifetime
        self.future = future
        super().__init__(io_controller, cov_lifetime, 0)

    def _build_requests(self) -> Iterable[ConfirmedRequestSequence]:
        yield SubscribeCOVRequest(
            destination=self.address,
            subscriberProcessIdentifier=getpid(),
            monitoredObjectIdentifier=self.object_identifier,
            issueConfirmedNotifications=False,
            lifetime=self.lifetime
        )

    def process_subscribe_ack(self, iocb: IOCB) -> None:
        if iocb.ioError:
            _logger.error("Failed to subscribe to %r@%r: %r",
                          self.object_identifier, self.address, iocb.ioError)
            if not self.future.done():
                self.future.set_exception(HTTPException(
                    500, f"Failed to subscribe to COV: {iocb.ioError}",
                ))
            self.cancel_task()
        else:
            _logger.debug("Subsribed to %r@%r", self.object_identifier,
                          self.address)
            if not self.future.done():
                self.future.set_result(True)

    def _add_callback(self, iocb: IOCB) -> None:
        iocb.add_callback(self.process_subscribe_ack)


from django.shortcuts import render, redirect
from django.views.generic.base import View
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.db.models import Q, Avg
from django.http import JsonResponse

from .models import Game, Genre, Category, Developer
from .forms import ReviewForm, RatingForm, Rating
# Create your views here.

class GenreYear:
    """Жанры и года выхода фильмов"""
    def get_genres(self):
        return Genre.objects.all()

    def get_years(self):
        return Game.objects.filter(draft=False).order_by('year').values("year").distinct()

class GamesView(GenreYear, ListView):
	"""Список игр"""
	model = Game
	queryset = Game.objects.filter(draft=False)
	template_name = "game/games.html"

	paginate_by = 10

class GameDetailView(GenreYear, DetailView):
    """Полное описание игры"""
    model = Game
    slug_field = "url"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["star_form"] = RatingForm()
        return context

class GenreView(GenreYear, DetailView):
    model = Genre
    template_name = "games/genre.html"
    slug_field = "url"

class AddReview(View):
	"""Отзывы"""
	def post(self, request, pk):
		form = ReviewForm(request.POST)
		game = Game.objects.get(id=pk)
		if form.is_valid():
			form = form.save(commit=False)
			if request.POST.get("parent", None):
				form.parent_id = int(request.POST.get("parent"))
			form.game_id = pk
			form.save()

		return redirect(game.get_absolute_url())

class DeveloperView(GenreYear, DetailView):
	"""Полное описание разработчика или публ"""
	model = Developer
	template_name = 'games/developer.html'
	slug_field = "name"

class FilterGamesView(GenreYear, ListView):
    """Фильтр игр"""
    paginate_by = 6

    def get_queryset(self):
        queryset = Game.objects.filter(
            Q(year__in=self.request.GET.getlist("year")) |
            Q(genre__in=self.request.GET.getlist("genre"))
        ).distinct()
        return queryset

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context["year"] = ''.join([f"year={x}&" for x in self.request.GET.getlist("year")])
        context["genre"] = ''.join([f"genre={x}&" for x in self.request.GET.getlist("genre")])
        return context

class AddStarRating(View):
    """Добавление рейтинга фильму"""
    def get_client_ip(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip

    def post(self, request):
        form = RatingForm(request.POST)
        if form.is_valid():
            Rating.objects.update_or_create(
                ip=self.get_client_ip(request),
                game_id=int(request.POST.get("game")),
                user=request.POST.get("username"),
                defaults={'star_id': int(request.POST.get("star"))},

            )
            return HttpResponse(status=201)
        else:
            return HttpResponse(status=400)

class Search(ListView):
    """Поиск фильмов"""
    paginate_by = 4

    def get_queryset(self):
        return Game.objects.filter(title__icontains=self.request.GET.get("q"))

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context["q"] = f'q={self.request.GET.get("q")}&'
        return context