from decimal import Context
from django.shortcuts import redirect, render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .models import Profile
from django.contrib.auth import authenticate, login,logout,models
import http.client
from .models import Product
from .distance_calc.distance import PincodeDistance
from .models import Contact_us
from .models import Sold,Bought,ForSale

def home(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    return render(request, 'index.html')

def about(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    return render(request, 'about.html')

def contact(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    if request.method == 'POST':
        name = request.POST['name']
        phone = request.POST['phone']
        subject = request.POST['subject']
        message = request.POST['message']
        ins = Contact_us(name=name,phone=phone,subject=subject,message=message)
        ins.save()
        return redirect('/home/')
    return render(request, 'contact.html')

def trend(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    return render(request, 'pricetrend.html')

def user_analytics(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    return render(request, 'user_analytics.html')

def option(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    return render(request, 'option.html')

def view_store(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    return render(request, 'view_store.html')

def sample(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    return render(request, 'sample-inner-page.html')

def service(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    return render(request, 'services.html')

def service_detail(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    return render(request, 'service-details.html')

def sell(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    if request.method == 'POST':
       product = request.POST['product']
       quantity = request.POST['quantity']
       price = request.POST['price']
       cur_profile=Profile.objects.filter(user=request.user).first()
       phone = request.POST['phone']
       country = request.POST['Country']
       state = request.POST['State']
       district = request.POST['District']
       pin_code = request.POST['pin-code']
       prodId="prod"+str(Product.objects.all().count()+1)
       ins = Product(profile=cur_profile,prodId=prodId,product_name=product, product_quantity=quantity, product_price=price, phone_number=phone, seller_country=country, seller_state=state, seller_district=district, pin_code=pin_code)
       ins.save()
       forSale = ForSale(profile=cur_profile,prodId=prodId,product_name=product, product_quantity=quantity, product_price=price, phone_number=phone, seller_country=country, seller_state=state, seller_district=district, pin_code=pin_code)
       forSale.save()
       message=f"Congratulations! Your offer has been placed, let's hope to connect you to a buyer! Happy Trading :).\nThe details of the offer are :\nProduct Id: {prodId}\nProduct Name: {product}\n Product Quantity: {quantity} Quintal \n Product Price: Rs. {price} per Quintal"
       conn = http.client.HTTPSConnection("kptries-otp-api.herokuapp.com")
       payload = 'phone='+str(cur_profile.mobile)+'&message='+message
       headers = {
       'Content-Type': 'application/x-www-form-urlencoded'
       }
       conn.request("POST", "/message", payload, headers)
       res = conn.getresponse()
       return redirect("/option/")
    return render(request, 'sell.html')

def buy(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    if request.method == 'POST':
        name=request.POST['product']
        pincode=request.POST['pincode']
        p=PincodeDistance()
        products=Product.objects.filter(product_name=name)
        dist=[]
        for product in products:
            dis=p.getDistance(pincode,product.pin_code)
            while 1:
                if dist.count(dis) > 0:
                    dis+=1
                else:
                    break
            dist.append(dis)
        sorted_prod= [x for _,x in sorted(zip(dist,products))]
        context = {
        'products': sorted_prod,
        }
        return render(request,"view_store.html",context)
    return render(request, 'buy.html')

def confirm(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    return redirect("/confirm/")
    print(request.user)

def confirmBuy(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    if request.method == 'GET':
        prodId=request.GET['product']
        product=Product.objects.get(prodId=prodId)
        forSale=ForSale.objects.get(prodId=prodId)
        cur_profile=Profile.objects.filter(user=request.user).first()
        buyer = Bought(profile=cur_profile,seller_name=product.profile.user.first_name,prodId=product.prodId,product_name=product.product_name, product_quantity=product.product_quantity, product_price=product.product_price, phone_number=product.phone_number, seller_country=product.seller_country, seller_state=product.seller_state, seller_district=product.seller_district, pin_code=product.pin_code)
        buyer.save()
        seller = Sold(profile=product.profile,buyer_name=cur_profile.user.first_name,buyer_phone=cur_profile.mobile,prodId=product.prodId,product_name=product.product_name, product_quantity=product.product_quantity, product_price=product.product_price, phone_number=product.phone_number, seller_country=product.seller_country, seller_state=product.seller_state, seller_district=product.seller_district, pin_code=product.pin_code)
        seller.save()
        product.product_name=product.product_name+" Sold"
        product.save()
        forSale.delete()
        message=f"Congratulations! Your order has been placed, Please connect to your seller! Happy Trading :).\nThe details of the farmer are \nFarmer Name: {product.profile.user.first_name}\n  Farmer Phone Number: {product.profile.mobile}\nProduct Id: {product.prodId}\nProduct Name: {product.product_name}\n Product Quantity: {product.product_quantity} Quintal\n Product Price: Rs. {product.product_price} per Quintal"
        conn = http.client.HTTPSConnection("kptries-otp-api.herokuapp.com")
        payload = 'phone='+str(cur_profile.mobile)+'&message='+message
        headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
        }
        conn.request("POST", "/message", payload, headers)
        res = conn.getresponse()
        message=f"Congratulations! We see a buyer for your crop! Please connect to your Buyer! Happy Trading :).\nThe details of the Buyer are \nBuyer Name: {cur_profile.user.first_name}\n  Buyer Phone Number: {cur_profile.mobile}\nProduct Id: {product.prodId}\nProduct Name: {product.product_name}\n Product Quantity: {product.product_quantity} Quintal\n Product Price: Rs. {product.product_price} per Quintal"
        payload = 'phone='+str(product.profile.mobile)+'&message='+message
        conn.request("POST", "/message", payload, headers)
        res = conn.getresponse()
    return redirect("/home/")

def buyer(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    return render(request, 'buyer.html')

def profile(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    if request.method=="POST":
        mobile = request.POST.get('mobile')
        pincode=request.POST.get('pincode')
        name=request.POST.get('name')
        city=request.POST.get('city')
        user = request.user
        profile = Profile.objects.get(user = user)
        user.first_name=name
        profile.mobile=mobile
        profile.pincode=pincode
        profile.user.first_name=name
        profile.city=city
        user.save()
        profile.save()
        login(request,user)
    profile=Profile.objects.filter(user=request.user).first()
    context = {
        'profile': profile,
        }
    return render(request, 'profile.html',context)

def loginp(request):
    if request.method=="POST":
        mobile = request.POST.get('mobile')
        conn = http.client.HTTPSConnection("kptries-otp-api.herokuapp.com")
        payload = 'number='+str(mobile)
        headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
        }
        conn.request("POST", "/send", payload, headers)
        res = conn.getresponse()
        data = res.read()
        print(data.decode("utf-8"))
        request.session['mobile']=mobile
        return redirect("/otp/")
    return render(request, 'login.html')

def signup(request):
    # is_auth=request.session['auth']
    # if is_auth is not "true":
        # return redirect("/login/")
    if request.method=="POST":
        mobile = request.session['mobile']
        pincode=request.POST.get('pincode')
        name=request.POST.get('name')
        city=request.POST.get('city')
        role=request.POST.get('role')
        userId="user"+str(Profile.objects.all().count()+1)
        user = User(username = userId,first_name=name)
        user.save()
        profile = Profile(user = user , mobile=mobile , pincode=pincode,role=role,city=city)
        profile.save()
        login(request,user)
        return redirect("/home/")
    return render(request, 'signup.html')

def otp(request):
    if request.method=="POST":
        mobile = request.session['mobile']
        otp=request.POST.get('OTP')
        conn = http.client.HTTPSConnection("kptries-otp-api.herokuapp.com")
        payload = 'number='+str(mobile)+'&otp='+str(otp)
        headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
        }
        conn.request("POST", "/verify", payload, headers)
        res = conn.getresponse()
        data = res.read().decode('utf-8')
        if data.find("Success")!=-1:
            profile = Profile.objects.filter(mobile = mobile).first()
            if not profile:
                # request.session['auth']="true"
                return redirect("/signup/")
            login(request,profile.user)
            return redirect("/home/")
        else:
            return redirect("/invalid")
    return render(request,'otp.html')

def invalid(request):
    return render(request,'invalid.html')

def my_logout(request):
    logout(request)
    return redirect('login')

def analyticsBought(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    profile=Profile.objects.filter(user=request.user).first()
    products=Bought.objects.filter(profile=profile)
    context = {
        'products': products,
        }
    return render(request, 'analytics_buyer.html',context)

def analyticsSold(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    profile=Profile.objects.filter(user=request.user).first()
    products=Sold.objects.filter(profile=profile)
    context = {
        'products': products,
        }
    return render(request, 'analytics_seller.html',context)

def analyticsForSale(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    profile=Profile.objects.filter(user=request.user).first()
    products=ForSale.objects.filter(profile=profile)
    context = {
        'products': products,
        }
    return render(request, 'analytics_forSale.html',context)

def analyticsOption(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    return render(request, 'analytics_option.html')


from tkinter import*

def hello():
    print("hello tkinter button")
def name():
    print("name is hema")
root=Tk()
root.geometry("644x432")

frame=Frame(root,borderwidth=6,bg="pink",relief=RAISED)
frame.pack(side=LEFT,anchor=NW)

b1= Button(frame,bg="red",text="Print now",command=hello)
b1.pack(side=RIGHT,padx=23,pady=24)

b2= Button(frame,bg="red",text="tell now",command=name)
b2.pack(side=TOP,padx=23,pady=24)

b3= Button(frame,bg="red",text="Print now")
b3.pack(side=BOTTOM,padx=23,pady=24)

root.mainloop()


import ui_4_03
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog
import sys
import os

__author__ = 'Milan Cugurovic & Ivan Ristovic, 2020.'

class SimplePadClass(ui_4_03.Ui_MainWindow, QtWidgets.QMainWindow):
    def __init__(self):
        super(SimplePadClass, self).__init__()
        self.setupUi(self)

        # Putanja do trenurno otvorenog fajla
        self.path = None

        # Akcije
        self.actionNew.triggered.connect(lambda: self.OpenMe())
        self.actionSave.triggered.connect(lambda: self.SaveMe())
        self.actionSaveAs.triggered.connect(lambda: self.SaveAsMe())

    # Azuriram naslov prozora
    def __title(self):
        self.setWindowTitle("{} - SimplePad".format(os.path.basename(self.path) if self.path is not None else 'Untitled'))

    # Poruka za korisnika
    def __dialog(self, msg):
        box = QMessageBox(self)
        box.setText(msg)
        box.show()

    # Cuvam na fajl sistemu
    def __save_util(self, path):
        data = self.editor.toPlainText()
        try:
            with open(path, "w") as f:
                f.write(data)
        except Exception as e:
            self.__dialog(str(e))
        else:
            self.path = path
            self.__title()

    # ctr+O
    def OpenMe(self):
        path, _ = QFileDialog.getOpenFileName(self, "Open file", "", "All files (*.*);")
        if path:
            try:
                with open(path, "r") as f:
                    data = f.read()
            except Exception as e:
                self.__dialog(str(e))
            else:
                self.path = path
                self.editor.setPlainText(data)
                self.__title()

    # Ctr+S
    def SaveMe(self):
        if self.path is None:
            return self.SaveAsMe()
        self.__save_util(self.path)

    # Ctrl+Alt+S
    def SaveAsMe(self):
        path, _ = QFileDialog.getSaveFileName(self, "Save file", "", "All files (*.*);")
        if not path:
            return  # cancelled
        self.__save_util(path)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    simplePad = SimplePadClass()
    simplePad.show()
    sys.exit(app.exec_())


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

__author__ = 'BlackYe.'

__all__ = [

    # Base class for all data objects.
    "Data",
]

#------------------------------------------------------------------------------
class Data(object):
    """
    Base class for all data entities.
    This is the common interface for Information, Resource and Vulnerability.
    """
    #--------------------------------------------------------------------------
    # Data types

    TYPE_UNKNOWN = 0      # not a real type! only used in get_accepted_types()

    TYPE_INFORMATION   = 1
    TYPE_VULNERABILITY = 2
    TYPE_RESOURCE      = 3

    data_type = TYPE_UNKNOWN

    #--------------------------------------------------------------------------
    def __init__(self):
       pass

    def is_instance(self, clazz):
        try:
            data_type    = clazz.data_type
            data_subtype = clazz.data_subtype
        except AttributeError:
            return False
        return self.data_type    == data_type    and \
               self.data_subtype == data_subtype


#reverse snake game
from winsound import PlaySound
import pygame
from pygame.locals import *         # imports certain global Variables
import time

SIZE = 16
Start = 100

class Apple:
    def __init__(self, parent_screen):
        self.parent_screen = parent_screen
        self.apple = pygame.image.load("resources/apple.jpg").convert()
        self.x = SIZE * 10
        self.y = SIZE * 5
        self.counter = 20                   #counter to count loops till movement
        self.current = 20                  #current loops since last movement
        self.direc = "down"

    def draw(self):
        self.parent_screen.blit(self.apple, (self.x, self.y))
        pygame.display.flip()

    def move_left(self):   #from normal snake
        self.direc = 'left'

    def move_right(self):
        self.direc = 'right'

    def move_up(self):
        self.direc = 'up'

    def move_down(self):
        self.direc = 'down'

    def move(self):             #movement taken from snake head
        if self.direc == 'left':
            self.x -= SIZE
        if self.direc == 'right':
            self.x += SIZE
        if self.direc == 'up':
            self.y -= SIZE
        if self.direc == 'down':
            self.y += SIZE

class Snake:
    def __init__(self, parent_screen, length):
        self.parent_screen = parent_screen
        self.head = pygame.image.load("resources/greeneye.jpeg").convert()     #importing a picture
        self.block = pygame.image.load("resources/green.jpeg").convert()

        self.length = length
        self.x = [SIZE]*length
        self.y = [SIZE]*length
        self.counter = 20                  #counter to count loops till movement
        self.current = 20                  #current loops since last movement
        self.length_increase_counter = 0

        for i in range (self.length):
            self.x.append(Start )
            self.y.append(Start + SIZE*i)

        self.direc = 'down'

    def set_direction(self, xa, ya, xb, yb):
        x = xa - xb
        y = ya - yb
        if abs(x) > abs(y):
            if x > 0:
                self.direc = "right"
            else:
                self.direc = "left"
        else:
            if y > 0:
                self.direc = "down"
            else:
                self.direc = "up"

    def move(self):
        #update body
        for i in range(self.length-1,0,-1):
            self.x[i] = self.x[i-1]
            self.y[i] = self.y[i-1]

        # update head
        if self.direc == 'left':
            self.x[0] -= SIZE
        if self.direc == 'right':
            self.x[0] += SIZE
        if self.direc == 'up':
            self.y[0] -= SIZE
        if self.direc == 'down':
            self.y[0] += SIZE

    def draw(self):
        self.parent_screen.blit(self.head, (self.x[0], self.y[0]))
        for i in range(1, self.length):
            self.parent_screen.blit(self.block, (self.x[i], self.y[i]))                         #drawing the image        ((0,0) is upper left corner)
        pygame.display.flip()                                       #update screen

    def length_increase(self):
        self.length += 1
        self.x.append(0)
        self.y.append(0)

class Game:
    def __init__(self):
        pygame.init()               #initialising the pygame module
        pygame.display.set_caption("Codebasics Snake And Apple Game")
        pygame.mixer.init()                     #initzializing sound module

        self.play_background_music()

        self.surface = pygame.display.set_mode((SIZE * 30, SIZE * 25))             #initialising the window and its properties, size in pixels
        self.snake = Snake(self.surface, 3)
        self.snake.draw()
        self.apple = Apple(self.surface)
        self.apple.draw()
        self.game_over_type = 0          # = 1 if won, = 2 if lost

    def display_score(self):
        font = pygame.font.SysFont('arial', 30)
        score = font.render(f"Score: {self.snake.length-3}", True, (255, 255, 255))
        self.surface.blit(score, (320, 20))

    def is_collision(self, x1, y1, x2, y2):
        if x1 >= x2 and x1 < x2 + SIZE:
            if y1 >= y2 and y1 < y2 + SIZE:
                return True
        return False

    def show_game_over(self):
        self.render_background()
        font = pygame.font.SysFont('arial',20)
        if self.game_over_type == 1:
            line1 = font.render(f"You won. Congratulations. Your score: {self.snake.length-3}", True, (255, 255, 255))
            self.surface.blit(line1, (50, 100))
            line2 = font.render(f"To play again press Enter. To exit press Escape", True, (255, 255, 255))
            self.surface.blit(line2, (50, 150))
        elif self.game_over_type == 2:
            line1 = font.render(f"The game is over. Your score: {self.snake.length-3}", True, (255, 255, 255))
            self.surface.blit(line1, (50, 100))
            line2 = font.render(f"To play again press Enter. To exit press Escape", True, (255, 255, 255))
            self.surface.blit(line2, (50, 150))
        else:
            line1 = font.render("Unexpected Error occurred", True, (255, 255, 255))
            self.surface.blit(line1, (50, 100))
            line2 = font.render("To play again press Enter. To exit press Escape", True, (255, 255, 255))
            self.surface.blit(line2, (50, 150))

        pygame.display.flip()

        pygame.mixer.music.pause()

    def play_sound(self, sound):
        sound = pygame.mixer.Sound(f"resources/{sound}.mp3")
        pygame.mixer.Sound.play(sound)
        pygame.mixer.Sound.set_volume(sound, 0.2)

    def play_background_music(self):
        pygame.mixer.music.load("resources/bensound-happyrock.mp3")
        pygame.mixer.music.play()
        pygame.mixer.music.set_volume(0.1)

    def render_background(self):
        bg = pygame.image.load("resources/background_green.jpeg")
        self.surface.blit(bg, (0, 0))

    def reset(self):
        self.snake = Snake(self.surface, 3)
        self.apple = Apple(self.surface)

    def play(self):
        if self.snake.current >= self.snake.counter:
            if self.snake.length_increase_counter >= 50:
                self.snake.length_increase()
                if self.snake.counter > 14:
                    self.snake.counter -= 1
                self.snake.length_increase_counter = 0

            self.snake.current = 0
            self.snake.set_direction(self.apple.x, self.apple.y, self.snake.x[0], self.snake.y[0])
            self.snake.move()
            self.snake.current = 0

        if self.apple.current >= self.apple.counter:
            self.apple.current = 0
            self.apple.move()

        if self.is_collision(self.apple.x, self.apple.y, self.snake.x[0], self.snake.y[0]):
            self.game_over_type = 2
            raise "Game over"

        for i in range(1, self.snake.length):
            if self.is_collision(self.snake.x[0], self.snake.y[0], self.snake.x[i], self.snake.y[i]):
                self.game_over_type = 1
                raise "Game over"

        self.render_background()
        self.apple.draw()
        self.snake.draw()

        self.snake.current += 1
        self.apple.current += 1
        self.snake.length_increase_counter += 1

    def run(self):
        pause = False
        running = True
        while running:
            for event in pygame.event.get():
                if event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        running = False

                    if event.key == K_RETURN:
                        pygame.mixer.music.unpause()
                        pause = False

                    if not False:
                        if event.key == K_LEFT:
                            self.apple.move_left()
                        if event.key == K_RIGHT:
                            self.apple.move_right()
                        if event.key == K_UP:
                            self.apple.move_up()
                        if event.key == K_DOWN:
                            self.apple.move_down()

                elif event.type == QUIT:
                    running = False
            #self.play()
            try:
                if not pause:
                    self.play()
            except Exception as e:
                self.show_game_over()
                pause = True
                self.reset()

            time.sleep(0.01)

if __name__ == "__main__":
    game = Game()
    game.run()


#index() 함수 사용법 : 리스트이름.index(리스트요소)
#for key in key_list : 사전의 키만 뽑은 리스트에서 키 탐색

N = int(input())
l = list(map(int, input().split()))

ans = dict()

l_new = sorted(l)

ans_list = []

for i in range(N) :
    ans[l_new[i]] = l_new.index(l_new[i])

key_list = ans.keys()

for i in range(N) :
    for key in key_list :
        if l[i] == key :
            ans_list.append(ans[key])

for i in range(N) :
    print(ans_list[i], end = " ")


# Введите количество изделий
print ('Количество изделий')
productCnt=int(input())

# Количество рабочих мест на конвейере
print ('Количество рабочих мест')
workPlacesCnt=int(input())

# Время механообработки
print ('Время механообработки партии')
machiningTime=float(input())

# Заполняем время сборки каждого типа деталей
assemblyTimesForDetails=[]
print('Время сборки каждой детали в изделие')
for i in range (workPlacesCnt):
    assemblyTimesForDetails.append(float(input()))

# Общее время сборки
assemblyTime=0
# Расчет общего времени сборки
if productCnt<=workPlacesCnt:
    for i in range(1, productCnt+workPlacesCnt):
        if i<=productCnt:
            assemblyTime += max(assemblyTimesForDetails[0:i])
        elif i>workPlacesCnt:
            assemblyTime += max(assemblyTimesForDetails[(i-productCnt):workPlacesCnt])
        else :
            assemblyTime += max(assemblyTimesForDetails[(i - productCnt):i])
else:
    for i in range(1, productCnt+workPlacesCnt):
        if i<=workPlacesCnt:
            assemblyTime += max(assemblyTimesForDetails[0:i])
        elif i>productCnt:
            assemblyTime += max(assemblyTimesForDetails[(i-productCnt):workPlacesCnt])
        else :
            assemblyTime += max(assemblyTimesForDetails[0:workPlacesCnt])

# Вывод результатов
print ('Общее время сборки =',assemblyTime)
if ((assemblyTime<machiningTime) and (abs(((machiningTime-assemblyTime)/machiningTime)*100)<=5)):
    print('Механообрабатывающий цех и сборочный согласованы\n',
         'Попробуйте уменьшить количество мест на конвейере в ', machiningTime/assemblyTime,' раз')
elif ((assemblyTime>=machiningTime) and (abs(((assemblyTime-machiningTime)/machiningTime)*100)<=5)):
    print ('Механообрабатывающий цех и сборочный согласованы')
else:
    print ('Механообрабатывающий цех и сборочный НЕ согласованы! Уменьшите время обработки деталей')


"""
Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array.

A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true:

0 <= i < j < nums.length
|nums[i] - nums[j]| == k
Notice that |val| denotes the absolute value of val.

Example 1:
Input: nums = [3,1,4,1,5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of unique pairs.

Example 2:
Input: nums = [1,2,3,4,5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).

Example 3:
Input: nums = [1,3,1,5,4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).

"""

# O(n) time complexity
class Solution:
    def findPairs(self, nums: List[int], k: int) -> int:
        nums_dict = {}
        # put all list items into a hash table
        for i in range(0, len(nums)):
            if not nums_dict.get(nums[i]):
                nums_dict[nums[i]] = []
            nums_dict[nums[i]].append(i)

        result_dict = {}

        # for each item check if its k sum counterparts exist
        for i in range(0, len(nums)):
            pair_sum = (nums[i] - k, nums[i] + k)
            pair_list = []

            for pair in pair_sum:
                if nums_dict.get(pair) and (not i == nums_dict.get(pair)[0]):
                    pair_list.append(pair)
                    result_dict[tuple(sorted([nums[i], pair]))] = True

        return (len(result_dict.keys()))


"""
This py file contains two approaches to deal with imbalanced datasets.

- 'class_weights' method assigns to each class a weight equal of the class inverse frequency.
    The calculated output weights should be passed to the loss function, via 'weight' argument,
    in order to be used as penalties in the loss function during training.
    In that way the model tends to avoid false negatives over false positives.
    see also : https://datascience.stackexchange.com/questions/52627/why-class-weight-is-outperforming-oversampling

- 'get_sampler' method constructs a 'WeightedRandomSampler' instance which can be used to ovesample
    the minority class(es); by increasing the frequency that images from these classes are seen
    by the model during training.
    The output of get_sampler method should be passed as the 'sampler' argument of the DataLoader.
    see also : https://www.youtube.com/watch?v=4JFVhJyTZ44&ab_channel=AladdinPersson   (code)
               https://towardsdatascience.com/demystifying-pytorchs-weightedrandomsampler-by-example-a68aceccb452
               https://stackoverflow.com/questions/67799246/weighted-random-sampler-oversample-or-undersample
"""

import os
from torch.utils.data import WeightedRandomSampler
import torch

def class_weights(dataset_dir, dataset):

    #device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

    weights=[]; no_files = [] ;i=0
    for root, subdir, files in os.walk(dataset_dir):
        subdir.sort()
        if len(files)>0:
            no_files.append(len(files))
            weights.append(1/len(files))
            print('{} class - instances {} - assigned weight {}'. \
                  format(list(dataset.class_to_idx.keys())[i], len(files), 1/len(files)))
            i += 1

    weights = torch.Tensor(weights)

    return weights

def get_sampler(dataset_dir, dataset):

    weights = class_weights(dataset_dir, dataset).tolist()

    sample_weights = [0]*len(dataset)
    for idx, (data, label) in enumerate(dataset):
        class_weight = weights[label]
        sample_weights[idx] = class_weight

    sampler = WeightedRandomSampler(sample_weights,
                                    num_samples=len(sample_weights), # len(sample_weights) = len(dataset)
                                    replacement=True)

    return sampler


#!/usr/bin/python -tt
from werkzeug.wrappers import Response, Request
from werkzeug.serving import run_simple
import posixpath, urllib, os, mimetypes, json, sqlite3
from operator import attrgetter
import get_events, datetime
import combine
import time

from feed.date.rfc3339 import *

def manage_db():
	conn = sqlite3.connect('example.db')
	conn.row_factory = sqlite3.Row
	c = conn.cursor()
	yield c
	conn.commit()
	conn.close()

def application(environ, start_response):
	request = Request(environ)
	path = translate_path(request.path)
	try:
		f = open(path,'rb')
	except IOError:
		if "login" in request.path:
			response = Response()
			response.status_code = 301
			response.location = get_events.login()
			return response(environ, start_response)
		if "callback" in request.path:
			email = get_events.callback(request.args.get("code"))
			response = Response()
			response.status_code = 301
			response.location = "/static/app.html"
			response.set_cookie("blah",email,expires=datetime.datetime.now() + datetime.timedelta(days=1))
			return response(environ, start_response)
		if "addtask" in request.path:
			deadline = tf_from_timestamp(request.form["deadline"]) * 1000
			name = request.form["name"]
			hours = int(request.form["hours"])
			minutes = int(request.form["minutes"])
			duration = 3600*hours + 60*minutes
			repeat = request.form["repeat"]
			new_task = {"summary":name,"deadline":deadline,"duration":duration,"repeat":repeat}
			email = request.cookies.get("blah")
			for c in manage_db():
				c.execute("select * from events where email=?",(email,))
				curr_tasks = []
				result = c.fetchone()
				if result['tasks'] is not None:
					curr_tasks = json.loads(result['tasks'])
				curr_tasks.append(new_task)
				curr_tasks.sort(key=lambda x: x["duration"], reverse=True)
				curr_tasks.sort(key=lambda x: x["deadline"])
				c.execute("insert or replace into events (tasks,email,data) values (:tasks,:email,(select data from events where email=:email))",{"email":email,"tasks":json.dumps(curr_tasks)})
			response = Response("a")
			return response(environ, start_response)
		if "removetasks" in request.path:
			position = int(request.form["position"])
			email = request.cookies.get("blah")
			response = Response()
			for c in manage_db():
				c.execute("select * from events where email=?",(email,))
				result = c.fetchone()
				if result['tasks'] is not None:
					curr_tasks = json.loads(result['tasks'])
					del curr_tasks[position]
					c.execute("insert or replace into events (tasks,email,data) values (:tasks,:email,(select data from events where email=:email))",{"email":email,"tasks":json.dumps(curr_tasks)})
				else:
					response.status_code = 404
			return response(environ, start_response)
		if "edittask" in request.path:
			deadline = tf_from_timestamp(request.form["deadline"]) * 1000
			name = request.form["name"]
			hours = int(request.form["hours"])
			minutes = int(request.form["minutes"])
			duration = 3600*hours + 60*minutes
			position = int(request.form["position"])
			repeat = request.form["repeat"]
			new_task = {"summary":name,"deadline":deadline,"duration":duration,"repeat":repeat}
			email = request.cookies.get("blah")
			response = Response()
			for c in manage_db():
				c.execute("select * from events where email=?",(email,))
				result = c.fetchone()
				curr_tasks = json.loads(result['tasks'])
				curr_tasks[position] = new_task
				c.execute("insert or replace into events (tasks,email,data) values (:tasks,:email,(select data from events where email=:email))",{"email":email,"tasks":json.dumps(curr_tasks)})
			return response(environ, start_response)
		if "loadtasks" in request.path:
			email = request.cookies.get("blah")
			for c in manage_db():
				c.execute("select tasks from events where email=?",(email,))
				result = c.fetchone()
			tasks = json.loads(result['tasks'])
			currtime = time.time() * 1000
			for task in tasks:
				if task['deadline'] < currtime or task['duration'] == 0:
					task['showAlertPane'] = True
			response = Response(json.dumps(tasks), mimetype="application/json")
			return response(environ, start_response)
		if "loadall" in request.path:
			email = request.cookies.get("blah")
			for c in manage_db():
				c.execute("select * from events where email=?",(email,))
				result = c.fetchone()
				events = json.loads(result['data'])
				tasks = json.loads(result['tasks'])
			currtime = time.time() * 1000
			tasks = [task for task in tasks if not (task['deadline'] < currtime or task['duration'] == 0)]
			events = [combine.Thing(x) for x in events]
			tasks = [combine.Thing(x) for x in tasks]
			events = sorted(events,key=lambda k:k.start)
			tasks = sorted(tasks,key=lambda k:k.start)
			toReturn = combine.combine(events,tasks)
			toReturn = [x.__dict__ for x in toReturn]
			globalError = False
			for elem in toReturn:
				if elem["type"] != 3:
					if elem["start"] < currtime:
						globalError = True
			response = Response(json.dumps({"error":globalError,"data":toReturn}), mimetype="application/json")
			return response(environ, start_response)
		if "startstop" in request.path:
			email = request.cookies.get("blah")
			position = int(request.form["position"])
			taskInProgress = False
			for c in manage_db():
				c.execute("select tasks from events where email=?",(email,))
				tasks = json.loads(c.fetchone()['tasks'])
				for task in tasks:
					if "startedTime" in task:
						taskInProgress = True
						task["duration"] = max(task["duration"] - (time.time() - task["startedTime"]),0)
						del task["startedTime"]
						c.execute("insert or replace into events (tasks,email,data) values (:tasks,:email,(select data from events where email=:email))",{"email":email,"tasks":json.dumps(tasks)})
						break
				if not taskInProgress:
					tasks[position]["startedTime"] = time.time()
					c.execute("insert or replace into events (tasks,email,data) values (:tasks,:email,(select data from events where email=:email))",{"email":email,"tasks":json.dumps(tasks)})
			response = Response()
			return response(environ, start_response)
		# if not, 404 this sucker
		response = Response()
		response.status_code = 404
		return response(environ, start_response)
	response = Response(f.read(), mimetype=mimetypes.guess_type(request.path)[0])
	return response(environ, start_response)

def translate_path(path):
	# abandon query parameters
	path = path.split('?',1)[0]
	path = path.split('#',1)[0]
	path = posixpath.normpath(urllib.unquote(path))
	words = path.split('/')
	words = filter(None, words)
	path = os.getcwd()
	for word in words:
		drive, word = os.path.splitdrive(word)
		head, word = os.path.split(word)
		if word in (os.curdir, os.pardir): continue
		path = os.path.join(path, word)
	return path

"""
def guess_type(path):
   extensions_map = mimetypes.types_map.copy()
   extensions_map.update({
        '': 'application/octet-stream', # Default
        '.c': 'text/plain',
        '.h': 'text/plain',
        })
   base, ext = posixpath.splitext(path)
   print base,ext
   if ext in extensions_map:
	   return extensions_map[ext]
   ext = ext.lower()
   if ext in extensions_map:
	   return extensions_map[ext]
   else:
	   return extensions_map['']
"""

if __name__ == '__main__':
	run_simple('0.0.0.0', 80, application, use_debugger=True, use_reloader=True)


from configparser import ConfigParser
from datetime import date, timedelta
from queue import Queue
from threading import Thread

from .dellin import DellinAPI
from .pecom import PecomAPI
from .gtd import GtdAPI
from .baikal import BaikalAPI
from .nrgtk import NrgtkAPI
from .dpd import DPDApi

class Calculator:
    """ Calculator class that gathers all delivery calculators and
    transfers config and delivery info to them.
    """
    def __init__(self, delivery_info: dict):
        self.config = ConfigParser()
        self.config.read('assets/data/config.ini')
        self.delivery_info = delivery_info
        self.delivery_info['produce_date'] = self.get_date()
        self.calculators = [
            DellinAPI,
            PecomAPI,
            GtdAPI,
            BaikalAPI,
            NrgtkAPI,
            DPDApi,
        ]
        self.result = []

    def thread_run(self, work: Queue, result: Queue):
        """ Function for running in threads
        work: queue with calc functions
        param: queue to put results from calc functions
        """
        while not work.empty():
            api_class = work.get_nowait()
            api = api_class(self.config, self.delivery_info)
            res = api.calculate()
            result.put_nowait(res)
            work.task_done()

    def calculate(self):
        """ Get result massages from all calc from self.calculators using queues and
        concatenate them in self.result string.
        Return: result massage
        """
        thread_count = len(self.calculators)
        work_queue = Queue()
        result_queue = Queue()

        for calc in self.calculators:
            work_queue.put(calc)

        for _ in range(thread_count):
            thread = Thread(target=self.thread_run, args=(work_queue, result_queue), daemon=True)
            thread.start()

        work_queue.join()

        while not result_queue.empty():
            self.result.append(result_queue.get_nowait())

        return sorted(self.result, key=lambda x: x['name'])

    @staticmethod
    def get_date():
        """ Get current date plus one day
        Return: date
        """
        elapsed_date = date.today() + timedelta(days=1)

        return elapsed_date.strftime('%Y-%m-%d')


import abc

from typing import TypeVar, Dict, Union

from .table import Table

__all__ = ["Database"]

T = TypeVar("T")

class Database(metaclass=abc.ABCMeta):
    """Manage all the tables"""

    def __init__(self) -> None:
        self.__tables: Dict[str, Table] = {}

        map(
            lambda t: self.add_table(t[1](t[0])),
            self.__annotations__.items(),
        )

        if not len(self.tables):
            raise ValueError("No tables defined")

    @property
    def tables(self) -> Dict[str, Table]:
        """Get all tables"""
        return self.__tables

    def add_table(self, table: Table) -> None:
        """Add a table to the database"""
        setattr(self, table.name, table)
        self.__tables[table.name] = table

    def get_table(self, name: str) -> Union[Table, int]:
        """Get table by name"""
        return self.tables.get(name, -1)


n = int(input())
st = list(map(str, input().split()) for _ in range(n))
s,t =list(zip(*st))
# print(t)
score_MAX = 0
index_MAX = 0
original = set()

for i in range(n):
    if s[i] in original:continue
    else:
        original.add(s[i])
        if score_MAX < int(t[i]):
            score_MAX = int(t[i])
            index_MAX = i
print(index_MAX+1)


# importing the necessary libraries
import unittest
from src.utils.drivers import ChromeDriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# creating the class for the tests
class RemovingAnItem(unittest.TestCase):
    # creating the setup for the tests
    def setUp(self) -> None:
        self.driver = ChromeDriver().get_chrome_driver()
        self.driver.implicitly_wait(5)
        self.driver.get("https://www.demoblaze.com/index.html")
        self.driver.maximize_window()

    # creating the teardown for the tests
    def tearDown(self) -> None:
        self.driver.quit()

    # the start of the test
    def test_1_removing_an_item_from_the_cart(self):
        # finding and pressing on a product
        first_button = WebDriverWait(self.driver, 3).until(EC.presence_of_element_located((By.XPATH,
                                                                                '/html/body/div[5]/div/'
                                                                                'div[2]/div/div[1]/div/'
                                                                                'div/h4')))
        first_button.click()
        # finding and pressing the "add to cart" button
        second_button = WebDriverWait(self.driver, 3).until(EC.presence_of_element_located((By.XPATH,
                                                                                '/html/body/div['
                                                                                '5]/div/div[2]/div['
                                                                                '2]/div/a')))
        second_button.click()
        # finding and pressing the cart button at the navigation bar
        third_button = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#cartur"
                                                                                )))
        third_button.click()
        # asserting that the correct page was opened
        assert self.driver.current_url == "https://www.demoblaze.com/cart.html"
        # finding and pressing on the button to remove an item from the cart
        fourth_button = WebDriverWait(self.driver, 3).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#tbodyid > "
                                                                                "tr > "
                                                                                "td:nth"
                                                                                "-child(4) > "
                                                                                "a")))
        fourth_button.click()
        # asserting that a change has happened
        assert self.driver.current_url == "https://www.demoblaze.com/cart.html#"


import sys
from pathlib import Path
from omegaconf import DictConfig, OmegaConf
import torch

import pycolmap

from pixsfm.refine_colmap import PixSfM
from pixsfm.configs import parse_config_path, default_configs
from pixsfm.util.database import COLMAPDatabase, pair_id_to_image_ids

torch.cuda.empty_cache()

def pairs_from_db(pairs_path: Path, database_path: Path):
    db = COLMAPDatabase.connect(str(database_path))
    pair_ids = db.execute("SELECT pair_id FROM matches").fetchall()
    pairs = [pair_id_to_image_ids(pids[0]) for pids in pair_ids]
    image_id_to_name = db.image_id_to_name()
    pairs = [(image_id_to_name[id1], image_id_to_name[id2])
             for id1, id2 in pairs]
    with open(pairs_path, "w") as doc:
        [doc.write(" ".join(pair) + "\n") for pair in pairs]
    db.close()

# BASE_PATH = '/home/gkiavash/Downloads/sfm_street_1'
# tag = 't1'

BASE_PATH = sys.argv[1]
tag = sys.argv[2]
config = sys.argv[3]

dataset = Path(BASE_PATH)
outputs = dataset / 'refined/'
outputs.mkdir(parents=True, exist_ok=True)

# Setup the paths
images = dataset / 'images/'
sift_sfm_dir = dataset / 'sparse/0/'
sift_database_path = dataset / "database.db"

sfm_dir = outputs / f'sfm_{tag}'
database_path = sfm_dir / f'database_refined_{tag}.db'
pairs_path = sfm_dir / "pairs.txt"
cache = sfm_dir / f'dense_features_{tag}.h5'
sfm_dir_colmap = sfm_dir / "colmap"

sfm_dir.mkdir(parents=True, exist_ok=True)
sfm_dir_colmap.mkdir(parents=True, exist_ok=True)

if config == "low":
    conf = OmegaConf.load(parse_config_path("low_memory"))
    print(type(conf), conf)
    conf['dense_features']['model'] = {"name": 'dsift'}
    # conf['dense_features']['device'] = "cpu"
    print(type(conf), conf)
else:
    conf = OmegaConf.load(parse_config_path("default"))

refiner = PixSfM(conf=conf)
# refiner = PixSfM(config)

# Refine keypoints in database
keypoints, ka_data, feature_manager = refiner.refine_keypoints_from_db(
    database_path,
    sift_database_path,
    images,
    cache_path=cache
)

pairs_from_db(pairs_path, database_path)
pycolmap.verify_matches(database_path, pairs_path)

# triangulate new points with poses from original model
reference_model = pycolmap.Reconstruction(sift_sfm_dir)
reconstruction = pycolmap.triangulate_points(reference_model, database_path, images, sfm_dir_colmap)

# Refine the resulting reconstruction
refiner.run_ba(
    reconstruction,
    images,
    cache_path=cache,
    # feature_manager=feature_manager
)

reconstruction.write(sfm_dir)
print('done')


# El área de un triángulo se puede calcular a partir de valor de dos de sus lados mediante  la fórmula
#                A=12absin(θ)

# Realiza un programa que pida el valor de los lados y el ángulo (en grados) y muestre el valor del área.

from math import radians, sin

ca = int(input("Ingresa la longitud del cateto adyacente: "))
hi = int(input("Ingresa la longitud de la hipotenusa: "))
angle = radians(int(input("Ingresa el valor del ángulo: ")))
res = (ca*hi*sin(angle))/2
print("El resultado es: " + str(res))


'''
Problema: João precisa calcular seu Índice de Massa Corporal (IMC) para avaliar seu peso ideal.
Sabendo que a fórmula para calcular o IMC é: peso ÷ altura², crie um programa que calcule e
informe a classificação do IMC.
'''

def imc(peso, altura):
    imc = peso / (altura*altura)
    if imc <= 18.5:
        return "Magreza"
    elif (imc > 18.5) and (imc <= 24.9):
        return "Saudável"
    elif (imc > 24.9) and (imc <= 29.9):
        return "Sobrepeso"
    elif (imc > 29.9) and (imc <= 39.9):
        return "Obesidade"
    else:
        return "Obesidade grave"

p = float(input("Informe seu peso (em kg): "))
a = float(input("Informe sua altura (em metros): "))

print(imc(p, a))

Lógica de Programação OO/Módulo 2 - Introdução a Programação/HipertextoPraticando2.py


import logging
import asyncio, os, json, time
from datetime import datetime
from aiohttp import web
from www.coroweb import add_routes

logging.basicConfig(level=logging.INFO)

async def logger_factory(app, handler):
    async def logger(request):
        logging.info('Request: %s %s' % (request.method, request.path))
        # await asyncio.sleep(0.3)
        return (await handler(request))
    return logger

@asyncio.coroutine
def response_factory(app, handler):
    @asyncio.coroutine
    def response(request):
        logging.info('Response handler...')
        r = yield from handler(request)
        # if isinstance(r, dict):
        #     template = r.get('__template__')
        resp = web.Response(body=str(r).encode('utf-8'))
        resp.content_type = 'text/html;charset=utf-8'
        return resp
    return response

@asyncio.coroutine
def init(loop):
    app = web.Application(loop=loop,middlewares=[logger_factory,response_factory])
    add_routes(app, 'www.handlers')
    srv = yield from loop.create_server(app.make_handler(), 'localhost', 8080)
    logging.info('server started at http://localhost:8080...')
    return srv

loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()


#-- coding: utf-8 --
#@Time : 30/12/2021 上午 11:00
#@Author : wkq

import torch
import numpy as np
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from sklearn.model_selection import train_test_split

# 读取原始数据，并划分训练集和测试集
raw_data = np.loadtxt('../resource/diabetes.csv', delimiter=',', dtype=np.float32)
X = raw_data[:, :-1]
y = raw_data[:, [-1]]
Xtrain, Xtest, Ytrain, Ytest = train_test_split(X, y, test_size=0.3)
Xtest = torch.from_numpy(Xtest)
Ytest = torch.from_numpy(Ytest)

# 将训练数据集进行批量处理
# prepare dataset

class DiabetesDataset(Dataset):
    def __init__(self, data, label):
        self.len = data.shape[0]  # shape(多少行，多少列)
        self.x_data = torch.from_numpy(data)
        self.y_data = torch.from_numpy(label)

    def __getitem__(self, index):
        return self.x_data[index], self.y_data[index]

    def __len__(self):
        return self.len

train_dataset = DiabetesDataset(Xtrain, Ytrain)
train_loader = DataLoader(dataset=train_dataset, batch_size=32, shuffle=True, num_workers=1)  # num_workers 多线程

# design model using class

class Model(torch.nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.linear1 = torch.nn.Linear(8, 6)
        self.linear2 = torch.nn.Linear(6, 4)
        self.linear3 = torch.nn.Linear(4, 2)
        self.linear4 = torch.nn.Linear(2, 1)
        self.sigmoid = torch.nn.Sigmoid()

    def forward(self, x):
        print(x.shape)
        x = self.sigmoid(self.linear1(x))
        x = self.sigmoid(self.linear2(x))
        x = self.sigmoid(self.linear3(x))
        x = self.sigmoid(self.linear4(x))
        return x

model = Model()

# construct loss and optimizer
criterion = torch.nn.BCELoss(reduction='mean')
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)

# training cycle forward, backward, update

def train(epoch):
    train_loss = 0.0
    count = 0
    for i, data in enumerate(train_loader, 0):
        inputs, labels = data
        y_pred = model(inputs)
        print(inputs.data.numpy().shape)
        print(labels.data.numpy().shape)
        loss = criterion(y_pred, labels)
        print(epoch, i, loss.item())
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        train_loss += loss.item()
        count = i

    if epoch % 2000 == 1999:
        print("train loss:", train_loss / count, end=',')

def test():
    with torch.no_grad():
        y_pred = model(Xtest)
        y_pred_label = torch.where(y_pred >= 0.5, torch.tensor([1.0]), torch.tensor([0.0]))
        acc = torch.eq(y_pred_label, Ytest).sum().item() / Ytest.size(0)
        print("test acc:", acc)

if __name__ == '__main__':
    for epoch in range(100):
        train(epoch)
        if epoch % 2000 == 1999:
            test()


from django.db import models

class Label(models.Model):
    name = models.CharField(
        max_length=50, verbose_name='Label of framework, library, language etc.')
    order = models.IntegerField(choices=[
        (1, 'Has to be at the front'),
        (2, 'Main categories'),
        (3, 'Front-end'),
        (4, 'Back-end'),
        (5, 'Has to be at the back'),
    ], default=1)

    class Meta():
        verbose_name = 'Label'
        verbose_name_plural = 'Labels'
        ordering = ['order', 'name']

    def __str__(self):
        return self.name

    @property
    def showcase_numbers_with_this_label(self):
        return self.showcase_set.count()

class Tech(models.Model):
    name = models.CharField(
        max_length=250, verbose_name='Techniques for technical sheet')

    class Meta():
        verbose_name = 'Technique'
        verbose_name_plural = 'Techniques'
        ordering = ['name']

    def __str__(self):
        return self.name

    @property
    def showcase_numbers_used_this_tech(self):
        return self.showcase_set.count()

class Showcase(models.Model):
    name = models.CharField(max_length=200, verbose_name='Showcase Name')
    brief = models.CharField(
        max_length=200, verbose_name='A brief of the showcase')
    about = models.TextField(verbose_name='About the showcase')
    labels = models.ManyToManyField(
        Label, blank=True)
    techs = models.ManyToManyField(
        Tech, blank=True)
    link_online = models.CharField(
        max_length=300, blank=True, null=True, verbose_name='Link to online presence')
    link_github = models.CharField(
        max_length=300, blank=True, null=True, verbose_name='Link to GitHub')
    link_codesandbox = models.CharField(
        max_length=300, blank=True, null=True, verbose_name='Link to CodeSandbox')

    img_front = models.ImageField(
        upload_to='showcase_images', null=True, blank=True, verbose_name='Image (size: 600px x 400px) to show on the front of the card')
    img_back = models.ImageField(
        upload_to='showcase_images', null=True, blank=True, verbose_name='Image (size: 600px x 400px) to show on the back of the card')
    img_third = models.ImageField(
        upload_to='showcase_images', null=True, blank=True, verbose_name='Image (size: 600px x 400px) to show in detail page (optional)')

    order = models.IntegerField(choices=[
        (1, 'NEW'),
        (2, 'Super Fine'),
        (3, 'Fine'),
        (4, 'Okay'),
        (5, 'Beginner'),
        (6, 'Doodle'),
    ], default=1)

    class Meta():
        verbose_name = 'Showcase'
        verbose_name_plural = 'Showcases'
        ordering = ['order', 'name']

    def __str__(self):
        return self.name

    @property
    def get_labels(self):
        return ", ".join([l.name for l in self.labels.all()])

    @property
    def get_techs(self):
        return ", ".join([t.name for t in self.techs.all()])

class Tag(models.Model):
    name = models.CharField(
        max_length=50, verbose_name='Keywords of the post')
    order = models.IntegerField(choices=[
        (1, 'Absolute front'),
        (2, 'Front'),
        (3, 'Middle'),
        (4, 'Back'),
        (5, 'Absolute back'),
    ], default=3)

    class Meta():
        verbose_name = 'Tag'
        verbose_name_plural = 'Tags'
        ordering = ['order', 'name']

    def __str__(self):
        return self.name

    @property
    def post_numbers_with_this_tag(self):
        return self.post_set.count()

class Post(models.Model):
    title = models.CharField(max_length=200, verbose_name='Post Title')
    tags = models.ManyToManyField(
        Tag, blank=True)
    content = models.TextField()
    uploaded_date = models.DateTimeField(null=True, blank=True)
    order = models.IntegerField(choices=[
        (1, 'Absolute front'),
        (2, 'Front'),
        (3, 'Middle'),
        (4, 'Back'),
        (5, 'Absolute back'),
    ], default=3)

    class Meta():
        verbose_name = 'Post'
        verbose_name_plural = 'Posts'
        ordering = ['order', '-uploaded_date', 'title']

    def __str__(self):
        return self.title

    @property
    def get_tags(self):
        return ", ".join([t.name for t in self.tags.all()])


#!/usr/bin/python

import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['mathtext.fontset'] = 'stix'
mpl.rcParams['font.family'] = 'STIXGeneral'

data = []
data.append(pd.read_csv('results/hist_work_v6_4800.dat', delimiter='\t'))
data.append(pd.read_csv('results/hist_work_v10_48.dat', delimiter='\t'))
data.append(pd.read_csv('results/hist_work_v30_48.dat', delimiter='\t'))
label = ['v = 6/4800', 'v = 10/48', 'v=30/48']

bins = int(sys.argv[1])

fig, ax = plt.subplots(1,3,layout='tight')
for j in range(len(data[0].columns)):
    avg = np.average(data[0].iloc[:,j])
    for i in range(len(data)):
        bin_heights, bin_borders, _ = ax[j].hist(data[i].iloc[:,j]-avg,bins,histtype='step', label=label[i])

fig.suptitle('Work histograms')
fig.text(0.5, 0.01, 'Work', ha='center')
ax[0].grid()
ax[0].set_title(r'$x_{c}=-6$')
ax[1].grid()
ax[1].set_title(r'$x_{c}=-9$')
ax[2].grid()
ax[2].set_title(r'$x_{c}=-3$')
ax[1].legend()

#plt.show()
plt.savefig('results/hist_work.png', format='png',bbox_inches='tight',dpi=300)


# -*- coding: utf-8 -*-
"""
Created on Sun May 15 20:08:27 2022

@author: User
"""
def avto_info(kompaniya,model,**malumotlar):
    """Avto haqidagi ma'lumotlarni lug'at ko'rinishdia qaytaruvchi funksiya"""
    malumotlar['kompaniya']=kompaniya
    malumotlar['model']=model
    return malumotlar

avto1 = avto_info("GM", "malibu", rang='qora', yil=2018)
avto2 = avto_info("Kia", "K5", rang='qizil', narh=35000,karobka='avtomat')

def multiply(*sonlar):
    kopaytma = 1
    for son in sonlar:
        kopaytma *= son
    return kopaytma

print(multiply(4,5,6))

#ixtiyoriy argument qoshish(*kwargs)
def talaba_info(ism, familiya, **kwargs):
    kwargs['ism']=ism
    kwargs['familiya']=familiya
    return kwargs

talaba = talaba_info('olim','olimov',tyil=1995,fakultet='IT',yonalish='AT')


from django.shortcuts import render
from .models import User
from django.core.files.storage import FileSystemStorage
import re
import cv2
import pytesseract
from django.conf import settings
from django.http import JsonResponse
def index(request):
    return render(request,'index.html')

def uploadImage(request):
    pytesseract.pytesseract.tesseract_cmd = "C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe"

    pi = request.FILES['image']
    fs = FileSystemStorage()
    print("request handling...")
    fs.save(pi.name,pi)
    img=cv2.imread(settings.MEDIA_ROOT+'\\'+pi.name)
    img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

    #print(pytesseract.image_to_boxes(img))
    himg , wimg, _ = img.shape

    boxes = pytesseract.image_to_data(img)

    print(boxes)
    for x,b in enumerate(boxes.splitlines()) :
        if x!=0:
            b = b.split()
            if len(b)==12:
                if isValidPanCardNo(b[11]):
                    print(b[11])
                    pno = b[11]
    #            x,y,w,h = int (b[6]),int (b[7]),int (b[8]),int (b[9])
    #            cv2.rectangle(img,(x,y),(w+x,y+h),(0,0,255),3)
    #            cv2.putText(img,b[11],(x,y),cv2.FONT_HERSHEY_COMPLEX,1,(50,50,255),2)
    print(img.shape)
    print(pi.name)
    print(pi.size)
    #return render(request,'index.html')
    return JsonResponse({
        "pan number" : pno
    })
# Create your views here.

def isValidPanCardNo(panCardNo):

    # Regex to check valid
    # PAN Card number
    regex = "[A-Z]{5}[0-9]{4}[A-Z]{1}"

    # Compile the ReGex
    p = re.compile(regex)

    # If the PAN Card number
    # is empty return false
    if(panCardNo == None):
        return False

    # Return if the PAN Card number
    # matched the ReGex
    if(re.search(p, panCardNo) and
       len(panCardNo) == 10):
        return True
    else:
        return False


import pygame
from input_manager import InputManager
from state_game_server import StateGameServer
from server import start_server, run

#initiate the pygame
pygame.init()
fpsClock = pygame.time.Clock()
#print("initializing clock: ", fpsClock)

#Manager class
class Manager:

    ##Screen
    width, height = 950, 600
    size = width, height

    screen  = pygame.display.set_mode(size)

    pygame.display.set_caption("SpaceInvaders")

    #Server
    server = start_server()

    #InputManager
    inputManager = InputManager()

    #Introduction state
    state = StateGameServer(screen, inputManager)

    #Main Loop
    def _run(self):
        self.gameOn = True

        while self.gameOn:
            run()
            dt = fpsClock.tick(30)

            #Inputs
            self.inputManager.update()

            #Updates
            self.update(dt)

            #Renders, put in the screen
            self.render()

    #Update
    def update(self, dt):
        #state updates
        new_state = self.state.update(dt)
        if (new_state == 0):
            return

    def set_state(self, state):
        self.state.destroy()
        self.state = state

    #Render
    def render(self):
        #state renders
        self.state.render()

        #updates the display
        pygame.display.update()

#Run the main loop
if "__main__" == __name__:

    manager = Manager()
    manager._run()


# Tests for Python charm helpers.

import unittest
import yaml
from testtools import TestCase

from io import StringIO

import sys
# Path hack to ensure we test the local code, not a version installed in
# /usr/local/lib.  This is necessary since /usr/local/lib is prepended before
# what is specified in PYTHONPATH.
sys.path.insert(0, 'helpers/python')
from charmhelpers.contrib import charmhelpers  # noqa

class CharmHelpersTestCase(TestCase):
    """A basic test case for Python charm helpers."""

    def _patch_command(self, replacement_command):
        """Monkeypatch charmhelpers.command for testing purposes.

        :param replacement_command: The replacement Callable for
                                    command().
        """
        self.patch(charmhelpers, 'command', lambda *args: replacement_command)

    def _make_juju_status_dict(self, num_units=1,
                               service_name='test-service',
                               unit_state='pending',
                               machine_state='not-started'):
        """Generate valid juju status dict and return it."""
        machine_data = {}
        # The 0th machine is the Zookeeper.
        machine_data[0] = {'dns-name': 'zookeeper.example.com',
                           'instance-id': 'machine0',
                           'state': 'not-started'}
        service_data = {'charm': 'local:precise/{}-1'.format(service_name),
                        'relations': {},
                        'units': {}}
        for i in range(num_units):
            # The machine is always going to be i+1 because there
            # will always be num_units+1 machines.
            machine_number = i + 1
            unit_machine_data = {
                'dns-name': 'machine{}.example.com'.format(machine_number),
                'instance-id': 'machine{}'.format(machine_number),
                'state': machine_state,
                'instance-state': machine_state}
            machine_data[machine_number] = unit_machine_data
            unit_data = {
                'machine': machine_number,
                'public-address':
                '{}-{}.example.com'.format(service_name, i),
                'relations': {'db': {'state': 'up'}},
                'agent-state': unit_state}
            service_data['units']['{}/{}'.format(service_name, i)] = (
                unit_data)
        juju_status_data = {'machines': machine_data,
                            'services': {service_name: service_data}}
        return juju_status_data

    def _make_juju_status_yaml(self, num_units=1,
                               service_name='test-service',
                               unit_state='pending',
                               machine_state='not-started'):
        """Convert the dict returned by `_make_juju_status_dict` to YAML."""
        return yaml.dump(
            self._make_juju_status_dict(
                num_units, service_name, unit_state, machine_state))

    def test_make_charm_config_file(self):
        # make_charm_config_file() writes the passed configuration to a
        # temporary file as YAML.
        charm_config = {'foo': 'bar',
                        'spam': 'eggs',
                        'ham': 'jam'}
        # make_charm_config_file() returns the file object so that it
        # can be garbage collected properly.
        charm_config_file = charmhelpers.make_charm_config_file(charm_config)
        with open(charm_config_file.name) as config_in:
            written_config = config_in.read()
        self.assertEqual(yaml.dump(charm_config), written_config)

    def test_unit_info(self):
        # unit_info returns requested data about a given service.
        juju_yaml = self._make_juju_status_yaml()
        self.patch(charmhelpers, 'juju_status', lambda: juju_yaml)
        self.assertEqual(
            'pending',
            charmhelpers.unit_info('test-service', 'agent-state'))

    def test_unit_info_returns_empty_for_nonexistent_service(self):
        # If the service passed to unit_info() has not yet started (or
        # otherwise doesn't exist), unit_info() will return an empty
        # string.
        juju_yaml = "services: {}"
        self.patch(charmhelpers, 'juju_status', lambda: juju_yaml)
        self.assertEqual(
            '', charmhelpers.unit_info('test-service', 'state'))

    def test_unit_info_accepts_data(self):
        # It's possible to pass a `data` dict, containing the parsed
        # result of juju status, to unit_info().
        juju_status_data = yaml.safe_load(
            self._make_juju_status_yaml())
        self.patch(charmhelpers, 'juju_status', lambda: None)
        service_data = juju_status_data['services']['test-service']
        unit_info_dict = service_data['units']['test-service/0']
        for key, value in unit_info_dict.items():
            item_info = charmhelpers.unit_info(
                'test-service', key, data=juju_status_data)
            self.assertEqual(value, item_info)

    def test_unit_info_returns_first_unit_by_default(self):
        # By default, unit_info() just returns the value of the
        # requested item for the first unit in a service.
        juju_yaml = self._make_juju_status_yaml(num_units=2)
        self.patch(charmhelpers, 'juju_status', lambda: juju_yaml)
        unit_address = charmhelpers.unit_info(
            'test-service', 'public-address')
        self.assertEqual('test-service-0.example.com', unit_address)

    def test_unit_info_accepts_unit_name(self):
        # By default, unit_info() just returns the value of the
        # requested item for the first unit in a service. However, it's
        # possible to pass a unit name to it, too.
        juju_yaml = self._make_juju_status_yaml(num_units=2)
        self.patch(charmhelpers, 'juju_status', lambda: juju_yaml)
        unit_address = charmhelpers.unit_info(
            'test-service', 'public-address', unit='test-service/1')
        self.assertEqual('test-service-1.example.com', unit_address)

    def test_get_machine_data(self):
        # get_machine_data() returns a dict containing the machine data
        # parsed from juju status.
        juju_yaml = self._make_juju_status_yaml()
        self.patch(charmhelpers, 'juju_status', lambda: juju_yaml)
        machine_0_data = charmhelpers.get_machine_data()[0]
        self.assertEqual('zookeeper.example.com', machine_0_data['dns-name'])

    def test_wait_for_machine_returns_if_machine_up(self):
        # If wait_for_machine() is called and the machine(s) it is
        # waiting for are already up, it will return.
        juju_yaml = self._make_juju_status_yaml(machine_state='running')
        self.patch(charmhelpers, 'juju_status', lambda: juju_yaml)
        machines, time_taken = charmhelpers.wait_for_machine(timeout=1)
        self.assertEqual(1, machines)

    def test_wait_for_machine_times_out(self):
        # If the machine that wait_for_machine is waiting for isn't
        # 'running' before the passed timeout is reached,
        # wait_for_machine will raise an error.
        juju_yaml = self._make_juju_status_yaml()
        self.patch(charmhelpers, 'juju_status', lambda: juju_yaml)
        self.assertRaises(
            RuntimeError, charmhelpers.wait_for_machine, timeout=0)

    def test_wait_for_machine_always_returns_if_running_locally(self):
        # If juju is actually running against a local LXC container,
        # wait_for_machine will always return.
        juju_status_dict = self._make_juju_status_dict()
        # We'll update the 0th machine to make it look like it's an LXC
        # container.
        juju_status_dict['machines'][0]['dns-name'] = 'localhost'
        juju_yaml = yaml.dump(juju_status_dict)
        self.patch(charmhelpers, 'juju_status', lambda: juju_yaml)
        machines, time_taken = charmhelpers.wait_for_machine(timeout=1)
        # wait_for_machine will always return 1 machine started here,
        # since there's only one machine to start.
        self.assertEqual(1, machines)
        # time_taken will be 0, since no actual waiting happened.
        self.assertEqual(0, time_taken)

    def test_wait_for_machine_waits_for_multiple_machines(self):
        # wait_for_machine can be told to wait for multiple machines.
        juju_yaml = self._make_juju_status_yaml(
            num_units=2, machine_state='running')
        self.patch(charmhelpers, 'juju_status', lambda: juju_yaml)
        machines, time_taken = charmhelpers.wait_for_machine(num_machines=2)
        self.assertEqual(2, machines)

    def test_wait_for_unit_returns_if_unit_started(self):
        # wait_for_unit() will return if the service it's waiting for is
        # already up.
        juju_yaml = self._make_juju_status_yaml(
            unit_state='started', machine_state='running')
        self.patch(charmhelpers, 'juju_status', lambda: juju_yaml)
        charmhelpers.wait_for_unit('test-service', timeout=0)

    def test_wait_for_unit_raises_error_on_error_state(self):
        # If the unit is in some kind of error state, wait_for_unit will
        # raise a RuntimeError.
        juju_yaml = self._make_juju_status_yaml(
            unit_state='start-error', machine_state='running')
        self.patch(charmhelpers, 'juju_status', lambda: juju_yaml)
        self.assertRaises(RuntimeError, charmhelpers.wait_for_unit,
                          'test-service', timeout=0)

    def test_wait_for_unit_raises_error_on_timeout(self):
        # If the unit does not start before the timeout is reached,
        # wait_for_unit will raise a RuntimeError.
        juju_yaml = self._make_juju_status_yaml(
            unit_state='pending', machine_state='running')
        self.patch(charmhelpers, 'juju_status', lambda: juju_yaml)
        self.assertRaises(RuntimeError, charmhelpers.wait_for_unit,
                          'test-service', timeout=0)

    def test_wait_for_relation_returns_if_relation_up(self):
        # wait_for_relation() waits for relations to come up. If a
        # relation is already 'up', wait_for_relation() will return
        # immediately.
        juju_yaml = self._make_juju_status_yaml(
            unit_state='started', machine_state='running')
        self.patch(charmhelpers, 'juju_status', lambda: juju_yaml)
        charmhelpers.wait_for_relation('test-service', 'db', timeout=0)

    def test_wait_for_relation_times_out_if_relation_not_present(self):
        # If a relation does not exist at all before a timeout is
        # reached, wait_for_relation() will raise a RuntimeError.
        juju_dict = self._make_juju_status_dict(
            unit_state='started', machine_state='running')
        units = juju_dict['services']['test-service']['units']
        # We'll remove all the relations for test-service for this test.
        units['test-service/0']['relations'] = {}
        juju_dict['services']['test-service']['units'] = units
        juju_yaml = yaml.dump(juju_dict)
        self.patch(charmhelpers, 'juju_status', lambda: juju_yaml)
        self.assertRaises(
            RuntimeError, charmhelpers.wait_for_relation, 'test-service',
            'db', timeout=0)

    def test_wait_for_relation_times_out_if_relation_not_up(self):
        # If a relation does not transition to an 'up' state, before a
        # timeout is reached, wait_for_relation() will raise a
        # RuntimeError.
        juju_dict = self._make_juju_status_dict(
            unit_state='started', machine_state='running')
        units = juju_dict['services']['test-service']['units']
        units['test-service/0']['relations']['db']['state'] = 'down'
        juju_dict['services']['test-service']['units'] = units
        juju_yaml = yaml.dump(juju_dict)
        self.patch(charmhelpers, 'juju_status', lambda: juju_yaml)
        self.assertRaises(
            RuntimeError, charmhelpers.wait_for_relation, 'test-service',
            'db', timeout=0)

    def test_wait_for_page_contents_returns_if_contents_available(self):
        # wait_for_page_contents() will wait until a given string is
        # contained within the results of a given url and will return
        # once it does.
        # We need to patch the charmhelpers instance of urlopen so that
        # it doesn't try to connect out.
        test_content = "Hello, world."
        self.patch(charmhelpers, 'urlopen',
                   lambda *args: StringIO(test_content))
        charmhelpers.wait_for_page_contents(
            'http://example.com', test_content, timeout=0)

    def test_wait_for_page_contents_times_out(self):
        # If the desired contents do not appear within the page before
        # the specified timeout, wait_for_page_contents() will raise a
        # RuntimeError.
        # We need to patch the charmhelpers instance of urlopen so that
        # it doesn't try to connect out.
        self.patch(charmhelpers, 'urlopen',
                   lambda *args: StringIO("This won't work."))
        self.assertRaises(
            RuntimeError, charmhelpers.wait_for_page_contents,
            'http://example.com', "This will error", timeout=0)

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


from contextlib import contextmanager

from ..util import resolveProcesses

class SequentialTextChecker:
    """Helper class for asserting that text is found in a certain order."""

    def __init__(self, output):
        self._output = output
        self._array_index = 0  # Keeps track of how far we are into the output array
        self._substring_index = 0  # Keeps track of how far we are into an individual string

    def assertInText(self, msg):
        return self.assertInStdout(msg)

    def assertInStdout(self, msg):

        # Keep local copies of the array index and the substring index.  We only advance them
        # if we find a matching string.

        array_index = self._array_index
        substring_index = self._substring_index

        for text in self._output[array_index:]:
            found = text.find(msg, substring_index)

            if found != -1:
                # We found the string!  Update the search state for the next string
                substring_index = found + len(msg)
                self._array_index = array_index
                self._substring_index = substring_index
                return

            # We failed to find the string.  Go around the loop again
            array_index += 1
            substring_index = 0

        assert False, (
            "'{}' not found in sequence after previous match.  "
            'The output near the last matched line:\n{}'
        ).format(
            msg,
            self.get_nearby_lines()
        )

    def get_nearby_lines(self):

        # This works by concatinating a few of the process_io outputs that we received, then
        # searching forward and backward for two return-lines in each direction, then returning
        # just that portion to give context about where a failure happened

        start_idx = max(0, self._array_index - 2)
        end_idx = self._array_index + 4

        full_text = ''.join(self._output[start_idx:end_idx])

        current_absolute_position = self._substring_index
        for txt in self._output[start_idx:self._array_index]:
            current_absolute_position += len(txt)

        start_abs_position = current_absolute_position
        for _ in range(3):
            start_abs_position = max(full_text.rfind('\n', 0, start_abs_position), 0)

        if start_abs_position != 0:
            # Complicated, but if the start_abs_position is not zero, it's pointed to a \n
            # we need to increment by 1 so the leading \n is not in the resulting text
            start_abs_position += 1

        end_abs_position = current_absolute_position
        for _ in range(3):
            end_abs_position = max(full_text.find('\n', end_abs_position + 1), end_abs_position)

        return full_text[start_abs_position:end_abs_position]

@contextmanager
def assertSequentialStdout(proc_output,
                           process,
                           cmd_args=None):
    """
    Create a context manager used to check stdout occurred in a specific order.

    :param proc_output:  The captured output from a test run

    :param process: The process whose output will be searched
    :type process: A string (search by process name) or a launch.actions.ExecuteProcess object

    :param cmd_args: Optional.  If 'proc' is a string, cmd_args will be used to disambiguate
    processes with the same name.  Pass launch_testing.asserts.NO_CMD_ARGS to match a proc without
    command arguments
    :type cmd_args: string
    """
    process = resolveProcesses(
        proc_output,
        process=process,
        cmd_args=cmd_args,
        # There's no good way to sequence output from multiple processes reliably, so we won't
        # pretend to be able to. Only allow one matching process for the combination of proc and
        # cmd_args
        strict_proc_matching=True,
    )[0]

    # Get all the output from the process.  This will be a list of strings.  Each string may
    # contain multiple lines of output
    to_check = [p.text.decode() for p in proc_output[process]]
    checker = SequentialTextChecker(to_check)

    try:
        yield checker
    except Exception:
        # Do we need to log this, or give a better message?  Need to re-raise so we can
        # cause the test to fail
        raise
    finally:
        # We don't need to do anything to finalize the checker here
        pass


from collections import Counter

import gym
import numpy as np
import pytest

from rl_agents.agents import ExpectedSarsaAgent, QLearningAgent, SarsaAgent
from rl_agents.agents.functions import QMatrixFunction, QTableFunction
from rl_agents.agents.policies import (
    BoltzmanPolicy,
    EDecreasePolicy,
    EGreedyPolicy,
)
from rl_agents.runners import simple_tab_runner

def gen_list():
    pis = [
        EGreedyPolicy(0.1),
        BoltzmanPolicy(10),
        EDecreasePolicy(0.9, 0.1, 0.9),
    ]
    funcs = [QMatrixFunction, QTableFunction]
    ags = [QLearningAgent, SarsaAgent, ExpectedSarsaAgent]
    mets = ["zeros", "ones", "random"]
    return [
        (v1, v2, v3, v4)
        for v1 in ags
        for v2 in pis
        for v3 in funcs
        for v4 in mets
    ]

@pytest.mark.parametrize("AgentC, policy, FunctionC, method", gen_list())
def test_frozen_lake(AgentC, policy, FunctionC, method):
    env = gym.make("FrozenLake-v0")
    q_func_kwargs = {"method": method}
    agent = AgentC(
        n_states=env.nS,
        n_actions=env.nA,
        alpha=0.4,
        gamma=0.5,
        policy=policy,
        q_function=FunctionC,
        q_func_kwargs=q_func_kwargs,
    )
    _ = simple_tab_runner(env, agent, 200)

@pytest.mark.parametrize("epsilon", [0.1, 0.5, 0.9])
def test_egreedy_policy(epsilon):
    n_tests = 10000
    # Best Q value is the index 1
    q_values = np.array([1, 5, 2, 1, 3])
    # Test valid values:
    policy = EGreedyPolicy(epsilon)
    counter = Counter([policy(q_values) for _ in range(n_tests)])
    # Test max value:
    assert counter.most_common(1)[0][0] == 1
    # Test Counting is approx epsilon:
    counts_max = counter.most_common()[0][1]
    counts_min = counter.most_common()[-1][1]
    assert counts_max > (1 - epsilon) * n_tests
    assert counts_min == pytest.approx(epsilon * n_tests / 5, rel=100)
    # Test get_values method:
    assert type(policy.get_values(q_values)) == type(q_values)
    assert len(policy.get_values(q_values)) == len(q_values)

@pytest.mark.parametrize(
    "epsilon, epsilon_min, decay", [(0.9, 0.5, 0.9), (0.5, 0.1, 0.8)]
)
def test_edecrease_policy(epsilon, epsilon_min, decay):
    n_tests = 10000
    # Best Q value is the index 1
    q_values = np.array([1, 5, 2, 1, 3])
    # Test valid values:
    policy = EDecreasePolicy(epsilon, epsilon_min, decay)
    ls = []
    for _ in range(n_tests):
        ls.append(policy(q_values))
        policy.update()
    counter = Counter(ls)
    # Test max value:
    assert counter.most_common(1)[0][0] == 1
    assert policy.epsilon == epsilon_min

@pytest.mark.parametrize("temperature", [10, 5, 1, 0.8])
def test_boltzman_policy(temperature):
    n_tests = 10000
    # Best Q value is the index 1
    q_values = np.array([1, 5, 2, 1.5, 3])
    true_order = [1, 4, 2, 3, 0]
    # Test valid values:
    policy = BoltzmanPolicy(temperature)
    counter = Counter([policy(q_values) for _ in range(n_tests)])
    print(counter.most_common())
    print(policy.get_values(q_values))
    # Test max value:
    assert counter.most_common(1)[0][0] == 1
    # Test Order:
    counter_order = [n[0] for n in counter.most_common()]
    assert counter_order == true_order
    # Test get_values method:
    assert type(policy.get_values(q_values)) == type(q_values)
    assert len(policy.get_values(q_values)) == len(q_values)

def test_policies_errors():
    with pytest.raises(ValueError):
        EGreedyPolicy(-0.1)
    with pytest.raises(ValueError):
        EGreedyPolicy(1.1)
    with pytest.raises(ValueError):
        EDecreasePolicy(1.1, 0.1, 0.9)
    with pytest.raises(ValueError):
        EDecreasePolicy(-0.2, 0.2, 0.8)
    with pytest.raises(ValueError):
        BoltzmanPolicy(-500)

def test_functions_errors():
    with pytest.raises(ValueError):
        QMatrixFunction(2, 2, "blabla")
    with pytest.raises(ValueError):
        QTableFunction(2, 2, "blablo")

def test_functions():
    # Test Initialization:
    q_func0 = QMatrixFunction(2, 2, "zeros")
    q_func1 = QMatrixFunction(2, 2, "ones")
    q_funcR = QMatrixFunction(2, 2, "random")
    assert q_func0(0, 0) == 0
    assert q_func1(0, 0) == 1
    assert q_funcR(0, 0) != q_funcR(0, 1)
    # Test update:
    q_value = 5.5
    q_func0.update(0, 0, q_value)
    q_func1.update(0, 0, q_value)
    q_funcR.update(0, 0, q_value)
    assert q_func0(0, 0) == 5.5
    assert q_func1(0, 0) == 5.5
    assert q_funcR(0, 0) == 5.5


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation
import random
def wykres_spaceru(nk):
    a = np.zeros(nk)
    x=0
    a[0]=x
    for i in range(1,nk):
        x=x+random.choice([-1, 1])
        a[i]=x
    t = np.arange(nk)
    plt.rcParams["figure.figsize"] = (10,5)
    plt.plot(t,a)
    plt.ylabel('x')
    plt.xlabel('numer kroku')

wykres_spaceru(100)
wykres_spaceru(100)

def koniec_spaceru(nk,ns):
    ks=np.zeros(ns)
    for i in range(ns):
        x=0
        for k in range(1,nk):
            x=x+random.choice([-1, 1])
        ks[i]=x
    return ks

xs = koniec_spaceru(101,10000)
plt.show()
nh, xh,pa = plt.hist(xs,85,histtype='stepfilled')
plt.xlabel('x_k')
plt.ylabel('czestosc')
plt.title('Histogram błądzenia losowego')
plt.show()