class StringListener(object):
    """
    Recognizes a string in a stream of characters
    """
    def __init__(self, string, any_position=True):
        """
        @param string: the character sequence to be recognized
        @param any_position: if True the sequence may occur at any position in
                the stream, if False it must occur at the start
        """
        self._string = string
        self._last = len(string)
        self._pos = 0
        self._any_position = any_position

        self._active = True

    def put(self, char):
        """
        Returns True if the string is recognized
        """
        if not self._active:
            return False

        if char == self._string[self._pos]:
            self._pos += 1

            if self._pos == self._last:
                return True
        else:
            if self._any_position:
                self._pos = 0
            else:
                self._active = False

        return False

from ..util import StringReader

class Token(object):
    """
    A Token returned by the Lexer
    """

    COMMAND, TEXT, COMMENT, VERBATIM, BEGIN_CURLY, END_CURLY, BEGIN_SQUARE, END_SQUARE = list(range(8))

    def __init__(self, type, offset=None, value=None):
        self.type = type
        self.offset = offset
        self.value = value

    @property
    def xml(self):
        if self.type == self.COMMAND:
            return "<t:command>%s</t:command>" % self.value
        elif self.type == self.TEXT:
            return "<t:text>%s</t:text>" % self.value
        elif self.type == self.VERBATIM:
            return "<t:verbatim>%s</t:verbatim>" % self.value
        elif self.type == self.COMMENT:
            return "<t:comment>%s</t:comment>" % self.value
        else:
            return "<t:terminal />"

class Lexer(object):
    """
    LaTeX lexer
    """

    # TODO: redesign and optimize this from a DFA

    # states of the lexer
    _DEFAULT, _BACKSLASH, _COMMAND, _TEXT, _COMMENT, _PRE_VERB, _VERB, _VERBATIM = list(range(8))

    _SPECIAL = set(["&", "$", "{", "}", "[", "]", "%", "#", "_", "\\"])

    _TERMINALS = set(["{", "}", "[", "]"])
    _TERMINALS_MAP = {"{" : Token.BEGIN_CURLY, "}" : Token.END_CURLY,
                      "[" : Token.BEGIN_SQUARE, "]" : Token.END_SQUARE}

    _VERBATIM_ENVIRONS = set(["verbatim", "verbatim*", "lstlisting", "lstlisting*"])

    # additional states for recognizing "\begin{verbatim}"
    _VERBATIM_DEFAULT, _VERBATIM_BEGIN, _VERBATIM_BEGIN_CURLY, _VERBATIM_BEGIN_CURLY_ENVIRON = list(range(4))

    def __init__(self, string, skipWs=True, skipComment=False):
        self._reader = StringReader(string)

        self._skipWs = skipWs
        self._skipComment = skipComment

        self._state = self._DEFAULT
        self._verbatimState = self._VERBATIM_DEFAULT

        self._eof = False
        self._tokenStack = []    # used to return a sequence of tokens after a verbatim ended

    def __iter__(self):
        return self

    def __next__(self):
        if self._eof:
            raise StopIteration

        # first empty the token stack
        if len(self._tokenStack):
            return self._tokenStack.pop()

        while True:
            try:
                char = self._reader.read()

                if self._state == self._DEFAULT:
                    if char == "\\":
                        self._state = self._BACKSLASH
                        self._verbatimState = self._VERBATIM_DEFAULT
                        self._startOffset = self._reader.offset - 1

                    elif char == "%":
                        self._state = self._COMMENT
                        self._verbatimState = self._VERBATIM_DEFAULT
                        self._startOffset = self._reader.offset - 1
                        if not self._skipComment:
                            self._text = []

                    elif char in self._TERMINALS:
                        if self._verbatimState == self._VERBATIM_BEGIN and char == "{":
                            self._verbatimState = self._VERBATIM_BEGIN_CURLY

                        elif self._verbatimState == self._VERBATIM_BEGIN_CURLY_ENVIRON and char == "}":
                            # we have "\begin{verbatim}"
                            self._verbatimState = self._VERBATIM_DEFAULT
                            self._state = self._VERBATIM
                            self._text = []
                            self._startOffset = self._reader.offset
                            self._verbatimSequenceListener = StringListener("\\end{%s}" % self._verbatimEnviron)

                        else:
                            self._verbatimState = self._VERBATIM_DEFAULT

                        return Token(self._TERMINALS_MAP[char], self._reader.offset - 1)

                    else:
                        self._state = self._TEXT
                        self._startOffset = self._reader.offset - 1
                        self._text = [char]

                elif self._state == self._BACKSLASH:
                    if char in self._SPECIAL or char.isspace():
                        # this is a one-character-command, also whitespace is allowed
                        self._state = self._DEFAULT
                        return Token(Token.COMMAND, self._startOffset, char)

                    else:
                        self._state = self._COMMAND

                        self._verbListener = StringListener("verb", any_position=False)
                        self._verbListener.put(char)

                        self._text = [char]

                elif self._state == self._COMMENT:
                    if char == "\n":
                        self._state = self._DEFAULT
                        if not self._skipComment:
                            return Token(Token.COMMENT, self._startOffset, "".join(self._text))

                    else:
                        if not self._skipComment:
                            self._text.append(char)

                elif self._state == self._COMMAND:
                    if char in self._SPECIAL or char.isspace():

                        name = "".join(self._text)

                        # this is mostly false because \verb is mostly followed by something like |
                        if name == "verb":
                            self._state = self._VERB
                            self._verbDelimiter = char
                            self._startOffset = self._reader.offset - 1
                            self._text = [char]

                        elif name == "url":     # we handle "\url" just like "\verb"
                            self._state = self._VERB
                            self._verbDelimiter = "}"
                            self._startOffset = self._reader.offset - 1
                            self._text = []

                        else:
                            self._state = self._DEFAULT
                            self._reader.unread(char)

                            if name == "begin":
                                self._verbatimState = self._VERBATIM_BEGIN

                            return Token(Token.COMMAND, self._startOffset, name)

                    else:
                        if self._verbListener.put(char):
                            # we have "\verb"
                            self._state = self._PRE_VERB
                        else:
                            self._text.append(char)

                elif self._state == self._PRE_VERB:
                    self._state = self._VERB
                    self._verbDelimiter = char
                    self._startOffset = self._reader.offset - 1
                    self._text = []

                elif self._state == self._TEXT:
                    if char in self._SPECIAL:
                        self._state = self._DEFAULT
                        self._reader.unread(char)

                        text = "".join(self._text)

                        if self._skipWs and text.isspace():
                            continue
                        else:

                            if self._verbatimState == self._VERBATIM_BEGIN_CURLY:
                                # we have "\begin{" until now, handle verbatim environment

                                if text in self._VERBATIM_ENVIRONS:
                                    self._verbatimEnviron = text
                                    self._verbatimState = self._VERBATIM_BEGIN_CURLY_ENVIRON

                                else:
                                    self._verbatimState = self._VERBATIM_DEFAULT

                            return Token(Token.TEXT, self._startOffset, text)

                    else:
                        self._text.append(char)

                elif self._state == self._VERB:
                    if char == self._verbDelimiter:        # FIXME: \overbrace
                        self._state = self._DEFAULT

                        return Token(Token.VERBATIM, self._startOffset, "".join(self._text) + char)

                    else:
                        self._text.append(char)

                elif self._state == self._VERBATIM:
                    if self._verbatimSequenceListener.put(char):
                        self._state = self._DEFAULT

                        # TODO: calculate offsets
                        self._tokenStack = [ Token(Token.END_CURLY, 0),
                                             Token(Token.TEXT, 0, self._verbatimEnviron),
                                             Token(Token.BEGIN_CURLY, 0),
                                             Token(Token.COMMAND, 0, "end") ]

                        text = "".join(self._text)
                        text = text[5:]        # cut off "\end{"
                        return Token(Token.VERBATIM, self._startOffset, text)
                    else:
                        self._text.append(char)

                elif self._state == self._VERB:
                    # this char is the verb delimiter
                    # TODO: implement verbatim detection
                    pass

            except StopIteration:
                self._eof = True

                # evaluate final state
                if self._state == self._BACKSLASH:
                    return Token(Token.COMMAND, self._startOffset, "")

                elif self._state == self._COMMAND:
                    return Token(Token.COMMAND, self._startOffset, "".join(self._text))

                elif self._state == self._TEXT:
                    text = "".join(self._text)
                    if not (self._skipWs and text.isspace()):
                        return Token(Token.TEXT, self._startOffset, text)

                elif self._state == self._VERB:

                    # TODO: the document is malformed in this case, so the lexer should be
                    # able to produce issues, too
                    #
                    # TODO: return a VERBATIM token

                    return Token(Token.TEXT, self._startOffset, "".join(self._text))

                raise StopIteration
# ex:ts=4:et:


# https://adventofcode.com/2020/day/11

def apply_rules_seat(nearby_seats, seat, max):
    """ Checks seating conditions based on nearby seats """
    if seat == "L" and "#" not in nearby_seats:
            return "#"
    if seat == "#" and nearby_seats.count("#") >= max:
            return "L"
    return seat

def apply_rules_row(row, top_row=None, bottom_row=None):
    """ Create new row based on simple rule for row with 8 nearby seats """
    new_row = ""
    if not top_row:
        top_row = "." * len(row)
    if not bottom_row:
        bottom_row = "." * len(row)
    row = "." + row + "."
    top_row = "." + top_row + "."
    bottom_row = "." + bottom_row + "."
    for i, seat in enumerate(row[1:-1]):
        nearby_seats = (top_row[i:i+3] + bottom_row[i:i+3] + row[i] + row[i+2])
        new_row += apply_rules_seat(nearby_seats, seat, 4)
    return new_row

def model_people():
    """ Simulates the seating of people
    according to simple rules sitting nearby.
    """
    layout = open("input.txt").read().splitlines()
    count_occupied_seats = 0
    while True:
        layout_new = []
        for i, row in enumerate(layout):
            if i == 0:
                layout_new.append(apply_rules_row(row=row,
                                                  bottom_row=layout[1]))
            elif i == len(layout)-1:
                layout_new.append(apply_rules_row(row=row, top_row=layout[-2]))
            else:
                layout_new.append(apply_rules_row(row=row, top_row=layout[i-1],
                                                  bottom_row=layout[i+1]))
        count_seats = sum([seats.count("#") for seats in layout_new])
        if count_occupied_seats == count_seats:
            return count_occupied_seats
        else:
            count_occupied_seats = count_seats
        layout = layout_new

print(model_people())

""" PART 2 """

def model_people_second():
    """ Simulates the seating of people according to
    rules sitting visibility in in each eight directions.
    """
    layout = open("input.txt").read().splitlines()
    count_occupied_seats = 0
    while True:
        layout_new = []
        for row in range(len(layout)):
            new_row = ''
            for col in range(len(layout[0])):
                visible_seats = ""
                for x in (-1, 0, 1):
                    for y in (-1, 0, 1):
                        if x == y == 0:
                            continue
                        i = 1
                        while (0 <= row+i*x < len(layout) and
                               0 <= col+i*y < len(layout[0])):
                            seat = layout[row+i*x][col+i*y]
                            if seat != '.':
                                visible_seats += seat
                                break
                            i += 1
                new_row += apply_rules_seat(visible_seats, layout[row][col], 5)
            layout_new.append(new_row)
        count_seats = sum([seats.count("#") for seats in layout_new])
        if count_occupied_seats == count_seats:
            return count_occupied_seats
        else:
            count_occupied_seats = count_seats
        layout = layout_new

print(model_people_second())


import logging
import os.path
import unittest

from selenium import webdriver
import json
from os import walk

import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys

import PrototypeCommon

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

class PrototypeTeso(PrototypeCommon.PrototypeCommon):
    pathApp = "C:\\Users\\hgarau\\Documents\\Visual Studio 2015\\Projects\\puntacaja_net-release-2.15.0\\puntacaja_net-release-2.15.0\\SirisMVC\\UseMVCApplication\\bin\\Debug\\SirisNet.exe"

    fileGestionJSON = "data\\teso_test\\gestion_cajas.json"

    def inicioAbrir(self):
        self.driver.find_element_by_name("Herramientas").click()
        self.driver.find_element_by_name("Abrir agencia").click()

    def abrirCaja(self):
        self.inicioAbrir()
        self.logger("ABRIR AGENCIA",'abrir_agencia.jpg')
        self.driver.find_element_by_name("Confirmar <F2>").click()
        if self.driver.find_elements_by_name("Yes"):
            self.driver.find_element_by_name("Yes").click()
            self.login()
        self.driver.find_element_by_name("OK").click()

    def gestionCajas(self, data):
        self.inicioGestionCajas()

        if isinstance(data,str):
            os.path.isfile(data)
            data = self.loadFromJSon(data)

        for i in range(0, 10): #asumo que no hay as de 50 terminales
            logging.info(str(i))
            try:
                rowTerminal = self.driver.find_element_by_name("Nro terminal Row " + str(i))
            except NoSuchElementException:
                break
            if rowTerminal.text in data["Habilitadas"]:
                try:
                    if self.driver.find_element_by_name("Habilitada Row " + str(i)).text == 'False':
                        self.switchTerminal(rowTerminal)
                except NoSuchElementException:
                    self.switchTerminal(rowTerminal)
            else:
                if rowTerminal.text in data["Deshabilitadas"]:
                    try:
                        if self.driver.find_element_by_name("Habilitada Row " + str(i)).text == 'True':
                            self.switchTerminal(rowTerminal)
                    except NoSuchElementException:
                        pass
        self.logger('Gestion de agencias','gestion_agencia.jpg')
        self.driver.find_element_by_name("Guardar <F2>").click()
        self.driver.find_element_by_name("Yes").click()
        self.driver.find_element_by_name("OK").click()

    def switchTerminal(self, rowTerminal):
        ac = ActionChains(self.driver)
        rowTerminal.click()
        ac.move_to_element(rowTerminal) \
            .key_down(Keys.SHIFT) \
            .send_keys(Keys.TAB + Keys.TAB + Keys.TAB ) \
            .key_up(Keys.SHIFT) \
            .send_keys(Keys.SPACE) \
            .perform()

    def inicioGestionCajas(self):
        menu = self.driver.find_element_by_name("Herramientas")
        menu.click()
        menu.send_keys(Keys.ARROW_DOWN + Keys.ARROW_DOWN + Keys.ENTER)

    def inicioCerrar(self):
        menu = self.driver.find_element_by_name("Operaciones")
        menu.click()
        menu.send_keys(Keys.CONTROL, Keys.F3)


from django.shortcuts import render, redirect
from . models import Short
from django.utils.crypto import get_random_string
from django.contrib import messages

# Create your views here.

def enter_url(request):
    if request.method == "GET":
        return render(request, 'enter_url.html')
    elif request.method == "POST":
        # creates dictionary
        url_entered = request.POST['url_entered']
        for u in url_entered:
            if 'https://' in url_entered:
                messages.warning(request, 'Remove HTTPS:// from the URL')
                return render(request, 'enter_url.html')
            else:
                decode_url = url_entered.split('/')
                random = get_random_string(length=5)
                ending_url = decode_url[0] + u + '/' + random
                shortened = Short.objects.create(url=url_entered, code=ending_url)

                return render(request, 'show.html')

def show_all(request):
    url_list = Short.objects.all()
    context = {
        'url_list': url_list
    }
    if request.method == 'GET':
        return render(request, 'show.html', context)
    elif request.method == 'POST':
        return render(request, 'enter_url.html')

# name="url" in template html in input refers to the key in veiws.py ['url']
# where the vars does not have to be the same name as the key in veiws.py
# the {% url 'add_url' %} refers to the urls.py name=


import requests

from wwl_task.settings import BOT_TOKEN, CHAT_ID

bot_token = BOT_TOKEN
chat_id = CHAT_ID

def send_message(message):
    requests.get(
        f"https://api.telegram.org/bot{bot_token}/sendMessage",
        {"chat_id": chat_id, "text": message},
    )


from jobs.models import Applicant, ApplicantHistory, Comment
from jobs.serializers import ApplicantListSerializer, ApplicantDetailSerializer, ApplicantHistorySerializer, \
    CommentSerializer
from rest_framework import viewsets
from rest_framework import permissions
from rest_framework.decorators import action
from rest_framework.response import Response

class ApplicantViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows applicants to be viewed or edited.
    """
    queryset = Applicant.objects.all().order_by('-created_at')

    def get_queryset(self):
        """
        Optionally restricts the returned applicants to a given job posting,
        by filtering against some query parameters in the URL.
        """
        queryset = self.queryset
        job_posting = self.request.query_params.get('job_posting', None)
        status = self.request.query_params.get('status', None)
        full_name = self.request.query_params.get('full_name', None)
        if job_posting is not None:
            queryset = queryset.filter(job_posting=job_posting)
        if status is not None:
            queryset = queryset.filter(status=status)
        if full_name is not None:
            queryset = queryset.filter(full_name__icontains=full_name)
        return queryset

    def get_serializer_class(self):
        if self.action == 'list':
            return ApplicantListSerializer
        else:
            return ApplicantDetailSerializer

    def get_permissions(self):
        """
        Instantiates and returns the list of permissions that this view requires.
        """
        if self.action == 'create':
            permission_classes = []
        else:
            permission_classes = [permissions.IsAuthenticated]
        return [permission() for permission in permission_classes]

    @action(detail=True, methods=['get'])
    def history(self, request, pk=None):
        applicant = self.get_object()
        history = ApplicantHistory.objects.all().filter(applicant__pk=applicant.id).order_by('-created_at')
        serializer = ApplicantHistorySerializer(history, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=['get'])
    def statuses(self, request, pk=None):
        statuses = {}
        for (choice, label) in Applicant.ApplicantStatus.choices:
            statuses[choice] = label
        return Response(statuses)

    @action(detail=True, methods=['get'])
    def comments(self, request, pk=None):
        applicant = self.get_object()
        comments = Comment.objects.all().filter(applicant=applicant).order_by('-created_at')
        page = self.paginate_queryset(comments)
        if page is not None:
            serializer = CommentSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = CommentSerializer(comments, many=True)
        return Response(serializer.data)


#! /usr/bin/env python3
#

import numpy as np
import matplotlib.pyplot as plt
import random as rn
import platform
import time
import sys
import os
import math
from mpl_toolkits.mplot3d import Axes3D
from sys import exit

sys.path.append(os.path.join("../"))
from base import plot2d, plotocc
from timestamp.timestamp import timestamp

from i4lib.i4vec_print import i4vec_print
from i4lib.i4mat_print import i4mat_print, i4mat_print_some
from r8lib.r8vec_print import r8vec_print
from r8lib.r8mat_print import r8mat_print, r8mat_print_some
from r8lib.r8mat_write import r8mat_write
from i4lib.i4vec_transpose_print import i4vec_transpose_print
from r8lib.r8mat_transpose_print import r8mat_transpose_print, r8mat_transpose_print_some

from i4lib.i4vec_uniform_ab import i4vec_uniform_ab
from i4lib.i4mat_uniform_ab import i4mat_uniform_ab
from r8lib.r8_uniform_ab import r8vec_uniform_01, r8mat_uniform_ab
from monomial.monomial_value import monomial_value
from rnglib.sample import wedge01_sample

def wedge01_monomial_integral(e):

    # *****************************************************************************80
    #
    # WEDGE01_MONOMIAL_INTEGRAL: integral of a monomial in the unit wedge in 3D.
    #
    #  Discussion:
    #
    #    This routine returns the integral of
    #
    #      product ( 1 <= I <= 3 ) X(I)^E(I)
    #
    #    over the unit wedge.
    #
    #    The integration region is:
    #
    #      0 <= X
    #      0 <= Y
    #      X + Y <= 1
    #      -1 <= Z <= 1.
    #
    #  Licensing:
    #
    #    This code is distributed under the GNU LGPL license.
    #
    #  Modified:
    #
    #    23 June 2015
    #
    #  Author:
    #
    #    John Burkardt
    #
    #  Reference:
    #
    #    Arthur Stroud,
    #    Approximate Calculation of Multiple Integrals,
    #    Prentice Hall, 1971,
    #    ISBN: 0130438936,
    #    LC: QA311.S85.
    #
    #  Parameters:
    #
    #    Input, integer E(3), the exponents.
    #
    #    Output, real VALUE, the integral of the monomial.
    #
    from sys import exit

    value = 1.0

    k = e[0]

    for i in range(1, e[1] + 1):
        k = k + 1
        value = value * float(i) / float(k)

    k = k + 1
    value = value / float(k)

    k = k + 1
    value = value / float(k)

    #
    #  Now account for integration in Z.
    #
    if (e[2] == - 1):
        print('')
        print('WEDGE01_MONOMIAL_INTEGRAL - Fatal error!')
        print('  E(3) = -1 is not a legal input.')
        exit('WEDGE01_MONOMIAL_INTEGRAL - Fatal error!')
    elif ((e[2] % 2) == 1):
        value = 0.0
    else:
        value = value * 2.0 / float(e[2] + 1)

    return value

def wedge01_monomial_integral_test():

    # *****************************************************************************80
    #
    # WEDGE01_MONOMIAL_INTEGRAL_TEST tests WEDGE01_MONOMIAL_INTEGRAL.
    #
    #  Licensing:
    #
    #    This code is distributed under the GNU LGPL license.
    #
    #  Modified:
    #
    #    23 June 2015
    #
    #  Author:
    #
    #    John Burkardt
    #
    import numpy as np
    import platform

    m = 3
    n = 500000
    e_max = 6

    print('')
    print('WEDGE01_MONOMIAL_INTEGRAL_TEST:')
    print('  Python version: %s' % (platform.python_version()))
    print('  WEDGE01_MONOMIAL_INTEGRAL computes the integral of a monomial')
    print('  over the interior of the unit wedge in 3D.')
    print('  Compare with a Monte Carlo estimate.')

    seed = 123456789
    x, seed = wedge01_sample(n, seed)

    print('')
    print('  Number of sample points used is %d' % (n))
    print('')
    print('   E1  E2  E3     MC-Estimate      Exact           Error')
    print('')
    #
    #  Check all monomials up to total degree E_MAX.
    #
    e = np.zeros(3, dtype=np.int32)

    for e3 in range(0, e_max + 1):
        e[2] = e3
        for e2 in range(1, e_max - e3 + 1):
            e[1] = e2
            for e1 in range(0, e_max - e3 - e2 + 1):
                e[0] = e1

                value = monomial_value(m, n, e, x)

                q = 1 * np.sum(value) / float(n)
                exact = wedge01_monomial_integral(e)
                error = abs(q - exact)

                print('  %2d  %2d  %2d  %14.6g  %14.6g  %14.6g'
                      % (e[0], e[1], e[2], q, exact, error))

    print('')
    print('WEDGE01_MONOMIAL_INTEGRAL_TEST:')
    print('  Normal end of execution.')

def wedge01_monte_carlo_test():

    # *****************************************************************************80
    #
    # WEDGE01_MONTE_CARLO_TEST uses WEDGE01_SAMPLE with an increasing number of points.
    #
    #  Licensing:
    #
    #    This code is distributed under the GNU LGPL license.
    #
    #  Modified:
    #
    #    13 November 2016
    #
    #  Author:
    #
    #    John Burkardt
    #

    m = 3

    e_test = np.array([
        [0, 0, 0],
        [1, 0, 0],
        [0, 1, 0],
        [0, 0, 1],
        [2, 0, 0],
        [1, 1, 0],
        [0, 0, 2],
        [3, 0, 0]])

    print('')
    print('WEDGE01_MONTE_CARLO_TEST')
    print('  Python version: %s' % (platform.python_version()))
    print('  Use WEDGE01_SAMPLE for a Monte Carlo estimate of an')
    print('  integral over the interior of the unit wedge in 3D.')

    seed = 123456789

    print('')
    print('         N        1               X               Y               Z                X^2            XY              Z^2            X^3')
    print('')

    n = 1

    e = np.zeros(3, dtype=np.int32)

    while (n <= 65536):

        x, seed = wedge01_sample(n, seed)

        print('  %8d' % (n), end='')

        for j in range(0, 8):

            e[0:m] = e_test[j, 0:m]

            value = monomial_value(m, n, e, x)

            result = 1 * np.sum(value[0:n]) / float(n)
            print('  %14.6g' % (result), end='')

        print('')

        n = 2 * n

    print('')
    print('     Exact', end='')

    for j in range(0, 8):

        e[0:m] = e_test[j, 0:m]
        result = wedge01_monomial_integral(e)
        print('  %14.6g' % (result), end='')

    print('')
    print('')
    print('WEDGE01_MONTE_CARLO_TEST')
    print('  Normal end of execution.')

def wedge_monte_carlo_test():

    # *****************************************************************************80
    #
    # WEDGE_MONTE_CARLO_TEST tests the WEDGE_MONTE_CARLO library.
    #
    #  Licensing:
    #
    #    This code is distributed under the GNU LGPL license.
    #
    #  Modified:
    #
    #    13 November 2016
    #
    #  Author:
    #
    #    John Burkardt
    #

    print('')
    print('WEDGE_MONTE_CARLO_TEST')
    print('  Python version: %s' % (platform.python_version()))
    print('  Test the WEDGE_MONTE_CARLO library.')

    wedge01_monomial_integral_test()
    wedge01_monte_carlo_test()

    print('')
    print('WEDGE_MONTE_CARLO_TEST')
    print('  Normal end of execution.')

if (__name__ == '__main__'):
    timestamp()
    wedge_monte_carlo_test()
    timestamp()


tc = int(input())
for _ in range(tc):
    n,m,k = map(int,input().split())
    arr2d = [[int(j) for j in input().strip().split()] for i in range(n)]
    min_cost = 0

    print(arr2d)
    if k>n or k>m:
        print(-1)
    else:
        cost = 0
        for i in range(n):
            print("i is"+str(i))
            if i>=n-1:
                break
            else:
                for k in range(m):
                    print("k is" + str(k))
                    if k>=m-1:
                        break
                    else:
                        cost+=arr2d[i][k]
        if cost<min_cost:
            min_cost=cost
    print(min_cost)


import numpy as np
from easydict import EasyDict

def cost_map2edges(error_map: np.array) -> list:
    edges = list()
    w, h = error_map.shape

    for i in range(w):
        if i == 0:
            edges.append(('-1,-1', '0,0', error_map[0, 0]))
        for j in range(h):
            edges.extend(get_neighbours(i, j, error_map, w, h))
    return edges

def get_neighbours(i: int, j: int, error_map: np.array, w: int, h: int) -> list:
    neighbours = list()
    if i != 0:
        # can add neighbours from top
        edge = (f'{i},{j}', f'{i - 1},{j}', error_map[i - 1, j])
        neighbours.append(edge)
        if j != h - 1:
            # can add neighbours from top right
            edge = (f'{i},{j}', f'{i - 1},{j + 1}', error_map[i - 1, j + 1])
            neighbours.append(edge)
    if i != w - 1:
        # can add neighbours from bot
        edge = (f'{i},{j}', f'{i + 1},{j}', error_map[i + 1, j])
        neighbours.append(edge)
        if j != h - 1:
            # can add neighbours from bot right
            edge = (f'{i},{j}', f'{i + 1},{j + 1}', error_map[i + 1, j + 1])
            neighbours.append(edge)
    if j != h - 1:
        # can add neighbours from right
        edge = (f'{i},{j}', f'{i},{j + 1}', error_map[i, j + 1])
        neighbours.append(edge)
    return neighbours

def get_params(calib_param: str, resize: float) -> EasyDict:
    calib_params = EasyDict()
    lines = calib_param.split('\n')
    for line in lines:
        if 'cam' in line:
            params = line.split('[')[1][:-1].split(' ')
            params = [param.replace(';', '') for param in params]
            params = [float(param) for param in params]
            calib_params.f = params[0]*resize

            calib_params.cx = params[2]*resize
            calib_params.cy = params[5]*resize
        else:
            res = line.split('=')
            if '' in res:
                continue
            param_name, value = res[0], float(res[1])
            if param_name == 'width' or param_name == 'height':
                calib_params[param_name] = int(value*resize)
            else:
                calib_params[param_name] = value * resize
    return calib_params


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 10 16:05:45 2020

@author: jenny
"""

# this scripts build a fully connected neural network using SSVEP power to predict accuracy

import torch
from torchvision import datasets, transforms
from matplotlib import pyplot as plt
from torch.utils.data import Dataset
import numpy as np
from itertools import cycle, islice

class toOneHot(object):
    def __init__(self, num_classes):
        self.num_classes = num_classes

    def __call__(self, integer):
        y_onehot = torch.zeros(self.num_classes)
        y_onehot[integer]=1
        return y_onehot

# Write my own data structure
class MyTrainingDataset(Dataset):
    def __init__(self, root, transform=None, target_transform=None):
        self.root = root
        self.transform = transform
        self.target_transform = target_transform

        self.data = np.expand_dims(np.load(self.root + '/data_n200adapted.npy'), axis=1)
        # self.data2 = np.expand_dims(np.load(self.root + '/n200param.npy'), axis=1)
        # self.data3 = np.expand_dims(np.load(self.root + '/data_n200raw.npy'), axis=1)
        # self.data = np.dstack((self.data1, self.data2))
        self.targets = np.load(self.root + '/target_rt.npy').astype(int)
        # oversampling the low acc data
        # self.data= np.dstack((self.data, self.data3))
        # self.data = self.data*(np.random.normal(0,100,(len(self.data),1,244)))
        # self.ind = np.load(self.root + '/dropout_acc.npy')
        # self.data = np.delete(self.data,self.ind, axis=0)
        #
        # # oversample the inaccurate trials
        # self.incorrect_ind = np.where(self.targets == 0)[0]
        # self.correct_ind = np.where(self.targets == 1)[0]
        # self.testlist = list(islice(cycle(self.incorrect_ind), 6430))
        # self.oversample = self.data[self.testlist,:,:]
        # self.data = np.vstack((self.data, self.oversample))
        # self.targets = np.hstack((self.targets, np.zeros(6430))).astype(int)
        #

        # self.targets = np.hstack((self.targets, np.zeros(6430))).astype(int)

        # self.data = np.expand_dims(np.load(self.root + '/data_real.npy'), axis=1)

        # self.data = self.data*(np.random.normal(0,100,(len(self.data),1,242)))

        # self.targets = np.delete( self.targets,self.ind, axis=0)

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):
        sample = self.data[idx]
        target = self.targets[idx]

        if self.transform:
            sample = self.transform(sample)
        if self.target_transform:
            target = self.target_transform(target)

        return sample, target

class MyTestingDataset(Dataset):
    def __init__(self, root, transform=None, target_transform=None):
        self.root = root
        self.transform = transform
        self.target_transform = target_transform

        self.data = np.expand_dims(np.load(self.root + '/data_n200 adapted .npy'), axis=1)
        # self.data2 = np.expand_dims(np.load(self.root + '/n200param.npy'), axis=1)
        # self.data3 = np.expand_dims(np.load(self.root + '/data_n200raw.npy'), axis=1)
        # self.data = np.dstack((self.data1, self.data2))
        self.targets = np.load(self.root + '/target_rt.npy').astype(int)

        # self.data = np.expand_dims(np.load(self.root + '/data_real.npy'), axis=1)

        # self.data = self.data*(np.random.normal(0,100,(len(self.data),1,242)))

        # self.targets = np.delete( self.targets,self.ind, axis=0)

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):
        sample = self.data[idx]
        target = self.targets[idx]

        if self.transform:
            sample = self.transform(sample)
        if self.target_transform:
            target = self.target_transform(target)

        return sample, target

root = '/home/jenny/pdmattention/ssvep'
# Load the training set
train_set = MyTrainingDataset('/home/jenny/pdmattention/ssvep',
                           transform=transforms.Compose([
                             transforms.ToTensor(),
                             ]),
                           target_transform = None,)
train_loader = torch.utils.data.DataLoader(train_set, batch_size=100, shuffle=True)

# Load the test set
test_set = MyTestingDataset('/home/jenny/pdmattention/ssvep/test',
                             transform=transforms.Compose([
                                 transforms.ToTensor(),
                             ]),
                             target_transform=None, )
test_loader = torch.utils.data.DataLoader(test_set, batch_size=100, shuffle=False)

# Sample the data loader
data, target = next(iter(train_loader))
data.shape
# plt.imshow(data[1][0])
# torch.argmax(target[1])

# build the neural network
# net = torch.nn.Sequential(torch.nn.Linear(121, 242),
#                           torch.nn.ReLU(), #this is an activation function
#                           torch.nn.Linear(242, 242),
#                           torch.nn.ReLU(), #this is an activation function
#                           torch.nn.Linear(242, 2)).cuda()

class net(torch.nn.Module):
    def __init__(self):
        super(net, self).__init__()
        self.fc1 = torch.nn.Linear(242,600)
        self.dropout = torch.nn.Dropout(p = .5)
        self.fc2 = torch.nn.Linear(600,600)
        self.fc3 = torch.nn.Linear(600,3)
    def forward(self, x):
        x = self.fc1(x)
        x = torch.relu(x)
        x = self.dropout(x)
        x = self.fc2(x)
        x = torch.relu(x)
        x = self.dropout(x)
        x = self.fc3(x)
        return x

net = net().cuda()

# calculate the loss function
mse_loss = torch.nn.CrossEntropyLoss().cuda()
opt = torch.optim.Adam(net.parameters(), lr=1e-3)

# define train_step
def train_step(x, t, net, opt_fn, loss_fn):
    y = net(x.cuda())
    loss = loss_fn(y, t.cuda())
    loss.backward()
    opt_fn.step()
    opt_fn.zero_grad()
    return loss

x,t = next(iter(train_loader))
x = x.float()
loss_ = train_step(x.view(-1,242), t, net, opt, mse_loss)

# make prediction
x,t = next(iter(test_loader))
x = x.float()
y = net(x.view(-1,242).cuda())
# model_arch = make_dot(y.mean(), params = dict(net.named_parameters())
# Source(model_arch).render(root)
# make_dot(y, params=dict(list(net.named_parameters()))).render("rnn_torchviz", format="png")
# torch.argmax(y[1])
#
# torch.argmax(t[1])

train_accuracy = []
test_accuracy = []

train_precision = []
test_precision = []

for epoch in range(100):
    net.train()  # training mode
    # for x, t in iter(test_loader):
    #     x=x.float()
        # loss_ = train_step(x.view(-1, 121), t, net, opt, mse_loss)

    acc_batch = []
    prc_batch = []
    for x, t in iter(train_loader):
        x = x.float()
        loss_ = train_step(x.view(-1, 242), t, net, opt, mse_loss)
        y = net(x.view(-1, 242).cuda())
        batch_accuracy = torch.mean((t.cuda() == y.argmax(1).cuda()).float())
        tp = torch.sum(torch.logical_and(t.cuda() == y.argmax(1).cuda(), t.cuda() ==1).float())
        fp = torch.sum(torch.logical_and(y.argmax(1).cuda()==1, t.cuda() ==0).float())
        batch_precision = tp / (tp+fp)
        acc_batch.append(batch_accuracy)
        prc_batch.append(batch_precision)
    train_accuracy.append(torch.mean(torch.FloatTensor(acc_batch)))
    train_precision.append(torch.mean(torch.FloatTensor(prc_batch)))
    print('Loss:',loss_)
    print('Train Acc:', torch.mean(torch.FloatTensor(acc_batch)))
    print('Train Prc:', torch.mean(torch.FloatTensor(prc_batch)))

    acc_batch = []
    prc_batch = []
    net.eval()  # evaluation mode
    for x, t in iter(test_loader):
        x = x.float()
        y = net(x.view(-1, 242).cuda())  # This is necessary because the data has shape [1,28,28], but the input layer is [784]
        batch_accuracy = torch.mean((t.cuda() == y.argmax(1).cuda()).float())
        tp = torch.sum(torch.logical_and(t.cuda() == y.argmax(1).cuda(), t.cuda() ==1).float())
        fp = torch.sum(torch.logical_and(y.argmax(1).cuda()==1, t.cuda() ==0).float())
        batch_precision = tp / (tp + fp)
        acc_batch.append(batch_accuracy)
        prc_batch.append(batch_precision)
    test_accuracy.append(torch.mean(torch.FloatTensor(acc_batch)))
    test_precision.append(torch.mean(torch.FloatTensor(prc_batch)))
    print('Test Accuracy:', torch.mean(torch.FloatTensor(acc_batch)))
    print('Test Prc:', torch.mean(torch.FloatTensor(prc_batch)))

plt.figure()
plt.plot(train_accuracy, ls = '--', label = 'training accuracy')
plt.plot(test_accuracy, ls = '--',label = 'testinging accuracy')
# plt.plot(train_precision, label = 'training precision')
# plt.plot(test_precision, label = 'testing precision')
plt.plot()
plt.legend(loc='best')
plt.title('two-layer FCN using 242 features on RT')

plt.figure()
plt.plot(train_accuracy, label = 'training',color = 'red')
plt.plot(test_accuracy, label = 'testing', color = 'green')
plt.legend(loc='best')
plt.title('Using Random Noise on Accuracy')
#


# coding:utf-8
'''
Created on 2013-11-28

@author: likaiguo.happy@163.com 2013-11-28 11:01:49
'''

import bleach
from django import forms
from .models import (
    Feed,
)

from Common.forms import NormalizeFormStringMixin
from pin_utils.django_utils import (
    get_int
)
from pin_utils.form_mixin import (
    FormErrors,
)

class BaseFeedForm(NormalizeFormStringMixin, forms.ModelForm, FormErrors):

    def clean_salary_min(self):
        salary_min = self.data['salary_min']
        salary_min = get_int(salary_min)
        salary_max = self.data['salary_max']
        salary_max = get_int(salary_max)

        if salary_min == 0 and salary_max == 1000000:
            return salary_min
        if salary_min < 1000 or salary_min > 1000001:
            raise forms.ValidationError(u'最小薪资有误，薪资数在1000~1000000之间')
        return salary_min

    def clean_salary_max(self):
        salary_min = self.data['salary_min']
        salary_min = get_int(salary_min)
        salary_max = self.data['salary_max']
        salary_max = get_int(salary_max)

        if salary_min == 0 and salary_max == 1000000:
            return salary_max
        if salary_max < 1000 or salary_max > 10000001:
            raise forms.ValidationError(u'最大薪资有误，薪资数在1000~1000000之间')
        if salary_min > salary_max:
            raise forms.ValidationError(u'最大薪资小于最小薪资，请重新填写')
        if salary_min * 2 < salary_max:
            raise forms.ValidationError(u'最高薪资不能高于最低薪资的两倍，请重新填写')
        return salary_max

    def clean_job_desc(self):
        job_desc = self.data['job_desc'].strip()
        if not job_desc:
            raise forms.ValidationError(u'职位描述必填')
        if len(job_desc) > 1000:
            raise forms.ValidationError(u'必须在1000字符以内')
        return bleach.clean(job_desc, tags=['br'], strip=True)

class FeedNewForm(BaseFeedForm):
    """
    @summary: 添加新的订阅表单

    """

    class Meta:
        model = Feed
        fields = (
            'job_desc',
            'salary_min',
            'salary_max',
            'skill_required',
            'expect_area',
            'talent_level',
            'job_type',
            'keywords',
            'title',
        )

class NewFeedForm(BaseFeedForm):

    analyze_fields = (
        'language',
        'degree',
        'gender',
        'major',
        'job_type',
    )
    unrequired_fields = (
        'company_prefer',
        'job_domain',
        'job_welfare',
        'job_desc',
    )

    def __init__(self, *args, **kwargs):
        self.post_data = kwargs.pop('post_data')
        super(NewFeedForm, self).__init__(*args, **kwargs)

        if self.instance and not self.instance.title:
            self.fields['title'] = forms.CharField(label='职位名称', max_length=100)

        for i in self.analyze_fields + self.unrequired_fields:
            self.fields[i].required = False

    def clean_job_desc(self):
        job_desc = self.cleaned_data['job_desc']
        return job_desc or u''

    class Meta:
        model = Feed
        fields = (
            'keywords',
            'talent_level',
            'expect_area',
            'title',
            'salary_min',
            'salary_max',
            'job_domain',
            'job_welfare',
            'company_prefer',
            'language',
            'degree',
            'gender',
            'major',
            'job_type',
            'job_desc',
            'analyze_titles',
        )
        error_messages = {
            'keywords': {
                'max_length': u"最多添加15个技能关键词",
            },
            'analyze_titles': {
                'max_length': u"最多添加15个职位拓展名",
            },
            'job_desc': {
                'max_length': u"必须少于1000字",
            },
            'skill_required': {
                'max_length': u"必须少于1000字",
            },
        }

class ChangeFeedForm(NewFeedForm):

    class Meta:
        model = Feed
        fields = (
            'keywords',
            'talent_level',
            'job_desc',
            'salary_min',
            'salary_max',
            'job_domain',
            'job_welfare',
            'company_prefer',
            'language',
            'language',
            'degree',
            'gender',
            'major',
            'job_type',
            'analyze_titles',
        )
        error_messages = {
            'keywords': {
                'max_length': u"最多添加15个技能关键词",
            },
            'analyze_titles': {
                'max_length': u"最多添加15个职位拓展名",
            },
            'job_desc': {
                'max_length': u"必须少于1000字",
            },
            'skill_required': {
                'max_length': u"必须少于1000字",
            },
        }

class FeedStep1Form(BaseFeedForm):

    class Meta:
        model = Feed
        fields = (
            'title',
            'talent_level',
            'job_desc',
            'expect_area',
        )


class Dog:
    def __init__(self, race):
        self.race = race
        self.age = 10
        print('{} criado'.format(race))

    def get_old(self):
        self.age += 1
        return self.age

# herança (inheritance)
class Animal:
    def __init__(self):
        print('Animal criado')

    def quem_sou_eu(self):
        print('Eu sou um animal')

    def comer(self):
        print('Comendo')

class Cachorro(Animal):
    def quem_sou_eu(self):
        print('Eu sou um cachorro')

catiorro = Dog('Labrador')
doguinho = Dog('Huskie')
print(catiorro.age)
print(catiorro.race)
catiorro.get_old()
print(catiorro.age)
print(catiorro.race)
print(doguinho.age)
print(doguinho.race)

animal = Animal()
animal.quem_sou_eu()

dog = Cachorro()
dog.quem_sou_eu()


from __future__ import absolute_import, division, print_function

import os
import sys

from ._base import BaseApp, check_output, test_call

# Note: zenity returns 1 (i.e. False) when the dialig is closed by
# pressing the cross, but since that does not mean anything for
# info/warn/fail, we ignore that.

class LinuxApp(BaseApp):
    """Implementation of dialogs for Linux, by making use of Zenity."""

    def works(self):
        return test_call(["zenity", "--version"])

    def fail(self, title, message):
        self._message("--error", title, message)

    def warn(self, title, message):
        self._message("--warning", title, message)

    def inform(self, title, message):
        self._message("--info", title, message)

    def ask_ok(self, title, message):
        return self._message(
            "--question", title, message, "--ok-label", "OK", "--cancel-label", "Cancel"
        )

    def ask_retry(self, title, message):
        return self._message(
            "--question",
            title,
            message,
            "--ok-label",
            "Retry",
            "--cancel-label",
            "Cancel",
        )

    def ask_yesno(self, title, message):
        return self._message(
            "--question", title, message, "--ok-label", "Yes", "--cancel-label", "No"
        )

    def _message(self, type, title, message, *more):
        env = os.environ.copy()
        env["WINDOWID"] = ""
        message = message.replace('"', u"\u201C").replace("'", u"\u2018")
        if sys.version_info[0] == 2:
            message = message.encode("utf-8")
        res, _ = check_output(
            ["zenity", type, "--title", title, "--text", message] + list(more), env=env
        )
        return not res  # an exit-code of zero means yes/ok


import logging

import pandas as pd
from sklearn import mixture

_logger = logging.getLogger(__name__)

class BayesianGaussianMixtureWrapper(object):
    """
    A class that wraps BayesianGaussianMixture.
    """

    def __init__(self, ):
        pass

    def get_gmm_sample_data(self, incoming_df, column_list, sample_size):
        """
        Unsupervised Learning in the form of BayesianGaussianMixture to create sample data.
        """
        gmm = mixture.BayesianGaussianMixture(n_components=2,
                                              covariance_type="full",
                                              n_init=100,
                                              random_state=42).fit(incoming_df)
        clustered_data = gmm.sample(sample_size)
        clustered_df = pd.DataFrame(clustered_data[0], columns=column_list)
        return clustered_df

    def get_synthetic_training_data(self, incoming_df):
        """
        Creates synthetic training data by sampling from a BayesianGaussianMixture supplied distribution.
        Synthetic data is then labelled differently from the original data.
        """
        # number of records in df
        number_records = len(incoming_df.index)

        # get sample data from the unsupervised BayesianGaussianMixture
        df_bgmm = self.get_gmm_sample_data(incoming_df, list(incoming_df), number_records)

        # set the class on the samples
        df_bgmm['original_data'] = 0

        # add the class to a copy of incoming df, stops weird errors due to changed dataframes
        working_df = incoming_df.copy(deep=True)
        working_df['original_data'] = 1

        # concatinate the two dataframes
        df_combined = working_df.append(df_bgmm, ignore_index=True)

        # shuffle the data
        df_combined = df_combined.sample(frac=1)

        # get the X and y
        x = df_combined.drop(['original_data'], axis=1).values
        y = df_combined['original_data'].values
        y = y.ravel()

        return x, y

    def get_reduced_dataframe(self, incoming_df, feature_indices, sample_with_gmm=False):
        """
        Returns a df with the requested features only.
        """
        requested_features = [list(incoming_df)[i] for i in feature_indices]
        df_reduced = incoming_df[requested_features]
        if sample_with_gmm:
            return self.get_gmm_sample_data(df_reduced,
                                            list(df_reduced),
                                            len(df_reduced.index))
        return df_reduced, requested_features


import cv2
import os
import mediapipe as mp
import pyautogui
import math

#face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
#face_recognizer = cv2.face.LBPHFaceRecognizer_create()
#face_recognizer.read('face_recognition_model.yml')

cap = cv2.VideoCapture(0)
hand_detector= mp.solutions.hands.Hands(max_num_hands = 1,min_detection_confidence=0.5, min_tracking_confidence=0.5)
sw, sh = pyautogui.size()

def face_det(frame,_):
    label_names = ["name"]
    gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray_frame, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
    for (x, y, w, h) in faces:
        roi_gray = gray_frame[y:y + h, x:x + w]
        label, confidence = face_recognizer.predict(roi_gray)
        if confidence < 100:
            ck_face = False
            if label in label_names:
                ck_face = True
    return ck_face

def mov():
    x = int(landmark[8].x*fw)
    y = int(landmark[8].y*fh)
    index_x = sw/fw*x
    index_y = sh/fh*y
    x = int(landmark[8].x*fw)
    y = int(landmark[8].y*fh)
    middle_x = sw/fw*x
    middle_y = sh/fh*y
    pyautogui.moveTo(index_x, index_y)
#    pyautogui.mouseUp(button = "left")
while True:
    _, frame = cap.read()
    frame = cv2.flip(frame, 1)
    #check=face_det(frame,_)
    #if(check):
    fh, fw, _ = frame.shape
    rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    output = hand_detector.process(rgb_frame)
    hands = output.multi_hand_landmarks
    if hands:
        for hand in hands:
            mp.solutions.drawing_utils.draw_landmarks(frame, hand, mp.solutions.hands.HAND_CONNECTIONS)
            landmark = hand.landmark
            dist = (hand.landmark[8].x - hand.landmark[12].x)**2
            dist += (hand.landmark[8].y - hand.landmark[12].y)**2
            dist1 = math.sqrt(dist)
            dist = (hand.landmark[5].x - hand.landmark[9].x)**2
            dist += (hand.landmark[5].y - hand.landmark[9].y)**2
            dist2 = math.sqrt(dist)
            ratio = dist1/dist2
            dist = (hand.landmark[9].x - hand.landmark[12].x)**2
            dist += (hand.landmark[9].y - hand.landmark[12].y)**2
            dist3 = math.sqrt(dist)

            if ratio > 2 and dist3>0.11:
                mov()
            elif ratio<1.4 and dist3>0.11:

                pyautogui.click(button = "left")
                pyautogui.sleep(1)
            elif dist3<0.01 or hand.landmark[9].y<hand.landmark[12].y:
                pyautogui.click(button = "right")
                pyautogui.sleep(1)

    cv2.imshow('Virtual Mouse', frame)
    cv2.waitKey(1)


from . import views
from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('', views.index, name='home'),
    path('bloodTips', views.bloodTips, name='bloodTips'),
    path('reg', views.reg, name='reg'),
    path('login', views.login, name='login'),
    path('logout', views.logout, name='logout'),
    path('about', views.about, name='about'),
    path('donate', views.donate, name='donate'),
]


# https://py.checkio.org/en/mission/non-unique-elements/
# Difficulty : Elementary

def checkio(data:list):
    ans=[]
    for a in data:
        if data.count(a)>1:
            ans.append(a)
    return ans

# Example)
# checkio([1, 2, 3, 1, 3]) == [1, 3, 1, 3]
# checkio([1, 2, 3, 4, 5]) == []
# checkio([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5]
# checkio([10, 9, 10, 10, 9, 8]) == [10, 9, 10, 10, 9]


fname=input('Enter File Name: ')
fhandle=open(fname)
count=0
totalnum=0
for line in fhandle:
    line = line.rstrip()
    num = None
    if line.startswith('X-DSPAM-Confidence'):
        num = float(line[19:40])
        totalnum = num + totalnum
        count = count +  1
print('Average spam confidence:',totalnum/count)


import numpy as np
import matplotlib.pyplot as plt

def logic_get_data():
    D=2
    K=3
    N= K * 1000
    X1=np.random.randn(N//K,D)+np.array([2,2])
    X2=np.random.randn(N//K,D)+np.array([0,-2])
    X3=np.random.randn(N//K,D)+np.array([-2,2])
    X=np.vstack((X1,X2,X3))
    X=np.column_stack((np.array([[1]*N]).T,X))
    y=np.array([0]*(N//K)+[1]*(N//K)+[2]*(N//K))
    Y=np.zeros((N,K))
    for i in range(N):
        Y[i,y[i]]=1
    X_test = X[:N//10]
    Y_test = Y[:N//10]
    Xtrain = X[N//10:]
    ytrain = Y[N//10:]
    y = y[N//10:]
    y_test=y[:N//10]
    X = Xtrain
    Y = ytrain
    Y_test=y_test
    return X,Y,y,X_test,Y_test,y_test


import sys
sys.stdin = open("input.txt", "r")

# N = int(input())
# ans = []
# for i in range(N + 1):
#     ans.append(N - i)
#
# print(*ans)

N = 8
ans = list(range(N+1))[::-1]

print(*ans)

1545_거꾸로 출력해 보아요.py


from contextlib import contextmanager

import pytest

from mixt.contrib.css import render_css
from mixt.contrib.css.loading import CSS_VARS, css_vars, import_css, load_css_keywords

from .test_vars import test_defaults

DEFAULT_CSS_VARS_LEN = 147
LOADED_CSS_VARS_LEN = 4982

def len_css_vars():
    return len([key for key in CSS_VARS if not key.lower().startswith("pytest")])

@contextmanager
def tmp_load_keywords():
    css_vars_copy = CSS_VARS.copy()
    try:
        load_css_keywords()
        yield
    finally:
        load_css_keywords.main_is_done = False
        CSS_VARS.clear()
        CSS_VARS.update(css_vars_copy)

def test_default_css_vars():
    assert len_css_vars() == DEFAULT_CSS_VARS_LEN
    test_defaults()

def test_load_css_keywords():
    with tmp_load_keywords():
        assert len_css_vars() == LOADED_CSS_VARS_LEN
    assert len_css_vars() == DEFAULT_CSS_VARS_LEN

def test_default_still_works_after_loading():
    with tmp_load_keywords():
        test_defaults()

# noinspection PyUnresolvedReferences
def test_import_css():

    #  globals are clean
    with pytest.raises(NameError):
        3 * px

    with import_css(globals()):
        assert b.str(px(3)) == "3px"  # b.str for builtins

    # globals are clearer
    with pytest.raises(NameError):
        3 * px

# noinspection PyUnresolvedReferences
def test_css_vars_decorator():
    with tmp_load_keywords():
        # globals are clean
        with pytest.raises(NameError):
            margin-bottom

        # noinspection PyUnresolvedReferences
        @css_vars(globals())
        def css():
            return {body: {margin-bottom: 3 * px, foo: none}}

        assert (
            render_css(css())
            == """\
body {
  margin-bottom: 3px;
  foo: none;
}
"""
        )
        # foo and Foo where added to CSS_VARS
        assert len_css_vars() == LOADED_CSS_VARS_LEN + 2

        # globals are cleared
        with pytest.raises(NameError):
            margin-bottom


from types import SimpleNamespace
import pandas as pd
from rate_code.load_data import scope_paths

target_app_columns 	= ['campaign', 'payment_country', 'region', 'tenure', 'metric', 'result']
finance_columns 	= ['finance_measure','formula','result']

target_campaign = 2018

def set_scope():
	scope = SimpleNamespace(

								nrows 				= None,

								campaign_previous	= target_campaign - 1,
								campaign_retained	= target_campaign - 2,
								# campaign_previous	= 2018,
								# campaign_retained	= 2017,

								show_regions		= False,
								save_rates			= True,
								show_community		= False,

								target_app_rates_df = pd.DataFrame( columns=target_app_columns),
								finance_rates_df 	= pd.DataFrame( columns=finance_columns),
								)

	scope_paths(scope)

	return scope


def base64_encode(text: str, hex: bool = False) -> str:
    BASE_64_ALPHABET = (
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
    )

    # convert entire thing to binary
    binary = (
        "{:08b}".format(int(bytes.fromhex(text).hex(), 16))
        if hex
        else "".join(format(ord(i), "08b") for i in text)
    )

    # split into 6 bit chunks
    chunks = [[j for j in binary[i : i + 6]] for i in range(0, len(binary), 6)]

    # convert all binary numbers to base10 for array index
    chunks = [
        int("".join(i), base=2)
        if len(i) == 6
        else int("".join(i) + ("0" * (6 - len(i))), base=2)
        for i in chunks
    ]

    # encoded result without any padding yet
    pre_padding = "".join(BASE_64_ALPHABET[i] for i in chunks)

    # add final padding to make the length a multiple of 4
    padding = abs(len(pre_padding) - (4 * round(len(pre_padding) / 4))) * "="

    return pre_padding + padding

def test():
    """
    Generate random strings and pass them through my encoder
    if the encoded result matches the result produced by the
        official built in library the text is successful!
    """
    import base64
    import random
    import string

    for _ in range(100):
        testing_string = "".join(
            [
                random.choice(string.ascii_letters + string.punctuation + string.digits)
                for _ in range(random.randint(0, 100))
            ]
        )
        assert base64.b64encode(testing_string.encode()).decode() == base64_encode(
            testing_string
        )

test()
print(base64_encode("deadbeef", hex=True))  # -> 3q2+7w==


class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        # 3가지 연산을 다 해보는 방법밖에 없을 것 같은데?
        # 우선 dfs로
        # def dfs(i, j, cache):
        #     if i == len(word1) and j == len(word2):
        #         return 0
        #     if i == len(word1):
        #         return len(word2) - j
        #     if j == len(word2):
        #         return len(word1) - i

        #     if (i, j) in cache:
        #         return cache[(i, j)]

        #     if word1[i] == word2[j]:
        #         return dfs(i + 1, j + 1, cache)

        #     insert = 1 + dfs(i, j + 1, cache)
        #     delete = 1 + dfs(i + 1, j, cache)
        #     replace = 1 + dfs(i + 1, j + 1, cache)

        #     cache[(i, j)] = min(insert, delete, replace)
        #     return cache[(i, j)]

        # return dfs(0, 0, {})

        # bottom-up으로
        M, N = len(word1), len(word2)
        dp = [[0] * (N + 1) for _ in range(M + 1)]

        for i in range(M + 1):
            dp[i][0] = i
        for j in range(N + 1):
            dp[0][j] = j

        for i in range(1, M + 1):
            for j in range(1, N + 1):
                if word1[i - 1] == word2[j - 1]:
                    dp[i][j] = dp[i - 1][j - 1]
                else:
                    dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1])

        return dp[M][N]


#Takip edilenler ve takipçiler dosyası her zaman instagramdaki son verilere göre yazılmalıdır.İşlem bittikten sonra random dosyası silinmelidir.

with open('Takip.txt', 'r') as file1:
    with open('Takipci.txt', 'r') as file2:
        notsame = set(file1).difference(file2)

notsame.discard('\n')

with open('random.txt', 'w') as file_out:

    for (line) in notsame:
        file_out.write(line)


import os
import csv
import math
from collections import defaultdict

from joblib import Parallel, delayed

from .datum import Datum
from .dataset import Dataset
from .image import PathImage
from .annotation import ClassificationAnnotation
from .annotation import DetectionAnnotation
from .annotation import BoundingBox, is_valid_coordinates
from .class_map import CSVClassMapIO

import logging
logger = logging.getLogger(__name__)

def create_datum_helper(image_path, bbox_data):
    """Helper to create Datum

    Assumes that if any bounding box coordinates specified is negative
    in the Open Images format (usually -1), then the entry is a
    classification label rather than a detection label.

    Parameters
    ----------
    image_path : str
        full path to image
    bbox_data : list
        list of tuples where each tuple is (xmin, ymin, xmax, ymax, class_id)
        should have at least one element

    Returns
    -------
    Datum
    """
    image = PathImage(image_path)
    if any(coord < 0 for coord in bbox_data[0][:4]):
        annotation = ClassificationAnnotation(bbox_data[0][4])
    else:
        annotation = DetectionAnnotation([BoundingBox(*bbox_tuple) for bbox_tuple in bbox_data])
    return Datum(image, [annotation])

def create_data_job_helper(image_ids_list, image_paths,
        annotations, job_index, num_loading_workers):
    """Helper to create data (image ID -> Datum)

    Parameters
    ----------
    image_ids_list : list
        list of image IDs
    image_paths : dict
        image_id -> full path to image
    annotations : dict
        image_id -> list of tuples where each tuple is (xmin, ymin, xmax, ymax, class_id)
    job_index : int
        job index, should be 0 <= job_index < num_loading_workers
    num_loading_workers : int
        number of parallel loading workers

    Returns
    -------
    dict : image ID -> Datum
    """
    chunk_len = int(math.ceil(len(image_ids_list) / num_loading_workers))
    subset_image_ids_list = image_ids_list[chunk_len*job_index:chunk_len*(job_index+1)]
    data = {image_id : create_datum_helper(image_paths[image_id], annotations[image_id]) for image_id in subset_image_ids_list}
    return data

def create_data_parallel_job_helper(image_paths, annotations, num_loading_workers):
    """Helper to create data (image ID -> Datum) in parallel

    Parameters
    ----------
    image_paths : dict
        image_id -> full path to image
    annotations : dict
        image_id -> list of tuples where each tuple is (xmin, ymin, xmax, ymax, class_id)
    num_loading_workers : int
        number of parallel loading workers

    Returns
    -------
    dict : image ID -> Datum
    """
    image_ids_list = list(annotations.keys())
    results = Parallel(n_jobs=num_loading_workers)(delayed(create_data_job_helper)(image_ids_list, image_paths, annotations, job_index, num_loading_workers) for job_index in range(num_loading_workers))
    data = {}
    for d in results:
        data.update(d)
    return data

def annotation_file_contains_label_names(annotation_file):
    """Checks if the annotation file contains label names or class ID

    Parameters
    ----------
    annotation_file : str
        path to annotation file

    Returns
    -------
    True if file contains label names (not class IDs)
    """
    with open(annotation_file, 'r') as f:
        reader = csv.reader(f, delimiter=OpenImagesDataset.DELIMITER)
        for idx, row in enumerate(reader):
            # get header names and skip
            if idx == 0:
                column_keys = row
                continue

            # get data from each column
            image_entry_data = {}
            for col_idx, entry in enumerate(row):
                image_entry_data[column_keys[col_idx]] = entry

            # test value
            label_name_data = image_entry_data[OpenImagesDataset.LABEL_NAME]
            try:
                int(label_name_data)
            except ValueError:
                return True

    return False

class OpenImagesDataset(Dataset):
    """OpenImagesDataset loads a dataset in Open Images format

    Loading this dataset requires 1) an annotation file specified in the
    Open Images format and 2) a csv file that maps class names to class IDs.
    The annotations file follows the Open Images format. A few notes:
    1) The image IDs are image file names relative to some root
    (which can be specified in initialization), and 2) the labels are
    class IDs (if class names, specify read_as_label_names=True).
    The csv file contains two columns: the first column is the class ID
    and the second column is the class name.

    Parameters
    ----------
    annotation_file : str
        path to annotation csv file
    class_map_file : str
        path to class map csv file
    images_root : str
        path to root for images
    metadata : dict (default {})
        arbitrary dataset metadata, just used for book keeping if needed
    read_as_label_names : bool or None (default None)
        if True, force reading LabelName column as a label name
        if False, force reading LabelName column as a class ID
        if None, automatically determine whether label name or class ID
    skip_invalid_bboxes : bool (default True)
        if True, skip invalid bboxes, otherwise throw error
    num_loading_workers : int (default 8)
        number of workers for loading data from csv for potential speedups
    """
    DELIMITER = ','
    IMAGE_ID = 'ImageID'
    LABEL_NAME = 'LabelName'
    XMIN = 'XMin'
    XMAX = 'XMax'
    YMIN = 'YMin'
    YMAX = 'YMax'

    def __init__(self, annotation_file, class_map_file, images_root=None,
            metadata={}, read_as_label_names=None, skip_invalid_bboxes=True,
            num_loading_workers=16, offset=0):
        assert isinstance(annotation_file, str), type(annotation_file)
        assert os.path.exists(annotation_file), annotation_file
        assert isinstance(class_map_file, str), type(class_map_file)
        assert os.path.exists(class_map_file), class_map_file
        if images_root is not None:
            assert isinstance(images_root, str), type(images_root)
            assert os.path.exists(images_root), images_root
        assert isinstance(metadata, dict), type(metadata)
        assert isinstance(num_loading_workers, int), type(num_loading_workers)
        assert num_loading_workers >= 1, num_loading_workers

        if read_as_label_names is None:
            read_as_label_names = annotation_file_contains_label_names(annotation_file)

        # read in class map file
        class_map = CSVClassMapIO.read(class_map_file)
        self.offset = offset

        # parse annotations data
        annotations = defaultdict(list) # image_id -> [(xmin, ymin, xmax, ymax, class_id)]
        image_paths = {} # image_id -> path
        with open(annotation_file, 'r') as f:
            reader = csv.reader(f, delimiter=OpenImagesDataset.DELIMITER)
            for idx, row in enumerate(reader):
                # get header names and skip
                if idx == 0:
                    column_keys = row
                    continue

                # get data from each column
                image_entry_data = {}
                for col_idx, entry in enumerate(row):
                    image_entry_data[column_keys[col_idx]] = entry

                image_id = image_entry_data[OpenImagesDataset.IMAGE_ID]
                class_name = image_entry_data[OpenImagesDataset.LABEL_NAME]
                xmin = float(image_entry_data[OpenImagesDataset.XMIN])
                ymin = float(image_entry_data[OpenImagesDataset.YMIN])
                xmax = float(image_entry_data[OpenImagesDataset.XMAX])
                ymax = float(image_entry_data[OpenImagesDataset.YMAX])

                if not ( all(coord >= 0 for coord in [xmin, ymin, xmax, ymax]) and is_valid_coordinates(xmin, ymin, xmax, ymax) ):
                    message = 'invalid coordinates: {}: {}'.format(image_id, (xmin, ymin, xmax, ymax))
                    if skip_invalid_bboxes:
                        logger.warn('skipping ' + message)
                        continue
                    else:
                        raise ValueError(message)

                class_id = class_map.get_index(class_name) if read_as_label_names else int(class_name)
                annotations[image_id].append((xmin, ymin, xmax, ymax, class_id))
                image_paths[image_id] = image_id

        # put data into desired format
        data = create_data_parallel_job_helper(image_paths, annotations, num_loading_workers)
        super(OpenImagesDataset, self).__init__(data, metadata=metadata)


from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import configparser
import logging
from telegram import ChatAction,ParseMode
from telegram.ext.dispatcher import run_async
from random import choice
import os

BOTNAME = 'ILUGDbot'

@run_async
def send_async(bot, *args, **kwargs):
    bot.sendMessage(*args, **kwargs)

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.DEBUG)

config = configparser.ConfigParser()
config.read('bot.ini')

updater = Updater(os.environ['token']) # we should use env variable !!
dispatcher = updater.dispatcher

def start(bot, update):
    bot.sendChatAction(chat_id=update.message.chat_id, action=ChatAction.TYPING)
    bot.sendMessage(chat_id=update.message.chat_id, text= '''
Hey!! I'm currently Working with Ilug-Delhi To hire me contact my admin
Use /help to get help''')

def website(bot, update):
    bot.sendChatAction(chat_id=update.message.chat_id,
                       action=ChatAction.TYPING)
    bot.sendMessage(chat_id=update.message.chat_id, text=config['BOT']['website'])

def facebok(bot, update):
    bot.sendChatAction(chat_id=update.message.chat_id,
                       action=ChatAction.TYPING)
    bot.sendMessage(chat_id=update.message.chat_id, text=config['BOT']['facebook'])

def invitelink(bot, update):
    bot.sendChatAction(chat_id=update.message.chat_id,
                       action=ChatAction.TYPING)
    bot.sendMessage(chat_id=update.message.chat_id, text=config['BOT']['invite_link'])

def mailinglist(bot,update):
    bot.sendChatAction(chat_id=update.message.chat_id,
                       action=ChatAction.TYPING)
    bot.sendMessage(chat_id=update.message.chat_id, text=config['BOT']['mailinglist'])

def twitter(bot,update):
    bot.sendChatAction(chat_id=update.message.chat_id,
                       action=ChatAction.TYPING)
    bot.sendMessage(chat_id=update.message.chat_id, text=config['BOT']['twitter'])

def meetuplink(bot,update):
    bot.sendChatAction(chat_id=update.message.chat_id,
                       action=ChatAction.TYPING)
    bot.sendMessage(chat_id=update.message.chat_id, text=config['BOT']['meetuplink'])

def github(bot,update):
    bot.sendChatAction(chat_id=update.message.chat_id,
                       action=ChatAction.TYPING)
    bot.sendMessage(chat_id=update.message.chat_id, text=config['BOT']['github'])

def coc(bot,update):
    bot.sendChatAction(chat_id=update.message.chat_id,
                       action=ChatAction.TYPING)
    bot.sendMessage(chat_id=update.message.chat_id, text=config['BOT']['coc'])

def help(bot, update):
     bot.sendChatAction(chat_id=update.message.chat_id, action=ChatAction.TYPING)
     bot.sendMessage(chat_id=update.message.chat_id, text='''Use one of the following commands
/invitelink - to get Ilug-D Telegram group invite link
/facebook - to get a link to Ilug-D  Facebook page
/website - to get Ilug-D website link
/mailinglist - link for our mailing list
/twitter - twitter link for ILUGD
/meetuplink - to get meetup link for ILUGD
/github - link to ilugd github repos
''')

# Welcome a user to the chat
def welcome(bot, update):
    message = update.message
    chat_id = message.chat.id
    phrases = ['Hello {}! Welcome to {} .Please introduce yourself. Dont forget to read the chat rules using !rules command'.format(message.new_chat_member.first_name,message.chat.title),
               'Hi {}! Welcome to {} .let\'s start with introduction. Dont forget to read the chat rules using !rules command'.format(message.new_chat_member.first_name,message.chat.title)
               #'Hello {}! Welcome to {} .Please introduce yourself.'.format(message.new_chat_member.first_name,message.chat.title),
               #'Hello {}! Welcome to {} .Please introduce yourself.'.format(message.new_chat_member.first_name,message.chat.title),
               #'Hello {}! Welcome to {} .Please introduce yourself.'.format(message.new_chat_member.first_name,message.chat.title)
                ]
    text = choice(phrases)
    send_async(bot, chat_id=chat_id, text=text, parse_mode=ParseMode.HTML)

def goodbye(bot, update):
    message = update.message
    chat_id = message.chat.id
    text = 'Goodbye, $username!'
    text = text.replace('$username',message.left_chat_member.first_name).replace('$title', message.chat.title)
    send_async(bot, chat_id=chat_id, text=text, parse_mode=ParseMode.HTML)

def intro(bot, update):
    message = update.message
    chat_id = message.chat.id
    text = 'Hi everyone,I am a python bot working to serve Ilug-D.'
    send_async(bot, chat_id=chat_id, text=text, parse_mode=ParseMode.HTML)

def empty_message(bot, update):

    if update.message.new_chat_member is not None:
        # Bot was added to a group chat
        if update.message.new_chat_member.username == BOTNAME:
            return intro(bot, update)
        # Another user joined the chat
        else:
            return welcome(bot, update)

    # Someone left the chat
    elif update.message.left_chat_member is not None:
        if update.message.left_chat_member.username != BOTNAME:
            return goodbye(bot, update)

dispatcher.add_handler(CommandHandler('website', website))
dispatcher.add_handler(CommandHandler('facebook', facebok))
dispatcher.add_handler(CommandHandler('help', help))
dispatcher.add_handler(MessageHandler([Filters.status_update], empty_message))
dispatcher.add_handler(CommandHandler('invitelink',invitelink))
dispatcher.add_handler(CommandHandler('mailinglist',mailinglist))
dispatcher.add_handler(CommandHandler('twitter',twitter))
dispatcher.add_handler(CommandHandler('meetuplink',meetuplink))
dispatcher.add_handler(CommandHandler('start', start))
dispatcher.add_handler(CommandHandler('github',github))

updater.start_polling()
updater.idle()


"""IceCube-specific `Detector` class(es)."""

import torch
from torch_geometric.data import Data

from graphnet.models.components.pool import (
    group_pulses_to_dom,
    group_pulses_to_pmt,
    sum_pool_and_distribute,
)
from graphnet.data.constants import FEATURES
from graphnet.models.detector.detector import Detector

class IceCube86(Detector):
    """`Detector` class for IceCube-86."""

    # Implementing abstract class attribute
    features = FEATURES.ICECUBE86

    def _forward(self, data: Data) -> Data:
        """Ingest data, build graph, and preprocess features.

        Args:
            data: Input graph data.

        Returns:
            Connected and preprocessed graph data.
        """
        # Check(s)
        self._validate_features(data)

        # Preprocessing
        data.x[:, 0] /= 500.0  # dom_x
        data.x[:, 1] /= 500.0  # dom_y
        data.x[:, 2] /= 500.0  # dom_z
        data.x[:, 3] = (data.x[:, 3] - 1.0e04) / 3.0e4  # dom_time
        data.x[:, 4] = torch.log10(data.x[:, 4]) / 3.0  # charge
        data.x[:, 5] -= 1.25  # rde
        data.x[:, 5] /= 0.25
        data.x[:, 6] /= 0.05  # pmt_area

        return data

class IceCubeKaggle(Detector):
    """`Detector` class for Kaggle Competition."""

    # Implementing abstract class attribute
    features = FEATURES.KAGGLE
    xy_anisotropy_k = [
        -1.2334245570477371,
        -6.279196009389672,
        2.6169062228573026,
        0.8034497666860473,
        0.17294482605805447,
        -0.38345223229188563,
    ]

    def _forward(self, data: Data) -> Data:
        """Ingest data, build graph, and preprocess features.

        Args:
            data: Input graph data.

        Returns:
            Connected and preprocessed graph data.
        """
        # Check(s)
        self._validate_features(data)

        # Node features
        # Preprocessing
        data.x[:, 0] /= 500.0  # x
        data.x[:, 1] /= 500.0  # y
        data.x[:, 2] /= 500.0  # z
        data.x[:, 3] = (data.x[:, 3] - 1.0e04) / 3.0e4  # time
        data.x[:, 4] = torch.log10(data.x[:, 4]) / 3.0  # charge
        # data.x[:, 5] is bool auxilaty, no need to normalize
        data.x[:, 6] /= 2.0  # sensor group
        data.x[:, 7] /= 1.35  # sensor relative qe

        # Edge attributes
        data.edge_attr = self.rebuild_edge_attr(data.x, data.edge_index)

        return data

    def rebuild_edge_attr(self, x, edge_index):
        # Get edge XYZ vector
        edge_x = x[edge_index[0], 0] - x[edge_index[1], 0]
        edge_y = x[edge_index[0], 1] - x[edge_index[1], 1]
        edge_z = x[edge_index[0], 2] - x[edge_index[1], 2]

        # Angle between projection on XY and symmetry plane
        angles_to_symmetry_xy_plane = []
        for k in self.xy_anisotropy_k:
            k = torch.tensor(k)  # x = k * y, z plane
            dot = (edge_x * 1.0 + edge_y * k)
            angle_to_symmetry_xy_plane = torch.arccos(
                torch.clamp(dot / torch.sqrt(1 + k ** 2) / torch.sqrt(edge_x ** 2 + edge_y ** 2), -1.0, 1.0)
            )
            angle_to_symmetry_xy_plane = torch.where(
                torch.isnan(angle_to_symmetry_xy_plane),
                torch.full_like(angle_to_symmetry_xy_plane, torch.pi / 2),
                angle_to_symmetry_xy_plane
            )
            angle_to_symmetry_xy_plane = angle_to_symmetry_xy_plane / torch.pi
            angles_to_symmetry_xy_plane.append(angle_to_symmetry_xy_plane)

        # Angle to (0, 0, 1) vector: same string + up or down
        dot = (edge_x * 0.0 + edge_y * 0.0 + edge_z * 1.0)
        angle_to_z_axis = torch.arccos(
            torch.clamp(dot / torch.sqrt(edge_x ** 2 + edge_y ** 2 + edge_z ** 2), -1.0, 1.0)
        )
        angle_to_z_axis = torch.where(
            torch.isnan(angle_to_z_axis),
            torch.zeros_like(angle_to_z_axis),
            angle_to_z_axis
        )
        angle_to_z_axis = angle_to_z_axis / torch.pi

        # Sensor group diff
        sensor_group_diff = torch.abs(x[edge_index[0], 6] - x[edge_index[1], 6])

        # Eucledian distance between sensor positions
        edge_distance = torch.sqrt(edge_x ** 2 + edge_y ** 2 + edge_z ** 2)

        # Same sensor
        same_sensor = \
            torch.isclose(edge_distance, torch.tensor(0.0), atol=1e-5)

        # Time difference
        time_diff = x[edge_index[0], 3] - x[edge_index[1], 3]

        # Activation speed, to m / ns then normed by speed of light
        # https://www.kaggle.com/competitions/icecube-neutrinos-in-deep-ice/
        # discussion/382131
        activation_speed = edge_distance * 500.0 / torch.abs(time_diff * 3.0e4) / 0.3
        activation_speed = torch.where(
            torch.isnan(activation_speed) | torch.isinf(activation_speed),
            torch.full_like(activation_speed, 0.0),
            activation_speed
        )

        edge_attr = torch.stack(
            [
                *angles_to_symmetry_xy_plane,
                angle_to_z_axis,
                sensor_group_diff,
                edge_distance,
                same_sensor.float(),
                time_diff,
                activation_speed,
            ]
        ).T

        return edge_attr

    @property
    def nb_edge_attrs(self) -> int:
        """Return number of edge_attrs features.

        This the default, but may be overridden by specific inheriting classes.
        """
        return 12

class IceCubeDeepCore(IceCube86):
    """`Detector` class for IceCube-DeepCore."""

    # Implementing abstract class attribute
    features = FEATURES.DEEPCORE

    def _forward(self, data: Data) -> Data:
        """Ingest data, build graph, and preprocess features.

        Args:
            data: Input graph data.

        Returns:
            Connected and preprocessed graph data.
        """
        # Check(s)
        self._validate_features(data)

        # Preprocessing
        data.x[:, 0] /= 100.0  # dom_x
        data.x[:, 1] /= 100.0  # dom_y
        data.x[:, 2] += 350.0  # dom_z
        data.x[:, 2] /= 100.0
        data.x[:, 3] /= 1.05e04  # dom_time
        data.x[:, 3] -= 1.0
        data.x[:, 3] *= 20.0
        data.x[:, 4] /= 1.0  # charge
        data.x[:, 5] -= 1.25  # rde
        data.x[:, 5] /= 0.25
        data.x[:, 6] /= 0.05  # pmt_area

        return data

class IceCubeUpgrade(IceCubeDeepCore):
    """`Detector` class for IceCube-Upgrade."""

    # Implementing abstract class attribute
    features = FEATURES.UPGRADE

    def _forward(self, data: Data) -> Data:
        """Ingest data, build graph, and preprocess features.

        Args:
            data: Input graph data.

        Returns:
            Connected and preprocessed graph data.
        """
        # Check(s)
        self._validate_features(data)

        # Preprocessing
        data.x[:, 0] /= 500.0  # dom_x
        data.x[:, 1] /= 500.0  # dom_y
        data.x[:, 2] /= 500.0  # dom_z
        data.x[:, 3] /= 2e04  # dom_time
        data.x[:, 3] -= 1.0
        data.x[:, 4] = torch.log10(data.x[:, 4]) / 2.0  # charge
        # data.x[:,5] /= 1.  # rde
        data.x[:, 6] /= 0.05  # pmt_area
        data.x[:, 7] -= 50.0  # string
        data.x[:, 7] /= 50.0
        data.x[:, 8] /= 20.0  # pmt_number
        data.x[:, 9] -= 60.0  # dom_number
        data.x[:, 9] /= 60.0
        # data.x[:,10] /= 1.  # pmt_dir_x
        # data.x[:,11] /= 1.  # pmt_dir_y
        # data.x[:,12] /= 1.  # pmt_dir_z
        data.x[:, 13] /= 130.0  # dom_type

        return data

class IceCubeUpgrade_V2(IceCubeDeepCore):
    """`Detector` class for IceCube-Upgrade."""

    # Implementing abstract class attribute
    features = FEATURES.UPGRADE

    @property
    def nb_outputs(self) -> int:
        """Return number of output features."""
        return self.nb_inputs + 3

    def _forward(self, data: Data) -> Data:
        """Ingest data, build graph, and preprocess features.

        Args:
            data: Input graph data.

        Returns:
            Connected and preprocessed graph data.
        """
        # Check(s)
        self._validate_features(data)

        # Assign pulse cluster indices to DOMs and PMTs, respectively
        data = group_pulses_to_dom(data)
        data = group_pulses_to_pmt(data)

        # Feature engineering inspired by Linea Hedemark and Tetiana Kozynets.
        xyz = torch.stack((data["dom_x"], data["dom_y"], data["dom_z"]), dim=1)
        pmt_dir = torch.stack(
            (data["pmt_dir_x"], data["pmt_dir_x"], data["pmt_dir_x"]), dim=1
        )
        charge = data["charge"].unsqueeze(dim=1)
        center_of_gravity = sum_pool_and_distribute(
            xyz * charge, data.batch
        ) / sum_pool_and_distribute(charge, data.batch)
        vector_to_center_of_gravity = center_of_gravity - xyz
        distance_to_center_of_gravity = torch.norm(
            vector_to_center_of_gravity, p=2, dim=1
        )
        unit_vector_to_center_of_gravity = vector_to_center_of_gravity / (
            distance_to_center_of_gravity.unsqueeze(dim=1) + 1e-3
        )
        cos_angle_wrt_center_of_gravity = (
            pmt_dir * unit_vector_to_center_of_gravity
        ).sum(dim=1)
        photoelectrons_on_pmt = (
            sum_pool_and_distribute(data["charge"], data.pmt_index, data.batch)
            .floor()
            .clip(1, None)
        )

        # Add new features
        data.x = torch.cat(
            (
                data.x,
                photoelectrons_on_pmt.unsqueeze(dim=1),
                distance_to_center_of_gravity.unsqueeze(dim=1),
                cos_angle_wrt_center_of_gravity.unsqueeze(dim=1),
            ),
            dim=1,
        )

        # Preprocessing
        data.x[:, 0] /= 500.0  # dom_x
        data.x[:, 1] /= 500.0  # dom_y
        data.x[:, 2] /= 500.0  # dom_z
        data.x[:, 3] /= 2e04  # dom_time
        data.x[:, 3] -= 1.0
        data.x[:, 4] = torch.log10(data.x[:, 4]) / 2.0  # charge
        # data.x[:,5] /= 1.  # rde
        data.x[:, 6] /= 0.05  # pmt_area
        data.x[:, 7] -= 50.0  # string
        data.x[:, 7] /= 50.0
        data.x[:, 8] /= 20.0  # pmt_number
        data.x[:, 9] -= 60.0  # dom_number
        data.x[:, 9] /= 60.0
        # data.x[:,10] /= 1.  # pmt_dir_x
        # data.x[:,11] /= 1.  # pmt_dir_y
        # data.x[:,12] /= 1.  # pmt_dir_z
        data.x[:, 13] /= 130.0  # dom_type

        # -- Engineered features
        data.x[:, 14] = (
            torch.log10(data.x[:, 14]) / 2.0
        )  # photoelectrons_on_pmt
        data.x[:, 15] = (
            torch.log10(1e-03 + data.x[:, 15]) / 2.0
        )  # distance_to_center_of_gravity

        return data


import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt

def analise_carteira(lista_carteira):

    start_date = input("Informe a data de início da consulta (YYYY-MM-DD): ")
    end_date = input("Informa a data final da consulta (YYYY-MM-DD): ")

    df = pd.DataFrame()

    for i in lista_carteira:
        cotacao = yf.download(i, start=start_date, end=end_date)
        df[i] = cotacao['Adj Close']

    df.plot(figsize=(15, 10))

    plt.xlabel('Anos')
    plt.ylabel('Valor Ticket')
    plt.title('Variação de valor das ações')
    plt.legend()
    plt.show()