from django.db import transaction
from django.http import JsonResponse
from rest_framework.decorators import api_view
from rest_framework.parsers import JSONParser

from store.Class.Order import Order
from store.Class.Product import Product
from store.Class.Store import Store
from store.serializers.OrderSerializer import CreateOrderRequest, ProductListFields

@api_view(['POST'])
def create_order(request):
    try:
        input = JSONParser().parse(request)
        createOrderSerializer = CreateOrderRequest(data=input)

        if not createOrderSerializer.is_valid():
            return JsonResponse('Invalid request',safe=False,status=500)

        products = []
        for product in createOrderSerializer.get_products():
            pObj = ProductListFields()
            pObj.setId(product[pObj.ID_FIELD])
            pObj.setQuantity(product[pObj.QUANTITY_FIELD])
            pObj.setPrice(product[pObj.PRICE_FIELD])
            products.append(pObj)

        Order.create_order(createOrderSerializer.get_customer_id(),
                           createOrderSerializer.get_address(),
                           products)

        return JsonResponse({}, status=200)
    except Exception:
        return JsonResponse('Can not create Order.', safe=False, status=500)


from typing import Any
from django.db.models import Manager, Model, QuerySet, Q

from core.apps.checks.constants import CheckStatus, CheckTypeChoices

class CheckQuerySet(QuerySet):
    def avaliable_for_printing(self):
        return self.filter(
            Q(status=CheckStatus.RENDERED) | Q(status=CheckStatus.PRINTED),
            pdf_file__isnull=False,
        )

class CheckManager(Manager):
    def get_queryset(self) -> CheckQuerySet:
        return CheckQuerySet(self.model, using=self._db)

    def avaliable_for_printing(self):
        return self.get_queryset().avaliable_for_printing()

    def attach_pdf_file(self, check_id: int, filepath: str):
        '''
        Прикрепить файл с отрендеренным чеком в формате pdf
        '''
        self.filter(id=check_id).update(status=CheckStatus.RENDERED, pdf_file=filepath)

    def create_both_checks(
        self,
        order: dict[str, Any],
        printer_kitchen_id: int,
        printer_client_id: int,
    ) -> list[Model]:
        '''
        Метод создания чеков сразу для обоих принтеров по их id.
        '''
        created_objs = []

        created_objs.append(
            self.create(
                order=order,
                printer_id=printer_kitchen_id,
                type=CheckTypeChoices.KITCHEN,
            ),
        )
        created_objs.append(
            self.create(
                order=order,
                printer_id=printer_client_id,
                type=CheckTypeChoices.CLIENT,
            ),
        )
        return created_objs


import sqlite3

def valida(limite_inferior, limite_superior):
    """
   -> Verificar se tem coerencia nos dados inseridos
    :param limite_inferior: Valor de medição minímo do conversor
    :param limite_superior: Valor de medição maxímo do conversor
    """
    while True:
        if limite_inferior > limite_superior:
            print('Limites inválidos, digite novamente')
            limite_inferior = float(input('Digite o limite inferior'))
            limite_superior = float(input('Digite o limite superior'))
        else:
            break
    return limite_inferior, limite_superior

def escala(limite_inferior, limite_superior):
    """
    ->Validar os dados e descobrir a escala total
    :param limite_inferior: Valor minímo do conversor
    :param limite_superior: Valor maxímo do conversor
    :return: retorna a escala total do conversor e quanto vale  1 bits convertido
    """
    total = abs(limite_superior - limite_inferior)
    return total

def equivalente(escala_total,tipo_conversor):
    """
    ->Descobrir o valor equivalente de um único bit
    :param tipo_conversor: Tipo do conversor
    :param escala_total: Escala total do conversor
    :return: Retorna o valor equivalente a um bit
    """
    if tipo_conversor == 1 or tipo_conversor == 2:
        valor_1_bit = escala_total / 32768
        return valor_1_bit
    elif tipo_conversor == 3:
        valor_1_bit = escala_total / 26214
        #valor_1_bit = escala_total / 65535/2
        return valor_1_bit

def conversão(limite_inferior, valor_1_bit, valor_medido, tipo_conversor):
    """
    ->Converter valores medidos
    :param tipo_conversor: O tipo de conversor utilizado, tensão ou corrente(0-20mA / 4-20mA)
    :param limite_inferior: Valor minímo do conversor
    :param valor_1_bit: Valor equivalente a um bits do conversor
    :param valor_medido: Valor vindo do conversor
    :return: Valor já convertido
    """
    if tipo_conversor == 1 or tipo_conversor == 2:
        valor_convertido = valor_medido * valor_1_bit
        valor_real = limite_inferior + valor_convertido
    elif tipo_conversor == 3:
        if valor_medido <= 6553:
            return 'Conversor desconectado'
        elif valor_medido > 6553:
            valor_certo = (valor_medido - 6553)  # Faz a diferença e calcular o valor correspondente real
            valor_convertido = valor_certo * valor_1_bit
            valor_real = limite_inferior + valor_convertido
    return valor_real

def valor_real():
    return valor_real

def conversor(tipo_conversor):
    """
    -> Tipo de conversor que o usuario diz que vai usar
    :param tipo_conversor:
    :return: (número de identificação, tipo de sensor)
    """
    while True:
        if tipo_conversor == 1:
            return 1, 'Sensor tipo tensão'
            break
        elif tipo_conversor == 2:
            return 2, 'Sensor tipo corrente (0-20mA)'
            break
        elif tipo_conversor == 3:
            return 3, 'Sensor tipo corrente (4-20mA)'
            break
        else:
            print('Dado invalido, favor inserir uma das opções abaixo')
            tipo_conversor = int(input('''Digite o número correspondete ao sensor utilizado
            [1] Tensão
            [2] Corrente (0-20mA)
            [3] Corrente (4-20mA)
            Sensor corresponde ao número: '''))

# BACKUP DO BANCO DE DADOS
    # -> FAZER VERIFICAÇÃO DE NOME VÁLIDO
def backup(self):
    file_name = input('Digite o nome do arquivo de backup: ')
    file_name = file_name + '.sql'
    with io.open(file_name, 'w') as f:
        for linha in self.conn.iterdump():
            f.write('%f\n' % linha)
    # VERIFICAR SE DEU CERTO
    print('Backup realizado com sucesso!')
    print('Salvo como: %s' % file_name)

def arquivo():
    """
    -> Pedir para salvar no mesmo arquivo ou criar um novo
    :param teste: Resposta do usuario
    :return: retorna o nome do novo banco de dados
    """
    # CRIA UM NOVO ARQUIVO .db
    # CONFIGURA O SQLITE
    conn = sqlite3.connect('datalogger.db')
    cursor = conn.cursor()

    while True:
        novo = str(input('Deseja criar uma nova tabela? [S/N]: '))

        if novo in 'Ss':
            nome_tabela = str(input('Digite o nome da tabela: '))
            dados = nome_tabela
            continuar = input('Alerta: caso exista uma tabela com esse mesmo nome, a anterior sera apagada. Continuar? [S/N]: ')

            if continuar in 'Ss':
                cursor.execute("DROP TABLE IF EXISTS "+dados)
                cursor.execute("CREATE TABLE "+dados+"(id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,"
                               "dia TINYINT, mes TINYINT, ano SMALLINT, hora TINYINT,"
                               "minuto TINYINT, segundo TINYINT, dado FLOAT)")
                break
            else:
                break

        elif novo in 'Nn':
            print('Alerta: caso a tabela não exista o programa resultará em erro')
            nome_tabela = str(input('Digite o nome da tabela: '))
            dados = nome_tabela
            break

        else:
            print('Resposta Inválida!')

    return nome_tabela


import numpy as np

data = open('input.txt').read().split('\n\n')

draw = [ int(d) for d in data[0].split(',') ]

def pipo(s):
  return list(map(int, s.split()))

cards = [ np.array(list(map(pipo, d.splitlines()))) for d in data[1:] ]

def bingo(d):
  global cards
  to_be_removed = []

  for i in range(len(cards)):
    c = cards[i]
    c[c == d] = -1

    for row in c:
      if np.sum(row) == -5:
        to_be_removed.append(i)
        continue

    for column in c.T:
      if np.sum(column) == -5:
        to_be_removed.append(i)
        continue

  cards = np.delete(cards, to_be_removed, axis=0)

  return len(cards) < 1

for d in draw:
  c = cards[0]
  b = bingo(d)
  if b:
    c[c == -1] = 0
    print(d * sum(c.flatten()))
    break


import logging
import uuid
from typing import Any, Optional, TypeVar, Union

from sqlalchemy import select, update
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.inspection import inspect
from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy.sql.base import ColumnCollection
from sqlalchemy.sql.schema import Column, MetaData

from conf import settings

logger = logging.getLogger(__name__)

DeclarativeBaseType = TypeVar('DeclarativeBaseType', bound='DeclarativeBase')

class DeclarativeBase:

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        self.metadata: MetaData = MetaData()
        super().__init__(*args, **kwargs)

    def __repr__(self) -> str:
        return f'{self.__class__.__name__}'

    @classmethod
    @property
    def _columns(cls) -> ColumnCollection:
        return inspect(cls).columns

    @classmethod
    @property
    def _columns_keys(cls) -> list[Column]:
        return [c.key for c in cls._columns]  # type: ignore

    @classmethod
    @property
    def _pk_name(cls) -> str:
        return inspect(cls).primary_key[0].name

    @classmethod
    @property
    def _pk_column(cls) -> Column:
        return getattr(cls, cls._pk_name)  # type: ignore

    @property
    def _pk_value(self) -> Union[int, uuid.UUID]:
        return getattr(self, self._pk_name)

    @classmethod
    def _get_db(cls) -> AsyncSession:
        return make_db()

    @classmethod
    async def create(
            cls,
            _db: Optional[AsyncSession] = None,
            _commit: bool = True,
            _refresh: bool = True,
            **kwargs: Any
    ) -> DeclarativeBaseType:
        """Create a new model instance and saves to DB."""

        db: AsyncSession = _db or cls._get_db()
        try:
            obj = cls.__call__(**kwargs)
            db.add(obj)

            if _commit:
                await db.commit()
                if _refresh:
                    await db.refresh(obj)
        finally:
            if not _db:
                await db.close()

        return obj

    @classmethod
    async def get(cls, pk: Any, _db: Optional[AsyncSession] = None) -> DeclarativeBaseType:
        """Return a model instance by PK."""

        db: AsyncSession = _db or cls._get_db()
        try:
            obj = await db.get(cls, ident=pk)
        finally:
            if not _db:
                await db.close()

        return obj

    @classmethod
    async def get_list(
            cls, *args: Any, _db: Optional[AsyncSession] = None, **kwargs: Any
    ) -> list[DeclarativeBaseType]:
        """Return a list of model instances."""

        db: AsyncSession = _db or cls._get_db()
        order_by = kwargs.pop('order_by', None)
        try:
            result = await db.execute(select(cls).filter(*args, **kwargs).order_by(
                order_by if order_by else cls._pk_column
            ))
        finally:
            if not _db:
                await db.close()

        return result.all()

    async def save(
            self,
            update_fields: Optional[Union[tuple[str, ...], list[str], set[str]]] = None,
            _db: Optional[AsyncSession] = None,
            _commit: bool = True,
    ) -> None:
        """Save changed model's fields to DB."""

        if not self._pk_value:
            raise Exception(f'Unable to get primary key value for {self} column {self._pk_column}')

        if update_fields:
            data = {k: getattr(self, str(k)) for k in self._columns_keys if k in update_fields}
        else:
            data = {k: getattr(self, str(k)) for k in self._columns_keys}

        db: AsyncSession = _db or self._get_db()
        try:
            query = update(self.__class__).values(**data).where(self._pk_column == self._pk_value)

            query.execution_options(synchronize_session='fetch')
            await db.execute(query)

            if _commit:
                await db.commit()
        finally:
            if not _db:
                await db.close()

    async def delete(self, _db: Optional[AsyncSession] = None, _commit: bool = True) -> None:
        """Delete a model instance from DB."""

        db: AsyncSession = _db or self._get_db()
        try:
            await db.delete(self)

            if _commit:
                await db.commit()
        finally:
            if not _db:
                await db.close()

Base: DeclarativeBase = declarative_base(cls=DeclarativeBase)

# Make DB
engine = create_async_engine(settings.POSTGRES_DSN)
make_db = sessionmaker(bind=engine, class_=AsyncSession, future=True, expire_on_commit=False)


# -*- coding: utf-8 -*-
"""
Created on Fri Jan 31 18:50:47 2020

@author: CEC
"""

def readint(prompt, min, max):
#
# put your code here
    while (True):
        try:
            x=int(input())
            assert x >= min and x <= max
            return x
            break
        except ValueError:
            print("Error: wrong input")
            return None
        except:
            print("El valor debe estar dentro del RANGO --> (-10..10) <--")

v = readint("Enter a number from -10 to 10: ", -10, 10)

print("The number is:", v)

def validarNumero(prompt, min, max):
    while (True):
        try:
            x = int(input(prompt))
            assert x >= min and x <= max
            return x
            break
        except ValueError:
            print("Ingresar solo numeros")
        except:
            print("El valor debe estar dentro del RANGO --> (-10..10) <--")

v = validarNumero("Ingrese un valor desde -10 a 10:", -10, 10)

print("El número es:", v)


# Day 6, Tuning Trouble
from typing import List, Union

# Q1 & Q2
def report_first_marker(signal: str, size: int) -> int:
    for s, _ in enumerate(signal):
        if len(set(signal[s:s+size])) == size: return s+size
    assert False, f"unreachable, signal: {signal}, size: {size}"

# Input
def parse_input(file: str) -> Union[List[str], str]:
    with open(file, 'r') as inp:
        output = inp.read().strip().splitlines()
    return output.pop() if len(output) == 1 else [line.strip() for line in output]

if __name__ == '__main__':
    # Samples
    sample_input = parse_input('sample')

    # Tests
    sample_asserts = [(7,19), (5,23), (6,23), (10,29), (11,26)]
    assert all(report_first_marker(s, 4) == sa_p1 and report_first_marker(s, 14) == sa_p2 for
               s, (sa_p1, sa_p2) in zip(sample_input, sample_asserts))

    # Puzzle input
    puzzle_input = parse_input('puzzle-input')

    # Results
    q1 = report_first_marker(puzzle_input,  4)
    q2 = report_first_marker(puzzle_input, 14)

    print(f'Q1: {q1}')
    print(f'Q2: {q2}')


#imports
import tensorflow as tf
import numpy as np
from tensorflow.keras import datasets, layers, models
from tensorflow.keras.models import Sequential
import matplotlib.pyplot as plt

#loading data
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data() #splits data into 50k training and 10k testing

#normalising pixel values to be between 0 and 1
train_images, test_images = train_images / 255.0, test_images / 255.0

class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
               'dog', 'frog', 'horse', 'ship', 'truck']

#show first picture from each class
for i in range(9):
    examples = np.where(train_labels == i)
    first_index = examples[0][0]
    plt.imshow(train_images[first_index])
    plt.xlabel(class_names[train_labels[first_index][0]])
    plt.figure()

#define baseline model
model = Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10))

model.summary()

#training
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

#evaluating
history = model.fit(train_images, train_labels, epochs=10,
                    validation_data=(test_images, test_labels))

plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')

test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)


from django.template import Library

from rest_framework import serializers
from rest_framework.renderers import JSONRenderer
register = Library()
from . import models
import json

class UtilitiesSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Utilities
        depth = 1
        fields = (
            'utility', 'utilityPic'
        )

class LabelsSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Labels
        depth = 1
        fields = (
            'name',
        )

class RecipesSerializer(serializers.ModelSerializer):
  #  utilities = UtilitiesSerializer(many=True)
   # labels = LabelsSerializer(many=True)
    class Meta:
        model = models.Recipes
        depth = 3
        fields = (
            'id',
            'title',
            'description',
            'utilities',
            'labels',
            'forPeople',
            'cKal',
            'timeToMake',
            'timeToMakeActive',
            'image',
            'ingredients',
            'steps',
        )


# *_*coding:utf-8 *_*
# @Author : YueMengRui
import requests
from mylogger import logger
from typing import List
from configs import LLM_SERVER_APIS, EMBEDDING_SERVER_APIS

def servers_llm_chat(prompt, model_name: str = "", history: list = [], generation_configs: dict = {}):
    req_data = {
        "model_name": model_name,
        "prompt": prompt,
        "history": history,
        "generation_configs": generation_configs,
        "stream": False
    }
    resp = requests.post(url=LLM_SERVER_APIS['chat'], json=req_data)
    try:
        return resp.json()['answer']
    except Exception as e:
        logger.info(resp.text, e)
        return None

def servers_token_count(prompt: str, model_name: str = ""):
    req_data = {
        "model_name": model_name,
        "prompt": prompt
    }

    return requests.post(url=LLM_SERVER_APIS['token_counter'], json=req_data)

def servers_get_llm_list():
    return requests.get(url=LLM_SERVER_APIS['model_list'])

def servers_get_embedding_model_list():
    resp = requests.get(url=EMBEDDING_SERVER_APIS['model_list'])
    logger.info(resp.text)
    return resp

def servers_embedding_text(sentences: List[str], model_name: str = ""):
    req_data = {
        "model_name": model_name,
        "sentences": sentences
    }

    return requests.post(url=EMBEDDING_SERVER_APIS['embedding_text'], json=req_data)


import os
from . import CollectCurriculum
from traitlets.config import Configurable
from traitlets import List

class DsPipeline(Configurable):

    name = 'DsPipeline'
    description = '''
    The primary pipeline for dscreate

    DsPipeline's primary variable is ``steps`` containing converter and controller objects.
    Every object included in steps must have ``enabled`` and ``printout`` attributes, and a ``.start``  method
    '''
    steps = List(config=True)
    branches = List(config=True)

    def __init__(self, **kwargs) -> None:
        """
        Set up configuration file.
        """
        super(DsPipeline, self).__init__(**kwargs)

    def start(self) -> None:
        for step in self.steps:
            pipeline_step = step(config=self.config)
            if pipeline_step.enabled:
                print(pipeline_step.printout)
                pipeline_step.start()
                self.update_config(pipeline_step.config)
        if self.config.inline.enabled:
            os.remove(self.config.CollectCurriculum.edit_file)


from ellipticCurve import ellipticCurveSolver
from primeChecker import primeChecker
from new_simple import *
from power import powerCongruence
from simply_exp import *
from numsix import *

def show_menu():
    print("\"simple\": to calculate a simple linear congruence of style ax = b mod(n)")
    print("\"power\": to calculate a powered congruence of style x^e = b mod(n)")
    print("\"elliptic\": to calculate an elliptic curve of style Y=y^2 = x^3 + ax + b (mod p)")
    print("\"prime check\": check if an extremely large integer is prime")
    print("\"new_simple\": problem like 13x+5= 15(mod 23)")
    print("\"simplify\": 'Simplify the following expressions")
    print("\"menu\": to see all available options")
    print("\"ecadd\": To calculate #P using the double-and-add algorithm")
    print("\"order_num\": Find the possible orders of number in Zp")
    print("\"end\": to close program\n")

def main():
    print("welcome to the Modulus Calculator")

    # initialize option before using in while loop
    option = "placeholder"

    print("type \"menu\" to see all available options")
    while option != "end":
        option = input("\nWhat would you like to do?: ")

        if option == "simplify":
            print("a^b (mod p)")
            a = int(input("a = "))
            b = int(input("b = "))
            p = int(input("p = "))
            simplify_base(a, b, p)

        if option == "simple":
            print("ax = b mod(n)")
            num = int(input("a = "))
            num2 = int(input("b = "))
            mod_value = int(input("n = "))

            #fixed to use minv
            mod_inv = minv(num, mod_value)
            print("First find the modulus inverse of a")
            print("modulus inverse of", num, "=", mod_inv)
            solution = num2*mod_inv % mod_value
            print("multiply the mod inverse on both sides")
            print(mod_inv, "*", num, " = ", mod_inv, "*", num2, " (mod ", mod_value, ")", sep='')
            print("therefore: ", num2*mod_inv, " (mod ", mod_value, ")", sep='')
            print("solution =", solution)

        if option == "order_num":
            numbers_of_order_base()

        if option == "power":
            print("x^e = b mod(n)")
            num = int(input("b = "))
            mod_value = int(input("n = "))
            exponent = int(input("e = "))
            powerCongruence(num, exponent, mod_value, False)

        if option == "power show":
            print("x^e = b mod(n)")
            num = int(input("b = "))
            mod_value = int(input("n = "))
            exponent = int(input("e = "))
            answer = powerCongruence(num, exponent, mod_value, True)
            print("x =", answer)

        if option == "ecadd":
            print("Y=y^2 = x^3 + ax + b  (mod p)")
            a = int(input("a = "))
            b = int(input("b = "))
            x = int(input("x = "))
            p = int(input("p = "))
            print("P = (x1, y1)")
            x1 = int(input("x1 = "))
            y1 = int(input("y1 = "))
            print("REMEMBER: If using double and add, type in the same point as (x1, y1)")
            print("P = (x2, y2)")
            x2 = int(input("x2 = "))
            y2 = int(input("y2 = "))
            print("Calculate #P using...")
            np = int(input("#P = "))
            for x in range(1, np):
                (x2, y2) = ecadd(p, a, x1, y1, x2, y2)
                print(x + 1, "P = (", x2, ",", y2, ")", sep='')

        if option == "elliptic":
            print("Y=y^2 = x^3 + ax + b (mod p)")
            x = int(input("x = "))
            mod_value = int(input("p = "))
            a = int(input("a = "))
            b = int(input("b = "))
            values = ellipticCurveSolver(x, mod_value, a, b, False)
            print("y values are", values)

        if option == "elliptic show":
            print("Y=y^2 = x^3 + ax + b (mod p)")
            x = int(input("x = "))
            mod_value = int(input("p = "))
            a = int(input("a = "))
            b = int(input("b = "))
            values = ellipticCurveSolver(x, mod_value, a, b, True)
            print("y values are", values)

        if option == "prime check":
            prime = int(input("prime = "))
            isPrime = primeChecker(prime)

            print(isPrime)
        if option == "menu":
            show_menu()
        if option == "new_simple":
            print("ax = b mod(n)")
            numa = int(input("a = "))
            numb = int(input("b = "))
            numn = int(input("n = "))
            new_simple(numa, numb, numn)

if __name__ == "__main__":
    main()


#  1a - Given a list of the numbers between 1 and 10 (but excluding one number) find the missing number
x = set([1, 2, 3, 4, 5, 6, 7, 8, 10])
y = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

z = y.difference(x)
print (z)

#  1b - Modify your program to remove a random number
b = [1, 2, 3, 4, 5, 6, 7, 8, 10]
import random
b.pop(random.randrange(len(b)))
print(b)

#  1c - Update the program to have all numbers from 1 to 100 and remove a random number of elements. Find how many numbers were removed and what they were
lst = list(range(1,101))
print(lst)
a = random.randint(0,101)
print(a)
(lst.pop(random.randrange(len(lst))))*a #how to pass 'a' into this line?
print(lst)

#  1d - Create a new program that duplicates one element in the list at random and then find which number has been duplicated

# 2a - Given the following tuple of numbers, what is the difference between the biggest and smallest number? 2, 5, 12, 7, 9

tup = (2, 5, 12, 7, 9)
tup_diff = (max(tup))-(min(tup))
print(tup_diff)

#  2b - Find the product of the elements of the tuple (product is each item multiplied together)
#print(zip(tup))

from math import prod
print(prod(tup))

#  2c - Modify your program to generate a tuple of random numbers of a random length and still show what the difference and product is

#  3a - Create a dictionary to store the favourite colours of the following individuals
fave_colours = {'Becci' : 'green', 'Steve' : 'orange', 'Melinda' : 'purple', 'Ryan' : 'orange', 'Nate' : 'green' , 'Anna' : 'green'}
#  3b - Add your own favourite colours. Update Melinda’s preference to green and remove Becci’s preference from the dictionary
fave_colours['Lonie']='black'
fave_colours.pop('Becci')
fave_colours.get('Melinda')
fave_colours['Melinda']='green'
print(fave_colours)

#  3c - Write code to create a new dictionary that has the key as each colour’s name and the value being how many people have that colour as their favourite
print(len(fave_colours))

# from collections import counter
# counter(fave_colours))

#  3d - Write code to create another dictionary that has the colour name as the key and a list of all the people that don’t have that colour as their favourite as the value


import torch
import torch.nn as nn

from utils.linear import Linear
from crossbar.crossbar import crossbar
from utils.observer import Observer
from networks.ode_net import ODE_Net

class ODE_NN(nn.Module):

    def __init__(self, input_size, output_size, device_params, time_steps):

        super(ODE_NN, self).__init__()

        self.observer = Observer()
        self.cb = crossbar(device_params)

        # Construct model and layers
        self.hidden_layer_size = hidden_layer_size
        self.linear_hidden = Linear(input_size, output_size, self.cb)

        self.solve = ODE_Net(input_size, self.N, self.cb, self.observer)
        self.nonlinear = nn.Tanh()

    # Taking a sequence, this predicts the next N points, where
    def forward(self, x, t):

        h_i = torch.zeros(self.input_size, 1)

        for i, x_i in enumerate(x):
            if i == (len(x) - 1) and self.observer.on == True:
                self.solve.observer_flag = True

            h_i = self.solve(h_i, t[i-1] if i>0 else t[i], t[i])

            if i == (len(x) - 1):
                self.observer.append(h_i.view(1, -1), t[i])

            h_i = self.nonlinear(self.linear_in(x_i) + self.linear_hidden(h_i))

            if i == (len(x) - 1):
                self.observer.append(h_i.view(1, -1), t[i])

            self.solve.observer_flag = False

        return self.linear_out(h_i)


from keras.utils import to_categorical
import tensorflow as tf
import pygame

class pytennis:
    def __init__(self, fps = 50):
        self.net = Network(150,450,100,600)
        self.updateRewardA = 0
        self.updateRewardB = 0
        self.updateIter = 0
        self.lossA = 0
        self.lossB = 0

        # Testing
        self.net = Network(150, 450, 100, 600)
        self.NetworkA = self.net.network(300, ysource=100, Ynew=600)  # Network A
        self.NetworkB = self.net.network(200, ysource=600, Ynew=100)  # Network B
        # NetworkA

        # display test plot of network A
        #sns.jointplot(NetworkA[0], NetworkA[1])

        # display test plot of network B
        #sns.jointplot(NetworkB[0], NetworkB[1])

        self.out = self.net.DefaultToPosition(250)

        self.lastxcoordinate = 350

        pygame.init()
        self.BLACK = ( 0,0,0)

        self.myFontA = pygame.font.SysFont("Times New Roman", 25)
        self.myFontB = pygame.font.SysFont("Times New Roman", 25)
        self.myFontIter = pygame.font.SysFont('Times New Roman', 25)

        self.FPS = fps
        self.fpsClock = pygame.time.Clock()

    def setWindow(self):

        # set up the window
        self.DISPLAYSURF = pygame.display.set_mode((600, 700), 0, 32)
        pygame.display.set_caption('REINFORCEMENT LEARNING (Discrete Mathematics) - TABLE TENNIS')
        # set up the colors
        self.BLACK = ( 0,0,0)
        self.WHITE = (255, 255, 255)
        self.RED= (255,0,0)
        self.GREEN = ( 0, 255,0)
        self.BLUE = ( 0,0, 255)

        return

    def display(self):
        self.setWindow()
        self.DISPLAYSURF.fill(self.WHITE)
        pygame.draw.rect(self.DISPLAYSURF, self.GREEN, (150, 100, 300, 500))
        pygame.draw.rect(self.DISPLAYSURF, self.RED, (150, 340, 300, 20))
        pygame.draw.rect(self.DISPLAYSURF, self.BLACK, (0, 20, 600, 20))
        pygame.draw.rect(self.DISPLAYSURF, self.BLACK, (0, 660, 600, 20))
        return

    def reset(self):
        return

    def evaluate_state_from_last_coordinate(self, c):
        """
        cmax: 450
        cmin: 150

        c definately will be between 150 and 450.
        state0 - (150 - 179)
        state1 - (180 - 209)
        state2 - (210 - 239)
        state3 - (240 - 269)
        state4 - (270 - 299)
        state5 - (300 - 329)
        state6 - (330 - 359)
        state7 - (360 - 389)
        state8 - (390 - 419)
        state9 - (420 - 450)
        """
        if c >= 150 and c <=179:
            return 0
        elif c >= 180 and c <= 209:
            return 1
        elif c >=210 and c <= 239:
            return 2
        elif c >=240 and c <= 269:
            return 3
        elif c>= 270 and c<=299:
            return 4
        elif c >= 300 and c <= 329:
            return 5
        elif c >= 330 and c <= 359:
            return 6
        elif c >= 360 and c <= 389:
            return 7
        elif c >= 390 and c <= 419:
            return 8
        elif c >= 420 and c <= 450:
            return 9

    def evaluate_action(self, action, expectedState):
        if action == expectedState:
            return True
        else:
            return False

    def randomVal(self, action):
        """
        cmax: 450
        cmin: 150

        c definately will be between 150 and 450.
        state0 - (150 - 179)
        state1 - (180 - 209)
        state2 - (210 - 239)
        state3 - (240 - 269)
        state4 - (270 - 299)
        state5 - (300 - 329)
        state6 - (330 - 359)
        state7 - (360 - 389)
        state8 - (390 - 419)
        state9 - (420 - 450)
        """
        if action == 0:
            val = np.random.choice([i for i in range(150, 180)])
        elif action == 1:
            val = np.random.choice([i for i in range(180, 210)])
        elif action == 2:
            val = np.random.choice([i for i in range(210, 240)])
        elif action == 3:
            val = np.random.choice([i for i in range(240, 270)])
        elif action == 4:
            val = np.random.choice([i for i in range(270, 300)])
        elif action == 5:
            val = np.random.choice([i for i in range(300, 330)])
        elif action == 6:
            val = np.random.choice([i for i in range(330, 360)])
        elif action == 7:
            val = np.random.choice([i for i in range(360, 390)])
        elif action == 8:
            val = np.random.choice([i for i in range(390, 420)])
        else:
            val = np.random.choice([i for i in range(420, 450)])
        return val

    def stepA(self, action, count = 0):
        #playerA should play
        if count == 0:
            #playerax = lastxcoordinate
            self.NetworkA = self.net.network(self.lastxcoordinate, ysource = 100, Ynew = 600) #Network A
            self.out = self.net.DefaultToPosition(self.lastxcoordinate)

            #update lastxcoordinate

            self.bally = self.NetworkA[1][count]
            #here
            #self.playerax = self.out[count]
            self.playerbx = self.randomVal(action)

#             soundObj = pygame.mixer.Sound('sound/sound.wav')
#             soundObj.play()
#             time.sleep(0.4)
#             soundObj.stop()
        elif count == 49:
            self.ballx = self.NetworkA[0][count]
            self.bally = self.NetworkA[1][count]

            # move playerbx with respect to action
            self.playerbx = self.randomVal(action)

        else:
            self.ballx = self.NetworkA[0][count]
            self.bally = self.NetworkA[1][count]

            # move playerbx with respect to action
#             self.playerbx = self.randomVal(action)

        obs = self.evaluate_state_from_last_coordinate(int(self.ballx)) # last state of the ball
        reward = self.evaluate_action(action, obs)
        done = True
        info = ''

        return obs, reward, done, info

    def stepB(self, action, count):
        #playerB can play
        if count == 0:
            #playerbx = lastxcoordinate
            self.NetworkB = self.net.network(self.lastxcoordinate, ysource = 600, Ynew = 100) #Network B
            self.out = self.net.DefaultToPosition(self.lastxcoordinate)

            #update lastxcoordinate
            self.bally = self.NetworkB[1][count]
            #self.playerax = self.out[count]
            self.playerax = self.randomVal(action)

#             soundObj = pygame.mixer.Sound('sound/sound.wav')
#             soundObj.play()
#             time.sleep(0.4)
#             soundObj.stop()
        elif count ==49:
            self.ballx = self.NetworkA[0][count]
            self.bally = self.NetworkA[1][count]

            # move playerbx with respect to action
            self.playerbx = self.randomVal(action)

        else:
            self.ballx = self.NetworkB[0][count]
            self.bally = self.NetworkB[1][count]
#             self.playerbx = self.randomVal(action)

        obs = self.evaluate_state_from_last_coordinate(int(self.ballx)) # last state of the ball
        reward = self.evaluate_action(action, obs)
        done = True
        info = ''

        return obs, reward, done, info

    def computeLossA(self, reward):
        if reward == 0:
            self.lossA += 1
        else:
            self.lossA += 0
        return

    def computeLossB(self, reward):
        if reward == 0:
            self.lossB += 1
        else:
            self.lossB += 0
        return

    def render(self):
        # diplay team players
        self.PLAYERA = pygame.image.load('images/cap.jpg')
        self.PLAYERA = pygame.transform.scale(self.PLAYERA, (50, 50))
        self.PLAYERB = pygame.image.load('images/cap.jpg')
        self.PLAYERB = pygame.transform.scale(self.PLAYERB, (50, 50))
        self.ball = pygame.image.load('images/ball.png')
        self.ball = pygame.transform.scale(self.ball, (15, 15))

        self.playerax = 150
        self.playerbx = 250

        self.ballx = 250
        self.bally = 300

        count = 0
        nextplayer = 'A'
        #player A starts by playing with state 0
        obs, reward, done, info = self.stepA(0)
        stateA = obs
        stateB = obs
        next_state = 0

        iterations = 20000
        iteration = 0
        restart = False

        while iteration < iterations:
            self.display()
            self.randNumLabelA = self.myFontA.render('A (Win): '+str(self.updateRewardA) + ', A(loss): '+str(self.lossA), 1, self.BLACK)
            self.randNumLabelB = self.myFontB.render('B (Win): '+str(self.updateRewardB) + ', B(loss): '+ str(self.lossB), 1, self.BLACK)
            self.randNumLabelIter = self.myFontIter.render('Iterations: '+str(self.updateIter), 1, self.BLACK)
            if nextplayer == 'A':

                if count == 0:
                    # Online DQN evaluates what to do
                    q_valueA = AgentA.model.predict([stateA])
                    actionA = AgentA.epsilon_greedy(q_valueA, iteration)

                    # Online DQN plays
                    obs, reward, done, info = self.stepA(action = actionA, count = count)
                    next_stateA = obs

                    # Let's memorize what just happened
                    AgentA.replay_memory.append((stateA, actionA, reward, next_stateA, 1.0 - done))
                    stateA = next_stateA

                else:
                    # Online DQN evaluates what to do
                    q_valueA = AgentA.model.predict([stateA])
                    actionA = AgentA.epsilon_greedy(q_valueA, iteration)

                    # Online DQN plays

                    obs, reward, done, info = self.stepA(action = actionA, count = count)
                    next_stateA = obs

                    # Let's memorize what just happened
#                     AgentA.replay_memory.append((state, action, reward, next_state, 1.0 - done))
                    stateA = next_stateA

                count += 1
                if count == 50:
                    count = 0

                    self.updateRewardA += reward
                    self.computeLossA(reward)

                    #restart the game if player A fails to get the ball, and let B start the game
                    if reward == 0:
                        restart = True
                        time.sleep(0.5)
                        nextplayer = 'B'
                        self.playerbx = self.ballx
                    else:
                        restart = False

                    # Sample memories and use the target DQN to produce the target Q-Value
                    X_state_val, X_action_val, rewards, X_next_state_val, continues = (AgentA.sample_memories(AgentA.batch_size))
                    next_q_values = AgentA.model.predict([X_next_state_val])
                    max_next_q_values = np.max(next_q_values, axis=1, keepdims=True)
                    y_val = rewards + continues * AgentA.discount_rate * max_next_q_values

                    # Train the online DQN
                    AgentA.model.fit(X_state_val,tf.keras.utils.to_categorical(X_next_state_val, num_classes=10), verbose = 0)

                    nextplayer = 'B'
                    self.updateIter += 1

                    #evaluate A
                else:
                    nextplayer = 'A'

            else:

                if count == 0:
                    # Online DQN evaluates what to do
                    q_valueB = AgentB.model.predict([stateB])
                    actionB = AgentB.epsilon_greedy(q_valueB, iteration)

                    # Online DQN plays
                    obs, reward, done, info = self.stepB(action = actionB, count = count)
                    next_stateB = obs

                    # Let's memorize what just happened
                    AgentB.replay_memory.append((stateB, actionB, reward, next_stateB, 1.0 - done))
                    stateB = next_stateB
                else:
                    # Online DQN evaluates what to do
                    q_valueB = AgentB.model.predict([stateB])
                    actionB = AgentB.epsilon_greedy(q_valueB, iteration)

                    # Online DQN plays
                    obs, reward, done, info = self.stepB(action = actionB, count = count)
                    next_stateB = obs

                    # Let's memorize what just happened
#                     AgentB.replay_memory.append((state, action, reward, next_state, 1.0 - done))
                    stateB = next_stateB

                count += 1
                if count == 50:
                    count = 0

                    self.updateRewardB += reward
                    self.computeLossB(reward)

                    #restart the game if player A fails to get the ball, and let B start the game
                    if reward == 0:
                        restart = True
                        time.sleep(0.5)
                        nextplayer = 'A'
                        self.playerax = self.ballx
                    else:
                        restart = False

                    # Sample memories and use the target DQN to produce the target Q-Value
                    X_state_val, X_action_val, rewards, X_next_state_val, continues = (AgentB.sample_memories(AgentB.batch_size))
                    next_q_values = AgentB.model.predict([X_next_state_val])
                    max_next_q_values = np.max(next_q_values, axis=1, keepdims=True)
                    y_val = rewards + continues * AgentB.discount_rate * max_next_q_values

                    # Train the online DQN
                    AgentB.model.fit(X_state_val,tf.keras.utils.to_categorical(X_next_state_val, num_classes=10), verbose = 0)

                    nextplayer = 'A'
                    self.updateIter += 1
                    #evaluate B
                else:
                    nextplayer = 'B'

                count += 1
            #CHECK BALL MOVEMENT
            self.DISPLAYSURF.blit(self.PLAYERA, (self.playerax, 50))
            self.DISPLAYSURF.blit(self.PLAYERB, (self.playerbx, 600))
            self.DISPLAYSURF.blit(self.ball, (self.ballx, self.bally))
            self.DISPLAYSURF.blit(self.randNumLabelA, (300, 630))
            self.DISPLAYSURF.blit(self.randNumLabelB, (300, 40))
            self.DISPLAYSURF.blit(self.randNumLabelIter, (50, 40))

            #update last coordinate
            self.lastxcoordinate = self.ballx

            pygame.display.update()
            self.fpsClock.tick(self.FPS)

            for event in pygame.event.get():

                if event.type == QUIT:
                    AgentA.model.save('AgentA.h5')
                    AgentB.model.save('AgentB.h5')
                    pygame.quit()
                    sys.exit()


#main programm.
import sqlite3
mybook=sqlite3.connect('bookstore.db')

ans='y'
total=0
while ans=='y' or ans=='Y':
    bt=input("\nBook Title : ")
    sql="SELECT * from books WHERE Title='"+bt+"';"
    cursbook=mybook.cursor()
    cursbook.execute(sql)
    record=cursbook.fetchone()
    if record==None:
        print("\n*no result found*")
    else:
        print(record)
        qt=int(input("\nno. of copies : "))
        sql="SELECT Price from books WHERE Title='"+bt+"';"
        cursbook=mybook.cursor()
        cursbook.execute(sql)
        price=cursbook.fetchone()
        for i in price:
            total=total + i*qt
    ans=input("\nadd more books? Y/N : ")

print("\ntotal cost : ",total)

Python_Module_Assignments/ADARSH NISHAD - Python_M5Assignment/main.py


from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

import collections
import json

from googlecloudsdk.command_lib.apigee import errors
from googlecloudsdk.command_lib.apigee import resource_args
from googlecloudsdk.core import properties
from googlecloudsdk.core.credentials import requests
from six.moves import urllib

APIGEE_HOST = "apigee.googleapis.com"
ERROR_FIELD = "error"
MESSAGE_FIELD = "message"

def _ResourceIdentifier(identifiers, entity_path):
  """Returns an OrderedDict uniquely identifying the resource to be accessed.

  Args:
    identifiers: a collection that maps entity type names to identifiers.
    entity_path: a list of entity type names from least to most specific.

  Raises:
    MissingIdentifierError: an entry in entity_path is missing from
      `identifiers`.
  """
  resource_identifier = collections.OrderedDict()

  for entity_name in entity_path:
    entity = resource_args.ENTITIES[entity_name]
    id_key = entity.plural + "Id"
    if id_key not in identifiers or identifiers[id_key] is None:
      raise errors.MissingIdentifierError(entity.singular)
    resource_identifier[entity] = identifiers[id_key]
  return resource_identifier

def _Communicate(url, method, body, headers):
  """Returns HTTP status, reason, and response body for a given HTTP request."""
  response = requests.GetSession().request(
      method, url, data=body, headers=headers, stream=True)
  status = response.status_code
  reason = response.reason
  data = response.content
  return status, reason, data

def _DecodeResponse(response):
  """Returns decoded string.

  Args:
    response: the raw string or bytes of JSON data

  Raises:
    ValueError: failure to load/decode JSON data
  """
  # In older versions of Python 3, the built-in JSON library will only
  # accept strings, not bytes.
  if not isinstance(response, str) and hasattr(response, "decode"):
    response = response.decode()
  return response

def _GetResourceType(entity_collection, entity_path):
  """Gets resource type from the inputed data."""
  return entity_collection or entity_path[-1]

def _BuildErrorIdentifier(resource_identifier):
  """Builds error identifier from inputed data."""
  return collections.OrderedDict([
      (key.singular, value) for key, value in resource_identifier.items()
  ])

def _ExtractErrorMessage(response):
  """Extracts error message from response, returns None if message not found."""
  json_response = json.loads(response)
  if ERROR_FIELD in json_response and isinstance(
      json_response[ERROR_FIELD],
      dict) and MESSAGE_FIELD in json_response[ERROR_FIELD]:
    return json_response[ERROR_FIELD][MESSAGE_FIELD]
  return None

def ResponseToApiRequest(identifiers,
                         entity_path,
                         entity_collection=None,
                         method="GET",
                         query_params=None,
                         accept_mimetype=None,
                         body=None,
                         body_mimetype="application/json"):
  """Makes a request to the Apigee API and returns the response.

  Args:
    identifiers: a collection that maps entity type names to identifiers.
    entity_path: a list of entity type names from least to most specific.
    entity_collection: if provided, the final entity type; the request will not
      be specific as to which entity of that type is being referenced.
    method: an HTTP method string specifying what to do with the accessed
      entity. If the method begins with a colon, it will be interpreted as a
      Cloud custom method (https://cloud.google.com/apis/design/custom_methods)
      and appended to the request URL with the POST HTTP method.
    query_params: any extra query parameters to be sent in the request.
    accept_mimetype: the mimetype to expect in the response body. If not
      provided, the response will be parsed as JSON.
    body: data to send in the request body.
    body_mimetype: the mimetype of the body data, if not JSON.

  Returns:
    an object containing the API's response. If accept_mimetype was set, this
      will be raw bytes. Otherwise, it will be a parsed JSON object.

  Raises:
    MissingIdentifierError: an entry in entity_path is missing from
      `identifiers`.
    RequestError: if the request itself fails.
  """
  headers = {}
  if body:
    headers["Content-Type"] = body_mimetype
  if accept_mimetype:
    headers["Accept"] = accept_mimetype

  resource_identifier = _ResourceIdentifier(identifiers, entity_path)
  url_path_elements = ["v1"]
  for key, value in resource_identifier.items():
    url_path_elements += [key.plural, urllib.parse.quote(value)]
  if entity_collection:
    collection_name = resource_args.ENTITIES[entity_collection].plural
    url_path_elements.append(urllib.parse.quote(collection_name))

  query_string = urllib.parse.urlencode(query_params) if query_params else ""

  endpoint_override = properties.VALUES.api_endpoint_overrides.apigee.Get()
  if endpoint_override:
    endpoint = urllib.parse.urlparse(endpoint_override)
    scheme = endpoint.scheme
    host = endpoint.netloc
  else:
    scheme = "https"
    host = APIGEE_HOST

  url_path = "/".join(url_path_elements)
  if method and method[0] == ":":
    url_path += method
    method = "POST"
  url = urllib.parse.urlunparse((scheme, host, url_path, "", query_string, ""))

  status, reason, response = _Communicate(url, method, body, headers)

  if status >= 400:
    resource_type = _GetResourceType(entity_collection, entity_path)
    if status == 404:
      exception_class = errors.EntityNotFoundError
    elif status in (401, 403):
      exception_class = errors.UnauthorizedRequestError
    else:
      exception_class = errors.RequestError
    error_identifier = _BuildErrorIdentifier(resource_identifier)

    try:
      user_help = _ExtractErrorMessage(_DecodeResponse(response))
    except ValueError:
      user_help = None

    raise exception_class(resource_type, error_identifier, method,
                          reason, response, user_help=user_help)

  if accept_mimetype is None:
    try:
      response = _DecodeResponse(response)
      response = json.loads(response)
    except ValueError as error:
      resource_type = _GetResourceType(entity_collection, entity_path)
      error_identifier = _BuildErrorIdentifier(resource_identifier)
      raise errors.ResponseNotJSONError(error, resource_type, error_identifier,
                                        response)

  return response


from dataclasses import dataclass

temperature = int

a: temperature = 1
b = 1

assert a == b

int_or_float = int | float

c: int_or_float = 10
d: int_or_float = 10.0

assert c == 10
assert d == 10.0

@dataclass
class Point:
    x: int
    y: int

str_or_Point = str | Point

hello = "hello"
e: str_or_Point = "hello"
origin = Point(0, 0)
f: str_or_Point = Point(0, 0)

assert e == "hello"
assert hello == e
assert f == Point(0, 0)
assert origin == f

g = f

assert g == f
assert origin == g


import argparse
import numpy as np
import os
import json
from builtins import range
import tensorrtserver.api.model_config_pb2 as model_config
from tensorrtserver.api import *
import time

def triton_inferer(ctx, input_name, output_name, batch):
    batch = [batch[i].astype(np.float32) for i in range(0,batch.shape[0]) ]

    input_dict = { input_name : batch }
    output_dict = { output_name : (InferContext.ResultFormat.RAW)}
    results = ctx.run(
        inputs=input_dict,
        outputs=output_dict,
        batch_size=80
    )
    return results[output_name]

def parse_model(url, protocol, model_name, batch_size, verbose=False):
    """
    Check the configuration of a model to make sure it meets the
    requirements
    """
    ctx = ServerStatusContext(url, protocol, model_name, verbose)
    server_status = ctx.get_server_status()

    if model_name not in server_status.model_status:
        raise Exception("unable to get status for '" + model_name + "'")

    status = server_status.model_status[model_name]
    config = status.config

    if len(config.input) != 1:
        raise Exception("expecting 1 input, got {}".format(len(config.input)))
    if len(config.output) != 1:
        raise Exception("expecting 1 output, got {}".format(len(config.output)))

    input = config.input[0]
    output = config.output[0]

    # Model specifying maximum batch size of 0 indicates that batching
    # is not supported and so the input tensors do not expect an "N"
    # dimension (and 'batch_size' should be 1 so that only a single
    # image instance is inferred at a time).
    max_batch_size = config.max_batch_size
    if max_batch_size == 0:
        if batch_size != 1:
            raise Exception("batching not supported for model '" + model_name + "'")
    else: # max_batch_size > 0
        if batch_size > max_batch_size:
            raise Exception("expecting batch size <= {} for model {}".format(max_batch_size, model_name))

#     Model input must have 3 dims, either CHW or HWC
    if len(input.dims) != 3:
        raise Exception(
            "expecting input to have 3 dimensions, model '{}' input has {}".format(
                model_name, len(input.dims)))

    if input.format == model_config.ModelInput.FORMAT_NHWC:
        h = input.dims[0]
        w = input.dims[1]
        c = input.dims[2]
    else:
        c = input.dims[0]
        h = input.dims[1]
        w = input.dims[2]

    return (input.name, output.name, c, h, w, input.format, input.data_type)

def main():
    parser = argparse.ArgumentParser(description='Run inference with a model on the TRITON server')
    parser.add_argument('--model', help='Model in TRITON server')
    parser.add_argument('-u', '--url', type=str, required=False, default='localhost:8000',
                        help='Inference server URL. Default is localhost:8000.')
    parser.add_argument('-i', '--protocol', type=str, required=False, default='http',
                        help='Protocol ("http"/"grpc") used to ' +
                        'communicate with inference service. Default is "http".')
    parser.add_argument('-H', dest='http_headers', metavar="HTTP_HEADER",
                        required=False, action='append',
                        help='HTTP headers to add to inference server requests. ' +
                        'Format is -H"Header:Value".')
    parser.add_argument('--interval', default=1, type=int,
                        metavar='N', help='interval to simulate inference requests')
    args = parser.parse_args()

    url = args.url
    protocol = ProtocolType.from_str(args.protocol)
    model_name = args.model
    model_version = -1

    try:
        print("Checking Health for model {}".format(model_name))
        health_ctx = ServerHealthContext(args.url, protocol,
                                     http_headers=args.http_headers)
        print("Live: {}".format(health_ctx.is_live()))
        print("Ready: {}".format(health_ctx.is_ready()))
    except:
        raise RuntimeError("Model not available in server.. OR.. Is it running?")

    batch_size = 80
    input_name, output_name, c, h, w, format, dtype = parse_model(url, protocol, model_name, batch_size, verbose=True)

    ## Generate random inputs
    input_shape = (batch_size,c,h,w)
    inputs = np.random.random(input_shape).astype(np.float32)
    ctx = InferContext(url, protocol, model_name, model_version, verbose=False)

    request_interval = args.interval

    counter = 0
    while counter < 10000:
        out = triton_inferer(ctx, input_name, output_name, inputs)
        if counter % 100 == 0: print('Iteration {}'.format(counter))
        time.sleep(1)
        counter += 1

if __name__ == "__main__":
    main()


#!/usr/bin/python
# -*- coding:utf-8 -*-
from django.urls import path
from favorite import views

# 收藏页面
urlpatterns = [
    path('add/<game_id>', views.add, name="favorite-add"),
    path('remove/<game_id>', views.remove, name="favorite-remove"),
    path('list', views.list, name="favorite-list"),
]


import numpy as np
from rbf_nn import sigmoid, sigmoidPrime, feedforward, backpropagation, loss, model
import matplotlib.pyplot as plt
from random import randint
import copy
from numpy.linalg import norm

p = np.zeros((2, 2000))
u = []
t = []
d = [0.5]
for i in range(2000):
    u.append(2*np.random.uniform(0, 1)-1)
    dd = d[-1]/(1+d[-1]*d[-1]) + np.power(u[-1], 3)
    d.append(dd)
    p[0][i] = u[i]
    p[1][i] = d[i]
    t.append(dd)

t = np.array(t)/3 + 0.5
plt.plot(u, t, marker='o', markersize=2, linewidth=0, color='r')
plt.show()

X = np.array(p).T
y = np.array(t)
y = np.reshape(y, (np.size(y), 1))

layer = [50, 20, 1]
learning_rate = 0.001
learning_rate_c = 0.005
l2_lambda = 0
batch_size = 100
num_batch = int(X.shape[0]/ batch_size)
input_dim = X.shape[1]

np.random.seed(0)
init_center = copy.deepcopy(X)
centers, sigmas, weights, bias = model(init_center, layer)

for i in range(5000):
    for rr in range(num_batch):
        input_x = X[batch_size*rr:batch_size*(rr+1)]
        input_y = y[batch_size*rr:batch_size*(rr+1)]

        aa = feedforward(input_x[:], centers, sigmas, weights, bias)
        centers, sigmas, weights, bias, dd = backpropagation(input_y[:], aa, centers, sigmas, weights, bias, learning_rate_c, learning_rate=learning_rate, l2_lambda=l2_lambda)

    if(i%100==0):
        aa = feedforward(X[:], centers, sigmas, weights, bias)
        yd = aa[-1]
        lo = loss(y, yd)
        print(i, lo)

# Prediction
aa = feedforward(X, centers, sigmas, weights, bias)
yd = aa[-1]

fig=plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k')
plt.plot(u,(yd-0.5)*3, marker='o', markersize=5, linewidth=0, color='orange')
plt.plot(u,(t-0.5)*3, marker='^', markersize=5, linewidth=0, color='g')
plt.show()


from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView
from .models import Restaurant, Dish, RestaurantReview
from .forms import RestaurantForm, DishesForm
from django.urls import reverse_lazy, reverse
from django.http import HttpResponseRedirect

# Create your views here.

class RestaurantDetailView(DetailView):
    model = Restaurant
    template_name = 'restaurantApp/restaurant_detail.html'
    context_object_name = 'restaurant_object'
    success_url = 'restaurant-detail'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['RATING_CHOICES'] = RestaurantReview.RATING_CHOICES
        return context

class RestaurantCreateView(CreateView):
    model = Restaurant
    template_name = 'restaurantApp/restaurant_create.html'
    form_class = RestaurantForm
    success_url = '/'

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

class RestaurantUpdateView(UpdateView):
    model = Restaurant
    template_name = 'restaurantApp/restaurant_edit.html'
    form_class = RestaurantForm
    success_url = '/'

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

class DishesCreateView(CreateView):
    model = Dish
    template_name = 'restaurantApp/dishes_create.html'
    form_class = DishesForm
    success_url = '/'

    def form_valid(self, form):
        form.instance.user = self.request.user
        form.instance.restaurant = Restaurant.objects.get(id=self.kwargs['pk'])
        return super().form_valid(form)

class DishesDetailView(DetailView):
    model = Dish
    template_name = 'restaurantApp/dishes_detail.html'
    context_object_name = 'dishes_detail'

class DishesUpdateView(UpdateView):
    model = Dish
    template_name = 'restaurantApp/dishes_edit.html'
    form_class = DishesForm
    success_url = '/'

    def form_valid(self, form):
        form.instance.user = self.request.user
        form.instance.restaurant = Restaurant.objects.get(id=self.kwargs['pk'])
        return super().form_valid(form)

# class ReviewCreateView(CreateView):
#     success_url = 'restaurant-detail'

#     def get_queryset(self):
#         restaurant = get_object_or_404(Restaurant, pk=pk)

#     def get_context_data(self, **kwargs):
#         context = super().get_context_data(**kwargs)
#         context['review'] = RestaurantReview(
#             rating=request.POST['rating'],
#             comment=request.POST['comment'],
#             user=request.user,
#             restaurant=restaurant)
#         return context

def review(request, pk):
    restaurant = get_object_or_404(Restaurant, pk=pk)
    review = RestaurantReview(
        rating=request.POST.get('rating', False),
        comment=request.POST.get('comment', False),
        user=request.user,
        restaurant=restaurant
        )
    review.save()
    return HttpResponseRedirect(reverse('restaurant-detail', args=(restaurant.id,)))


import time
import torch
import torch.nn as nn
from torch.utils.data.dataloader import DataLoader, Dataset
from torch.optim import Adam
from torch.optim import lr_scheduler
from .utils import EarlyStopping
from .loss import mae_loss

class Trainer:
    """
    Default training loss is MAE. If you want to change it, you need
    to change it in the trainer.
    """

    def __init__(
        self,
        model: nn.Module,
        use_amp: bool = False,
        features: str = "M",
        inverse: bool = False,
        num_workers: int = 0,
    ) -> None:
        """
        Args:
            model: the model to train
            use_amp: whether to use automatic mixed precision training
            features: the features to use, either M (multivariate predict multivariate),
                S (univariate predict univariate) or MS (multivariate predict univariate)
            inverse: whether to inverse the target sequence
            num_workers: number of workers for data loader
        """
        self.device = "cuda" if torch.cuda.is_available() else "cpu"
        self.model = model.to(self.device)
        self.use_amp = use_amp  # automatic mixed precision training

        self.ealry_stopping = EarlyStopping(patience=10, verbose=True)

        self.f_dim = -1 if features == "MS" else 0  # -1 for MS, 0 for M and S
        self.inverse = inverse
        self.num_workers = num_workers

    def train(
        self,
        train_dataset: Dataset,
        val_dataset: Dataset,
        batch_size: int,
        max_epochs: int,
        lr: float,
        pct_start: float = 0.3,
    ):
        # save meta data
        self.train_info = {
            "batch_size": batch_size,
            "max_epochs": max_epochs,
            "lr": lr,
            "pct_start": pct_start,
            "num_workers": self.num_workers,
            "use_amp": self.use_amp,
        }
        self.max_epochs = max_epochs

        # initialize data loader
        train_loader = DataLoader(
            train_dataset,
            batch_size=batch_size,
            shuffle=True,
            num_workers=self.num_workers,
        )
        val_loader = DataLoader(
            val_dataset,
            batch_size=batch_size,
            shuffle=False,
            num_workers=self.num_workers,
        )

        train_steps = len(train_loader)
        self.train_info.update({"train_steps": train_steps})

        # initialize optimizer
        self.optimizer = Adam(
            filter(lambda p: p.requires_grad, self.model.parameters()), lr=lr
        )

        # initialize lr scheduler
        self.scheduler = lr_scheduler.OneCycleLR(
            optimizer=self.optimizer,
            steps_per_epoch=train_steps,
            pct_start=pct_start,
            epochs=max_epochs,
            max_lr=lr,
        )

        scaler = torch.cuda.amp.GradScaler() if self.use_amp else None

        for epoch in range(max_epochs):
            start_time = time.time()
            train_loss = self._train_epoch(train_loader, scaler)
            val_loss = self._val_epoch(val_loader)

            self.ealry_stopping(val_loss, self.model, "checkpoint")

            if self.ealry_stopping.early_stop:
                print("Early stopping")
                break

            print(
                f"Epoch: {epoch+1}/{self.max_epochs} | Train loss: {train_loss} | Val loss: {val_loss} | Time: {time.time()-start_time: .3f}s"
            )

    def _train_epoch(self, train_loader, scaler=None):
        self.model.train()

        total_loss = 0
        for x, y in train_loader:
            x = x.to(self.device)
            y = y.to(self.device)

            self.optimizer.zero_grad()

            pred, y_true = self._run_on_batch(train_loader.dataset, x, y)

            loss = mae_loss(pred, y_true)

            if self.use_amp:
                scaler.scale(loss).backward()
                scaler.step(self.optimizer)
                scaler.update()
            else:
                loss.backward()
                self.optimizer.step()

            total_loss += loss.item()

        return total_loss / len(train_loader)

    def _val_epoch(self, val_loader):
        self.model.eval()

        total_loss = 0
        with torch.no_grad():
            for x, y in val_loader:
                x = x.to(self.device)
                y = y.to(self.device)

                pred, y_true = self._run_on_batch(val_loader.dataset, x, y)

                loss = mae_loss(pred, y_true)

                total_loss += loss.item()

        return total_loss / len(val_loader)

    def _run_on_batch(
        self,
        dataset_object: Dataset,
        x_batch: torch.Tensor,
        y_batch: torch.Tensor = None,
    ):
        if self.use_amp:
            with torch.cuda.amp.autocast():
                outputs = self.model(x_batch)
        else:
            outputs = self.model(x_batch)

        if self.inverse:
            outputs = dataset_object.inverse_transform(outputs)

        if y_batch is not None:
            y_batch = y_batch[:, self.f_dim :, :].to(self.device)  # B, N (target), Y

        outputs = outputs[:, self.f_dim :, :]  # B, N (target), Y

        return outputs, y_batch

    def test(self, test_dataset, batch_size):
        test_loader = DataLoader(
            test_dataset,
            batch_size=batch_size,
            shuffle=False,
            num_workers=self.num_workers,
        )

        self.model.load_state_dict(torch.load("checkpoint/checkpoint.pth"))

        self.model.eval()

        total_loss = 0
        with torch.no_grad():
            for x, y in test_loader:
                x = x.to(self.device)
                y = y.to(self.device)

                pred, y_true = self._run_on_batch(test_loader.dataset, x, y)

                loss = mae_loss(pred, y_true)

                total_loss += loss.item()

        return total_loss / len(test_loader)

    def predict(self, dataset, batch_size):
        loader = DataLoader(
            dataset,
            batch_size=batch_size,
            shuffle=False,
            num_workers=self.num_workers,
        )

        self.model.load_state_dict(torch.load("checkpoint/checkpoint.pth"))

        self.model.eval()

        with torch.no_grad():
            for x, y in loader:
                x = x.to(self.device)
                y = y.to(self.device)

                pred, y_true = self._run_on_batch(loader.dataset, x, y)

        return pred, y_true


# 3.创建Student类，继承Person类，属性有学院college，班级class，重写父类personInfo方法，调用父类方法打印个人信息外，
# 将学生的学院、班级信息也打印出来，创建方法study参数为Teacher对象，调用Teacher类的teachObj方法，
# 接收老师教授的知识点，然后打印‘老师xxx,我终于学会了！’xxx为老师的teach方法返回的信息。

class Person(object):
    def personInfo(self,name,age,sex):
        self.name=name
        self.age=age
        self.sex=sex
        return self.name,self.age,self.sex
class Teach(Person):
    def personInfo(self,name,age,sex,college,professional):
        self.name=name
        self.age=age
        self.sex=sex
        self.college=college
        self.professional=professional
        return self.name,self.age,self.sex,self.college,self.professional
class Student(Person):
    def personInfo(self,college,classroom):
        self.college=college
        self.classroom=classroom
        return self.college,self.classroom
    def study(self):
        return '老师xxx,我终于学会了！'
# a=Student
# print(a.personInfo('小鹿','19','女','信工学院','12'))
# print(a.study())


"""
Visualization using visdom.
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from itertools import *
from keras import backend

def preview_samples(images, labels, title):
    """
    Shows a few samples of the loader.
    """

    # We generate a plot
    (fig, ax) = plt.subplots(11, 11, figsize=(10, 10))
    plt.subplots_adjust(hspace=0.5)
    for i, (x,y) in enumerate(product(range(11), range(11))):
        current_axis = ax[x, y]
        current_axis.imshow(images[i].reshape(28, 28))
        current_axis.set_title(labels[i].item())
        current_axis.set_axis_off()
    fig.suptitle(title)
    plt.show()

def preview_kernels(kernels, title):
    """
    Shows a few kernels in 2d
    """

    # We reshape kernels
    (w, h, a, b) = kernels.shape

    # We generate a plot
    (fig, ax) = plt.subplots(a, b)
    for x, y in product(range(a), range(b)):
        if a == 1:
            current_axis = ax[y]
        else:
            current_axis = ax[x, y]
        current_axis.imshow(kernels[:,:,x,y])
        current_axis.set_axis_off()
    fig.suptitle(title)
    plt.show()

def plot_learning_curves(train_loss, test_loss, title):
    """
    Plot learning curves
    """
    fig, ax = plt.subplots()
    ax.plot(train_loss, color="blue", label="Train-set")
    ax.plot(test_loss, color="green", label="Test-set")
    ax.set_ylabel("Loss")
    ax.set_xlabel("Epochs")
    ax.set_title(title)
    ax.legend()
    plt.show()

def show_image(im, title):
    """
    This function shows an image.
    """
    plt.imshow(im)
    plt.colorbar()
    plt.title(title)
    plt.show()

def show_binary(orig, binarized, title):
    """
    This function shows the binarized version of the image
    """

    fig, ax = plt.subplots(2)
    ax[0].imshow(orig)
    ax[0].set_title("Original")
    ax[1].imshow(binarized)
    ax[1].set_title("Binary")
    fig.suptitle(title)
    plt.show()

def preview_activations(model, sample, title):
    """
    This function allows to preview the activations through the model.
    """

    activations = backend.function([model.layers[0].input],
                                   [model.layers[0].output,
                                    model.layers[1].output,
                                    model.layers[2].output,
                                    model.layers[3].output,
                                    model.layers[4].output,
                                    model.layers[5].output,
                                    model.layers[6].output,
                                    model.layers[7].output])
    output = activations(sample)

    fig = plt.figure()
    fig.suptitle(title)
    plt.subplots_adjust(hspace=0.5)
    gs = gridspec.GridSpec(8, 1)

    def add_volume_activation(n, title):
        act = output[n]
        w = act.shape[-1]
        g = gridspec.GridSpecFromSubplotSpec(1, w, subplot_spec=gs[n])
        for i in range(w):
            ax = fig.add_subplot(g[i])
            ax.imshow(act[0,:,:,i])
            ax.set_xticks([])
            ax.set_yticks([])
            if float(w)/float(i+1) == 2:
                ax.set_title(title)

    add_volume_activation(0, "First Convolutional layer output")
    add_volume_activation(1, "First MaxPooling layer output")
    add_volume_activation(2, "Second Convolutional layer output")
    add_volume_activation(3, "Second MaxPooling layer output")

    def add_flat_activation(n, title):
        act = output[n]
        w = act.shape[-1]
        g = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs[n])
        ax = fig.add_subplot(g[0])
        ax.imshow(act)
        ax.set_xticks([])
        ax.set_yticks([])
        ax.set_title(title)

    add_flat_activation(4, "Flatten layer output")
    add_flat_activation(5, "First Dense layer output")
    add_flat_activation(6, "Second Dense layer output")
    add_flat_activation(7, "Output layer output")

    plt.show()


import os
import pandas as pd
ENCODING= 'utf-8'
class QuickLoader_CVS:
    '''
    A Class helps you read csv backwards faster
    '''
    def __init__(self, filename):
        self.filename = filename
        self.current_position = None
        # 读取第一行作为表头
        self.file = open(self.filename, 'rb')
        self.header = self.file.readline().decode(ENCODING).strip().split(',')
        self.go_to_last_line()

    def file_exists_and_readable(self):
        if not os.path.exists(self.filename):
            print(f"File '{self.filename}' does not exist.")
            return False
        try:
            with open(self.filename, 'r', encoding=ENCODING) as f:
                pass
        except IOError:
            print(f"File '{self.filename}' is not readable.")
            return False

        return True

    def read_last_line(self):
        if not self.file_exists_and_readable() or self.current_position is None:
            return None
        if self.current_position == 0:
            return None
        with open(self.filename, 'r', encoding=ENCODING) as f:
            line = ''
            while self.current_position > 0:
                self.current_position -= 1
                f.seek(self.current_position, os.SEEK_SET)
                current_char = f.read(1)
                if current_char == '\n' and line:
                    break
                line = current_char + line

            return line.strip()

    def go_to_last_line(self):
        if not self.file_exists_and_readable():
            return
        with open(self.filename, 'r', encoding=ENCODING) as f:
            f.seek(0, os.SEEK_END)
            self.current_position = f.tell()

    def read_last_line_as_dataframe(self):
        if self.current_position == 0:
            return None
        line = self.read_last_line()
        if line==None or line == '':
            return self.read_last_line_as_dataframe()
        data = [cell.strip() for cell in line.split(',')]
        return pd.DataFrame([data], columns=self.header)

if __name__ == '__main__':

    # 创建一个CSVFile对象，传入CSV文件名
    csv_file = QuickLoader_CVS('Data\output.csv')

    # 读取最后一行
    last_line = csv_file.read_last_line_as_dataframe()
    print("Last line:", last_line['ID'])

    # 再次调用read_last_line以读取倒数第二行
    second_last_line = csv_file.read_last_line_as_dataframe()
    print("Second last line:", second_last_line)

    # 将指针重置回最后一行
    csv_file.go_to_last_line()


# -*- coding: utf-8 -*-

import json
from typing import List, Tuple

from django.http import HttpRequest, JsonResponse

from catmaid.apps import get_system_user
from catmaid.control.authentication import requires_user_role
from catmaid.control.common import get_class_to_id_map, get_relation_to_id_map
from catmaid.models import (Class, ClassInstance, Relation, SamplerDomainType,
        SamplerIntervalState, SamplerState, SamplerConnectorState, UserRole)

# All classes needed by the tracing system alongside their
# descriptions.
needed_classes = {
    'group': "A group",
    'annotation': "A generic semantic annotation",
    'label': "A label",
    'neuron': "A neuron representation",
    'root': "The root node for the tracing system",
    'skeleton': "The representation of a skeleton",
    'sampler-created': "Nodes that are created by the reconstruction sampler"
}

# All relations needed by the tracing system alongside their
# descriptions.
needed_relations = {
    'labeled_as': "Something is labeled by sth. else.",
    'element_of': "A generic element-of relationship",
    'presynaptic_to': "Something is presynaptic to something else.",
    'postsynaptic_to': "Something is postsynaptic to something else.",
    'abutting': "Two things abut against each other",
    'gapjunction_with': "Something has a gap junction with something else",
    'tightjunction_with': "A tight juction between two objects",
    'desmosome_with': "A desmosome between two objects",
    'attached_to': "Something is considered attached/linked to something else",
    'adjacent_to': { 'description': "Next to each other", 'isreciprocal': True },
    'mirror_of': { 'description': "A mirror configuration to each other", 'isreciprocal': True },
    'annotated_with': "Something is annotated with sth. else.",
}

# Expected sampler states, sampler interval sates and sampler domain types
needed_sampler_states = {
    'open':    'A sampler that hasn\'t been completed yet',
    'closed':  'A completed sampler'
}
needed_sampler_interval_states = {
    'untouched': 'A new interval, which has not been looked at',
    'started':   'The interval is being worked on',
    'completed': 'The interval has been completed',
    'abandoned': 'The interval has been abandoned and won\'t be completed'
}
needed_sampler_domain_types = {
    'regular':  'A general explicitly defined domain',
    'backbone': 'The backbone of a neuron',
    'bouton':   'A particular type of morphology',
    'covering': 'Complete neuron',
    'twig':     'A small distal fragment'
}
needed_sampler_connector_states = {
    'untouched': 'A new connector, which has not been sampled so far',
    'started':   'The connector can be sampled',
    'completed': 'The connector has been completed and shouldn\'t be used for sampling',
    'excluded':  'The connector is excluded from sampling'
}

# Tags that mark a true end
end_tags = frozenset(['uncertain continuation', 'not a branch', 'ends',
        'really ends', 'uncertain end', 'anterior end', 'posterior end',
        'soma', 'out to nerve'])

known_tags = end_tags.union(frozenset(['microtubules end', 'soma']))

def check_tracing_setup_view(request:HttpRequest, project_id=None) -> JsonResponse:
    all_good, mc, mr, mci = check_tracing_setup_detailed(project_id)
    initialize = (len(mc) == len(needed_classes)) and \
                 (len(mr) == len(needed_relations))
    can_administer = request.user.has_perm('can_administer', project_id)
    return JsonResponse({
        'needs_setup': not all_good,
        'missing_classes': mc,
        'missing_relations': mr,
        'missing_classinstances': mci,
        'has_needed_permissions': can_administer,
        'initialize': initialize
    })

def check_tracing_setup(project_id, opt_class_map=None, opt_relation_map=None,
        check_root_ci=True) -> bool:
    """ Checks if all classes and relations needed by the tracing system are
    available. Allows avoiding tests for root class instances and passing
    already available class and relation maps to saved queries.
    """
    all_good, _, _, _ = check_tracing_setup_detailed(project_id, opt_class_map,
            opt_relation_map, check_root_ci)
    return all_good

def check_tracing_setup_detailed(project_id, opt_class_map=None,
        opt_relation_map=None, check_root_ci=True) -> Tuple[bool, List, List, List]:
    """ Checks if all classes and relations needed by the tracing system are
    available. It returns a four-tuple with a boolean indicating if all is
    setup, the missing class names, the missing relation names and the missing
    class instance names. Allows avoidng tests for root class instances and
    passing already available class and relation maps.
    """
    # Get class and relation data. If available, use the provided one.
    class_map = opt_class_map or get_class_to_id_map(project_id)
    relation_map = opt_relation_map or get_relation_to_id_map(project_id)

    # Check if all classes and relations are available
    all_good = True
    missing_classes = []
    missing_relations = []
    missing_classinstances = []

    for c in needed_classes:
        if c not in class_map:
            all_good = False
            missing_classes.append(c)
    for r in needed_relations:
        if r not in relation_map:
            all_good = False
            missing_relations.append(r)
    # Check if the root node is there if requested
    if check_root_ci:
        if 'root' in class_map:
            exists = ClassInstance.objects.filter(
                class_column=class_map['root'],
                project_id=project_id).exists()
            if not exists:
                all_good = False
                missing_classinstances.append('root')
        else:
            missing_classinstances.append('root')

    return all_good, missing_classes, missing_relations, missing_classinstances

@requires_user_role([UserRole.Admin])
def rebuild_tracing_setup_view(request:HttpRequest, project_id=None) -> JsonResponse:
    setup_tracing(project_id, request.user)
    all_good = check_tracing_setup(project_id)
    return JsonResponse({'all_good': all_good})

@requires_user_role([UserRole.Browse])
def validate_tracing_setup(request:HttpRequest, project_id) -> JsonResponse:
    setup_tracing(project_id)
    return JsonResponse({'success': True})

def setup_tracing(project_id, user=None) -> None:
    """ Tests which of the needed classes and relations is missing
    from the project's semantic space and adds those.
    """
    if not user:
        user = get_system_user()
    # Remember available classes
    available_classes = {}

    # Add missing classes
    for c in needed_classes:
        class_object, _ = Class.objects.get_or_create(
            class_name=c,
            project_id=project_id,
            defaults={'user': user,
                      'description': needed_classes[c]})
        available_classes[c] = class_object
    # Add missing relations
    for r in needed_relations:
        defaults = {
            'user': user,
        }
        data_type = type(needed_relations[r])
        if data_type == str:
            defaults['description'] = needed_relations[r]
        else:
            defaults.update(needed_relations[r]) # type: ignore

        Relation.objects.get_or_create(
            relation_name=r,
            project_id=project_id,
            defaults=defaults)
    # Add missing sampler states
    for sn, sd in needed_sampler_states.items():
        SamplerState.objects.get_or_create(
            name=sn, defaults={'description': sd})
    # Add missing sampler interval states
    for sn, sd in needed_sampler_interval_states.items():
        SamplerIntervalState.objects.get_or_create(
            name=sn, defaults={'description': sd})
    # Add missing sampler domain types
    for sn, sd in needed_sampler_domain_types.items():
        SamplerDomainType.objects.get_or_create(
            name=sn, defaults={'description': sd})
    # Add missing sampler connector states
    for sn, sd in needed_sampler_connector_states.items():
        SamplerConnectorState.objects.get_or_create(
            name=sn, defaults={'description': sd})

    # Add root class instance
    ClassInstance.objects.get_or_create(
        class_column=available_classes['root'],
        project_id=project_id,
        defaults={'user': user,
                  'name': 'neuropile'})