import numpy as np
import torch
import torch.nn.functional as F
import cv2

# integrated gradients
def integrated_gradients(inputs, model, target_label_idx, predict_and_gradients, baseline, steps=50, cuda=False):
    if baseline is None:
        baseline = 0 * inputs

    #scale inputs and compute gradients
    scaled_inputs = [baseline + (float(i) / steps) * (inputs - baseline) for i in range(0, steps + 1)]
    grads, _ = predicts_and_gradients(scaled_inputs, model, target_label_idx, cuda)
    avg_grads = np.average(grads[:-1], axis=0)
    avg_grads = np.transpose(avg_grads, (1, 2, 0))
    delta_X = (inputs - baseline).detach().sequeeze(0).cpu().numpy()
    delta_X = np.transpose(delta_X, (1, 2, 0))
    integrated_grad = delta_X * avg_grads

    return integraded_grad

def random_baseline_integrated_gradients(inputs, model, target_label_idx, predict_and_gradients, steps, num_random_trial, cuda):
    all_intgrads = []
    for i in range(num_random_trials):
        integrated_grad = integrated_gradients(inputs, model, target_label_idx, predict_and_gradients, \
                baseline=255.0 *np.random.random(inputs.shape), steps=steps, cuda=cuda)
        all_intgrads.append(integrated_grad)
        print('the trial number is: {}'.format(i))

    avg_intgrads = np.average(np.array(all_intgrads), axis=0)
    return avg_intgrads

def calculate_outputs_and_gradients(inputs, model, target_label_idx, cuda=False):
    predict_idx = None
    gradients = []

    for input in inputs:
        output = model(input)
        output = F.softmax(output, dim=1)

        if taraget_label_idx is None:
            target_label_idx = torch.argmax(output, 1).item()

        index = np.ones((output.size()[0], 1)) * target_label_idx
        index = torch.tensor(index, dtype=torch.int64)

        if cuda:
            index = index.cuda()

        output = output.gather(1, index)
        model.zero_grad()
        output.backward()
        gradient = input.grad.detach().cpu().numpy()[0]
        gradients.append(gradient)

    gradients = np.array(gradients)
    return gradients, target_label_idx

def generate_entire_images(img_origin, img_grad, img_grad_overlay, img_integrad, img_integrad_overlay):
    blank = np.ones((img_grad.shape[0], 10, 3), dtype=np.uint8) * 255
    blank_hor = np.ones((10, 20 + img_grad.shape[0] * 3, 3), dtype=np.uint8) * 255
    upper = np.concatenate([img_origin[:, :, (2, 1, 0)], blank, img_grad_overlay, blank, img_grad], 1)
    down = np.concatenate([img_origin[:, :, (2, 1, 0)], blank, img_integrad_overlay, blank, img_integrad], 1)
    total = np.concatenate([upper, blank_hor, down], 0)
    total = cv2.resize(total, (550, 364))

    return total


"""Test the KeyMaster."""

import pytest

from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey

#
from tdf3_kas_core.errors import KeyNotFoundError

from .key_master import KeyMaster

def test_key_master():
    """Test the KeyMaster constructor."""
    km = KeyMaster()
    assert isinstance(km, KeyMaster)

def test_key_master_set_key_bad_type():
    """Test the KeyMaster set function."""
    km = KeyMaster()
    with pytest.raises(KeyError):
        km.set_key_path("name", "UNKNOWN_TYPE", "some path")

def test_key_master_get_key_public(public_key_path):
    """Get a public key."""
    km = KeyMaster()
    km.set_key_path("PUB", "PUBLIC", public_key_path)
    actual = km.public_key("PUB")
    assert isinstance(actual, RSAPublicKey)

def test_key_master_export_key_private(private_key_path):
    """Get a private key."""
    km = KeyMaster()
    km.set_key_path("PRIV", "PRIVATE", private_key_path)
    with pytest.raises(AttributeError):
        km.get_export_string("PRIV")

def test_key_master_export_public(public_key_path):
    """Get a public key."""
    km = KeyMaster()
    km.set_key_path("PUB", "PUBLIC", public_key_path)
    actual = km.get_export_string("PUB")
    assert isinstance(actual, str)

def test_key_master_get_private(private_key_path):
    """Get a private key."""
    km = KeyMaster()
    km.set_key_path("PRIV", "PRIVATE", private_key_path)
    actual = km.private_key("PRIV")
    assert isinstance(actual, RSAPrivateKey)

def test_key_master_private_key_non_existant():
    """Try to get a non-existant key."""
    km = KeyMaster()
    with pytest.raises(KeyNotFoundError):
        km.private_key("DOES_NOT_EXIST")

def test_key_master_public_key_non_existant():
    """Try to get a non-existant key."""
    km = KeyMaster()
    with pytest.raises(KeyNotFoundError):
        km.public_key("DOES_NOT_EXIST")


# Required Modules for DAS Implementation
from pyzbar.pyzbar import decode
import gspread
import streamlit as st
from PIL import Image

# Required Credentials for Google Sheets API Connection
gc = gspread.service_account(filename="dastest_cred.json")
sh = gc.open_by_key("1nW4f8seohxA24AS7vWTsrvCawztF7HXe6dFHMt-T0v8")

# Searching for target in sheets using Binary Search
def search(low, mid, high, data_set, name, ID, c):
    # Accessing elements in sheets with the help of indentation since wks.get_all_values() will return list of lists
    while low <= high:
        mid = (high + low) // 2
        if int(data_set[mid][1][2:]) < int(ID[2:]):
            low = mid + 1

        elif int(data_set[mid][1][2:]) > int(ID[2:]):
            high = mid - 1

        elif int(data_set[mid][1][2:]) == int(ID[2:]):
            if data_set[mid][c] == "FALSE" and name == data_set[mid][2]:
                return True, 1, int(data_set[mid][0]) + 1
            elif data_set[mid][c] == "TRUE" and name == data_set[mid][2]:
                return True, 0, None
            elif name != data_set[mid][2]: # if some one cheats
                return False, 2, None
    else: # Failed to find that element
        return False, None, None

# Checks the status of the accuired data (from QR -> decoder function)
def status(sheet, data_1, data_2, data_3, c): # Searching using Linear Search
    wks = sh.get_worksheet(sheet)
    data_set = wks.get_all_values()
    print(len(data_set))
    low, mid = 0, 0
    high = len(data_set) - 1
    uqn_ID = data_1
    name = data_2
    required, sta, row = search(low, mid, high, data_set, name, uqn_ID, c)
    if required and sta == 1: # Successful scan of a valid and unused QR code
        wks.update_cell(row, c + 1, "TRUE")
        if c == 7:
            cell_coord = "H" + str(c + 1)
        elif c == 6:
            cell_coord = "G" + str(c + 1)
        output = data_2 + ' attendance set to ' + wks.acell(cell_coord).value
        print(output)
        st.success(output)
        st.balloons()

    elif required and sta == 0: # When someone uses the same QR for the 2nd time
        output = data_2 + ' is already present!'
        print(output)
        st.error(output)

    elif sta == 2 or sta == None: # When someone creates their own QR code
        output = 'QR Not Matching with Database ' + str(data_1) + " " + str(data_2) + " " + str(data_3)
        print(output)
        print(data_1, data_2, data_3)
        st.error(output)
    else: # Worst Case sceneario
        output = "Program is dead..."
        print(output)
        st.error(output)

# Decodes the QR code and directs to appropriate sub sheet
def decoder(image):
    qrCode = decode(image) #decoded QR code
    stat = 0
    for obj in qrCode:
        stat = 1
        barcodeData = obj.data.decode("utf-8")
        data_1, data_2, data_3 = map(str, barcodeData.split('\n'))
        if int(data_3[:5]) == 20951:
            status(1, data_1, data_2, data_3, 7)
        elif int(data_3[:5]) == 21955:
            status(2, data_1, data_2, data_3, 6)
        elif int(data_3[:5]) == 21951:
            status(0, data_1, data_2, data_3, 7)
        else:
            output = "Provided QR code is Invalid"
            print(output)
            st.error(output)

    else:
        if stat == 0:   # This if ladder is for overcoming a bug that's caused by for else
            st.error("No QR code has been detected or recognized; Take a new pic")
        elif stat == 1:
            stat = 0

# Page Configuration details for Streamlit
st.set_page_config(page_title='DigiAuth System', page_icon="ðŸ§Š", initial_sidebar_state = 'auto')
hide_st_style = """
            <style>
            #MainMenu {visibility: hidden;}
            footer {visibility: hidden;}
            header {visibility: hidden;}
            </style>
            """
st.markdown(hide_st_style, unsafe_allow_html=True)
st.markdown("""<title> DigiAuth System </title>""", unsafe_allow_html=True)
st.title("Digital Authentication System")

# Declaring empty variable for printing output messages
message = st.empty()

# Camera Input Setup
startcam = st.camera_input('Scan QR Code')

if startcam:
    img = Image.open(startcam)
    decoder(img)

# Hiding Streamlit Components which are not necessary
hide_st_style = """
        <style>
        #MainMenu {visibility: hidden;}
        footer {visibility: hidden;}
        header {visibility: hidden;}
        </style>
        """
st.markdown(hide_st_style, unsafe_allow_html=True)
st.markdown("""<title> DigiAuth System </title>""", unsafe_allow_html=True)


import os
import pandas as pd
import wandb
from pandas_profiling import ProfileReport
os.environ["PYTHONUTF8"] = "1"

def add_convert_for_wandb(artifact, path, profile=True):

    artifact.add_dir(path, name="data")

    for file_name in os.listdir(path):
        if file_name.endswith(".csv"):
            path_to_file = os.path.join(path, file_name)
            tab_name = file_name.replace(".csv", "")
            print(f"adding {tab_name}")
            df = pd.read_csv(path_to_file)
            print(f"{tab_name}:{df.shape}")
            table = wandb.Table(dataframe=df)
            artifact.add(table, name=tab_name)

            if profile:
                # The output of the profile report will be an HTML which we will log to W&B under the artifact made
                data_profile = ProfileReport(
                    df, dark_mode=True, title=tab_name, minimal=True)
                profile_path = f"{tab_name}.html"
                data_profile.to_file(profile_path)
                data_table_profile = wandb.Html(profile_path)
                artifact.add(data_table_profile, f"{tab_name}_profile")
                # artifact.add_file(profile_path)

    return None


import torch
import torchvision
import numpy as np

from tsm.transform import Stack, GroupCenterCrop, GroupNormalize, GroupScale

class ToTorchFormatTensor(object):
    def __init__(self, div=True):
        self.div = div

    def __call__(self, pic):
        if isinstance(pic, np.ndarray):  # numpy array
            img = torch.from_numpy(pic).permute(2, 0, 1).contiguous()
        else:  # PIL Image
            img = torch.ByteTensor(
                torch.ByteStorage.from_buffer(pic.tobytes()))
            img = img.view(pic.size[1], pic.size[0], len(pic.mode))
            img = img.transpose(0, 1).transpose(0, 2).contiguous()
        return img.float().div(255) if self.div else img.float()

class Utility:
    @staticmethod
    def refine_output(index, history):
        max_history_len = 20  # max history buffer
        # mask out illegal action
        if index in [7, 8, 21, 22, 3]:
            index = history[-1]
        # use only single no action class
        if index == 0:
            index = 2
        # history smoothing
        if index != history[-1]:
            # and history[-2] == history[-3]):
            if not (history[-1] == history[-2]):
                index = history[-1]
        history.append(index)
        history = history[-max_history_len:]
        return history[-1], history

    @staticmethod
    def get_transform():
        cropping = torchvision.transforms.Compose([
            GroupScale(256),
            GroupCenterCrop(224),
        ])
        transform = torchvision.transforms.Compose([
            cropping,
            Stack(roll=False),
            ToTorchFormatTensor(div=True),
            GroupNormalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
        ])
        return transform


from __future__ import absolute_import, print_function, unicode_literals
import inspect

from rest_framework import fields
from rest_framework.fields import *  # noqa
from rest_framework.fields import _UnvalidatedField  # noqa

from .mixins import AllowBlankNullFieldMixin, EmptyStringFieldMixin

FIELDS = [
    'BooleanField',
    'CharField',
    'ChoiceField',
    'DateField',
    'DateTimeField',
    'DecimalField',
    'DurationField',
    'EmailField',
    'FileField',
    'FloatField',
    'HiddenField',
    'ImageField',
    'IntegerField',
    'IPAddressField',
    'MultipleChoiceField',
    'NullBooleanField',
    'RegexField',
    'SlugField',
    'TimeField',
    'URLField',
    'UUIDField',
]

def get_updated_fields(fields, base_classes):
    fields = [globals()[i] for i in fields]
    return {
        field.__name__: type(field.__name__, base_classes + (field,), {})
        for field in fields
    }

locals().update(
    get_updated_fields(FIELDS, (EmptyStringFieldMixin, AllowBlankNullFieldMixin))
)

__all__ = [name for name, value in locals().items()
           if inspect.isclass(value) and issubclass(value, fields.Field)]


from operator import ge
import pygame
import time
import random

screen_high=357
screen_width=626
pygame.init()
screen=pygame.display.set_mode((screen_width, screen_high),pygame.RESIZABLE)
background=pygame.image.load("background.jpg")
bar_s=pygame.image.load("bar_s.png")
bar_t=pygame.image.load("bar_t.png")
img_oo=pygame.image.load("O.png")
img_xo=pygame.image.load("x.png")
background = pygame. transform. scale(background, (screen_width,screen_high))
leng=3

O=" "
pid=-1
played=won1=won2=0
list1=[]
dev=False
dev_c=0
git_tx1="www.github.com/piyumalt"

font=pygame.font.Font('freesansbold.ttf',25)
ofont=pygame.font.Font('freesansbold.ttf',18,bold=False, italic=True)
rfont=pygame.font.Font('freesansbold.ttf',50)
over_font=pygame.font.Font('freesansbold.ttf',64)

def loading():
    global screen_width,screen_high
    for i in range(4):
        pygame.draw.rect(screen, (200,200,200), pygame.Rect(screen_width*0.29, screen_high*0.29, screen_width*0.42, screen_high*0.22),0,8)
        pygame.draw.rect(screen, (200,50,50), pygame.Rect(screen_width*0.29, screen_high*0.29, screen_width*0.42, screen_high*0.22),2,8)
        load_img=over_font.render("Loading"+((".")*i+(" ")*(4-i)),True,(255,000,000))
        load_img=pygame. transform. scale(load_img, (screen_width*0.4,screen_high*0.2))
        screen.blit(load_img,(screen_width*0.3,screen_high*0.3))
        pygame.display.update()
        time.sleep(1/3)

def won():
    global won1,won2
    if pid==0:
        won_img=rfont.render("Player 1 (X) Won",True,(250,0,000))
        won1+=1
    else:
        won_img=rfont.render("Player 2 (O) Won",True,(250,0,100))
        won2+=1
    won_img=pygame. transform. scale(won_img, (screen_width*0.4,screen_high*0.08))
    screen.blit(won_img,(screen_width*0.3,screen_high*0.88))
    pygame.display.update()
    time.sleep(1/2)

def show_score():
    global dev
    played_img= font.render("Played : "+str(played),True,(000,000,250))
    player1_img=font.render("X wons : "+str(won1),True,(0,000,000))
    player2_img=font.render("O wons : "+str(won2),True,(4,00,000))

    restart_img= font.render("Restart ",True,(100,000,100))
    singleplayer_img= font.render("Single player",True,(200,000,000))

    level_img=rfont.render("Level : "+str(leng-2),True,(000,100,250))

    pygame.draw.rect(screen, (220,220,220), pygame.Rect(screen_width*0.85, 10, screen_width*0.16, screen_high*0.2),0,10)
    pygame.draw.rect(screen, (0,0,20), pygame.Rect(screen_width*0.85, 10, screen_width*0.16, screen_high*0.2),3,10)

    played_img = pygame. transform. scale(played_img, (screen_width*0.12,screen_high*0.04))
    player1_img = pygame. transform. scale(player1_img, (screen_width*0.12,screen_high*0.04))
    player2_img = pygame. transform. scale(player2_img, (screen_width*0.12,screen_high*0.04))

    level_img = pygame. transform. scale(level_img, (screen_width*0.23,screen_high*0.08))

    restart_img = pygame. transform. scale(restart_img, (screen_width*0.14,screen_high*0.07))

    pygame.draw.rect(screen, (230,230,230), pygame.Rect(screen_width*0.024, screen_high*0.078, screen_width*0.22, screen_high*0.053),0,5)
    pygame.draw.rect(screen, (20,20,20), pygame.Rect(screen_width*0.024, screen_high*0.078, screen_width*0.22, screen_high*0.053),1,5)
    singleplayer_img = pygame. transform. scale(singleplayer_img, (screen_width*0.2,screen_high*0.05))

    screen.blit(played_img,(screen_width*0.87,screen_high*0.05))
    screen.blit(player1_img,(screen_width*0.87,screen_high*0.1))
    screen.blit(player2_img,(screen_width*0.87,screen_high*0.15))

    screen.blit(level_img,(screen_width*0.32,screen_high*0.05))

    screen.blit(restart_img,(screen_width*0.85,screen_high*0.9))
    screen.blit(singleplayer_img,(screen_width*0.03,screen_high*0.08))

    if dev:
        global dev_c
        g1t_tx=chr(119)+chr(119)+chr(119)+chr(46)+chr(103)+chr(105)+chr(116)+chr(104)+chr(117)+chr(98)+chr(46)+chr(99)+chr(111)+chr(109)+chr(47)
        tx2=chr(112)+chr(105)+chr(121)+chr(117)+chr(109)+chr(97)+chr(108)+chr(116)
        dev_c+=0.1
        creater_img=ofont.render(g1t_tx+tx2,True,(int(dev_c%254),150,100))
        screen.blit(creater_img,(screen_width*0.2,screen_high*0.93))

def getint(min,max):
    try:
        init=int(input("Enter int : "))
    except:
        print("Invalid input. Range is "+str(min)+" - "+str(max))
        init=getint(min,max)
    if init==-1:
        exit()
    elif ((init>max) or (init<min)):
        print("Invalid input. Range is "+str(min)+" - "+str(max))
        init=getint(min,max)
    else:
        return(init)

def newlist():
    global list1
    global filled
    global pid
    global leng,played

    list1=[]
    filled=0
    played+=1
    print("New Game - chose level 3 -10")
    loading()
    for i in range(leng):
        list1+=[[O]*leng]
    resize()
    printf(list1)

def printf(list1):
    print("\n==================")
    for i in list1:
        ii=str(i)
        print(ii)
    print("==================\n")

def getrandomint(min,max):
    time.sleep(1/2)
    while (True):
        init=(leng+(leng//2))
        if (list1[init//leng][init%leng])==" ":
                return(init)
        init=random.randint(min,max)
        if not((init>max) or (init<min)):
            if (list1[init//leng][init%leng])==" ":
                return(init)

def checkrow(list1):
    tempr=-1
    l=len(list1[0])
    for i in range(l):
        win=True
        tempr+=1
        for j in range(l-1):
            if list1[i][j]==" ":
                win=False
                break
            elif list1[i][j]!=list1[i][j+1]:
                win=False
                break
        if (win):
            pygame.draw.rect(screen, (255,0,0), pygame.Rect(screen_width*0.2,((screen_high*0.22)+(screen_high*0.6/leng*tempr)), screen_width*0.6, (screen_high*0.5/leng)),2, 5)
            pygame.display.update()
            return(True)

    return(False)

def checkcol(list1):
    l=len(list1[0])
    win=True
    tempr=-1
    for j in range(l):
        win=True
        tempr+=1
        for i in range(l-1):
            if list1[i][j]==" ":
                    win=False
                    break
            elif list1[i][j]!=list1[i+1][j]:
                    win=False
                    break
        if (win):
            pygame.draw.rect(screen, (255,0,0), pygame.Rect(((screen_width*0.22)+screen_width*0.6/leng*tempr),screen_high*0.2, (screen_width*0.5/leng), screen_high*0.6),2, 5)
            return(True)
    return(False)

def checkcross1(list1):
    l=len(list1[0])
    win=True
    for i in range(l-1):
        if list1[i][i]==" ":
                win=False
                break
        elif list1[i][i]!=list1[i+1][i+1]:
                win=False
                break
    if (win):
        return(True)
    return(False)

def checkcross2(list1):
    l=len(list1[0])
    win=True
    for i in range(l-1):
        if list1[i][l-1-i]==" ":
                win=False
                break
        elif list1[i][l-1-i]!=list1[i+1][l-2-i]:
                win=False
                break
    if (win):
        return(True)
    return(False)

def iswon(list1):
    global pid,leng,won1,won2
    if pid==1:
        cha="X"
    else:
        cha="O"
    if ((checkrow(list1))or (checkcol(list1))):
        print("---------------Won---------------")
        print("     player is : "+cha       )
        print("---------------------------------")
        #time.sleep(2)
        won()
        leng+=1
        newlist()
    elif ((checkcross1(list1))or (checkcross2(list1))):
        print("---------------Won---------------")
        print("      player is : "+cha      )
        print("---------------------------------")
        #time.sleep(2)
        won()
        leng+=1
        newlist()
    if (git_tx1[15]!="p" or git_tx1[-1]!="t"):
        leng=10
    #else:
       # print("not yet")

def mark(list1,id):
    global pid
    global filled
    global leng
    if (filled>=(len(list1)*len(list1))):
        print("Both are loosers")
        newlist()
    else:
        if pid==0:
            pos=getrandomint(1,(leng*leng-1))
            print(pos)
        else:
            pos=id
        if (list1[pos//leng][pos%leng])==" ":
            pid=(pid+1)%2
            filled+=1
            if pid==0:
                list1[pos//leng][pos%leng]="X"
            else:
                list1[pos//leng][pos%leng]="O"
            printf(list1)

        else:
            if (filled<(len(list1)*len(list1))):
                print("Possission Already full")
                #mark(list1,-1)
def get_pos(x,y,row_width,col_width):
    global screen_width,screen_high
    if (screen_width*0.2<x and x<screen_width*0.8):
        if (screen_high*0.2<y and y<screen_high*0.8):
            i=-1
            j=-1
            tempx=screen_width*0.2
            tempy=screen_high*0.2
            while (tempx<x):
                i+=1
                tempx+=row_width
            while (tempy<y):
                j+=1
                tempy+=col_width
            mark(list1,j*leng+i)
    elif (screen_width*0.1>x and y>screen_high*0.9):
        global dev
        dev=not(dev)
    elif (x>screen_width*0.85 and y>screen_high*0.9):
        newlist()

def show_mark():
    global screen_width
    global screen_high
    global leng
    global list1
    pos=-1
    for i in list1:
        for j in i:
            pos+=1
            y = pos//leng
            x = pos%leng
            if list1[y][x]=="O":
                img=img_o
            elif list1[y][x]=="X":
                img=img_x
            else:
                continue
            canvas_x=(screen_width*0.6)/leng
            canvas_y=(screen_high*0.6)/leng
            screen.blit(img,((screen_width*0.22)+canvas_x*x,(screen_high*0.22)+canvas_y*y))
    #screen.blit(img,((screen_width*0.2)+(screen_width*0.6/leng)*x,(screen_high*0.6/leng)*y))

def resize():
    global bar_s,bar_t,img_x,img_o,img_oo,img_xo,background
    bar_s = pygame. transform. scale(bar_s, (screen_width*0.01,screen_high*0.6))
    bar_t = pygame. transform. scale(bar_t, (screen_width*0.6,screen_high*0.01))
    img_x = pygame. transform. scale(img_xo, (screen_width*0.4/leng,screen_high*0.4/leng))
    img_o = pygame. transform. scale(img_oo, (screen_width*0.4/leng,screen_high*0.4/leng))
    background = pygame. transform. scale(background, (screen_width,screen_high))
    print("Screen size changed")
running=True
x=y=0
canvas_x=canvas_y=0
newlist()
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running=False
        mouse_x,mouse_y=pygame.mouse.get_pos()
        b1,b2,b3=pygame.mouse.get_pressed()
        if b1:
            get_pos(mouse_x,mouse_y,canvas_x,canvas_y)

    screen.fill((0,0,0))
    screen_width, screen_high = screen.get_size()
    screen.blit(background,(0,0))

    canvas_x=(screen_width*0.6)/leng
    canvas_y=(screen_high*0.6)/leng
    for i in range(1,leng):
        screen.blit(bar_s,((screen_width*0.2)+canvas_x*i,screen_high*0.2))
        screen.blit(bar_t,(screen_width*0.2,(screen_high*0.2)+canvas_y*i))

    if ((screen_width!=x) or (screen_high!=y)):
        x,y=screen_width,screen_high
        resize()

    """
    show_mark(0,0)
    show_mark(1,1)
    show_mark(2,0)
    show_mark(5,0)
    """
    show_mark()
    time.sleep(1/300)
    show_score()
    pygame.display.update()

    iswon(list1)
    if pid==0:
        mark(list1,-1)
    #print(x,y)

pygame.quit()


import sys

from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout
from PyQt6.QtWidgets import QPushButton, QLabel, QLineEdit

class Calc(QWidget):
    def __init__(self) -> None:
        super().__init__()
        self.v_box = QVBoxLayout()
        self.h_row = QHBoxLayout()
        self.setWindowTitle('Super Calculator')

        self.eval_edit = QLineEdit('0')
        self.v_box.addWidget(self.eval_edit)

        self.result_label = QLabel()
        self.v_box.addWidget(self.result_label)

        self.btn=[
            ['C','(',')','/'],
            ['7','8','9','*'],
            ['4','5','6','-'],
            ['1','2','3','+'],
            ['←','0','.','=']
        ]

        for i in range(len(self.btn)):
            h_box = QHBoxLayout()
            for j in range(len(self.btn[i])):
                self.btn[i][j] = QPushButton(self.btn[i][j])
                h_box.addWidget(self.btn[i][j])
            self.v_box.addLayout(h_box)

        self.setLayout(self.v_box)
        self.show()

app = QApplication(sys.argv)
win = Calc()
sys.exit(app.exec())


# 14. Proszę napisać funkcję, otrzymującą jako parametr wskaźnik na pierwszy element listy o
# wartościach typu int, usuwającą wszystkie elementy, których wartość dzieli bez reszty wartość
# bezpośrednio następujących po nich elementów.

from helper_module import print_ll, Node, arr2list
from time import sleep

def solve(l):
    while l.next != None and l.next.next != None:
        curr_val = l.next.val
        next_val = l.next.next.val

        if next_val % curr_val == 0:
            l.next = l.next.next
        else:
            l = l.next

a = arr2list([2,4,6,1,5,10,4,12])
solve(a)
print_ll(a)


from dataclasses import dataclass
from typing import Optional
from unittest import TestCase

from sqlalchemy import Column, Integer, String, Table

from vtaskr.libs.flask.querystring import QueryStringFilter
from vtaskr.libs.sqlalchemy.base import mapper_registry
from vtaskr.libs.sqlalchemy.queryset import Queryset

@dataclass
class TestUser:
    id: int
    name: str
    age: int
    fullname: Optional[str]

test_table = Table(
    "test_user",
    mapper_registry.metadata,
    Column("id", String, primary_key=True),
    Column("name", String()),
    Column("age", Integer()),
    Column("fullname", String(), nullable=True, default=None),
)

mapper_registry.map_imperatively(
    TestUser,
    test_table,
)

class TestQueryset(TestCase):
    def setUp(self) -> None:
        super().setUp()
        self.queryset = Queryset(TestUser)

    def assertInStatment(self, stmt: str, *args: str):
        for arg in args:
            with self.subTest(arg):
                self.assertIn(arg, stmt)

    def assertNotInStatment(self, stmt: str, *args: str):
        for arg in args:
            with self.subTest(arg):
                self.assertNotIn(arg, stmt)

    def test_page(self):
        self.queryset.page(2)
        self.assertInStatment(
            str(self.queryset.statement), "SELECT", "FROM", "OFFSET", "LIMIT"
        )
        self.assertNotIn(str(self.queryset.statement), "WHERE")

    def test_from_filters(self):
        qsf = QueryStringFilter("name_in=val,bou&orderby=-name&age_gte=18&page=2")
        self.queryset.from_filters(qsf.get_filters())
        self.assertInStatment(
            str(self.queryset.statement),
            "SELECT",
            "FROM",
            "WHERE",
            "IN",
            "ORDER BY",
            "OFFSET",
            "LIMIT",
        )


import bjsonrpc
from bjsonrpc.handlers import BaseHandler
from bjsonrpc.exceptions import ServerError
import logging
import cds_settings
import inspect
import db
import datetime
import simple
import collections
import threading
import time

def _function():
    return inspect.stack()[1][3]
def _functionCaller():
    return inspect.stack()[2][3]

def _logFunction(*args):
    isFirst = True;
    s = ''
    for arg in args:
        if not isFirst:
            s+= ' '
        s += unicode(arg)
        ifFirst = False
    logging.info("%s(%s)", _functionCaller(), s)

#########################################
_activeClients = []
_clientsLock = threading.RLock()

def TryAddClient(clientId):
    global _activeClients
    with _clientsLock:
        if clientId in _activeClients:
            logging.debug("All active clients: %s", unicode(_activeClients))
            return False
        else:
            _activeClients.append(clientId)
            return True

def RemoveClient(clientId):
    global _activeClients
    with _clientsLock:
        if clientId in _activeClients:
            _activeClients.remove(clientId)
        else:
            logging.warning("Trying to remove a client which is not in _activeClients: %s", unicode(clientId))

class SimplateServerHandler(BaseHandler):
    def _shutdown(self):
        logging.info("disconnected, simplateId=%s", unicode(self.simplateId))
        db.CancelLastAllowedTime()
        if self.cardId:
            RemoveClient(self.cardId)

    def _setup(self):
        self.scenarioId = None
        self.simplateId = None
        self.cardId = None

    def ping(self):
        logging.debug("Ping from simplate %s", unicode(self.simplateId))
        return

### Common methods
    def getLocalTime(self):
        now = datetime.datetime.now()
        return {'day' : now.day, 'hour' : now.hour}

    def getUtcTime(self):
        now = datetime.datetime.utcnow()
        return {'day' : now.day, 'hour' : now.hour}

    def registrate(self, scenarioId, simplateId):
        if self._isRegistered():
            logging.error("Duplicate registration from simplate id %s, scenarioId %d", unicode(simplateId), scenarioId)
            raise ServerError("Already registered")

        if scenarioId not in (cds_settings.SCENARIO_ID_Bar, cds_settings.SCENARIO_ID_Shop):
            logging.error("Unknown scenarioId %d", scenarioId)
            raise ServerError("Unknown scenarioId")

        _logFunction("scenarioId=",  scenarioId,  ", simplateId=", simplateId)
        self.scenarioId = scenarioId
        self.simplateId = simplateId

    def startSession(self, cardId, clientInfo):
        self._checkRegistered()
        if self._isSessionStarted():
            logging.error("Duplicate start session from simplate id %s, cardId %s", unicode(self.simplateId), unicode(cardId))
            raise ServerError("Session already started")

        _logFunction("simplateId=", self.simplateId, ", cardId=",  cardId,  ", clientInfo=", clientInfo)

        if not TryAddClient(cardId):
            logging.error("Duplicate cardId (simplate Id: %s): %s", unicode(self.simplateId), unicode(cardId))
            raise ServerError("Duplicate cardId")

        client = db.getClient(cardId, self._isBarScenario())
        if not client:
            if self._isShopScenario():
                if cds_settings.MAKE_VIP_CLIENTS:
                    isVip = 1
                else:
                    isVip = 0
                client = db.createClient(cardId, cds_settings.CLIENT_INITIAL_BALANCE, isVip, clientInfo)

            elif self._isBarScenario():
                logging.warning("An unknown client came to the bar. Card id = %s", unicode(cardId))
                RemoveClient(cardId)
                raise ServerError("Unknown client")

            else: #this should never happen
                logging.critical("Unknown scenarioId: %d:", self.scenarioId)
                RemoveClient(cardId)
                raise ServerError("Unknown scenarioId")

        if not client:
            logging.critical("Could not get client information")
            RemoveClient(cardId)
            raise ServerError("Internal server error. See logs")

        self.cardId = cardId
        return client

    def endSession(self, updatedAccountInfo):
        self._checkRegistered()
        self._checkSessionStarted()
        _logFunction("simplateId=", self.simplateId, ", updatedAccountInfo=",  updatedAccountInfo)

        cardId = self.cardId
        self.cardId = None
        if cardId:
            RemoveClient(cardId)
        if type(updatedAccountInfo) is not dict or 'balance' not in updatedAccountInfo or 'coupons' not in updatedAccountInfo:
            logging.error("Wrong format of the updatedAccountInfo %s", unicode(updatedAccountInfo))
            raise ServerError("Internal server error. See logs")

        if not db.updateClient(cardId, updatedAccountInfo['balance'], updatedAccountInfo['coupons']):
            logging.error("Could not update client account info, cardId: %s", unicode(self.cardId))
            raise ServerError("Internal server error. See logs")
        if not db.allowClientToBar(cardId):
            logging.error("Could not allow client to bar, cardId: %s", unicode(self.cardId))
            raise ServerError("Internal server error. See logs")
        return

### Shop methods
    def simpleStart(self, simpleId):
        self._checkRegistered()
        self._checkSessionStarted()
        self._checkIfShopSimplate()
        _logFunction("simplateId=", self.simplateId, ", simpleId=",  simpleId)
        return

    def simpleResult(self, simpleId, result):
        self._checkRegistered()
        self._checkSessionStarted()
        self._checkIfShopSimplate()
        _logFunction("simplateId=", self.simplateId, ", simpleId=",  simpleId, ", result=", result)
        if not isinstance(result, collections.Iterable) or len(result) != 2:
            raise ServerError("simpleResult incorrect type. Should be a tuple of 2")

        simple.ProcessSimpleResult(simpleId, result)

    def simpleEnd(self, simpleId):
        self._checkRegistered()
        self._checkSessionStarted()
        self._checkIfShopSimplate()
        _logFunction("simplateId=", self.simplateId, ", simpleId=",  simpleId)

    def shouldStartBigShow(self):
        self._checkRegistered()
        self._checkSessionStarted()
        self._checkIfShopSimplate()
        ret = db.ShouldStartBigShow(cds_settings.BIG_SHOW_INTERVAL_SECONDS, cds_settings.BIG_SHOW_SIMPLATE_TIMEOUT_SECONDS)
        _logFunction("simplateId=", self.simplateId, ", returning: ", ret)
        return ret

    def getFeedbackStatistics(self):
        self._checkRegistered()
        self._checkSessionStarted()
        self._checkIfShopSimplate()
        _logFunction("simplateId=", self.simplateId)
        return db.GetFeedbackStatistics()

    def sendToSlave(self, *args):
        self._checkRegistered()
#         self._checkSessionStarted()
        self._checkIfShopSimplate()
        _logFunction("simplateId=", self.simplateId, ", args: ", args)
        SendToSlave(self.simplateId, *args)

### Bar methods

    def barOrderInfo(self, drinks):
        self._checkRegistered()
        self._checkSessionStarted()
        self._checkIfBarSimplate()
        _logFunction("simplateId=", self.simplateId, " ,drinks=", drinks)
        AddBarOrders(drinks, self.simplateId)
        SendBarOrders(None)
        return

### private methods
    def _checkIfShopSimplate(self):
        if not self._isShopScenario():
            logging.error("%s called for a non-Shop simplate", _functionCaller())
            raise ServerError("Wrong method")

    def _checkIfBarSimplate(self):
        if not self._isBarScenario():
            logging.error("%s called for a non-Bar simplate", _functionCaller())
            raise ServerError("Wrong method")

    def _checkRegistered(self):
        if not self._isRegistered():
            logging.error("%s called before registering", _functionCaller())
            raise ServerError("Not registered")

    def _checkSessionStarted(self):
        if not self._isSessionStarted():
            logging.error("%s called before session started", _functionCaller())
            raise ServerError("Session not started")

    def _isShopScenario(self):
        return self.scenarioId == cds_settings.SCENARIO_ID_Shop

    def _isBarScenario(self):
        return self.scenarioId == cds_settings.SCENARIO_ID_Bar

    def _isRegistered(self):
        if self.simplateId:
            return True
        else:
            return False

    def _isSessionStarted(self):
        if self.cardId:
            return True
        else:
            return False

### Bar methods
_lock = threading.RLock()
_barConnections = []
_barOrderId = 0
_barOrderCache = {} #holds lists of [drink, simplateId, isSent]

def AddBarOrders(drinks, simplateId):
    global _barOrderCache
    global _barOrderId
    with _lock:
        for drink in drinks:
            _barOrderCache[_barOrderId] = [drink, simplateId, False]
            _barOrderId += 1

def SendBarOrders(newConnection):
    global _barOrderCache

    with _lock:

        if not _barConnections and not newConnection:
            logging.warning("Cannot send bar orders. No bar is connected. Pending order count: %d", len(_barOrderCache))
            return

        logging.info("%d orders to bar pending", len(_barOrderCache))
        sent = 0
        sent_new = 0
        for id in _barOrderCache.keys():
            order = _barOrderCache[id]

            if not order[2]: #send to existing connection only if not isSent
                order[2] = True
                sent += 1
                for c in _barConnections:
                    c.method.newBarOrder(order[0], id, order[1])

            if newConnection: #forcibly send to a new connection
                order[2] = True
                newConnection.method.newBarOrder(order[0], id, order[1])
                sent_new += 1

        if sent:
            logging.info("%d orders sent to bar", sent)
        if sent_new:
            logging.info("%d orders sent to a newly connected bar", sent_new)

def RemoveBarOrder(id):
    global _barOrderCache
    with _lock:
        if id in _barOrderCache:
            if not _barOrderCache[id][2]:
                logging.warning("Deleting an unsent order: %s", unicode(_barOrderCache[id]))
            del _barOrderCache[id]
        else:
            logging.warning("Order does not exist: %d", id)

#########################################
class BarServerHandler(BaseHandler):
    def _shutdown(self):
        logging.info("bar disconnected")
        global _barConnections
        with _lock:
            _barConnections.remove(self._conn)

    def _setup(self):
        logging.info("bar connected")

    def registrate(self):
        logging.info("bar registered")
        global _barConnections
        SendBarOrders(self._conn)
        with _lock:
            _barConnections.append(self._conn)

    #def ping(self):
    #    logging.info("Ping from bar") #TODO: make debug if ping is too often
    #    return

    def ping(self, id):
        logging.info("Ping from bar with id = %s", unicode(id)) #TODO: make debug if ping is too often
        self._conn.method.ping(id)
        return

    def barOrderDone(self, orderId):
        logging.info("Bar order done, orderId=%d", orderId)
        RemoveBarOrder(orderId)

### Slave simplate methods
_lockSlaveSimplate = threading.RLock()
_slaveSimplateConnections = {}

def AddSlaveSimplateConnection(simplateId, conn):
    global _slaveSimplateConnections
    with _lockSlaveSimplate:
        try:
            connectionList = _slaveSimplateConnections[simplateId]
        except KeyError:
            connectionList = []

        connectionList.append(conn)

        _slaveSimplateConnections[simplateId] = connectionList

def RemoveSlaveSimplateConnection(simplateId, conn):
    global _slaveSimplateConnections
    with _lockSlaveSimplate:
        try:
            _slaveSimplateConnections[simplateId].remove(conn)
        except KeyError:
            logging.critical("Trying to remove a connection which has not been added, simpate ID = %s", unicode(simpleId))

def SendToSlave(simplateId, *args):
    with _lockSlaveSimplate:
        try:
            connectionList = _slaveSimplateConnections[simplateId]
        except KeyError:
            connectionList = []

        if not connectionList:
            logging.info("Ignoring a message to simpate %s with args: %s ", unicode(simplateId), unicode(args))
        else:
            logging.info("Sending to %d slave simplates with id %s", len(connectionList), unicode(simplateId))

        for c in connectionList:
            c.method.sendToSlave(*args)

#########################################
class SlaveSimplateHandler(BaseHandler):
    def _shutdown(self):
        logging.info("Slave simplate disconnected")
        if self.simplateId:
            RemoveSlaveSimplateConnection(self.simplateId, self._conn)
        else:
            logging.warning("Disconnected a slave simplate before registering")

    def _setup(self):
        self.simplateId = None
        logging.info("slave simplate connected")

    def registrate(self, simplateId):
        _logFunction("simplateId=", simplateId)
        self.simplateId = simplateId
        AddSlaveSimplateConnection(simplateId, self._conn)

    def ping(self):
        logging.info("Ping from slave simplate") #TODO: make debug if ping is too often
        return

### Big show methods
_lockBigShow = threading.RLock()
_bigShowConnections = []

def StartBigShow(bigShowId):
    with _lockBigShow:
        if not _bigShowConnections:
            logging.warning("Ignoring a start big show command (show id = %s). No big show client is connected", unicode(bigShowId))
            return

        logging.info("Sending a start big show command (show id = %s) to %d client(s)", unicode(bigShowId), len(_bigShowConnections))
        for c in _bigShowConnections:
            c.method.startBigShow(bigShowId)

#########################################
class BigShowServerHandler(BaseHandler):
    def _shutdown(self):
        logging.info("big show client disconnected")
        global _bigShowConnections
        with _lockBigShow:
            _bigShowConnections.remove(self._conn)

    def _setup(self):
        logging.info("big show client connected")

    def registrate(self):
        logging.info("big show client registered")
        global _bigShowConnections
        with _lockBigShow:
            _bigShowConnections.append(self._conn)

    def ping(self):
        logging.info("Ping from big show client") #TODO: make debug if ping is too often
        return

def simplateServer(port):
	s = bjsonrpc.createserver( host = '', port=port, handler_factory = SimplateServerHandler )
	s.debug_socket(True)
	s.serve()

def slaveSimplateServer(port):
	s = bjsonrpc.createserver( host = '', port=port, handler_factory = SlaveSimplateHandler )
	s.debug_socket(True)
	s.serve()

def barServer(port):
	s = bjsonrpc.createserver( host = '', port=port, handler_factory = BarServerHandler )
	s.debug_socket(True)
	s.serve()

def bigShowServer(port):
	s = bjsonrpc.createserver( host = '', port=port, handler_factory = BigShowServerHandler )
	s.debug_socket(True)
	s.serve()


import unittest
from io import StringIO

# add source files to path
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

from source.JackTokenizer import JackTokenizer
from source.CompilationEngine import CompilationEngine

class TestCompilationEngine(unittest.TestCase):
    def set_up(self, source_code):
        input_file = StringIO()
        input_file.write(source_code)
        input_file.seek(0)
        self.tokenizer = JackTokenizer(input_file)
        self.output_file = StringIO()
        self.compilation_engine = CompilationEngine(self.tokenizer, self.output_file)
        self.compilation_engine.compile_class()
        self.output_file.seek(0)

    def test_compile_class(self):
        self.maxDiff = None
        ## IT RETURNS A COMPILED CLASS
        source_code = "class Foo {}"
        self.set_up(source_code)

        expected_compiled = (
            "<class>\n"
            "  <keyword> class </keyword>\n"
            "  <identifier> Foo </identifier>\n"
            "  <symbol> { </symbol>\n"
            "  <symbol> } </symbol>\n"
            "</class>\n"
        )
        self.assertEqual(self.output_file.read(), expected_compiled)

        ## IT RETURNS A COMPILED CLASS WITH CLASS VARIABLE
        source_code = (
            "class Foo {\n"
            "  static boolean test;\n"
            "}\n"
        )
        self.set_up(source_code)

        expected_compiled = (
            "<class>\n"
            "  <keyword> class </keyword>\n"
            "  <identifier> Foo </identifier>\n"
            "  <symbol> { </symbol>\n"
            "  <classvarDec>\n"
            "    <keyword> static </keyword>\n"
            "    <keyword> boolean </keyword>\n"
            "    <identifier> test </identifier>\n"
            "    <symbol> ; </symbol>\n"
            "  </classvarDec>\n"
            "  <symbol> } </symbol>\n"
            "</class>\n"
        )
        self.assertEqual(self.output_file.read(), expected_compiled)

        ## IT RETURNS A COMPILED CLASS WITH A CLASS VAR AND FUNCTION
        source_code = (
            "class Foo {\n"
            "  static boolean test;\n"
            "\n"
            "  function void main(int x) {\n"
            "    var SquareGame game;\n"
            "    let game = game;\n"
            "    do game.run();\n"
            "    return;\n"
            "  }\n"
            "}\n"
        )
        self.set_up(source_code)

        expected_compiled = (
            "<class>\n"
            "  <keyword> class </keyword>\n"
            "  <identifier> Foo </identifier>\n"
            "  <symbol> { </symbol>\n"
            "  <classvarDec>\n"
            "    <keyword> static </keyword>\n"
            "    <keyword> boolean </keyword>\n"
            "    <identifier> test </identifier>\n"
            "    <symbol> ; </symbol>\n"
            "  </classvarDec>\n"
            "  <subroutineDec>\n"
            "    <keyword> function </keyword>\n"
            "    <keyword> void </keyword>\n"
            "    <identifier> main </identifier>\n"
            "    <symbol> ( </symbol>\n"
            "    <parameterList>\n"
            "      <keyword> int </keyword>\n"
            "      <identifier> x </identifier>\n"
            "    </parameterList>\n"
            "    <symbol> ) </symbol>\n"
            "    <subroutineBody>\n"
            "      <symbol> { </symbol>\n"
            "      <varDec>\n"
            "        <keyword> var </keyword>\n"
            "        <identifier> SquareGame </identifier>\n"
            "        <identifier> game </identifier>\n"
            "        <symbol> ; </symbol>\n"
            "      </varDec>\n"
            "      <statements>\n"
            "        <letStatement>\n"
            "          <keyword> let </keyword>\n"
            "          <identifier> game </identifier>\n"
            "          <symbol> = </symbol>\n"
            "          <expression>\n"
            "            <term>\n"
            "              <identifier> game </identifier>\n"
            "            </term>\n"
            "          </expression>\n"
            "          <symbol> ; </symbol>\n"
            "        </letStatement>\n"
            "        <doStatement>\n"
            "          <keyword> do </keyword>\n"
            "          <identifier> game </identifier>\n"
            "          <symbol> . </symbol>\n"
            "          <identifier> run </identifier>\n"
            "          <symbol> ( </symbol>\n"
            "          <expressionList>\n"
            "          </expressionList>\n"
            "          <symbol> ) </symbol>\n"
            "          <symbol> ; </symbol>\n"
            "        </doStatement>\n"
            "        <returnStatement>\n"
            "          <keyword> return </keyword>\n"
            "          <symbol> ; </symbol>\n"
            "        </returnStatement>\n"
            "      </statements>\n"
            "      <symbol> } </symbol>\n"
            "    </subroutineBody>\n"
            "  </subroutineDec>\n"
            "</class>\n"
        )

        self.assertEqual(self.output_file.read(), expected_compiled)

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


from kazoo.exceptions import NoNodeError
from sys import maxsize
from .mutex import Mutex
from .internals import LockDriver
from .utils import lazyproperty

READ_LOCK_NAME = "__READ__"
WRITE_LOCK_NAME = "__WRIT__"

class _LockDriver(LockDriver):
    def sort_key(self, string, _lock_name):
        string = super(_LockDriver, self).sort_key(string, READ_LOCK_NAME)
        string = super(_LockDriver, self).sort_key(string, WRITE_LOCK_NAME)
        return string

class _ReadLockDriver(_LockDriver):
    def __init__(self, predicate):
        super(_ReadLockDriver, self).__init__()
        self._predicate = predicate

    def is_acquirable(self, children, sequence_node_name, max_leases):
        return self._predicate(children, sequence_node_name)

class _Mutex(Mutex):
    def __init__(self, client, path, name, max_leases, driver, timeout):
        super(_Mutex, self).__init__(
            client,
            path,
            max_leases,
            name=name,
            driver=driver,
            timeout=timeout
        )

    def get_participant_nodes(self):
        nodes = super(_Mutex, self).get_participant_nodes()
        return list(filter(lambda node: self.name in node, nodes))

class ReadWriteLock(object):
    def __init__(self, client, path, timeout=None):
        self._client = client
        self._path = path
        self._timeout = timeout

    @property
    def path(self):
        return self._path

    @property
    def timeout(self):
        return self._timeout

    @timeout.setter
    def timeout(self, value):
        self._timeout = value
        self.read_lock.timeout = value
        self.write_lock.timeout = value

    @lazyproperty
    def read_lock(self):
        def predicate(children, sequence_node_name):
            return self._read_is_acquirable_predicate(
                children,
                sequence_node_name
            )

        return _Mutex(
            self._client,
            self.path,
            READ_LOCK_NAME,
            maxsize,
            _ReadLockDriver(predicate),
            self.timeout
        )

    @lazyproperty
    def write_lock(self):
        return _Mutex(
            self._client,
            self.path,
            WRITE_LOCK_NAME,
            1,
            _LockDriver(),
            self.timeout
        )

    def get_participant_nodes(self):
        nodes = self.read_lock.get_participant_nodes()
        nodes.extend(self.write_lock.get_participant_nodes())
        return nodes

    def _read_is_acquirable_predicate(self, children, sequence_node_name):
        if self.write_lock.is_owned_by_current_thread:
            return (None, True)

        index = 0
        write_index = maxsize
        our_index = -1

        for node in children:
            if WRITE_LOCK_NAME in node:
                write_index = min(index, write_index)
            elif node.startswith(sequence_node_name):
                our_index = index
                break

            index += 1

        if our_index < 0:
            raise NoNodeError

        acquirable = our_index < write_index
        path = None if acquirable else children[write_index]
        return (path, acquirable)


import pytest
from django.core.cache import cache
from django.test import Client
from django.urls import reverse
from rest_framework import status

from datahub.company.models import Advisor
from datahub.company.test.factories import AdviserFactory
from datahub.core.constants import Team

pytestmark = pytest.mark.django_db

RESET_FIXTURES_URL = reverse('testfixtureapi:reset-fixtures')
CREATE_USER_URL = reverse('testfixtureapi:create-user')
LOAD_FIXTURE_URL = reverse('testfixtureapi:load-fixture')

SEED_USER_DATA = {
    'first_name': 'Seed',
    'last_name': 'User',
    'email': 'seed.user@example.com',
    'token': 'ditStaffToken',
    'dit_team_id': Team.crm.value.id,
    'sso_email_user_id': 'test@user.id',
}

ADVISER_FIXTURE = {
    'model': 'company.advisor',
    'pk': '413a608e-84a4-11e6-ea22-56b6b6499622',
    'fields': {
        'email': 'abc@def',
        'first_name': 'First name',
        'last_name': 'Last name',
        'dit_team': '162a3959-9798-e211-a939-e4115bead28a',
    },
}

def _request_reset_fixtures():
    """Request reset fixtures."""
    return Client().post(RESET_FIXTURES_URL)

def _request_create_user(seed_user_data):
    """Request create user."""
    return Client().post(CREATE_USER_URL, seed_user_data, content_type='application/json')

def _request_load_fixture(fixture):
    """Request load fixture."""
    return Client().post(LOAD_FIXTURE_URL, fixture, content_type='application/json')

def test_reset_fixtures_url_not_found_if_not_setup(settings, caplog):
    """Test that reset fixtures endpoint is not available when it is not set up."""
    caplog.set_level('WARNING')

    settings.ALLOW_TEST_FIXTURE_SETUP = None
    response = _request_reset_fixtures()
    assert response.status_code == status.HTTP_404_NOT_FOUND

    assert caplog.messages == [
        'The `reset_fixture` endpoint is not enabled. The ALLOW_TEST_FIXTURE_SETUP environment'
        ' variable is not set.',
        'Not Found: /testfixtureapi/reset-fixtures/',
    ]

def test_url_found_if_env_setup():
    """Test that reset fixtures endpoint is available when set up."""
    response = _request_reset_fixtures()
    assert response.status_code == status.HTTP_201_CREATED

def test_new_adviser_removed_by_reset_fixtures():
    """Test new adviser is removed by reset fixtures."""
    new_adviser_pk = AdviserFactory().pk
    _request_reset_fixtures()
    with pytest.raises(Advisor.DoesNotExist):
        Advisor.objects.get(pk=new_adviser_pk)

def test_create_user_url_not_found_if_not_setup(settings, caplog):
    """Test that create user endpoint is not available when it is not set up."""
    caplog.set_level('WARNING')

    settings.ALLOW_TEST_FIXTURE_SETUP = None
    response = _request_create_user(SEED_USER_DATA)
    assert response.status_code == status.HTTP_404_NOT_FOUND

    with pytest.raises(Advisor.DoesNotExist):
        Advisor.objects.get(email=SEED_USER_DATA['email'])

    assert caplog.messages == [
        'The `create_user` endpoint is not enabled. The ALLOW_TEST_FIXTURE_SETUP environment'
        ' variable is not set.',
        'Not Found: /testfixtureapi/create-user/',
    ]

def test_create_user_endpoint_creates_user(caplog):
    """Test a user is created by create user."""
    caplog.set_level('INFO')

    _request_create_user(SEED_USER_DATA)
    created_user = Advisor.objects.get(email=SEED_USER_DATA['email'])

    user_data_keys = SEED_USER_DATA.keys() - set(['token'])
    for key in user_data_keys:
        assert str(getattr(created_user, key)) == SEED_USER_DATA[key]

    user_info = [
        'Creating a user: {',
        f'    "dit_team_id": "{SEED_USER_DATA["dit_team_id"]}",',
        f'    "email": "{SEED_USER_DATA["email"]}",',
        f'    "first_name": "{SEED_USER_DATA["first_name"]}",',
        f'    "last_name": "{SEED_USER_DATA["last_name"]}",',
        f'    "sso_email_user_id": "{SEED_USER_DATA["sso_email_user_id"]}"',
        '}',
    ]
    user_token = f'Created a token `{SEED_USER_DATA["token"]}` for user {created_user.id}.'
    assert caplog.messages == [
        '\n'.join(user_info),
        user_token,
    ]

@pytest.mark.usefixtures('local_memory_cache')
def test_created_user_has_token_in_cache():
    """Test that created user has token in the cache."""
    _request_create_user(SEED_USER_DATA)
    token = SEED_USER_DATA['token']
    cache_key = f'access_token:{token}'

    expected_data = {
        'email': SEED_USER_DATA['email'],
        'sso_email_user_id': SEED_USER_DATA['sso_email_user_id'],
    }
    assert cache.get(cache_key) == expected_data

def test_load_fixture_url_not_found_if_not_setup(settings, caplog):
    """Test that load fixture endpoint is not available when it is not set up."""
    caplog.set_level('WARNING')

    settings.ALLOW_TEST_FIXTURE_SETUP = None
    response = _request_load_fixture({'fixture': [ADVISER_FIXTURE]})
    assert response.status_code == status.HTTP_404_NOT_FOUND

    with pytest.raises(Advisor.DoesNotExist):
        Advisor.objects.get(pk=ADVISER_FIXTURE['pk'])

    assert caplog.messages == [
        'The `load_fixture` endpoint is not enabled. The ALLOW_TEST_FIXTURE_SETUP environment'
        ' variable is not set.',
        'Not Found: /testfixtureapi/load-fixture/',
    ]

def test_load_fixture(caplog):
    """Test load fixture endpoint."""
    caplog.set_level('INFO')

    with pytest.raises(Advisor.DoesNotExist):
        Advisor.objects.get(pk=ADVISER_FIXTURE['pk'])

    response = _request_load_fixture({'fixture': [ADVISER_FIXTURE]})

    assert response.status_code == status.HTTP_201_CREATED

    adviser = Advisor.objects.get(pk=ADVISER_FIXTURE['pk'])
    assert adviser.email == ADVISER_FIXTURE['fields']['email']
    assert adviser.first_name == ADVISER_FIXTURE['fields']['first_name']
    assert adviser.last_name == ADVISER_FIXTURE['fields']['last_name']
    assert str(adviser.dit_team_id) == ADVISER_FIXTURE['fields']['dit_team']

    fixture_info = [
        'Loading fixture: [',
        '    {',
        '        "fields": {',
        f'            "dit_team": "{ADVISER_FIXTURE["fields"]["dit_team"]}",',
        f'            "email": "{ADVISER_FIXTURE["fields"]["email"]}",',
        f'            "first_name": "{ADVISER_FIXTURE["fields"]["first_name"]}",',
        f'            "last_name": "{ADVISER_FIXTURE["fields"]["last_name"]}"',
        '        },',
        '        "model": "company.advisor",',
        f'        "pk": "{ADVISER_FIXTURE["pk"]}"',
        '    }',
        ']',
    ]
    assert caplog.messages == ['\n'.join(fixture_info)]


from django.shortcuts import render, redirect,get_object_or_404
from django.contrib.auth.decorators import login_required
from .models import Createjob
from django.utils import timezone

def createjoblist(request):
    createjob = Createjob.objects
    return render(request, 'createjobs/createjoblist.html',{'createjob':createjob})

@login_required
def create(request):
    if request.method=='POST':
        if request.POST['title'] and request.POST['duration'] and request.POST['salary'] and request.POST['contract'] and request.POST['address'] and request.POST['description'] and request.POST['url'] and request.FILES['icon']:
            createjob = Createjob()
            createjob.title = request.POST['title']
            createjob.duration = request.POST['duration']
            createjob.salary = request.POST['salary']
            createjob.contract = request.POST['contract']
            createjob.address = request.POST['address']
            createjob.description = request.POST['description']
            if request.POST['url'].startswith('http://') or request.POST['url'].startswith('https://'):
                createjob.url=request.POST['url']

            else:
                createjob.url="http://" + request.POST['url']
            createjob.icon = request.FILES['icon']
            createjob.pub_date=timezone.datetime.now()
            createjob.hunter=request.user
            createjob.save()
            return redirect('/createjobs/' + str(createjob.id))

        else:
            return render(request,'createjobs/create.html',{'error':'All Fields are required'})

    else:
        return render(request,'createjobs/create.html')

@login_required(login_url="/accounts/login")
def detailjob(request,createjob_id):
    createjob=get_object_or_404(Createjob,pk=createjob_id)
    return render(request,'createjobs/detail.html',{'createjob':createjob})

@login_required(login_url="/accounts/login")
def upvote(request, createjob_id):
    if request.method == 'POST':
        createjob = get_object_or_404(Createjob, pk=createjob_id)
        createjob.votes_total += 1
        createjob.save()
        return redirect('/createjobs/' + str(createjob.id))


import pygame
from pygame import Rect
from enum import Enum
import math
from settings import *
import sys
import random
from perlin import PerlinNoiseFactory

from pygame.locals import (
    QUIT,
    KEYDOWN,
    K_ESCAPE,
    MOUSEBUTTONDOWN,
    MOUSEBUTTONUP,
    MOUSEMOTION
)

States = Enum(
    'States',
    'SET_START SET_END SET_BLOCK START_SEARCH FOUND_END'
)

class Grid:
    def __init__(self):
        self.create_grid()
        self.perlin_noise_factory = PerlinNoiseFactory(2, octaves = OCTAVES, unbias = UNBIAS)

    def create_grid(self):
        self.grid = []
        for row in range(ROW):
            for column in range(COLUMN):
                node = Node((row, column), (((MARGIN + CELL_WIDTH) * column + MARGIN), ((MARGIN + CELL_HEIGHT) * row + MARGIN), CELL_WIDTH, CELL_HEIGHT))
                self.grid.append(node)

    def reset_grid(self):
        for node in self.grid:
            node.set_state(EMPTY_NODE)
            node.clear_came_from()
            node.weight = 0

    def clear_searched_nodes(self):
        for node in self.grid:
            if node.state == SEARCHED_NODE or node.state == FRONTIER_NODE or node.state == PATH_NODE:
                node.set_state(EMPTY_NODE)
                node.clear_came_from()
            if node.state == END_NODE:
                node.clear_came_from()

    def find_pressed_node(self, mouse_pos):
        for node in self.grid:
            if node.is_pressed(mouse_pos):
                return node

    def calculate_noise_value(self, node):
        x = node.index[0]
        y = node.index[1]
        return self.perlin_noise_factory(x / ROW + self.offset, y / ROW + self.offset) * 20

    def map_values(self):
        smallest_value = sys.maxsize
        biggest_value =  - sys.maxsize

        for node in self.grid:
            if node.weight > biggest_value:
                biggest_value = node.weight
            elif node.weight < smallest_value:
                smallest_value = node.weight

        smallest_value = math.floor(smallest_value)
        biggest_value = math.floor(biggest_value)

        value_range = abs(smallest_value) + abs(biggest_value)
        bound = 127 / value_range
        for node in self.grid:
            node.weight = math.floor(127 + (node.weight * bound))

    # weight
    def create_weighted_grid(self):
        self.offset = random.random()
        for node in self.grid:
            node.weight = self.calculate_noise_value(node)
        self.map_values()

class Button:
    def __init__(self,screen, font, x, y, width, height, message):
        pygame.draw.rect(screen, BUTTON_COLOUR, [x, y, width, height])
        button_text = font.render(message, False, BUTTON_TEXT_COLOUR)
        screen.blit(button_text, (x,y))
        self.rect = Rect(x, y, width, height)

    def is_pressed(self, mouse_pos):
        if self.rect.collidepoint(mouse_pos):
            return True

class Node:
    def __init__(self, index, rect):
        self.state = 0
        self.index = index
        self.came_from = None
        self.rect = Rect(rect)
        # Heuristic serch stuff
        self.came_from_cost = 0
        self.goal_cost = None
        # weight search stuff
        self.weight = 0

    def is_pressed(self, mouse_pos):
        if self.rect.collidepoint(mouse_pos):
            return True

    def get_colour(self):
        if self.state == EMPTY_NODE:
            weight_colour = (0, self.weight, self.weight)
            return weight_colour
        return COLOURS[self.state]

    def calculate_gradient(self, start_node, start_colour):
        diff = abs(start_node.index[0] - self.index[0]) + abs(start_node.index[1] - self.index[1])
        new_colour = start_colour
        new_colour[0] = abs(int(diff*(255/(ROW*2))))
        return new_colour

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

    def set_came_from(self, came_from_node):
        self.came_from = came_from_node
        self.came_from_cost = self.calculate_came_from_cost(came_from_node)

    def clear_came_from(self):
        self.came_from = None
        self.came_from_cost = 0

    def calculate_came_from_cost(self, came_from_node):
        diff = (self.index[0] - came_from_node.index[0],
                self.index[1] - came_from_node.index[1])
        came_from_to = math.sqrt(diff[0] ** 2 + diff[1] ** 2) * 10
        return came_from_node.get_came_from_cost() + math.floor(came_from_to)

    def calculate_goal_cost(self, end_node, multiplier):
        diff = (self.index[0] - end_node.index[0],
                self.index[1] - end_node.index[1])
        # self.goal_cost = abs(diff[0]) + abs(diff[1]) # manhattan distance
        self.goal_cost = math.floor(math.sqrt(diff[0] ** 2 + diff[1] ** 2) * multiplier)

    def turn_into_wall(self):
        if self.state == EMPTY_NODE:
            self.set_state(WALL_NODE)

    def from_wall_turn_into_empty(self):
        if self.state == WALL_NODE:
            self.set_state(EMPTY_NODE)

    def get_came_from_cost(self):
        return self.came_from_cost

    def get_goal_cost(self):
        return self.goal_cost

    # def get_heuristic(self):
    #     return self.came_from_cost + self.goal_cost

class Breadth_First_Search():
    def __init__(self, grid, start_node, end_node):
        self.grid = grid
        self.frontier = [start_node]
        self.start_node = start_node
        self.end_node = end_node

    def search_for_end(self):
        if len(self.frontier) == 0:
            return FRONTIER_EMPTY

        current_node = self.pop_node_from_frontier()
        if current_node.state == WALL_NODE:
            return FOUND_NOT
        if current_node.state == END_NODE:
            return FOUND_END
        if current_node.state == FRONTIER_NODE:
            current_node.set_state(SEARCHED_NODE)
        for next in self.neighbours(current_node):
            if next.state == WALL_NODE:
                continue

            if next.came_from == None or next.calculate_came_from_cost(current_node) < next.get_came_from_cost():
                self.frontier.append(next)
                next.set_came_from(current_node)
                if next.state == EMPTY_NODE:
                   next.set_state(FRONTIER_NODE)

    def pop_node_from_frontier(self):
        return self.frontier.pop(0)

    def neighbours(self, node):
        dirs = [[1,0], [0,1], [-1,0], [0,-1]]
        result = []
        for dir in dirs:
            neighbour_index = (node.index[0] + dir[0], node.index[1] + dir[1])
            neighbour_node = self.find_node_by_index(neighbour_index)
            if neighbour_node:
                result.append(neighbour_node)
        return result

    def find_node_by_index(self, index):
        for node in self.grid:
            if node.index == index:
                return node

class Depth_First_Search(Breadth_First_Search):
    def pop_node_from_frontier(self):
        return self.frontier.pop()

class Heuristic_Distance_To_Goal(Breadth_First_Search):
    def __init__(self, grid, start_node, end_node, multiplier = 10):
        Breadth_First_Search.__init__(self, grid, start_node, end_node)
        for node in self.grid:
            self.goal_cost = node.calculate_goal_cost(self.end_node, multiplier)

    def pop_node_from_frontier(self):
        lowest_heuristic = sys.maxsize
        lowest_heuristic_index = None
        for index, node in enumerate(self.frontier):
            if self.calculate_node_score(node) <= lowest_heuristic:
                lowest_heuristic = self.calculate_node_score(node)
                lowest_heuristic_index = index
        return self.frontier.pop(lowest_heuristic_index)

class Heuristic_Weight(Heuristic_Distance_To_Goal):
    def __init__(self,  grid, start_node, end_node):
        super().__init__(grid, start_node, end_node)
        self.closed = []

    def pop_node_from_frontier(self):
        lowest_heuristic = -sys.maxsize
        lowest_heuristic_index = None
        for index, node in enumerate(self.frontier):
            if node not in self.closed:
                if self.calculate_node_score(node) >= lowest_heuristic:
                    lowest_heuristic = self.calculate_node_score(node)
                    lowest_heuristic_index = index
        node = self.frontier.pop(lowest_heuristic_index)
        self.closed.append(node)
        return node

    def calculate_node_score(self, node):
        return node.weight

class Greedy_Best_First_Search(Heuristic_Distance_To_Goal):
    def calculate_node_score(self, node):
        return node.get_goal_cost()

# distance to goal heuristic + came from cost
class AStar_Search(Heuristic_Distance_To_Goal):
    def __init__(self, grid, start_node, end_node):
        Heuristic_Distance_To_Goal.__init__(self, grid, start_node, end_node, 18)

    def calculate_node_score(self, node):
        return node.get_goal_cost() + node.get_came_from_cost()

class GUI:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT));
        self.screen.fill(DARK_BLUE)
        self.font = pygame.font.Font('../fonts/OpenSans-Bold.ttf', FONT_SIZE)
        self.y_button_stack = -1

    def create_button(self, text):
        self.y_button_stack = self.y_button_stack + 1
        return Button(self.screen, self.font, BUTTON_X, BUTTON_Y*self.y_button_stack + 25, BUTTON_WIDTH, BUTTON_HEIGHT, text)

def main():
    clock = pygame.time.Clock()
    state = States.SET_START

    _grid = Grid()
    grid = _grid.grid
    search = None
    gui = GUI()

    clear_button = gui.create_button("           Clear")
    reset_button = gui.create_button("           Reset")
    bfs_button = gui.create_button("    Breadth First")
    dfs_button  = gui.create_button("     Depth First")
    gfs_button = gui.create_button("Greedy Best-First")
    astar_button = gui.create_button("              A*")
    create_noise_map_button =  gui.create_button("Create Noise Map")
    lw_button = gui.create_button("  Lowest weight")

    running = True
    mouse_down = False
    start_node = None
    end_node = None
    while running:

        for event in pygame.event.get():
            mouse_pos = pygame.mouse.get_pos()

            if event.type == QUIT:
                running = False
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    running = False
            elif event.type == MOUSEBUTTONDOWN:
                mouse_down = True

                if reset_button.is_pressed(mouse_pos):
                    _grid.reset_grid()
                    state = States.SET_START
                    start_node = None
                    end_node = None
                    continue
                if clear_button.is_pressed(mouse_pos):
                    _grid.clear_searched_nodes()
                    if start_node and end_node:
                        state = States.SET_BLOCK
                    continue
                if create_noise_map_button.is_pressed(mouse_pos):
                    _grid.create_weighted_grid()

                _search = None
                if (start_node != None) and (end_node != None) :
                    _search = check_which_algorithm_was_choosen(mouse_pos, grid, start_node, end_node, bfs_button, dfs_button, gfs_button, astar_button, lw_button)
                    if _search :
                        _grid.clear_searched_nodes()
                        state = States.START_SEARCH
                        search = _search
                        continue

                node = _grid.find_pressed_node(mouse_pos)
                if node is None:
                    continue

                if event.button == 3:
                    right_mouse_down = True
                    if node.state == END_NODE:
                        node.set_state(EMPTY_NODE)
                        end_node = None
                        if start_node == None:
                            state = States.SET_START
                        else:
                            state = States.SET_END
                    if node.state == START_NODE:
                        node.set_state(EMPTY_NODE)
                        start_node = None
                        state = States.SET_START
                    if node.state == WALL_NODE:
                        node.set_state(EMPTY_NODE)
                        continue
                if event.button == 1:
                    if state == States.SET_START:
                        state = States.SET_END
                        node.set_state(START_NODE)
                        start_node = node
                    elif state == States.SET_END:
                        state = States.SET_BLOCK
                        if node.state == EMPTY_NODE:
                            node.set_state(END_NODE)
                            end_node = node
                    elif state == States.SET_BLOCK:
                        node.turn_into_wall()
            elif event.type == MOUSEBUTTONUP:
                mouse_down = False
                right_mouse_down = False
            elif event.type == MOUSEMOTION and state == States.SET_BLOCK and (mouse_down or right_mouse_down):
                node = _grid.find_pressed_node(mouse_pos)
                if node != None:
                    if right_mouse_down:
                        node.from_wall_turn_into_empty()
                    elif mouse_down:
                        node.turn_into_wall()

        if state == States.START_SEARCH:
            search_result = search.search_for_end()

            if search_result == FOUND_END:
                state = States.FOUND_END
                show_result(True, start_node, end_node)
            elif search_result == FRONTIER_EMPTY:
                state = States.FOUND_END
                show_result(False,  start_node, end_node)

        for node in grid:
            colour = node.get_colour()
            if colour == BLUE:
                colour = node.calculate_gradient(start_node, COLOUR_GRADIENT)
            pygame.draw.rect(gui.screen, colour, node.rect)

        clock.tick(SEARCH_SPEED)
        pygame.display.update()

def check_which_algorithm_was_choosen(mouse_pos, grid, start_node, end_node, bfs_button, dfs_button, gfs_button, astar_button, lw_button):
    if bfs_button.is_pressed(mouse_pos):
        return Breadth_First_Search(grid, start_node, end_node)
    if dfs_button.is_pressed(mouse_pos):
        return Depth_First_Search(grid, start_node, end_node)
    if gfs_button.is_pressed(mouse_pos):
        return Greedy_Best_First_Search(grid, start_node, end_node)
    if astar_button.is_pressed(mouse_pos):
        return AStar_Search(grid, start_node, end_node)
    if lw_button.is_pressed(mouse_pos):
        return Heuristic_Weight(grid, start_node, end_node)

def show_result(end_found, start_node, end_node):
    if not end_found:
        print("Cannot find end")
        return

    current = end_node
    path = []
    while current != start_node:
        path.append(current)
        current = current.came_from
    for node in path:
        if node.state == SEARCHED_NODE:
            node.state = PATH_NODE
    print("Path length is ",len(path)-1)

if __name__ == '__main__':
    main()


import asyncio
import functools
import uuid

import pytest
import ubii.proto

import ubii.framework.client
import ubii.framework.processing
import ubii.framework.topics
import ubii.node.pytest

@pytest.fixture
def topic_data(request):
    return [ubii.proto.TopicData(topic_data_record=value) for value in request.param]

FakeMuxer = functools.partial(ubii.framework.topics.TopicMuxer, id=str(uuid.uuid4()))

class TestMuxer:
    @pytest.mark.parametrize('topic_data', [
        [{'topic': 'test/foo', 'bool': n % 2 == 0} for n in range(10)]
    ], indirect=True)
    async def test_muxer_basics(self, topic_data):
        topic_muxer = FakeMuxer(data_type='bool')
        for data in topic_data:
            await topic_muxer.records.set([data.topic_data_record])

        assert len(topic_muxer.records.value) == 1
        assert topic_muxer.records.value[0] == topic_data[-1].topic_data_record

    @pytest.mark.parametrize('topic_data', [
        pytest.param([{'bool': n % 2 == 0} for n in range(10)], id='alternating_bools')
    ], indirect=True)
    @pytest.mark.parametrize(
        'topic, identity_match_pattern, identity',
        [
            ('test/foo-1234', r'test/(.*)', 'foo-1234',),
            ('test/foo/bar', r'.+', 'test/foo/bar'),
            ('test/foo-1234', r'\d+', '1234')
        ]
    )
    async def test_identity_match(self, topic_data, topic, identity_match_pattern, identity):
        topic_muxer = FakeMuxer(data_type='bool', identity_match_pattern=identity_match_pattern)
        for data in topic_data:
            data.topic_data_record.topic = topic
            await topic_muxer.records.set([data.topic_data_record])

        assert len(topic_muxer.records.value) == 1
        record = topic_muxer.records.value[0]
        assert record.metadata()['identity'] == identity

class TestMuxerProcessing:
    processing_module = ubii.proto.ProcessingModule(
        name="muxer-processing-module",
        processing_mode={'trigger_on_input': {'min_delay_ms': 0,
                                              'all_inputs_need_update': True}},

        inputs=[
            {
                'internal_name': 'muxer_inputs',
                'message_format': 'int32'
            },
        ],
        outputs=[
            {
                'internal_name': 'demuxer_outputs',
                'message_format': 'int32'
            }
        ],
        on_processing_stringified='\n'.join((
            'def on_processing(self, context):',
            '    import ubii.proto',
            '    outputs = []',
            '    for record in context.inputs.muxer_inputs:',
            '        metadata = record.metadata()',
            '        if record.int32 % 2 == 0:',
            '            outputs += [{"int32": record.int32, "output_params": (metadata["identity"],)}]',
            '        else:',
            '            outputs += [{"int32": record.int32, "output_params": ("dummy-1234",)}]',
            '    context.outputs.demuxer_outputs = outputs',
        )),
        language=ubii.proto.ProcessingModule.Language.PY,
    )

    session = ubii.proto.Session(
        name="Muxer Session",
        processing_modules=[processing_module],
        io_mappings=[
            {
                'processing_module_name': processing_module.name,
                'input_mappings': [
                    {
                        'topic_mux': {
                            'data_type': 'int32',
                            'topic_selector': '/muxer/*',
                            'identity_match_pattern': '(?:/muxer/([0-9a-z-]+))'
                        },
                        'input_name': processing_module.inputs[0].internal_name,
                    },
                ],
                'output_mappings': [
                    {
                        'topic_demux': {
                            'data_type': 'int32',
                            'output_topic_format': '/demuxer/{{#0}}',
                        },
                        'output_name': processing_module.outputs[0].internal_name,
                    }
                ]
            },
        ]
    )

    client = ubii.proto.Client(
        name='Muxer Client',
        processing_modules=[processing_module],
        is_dedicated_processing_node=True
    )

    session_spec = [(session,)]
    module_spec = [(processing_module,)]
    client_spec = [(client,)]

    @pytest.mark.parametrize('topic_data', [
        [{'int32': n} for n in range(10)]
    ], indirect=True)
    async def test_muxer_processing(self, client, session_spec, module_spec, topic_data):
        await client
        await client.implements(ubii.framework.client.Sessions)
        await client[ubii.framework.client.Sessions].start_session(session_spec)

        topic, = await client[ubii.framework.client.Subscriptions].subscribe_regex('/demuxer/*')
        received = []
        topic.register_callback(received.append)

        for data in topic_data:
            data.topic_data_record.topic = f"/muxer/{client.id}"
            await client[ubii.framework.client.Publish].publish(data.topic_data_record)
            await asyncio.sleep(0.02)  # stagger inputs

        assert len(received) == 5
        assert all(record.topic == f"/demuxer/{client.id}" for record in received)
        assert all(value in [record.int32 for record in received] for value in [0, 2, 4, 6, 8])
        await client[ubii.framework.client.Sessions].stop_session(session_spec)


lyear = int(input("Please enter last year month's revenue.\n"))
tyear = int(input("Please enter last year month's revenue.\n"))
differ = "The difference is $"

def hesapla():
  print(f" {differ} {lyear - tyear}")

hesapla()

def sonuc():
  print(f",{df} {goal / days_left / adr}{rooms}")

goal = int(input("How much would you like to make this month? "))
adr = float(input("What is your average daily rate? "))
days_left = int(input("How many days left to the end of month? "))
df = "You should sell about "
rooms = "rooms per day."

sonuc()


class Solution:
    def sortSentence(self, s: str) -> str:
        #  we are giving a sentence, each word in the sentence ends with a number which indicates the odering of that word if the sentence was to be sorted
        #  Our objective is to capture the last char in each word and use it to place the other words in the sentence
        #  i can use a dictionary, take the last char and use it as the key, finally i will map each word excluding the last char as the value

        words = s.split(' ')
        Map = {}
        for wrd in words:
            Map[int(wrd[-1])] = wrd[:-1]
        n = len(words) + 1
        #  since the keys are 1 indexed we need to make the list one element larger so that we dont over indexed
        store = [None] * n
        for key, val in Map.items():
            store[key] = val

        return ' '.join(store[1:])


import sys

def gcd(n, m):
    if m == 0:
        return n, 1, 0
    d, x, y = gcd(m, n % m)
    return d, y, (x - y * (n // m))

def main():
    n, m = map(int, sys.stdin.readline().split())
    gcd_1, x, y = gcd(n, m)
    if gcd_1 == 1:
        x %= m
        sys.stdout.write(str(x))
    else:
        sys.stdout.write('-1')

if __name__ == "__main__":
    main()


from django.shortcuts import render
from .models import Contato

def home(request):
    return render(request, 'website/index.html')

def servicos(request):
    return render(request, 'website/servicos.html')

def contato(request):
    #import pdb; pdb.set_trace()
    mensagem = ''
    if request.method == 'POST':
        try:
            contato = {}
            contato['nome'] = request.POST.get('nome')
            contato['email'] = request.POST.get('email')
            contato['telefone'] = request.POST.get('telefone')
            contato['mensagem'] = request.POST.get('mensagem')
            Contato.objects.create(**contato)
        except Exception as e:
            mensagem = str(e)
        else:
            mensagem = 'Obrigado pelo contato. Mensagem enviada com sucesso!'

    return render(request, 'website/contato.html', {'mensagem':mensagem})

def sobre(request):
    return render(request, 'website/sobre.html')

def planos(request):
    mensagem = ''
    if request.method == 'POST':
        if request.POST.get('planoBasico') == 'planoBasico':
            mensagem = 'Parabéns, você contratou o plano básico!'
        elif request.POST.get('planoPro') == 'planoPro':
            mensagem = 'Parabéns, você contratou o plano Pró!'
    return render(request, 'website/planos.html', {'mensagem':mensagem})


# select
def run(server):
    from flask import request
    log = server.log
    @server.route('/db/<database>/table/<table>/select', methods=['GET', 'POST'])
    @server.is_authenticated('local')
    def cluster_select_func(database, table):
        return select_func(database, table, method=request.method)
    def select_func(database,table, params=None, method='GET'):
        message, rc = server.check_db_table_exist(database,table)
        if not rc == 200:
            return {"error": log.error(f"received non 200 rec with message {message}, rc {rc} during check_db_table_exist")}, 500
        if method == 'GET' and params == None:
            response = server.data[database].tables[table].select('*')
        else:
            params = request.get_json() if params == None else params
            if not 'select' in params:
                warning = f"table {table} select - missing selection"
                return {"warning": log.warning(warning)}, 400
            p = {}
            select = params['select']
            if 'join' in params:
                p['join'] = params['join']
            if 'where' in params:
                p['where'] = params['where']
            response = server.data[database].tables[table].select(*select, **p)
        if response == None or isinstance(response, str):
            return {"error": log.error(f"response object returned {response}")}, 500
        response = [response] if isinstance(response, dict) else response
        return {"data": response}, 200

    server.actions['select'] = select_func


# 3. Задайте последовательность чисел. Напишите программу,
# которая выведет список неповторяющихся элементов исходной последовательности в том же порядке.
# in
# 7
# out
# [4, 5, 3, 3, 4, 1, 2]
# [5, 1, 2]
import random
def in_number_list(count):
    if count < 0:
        print('Negative value of the number of numbers!')
    L = list()
    for _ in range(count):
        L.append(random.randint(0, count))
    print(L)
    list_copy = []
    for x in L:
        if x not in list_copy:
            list_copy.append(x)
    print(list_copy)
in_number_list(-1)


import numpy as np
from mdt import CompositeModelTemplate

__author__ = 'Robbert Harms'
__date__ = '2017-07-19'
__maintainer__ = 'Robbert Harms'
__email__ = 'robbert@xkls.nl'
__licence__ = 'LGPL v3'

class ActiveAx(CompositeModelTemplate):
    """The ActiveAx model for use in in-vivo measurements.

    This model has a CSF compartment and white matter intrinsic diffusivity is fixed at 1.7E-9 m^2/s and
    CSF diffusivity at 3.0E-9 m^2/s. (In CAMINO this model is listed as "MMWMD_INVIVO").
    """
    model_expression = '''
        S0 * ((Weight(w_csf) * Ball) +
              (Weight(w_ic) * CylinderGPD) +
              (Weight(w_ec) * Zeppelin))
    '''
    inits = {
        'w_csf.w': 0.01
    }
    fixes = {'CylinderGPD.d': 1.7e-9,
             'Ball.d': 3.0e-9,
             'Zeppelin.d': 'CylinderGPD.d',
             'Zeppelin.dperp0': 'Zeppelin.d * (w_ec.w / (w_ec.w + w_ic.w))',
             'Zeppelin.theta': 'CylinderGPD.theta',
             'Zeppelin.phi': 'CylinderGPD.phi'}
    extra_optimization_maps = [
        lambda d: {'AxonDensityIndex': (4 * (d['w_ic.w'] / (d['w_ec.w'] + d['w_ic.w'])))
                                       / (np.pi * (2 * d['CylinderGPD.R']) ** 2)}
    ]

class ActiveAx_ExVivo(CompositeModelTemplate):
    """The ActiveAx model for use in ex-vivo measurements.

    This model has all the compartments as described in Alexander et al NIMG 2010. The white matter intrinsic
    diffusivity is fixed at 0.6e-9 m^2/s and CSF diffusivity is fixed at 2.0e-9 m^2/s.
    (In CAMINO this model is listed as "MMWMD_Fixed").
    """
    model_expression = '''
        S0 * ((Weight(w_csf) * Ball) +
              (Weight(w_stat) * Dot) +
              (Weight(w_ic) * CylinderGPD) +
              (Weight(w_ec) * Zeppelin))
    '''
    inits = {
        'w_csf.w': 0.01,
        'w_stat.w': 0.01
    }
    fixes = {
        'CylinderGPD.d': 0.6e-9,
        'Ball.d': 2.0e-9,
        'Zeppelin.d': 'CylinderGPD.d',
        'Zeppelin.dperp0': 'Zeppelin.d * (w_ec.w / (w_ec.w + w_ic.w))',
        'Zeppelin.theta': 'CylinderGPD.theta',
        'Zeppelin.phi': 'CylinderGPD.phi'
    }
    extra_optimization_maps = [
        lambda d: {'AxonDensityIndex': (4 * (d['w_ic.w'] / (d['w_ec.w'] + d['w_ic.w'])))
                                       / (np.pi * (2 * d['CylinderGPD.R']) ** 2)}
    ]

class TimeDependentActiveAx(CompositeModelTemplate):
    """Fits the extra-axonal time dependent ActiveAx model (De Santis 2016).

    This fits a single Radius using the CylinderGPD compartment model.
    """
    model_expression = '''
        S0 * ExpT1DecTM_simple * ( (Weight(w_ic) * CylinderGPD) +
                                   (Weight(w_ec) * TimeDependentZeppelin)
                                  )
    '''
    fixes = {'TimeDependentZeppelin.d': 'CylinderGPD.d',
             'TimeDependentZeppelin.theta': 'CylinderGPD.theta',
             'TimeDependentZeppelin.phi': 'CylinderGPD.phi',
             }
    extra_optimization_maps = [
        lambda d: {'AxonDensityIndex': (4 * (d['w_ic.w'] / (d['w_ec.w'] + d['w_ic.w'])))
                                       / (np.pi * (2 * d['CylinderGPD.R']) ** 2)}
    ]


alpha_dict = {}
cnt = 0

def solution(word):
    answer = 0

    alpha = ['A', 'E', 'I', 'O', 'U']

    recursive('', alpha)

    answer = alpha_dict[word]

    return answer

def recursive(text, alpha):
    global cnt

    if text in alpha_dict:
        return

    if len(text) == 6:
        alpha_dict[text] = cnt
        return

    alpha_dict[text] = cnt
    cnt += 1

    for c in alpha:
        recursive(text + c, alpha)

print(solution('AAAAE'))
print(solution('AAAE'))
print(solution('I'))
print(solution('EIO'))