# https://leetcode.com/problems/stock-price-fluctuation/
# tags: #data_stream, #design, #google, #hash_table, #heap, #ordered_set
#
# Solution: Heap + Dictionary
# Designing the class we will initialize the following variables:
# * current_timestamp: Latest timestamp based on the data stream.
# * timestamp_price: Dictionary which will store the latest value per timestamp coming from the data stream.
# * min_prices, max_prices: min/max heaps respectively to store (price, timestamp) tuples sorted by price.
# In the update function, we will update the timestamp price and insert (price, timestamp) in both
# the min and max heap to keep track of the min/max values
# Eventually, when minimum or maximum method is called we will retrieve the first value
# of the heap accordingly, if the value is not the latest value that came from the stream
# then we remove that value from the heap.
# Time complexity : O(n*log(n)), Space complexity: O(n)
import heapq

class StockPrice:

    def __init__(self):
        self.current_timestamp = None
        self.timestamp__price = dict()
        self.min_prices = []  # heap
        self.max_prices = []  # heap

    def update(self, timestamp: int, price: int) -> None:
        if not self.current_timestamp or self.current_timestamp < timestamp:
            self.current_timestamp = timestamp

        heapq.heappush(self.min_prices, (price, timestamp))
        heapq.heappush(self.max_prices, (-price, timestamp))

        self.timestamp__price[timestamp] = price

    def current(self) -> int:
        return self.timestamp__price.get(self.current_timestamp, 0)

    def minimum(self) -> int:
        price, timestamp = self.min_prices[0]

        while price != self.timestamp__price[timestamp]:
            heapq.heappop(self.min_prices)
            price, timestamp = self.min_prices[0]

        return price

    def maximum(self) -> int:
        price, timestamp = self.max_prices[0]

        while -price != self.timestamp__price[timestamp]:
            heapq.heappop(self.max_prices)
            price, timestamp = self.max_prices[0]

        return -price

if __name__ == '__main__':
    sp = StockPrice()
    sp.update(1, 10)
    sp.update(2, 5)
    print(sp.current())  # 5
    print(sp.maximum())  # 10
    sp.update(1, 3)
    print(sp.maximum())  # 5
    sp.update(4, 2)
    print(sp.minimum())  # 2


"""
https://www.hackerrank.com/challenges/closest-numbers/problem
"""

def closestNumbers(arr):
    arr.sort()
    pairs = []
    absDiff = abs(arr[0] - arr[1])
    for num in range(len(arr) - 1):
        newAbsDiff = abs(arr[num] - arr[num + 1])
        if newAbsDiff < absDiff:
            pairs = [arr[num], arr[num + 1]]
            absDiff = newAbsDiff
        elif newAbsDiff == absDiff:
            pairs.append(arr[num])
            pairs.append(arr[num + 1])

    return pairs


import asyncio
import json
from asyncio import AbstractEventLoop
from typing import AsyncIterator, Callable

import aioredis
import pytest
import pytest_asyncio
from aioredis import Redis
from elasticsearch import AsyncElasticsearch
from elasticsearch.helpers import async_bulk
from httpx import AsyncClient

from db import elastic
from db import redis
from db.elastic import AsyncSearchEngine
from main import app
from tests.functional.config import get_settings
from tests.functional.testdata.films import es_film_works_data
from tests.functional.testdata.genres import es_genres_data
from tests.functional.testdata.persons import es_persons_data
from tests.functional.utils.helpers import get_es_fw_bulk_query

conf = get_settings()

async def create_index(es, index_name, index_json_path):
    """Создает индекс в случае его отсутствия."""
    if not await es.indices.exists(index=index_name):
        with open(index_json_path, 'r') as index_file:
            index_dict = json.load(index_file)
            await es.indices.create(
                index=index_name,
                ignore=400,
                **index_dict,
            )

@pytest_asyncio.fixture(scope="session")
async def es_write_data(es_client: AsyncElasticsearch) -> Callable:
    """Фикстура записи данных в es."""

    async def inner(data: list[dict], es_index: str, index_json_path: str):
        """Внутренний метод для записи списка данных одним запросом в es."""
        await create_index(es_client, es_index, index_json_path)
        await async_bulk(
            es_client,
            get_es_fw_bulk_query(
                data,
                es_index,
                conf.SEARCH_ENGINE_ID_FIELD_NAME,
            ),
        )

    return inner

@pytest_asyncio.fixture(scope="session")
async def es_client() -> AsyncSearchEngine:
    """Фикстура соединения с es."""
    client = AsyncElasticsearch(hosts=[f'http://{conf.SEARCH_ENGINE_HOST}:{conf.SEARCH_ENGINE_PORT}'])
    yield client
    await client.close()

@pytest_asyncio.fixture(scope="session")
async def redis_pool() -> AsyncIterator[Redis]:
    """Фикстура соединения с redis."""
    pool = aioredis.from_url(
        f"redis://{conf.CACHE_HOST}:{conf.CACHE_PORT}", encoding="utf-8", decode_responses=True
    )
    yield pool
    await pool.close()

@pytest_asyncio.fixture
async def redis_flushall(redis_pool):
    """Фикстура, удаляющая кеш редиса."""
    await redis_pool.flushall()

@pytest.fixture(scope="session")
def event_loop() -> AbstractEventLoop:
    """Фикстура главного цикла событий."""
    loop = asyncio.get_event_loop()
    yield loop
    loop.close()

@pytest.fixture(scope="session")
def api_client(event_loop: AbstractEventLoop, es_client: AsyncElasticsearch, redis_pool: Redis) -> AsyncClient:
    """Фикстура апи-клиента с моком es и redis."""
    elastic.es = es_client
    redis.cache = redis_pool
    client = AsyncClient(app=app, base_url=conf.BASE_URL)
    yield client
    event_loop.run_until_complete(client.aclose())

@pytest_asyncio.fixture(scope="session")
async def film_works_api_client(api_client: AsyncClient, es_write_data: Callable) -> AsyncClient:
    """Фикстура апи-клиента с заполненными данными es для тестирования фильмов."""
    await es_write_data(es_film_works_data, conf.SEARCH_ENGINE_FILM_WORKS_INDEX,
                        conf.SEARCH_ENGINE_FILM_WORKS_INDEX_FILE)
    yield api_client

@pytest_asyncio.fixture(scope="session")
async def persons_api_client(
        api_client: AsyncClient,
        es_write_data: Callable,
        film_works_api_client: AsyncClient,
) -> AsyncClient:
    """Фикстура апи-клиента с заполненными данными es для тестирования участников фильма."""
    await es_write_data(es_persons_data, conf.SEARCH_ENGINE_PERSONS_INDEX, conf.SEARCH_ENGINE_PERSONS_INDEX_FILE)
    yield api_client

@pytest_asyncio.fixture(scope="session")
async def genres_api_client(api_client: AsyncClient, es_write_data: Callable) -> AsyncClient:
    """Фикстура апи-клиента с заполненными данными es для тестирования жанров."""
    await es_write_data(es_genres_data, conf.SEARCH_ENGINE_GENRES_INDEX, conf.SEARCH_ENGINE_GENRES_INDEX_FILE)
    yield api_client


import tensorflow as tf

def conv2d(x, kernel, out_channels,name):
    input_channels = x.get_shape()[-1]
    # strides=[1,x_movement,y_movement,1]
    with tf.variable_scope(name):
        w = tf.get_variable(name='weights',
                            shape=[kernel[0], kernel[1], input_channels, out_channels],
                            initializer=tf.truncated_normal_initializer(stddev=0.1,dtype=tf.float32))
        b = tf.get_variable(name='biases',
                            shape=[out_channels],
                            initializer=tf.constant_initializer(0.1))
    return tf.nn.relu(tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME') + b)

def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

def FC_layer(input_image, out_nodes, name):
    shape = input_image.get_shape()
    if (len(shape) == 4):
        size = shape[1].value * shape[2].value * shape[3].value
    else:
        size = shape[-1].value

    with tf.variable_scope(name):
        w = tf.get_variable('weights',
                            shape=[size, out_nodes],
                            initializer=tf.contrib.layers.xavier_initializer())
        b = tf.get_variable('biases',
                            shape=[out_nodes],
                            initializer=tf.constant_initializer(0.0))
        flat_x = tf.reshape(input_image, [-1, size])
        x = tf.nn.bias_add(tf.matmul(flat_x, w), b)
        x = tf.nn.relu(x)
        return x

def net(image, num_class):
    with tf.name_scope('alex_net'):
        with tf.name_scope('floor_1'):
            conv1 = conv2d(image,[5,5],32,name="conv1")
            pool1 = max_pool_2x2(conv1)
        with tf.name_scope('floor_2'):
            conv2 = conv2d(pool1,[5,5],64,name="conv2")
            pool2 = max_pool_2x2(conv2)
        with tf.name_scope('fc'):
            fc_1 = FC_layer(pool2, 1024, "fc1")
            fc_1_drop_out = tf.nn.dropout(fc_1,0.5)
            softmax_linear = FC_layer(fc_1_drop_out, num_class, 'soft_max')
        return softmax_linear


from PyQt5.QtCore import QObject
from model.ConfigParser.ConfigParserPostToGroup.ConfigParserPostToGroup import ConfigParser
from model.ActionsDelayer.ActionDelayer import ActionDelayer
from model.ConfigParser.ConfigContainerPostToGroup.ConfigContainerPostToGroup import ConfigContainerPostToGroup
from model.SplashScreen.SplashScreen import SplashScreen
from model.VkSessionData.VkSessionData import VkSessionData
from model.VkSessionData.VkSessionDataConfigurator import VkSessionDataConfigurator
from model.Messages.AcceptLeaveApp import AcceptLeaveApp
from model.VkAuthorizationModel.VkAuthorizationModel import VkAuthorizationModel
from model.StartChoiceModel.StartChoiceModel import StartChoiceModel
from model.LiableAboutView.LiableAboutView import LiableAboutView
from model.ChosePostForEdit.ChosePostForEditModel import ChosePostForEditModel
from model.PostToGroup.PostToGroupModel import PostToGroupModel
from model.EditPost.EditPostModel import EditPostModel
from model.ExceptionHandler.ExceptionHandler import ExceptionHandler
from model.ExceptionSignalsBinder.ExceptionSignalsBinder import ExceptionSignalsBinder
from view.Exceptions.ExceptionWarning import ExceptionWarning
from model.ActionBinder import ActionBinder
from model.ActionExecturors.ActionExecutor import ActionExecutor
from model.ActionExecturors.EditContainersQueueExecutor import EditContainersQueueExecutor
from model.ActionExecturors.HurriedlyQueueExecutor import HurriedlyQueueExecutor
from model.ActionExecturors.LeisurelyQueueExecutor import LeisurelyQueueExecutor
from model.ActionExecturors.VkOperator import VkOperator
from model.ActionMaker.ActionMaker import ActionMaker
from model.Containers.ActionQueue.ActionQueue import ActionQueue
from model.Containers.GroupContainer.GroupContainer import GroupContainer
from model.Containers.GroupContainer.GroupContainerWithQImages import GroupContainerWithQImages
from model.Containers.PostContainer.PostContainer import PostContainer
from model.Containers.PostContainer.PostContainerWithQImages import PostContainerWithQImages
from model.PhotoManager.PhotoManager import PhotoManager
from model.StorageOperator.StorageOperator import StorageOperator
from model.Containers.PhotoCompliancesContainer import PhotoCompliancesContainer
from model.ConfigParser.ConfigContainerPostToGroup.ConfigContainerVkOpererations import ConfigContainerVkOperations
from model.ConfigParser.ConfigParserPostToGroup.ConfigParserVkOperGathering import ConfigParserVkOperationGathering
from model.SettingsManager.SettingsManager import SettingsManager
from model.Settings.SettingsModel import SettingsModel
from model.Logger.Logger import MyLogger
from model.ProgressBinder.ProgressBinder import ProgressBinder
from model.Containers.SendingsContainer import SendingsContainer
import sys,shelve,webbrowser

from datetime import datetime

from PyQt5.QtWidgets import QApplication

class MainStarter(QObject):

    def __init__(self,logger, app):
        super(MainStarter, self).__init__()
        self.__start_timestamp = str(int(datetime.timestamp(datetime.now())))
        self.save_start_timestamp()

        self.create_splash_screen()
        self.__splash_screen.show()

        for i in range(10_000):  # Need to show splash -> dirty hack from stack overflow ) but it works as expected !
            app.processEvents()

        self.__logger = logger
        self.__action_maker = None
        self.create_auxiliary_elements()
        self.__start_choice_model.show()
        self.__splash_screen.hide()

        self.create_messages_and_warnings()
        self.check_existing_of_token()

    def accept_exit(self):
        if self.__accept_leave_app.exec() == AcceptLeaveApp.Ok:
            return False
        return True

    def create_messages_and_warnings(self):
        self.__accept_leave_app = AcceptLeaveApp()

    def snapping_signals(self):
        self.__vk_authorization_model.token_recieved_signal.connect \
            (self.__vk_session_data_configurator.update_session_data_container_with_new_token)
        self.__vk_authorization_model.token_recieved_signal.connect(self.__vk_authorization_model.hide)
        self.__vk_authorization_model.auth_window_closed.connect(self.__vk_authorization_model.hide)
        self.__vk_authorization_model.auth_window_closed.connect(self.check_existing_of_token)
        self.__vk_operator.action_has_done.connect(self.__leisurely_queue_executor.last_action_has_executed)
        self.__vk_operator.action_has_done.connect(self.__leisurely_queue_executor.increment_action_has_done)
        self.__vk_operator.action_has_done.connect(self.__leisurely_queue_executor.notify_suscribers_about_changes_of_amount)
        self.__vk_operator.action_has_failed.connect(self.__leisurely_queue_executor.increment_action_has_failed)
        self.__vk_operator.action_has_failed.connect(
            self.__leisurely_queue_executor.notify_suscribers_about_changes_of_amount)
        self.__vk_operator.action_has_failed.connect(self.__leisurely_queue_executor.last_action_has_executed)
        self.__vk_operator.update_resend_button_state.connect(self.__post_to_group_model.append_resend_by_post)
        self.__settings_model.update_settings.connect(self.__config_parser_vk_operations.update_values)
        self.__start_choice_model.change_account.connect(self.get_token)
        self.__vk_operator.actions_delayed.connect(self.__action_delayer.write_all_action_to_file)
        self.__post_to_group_model.recover_actions_clicked.connect(self.__action_delayer.read_actions_from_file)
        self.__post_to_group_model.btn_helper_clecked.connect(self.start_helper)

        self.__vk_operator.uploaded_thread.need_to_upload_photos.connect(self.__post_to_group_model.show_start_upload_image)
        self.__vk_operator.uploaded_thread.data_have_uploaded_to_vk.connect(self.__post_to_group_model.hide_start_upload_image)

    def start_helper(self):
        webbrowser.open("https://github.com/SokolnikSergey/VkPoster/wiki")

    def inform_relogin_if_user_blocked(self, vk_api):
        try:
            vk_api.users.account.getInfo(v="5.81")
        except Exception as ex:
            if str(ex).split(".")[0] == '5':
                self.__accept_leave_app.set_texts("The account is blocked by VK", "Start another authorization?")
                self.show_get_token_or_exit()

    def check_existing_of_token(self):
        self.inform_relogin_if_user_blocked(self.__vk_session_data.vk_api)
        token = self.__vk_session_data.token
        if not token:
            self.__accept_leave_app.set_texts("Application doesn't work without signed in account", "Start authorization?")
            self.show_get_token_or_exit()

    def get_token(self):
        self.__vk_authorization_model.show()
        self.__vk_authorization_model.start_authorization()

    def show_get_token_or_exit(self):
        if self.accept_exit():
            sys.exit()
        else:
            self.get_token()
###############################################################

    def save_start_timestamp(self):
        with open('../AuxElements/start_timestamp', 'w') as f:
            f.write(self.__start_timestamp)

    def create_auxiliary_elements(self):
        self.__handlder_ex = ExceptionHandler()

        self.create_config_container()
        self.create_config_parser()
        self.create_settings_manager()

        self.create_vk_session_data()
        self.create_vk_session_data_configurator(self.__vk_session_data)
        self.create_containers()
        self.create_action_executors(self.__vk_session_data)
        self.create_models()
        self.create_exceptions()
        self.create_liable_about_view()
        self.create_action_binder()
        self.create_progress_binders()
        self.create_action_delayer()
        self.snapping_signals()
        self.create_and_bind_handlers()

        self.__logger.info("APP successfully started!")

    def create_progress_binders(self):
        self.__progress_binder = ProgressBinder(self.__start_choice_model,self.__post_to_group_model,
                                                self.__leisurely_queue_executor)

    def create_splash_screen(self):
        self.__splash_screen = SplashScreen("../AuxElements/hqdefault.jpg")

    def create_vk_authhorization(self):
        self.__vk_authorization_model = VkAuthorizationModel(self.__config_container.application_id)

    def create_settings_manager(self):
        self.__settings_manager = SettingsManager(self.__config_container_vk_operations)

    def create_exceptions(self):
        self.__warning_message = ExceptionWarning("")

    def create_and_bind_handlers(self):
        self.__ex_signals_binder = ExceptionSignalsBinder\
            (self.__handlder_ex,self.__post_to_group_model, self.__chose_post_for_edit,self.__edit_post_model,
             self.__liable_about_view,self.__warning_message,self.__vk_operator)

    def create_action_delayer(self):
        self.__action_delayer = ActionDelayer(self.__actions_queue)

    def create_models(self):

        self.create_start_choice_model()
        self.create_settings_model()
        self.create_post_to_group()
        self.create_chose_post_for_edit()
        self.create_edit_post_model()
        self.create_vk_authhorization()

    def create_start_choice_model(self):
        self.__start_choice_model  = StartChoiceModel(self.__logger,self.__vk_session_data)

    def create_settings_model(self):
        self.__settings_model = SettingsModel(self.__config_container_vk_operations.country_number,
                                  self.__config_container_vk_operations.max_amount_of_groups,
                                  self.__config_container_vk_operations.min_amount_users_in_group,
                                  self.__config_container_vk_operations.timeout,
                                  self.__config_container_vk_operations.each_to_each,
                                  self.__config_container_vk_operations.limit_reached_just_once)

    def create_post_to_group(self):
        self.__post_to_group_model = PostToGroupModel(PostContainerWithQImages([]),
                                GroupContainerWithQImages([]), self.__post_container,self.__group_container,
                              self.__sending_container, self.__photo_manager.compliances_container, self.__action_maker)

    def create_chose_post_for_edit(self):
        self.__chose_post_for_edit = ChosePostForEditModel(PostContainerWithQImages([]),
                                                           self.__post_container)

    def create_edit_post_model(self):
        self.__edit_post_model = EditPostModel(self.__posts_db)

    def create_action_executors(self,session_data):
        self.__photo_manager = PhotoManager(self.__logger,self.__config_container.photo_complience_path,
                            self.__vk_session_data,PhotoCompliancesContainer([],[]),session_data.album_id )

        self.__vk_operator = VkOperator(self.__logger,self.__vk_session_data,self.__group_container,
        session_data.vk_api,self.__photo_manager,self.__sending_container, self.__config_container_vk_operations )

        self.__posts_db = shelve.open(self.__config_container.post_container_path)
        self.__action_executor = ActionExecutor(self.__vk_operator,StorageOperator(self.__logger,
                    self.__post_container,self.__posts_db))

        self.__hurriedly_queue_executor = HurriedlyQueueExecutor(
            self.__actions_queue,[],self.__action_executor)

        self.__leisurely_queue_executor = LeisurelyQueueExecutor(
            self.__actions_queue, [], self.__action_executor)

        self.__edit_container_queue_executor = EditContainersQueueExecutor(
            self.__actions_queue, [], self.__action_executor)

    def create_containers(self):

        self.__sending_container = SendingsContainer(current_start_timestamp=self.__start_timestamp)
        self.__post_container = PostContainer([])
        self.__group_container = GroupContainer([])
        self.__actions_queue = ActionQueue([],[],[])

    def create_action_binder(self):
        self.__action_maker = ActionMaker(self.__actions_queue,self.__config_container_vk_operations.timeout,0,0)
        self.__post_to_group_model.action_maker = self.__action_maker # dirty hack :(
        self.__action_binder = ActionBinder(self.__post_to_group_model,self.__chose_post_for_edit,
                                            self.__edit_post_model,self.__action_maker)

    def create_liable_about_view(self):
        self.__liable_about_view = LiableAboutView(self.__settings_model, self.__start_choice_model,
                                    self.__post_to_group_model,self.__chose_post_for_edit,
                                            self.__edit_post_model,self.__warning_message)

    def create_config_container(self):
        self.__config_container = ConfigContainerPostToGroup()
        self.__config_container_vk_operations = ConfigContainerVkOperations()

    def create_config_parser(self):
        self.__config_parser = ConfigParser("../AuxElements/in.ini", self.__config_container)
        self.__config_parser_vk_operations = ConfigParserVkOperationGathering("../AuxElements/vk_settings.ini",
                                                                self.__config_container_vk_operations)

    def create_vk_session_data(self):
        self.__vk_session_data = VkSessionData()

    def create_vk_session_data_configurator(self, session_data_container):
        self.__vk_session_data_configurator = VkSessionDataConfigurator(self.__logger,session_data_container
                                                                        , "../AuxElements/token.bin")

app = QApplication(sys.argv)
MyLogger.PATH_TO_FILE = '../AuxElements/logger'
logger = MyLogger()
try:
    starter = MainStarter(logger, app)
except Exception as ex:
    logger.exception(ex)
sys.exit(app.exec_())


# Author J'yrens Christenvie , Please acknowledge the author if you are using his code for your game

import pygame

class Ship:
    """A class to manage a ship behavior """

    def __init__(self,tg_game):
        """Initialize the ship and set its starting position """
        # Take the screen settings and its rectangle
        self.settings = tg_game.settings
        self.screen = tg_game.screen
        self.screen_rect = self.screen.get_rect()

        # loading the ship and getting its rectangle
        self.ship_image = pygame.image.load("images/ship2.bmp")
        self.ship_image_rect = self.ship_image.get_rect()

        # start each new ship at the left side of the screen
        self.ship_image_rect.bottom = self.screen_rect.bottom

        #store decimal position of the ship y value
        self.y = float(self.ship_image_rect.y)

        #flag movement
        self.moving_up = False
        self.moving_down =False

    def update(self):
        """Update the ship position based on the movement's flag """
        if self.moving_up and self.ship_image_rect.top >= 0:
            self.y  -=self.settings.ship_speed
        if self.moving_down and self.ship_image_rect.bottom <= self.screen_rect.bottom :
            self.y  +=self.settings.ship_speed

        self.ship_image_rect.y = self.y

    def blitme(self):
        """Draw the ship at its current location """
        self.screen.blit(self.ship_image,self.ship_image_rect)

    def center_ship(self):
        """center the ship """
        self.ship_image_rect.midleft = self.screen_rect.midleft
        self.y = float(self.ship_image_rect.y)


"""
Quick Sort implementation: Recursive way

Time complexity:  O(nlogn) and worst O(n2)
Space complexity: O(n)

The logic implemented here takes the 'pivot' value as the first element in the given input list

"""

def QuickSort(alist):
    quicksorthelper(alist, 0, len(alist)-1)

    return alist

def quicksorthelper(alist, first, last):
    if first < last:
        splitpos = partition(alist, first, last)

        quicksorthelper(alist, first, splitpos-1)
        quicksorthelper(alist, splitpos+1, last)

def partition(alist, first, last):

    pivotvalue = alist[first]

    left = first + 1
    right = last

    done = False
    while not done:

        while left <= right and alist[left] <= pivotvalue:
            left += 1

        while alist[right] >= pivotvalue and right >= left:
            right -= 1

        if right < left:
            done = True
        else:
            alist[left], alist[right] = alist[right], alist[left]

    alist[first], alist[right] = alist[right], alist[first]

    return right

if __name__ == "__main__":

        print(QuickSort([9, 10, 1, 3, 7, 8, 5, 6, 4, 2]))


from .stats import (
    compute_year_histogram,
    compute_author_histogram,
    compute_author_affiliation_histogram,
    compute_language_histogram,
    compute_number_authors_histogram,
    compute_source_histogram,
    compute_source_type_histogram,
    compute_affiliation_histogram,
    compute_country_histogram,
    compute_continent_histogram,
    compute_groups_histogram,
)
from .nlp import (
    generate_topic_cloud,
    calculate_embedding,
    compute_word_distribution,
    TopicModel,
    Corpus,
)
from .types import DocumentSet
import inspect
import math
import matplotlib.pyplot as plt
import numpy as np
import seaborn
import pandas as pd

def plot_histogram(
    data: pd.DataFrame,
    keys=None,
    title="",
    xlabel="",
    ylabel="",
    label_rotation=None,
    vertical=False,
    bar_width=0.8,
    max_label_length=100,
    stacked=False,
    legend=True,
    relative_to=None,
    ax=None,
):
    """
    This is the general function to plot a histogram (bar plot). All other
    `plot_*_histogram` functions in this module will call this function.

    This function takes a pandas `DataFrame`. Each column represents one
    group and a sequence of bars that will be plotted. The names in the index
    are placed as labels on the axis.

    For instance, a possible input could be
    data frame where the columns are different authors, rows are different
    years, and values are the number of publications per year per author.

    :param ax: The `matplotlib` `Axes` instance the plot will be drawn on. If
               `None`, the current `Axes` instance is used (`plt.gca()`).
    :param vertical: Default bars are horizontal (left to right). Set
                     `vertical=True` for vertical bars (bottom to top).
    :param bar_width: Width of bars. Should be at most `1.0` for 100%.
    :param label_rotation: Rotates the xlabels. This is useful if
                           `vertical=True` since it can be used to place the
                           labels horziontal (`label_rotation=0`), vertical
                           (`label_rotation=90`), or diagonal
                           (`label_rotation=45`).
    :param max_label_length: Labels longer than this length are shortened.
    :param stacked: By default, different groups are drawn next to each other.
                    If `True`, the different groups are stacked on top of each
                    other instead.
    :param legend: Show legend.
    :param relative_to: If not `None`, all bars will be plotted as a
                        percentage relative to this value.
    :param title: Title of plot (set using `ax.set_title`).
    :param xlabel: Title on the X axis (or Y axis if `vertical=True`).
    :param ylabel: Title on the Y axis (or X axis if `vertical=True`).
    """
    if ax is None:
        ax = plt.gca()

    if label_rotation is None:
        if vertical:
            label_rotation = 90
        else:
            label_rotation = 0

    if not ylabel:
        if relative_to is not None:
            ylabel = "% of documents"
        else:
            ylabel = "No. of documents"

    if not vertical:
        ax.grid(visible=False, which="both", axis="y")
        xlabel, ylabel = ylabel, xlabel
    else:
        ax.grid(visible=False, which="both", axis="x")

    if title:
        ax.set_title(title)

    if xlabel:
        ax.set_xlabel(xlabel)

    if ylabel:
        ax.set_ylabel(ylabel)

    if keys is None:
        keys = list(data.index)

    n = len(keys)
    groups = list(data)

    if not groups or not keys:
        return

    bar_bottom = np.array([0] * len(keys))

    for i, group in enumerate(groups):
        ys = data[group]
        bottom = bar_bottom

        if relative_to is not None:
            ys = ys / relative_to * 100

        if stacked:
            bar_bottom = bar_bottom + ys
            xs = np.arange(n) - 0.5 * bar_width
            bin_width = bar_width
        else:
            bin_width = bar_width / len(groups)
            xs = np.arange(n) + i * bin_width - 0.5 * bar_width

        if not vertical:
            ax.barh(xs, ys, label=group, height=bin_width, left=bottom, align="edge")
        else:
            ax.bar(xs, ys, label=group, width=bin_width, bottom=bottom, align="edge")

    if legend and len(groups) > 1:
        ax.legend()

    def shorten(label):
        label = str(label)
        n = max_label_length
        return label[:n] + "..." if len(label) > n else label

    labels = list(map(shorten, keys))

    if not vertical:
        ax.set_ylim((n - 0.5, -0.5))
        ax.set_yticks(range(n))
        ax.set_yticklabels(labels, rotation=label_rotation)
    else:
        ax.set_xlim((-0.5, n - 0.5))
        ax.set_xticks(range(n))
        ax.set_xticklabels(labels, rotation=label_rotation, ha="right")

    return ax

def wrapper(docs, fun, default, **kwargs):
    for key, value in default.items():
        kwargs.setdefault(key, value)

    plot_kwargs = dict()
    params = inspect.signature(plot_histogram).parameters

    for key in list(kwargs):
        if key in params:
            plot_kwargs[key] = kwargs.pop(key)

    if kwargs.pop("relative", False):
        plot_kwargs["relative_to"] = len(docs)

    data = fun(docs, **kwargs)
    return plot_histogram(data, **plot_kwargs)

def plot_groups_histogram(docs, **kwargs):
    """ """

    def fun(docs, **kwargs):
        return compute_groups_histogram(docs, **kwargs).T

    default = dict(title="Categories")
    return wrapper(docs, fun, default, **kwargs)

def plot_year_histogram(docs: DocumentSet, **kwargs):
    """Plot histogram of the number of documents published in each year.

    :param kwargs: Passed to `plot_histogram`.
    """
    default = dict(title="Year of publications")
    return wrapper(docs, compute_year_histogram, default, **kwargs)

def plot_author_histogram(docs: DocumentSet, **kwargs):
    """Plot histogram of the number of documents published per author.

    :param kwargs: Passed to `plot_histogram`.
    """
    default = dict(title="Authors", limit=25)
    return wrapper(docs, compute_author_histogram, default, **kwargs)

def plot_number_authors_histogram(docs: DocumentSet, **kwargs):
    """Plot histogram of the number of authors per document.

    :param kwargs: Passed to `plot_histogram`.
    """
    default = dict(title="No. of authors")
    return wrapper(docs, compute_number_authors_histogram, default, **kwargs)

def plot_author_affiliation_histogram(docs: DocumentSet, **kwargs):
    """Plot histogram of the number of documents published per author
    affiliation.

    :param kwargs: Passed to `plot_histogram`.
    """
    default = dict(title="Author + Affiliation", limit=25)
    return wrapper(docs, compute_author_affiliation_histogram, default, **kwargs)

def plot_language_histogram(docs: DocumentSet, **kwargs):
    """Plot histogram of the number of documents by language."""
    default = dict(title="Language")
    return wrapper(docs, compute_language_histogram, default, **kwargs)

def plot_source_histogram(docs: DocumentSet, **kwargs):
    """Plot histogram of the number of documents by publication source."""
    default = dict(title="Publication source", limit=25)
    return wrapper(docs, compute_source_histogram, default, **kwargs)

def plot_source_type_histogram(docs: DocumentSet, **kwargs):
    """Plot histogram of the number of documents by publication source
    type.

    :param kwargs: Passed to `plot_histogram`.
    """
    default = dict(title="Publication source type", limit=25)
    return wrapper(docs, compute_source_type_histogram, default, **kwargs)

def plot_affiliation_histogram(docs: DocumentSet, **kwargs):
    """Plot histogram of the number of documents by author affiliation.

    :param kwargs: Passed to `plot_histogram`.
    """
    default = dict(title="Affiliations", limit=25)
    return wrapper(docs, compute_affiliation_histogram, default, **kwargs)

def plot_country_histogram(docs: DocumentSet, **kwargs):
    """Plot histogram of the number of documents by country of author
    affiliation

    :param kwargs: Passed to `plot_histogram`.
    """
    default = dict(title="Countries", limit=25)
    return wrapper(docs, compute_country_histogram, default, **kwargs)

def plot_continent_histogram(docs: DocumentSet, **kwargs):
    """Plot histogram of the number of documents by continent of author
    affiliation.

    :param kwargs: Passed to `plot_histogram`.
    """
    default = dict(title="Continents", limit=25)
    return wrapper(docs, compute_continent_histogram, default, **kwargs)

def plot_word_distribution(corpus: Corpus, *, limit=25, **kwargs):
    """Plot the frequency of the top words in the given corpus.

    :param kwargs: Passed to `plot_histogram`.
    """
    n = len(corpus.frequencies)
    data = compute_word_distribution(corpus, limit=limit)
    return plot_histogram(data, relative_to=n, **kwargs)

def plot_embedding(corpus: Corpus, model: TopicModel, layout=None, ax=None):
    """TODO"""
    if ax is None:
        ax = plt.gca()

    if layout is None:
        layout = calculate_embedding(corpus)

    num_topics = len(model.topic2token)
    best_topic = np.argmax(model.doc2topic.T, axis=0)

    colors = seaborn.color_palette("hls", num_topics)
    colors = np.array(colors)[:, :3] * 0.9  # Mute colors a bit

    for i in range(num_topics):
        indices = best_topic == i
        # label = 'ABCDEFGHIJLMNOPQRSTUVWXYZ'[i]
        label = i + 1

        for j in np.argwhere(indices)[:, 0]:
            x, y = layout[j]
            ax.scatter(
                x,
                y,
                marker="o",
                s=150,
                linewidth=0.5,
                color=colors[i],
                zorder=2 * j,
            )

            ax.text(
                x,
                y,
                label,
                fontsize=6,
                color="1",
                va="center",
                ha="center",
                fontweight="bold",
                zorder=2 * j + 1,
            )

        top_items = model.best_tokens_for_topic(i, limit=3)
        label = f"Topic {label}:" + ", ".join(top_items)

        center = np.median(layout[indices], axis=0)
        ax.text(
            center[0],
            center[1],
            label,
            va="center",
            ha="center",
            color="1",
            backgroundcolor=(0, 0, 0, 0.75),
            zorder=10 * len(best_topic),
        )

    ax.set_aspect("equal")
    ax.set_xticks([])
    ax.set_yticks([])

def plot_topic_clouds(model: TopicModel, *, fig=None, ncols=3, **kwargs):
    """Plot word clouds for each of the topics from the given topic model."""
    if fig is None:
        plt.clf()
        fig = plt.gcf()

    nrows = math.ceil(model.num_topics / float(ncols))

    for i in range(model.num_topics):
        ax = fig.add_subplot(nrows, ncols, i + 1)
        plot_topic_cloud(model, i, ax=ax, **kwargs)

def plot_topic_cloud(model: TopicModel, topic_id: int, *, ax=None, **kwargs):
    """Plot a word cloud for the given topic from the given topic model."""
    if ax is None:
        ax = plt.gca()

    ax.set_xticks([])
    ax.set_yticks([])

    im = generate_topic_cloud(model, topic_id, **kwargs).to_array()
    ax.set_title(f"Topic {topic_id + 1}")
    ax.imshow(im, interpolation="bilinear")

def plot_document_topics(model: TopicModel, document_id: int, *, ax=None):
    if ax is None:
        ax = plt.gca()

    weights = model.document_topics(document_id)

    ax.bar(np.arange(model.num_topics), model.document_topics(document_id))
    ax.set_ylim(0, 1)
    ax.set_ylabel("Relevance")
    ax.set_ylabel("Topics")

    for i, w in enumerate(weights):
        if w > 0.01:
            plt.text(i, w, str(i + 1), ha="center", va="bottom")


# Uses python3
import sys

def get_change(m):
    #write your code here
    output = (m // 10) + ( (m % 10) // 5 + (m % 5) )
    # print('Dimes: ', m//10)
    # print('Nickels', (m%10)//5)
    # print('Pennies', m%5)
    return output

if __name__ == '__main__':
    # m = int(sys.stdin.read())
    input = int(input())
    print(get_change(input))


from sklearn.linear_model import ElasticNet
from sklearn.model_selection import train_test_split
from egeaML.egeaML import DataIngestion

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

raw_data = DataIngestion(
    df='/content/drive/MyDrive/Machine Learning/Bocconi - Feb 2021/Lecture_02/boston.csv',
    col_target='MEDV'
    )

df = raw_data.load_data()

X = raw_data.features()
y = raw_data.target()

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

steps = [
         ('scaler', StandardScaler()),
         ('elasticnet', ElasticNet())
         ]

pipeline = Pipeline(steps)
parameters = {
    'elasticnet__l1_ratio': np.linspace(0, 1, 30), # eta
    }
elastic_cv = GridSearchCV(pipeline, param_grid=parameters)
elastic_cv.fit(X_train, y_train)
r2 = elastic_cv.score(X_test, y_test)

print(f"Tuned ElasticNet Alpha: {elastic_cv.best_params_}")
print(f"Tuned ElasticNet R squared: {r2}")


#!/usr/bin/env python
'''
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000.
'''

import time
import math
from algorithms import factors_list as f

start = time.perf_counter()

t = 0
for a in range(1,10000):
    b = sum(f(a))
    if sum(f(b)) == a and b != a:
            print(a, 'is amicable with', b)
            t += a

print(t)
print(time.perf_counter()-start)


'''
Напишите программу, которая принимает две строки вида “a/b” - дробь с числителем и знаменателем.
Программа должна возвращать сумму и произведение* дробей.
Для проверки своего кода используйте модуль fractions.
'''

def main():

    fraction1_str = str(input("Введите 1-ю дробь: "))
    fraction2_str = str(input("Введите 2-ю дробь: "))

    def process_fractions(fraction1_str, fraction2_str):

        # Преобразуем дроби из строк в числа
        number1, denom1 = map(int, fraction1_str.split("/"))
        number2, denom2 = map(int, fraction2_str.split("/"))

        # Сумма дробей
        sum_fraction_num = number1 * denom2 + number2 * denom1
        sum_fraction_denom = denom1 * denom2
        sum_fraction = (sum_fraction_num, sum_fraction_denom)

        # Произведение дробей
        prod_fraction_num = number1 * number2
        prod_fraction_denom = denom1 * denom2
        prod_fraction = (prod_fraction_num, prod_fraction_denom)

        return sum_fraction, prod_fraction

    sum_fraction, prod_fraction = process_fractions(fraction1_str, fraction2_str)

    print(f"Сумма дробей {fraction1_str} и {fraction2_str} - {sum_fraction[0]}/{sum_fraction[1]}")
    print(f"Произведение дробей {fraction1_str} и {fraction2_str} - {prod_fraction[0]}/{prod_fraction[1]}")

# Старт
if __name__ == "__main__":
    main()


import numpy as np
import onnxruntime
from tqdm import tqdm
import os
from PIL import Image
import argparse
import psutil
import gpizero
import telnetlib as tel
import time

#argument parser
parser = argparse.ArgumentParser(description='EE379K project - Deployment code')
parser.add_argument('--model', type=str, default='mbvn1_e0_f5.onnx', help='Enter model name')

args = parser.parse_args()

# Create Inference session using ONNX runtime
sess = onnxruntime.InferenceSession(args.model)

# Get the input name for the ONNX model
input_name = sess.get_inputs()[0].name
print("Input name  :", input_name)

# Get the shape of the input
input_shape = sess.get_inputs()[0].shape
print("Input shape :", input_shape)

# Mean and standard deviation used for PyTorch models
mean = np.array((0.4914, 0.4822, 0.4465))
std = np.array((0.2023, 0.1994, 0.2010))

def getTelnetPower(SP2_tel, last_power):    #for both devices
    tel_dat = str(SP2_tel.read_very_eager())
    #print("telnet reading:", tel_dat)
    findex = tel_dat.rfind('\n')
    findex2 = tel_dat[:findex].rfind('\n')
    findex2 = findex2 if findex2 != -1 else 0
    ln = tel_dat[findex2: findex].strip().split(',')
    if len(ln) < 2:
        total_power = last_power
    else:
        total_power = float(ln[-2])
    return total_power

SP2_tel = tel.Telnet('192.168.4.1')
DELAY = 0.2

# Label names for CIFAR10 Dataset
label_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
accuracy = 0
total_inference_time = 0
total_power = 0
max_power = -1
# The test_deployment folder contains all 10.000 images from the testing dataset of CIFAR10 in .png format
for filename in tqdm(os.listdir("HW3_files/test_deployment")):
    # Take each image, one by one, and make inference
    with Image.open(os.path.join("HW3_files/test_deployment", filename)).resize((32, 32)) as img:
        last_time  = time.time()
        #print("Image shape:", np.float32(img).shape)
        # For PyTorch models ONLY: normalize image
        input_image = (np.float32(img) / 255. - mean) / std
        # For PyTorch models ONLY: Add the Batch axis in the data Tensor (C, H, W)
        input_image = np.expand_dims(np.float32(input_image), axis=0)
        # For PyTorch models ONLY: change the order from (B, H, W, C) to (B, C, H, W)
        input_image = input_image.transpose([0, 3, 1, 2])

        # Run inference and get the prediction for the input image
        start_time = time.time()
        pred_onnx = sess.run(None, {input_name: input_image})[0]
        total_inference_time += time.time() - start_time()
        # Find the prediction with the highest probability
        top_prediction = np.argmax(pred_onnx[0])

        # Get the label of the predicted class
        pred_class = label_names[top_prediction]
        #true label
        true_class = ''.join([i for i in filename[:-4] if i.isalpha()])

        #accuracy calculation
        if pred_class == true_class:
            accuracy += 1

        #power calculation
        power = getTelnetPower(SP2_tel,power)
        if power > max_power:
            max_power = power
        total_power += power
        #sampling rate = 0.2s
        elapsed = time.time() - last_time
        time.sleep(max(0,DELAY-elapsed))
print("Accuracy: " + str(accuracy/10000))
print("Average Latency: " + str(total_inference_time/10000))
print("Maximum Power Cconsumption: " + str(max_power))
print("Average Energy Consumption: " +str(total_power*DELAY/10000))


import unittest

import torch
import torch.nn as nn
import torch.nn.functional as F

# Ask lazy backend to use Pytorch's JIT as
# lazy backend's executor.
from torch._lazy.ts_backend import init as init_ts_backend

init_ts_backend()

# Handle ORT dependencies.
import onnxruntime as ort  # noqa: E402
from onnxruntime.capi import _pybind_state as C  # noqa: E402

# Set up ORT as torch.jit's sub-executor.
C.register_ort_as_torch_jit_executor()

# Make computation deterministic.
torch.manual_seed(42)
ort.set_seed(1)

class TestOrtLazyTensor(unittest.TestCase):
    def test_elementwise_model(self):
        def run_elementwise_model():
            # A function to test.
            def elementwise_model(x):
                w = x.relu()
                y = w * w + 1.5
                z = y + x
                p = z * x
                q = p.relu()
                return q

            def run(fun, device, x):
                x = torch.tensor(x, device=device, dtype=torch.float32).requires_grad_()
                y = fun(x)
                y.sum().backward()
                return x, y, x.grad

            # Baseline.
            x, y, g_x = run(elementwise_model, "cpu", [-1.0, 2.0])
            # ORT result.
            x_new, y_new, g_x_new = run(elementwise_model, "lazy", [-1.0, 2.0])

            torch.testing.assert_close(x.to("lazy"), x_new)
            torch.testing.assert_close(y.to("lazy"), y_new)
            torch.testing.assert_close(g_x.to("lazy"), g_x_new)

        for _ in range(5):
            run_elementwise_model()

    def test_mnist_model(self):
        def run_mnist_model():
            class MNISTModel(nn.Module):
                def __init__(self):
                    super().__init__()
                    self.conv1 = nn.Conv2d(1, 32, 3, 1, bias=False)
                    self.conv2 = nn.Conv2d(32, 64, 3, 1, bias=False)
                    self.fc1 = nn.Linear(9216, 128, bias=False)
                    self.fc2 = nn.Linear(128, 10, bias=False)

                def forward(self, x):
                    x = self.conv1(x)
                    x = F.relu(x)
                    x = self.conv2(x)
                    x = F.relu(x)
                    x = F.max_pool2d(x, 2)
                    x = torch.flatten(x, 1)
                    x = self.fc1(x)
                    x = F.relu(x)
                    x = self.fc2(x)
                    output = F.log_softmax(x, dim=1)
                    return output

            def run(model, device, x, y):
                for param in model.parameters():
                    param.grad = None
                model.to(device)
                x = x.to(device)
                y = y.to(device)
                output = model(x)
                loss = F.nll_loss(output, y)
                # return loss
                loss.backward()
                return loss, (param.grad for param in model.parameters())

            x = torch.rand((64, 1, 28, 28), dtype=torch.float32)
            y = torch.randint(0, 9, (64,), dtype=torch.int64)
            model = MNISTModel()

            # Baseline.
            loss, grads = run(model, "cpu", x, y)
            # ORT result.
            loss_new, grads_new = run(model, "lazy", x, y)

            print(f"MNIST loss: {loss} (pytorch), {loss_new} (ort).")
            torch.testing.assert_close(loss.to("lazy"), loss_new, rtol=1e-2, atol=1e-5)
            for g, g_new in zip(grads, grads_new):
                torch.testing.assert_close(g.to("lazy"), g_new)

        for _ in range(5):
            run_mnist_model()

if __name__ == "__main__":
    # For a specific model, the first 1 or 2 runs of Pytorch
    # JIT is actual eager mode. As a Pytorch JIT sub-executor,
    # ORT won't be unless we run multiple times. Thus, in each
    # test function, we repeat their core test function multiple times.
    # Here we repeat 5 times because we want to our test similar to
    # training loop.
    # TODO: we should force torch.jit executor to use ORT at the first run.
    unittest.main()


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        """
        Iterative approach
        """
        curr = root

        while curr:
            if val > curr.val:
                curr = curr.right
            elif val < curr.val:
                curr = curr.left
            else:
                return curr

        return None

"""
Recursive approach

curr = root

if not curr:
    return None

if val > curr.val:
    return self.searchBST(curr.right, val)
elif val < curr.val:
    return self.searchBST(curr.left, val)
else:
    return curr

"""


from django import forms
from .models import Loan

class LoanAddForm(forms.ModelForm):

    class Meta:
        model = Loan
        fields = [
            'loan_name',
            'loan_start_date',
            'loan_starting_principal',
            'loan_principal',
            'loan_last_action_date',
            'loan_interest',
            'loan_payment'
        ]

class LoanEmailForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.EmailField()


patients_dobs=['21-01-1998','26-10-1999','12-01-1985']
curr_yr=2022
def get_yob(patients_dobs):
    patients_yobs=[]
    for dob in patients_dobs:
        patients_yobs.append(int(dob.split('-')[2]))
    return patients_yobs

def get_ages(yobs):
    ages =[]
    for yr in yobs:
        ages.append(curr_yr - yr)
    return ages

def get_patient_status(get_yob, get_ages, dobs):
    is_major=[]
    yobs= get_yob(dobs)
    ages= get_ages(get_yob(dobs))
    for age in ages:
        if age >= 18:
            is_major.append(ages)
    return  is_major

print(get_patient_status(get_yob,get_ages ,patients_dobs))


import matplotlib.pyplot as plt
from pylab import rcParams
import numpy as np

class Plot:
    def __init__(self):
        self.temp_c = "skyblue"
        self.sunlight_c = "khaki"
        self.greenhouse_temp_c = "mediumspringgreen"
        self.heating_c = "red"
        self.ventilation_c = "blue"

        self.max_temp_c = "lightcoral"
        self.min_temp_c = "cornflowerblue"
        self.crit_max_temp_c = "firebrick"
        self.crit_min_temp_c = "darkblue"

    def plot(self, world):

        rcParams['figure.figsize'] = 20, 5

        plt.plot(world.H_temp, label='Outside temperature', linewidth='1', color=self.temp_c, linestyle = '-')

        plt.plot([light * max(world.H_greenhouse_temp) for light in world.H_sunlight],
                 label='Sunlight', linewidth='1', color=self.sunlight_c, linestyle = '-')

        plt.plot(world.H_greenhouse_temp, label='Greenhouse temperature', linewidth='1', color=self.greenhouse_temp_c, linestyle = '-')

        plt.plot(world.max_temp, label='Maximum temp', linewidth='1', color=self.max_temp_c, linestyle = '--')
        plt.plot(world.min_temp, label='Minimum temp', linewidth='1', color=self.min_temp_c, linestyle = '--')
        plt.plot(world.crit_max_temp, label='Maximum critical temp', linewidth='1', color=self.crit_max_temp_c, linestyle = '--')
        plt.plot(world.crit_min_temp, label='Minimum critical temp', linewidth='1', color=self.crit_min_temp_c, linestyle = '--')

        # lake below

        heating_plot = self.list_window_averaging(win_len=50, list_to_avg=world.H_greenhouse_heating)
        ventilation_plot = self.list_window_averaging(win_len=50, list_to_avg=world.H_greenhouse_ventilation)

        plt.plot([energy * max(world.H_greenhouse_temp) for energy in heating_plot],
                 label='Heating (Averaged and scaled)', linewidth='2', color=self.heating_c)

        plt.plot([cooler * max(world.H_greenhouse_temp) for cooler in ventilation_plot], label="Ventilation (Averaged and scaled)",
                 linewidth='2',
                 color=self.ventilation_c)

        custom_ticks, custom_tick_names = self.get_custom_xcticks(world.H_temp)
        plt.xticks(custom_ticks, custom_tick_names)

        plt.legend()
        plt.show()

    def list_window_averaging(self, win_len, list_to_avg):
        return_list = []
        current_window = 0
        current_window_sum = 0

        for i in list_to_avg:
            current_window += 1
            current_window_sum += i

            if current_window >= win_len:
                current_window = 0
                return_list.append([current_window_sum / win_len] * win_len)
                current_window_sum = 0

        return np.asarray(return_list).flatten()

    def get_custom_xcticks(self, historical_data):
        ticks = []
        tick_names = []
        last_tick_name = 0
        for step in range(len(historical_data)):
            name_freq = 240
            if step % name_freq == 0:
                ticks.append(step)
                tick_names.append(last_tick_name)
                last_tick_name += int(name_freq/60)
                if last_tick_name >= 24:
                    last_tick_name = 0
            elif step % 60 == 0:
                ticks.append(step)
                tick_names.append("")
        return ticks, tick_names


from PIL import Image
import os
from tqdm import tqdm

'''
由于部分的face_dataset的图片的格式是32位位深，但是在我的网络网络卷积中只有三层无法进行4层的卷积。

'''

def convert_to_24bit_depth(input_dir, output_dir):
    # 确保输出目录存在
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # 获取输入目录中的图片文件列表
    image_files = [f for f in os.listdir(input_dir) if f.endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif'))]

    # 使用tqdm创建进度条
    for filename in tqdm(image_files, desc="Converting images", unit="image"):
        input_path = os.path.join(input_dir, filename)
        output_path = os.path.join(output_dir, filename)

        # 打开图像
        image = Image.open(input_path)

        # 将图像转换为24位位深
        image = image.convert('RGB')

        # 保存转换后的图像
        image.save(output_path)

if __name__ == "__main__":
    # 指定输入和输出目录
    input_directory = 'face_dataset'
    output_directory = 'output'

    # 调用函数进行转换
    convert_to_24bit_depth(input_directory, output_directory)


import torch.nn as nn

class eca_layer(nn.Module):
    """Constructs a ECA module.

    Args:
        channel: Number of channels of the input feature map
        k_size: Adaptive selection of kernel size
    """

    def __init__(self, channel, k_size=3):
        super(eca_layer, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.conv = nn.Conv1d(1, 1, kernel_size=k_size, padding=(k_size - 1) // 2, bias=False)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        y = self.avg_pool(x)
        y = self.conv(y.squeeze(-1).transpose(-1, -2)).transpose(-1, -2).unsqueeze(-1)
        y = self.sigmoid(y)

        return x * y.expand_as(x)

def conv3x3(in_planes, out_planes, stride=1):
    """3x3 convolution with padding"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=1, bias=False)

class ECABasicBlock(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None, k_size=3):
        super(ECABasicBlock, self).__init__()
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = nn.BatchNorm2d(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes, 1)
        self.bn2 = nn.BatchNorm2d(planes)
        self.eca = eca_layer(planes, k_size)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x
        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.eca(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out

class ECABottleneck(nn.Module):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None, k_size=3):
        super(ECABottleneck, self).__init__()
        self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
                               padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(planes)
        self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
        self.bn3 = nn.BatchNorm2d(planes * 4)
        self.relu = nn.ReLU(inplace=True)
        self.eca = eca_layer(planes * 4, k_size)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)
        out = self.eca(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


from BinaryGene import BinaryGene;
import random;
population_size = 10
gene_len = 10
epoch = 50
mutation = 1
population_obj = []
offspring_obj = []
val = 2
temp_holder = BinaryGene()

def crossover():
    global population_obj
    global gene_len
    #loop population
    for i in range(len(population_obj)):
        #declare variables
        fitness = fitness_two = 0
        rand = random.random()
        #modulo to gather two parents
        if i % 2 is 1 and rand > 0:
            #calculate point of crossover for gene
            crossover_val = random.randrange(0, gene_len);
            #place both parents in temp arrays and update population genes values with temp genes after crossover
            for j in range(gene_len):
                if j >= crossover_val:
                    temp_1 = population_obj[i].get_gene_value()[j]
                    temp_2 = population_obj[i - 1].get_gene_value()[j]
                    population_obj[i].update_gene(j, temp_2)
                    population_obj[i - 1].update_gene(j, temp_1)
            #calculate fitness
            for j in range(gene_len):
                fitness =  fitness_func(population_obj[i].get_gene_value())
                fitness_two = fitness_func(population_obj[i - 1].get_gene_value())
            #set fitness for both population genes after crossover
            population_obj[i].set_fitness(fitness)
            population_obj[i - 1].set_fitness(fitness_two)

def mutation():
    global population_obj
    for i in range(len(population_obj)):
        #set variables
        #if random below threshold loop gene at population index and create tempory gene
        for k in range(len(population_obj[i].get_gene_value())):
            rand = random.random()
        #get random point in gene to mutate and flip bit
            if rand < 0.01:
                if population_obj[i].get_gene_value()[k] is 1:
                    population_obj[i].update_gene(k, 0)
                else:
                    population_obj[i].update_gene(k, 1)
        #update population gene with temp gene values and calculate new fitness
        fitness = fitness_func(population_obj[i].get_gene_value())
        population_obj[i].set_fitness(fitness)

def tournament_selection(pop_size):
    global offspring_obj
    global population_obj
    for i in range(pop_size):
        offspring_obj.pop()
    #select to random parents from population
    for i in range(pop_size):
        parent_one = random.randrange(0, pop_size)
        parent_two = random.randrange(0, pop_size)
        #find parent with highest fitness value and add to offspring pool
        if population_obj[parent_one].get_fitness() > population_obj[parent_two].get_fitness():
            offspring_obj.append(population_obj[parent_one])
        else:
            offspring_obj.append(population_obj[parent_two])
    #after population size iterations replace population pool with the new offspring
    for i in range(pop_size):
        population_obj[i] = offspring_obj[i]

#def sqr(n):
#    n = n * n
#    return n

def fitness_func(val):
    fitness = 0
    for i in range(len(val)):
        if val[i] is 1:
            fitness = fitness + 1
    return fitness

def overall_fitness():
    global population_obj
    global population_size
    summ = 0
    maxx = 0
    for i in range(len(population_obj)):
        summ = summ + population_obj[i].get_fitness()
        if population_obj[i].get_fitness() > maxx:
            maxx = population_obj[i].get_fitness()
    meann = summ / population_size
    return summ, meann, maxx

#initilize population
for i in range(population_size):
    p = BinaryGene();
    for j in range(gene_len):
        val = random.randrange(0, 2)
        p.set_gene_value(val)
    fitness = fitness_func(p.get_gene_value())
    p.set_fitness(fitness)
    population_obj.append(p)
    offspring_obj.append(p)

best = 0
for i in range(epoch):
    #initilize variables
    sum = mean = max = 0
    sum, mean, max = overall_fitness()

    #print mean, sum and max for population
    #print("Sum: " + str(sum))
    print("Mean: " + str(mean))
    print("Max: " + str(max))
    print("------------")
    print("Generation " + str(i + 1))

    for j in range(population_size):
        print(str(j) + ": Population " + str(population_obj[j].get_gene_value()) + str(population_obj[j].get_fitness()))
    #select random mating pool
    tournament_selection(population_size)
    #shuffle mating pool
    random.shuffle(population_obj)
    #crossover all parents in mating pool to gather offspring for new population
    crossover()
    #muta selected genes
    mutation()

    #find best and worst chromosomes and replace worst with best to maintain best solution found in all mating pools
    #for j in range(population_size):
    #    if population_obj[j].get_fitness() >= best:
    #        best_gene = population_obj[j].get_gene_value().copy()
    #        temp = j
    #        best = population_obj[j].get_fitness()
    #worst = best
    #for j in range(population_size):
    #    if population_obj[j].get_fitness() < worst:
    #        worst = population_obj[j].get_fitness()

    #for j in range(population_size):
     #   if population_obj[j].get_fitness() is worst:
      #      for k in range(gene_len):
       #         population_obj[j].update_gene(k, best_gene[k])
        #        population_obj[j].set_fitness(best)

    #print(population_obj[temp_two].get_gene_value())
    #for j in range(population_size):
     #   print(str(j) + ": population " + str(population_obj[j].get_gene_value()) + str(population_obj[j].get_fitness()))

 #fitness = fitness + (fitness_var * val);
    #fitness_var = fitness_var * 2;
    #return fitness, fitness_var


def sum_lst(lst):
    sum = 0
    for i in lst:
        sum += i
    return sum

def espejos(arr):
    espejos = 0
    for i in range(1, len(arr)):
        lst_1 = arr[:i]
        lst_2 = arr[i:]
        sum_lst_1 = sum_lst(lst_1)
        sum_lst_2 = sum_lst(lst_2)
        if sum_lst_1 == sum_lst_2:
            espejos += 1

    return espejos

def main():

    vals = int(input())
    lst = []

    for i in range(vals):
        val = float(input())
        lst.append(val)

    print(espejos(lst))

if __name__ == '__main__':
    main()


"""Auteur: Simon LEYRAL
   Date : Octobre 2017

Enoncé

Écrire une fonction my_insert qui reçoit comme premier paramètre une liste triée d’entiers par ordre croissant et comme
deuxième paramètre un entier n, et qui renvoie une liste correspondant à la liste reçue, mais dans laquelle le nombre
n a été inséré à la bonne place.

La liste donnée en paramètre ne doit pas être modifiée par votre fonction.

Vous pouvez supposer que le premier paramètre sera bien une liste triée d’entiers, mais si le deuxième paramètre
n’est pas du bon type, la fonction retourne None.

Consignes

Dans cet exercice, il vous est demandé d’écrire seulement la fonction my_insert.

Le code que vous soumettez à UpyLaB doit donc comporter uniquement la définition de cette fonction, et ne
 fait en particulier aucun appel à input ou à print.

"""

def my_insert(liste, n):
    new_liste = liste.copy()
    if type(liste) != list or type(n) != int:
        new_liste = None
    else:
        for i in liste:
            if i > n:
                pos = liste.index(i)
                new_liste.insert(pos, n)
                break
    return new_liste


import numpy as np

def feladat_1():
    n=int(input("Hány darab szám? "))
    t=np.empty(n,int)
    for i in range(n):
        a=int(input())
        t[i]=a
    for i in range(0,n-1):
        if t[i]==t[i+1] or t[i]==t[i-1]:
            print(i)

def feladat_2():
    n=int(input("Hány darab szám? "))
    paros=0
    paratlan=0
    for i in range(n):
        a=int(input())
        if a%2==0:
            paros+=1
        else:
            paratlan+=1
    return paros/paratlan

def feladat_3():
    n = int(input("Hány darab szám? "))
    s=0
    t=np.empty(n,float)
    for i in range(n):
        a=float(input())
        t[i]=abs(a)
        s=s+abs(a)
    return s/n

def feladat_4():
    n=int(input("Hány darab szám? "))
    szorzat=1
    negativ_osszeg=0
    negativ_db=0
    for i in range(n):
        a=float(input())
        if a>0:
            szorzat=szorzat*a
        elif a<0:
            negativ_osszeg=negativ_osszeg+a
            negativ_db+=1
    return szorzat,negativ_osszeg/negativ_db

def feladat_5():
    n=int(input("Hány darab szám? "))
    t=np.empty(n,int)
    szorzat=1
    osszeg=0
    for i in range(n):
        t[i]=int(input())
    for k in t:
        if k<7:
            szorzat=szorzat*k
        elif k>10:
            osszeg+=k
    return szorzat,osszeg

def feladat_6():
    strazsa=True
    k=0
    elozo = 0
    elozo_elotti = 0
    while strazsa:
        k=k+1
        aktualis=int(input())
        if aktualis==0:
            strazsa=False
        elif elozo+elozo_elotti==aktualis:
            print(aktualis)
        elif k==1:
            elozo=aktualis
        else:
            elozo_elotti=elozo
            elozo=aktualis

def feladat_7():
    li=[]
    strazsa=True
    while strazsa:
        a=int(input())
        if a==0:
            strazsa=False
        else:
            li.append(a)
    a,b,c=0,0,0
    max_atlag = 0
    for i in range(0,len(li)-2):
        if ((li[i]+li[i+1]+li[i+2])/3)>max_atlag:
            a,b,c=li[i],li[i+1],li[i+2]
            max_atlag=(li[i]+li[i+1]+li[i+2])/3
    print(a,b,c)

double_tomb=np.empty(4,np.double)
double_tomb[0]=1.144234
double_tomb[1]=2
double_tomb[2]=9.214
double_tomb[3]=7
def feladat_8(double_tomb,n):
    novekvo=True
    for i in range(0,len(double_tomb)-1):
        if double_tomb[i]>double_tomb[i+1]:
            novekvo=False
    return novekvo

tomb=np.empty(5,np.int)
tomb[0]=1
tomb[1]=2
tomb[2]=9
tomb[3]=7
tomb[4]=11
def feladat_9(tomb,n):
    osztok=[]
    for i in tomb:
        for j in range(2,(i//2)+1):
            if i%j==0 and j not in osztok:
                osztok.append(j)
            elif i%j==0 and j in osztok:
                return 0
    return 1

tomb=np.empty(5,np.int)
tomb[0]=1
tomb[1]=2
tomb[2]=9
tomb[3]=7
tomb[4]=11
def feladat_10(tomb,n,k):
    for i in range(0,n-1):
        minh=i
        for j in range(i+1,n):
            if tomb[j]<tomb[minh]:
                minh=j
        tomb[i],tomb[minh]=tomb[minh],tomb[i]
    ah=0
    fh=n-1
    kozep=(ah+fh)//2
    while ah<=fh:
        osztok=2
        for i in range(2,(tomb[kozep]//2)+1):
            if tomb[kozep]+i==0:
                osztok+=1
        if osztok>k:
            return kozep
        elif osztok<k:
            ah=kozep+1
        else:
            return -1

def feladat_11():
    n=int(input("Sorok száma: "))
    m=int(input("Oszlopok száma"))
    matrix=np.empty((n,m),np.int)
    indexek=[]
    for i in range(n):
        for j in range(m):
            matrix[i][j]=int(input())
    for j in range(m):
        negativ=0
        nulla=0
        for i in range(n):
            if matrix[i][j]<0:
                negativ+=1
            elif matrix[i][j]==0:
                nulla+=1
        if negativ>=nulla*2:
            indexek.append(j)
    return indexek

matrix12=np.empty((3,2),np.int)
matrix12[0][0]=1
matrix12[0][1]=69
matrix12[1][0]=32
matrix12[1][1]=9
matrix12[2][0]=2
matrix12[2][1]=19
def feladat_12(matrix,n,m):
    eredmeny=[]
    for i in range(n):
        for j in range(m):
            if (i+j)!=0 and matrix[i][j]%(i+j)==0:
                eredmeny.append(matrix[i][j])
    return eredmeny

matrix13=np.empty((3,2),np.int)
matrix13[0][0]=2
matrix13[0][1] = 69
matrix13[1][0] = 32
matrix13[1][1] = 9
matrix13[2][0] = 1
matrix13[2][1] = 19
def feladat_13(matrix,n,m):
    matrix_uj=np.empty((n,m),np.int)
    minimumok=[]
    for j in range(m):
        minimum=matrix[j][0]
        for i in range(n):
            if matrix[i][j]<minimum:
                minimum=matrix[i][j]
        minimumok.append(minimum)
    for j in range(m):
        for i in range(n):
            matrix_uj[i][j]=matrix[i][j]-minimumok[j]
    return matrix_uj

matrix14=np.empty((3,3),np.int)
matrix14[0][0] = 1
matrix14[0][1] = 69
matrix14[0][2] = 7
matrix14[1][0] = 32
matrix14[1][1] = 0
matrix14[1][2] = 9
matrix14[2][0] = 2
matrix14[2][1] = 0
matrix14[2][2] = 3
def feladat_14(matrix,n):
    max=matrix[0][0]
    for i in range(n):
        for j in range(0,i+1):
            if matrix[i][j]>max:
                max=matrix[i][j]
    return max

matrix15 = np.empty((2, 2), np.int)
matrix15[0][0] = 1
matrix15[0][1] = 69
matrix15[1][0] = 32
matrix15[1][1] = 0
def feladat_15(matrix,n):
    valasz=True
    for i in range(n):
        if matrix[i][i]!=0:
            valasz=False
    return valasz

matrix16=np.empty((3,2),np.double)
matrix16[0][0] = 2
matrix16[0][1] = 69
matrix16[1][0] = 32
matrix16[1][1] = 9
matrix16[2][0] = 1
matrix16[2][1] = 19
transzponalt16=np.empty((2,3),np.double)
def feladat_16(matrix,n,m,transzponalt):
    for j in range(m):
        for i in range(n):
            transzponalt[j][i]=matrix[i][j]
    return transzponalt

#17-18-ik feladatot nem vettük
def main():
    feladat_1()
    print(feladat_2)
    print(feladat_3(7))
    print(feladat_4)
    print(feladat_5(7))
    feladat_6()
    feladat_7()
    print(feladat_8(double_tomb,4))
    print(feladat_9(tomb,5))
    print(feladat_10(tomb,5,2))
    print(feladat_11())
    print(feladat_12(matrix12,3,2))
    print(feladat_13(matrix13, 3, 2))
    print(feladat_14(matrix14,3))
    print(feladat_15(matrix15,2))
    print(feladat_16(matrix16,3,2,transzponalt16))
if __name__ == '__main__':
    main()


""" File which handles caching of S matrices """

import os
import numpy as np
import copy

# Global list of kwargs which aren't important for S generation
beta_kwargs = ['coeff_size', 'sparsity', 'k', 'y_dist']

def construct_S_path(p, seed, cutoff,
					 link_method, sample_kwargs,
					 roundto = 5):

	# Round cutoff and remove useless string
	cutoff = str(round(cutoff, roundto))
	sample_kwargs = copy.copy(sample_kwargs)
	for arg in beta_kwargs:
		if arg in sample_kwargs:
			sample_kwargs.pop(arg)

	# Turn kwargs into a string
	sample_string = [
		('').join([k.replace('_', ''), str(sample_kwargs[k])]) for k in sample_kwargs
	]
	sample_string = ('_').join(sample_string)

	# Construct path
	path = f'data/S/p{p}_seed{seed}_{sample_string}/cutoff{cutoff}_link{link_method}'
	path = path + '.txt'

	# Return
	return path

def cache_S_matrix(S, p, seed, cutoff,
				   link_method, sample_kwargs,
				   roundto = 5):

	# Get path
	path = construct_S_path(
		p, seed, cutoff, link_method, sample_kwargs, roundto = roundto
	)

	# Create directory
	dirname = os.path.dirname(path)
	if not os.path.exists(dirname):
		os.makedirs(dirname)

	# Save S as csvprint(path)
	np.savetxt(path, S)

def load_S_matrix(p, seed, cutoff,
				  link_method, sample_kwargs,
				  roundto = 5):
	""" If S has been cached, load it.
	Otherwise, return None."""

	# Get path
	path = construct_S_path(
		p, seed, cutoff, link_method, sample_kwargs, roundto = roundto
	)

	# Check if file exists
	if os.path.exists(path):
		return np.loadtxt(path, dtype = float)
	else:
		return None


# Import libraries
from google.cloud import vision
import io
import os

# Instantiates a client
client = vision.ImageAnnotatorClient()

# Loads the image from local
source_image = "images/street.jpg"
with io.open(source_image, "rb") as image_file:
    content = image_file.read()
image = vision.Image(content=content)

# Perform label detection
print("Detecting labels from {}...".format(
    os.path.basename(source_image)), end=" ")
response = client.label_detection(image=image, max_results=5)
labels = response.label_annotations

# Count labels detected
if labels:
    print("found {} label{}\n".format(
        len(labels), "" if len(labels) == 1 else "s"))
else:
    print("no label detected")

# Shows label information
for label in labels:
    description = label.description
    confidence = int(label.score * 100)
    print("{} ({}% confidence)".format(description, confidence))


from pylab import *

rc("font", size=16, family="serif", serif="Computer Sans")
rc("text", usetex=True)

x = linspace(0., 100., 1001)

prior = 1./(x + 10.)**2
prior = prior/trapz(prior, x=x)
lik = 0.08*exp(-0.5*(x - 60)**2/10**2)
post = prior*lik
post = post/trapz(post, x=x)

plot(x, prior, 'b', linewidth=3, label='Prior')
plot(x, lik, 'c--', linewidth=2, label='Likelihood')
plot(x, post, 'r', linewidth=3, label='Posterior')
plot(60, 0.08, 'c*', markersize=20, label='``Best fit\'\'')
xlabel(r'$\theta$')
ylabel('Probability Density')
legend(loc='upper right', numpoints=1)
savefig('bayes.pdf', bbox_inches='tight')
show()

x = linspace(-1, 1, 201)
[x, y] = meshgrid(x, x)
y = y[::-1, :]

rsq1 = (x + 0.2)**2 + (y - 0.5)**2
rsq2 = (x - 0.4)**2 + (y - 0.7)**2
rsq3 = (y + 1 - x**2)**2
f1 = exp(-0.5*rsq1/0.05**2)
f2 = exp(-0.5*rsq2/0.03**2)
f3 = exp(-0.5*rsq3/0.02**2)
f4 = exp(-0.5*rsq2/0.3**2)
imshow(-f1 - f2 - f3 - f4, cmap='gray')
xlabel('$x$')
ylabel('$y$')
gca().set_xticks([])
gca().set_yticks([])
savefig('challenges.pdf', bbox_inches='tight')
show()

sample = loadtxt('sample.txt')
plot(sample[:,0], sample[:,1], 'k.', markersize=1)
axis('scaled')
xlabel('$x$')
ylabel('$y$')
gca().set_xticks([])
gca().set_yticks([])
savefig('dnest.png', bbox_inches='tight')
show()


import random
import geohash

import route

# A function to randomly select k items from stream[0..n-1].
def selectKItems(numPoints, numPointsToSample):
  # reservoir[] is the output array. Initialize it with
  # first k elements from stream[]
  reservoir = range(numPointsToSample)

  # Iterate from the (k+1)th element to nth element
  for i in range(numPointsToSample,numPoints):
    # Pick a random index from 0 to i.
    j = random.randrange(i+1);

    # If the randomly  picked index is smaller than k, then replace
    # the element present at the index with new element from stream
    if (j < numPointsToSample):
      reservoir[j] = i

  return sorted(reservoir)

def geohash_exactDistance(h1,h2):
    lat1,lon1 = geohash.decode(h1)
    lat2,lon2 = geohash.decode(h2)
    return route.Location(lat1, lon1).distanceInMetersTo(route.Location(lat2, lon2))

def geohashNeighbors(h,dist=2):
  if dist<=0:
    return {h:0}
  d = 1
  n = geohash.neighbors(h)
  s = dict(zip(n, [d for x in n]))
  while (d<dist):
    d+=1
    ss = set([])
    for hh  in s.keys():
      n = geohash.neighbors(hh)
      for k in n:
        if k not in s:
          ss.add(k)
    for k in ss:
      s[k] = d

  return s


import json

from tuckshop.page.page_base import PageBase, VariableVerificationTypes
from tuckshop.core.config import Config
from tuckshop.app.models import Inventory, User
from tuckshop.core.tuckshop_exception import TuckshopException
from tuckshop.core.permission import Permission

class Credit(PageBase):
    """Class for displaying the credit page"""

    NAME = 'Credit'
    TEMPLATE = 'credit'
    REQUIRES_AUTHENTICATION = True
    PERMISSION = Permission.ACCESS_CREDIT_PAGE
    MENU_ORDER = 1
    URL = '/credit'

    def processPage(self):
        """Set variables for displaying the credit page"""
        self.return_vars['user'] = self.getCurrentUserObject()
        self.return_vars['enable_custom'] = Config.ENABLE_CUSTOM_PAYMENT()
        self.return_vars['inventory'] = Inventory.getAvailableItemsByPopularity()

        shared_user_data = []
        for user in User.objects.filter(shared=True):
            shared_user_data.append([user.id, user.shared_name])
        self.return_vars['shared_user_data'] = json.dumps(shared_user_data).replace("'", r"\'")

    def processPost(self):
        """Process post requests to credit page"""
        # Obtain post variables
        available_actions = ['pay']
        if Config.ENABLE_CUSTOM_PAYMENT():
            available_actions.append('pay_custom')
        action = self.getPostVariable(name='action', possible_values=available_actions)

        user_object = self.getCurrentUserObject()

        if action == 'pay':
            use_shared_user = self.getPostVariable(name='use_shared_user', var_type=str,
                                                   default=None, set_default=True)

            # Obtain variables to item purchase
            item_id = self.getPostVariable(name='item_id', var_type=int,
                                           special=[VariableVerificationTypes.POSITIVE])
            original_price = self.getPostVariable(name='sale_price', var_type=int,
                                                  special=[VariableVerificationTypes.NON_NEGATIVE])
            inventory_object = Inventory.objects.get(pk=item_id)
            current_user = self.getCurrentUserObject()

            payment_arguments = {
                'inventory': inventory_object,
                'verify_price': original_price,
                'author': current_user,
                'affect_float': False
            }

            if use_shared_user:
                payment_arguments['description'] = self.getPostVariable(name='description', var_type=str,
                                                                        message='Description must be provided and be less than 255 characters',
                                                                        special=[VariableVerificationTypes.NOT_EMPTY])
                shared_account_ids = [account.id for account in User.objects.filter(shared=True)]
                shared_account_id = self.getPostVariable(name='shared_account', var_type=int, possible_values=shared_account_ids)
                target_user = User.objects.get(pk=shared_account_id)
            else:
                target_user = current_user

            # Perform purchase
            target_user.removeCredit(**payment_arguments)

        elif action == 'pay_custom':
            # Handle custom payment
            amount = self.getPostVariable(name='amount', var_type=int,
                                          special=[VariableVerificationTypes.POSITIVE])
            description = self.getPostVariable(name='description', var_type=str, default=None, set_default=True,
                                               message='Description must be less than 255 characters')
            user_object.removeCredit(amount=amount, description=description, author=user_object, affect_float=False)


"""Settings Module
functions behind the settings window ui-elements
"""
import logging
import logging.config
from PyQt5.QtCore import pyqtSlot as Slot # ui elements communication
import os.path
import os
import configparser
import sys

import client
sys.path.append('../client')
import backend
import client_functions

dir = os.path.dirname(__file__)
os.chdir(dir)
config_file = "../client/client.conf"
config = configparser.ConfigParser() # client config file
config.read(config_file)

connected = False

@Slot()
def save_frontend_config(settings):
    """Save the settings values to a .config file"""
    logging.info(f"Saving current settings to {config_file}...")
    user = settings.InputUsername.text()
    addr = settings.InputServerAddress.text()
    port = settings.InputPort.text()
    config.read(config_file)
    if(not config.has_section("frontend")):
        logging.info(f"No 'frontend' section found in {config_file}, creating one")
        config.add_section("frontend")
    config.set("frontend", "host", addr)
    config.set("frontend", "port", port)
    config.set("frontend", "user", user)

    en_ssl = str(settings.SSLCheckBox.isChecked())
    if(not config.has_section("SSL")):
        logging.info(f"No 'SSL' section found in {config_file}, creating one")
        config.add_section("SSL")
    config.set("SSL", "enable_ssl", en_ssl)

    config.write(open(config_file,'w'))

@Slot()
def delete_frontend_config(settings):
    """Delete the settings values in the .config file."""
    logging.info(f"Clearing frontend section in {config_file}...")
    if(config.has_section("frontend")):
        config["frontend"].clear()
    else: logging.warning("No 'frontend' section found to delete, skipping")
    config.write(open(config_file,'w'))

@Slot()
def load_frontend_config(settings):
    """Load the values stored in the .config file for frontend settings"""
    logging.info(f"Loading .config Profile")
    try:
        host = config.get("frontend", "host")
        user = config.get("frontend", "user")
        port = config.get("frontend", "port")
        en_ssl = config.getboolean("SSL", "enable_ssl")
    except:
        logging.error("No or empty 'frontend' section found in {config_file} !")
        return

    settings.InputServerAddress.setText(host)
    settings.InputUsername.setText(user)
    settings.InputPort.setText(port)
    settings.SSLCheckBox.setChecked(en_ssl)
    logging.info(f"frontend loaded user {user}, host {host}")

@Slot()
def connect_server(settings):
    """Connect to a chat server

    Connect to a chat server via the settings window and the
    information provided through the same window.
    This function is called when the user presses the 'Connect'
    button in the settings window.
    The function is a stub.
    """

    global connected

    if not connected:
        addr = settings.InputServerAddress.text()
        port = int(settings.InputPort.text())
        username = settings.InputUsername.text()
        en_ssl = settings.SSLCheckBox.isChecked()

        settings.InputServerAddress.setReadOnly(True)
        settings.InputPort.setReadOnly(True)
        settings.InputUsername.setReadOnly(True)

        backend.init_backend(addr, port, username, en_ssl)
        connected = True

@Slot()
def disconnect_server(settings):
    """Disconnect from a chat server

    Disconnect from a chat server via the settings window.
    This function is called when the user presses the 'Disconnect'
    button for server connection in the settings window.
    The function is a stub.
    """

    global connected

    if connected == True:
        connected = False
        addr = settings.InputServerAddress.text()

        settings.InputServerAddress.setReadOnly(False)
        settings.InputPort.setReadOnly(False)
        settings.InputUsername.setReadOnly(False)

        logging.info(f"frontend disconnecting from server '{addr}'")
        client_functions.close_connection(backend.my_client.sock)

@Slot()
def quickConnect(mainui, settingsui):
    global connected
    if mainui.ConnectButton.text() == "Connect" and not connected:
        settingsui.ButtonStartConnection.pressed.emit()
        mainui.ConnectButton.setText("Disconnect")
    elif mainui.ConnectButton.text() == "Disconnect" and connected:
        settingsui.ButtonEndConnection.pressed.emit()
        mainui.ConnectButton.setText("Connect")
    else:
        if connected:
            mainui.ConnectButton.setText("Disconnect")
        else:
            mainui.ConnectButton.setText("Connect")

def init_settings_window(settings):
    """Initialize settings-window
    Actions and signals are being connected to their Slots
    """
    settings.ButtonStartConnection.pressed.connect(lambda: connect_server(settings))
    settings.ButtonEndConnection.pressed.connect(lambda: disconnect_server(settings))
    settings.ButtonSaveProfile.pressed.connect(lambda: save_frontend_config(settings))
    settings.ButtonDeleteProfile.pressed.connect(lambda: delete_frontend_config(settings))
    settings.ButtonLoadProfile.pressed.connect(lambda: load_frontend_config(settings))

    settings.InputServerAddress.setText(backend.host)
    settings.InputPort.setText(str(backend.port))
    settings.InputUsername.setText(backend.user)
    settings.SSLCheckBox.setChecked(backend.en_ssl)


"""Auteur: Simon LEYRAL
   Date : Octobre 2017

Enoncé

Écrire un programme qui lit sur input une valeur naturelle n et qui affiche à l’écran un carré de
n caractères X (majuscule) de côté.

"""

n = int(input())

for i in range(n):
    print("X" * n)


# coding: utf-8

n, k = map(int, input().split())

coins = []
for _ in range(n):
    coin = int(input())
    coins.append(coin)

coins.reverse()

ans = 0
for coin in coins:
    if k >= coin:
        ans += k // coin
        k = k % coin

print(ans)


# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head is None:
            return None
        tail = ListNode(-1)
        while head:
            tmp = tail.next
            tail.next = head
            head = head.next
            tail.next.next = tmp
        return tail.next


""" Unit tests for skycomponents

"""

import logging
import unittest

import astropy.units as u
import numpy
from astropy.coordinates import SkyCoord

from rascil.data_models.polarisation import PolarisationFrame
from rascil.processing_components.simulation import (
    create_low_test_skycomponents_from_gleam,
)
from rascil.processing_components.skycomponent.operations import (
    create_skycomponent,
    find_separation_skycomponents,
    find_skycomponent_matches,
    find_nearest_skycomponent,
    find_nearest_skycomponent_index,
    filter_skycomponents_by_flux,
    select_neighbouring_components,
    voronoi_decomposition,
    apply_beam_to_skycomponent,
    image_voronoi_iter,
    partition_skycomponent_neighbours,
    remove_neighbouring_components,
)
from rascil.processing_components import create_image
from rascil.processing_components.imaging.primary_beams import create_low_test_beam

log = logging.getLogger("rascil-logger")

log.setLevel(logging.WARNING)

class TestSkycomponent(unittest.TestCase):
    def setUp(self):
        from rascil.data_models.parameters import rascil_path, rascil_data_path

        self.results_dir = rascil_path("test_results")

        self.frequency = numpy.array([1e8])
        self.channel_bandwidth = numpy.array([1e6])
        self.phasecentre = SkyCoord(
            ra=+0.0 * u.deg, dec=-55.0 * u.deg, frame="icrs", equinox="J2000"
        )

    def test_filter_flux(self):
        self.components = create_low_test_skycomponents_from_gleam(
            flux_limit=0.1,
            phasecentre=self.phasecentre,
            frequency=self.frequency,
            polarisation_frame=PolarisationFrame("stokesI"),
            radius=0.5,
        )
        newsc = filter_skycomponents_by_flux(self.components, flux_min=0.3)
        assert len(newsc) < len(self.components), len(self.components)
        newsc = filter_skycomponents_by_flux(self.components, flux_min=5.0)
        assert len(newsc) == 138, len(newsc)
        newsc = filter_skycomponents_by_flux(self.components, flux_max=8.0)
        assert len(newsc) == 11744, len(newsc)

    def test_copy(self):
        self.components = create_low_test_skycomponents_from_gleam(
            flux_limit=0.1,
            phasecentre=self.phasecentre,
            frequency=self.frequency,
            polarisation_frame=PolarisationFrame("stokesI"),
            radius=0.5,
        )
        fluxes = numpy.linspace(0, 1.0, 10)
        sc = [
            create_skycomponent(
                direction=self.phasecentre,
                flux=numpy.array([[f]]),
                frequency=self.frequency,
                polarisation_frame=PolarisationFrame("stokesI"),
            )
            for f in fluxes
        ]
        assert len(sc) == len(fluxes)

    def test_find_skycomponent_separation(self):
        self.components = create_low_test_skycomponents_from_gleam(
            flux_limit=0.1,
            phasecentre=self.phasecentre,
            frequency=self.frequency,
            polarisation_frame=PolarisationFrame("stokesI"),
            radius=0.5,
        )
        separations = find_separation_skycomponents(self.components[0:99])
        assert separations[0, 0] == 0.0
        assert numpy.max(separations) > 0.0

    def test_find_skycomponent_separation_binary(self):
        self.components = create_low_test_skycomponents_from_gleam(
            flux_limit=0.1,
            phasecentre=self.phasecentre,
            frequency=self.frequency,
            polarisation_frame=PolarisationFrame("stokesI"),
            radius=0.5,
        )
        test = self.components[0:9]
        separations = find_separation_skycomponents(test, test)

        assert separations[0, 0] == 0.0
        assert numpy.max(separations) > 0.0

    def test_find_skycomponent_matches(self):
        self.components = create_low_test_skycomponents_from_gleam(
            flux_limit=0.1,
            phasecentre=self.phasecentre,
            frequency=self.frequency,
            polarisation_frame=PolarisationFrame("stokesI"),
            radius=0.5,
        )
        matches = find_skycomponent_matches(
            self.components[: len(self.components) // 2], self.components
        )
        assert len(matches) == 5900, len(matches)

    def test_find_nearest_component_index(self):
        self.components = create_low_test_skycomponents_from_gleam(
            flux_limit=0.1,
            phasecentre=self.phasecentre,
            frequency=self.frequency,
            polarisation_frame=PolarisationFrame("stokesI"),
            radius=0.5,
        )
        match = find_nearest_skycomponent_index(
            self.components[3].direction, self.components
        )
        assert match == 3

    def test_find_nearest_component(self):
        self.components = create_low_test_skycomponents_from_gleam(
            flux_limit=0.1,
            phasecentre=self.phasecentre,
            frequency=self.frequency,
            polarisation_frame=PolarisationFrame("stokesI"),
            radius=0.5,
        )
        match, sep = find_nearest_skycomponent(
            self.components[3].direction, self.components
        )
        assert match.name == "GLEAM J211146-685527", match.name

    def test_select_neighbouring_components(self):
        self.components = create_low_test_skycomponents_from_gleam(
            flux_limit=0.1,
            phasecentre=self.phasecentre,
            frequency=self.frequency,
            polarisation_frame=PolarisationFrame("stokesI"),
            radius=0.5,
        )
        bright_components = filter_skycomponents_by_flux(self.components, flux_min=2.0)
        indices, d2d = select_neighbouring_components(
            self.components, bright_components
        )
        assert len(indices) == 11801, len(indices)
        assert numpy.max(indices) == (len(bright_components) - 1)

    def test_voronoi_decomposition(self):
        bright_components = create_low_test_skycomponents_from_gleam(
            flux_limit=1.0,
            phasecentre=self.phasecentre,
            frequency=self.frequency,
            polarisation_frame=PolarisationFrame("stokesI"),
            radius=0.5,
        )
        model = create_image(
            npixel=512,
            cellsize=0.001,
            phasecentre=self.phasecentre,
            frequency=self.frequency,
            polarisation_frame=PolarisationFrame("stokesI"),
        )
        beam = create_low_test_beam(model, use_local=False)
        bright_components = apply_beam_to_skycomponent(bright_components, beam)
        bright_components = filter_skycomponents_by_flux(
            bright_components, flux_min=2.0
        )

        vor, vor_array = voronoi_decomposition(model, bright_components)
        assert len(bright_components) == (numpy.max(vor_array) + 1)

    def test_image_voronoi_iter(self):
        bright_components = create_low_test_skycomponents_from_gleam(
            flux_limit=1.0,
            phasecentre=self.phasecentre,
            frequency=self.frequency,
            polarisation_frame=PolarisationFrame("stokesI"),
            radius=0.5,
        )
        model = create_image(
            npixel=512,
            cellsize=0.001,
            phasecentre=self.phasecentre,
            frequency=self.frequency,
            polarisation_frame=PolarisationFrame("stokesI"),
        )
        model["pixels"].data[...] = 1.0
        beam = create_low_test_beam(model, use_local=False)
        bright_components = apply_beam_to_skycomponent(bright_components, beam)
        bright_components = filter_skycomponents_by_flux(
            bright_components, flux_min=2.0
        )

        for im in image_voronoi_iter(model, bright_components):
            assert numpy.sum(im["pixels"].data) > 1

    def test_partition_skycomponent_neighbours(self):
        all_components = create_low_test_skycomponents_from_gleam(
            flux_limit=0.1,
            phasecentre=self.phasecentre,
            frequency=self.frequency,
            polarisation_frame=PolarisationFrame("stokesI"),
            radius=0.5,
        )

        bright_components = create_low_test_skycomponents_from_gleam(
            flux_limit=1.0,
            phasecentre=self.phasecentre,
            frequency=self.frequency,
            polarisation_frame=PolarisationFrame("stokesI"),
            radius=0.5,
        )
        model = create_image(
            npixel=512,
            cellsize=0.001,
            phasecentre=self.phasecentre,
            frequency=self.frequency,
            polarisation_frame=PolarisationFrame("stokesI"),
        )
        beam = create_low_test_beam(model, use_local=False)
        all_components = apply_beam_to_skycomponent(all_components, beam)
        all_components = filter_skycomponents_by_flux(all_components, flux_min=0.1)
        bright_components = apply_beam_to_skycomponent(bright_components, beam)
        bright_components = filter_skycomponents_by_flux(
            bright_components, flux_min=2.0
        )

        comps_lists = partition_skycomponent_neighbours(
            all_components, bright_components
        )
        assert len(comps_lists) == len(bright_components)
        assert len(comps_lists[0]) > 0
        assert len(comps_lists[-1]) > 0

    def test_remove_neighbouring_components(self):
        all_components = create_low_test_skycomponents_from_gleam(
            flux_limit=3.0,
            phasecentre=self.phasecentre,
            frequency=self.frequency,
            polarisation_frame=PolarisationFrame("stokesI"),
            radius=0.5,
        )

        model = create_image(
            npixel=512,
            cellsize=0.001,
            phasecentre=self.phasecentre,
            frequency=self.frequency,
            polarisation_frame=PolarisationFrame("stokesI"),
        )
        beam = create_low_test_beam(model, use_local=False)
        all_components = apply_beam_to_skycomponent(all_components, beam)
        all_components = filter_skycomponents_by_flux(all_components, flux_min=0.1)

        idx, comps = remove_neighbouring_components(all_components, 0.1)
        assert idx == [2, 4, 5, 7], idx
        assert comps[0].name == "GLEAM J234118-581606", comps[0].name

if __name__ == "__main__":
    unittest.main()


import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, MinMaxScaler

from .custom_transforms import MedianScaler, DropColumns

def build_pipeline() -> Pipeline:
    transformer = ColumnTransformer(
        [
            (
                "categorical_pipeline",
                Pipeline(
                    [
                        (
                            "impute",
                            SimpleImputer(
                                missing_values=np.nan, strategy="most_frequent"
                            ),
                        ),
                        ("ohe", OneHotEncoder()),
                    ]
                ),
                ["cp", "restecg", "slope"],
            ),
            (
                "custom_transform",
                MedianScaler(),
                ["oldpeak", "thalach"],
            ),
            (
                "min_max_scaler",
                MinMaxScaler(),
                ["age", "trestbps", "chol"],
            ),
        ],
        remainder="passthrough",
    )

    pipeline = Pipeline(
        steps=[
            ("transformer", transformer),
        ]
    )
    return pipeline


# 체스판의 형태가 주어지면 주어진 형태에서 채워주어야 할 체스 칸의 개수를 구하면 된다.
# ex. BWBBBWBW    black과 white가 번갈아가면서 있어야 하지만 B이 연속하여 있다.

# 세로, 가로
n, m = map(int, input().split())
c = []
result = []

# 현재 체스판 형태 입력
for i in range(n):
    chess = input()
    che_ss = list(chess)
    c.append(che_ss)

def repaint(c):
    need_tile = 0
    # 정답지를 만들어 비교
    if (m % 2) != 0:  # 가로가 짝수가 아닐 때
        black = ['B', 'W'] * (m // 2)
        black.append('B')
        white = ['W', 'B'] * (m // 2)
        white.append('W')
    else:  # 가로가 짝수 일 때
        black = ['B', 'W'] * (m // 2)
        white = ['W', 'B'] * (m // 2)

    for i in range(n):
        for j in range(m):
            if (c[0][0] == 'B'):  # 맨 왼쪽 위 칸이 Black인 경우

                if (i % 2) == 0:  # i가 짝수일 때
                    if c[i][j] != black[j]:
                        need_tile += 1
                else:  # i가 홀수 일 때
                    if c[i][j] != white[j]:
                        need_tile += 1
            else:  # 맨 왼쪽 위 칸이 White 인 경우

                if (i % 2) == 0:  # i가 짝수일 때
                    if c[i][j] != white[j]:
                        need_tile += 1
                else:  # i가 홀수 일 때
                    if c[i][j] != black[j]:
                        need_tile += 1
    return need_tile

print(repaint(c))