import pytest
from sqlalchemy import Sequence

from pcapi.local_providers.chunk_manager import save_chunks
from pcapi.model_creators.generic_creators import create_offerer
from pcapi.model_creators.generic_creators import create_stock
from pcapi.model_creators.generic_creators import create_venue
from pcapi.model_creators.specific_creators import create_offer_with_thing_product
from pcapi.model_creators.specific_creators import create_product_with_thing_subcategory
from pcapi.models import Offer
from pcapi.models import Stock
from pcapi.models.db import db
from pcapi.repository import repository

class SaveChunksTest:
    @pytest.mark.usefixtures("db_session")
    def test_save_chunks_insert_1_offer_in_chunk(self, app):
        # Given
        offerer = create_offerer()
        venue = create_venue(offerer)
        product = create_product_with_thing_subcategory()
        repository.save(venue, product)

        offer = create_offer_with_thing_product(venue, product=product, id_at_providers="1%12345678912345")
        offer.venueId = venue.id
        chunk_to_insert = {"1|Offer": offer}
        db.session.expunge(offer)

        chunk_to_update = {}

        # When
        save_chunks(chunk_to_insert, chunk_to_update)

        # Then
        assert Offer.query.count() == 1

    @pytest.mark.usefixtures("db_session")
    def test_save_chunks_insert_1_offer_and_1_stock_in_chunk(self, app):
        # Given
        offerer = create_offerer()
        venue = create_venue(offerer)
        product = create_product_with_thing_subcategory()
        repository.save(venue, product)

        offer = create_offer_with_thing_product(venue, product=product, id_at_providers="1%12345678912345")
        offer.venueId = venue.id
        offer_id = db.session.execute(Sequence("offer_id_seq"))
        offer.id = offer_id

        stock = create_stock(offer=offer)
        stock.offerId = offer_id

        chunk_to_insert = {
            "1|Offer": offer,
            "1|Stock": stock,
        }
        db.session.expunge(offer)
        db.session.expunge(stock)

        chunk_to_update = {}

        # When
        save_chunks(chunk_to_insert, chunk_to_update)

        # Then
        assert Offer.query.count() == 1
        assert Stock.query.count() == 1

    @pytest.mark.usefixtures("db_session")
    def test_save_chunks_update_1_offer_in_chunk(self, app):
        # Given
        offerer = create_offerer()
        venue = create_venue(offerer)
        product = create_product_with_thing_subcategory()
        offer = create_offer_with_thing_product(venue, product=product, id_at_providers="1%12345678912345")
        repository.save(venue, product, offer)

        db.session.refresh(offer)
        offer.isDuo = True
        chunk_to_update = {
            "1|Offer": offer,
        }
        db.session.expunge(offer)

        chunk_to_insert = {}

        # When
        save_chunks(chunk_to_insert, chunk_to_update)

        # Then
        assert Offer.query.count() == 1

    @pytest.mark.usefixtures("db_session")
    def test_save_chunks_update_2_offers_and_1_stock_in_chunk(self, app):
        # Given
        offerer = create_offerer()
        venue = create_venue(offerer)
        product = create_product_with_thing_subcategory()
        offer1 = create_offer_with_thing_product(venue, product=product, id_at_providers="1%12345678912345")
        offer2 = create_offer_with_thing_product(venue, product=product, id_at_providers="2%12345678912345")
        stock = create_stock(offer=offer1)
        repository.save(venue, product, offer1, offer2, stock)

        db.session.refresh(offer1)
        db.session.refresh(offer2)
        db.session.refresh(stock)
        offer1.isDuo = True
        offer2.isDuo = True
        stock.quantity = 2
        chunk_to_update = {
            "1|Offer": offer1,
            "1|Stock": stock,
            "2|Offer": offer2,
        }
        db.session.expunge(offer1)
        db.session.expunge(offer2)
        db.session.expunge(stock)

        chunk_to_insert = {}

        # When
        save_chunks(chunk_to_insert, chunk_to_update)

        # Then
        offers = Offer.query.all()
        assert len(offers) == 2
        assert any(offer.isDuo for offer in offers)
        assert Stock.query.count() == 1


from django.urls import path, include
from rest_framework import routers

from . import views

router = routers.DefaultRouter()
router.register(r'clients', views.ClientAPIView, basename='clients')
router.register(r'mailings', views.MailingAPIView, basename='mailings')

urlpatterns = [
    path('', include(router.urls)),
    path('mailing-report/', views.MailingReportAPIView.as_view()),
    path('mailing-report/<int:mailing_id>/', views.MailingReportAPIView.as_view()),
    path('docs/', views.SchemaView.with_ui('swagger', cache_timeout=0)),
]


import tkinter as tk
from tkinter import ttk
import threading
import keyboard
import time
from tkinter import messagebox

icon_path = 'C:\\Users\\Mr_Pryor\\Desktop\\Save Scummer\\bg3.ico'

class KeySenderApp:
    def __init__(self, root):
        self.root = root
        self.root.title("BG3: Save Scummer")  # Change the window title here

        # Set the background color to #313338
        self.root.configure(bg='#313338')

        # Calculate the center position of the screen
        screen_width = root.winfo_screenwidth()
        screen_height = root.winfo_screenheight()
        x = (screen_width - 300) // 2  # 300 is the width of the window
        y = (screen_height - 250) // 2  # 250 is the height of the window

        # Set the window size and position
        self.root.geometry("300x200+{}+{}".format(x, y))

        # Set the window icon
        self.root.iconbitmap(icon_path)

        # Create a custom style to match Discord's color scheme
        self.style = ttk.Style()
        self.style.configure('TLabel', foreground='#949B9A', background='#313338')  # Change label text color to #949B9A and background to #313338
        self.style.configure('TEntry', foreground='black', background='#2B2D31')  # Change text color to black and entry background to #2B2D31
        self.style.configure('TCombobox', foreground='black', background='#2C2F33')  # Change text color to black and combobox background to #2C2F33
        self.style.configure('TButton', foreground='black', background='#B5BAC1')  # Change text color to black and button background to #B5BAC1
        self.style.configure('TFrame', background='#1E1F22')  # Change the frame background color to #1E1F22
        self.style.configure('TNotebook', background='#1E1F22')  # Change the notebook background color to #1E1F22

        self.key_label = ttk.Label(root, text="Key", style='TLabel')
        self.key_label.pack()

        # Set the default key to "F5"
        self.key_entry = ttk.Entry(root, style='TEntry')
        self.key_entry.insert(0, "F5")
        self.key_entry.pack()

        self.key_set = False  # Flag to check if the key is set

        self.delay_label = ttk.Label(root, text="Delay", style='TLabel')
        self.delay_label.pack()

        # Set the default delay to "5"
        self.delay_var = tk.StringVar()
        vcmd = (self.root.register(self.validate_delay_input), "%P")
        self.delay_entry = ttk.Entry(root, style='TEntry', textvariable=self.delay_var, validate="key", validatecommand=vcmd)
        self.delay_entry.insert(0, "5")
        self.delay_entry.pack()

        # Set the default delay units to "Minutes"
        self.delay_units = tk.StringVar()
        self.delay_units.set("Minutes")

        self.delay_units_label = ttk.Label(root, text="Delay Units", style='TLabel')
        self.delay_units_label.pack()

        self.delay_units_combobox = ttk.Combobox(root, textvariable=self.delay_units, values=["Seconds", "Minutes"], state="readonly", style='TCombobox')
        self.delay_units_combobox.pack()

        self.countdown_label = ttk.Label(root, text="Countdown:", style='TLabel')
        self.countdown_label.pack()

        self.countdown_value = tk.StringVar()
        self.countdown_label_value = ttk.Label(root, textvariable=self.countdown_value, style='TLabel')
        self.countdown_label_value.pack()

        # Create a toggle button for start/stop
        self.start_button = ttk.Button(root, text="Start", command=self.toggle_countdown, style='TButton')
        self.start_button.pack()

        self.is_counting_down = False
        self.countdown_thread = None

        # Store the previous delay units
        self.prev_delay_units = "Minutes"

        # Counter for key presses
        self.key_press_count = 0
        self.key_press_label = ttk.Label(root, text="Saves: {}".format(self.key_press_count), style='TLabel')
        self.key_press_label.pack(side="bottom", anchor="se")

        # Bind a key press event to capture the key
        self.root.bind("<KeyPress>", self.capture_key_press)

    def validate_delay_input(self, input_text):
        # This function validates the input in the Delay entry field to allow only numbers and an empty string.
        return input_text == "" or input_text.isdigit()

    def toggle_countdown(self):
        if self.is_counting_down:
            self.stop_countdown()
        else:
            self.start_countdown()

    def start_countdown(self):
        if not self.is_counting_down:
            delay = float(self.delay_var.get())

            if delay <= 1:
                # Display an error message and return without starting the countdown
                messagebox.showerror("Error", "Delay must be greater than 1.")
                return

            self.is_counting_down = True
            self.start_button.config(text="Stop")
            if self.delay_units.get() == "Minutes":
                delay *= 60

            self.stop_countdown_event = threading.Event()

            def countdown(delay):
                original_delay = delay  # Store the original delay
                while not self.stop_countdown_event.is_set():
                    while delay > 0 and not self.stop_countdown_event.is_set():
                        self.countdown_value.set(f"{delay:.1f} seconds")
                        time.sleep(1)
                        delay -= 1
                    if not self.stop_countdown_event.is_set():
                        self.send_key()
                        delay = original_delay  # Reset the delay to the original value

                self.reset_countdown()

            self.countdown_thread = threading.Thread(target=countdown, args=(delay,))
            self.countdown_thread.start()

    def stop_countdown(self):
        if self.is_counting_down:
            self.stop_countdown_event.set()

    def send_key(self):
        key_to_send = self.key_entry.get()
        keyboard.press_and_release(key_to_send)
        self.key_press_count += 1
        self.key_press_label.config(text="Saves: {}".format(self.key_press_count))

    def reset_countdown(self):
        self.is_counting_down = False
        self.start_button.config(text="Start")
        self.countdown_value.set("")

        # Check if the countdown thread is not the current thread before attempting to join it
        if self.countdown_thread and self.countdown_thread != threading.current_thread():
            self.countdown_thread.join()

    def on_delay_units_change(self, *args):
        # Check if delay units have changed
        if self.delay_units.get() != self.prev_delay_units:
            self.prev_delay_units = self.delay_units.get()
            self.reset_countdown()  # Reset the countdown

    def capture_key_press(self, event):
        # This function captures the key press event and sets the key entry field to the pressed key.
        if not self.key_set:
            pressed_key = event.keysym
            self.key_entry.delete(0, tk.END)
            self.key_entry.insert(0, pressed_key)
            self.key_set = True

if __name__ == "__main__":
    root = tk.Tk()
    app = KeySenderApp(root)
    # Bind the delay units change event to the handler
    app.delay_units.trace_add("write", app.on_delay_units_change)
    root.mainloop()


"""
plugin for Trac to give anonymous users authenticated access
using a CAPTCHA
"""

# Plugin for trac 0.11

import random
import sys
import time
import urllib

from componentdependencies import IRequireComponents

from genshi.builder import Markup
from genshi.builder import tag
from genshi.filters.transform import Transformer

from pkg_resources import resource_filename

from skimpyGimpy import skimpyAPI

from trac.core import *
from trac.db import Table, Column
from trac.env import IEnvironmentSetupParticipant
from trac.web import IRequestFilter
from trac.web import ITemplateStreamFilter
from trac.web.api import IAuthenticator
from trac.web.auth import LoginModule
from trac.web.chrome import add_warning
from trac.web.chrome import Chrome
from trac.web.chrome import INavigationContributor
from trac.web.chrome import ITemplateProvider
from trac.config import ListOption
from trac.config import Option

from tracsqlhelper import create_table
from tracsqlhelper import execute_non_query
from tracsqlhelper import get_scalar
from tracsqlhelper import get_table
from tracsqlhelper import insert_update

from utils import random_word
from web_ui import ImageCaptcha

try:
    from acct_mgr.api import AccountManager
    from acct_mgr.web_ui import RegistrationModule
except:
    AccountManager = None

class AuthCaptcha(Component):

    ### class data
    implements(IRequestFilter,
               ITemplateStreamFilter,
               ITemplateProvider,
               IAuthenticator,
               IEnvironmentSetupParticipant,
               IRequireComponents,
               INavigationContributor
               )

    dict_file = Option('captchaauth', 'dictionary_file',
                           default="http://java.sun.com/docs/books/tutorial/collections/interfaces/examples/dictionary.txt")
    captcha_type = Option('captchaauth', 'type',
                          default="png")
    realms = ListOption('captchaauth', 'realms',
                        default="wiki, newticket")
    permissions = { 'wiki': [ 'WIKI_CREATE', 'WIKI_MODIFY' ],
                    'newticket': [ 'TICKET_CREATE' ] }

    xpath = { 'ticket.html': "//div[@class='buttons']" }
    delete = { 'ticket.html': "//div[@class='field']" }

    ### IRequestFilter methods

    def pre_process_request(self, req, handler):
        """Called after initial handler selection, and can be used to change
        the selected handler or redirect request.

        Always returns the request handler, even if unchanged.
        """

        if req.method == 'GET':
            if req.path_info.strip('/') in ['register', 'login'] and req.authname != 'anonymous':
                login_module = LoginModule(self.env)
                login_module._do_logout(req)
                req.redirect(req.href(req.path_info))

        if req.method == 'POST':

            realm = self.realm(req)

            # set the session data for name and email if CAPTCHA-authenticated
            if 'captchaauth' in req.args:
                name, email = self.identify(req)
                for field in 'name', 'email':
                    value = locals()[field]
                    if value:
                        req.session[field] = value
                req.session.save()
                if req.authname != 'anonymous' and realm == 'newticket':
                    req.args['author'] = name
                    if email:
                        req.args['author'] += ' <%s>' % email

            # redirect anonymous user posts that are not CAPTCHA-identified
            if req.authname == 'anonymous' and realm in self.realms:

                if 'captchaauth' in req.args and 'captchaid' in req.args:
                    # add warnings from CAPTCHA authentication
                    captcha = self.captcha(req)
                    if req.args['captchaauth'] != captcha:
                        add_warning(req, "You typed the wrong word. Please try again.")
                        try:
                            # delete used CAPTCHA
                            execute_non_query(self.env, "DELETE FROM captcha WHERE id=%s", req.args['captchaid'])
                        except:
                            pass

                    name, email = self.identify(req)
                    if not name:
                        add_warning(req, 'Please provide your name')
                    if AccountManager and name in AccountManager(self.env).get_users():
                        add_warning(req, '%s is already taken as by a registered user.  Please login or use a different name' % name)

                # redirect to previous location
                location = req.get_header('referer')
                if location:
                    location, query = urllib.splitquery(location)

                    if realm == 'newticket':
                        args = [(key.split('field_',1)[-1], value)
                                for key, value in req.args.items()
                                if key.startswith('field_')]
                        location += '?%s' % urllib.urlencode(args)
                else:
                    location =  req.href()
                req.redirect(location)

        return handler

    # for ClearSilver templates
    def post_process_request(self, req, template, content_type):
        """Do any post-processing the request might need; typically adding
        values to req.hdf, or changing template or mime type.

        Always returns a tuple of (template, content_type), even if
        unchanged.

        Note that `template`, `content_type` will be `None` if:
         - called when processing an error page
         - the default request handler did not return any result

        (for 0.10 compatibility; only used together with ClearSilver templates)
        """
        return (template, content_type)

    # for Genshi templates
    def post_process_request(self, req, template, data, content_type):
        """Do any post-processing the request might need; typically adding
        values to the template `data` dictionary, or changing template or
        mime type.

        `data` may be update in place.

        Always returns a tuple of (template, data, content_type), even if
        unchanged.

        Note that `template`, `data`, `content_type` will be `None` if:
         - called when processing an error page
         - the default request handler did not return any result

        (Since 0.11)
        """
        return (template, data, content_type)

    ### ITemplateStreamFilter method

    def filter_stream(self, req, method, filename, stream, data):
        """Return a filtered Genshi event stream, or the original unfiltered
        stream if no match.

        `req` is the current request object, `method` is the Genshi render
        method (xml, xhtml or text), `filename` is the filename of the template
        to be rendered, `stream` is the event stream and `data` is the data for
        the current template.

        See the Genshi documentation for more information.
        """

        # only show CAPTCHAs for anonymous users
        if req.authname != 'anonymous':
            return stream

        # only put CAPTCHAs in the realms specified
        realm = self.realm(req)
        if realm not in self.realms:
            return stream

        # add the CAPTCHA to the stream
        if filename in self.xpath:

            # store CAPTCHA in DB and session
            word = random_word(self.dict_file)
            insert_update(self.env, 'captcha', 'id', req.session.sid, dict(word=word))
            req.session['captcha'] = word
            req.session.save()

            # render the template
            chrome = Chrome(self.env)
            template = chrome.load_template('captcha.html')
            _data = {}

            # CAPTCHA type
            if self.captcha_type == 'png':
                captcha = tag.img(None, src=req.href('captcha.png'))
            else:
                captcha = Markup(skimpyAPI.Pre(word).data())

            _data['captcha'] = captcha
            _data['email'] = req.session.get('email', '')
            _data['name'] = req.session.get('name', '')
            _data['captchaid'] = req.session.sid
            xpath = self.xpath[filename]
            stream |= Transformer(xpath).before(template.generate(**_data))
            if filename in self.delete:
                stream |= Transformer(self.delete[filename]).remove()

        return stream

    ### methods for ITemplateProvider

    """Extension point interface for components that provide their own
    ClearSilver templates and accompanying static resources.
    """

    def get_htdocs_dirs(self):
        """Return a list of directories with static resources (such as style
        sheets, images, etc.)

        Each item in the list must be a `(prefix, abspath)` tuple. The
        `prefix` part defines the path in the URL that requests to these
        resources are prefixed with.

        The `abspath` is the absolute path to the directory containing the
        resources on the local file system.
        """
        return []

    def get_templates_dirs(self):
        """Return a list of directories containing the provided template
        files.
        """
        return [resource_filename(__name__, 'templates')]

    ### method for IAuthenticator

    """Extension point interface for components that can provide the name
    of the remote user."""

    def authenticate(self, req):
        """Return the name of the remote user, or `None` if the identity of the
        user is unknown."""

        # check for an authenticated user
        login_module = LoginModule(self.env)
        remote_user = login_module.authenticate(req)
        if remote_user:
            return remote_user

        # authenticate via a CAPTCHA
        if 'captchaauth' in req.args and 'captchaid' in req.args:

            # ensure CAPTCHA identification
            captcha = self.captcha(req)
            if captcha != req.args['captchaauth']:
                return

            # ensure sane identity
            name, email = self.identify(req)
            if name is None:
                return
            if AccountManager and name in AccountManager(self.env).get_users():
                return

            # delete used CAPTCHA on success
            try:
                execute_non_query(self.env, "DELETE FROM captcha WHERE id=%s", req.args['captchaid'])
            except:
                pass

            # log the user in
            req.environ['REMOTE_USER'] = name
            login_module._do_login(req)

    ### methods for INavigationContributor

    """Extension point interface for components that contribute items to the
    navigation.
    """

    def get_active_navigation_item(self, req):
        """This method is only called for the `IRequestHandler` processing the
        request.

        It should return the name of the navigation item that should be
        highlighted as active/current.
        """
        return None

    def get_navigation_items(self, req):
        """Should return an iterable object over the list of navigation items to
        add, each being a tuple in the form (category, name, text).
        """
        if req.authname != 'anonymous' and 'captcha' in req.session:
            return [('metanav', '_login', tag.a("Login",
                                               href=req.href.login())),
                    ('metanav', '_register', tag.a("Register",
                                                  href=req.href.register()))]
        return []

    ### methods for IEnvironmentSetupParticipant

    """Extension point interface for components that need to participate in the
    creation and upgrading of Trac environments, for example to create
    additional database tables."""

    def environment_created(self):
        """Called when a new Trac environment is created."""
        if self.environment_needs_upgrade(None):
            self.upgrade_environment(None)

    def environment_needs_upgrade(self, db):
        """Called when Trac checks whether the environment needs to be upgraded.

        Should return `True` if this participant needs an upgrade to be
        performed, `False` otherwise.
        """
        try:
            get_table(self.env, 'captcha')
        except:
            return True
        return False

    def upgrade_environment(self, db):
        """Actually perform an environment upgrade.

        Implementations of this method should not commit any database
        transactions. This is done implicitly after all participants have
        performed the upgrades they need without an error being raised.
        """

        # table of CAPTCHAs
        captcha_table = Table('captcha', key='key')[
            Column('id'),
            Column('word')]
        create_table(self.env, captcha_table)

    ### method for IRequireComponents

    def requires(self):
        """list of component classes that this component depends on"""
        return [ImageCaptcha]

    ### internal methods

    def identify(self, req):
        """
        identify the user, ensuring uniqueness (TODO);
        returns a tuple of (name, email) or success or None
        """
        name = req.args.get('name', None).strip()
        email = req.args.get('email', None).strip()
        return name, email

    def realm(self, req):
        """
        returns the realm according to the request
        """
        path = req.path_info.strip('/').split('/')
        if not path:
            return
        # TODO: default handler ('/')
        return path[0]

    def captcha(self, req):
        return get_scalar(self.env, "SELECT word FROM captcha WHERE id=%s", 0, req.args['captchaid'])


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt

import pywt
import pywt.data

ecg = pywt.data.ecg()

data1 = np.concatenate((np.arange(1, 400),
                        np.arange(398, 600),
                        np.arange(601, 1024)))
x = np.linspace(0.082, 2.128, num=1024)[::-1]
data2 = np.sin(40 * np.log(x)) * np.sign((np.log(x)))

mode = pywt.Modes.smooth

def plot_signal_decomp(data, w, title):
    """Decompose and plot a signal S.

    S = An + Dn + Dn-1 + ... + D1
    """
    w = pywt.Wavelet(w)
    a = data
    ca = []
    cd = []
    for i in range(5):
        (a, d) = pywt.dwt(a, w, mode)
        ca.append(a)
        cd.append(d)

    rec_a = []
    rec_d = []

    for i, coeff in enumerate(ca):
        coeff_list = [coeff, None] + [None] * i
        rec_a.append(pywt.waverec(coeff_list, w))

    for i, coeff in enumerate(cd):
        coeff_list = [None, coeff] + [None] * i
        rec_d.append(pywt.waverec(coeff_list, w))

    fig = plt.figure()
    ax_main = fig.add_subplot(len(rec_a) + 1, 1, 1)
    ax_main.set_title(title)
    ax_main.plot(data)
    ax_main.set_xlim(0, len(data) - 1)

    for i, y in enumerate(rec_a):
        ax = fig.add_subplot(len(rec_a) + 1, 2, 3 + i * 2)
        ax.plot(y, 'r')
        ax.set_xlim(0, len(y) - 1)
        ax.set_ylabel("A%d" % (i + 1))

    for i, y in enumerate(rec_d):
        ax = fig.add_subplot(len(rec_d) + 1, 2, 4 + i * 2)
        ax.plot(y, 'g')
        ax.set_xlim(0, len(y) - 1)
        ax.set_ylabel("D%d" % (i + 1))

plot_signal_decomp(data1, 'coif5', "DWT: Signal irregularity")
plot_signal_decomp(data2, 'sym5',
                   "DWT: Frequency and phase change - Symmlets5")
plot_signal_decomp(ecg, 'sym5', "DWT: Ecg sample - Symmlets5")

plt.show()


from google.cloud import bigquery

class BigQueryClient:
    """
    Class to establish a client connection, execute queries and compare result sets
    """

    def __init__(self, credentials):
        self.credentials = credentials

    def get_client(self):
        """
        Method to return big query client authenticated by service account credentials
        """
        client_ = bigquery.Client(credentials=self.credentials)
        return client_

    @staticmethod
    def execute_query(client, query, result_type="rows", timeout=None):
        """
        Method to execute the query and return the data as per result type
        """
        query_job = client.query(query)
        if timeout is not None:
            query_job.configuration.query.timeout = timeout
        result = query_job.result()
        if result_type.lower() == "json":
            json_data = [dict(row) for row in result]
            return json_data
        elif result_type.lower() == "dataframe":
            df = query_job.to_dataframe()
            return df
        else:
            return result


class Ponto:
    def __init__(self, x, y):
        self.x: int = x
        self.y: int = y
        self.coordenada: list = [self.x, self.y]

    def getPontos(self):
        return self.coordenada

class Retangulo:
    def __init__(self, base, altura):
        self.base: int = base
        self.altura: int = altura
        self.verticeDePartida: Ponto = Ponto(0, 0)

    def encontrarCentro(self):
        x = self.base/2
        y = self.altura/2
        centro = Ponto(x, y)
        return print(f'O centro do retângulo de base {self.base} e altura {self.altura} é: {centro.getPontos()}')

    def setLado(self, qualLado, valorLado):
        if qualLado == 'base':
            self.base = valorLado
        elif qualLado == 'altura':
            self.altura = valorLado
        else:
            return print('Escolha apenas entre "base" ou "altura".')

retangulo1 = Retangulo(4, 6)
retangulo1.encontrarCentro()
retangulo2 = Retangulo(6, 6)
retangulo2.encontrarCentro()
retangulo3 = Retangulo(8, 4)
retangulo3.encontrarCentro()

retangulo3.setLado("base", 4)
retangulo3.encontrarCentro()


import numpy as np
import torch
from sklearn.metrics import f1_score
from core.utils import METRIC_REGISTRY

@METRIC_REGISTRY.register()
class AUMetric:
    def __call__(self, pred, gt, sigmoid=True, threshold=0.5):
        """calc au metrics(with sigmoid)

        Args:
            pred (list(list())): pred list like [[-0.2, 0.1, 0.2, 0.3, ..], [...], ...]
            gt (list(list())): label list like [[0, 1, 0, ...], ...]
            threshold (float): threshold to determine whether active (default: 0.5)

        Returns:
            F1_mean (float): binary F1 score
            acc (float): accuracy
            F1 (list(float)): each au's F1 score
        """
        F1 = []
        if sigmoid:
            pred = torch.tensor(pred)
            pred = torch.sigmoid(pred)

        gt = np.array(gt)
        pred = np.array(pred)
        class_num = gt.shape[-1]

        index = [i for i in range(class_num)]

        for t in index:
            gt_ = gt[:, t]
            pred_ = pred[:, t]
            new_pred = ((pred_ >= threshold) * 1).flatten()
            F1.append(f1_score(gt_.flatten(), new_pred))

        F1_mean = np.mean(F1)

        counts = gt.shape[0]
        accs = 0
        for i in range(counts):
            pred_label = ((pred[i,:] >= threshold) * 1).flatten()
            gg = gt[i].flatten()
            j = 0
            for k in index:
                if int(gg[k]) == int(pred_label[k]):
                        j += 1
            if j == class_num:
                accs += 1

        acc = 1.0 * accs / counts

        return {'F1': F1_mean, 'ACC': acc, 'F1_list': F1}


#!/usr/bin/python

def retreat(bg_grd_path, gmt_paths, utm_zone):

	LEGEND_Y = 0.6;
	LEGEND_YSPACING = 3;
	LEGEND_X = 0.7;
	LEGEND_XSPACING = 1.0;
	LEGEND_FONTSIZE = "8";
	LEGEND_FONT	= "1";
	LEGEND_BOXWIDTH = 0.12;

	ice_bounds_path  = "/home/akm26/Documents/Russia/NovZ/Boundaries/NovZ_bounds_ice_sub_utm42x.gmt"
	rock_bounds_path = "/home/akm26/Documents/Russia/NovZ/Boundaries/NovZ_bounds_rock_sub_utm42x.gmt"

	existing_gmt_paths = [];

	for path in gmt_paths:

		if not os.path.exists(path):
			print("\n***** WARNING, " + path + " does not exist, skipping...\n");

		existing_gmt_paths.append(path);

	import re;
	import subprocess;

	cmd  = "\ngrdinfo " + bg_grd_path + "\n";
	pipe = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE).stdout;
	info = pipe.read();
	pipe.close();

	xmin = info[re.search("x_min: ",info).end(0):re.search("x_min: \d+\.*\d*",info).end(0)];
	xmax = info[re.search("x_max: ",info).end(0):re.search("x_max: \d+\.*\d*",info).end(0)];
	ymin = info[re.search("y_min: ",info).end(0):re.search("y_min: \d+\.*\d*",info).end(0)];
	ymax = info[re.search("y_max: ",info).end(0):re.search("y_max: \d+\.*\d*",info).end(0)];
	bg_min = info[re.search("z_min:\s*",info).end(0):re.search("z_min:\s*\d+\.*\d*",info).end(0)];
	bg_max = info[re.search("z_max:\s*",info).end(0):re.search("z_max:\s*\d+\.*\d*",info).end(0)];

#	xmin = "368914.24565";
#	xmax = "389991.512562";
#	ymin = "8385656.90714";
#	ymax = "8403318.96781";

	R = "-R" + xmin + "/" + ymin + "/" + xmax + "/" + ymax + "r";

	cmd  = "\necho \"" + xmin + " " + ymin + "\n" + xmax + " " + ymax + "\" | /usr/local/gmt/bin/mapproject -Ju" + utm_zone + "/1:1 -F -C -I\n";
	pipe = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE).stdout;
	out  = pipe.read().strip().split();
	pipe.close();

	geo_R  = "-R" + out[0] + "/" + out[1] + "/" + out[2] + "/" + out[3] + "r";

	ps_path = existing_gmt_paths[0];
	ps_path = ps_path[ps_path.rfind("/") + 1 : re.search("_\d{14}", ps_path).start(0)];
	ps_path = ps_path + "_retreat.ps";

	scale = "40000";
	J     = "-Jx1:" + scale;
	geo_J = "-Ju" + utm_zone + "/1:" + scale;

	legend_barwidth  = str(0.01 * (float(xmax) - float(xmin)));
	legend_xpos      = str(LEGEND_X * (float(xmax) - float(xmin)) + float(xmin));
	legend_xint      = str(float(legend_barwidth) * float(LEGEND_XSPACING));
	legend_barend    = str(float(legend_xpos) + float(legend_barwidth));
	legend_text_xpos = str(float(legend_xint) + float(legend_barend));
	legend_ypos      = str(LEGEND_Y * (float(ymax) - float(ymin)) + float(ymin));
	legend_yint      = str((float(ymax) - float(ymin)) / 100 * LEGEND_YSPACING);
	legend_box_l     = str(float(legend_xpos) - float(legend_xint));
	legend_box_r     = str(float(legend_xpos) + LEGEND_BOXWIDTH * (float(xmax) - float(xmin)));
	legend_box_u     = str(float(legend_ypos) + float(legend_yint) * (len(existing_gmt_paths) + 1) - float(legend_yint) / 2);
	legend_box_d     = str(float(legend_ypos) - float(legend_yint) / 2);

	cmd  = "\nmakecpt -Cgray -T" + bg_min + "/" + bg_max + "/1 > grayscale.cpt";
	cmd += "\nmakecpt -Cno_green -T0/" + str(len(existing_gmt_paths) - 1) + "/0.1 > retreat.cpt\n";
	cmd += "\ngrdimage " + bg_grd_path + " " + J + " " + R + " -Cgrayscale.cpt -Q -P -K > " + ps_path + "\n";
	cmd += "\npsxy " + ice_bounds_path + " " + J + " " + R + " -W2p,black -m -O -K >> " + ps_path + "\n";
	cmd += "\npsxy " + rock_bounds_path + " " + J + " " + R + " -W2p,black -m -O -K >> " + ps_path + "\n";
	cmd += "\npsbasemap " + geo_J + " " + geo_R + " -Bf0.125a0.125g0.125:\"Longitude\":/a0.0625g0.0625:\"\"::,::.\"\":wESn -K -O --BASEMAP_TYPE=inside --PLOT_DEGREE_FORMAT=ddd:mmF --ANNOT_FONT_PRIMARY=1 --ANNOT_FONT_SIZE_PRIMARY=12 --GRID_PEN_PRIMARY=0.25p,100/100/100,- --OBLIQUE_ANNOTATION=6 >> " + ps_path + "\n";

	cmd += "\necho \"" + legend_box_l + " " + legend_box_u + "\\n" + legend_box_r + " " + legend_box_u + "\\n" + legend_box_r + " " + legend_box_d + "\\n" + legend_box_l + " " +legend_box_d + "\" | psxy " + J + " " + R + " -L -Gwhite -W0.5p,black -O -K >> " + ps_path + "\n";
	cmd += "\necho \"" + legend_xpos + " " + str(float(legend_ypos) + float(legend_yint) * len(existing_gmt_paths)) + " " + LEGEND_FONTSIZE + " 0 " + LEGEND_FONT + " LM Front position\" | pstext " + J + " " + R + " -O -K >> " + ps_path + "\n";

	i = 0;

	for path in existing_gmt_paths:

		label = path[re.search("\d{14}", path).start(0) : re.search("\d{14}", path).end(0)];
		label = label[0:4] + "/" + label[4:6] + "/" + label[6:8];

		cmd += "\n/usr/local/gmt/bin/mapproject -m -Ju" + utm_zone + "/1:1 -F -C " + path + " | psxy -m " + J + " " + R + " -W1p -Cretreat.cpt -O -K >> " + ps_path + "\n";
		cmd += "\necho \"" + legend_barend + " " + str(float(legend_ypos) + float(legend_yint) * i) + " " + str(i) + "\" | psxy " + J + " " + R + " -SB0.1cb" + legend_xpos + " -Cretreat.cpt -O -K >> " + ps_path + "\n";
		cmd += "\necho \"" + legend_text_xpos + " " + str(float(legend_ypos) + float(legend_yint) * i) + " " + LEGEND_FONTSIZE + " 0 " + LEGEND_FONT + " LM " + label + "\" | pstext " + J + " " + R + " -O -K >> " + ps_path + "\n";
		i   += 1;

	cmd += "\npsbasemap " + geo_J + " " + geo_R + " -Lfx2c/2c/76.5/1k+jr+u+p0.5,black+fwhite -O --ANNOT_FONT_PRIMARY=1 --LABEL_FONT=1 --ANNOT_FONT_SIZE_PRIMARY=10 --LABEL_FONT_SIZE=10 >> " + ps_path + "\n";
	cmd += "\nps2raster -A -Tf " + ps_path + "\n";
	print(cmd);
	subprocess.call(cmd,shell=True);

if __name__ == "__main__":

	import os;
	import sys;

	assert len(sys.argv) > 2, "\n***** ERROR: retreat.py requires at least 2 arguments, " + str(len(sys.argv) - 1) + " given\n";

	bg_grd_path = sys.argv[1];

	gmt_paths = [];

	for i in range(2, len(sys.argv)):
		gmt_paths.append(sys.argv[i]);

	utm_zone = "41X";

	if not os.path.exists(sys.argv[len(sys.argv) - 1]):
		utm_zone  = sys.argv[len(sys.argv) - 1];
		gmt_paths = gmt_paths[0 : len(gmt_paths) - 1];

	retreat(bg_grd_path, gmt_paths, utm_zone);

	exit();


#from key.key import *

import urllib
import json
import requests
import os

key = os.environ['WUNDERGROUND_KEY']

class CurrentWeather:
    def __init__(self, r, zip):
        self.zip = zip
        self.r = requests.get('http://api.wunderground.com/api/{}/geolookup/conditions/q/{}.json'.format(key, self.zip))

    def get(self):
        parsed_json = self.r.json()
        city = parsed_json['location']['city']
        state = parsed_json['location']['state']
        weather = parsed_json['current_observation']['weather']
        temperature_string = parsed_json['current_observation']['temperature_string']
        feelslike_string = parsed_json['current_observation']['feelslike_string']
        return print('Weather in ' + city + ', ' + state + ': ' + weather.lower() + '. The temperature is ' + temperature_string + ' but it feels like ' + feelslike_string + '.')

class TenDayWeather:
    def __init__(self, r, zip):
        self.zip = zip
        self.r = requests.get('http://api.wunderground.com/api/{}/geolookup/forecast10day/q/{}.json'.format(key, self.zip))

    def get(self):
        parsed_json = self.r.json()
        #print(json.dumps(parsed_json, indent=4, sort_keys=True))
        for day in parsed_json['forecast']['txt_forecast']['forecastday']:
            print("On "+day['title']+ " the forecast is "+day['fcttext'])

class SunRiseWeather:
    def __init__(self, r, zip):
        self.zip = zip
        self.r = requests.get('http://api.wunderground.com/api/{}/geolookup/astronomy/q/{}.json'.format(key, self.zip))

    def get(self):
        parsed_json = self.r.json()
        sunrise = parsed_json['sun_phase']['sunrise']['hour']+':'+parsed_json['sun_phase']['sunrise']['minute']
        sunset = parsed_json['sun_phase']['sunset']['hour']+':'+parsed_json['sun_phase']['sunset']['minute']
        print("Sunrise is at: " + sunrise + ", sunset is at: " + sunset)

class AlertsWeather:
    def __init__(self, r, zip):
        self.zip = zip
        self.r = requests.get('http://api.wunderground.com/api/{}/alerts/q/{}.json'.format(key, self.zip))

    def get(self):
        parsed_json = self.r.json()
        #print(json.dumps(parsed_json, indent=4, sort_keys=True))
        alert = parsed_json['alerts']
        if alert == []:
            print("There are no alerts for your area! Probably a good thing...")
        else:
            alert_type = parsed_json['alerts']['message']
            print("Oh no! The Weather Service says "+alert_type)

class HurricanesWeather:
    def __init__(self, r):
        self.r = requests.get('http://api.wunderground.com/api/{}/currenthurricane/view.json'.format(key))

    def get(self):
        parsed_json = self.r.json()
        print("There are currently "+str(len(parsed_json['currenthurricane']))+ " hurricanes: ")
        for hurricane in parsed_json['currenthurricane']:
        #print(json.dumps(hurricane, indent=4, sort_keys=True))
            name = hurricane['stormInfo']['stormName']
            print(name)

def get_zip():
    zip = input("What is your five digit zip code?\n")
    return zip

def main():
    option = input("""So what do you want to know?
    Enter 1 for current conditions;
    Enter 2 for ten day forecast;
    Enter 3 for sunrise and sunset times;
    Enter 4 for all current weather alerts;
    Enter 5 for all current tracked hurricanes.\n""" )
    if option == '1':
        new = CurrentWeather(key, get_zip())
        new.get()
    elif option == '2':
        new = TenDayWeather(key, get_zip())
        new.get()
    elif option == '3':
        new = SunRiseWeather(key, get_zip())
        new.get()
    elif option == '4':
        new = AlertsWeather(key, get_zip())
        new.get()
    else:
        new = HurricanesWeather(key)
        new.get()
main()


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import plotly.graph_objects as go
import seaborn as sns
import plotly.express as px

import warnings
warnings.filterwarnings('ignore')

df = pd.read_csv('/content/threads_reviews.csv')

df

df.head()

df.tail()

df.shape

df.columns

df.isnull().sum()

df.duplicated().sum()

df.drop_duplicates

df.describe()

df.info()

df.nunique()

df['source'].unique()

df['source'].value_counts()

plt.figure(figsize=(5,5))
counts = df['source'].value_counts()
plt.pie(counts,labels = counts.index,autopct='%1.1f%%', colors = sns.color_palette('hls'))
plt.title("Source of reviews")
plt.show()

fig = go.Figure(data=[go.Bar(x=df['source'].value_counts().index, y=df['source'].value_counts())])
fig.update_layout(title='Source of Reviews',xaxis_title="Source",yaxis_title="Count")
fig.show()

counts = df['source'].value_counts()
fig = go.Figure(data=[go.Pie(labels=counts.index, values=counts)])
fig.update_layout(title='Source of Reviews')
fig.show()

df['rating'].unique()

df['rating'].value_counts()

plt.figure(figsize=(15,6))
sns.countplot(x = df['rating'], data = df, palette = 'hls')
plt.show()

plt.figure(figsize=(10, 10))
counts = df['rating'].value_counts()
plt.pie(counts, labels=counts.index, autopct='%1.1f%%', colors=sns.color_palette('hls'))
plt.title('Rating')
plt.show()

fig = go.Figure(data=[go.Bar(x=df['rating'].value_counts().index, y=df['rating'].value_counts())])
fig.update_layout(title='Rating',xaxis_title="Rating",yaxis_title="Count")
fig.show()

counts = df['rating'].value_counts()
fig = go.Figure(data=[go.Pie(labels=counts.index, values=counts)])
fig.update_layout(title='Rating')
fig.show()

df['review_date'] = pd.to_datetime(df['review_date'])

df1 = df.copy()

df1.set_index('review_date', inplace=True)

start_date = df1.index.min()
end_date = df1.index.max()

print("Start Date of Reviews:", start_date)
print("End Date of Reviews:", end_date)

week_delta = pd.Timedelta(days=7)
current_date = start_date

while current_date <= end_date:
    start_week = current_date
    end_week = current_date + week_delta
    current_week_data = df1[(df1.index >= start_week) & (df1.index < end_week)]
    print(current_week_data)
    weekly_counts = current_week_data.resample('D').size()
    print(weekly_counts)
    fig = px.bar(weekly_counts, x=weekly_counts.index, y=weekly_counts.values,
                 labels={'x': 'Date', 'y': 'Number of Reviews'},
                 title=f'Reviews for Week {start_week.strftime("%Y-%m-%d")} to {end_week.strftime("%Y-%m-%d")}')
    fig.update_layout(xaxis_tickangle=-45)
    fig.show()
    current_date += week_delta

daily_counts = df1.resample('D').size()

fig = go.Figure()
fig.add_trace(go.Bar(x=daily_counts.index, y=daily_counts.values,
                     marker_color='skyblue'))
fig.update_layout(title='Number of Reviews Day-wise',
                  xaxis_title='Date',
                  yaxis_title='Number of Reviews',
                  xaxis_tickangle=-45)
fig.show()

fig = go.Figure()
for source_name, source_data in df1.groupby('source'):
    fig.add_trace(go.Scatter(x=source_data.resample('D').size().index, y=source_data.resample('D').size().values,
                            mode='lines', name=source_name))
fig.update_layout(title='Number of Reviews Day-wise',
                  xaxis_title='Date',
                  yaxis_title='Number of Reviews',
                  xaxis_tickangle=-45)
fig.show()

fig = go.Figure()
for source_name, source_data in df1.groupby('source'):
    fig.add_trace(go.Scatter(x=source_data.resample('D').size().index, y=source_data.resample('D').size().values,
                            mode='lines+markers', name=source_name))
fig.update_layout(title='Number of Reviews Day-wise',
                  xaxis_title='Date',
                  yaxis_title='Number of Reviews',
                  xaxis_tickangle=-45)
fig.show()

fig = go.Figure()
for source_name, source_data in df1.groupby('source'):
    fig.add_trace(go.Scatter(x=source_data.resample('D').size().index, y=source_data.resample('D').size().values,
                            mode='markers', name=source_name))
fig.update_layout(title='Number of Reviews Day-wise',
                  xaxis_title='Date',
                  yaxis_title='Number of Reviews',
                  xaxis_tickangle=-45)
fig.show()

fig = go.Figure()
for rating_val, rating_data in df1.groupby('rating'):
    fig.add_trace(go.Scatter(x=rating_data.resample('D').size().index, y=rating_data.resample('D').size().values,
                             mode='lines+markers', name=f'Rating {rating_val}'))
fig.update_layout(title='Number of Reviews Day-wise by Rating',
                  xaxis_title='Date',
                  yaxis_title='Number of Reviews',
                  xaxis_tickangle=-45)
fig.show()

fig = go.Figure()
for rating_val, rating_data in df1.groupby('rating'):
    fig.add_trace(go.Scatter(x=rating_data.resample('D').size().index, y=rating_data.resample('D').size().values,
                             mode='markers', name=f'Rating {rating_val}'))
fig.update_layout(title='Number of Reviews Day-wise by Rating',
                  xaxis_title='Date',
                  yaxis_title='Number of Reviews',
                  xaxis_tickangle=-45)
fig.show()

df['rating']=df['rating'].map({1:-1,2:-1,3:0,4:1,5:1})

df

df_new = df[['review_description', 'rating']]

df_new

df_new['rating'].unique()

df_new['rating'].value_counts()

fig = go.Figure(data=[go.Bar(x=df_new['rating'].value_counts().index, y=df_new['rating'].value_counts())])
fig.update_layout(title='Rating',xaxis_title="Rating",yaxis_title="Count")
fig.show()

counts = df_new['rating'].value_counts()
fig = go.Figure(data=[go.Pie(labels=counts.index, values=counts)])
fig.update_layout(title='Rating')
fig.show()

"""data preprocessing

"""

def clean_text(text):
    text = text.lower()
    return text.strip()

df_new.review_description = df_new.review_description.apply(lambda x: clean_text(x))

df_new.review_description

import string
string.punctuation

def remove_punctuation(text):
    punctuationfree="".join([i for i in text if i not in string.punctuation])
    return punctuationfree

df_new.review_description = df_new.review_description.apply(lambda x:remove_punctuation(x))

df_new.review_description

df_new.review_description = df_new.review_description.apply(lambda x: x.lower())

df_new.review_description

import re

def tokenization(text):
    tokens = re.split(' ',text)
    return tokens

df_new.review_description = df_new.review_description.apply(lambda x: tokenization(x))

df_new.review_description

import nltk
nltk.download('stopwords')
stopwords = nltk.corpus.stopwords.words('english')
stopwords[0:10]
['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're"]

def remove_stopwords(text):
    output= " ".join(i for i in text if i not in stopwords)
    return output

df_new.review_description = df_new.review_description.apply(lambda x:remove_stopwords(x))

df_new.review_description

def clean_text(text):
    text = re.sub('\[.*\]','', text).strip()
    text = re.sub('\S*\d\S*\s*','', text).strip()
    return text.strip()

df_new.review_description = df_new.review_description.apply(lambda x: clean_text(x))

df_new.review_description

import spacy
nlp = spacy.load('en_core_web_sm')

stopwords = nlp.Defaults.stop_words
def lemmatizer(text):
    doc = nlp(text)
    sent = [token.lemma_ for token in doc if not token.text in set(stopwords)]
    return ' '.join(sent)

df_new.review_description =  df_new.review_description.apply(lambda x: lemmatizer(x))

def remove_urls(vTEXT):
    vTEXT = re.sub(r'(https|http)?:\/\/(\w|\.|\/|\?|\=|\&|\%)*\b', '', vTEXT, flags=re.MULTILINE)
    return(vTEXT)

df_new.review_description = df_new.review_description.apply(lambda x: remove_urls(x))

def remove_urls(vTEXT):
    vTEXT = re.sub(r'(https|http)?:\/\/(\w|\.|\/|\?|\=|\&|\%)*\b', '', vTEXT, flags=re.MULTILINE)
    return(vTEXT)

def remove_digits(text):
    clean_text = re.sub(r"\b[0-9]+\b\s*", "", text)
    return(text)

df_new.review_description = df_new.review_description.apply(lambda x: remove_digits(x))

def remove_digits1(sample_text):
    clean_text = " ".join([w for w in sample_text.split() if not w.isdigit()])
    return(clean_text)

df_new.review_description = df_new.review_description.apply(lambda x: remove_digits1(x))

def remove_emojis(data):
    emoji_pattern = re.compile("["
                               u"\U0001F600-\U0001F64F"
                               u"\U0001F300-\U0001F5FF"
                               u"\U0001F680-\U0001F6FF"
                               u"\U0001F1E0-\U0001F1FF"
                               "]+", flags=re.UNICODE)
    return re.sub(emoji_pattern, '', data)

df_new.review_description = df_new.review_description.apply(lambda x: remove_emojis(x))

df_new

import wordcloud

from wordcloud import WordCloud
data = df_new.review_description
plt.figure(figsize = (20,20))
wc = WordCloud(max_words = 1000 , width = 1600 , height = 800,
               collocations=False).generate(" ".join(data))
plt.imshow(wc)
plt.axis('off')
plt.show()

from wordcloud import WordCloud
data = df_new[df_new['rating'] == 1]['review_description']
plt.figure(figsize = (20,20))
wc = WordCloud(max_words = 1000 , width = 1600 , height = 800,
               collocations=False).generate(" ".join(data))
plt.imshow(wc)
plt.axis('off')
plt.show()

data = df_new[df_new['rating'] == 0]['review_description']
plt.figure(figsize = (20,20))
wc = WordCloud(max_words = 1000 , width = 1600 , height = 800,
               collocations=False).generate(" ".join(data))
plt.imshow(wc)
plt.axis('off')
plt.show()

data = df_new[df_new['rating'] == -1]['review_description']
plt.figure(figsize = (20,20))
wc = WordCloud(max_words = 1000 , width = 1600 , height = 800,
               collocations=False).generate(" ".join(data))
plt.imshow(wc)
plt.axis('off')
plt.show()

from sklearn.feature_extraction.text import TfidfVectorizer

tf1=TfidfVectorizer()
data_vec=tf1.fit_transform(df_new['review_description'])

data_vec

import pickle
model_filename = 'tfidf_vectorizer.pkl'
with open('mode_filename', 'wb') as model_file:
  pickle.dump(tf1, model_file)

y=df_new['rating'].values

from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.model_selection import train_test_split

X_train,X_test,y_train,y_test=train_test_split(data_vec,y,test_size=0.2,stratify = y, random_state=42)

from imblearn.over_sampling import SMOTE

smote = SMOTE(random_state=42)
X_balanced, y_balanced = smote.fit_resample(X_train, y_train)

X_balanced, y_balanced

from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

sv = SVC()

model_sv = sv.fit(X_balanced, y_balanced)

y_pred_sv = model_sv.predict(X_test)

accuracy = accuracy_score(y_test,y_pred_sv)
print(f'Accuracy: {accuracy:2f}')

model_filename = 'svm_model.pkl'
with open(model_filename, 'wb') as model_file:
  pickle.dump(model_sv, model_file)

dt = DecisionTreeClassifier()

model_dt = dt.fit(X_balanced, y_balanced)

y_pred_dt = model_dt.predict(X_test)

sv = SVC()
dt = DecisionTreeClassifier()
rf = RandomForestClassifier()
ad = AdaBoostClassifier()

models = [sv, dt, rf, ad]

accuracies = []

for model in models:
    print('Results for the model:', model.__class__.__name__)
    model.fit(X_balanced, y_balanced)
    y_pred = model.predict(X_test)

    accuracy = accuracy_score(y_test, y_pred)
    print('Accuracy:', accuracy)

    cm = confusion_matrix(y_test, y_pred)
    print('Confusion Matrix:\n', cm)

    report = classification_report(y_test, y_pred)
    print('Classification Report:\n', report)

    print('\n')

    accuracies.append(accuracy)

print('List of Accuracies:', accuracies)

model_names = ['SVC', 'DecisionTree', 'RandomForest', 'AdaBoost']
fig = go.Figure(data=go.Bar(x=model_names, y=accuracies))
fig.update_layout(title='Model Accuracies',
                  xaxis_title='Model',
                  yaxis_title='Accuracy',
                  yaxis_tickformat='.2%',
                  yaxis_range=[0, 1],
                  xaxis_tickangle=0)
fig.show()

import pickle
model_filename = 'svm_model.pkl'
with open(model_filename,'wb') as model_file:
    pickle.dump(sv,model_file)


#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:abner
@file:paddle_ocr_rec.py
@time:2021/11/03
"""
import os
import sys
import subprocess
__dir__ = os.path.dirname(os.path.abspath(__file__))
sys.path.append(__dir__)
sys.path.append(os.path.abspath(os.path.join(__dir__, '../..')))

sys.path.append(os.path.abspath(os.path.join(__dir__, '..')))
sys.path.append(os.path.abspath(os.path.join(__dir__, '..', '..')))
sys.path.append(os.path.abspath(os.path.join(__dir__, 'ocr_infer')))
sys.path.append(os.path.abspath(os.path.join(__dir__, 'ocr_infer', 'ppocr')))

os.environ["FLAGS_allocator_strategy"] = 'auto_growth'

import cv2
import copy
import numpy as np
import time
import logging
from PIL import Image
import utility as utility
import predict_rec as predict_rec
from predict_rec import TextRecognizer

args = utility.parse_args()
text_recognizer = TextRecognizer(args)

def get_rec_result(img):
    """
    Args:
        img_path: 图片路径

    Returns: tuple (识别字符，得分) 如：（‘123’，0.9），空返回：（‘’，nan）

    """
    # img = cv2.imread(img_path)

    rec_res, _ = text_recognizer([img])
    logging.info("rec:{} ".format(rec_res[0]))
    return rec_res

def extract_text(img):
    rec_res = get_rec_result(img)
    ret = []
    for v in rec_res:
        if v[0]:
            data = {
                'text': v[0],
                'confidence': v[1],
                'cx': 0.5,
                'cy': 0.5
            }
            ret.append(data)
    return ret

if __name__ == "__main__":
    img_path = r'E:\dataset\friends\wandou\images\id_images\0_0_0a3f9df8be6946cbb210a50cc3012d18.png'
    get_rec_result(img_path)


"""Pyrgo configuration."""
from __future__ import annotations

import pathlib
import sys
from dataclasses import dataclass
from typing import Any

import loguru
import tomli

class PyProjectNotFoundError(Exception):
    """Raised when `pyproject.toml` not found."""

    def __init__(self, path: pathlib.Path) -> None:  # noqa: D107
        super().__init__(f"`pyproject.toml` not found at {path.as_posix()}")

def _configure_logger(logger: loguru.Logger) -> loguru.Logger:
    logger.remove()
    fmt = "<lvl>[{level}]</lvl> {message} <green>{name}:{function}:{line}</green> @ {time:HH:mm:ss}"  # noqa: E501
    logger.add(sys.stderr, format=fmt)
    return logger

@dataclass(frozen=True)
class PyrgoConf:
    """Pyrgo configuration."""

    cwd: pathlib.Path
    requirements: pathlib.Path
    logger: loguru.Logger
    relevant_paths: list[str]
    artifacts: list[pathlib.Path]
    caches: list[pathlib.Path]
    core_deps_alias: str
    env_groups: set[str]

    @classmethod
    def new(cls: type[PyrgoConf]) -> PyrgoConf:
        """Create new configuration instance."""
        logger = _configure_logger(logger=loguru.logger)
        cwd = pathlib.Path().cwd()
        pyproject_path = cwd.joinpath("pyproject.toml")
        if not (pyproject_path.exists() and pyproject_path.is_file()):
            raise PyProjectNotFoundError(path=cwd)

        pyproject_data = tomli.loads(pyproject_path.read_text())
        relevant_paths: list[str] = [
            pyproject_data["project"]["name"].strip().replace("-", "_"),
        ]
        relevant_paths.extend(
            pyproject_data["tool"]["pytest"]["ini_options"]["testpaths"],
        )
        pyrgo_config = pyproject_data["tool"].get("pyrgo", None)
        caches = [
            cwd.joinpath(".pytest_cache"),
            cwd.joinpath(".ruff_cache"),
            cwd.joinpath(".mypy_cache"),
        ]
        if pyrgo_config is not None:
            extra_paths = pyrgo_config.get("extra-paths", None)
            extra_caches = pyrgo_config.get("extra-caches", None)
            if extra_paths is not None:
                relevant_paths.extend(extra_paths)
            if extra_caches is not None:
                caches.extend(cwd.joinpath(extra) for extra in extra_caches)

        core_deps_alias = "core"
        env_groups = {core_deps_alias}
        op_deps: dict[str, Any] | None = pyproject_data["project"].get(
            "optional-dependencies",
            None,
        )
        if op_deps is not None:
            env_groups = env_groups.union(op_deps.keys())

        return cls(
            cwd=cwd,
            requirements=cwd.joinpath("requirements"),
            logger=logger,
            relevant_paths=relevant_paths,
            artifacts=[cwd.joinpath("dist")],
            caches=caches,
            core_deps_alias=core_deps_alias,
            env_groups=env_groups,
        )

    def locked_envs(self) -> set[str]:
        """Get a set of available locked envs."""
        locked_envs: set[str] = set()
        for env in self.requirements.glob(pattern="*.txt"):
            locked_envs.add(
                env.relative_to(self.requirements).as_posix().removesuffix(".txt"),
            )

        return locked_envs


from django.contrib import admin

from .models import Proveedor

@admin.register(Proveedor)
class ProveedorAdmin(admin.ModelAdmin):

    # https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display
    # Modificar el qs para que muestre los objetos que fueron eliminados
    def get_queryset(self, request):
        return Proveedor.all_objects.all()

    list_display = (
        "cuit",
        "razon_social",
        "telefono",
        "email",
        "calle",
        "numero",
        "localidad",
        "created",
        "modified",
        "is_removed",
    )
    list_filter = ("created", "modified", "is_removed", "localidad")
    search_fields = ("cuit", "razon_social")
    list_display_links = ("razon_social",)
    ordering = ("razon_social",)


import torchvision.datasets

# train_data = torchvision.datasets.ImageNet("../dataset_image_net", train=True, transform=torchvision.transforms.ToTensor(), download=True)
from torch import nn

vgg16_false = torchvision.models.vgg16(pretrained=False)
vgg16_true = torchvision.models.vgg16(pretrained=True)

train_data = torchvision.datasets.CIFAR10("../dataset", train=True, transform=torchvision.transforms.ToTensor(), download=True)

vgg16_true.classifier.add_module('add_linear', nn.Linear(1000, 10))# 添加一个线性层   (6): Linear(in_features=4096, out_features=1000, bias=True)
print(vgg16_true)
vgg16_false.add_module('add_linear', nn.Linear(1000, 10))# 修改最后一层的输出为10，out_features=10
print(vgg16_false)


'''
Basic Operations example using TensorFlow library.
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''

import numpy as np
import tensorflow as tf

indices = [0, 3, 7]
depth = 10
one_hot = tf.one_hot(indices, depth)

tf.initialize_all_variables()

with tf.Session() as sess:
    print (sess.run(one_hot))


import argparse
import json

import numpy
import os
from gensim.models import KeyedVectors
from gensim.utils import to_unicode

from Fusion_embedding.src.evaluation.check_pivot_word_neighbors import create_save_pivot
from Fusion_embedding.src.evaluation.vector_space_comparison import create_save_vector_space_comparison
from embedding_vector_similarity.src.embeddings.embeddingmodel import GensimEmbeddingModel
from embedding_vector_similarity.src.post_filtering.postfilters import PostFilters

parser = argparse.ArgumentParser()

parser.add_argument('--vec-1', action='store', dest='vec1_path',
                    help='word2vec model 1', required=True)

parser.add_argument('--vec-2', action='store', dest='vec2_path',
                    help='word2vec model 2', required=True)

parser.add_argument('--min-s', action='store', dest='sim_min', type=float,
                    help='sim_min', required=True)
parser.add_argument('--max-s', action='store', dest='sim_max', type=float,
                    help='sim_max', required=True)
parser.add_argument('--step-s', action='store', dest='sim_steps', type=float,
                    help='sim_steps', required=True)

parser.add_argument('--terms', action='store', dest='terms_path',
                    help='query term list', required=True)

parser.add_argument('--out', action='store', dest='out_path',
                    help='output folder', required=True)

parser.add_argument('--out-eval', action='store', dest='out_eval_path',
                    help='output folder', required=True)

parser.add_argument('--name', action='store', dest='name',
                    help='run nam', required=True)

args = parser.parse_args()

#
# query terms
#
query_term_list = open(args.terms_path, 'r').read().splitlines()
for i in range(len(query_term_list)):
    query_term_list[i] = to_unicode(query_term_list[i])
query_term_list = list(set(query_term_list))  # remove duplicates

#
# gensim models
#
model1 = KeyedVectors.load_word2vec_format(args.vec1_path, binary=False)
model2 = KeyedVectors.load_word2vec_format(args.vec2_path, binary=False)

embedding1 = GensimEmbeddingModel()
embedding1.load_model_in_memory(model1, '')

embedding2 = GensimEmbeddingModel()
embedding2.load_model_in_memory(model2, '')

print(args.vec1_path)
print(args.vec2_path)

#
# eval
#

create_save_vector_space_comparison(base_vectors=embedding1.get_vectors_all(),
                                    experiment_vectors=embedding2.get_vectors_all(),
                                    filename=args.out_eval_path + "all_space_comparison.csv",
                                    name="two_retrofitted")

create_save_pivot(embedding1.word_vectors,
                  embedding2.word_vectors,
                  os.path.join(args.out_eval_path, 'all_pivot_queryterm_'".csv"),
                  "two_retrofitted",
                  query_term_list,
                  numpy.arange(args.sim_min, args.sim_max + 0.0001, args.sim_steps))

pivot_file = open(args.out_eval_path+"all_neighbors_combined.csv", 'w')
pivot_file.write(",v1_weight,v2_weight,neighbor_threshold,,count_total, count_avg\n")

#print("embedding equals: ", numpy.array_equal(embedding1.get_vectors_all(),embedding2.get_vectors_all()))

#
# per threshold - compute similar
#

vec_1_weight = 0.5

for vec_1_weight in numpy.arange(0.1, 0.901, 0.1):

    vec_2_weight = 1 - vec_1_weight

    for filter_value in numpy.arange(args.sim_min, args.sim_max + 0.0001, args.sim_steps):

        term_relterms_withweight1 = embedding1.search_neighbors_cosine(query_term_list, 400)
        term_relterms_withweight2 = embedding2.search_neighbors_cosine(query_term_list, 400)

        result = {}

        for term in term_relterms_withweight1:
            result[term] = [[], []]

            d1 = term_relterms_withweight1[term]
            d2 = term_relterms_withweight2[term]

            if d1[0] == d2[0] and d1[1] == d2[1]:
                print("same result @",term , filter_value,"for:", args.vec2_path)

            for i, sim_term in enumerate(d1[0]):

                sim_score_1 = d1[1][i]
                sim_score_2 = 0

                for t, sim_term_2 in enumerate(d2[0]):
                    if sim_term_2 == sim_term:
                        sim_score_2 = d2[1][i]
                        break

                result[term][0].append(sim_term)
                # arithmetic mean
                result[term][1].append((sim_score_1 * vec_1_weight + sim_score_2 * vec_2_weight)/(vec_1_weight + vec_2_weight))
                # harmonic mean
                #result[term][1].append(pow(
                #    (pow(sim_score_1,-1) * vec_1_weight + pow(sim_score_2, -1) * vec_2_weight)/(vec_1_weight + vec_2_weight),
                #    -1))

        result = PostFilters.filter_embedding_threshold(result, filter_value)

        neighbors = 0
        terms = 0
        sims = 0
        for term, related in result.items():
            terms +=1
            neighbors += len (related[0])
            sims += numpy.sum(related[1])

        #print('avg @',args.vec2_path,vec_1_weight,filter_value,"val: ",neighbors/terms)
        #print('sum @',args.vec2_path,vec_1_weight,filter_value,"val: ",sims)

        #",v1_weight,v2_weight,neighbor_threshold,,count_total, count_avg\n"
        pivot_file.write(os.path.basename(args.vec2_path) + ","+str(vec_1_weight)+ ","+str(vec_2_weight)+
                         "," + str(filter_value) + ",," + str(neighbors)+"," + str(neighbors/terms)+ "\n")

        open(os.path.join(args.out_path,
                          args.name + "w" +
                          str("%0.3f" % vec_1_weight).replace('.', '-') + "_" +
                          str("%0.3f" % filter_value).replace('.', '-') + ".txt"),
             'w') \
            .write(json.dumps(result))


#!/usr/bin/env python
# -*- encoding: utf-8 -*-

import time
import unittest
import HTMLTestRunner
from utils.config import report_path,testcase_path,caselist_path
from utils.e_mail import Email
from utils.log import Logger

class Run_Suite():

    def __init__(self):
        self.caselist = []
        self.log = Logger().get_logger()

    def get_caselist(self):
        with open(caselist_path,'r') as fp:
            for line in fp.readlines():
                data = str(line)
                if data != '' and not data.startswith("#"):
                    self.caselist.append(data.replace("\n", ""))
        return  self.caselist

    def set_case_suite(self):
        test_suite = unittest.TestSuite()
        suite_module = []
        for case in  self.get_caselist():
            case_name = case.split("/")[-1]  # 通过split函数来将aaa/bbb分割字符串，-1取后面，0取前面
            discover = unittest.defaultTestLoader.discover(testcase_path,pattern = case_name + '.py',top_level_dir=None)
            suite_module.append(discover)#将discover存入suite_module元素组

        if len(suite_module) > 0:#判断suite_module元素组是否存在元素
            for suite in suite_module:#如果存在，循环取出元素组内容，命名为suite
                for case_name in suite:#从discover中取出case_name，使用addTest添加到测试集
                    test_suite.addTest(case_name)
        else:
            return None
        return test_suite#返回测试集

    def run_case_suite(self):
        try:
            suit = self.set_case_suite()#调用set_case_suite获取test_suite
            print(str(suit))
            if suit is not None:#判断test_suite是否为空
                now = time.strftime("%Y-%m-%d-%H %M %S", time.localtime(time.time()))
                filename = report_path + "\\" + now + "-" + "ResultReport.html"
                with open(filename, 'wb') as fp:
                    runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title=u"测试报告",
                                                           description=u"测试用例执行的结果", verbosity=2)
                    runner.run(suit)

            else:
                print("没有要执行的测试用例.")
        except Exception as ex:
            print(str(ex))
            self.log.info(str(ex))

        finally:
            print("*********TEST END*********")
            self.log.info(str("*********TEST END*********"))

        e = Email()
        e.send_email()

if __name__ == "__main__":
    c = Run_Suite()
    data = c.run_case_suite()


import unittest
import os
import json
import time
import uuid

from os import environ
from ConfigParser import ConfigParser
from pprint import pprint

from installed_clients.WorkspaceClient import Workspace as workspaceService
from kb_gblocks.kb_gblocksImpl import kb_gblocks

class kb_gblocksTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        token = environ.get('KB_AUTH_TOKEN', None)
        cls.ctx = {'token': token, 'provenance': [{'service': 'kb_gblocks',
            'method': 'please_never_use_it_in_production', 'method_params': []}],
            'authenticated': 1}
        config_file = environ.get('KB_DEPLOYMENT_CONFIG', None)
        cls.cfg = {}
        config = ConfigParser()
        config.read(config_file)
        for nameval in config.items('kb_gblocks'):
            cls.cfg[nameval[0]] = nameval[1]
        cls.wsURL = cls.cfg['workspace-url']
        cls.wsClient = workspaceService(cls.wsURL, token=token)
        cls.serviceImpl = kb_gblocks(cls.cfg)

    @classmethod
    def tearDownClass(cls):
        if hasattr(cls, 'wsName'):
            cls.wsClient.delete_workspace({'workspace': cls.wsName})
            print('Test workspace was deleted')

    def getWsClient(self):
        return self.__class__.wsClient

    def getWsName(self):
        if hasattr(self.__class__, 'wsName'):
            return self.__class__.wsName
        suffix = int(time.time() * 1000)
        wsName = "test_kb_gblocks_" + str(suffix)
        ret = self.getWsClient().create_workspace({'workspace': wsName})
        self.__class__.wsName = wsName
        return wsName

    def getImpl(self):
        return self.__class__.serviceImpl

    def getContext(self):
        return self.__class__.ctx

    def test_kb_gblocks_run_Gblocks_01(self):
        # Prepare test objects in workspace if needed using
        # self.getWsClient().save_objects({'workspace': self.getWsName(), 'objects': []})
        #
        # Run your method by
        # ret = self.getImpl().your_method(self.getContext(), parameters...)
        #
        # Check returned data with
        # self.assertEqual(ret[...], ...) or other unittest methods

        obj_basename = 'gblocks'
        obj_out_name = obj_basename+'.'+"test_output.MSA"
        obj_out_type = 'KBaseTrees.MSA'

        # MSA
        MSA_json_file = os.path.join('data', 'DsrA.MSA.json')
        with open (MSA_json_file, 'r', 0) as MSA_json_fh:
            MSA_obj = json.load(MSA_json_fh)

        provenance = [{}]
        MSA_info = self.getWsClient().save_objects({
            'workspace': self.getWsName(),
            'objects': [
                {
                    'type': 'KBaseTrees.MSA',
                    'data': MSA_obj,
                    'name': 'test_MSA',
                    'meta': {},
                    'provenance': provenance
                }
            ]})[0]

        [OBJID_I, NAME_I, TYPE_I, SAVE_DATE_I, VERSION_I, SAVED_BY_I, WSID_I, WORKSPACE_I, CHSUM_I, SIZE_I, META_I] = range(11)  # object_info tuple
        MSA_ref = str(MSA_info[WSID_I])+'/'+str(MSA_info[OBJID_I])+'/'+str(MSA_info[VERSION_I])

        parameters = { 'workspace_name': self.getWsName(),
		       'desc':           'test_Gblocks',
                       'input_ref':      MSA_ref,
                       'output_name':    obj_out_name,
                       'trim_level':                  "1",
		       'min_seqs_for_conserved':      "0",
		       'min_seqs_for_flank':          "0",
                       'max_pos_contig_nonconserved': "8",
                       'min_block_len':               "10",
                       'remove_mask_positions_flag':  "0"
                     }

        ret = self.getImpl().run_Gblocks(self.getContext(), parameters)[0]
        self.assertIsNotNone(ret['report_ref'])

        # check created obj
        #report_obj = self.getWsClient().get_objects2({'objects':[{'ref':ret['report_ref']}]})[0]['data']
        report_obj = self.getWsClient().get_objects([{'ref':ret['report_ref']}])[0]['data']
        self.assertIsNotNone(report_obj['objects_created'][0]['ref'])

        created_obj_0_info = self.getWsClient().get_object_info_new({'objects':[{'ref':report_obj['objects_created'][0]['ref']}]})[0]
        self.assertEqual(created_obj_0_info[NAME_I], obj_out_name)
        self.assertEqual(created_obj_0_info[TYPE_I].split('-')[0], obj_out_type)

        pass


import random
import pygame

# Initializing Pygame
pygame.init()

# Game window
width, height = 800, 600
window = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Game")

# Colors
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

# properties for building snake
snake_size = 14
snake_speed = 7

# properties for the food
food_size = 20
food_color = BLUE

# Initial position of the snake
x = width // 2
y = height // 2

# Starting velocity
dx = 0
dy = 0

# Food instance
normal_food = None
special_food = None

# Starting position of the food
food_x = random.randint(0, width - food_size)
food_y = random.randint(0, height - food_size)

snake_score = 0
font = pygame.font.Font(None, 24)

snake_segments = []

Time = pygame.time.Clock()
timer_font = pygame.font.Font(None, 16)

def add_segment():
    snake_segments.append((0, 0))

def check_collision():
    if x < 0 or x + snake_size > width or y < 0 or y + snake_size > height:
        return True
    return False

# Timer
start_time = pygame.time.get_ticks()
game_duration = 60  # in secs
food_eaten = 0
max_food_eaten = 10

# Game loop
running = True
Game_over = False
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if not Game_over and event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                dx = -snake_speed
                dy = 0
            elif event.key == pygame.K_RIGHT:
                dx = snake_speed
                dy = 0
            elif event.key == pygame.K_UP:
                dx = 0
                dy = -snake_speed
            elif event.key == pygame.K_DOWN:
                dx = 0
                dy = snake_speed
    if not Game_over:
        current_timing = pygame.time.get_ticks()
        elapsed_timing = (current_timing - start_time) // 1000

        if elapsed_timing >= game_duration:
            Game_over = True

        x += dx
        y += dy

        if x < food_x + food_size and x + snake_size > food_x and y < food_y + food_size and y + snake_size > food_y:
            snake_score += 1
            food_x = random.randint(0, width - food_size)
            food_y = random.randint(0, height - food_size)
            add_segment()

        if len(snake_segments) > 0:
            for i in range(len(snake_segments) - 1, 0, -1):
                snake_segments[i] = snake_segments[i - 1]
            snake_segments[0] = (x, y)

        if check_collision():
            Game_over = True

        window.fill(BLACK)

        pygame.draw.rect(window, GREEN, (x, y, snake_size, snake_size))
        for segment in snake_segments:
            pygame.draw.rect(window, GREEN, (segment[0], segment[1], snake_size, snake_size))

        pygame.draw.rect(window, food_color, (food_x, food_y, food_size, food_size))

        snake_score_text = font.render("Score:" + str(snake_score), True, GREEN)
        window.blit(snake_score_text, (10, 10))

        timer_text = timer_font.render("Time:" + str(game_duration - elapsed_timing), True, GREEN)
        window.blit(timer_text, (10, 30))
        pygame.display.update()
        Time.tick(30)

    else:
        window.fill(BLACK)
        Game_over_text = font.render("Game over", True, GREEN)
        snake_score_text = font.render("Score:" + str(snake_score), True, GREEN)
        window.blit(Game_over_text, (width // 2 - 100, height // 2 - 50))
        window.blit(snake_score_text, (width // 2 - 70, height // 2))
        pygame.display.update()

pygame.quit()


import os
import soco
from evdev import InputDevice, categorize, ecodes

def play(nfc_number):
    print('start play "' + nfc_number + '"')
    try:
        sonos = {
            s for s in soco.discover() if s.player_name == os.environ["SPEAKER"]
        }.pop()
        playlist = next(
            p
            for p in sonos.music_library.get_music_library_information(
                "sonos_playlists"
            )
            if p.title.endswith(nfc_number)
        )
        sonos.unjoin()
        sonos.clear_queue()
        sonos.add_to_queue(playlist)
        sonos.play_from_queue(0)
    except StopIteration:
        print('found no Playlist for "' + nfc_number + '"')

scancodes = {
    2: u"1",
    3: u"2",
    4: u"3",
    5: u"4",
    6: u"5",
    7: u"6",
    8: u"7",
    9: u"8",
    10: u"9",
    11: u"0",
}

def main():
    accumluator = ""
    devicePath = "/dev/input/event0"
    dev = InputDevice(devicePath)
    dev.grab()

    print("Start listining on " + devicePath)
    for event in dev.read_loop():
        if event.type == ecodes.EV_KEY:
            data = categorize(event)
            if data.keystate == 1:
                if data.scancode == 28:
                    play(accumluator)
                    accumluator = ""
                else:
                    accumluator += scancodes.get(data.scancode)

main()


'''
Создайте словарь со списком вещей для похода в качестве ключа и их массой в качестве значения.
Определите какие вещи влезут в рюкзак передав его максимальную грузоподъёмность.
Достаточно вернуть один допустимый вариант.
*Верните все возможные варианты комплектации рюкзака.
'''

dict_items = {'спальник': 2, 'котелок': 3, 'спички': 7, 'палатка': 17, 'фонарик': 2, 'вода': 1, 'стул': 8}
# dict_items = {'спальник': 12, 'котелок': 1, 'спички': 7, 'палатка': 17, 'фонарик': 6, 'вода': 5, 'стул': 7}

SIZE_BACKPACK = 10
list_items_var = list()
list_all_items = list(dict_items.keys())
count_items = len(list_all_items)
list_all_backpack = []

def all_valid_set(current_size, current_list, start, list_all: list) -> list:
    for item in range(start, count_items):

        size = dict_items.get(list_all_items[item])
        if (current_size < SIZE_BACKPACK) and (SIZE_BACKPACK - current_size) >= size:
            current_size += size
            list_items_var.append(list_all_items[item])

        if current_size == SIZE_BACKPACK:
            list_all.append(tuple([current_size, tuple(list_items_var)]))
            list_items_var.pop()
            current_size -= size

    if len(list_items_var) != 0:
        list_all.append(tuple([current_size, tuple(list_items_var)]))
        remove_element = list_items_var.pop()
        next_start = list_all_items.index(remove_element) + 1
        current_size -= dict_items.get(remove_element)
        all_valid_set(current_size, current_list, next_start, list_all)

    return list_all

all_var: list = sorted(all_valid_set(0, list_items_var, 0, list_all_backpack), key=lambda x: x[0], reverse=True)

print(f'любой вариант (вес = {all_var[0][0]}ед):\t {all_var[0][1]}')
if min(list(dict_items.values())) > SIZE_BACKPACK:
    print("все вещи по весу больше чем рюкзак")
elif sum(list(dict_items.values())) <= SIZE_BACKPACK:
    print("все вещи поместятся рюкзак")
else:
    print(f'\nмаксимально возможные варианты загрузки (на {all_var[0][0]} ед):')
    i = 0
    while all_var[i][0] == all_var[0][0]:
        print(all_var[i][1])
        i += 1


#! /usr/bin/env python3

# Michael Gates
# 23 October 2017
# Test suite implementations for lab07

# The parameter intList is supposed to be a list of integers.
# The function returns the product of the odd integers from intList, and leaves intList not modified.
# For instance, given [1,2,3,4], the function returns 3.
# The function performs no I/O.
def productOfOdd(intList):
	# if list is empty
	if(len(intList) <= 0):
		return 0

	last = 1
	for i in intList:
		if(i % 2 != 0):
			last = last * i
	return last

# The parameter intList is supposed to be a list of integers.
# The function returns the sum of the even integers from intList, and leaves intList not modified.
# For instance, given [1,2,3,4], the function returns 6.
# The function performs no I/O.
def sumOfEven(intList):
	# if list is empty
	if(len(intList) <= 0):
		return 0

	sumTotal = 0
	for i in intList:
		if(i % 2 == 0):
			sumTotal = sumTotal + i
	return sumTotal

#The parameter intList is supposed to be a list of integers.
# The function returns a new list containing the even integers from intList, in the same order, and
# leaves intList not modified.
# For instance, given [1,2,3,4,2,3,6], the function returns [2,4,2,6].
# The function performs no I/O.
def evenMembers(intList):
	evenList = []
	for i in intList:
		if(i % 2 == 0):
			evenList.append(i)
	return evenList

# The parameter intList is supposed to be a list of integers.
# The function modifies intList:
# 	● For odd integers one (1) is added and then the result is divided by 2
# 	● Even integers are multiplied by 3.
# This function does not return anything. (void)
# For instance, the parameter [1,2,3,4]  should become [1,6,2,12].
# The function performs no I/O.
def changeList(intList):
	for index, value in enumerate(intList):
		if(value % 2 == 0):
			intList[index] = value*3
		else:
			intList[index] = round((value+1) / 2)

# The parameters intListOne and intListTwo are supposed to be lists of integers.
# The function will return true if intListTwo is the reversed version of intListOne.
# The function will return false if intListTwo is NOT the reversed version of intListOne.
# The function performs no I/O.
def isReverse(intListOne, intListTwo):
	return intListTwo == intListOne[::-1]

def main():
	pass

if __name__ == '__main__':
	main()


# You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
# Merge all the linked-lists into one sorted linked-list and return it.

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def merge2Lists(self, l1, l2):
        head = ListNode()
        p = head
        while l1 and l2:
            if l1.val <= l2.val:
                p.next = l1
                while l1 and l1.val <= l2.val:
                    p = l1
                    l1 = l1.next
            else:
                p.next = l2
                while l2 and l2.val <= l1.val:
                    p = l2
                    l2 = l2.next

        if not l1 and not l2:
            pass
        elif l1:
            p.next = l1
        elif l2:
            p.next = l2

        return head.next

    def mergeKLists(self, lists):
        if len(lists) == 0:
            return None
        if len(lists) == 1:
            return lists[0]
        ls = []
        for i in range(1, len(lists), 2):
            merged = self.merge2Lists(lists[i-1], lists[i])
            ls.append(merged)
        if len(lists) % 2 == 1:
            ls.append(lists[-1])
        result = self.mergeKLists(ls)
        return result

class Solution_0(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        amount = len(lists)
        interval = 1
        while interval < amount:
            for i in range(0, amount - interval, interval * 2):
                lists[i] = self.merge2Lists(lists[i], lists[i + interval])
            interval *= 2
        return lists[0] if amount > 0 else None

    def merge2Lists(self, l1, l2):
        head = point = ListNode(0)
        while l1 and l2:
            if l1.val <= l2.val:
                point.next = l1
                l1 = l1.next
            else:
                point.next = l2
                l2 = l1
                l1 = point.next.next
            point = point.next
        if not l1:
            point.next=l2
        else:
            point.next=l1
        return head.next


# encoding=utf8
"""
    Author:  'jdwang'
    Date:    'create date: 2017-04-07'; 'last updated date: 2017-04-07'
    Email:   '383287471@qq.com'
    Describe:
"""
from __future__ import print_function
from sklearn.metrics import f1_score
import numpy as np

__version__ = '1.0'

def get_evaluate_score(y_true, y_predict):
    accuracy = np.mean(y_true == y_predict)
    print('准确度:%f' % accuracy)
    print('错误个数: %d (总:%d)' % (sum(y_true != y_predict), len(y_true)))
    f1 = f1_score(y_true, y_predict, average=None)
    print('F1 score:', f1)
    return accuracy


import asyncio
import time
import unittest
from collections import deque
from decimal import Decimal
from typing import Union

from hummingbot.client.config.client_config_map import ClientConfigMap
from hummingbot.client.config.config_helpers import ClientConfigAdapter
from hummingbot.connector.test_support.mock_paper_exchange import MockPaperExchange
from hummingbot.core.data_type.common import OrderType, TradeType
from hummingbot.core.data_type.limit_order import LimitOrder
from hummingbot.core.data_type.market_order import MarketOrder
from hummingbot.core.event.events import (
    BuyOrderCompletedEvent,
    BuyOrderCreatedEvent,
    FundingPaymentCompletedEvent,
    MarketEvent,
    MarketOrderFailureEvent,
    OrderCancelledEvent,
    OrderExpiredEvent,
    OrderFilledEvent,
    SellOrderCompletedEvent,
    SellOrderCreatedEvent,
)
from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple
from hummingbot.strategy.strategy_py_base import StrategyPyBase

class MockPyStrategy(StrategyPyBase):

    def __init__(self):
        super().__init__()

        # Used the check the events are recorded
        self.events_queue = deque()

    def did_create_buy_order(self, order_created_event: BuyOrderCreatedEvent):
        self.events_queue.append(order_created_event)

    def did_create_sell_order(self, order_created_event: SellOrderCreatedEvent):
        self.events_queue.append(order_created_event)

    def did_fill_order(self, order_filled_event: OrderFilledEvent):
        self.events_queue.append(order_filled_event)

    def did_fail_order(self, order_failed_event: MarketOrderFailureEvent):
        self.events_queue.append(order_failed_event)

    def did_cancel_order(self, cancelled_event: OrderCancelledEvent):
        self.events_queue.append(cancelled_event)

    def did_expire_order(self, expired_event: OrderExpiredEvent):
        self.events_queue.append(expired_event)

    def did_complete_buy_order(self, order_completed_event: BuyOrderCompletedEvent):
        self.events_queue.append(order_completed_event)

    def did_complete_sell_order(self, order_completed_event: SellOrderCompletedEvent):
        self.events_queue.append(order_completed_event)

    def did_complete_funding_payment(self, funding_payment_completed_event: FundingPaymentCompletedEvent):
        self.events_queue.append(funding_payment_completed_event)

class StrategyPyBaseUnitTests(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.ev_loop = asyncio.get_event_loop()
        cls.trading_pair = "COINALPHA-HBOT"

    def setUp(self):
        self.market: MockPaperExchange = MockPaperExchange(
            client_config_map=ClientConfigAdapter(ClientConfigMap())
        )
        self.market_info: MarketTradingPairTuple = MarketTradingPairTuple(
            self.market, self.trading_pair, *self.trading_pair.split("-")
        )

        self.strategy: StrategyPyBase = MockPyStrategy()
        self.strategy.add_markets([self.market])

    @staticmethod
    def simulate_order_created(market_info: MarketTradingPairTuple, order: Union[LimitOrder, MarketOrder]):
        event_tag = MarketEvent.BuyOrderCreated if order.is_buy else MarketEvent.SellOrderCreated
        event_class = BuyOrderCreatedEvent if order.is_buy else SellOrderCreatedEvent

        market_info.market.trigger_event(
            event_tag,
            event_class(
                int(time.time() * 1e3),
                OrderType.LIMIT if isinstance(order, LimitOrder) else OrderType.MARKET,
                order.trading_pair,
                order.quantity if isinstance(order, LimitOrder) else order.amount,
                order.price,
                order.client_order_id if isinstance(order, LimitOrder) else order.order_id,
                time.time()
            )
        )

    @staticmethod
    def simulate_order_filled(market_info: MarketTradingPairTuple, order: Union[LimitOrder, MarketOrder]):
        market_info.market.trigger_event(
            MarketEvent.OrderFilled,
            OrderFilledEvent(
                time.time(),
                order.client_order_id if isinstance(order, LimitOrder) else order.order_id,
                order.trading_pair,
                TradeType.BUY if order.is_buy else TradeType.SELL,
                OrderType.LIMIT if isinstance(order, LimitOrder) else OrderType.MARKET,
                order.price,
                order.quantity if isinstance(order, LimitOrder) else order.amount,
                Decimal("1")
            )
        )

    @staticmethod
    def simulate_order_failed(market_info: MarketTradingPairTuple, order: Union[LimitOrder, MarketOrder]):
        market_info.market.trigger_event(
            MarketEvent.OrderFailure,
            MarketOrderFailureEvent(
                int(time.time() * 1e3),
                order.client_order_id if isinstance(order, LimitOrder) else order.order_id,
                OrderType.LIMIT if isinstance(order, LimitOrder) else OrderType.MARKET
            )
        )

    @staticmethod
    def simulate_cancel_order(market_info: MarketTradingPairTuple, order: Union[LimitOrder, MarketOrder]):
        market_info.market.trigger_event(
            MarketEvent.OrderCancelled,
            OrderCancelledEvent(
                int(time.time() * 1e3),
                order.client_order_id if isinstance(order, LimitOrder) else order.order_id,
            )
        )

    @staticmethod
    def simulate_order_expired(market_info: MarketTradingPairTuple, order: Union[LimitOrder, MarketOrder]):
        market_info.market.trigger_event(
            MarketEvent.OrderExpired,
            OrderExpiredEvent(
                int(time.time() * 1e3),
                order.client_order_id if isinstance(order, LimitOrder) else order.order_id,
            )
        )

    @staticmethod
    def simulate_order_completed(market_info: MarketTradingPairTuple, order: Union[LimitOrder, MarketOrder]):
        event_tag = MarketEvent.BuyOrderCompleted if order.is_buy else MarketEvent.SellOrderCompleted
        event_class = BuyOrderCompletedEvent if order.is_buy else SellOrderCompletedEvent

        market_info.market.trigger_event(
            event_tag,
            event_class(
                int(time.time() * 1e3),
                order.client_order_id if isinstance(order, LimitOrder) else order.order_id,
                order.trading_pair.split("-")[0],
                order.trading_pair.split("-")[1],
                Decimal("1") if order.is_buy else Decimal("0"),
                Decimal("0") if order.is_buy else Decimal("1"),
                OrderType.LIMIT if isinstance(order, LimitOrder) else OrderType.MARKET,
            )
        )

    @staticmethod
    def simulate_funding_payment_completed(market_info: MarketTradingPairTuple):

        example_rate: Decimal = Decimal("100")

        # Example API response for funding payment details
        response = {
            "symbol": "BTCUSDT",
            "incomeType": "COMMISSION",
            "income": "-0.01000000",
            "asset": "USDT",
            "info": "COMMISSION",
            "time": 1570636800000,
            "tranId": "9689322392",
            "tradeId": "2059192"
        }

        market_info.market.trigger_event(
            MarketEvent.FundingPaymentCompleted,
            FundingPaymentCompletedEvent(
                response["time"],
                market_info.market.name,
                example_rate,
                response["symbol"],
                response["income"]
            )
        )

    def test_did_create_buy_order(self):
        limit_order: LimitOrder = LimitOrder(client_order_id="test",
                                             trading_pair=self.trading_pair,
                                             is_buy=True,
                                             base_currency=self.trading_pair.split("-")[0],
                                             quote_currency=self.trading_pair.split("-")[1],
                                             price=Decimal("100"),
                                             quantity=Decimal("50"))
        self.simulate_order_created(self.market_info, limit_order)

        event = self.strategy.events_queue.popleft()

        self.assertIsInstance(event, BuyOrderCreatedEvent)

    def test_did_create_sell_order(self):
        limit_order: LimitOrder = LimitOrder(client_order_id="test",
                                             trading_pair=self.trading_pair,
                                             is_buy=False,
                                             base_currency=self.trading_pair.split("-")[0],
                                             quote_currency=self.trading_pair.split("-")[1],
                                             price=Decimal("100"),
                                             quantity=Decimal("50"))

        self.simulate_order_created(self.market_info, limit_order)

        event = self.strategy.events_queue.popleft()

        self.assertIsInstance(event, SellOrderCreatedEvent)

    def test_did_fill_order(self):
        limit_order: LimitOrder = LimitOrder(client_order_id="test",
                                             trading_pair=self.trading_pair,
                                             is_buy=False,
                                             base_currency=self.trading_pair.split("-")[0],
                                             quote_currency=self.trading_pair.split("-")[1],
                                             price=Decimal("100"),
                                             quantity=Decimal("50"))

        self.simulate_order_filled(self.market_info, limit_order)

        event = self.strategy.events_queue.popleft()

        self.assertIsInstance(event, OrderFilledEvent)

    def test_did_cancel_order(self):
        limit_order: LimitOrder = LimitOrder(client_order_id="test",
                                             trading_pair=self.trading_pair,
                                             is_buy=True,
                                             base_currency=self.trading_pair.split("-")[0],
                                             quote_currency=self.trading_pair.split("-")[1],
                                             price=Decimal("100"),
                                             quantity=Decimal("50"))

        self.simulate_cancel_order(self.market_info, limit_order)

        event = self.strategy.events_queue.popleft()

        self.assertIsInstance(event, OrderCancelledEvent)

    def test_did_fail_order(self):
        limit_order: LimitOrder = LimitOrder(client_order_id="test",
                                             trading_pair=self.trading_pair,
                                             is_buy=False,
                                             base_currency=self.trading_pair.split("-")[0],
                                             quote_currency=self.trading_pair.split("-")[1],
                                             price=Decimal("100"),
                                             quantity=Decimal("50"))

        self.simulate_order_failed(self.market_info, limit_order)

        event = self.strategy.events_queue.popleft()

        self.assertIsInstance(event, MarketOrderFailureEvent)

    def test_did_expire_order(self):
        limit_order: LimitOrder = LimitOrder(client_order_id="test",
                                             trading_pair=self.trading_pair,
                                             is_buy=False,
                                             base_currency=self.trading_pair.split("-")[0],
                                             quote_currency=self.trading_pair.split("-")[1],
                                             price=Decimal("100"),
                                             quantity=Decimal("50"))

        self.simulate_order_expired(self.market_info, limit_order)

        event = self.strategy.events_queue.popleft()

        self.assertIsInstance(event, OrderExpiredEvent)

    def test_did_complete_buy_order(self):
        limit_order: LimitOrder = LimitOrder(client_order_id="test",
                                             trading_pair=self.trading_pair,
                                             is_buy=True,
                                             base_currency=self.trading_pair.split("-")[0],
                                             quote_currency=self.trading_pair.split("-")[1],
                                             price=Decimal("100"),
                                             quantity=Decimal("50"))

        self.simulate_order_completed(self.market_info, limit_order)

        event = self.strategy.events_queue.popleft()

        self.assertIsInstance(event, BuyOrderCompletedEvent)

    def test_did_complete_sell_order(self):
        limit_order: LimitOrder = LimitOrder(client_order_id="test",
                                             trading_pair=self.trading_pair,
                                             is_buy=False,
                                             base_currency=self.trading_pair.split("-")[0],
                                             quote_currency=self.trading_pair.split("-")[1],
                                             price=Decimal("100"),
                                             quantity=Decimal("50"))

        self.simulate_order_completed(self.market_info, limit_order)

        event = self.strategy.events_queue.popleft()

        self.assertIsInstance(event, SellOrderCompletedEvent)

    def test_did_complete_funding_payment(self):
        self.simulate_funding_payment_completed(self.market_info)

        event = self.strategy.events_queue.popleft()

        self.assertIsInstance(event, FundingPaymentCompletedEvent)