'''
Question 2 Skeleton Code

Here you should implement and evaluate the Conditional Gaussian classifier.
'''

import data
import numpy as np
# Import pyplot - plt.imshow is useful!
import zipfile
import os
from scipy.special import logsumexp
import matplotlib.pyplot as plt

def compute_mean_mles(train_data, train_labels):
    '''
    Compute the mean estimate for each digit class

    Should return a numpy array of size (10,64)
    The ith row will correspond to the mean estimate for digit class i
    '''
    means = []
    for i in range(0, 10):
        values_i = data.get_digits_by_label(train_data, train_labels, i) #this is all training examples for digit i
        avg_list = np.mean(values_i, axis=0) #averages every row in each column, reminder that rows are examples and each column is a pixel
        means.append(avg_list)

    # Compute means
    return np.array(means)

def compute_sigma_mles(train_data, train_labels):
    '''
    Compute the covariance estimate for each digit class

    Should return a three dimensional numpy array of shape (10, 64, 64)
    consisting of a covariance matrix for each digit class
    '''
    #remember from the assignment instructions we should add 0.01*identity matrix to our answer to avoid numerical errors
    covariances = []
    averages = compute_mean_mles(train_data, train_labels)
    for i in range(0, 10):
        values_i = data.get_digits_by_label(train_data, train_labels, i)
        avg_i = averages[i]
        difference_from_mean = values_i - avg_i
        #the covariance matrix - calculated using the formula: 1/m sum(i=1..m) (xi-Mew)(xi-mew).T
        covariance = np.dot(difference_from_mean.transpose(), difference_from_mean) / values_i.shape[0]

        #add the stabalizing constant
        covariance = covariance + np.eye(values_i.shape[1]) * 0.01

        covariances.append(covariance)
    # Compute covariances
    return covariances

def generative_likelihood(digits, means, covariances):
    '''
    Compute the generative log-likelihood:
        log p(x|y,mu,Sigma)

    Should return an n x 10 numpy array
    '''
    #we need to compute this formula: log(p(x|y=k, mew, sigmak)) = log((2*pi)^(-d/2)|sigmak|^(-1/2) exp {-1/2(x-mewk).T sigmak^-1(x-mewk)})
    #will return the log-likelihood of each example being from each category

    likelihoods = []

    #multiplied terms can now be added once you take the log
    #log(2*pi^-d/2)) becomes (-d/2)*log(2*pi)

    first = (-means.shape[0]/2)*np.log(2*np.pi)
    for digit in digits:
        likelihoods_digit = []
        for i in range(0, 10):

            #next term is the determinent of sigma to the power of -1/2 which becomes: -1/2 log(det(sigma k))
            second = (-1/2)*np.log(np.linalg.det(covariances[i]))

            #last term becomes -1/2*(x-mewk).T * sigmak^-1(x-mewk)
            inv = np.linalg.inv(covariances[i])
            x_minus_mewk = digit - means[i]
            #print(inv.shape)
            #print(x_minus_mewk.shape)

            last = (-1/2) * np.matmul(np.transpose(x_minus_mewk),inv)
            last = np.matmul(last, x_minus_mewk)
            likelihoods_digit.append((first+second+last))
        likelihoods.append(likelihoods_digit)
    #print(np.array(likelihoods).shape)
    return np.array(likelihoods)

def conditional_likelihood(digits, means, covariances):
    '''
    Compute the conditional likelihood:

        log p(y|x, mu, Sigma)

    This should be a numpy array of shape (n, 10)
    Where n is the number of datapoints and 10 corresponds to each digit class
    '''
    # using bayes rule: p(y|x) = p(x|y)p(y) / P(x) and taking the log of this gives us: log(p(y|x) = log(p(x|y)) + log(p(y)) - log(p(x))
    #in generative_likelihoods we calculated log(p(x|y))

    log_prob_x_y = generative_likelihood(digits, means, covariances)

    log_prob_y = np.log(1/10)

    #p(x) = sum over all y p(x, y) = sum over all y (p(x|y)p(y))

    log_prob_x = logsumexp(log_prob_x_y + log_prob_y, axis=1).reshape(-1, 1)

    log_prob_y_x = log_prob_x_y + log_prob_y - log_prob_x

    return log_prob_y_x

def avg_conditional_likelihood(digits, labels, means, covariances):
    '''
    Compute the average conditional likelihood over the true class labels

        AVG( log p(y_i|x_i, mu, Sigma) )

    i.e. the average log likelihood that the model assigns to the correct class label
    '''
    cond_likelihood = conditional_likelihood(digits, means, covariances)

    #need to get the conditional likelihood for only the correct class labels
    #slice data where the label is equal to i
    sums = 0
    for i, likelihoods in enumerate(cond_likelihood):
        sums += likelihoods[int(labels[i])]
    avg = sums/cond_likelihood.shape[0]
    # Compute as described above and return
    return avg

def classify_data(digits, means, covariances):
    '''
    Classify new points by taking the most likely posterior class
    '''
    #look at the conditional likelihood and choose the column (out of 10) that has the highest value for each example (row)
    prob_y_given_x = conditional_likelihood(digits, means, covariances)
    # Compute and return the most likely class
    #pick the column with the highest likelihood

    most_likely = np.argmax(prob_y_given_x, axis=1)

    return most_likely

def questiona (train_data, train_labels, test_data, test_labels):

    #compute average conditional log likelihood on both the train and test set
    means = compute_mean_mles(train_data, train_labels)
    covariances = compute_sigma_mles(train_data, train_labels)

    train_avg_conditional_log_likelihood = avg_conditional_likelihood(train_data, train_labels, means, covariances)

    print("training avg log likelihood: " + str(train_avg_conditional_log_likelihood))

    test_avg_conditional_log_likelihood = avg_conditional_likelihood(test_data, test_labels, means, covariances)

    print("test avg log likelihood: " + str(test_avg_conditional_log_likelihood))

def questionb(train_data, train_labels, test_data, test_labels):
    # select the most likely posterior class for each training and test point as your prediction and report your accuracy on the training and test set
    # need to call classify data function and keep track of accuracy
    means = compute_mean_mles(train_data, train_labels)
    covariances = compute_sigma_mles(train_data, train_labels)

    #predict
    train_predictions = classify_data(train_data, means, covariances)
    #create a list of True or False if they were correct
    train_correct = [train_predictions == train_labels]
    #averaging 0s and 1s gives you the percentage of correctly classified data
    train_accuracy = np.mean(train_correct)
    print("train accuracy is: " + str(train_accuracy))

    test_predictions = classify_data(test_data, means, covariances)
    test_correct = [test_predictions == test_labels]
    test_accuracy = np.mean(test_correct)
    print("test accuracy is: " + str(test_accuracy))

def questionc(covariances):
    # Compute the leading eigenvectors (largest eigenvalue) for each class covariance matrix (can use np.linalg.eig) and plot them side by side as 8 by 8 images.

    each_digit = []
    #for each class, compute the eigenvalues and eigenvectors and then choose the eigenvector with the highest associated eigenvalue
    for i in range(0, 10):
        cov = covariances[i]
        vals, vecs = np.linalg.eig(cov)
        #get largest eigenvalue - this expression is from the np.linalg.eig documentation:
        leading_eigenvector = vecs[:, np.argmax(vals)]
        each_digit.append(leading_eigenvector.reshape(8, 8))

    #this only works when run on an interactive python terminal and it seems to be a common issue with plt.imshow
    plt.title("leading eignvectors")
    plt.imshow(np.concatenate(np.array(each_digit), axis = 1), cmap = 'gray')
    plt.show()

def main():
    train_data, train_labels, test_data, test_labels = data.load_all_data('hw4digits/')

    # Evaluation
    # Fit the model
    means = compute_mean_mles(train_data, train_labels)
    covariances = compute_sigma_mles(train_data, train_labels)

    #part a
    print("question 2)a)")
    questiona(train_data, train_labels,test_data,test_labels)

    #part b
    print("question 2)b)")
    questionb(train_data, train_labels, test_data, test_labels)

    #part c
    print("question 2)c)")
    questionc(covariances)

if __name__ == '__main__':
    main()


import time
import os
import pprint
from sys import exit
from math import ceil
from signal import signal, SIGINT
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options
from tqdm import tqdm
from dotenv import load_dotenv
from utils import is_subseq
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
import pandas as pd
from datetime import datetime

load_dotenv()

result = []
col_names = [
    "lieu",
    "duree",
    "tarif",
    "teletravail",
    "debut",
    "description",
    "date",
    "link",
]
my_df = pd.DataFrame(columns=col_names)
options = Options()
options.headless = True
driver = webdriver.Firefox(
    options=options, service=Service(GeckoDriverManager().install())
)

def handler(signal_received, frame):
    print("SIGINT or CTRL-C detected. Exiting gracefully")
    my_df.to_csv(
        "report_file" + str(datetime.now()) + ".csv", sep=";", encoding="utf-8"
    )
    driver.close()
    exit(0)

driver.get("https://www.freelance-info.fr/login-page.php")

username_elem = driver.find_element(by=By.ID, value="_username")
password_elem = driver.find_element(by=By.ID, value="_password")

username_elem.clear()
password_elem.clear()

username_elem.send_keys(os.getenv("USERNAME"))  # email freelance-info
password_elem.send_keys(os.getenv("PASSWORD"))  # mot de passe freelance-info
password_elem.send_keys(Keys.RETURN)

list_keywords = ["développeur", "python", "flask", "django", "backend", "test"]
mandatory_keywords = ["python", "django", "flask"]
param_keyword = ",".join(list_keywords)
current_page = 1
driver.get(
    "https://www.freelance-info.fr/missions?keywords=" + param_keyword + "&page=1"
)
nb_total_page = (
    max(
        [
            int(word)
            for word in driver.find_element(by=By.ID, value="mission2").text.split()
            if word.isdigit()
        ]
    )
    / 10
)
signal(SIGINT, handler)

for page in tqdm(range(1, ceil(nb_total_page))):
    print(page)
    driver.get(
        "https://www.freelance-info.fr/missions?keywords="
        + param_keyword
        + "&page="
        + str(page)
    )
    pagination_xpath = "/html/body/div[2]/main/div/div/div[1]/nav/ul"
    list_pagination = driver.find_element(
        by=By.XPATH, value=pagination_xpath
    ).find_elements(by=By.XPATH, value="./*")

    list_offers = driver.find_elements(by=By.ID, value="offre")
    link_list = [
        offer.find_element(
            by=By.CSS_SELECTOR, value=".rtitre.filter-link"
        ).get_attribute("href")
        for offer in list_offers
    ]
    for link in link_list:
        driver.get(link)
        abstract = driver.find_element(by=By.CSS_SELECTOR, value=".col-8.left")
        list_abstract_content_line = abstract.text.split("\n")
        list_abstract_content_split = [
            elem.split(":") for elem in list_abstract_content_line
        ]
        payload = {}
        payload["title"] = driver.find_element(
            by=By.CLASS_NAME, value="title-grand"
        ).text
        payload["lieu"] = list_abstract_content_split[0][1].strip()
        payload["duree"] = list_abstract_content_split[1][1].strip()
        payload["tarif"] = list_abstract_content_split[2][1].strip()
        payload["teletravail"] = list_abstract_content_split[3][1].strip()
        payload["debut"] = list_abstract_content_split[4][1].strip()
        payload["description"] = driver.find_element(
            by=By.ID, value="description-mission"
        ).text
        payload["link"] = link
        tmp_date = driver.find_element(by=By.ID, value="publié").text.split(" ")[2]
        payload["date"] = datetime.strptime(tmp_date, "%d/%m/%Y")
        tmp_df = pd.DataFrame(columns=col_names)
        # TODO on recupere toutes les donnees puis on filtre ensuite
        my_df.loc[len(my_df)] = payload

        # if is_subseq(mandatory_keywords, [payload["description"].lower()]):
        #     print(payload["title"], payload["link"])
        #     result.append(payload)

    current_page += 1

my_df.to_csv("report_file" + str(datetime.now()) + ".csv", sep=";", encoding="utf-8")
driver.close()
# with open(
#     "report_file.txt", "w", encoding="utf-8"
# ) as output_file:  # enregistrement des resultats
#     output_file.write(pprint.pformat(result, indent=4))


#Unir uno o mas interables

#print(dir(__builtins__))
#print(help(zip))
numeros=[1,2,3]
letras=['a','b','c']
identificadores= 321,322,323,324,325
mezcla=zip(numeros,letras,identificadores)
print(mezcla)
print(list(mezcla))
print(tuple(zip(numeros,letras)))

#Interar en paralelo
for numero, letras, identificadores in zip (numeros,letras,identificadores):
    print(f"Numero: {numeros}, letra: {letras}, identificadores: {identificadores}")

# nueva_lista=[]
# for numero, letras, identificadores in zip (numeros,letras,identificadores):
#     nueva_lista.append(f"{numero},{letras},{identificadores}")
# print(nueva_lista)

#Ordenamiento
letras = ['c','d','a','e','b']
numero =[3,2,4,1,0]
mezcla=zip(letras,numero)
print(tuple(mezcla))

print(sorted(zip(letras,numero)))

#Crear Diccionario con zip y dos iterables
llaves=['Nombres','Apellido','Edad']
valores=['Juan','Perez','18']
diccionario=dict(zip(llaves,valores))
print(diccionario)

#Actualizar un elemento
llave=['Edad']
nuevaEdad=[28]
diccionario.update(zip(llaves,nuevaEdad))
print(diccionario)


import random
from art import logo
import replit
print(logo)
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

def deal_card():
  """Deals new randomly chosen card"""
  new_card = random.choice(cards)
  return new_card

def calculate_score(cards_delt):
  """"Checks for blackjack, calculates score, converts ace to one if over 21"""
  if cards_delt == [10, 11] or cards_delt == [11, 10]:
    return 0
  if 11 in cards_delt and sum(cards_delt) > 21:
      cards_delt.remove(11)
      cards_delt.append(1)
  return sum(cards_delt)

def compare(user_score, computer_score):
  if user_score == computer_score:
    return "It's a draw"
  elif computer_score == 0:
    return "Computer has blackjack, You lose!"
  elif user_score == 0:
    return "BlackJack, You win!"
  elif user_score > 21:
    return f"Bust, you lose with a score of {user_score}"
  elif computer_score > 21:
    return f"Computer busts with a score of {computer_score}, You Win!"
  elif user_score < computer_score:
    return f"Computer has {computer_score}, you have {user_score}, computer wins"
  else:
    return f"You have {user_score}, computer has {computer_score}, YOU WIN"

continue_playing = True

while continue_playing:
  user_cards = []
  computer_cards = []
  for i in range(2):
      user_cards.append(deal_card())
      computer_cards.append(deal_card())
  user_score = calculate_score(user_cards)
  computer_score = calculate_score(computer_cards)
  print(f'You have {user_cards} with a total score of {user_score}')
  print(f'The computer has [{computer_cards[0]}]')

  while user_score <= 21 and user_score != 0:
    hit = input('Do you want another card? Y/N: ')
    if hit == "Y" or hit == "y":
      user_cards.append(deal_card())
      user_score = calculate_score(user_cards)
      print(f"You have {user_cards} with a total score of {user_score}")
    else:
      break

  while computer_score < 17 and user_score <= 21:
    computer_cards.append(deal_card())
    computer_score = calculate_score(computer_cards)
    print(f'Computer draws a card, computer has {computer_cards} totalling {computer_score}')

  print(compare(user_score, computer_score))

  fortsette = input('Do you want to play again? Y/N: ')
  if fortsette == "y" or fortsette == "Y":
    continue_playing = True
    replit.clear()
  else:
    print('Thank you for playing!')
    break


from unittest import TestCase
from app import app
from models import db, User

app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql:///blogly_test"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SQLALCHEMY_ECHO"] = True
app.config["TESTING"] = True
app.config["DEBUG_TB_HOSTS"] = ["dont-show-debug-toolbar"]

db.drop_all()
db.create_all()

base_url = "http://localhost"

class UserViewsTestCase(TestCase):
    """
        Tests for views for Users.
    """
    def setUp(self):
        """
            Adds test users to test db
        """
        num_of_users = 3
        first_names = ["Alan", "Joel", "Jane"]
        last_names = ["Alda", "Burton", "Smith"]
        image_urls = [
            "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9e/Alan_Alda_circa_1960s.JPG/800px-Alan_Alda_circa_1960s.JPG",
            "",
            ""
        ]
        users = []
        for i in range(num_of_users):
            user = User(
                first_name=first_names[i],
                last_name=last_names[i],
                image_url=image_urls[i]
            )
            users.append(user)

        User.query.delete()
        db.session.add_all(users)
        db.session.commit()

        self.users = users
        self.num_of_users = num_of_users
        self.first_names = first_names
        self.last_names = last_names
        self.image_urls = image_urls

    def tearDown(self):
        """
            Undoes any failed transactions
        """
        db.session.rollback()

    def test_go_to_users_page(self):
        """
            Tests go_to_users_page() redirects correctly
        """
        with app.test_client() as client:
            resp = client.get("/")

            self.assertEqual(resp.status_code, 302)
            self.assertEqual(resp.location, f"{base_url}/users")

    def test_show_user_list(self):
        """
            Tests show_user_list() renders users.html correctly with the users'
            names and correct links
        """
        with app.test_client() as client:
            resp = client.get("/users")
            html = resp.get_data(as_text=True)

            self.assertEqual(resp.status_code, 200)
            for user in self.users:
                self.assertIn(f"/users/{user.id}", html)
                self.assertIn(f"{user.first_name} {user.last_name}", html)

    def test_add_new_user(self):
        """
            Tests add_new_user() correctly adds user to db and redirects
        """
        with app.test_client() as client:
            first_name = "Sean"
            last_name = "Gibson"
            data = {
                "first-name": first_name,
                "last-name": last_name,
                "image-url": ""
            }
            resp = client.post("/users/new", data=data, follow_redirects=True)
            html = resp.get_data(as_text=True)

            self.assertEqual(resp.status_code, 200)
            self.assertIn(f"{first_name} {last_name}", html)

    def test_show_user_details(self):
        """
            Tests show_user_details(user_id) renders user info correctly
        """
        with app.test_client() as client:
            for i in range(self.num_of_users):
                test_user = User.query.filter_by(
                    first_name=self.first_names[i]
                ).one()
                user_id = test_user.id
                resp = client.get(f"/users/{user_id}")
                html = resp.get_data(as_text=True)

                self.assertEqual(resp.status_code, 200)
                self.assertIn( \
                    f"{self.first_names[i]} {self.last_names[i]}", \
                    html)
                if self.image_urls[i]:
                    self.assertIn(self.image_urls[i], html)
                else:
                    self.assertIn("/static/placeholder.jpg", html)

    def test_edit_user(self):
        """
            Tests edit_user(user_id) updates user info and redirects to user
            details page correctly
        """
        with app.test_client() as client:
            new_first_name = "Sean"
            new_last_name = "Gibson"
            new_image_url = ""
            data = {
                "first-name": new_first_name,
                "last-name": new_last_name,
                "image-url": new_image_url
            }
            test_user = User.query.filter_by(
                first_name=self.first_names[0]
            ).one()
            user_id = test_user.id
            resp = client.post(f"/users/{user_id}/edit", data=data, \
                follow_redirects=True)
            html = resp.get_data(as_text=True)

            self.assertEqual(resp.status_code, 200)
            self.assertIn(f"{new_first_name} {new_last_name}", html)


for a in range(100000):
    M = int(input())
    if M == 0:
        break
    n = M*2
    a = [False, False] + [True]*(n-1)
    primes = []
    for i in range(2, int(n**0.5)+1):
        if a[i]:
            primes.append(i)
            for j in range(2*i, n+1, i):
                a[j] = False
    num = []
    for k in range(M+1, n+1):
        if a[k]:
            num.append(k)
    if M != 0:
        print(len(num))

백준/Silver/4948. 베르트랑 공준/베르트랑 공준.py


def opencv_version_conf_impl(repository_ctx):
    version = str(repository_ctx.attr.version)
    flattened_version = "v" + version.replace(".", "_").replace("-", "_")

    repository_ctx.symlink(
        repository_ctx.path(Label("@wpi_bazel_deps//third_party/edu_wpi_first_thirdparty_opencv/" + flattened_version + ":BUILD.bazel")),
        "BUILD.bazel",
    )

    repository_ctx.symlink(
        repository_ctx.path(Label("@wpi_bazel_deps//third_party/edu_wpi_first_thirdparty_opencv/" + flattened_version + ":repo.bzl")),
        "repo.bzl",
    )

opencv_version_conf = repository_rule(
    implementation = opencv_version_conf_impl,
    configure = True,
    attrs = {
        "version": attr.string(mandatory = True),
    },
)

def load_opencv(version):
    opencv_version_conf(name = "local_opencv", version = version)


from django.contrib.auth.decorators import login_required, user_passes_test
from django.http import Http404
from django.shortcuts import render, get_object_or_404
from BTsuperintendent.user_access_test import grades_threshold_access, grades_threshold_status_access
from BTfaculty.models import BTGradesThreshold, BTMarks_Staging
from BThod.models import BTFaculty_user, BTCoordinator
from BTco_ordinator.models import BTFacultyAssignment, BTSubjects
from BTsuperintendent.models import BTGradePoints, BTHOD, BTCycleCoordinator
from BTfaculty.forms import GradeThresholdForm, GradeThresholdStatusForm
from ADUGDB.models import BTRegistrationStatus
from json import dumps
import statistics as stat
from import_export.formats.base_formats import XLSX
import pandas as pd

@login_required(login_url="/login/")
@user_passes_test(grades_threshold_access)
def grades_threshold(request):
    user = request.user
    groups = user.groups.all().values_list('name', flat=True)
    faculty = BTFaculty_user.objects.filter(User=user, RevokeDate__isnull=True).first()
    subjects = BTFacultyAssignment.objects.filter(RegEventId__Status=1, RegEventId__GradeStatus=1, Coordinator=faculty.Faculty).distinct('Subject','RegEventId_id')
    if not subjects:
        raise Http404('You are not allowed to add threshold marks')
    return render(request, 'BTfaculty/GradesThreshold.html', {'subjects': subjects})

@login_required(login_url="/login/")
@user_passes_test(grades_threshold_access)
def grades_threshold_assign(request, pk):
    subject_faculty = get_object_or_404(BTFacultyAssignment, id=pk)
    subject = subject_faculty.Subject
    grades = BTGradePoints.objects.filter(Regulation=subject.RegEventId.Regulation).exclude(Grade__in=['I', 'X', 'R','W'])
    prev_thresholds = BTGradesThreshold.objects.filter(Subject=subject, RegEventId=subject_faculty.RegEventId)
    marks = BTMarks_Staging.objects.filter(Registration__RegEventId=subject_faculty.RegEventId.id, Registration__sub_id=subject.id)
    marks_list = marks.values_list('TotalMarks', flat=True)
    mean = round(stat.mean(marks_list), 2)
    stdev = round(stat.stdev(marks_list), 2)
    maximum = max(marks_list)
    if request.method == 'POST':
        form = GradeThresholdForm(subject_faculty, request.POST)
        if request.POST.get('submit-form'):
            if form.is_valid():
                if prev_thresholds:
                    # if (form.cleaned_data.get('uniform_grading')=='1' and prev_thresholds.first().uniform_grading) or \
                    #     (form.cleaned_data.get('uniform_grading')=='0' and not prev_thresholds.first().uniform_grading):
                    #     if form.cleaned_data.get('uniform_grading')=='1':
                    for grade in grades:
                        if form.cleaned_data[str(grade.id)]:
                            prev_thresholds.filter(Grade=grade, Exam_Mode=False).update(Threshold_Mark=float(form.cleaned_data[str(grade.id)]))

                    exam_mode_grade = grades.filter(Grade__in=['P','F'])
                    for grade in exam_mode_grade:
                        if form.cleaned_data[str('exam_mode_')+str(grade.id)]:
                            prev_thresholds.filter(Grade=grade, Exam_Mode=True).update(Threshold_Mark=float(form.cleaned_data[str('exam_mode_')+str(grade.id)]))
                        # else:
                        #     section = form.cleaned_data.get('section')
                        #     for grade in grades:
                        #         if form.cleaned_data[section+str(grade.id)]:
                        #             prev_thresholds.filter(Grade=grade, Section=section).update(Threshold_Mark=int(form.cleaned_data[section+str(grade.id)]))
                    # else:
                    #     prev_thresholds.delete()
                    #     if form.cleaned_data.get('uniform_grading')=='1':
                    #         for grade in grades:
                    #             if form.cleaned_data[str(grade.id)]:
                    #                 threshold_mark = GradesThreshold(Grade=grade, Subject=subject, RegEventId=subject_faculty.RegEventId, \
                    #                     uniform_grading=True, Threshold_Mark=int(form.cleaned_data[str(grade.id)]))
                    #                 threshold_mark.save()
                    #     else:
                    #         section = form.cleaned_data.get('section')
                    #         for grade in grades:
                    #             if form.cleaned_data[section+str(grade.id)]:
                    #                 threshold_mark = GradesThreshold(Grade=grade, Subject=subject, RegEventId=subject_faculty.RegEventId, \
                    #                     uniform_grading=False, Section=section, \
                    #                         Threshold_Mark=int(form.cleaned_data[section+str(grade.id)]))
                    #                 threshold_mark.save()
                else:
                    # if form.cleaned_data.get('uniform_grading')=='1':
                    for grade in grades:
                        if form.cleaned_data[str(grade.id)]:
                            threshold_mark = BTGradesThreshold(Grade=grade, Subject=subject, RegEventId=subject_faculty.RegEventId, \
                                Threshold_Mark=float(form.cleaned_data[str(grade.id)]), Exam_Mode=False)
                            threshold_mark.save()
                    exam_mode_grade = grades.filter(Grade__in=['P','F'])
                    for grade in exam_mode_grade:
                        if form.cleaned_data[str('exam_mode_')+str(grade.id)]:
                            threshold_mark = BTGradesThreshold(Grade=grade, Subject=subject, RegEventId=subject_faculty.RegEventId, \
                                    Threshold_Mark=float(form.cleaned_data[str('exam_mode_')+str(grade.id)]), Exam_Mode=True)
                            threshold_mark.save()

                    # else:
                    #     section = form.cleaned_data.get('section')
                    #     for grade in grades:
                    #         if form.cleaned_data[section+str(grade.id)]:
                    #             threshold_mark = GradesThreshold(Grade=grade, Subject=subject, RegEventId=subject_faculty.RegEventId, \
                    #                 uniform_grading=False, Section=section, \
                    #                     Threshold_Mark=int(form.cleaned_data[section+str(grade.id)]))
                    #             threshold_mark.save()
                msg = 'Grades Threshold noted successfully'
                return render(request, 'BTfaculty/GradesThresholdAssign.html', {'subject':subject_faculty, 'msg':msg})
        else:
            grades_data = [grade.Grade for grade in grades]
            no_of_students = {grade.Grade:0 for grade in grades}
            for index, grade in enumerate(grades):
                if request.POST.get(str(grade.id)):
                    no_of_students[grades_data[index]] = len(list(mark for mark in marks_list if mark>=float(request.POST.get(str(grade.id)))))
            for index in range(len(grades)-1, 0, -1):
                no_of_students[grades_data[index]] = no_of_students[grades_data[index]] - no_of_students[grades_data[index-1]]
            no_of_students = dumps(no_of_students)
            return render(request, 'BTfaculty/GradesThresholdAssign.html', {'subject':subject_faculty, 'form':form, 'students':no_of_students, 'mean':mean, 'stdev':stdev, 'max':maximum})

    else:
        form = GradeThresholdForm(subject_faculty)
        no_of_students = None
        if prev_thresholds:
            grades_data = [grade.Grade for grade in grades]
            no_of_students = {grade.Grade:0 for grade in grades}
            for index, grade in enumerate(grades):
                if prev_thresholds.filter(Grade=grade.id):
                    threshold_mark = prev_thresholds.filter(Grade=grade.id).first().Threshold_Mark
                    no_of_students[grades_data[index]] = len(list(mark for mark in marks_list if mark>=threshold_mark))
            total = 0
            for index in range(len(grades)-1, 0, -1):
                no_of_students[grades_data[index]] = no_of_students[grades_data[index]] - no_of_students[grades_data[index-1]]
                total += no_of_students[grades_data[index]]
            no_of_students = dumps(no_of_students)
    return render(request, 'BTfaculty/GradesThresholdAssign.html', {'subject':subject_faculty, 'form':form,  'students':no_of_students, 'mean':mean, 'stdev':stdev, 'max':maximum})

@login_required(login_url="/login/")
@user_passes_test(grades_threshold_status_access)
def grades_threshold_status(request):
    user = request.user
    groups = user.groups.all().values_list('name', flat=True)
    subjects = None
    if 'Faculty' in groups:
        faculty = BTFaculty_user.objects.filter(User=user, RevokeDate__isnull=True).first()
        subjects = BTFacultyAssignment.objects.filter(Faculty=faculty.Faculty, RegEventId__Status=1).distinct('Subject','RegEventId_id')
    elif 'Superintendent' in groups or 'Associate-Dean' in groups:
        subjects = BTFacultyAssignment.objects.filter(RegEventId__Status=1).distinct('Subject','RegEventId_id')
    elif 'Co-ordinator' in groups:
        co_ordinator = BTCoordinator.objects.filter(User=user, RevokeDate__isnull=True).first()
        subjects = BTFacultyAssignment.objects.filter(Faculty__Dept=co_ordinator.Dept, RegEventId__Status=1).distinct('Subject','RegEventId_id')
    elif 'HOD' in groups:
        hod = BTHOD.objects.filter(User=user, RevokeDate__isnull=True).first()
        subjects = BTFacultyAssignment.objects.filter(Faculty__Dept=hod.Dept, RegEventId__Status=1).distinct('Subject','RegEventId_id')
    elif 'Cycle-Co-ordinator' in groups:
        cycle_cord = BTCycleCoordinator.objects.filter(User=user, RevokeDate__isnull=True).first()
        subjects = BTFacultyAssignment.objects.filter(RegEventId__Dept=cycle_cord.Cycle, RegEventId__BYear=1, RegEventId__Status=1).distinct('Subject','RegEventId_id')
    else:
        raise Http404('You are not allowed to view threshold marks')
    if request.method == 'POST':
        form = GradeThresholdStatusForm(subjects, request.POST)
        if form.is_valid():
            subject = request.POST['subject'].split(':')[0]
            regEvent = request.POST['subject'].split(':')[1]
            thresholds = BTGradesThreshold.objects.filter(Subject_id=subject, RegEventId_id=regEvent)
            return render(request, 'BTfaculty/GradesThresholdStatus.html', {'form':form, 'thresholds':thresholds})
    else:
        form = GradeThresholdStatusForm(subjects=subjects)
    return render(request, 'BTfaculty/GradesThresholdStatus.html', {'form':form})

def add_grades_threshold(file):
    file = pd.read_excel(file)
    error_rows=[]
    for rIndex, row in file.iterrows():
        print(row)
        fac_assign_objs = BTFacultyAssignment.objects.filter(RegEventId__Status=1, RegEventId__GradeStatus=1, RegEventId__AYear=row[0], RegEventId__ASem=row[1], RegEventId__BYear=row[2], RegEventId__BSem=row[3], \
            RegEventId__Dept=row[4], RegEventId__Regulation=row[5], RegEventId__Mode=row[6], Subject__SubCode=row[7])
        for fac_assign_obj in fac_assign_objs:
            study_grades = BTGradePoints.objects.filter(Regulation=fac_assign_obj.Subject.RegEventId.Regulation).exclude(Grade__in=['I', 'X', 'R','W'])
            index = 8
            for grade in study_grades:
                if row[index] >= 0:
                    if not BTGradesThreshold.objects.filter(Subject=fac_assign_obj.Subject, RegEventId=fac_assign_obj.RegEventId, Grade=grade, Exam_Mode=False).exists():
                        grades_threshold_row = BTGradesThreshold(Subject=fac_assign_obj.Subject, RegEventId=fac_assign_obj.RegEventId, Grade=grade, Threshold_Mark=row[index], Exam_Mode=False)
                        grades_threshold_row.save()
                    else:
                        BTGradesThreshold.objects.filter(Subject=fac_assign_obj.Subject, RegEventId=fac_assign_obj.RegEventId, Grade=grade, Exam_Mode=False).update(Threshold_Mark=row[index])
                else:
                    error_rows.append(row)
                index += 1

            exam_grades = BTGradePoints.objects.filter(Regulation=fac_assign_obj.Subject.RegEventId.Regulation, Grade__in=['P','F'])
            if fac_assign_obj.Subject.RegEventId.Regulation == 1:
                p_threshold = 15
                f_threshold = 0
            else:
                p_threshold = 17.5
                f_threshold = 0
            if not BTGradesThreshold.objects.filter(Subject=fac_assign_obj.Subject, RegEventId=fac_assign_obj.RegEventId, Grade=exam_grades.filter(Grade='P').first(), Exam_Mode=True).exists():
                grades_threshold_row = BTGradesThreshold(Subject=fac_assign_obj.Subject, RegEventId=fac_assign_obj.RegEventId, Grade=exam_grades.filter(Grade='P').first(), Threshold_Mark=p_threshold, Exam_Mode=True)
                grades_threshold_row.save()
            if not BTGradesThreshold.objects.filter(Subject=fac_assign_obj.Subject, RegEventId=fac_assign_obj.RegEventId, Grade=exam_grades.filter(Grade='F').first(), Exam_Mode=True).exists():
                grades_threshold_row = BTGradesThreshold(Subject=fac_assign_obj.Subject, RegEventId=fac_assign_obj.RegEventId, Grade=exam_grades.filter(Grade='F').first(), Threshold_Mark=f_threshold, Exam_Mode=True)
                grades_threshold_row.save()
    print("Errors")
    print(error_rows)
    return "Completed!!"


from copy import copy
from typing import Iterable, Union, Any
import pygame
import random
import os
from enum import Enum
from pygame.sprite import AbstractGroup

# Configuración
scrip_dir = os.path.dirname(__file__)
pygame.init()
fps = 60
clock = pygame.time.Clock()

ANCHO, ALTURA = (480, 320)
pantalla = pygame.display.set_mode((ANCHO, ALTURA))
objects = pygame.sprite.Group()
misiles = pygame.sprite.Group()

class EVENTOS(Enum):
    SPAWN_PIPE = pygame.USEREVENT + 1

class Misil(pygame.sprite.Sprite):
    def __init__(self, *groups) -> None:
        super().__init__(*groups)
        self.image = pygame.Surface((32, 16))
        self.image.fill((255, 215, 0))
        self.rect = self.image.get_rect()

    def update(self, dt):
        self.rect.x += 20 * dt
        if self.rect.x > ANCHO:
            self.kill()

class Ammo(pygame.sprite.Sprite):

    def __init__(self, *groups) -> None:
        super().__init__(*groups)
        self.image = pygame.image.load(
            os.path.join(scrip_dir, "sprites\\ammo.png")
        ).convert_alpha()
        self.rect = self.image.get_rect()

    def update(self, dt):
        self.rect.x -= 10 * dt
        if self.rect.x + self.rect.width < 0:
            self.kill()

class Area(pygame.sprite.Sprite):
    def __init__(self, rect, sprite_url, *groups) -> None:
        super().__init__(*groups)
        self.rect = rect
        self.image = pygame.image.load(os.path.join(scrip_dir, f"sprites\{sprite_url}"))
        self.image = pygame.transform.scale(self.image, (rect.width, rect.height))

    def update(self, dt):
        self.rect.x -= 10 * dt
        if self.rect.x + self.rect.width < 0:
            self.kill()

class Jugador(pygame.sprite.Sprite):
    def __init__(self, *groups) -> None:
        super().__init__(*groups)
        self.image = pygame.image.load(
            os.path.join(scrip_dir, "sprites\\flappy_bird.png")
        )
        self.rect = self.image.get_rect()
        self.rect.x = 30
        self.rect.y = ALTURA - 32
        self.salto = -20
        self.velocidad_y = 0
        self.ammo = 100

    def input(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_SPACE]:
            self.velocidad_y = self.salto

    def shoot(self):
        if self.ammo > 0 and self.ammo != 0:
            self.ammo -= 2
            print(self.ammo)
            return self.rect.centerx, self.rect.centery
        return None, None

    def update(self, dt):
        self.input()
        self.velocidad_y += 4.5 * dt
        self.rect.y += self.velocidad_y * dt
        if self.rect.y + 32 >= ALTURA:
            self.rect.y = ALTURA - 32
            self.velocidad_y = 0
        if self.rect.y < 0:
            self.rect.y = 1

class Pipe(pygame.sprite.Group):
    def __init__(self, *sprites: Any | AbstractGroup | Iterable) -> None:
        super().__init__(*sprites)
        self.areas = self.genAreas(4)
        self.add(self.areas)

    def genAreas(self, numAreas):
        hueco = random.randint(0, numAreas - 1)
        ancho, alto = 50, ALTURA // numAreas
        areas = []
        for index in range(numAreas):
            if hueco == index:
                ammo = Ammo(objects)
                ammo.rect.centerx = ANCHO + 50 + ancho // 2
                ammo.rect.centery = index * alto + alto // 2
                continue
            rect = pygame.Rect(0, index * alto, ancho, alto)
            rect.x = ANCHO + 50
            area = Area(rect, self.chooseSprite(index, hueco), self)
            areas.append(area)
        return areas

    def chooseSprite(self, index, hueco):
        if index == hueco - 1:
            return "flappy_todown.png"
        elif index == hueco + 1:
            return "flappy_totop.png"
        return "flappy_pipe.png"

    def canBeRemoved(self):
        if all(area.rect.right <= 0 for area in self.areas):
            return True
        return False

# delta time
current_time = pygame.time.get_ticks()
previous_time = current_time
pipes_group = pygame.sprite.Group()
pipes = []
jugador = pygame.sprite.GroupSingle(Jugador())
pygame.time.set_timer(EVENTOS.SPAWN_PIPE.value, 3000)

while True:
    pantalla.fill((0, 255, 255))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            break
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_e:
                x, y = jugador.sprites()[0].shoot()
                if all([x, y]):
                    misil = Misil(misiles)
                    misil.rect.centerx = x
                    misil.rect.centery = y
        elif event.type == EVENTOS.SPAWN_PIPE.value:
            pipe = Pipe()
            pipes.append(pipe)
            pipes_group.add(pipe)
    # update
    deltatime = (current_time - previous_time) / 1000.0  # Tiempo en segundos
    previous_time = deltatime
    jugador.update(deltatime)
    pipes_group.update(deltatime)
    objects.update(deltatime)
    misiles.update(deltatime)

    if pygame.sprite.spritecollide(jugador.sprite, pipes_group, False):
        pipes_group.empty()
        pipes.clear()

    if pygame.sprite.groupcollide(misiles, pipes_group, True, True):
        pass

    if pygame.sprite.spritecollide(jugador.sprite, objects, True):
         jugador.sprites()[0].ammo += 1

    for pipe in pipes:
        if pipe.canBeRemoved():
            pipes.remove(pipe)
            pipes_group.remove(pipe)
    # Draw
    jugador.draw(pantalla)
    objects.draw(pantalla)
    pipes_group.draw(pantalla)
    misiles.draw(pantalla)
    # Final
    pygame.display.flip()
    clock.tick(fps)


# Meta / Title
# Set the browser window title for a page. #meta
# ---
from h2o_wave import site, ui

page = site['/demo']

page['meta'] = ui.meta_card(box='', title='And now for something completely different!')

page['example'] = ui.markdown_card(
    box='1 1 2 2',
    title='',
    content='Open this page in a new window to view its title.',
)

page.save()


from typing import List

# Given an array the algorithm to find the maximum sub-array sum, is called: Kadane's algorithm

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        best_sum = current_sum = float('-inf')
        current_sum = best_sum

        for num in nums:
            current_sum = max(current_sum + num, num)
            best_sum = max(current_sum, best_sum)
        return best_sum

solution = Solution()
input_values = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
ans = solution.maxSubArray(input_values)
print(ans)


# Why we chose adaboost
# It helps reduce bias
# Since Naive Bayes is considered to be high bias/low variance

import random

import time
current_milli_time = lambda: int(round(time.time() * 1000))

import math
from naivebayes import NaiveBayes

class AdaBoost(object):

  def __init__(self, laplace=1):
    self.model = NaiveBayes

  def train_set(self, dataset, M=20):
    M = 20
    N = len(dataset)
    ws = [1.0/N for i in dataset]
    models = [self.model() for i in range(M)]
    errs = [1.0 for i in range(M)]
    alphas = [1.0 for i in range(M)]
    part = 0.8

    for m in range(M):
      print("m is", m)
      sub_sample_size = int(part * N)
      sub_sample = random.choices(dataset, ws, k=sub_sample_size)

      for n in range(len(sub_sample)):
        example = sub_sample[n]
        # print("n is")
        # print(ws[n])
        # models[m].train(*example, float(ws[n]))
        models[m].train(*example, 1.0)

      print("predicting %s examples" % N)
      incorrects = [1 if models[m].predict(*dataset[n][1:]) != dataset[n][0] else 0 for n in range(N)]
      print("incorrects: %s" % sum(incorrects))
      numerator = sum([ws[n] * incorrects[n] for n in range(N)])
      denominator = float(sum(ws))

      errs[m] = numerator / denominator

      alphas[m] = math.log( (1 - errs[m]) / errs[m])

      ws = [ws[n] * math.exp( alphas[m] * incorrects[n]) for n in range(N)]

    self.models = models
    self.alphas = alphas

  def predict(self, features):
    weights = {}
    M = len(self.models)
    for m in range(M):
      prediction = self.models[m].predict(features)

      if prediction not in weights:
        weights[prediction] = 0.0

      weights[prediction] += self.alphas[m]

    max_prediction = (None, 0)
    for k,v in weights.items():
      if v > max_prediction[1]:
        max_prediction = (k,v)

    return max_prediction[0]


__all__ = ["CONFIG_SCHEMA"]

import yaml

# Configuration for SimpleCsc
CONFIG_SCHEMA = yaml.safe_load(
    """
$schema: http://json-schema.org/draft-07/schema#
$id: https://github.com/lsst-ts/ts_hexrotcomm/blob/main/python/lsst/ts/hexrotcomm/config_schema.py
title: MTRotator v2
description: Configuration for SimpleCsc, which has no configuration.
type: object
properties:
  host:
    description: >-
      IP address of the TCP/IP interface.
      Ignored for SimpleCsc, because it always runs in simulation mode.
    type: string
    format: hostname
  port:
    description: >-
      Port number of the TCP/IP interface.
      Ignored for SimpleCsc, because it always runs in simulation mode.
    type: integer
  connection_timeout:
    description: Time limit for connecting to the TCP/IP interface (sec)
    type: number
    exclusiveMinimum: 0
required: [host, port, connection_timeout]
additionalProperties: false
"""
)


import time
import threading
CONTINUM = 1
RESOLUTION = 200

#该类播放固定一个任务的动画
class animation(object):

    """
    Implement the animation effect.
    :param Qwin: The Qwindow object of broadcasting animation.
    :param actor: The VTK actor object of QWindow.
    :param label: The target state space label.
    :type Qwin: QWindow
    :type actor: vtkActor
    :type label: ndarray 6X1
    """
    def __init__(self,Qwin):
        self.Qwin = Qwin
        self.broadcast = False#停止播放信号
    #持续时间（秒数）
    def setContinum(self,continum):
        self.continum = continum
        return
    #res为一秒的分割数，表示分辨率
    def setResolution(self,resolution):
        self.resolution = resolution
        return
    def getStep(self):
        return self.continum * self.resolution
    def setLabel(self,label):
        self.label = label
    def getLabel(self):
        return self.label
    def runAnimation(self):
        step = self.getStep()
        label = self.getLabel()
        actor = self.Qwin.actors[0]
        def _run(Qwin,actor,label,step):
            #label为目标状态空间的标签值，SetPosition需要有基坐标的运算
            #根据i返回该维度下切分步数下的幅度
            lstep = lambda i : label[i]/step
            while(True):
                i = 1
                while(i<=step):
                    actor.SetPosition(lstep(0)*i,\
                                                lstep(1)*i,\
                                                lstep(2)*i)
                    actor.RotateX(lstep(3))
                    actor.RotateY(lstep(4))
                    actor.RotateZ(lstep(5))
                    Qwin.VisualTarget.update()
                    i += 1
                    time.sleep(1/RESOLUTION)
                time.sleep(0.25)
                actor.SetPosition(0,0,0)
                actor.RotateX(-label[3])
                actor.RotateY(-label[4])
                actor.RotateZ(-label[5])
                time.sleep(0.25)
        thread = threading.Thread(target=_run,kwargs={\
                "Qwin":self.Qwin,"actor":actor,\
                "label":label,"step":step})
        thread.start()
        self.thread = thread
        return
    def endAnimation(self):
        self.thread.join()
        return


import pytest
import numpy as np

import time_evolving_mpo as tempo

# -----------------------------------------------------------------------------
# -- Test C: Spin-1 boson model -------------------------------------------------

# Initial state:
initial_state_C = np.array([[0.0,0.0,0.0],
                            [0.0,1.0,0.0],
                            [0.0,0.0,0.0]])

# System operator
h_sys_C = np.array([[1.0,0.0,0.0],
                    [0.0,0.5,0.0],
                    [0.0,0.0,0.0]])
h_sys_C += np.array([[0.0,0.5,0.0],
                     [0.5,0.0,0.5],
                     [0.0,0.5,0.0]])

# Markovian dissipation
gamma_C_1 = 0.1
gamma_C_2 = 0.2
lindblad_operators_C_1 = np.array([[0.0, 0.0, 0.0],
                                   [0.0, 0.0, 0.0],
                                   [0.0, 1.0, 0.0]])
lindblad_operators_C_2 = np.array([[0.5, 0.0, 0.0],
                                   [0.0,-0.5, 0.0],
                                   [0.0, 0.0, 0.0]])

# Ohmic spectral density with exponential cutoff
coupling_operator_C = np.array([[0.5, 0.0, 0.0],
                                [0.0,-0.5, 0.0],
                                [0.0, 0.0, 0.0]])
alpha_C = 0.3
cutoff_C = 5.0
temperature_C = 0.0

# end time
t_end_C = 1.0

# result obtained with release code (made hermitian, dkmax=10):
rho_C = np.array(
    [[ 0.12576653+0.j        ,-0.11739956-0.14312036j, 0.12211454-0.05963583j],
     [-0.11739956+0.14312036j, 0.61315893+0.j        ,-0.06636825+0.26917271j],
     [ 0.12211454+0.05963583j,-0.06636825-0.26917271j, 0.26107455+0.j        ]])

correlations_C = tempo.PowerLawSD(alpha=alpha_C,
                                  zeta=1.0,
                                  cutoff=cutoff_C,
                                  cutoff_type="exponential",
                                  temperature=temperature_C,
                                  name="ohmic",
                                  max_correlation_time=0.55)
bath_C = tempo.Bath(coupling_operator_C,
                    correlations_C,
                    name="phonon bath")
system_C = tempo.System(h_sys_C,
                        gammas=[gamma_C_1, gamma_C_2],
                        lindblad_operators=[lindblad_operators_C_1,
                                            lindblad_operators_C_2])

# -----------------------------------------------------------------------------

@pytest.mark.parametrize('backend',["tensor-network"])
def test_tensor_network_tempo_backend_C(backend):
    tempo_params_C = tempo.TempoParameters(dt=0.05,
                                           dkmax=10,
                                           epsrel=10**(-7))
    tempo_C = tempo.Tempo(system_C,
                          bath_C,
                          tempo_params_C,
                          initial_state_C,
                          start_time=0.0,
                          backend=backend)
    tempo_C.compute(end_time=1.0)
    dyn_C = tempo_C.get_dynamics()
    assert dyn_C.times[-1] == 1.0
    np.testing.assert_almost_equal(dyn_C.states[-1], rho_C, decimal=4)

@pytest.mark.parametrize('backend',["tensor-network"])
def test_tensor_network_pt_tempo_backend_C(backend):
    tempo_params_C = tempo.PtTempoParameters(dt=0.05,
                                             dkmax=10,
                                             epsrel=10**(-7))
    pt = tempo.pt_tempo_compute(
                bath_C,
                start_time=0.0,
                end_time=1.0,
                parameters=tempo_params_C,
                backend=backend)
    state = pt.compute_final_state_from_system(system=system_C,
                                               initial_state=initial_state_C)
    np.testing.assert_almost_equal(state, rho_C, decimal=4)

    dyn = pt.compute_dynamics_from_system(system=system_C,
                                          initial_state=initial_state_C)
    assert dyn.times[-1] == 1.0
    np.testing.assert_almost_equal(dyn.states[-1], rho_C, decimal=4)

# -----------------------------------------------------------------------------


import typing_extensions

from api.paths import PathValues
from api.apis.paths.daily_ import Daily
from api.apis.paths.leaderboard_seed import LeaderboardSeed
from api.apis.paths.tombstone_seed import TombstoneSeed

PathToApi = typing_extensions.TypedDict(
    'PathToApi',
    {
        PathValues.DAILY_: Daily,
        PathValues.LEADERBOARD_SEED: LeaderboardSeed,
        PathValues.TOMBSTONE_SEED: TombstoneSeed,
    }
)

path_to_api = PathToApi(
    {
        PathValues.DAILY_: Daily,
        PathValues.LEADERBOARD_SEED: LeaderboardSeed,
        PathValues.TOMBSTONE_SEED: TombstoneSeed,
    }
)


"""
TESTCASE:
Run your program with python plates.py. Type CS50 and press Enter. Your program should output:
Valid
Run your program with python plates.py. Type CS05 and press Enter. Your program should output:
Invalid
Run your program with python plates.py. Type CS50P and press Enter. Your program should output
Invalid
Run your program with python plates.py. Type PI3.14 and press Enter. Your program should output
Invalid
Run your program with python plates.py. Type H and press Enter. Your program should output
Invalid
Run your program with python plates.py. Type OUTATIME and press Enter. Your program should output
Invalid
"""
def main():
    plate = input("Plate: ")
    if is_valid(plate):
        print("Valid")
    else:
        print("Invalid")

def is_valid(s):
    if 2 <= len(s) <= 6 and s.isalnum():
        # Return true if characters are all letters
        if s.isalpha():
            return True
        else:
            # Check for number in the middle
            # (only if the first two characters are letters and the last character is number)
            if s[:2].isalpha() and s[-2:].isdigit():
                for i in range(len(s)):
                    if s[i].isdigit():
                        # Return false if number starts with 0 or the following character is letter
                        if s[i].startswith("0") or s[i:].isalpha():
                            return False
                        else:
                            return True
            else:
                return False
    else:
        return False

if __name__ == "__main__":
    main()


import pandas

def flatten_json(json, return_type = 'json', sep = "__", cols = [], col_names = None):
	df = pandas.DataFrame(json)
	while any((df.applymap(type) == list).any()) or any((df.applymap(type) == dict).any()):
		df = explode_list(split_dict(df, sep))
	if cols:
		df = df[cols].reset_index(drop=True).loc[df[cols].reset_index(drop=True).astype(str).drop_duplicates().index].reset_index(drop=True)
	if type(col_names) == list:
		df.columns = col_names
	if type(col_names) == dict:
		df = df.rename(columns=col_names)
	if return_type =='df':
		return(df).where((pandas.notnull(df)), None)
	if return_type =='json':
		return(df.where((pandas.notnull(df)), None).to_dict(orient='records'))

def split_dict(df, sep):
	for index, value in (df.applymap(type) == dict).any().iteritems():
		if value:
			df1 = df[index].apply(pandas.Series)
			cols = []
			for col in df1.columns:
				cols.append(str(index) + sep +str(col))
			df1.columns = cols
			df = pandas.concat([df.drop([index], axis=1), df1], axis=1)
	return(df)

def explode_list(df):
	for index, value in (df.applymap(type) == list).any().iteritems():
		if value:
			df[index] = df[index].apply(lambda d: d if isinstance(d, list) else [])
			df = df.reset_index(drop=True).explode(index).reset_index(drop=True)
	return(df)


import click as cli
import wandb
import yaml

from itertools import accumulate

ALL_METRICS = {True: ["hdf95/1", "hdf95/2", "masd/1", "masd/2", "dice", "dice/1", "dice/2",
                      "acc/1", "acc/2", "prec/1", "prec/2", "rec/1", "rec/2"],
               False: ["hdf95/1", "masd/1", "dice", "acc/1", "prec/1", "rec/1"]}
CORE_METRICS = {True: ["hdf95/1", "hdf95/2", "masd/1", "masd/2", "dice", "dice/1", "dice/2"],
                False: ["hdf95/1", "masd/1", "dice"]}
# Hardcoded for lazyness
NBF = [7, 15, 14, 10, 5, 14, 12, 12, 3, 11, 5, 77]
CUMNBF = list(accumulate(NBF, initial=0))

def clean_history(hist, keeper):
    # Remove unwanted stuff from WandB history
    hist = hist[keeper]
    hist = hist.astype(float) # Just in case
    hist[hist.columns[hist.columns.str.contains("masd|hdf")]] *= 0.7 # Vox to mm
    hist[hist.columns[~hist.columns.str.contains("masd|hdf")]] *= 100 # Accuracies
    return hist

@cli.command(context_settings={"help_option_names": ["-h", "--help"],
                               "show_default": True})
@cli.argument("run_id", type=str)
@cli.option("--accuracies/--core", "-a/-C", default=True,
            help="Also compute summary for accuracies.")
@cli.option("--multiclass/--binary", "-m/-b", "multi", default=False,
            help="Whether your run was binary or multi segmentation.")
@cli.option("--sequences-files", "-s", "sequences", default=None, type=cli.Path(),
            help="If given, use the listed test files' frames to aggregate to sequence.")
@cli.option("--post-process", "-p / -P", "post", is_flag=True, default=True,
            help="Also compute the summary for post-process values")
def summarize(run_id, accuracies, multi, sequences, post):
    """ Pouet pouet pouet """
    api = wandb.Api()
    smulti = "multi-" if multi else ''
    run = api.run(f"tee-4d/3DMV-{smulti}segmentation/{run_id}")
    metrics = ALL_METRICS[multi] if accuracies else CORE_METRICS[multi]
    if "dice" not in run.summary:
        metrics.remove("dice") # Looking at multi head architecture
    else: # Old case
        metrics.remove("dice/1")
        metrics.remove("dice/2")
    pmetrics = [ f"p_{m}" for m in metrics ] if post else []
    allres = run.history() # Return `pandas.DataFrame`
    res, pres = clean_history(allres, metrics), clean_history(allres, pmetrics)
    print("Gobal summary: ")
    for c in res.columns:
        print(f"  {c.capitalize():<{7}}: {res[c].mean():>{5}.2f} ± {res[c].std():.2f}")
    if post:
        print("Post-processed global summary:")
    for c in pres.columns:
        cc = c.split('_')[-1]
        print(f"  {cc.capitalize():<{7}}: {pres[c].mean():>{5}.2f} ± {pres[c].std():.2f}")
    if sequences:
        # Get number of frames per file
        with open(sequences, 'r') as fd:
            split = yaml.safe_load(fd)
        nbf = [ x[1] for x in split["test"]["files"] ]
        cumnbf = list(accumulate(nbf, initial=0))
        print("\nPer sequence summary:")
        for i in range(len(cumnbf) - 1):
            seq = res.iloc[cumnbf[i]:cumnbf[i + 1]]
            print("  ", end='')
            print(" | ".join([
                f"{c.capitalize()}: {seq[c].mean():>{5}.2f} ± {seq[c].std():>{5}.2f}"
                    for c in seq.columns]))

if __name__ == "__main__":
    summarize()


from django.urls import path
from . import views

urlpatterns = [
    path('test', views.test, name='test'),
    path('users', views.ListClinicianUser.as_view()),
    path('authenticate/clinicians', views.login_as_clinician, name='login_as_clinician'),
    path('authenticate/instructors', views.login_as_instructor, name='login_as_instructor'),
    path('authenticate/patients', views.login_as_patient, name='login_as_patient')
]


import json
import re
import binascii
'''
"{0:#0{1}x}".format(42,6)
'0x002a'
{   # Format identifier
0:  # first parameter
#   # use "0x" prefix
0   # fill with zeroes
{1} # to a length of n characters (including 0x), defined by the second parameter
x   # hexadecimal number, using lowercase letters for a-f
}   # End of format identifier
"{0:0{1}x}".format(address, 4)
'''

def ConvertToHex(conf_data):

    temp = conf_data["hardware_rev"]
    temp = int(temp, 10)
    temp = "{0:0{1}x}".format(temp, 2)
    conf_data["hardware_rev"] = temp

    temp = conf_data["hardware_type"]
    temp = int(temp, 10)
    temp = "{0:0{1}x}".format(temp, 2)
    conf_data["hardware_type"] = temp

    #temp = conf_data["firmware_version"].encode("utf-8").hex()
    #conf_data["firmware_version"] = temp.upper()

    temp = conf_data["serial_number"]
    temp = int(temp, 10)
    temp = "{0:0{1}x}".format(temp, 8)
    temp = re.findall(r'.{2}', temp)
    temp.reverse()
    temp = "".join(temp)
    conf_data["serial_number"] = temp

    temp = conf_data["identifier_number"]
    temp = int(temp, 10)
    temp = "{0:0{1}x}".format(temp, 8)
    temp = re.findall(r'.{2}', temp)
    temp.reverse()
    temp = "".join(temp)
    conf_data["identifier_number"] = temp

    temp = conf_data["name_dcu"].encode("utf-8").hex()
    conf_data["name_dcu"] = temp.upper()

    temp = conf_data["cmd_password_dcu"].encode("utf-8").hex()
    conf_data["cmd_password_dcu"] = temp.upper()

    temp = conf_data["cmd_login_dcu"].encode("utf-8").hex()
    conf_data["cmd_login_dcu"] = temp.upper()

    temp = int(conf_data["dns_enable"], 10)
    temp = "{0:0{1}x}".format(temp, 2)
    conf_data["dns_enable"] = temp.upper()

    temp = int(conf_data["dhcp_enable"], 10)
    temp = "{0:0{1}x}".format(temp, 2)
    conf_data["dhcp_enable"] = temp.upper()

    temp = conf_data["mac_address"].split(":")
    str_temp = ""
    for item in temp:
        item = int(item, 16)
        str_temp = str_temp + "{0:0{1}x}".format(item, 2)
    conf_data["mac_address"] = str_temp.upper()

    temp = conf_data["ip_source"].split(".")
    str_temp = ""
    for item in temp:
        item = int(item, 10)
        str_temp = str_temp + "{0:0{1}x}".format(item, 2)
    conf_data["ip_source"] = str_temp.upper()

    temp = conf_data["mask"].split(".")
    str_temp = ""
    for item in temp:
        item = int(item, 10)
        str_temp = str_temp + "{0:0{1}x}".format(item, 2)
    conf_data["mask"] = str_temp.upper()

    temp = conf_data["ip_gateway"].split(".")
    str_temp = ""
    for item in temp:
        item = int(item, 10)
        str_temp = str_temp + "{0:0{1}x}".format(item, 2)
    conf_data["ip_gateway"] = str_temp.upper()

    temp = conf_data["ip_dds_first"].split(".")
    str_temp = ""
    for item in temp:
        item = int(item, 10)
        str_temp = str_temp + "{0:0{1}x}".format(item, 2)
    conf_data["ip_dds_first"] = str_temp.upper()

    temp = conf_data["ip_dds_second"].split(".")
    str_temp = ""
    for item in temp:
        item = int(item, 10)
        str_temp = str_temp + "{0:0{1}x}".format(item, 2)
    conf_data["ip_dds_second"] = str_temp.upper()

    temp = conf_data["ip_dns"].split(".")
    str_temp = ""
    for item in temp:
        item = int(item, 10)
        str_temp = str_temp + "{0:0{1}x}".format(item, 2)
    conf_data["ip_dns"] = str_temp.upper()

    temp = conf_data["url_dds_first"].encode("utf-8").hex()
    conf_data["url_dds_first"] = temp.upper()

    temp = conf_data["url_dds_second"].encode("utf-8").hex()
    conf_data["url_dds_second"] = temp.upper()

    temp = conf_data["identifier_scu_number"]
    temp = int(temp, 10)
    temp = "{0:0{1}x}".format(temp, 8)
    temp = re.findall(r'.{2}', temp)
    temp.reverse()
    temp = "".join(temp)
    conf_data["identifier_scu_number"] = temp

    temp = conf_data["numbers_slave"]
    temp = int(temp, 10)
    temp = "{0:0{1}x}".format(temp, 2)
    conf_data["numbers_slave"] = temp

    return conf_data

def ArrangeBytes(data):
    eeprom = ""
    # 0 page - reset and bootloader - reset off
    eeprom = eeprom + "AA00{:F<28}".format("")
    # 1 page - reserve for future
    eeprom = eeprom + "{:F<32}".format("")
    # 2 page - ip source
    eeprom = eeprom + "{:F<32}".format(data["ip_source"])
    # 3 page - ip dest - empty
    eeprom = eeprom + "{:F<32}".format("")
    # 4 page - ip gateway
    eeprom = eeprom + "{:F<32}".format(data["ip_gateway"])
    # 5 page - mask
    eeprom = eeprom + "{:F<32}".format(data["mask"])
    # 6 page - mac
    eeprom = eeprom + "{:F<32}".format(data["mac_address"])
    # 7 page - ip dns
    eeprom = eeprom + "{:F<32}".format(data["ip_dns"])
    # 8, 9 page - url - not used
    eeprom = eeprom + "{:F<64}".format("")
    # 10 page - login
    eeprom = eeprom + "{:0<32}".format(data["cmd_login_dcu"])
    # 11 page - password
    eeprom = eeprom + "{:0<32}".format(data["cmd_password_dcu"])
    # 12 page - name dcu
    eeprom = eeprom + "{:0<32}".format(data["name_dcu"])
    # 13 page - version
    eeprom = eeprom + "{:F<32}".format("")
    # 14 page - dns_dhcp enable
    eeprom = eeprom + "{:F<32}".format(data["dns_enable"] + data["dhcp_enable"])
    # 15 page - hardware type
    eeprom = eeprom + "{:F<32}".format(data["hardware_type"])
    # 16 page - hardware revision
    eeprom = eeprom + "{:F<32}".format(data["hardware_rev"])
    # 17 page - serial_number
    eeprom = eeprom + "{:F<32}".format(data["serial_number"])
    # 18 page - identifier
    eeprom = eeprom + "{:F<32}".format(data["identifier_number"])
    # 19 page - first dds ip destination
    eeprom = eeprom + "{:F<32}".format(data["ip_dds_first"])
    # 20 page - second dds ip destination
    eeprom = eeprom + "{:F<32}".format(data["ip_dds_second"])
    # 21, 22 page - first dds url
    eeprom = eeprom + "{:0<64}".format(data["url_dds_first"])
    # 23, 24 page - second dds url
    eeprom = eeprom + "{:0<64}".format(data["url_dds_second"])
    # 25 - scu id
    eeprom = eeprom + "{:F<32}".format(data["identifier_scu_number"])
    # 26 - numbers slave board
    eeprom = eeprom + "{:F<32}".format(data["numbers_slave"])

    eeprom = eeprom.upper()
    return eeprom

def AddingHead(data):
    data_list = re.findall(r'.{32}', data)
    end_data = []
    address = 0

    for part_data in data_list:
        one_row_hex = "10{0:0{1}x}00".format(address, 4) + part_data
        one_row = re.findall(r'.{2}', one_row_hex)
        sum = 0
        for byte_hex in one_row:
            sum = sum + int(byte_hex, 16)
        sum = sum%256
        crc = 256 - sum
        crc = crc % 256
        one_row_hex = ":" + one_row_hex + "{0:0{1}x}".format(crc, 2)
        address = address + 16
        end_data.append(one_row_hex.upper())

    return end_data

def main():
    conf_file = open("config_eeprom.json", "r")
    conf_data = json.load(conf_file)
    conf_file.close()

    name_file = conf_data["name_file"]

    conf_data = ConvertToHex(conf_data)
    eeprom_data = ArrangeBytes(conf_data)
    ready_eeprom = AddingHead(eeprom_data)

    out_file = open(name_file+".eep", "w")
    for row in ready_eeprom:
        out_file.write(row+"\n")

    out_file.write(":00000001FF")
    out_file.close()

    #temp = "{:0<64}".format(temp)

    print(conf_data)

if __name__ == "__main__":
    # execute only if run as a script
    main()


"""Вводится список имен студентов в одну строчку через пробел. Определить, что хотя бы одно имя в этом списке начинается и заканчивается на ту же самую букву (без учета регистра). Реализовать программу с использованием цикла while и оператора break. Вывести ДА, если условие выполняется и НЕТ - в противном случае."""

names = [elem.lower() for elem in input().split()]
flag = "НЕТ"
i = 0

while i < len(names):
    if names[i][0] == names[i][-1]:
        flag = "ДА"
        break
    i += 1

print(flag)


import pandas as pd
import pandas_flavor as pf
import numpy as np

from typing import Union, Optional

from pytimetk.utils.checks import check_dataframe_or_groupby, check_date_column, check_value_column
from pytimetk.core.frequency import get_frequency, get_seasonal_frequency, get_trend_frequency
from pytimetk.utils.memory_helpers import reduce_memory_usage

from pytimetk.utils.parallel_helpers import parallel_apply, get_threads, progress_apply

from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.tsa.seasonal import STL

@pf.register_dataframe_method
def anomalize(
    data: Union[pd.DataFrame, pd.core.groupby.generic.DataFrameGroupBy],
    date_column: str,
    value_column: str,
    period: Optional[int] = None,
    trend: Optional[int] = None,
    method: str = 'stl',
    decomp: str = 'additive',
    clean: str = 'min_max',
    iqr_alpha: float = 0.05,
    clean_alpha: float = 0.75,
    max_anomalies: float = 0.2,
    bind_data: bool = False,
    threads: int = 1,
    show_progress: bool = True,
    verbose = False,
) -> pd.DataFrame:
    '''
    The `anomalize` function is used to detect anomalies in time series data,
    either for a single time
    series or for multiple time series grouped by a specific column.

    Parameters
    ----------
    data : Union[pd.DataFrame, pd.core.groupby.generic.DataFrameGroupBy]
        The input data, which can be either a pandas DataFrame or a pandas
        DataFrameGroupBy object.
    date_column : str
        The name of the column in the data that contains the dates or timestamps.
    value_column : str
        The name of the column in the data that contains the values to be analyzed
        for anomalies.
    period : Optional[int]
        The `period` parameter specifies the length of the seasonal component in the
        time series. It is used in the decomposition process to separate the time
        series into its seasonal, trend, and remainder components. If not specified,
        the function will automatically determine the period based on the data.
    trend : Optional[int]
        The `trend` parameter is an optional integer that specifies the length of
        the moving average window used for trend estimation. If `trend` is set to
        `None`, no trend estimation will be performed.
    method : str
        The `method` parameter determines the method used for anomaly detection.
        The only available method is `twitter`, which is the default value.
        More anomaly detection methods will be added in upcoming releases.
    decomp : str
        The `decomp` parameter specifies the type of decomposition to use for time
        series decomposition. It can take two values:
        1. 'additive' - This is the default value. It specifies that the time series
            will be decomposed using an additive model.
        2. 'multiplicative' - This specifies that the time series will be decomposed
            using a multiplicative model.
    clean : str
        The `clean` parameter specifies the method used to clean the anomalies.
        It can take two values:

        1. 'min_max' - This specifies that the anomalies will be cleaned using the
            min-max method. This method replaces the anomalies with the 0.75 * lower
            or upper bound of the recomposed time series, depending on the direction
            of the anomaly. The 0.75 multiplier can be adjusted using the
            `clean_alpha` parameter.
        2. 'linear' - This specifies that the anomalies will be cleaned using
                    linear interpolation.
    iqr_alpha : float
        The `iqr_alpha` parameter is used to determine the threshold for detecting
        outliers. It is the significance level used in the interquartile range (IQR)
        method for outlier detection.
        - The default value is 0.05, which corresponds to a 5% significance level.
        - A lower significance level will result in a higher threshold, which means
        fewer outliers will be detected.
        - A higher significance level will result in a lower threshold, which means
        more outliers will be detected.
    clean_alpha : float
        The `clean_alpha` parameter is used to determine the threshold for cleaning
        the outliers. The default is 0.75, which means that the anomalies will be
        cleaned using the 0.75 * lower or upper bound of the recomposed time series,
        depending on the direction of the anomaly.
    max_anomalies : float
        The `max_anomalies` parameter is used to specify the maximum percentage of
        anomalies allowed in the data. It is a float value between 0 and 1. For
        example, if `max_anomalies` is set to 0.2, it means that the function will
        identify and remove outliers until the percentage of outliers in the data is
        less than or equal to 20%. The default value is 0.2.
    bind_data : bool
        The `bind_data` parameter determines whether the original data will be
        included in the output. If set to `True`, the original data will be included
        in the output dataframe. If set to `False`, only the anomalous data will be
        included.
    threads : int
        The `threads` parameter specifies the number of threads to use for parallel
        processing. By default, it is set to `1`, which means no parallel processing
        is used. If you set `threads` to `-1`, it will use all available processors
        for parallel processing.
    show_progress : bool
        A boolean parameter that determines whether to show a progress bar during
        the execution of the function. If set to True, a progress bar will be
        displayed. If set to False, no progress bar will be shown.
    verbose: bool
        The `verbose` parameter is a boolean flag that determines whether or not to
        display additional information and progress updates during the execution of
        the `anomalize` function. If `verbose` is set to `True`, you will see more
        detailed output.

    Returns
    -------
    pd.DataFrame
        The `anomalize` function returns a pandas DataFrame containing the original
        data with additional
    columns:
        - observed: original data
        - seasonal: seasonal component
        - seasadaj: seasonal adjusted
        - trend: trend component
        - remainder: residual component
        - anomaly: Yes/No flag for outlier detection
        - anomaly score: distance from centerline
        - anomaly direction: -1, 0, 1 inidicator for direction of the anomaly
        - recomposed_l1: lower level bound of recomposed time series
        - recomposed_l2: upper level bound of recomposed time series
        - observed_clean: original data with anomalies interpolated

    Notes
    -----
    ## Performance

    This function uses parallel processing to speed up computation for large
    datasets with many time series groups:

    Parallel processing has overhead and may not be faster on small datasets.

    To use parallel processing, set `threads = -1` to use all available processors.

    Examples
    --------
    ``` {python}
    # EXAMPLE 1: SINGLE TIME SERIES
    import pytimetk as tk
    import pandas as pd
    import numpy as np

    # Create a date range
    date_rng = pd.date_range(start='2021-01-01', end='2024-01-01', freq='MS')

    # Generate some random data with a few outliers
    np.random.seed(42)
    data = np.random.randn(len(date_rng)) * 10 + 25
    data[3] = 100  # outlier

    # Create a DataFrame
    df = pd.DataFrame(date_rng, columns=['date'])
    df['value'] = data

    # Anomalize the data
    anomalize_df = tk.anomalize(
        df, "date", "value",
        method = "twitter",
        iqr_alpha = 0.10,
        clean_alpha = 0.75,
        clean = "min_max",
        verbose = True,
    )

    anomalize_df.glimpse()
    ```

    ``` {python}
    # Visualize the results
    anomalize_df.plot_anomalies_decomp("date")
    ```

    ``` {python}
    # Visualize the anomaly bands
    (
         anomalize_df
            .plot_anomalies(
                date_column = "date",
                engine = "plotly",
            )
    )
    ```

    ``` {python}
    # Get the anomalies
    anomalize_df.query("anomaly=='Yes'")
    ```

    ``` {python}
    # Visualize observed vs cleaned
    anomalize_df.plot_anomalies_cleaned("date")
    ```

    ``` {python}
    # EXAMPLE 2: MULTIPLE TIME SERIES
    import pytimetk as tk
    import pandas as pd

    df = tk.load_dataset("wikipedia_traffic_daily", parse_dates = ['date'])

    anomalize_df = (
        df
            .groupby('Page', sort = False)
            .anomalize(
                date_column = "date",
                value_column = "value",
                method = "stl",
                iqr_alpha = 0.025,
                verbose = False,
            )
    )

    # Visualize the decomposition results

    (
        anomalize_df
            .groupby("Page")
            .plot_anomalies_decomp(
                date_column = "date",
                width = 1800,
                height = 1000,
                x_axis_date_labels = "%Y",
                engine = 'plotly'
            )
    )
    ```

    ``` {python}
    # Visualize the anomaly bands
    (
        anomalize_df
            .groupby("Page")
            .plot_anomalies(
                date_column = "date",
                facet_ncol = 2,
                width = 1000,
                height = 1000,
            )
    )
    ```

    ``` {python}
    # Get the anomalies
    anomalize_df.query("anomaly=='Yes'")
    ```

    ``` {python}
    # Visualize observed vs cleaned
    (
        anomalize_df
            .groupby("Page")
            .plot_anomalies_cleaned(
                "date",
                facet_ncol = 2,
                width = 1000,
                height = 1000,
            )
    )
    ```
    '''

    check_dataframe_or_groupby(data)
    check_date_column(data, date_column)
    check_value_column(data, value_column)

    if isinstance(data, pd.DataFrame):
        result = _anomalize(
            data = data,
            date_column=date_column,
            value_column=value_column,
            period=period,
            trend=trend,
            method=method,
            decomp=decomp,
            clean=clean,
            iqr_alpha=iqr_alpha,
            clean_alpha=clean_alpha,
            max_anomalies=max_anomalies,
            bind_data=bind_data,
            verbose=verbose,
        )

    if isinstance(data, pd.core.groupby.generic.DataFrameGroupBy):

        group_names = data.grouper.names

        # Get threads
        threads = get_threads(threads)

        if threads == 1:

            result = progress_apply(
                data,
                func = _anomalize,
                show_progress=show_progress,
                desc="Anomalizing...",
                # kwargs
                date_column=date_column,
                value_column=value_column,
                period=period,
                trend=trend,
                method=method,
                decomp=decomp,
                clean=clean,
                iqr_alpha=iqr_alpha,
                clean_alpha=clean_alpha,
                max_anomalies=max_anomalies,
                bind_data=bind_data,
                verbose=verbose,
            ).reset_index(level=group_names)

        else:

            result = parallel_apply(
                data,
                _anomalize,
                date_column=date_column,
                value_column=value_column,
                period=period,
                trend=trend,
                method=method,
                decomp=decomp,
                clean=clean,
                iqr_alpha=iqr_alpha,
                clean_alpha=clean_alpha,
                max_anomalies=max_anomalies,
                bind_data=bind_data,
                threads=threads,
                show_progress=show_progress,
                verbose=verbose,
                desc="Anomalizing...",
            ).reset_index(level=group_names)

    return result

# Monkey patch the method to pandas groupby objects
pd.core.groupby.generic.DataFrameGroupBy.anomalize = anomalize

def _anomalize(
    data: Union[pd.DataFrame, pd.core.groupby.generic.DataFrameGroupBy],
    date_column: str,
    value_column: str,
    period: Optional[int] = None,
    trend: Optional[int] = None,
    method: str = 'stl',
    decomp: str = 'additive',
    clean: str = 'linear',
    iqr_alpha: float = 0.05,
    clean_alpha: float = 0.75,
    max_anomalies: float = 0.2,
    bind_data: bool = False,
    verbose = False,
) -> pd.DataFrame:

    orig_date_column = data[date_column]

    data = reduce_memory_usage(data.copy())

    # STEP 0: Get the seasonal period and trend frequency
    if period is None:
        period = get_seasonal_frequency(data[date_column], numeric=True)
        period = int(period)
    if verbose:
        print(f"Using seasonal frequency of {period} observations")

    if trend is None:
        trend = get_trend_frequency(data[date_column], numeric=True)
        trend = int(trend)
    if verbose:
        print(f"Using trend frequency of {trend} observations")

    # STEP 1: Decompose the time series
    if method == 'twitter':

        median_span = np.round(len(data) / trend)
        median_span = int(median_span)

        result = _twitter_decompose(
            data = data,
            date_column=date_column,
            value_column=value_column,
            period=period,
            median_span=median_span,
            model=decomp,
        )
    elif method == 'stl':

        def make_odd(n):
            return n + 1 if n % 2 == 0 else n

        seasonal = make_odd(period)
        trend = make_odd(trend)

        result = _stl_decompose(
            data=data,
            date_column=date_column,
            value_column=value_column,
            period=period,
            seasonal=seasonal,
            trend=trend,
            robust = True,
        )
    else:
        raise ValueError(f"Method {method} is not supported. Please use one of 'stl' or 'twitter'.")

    # STEP 2: Identify the outliers

    outlier_df = _iqr(
        data = result,
        target = 'remainder',
        alpha = iqr_alpha,
        max_anoms = max_anomalies
    )

    # STEP 3: Recompose the time series

    result['anomaly'] = outlier_df['outlier_reported']
    result['anomaly_score'] = outlier_df['score']
    result['anomaly_direction'] = outlier_df['direction']

    result['recomposed_l1'] = result['seasonal'] + result['trend'] + outlier_df['remainder_l1']

    result['recomposed_l2'] = result['seasonal'] + result['trend'] + outlier_df['remainder_l2']

    # STEP 4: Clean the Anomalies

    if clean == 'linear':
        result['observed_clean'] = result['observed'] \
            .where(result['anomaly']=='No', np.nan) \
            .interpolate(method=clean, limit_direction='both')
    else:
        # min_max
        result['observed_clean'] = np.where(
            result['anomaly_direction'] == -1,
            result['recomposed_l1'] + ((1-clean_alpha)*(result['recomposed_l2'] - result['recomposed_l1'])/2),
            np.where(
                result['anomaly_direction'] == 1,
                result['recomposed_l2'] - ((1-clean_alpha)*(result['recomposed_l2'] - result['recomposed_l1'])/2),
                result['observed']
            )
        )

    result[date_column] = orig_date_column

    # STEP 5: Bind the data
    if bind_data:
        result = pd.concat([data, result.drop(date_column, axis=1)], axis=1)

    return reduce_memory_usage(result)

def _twitter_decompose(
    data,
    date_column,
    value_column,
    period = None,
    median_span = None,
    model = 'additive',
):
    orig_index = data.index

    series = data.set_index(date_column)[value_column]

    # Need to add freq, trend, and kwargs
    # TODO - Median Seasonal Trend (More robust to outliers)
    result = seasonal_decompose(
        series,
        period=period,
        model=model,
        extrapolate_trend='freq',
    )

    # Construct TS Decomposition DataFrame
    observed = series

    seasadj = series - result.seasonal
    seasadj.name = 'seasadj'

    # Calculate median trend
    if median_span is None:
        median_span = 4

    def repeat_sequence(seq, length_out):
        quotient, remainder = divmod(length_out, len(seq))
        return seq * quotient + seq[:remainder]

    df = pd.DataFrame(seasadj)

    df['median_index'] = sorted(repeat_sequence(list(range(median_span)), len(seasadj)))

    trend = df.groupby('median_index')['seasadj'].transform('median')

    resid = seasadj - trend

    result_df = pd.concat([observed, result.seasonal, seasadj, trend, resid], axis=1)

    result_df.columns = ['observed', 'seasonal', 'seasadj', 'trend', 'remainder']

    result_df.reset_index(inplace=True)

    result_df.index = orig_index

    return result_df

def _seasonal_decompose(
    data,
    date_column,
    value_column,
    model='additive',
    period = None,
    filt=None,
    two_sided=True,
    extrapolate_trend = 'freq'
):

    orig_index = data.index

    series = data.set_index(date_column)[value_column]

    # Need to add freq, trend, and kwargs
    result = seasonal_decompose(
        series,
        model=model,
        period = period,
        filt=filt,
        two_sided=two_sided,
        extrapolate_trend = extrapolate_trend,
    )

    # Construct TS Decomposition DataFrame
    observed = series

    seasadj = series - result.seasonal

    trend = result.trend

    resid = seasadj - trend

    result_df = pd.concat([observed, result.seasonal, seasadj, trend, resid], axis=1)

    result_df.columns = ['observed', 'seasonal', 'seasadj', 'trend', 'remainder']

    result_df.reset_index(inplace=True)

    result_df.index = orig_index

    return result_df

def _stl_decompose(
    data,
    date_column,
    value_column,
    period = None,
    **kwargs
):

    orig_index = data.index

    series = data.set_index(date_column)[value_column]

    # Need to add freq, trend, and kwargs
    stl = STL(
        series,
        period = period,
        **kwargs
    )

    result = stl.fit()

    # Construct TS Decomposition DataFrame
    observed = series

    seasadj = series - result.seasonal

    trend = result.trend

    resid = seasadj - trend

    result_df = pd.concat([observed, result.seasonal, seasadj, trend, resid], axis=1)

    result_df.columns = ['observed', 'seasonal', 'seasadj', 'trend', 'remainder']

    result_df.reset_index(inplace=True)

    result_df.index = orig_index

    return result_df

def _iqr(data, target, alpha=0.05, max_anoms=0.2):
    """
    This function is not intended for general use. It is used internally by the anomaly detection functions.

    Examples
    --------
    ``` {python}
    import pytimetk as tk
    import pandas as pd
    import numpy as np

    # Example Usage:
    df = pd.DataFrame({
        'x': list(range(100)),
        'y': np.random.randn(100)
    })

    outlier_dict = tk.iqr(df, 'y')
    ```
    """

    data = data.copy()

    # Compute the interquartile range
    q1, q3 = np.percentile(data[target], [25, 75])
    iq_range = q3 - q1
    limits = [-1*(q1 + (0.15 / alpha) * iq_range), q3 + (0.15 / alpha) * iq_range]

    # Identify the outliers
    outlier_idx = (data[target] < limits[0]) | (data[target] > limits[1])

    # Calculate the anomaly_score from the centerline
    centerline = sum(limits) / 2
    data['score'] = abs(data[target] - centerline)

    # Yes/No flag for outlier
    data['outlier_reported'] = np.where(data[target] > limits[1], "Yes", np.where(data[target] < limits[0], "Yes", "No"))

    # Direction of the outlier
    data['direction'] = np.where(data[target] > limits[1], 1, np.where(data[target] < limits[0], -1, 0))

    # Remainder Limits
    data['remainder_l1'] = limits[0]
    data['remainder_l2'] = limits[1]

    return data[['outlier_reported', 'direction', 'score', 'remainder_l1', 'remainder_l2']]


from model.paramsPattern import ParamsPattern
from controller.world.robot import Robot
from controller.world.ball import Ball
import time
import numpy as np

class Field():
  LEFT = -1
  """Lado aliado está a esquerda"""

  RIGHT = 1
  """Lado aliado está a direita"""

class World(ParamsPattern):
  """Classe de mundo que armazena as posições dos robôs, velocidades, posição da bola, limites de campo e escore de jogo."""

  def __init__(self, n_robots):
    ParamsPattern.__init__(self, "worldConfig", {
      "UVF_r": 0.05,
      "UVF_Kr": 15,
      "UVF_Kr_single": 0.1,
      "UVF_horRepSize": 0.05,
      "UVF_horMinDist": 0.1,
      "UVF_verRepSize": 0.15,
      "UVF_verGoalSize": 0.2,
      "UVF_verMinDist": 0.15,
      "UVF_ponRadius": 0.3,
      "UVF_ponDistanceRadius": 0.1,
      "UVF_ponMinAvoidanceAngle": 0.5
    })

    self.field_x_length = 1.75
    self.field_y_length = 1.35
    self.xmax = (self.field_x_length) / 2
    self.ymax = (self.field_y_length) / 2
    self.xmaxmargin = self.xmax - 0.10
    self.ymaxmargin = self.ymax - 0.20
    self.marginLimits = (self.xmaxmargin, self.ymaxmargin)
    self.goalpos = (self.xmax, 0)
    self.allyGoalPos = np.array([-self.xmax, 0])
    self.rg = np.array([-0.75, 0])
    self.goalAreaSize = np.array([0.3, 0.4])
    self.goalylength = 0.4
    self.n_robots = n_robots
    self.fieldSide = Field.RIGHT
    self.running = False
    self.checkBatteries = False
    self.manualControlSpeedV = 0
    self.manualControlSpeedW = 0
    self.mus = [0.07, 0.07, 0.12, 0.07, 0.07]
    self.robots = [Robot(self, i, self.mus[i]) for i in range(self.n_robots)]
    self.enemyRobots = []
    self.edges = []
    self.ball = Ball(self)
    self.__referenceTime = 0
    self.dt = 0

  def update(self, visionMessage):
    """Recebe uma mensagem da visão e atualiza as posições e velocidades de robôs e bola"""

    # Atualiza cada robô localizado e identificado
    for i,allyPose in enumerate(visionMessage.allyPoses):
      if not allyPose[3]: continue

      # O ângulo do robô não pode variar de um loop para outro mais que 70% de pi/2, se isso ocorrer deve ser algum erro da visão
      # if self.robots[i].poseDefined and np.arccos(np.cos(allyPose[2]-self.robots[i].th)) > 0.49*np.pi/2:
      #   theta = self.robots[i].th
      # else:
      theta = allyPose[2]

      self.robots[i].raw_update(allyPose[0], allyPose[1], theta)

    # Atualiza a lista de robôs adversários
    self.enemyRobots = visionMessage.advPos

    # Atualiza a bola se ela foi localizada
    if visionMessage.ball_found:
      self.ball.raw_update(visionMessage.ball_x, visionMessage.ball_y)

    # Computa a velocidade com base no tempo passado desde a última chamada a `update` e atualiza o tempo para o tempo atual.
    self.dt = time.time() - self.__referenceTime
    self.calc_velocities(self.dt)
    self.__referenceTime = time.time()

  def setRunning(self, state):
    """Recebe uma flag `state` indicando se o jogo está ou não rodando."""
    self.running = state
    if state is True:
      for robot in self.robots:
        robot.lastTimeAlive = time.time()
        robot.spin = 0

  def getRobots(self):
    """Retorna os robôs."""
    return self.robots

  def calc_velocities(self, dt):
    """Computa as velocidades para robôs e bola com base em suas posições anteriores e atuais e com base no intervalo de tempo `dt`."""
    for robot in self.robots:
      robot.calc_velocities(dt)

    self.ball.calc_velocities(dt)

  def setEdges(self, points):
    self.edges = points

  def setFieldSide(self, side):
    self.fieldSide = side

  def setPreferedEntity(self, robotIndex, entityPref):
    self.robots[robotIndex].preferedEntity = entityPref


import os
import socket
import datetime
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from dataclasses import dataclass

# from configs.config import SLACK_TOKEN, SLACK_CHANNEL
from tabulate import tabulate
from typing import List, Dict

@dataclass
class SlackContent:
    message: str
    error: str = ""

hex = {
    "green": "#00ff00",
    "red": "ff0000",
    "yellow": "#ffba01",
    "white": "ffffff",
}

token = os.getenv("SLACK_TOKEN")
client = WebClient(token=token)
channel = os.getenv("SLACK_CHANNEL")
# host = socket.gethostname()

# token = SLACK_TOKEN
# client = WebClient(token=token)
# channel = SLACK_CHANNEL

def post_apt_message(complex_name: str, available_apt_list: List[Dict]):
    attachments = generate_apt_info(complex_name, available_apt_list)
    try:
        response = client.chat_postMessage(channel=channel, **attachments)
    except SlackApiError as e:
        print(f"메시지 전송 실패: {e.response['error']}")

def generate_apt_info(complex_name: str, available_apt_list: List[Dict]):
    if available_apt_list == []:
        return {"title": complex_name, "text": f"{complex_name}: 확인된 매물이 없습니다."}

    row_text = ""
    for apt in available_apt_list:
        row_text += "{} <https://m.land.naver.com/article/info/{}|아파트이름: {}>\n".format(
            apt.get("noticed_label"), apt.get("item_id"), apt.get("title")
        )
        row_text += "동: {}\n".format(apt.get("building"))
        row_text += "가격: {}\n".format(apt.get("price"))
        row_text += "평형: {}\n".format(apt.get("size"))
        row_text += "층: {}\n".format(apt.get("floor"))
        row_text += "거실창 방향: {}\n".format(apt.get("direction"))
        row_text += "기타: {}\n".format(apt.get("describe"))
        row_text += "\n"
    if len(row_text) > 3000:
        row_text = row_text[:3000]
    text = "아파트 매일 알람"
    blocks = [
        {
            "type": "section",
            "text": {"type": "mrkdwn", "text": f"{row_text}"},
        }
    ]
    return {
        "title": f"{complex_name}",
        "text": text,
        "blocks": blocks,
    }

def post_log_message(color: str, slack_content: SlackContent):
    attachments = generate_attachments(color, slack_content)
    try:
        response = client.chat_postMessage(channel=channel, attachments=attachments)
    except SlackApiError as e:
        print(f"메시지 전송 실패: {e.response['error']}")

def generate_attachments(color: str, slack_content: SlackContent) -> str:
    ts = datetime.datetime.now()
    ts = ts.isoformat("T") + "Z"
    msg = f"`TS`: {ts}\n{slack_content.message}\n"

    if slack_content.error:
        msg += "*ERROR*\n```{}```".format(slack_content.error)

    return [{"color": hex[color], "title": "아파트 알리미 로그", "text": msg}]

def info(message: str):
    post_log_message("green", SlackContent(message=message))

def error(message: str, error_message: str = ""):
    post_log_message(
        "red",
        SlackContent(message=message, error=error_message),
    )

def warning(message: str):
    post_log_message("yellow", SlackContent(message=message))


from ..capacitor_launchpad_connector_base import CapacitorLaunchpadConnectorBase
from qiskit_metal import Dict
from qiskit_metal.designs import DesignPlanar
from qiskit_metal.qlibrary.tlines.pathfinder import RoutePathfinder
import numpy as np

class CapacitorLaunchpadConnector(CapacitorLaunchpadConnectorBase):
    def __init__(
        self, design: DesignPlanar = None, qubit_grid: np.ndarray = np.array([])
    ):
        self._design = design
        self._qubit_grid = qubit_grid

    def generate_capacitor_launchpad_connection(
        self,
    ) -> list[tuple[list[str, str], RoutePathfinder]]:
        N_x = len(self._qubit_grid[0])
        N_y = len(self._qubit_grid)
        tl_readouts = []
        # Loop to generate and draw the launchpads
        for x in range(N_x):
            for y in range(N_y):
                current_qubit = self._qubit_grid[y][x]

                # Skip readout if no qubit at position
                if current_qubit == -1:
                    continue

                start_pin_, end_pin_ = self.get_configuration(N_y, y)

                tl_readout = RoutePathfinder(
                    self._design,
                    f"TL_Readout_{current_qubit}",
                    options=dict(
                        hfss_wire_bonds=True,
                        pin_inputs=Dict(
                            start_pin=Dict(
                                component=f"Cap_Readout_{current_qubit}", pin=start_pin_
                            ),
                            end_pin=Dict(
                                component=f"Launch_Readout_{current_qubit}",
                                pin=end_pin_,
                            ),
                        ),
                    ),
                )

                tl_readouts.append(
                    [
                        (
                            f"Cap_Readout_{current_qubit}",
                            f"Launch_Readout_{current_qubit}",
                        ),
                        tl_readout,
                    ]
                )

        return tl_readouts

    def get_configuration(self, N_y, y):
        # Bottom row
        if y == 0:
            start_pin_ = "south_end"
        # Top row
        elif y == (N_y - 1):
            start_pin_ = "north_end"
        # Middle row
        else:
            start_pin_ = "south_end"
        end_pin_ = "tie"
        return start_pin_, end_pin_