text
stringlengths
184
4.48M
<!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="author" content="Nicolas Huanca"> <meta name="description" content="Pagina Web ECommerce"> <meta name="keywords" content="HTML, CSS, Bootstrap, Javascript, ECommerce"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css"> <link rel="stylesheet" href="./styles/styles.css"> <title>Web ECommerce</title> </head> <body> <!-- BARRA DE NAVEGACION --> <nav class="navbar navbar-expand-lg navbar-light" id="home"> <div class="container"> <a class="navbar-brand order-lg-0" href="index.html"> <img width="120" src="./images/mlg-logo.png" alt=""> </a> <div class="order-lg-2"> <button type="button" class="btn position-relative"> <i class="fa fa-shopping-cart"></i> <span class="position-absolute top-0 start-100 translate-middle badge bg-danger">5</span> </button> <button type="button" class="btn position-relative"> <i class="fa fa-heart"></i> <span class="position-absolute top-0 start-100 translate-middle badge bg-danger">2</span> </button> <!-- <button type="button" class="btn position-relative"> <i class="fa fa-search"></i> </button> --> </div> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse order-lg-1" id="navbarSupportedContent"> <ul class="navbar-nav mx-auto text-center"> <li class="nav-item"> <a class="nav-link" aria-current="page" href="#home">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#collection">Colección</a> </li> <li class="nav-item"> <a class="nav-link" href="#special">Especial</a> </li> <li class="nav-item"> <a class="nav-link" href="#blogs">Blogs</a> </li> <li class="nav-item"> <a class="nav-link" href="#about">Sobre Nosotros</a> </li> <li class="nav-item"> <a class="nav-link" href="#newsletter">Suscripción</a> </li> </ul> </div> </div> </nav> <!-- HEADER --> <header class="header carousel slide" id="carouselExampleRide"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="2" aria-label="Slide 3"></button> </div> <div class="header-carousel container carousel-inner"> <div class="carousel-item active"> <h2 class="text-white">Los Mejores Productos</h2> <p class="text-white">Lorem ipsum dolor sit amet consectetur adipisicing elit. Beatae, ipsa.</p> <a href="#" class="btn-header btn btn-primary btn-circle">Comprar ahora</a> </div> <div class="carousel-item"> <h2 class="text-white">Stock En Promocion</h2> <p class="text-white">Lorem ipsum dolor sit amet consectetur adipisicing elit. Beatae, ipsa.</p> <a href="#" class="btn-header btn btn-primary btn-circle">Comprar ahora</a> </div> <div class="carousel-item"> <h2 class="text-white">Nuevos Lanzamientos</h2> <p class="text-white">Lorem ipsum dolor sit amet consectetur adipisicing elit. Beatae, ipsa.</p> <a href="#" class="btn-header btn btn-primary btn-circle">Comprar ahora</a> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleRide" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Siguiente</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleRide" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Anterior</span> </button> </header> <!-- COLLECTION --> <section class="collection" id="collection"> <!-- <div class="added-collection"> <div class="added-img-container"> <span class="close"><i class="fa-regular fa-rectangle-xmark"></i></span> <img class="added-img" src="" alt=""> </div> </div> --> <div class="container"> <div class="text-center"> <h2 class="titulo">Colección 2023</h2> </div> <div class="row"> <!-- se agrega la clase para filtrar productos "filter-button-group" --> <div class="collection-btns d-flex justify-content-center flex-wrap gap-3 filter-button-group"> <button class="btn btn-outline-primary btn-activo btn-todo" type="button" data-filter="*">Todo</button> <button class="btn btn-outline-primary btn-vendido" type="button" data-filter=".vendido">Mas vendidos</button> <button class="btn btn-outline-primary btn-recomendado" type="button" data-filter=".recomendado">Recomendados</button> <button class="btn btn-outline-primary btn-nuevo" type="button" data-filter=".nuevo">Nuevo</button> </div> </div> <div class="collection-list row"> <div class="col-md-6 col-lg-4 col-xl-3 vendido"> <div class="collection-img"> <img src="./images/Star-Wars-Darth-Vader-Buddha.jpg" class="w-100" alt=""> <!-- <span>En venta</span> --> </div> <div class="text-center mt-3"> <div class="rating"> <i class="bi bi-star-fill"></i> <i class="bi bi-star-fill"></i> <i class="bi bi-star-fill"></i> <i class="bi bi-star-fill"></i> <i class="bi bi-star-fill"></i> </div> <p>Darth Vader Buda <span class="fw-bold">$99.99</span></p> </div> </div> <div class="col-md-6 col-lg-4 col-xl-3 vendido"> <div class="collection-img"> <img src="./images/LED-Clock-Fan.jpg" class="w-100" alt=""> <!-- <span>En venta</span> --> </div> <div class="text-center mt-3"> <div class="rating"> <i class="bi bi-star-fill "></i> <i class="bi bi-star-fill "></i> <i class="bi bi-star-fill "></i> <i class="bi bi-star-fill "></i> <i class="bi bi-star-half "></i> </div> <p>Reloj Ventilador LED <span class="fw-bold">$99.99</span></p> </div> </div> <div class="col-md-6 col-lg-4 col-xl-3 nuevo"> <div class="collection-img"> <img src="./images/miniguitar.webp" class="w-100" alt=""> <!-- <span>En venta</span> --> </div> <div class="text-center mt-3"> <div class="rating"> <i class="bi bi-star-fill "></i> <i class="bi bi-star-fill "></i> <i class="bi bi-star-fill "></i> <i class="bi bi-star "></i> <i class="bi bi-star "></i> </div> <p>Mini Guitarra Electrica <span class="fw-bold">$99.99</span></p> </div> </div> <div class="col-md-6 col-lg-4 col-xl-3 recomendado"> <div class="collection-img"> <img src="./images/aeroplano.webp" class="w-100" alt=""> <!-- <span>En venta</span> --> </div> <div class="text-center mt-3"> <div class="rating"> <i class="bi bi-star-fill "></i> <i class="bi bi-star-fill "></i> <i class="bi bi-star-fill "></i> <i class="bi bi-star-fill "></i> <i class="bi bi-star-half "></i> </div> <p>Aeroplano Mecanico <span class="fw-bold">$99.99</span></p> </div> </div> <div class="col-md-6 col-lg-4 col-xl-3 nuevo"> <div class="collection-img"> <img src="./images/superman.webp" class="w-100" alt=""> <!-- <span>En venta</span> --> </div> <div class="text-center mt-3"> <div class="rating"> <i class="bi bi-star-fill "></i> <i class="bi bi-star-fill "></i> <i class="bi bi-star-fill "></i> <i class="bi bi-star-fill "></i> <i class="bi bi-star "></i> </div> <p>Superman Light Block <span class="fw-bold">$99.99</span></p> </div> </div> <div class="col-md-6 col-lg-4 col-xl-3 recomendado"> <div class="collection-img"> <img src="./images/lampara.webp" class="w-100" alt=""> <!-- <span>En venta</span> --> </div> <div class="text-center mt-3"> <div class="rating"> <i class="bi bi-star-fill "></i> <i class="bi bi-star-fill "></i> <i class="bi bi-star-fill "></i> <i class="bi bi-star-half "></i> <i class="bi bi-star-half "></i> </div> <p>Lampara de prisma <span class="fw-bold">$99.99</span></p> </div> </div> <div class="col-md-6 col-lg-4 col-xl-3 vendido"> <div class="collection-img"> <img src="./images/cinema.webp" class="w-100" alt=""> <!-- <span>En venta</span> --> </div> <div class="text-center mt-3"> <div class="rating"> <i class="bi bi-star-fill "></i> <i class="bi bi-star-fill "></i> <i class="bi bi-star-fill "></i> <i class="bi bi-star "></i> <i class="bi bi-star "></i> </div> <p>Cinema Lightbox <span class="fw-bold">$99.99</span></p> </div> </div> <div class="col-md-6 col-lg-4 col-xl-3 recomendado"> <div class="collection-img"> <img src="./images/collar.webp" class="w-100" alt=""> <!-- <span>En venta</span> --> </div> <div class="text-center mt-3"> <div class="rating"> <i class="bi bi-star-fill "></i> <i class="bi bi-star-fill "></i> <i class="bi bi-star-fill "></i> <i class="bi bi-star-fill "></i> <i class="bi bi-star-fill "></i> </div> <p>Collar Sistema Solar <span class="fw-bold">$99.99</span></p> </div> </div> </div> </div> </section> <!-- PRODUCTOS ESPECIALES --> <section id="special"> <div class="container"> <div class="text-center"> <h2 class="titulo">Colección Especial</h2> </div> <div class="special-list row"> <div class="col-md-6 col-lg-4 col-xl-3"> <div class="special-img"> <img src="./images/esferamarte.webp" class="w-100" alt=""> </div> <div class="text-center mt-3"> <p>Esfera de Marte <span class="fw-bold">$99.99</span></p> <a class="btn btn-outline-primary btn-carrito" href=""><i class="bi bi-cart-check"></i> Agregar</a> </div> </div> <div class="col-md-6 col-lg-4 col-xl-3"> <div class="special-img"> <img src="./images/lamparamesa.webp" class="w-100" alt=""> </div> <div class="text-center mt-3"> <p>Lampara de Mesa <span class="fw-bold">$99.99</span></p> <a class="btn btn-outline-primary btn-carrito" href=""><i class="bi bi-cart-check"></i> Agregar</a> </div> </div> <div class="col-md-6 col-lg-4 col-xl-3"> <div class="special-img"> <img src="./images/gameboy.jpg" class="w-100" alt=""> </div> <div class="text-center mt-3"> <p>GameBoy <span class="fw-bold">$99.99</span></p> <a class="btn btn-outline-primary btn-carrito" href=""><i class="bi bi-cart-check"></i> Agregar</a> </div> </div> <div class="col-md-6 col-lg-4 col-xl-3"> <div class="special-img"> <img src="./images/gocube.webp" class="w-100" alt=""> </div> <div class="text-center mt-3"> <p>Juego GoCube <span class="fw-bold">$99.99</span></p> <a class="btn btn-outline-primary btn-carrito" href=""><i class="bi bi-cart-check"></i> Agregar</a> </div> </div> </div> </div> </section> <!-- OFERTAS --> <section class="offers" id="offers"> <div class="container"> <div class="row d-flex align-items-center text-center"> <div class="offers-content"> <h2>Super Ofertas</h2> <p>Descuentos de hasta el 40%</p> <a href="" class="btn btn-primary">Realizar compra</a> </div> </div> </div> </section> <!-- BLOG --> <section id="blogs" class="blog"> <div class="container"> <div class="text-center"> <h2 class="titulo">Blog de Novedades</h2> </div> <div class="row d-flex justify-content-around gap-3"> <div class="card cols-sm-12 col-md-6 col-lg-4"> <img src="./images/blogg.jpg" alt=""> <div class="card-body"> <h4 class="card-title">Assassin’s Creed Valhalla es el primer videojuego en ganar un Grammy</h4> <p class="card-text">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Optio accusantium debitis numquam aperiam reprehenderit, facilis ea vel dolorum veniam, accusamus aliquid commodi architecto natus.</p> <p class="card-text"><span class="fw-bold">Author: </span>Nicolas H.</p> <a href="" class="btn btn-outline-primary">Leer Mas</a> </div> </div> <div class="card cols-sm-12 col-md-6 col-lg-4"> <img src="./images/blog2.jpg" alt=""> <div class="card-body"> <h4 class="card-title">Nuevos lanzamientos para tu PC Gamer</h4> <p class="card-text">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Optio accusantium debitis numquam aperiam reprehenderit, facilis ea vel dolorum veniam, accusamus aliquid commodi architecto natus.</p> <p class="card-text"><span class="fw-bold">Author: </span>Nicolas H.</p> <a href="" class="btn btn-outline-primary">Leer Mas</a> </div> </div> <div class="card cols-sm-12 col-md-6 col-lg-4"> <img src="./images/blog3.jpg" alt=""> <div class="card-body"> <h4 class="card-title">Poco presentó los nuevos integrantes de su familia, el Poco X5 y X5 Pro</h4> <p class="card-text">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Optio accusantium debitis numquam aperiam reprehenderit, facilis ea vel dolorum veniam, accusamus aliquid commodi architecto natus.</p> <p class="card-text"><span class="fw-bold">Author: </span>Nicolas H.</p> <a href="" class="btn btn-outline-primary">Leer Mas</a> </div> </div> </div> </div> </section> <!-- sobre nosotros --> <section id="about" class="sobre-nosotros"> <div class="container"> <div class="row"> <div class="text-center"> <h2 class="titulo">Sobre Nosotros</h2> </div> <div class="sobre-nosotros-texto col-lg-6"> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Est iure iusto nihil itaque voluptatum adipisci suscipit sapiente at quam omnis, explicabo debitis minus repellat autem!</p> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quod, sequi? Fuga quae voluptatem quis libero inventore eius est repudiandae. Commodi placeat sed, neque ad vitae natus dicta rem omnis sequi?</p> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Repellat voluptate obcaecati, distinctio consequatur laudantium, pariatur dignissimos est, libero omnis quam repudiandae dicta nihil? Molestias, numquam saepe cumque reprehenderit optio similique aspernatur dolores recusandae provident, labore repellat? Itaque dolor veritatis dolorem?</p> </div> <div class="col-lg-6"> <img src="./images/blog.jpg" class="img-fluid" alt=""> </div> </div> </div> </section> <!-- Newsletter --> <section id="newsletter" class="newsletter"> <div class="container"> <div class="d-flex flex-column align-items-center justify-content-center"> <div class="text-center"> <h2 class="titulo">Suscripción de Noticias</h2> </div> <p class="text-center">Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam repellat non cum corporis distinctio eius odit sed rerum commodi ad!</p> <div class="input-group"> <input type="email" placeholder="Email" class="form-control"> <button class="btn text-white" type="submit">suscribirse</button> </div> </div> </div> </section> <!-- footer --> <footer> <div class="container"> <div class="row d-flex justify-content-around align-items-start"> <div class="footer-seccion col-md-6 col-lg-3"> <h5>Enlaces</h5> <ul> <li><a href="#home"><i class="bi bi-caret-right"></i> Home</a></li> <li><a href="#collection"><i class="bi bi-caret-right"></i> Colección</a></li> <li><a href="#blogs"><i class="bi bi-caret-right"></i> Blog de Novedades</a></li> <li><a href="#about"><i class="bi bi-caret-right"></i> Sobre Nosotros</a></li> </ul> </div> <div class="footer-seccion col-md-6 col-lg-3"> <h5>Contacto</h5> <div class="d-flex justify-content-start align-items-start"> <p><i class="bi bi-envelope-at r-3"></i> [email protected]</p> </div> <div class="d-flex justify-content-start align-items-start"> <p><i class="bi bi-telephone-plus-fill"></i> 555-555-5555</p> </div> </div> <div class="footer-seccion col-md-6 col-lg-3"> <h5>Redes</h5> <ul class="redes-iconos"> <li><a href="#"><i class="footer-icono bi bi-facebook"></i></a></li> <li><a href="#"><i class="footer-icono bi bi-instagram"></i></a></li> <li><a href="#"><i class="footer-icono bi bi-twitter"></i></a></li> </ul> </div> </div> </div> <div class="footer-datos">&copy Nicolas Huanca 2023 - <a target="_blank" class="footer-datos__github" href="https://github.com/nicolas2289h">Github</a></div> </footer> <!-- fontawesome --> <script src="https://kit.fontawesome.com/182ae96ce8.js" crossorigin="anonymous"></script> <!-- bootstrap --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script> <script src="main.js"></script> </body> </html>
''' Neste código é feita a aproximação dos ângulos do pêndulo duplo com o método RK3, que é comparada com a interpolação por splines cubicas de pontos selecionados dessa aproximação. ''' import numpy as np import math import matplotlib.pyplot as plt from tabulate import tabulate import cubic_splines as sp # Altere as condições iniciais e parametros como desejar # Busque no código por "Condições iniciais" MODELO = "pendulo" ########### RUNGE KUTTA 3a ORDEM ########### def RK3(f, tk, yk, h): k1 = h*f(tk, yk) k2 = h*f(tk + h/2, yk+ k1/2) k3 = h*f(tk + 3*h/4, yk + 3*k2/4) yk_1 = yk + (2*k1 + 3*k2 + 4*k3)/9 return yk_1 # --------------------- PENDULO DUPLO --------------------- ############ CONDIÇÕES INICIAIS ########### angle1 = 90 angle2 = 60 THETA1_0 = np.radians(angle1) THETA2_0 = np.radians(angle2) THETA1P_0 = 0 THETA2P_0 = 0 ############## PARÂMETROS ################ M1 = 0.2 M2 = 0.2 L1 = 0.84 L2 = 0.84 G = 9.8 ############# FUNÇÃO DERIVADA ########### def f(t, y): # print(y) theta1, theta2, theta1p, theta2p = y # Retorna a derivada de cada componente de y # [theta1, that2, theta1p, theta2p] -> [theta1p, theta2p, theta1pp, theta2pp] return np.array([theta1p, theta2p, ( -G*(2*M1 + M2)*np.sin(theta1) -M2*G*np.sin(theta1 - 2*theta2) -2*np.sin(theta1 - theta2) * M2*(theta2p**2*L2 + theta1p**2*L1 * np.cos(theta1-theta2))) / (L1 * (2*M1 + M2 -M2*np.cos(2*theta1 - 2*theta2))), (2*np.sin(theta1 - theta2) * (theta1p**2*L1*(M1+M2) + G*(M1+M2)*np.cos(theta1) + theta2p**2*L2 *M2*np.cos(theta1-theta2))) / (L2 * (2*M1 + M2 -M2*np.cos(2*theta1 - 2*theta2)))]) if MODELO == "pendulo": ####### APROXIMAÇÃO PENDULO DUPLO ######## t0 = 0 y0 = np.array([THETA1_0, THETA2_0, THETA1P_0, THETA2P_0]) h = 0.01 n = 3000 # Iterar para calcular a posição em vários passos de tempo usando RK3 t_values_rk = [t0] y1_values_rk = [y0[0]] # Valores de theta1 y2_values_rk = [y0[1]] # Valores de theta2 num_steps = n y = y0 t = t0 ##### LOOP ##### for _ in range(num_steps): y = RK3(f, t, y, h) t += h t_values_rk.append(t) y1_values_rk.append(y[0]) y2_values_rk.append(y[1]) ####### APROXIMAÇÃO PENDULO DUPLO DIF ######## # Pequena mudança nas condicoes iniciais t0 = 0 dif = 1.001 # Multiplicador (+0.1%) THETA1_0_dif = THETA1_0 * dif THETA2_0_dif = THETA2_0 * dif # Velocidade inciial permance nula THETA1P_0_dif = THETA1P_0 THETA2P_0_dif = THETA2P_0 y0 = np.array([THETA1_0_dif, THETA2_0_dif, THETA1P_0_dif, THETA2P_0_dif]) t_values_rk = [t0] y1_values_rk_dif = [y0[0]] # Valores de theta1 y2_values_rk_dif = [y0[1]] # Valores de theta2 num_steps = n y = y0 t = t0 ##### LOOP ##### for _ in range(num_steps): y = RK3(f, t, y, h) t += h t_values_rk.append(t) y1_values_rk_dif.append(y[0]) y2_values_rk_dif.append(y[1]) # Aproximação para os 1000 primeiros pontos, utilizando 20 pontos para interpolação n_points = 50 y1_splines = sp.get_splines(t_values_rk[:1000:n_points], y1_values_rk[:1000:n_points]) y1_values_splines, t_splines = sp.spline_aproximation(t_values_rk[:1000:n_points], y1_splines, n_points) # Plotar theta1 com e sem variacao das condicoes iniciais plt.figure(figsize=(8, 6)) plt.plot(t_values_rk[:1000], y1_values_rk[:1000], label= f'RK3 sem interpolação (1000 pontos)') plt.plot(t_splines, y1_values_splines, label=f'RK3 com interpolaçao por splines de 20 pontos', linestyle='--') plt.xlabel('Tempo (s)') plt.ylabel('Ângulo (rad)') plt.title('Interpolação do ângulo theta1 por splines cubicas utilizando 20 pontos') plt.legend() plt.grid(True) plt.show() # Aproximação para os 1000 primeiros pontos, utilizando 100 pontos para interpolação n_points = 10 y1_splines = sp.get_splines(t_values_rk[:1000:n_points], y1_values_rk[:1000:n_points]) y1_values_splines, t_splines = sp.spline_aproximation(t_values_rk[:1000:n_points], y1_splines, n_points) # Plotar theta1 com e sem variacao das condicoes iniciais plt.figure(figsize=(8, 6)) plt.plot(t_values_rk[:1000], y1_values_rk[:1000], label= f'RK3 sem interpolação (1000 pontos)') plt.plot(t_splines, y1_values_splines, label=f'RK3 com interpolaçao por splines de 100 pontos', linestyle='--') plt.xlabel('Tempo (s)') plt.ylabel('Ângulo (rad)') plt.title('Interpolação do ângulo theta1 por splines cubicas utilizando 100 pontos') plt.legend() plt.grid(True) plt.show()
import React, { useState } from "react"; import { OpenAI } from "openai"; import rawPrompt from "../src/prompt.txt"; function Chatbot() { const [input, setInput] = useState(""); const [messages, setMessages] = useState([]); const apiKey = import.meta.env.VITE_API_KEY; const openai = new OpenAI({ apiKey: apiKey, dangerouslyAllowBrowser: true }); const handleInputChange = (e) => { setInput(e.target.value); }; const handleSubmit = async (e) => { e.preventDefault(); if (input.length === 0) { return; } try { setMessages((prevMessages) => [ ...prevMessages, { content: input, sender: "user" }, ]); const userInputPrompt = input; // Replace with the path to your text file await readTextFileAndUseAsPrompt(userInputPrompt); setInput(""); } catch (error) { console.error("An error occurred:", error.message); } }; const readTextFileAndUseAsPrompt = async (userInputPrompt) => { try { // Fetch the file content using fetch API const response = await fetch(rawPrompt); // Assuming the file is in the same location as Chatbot.jsx if (!response.ok) { throw new Error( `Failed to fetch file prompt.txt: ${response.statusText}` ); } const fileContent = await response.text(); // Append user input prompt to the file content const prompt = `${fileContent}\n${userInputPrompt}`; // Call the OpenAI API with the prompt const aiResponse = await openai.chat.completions.create({ model: "gpt-4", messages: [{ role: "user", content: prompt }], }); // Update messages state with the AI response aiResponse.choices.forEach((messageResponse) => { setMessages((prevMessages) => [ ...prevMessages, { content: messageResponse.message.content, sender: "bot" }, ]); }); } catch (error) { console.error("Error reading or using the file content:", error); } }; const renderFormattedText = (text) => { return text.split("\n").map((line, index) => ( <p key={index} className="mb-1"> {line} </p> )); }; return ( <div className="bg-pink-100 max-h-screen flex flex-col w-4/5 rounded-lg my-6"> <h1 className="text-6xl text-center font-bold mb-4">Chat with EVITA</h1> <div className="flex-1 overflow-y-auto px-4 py-8"> {messages.map((message, index) => ( <div key={index} className={`mb-4 ${ message.sender === "user" ? "flex justify-end" : "flex justify-start" } `} > <div className={`max-w-md rounded-lg px-4 py-2 shadow-md ${ message.sender === "user" ? "bg-purple-400 text-white self-end" : "bg-white text-black self-start" }`} > <p className="text-xs font-bold mb-1"> {message.sender === "user" ? "You" : "Evita"} </p> {renderFormattedText(message.content)} </div> </div> ))} </div> <form className="flex items-center px-4 py-2 my-6" onSubmit={handleSubmit} > <input type="text" className="flex-1 border border-gray-300 rounded-lg py-2 px-4 mr-4 focus:outline-none focus:border-blue-500 shadow-md" placeholder="Type your message..." value={input} onChange={handleInputChange} /> <button type="submit" className="bg-purple-400 text-white px-4 py-2 rounded-lg hover:bg-purple-600 shadow-md outline-none" > Send </button> </form> </div> ); } export default Chatbot;
---@class Opts ---@field name string: a string with the command name ---@field fargs table: containing the command arguments split by whitespace (see |<f-args>|) ---@field bang boolean: `true` if the command was executed with a `!` modifier (see |<bang>|) ---@field line1 number: starting line number of the command range (see |<line1>|) ---@field line2 number: final line number of the command range (see |<line2>|) ---@field range number: number of items in the command range: 0, 1, or 2 (see |<range>|) ---@field count number: any count supplied (see |<count>|) ---@field smods table: a table containing the command modifiers (see |<mods>|) vim.api.nvim_create_user_command("OpenGithubRepo", function(_) local ghpath = vim.api.nvim_eval("shellescape(expand('<cfile>'))") local formatpath = ghpath:sub(2, #ghpath - 1) local repourl = "https://www.github.com/" .. formatpath vim.fn.system({ "xdg-open", repourl }) end, { desc = "Open Github Repo", force = true, }) ---@param opts Opts vim.api.nvim_create_user_command("OpenLine", function(opts) local where = opts.fargs[1] if where == "below" then vim.cmd("normal mzo`z") else vim.cmd("normal mzO`z") end end, { desc = "Better open line", force = true, nargs = 1, }) vim.api.nvim_create_user_command("MkOpenSrc", function(_) local srcpath = "src/" .. vim.api.nvim_eval("expand('<cWORD>')") vim.cmd("e " .. srcpath) end, { desc = "Open code block source file", force = true, nargs = "?", }) vim.api.nvim_create_user_command("BiPolar", function(_) local moods_table = { ["true"] = "false", ["false"] = "true", ["True"] = "False", ["False"] = "True", ["on"] = "off", ["off"] = "on", ["On"] = "Off", ["Off"] = "On", ["Up"] = "Down", ["Down"] = "Up", ["up"] = "down", ["down"] = "up", ["cold"] = "hot", ["hot"] = "cold", ["Cold"] = "Hot", ["Hot"] = "Cold", ["open"] = "close", ["close"] = "open", ["Open"] = "Close", ["Close"] = "Open", ["opened"] = "closed", ["closed"] = "opened", ["Opened"] = "Closed", ["Closed"] = "Opened", ["sun"] = "moon", ["moon"] = "sun", ["Sun"] = "Moon", ["Moon"] = "Sun", ["water"] = "fire", ["fire"] = "water", ["Water"] = "Fire", ["Fire"] = "Water", ["good"] = "bad", ["Good"] = "Bad", ["bad"] = "good", ["Bad"] = "Good", } local cursor_word = vim.api.nvim_eval("expand('<cword>')") if moods_table[cursor_word] then vim.cmd("normal ciw" .. moods_table[cursor_word] .. "") end end, { desc = "Switch Moody Words", force = true }) -- turn table to a function returning a table -- like for completely erasing default options in plugin spec instead of merging tables -- put cursor on top of starting curly brace of table vim.api.nvim_create_user_command("WrapTableLuaFunc", function(_) -- stylua: ignore vim.cmd("normal %") -- vim.cmd("s/,//e") -- Not right, Do not know why I had this here ?? local tempmacro = [[aendifunction(lareturn]] local tempreg = vim.fn.getreg("k") vim.fn.setreg("k", tempmacro) vim.cmd("normal @k") vim.fn.setreg("k", tempreg) end, { desc = "Wrap lua table in a function and return it", force = true, }) vim.api.nvim_create_user_command("JustForExample", function(_) print("You can delete commands you don't need / want") end, { desc = "Example for deleting commands", force = true, })
package se.sundsvall.precheck.api.model; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanConstructor; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanEquals; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanHashCode; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanToString; import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSetters; import static com.google.code.beanmatchers.BeanMatchers.registerValueGenerator; import static java.time.LocalDate.now; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.MatcherAssert.assertThat; import java.time.LocalDate; import java.util.Map; import java.util.Random; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; class PreCheckResponseTest { @BeforeAll static void setup() { registerValueGenerator(() -> now().plusDays(new Random().nextInt()), LocalDate.class); } @Test void testBean() { assertThat(PreCheckResponse.class, allOf( hasValidBeanConstructor(), hasValidGettersAndSetters(), hasValidBeanHashCode(), hasValidBeanEquals(), hasValidBeanToString())); } @Test void testCreatePattern() { final var deliverable = false; final var futureDeliverable = true; final var plannedDevelopmentDate = LocalDate.now(); final var metaData = Map.of("key1", "value1", "key2", "value2"); PreCheckResponse preCheckResponse = PreCheckResponse.create() .withDeliverable(deliverable) .withFutureDeliverable(futureDeliverable) .withPlannedDevelopmentDate(plannedDevelopmentDate) .withMetaData(metaData); assertThat(preCheckResponse).isNotNull().hasNoNullFieldsOrPropertiesExcept("deliverable", "futureDeliverable"); assertThat(preCheckResponse.isDeliverable()).isEqualTo(deliverable); assertThat(preCheckResponse.isFutureDeliverable()).isEqualTo(futureDeliverable); assertThat(preCheckResponse.getPlannedDevelopmentDate()).isEqualTo(plannedDevelopmentDate); assertThat(preCheckResponse.getMetaData()).isEqualTo(metaData); } @Test void testCreateWithNoValueSet() { assertThat(PreCheckResponse.create()).hasAllNullFieldsOrPropertiesExcept("deliverable", "futureDeliverable") .hasFieldOrPropertyWithValue("deliverable", false) .hasFieldOrPropertyWithValue("futureDeliverable", false); } }
# from abc import ABC, abstractmethod # class Person(ABC): # def __init__(self,name,age,gender): # self.name = name # self.age = age # self.gender = gender # def display_info(self): # return f"Name: {self.name} \nAge: {self.age} \nGender: {self.gender}" # @abstractmethod # def random(self): # pass # class Employee(Person): # def __init__(self,name,age,gender,employee_id, department): # super().__init__(name,age,gender) # self.employee_id = employee_id # self.department = department # def manage_task(self): # print(f"Tasks managed") # class Student(Person): # def __init__(self,name,age,gender, student_id, major): # super().__init__(name,age,gender) # self.student_id = student_id # self.major = major # def submit_assignment(self, submission_date, deadline): # if submission_date <= deadline: # print(f"Your assingment has been submitted.") # else: # print(f"You have delaied {submission_date - deadline} days to submit the assingment!!!") # def random(self): # pass # class Admin(Employee): # def __inti__(self, name,age,gender,employee_id, department, admin_id): # super().__init__(name,age,gender,employee_id, department) # self.admin_id = admin_id # def handle_request(self, n): # print(f"{n} requests handled") # def random(self): # pass # class Teacher(Employee): # def __init__(self, name, age, gender, employee_id, department, teacher_id, designation, subject_taght): # super().__init__(name, age, gender, employee_id, department) # self.teacher_id = teacher_id # self.designation = designation # self.suject_taught = subject_taght # def conduct_class(self): # print(f"{self.designation} {self.name} is teaching {self.suject_taught}") # def random(self): # pass # class Classroom: # def __init__(self): # self.teacher = None # self.students = [] # def display_class_info(self): # return f"Class teacher: {self.teacher.name} \nNo of students: {len(self.students)}" # def add_teacher(self, teacher): # self.teacher = teacher # def add_student(self, student): # self.students.append(student) # def conduct_class_session(self): # for i in self.students: # if i == self.students[-1]: # print(i.name, end= " ") # else: # print(i.name, end=", ") # print(f"is attending the OOP class being taken by {self.teacher.designation} {self.teacher.name}.") # teacher = Teacher("Swakhar" , 23, "male", 2579234, "Data Science", 23456754, "Professor", "OOP") # teacher.conduct_class() # stu_1 = Student("Ashik", 12, "male", 38493, "OOP") # stu_2 = Student("Tawsif", 21, "female", 23245, "PPO") # class_11 = Classroom() # class_11.add_teacher(teacher) # class_11.add_student(stu_1) # class_11.add_student(stu_2) # class_11.display_class_info() # class_11.conduct_class_session() # person = Person("abvjc", 232, "male") # print(person.display_info()) class Person: def __init__(self, name:str, age:int, gender:str): self.name = name self.age = age self.gender = gender def display_info(self): print(f"Name: {self.name} \nAge: {self.age} \nGender: {self.gender}") class Employee(Person): def __init__(self, name:str, age:int, gender:str, employee_id:str, department:str): super().__init__(name, age, gender) self.emplayee_id = employee_id self.department = department def manage_tasks(self): print(f"Task Managed") class Student(Person): def __init__(self, name:str, age:int, gender:str, student_id:str, major:str): super().__init__(name, age, gender) self.student_id = student_id self.major = major def submit_assignment(self, submission_date, deadline): deadline = list(map(int, deadline.split("/"))) deadline_days = (deadline[1]*30) + deadline[0] submission_date = list(map(int, submission_date.split("/"))) submission_date_days = (submission_date[1]*30) + submission_date[0] if (submission_date_days <= deadline_days): print(f"Your assignment has been submited!") else: print(f"Your submission date has passed!!! \nYou are {submission_date_days - deadline_days} days late!!!") def __str__(self): return f"Student name: {self.name} \nID: {self.student_id} \nAge: {self.age} \nGender: {self.gender} \nMajor: {self.major}" def __repr__(self): return f"Student name: {self.name}; ID: {self.student_id}" class Admin(Employee): def __init__(self, employee_id:str, department:str, name:str, age:int, gender:str, admin_id:str): super().__init__(employee_id, department, name, age, gender) self.admin_id = admin_id def handle_requests(n): print(f"{n} requests handled.") class Teacher(Employee): def __init__(self, name:str, age:int, gender:str, employee_id:str, department:str, teacher_id:str, designation:str, subject_taught:str): super().__init__( name, age, gender, employee_id, department) self.teacher_id = teacher_id self.designation = designation self.subject_taught = subject_taught def conduct_class(self): print(f"{self.designation} {self.name} is teaching {self.subject_taught}.") def __str__(self): return f"Teacher name: {self.name} \nID: {self.teacher_id} \nAge: {self.age} \nGender: {self.gender} \nEmplyee ID: {self.emplayee_id} \nDepartment: {self.department} \nDesignation: {self.designation} \nSubject taught: {self.subject_taught}" def __repr__(self): return f"Teacher name: {self.name}; ID: {self.teacher_id}; Designation: {self.designation}; Department: {self.department}; Subject: {self.subject_taught}" class Classroom: #def __init__(self, teacher:Teacher, *students:Student): #self.teacher = teacher #self.students = [stu for stu in students] def __init__(self): self.teacher = None self.students = [] def display_class_info(self): print(f"Teacher Info: \n{self.teacher}") print(f"\nStudents Info:") #print(*self.students) for i in range(len(self.students)): print(f"{i+1}. {self.students[i]}") def add_teacher(self, teacher:Teacher): self.teacher = teacher def add_student(self, student:Student): self.students.append(student) def conduct_class_session(self): for stu in self.students: if stu == self.students[-1]: print(stu.name, end=" ") else: print(stu.name, end=", ") print(f"are attending the OOP class being taken by {self.teacher.designation} {self.teacher.name}.") #def conduct_class_session(self): #print(*self.students, sep="\n\n") #print(f"are attending the OOP class being taken by {self.teacher.designation} {self.teacher.name}") class_1 = Classroom() t_1 = Teacher("DMF", 46, "Male", "39874", "Data Science", "193479", "Professor", "Machine Learning") class_1.add_teacher(t_1) s_1 = Student("Musfique", 21, "Male", "0152330101", "Data Science") s_2 = Student("Tasfiya", 21, "Female", "0152330116", "Data Science") class_1.add_student(s_1) class_1.add_student(s_2) class_1.display_class_info() class_1.conduct_class_session()
<?php /** * PHPMovieDB is a movie database program. * * PHP version 7.4 and 8.1 * * LICENSE: This source file is subject to version 3.01 of the PHP license * that is available through the world-wide-web at the following URI: * http://www.php.net/license/3_01.txt. If you did not receive a copy of * the PHP License and are unable to obtain it through the web, please * send a note to [email protected] so we can mail you a copy immediately. * * @category Movie_Database * @package PHPMovieDB * @author Ed <[email protected]> * @copyright 2005-2020 Ed * @license http://www.gnu.org/licenses/ GNU * @link http://pear.php.net/package/PackageName */ require_once dirname(__FILE__) . "/DatabaseException.class.php"; require_once dirname(__FILE__) . "/ResultSet.class.php"; /** * Database object Doc Comment * * Database object connects to the database and executes queries on it * * @category Database_Class * @package Database. * @author Leslie Kleuver <[email protected]> * @license http://www.gnu.org/licenses/ GNU * @link http://localhost/ */ class Database { var $UNKNOWN_DATABASE_ERROR = 100; var $DATABASE_CONNECTION_ERROR = 101; var $DATABASE_SELECTION_ERROR = 102; var $SQL_SYNTAX_ERROR = 103; var $db; var $unbuffered; var $counter; // Counter for number of queries done. var $error = false; var $errormessage = "Undefined error"; /** * Database constructor * * @param string $settings Username, Password, Databasename, Host. * * @throws DatabaseException. * * @return this. */ function __construct($settings) { return $this->init($settings['user'], $settings['pass'], $settings['name'], $settings['host']); } /** * Destruct database construct * * @return Close Database. */ function __destruct() { mysqli_close($this->db); } /** * Database initialization * * @param string $user database user. * @param string $pasw database password. * @param string $name database name. * @param string $host database host. * * @throws DatabaseException * * @return this. */ function init($user, $pasw, $name, $host) { //initialize values to their defaults. $this->unbuffered = false; //connect to database. $this->db = mysqli_connect($host, $user, $pasw); // If anything goes wrong. if ($this->db === false) { $this->error = true; $this->errormessage = mysqli_error($this->db); } $this->selectDatabase($name); return $this; } /** * Database selection * * @param string $name database name. * * @throws DatabaseException * * @return selected database. */ function selectDatabase($name) { mysqli_select_db($this->db, $name); // If anything goes wrong. if (mysqli_select_db($this->db, $name) === false) { $this->error = true; $this->errormessage = mysqli_error($this->db); } } /** * Query the database * * @param string $sql sql query string. * * @throws DatabaseException * * @return ResultSet. */ function doQuery($sql) { $this->counter++; if ($this->unbuffered) { $resultmode = MYSQLI_USE_RESULT; } else { $resultmode = MYSQLI_STORE_RESULT; } $result = mysqli_query($this->db, $sql, $resultmode); // If anything goes wrong. if ($result === false) { $this->error = true; $this->errormessage = mysqli_error($this->db); } return new ResultSet($result); } /** * Alias select for doQuery * * @param string $sql sql query string. * * @return ResultSet. */ function select($sql) { return $this->doQuery($sql); } /** * Alias update for doQuery * * @param string $sql sql query string. * * @return ResultSet. */ function update($sql) { return $this->doQuery($sql); } /** * Alias insert for doQuery * * @param string $sql sql query string. * * @return ResultSet. */ function insert($sql) { return $this->doQuery($sql); } /** * Alias delete for doQuery * * @param string $sql sql query string. * * @return ResultSet. */ function delete($sql) { return $this->doQuery($sql); } /** * Get insertId from last query * * @return mysql insert. */ function insertId() { return mysqli_insert_id($this->db); } /** * Get number of affected rows * * @return mysql affected rows. */ function numberOfAffectedRows() { return mysqli_affected_rows($this->db); } /** * Get the amount of found rows * * @return array found rows. */ function getFoundRows() { $count = "SELECT FOUND_ROWS()"; $rs = $this->select($count); $row = $rs->getNextRow(); return $row["FOUND_ROWS()"]; } /** * Escape mysql query * * @param string $var sql query string. * * @return Escaped query string. */ function escape($var) { return "'" . mysqli_real_escape_string($var) . "'"; } } ?>
// SelectorForm.js import React, { useState, useLayoutEffect, useEffect } from 'react'; import InputElement from './InputElement'; import ListSelectElement from './ListSelectElement'; import styles from './InputElementContainer.module.css'; function InputElementContainer ({ containerName, containerData, containerid, defaultEnabled, onSetConfig, onSetEnabled}) { // store the default values for the input elements const defaultValues = containerData.map(option => option.default); // store the values of the input elements const [fieldValues, setFieldValues] = useState([{"key": "", "value": ""}]); // store the value of the checkbox const [checkboxValue, setCheckboxValue] = useState(defaultEnabled); // send the default values to the parent component useLayoutEffect(() => { onSetConfig(defaultValues, containerid); }, []); // if the field values change, send the new values to the parent component useEffect(() => { onSetConfig(fieldValues, containerid); }, [fieldValues]); // change the value of the field in the fieldValues container // (Stores the values of the container's input elements) function handleChangeFieldValue(fieldValue, id) { setFieldValues(prevFieldValues => { const updatedFieldValues = [...prevFieldValues]; const temp = updatedFieldValues.find((option, index) => option.key === id); temp !== undefined ? temp.value = fieldValue : updatedFieldValues.push({"key": id, "value": fieldValue}); return updatedFieldValues; }); } // change the value of the checkbox function handleCheckboxChange(e) { setCheckboxValue(c => e.target.checked); onSetEnabled(e.target.checked, containerid); } // change the value of the checkbox if function handleComponentClick() { setCheckboxValue(c => !checkboxValue); onSetEnabled(!checkboxValue, containerid); } // create the input elements for the container including the dependent input elements function getOptionsContainer() { let options = []; let idx = 0; containerData.forEach((option, index) => { if (option.inputType === 'text') { options.push( <InputElement key={option.configtext} fieldName={option.displaytext} configtext={option.configtext} changeFieldValue={handleChangeFieldValue} defaultValue={option.default} /> ); } else { options.push( <ListSelectElement key={option.configtext} fieldName={option.displaytext} options={option.options} configtext={option.configtext} changeFieldValue={handleChangeFieldValue} defaultValue={option.default} /> ); // check if the current option has dependent input elements // if so, create the dependent input elements if (option.dependentconfigs != undefined && option.dependentconfigs.length > 0) { option.dependentconfigs.forEach(dependentConfig => { dependentConfig.equals.forEach(e => { if (e == fieldValues.find(f => f.key === option.configtext)?.value ?? option.default) { if (dependentConfig.inputType === 'text') { options.push( <InputElement key={option.configtext + idx++} fieldName={dependentConfig.displaytext} configtext={dependentConfig.configtext} changeFieldValue={handleChangeFieldValue} defaultValue={dependentConfig.default} /> ); } else { options.push( <ListSelectElement key={option.configtext + idx++} fieldName={dependentConfig.displaytext} options={dependentConfig.options} configtext={dependentConfig.configtext} changeFieldValue={handleChangeFieldValue} defaultValue={dependentConfig.default} /> ); } } }); }); } } }); return options; } return ( <div className={styles.container}> <div className={styles.selectContainer} onClick={handleComponentClick}> <p className={styles.containerName}>{containerName}</p> <input name={containerName} className={styles.checkbox} type="checkbox" checked={checkboxValue} onChange={handleCheckboxChange}/> </div> <div className={styles.optionsContainer}> {checkboxValue && getOptionsContainer()} </div> </div> ); }; export default InputElementContainer;
import {createSlice, current, PayloadAction} from '@reduxjs/toolkit'; import {stat} from 'fs'; import {JokeCard} from '../components/Jokes/Joke/Joke'; import {Filter} from '../models/filter'; import {Joke} from '../models/joke'; import {ServerResponse} from '../models/serverResponse'; import {RootState} from './store'; const initialJoke: Joke = { id: '', categories: [], created_at: '', icon_url: '', url: '', value: '', likes: 0, dislikes: 0, }; export const jokeSlice = createSlice({ name: 'jokes', initialState: { loading: true, index: 0, total: 0, jokesList: new Array<Joke>(), jokeFilteredList: new Array<Joke>(), categories: new Array<string>(), selectedJoke: initialJoke, filter: { query: '', category: '', }, page: 0, end: 30, perPage: 30, hasMore: true, }, reducers: { fetchJokes: (state, action: PayloadAction<ServerResponse>) => { state.jokesList = action.payload.result.map(x => ({ ...x, likes:0, dislikes:0 })).filter(x => !x.categories.includes('religion'));//blasphemy state.jokeFilteredList = state.jokesList .slice( state.page, state.end, ); state.total = action.payload.total; state.loading = false; }, fetchCategories: (state, action: PayloadAction<string[]>) => { state.categories = action.payload; state.loading = false; }, filter: (state, action: PayloadAction<Filter>) => { state.filter = action.payload; state.page = 0; state.end = 30; const list = current(state.jokesList); const filteredList = list.filter((joke) => { return action.payload.query !== '' ? joke.value .toLowerCase() .includes(action.payload.query.toLowerCase()) : action.payload.category !== '' ? joke.categories.includes(action.payload.category) : true; }); state.jokeFilteredList = filteredList.slice(state.page, state.end); state.total = filteredList.length; state.hasMore = state.jokeFilteredList.length < state.total; }, loadMore: (state) => { state.page = state.page + state.perPage; state.end = state.end + state.perPage; state.hasMore = state.jokeFilteredList.length < state.total; state.jokeFilteredList = state.jokeFilteredList.concat( state.jokesList.slice(state.page, state.end), ); }, loading: (state) => { state.loading = true; }, detail: (state, action: PayloadAction<string>) => { const list = current(state.jokesList); const selectedJoke = list.find((x) => x.id === action.payload); if (selectedJoke) { state.selectedJoke = selectedJoke; state.index = state.jokeFilteredList.findIndex( (x) => x.id === selectedJoke.id, ); } }, like: (state, action: PayloadAction<Joke>) => { state.selectedJoke = action.payload; state.jokesList = state.jokesList.map((x) => { if (x.id === action.payload.id) { return action.payload; } return x; }); }, prev_joke: (state, action: PayloadAction<string>) => { const index = state.jokeFilteredList.findIndex( (x) => x.id === action.payload, ); state.selectedJoke = index < 0 ? state.jokeFilteredList[0] : state.jokeFilteredList[index - 1]; state.index = index - 1; }, next_joke: (state, action: PayloadAction<string>) => { const index = state.jokeFilteredList.findIndex( (x) => x.id === action.payload, ); state.selectedJoke = index >= state.total ? state.jokeFilteredList[state.total] : state.jokeFilteredList[index + 1]; state.index = index + 1; }, }, }); // export actions export const { fetchJokes, fetchCategories, filter, detail, like, next_joke, prev_joke, loading, loadMore, } = jokeSlice.actions; //export selectors export const jokesList = (state: RootState) => state.joke.jokeFilteredList; export const categoriesList = (state: RootState) => state.joke.categories; export const filterBody = (state: RootState) => state.joke.filter; export const selectedJoke = (state: RootState) => state.joke.selectedJoke; export const totalJokes = (state: RootState) => state.joke.total; export const JokeIndex = (state: RootState) => state.joke.index; export const appLoading = (state: RootState) => state.joke.loading; export const hasMore = (state: RootState) => state.joke.hasMore; //export reducer export default jokeSlice.reducer;
<template> <div> <van-nav-bar :left-text="$lang['返回']" left-arrow @click-left="onClickLeft" /> <div class="titleWrapper"> <h1 class="title">{{ $lang["高级商城"] }}</h1> <h2 class="methods" v-if="isShow">{{ $lang["登录"] }}</h2> <h2 class="methods" v-if="!isShow">{{ $lang["注册"] }}</h2> </div> <!-- 登陆 --> <div class="loginShop" v-if="isShow"> <div class="login"> <van-form @submit="onLogin"> <van-field v-model="nameLogin" :name="$lang['用户名']" :label="$lang['用户名']" :placeholder="$lang['用户名']" :rules="[{ required: true, message: this.$lang['请填写用户名'] }]" /> <van-field v-model="passwordLogin" type="password" :name="$lang['密码']" :label="$lang['密码']" :placeholder="$lang['密码']" :rules="[{ required: true, message: this.$lang['请填写密码'] }]" /> <div style="margin: 16px;"> <van-button round block type="danger" native-type="submit"> {{ $lang["立即登录"] }} </van-button> </div> </van-form> </div> <!-- 跳转注册 --> <div class="switherWrapper"> <span> {{ $lang["还没有账号"] }}? <i @click="register()">{{ $lang["注册"] }}</i> </span> </div> </div> <!-- 注册 --> <div class="register" v-else> <div class="login"> <van-form @submit="onRegister"> <van-field v-model="userRegister" name="pattern " :label="$lang['用户名称']" :placeholder="$lang['3~16位英文或数字']" :rules="[ { pattern, message: this.$lang['请输入符合规则的用户名'] }, ]" /> <van-field v-model="passwordRegister" type="password" name="validator" :label="$lang['密码']" :placeholder="$lang['6~18位英文或数字']" :rules="[ { validator, message: this.$lang['请输入符合规则的密码'] }, ]" /> <van-field v-model="passnewReg" type="password" :label="$lang['确认密码']" :placeholder="$lang['请再一次填写密码']" /> <div style="margin: 16px;"> <van-button round block type="danger" native-type="submit"> {{ this.$lang["立即注册"] }} </van-button> </div> </van-form> </div> <!-- 跳转注册 --> <div class="switherWrapper"> <span> <i @click="register()">{{ $lang["已经有账号"] }}</i> </span> </div> </div> </div> </template> <script> // import { Toast } from "vant"; export default { data() { return { nameLogin: "", passwordLogin: "", userRegister: "whm", passwordRegister: "whm123", passnewReg: "whm123", pattern: /^[a-zA-Z0-9_-]{3,16}$/, //用户名正则校验 isShow: true, registerflag: false }; }, inject:['loadCartList'] , created() { console.log(this.flag); }, methods: { onClickLeft() { this.$router.back(-1); }, // 注册密码正则校验 validator(val) { return /^[a-zA-Z0-9_-]{6,18}$/.test(val); }, register() { this.isShow = !this.isShow; }, login() { this.$request .login({ username: this.nameLogin, password: this.passwordLogin }) .then(res => { if (res.code == 0) { this.$store.commit("setToken", res.data.token); this.$store.dispatch("syncUpdateUserInfo"); this.loadCartList() //this.$store.dispatch("loadCartList"); this.$toast({ message: `${this.$lang["登录成功"]}` }); //if (this.flag) { // this.$router.push("/"); //} //else { this.$router.back(-1); // } // if (localStorage.getItem("cartInfo")) { // let localCart = JSON.parse(localStorage.getItem("cartInfo")); // localCart.forEach(item => { // this.$store.commit("saveCartList",item) // }); // } // console.log(this.$store.state.cartInfo); } else { this.$toast({ message: `${this.$lang["用户名或密码错误"]}` }); } }); }, // 登陆 onLogin() { this.login(); }, // 注册 onRegister() { if (this.passwordRegister != this.passnewReg) { this.$toast({ message: `${this.$lang["两次输入密码不同"] + "," + this.$lang["请重新输"]}` }); return; } this.$request .register({ username: this.userRegister, password: this.passnewReg }) .then(res => { console.log(res); if (res.code == 0) { this.nameLogin = this.userRegister; this.passwordLogin = this.passnewReg; this.$toast({ message: `${this.$lang["注册成功"]}` }); this.login(); } if (res.code == 1) { this.$toast({ message: `${this.$lang["该账号已注册"]}` }); } }); } } }; </script> <style lang="less" rel="stylesheet/less" scoped> .titleWrapper { padding: 50px 0px 20px; display: flex; justify-content: center; align-items: center; flex-direction: column; .title { font-size: 28px; font-weight: 600; color: #666; } .methods { font-size: 18px; font-weight: normal; } } .login { padding: 10px 16px; } .switherWrapper { font-size: 12px; color: #999; display: flex; justify-content: center; align-items: center; i { color: red; font-style: normal; } } </style>
<?php namespace App\Integrations\Nafath; use App\Integrations\BaseIntegration; use App\Integrations\CustomResponseDto; class NafathIntegration extends BaseIntegration { public function __construct($accessToken = null) { $baseApiUrl = config('integrations.nafath.base_url'); $headers = [ "APP-ID" => config('integrations.nafath.app_id'), "APP-KEY" => config('integrations.nafath.app_key'), ]; parent::__construct($baseApiUrl, $accessToken, $headers); } /** * @Request * local “ar” or “en”, default “ar” if not provided * requestId Unique identifier to identify the callback request, created by the client, most be UUID format. * nationalId targeted Member national id * service Service Type * please refer to the below table “service type table” * * @Response * STATUS CODE 200 { “transId”:” 3a4a3b26-3b8f-4d4f-90fe-d1a4ef834e8d”, “random”:” 80” } * transId Transaction Identifier * random Random number to be display to the end-user */ public function createRequest($requestUUID, $nationalId): CustomResponseDto { // api data $apiUrl = "/v1/mfa/request"; $queryParams = [ 'local' => "en", 'requestId' => $requestUUID ]; $body = [ 'service' => "OpenAccountWithoutBio", 'nationalId' => $nationalId ]; // api request return self::post($apiUrl,$body,$queryParams); } /** * @Reqeust * nationalId targeted Member national id * transId Transaction Id returned by Create request service * random Random Number returned by Create request service * * @Response * STATUS CODE 200 { “status”: "COMPLETED" } * status Request status [WAITING,EXPIRED,REJECTED,COMPLETED] */ public function checkRequestStatus($transactionId, $nationalId, $random):CustomResponseDto { // api data $apiUrl = "/v1/mfa/request/status"; $body = [ 'transId' => $transactionId, 'nationalId' => $nationalId, 'random' => $random ]; // api request return self::post($apiUrl,$body); } /** * This API is used to Retrieve ELM JWK, to Use the Key for token verification. * * @Response * STATUS CODE 200 {"keys": [ { "kty": "RSA", "e": "AQAB", "use": "sig","kid": "jwk-1234", "alg": "RS256", "n": "..." } ] } * kty Key type * kid Key ID * alg Algorithm * n Public key */ public function getJWT():CustomResponseDto { // api data $apiUrl = "/v1/mfa/jwt"; // api request return self::get($apiUrl); } }
import { Test, TestingModule } from '@nestjs/testing'; import { INestApplication } from '@nestjs/common'; import * as request from 'supertest'; import { AppModule } from '../../src/app.module'; import { getRepositoryToken } from '@nestjs/typeorm'; import { ExtensionInstallationWebhook } from '@/modules/extension-installations/extension-installations-webhook.entity'; import { getConnection, Repository } from 'typeorm'; import { webHookApprovedTransHP02, webHookCompletedTransHP02, webHookApprovedTransHP01, webHookCanceledTransHP01, } from '../mock/service/webhook.service.mock'; import { Enrollment } from '@/modules/enrollment/enrollment.entity'; import { sqlBaseInserts } from '../sql/base-sql'; let app: INestApplication; let extensionInstallationWebhook: Repository<ExtensionInstallationWebhook>; let enrollmentRepository: Repository<Enrollment>; const clearTables = async () => { const entities = [ 'extension_installations_webhooks', 'label_enrollment', 'enrollments', 'users', 'tokens', ]; for (const entity of entities) { const manager = getConnection(); await manager.query(`delete from "${entity}"`); } }; const createBaseData = async () => { for (const sqlBaseInsert of sqlBaseInserts) { const manager = getConnection(); await manager.query(sqlBaseInsert); } }; beforeAll(async () => { // await createBaseData(); }); beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [AppModule], }).compile(); extensionInstallationWebhook = module.get( getRepositoryToken(ExtensionInstallationWebhook), ); enrollmentRepository = module.get(getRepositoryToken(Enrollment)); app = module.createNestApplication(); await app.init(); clearTables(); }); afterEach(async () => { await app.close(); }); afterAll(async done => { setImmediate(done); }); it('should be able create enrollment', async () => { await request(app.getHttpServer()) .post('/extensions/1aa561d0-25ac-488c-b3c9-f997c8450e2a/webhook') .send(webHookApprovedTransHP02); await request(app.getHttpServer()) .post('/extensions/1aa561d0-25ac-488c-b3c9-f997c8450e2a/webhook') .send(webHookCompletedTransHP02); const extension = await extensionInstallationWebhook.find({ where: `payload ::jsonb @> '{"transaction":"${webHookApprovedTransHP02.transaction}"}'`, }); const enrollment = await enrollmentRepository.findOne({ where: { transactionId: webHookApprovedTransHP02.transaction }, }); expect(extension[0].response).toBe('approved'); expect(extension[1].response).toBe('completed'); expect(enrollment.transactionId).toBe(enrollment.transactionId); expect(enrollment.status).toBe('active'); }); it('should be able create enrollment', async () => { await request(app.getHttpServer()) .post('/extensions/1aa561d0-25ac-488c-b3c9-f997c8450e2a/webhook') .send(webHookApprovedTransHP02); await request(app.getHttpServer()) .post('/extensions/1aa561d0-25ac-488c-b3c9-f997c8450e2a/webhook') .send(webHookCompletedTransHP02); await request(app.getHttpServer()) .post('/extensions/1aa561d0-25ac-488c-b3c9-f997c8450e2a/webhook') .send(webHookCompletedTransHP02); await request(app.getHttpServer()) .post('/extensions/1aa561d0-25ac-488c-b3c9-f997c8450e2a/webhook') .send(webHookApprovedTransHP01); await request(app.getHttpServer()) .post('/extensions/1aa561d0-25ac-488c-b3c9-f997c8450e2a/webhook') .send(webHookCanceledTransHP01); const extension = await extensionInstallationWebhook.find({ where: `payload ::jsonb @> '{"transaction":"${webHookApprovedTransHP02.transaction}"}'`, }); const enrollmentTransHP02 = await enrollmentRepository.findOne({ where: { transactionId: webHookApprovedTransHP02.transaction }, }); const enrollmentTransHP01 = await enrollmentRepository.findOne({ where: { transactionId: webHookApprovedTransHP01.transaction }, }); expect(extension[0].response).toBe('approved'); expect(extension[1].response).toBe('completed'); expect(enrollmentTransHP02.transactionId).toBe( enrollmentTransHP02.transactionId, ); expect(enrollmentTransHP01.status).toBe('canceled'); expect(enrollmentTransHP02.status).toBe('active'); });
import { compare, hash } from "bcryptjs"; import { sign, verify } from "jsonwebtoken"; import User from "../models/user_model"; import http_response from "../helpers/http_response"; const sign_up = async (body) => { try { let { name, email, password } = body; if (password.length <= 4) return http_response.error_response({ message: "Senha ter mais de 4 caracteres" }) password = await hash(password, 15) await new User({ name, email, password }).save() return http_response.success_response({ message: "Usuário criado" }) } catch (error) { if (error.errors) { const errors = JSON.parse(JSON.stringify(error.errors)) let message = "" Object.keys(body).forEach((key) => { if (errors[key]) message = message + errors[key].message + "\n" }) return http_response.error_response({ message }) } if (error.code === 11000) return http_response.error_response({ message: "E-mail já cadastrado" }) return http_response.error_response({ message: JSON.stringify(error) }) } } const sign_in = async (body) => { try { const { email, password } = body; const user = await User.findOne({ email }) if (!user) return http_response.error_response({ message: "Usuário não encontrado" }) const password_valid = await compare(password, user.password); if (!password_valid) return http_response.error_response({ message: "Email e/ou senha inválidos" }) const token = sign({ user }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_REFRESH_EXPIRATION }); return http_response.success_response({ message: "sucesso", token }) } catch (error) { return http_response.error_response({ message: JSON.stringify(error) }) } } const authorizer = (request, response, next) => { const token = request.headers.authorization if (!token) return response.status(401).send("Acesso negado. Token não enviado") try { const payload = verify(token, process.env.JWT_SECRET) if (!payload.user) return response.status(401).send("Token invalido") request.headers['user'] = payload.user return next() } catch (error) { return response.status(401).send("Token invalido") } } export default { authorizer, sign_in, sign_up }
import styles from "./alertbox.module.css"; import PropTypes from "prop-types"; import { useTranslation } from "react-i18next"; // import { useNavigate } from "react-router-dom"; import LoadingIndicator from "../../../components/doctors-div/components/loading-indicator/LoadingIndicator"; const AlertBox = (props) => { const { t } = useTranslation(); // const navigate = useNavigate(); const handleDismiss = () => { props.setIsVisible(false); if (props.isError.isError) { return; } else { props.navToConfirmApp(); } }; return ( <div className={ styles.alertBox + " " + `${props.isVisible ? styles.isShown : ""}` } > {props.isLoading && ( <div className={styles.indicator}> <LoadingIndicator className={styles.indicator} /> </div> )} {!props.isLoading && ( <> <div className={styles.alertTitle}> <h2>{t(`${props.isError?.msg?.title}`)}</h2> </div> <div className={styles.alertMsg}> {<h3>{t(`${props.isError?.msg?.msg}`)}</h3>} </div> <div className={styles.alertAction}> <button className="btn" onClick={handleDismiss}> {" "} {t("Ok")} </button> </div> </> )} </div> ); }; AlertBox.propTypes = { isVisible: PropTypes.bool, setIsVisible: PropTypes.func, isError: PropTypes.object, setIsError: PropTypes.func, isLoading: PropTypes.bool, setIsLoading: PropTypes.func, navToConfirmApp: PropTypes.func, }; export default AlertBox;
import {Injectable} from "@angular/core"; import {HttpClient, HttpHeaders} from "@angular/common/http"; import {Observable} from "rxjs"; import {global} from "./global"; @Injectable() export class UserService{ public url: string; public identity; public token; constructor( public _http: HttpClient ) { this.url = global.url; } test(){ return "Hola mundo desde service"; } /** * Método para registrar usuarios mandando por JSON los datos al BackEnd */ register(user): Observable<any>{ let params = this.getJSONParams(user); let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded'); return this._http.post(this.url+'register', params, {headers: headers}); } /** * Método para loguear usuarios mandando por JSON los datos al BackEnd */ signIn(user, gettoken = null): Observable<any>{ if(gettoken != null){ user.gettoken = 'true'; } let params = this.getJSONParams(user); let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded'); return this._http.post(this.url+'login', params, {headers: headers}); } /** * Método para borrar un usuario por su id (DELETE) */ delete(token,id){ let headers = new HttpHeaders() .set('Content-Type', 'application/x-www-form-urlencoded') .set('Authorization', token); return this._http.delete(this.url + 'user/' +id, {headers: headers}); } getJSONParams(user){ let json = JSON.stringify(user); return 'json=' + json; } update(token, user) : Observable<any>{ //Coger datos de user y convertirlos a jsonString let params = this.getJSONParams(user); console.log('Parámetros: ' + typeof (params) + ' Token: ' +typeof (token)); let headers = new HttpHeaders() .set('Content-Type', 'application/x-www-form-urlencoded') .set('Authorization',token); return this._http.put(this.url+'user/update', params, {headers: headers}); } /** * Método para sacar la identidad del usuario del local storage */ getIdentity(){ let identity = JSON.parse(localStorage.getItem('identity')); if (identity && identity != "undefined"){ this.identity = identity; }else{ this.identity = null; } return this.identity; } /** * Método para sacar el token del usuario del local storage */ getToken(){ let token = localStorage.getItem('token'); if (token && token != "undefined"){ this.token = token; }else{ this.token = null; } return this.token; } }
package kz.zhelezyaka.core; /* * Инвертирование строки при помощи рекурсии. * * Если длина входной строки input меньше или равна 1, * возвращается исходная строка. * Это базовый случай, который завершает рекурсию. * * Если длина входной строки больше 1, * метод вызывает сам себя с аргументом input.substring(1), * что означает подстроку, начиная с первого символа и до конца строки. * К результату рекурсивного вызова добавляется первый символ * исходной строки (input.charAt(0)). * * Пример выполнения: * reverseString("input") вызывает reverseString("nput") + "i". * reverseString("nput") вызывает reverseString("put") + "n". * reverseString("put") вызывает reverseString("ut") + "p". * reverseString("ut") вызывает reverseString("t") + "u". * reverseString("t") возвращает "t" (базовый случай). * * Затем результаты объединяются: * "t" + "u" = "tu" * "tu" + "p" = "tup" * "tup" + "n" = "tupn" * "tupn" + "i" = "tupni" * * */ public class RecursiveReverseString { public String reverseString(final String input) { return input.length() <= 1 ? input : reverseString(input.substring(1)) + input.charAt(0); } }
from model.Student import Student from model.Certification import Certification from validate.StudentValidate import StudentValidate class StudentC(Student): # constructor def __init__(self, citizenIdentity: int, candidateNumber: int, name: str, address: str, literatureScore: float, historyScore: float, geographyScore: float, cert: Certification = None): super().__init__(citizenIdentity, candidateNumber, name, address, cert) self.__literatureScore = literatureScore self.__historyScore = historyScore self.__geographyScore = geographyScore # getter & setter def setLiteratureScore(self, literatureScore: float): self.__literatureScore = literatureScore def setHistoryScore(self, historyScore: float): self.__historyScore = historyScore def setGeographyScore(self, geographyScore: float): self.__geographyScore = geographyScore def getLitSrc(self) -> float: return self.__literatureScore def getHistSrc(self) -> float: return self.__historyScore def getGeoSrc(self) -> float: return self.__geographyScore def getSATScore(self) -> float: return StudentValidate.CalculatorSATScore(self.getLitSrc(), self.getHistSrc(), self.getGeoSrc(), self.getCert()) #subject dictionary subDict = dict([(0, 'ngữ văn'), (1, 'lịch sử'), (2, 'địa lý')])
package day23_exceptions; import java.util.Scanner; public class C02Exceptions02 { /* Exceptions are strict rules inJava. They help developers not to do critical mistakes. for example you want to do division operation. you are not so good in Math. You think you can divide any two numbers. Indeed a number can not be divided by zero. In this case Java will "throw exception" and: i) explain the rule ii) stop execution of the code */ public static void main(String[] args) { System.out.println("divide(12,4) = " + divide(12, 4)); //3 System.out.println("divide(2,4) = " + divide(2, 4)); //0 System.out.println("divide(0,8) = " + divide(8, 0));//ArithmeticException: Java throws ArithmeticException when there is a critical mistake in MAth operations System.out.println(divideNumbers(64, 0)); System.out.println(getNumOfChars("Java")); System.out.println(getNumOfChars("")); System.out.println(getNumOfChars(null)); } //First way to handle exception: public static int divide(int a, int b){ if(b==0){ return 0; } return a/b; } //Second Way: "try - catch" block public static int divideNumbers(int a, int b) { int result = 0; try{ result = a/b; System.out.println("Hi"); // calismaz cunku exceptionu gorunce satiri atlayip catch'e gecer } catch (ArithmeticException e){ result = 0; } return result; } // Create a method that will get the number of chars in a given String //First Way: public static int getNumOfChars (String str){ if(str == null){ return 0; } return str.length(); } //Second Way: public static int numberOfChars(String str){ int result = 0; try { str.length(); }catch (NullPointerException e){ result = 0; } return result; } }
#pragma once #include <algorithm> #include <cstdlib> #include <iostream> #include <limits> #include <list> #include <string> #include <vector> #include <Eigen/Dense> #include "Directory.hpp" #include "Entry.hpp" class Viewer_conic { public: // list of entries std::list<Entry> entries; bool m_show_axis = true; // true to display the axis bool m_show_grid = false; // true to display a grid bool m_show_value = false; // true to display the value of each object near the object bool m_show_label = false; // true to display the value of each object near the object bool m_show_xOy_plane = false; // show the gray xOy plane bool m_oriented_line = false; // true to add an arrow on a line to show its direction std::vector<float> m_background_color = { 1., 1., 1.}; // color of the background (RGB, from 0 to 255 per component) public: Viewer_conic(); ~Viewer_conic(); void display() const; void remove_name_doublons(); void render(const std::string &filename); /// \brief setter to enable / disable the option to show axis inline void show_axis(const bool show_axis_on) { m_show_axis = show_axis_on; } /// \brief setter to enable / disable the option to show a grid inline void show_grid(const bool show_grid_on) { m_show_grid = show_grid_on; } /// \brief setter to enable / disable the option to show the value of each /// object inline void show_value(const bool show_value_on) { m_show_value = show_value_on; } /// \brief setter to enable / disable the option to show the label of each /// object inline void show_label(const bool show_label_on) { m_show_label = show_label_on; } /// \brief setter to enable / disable the option to show the xOy plane inline void show_xOy_plane(const bool m_show_xOy_plane_on) { m_show_xOy_plane = m_show_xOy_plane_on; } /// \brief setter to enable / disable the option to show an arrow that /// specifies the line orientation inline void set_oriented_line(const bool oriented_line_on) { m_oriented_line = oriented_line_on; } /// \brief setter to choose the color of the background (default is white) inline void set_background_color(const unsigned char R, const unsigned char G, const unsigned char B) { m_background_color = {R / 255.f, G / 255.f, B / 255.f}; } inline int push_point(const Eigen::VectorXd &pt, const unsigned int &red = -1, const unsigned int &green = -1, const unsigned int &blue = -1) { return push_point(pt, "", red, green, blue); } int push_point(const Eigen::VectorXd &pt, std::string objectName = "", const unsigned int &red = -1, const unsigned int &green = -1, const unsigned int &blue = -1); inline int push_line(const Eigen::VectorXd &pt, const Eigen::VectorXd &dir, const unsigned int &red = -1, const unsigned int &green = -1, const unsigned int &blue = -1) { return push_line(pt, dir, "", red, green, blue); } int push_line(const Eigen::VectorXd &pt, const Eigen::VectorXd &dir, std::string objectName = "", const unsigned int &red = -1, const unsigned int &green = -1, const unsigned int &blue = -1); inline int push_direction(const Eigen::VectorXd &direction, const unsigned int &red = -1, const unsigned int &green = -1, const unsigned int &blue = -1) { return push_direction(direction, "", red, green, blue); } int push_direction(const Eigen::VectorXd &direction, std::string objectName = "", const unsigned int &red = -1, const unsigned int &green = -1, const unsigned int &blue = -1); inline int push_conic(const Eigen::VectorXd &c, const unsigned int &red = -1, const unsigned int &green = -1, const unsigned int &blue = -1) { return push_conic(c, "", red, green, blue); } int push_conic(const Eigen::VectorXd &c, std::string objectName = "", const unsigned int &red = -1, const unsigned int &green = -1, const unsigned int &blue = -1); };
import React, { useState } from "react"; import { Card, CardContent, Box, Avatar, Typography, Divider, CardActions, Button, Badge, FormControlLabel, Switch, CardHeader, Fab, Collapse, IconButton, } from "@mui/material"; import { red } from "@mui/material/colors"; import FavoriteIcon from "@mui/icons-material/Favorite"; import FavoriteBorderIcon from "@mui/icons-material/FavoriteBorder"; import { getInitials } from "src/utils/get-initials"; import { Stack } from "@mui/system"; import { StyledBadge } from "src/utils/styledBadge"; import api from "src/utils/api"; import { useRouter } from "next/router"; import { cloudinaryUpload } from "src/utils/cloudinary-upload"; import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; import styled from "@emotion/styled"; import { StudentProfileDetails } from "./student-profile-details"; import { MovementList } from "../movement/movement-list"; import { useTranslation } from "react-i18next"; import { PhoneEnabled } from "@mui/icons-material"; const ExpandMore = styled((props) => { const { expand, ...other } = props; return <IconButton {...other} />; })(({ theme, expand }) => ({ transform: !expand ? "rotate(0deg)" : "rotate(180deg)", marginLeft: "auto", transition: theme.transitions.create("transform", { duration: theme.transitions.duration.shortest, }), })); export const StudentProfile = ({ user, loggedUserProfile }) => { const { t } = useTranslation(); const [profile, setProfile] = useState(user); const [avatar, setAvatar] = useState(profile.avatar); const [likes, setLikes] = useState(profile.likes.length); const [liked, setLiked] = useState(profile.likes.includes(loggedUserProfile.id)); const [expanded, setExpanded] = useState(false); const [expandedMovements, setExpandedMovements] = useState(false); const router = useRouter(); const getThePage = (url) => { router.push(url); }; const switchAttendance = async (currentProfile) => { try { const updatedData = { is_in_school: !currentProfile.is_in_school, }; await api.put(`/student-profile/${currentProfile.id}/`, updatedData); setProfile({ ...currentProfile, is_in_school: !currentProfile.is_in_school }); // Handle successful update (e.g., update state or show a message) } catch (error) { console.error("Error updating student profile:", error); // Handle error appropriately } }; const handleAvatarClick = async () => { const fileInput = document.createElement("input"); fileInput.type = "file"; fileInput.accept = "image/*"; fileInput.onchange = async (e) => { const file = e.target.files[0]; const uploadedUrl = await cloudinaryUpload(file, profile); setAvatar(uploadedUrl); // Update avatar URL }; fileInput.click(); }; const like = async (receiver) => { const newData = { receiver: receiver, giver: loggedUserProfile.id }; try { if (!liked) { await api.post("/like/", newData); setLikes(likes + 1); } else { await api.delete("/unlike/", { data: newData }); // Correct way to send data in DELETE request setLikes(likes - 1); } setLiked(!liked); } catch (error) { console.log(error); } }; return ( <Card> <CardHeader avatar={ <> <Badge color="success" badgeContent={profile.events} max={999}> <Box sx={{ alignItems: "center", display: "flex", flexDirection: "column", }} > <Avatar src={avatar} // Assuming 'avatar' is part of the user profile data sx={{ height: 80, width: 80, }} onClick={ loggedUserProfile.role == "staff" ? handleAvatarClick : () => console.log("You have no permission") } alt={getInitials(`${profile.first_name} ${profile.last_name}`)} > {getInitials(`${profile.first_name} ${profile.last_name}`)} </Avatar> <Fab onClick={() => like(profile.id)} size="small" sx={{ zIndex: 100, mt: "-16px", color: red[500], alignItems: "center", display: "flex", flexDirection: "column", fontSize: "10px", }} > {liked ? ( <FavoriteIcon sx={{ fontSize: "20px" }} /> ) : ( <FavoriteBorderIcon sx={{ fontSize: "20px" }} /> )} {likes} </Fab> </Box> </Badge> </> } title={ <> <Typography gutterBottom variant="h6" sx={{ mr: 2 }}> {profile.first_name} {profile.last_name} <IconButton disabled={ loggedUserProfile.role == "staff" || profile.phone_number == "" || disabled } href={`tel: ${profile ? profile.phone_number : ""}`} > <PhoneEnabled color="success" /> </IconButton> </Typography> </> } subheader={ <> <Button onClick={() => getThePage("/team/" + profile.team.id)} size="small"> {profile.team?.teamName} </Button> {loggedUserProfile.role == "staff" && profile.room ? `Building: ${profile.room.building.buildingName}(${profile.room.number})` : ""} </> } action={ loggedUserProfile.role == "staff" ? ( <FormControlLabel control={ <Switch checked={profile.is_in_school} onChange={() => { switchAttendance(profile); }} name="jason" /> } /> ) : ( "" ) } /> <CardContent sx={{ p: 1 }}> <Box sx={{ alignItems: "center", display: "flex", flexDirection: "column", }} > <Stack direction="row" spacing={2}> {profile.team ? profile.team.staff.map((staff) => { return ( <div onClick={() => getThePage("/staff/" + staff.id)} sx={{ cursor: "pointer" }} key={staff.id} > <StyledBadge overlap="circular" anchorOrigin={{ vertical: "bottom", horizontal: "right" }} variant="dot" invisible={!staff.is_on_shift} > <Avatar alt={staff.first_name} src={staff.avatar} sx={{ width: 35, height: 35 }} /> </StyledBadge> </div> ); }) : ""} </Stack> </Box> </CardContent> {loggedUserProfile.role == "staff" ? ( <> <Divider /> <CardActions onClick={() => setExpanded(!expanded)} sx={{ px: 3 }}> <Typography variant="h6"> {/* {t("Info")} */} מידע </Typography> <ExpandMore expand={expanded} aria-expanded={expanded} aria-label="show more"> <ExpandMoreIcon /> </ExpandMore> </CardActions> <Collapse in={expanded} timeout="auto" unmountOnExit> <CardContent> <StudentProfileDetails user={profile} loggedUserProfile={loggedUserProfile} /> </CardContent> </Collapse> <Divider /> {/* <CardActions onClick={() => setExpandedMovements(!expandedMovements)} sx={{ px: 3 }}> <Typography variant="h6">Movements</Typography> <ExpandMore expand={expandedMovements} aria-expanded={expanded} aria-label="show more"> <ExpandMoreIcon /> </ExpandMore> </CardActions> <Collapse in={expandedMovements} timeout="auto" unmountOnExit> <CardContent> <MovementList user={profile} /> </CardContent> </Collapse> */} </> ) : ( "" )} </Card> ); }; export async function getStaticProps({ locale }) { return { props: { ...(await serverSideTranslations(locale, ["common"])), }, }; }
import asyncWrapper from "../../utilities/async-wrapper"; import AWS from "../../library/aws"; import DataModel from "../../helpers/DataModel"; import { CodeExecution } from "../../models/codeExecution.model"; import { TestCases } from "../../models/testcases.model"; import { DB_COLLECTIONS, DB_CONSTANTS } from "../../constants/index"; import EventEmitterHelper from "../../helpers/EventEmitter"; import Bluebird from "bluebird"; import axios from "axios"; /** * WORKING OF CODE EXECUTION ENGINE PRODUCER SIDE * * 1. Save the user's code on S3 * 2. Create a new doc in codeexecutiondetails with status="PROCESSING" * 3. Fetch all test cases for that lesson/code from testcasesdetails * 4. Fetch all test cases input/output files from S3 for that particular lesson or code * 5. Create an array of promises for each test case with all the requires fields like studentCode, stdin,output,totalTestCases,cpuTimeLimit,memoryLimit,stackLimit,timeAllotted,testCaseId, languageId,userEmail,lessonId,moduleId,courseId,docId * 6. Hit post request to for each element of above array to Judge0 to get token, and create a payload to send in CODE_EXECUTION queue, to poll for each test case result * 7. Afte all, these request from consumer side, enque a special message which will check if all the test cases are completed or not, and mark doc as completed */ /** * * @param userCode User's code coming from post request * @param userEmail Requested user email * @param moduleId ModuleId of the code being run * @param lessonId LessonId of the code being run * @param courseId CourseId of the code being run * @param languageId eg languageId of C language is 48 */ export const studentCodeDetails = ( userCode: string, userEmail: string, moduleId: string, lessonId: string, courseId: string, languageId: string ): Promise<any> => { let objQuery: any = new Object(); objQuery = { userEmail, moduleId, lessonId, courseId, status: "PROCESSING", }; const codeDetails = { userCode: JSON.stringify(userCode), userEmail, moduleId, lessonId, courseId, status: "PROCESSING", languageId, }; const CodeExecutionModel = new DataModel<CodeExecution>( DB_COLLECTIONS.CODE_EXECUTION_MODEL, DB_CONSTANTS.SEARCH_ACTION, DB_CONSTANTS.FIND_ONE, objQuery ); return CodeExecutionModel.exec().then((exists): Promise<any> => { if (!exists) { const CodeModel = new DataModel( DB_COLLECTIONS.CODE_EXECUTION_MODEL, DB_CONSTANTS.CREATE_ACTION ); CodeModel.setDocToUpdate(codeDetails); return CodeModel.exec().then((doc) => { return doc.save().then(() => { return doc; }); }); } else { console.log("ALREADY_IN_PROGRESS"); return Promise.resolve({ message: "ALREADY IN PROGRESS" }); } }); }; export const uploadContentDataToS3 = (dataObjS3: any): Bluebird<any> => { let { userCode, userEmail, moduleId, lessonId, courseId } = dataObjS3; if (!userCode || !userEmail || !moduleId || !lessonId || !courseId) { return Bluebird.resolve({ message: "No files received" }); } else { let dataObj: any = new Object(); dataObj.Bucket = "student-code-bucket-ss"; dataObj.Body = userCode; dataObj.Key = `${userEmail}/${courseId}/${moduleId + "_moduleId"}/${ lessonId + "_lessonId" }/userCode.txt`; return AWS.putObject(dataObj, `userCode.txt`) .then((res) => { return res; }) .catch((err) => { console.log(err); }); } }; export const getContentDataFromS3 = async ( dataObjS3: any, testCaseId: number ) => { let { courseId, moduleId, lessonId } = dataObjS3; let objData: any = {}; objData.bucketName = "student-code-bucket-ss"; const input = await AWS.promisifyGetAWSFileReadStream( objData.bucketName, `admin/${courseId}/${moduleId + "_moduleId"}/${ lessonId + "_lessonId" }/testcase${testCaseId}.txt` ); const output = await AWS.promisifyGetAWSFileReadStream( objData.bucketName, `admin/${courseId}/${moduleId + "_moduleId"}/${ lessonId + "_lessonId" }/output${testCaseId}.txt` ); const resultObj: any = new Object(); resultObj.stdin = Buffer.from(input.Body).toString("utf8"); resultObj.output = Buffer.from(output.Body).toString("utf8"); return resultObj; }; export const codeCompilationJudge0 = ( userCode: string, stdin: string, output: string, totalTestCases: number, cpuTimeLimit: string, memoryLimit: string, stackLimit: string, timeAllotted: string, testCaseId: number, languageId: string, userEmail: string, lessonId: string, moduleId: string, courseId: string, docId: string ) => { const response = axios({ method: "POST", url: "http://3.86.116.46/submissions", headers: { accept: "application/json", "content-type": "application/json", }, data: JSON.stringify({ language_id: languageId, source_code: userCode, cpu_time_limit: cpuTimeLimit, expected_output: output, memory_limit: memoryLimit, stack_limit: stackLimit, stdin: stdin, wall_time_limit: timeAllotted, }), }); return response .then((res: any) => { const payload: any = new Object(); payload.userEmail = userEmail; payload.totalTestCases = totalTestCases; payload.testCaseId = testCaseId; payload.lessonId = lessonId; payload.moduleId = moduleId; payload.courseId = courseId; payload.token = res.data.token; payload.docId = docId; const queuePayload = { data: payload, user: userEmail, q_name: "CODE_EXECUTION", process_type: "PARENT", dontWait: true, action: "codeExec", }; EventEmitterHelper.emitEvent("enqueue", queuePayload); return Promise.resolve(true); }) .catch((err: any) => { console.log(err); }); }; export const codeExecution = asyncWrapper((req, res): Bluebird<any> => { const { userCode, userEmail, lessonId, moduleId, courseId, languageId } = req.body; return uploadContentDataToS3(req.body) .then((resp) => { return resp; }) .then(() => { return studentCodeDetails( userCode, userEmail, moduleId, lessonId, courseId, languageId ).then((response): Promise<any> => { if (response.message === "ALREADY IN PROGRESS") { res.status(201).json({ message: "already in progress" }); return Promise.resolve({}); } else { return fetchTestCases(lessonId, moduleId, courseId, languageId).then( (testCasesResponse) => { //stdin input to be fetched from s3 admin let dataObj: any = { lessonId, moduleId, courseId }; const getAllFiles = testCasesResponse.exists.testCases[ languageId ].map((testCase: any, index: number) => { return getContentDataFromS3(dataObj, index + 1); }); return Bluebird.all(getAllFiles).then((allFiles) => { const prmExecutions = allFiles.map( (file: any, index: number) => { let execObj: any = new Object(); execObj.stdin = file.stdin; execObj.output = file.output; execObj.testCaseId = index + 1; execObj.totalTestCases = testCasesResponse.exists.testCases[languageId].length; execObj.cpuTimeLimit = testCasesResponse.exists.testCases[languageId][ index ].cpuTimeLimit; execObj.memoryLimit = testCasesResponse.exists.testCases[languageId][ index ].memoryLimit; execObj.stackLimit = testCasesResponse.exists.testCases[languageId][ index ].stackLimit; execObj.timeAllotted = testCasesResponse.exists.testCases[languageId][ index ].timeAllotted; execObj.studentCode = userCode; execObj.docId = response._id; return execObj; } ); const requestJudge0 = prmExecutions.map((exec) => { return codeCompilationJudge0( exec.studentCode, exec.stdin, exec.output, exec.totalTestCases, exec.cpuTimeLimit, exec.memoryLimit, exec.stackLimit, exec.timeAllotted, exec.testCaseId, languageId, userEmail, lessonId, moduleId, courseId, exec.docId.toString() ); }); const payload: any = new Object(); payload.userEmail = userEmail; payload.totalTestCases = testCasesResponse.exists.testCases[languageId].length; payload.lessonId = lessonId; payload.moduleId = moduleId; payload.courseId = courseId; payload.docId = response._id; payload.type = "MARKING_COMPLETED"; const queuePayload = { data: payload, user: userEmail, q_name: "CODE_EXECUTION", process_type: "PARENT", dontWait: true, action: "codeExec", }; return Promise.all(requestJudge0).then(() => { //Enqueuing a special message which will check if all the test cases are completed or not, and mark doc as completed EventEmitterHelper.emitEvent("enqueue", queuePayload); res.status(201).json({ message: "Code Execution Started!" }); return Promise.resolve(); }); }); } ); } }); }) .catch((err) => { let objQuery: any = new Object(); objQuery = { userEmail, moduleId, lessonId, courseId, }; const CodeExecutionModel = new DataModel<CodeExecution>( DB_COLLECTIONS.CODE_EXECUTION_MODEL, DB_CONSTANTS.UPDATE_ACTION, DB_CONSTANTS.FIND_ONE_UPDATE, objQuery ); CodeExecutionModel.setDocToUpdate({ $set: { status: "FAILED", error: err.message }, }); return CodeExecutionModel.exec(); }); }); export const setupTestCases = asyncWrapper((req, res) => { const { moduleId, lessonId, courseId, languageId, testCases } = req.body; let objQuery: any = new Object(); objQuery = { moduleId, lessonId, courseId, languageId, }; let testCasesObject: any = new Object(); testCasesObject = { moduleId, lessonId, courseId, languageId, testCases, }; const TestCasesModel = new DataModel<TestCases>( DB_COLLECTIONS.TEST_CASES_MODEL, DB_CONSTANTS.SEARCH_ACTION, DB_CONSTANTS.FIND_ONE, objQuery ); return TestCasesModel.exec().then((exists): Promise<any> => { if (!exists) { const TCasesModel = new DataModel( DB_COLLECTIONS.TEST_CASES_MODEL, DB_CONSTANTS.CREATE_ACTION ); TCasesModel.setDocToUpdate(testCasesObject); return TCasesModel.exec().then((doc) => { doc.save().then(() => { return res.status(201).json({ message: "OBJECT ADDED" }); }); }); } else { res.status(409).json({ message: "ALREADY EXISTS" }); return Promise.resolve({}); } }); }); export const fetchTestCases = ( lessonId: string, moduleId: string, courseId: string, languageId: string ) => { let objQuery: any = new Object(); objQuery = { moduleId, lessonId, courseId, languageId, }; const TestCasesModel = new DataModel<TestCases>( DB_COLLECTIONS.TEST_CASES_MODEL, DB_CONSTANTS.SEARCH_ACTION, DB_CONSTANTS.FIND_ONE, objQuery ); return TestCasesModel.exec().then((exists): Promise<any> => { if (!exists) { return Promise.resolve({ message: "OBJECT_NOT_FOUND" }); } else { return Promise.resolve({ exists }); } }); };
interface User { age: number; name: string; } // 변수에 인터페이스 활용 var seho: User = { age: 10, name: "세호", }; // 함수에 인터페이스 활용 function getUser(user: User) { console.log(user); } // const capt = { // name: "캡틴", // age: 100, // }; // getUser(capt); // 함수의 스펙(구조)에 인터페이스 활용 interface sumFunc { (a: number, b: number): number; } var sum: sumFunc; sum = function (a: number, b: number): number { return a + b; }; // 인덱싱 interface stringArray { [index: number]: string; } var arr: stringArray = ["a", "b", "c"]; // arr[0] = 10 // 딕셔너리 패턴 interface stringRegexDictionary { [key: string]: RegExp; } var obj: stringRegexDictionary = { cssFile: /\.css$/, jsFile: /\.js$/, }; // 인터페이스 확장 // interface Person { // name: string; // age: number; // } // interface Developer extends Person { // language: string; // } var capt: Developer = { language: "korean", name: "wonjae", age: 26, };
import { useState } from "react"; import reactLogo from "../assets/react.svg"; import viteLogo from "/vite.svg"; import { useParams } from "react-router-dom"; export default function About() { const [count, setCount] = useState(0); const { id } = useParams(); // const 변수명 return ( <> <div> <a href="https://vitejs.dev" target="_blank"> <img src={viteLogo} className="logo" alt="Vite logo" /> </a> <a href="https://react.dev" target="_blank"> <img src={reactLogo} className="logo react" alt="React logo" /> </a> </div> <h1>Vite + React with ID: {id}</h1> <div className="card"> <button data-testid="counterBtn" onClick={() => setCount((count) => count + 1)} > count is {count} </button> <p> Edit <code>src/App.tsx</code> and save to test HMR </p> </div> <p className="read-the-docs"> Click on the Vite and React logos to learn more </p> <ul> <li> <h3>Product 1</h3> <button>Add to cart</button> </li> <li> <h3>Product 2</h3> <button>Add to cart</button> </li> </ul> </> ); }
from django.shortcuts import render, redirect from django.core.mail import EmailMessage, get_connection from django.conf import settings from django.contrib import messages def send_email(request): """ Send email function connects the hosts details from settings.py and then set the details for the email to be sent to the host user. Assistance with django emails: https://opensource.com/article/22/12/django-send-emails-smtp A Success message is displayed once email is sent successfully. Help with EmailMessage class: https://stackoverflow.com/questions/59802624/contact-form-sending-emails-from-and-to-the-same-email-django """ if request.method == "POST": with get_connection( host=settings.EMAIL_HOST, port=settings.EMAIL_PORT, username=settings.EMAIL_HOST_USER, password=settings.EMAIL_HOST_PASS, use_tls=settings.EMAIL_USE_TLS ) as connection: name = request.POST.get("name") from_email = request.POST.get("email") recipient_list = [settings.EMAIL_HOST_USER, ] message = request.POST.get("message") EmailMessage(subject=name, body=message, from_email=from_email, to=recipient_list, reply_to=[from_email], connection=connection).send() messages.add_message(request, messages.SUCCESS, 'Your email was sent expect a reply in 24hrs.') return render(request, 'contact.html')
import { ChangeEvent, useState } from 'react'; export const useForm = <T extends object>(initialState: T) => { const [values, setValues] = useState(initialState); const handleInputChange = ({ target }: ChangeEvent<HTMLInputElement>) => { setValues({ ...values, [target.name]: target.value }); }; const reset = () => { setValues(initialState); }; return { values, reset, handleInputChange }; };
import React, { Component } from "react"; import { NavBar, List, InputItem, Grid, Icon } from "antd-mobile"; import { connect } from "react-redux"; import { sendMsg, readMsg } from "../../redux/actions"; // 进出场动画 import QueueAnim from "rc-queue-anim"; const Item = List.Item; class Chat extends Component { state = { content: "", // 要发送的内容 isShow: false, // 是否显示表情列表 }; // 在第一次render()之前回调 componentWillMount() { // 初始化表情列表数据 const emojis = [ "😀", "😁", "😂", "😃", "😄", "😅", "😆", "😉", "😊", "😋", "😎", "😍", "😘", "😗", "😙", "😚", "😇", "😐", "😑", "😶", "😏", "😣", "😥", "😮", "😯", "😪", "😫", "😴", "😌", "😛", "😜", "😝", "😒", "😓", "😔", "😕", "😲", "😷", "😖", "😞", "😟", "😤", "😢", "😭", "😦", "😧", "😨", "😬", "😰", "😱", "😳", "😵", "😡", "😠", ]; this.emojis = emojis.map((emoji) => ({ text: emoji })); // 初始化显示列表 window.scrollTo(0, document.body.scrollHeight); } componentWillUnmount() { // 在退出之前 // 发请求更新消息的未读状态 const from = this.props.match.params.userid; const to = this.props.user._id; this.props.readMsg(from, to); } componentDidUpdate() { // 更新显示列表 window.scrollTo(0, document.body.scrollHeight); } // 点击发送消息 handleSend = () => { // 收集数据 // 我的id const from = this.props.user._id; // 要发送的id const to = this.props.match.params.userid; // 发送内容 const content = this.state.content.trim(); // 发送请求(发消息) if (content) { this.props.sendMsg({ from, to, content }); // 清除输入数据 this.setState({ content: "", isShow: false }); } }; // 显示隐藏表情组件 toggleShow = () => { // 取反 const isShow = !this.state.isShow; // 设置值 this.setState({ isShow, }); // 如果显示 if (isShow) { // 异步手动派发 resize 事件,解决表情列表显示的 bug setTimeout(() => { window.dispatchEvent(new Event("resize")); }, 0); } }; render() { const { user } = this.props; const { users, chatMsgs } = this.props.chat; // 计算当前聊天的chatId const meId = user._id; if (!users[meId]) { // 如果还没有获取数据,直接不做任何显示 return null; } const targetId = this.props.match.params.userid; const chatId = [meId, targetId].sort().join("_"); // 对chatMsgs 进行过滤 const msgs = chatMsgs.filter((msg) => msg.chat_id === chatId); // 得到目标用户的header图片对像 const targetHeader = users[targetId].header; const targetIcon = targetHeader ? require(`../../assets/images/${targetHeader}.png`) : null; return ( <div id="chat-page"> <NavBar onLeftClick={() => { // 返回上一层路由 this.props.history.goBack(); }} icon={<Icon type="left"></Icon>} className="sticky-header" > {users[targetId].username} </NavBar> <List style={{ marginTop: 50, marginBottom: 50 }}> <QueueAnim type="scale" delay={100}> {msgs.map((msg) => { if (targetId === msg.from) { // 对方发给我的 return ( <Item key={msg._id} thumb={targetIcon}> {msg.content} </Item> ); } else { // 我发给对方 return ( <Item key={msg._id} className="chat-me" extra="我"> {msg.content} </Item> ); } })} </QueueAnim> </List> <div className="am-tab-bar"> <InputItem placeholder="请输入" onChange={(val) => this.setState({ content: val })} onFocus={() => { this.setState({ isShow: false }); }} value={this.state.content} extra={ <span> <span style={{ marginRight: 5 }} onClick={this.toggleShow}> 😁 </span> <span onClick={this.handleSend}>发送</span> </span> } /> {this.state.isShow ? ( <Grid data={this.emojis} columnNum={8} carouselMaxRow={4} isCarousel={true} onClick={(item) => { this.setState({ content: (this.state.content += item.text) }); }} /> ) : null} </div> </div> ); } } export default connect((state) => ({ user: state.user, chat: state.chat }), { sendMsg, readMsg, })(Chat);
#include "GamePlatform.h" #include <iostream> void GamePlatform::addGame(const Game& game) { if (gamesAmount >= MAX_GAMES_AMOUNT) { std::cout << "Platform is full!" << std::endl; return; } games[++gamesAmount] = game; } void GamePlatform::removeGame(size_t index) { if (index >= gamesAmount) { std::cout << "Invalid index!" << std::endl; return; } for (int i = index; i < gamesAmount - 1; i++) { Game temp = games[i]; games[i] = games[i + 1]; games[i + 1] = temp; } gamesAmount--; } void GamePlatform::printAllGames() const { for (int i = 0; i < gamesAmount; i++) { games[i].print(); } } void GamePlatform::printFreeGames() const { for (int i = 0; i < gamesAmount; i++) { if (games[i].isFree()) { games[i].print(); } } } const Game& GamePlatform::getGameByIndex(size_t index) const { if (index >= gamesAmount) { std::cout << "Invalid index!" << std::endl; return; } return games[index]; } const Game& GamePlatform::getCheapestGame() const { int cheapestIndex = 0; for (int i = 0; i < gamesAmount; i++) { if (games[i].getPrice() < games[cheapestIndex].getPrice()) { cheapestIndex = i; } } return games[cheapestIndex]; } const Game& GamePlatform::getMostExpensiveGame() const { int mostExpensiveIndex = 0; for (int i = 0; i < gamesAmount; i++) { if (games[i].getPrice() > games[mostExpensiveIndex].getPrice()) { mostExpensiveIndex = i; } } return games[mostExpensiveIndex]; } void GamePlatform::printGameByIndex(size_t index) const { getGameByIndex(index).print(); } void GamePlatform::printCheapestGame() const { getCheapestGame().print(); } void GamePlatform::printMostExpensiveGame() const { getMostExpensiveGame().print(); } void GamePlatform::saveToFile(const char* filePath) const { std::ofstream ofs(filePath); if (!ofs.is_open()) { std::cout << "Error!" << std::endl; return; } for (int i = 0; i < gamesAmount; i++) { games[i].writeToFile(ofs); } ofs.close(); } void GamePlatform::loadFromFile(const char* filePath) { std::ifstream ifs(filePath); if (!ifs) { std::cout << "Error!" << std::endl; return; } int i = 0; while (!ifs.eof()) { games[i].readFromFile(ifs); i++; } gamesAmount = i + 1; ifs.close(); }
import { CommonModule } from '@angular/common'; import { Component } from '@angular/core'; import { FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms'; import { Celular } from '../../models/celular'; import { CelularService } from '../../services/celular.service'; @Component({ selector: 'app-create', standalone: true, imports: [FormsModule, ReactiveFormsModule, CommonModule], templateUrl: './create.component.html', styleUrl: './create.component.css' }) export class CreateComponent { createCelularForm: FormGroup; celular: Celular = new Celular(); message: string = ""; constructor(private celularService: CelularService) { this.createCelularForm = new FormGroup({ marca: new FormControl("", [Validators.required]), fechaDeCompra: new FormControl("", [Validators.required]), anoLanzamiento: new FormControl("", [Validators.required]), precio: new FormControl("", [Validators.required, Validators.min(0)]), sistemaOperativo: new FormControl("", [Validators.required]), gama: new FormControl("", [Validators.required]) }); } createCelular(){ this.celular.marca = this.createCelularForm.get("marca")?.value; this.celular.fechaDeCompra = this.createCelularForm.get("fechaDeCompra")?.value; this.celular.anoLanzamiento = this.createCelularForm.get("anoDeLanzamiento")?.value; this.celular.precio = this.createCelularForm.get("precio")?.value; this.celular.sistemaOperativo = this.createCelularForm.get("sistemaOperativo")?.value; this.celular.gama = this.createCelularForm.get("gama")?.value; this.celularService.create(this.celular) .then(response => {this.message = "Celular creado con éxito";}) .catch(error => {this.message = "Error al crear el celular";}); } }
### -------------------------------- ### ### --- Intercalibration Fish DB --- ### ### -------------------------------- ### # ------------------------------- # date written: 22.04.22 # date last modified: 09.06.22 # Project: Evaluating European Broad River Types for Diatoms, Fish and Macrophytes # Purpose: Clean intercalibration fish DB # Notes: # ------------------------------- # setup ----------------------------------------------- options("box.path" = "~/R/box_modules/") pacman::p_load(data.table, magrittr, mapview, tidyr, mapview, lubridate, sf, dplyr, readxl, stringr) source("R/functions/add_typologies.R") # load data ------------------------------------------- bio <- read_excel("data/fish/original_data/mixed_intercalibration_didier_pont/raw/Catch selection final.xlsx") sites <- read_excel("data/fish/original_data/mixed_intercalibration_didier_pont/raw/Fishing_Occasion selection final.xlsx") taxontable <- readRDS("data/fish/2022-04-27_taxontable_fish.rds") typologies <- readRDS("data/all_typologies.rds") # prepare data ---------------------------------------- setDT(bio) setDT(sites) data <- sites[bio, on = "Site_code"] data <- data[, c("Site_code", "Date", "Species", "Number", "E_latitude", "E_longitude", "Country_code")] names(data) <- c("original_site_name", "date", "taxon","abundance", "y.coord", "x.coord", "country") data$date <- ymd(data$date) # sites <- unique(data, by = "original_site_name") # sites %<>% st_as_sf(coords = c("x.coord", "y.coord"), crs = 4326) # mapview::mapview(sites) data$EPSG <- 4326 data$data.set <- "interaclibration_fish_db" ## add season and year data[,c("season", "year") := .(case_when(month(date) %in% c(12,1,2) ~ "winter", month(date) %in% c(3,4,5) ~ "spring", month(date) %in% c(6,7,8) ~ "summer", month(date) %in% c(9,10,11) ~ "autumn"), year(date))] data$taxon <- str_replace_all(data$taxon, "_", "\\ ") TU <- unique(data$taxon) TU <- setdiff(TU, taxontable$original_name) #taxontable <- update_taxonomy2(TU) #saveRDS(taxontable, "data/fish/2022-04-22_taxontable_fish.rds") data%<>%rename("original_name" = taxon) data3 <- taxontable[data, on = "original_name"] data3[, site_id := .GRP, by = "original_site_name"] data3[, site_id := as.numeric(site_id)] data3[, date_id := .GRP, by = "date"] ## add leading zeros data3[, site_id := case_when( nchar(trunc(site_id)) == 1 ~ paste0("0000", site_id), nchar(trunc(site_id)) == 2 ~ paste0("000", site_id), nchar(trunc(site_id)) == 3 ~ paste0("00", site_id), nchar(trunc(site_id)) == 4 ~ paste0("0", site_id), nchar(trunc(site_id)) == 5 ~ paste0(site_id))] data3[, date_id := case_when( nchar(trunc(date_id)) == 1 ~ paste0("0000", date_id), nchar(trunc(date_id)) == 2 ~ paste0("000", date_id), nchar(trunc(date_id)) == 3 ~ paste0("00", date_id), nchar(trunc(date_id)) == 4 ~ paste0("0", date_id), nchar(trunc(date_id)) == 5 ~ paste0( date_id))] ## add gr_sample_id data3[,gr_sample_id := paste0("site_", site_id, "_date_", date_id, "_intercalibration_fish")] # - check that gr_sample_id matches sample_id ## reshape data data4 <- data3[, list( gr_sample_id, original_site_name, date, year, season, site_id, date_id, original_name, species, genus, family, order, class, phylum, kingdom, abundance, x.coord, y.coord, EPSG, country )] ## combine entries of same taxon data4[, lowest.taxon := ifelse(!is.na(species), species, ifelse(!is.na(genus), genus, ifelse(!is.na(family), family, ifelse(!is.na(order), order, ifelse(!is.na(class), class, ifelse(!is.na(phylum), phylum, kingdom))))))] data4[, abundance := as.numeric(abundance)] data4[, abundance := sum(abundance), by = c("gr_sample_id", "lowest.taxon")] data5 <- unique(data4, by = c("gr_sample_id", "lowest.taxon")) data5 <- add_typologies(data5) data5[country == "NO", least.impacted := TRUE] ## visual checks sites <- unique(data5, by = "site_id") |> st_as_sf(coords = c("x.coord", "y.coord"), crs = data5$EPSG[1]) # mapview(sites, zcol = "brt12") # mapview(sites, zcol = "ife") # mapview(sites, zcol = "bgr") mapview(sites, zcol = "least.impacted") # - subset to least impacted catchments data6 <- data5[least.impacted == TRUE] data6 <- data6[abundance != 0] sites <- unique(data6, by = "site_id") |> st_as_sf(coords = c("x.coord", "y.coord"), crs = data5$EPSG[1]) ## look for sites with different ID but same coordinates distances <- st_distance(sites) distances2 <- as.matrix(distances) diag(distances2) <- 999 (duplicate_sites <- which(distances2 < units::as_units(1, "m"))) data6[, richness := uniqueN(lowest.taxon), by = "gr_sample_id"] summary(data6$richness) hist(data6$richness) data7 <- data6[richness > 2] # - drop sites far removed from ECRINS river network data8 <- data7[distance < 300] updated_type_old <- readRDS("data/fish/original_data/mixed_intercalibration_didier_pont/2022-04-22_updated_type.rds") ## how many sites in data8: 314 uniqueN(data8$site_id) ## sites covered in updated_type_old: 250 sum(updated_type_old$site_id %in% data8$site_id) ## so we are missing: 64 # - visually check the assignment of sites rt <- data8 |> filter(!site_id %in% updated_type_old$site_id) |> unique(by = "site_id") |> st_as_sf(coords = c("x.coord", "y.coord"), crs = data5$EPSG[1]) plot_typology <- st_crop(typologies, st_transform(sites, crs = st_crs(typologies))) updated_type <- data.table(site_id = rt$site_id) options(warn = -1) for (i in 1:nrow(rt)){ #if (i < 327) next() i.percent <- i/nrow(rt) * 100 i.rt <- rt[i, ] i.plot_typology <- st_crop(plot_typology, st_buffer(st_transform(i.rt, crs = st_crs(typologies)), dist = 2000)) x <- mapview(i.plot_typology, zcol = "brt") + mapview(i.rt, popup = "waterbody", color = "red") print(x) i.bool <- "n" i.bool <- readline(paste0(i,"/", nrow(rt))) if (i.bool == "break") break() if (i.bool == "n"){ updated_type[site_id == i.rt$site_id, new_type := "drop"] } else if (i.bool == "c"){ i.towhat <- readline("change to:") updated_type[site_id == i.rt$site_id, new_type := i.towhat] } else { updated_type[site_id == i.rt$site_id, new_type := i.rt$brt12] } rm(list = ls()[grepl("i\\.", ls())]) } updated_type_combi <- bind_rows(updated_type, updated_type_old) #- save the remove list. saveRDS(updated_type, paste0("data/fish/original_data/mixed_intercalibration_didier_pont/", Sys.Date(), "_updated_type_combi.rds")) data9 <- left_join(data8, updated_type_combi, by = "site_id") #- drop "drop" rows determined in for-loop data9 <- data9[new_type != "drop"] data9[, brt12 := NULL] data9 <- rename(data9, brt12 = new_type) # temporal aggregation -------------------------------------------------------------- agg <- data9 |> unique(by = "gr_sample_id") unique(table(agg$site_id)) # no #source("R/functions/newest_sample.R") data10 <- copy(data9) data10$data.set <- "intercalibration_fish" data10[, country := NULL] saveRDS(data10, paste0("data/fish/original_data/mixed_intercalibration_didier_pont/",Sys.Date(),"_final_aggregated.rds")) data10 <- readRDS("data/fish/original_data/mixed_intercalibration_didier_pont/2022-04-25_final_aggregated.rds") # statistics ------------------------------------------------------------------------- # time span summary(data$year) # all sites and samples uniqueN(data5$site_id) uniqueN(data5$gr_sample_id) # least impacted sites and samples uniqueN(data6$site_id) uniqueN(data6$gr_sample_id) # no sites with <10 taxa uniqueN(data7$site_id) uniqueN(data7$gr_sample_id) # only close sites uniqueN(data8$site_id) uniqueN(data8$gr_sample_id) # no sites that can not definitively be assigned to a river segment uniqueN(data9$site_id) uniqueN(data9$gr_sample_id) uniqueN(data10$gr_sample_id) # mean richness: unique(data10, by = "gr_sample_id") |> pull(richness) |> mean() # histogram richness unique(data10, by = "gr_sample_id") |> pull(richness) |> hist()
#include "aileswhale.h" /** * reallocate - Doubles the space allocated for a pointer. * @pointer: Pointer to the original array. * @sizes: Pointer to the number of elements in the original array. * * Return: Pointer to the newly reallocated array. */ char **reallocate(char **pointer, size_t *sizes) { char **new; size_t i; new = malloc(sizeof(char *) * ((*sizes) + 10)); if (new == NULL) { free(pointer); return (NULL); } for (i = 0; i < (*sizes); i++) { new[i] = pointer[i]; } *sizes += 10; free(pointer); return (new); }
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'satori_container.dart'; class SatoriCard extends ConsumerWidget { const SatoriCard({ super.key, required this.body, this.header, this.footer, this.onTap, this.cursor = MouseCursor.defer, this.hoverEffect = false, }); final Widget body; final List<Widget>? header; final List<Widget>? footer; final void Function()? onTap; final MouseCursor cursor; final bool hoverEffect; @override Widget build(BuildContext context, WidgetRef ref) { return SatoriContainer( hoverEffect: hoverEffect, onTap: onTap, cursor: cursor, child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Row(children: header ?? []), Expanded( child: Container( margin: const EdgeInsets.symmetric(vertical: 8), child: body)), Row(children: footer ?? []) ])); } }
import React, { useState } from "react"; import Form from "./Form"; import Footer from "./Footer"; import Menu from "./Menu"; import Header from "./Header"; const animeData = [ { id: 1, name: "Naruto", genres: ["action", "adventure", "comedy", "drama", "shounen"], photoName: "poster/naruto.jpg", rating: 7, summary: "Naruto Uzumaki, is a loud, hyperactive, adolescent ninja who constantly searches for approval and recognition, as well as to become Hokage, who is acknowledged as the leader and strongest of all ninja in the village. Naruto Uzumaki wants to be the best ninja in the land.", }, { id: 2, name: "One Piece", genres: ["action", "adventure", "comedy", "drama", "shounen"], photoName: "poster/onepiece.jpg", rating: 5, summary: "The series focuses on Monkey D. Luffy—a young man made of rubber after unintentionally eating a Devil Fruit—who sets off on a journey from the East Blue Sea to find the deceased King of the Pirates Gol D. Roger's ultimate treasure known as the One Piece, and take over his prior title.", }, { id: 3, name: "Bleach", genres: ["action", "adventure", "comedy", "shounen"], photoName: "poster/bleach.jpg", rating: 2, summary: 'High school student Ichigo Kurosaki, who has the ability to see ghosts, gains soul reaper powers from Rukia Kuchiki and sets out to save the world from "Hollows". High school student Kurosaki Ichigo is unlike any ordinary kid. Why? Because he can see ghosts.', }, { id: 4, name: "Baki", genres: ["action", "adventure", "shounen"], photoName: "poster/baki.jpg", rating: 8, summary: "Baki Hanma strives to be the fighting equal of his legendary father, who is known as The Orge. Possessing incredible strength and combat abilities, Baki must go to extreme measures to become the equal of his old man.", }, { id: 5, name: "One Punch Man", genres: ["action", "adventure", "comedy"], photoName: "poster/onepunchman.jpg", rating: 7, summary: "It tells the story of Saitama, a superhero who, because he can defeat any opponent with a single punch, grows bored from a lack of challenge.", }, { id: 6, name: "Dragon Ball", genres: ["action", "adventure", "comedy", "shounen"], photoName: "poster/dragonball.jpeg", rating: 8, summary: "Dragon Ball tells the tale of a young warrior by the name of Son Goku, a young peculiar boy with a tail who embarks on a quest to become stronger and learns of the Dragon Balls, when, once all 7 are gathered, grant any wish of choice.", }, { id: 7, name: "Death Note", genres: ["drama", "mystery", "psychological", "thriller"], photoName: "poster/deathnote.jpg", rating: 4, summary: "The story follows Light Yagami, a genius high school student who discovers a mysterious notebook: the Death Note, which belonged to the shinigami Ryuk, and grants the user the supernatural ability to kill anyone whose name is written in its pages.", }, { id: 8, name: "Code Geass", genres: ["action", "mystery", "psychological", "thriller"], photoName: "poster/codegeass.jpg", rating: 9.8, summary: "Set in an alternate timeline, it follows the exiled prince Lelouch Lamperouge, who obtains the power of absolute obedience from a mysterious woman named C.C. Using this supernatural power, known as Geass, he leads a rebellion against the rule of the Holy Britannian Empire, commanding a series of mecha battles.", }, ]; export default function App() { const [showForm, setShowForm] = useState(false); function handleToggleForm(showForm) { setSelectedAnime(null); setShowForm((showForm) => !showForm); } const [animeList, setAnimeList] = useState(animeData); const [selectedAnime, setSelectedAnime] = useState(null); function handleSetAnimeList(newAnime) { setAnimeList((animeList) => [...animeList, newAnime]); } function handleEditAnimeList(newAnime) { setAnimeList( animeList.map((anime) => anime.id === newAnime.id ? { ...anime, name: newAnime.name, genres: newAnime.genres, rating: newAnime.rating, summary: newAnime.summary, } : anime ) ); } function handleDeleteAnimeList(animeName) { const animeListAfterDelete = animeList.filter( (anime) => anime.name !== animeName ); setAnimeList(animeListAfterDelete); } function handleSelectAnime(anime) { setSelectedAnime((selectedAnime) => anime); setShowForm((showForm) => !showForm); } return ( <div className="container"> <Header /> {showForm ? ( <Form selectedAnime={selectedAnime ?? []} onSetAnimeList={ selectedAnime ? handleEditAnimeList : handleSetAnimeList } onToggleForm={handleToggleForm} newID={++animeList[animeList.length - 1].id} animeList={animeList} /> ) : ( <Menu animeList={animeList} onDeleteAnimeList={handleDeleteAnimeList} onSelectAnime={handleSelectAnime} /> )} <Footer onToggleForm={handleToggleForm} showForm={showForm} /> </div> ); }
package com.educacionit.ejercicio02.exception; public class DBManagerException extends Exception { /* * Error 1: conectar a la db * Error 2: buscar provincias por pais * Error 3: obtener paises * Error 4: insertar provincia * Error 5: modificar provincia * Error 6: eliminar provincia * Error 7: cerrar conexion a la db */ public static final int ERROR_1= 1; public static final int ERROR_2= 2; public static final int ERROR_3= 3; public static final int ERROR_4= 4; public static final int ERROR_5= 5; public static final int ERROR_6= 6; public static final int ERROR_7= 7; private Integer error; public DBManagerException(Integer error, String message) { super(message); this.error = error; } public DBManagerException(Integer error, Throwable cause) { super(cause); this.error = error; } public DBManagerException(Integer error, String message, Throwable cause) { super(message, cause); this.error = error; } @Override public String getMessage() { switch (error) { case ERROR_1: return "Se produjo un error conectando a la base de datos: " + super.getMessage(); case ERROR_2: return "Se produjo un error al buscar provincias por pais: " + super.getMessage(); case ERROR_3: return "Se produjo un error al obtener los paises: " + super.getMessage(); case ERROR_4: return "Se produjo un error al agregar una provincia: " + super.getMessage(); case ERROR_5: return "Se produjo un error al modificar la provincia: " + super.getMessage(); case ERROR_6: return "Se produjo un error al eliminar la provincia: " + super.getMessage(); case ERROR_7: return "Se produjo un error cerrando la conexión a la base de datos: " + super.getMessage(); default: return super.getMessage(); } } }
import React, {useEffect, useState} from 'react'; import {Button, Card,Form, Input, Layout, Radio,message} from "antd"; import { useNavigate } from "react-router-dom"; import axios from "axios"; import './index.css' const {Header} = Layout function Index(props) { const navgiate = useNavigate() const [form] = Form.useForm() const [isAdmin,setIsAdmin] = useState(false) useEffect(()=>{ if(sessionStorage.getItem('user')){ message.error('请勿重复登陆',).then() navgiate('/') } }) const setAdmin = (e) => { if (e.target.value==='admin'){ setIsAdmin(true) form.setFieldsValue({department:'无'}) }else{ setIsAdmin(false) form.setFieldsValue({department:''}) } } const login = async (value) => { try { const data = await axios.post('http://127.0.0.1:8000/adminuser/login/',value) message.success(data.data.message,1).then(()=>{ sessionStorage.setItem('user',JSON.stringify(data.data.user)) navgiate('/') }) }catch (e) { message.error(e.response.data.message) } } return ( <> <Layout> <Header> <div className="login-logo"> <img src={require("../../static/img/logo.png")} alt="logo" width="45px" height="40px"/> <span>&nbsp;考勤管理平台</span> </div> </Header> </Layout> <Card title="登录" className='login-card' hoverable={true}> <Form labelCol={{span:6}} form={form} onFinish={login} preserve={false}> <Form.Item label="用户名" name="name" rules={[{required: true,message:'不得为空'}]}> <Input placeholder="请输入用户名"/> </Form.Item> <Form.Item label="密码" name="password" rules={[{required: true,message:'不得为空'}]}> <Input.Password placeholder='请输入密码'/> </Form.Item> <Form.Item label="角色" name="role" rules={[{required: true,message:'请选择角色'}]}> <Radio.Group onChange={setAdmin}> <Radio value="admin">admin</Radio> <Radio value="普通管理员">普通管理员</Radio> </Radio.Group> </Form.Item> <Form.Item label="部门" name="department" hidden={isAdmin} rules={[{required: true,message:'不得为空'}]}> <Input placeholder='请输入部门'/> </Form.Item> <Form.Item> <Button type="primary" htmlType="submit">登录</Button> </Form.Item> </Form> </Card> </> ); } export default Index;
import { createContext, FC, PropsWithChildren, useContext, useEffect, useState, } from 'react'; import { createDefaultState, createWeb3State, loadContract, Web3State, } from './utils'; import { ethers } from 'ethers'; import { MetaMaskInpageProvider } from '@metamask/providers'; import { NftCompleteCourses, NftClassRegistration, NftGraduation, NftIdentities, School, } from '@_types/contracts'; const pageReload = () => window.location.reload(); const Web3Context = createContext<Web3State>(createDefaultState()); const Web3Provider: FC<PropsWithChildren> = ({ children }) => { const [web3Api, setWeb3Api] = useState<Web3State>(createDefaultState()); const handleAccountChange = (ethereum: MetaMaskInpageProvider) => async () => { pageReload(); }; const setGlobalListeners = (ethereum: MetaMaskInpageProvider) => { ethereum.on('chainChanged', pageReload); ethereum.on('accountsChanged', handleAccountChange(ethereum)); }; const removeGlobalListeners = (ethereum?: MetaMaskInpageProvider) => { ethereum?.removeListener('chainChanged', pageReload); ethereum?.removeListener('accountsChanged', handleAccountChange(ethereum)); }; useEffect(() => { const initWeb3 = async () => { try { const ethereum = window.ethereum; const provider = new ethers.providers.Web3Provider(ethereum as any); const [ nftIdentities, school, nftCompleteCourses, nftClassRegistration, nftGraduation, ] = await Promise.all([ loadSignedContract('NftIdentities', provider), loadSignedContract('School', provider), loadSignedContract('NftCompleteCourses', provider), loadSignedContract('NftClassRegistration', provider), loadSignedContract('NftGraduation', provider), ]); const contracts = { nftIdentities: nftIdentities as unknown as NftIdentities, school: school as unknown as School, nftCompleteCourses: nftCompleteCourses as unknown as NftCompleteCourses, nftClassRegistration: nftClassRegistration as unknown as NftClassRegistration, nftGraduation: nftGraduation as unknown as NftGraduation, }; const web3State = { ethereum, provider, contracts, isLoading: false, }; setGlobalListeners(ethereum); setWeb3Api(createWeb3State(web3State)); } catch (e) { setWeb3Api(({ hooks, ...api }) => createWeb3State({ ...(api as any), isLoading: false, }) ); } }; const loadSignedContract = async (name, provider) => { const contract = await loadContract(name, provider); const signerContract = provider.getSigner(); return contract.connect(signerContract); }; initWeb3(); return () => removeGlobalListeners(window.ethereum); }, []); return ( <Web3Context.Provider value={web3Api}>{children}</Web3Context.Provider> ); }; export function useWeb3() { return useContext(Web3Context); } export function useContracts() { const { contracts } = useWeb3(); return contracts; } export function useHooks() { const { hooks } = useWeb3(); return hooks; } export default Web3Provider;
import React, { useState } from 'react'; import styled from 'styled-components'; import Categoria from './Categoria'; import Cliente from './Cliente'; import EntradaProduto from './EntradaProduto'; import Fabricante from './Fabricante'; import Fornecedor from './Fornecedor'; import Produto from './Produto'; import Venda from './Venda'; const Container = styled.div` background-color: #00BFFF; height: 100vh; display: flex; justify-content: center; align-items: center; `; const SidebarContainer = styled.aside` width: 64px; background-color: #00BFFF; padding: 4px; display: flex; flex-direction: column; align-items: center; text-align: center; color: white; `; const SidebarTitle = styled.span` font-size: 1.5rem; font-weight: bold; `; const SidebarButton = styled.button` margin-bottom: 8px; padding: 8px; width: 100%; background-color: ${(props) => (props.selected ? '#303030' : 'inherit')}; color: ${(props) => (props.selected ? 'white' : 'inherit')}; border: none; border-radius: 4px; cursor: pointer; transition: background-color 0.3s ease, color 0.3s ease; &:hover { background-color: #303030; color: white; } `; const ContentContainer = styled.div` flex: 1; overflow: hidden; `; const Sidebar = () => { const [selectedItem, setSelectedItem] = useState(null); const handleItemClick = (item) => { setSelectedItem(item); }; const renderComponent = () => { switch (selectedItem) { case 'Categoria': return <Categoria />; case 'Cliente': return <Cliente />; case 'Entrada Produto': return <EntradaProduto />; case 'Fabricante': return <Fabricante />; case 'Fornecedor': return <Fornecedor />; case 'Produto': return <Produto />; case 'Venda': return <Venda />; default: return null; } }; return ( <Container> <SidebarContainer> <div> <SidebarTitle>Controle De Estoque</SidebarTitle> </div> <div> <SidebarButton onClick={() => handleItemClick('Categoria')} selected={selectedItem === 'Categoria'}> Categoria </SidebarButton> <SidebarButton onClick={() => handleItemClick('Cliente')} selected={selectedItem === 'Cliente'}> Cliente </SidebarButton> <SidebarButton onClick={() => handleItemClick('Entrada Produto')} selected={selectedItem === 'Entrada Produto'}> Entrada Produto </SidebarButton> <SidebarButton onClick={() => handleItemClick('Fabricante')} selected={selectedItem === 'Fabricante'}> Fabricante </SidebarButton> <SidebarButton onClick={() => handleItemClick('Fornecedor')} selected={selectedItem === 'Fornecedor'}> Fornecedor </SidebarButton> <SidebarButton onClick={() => handleItemClick('Produto')} selected={selectedItem === 'Produto'}> Produto </SidebarButton> <SidebarButton onClick={() => handleItemClick('Venda')} selected={selectedItem === 'Venda'}> Venda </SidebarButton> </div> </SidebarContainer> <ContentContainer> <main>{selectedItem && renderComponent()}</main> </ContentContainer> </Container> ); }; export default Sidebar;
import {DomCustomLib} from "./DomCustomLib"; export class Listener { constructor(private _rootElemInstance: DomCustomLib, private listeners: (keyof HTMLElementEventMap)[]) { if (!_rootElemInstance) { throw new Error('no root provided for dom listener!') } } addEventListeners() { this.listeners.forEach(listener => { const callbackName = getCallbackName(listener); console.log(this); // nb! this тут без потери контекста можно использовать только если это стрелочная функция! // обычная функция создает свой собственный контекст //this._rootElemInstance[callbackName] = this._rootElemInstance[callbackName].bind(this); //TODO: пока что мне не оч понятно почему в this у класса Listner попадает также и все что связано с Formula // nb! биндим для того чтобы в конкретном уже методе типа onInput onClick и тд // чтобы в нем был доступен контекст this!!! if (!this[callbackName]) { throw new Error(`Вы забыли реализовать метод ${callbackName} для ${this.name} компонента`) } this[callbackName] = this[callbackName].bind(this); // callback[callbackName] = callback[callbackName].bind(this); this._rootElemInstance.on(listener, this[callbackName]); }) } removeEventListeners() { this.listeners.forEach(listener => { const callbackName = getCallbackName(listener); this._rootElemInstance.off(listener, this[callbackName]); }) } } function getCallbackName(name: string): string { return 'on' + name.charAt(0).toUpperCase() + name.slice(1); }
# -*- coding: utf-8 -*- """Setup tests for this package.""" from collective.announcement.testing import COLLECTIVE_ANNOUNCEMENT_INTEGRATION_TESTING # noqa from plone import api import unittest class TestSetup(unittest.TestCase): """Test that collective.announcement is properly installed.""" layer = COLLECTIVE_ANNOUNCEMENT_INTEGRATION_TESTING def setUp(self): """Custom shared utility setup for tests.""" self.portal = self.layer['portal'] self.installer = api.portal.get_tool('portal_quickinstaller') def test_product_installed(self): """Test if collective.announcement is installed.""" self.assertTrue(self.installer.isProductInstalled( 'collective.announcement')) def test_browserlayer(self): """Test that ICollectiveAnnouncementLayer is registered.""" from collective.announcement.interfaces import ( ICollectiveAnnouncementLayer) from plone.browserlayer import utils self.assertIn(ICollectiveAnnouncementLayer, utils.registered_layers()) class TestUninstall(unittest.TestCase): layer = COLLECTIVE_ANNOUNCEMENT_INTEGRATION_TESTING def setUp(self): self.portal = self.layer['portal'] self.installer = api.portal.get_tool('portal_quickinstaller') self.installer.uninstallProducts(['collective.announcement']) def test_product_uninstalled(self): """Test if collective.announcement is cleanly uninstalled.""" self.assertFalse(self.installer.isProductInstalled( 'collective.announcement')) def test_browserlayer_removed(self): """Test that ICollectiveAnnouncementLayer is removed.""" from collective.announcement.interfaces import ICollectiveAnnouncementLayer from plone.browserlayer import utils self.assertNotIn(ICollectiveAnnouncementLayer, utils.registered_layers())
import {TrashIcon} from '@heroicons/react/24/outline' import {MinusCircleIcon, ShoppingCartIcon} from '@heroicons/react/24/solid' import { ActionIcon, Anchor, Button, Input, Modal, Select, Textarea, } from '@mantine/core' import {cleanNotifications, showNotification} from '@mantine/notifications' import {OrderType, PaymentMethod} from '@prisma/client' import type {ActionArgs} from '@remix-run/node' import {redirect} from '@remix-run/node' import {Link, useFetcher, useLocation} from '@remix-run/react' import * as React from 'react' import ReactInputMask from 'react-input-mask' import {TailwindContainer} from '~/components/TailwindContainer' import type {CartItem} from '~/context/CartContext' import {useCart} from '~/context/CartContext' import {createOrder} from '~/lib/order.server' import {getUserId} from '~/session.server' import {useOptionalUser} from '~/utils/hooks' import {titleCase} from '~/utils/misc' import {badRequest, unauthorized} from '~/utils/misc.server' type ActionData = Partial<{ success: boolean message: string discount: number }> export async function action({request}: ActionArgs) { const formData = await request.formData() const userId = await getUserId(request) const intent = formData.get('intent')?.toString() if (!userId || !intent) { return unauthorized({success: false, message: 'Unauthorized'}) } switch (intent) { case 'place-order': { const stringifiedItems = formData.get('items[]')?.toString() const amount = formData.get('amount')?.toString() const orderType = formData.get('orderType')?.toString() const paymentMethod = formData.get('paymentMethod')?.toString() const address = formData.get('address')?.toString() if (!stringifiedItems || !amount || !paymentMethod || !orderType) { return badRequest<ActionData>({ success: false, message: 'Invalid request body', }) } const items = JSON.parse(stringifiedItems) as Array<CartItem> await createOrder({ userId, items, amount: Number(amount), paymentMethod: paymentMethod as PaymentMethod, orderType: orderType as OrderType, address: address || '', }) return redirect('/order-history/?success=true') } default: return badRequest<ActionData>({success: false, message: 'Invalid intent'}) } } export default function Cart() { const id = React.useId() const location = useLocation() const fetcher = useFetcher<ActionData>() const {clearCart, itemsInCart, totalPrice} = useCart() const {user} = useOptionalUser() const [orderType, setOrderType] = React.useState<OrderType>(OrderType.PICKUP) const [paymentMethod, setPaymentMethod] = React.useState<PaymentMethod>( PaymentMethod.CREDIT_CARD ) const [isPaymentModalOpen, setIsPaymentModalOpen] = React.useState(false) const [address, setAddress] = React.useState(user?.address ?? '') const closePaymentModal = () => setIsPaymentModalOpen(false) const showPaymentModal = () => setIsPaymentModalOpen(true) const placeOrder = () => { const formData = new FormData() formData.append('items[]', JSON.stringify(itemsInCart)) formData.append('amount', totalPrice.toString()) formData.append('intent', 'place-order') formData.append('orderType', orderType) formData.append('paymentMethod', paymentMethod) formData.append('address', address) fetcher.submit(formData, { method: 'post', replace: true, }) } const isSubmitting = fetcher.state !== 'idle' const isDelivery = orderType === OrderType.DELIVERY React.useEffect(() => { if (fetcher.type !== 'done') { return } cleanNotifications() if (!fetcher.data.success) { showNotification({ title: 'Error', message: fetcher.data.message, icon: <MinusCircleIcon className="h-7 w-7" />, color: 'red', }) return } }, [fetcher.data, fetcher.type]) return ( <> <div className="flex flex-col gap-4 p-4"> <div className="bg-white"> <TailwindContainer> <div className="sm:px-4py-16 py-16 px-4 sm:py-20"> <div className="flex items-center justify-between"> <div> <h1 className="text-2xl font-extrabold tracking-tight text-gray-900 sm:text-3xl"> Your cart </h1> <p className="mt-2 text-sm text-gray-500"> Check the cuisines in your cart </p> </div> {itemsInCart.length > 0 ? ( <div className="space-x-2"> <Button variant="subtle" color="red" onClick={() => clearCart()} disabled={isSubmitting} > Clear cart </Button> {user ? ( <Button variant="light" loading={isSubmitting} onClick={() => showPaymentModal()} > Make payment </Button> ) : ( <Button variant="light" component={Link} to={`/login?redirectTo=${encodeURIComponent( location.pathname )}`} > Sign in to order </Button> )} </div> ) : null} </div> <div className="mt-16"> <h2 className="sr-only">Current cuisines in cart</h2> <div className="flex flex-col gap-12"> {itemsInCart.length > 0 ? <CartItems /> : <EmptyState />} </div> </div> </div> </TailwindContainer> </div> </div> <Modal opened={!!user && isPaymentModalOpen} onClose={closePaymentModal} title="Payment" centered overlayBlur={1} overlayOpacity={0.5} > <fetcher.Form method="post" replace className="flex flex-col gap-4"> <div className="flex flex-col gap-2"> <h2 className="text-sm text-gray-600"> <span className="font-semibold">Amount: </span> <span>${totalPrice.toFixed(2)}</span> </h2> </div> <Select label="Order type" value={orderType} clearable={false} onChange={e => setOrderType(e as OrderType)} data={Object.values(OrderType).map(type => ({ label: titleCase(type.replace(/_/g, ' ')), value: type, }))} /> <Select label="Payment method" value={paymentMethod} clearable={false} onChange={e => setPaymentMethod(e as PaymentMethod)} data={Object.values(PaymentMethod).map(method => ({ label: titleCase(method.replace(/_/g, ' ')), value: method, }))} /> <Input.Wrapper id={id} label="Card Number" required labelProps={{className: '!text-[13px] !font-semibold'}} > <Input id={id} name="cardNumber" component={ReactInputMask} mask="9999 9999 9999 9999" placeholder="XXXX XXXX XXXX XXXX" alwaysShowMask={false} defaultValue="54326787678756467" /> </Input.Wrapper> <div className="flex items-center gap-4"> <Input.Wrapper id={id + 'cvv'} label="CVV" labelProps={{className: '!text-[13px] !font-semibold'}} required className="w-full" > <Input name="cvv" id={id + 'cvv'} component={ReactInputMask} mask="999" placeholder="XXX" alwaysShowMask={false} defaultValue="123" /> </Input.Wrapper> <Input.Wrapper id={id + 'expiry'} label="Expiry" labelProps={{className: '!text-[13px] !font-semibold'}} required className="w-full" > <Input name="Expiry" id={id + 'expiry'} component={ReactInputMask} mask="99/9999" placeholder="XX/XXXX" alwaysShowMask={false} defaultValue="122026" /> </Input.Wrapper> </div> {isDelivery ? ( <Textarea label="Delivery address" name="address" value={address} onChange={e => setAddress(e.target.value)} required /> ) : null} <div className="mt-6 flex items-center gap-4 sm:justify-end"> <Button variant="subtle" color="red" onClick={() => closePaymentModal()} > Cancel </Button> <Button variant="filled" onClick={() => placeOrder()} loading={isSubmitting} loaderPosition="right" > Place order </Button> </div> </fetcher.Form> </Modal> </> ) } function CartItems() { const {itemsInCart, removeItemFromCart, totalPrice} = useCart() return ( <> <table className="mt-4 w-full text-gray-500 sm:mt-6"> <caption className="sr-only">Cuisine</caption> <thead className="sr-only text-left text-sm text-gray-500 sm:not-sr-only"> <tr> <th scope="col" className="py-3 pr-8 font-normal sm:w-2/5 lg:w-1/3"> Cuisine </th> <th scope="col" className="hidden py-3 pr-8 font-normal sm:table-cell" > Price </th> <th scope="col" className="hidden py-3 pr-8 font-normal sm:table-cell" > Total price </th> <th scope="col" className="w-0 py-3 text-right font-normal" /> </tr> </thead> <tbody className="divide-y divide-gray-200 border-b border-gray-200 text-sm sm:border-t"> {itemsInCart.map(item => ( <tr key={item.id}> <td className="py-6 pr-8"> <div className="flex items-center"> <img src={item.image} alt={item.name} className="mr-6 h-16 w-16 rounded object-cover object-center" /> <div> <div className="font-medium text-gray-900"> <Anchor component={Link} to={`/items/${item.slug}`} size="sm" > {item.name} </Anchor>{' '} (x{item.quantity}) </div> </div> </div> </td> <td className="hidden py-6 pr-8 sm:table-cell">${item.price}</td> <td className="hidden py-6 pr-8 font-semibold sm:table-cell"> ${(item.price * item.quantity).toFixed(2)} </td> <td className="whitespace-nowrap py-6 text-right font-medium"> <ActionIcon onClick={() => removeItemFromCart(item.id)}> <TrashIcon className="h-5 w-5 text-red-400" /> </ActionIcon> </td> </tr> ))} <tr> <td className="py-6 pr-8"> <div className="flex items-center"> <div> <div className="font-medium text-gray-900" /> <div className="mt-1 sm:hidden" /> </div> </div> </td> <td className="hidden py-6 pr-8 sm:table-cell" /> <td className="hidden py-6 pr-8 font-semibold sm:table-cell"> ${totalPrice.toFixed(2)} </td> </tr> </tbody> </table> </> ) } function EmptyState() { return ( <div className="relative block w-full rounded-lg border-2 border-dashed border-gray-300 p-12 text-center"> <ShoppingCartIcon className="mx-auto h-9 w-9 text-gray-500" /> <span className="mt-4 block text-sm font-medium text-gray-500"> Your cart is empty </span> </div> ) }
import { AppSyncClient, type AppSyncClientConfig, type EvaluateCodeCommand, type EvaluateCodeCommandOutput, } from '@aws-sdk/client-appsync'; // limiting to scope of commands currently used in this tooling type SupportedCommand = EvaluateCodeCommand; type SupportedOutput = EvaluateCodeCommandOutput; const runtimeRegion = process.env.AWS_REGION; const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const isThrottleError = (err: Error): boolean => err.name === 'TooManyRequestsException' || err.message === 'Too Many Requests'; type ThrottledAppsyncClientConfig = AppSyncClientConfig & { // for send request throttling maxRetries?: number; opsPerSecond?: number; }; class ThrottledAppsyncClient extends AppSyncClient { static readonly defaultMaxRetries: 3; static readonly defaultOpsPerSecond: 5; firstRequestAt: number; requestCount: number; readonly maxRetries: number; readonly opsPerSecond: number; readonly requestInterval: number; private retryCounter: WeakMap<SupportedCommand, number>; constructor(opts?: ThrottledAppsyncClientConfig) { const { maxRetries = ThrottledAppsyncClient.defaultMaxRetries, opsPerSecond = ThrottledAppsyncClient.defaultOpsPerSecond, region = runtimeRegion, ...otherOpts } = opts ?? {}; super({ region, ...otherOpts, }); this.maxRetries = maxRetries; this.opsPerSecond = opsPerSecond; this.requestInterval = 1000 / opsPerSecond; this.firstRequestAt = 0; this.requestCount = 0; this.retryCounter = new WeakMap(); } async retry(command: SupportedCommand): Promise<SupportedOutput> { let retryCount = this.retryCounter.get(command) ?? 0; retryCount++; if (retryCount > this.maxRetries) { const msg = 'Max retries for Appsync command reached'; console.error(msg, command); throw new Error(msg); } this.retryCounter.set(command, retryCount); return this.send(command); } async send(command: SupportedCommand): Promise<SupportedOutput> { await this.throttle(); return super.send(command).catch((err) => { if (isThrottleError(err)) { console.warn('Command send throttled', command, err); return this.retry(command); } console.error('Command send error', command, err); throw err; }); } async throttle(): Promise<void> { if (!this.firstRequestAt) { this.firstRequestAt = Date.now(); } this.requestCount++; const executeAfter = this.firstRequestAt + this.requestCount * this.requestInterval; const waitFor = executeAfter - Date.now(); if (waitFor > 0) { await delay(waitFor); } } } let client; const getThrottledClient = ( opts?: ThrottledAppsyncClientConfig, ): ThrottledAppsyncClient => { if (!client) { client = new ThrottledAppsyncClient(opts); } return client; }; export { getThrottledClient, ThrottledAppsyncClient };
import Link from 'next/link' import React, { useEffect, useState } from 'react' import { GLOBAL_URL, getAlumniProfiles, searchAlumniByParameter } from '@/utils/fetch'; import toast from 'react-hot-toast'; function Author() { const searchAlumni = async (value) => { let finalValue = value; setLoading(true); if (SearchParameter === "bloodgroup") { if (finalValue.includes("+")) { finalValue = finalValue.replace("+", "%2B") } } console.log(finalValue) const response = await searchAlumniByParameter(SearchParameter, finalValue) setLoading(false); if (response?.status !== 200) { toast.error("Something went wrong"); return; } if (response?.status === 200) { if (response?.data?.length === 0) { toast.error("No data found"); return; } setAlumnusData(response?.data); return; } } const [Skip, setSkip] = useState(0); const [AlumnusData, setAlumnusData] = useState([]); const [SearchParameter, setSearchParameter] = useState("name"); const [searchValue, setSearchValue] = useState(""); const [Loading, setLoading] = useState(true) useEffect(() => { getAlumnusAllData(0) }, []) const getAlumnusAllData = async (skip) => { const response = await getAlumniProfiles(skip); setLoading(false); if (response?.status !== 200) return; // error handle if (response?.data?.length === 0) { toast.error("No more data to load"); return; } setAlumnusData([...AlumnusData, ...response?.data]); setSkip(skip); console.log(response?.data); } return ( <section className="author-section pt-100 pb-100"> <div className="container"> <div className="row gy-2 mb-60"> <div className="col-lg-4"> <div className="search-box" style={{ borderRadius: "5px", }}> <div className='category-wrap'> <form> <select defaultValue={SearchParameter} onChange={(e) => { console.log(e.target.value); setSearchParameter(e.target.value?.toLocaleLowerCase()); }}> <option value={"name"}>Name</option> <option value={"graduationyear"}>Batch</option> <option value={"schoolno"}>School No</option> <option value={"address"}>Address</option> <option value={"bloodgroup"}>Blood Group</option> </select> </form> </div> </div> </div> <div className="col-lg-8"> <div className="search-box" style={{ backgroundColor: "#EEEEEE", borderRadius: "23px", }} > <form> <input name='searchValue' onChange={(e) => setSearchValue(e.target.value)} value={searchValue || ""} type="text" placeholder={`Search alumni by ${SearchParameter}...`} /> <button onClick={(e) => { e.preventDefault(); searchAlumni(searchValue); }}><i className="bi bi-search" /></button> </form> </div> </div> </div> <div className="row g-4 mb-60"> { Loading && <div className="text-center"> <div className="spinner-border" style={{ width: "3rem", height: " 3rem" }} role="status"> <span className="visually-hidden">Loading...</span> </div> </div> } { AlumnusData?.length > 0 && AlumnusData.map((alumnus, index) => <div key={index} className="col-lg-3 col-md-6 col-sm-6"> <div className="author-1"> <div className="author-front"> <span className="categoty">{alumnus?.profileDetails?.graduationYear}</span> <Link legacyBehavior href={`/profile/member/${alumnus?._id}`}> <a className="image"> { alumnus?.mobile ? <img src={alumnus?.profileDetails?.profileImage ? `${GLOBAL_URL + "/api/user/post/image/" + alumnus?.profileDetails?.profileImage}` : "/assets/images/dummy/avatar/user.jpg"} alt="image" /> : <img style={{ filter: "blur(5px)" }} src={alumnus?.profileDetails?.profileImage ? `${GLOBAL_URL + "/api/user/post/image/" + alumnus?.profileDetails?.profileImage}` : "/assets/images/dummy/avatar/user.jpg"} alt="image" /> } </a> </Link> <h4>{alumnus?.name}</h4> <ul> <li><span>Mobile</span><span style={!alumnus?.mobile ? { filter: "blur(4px)" } : { filter: "blur(0px)" }}>{alumnus?.mobile || "1234567890"}</span></li> <li><span>School No</span><span>{alumnus?.profileDetails?.schoolNo}</span></li> </ul> </div> <div className="author-back"> <ul className="social-list"> { alumnus?.socials?.map((social, index) => { return <li key={index}> <a href={social?.link}><span><i className={social?.icon} />{social?.name}</span><span><strong>{social?.count}</strong> &nbsp;</span></a> </li> }) } </ul> { alumnus?.mobile ? <Link legacyBehavior href={`/profile/member/${alumnus?._id}`}><a className=" eg-btn arrow-btn four">View Details<i className="bi bi-arrow-right" /></a></Link> : <Link legacyBehavior href="/membership/offer/free-trials"><a className="eg-btn arrow-btn four">Activate Membership<i className="bi bi-arrow-right" /></a></Link> } </div> </div> </div>) } </div> <div className="row text-center justify-content-center"> <div className="col-md-6"> <button onClick={() => getAlumnusAllData(Skip + 16)} className="eg-btn btn--primary btn--lg"> { Loading ? <><span className="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Loading...</> : "Load More" } </button> </div> </div> </div> </section> ) } export default Author
'use client'; import { Product } from '@prisma/client'; import { formatCurrency } from '@/lib/formatters'; import Link from 'next/link'; import { Card, CardContent, CardFooter, CardHeader } from './ui/card'; import { Button } from './ui/button'; type TProductDetailsCardProps = Product; export default function ProductDetailsCard({ id, name, priceInCents, description, }: TProductDetailsCardProps) { return ( <Card className="flex h-full flex-col"> <CardHeader className="pb-1"> <h2 className="text-2xl font-bold">{name}</h2> </CardHeader> <CardContent className="flex-grow"> <div className="mb-3 text-lg"> {formatCurrency(priceInCents / 100)} </div> <div className="text-muted-foreground">{description}</div> </CardContent> <CardFooter> <Button className="w-full" asChild> <Link href={`/products/${id}/purchase`}>Buy now</Link> </Button> </CardFooter> </Card> ); }
package com.example.demo.services; import com.example.demo.entities.User; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.MalformedJwtException; import io.jsonwebtoken.UnsupportedJwtException; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.security.Keys; import io.jsonwebtoken.security.SignatureException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; import javax.crypto.SecretKey; import java.util.Date; @Component public class JwtUtils { private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class); @Value("${jwtSecret}") private String jwtSecret; // @Value("${jwtExpirationMs}") private int jwtExpirationMs = 50_000_000; public String generateJwtToken(User user) { return Jwts.builder() .subject((user.getUsername())) .issuedAt(new Date()) .expiration(new Date((new Date()).getTime() + jwtExpirationMs)) .signWith(getSigningKey()) .compact(); } private SecretKey getSigningKey() { byte[] keyBytes = Decoders.BASE64.decode(jwtSecret); return Keys.hmacShaKeyFor(keyBytes); } public String getUserName(String token) { return Jwts.parser() .verifyWith(getSigningKey()) .build() .parseSignedClaims(token) .getPayload() .getSubject(); } public boolean validateJwtToken(String authToken) { try { Jwts.parser() .verifyWith(getSigningKey()) .build() .parseSignedClaims(authToken); return true; } catch (SignatureException e) { logger.error("Invalid JWT signature: {}", e.getMessage()); } catch (MalformedJwtException e) { logger.error("Invalid JWT token: {}", e.getMessage()); } catch (ExpiredJwtException e) { logger.error("JWT token is expired: {}", e.getMessage()); } catch (UnsupportedJwtException e) { logger.error("JWT token is unsupported: {}", e.getMessage()); } catch (IllegalArgumentException e) { logger.error("JWT claims string is empty: {}", e.getMessage()); } return false; } }
import { Container } from "react-bootstrap"; import { useSelector, useDispatch } from "react-redux"; import { removeTodoAction, completeTodoTask, } from "../../redux/todo/todo.actions"; import "./TodoShow.component.scss"; const TodoShow = () => { const todo = useSelector((state) => state.todo); const dispatch = useDispatch(); return todo.length ? ( <Container> {todo.map((task, index) => ( <div className={`task ${index !== 0 ? "mt-2" : ""}`} key={index} > <div className="task__header d-flex"> <h6 className={`task__title ${ task.status === "completed" ? "completed" : "" }`} > {task.task} </h6> <div className="task__btns-group"> <button className={`task__btn ${ task.status === "completed" ? "" : "task__btn-check" }`} onClick={() => dispatch(completeTodoTask(index)) } > <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" > <path d="M9 21.035l-9-8.638 2.791-2.87 6.156 5.874 12.21-12.436 2.843 2.817z" /> </svg> </button> <button className="task__btn task__btn-del" onClick={() => dispatch(removeTodoAction(index)) } > <svg width="24" height="24" xmlns="http://www.w3.org/2000/svg" fillRule="evenodd" clipRule="evenodd" > <path d="M5.662 23 .293 17.635a.996.996 0 0 1 0-1.414L15.222 1.293a1.001 1.001 0 0 1 1.414 0l7.071 7.073a.994.994 0 0 1 .293.708.995.995 0 0 1-.293.707L12.491 21h5.514v2H5.662zm3.657-2-5.486-5.486-1.419 1.414L6.49 21h2.829zm.456-11.429-4.528 4.528 5.658 5.659 4.527-4.53-5.657-5.657z" /> </svg> </button> </div> </div> <p className={`task__desc ${ task.status === "completed" ? "completed" : "" }`} > {task.description} </p> </div> ))} </Container> ) : ( <div className="text-danger d-flex justify-content-center align-items-center h-100"> <h6>there's no tasks todo yet!</h6> </div> ); }; export default TodoShow;
print("hello world!") # this command is going to display something on our screen # print here is a function- it carries out some task # need ("") this for print to read the command # ctrl+ enter is used to run the code or that specific line, select the whole command if it is more than a line ">" this greater than symbol is called prompt # the command displayed on screen is also withtin double quotes 2 + 5 # here " + " is also a fucntion # " - " for subtraction # " * " for multiplication # " / " for division # " ** " or " ^ " for exponentiation # for integer division, the symbol is " % / % " [5/3= 1.333 so, 5 %/% = 1], it removes the decimal part that's it # for modulo- the symbol is " %% ", meaning the number which we were not able to divide, the remainder type [5 %% 3= 2] # ctrl + shift + C helps to comment multiple lines as a comment- we select them all and then use "ctrl+shift+C" # "ctrl + shift + Z" is to redo the command while "ctrl + Z" is to undo the command # how to make a variable # variable name <- "value we want to store" # "<-" an operator - it is called assignment operator # can check the variables we created in the environment tab # to seperate 2 words we use underscore, full stop (.) or abcDef (seperating them with capital alphabet) , eg: my_name <- rashi [or my.name or myName] # if we put the designated assigned variable within parenthesis, after running the commnad, the code will also be visible apart from the results # "alt" + "-" key will help us put " <- " automatically # the funtion whose value you want to store should be placed on the right and you don't need to put double codes if you are using a function # help("insert the function") # why ther command is not working, we will check the documentation # we can replace the "help" fucntion with "?" # "{}" this tells us the name of the package in which the function is present # KINDS OF DATA TRUE FALSE T F # these are the only ways in which True and false can be coded # Integer number 1L # This is how you express integer number- number followed by L typeof(1L) # this give the value as "integer" typeof(1) # this gives the value as "double" -> this means real number typeof(3.14) # this gives value as "double" typeof("any text") # this gives value as character first_word <- "Bellis" (second_word <- "perennis") paste(first_word, second_word) # this give sthe result as Bellis perennis species_name <- paste(first_word, second_word) species_name paste(species_name, "L.") full_name <- paste(species_name, "L.") full_name 0.00005 5*10^(-5) # both give the same result of 5e-05 # "+" sign in R reprrsents R is waiting for us to finish the code/command # 4 KINDS of data types exist: logical, character, integer, numeric (we have 2 more types which relate to complex numbers) ## Syntax errors- commas very imp- used to seperate arguments, close the parenthesis # R is case sensitive
import React, { ComponentProps, useState } from 'react' import { TextInputProps } from 'react-native' import { Container, IconContainer, InputText } from './styles' import { Feather } from '@expo/vector-icons' import { useTheme } from 'styled-components' interface Props extends TextInputProps { iconName: ComponentProps<typeof Feather>['name'] } const Input = ({ value, iconName, ...props }: Props) => { const [focus, setFocus] = useState(false) const [filled, setFilled] = useState(false) const theme = useTheme() return ( <Container> <IconContainer withBorderBottom={focus}> <Feather size={24} name={iconName} color={focus || filled ? theme.colors.main : theme.colors.text_detail} /> </IconContainer> <InputText withBorderBottom={focus} onBlur={() => { setFocus(false) setFilled(!!value) }} onFocus={() => setFocus(true)} value={value} {...props} /> </Container> ) } export default Input
#ifndef COMOVERIP_TCP_SERVER_H #define COMOVERIP_TCP_SERVER_H #include <i_source.h> #include <common/data.h> #include <asio.hpp> namespace comoverip { /// @brief Tcp сервер class TcpServer : public ISource, public Actor< TcpServer > { public: struct Args: public ISource::Args { asio::ip::port_type port; explicit Args( asio::ip::port_type p ) : ISource::Args( ISource::Type::TcpServer ) , port( p ) {} }; /// @brief Конструктор класса /// @param[in,out] ioContext /// @param[in] args TcpServer( const std::shared_ptr< asio::io_context >& ioContext, const Args& args ); void Receive( const std::shared_ptr< BaseMessage >& message ) override; ~TcpServer() override; /// @brief Запуск сервера void Start() override; /// @brief Остановка сервера void Stop() override; private: /// @brief Старт асинхронной задачи приема подключения void PushAcceptTask(); /// @brief Старт асинхронного чтения void PushReadTask(); /// @brief Запись данных текущему клиенту /// @param[in] data void Write( const DataPtr& data ); /// @brief Реализация остановки сервера void StopImpl(); public: asio::ip::tcp::acceptor acceptor_; asio::ip::tcp::socket socket_; std::atomic< bool > isStarted_; }; } #endif //COMOVERIP_TCP_SERVER_H
import 'package:flutter/material.dart'; import 'package:project_x/utils/app_text_style.dart'; class AppFeedback { final String text; final Color color; AppFeedback({ required this.text, required this.color, }); void showSnackbar(BuildContext context) { ScaffoldMessenger.of(context).removeCurrentSnackBar(); ScaffoldMessenger.of(context).showSnackBar( SnackBar( duration: const Duration(milliseconds: 2000), backgroundColor: color, content: SizedBox( width: double.maxFinite, child: Text( text, textAlign: TextAlign.center, style: AppTextStyle.size16(), ), ), ), ); } }
import { useEffect, useState } from 'react'; import './App.css'; import Contracts from './components/Contracts/Contracts'; import '@fortawesome/fontawesome-free/css/all.min.css'; function App() { const [forecasts, setForecasts] = useState(); useEffect(() => { populateWeatherData(); }, []); // eslint-disable-next-line no-unused-vars const contents = forecasts === undefined ? <p><em>Loading... Please refresh once the ASP.NET backend has started. See <a href="https://aka.ms/jspsintegrationreact">https://aka.ms/jspsintegrationreact</a> for more details.</em></p> : <table className="table table-striped" aria-labelledby="tabelLabel"> <thead> <tr> <th>Date</th> <th>Temp. (C)</th> <th>Temp. (F)</th> <th>Summary</th> </tr> </thead> <tbody> {forecasts.map(forecast => <tr key={forecast.date}> <td>{forecast.date}</td> <td>{forecast.temperatureC}</td> <td>{forecast.temperatureF}</td> <td>{forecast.summary}</td> </tr> )} </tbody> </table>; return ( <div> {/*<h1 id="tabelLabel">Weather forecast</h1> <p>This component demonstrates fetching data from the server.</p> {contents}*/} <Contracts/> </div> ); async function populateWeatherData() { const response = await fetch('weatherforecast'); const data = await response.json(); setForecasts(data); } } export default App;
package com.paj.project.bettingapp.jpa; import com.paj.project.bettingapp.bet.model.Ticket; import com.paj.project.bettingapp.util.TicketListCreator; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.TimeValue; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import java.util.List; import java.util.concurrent.TimeUnit; import static com.paj.project.bettingapp.util.TicketListCreator.updateTicketList; @BenchmarkMode(Mode.SingleShotTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @State(Scope.Benchmark) @Warmup(iterations = 1) @Measurement(iterations = 1) public class JPABenchmark { @State(Scope.Thread) public static class MyState { List<Ticket> tickets; long time1; EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa"); EntityManager em = emf.createEntityManager(); public void updateTickets() { updateTicketList(tickets); } public void start() { tickets = TicketListCreator.buildTicketList(); time1 = System.nanoTime(); } public void create() { System.out.println("Insert execution time: " + (System.nanoTime() - time1) / 1000_000); time1 = System.nanoTime(); } public void read() { System.out.println("Read execution time: " + (System.nanoTime() - time1) / 1000_000); } public void update() { System.out.println("Update execution time: " + (System.nanoTime() - time1) / 1000_000); time1 = System.nanoTime(); } public void delete() { System.out.println("Delete execution time: " + (System.nanoTime() - time1) / 1000_000); time1 = System.nanoTime(); } } public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() .include(".*" + JPABenchmark.class.getCanonicalName() + ".*") .timeout(TimeValue.hours(24)) .forks(1) .build(); new Runner(opt).run(); } @TearDown(Level.Trial) public void doTearDown(MyState state) { state.em.close(); state.emf.close(); } @Benchmark public void createReadUpdateDelete(MyState state, Blackhole bh) { state.start(); state.em.getTransaction().begin(); for (Ticket ticket : state.tickets) { state.em.persist(ticket); } state.em.getTransaction().commit(); state.create(); CriteriaBuilder cb = state.em.getCriteriaBuilder(); CriteriaQuery<Ticket> cq = cb.createQuery(Ticket.class); Root<Ticket> rootEntry = cq.from(Ticket.class); CriteriaQuery<Ticket> all = cq.select(rootEntry); TypedQuery<Ticket> allQuery = state.em.createQuery(all); bh.consume(allQuery.getResultList()); state.read(); state.updateTickets(); state.em.getTransaction().begin(); for (Ticket ticket : state.tickets) { state.em.merge(ticket); } state.em.getTransaction().commit(); state.update(); state.em.getTransaction().begin(); for (Ticket ticket : state.tickets) { state.em.remove(ticket); } state.em.getTransaction().commit(); state.delete(); } }
import { ApiProperty } from '@nestjs/swagger'; import { IsNotEmpty, IsPhoneNumber, IsString } from 'class-validator'; export class CreateUserDto { @ApiProperty() @IsString() @IsNotEmpty() name: string; @ApiProperty() @IsString() @IsNotEmpty() @IsPhoneNumber() phone: string; @ApiProperty() @IsString() @IsNotEmpty() email: string; @ApiProperty() @IsString() @IsNotEmpty() password: string; @IsString() address: string; @IsString() dateofbirth: string; @IsString() gender: string; }
<!DOCTYPE html> <html> <head> <style> /* Modify this section to solve the homework. Uncomment the codes below. */ div p { background-color: yellow; } div > p { background-color: orange; } div ~ p { background-color: blue; } div + p { background-color: green; } h2{ text-shadow: 2px 2px 5px red; } p{ font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif; font-style: italic; font-size: 14px; } a{ background-color: #0095B6; color: white; padding: 1rem; text-align: center; text-decoration: none; cursor: auto; position: absolute; } </style> </head> <body> <h2>Let's make a rainbow</h2> <p> Use combinators in internal CSS and inline CSS to produce rainbow below. Make the link into a button with "Bondi Blue" color. </p> <!--Use inline for Red; use predefined name--> <p style="background-color: red">Red</p> <div> <!--Use internal CSS + combinators for orange and yellow--> <p>Orange</p> <section> <p>Yellow</p> </section> </div> <!--Use internal CSS + combinators for green and blue--> <p>Green</p> <p>Blue</p> <!--Use inline for Indigo; use hex--> <p style="background-color: #4B0082;">Indigo</p> <!--Use inline for Indigo; use rgb--> <p style="background-color: rgb(238,130,238);">Violet</p> <a href="#">Rainbows are awesome!</a> </body> </html>
package leetcode.editor.en; //You are given the root of a binary search tree (BST) and an integer val. // // Find the node in the BST that the node's value equals val and return the //subtree rooted with that node. If such a node does not exist, return null. // // // Example 1: // // //Input: root = [4,2,7,1,3], val = 2 //Output: [2,1,3] // // // Example 2: // // //Input: root = [4,2,7,1,3], val = 5 //Output: [] // // // // Constraints: // // // The number of nodes in the tree is in the range [1, 5000]. // 1 <= Node.val <= 10⁷ // root is a binary search tree. // 1 <= val <= 10⁷ // // // Related Topics Tree Binary Search Tree Binary Tree 👍 3989 👎 157 public class SearchInABinarySearchTree { public static void main(String[] args) { Solution solution = new SearchInABinarySearchTree().new Solution(); } public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() { } TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } //leetcode submit region begin(Prohibit modification and deletion) /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public TreeNode searchBST(TreeNode root, int val) { if (root == null) { return root; } if (root.val == val) { return root; } if (root.val > val) { return searchBST(root.left, val); } return searchBST(root.right, val); } } //leetcode submit region end(Prohibit modification and deletion) }
package Tim13.BackendAuth.controller; import Tim13.BackendAuth.util.ExistConnProperties; import org.exist.xmldb.EXistResource; import org.springframework.web.bind.annotation.RestController; import org.xmldb.api.DatabaseManager; import org.xmldb.api.base.Collection; import org.xmldb.api.base.Database; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.CollectionManagementService; import org.xmldb.api.modules.XMLResource; import javax.xml.transform.OutputKeys; import java.io.File; @RestController public class UserController { private static ExistConnProperties conn; public static void retrive(ExistConnProperties conn, String args[]) throws Exception { // initialize collection and document identifiers String collectionId = null; String documentId = null; if (args.length == 2) { System.out.println("[INFO] Passing the arguments... "); collectionId = args[0]; documentId = args[1]; } else { System.out.println("[INFO] Using defaults."); collectionId = "/db/sample/library"; documentId = "1.xml"; } System.out.println("\t- collection ID: " + collectionId); System.out.println("\t- document ID: " + documentId + "\n"); // initialize database driver System.out.println("[INFO] Loading driver class: " + conn.driver); Class<?> cl = Class.forName(conn.driver); Database database = (Database) cl.newInstance(); database.setProperty("create-database", "true"); DatabaseManager.registerDatabase(database); Collection col = null; XMLResource res = null; try { // get the collection System.out.println("[INFO] Retrieving the collection: " + collectionId); col = DatabaseManager.getCollection(conn.uri + collectionId); col.setProperty(OutputKeys.INDENT, "yes"); System.out.println("[INFO] Retrieving the document: " + documentId); res = (XMLResource) col.getResource(documentId); if (res == null) { System.out.println("[WARNING] Document '" + documentId + "' can not be found!"); } else { System.out.println("[INFO] Showing the document as XML resource: "); System.out.println(res.getContent()); } } finally { //don't forget to clean up! if (res != null) { try { ((EXistResource) res).freeResources(); } catch (XMLDBException xe) { xe.printStackTrace(); } } if (col != null) { try { col.close(); } catch (XMLDBException xe) { xe.printStackTrace(); } } } } public static void store(ExistConnProperties conn, String args[]) throws Exception { // initialize collection and document identifiers String collectionId = null; String documentId = null; String filePath = null; if (args.length == 3) { System.out.println("[INFO] Passing the arguments... "); collectionId = args[0]; documentId = args[1]; filePath = args[2]; } else { System.out.println("[INFO] Using defaults."); collectionId = "/db/sample/library"; documentId = "1.xml"; filePath = "data/books.xml"; } System.out.println("\t- collection ID: " + collectionId); System.out.println("\t- document ID: " + documentId); System.out.println("\t- file path: " + filePath + "\n"); // initialize database driver System.out.println("[INFO] Loading driver class: " + conn.driver); Class<?> cl = Class.forName(conn.driver); // encapsulation of the database driver functionality Database database = (Database) cl.newInstance(); database.setProperty("create-database", "true"); // entry point for the API which enables you to get the Collection reference DatabaseManager.registerDatabase(database); // a collection of Resources stored within an XML database Collection col = null; XMLResource res = null; try { System.out.println("[INFO] Retrieving the collection: " + collectionId); col = getOrCreateCollection(collectionId); /* * create new XMLResource with a given id * an id is assigned to the new resource if left empty (null) */ System.out.println("[INFO] Inserting the document: " + documentId); res = (XMLResource) col.createResource(documentId, XMLResource.RESOURCE_TYPE); File f = new File(filePath); if (!f.canRead()) { System.out.println("[ERROR] Cannot read the file: " + filePath); return; } res.setContent(f); System.out.println("[INFO] Storing the document: " + res.getId()); col.storeResource(res); System.out.println("[INFO] Done."); } finally { //don't forget to cleanup if (res != null) { try { ((EXistResource) res).freeResources(); } catch (XMLDBException xe) { xe.printStackTrace(); } } if (col != null) { try { col.close(); } catch (XMLDBException xe) { xe.printStackTrace(); } } } } private static Collection getOrCreateCollection(String collectionUri) throws XMLDBException { return getOrCreateCollection(collectionUri, 0); } private static Collection getOrCreateCollection(String collectionUri, int pathSegmentOffset) throws XMLDBException { System.out.println(conn.uri + collectionUri); System.out.println(conn.user); System.out.println(conn.password); Collection col = DatabaseManager.getCollection(conn.uri + collectionUri, conn.user, conn.password); // create the collection if it does not exist if (col == null) { if (collectionUri.startsWith("/")) { collectionUri = collectionUri.substring(1); } String pathSegments[] = collectionUri.split("/"); if (pathSegments.length > 0) { StringBuilder path = new StringBuilder(); for (int i = 0; i <= pathSegmentOffset; i++) { path.append("/" + pathSegments[i]); } Collection startCol = DatabaseManager.getCollection(conn.uri + path, conn.user, conn.password); if (startCol == null) { // child collection does not exist String parentPath = path.substring(0, path.lastIndexOf("/")); Collection parentCol = DatabaseManager.getCollection(conn.uri + parentPath, conn.user, conn.password); CollectionManagementService mgt = (CollectionManagementService) parentCol.getService("CollectionManagementService", "1.0"); System.out.println("[INFO] Creating the collection: " + pathSegments[pathSegmentOffset]); col = mgt.createCollection(pathSegments[pathSegmentOffset]); col.close(); parentCol.close(); } else { startCol.close(); } } return getOrCreateCollection(collectionUri, ++pathSegmentOffset); } else { return col; } } }
// * Base import { Link } from 'react-router-dom'; import cn from 'classnames'; // * Styles import styles from './Button.module.css'; type TProps = { type?: 'button' | 'submit' | 'reset'; className?: string[]; color?: string; title: string; href?: string; text: string; }; function Button({ href, text, type, title, color, className = [] }: TProps) { if (href) { return ( <Link to={href} title={title} className={cn([styles.button, color && styles[color], ...className])}> <b>{text}</b> </Link> ); } return ( <button type={type} title={title} className={cn([styles.button, color && styles[color], ...className])}> <b>{text}</b> </button> ); } export default Button;
// // EditViewController.swift // Demo_Firebase_database // // Created by Артем Валерьевич on 06/10/2018. // Copyright © 2018 Артем Валерьевич. All rights reserved. // import UIKit import Firebase protocol EditObject { func editElements(numberZakaze: String?, adress: String?, numberDom: String?, numberPod: String?, numberEtaga: String?, numberKvartiry: String?, podyem: Bool?, lift: Bool?, sumPodyema: String?, index: IndexPath!) } class EditViewController: UIViewController { var delegate: EditObject? @IBOutlet weak var numberZLabel: UILabel! @IBOutlet weak var numberZ: UITextField! @IBOutlet weak var cityLocationLabel: UILabel! @IBOutlet weak var cityLocation: UITextField! @IBOutlet weak var numberDLabel: UILabel! @IBOutlet weak var numberD: UITextField! @IBOutlet weak var numberPLabel: UILabel! @IBOutlet weak var numberP: UITextField! @IBOutlet weak var numberELabel: UILabel! @IBOutlet weak var numberE: UITextField! @IBOutlet weak var numberKLabel: UILabel! @IBOutlet weak var numberK: UITextField! @IBOutlet weak var podyemLabel: UILabel! @IBOutlet weak var sumPodyem: UITextField! @IBOutlet weak var podyem: UISwitch! @IBOutlet weak var liftOutlet: UILabel! @IBOutlet weak var lift: UISwitch! @IBOutlet weak var saveButtonOutlet: UIButton! { didSet { saveButtonOutlet.layer.cornerRadius = 7 saveButtonOutlet.layer.borderWidth = 1 saveButtonOutlet.layer.borderColor = UIColor.black.cgColor saveButtonOutlet.layer.masksToBounds = true } } @IBOutlet weak var viewEditObject: UIView! { didSet { viewEditObject.transform = CGAffineTransform(scaleX: 10, y: 10) viewEditObject.layer.cornerRadius = 15 viewEditObject.layer.borderWidth = 1 viewEditObject.layer.borderColor = UIColor.black.cgColor viewEditObject.layer.masksToBounds = true viewEditObject.alpha = 0 } } var arrays: DataObject? var indexPath = IndexPath() @IBOutlet weak var blurEffect: UIVisualEffectView! var effect: UIVisualEffect! override func viewDidLoad() { super.viewDidLoad() effect = blurEffect.effect blurEffect.effect = nil numberZLabel.alpha = 0 numberZ.alpha = 0 cityLocationLabel.alpha = 0 cityLocation.alpha = 0 numberDLabel.alpha = 0 numberD.alpha = 0 numberPLabel.alpha = 0 numberP.alpha = 0 numberELabel.alpha = 0 numberE.alpha = 0 numberKLabel.alpha = 0 numberK.alpha = 0 podyemLabel.alpha = 0 sumPodyem.alpha = 0 podyem.alpha = 0 liftOutlet.alpha = 0 lift.alpha = 0 saveButtonOutlet.alpha = 0 numberZ.placeholder = arrays?.numberZakaza cityLocation.placeholder = arrays?.adress numberD.placeholder = arrays?.numberDom numberP.placeholder = arrays?.numberPod numberE.placeholder = arrays?.numberEtaga numberK.placeholder = arrays?.numberKvartiry sumPodyem.placeholder = arrays?.sumPodyema if arrays?.sumPodyema == "" { lift.isOn = true podyem.isOn = false } else { lift.isOn = false podyem.isOn = true } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) animationIn() } func animationIn() { UIView.animate(withDuration: 0.3, animations: { self.blurEffect.effect = self.effect }) { (_) in UIView.animate(withDuration: 0.5, animations: { self.viewEditObject.transform = CGAffineTransform.identity self.viewEditObject.alpha = 1 }, completion: { (_) in self.animations() }) } } func animationOut() { delegate?.editElements(numberZakaze: numberZ.text, adress: cityLocation.text, numberDom: numberD.text, numberPod: numberP.text, numberEtaga: numberE.text, numberKvartiry: numberK.text, podyem: podyem.isOn, lift: lift.isOn, sumPodyema: sumPodyem.text, index: indexPath) UIView.animate(withDuration: 0.4, animations: { self.viewEditObject.transform = CGAffineTransform(scaleX: 10, y: 10) self.viewEditObject.alpha = 0 }) { (_) in UIView.animate(withDuration: 0.4, animations: { self.blurEffect.alpha = 0 self.blurEffect.effect = nil }, completion: { (_) in self.dismiss(animated: false, completion: nil) }) } } func animations() { let arrayElements = [numberZLabel, numberZ, cityLocationLabel, cityLocation, numberDLabel, numberD, numberPLabel, numberP, numberELabel, numberE, numberKLabel, numberK, podyemLabel, sumPodyem, podyem, liftOutlet, lift, saveButtonOutlet] for (index, button) in arrayElements.enumerated() { let delay = 0.1 * Double(index) let delayT = delay / 2 UIView.animate(withDuration: 0.4, delay: delayT, animations: { button?.alpha = 1 }, completion: nil) } } @IBAction func cancel(_ sender: UIButton) { animationOut() } } extension EditViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == numberZ { cityLocation.becomeFirstResponder() } else if textField == cityLocation { numberD.becomeFirstResponder() } else if textField == numberD { numberP.becomeFirstResponder() } else if textField == numberP { numberE.becomeFirstResponder() } else if textField == numberE { numberK.becomeFirstResponder() } else if textField == numberK { view.endEditing(true) return true } return false } }
<?php declare(strict_types=1); namespace Domain\Date; use Domain\Date\Dto\InputDto; use Domain\Date\Dto\ResultDto; use DateTime; use DateTimeZone; final class DateManager { private const SECONDS_IN_HOUR = 60; public function process( InputDto $inputDto ): ResultDto { $result = new ResultDto(); $dateTime = self::getDateTimeForSpecificDate( $inputDto->getDate(), $inputDto->getTimezone(), ); $result ->setTimezoneMinutesOffsetWithUtc( $this->getOffsetWithUtcInMinutes($dateTime), ) ; $result ->setDayCountInFebruaryInSelectedYear( $this->getCurrentYearFebruaryDayCount($dateTime), ) ; $result ->setSelectedMonthDateDayCount( $this->getSelectedMonthDayCount($dateTime), ) ; $result ->setSelectedMonthName( $this->getSelectedMonthName($dateTime), ) ; return $result; } private function getOffsetWithUtcInMinutes(DateTime $dateTime): string { $offsetInMinutes = $dateTime->getOffset() / self::SECONDS_IN_HOUR; return sprintf('%+d', $offsetInMinutes); } private function getSelectedMonthDayCount(DateTime $dateTime): int { return (int) $dateTime->format('t'); } private function getCurrentYearFebruaryDayCount(DateTime $dateTime): int { return (int) (clone $dateTime) ->modify('first day of february') ->format('t') ; } private function getDateTimeForSpecificDate( string $date, ?string $timezone = null ): DateTime { return new DateTime($date, $timezone ? new DateTimeZone($timezone) : null); } private function getSelectedMonthName(DateTime $dateTime): string { return $dateTime->format('F'); } }
import {Routes, RouterModule} from '@angular/router'; import { ModuleWithProviders } from '@angular/core'; import { CursoDetalheComponent } from './cursos/curso-detalhe/curso-detalhe.component'; import { CursoNaoEncontradoComponent } from './cursos/curso-nao-encontrado/curso-nao-encontrado.component'; import { HomeComponent } from './home/home.component'; import { LoginComponent } from './login/login.component'; import { CursosComponent } from './cursos/cursos.component'; const APP_ROUTES: Routes =[ {path: '', component: HomeComponent}, {path: 'login', component: LoginComponent}, {path: 'cursos', component: CursosComponent}, {path: 'naoEncontrado', component: CursoNaoEncontradoComponent}, {path: 'curso/:id', component: CursoDetalheComponent} ] ; export const routing: ModuleWithProviders = RouterModule.forRoot(APP_ROUTES) ;
import { useState } from "react"; import GridLayout from "react-grid-layout"; import "react-grid-layout/css/styles.css"; import "react-resizable/css/styles.css"; // eslint-disable-next-line react/prop-types function Card({ children, isSelected, onClick }) { return ( <div className={`border border-gray-400 rounded p-5 h-20 w-full ${ isSelected ? "!border-green-500 !text-green-800 font-semibold cursor-not-allowed" : "cursor-pointer" }`} onClick={onClick} > {children} </div> ); } function App() { const [state, setState] = useState({ a: true, b: false, c: true, }); return ( <div className="flex"> <div className="bg-gray-50 h-screen w-[1000px] relative shadow-inner"> <GridLayout cols={12} rowHeight={100} width={1000}> {state["a"] ? ( <div key="a" className="w-10 h-[50px] bg-white border border-gray-300 shadow rounded p-5" data-grid={{ x: 0, y: 0, w: 6, h: 1 }} > Component A </div> ) : null} {state["b"] ? ( <div key="b" className="w-10 h-[50px] bg-white border border-gray-300 shadow rounded p-5" data-grid={{ x: 0, y: 0, w: 6, h: 1 }} > Component B </div> ) : null} {state["c"] ? ( <div key="c" className="w-10 h-[50px] bg-white border border-gray-300 shadow rounded p-5" data-grid={{ x: 0, y: 0, w: 6, h: 1 }} > Component C </div> ) : null} </GridLayout> </div> <div className="p-5"> <div>Select Widget</div> <div className="space-y-5 mt-3"> <Card isSelected={state["a"]} onClick={() => setState((prev) => ({ ...prev, a: !prev.a }))} > Component A </Card> <Card isSelected={state["b"]} onClick={() => setState((prev) => ({ ...prev, b: !prev.b }))} > Component B </Card> <Card isSelected={state["c"]} onClick={() => setState((prev) => ({ ...prev, c: !prev.c }))} > Component C </Card> </div> </div> </div> ); } export default App;
/* Custom validators to use everywhere. */ // SINGLE FIELD VALIDATORS import { FormGroup, FormControl } from '@angular/forms'; export function emailValidator(control: FormControl): { [key: string]: any } { var emailRegexp = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i; if (control.value && !emailRegexp.test(control.value)) { return { invalidEmail: true }; } } // FORM GROUP VALIDATORS export function matchingPasswords(passwordKey: string, confirmPasswordKey: string) { return (group: FormGroup): { [key: string]: any } => { let password = group.controls[passwordKey]; let confirmPassword = group.controls[confirmPasswordKey]; if (password.value !== confirmPassword.value) { return { mismatched: true }; } } } export function passValidator(control: any): any { let passreg = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20}$/; if (control.value && !passreg.test(control.value)) { return { pattern: true }; } }
package tests import ( "testing" "github.com/podocarp/goscript/machine" "github.com/stretchr/testify/require" ) func TestLoopsBasic(t *testing.T) { m := machine.NewMachine() // test loops stmt := ` func (A float64, B float64) { for i := 0; i < B; i++ { A += i } return A } ( 1 , 10) ` res, err := m.ParseAndEval(stmt) require.Nil(t, err, err) require.EqualValues(t, 46, res.Value) stmt = `func(a, b) { for i := 0; i < a; i++ { b += i } return b }( 10, 1 ) ` res, err = m.ParseAndEval(stmt) require.Nil(t, err, err) require.EqualValues(t, 46.0, res.Value) stmt = `func(a, b) { for i := 0; i < a; { b = i i++ } return b }( 10, 1 ) ` res, err = m.ParseAndEval(stmt) require.Nil(t, err, err) require.EqualValues(t, 9, res.Value) } func TestLoopsContinue(t *testing.T) { m := machine.NewMachine() stmt := ` func (A, B int) { for i := 0; i < B; i++ { if i > 4 { if i % 2 == 0 { continue } } A += i } return A } ( 1 , 10) ` res, err := m.ParseAndEval(stmt) require.Nil(t, err, err) require.EqualValues(t, 32, res.Value) } func TestLoopsRangeArray(t *testing.T) { m := machine.NewMachine() // test range over array stmt := ` func () { a := 0 vals := []int{2,4,6,8,10} for i := range vals { a += i } return a } () ` res, err := m.ParseAndEval(stmt) require.Nil(t, err, err) require.EqualValues(t, 10, res.Value) // test range over array with elem stmt = ` func () { a := 0 vals := []int{2,4,6,8,10} for i, b := range vals { a += i + b } return a } () ` res, err = m.ParseAndEval(stmt) require.Nil(t, err, err) require.EqualValues(t, 40, res.Value) }
#include <iostream> #include <set> using namespace std; /** * set 풀이 * multiset 이용 - set과 다르게 중복 값이 저장된다. & 정렬 * * set에서 삭제 - erase() * set의 맨 마지막 값(최댓값) 조회 - --ms.end() * set의 맨 앞 값(최솟값) 조회 - ms.begin() */ int main() { ios::sync_with_stdio(false); cin.tie(NULL); int t, k, n; char cmd; cin >> t; while (t--) { multiset<int> ms; cin >> k; while (k--) { //입력 cin >> cmd >> n; //연산 switch (cmd) { case 'I': //I 연산 ms.insert(n); break; case 'D': //D 연산 if (ms.empty()) //ms가 비어있다면 연산 무시 break; if (n == 1) //최댓값 삭제 ms.erase(--ms.end()); if (n == -1) //최솟값 삭제 ms.erase(ms.begin()); break; } } //출력 if (ms.empty()) cout << "EMPTY\n"; else cout << *(--ms.end()) << ' ' << *ms.begin() << '\n'; } }
import { useEffect, useState } from 'react'; const usePageTitle = (initialTitle: string): [string, (arg: string)=>void] => { const [title, changeTitle] = useState(initialTitle); useEffect(() => { document.title = title; }, [title]); return [title, changeTitle]; }; export default usePageTitle;
"""File Handling.""" from pathlib import Path import pandas as pd class FileHandling: """Handles Files.""" def read_csv_file(self, path_to_file: str) -> pd.DataFrame: """Read csv files. Parameters ---------- path_to_file : str path to file Returns ------- pd.DataFrame File data """ try: return pd.read_csv(path_to_file) except FileNotFoundError: print("File not found. Please check the file path.") except pd.errors.EmptyDataError: print("The file is empty.") except pd.errors.ParserError: print("There was an error parsing the file.") except Exception as e: print("An error occurred:", e) def write_file(self, path_to_file: Path, data: pd.DataFrame): """Write csv files. Parameters ---------- path_to_file : Path path to destination data : pd.DataFrame Dataframe to write """ try: data.to_csv(path_to_file, index=False) except Exception as e: print(f"An error occurred while writing data to the CSV file: {e}")
import { inject, Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, RouterStateSnapshot, TitleStrategy, } from '@angular/router'; import { BehaviorSubject, tap } from 'rxjs'; import { Title } from '@angular/platform-browser'; import { LoggerService } from '@sandbox/logging'; @Injectable({ providedIn: 'root', }) export class PageTitleService extends TitleStrategy { private _title = inject(Title); private _logger = inject(LoggerService); private _currentTitleSubject = new BehaviorSubject(''); title$ = this._currentTitleSubject .asObservable() .pipe( tap((title) => this._logger.log('PageTitleService.title$', { title })), ); private getTitle(root: ActivatedRouteSnapshot): string { if (root.data && root.data['title']) return root.data['title']; if (root.children && root.children.length) { return this.getTitle(root.children[0]); } return ''; } updateTitle(snapshot: RouterStateSnapshot): void { const title = this.getTitle(snapshot.root); this._logger.log('PageTitleService.updateTitle', { snapshot, title }); this._title.setTitle(title); this._currentTitleSubject.next(title); } }
import { Suspense } from 'react' import { ErrorBoundary } from 'react-error-boundary' import { useQueryErrorResetBoundary } from '@tanstack/react-query' import dynamic from 'next/dynamic' import { StyledStakingDashboard } from './styled' import Image from 'components/Image' import Apr from './Apr' import Fallback from './AprFallback' import Loading from './AprLoading' function StakingDashboard() { const { reset } = useQueryErrorResetBoundary() return ( <StyledStakingDashboard> <div className="imageContainer"> <Image className="image" src="/wncg-3d.webp" alt="Wrapped nine chronicles gold" priority /> </div> <ErrorBoundary onReset={reset} fallbackRender={({ resetErrorBoundary }) => ( <Fallback refetch={resetErrorBoundary} /> )} > <Suspense fallback={<Loading />}> <Apr /> </Suspense> </ErrorBoundary> </StyledStakingDashboard> ) } export default dynamic(() => Promise.resolve(StakingDashboard), { ssr: false })
package com.rb.anytextwiget.jetpackUI import android.content.Context import android.content.Intent import android.provider.MediaStore import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Create import androidx.compose.material.icons.rounded.Delete import androidx.compose.material3.Button import androidx.compose.material3.DismissDirection import androidx.compose.material3.DismissValue import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.SwipeToDismiss import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.rememberDismissState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshots.SnapshotStateList import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.rememberNestedScrollInteropConnection import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.TextUnitType import androidx.compose.ui.unit.dp import androidx.compose.ui.window.PopupProperties import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.jaredrummler.android.colorpicker.ColorPickerDialog import com.rb.anytextwiget.AppUtils import com.rb.anytextwiget.AppUtils.Companion.getSavedColors import com.rb.anytextwiget.AppUtils.Companion.getSavedWidgets import com.rb.anytextwiget.AppUtils.Companion.removeColor import com.rb.anytextwiget.AppUtils.Companion.saveTheNewColor import com.rb.anytextwiget.ColorData import com.rb.anytextwiget.ColorSelectionSheet import com.rb.anytextwiget.CreateWidgetActivity import com.rb.anytextwiget.R import com.rb.anytextwiget.WidgetData import com.rb.anytextwiget.WidgetUIData import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import java.util.Locale class ColoursSheet(var context: AppCompatActivity) { var coloursList = mutableStateListOf<ColorData>() lateinit var colourSheetInterface: ColorSelectionSheet.ColorSheetInterface var editColorPosition = 0 var sharedPreferences = context.getSharedPreferences("colorspref", Context.MODE_PRIVATE ) init { colourSheetInterface = object : ColorSelectionSheet.ColorSheetInterface { override fun saveColor(colorData: ColorData) { saveTheNewColor(context, colorData) coloursList.add(colorData) } override fun editColor(newColor: Int) { updateAndSaveEditedColor(newColor) } } (context as CreateWidgetActivity).seTColorSheetInterface(colourSheetInterface) } @OptIn(ExperimentalMaterial3Api::class) @Composable fun ColoursSheetUI(colourSelectedEvent: (colourData: ColorData) -> Unit, onDismiss: () -> Unit) { val fontUtils = FontUtils() coloursList = SnapshotStateList<ColorData>() val sharedPreferences = LocalContext.current.getSharedPreferences( "colorspref", Context.MODE_PRIVATE ) val context = LocalContext.current //Check and get the default colors. val defaultColorsJSON = sharedPreferences.getString("defaultcolors", null) if (defaultColorsJSON == null) { //Add the default colors to shared preferences coloursList.addAll(AppUtils.addDefaultColors(LocalContext.current)) } else { val defaultColors = AppUtils.getDefaultColorsFromJson(defaultColorsJSON) if (defaultColors.size == 6) { //Add the new color to shared preferences coloursList.addAll(AppUtils.addDefaultColors(LocalContext.current)) } else { coloursList.addAll(defaultColors) } } //Get the user's saved colors val savedColors = sharedPreferences.getString("savedcolors", null) if (savedColors != null) { coloursList.addAll(getSavedColors(LocalContext.current)) } val scrollState = rememberScrollState() ModalBottomSheet(onDismissRequest = onDismiss) { Text( text = "${LocalContext.current.getString(R.string.color).replace("c", "C")}s", fontFamily = fontUtils.openSans(FontWeight.Bold), fontSize = TextUnit(28f, TextUnitType.Sp), modifier = Modifier .padding(20.dp) .weight(1f, fill = false) ) LazyColumn(modifier = Modifier .weight(2f) .fillMaxWidth()) { items(coloursList) { ColourItem(colourData = it, fontUtils = fontUtils, colourSelectedEvent) } } Button( onClick = { val builder = ColorPickerDialog.newBuilder() builder.setColor(android.graphics.Color.parseColor("#ffffff")) builder.setDialogTitle(R.string.colorPickerTitle) builder.setSelectedButtonText(R.string.colorPickerAddButton) builder.setShowColorShades(true) builder.setDialogType(ColorPickerDialog.TYPE_CUSTOM) builder.setShowAlphaSlider(true) builder.setDialogId(21) builder.show(context as AppCompatActivity) }, contentPadding = PaddingValues(15.dp), modifier = Modifier .fillMaxWidth() .padding(10.dp, 15.dp) .weight(1f, fill = false) ) { Icon( painter = painterResource(id = R.drawable.ic_round_add_circle_24), contentDescription = "Add new ${LocalContext.current.getString(R.string.color)} button icon", modifier = Modifier.padding(10.dp, 0.dp) ) Text( text = "Add a new ${LocalContext.current.getString(R.string.color)}", fontFamily = fontUtils.openSans(FontWeight.SemiBold), fontSize = TextUnit(18f, TextUnitType.Sp), ) } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun ColourItem(colourData: ColorData, fontUtils: FontUtils, colourSelectedEvent: (colourData: ColorData) -> Unit) { var colour = MaterialTheme.colorScheme.onBackground try { colour = Color(android.graphics.Color.parseColor(colourData.colorHexCode)) } catch (e: Exception) { e.printStackTrace() } var showColourOptions by remember { mutableStateOf(false) } val context = LocalContext.current TextButton( modifier = Modifier.fillMaxWidth(), contentPadding = PaddingValues(15.dp), onClick = {colourSelectedEvent(colourData)}) { Image( painter = painterResource(id = R.drawable.ic_round_lens_24), contentDescription = "${colourData.colorName}", modifier = Modifier .align(Alignment.CenterVertically) .padding(10.dp, 0.dp), colorFilter = ColorFilter.tint(colour) ) Column( modifier = Modifier .align(Alignment.CenterVertically) .weight(1f) ) { Text( text = colourData.colorName!!, fontSize = TextUnit(18f, TextUnitType.Sp), fontFamily = fontUtils.openSans(FontWeight.Normal), textAlign = TextAlign.Start, ) Text( text = colourData.colorHexCode!!, fontSize = TextUnit(16f, TextUnitType.Sp), fontFamily = fontUtils.openSans(FontWeight.Normal), textAlign = TextAlign.Start, ) } Box(modifier = Modifier.align(Alignment.CenterVertically)) { //More options. IconButton(onClick = { showColourOptions = true }) { Icon( painter = painterResource(id = R.drawable.more_horiz_24dp), contentDescription = "${LocalContext.current.getString(R.string.color)} options" ) } //Colour options. DropdownMenu( expanded = showColourOptions, onDismissRequest = { }, properties = PopupProperties( dismissOnBackPress = true, dismissOnClickOutside = true, excludeFromSystemGesture = true ) ) { DropdownMenuItem( text = { Text( text = "Edit", fontFamily = fontUtils.openSans( FontWeight.SemiBold ) ) }, leadingIcon = { Icon( imageVector = Icons.Rounded.Create, contentDescription = "Edit ${LocalContext.current.getString(R.string.color)} Option" ) }, onClick = { showEditColorDialog(colourData) editColorPosition = coloursList.indexOf(colourData) showColourOptions = false }) DropdownMenuItem( text = { Text( text = "Delete", fontFamily = fontUtils.openSans( FontWeight.SemiBold ) ) }, leadingIcon = { Icon( imageVector = Icons.Rounded.Delete, contentDescription = "Remove ${LocalContext.current.getString(R.string.color)} Option" ) }, onClick = { removeColor(context, colourData) showColourOptions = false }) } } } } fun showEditColorDialog(colorData: ColorData){ val builder = ColorPickerDialog.newBuilder() builder.setColor(android.graphics.Color.parseColor("#ffffff")) try { builder.setColor(android.graphics.Color.parseColor(colorData.colorHexCode)) } catch (e:IllegalArgumentException){ e.printStackTrace() } builder.setDialogTitle(R.string.editColor) builder.setSelectedButtonText(R.string.colorPickerEditButton) builder.setShowColorShades(true) builder.setDialogType(ColorPickerDialog.TYPE_CUSTOM) builder.setShowAlphaSlider(true) builder.setDialogId(22) builder.show(context) } fun updateAndSaveEditedColor(newColor:Int){ var colorHexCode= String.format("#%08X",newColor).uppercase(Locale.getDefault()) val colorID = coloursList[editColorPosition].ID //Check if the edited color is a valid color try { android.graphics.Color.parseColor(colorHexCode) } catch (e: IllegalArgumentException){ colorHexCode="#000000" e.printStackTrace() } //Update the UI coloursList.get(editColorPosition).colorHexCode=colorHexCode CoroutineScope(Dispatchers.IO).launch{ //Save the edited color val currentSavedColors=ArrayList<ColorData>() //Save the color to shared preferences //Get the current saved colors and add them to a list val savedColorsJSON= sharedPreferences.getString("savedcolors", null) if (savedColorsJSON!=null){ currentSavedColors.addAll(getSavedColors(context)) } //Edit the color for (data in currentSavedColors){ if (data.ID==colorID){ data.colorHexCode=colorHexCode //Save back the updated list val gson=Gson() val json=gson.toJson(currentSavedColors) sharedPreferences.edit().putString("savedcolors", json).apply() break } } //Update the color in saved widgets updateSavedWidgets(colorHexCode,colorID.toString()) //Update the UI widgets updateUIWidgets(colorHexCode, colorID.toString()) } } suspend fun updateSavedWidgets(colorHexCode:String,colorID:String){ //Edit the color in the saved widgets //Get the saved widgets val savedWidgetsList=ArrayList<WidgetData>() val widgetPreferences=context.getSharedPreferences("widgetspref", Context.MODE_PRIVATE) val savedWidgetsJSON=widgetPreferences.getString("savedwidgets", null) if (savedWidgetsJSON!=null){ val savedWidgets=getSavedWidgets(savedWidgetsJSON) savedWidgetsList.addAll(savedWidgets) } for (data in savedWidgetsList){ if (data.widgetTextColor?.ID ==colorID){ data.widgetTextColor?.colorHexCode =colorHexCode } if (data.widgetBackGroundType.equals("color")){ if (data.widgetBackgroundColor?.ID ==colorID){ data.widgetBackgroundColor?.colorHexCode =colorHexCode } } } //Save back to shared preferences val gson=Gson() val json=gson.toJson(savedWidgetsList) widgetPreferences.edit().putString("savedwidgets", json).apply() } fun getSavedUIWidgets(json: String):MutableList<WidgetUIData>{ val gson=Gson() val type=object: TypeToken<MutableList<WidgetUIData>>(){}.type return gson.fromJson(json, type) } fun saveEditedUIWidget(editedUIList:List<WidgetUIData>){ val sharedPreferences=context.getSharedPreferences("widgetspref", Context.MODE_PRIVATE) val uiList=ArrayList<WidgetUIData>() //Add all UI widgets and save to shared preferences uiList.addAll(editedUIList) val gson=Gson() val savingJSON= gson.toJson(uiList) sharedPreferences.edit().putString("saveduiwidgets", savingJSON).apply() } suspend fun updateUIWidgets(newColor: String,colorID:String){ //Get the saved UI widgets val sharedPreferences =context.getSharedPreferences("widgetspref", Context.MODE_PRIVATE) val uiList=ArrayList<WidgetUIData>() val savedUIWidgetsJSON=sharedPreferences.getString("saveduiwidgets", null) if (savedUIWidgetsJSON!=null){ val savedUIWidgets=getSavedUIWidgets(savedUIWidgetsJSON) uiList.addAll(savedUIWidgets) } for (data in uiList){ if (data.widgetData!!.widgetTextColor?.ID ==colorID){ data.widgetData!!.widgetTextColor!!.colorHexCode=newColor saveEditedUIWidget(uiList) } if (data.widgetData!!.widgetBackGroundType.equals("color")){ if (data.widgetData!!.widgetBackgroundColor!!.ID==colorID){ data.widgetData!!.widgetBackgroundColor?.colorHexCode =newColor saveEditedUIWidget(uiList) } } } //Update the widgets on home screen AppUtils.updateUIWidgets(context) } }
import { Component, OnInit } from '@angular/core'; import { Store } from '@ngxs/store'; import { CountriesState, GetCountryCodes, GetCountryById, UpdateCountry } from './countries-state'; import { Country } from './country'; import { Observable } from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { countries$: Observable<Country[]>; countryCodes$: Observable<string[]>; latestFetchedCountry$: Observable<Country>; constructor( private store: Store ) { this.store.dispatch(new GetCountryCodes()); } ngOnInit() { this.countries$ = this.store.select<Country[]>(CountriesState.getCountries()); this.countryCodes$ = this.store.select(CountriesState.getCountryCodes()); } countryCodeClicked(alpha2Code: string) { this.store.dispatch(new GetCountryById(alpha2Code)); this.latestFetchedCountry$ = this.store.select(CountriesState.getCountryById(alpha2Code)); } updateCountry(country: Country) { this.store.dispatch(new UpdateCountry(country.alpha2Code, { population: 100 })); } }
<?php namespace App\Models\Formularios; use Carbon\Carbon; use App\Models\User; use App\Enums\EstadoType; use App\Models\Tipos\Estado; use App\Models\Tipos\TipoMoneda; use App\Models\Tipos\TipoEntidad; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Storage; use App\Models\Formularios\TipoFormulario; use Illuminate\Database\Eloquent\Factories\HasFactory; class Formulario extends Model { use HasFactory; protected $table = 'formulario'; protected $fillable = [ 'nombre_beneficiario', 'cedula_beneficiario', 'banco_beneficiario', 'telefono_beneficiario', 'nro_cuenta', 'tipo_persona', 'tipo_cuenta', 'monto_enviar', 'monto_convertido', 'imagen_comprobante', 'terminos_comprobante', 'email_comprobante', 'id_moneda', 'id_entidad', 'id_formulario', 'id_user', 'id_estado', 'archivo', 'pais', ]; const RELATION_SHIPS = ['tipo_moneda', 'tipo_entidad', 'tipo_formulario', 'user', 'estado']; public function tipo_moneda() { return $this->belongsTo(TipoMoneda::class, 'id_moneda'); } public function tipo_entidad() { return $this->belongsTo(TipoEntidad::class, 'id_entidad'); } public function tipo_formulario() { return $this->belongsTo(TipoFormulario::class, 'id_formulario')->with('tasa_cambios'); } public function user() { return $this->belongsTo(User::class, 'id_user'); } public function estado() { return $this->belongsTo(Estado::class, 'id_estado'); } public function getCreatedAtAttribute($value) { return Carbon::parse($value)->format('d/m/Y H:i:s'); } public function getIdEstadoAttribute($value) { switch ($value) { case 1: return EstadoType::PENDIENTE; case 2: return EstadoType::EN_PROCESO; case 3: return EstadoType::ENTREGADO; case 4: return EstadoType::CANCELADO; default: return 'Desconocido'; } } public function getImagenComprobanteAttribute() { $disk = 'comprobante_disk'; if ($this->attributes['imagen_comprobante']) { if (!Storage::disk($disk)->exists($this->attributes['imagen_comprobante'])) { return asset('img/no-image.png'); } return Storage::disk($disk)->url($this->attributes['imagen_comprobante']); } return null; } public function getArchivoAttribute() { $disk = 'comprobante_disk'; if ($this->attributes['archivo']) { if (!Storage::disk($disk)->exists($this->attributes['archivo'])) { return asset('img/no-image.png'); } return Storage::disk($disk)->url($this->attributes['archivo']); } return null; } }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:p="http://primefaces.org/ui" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core"> <h:head> <title>Cadastro de usuários</title> </h:head> <h:body> <center> <div> <h:form id="formularioCadastroUsuario"> <p:messages id="messages" showDetail="true" closable="true"> <p:autoUpdate /> </p:messages> <table style="border: 1.5px solid #D3D3D3; border-radius: 10px; padding: 5px;"> <caption style="font-size: 25px;">Cadastrar usuários</caption> <tr> <th><p:outputLabel value="Login suário " /></th> <th><p:inputText value="#{usuarioBean.usuario.usuario}" /></th> </tr> <tr> <th><p:outputLabel value="Nome " /></th> <th><p:inputText value="#{usuarioBean.usuario.nome}" /></th> </tr> <tr> <th><p:outputLabel value="Senha " /></th> <th><p:password value="#{usuarioBean.usuario.senha}" /></th> </tr> <tr> <th style="text-align: right;"><p:commandButton value="Salvar" action="#{usuarioBean.salvar}" update="formularioCadastroUsuario" /></th> </tr> </table> <p:dataTable value="#{usuarioBean.lista}" var="u"> <f:facet name="header">Lista de Usuários</f:facet> <p:column headerText="Id" visible="F"> <p:outputLabel value="#{u.id}" /> </p:column> <p:column headerText="Usuário"> <p:outputLabel value="#{u.usuario}" /> </p:column> <p:column headerText="Nome do usuário"> <p:outputLabel value="#{u.nome}" /> </p:column> <p:column headerText="Ações"> <p:commandButton value="&#128078;" title="Excluir" action="#{usuarioBean.excluir(u.id,u.nome)}" update="formularioCadastroUsuario" styleClass="ui-button-danger"> </p:commandButton> <p:commandButton value="&#9997;" title="Editar" action="edicaoUsuario" update="formularioCadastroUsuario" styleClass="ui-button-info"> <f:setPropertyActionListener value="#{u}" target="#{usuarioBean.usuario}" /> </p:commandButton> </p:column> </p:dataTable> <p:commandButton value="Voltar para o menu de opções" action="opcoes" /> </h:form> </div> </center> </h:body> </html>
package com.example.java; import jakarta.validation.Valid; import jakarta.validation.constraints.Email; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; import lombok.Data; import lombok.Getter; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController @Validated public class UserController { @PostMapping("/user") public ResponseEntity<String> createUser(@Valid @RequestBody User user) { // user 객체가 유효한지 여부를 확인하고 유효하지 않으면 예외가 발생합니다. // 유효한 경우 처리 로직을 추가하십시오. System.out.println(user.id +"--" + user.username); return ResponseEntity.ok( "User created successfully"); } @Data public static class User { @NotNull(message = "\"hostId\": You must provide hostId.") private Long id; @NotBlank @Size(min = 2, max = 50) private String username; @Email private String email; // 생성자, 게터, 세터 등 필요한 메서드 추가 } }
# Using XAMPP with MySQL Database and phpMyAdmin ## Database Connection - To access MySQL database using XAMPP: ```bash mysql -u root -h localhost -p ``` - Enter your password when prompted. ## Basic MySQL Commands - Show available databases: ```sql show databases; ``` - Use a specific database: ```sql use databasedb_name; ``` - Show tables in the current database: ```sql show tables; ``` - Describe a table structure: ```sql desc itembox; ``` - Select specific columns from a table: ```sql select name, product from itembox; ``` ## XSS (Cross-Site Scripting) ```html <script>alert("hey guys");</script> ``` ## Defensive Measures - Use `strip_tags()` as a filter to remove HTML tags: - Reference: [PHP Manual - strip_tags()](https://www.php.net/manual/en/function.strip-tags.php) - Implement SQL Injection Prevention: - Sanitize user inputs. - Avoid directly inserting user inputs into SQL queries. - Example queries: ```php $query ="insert into itembox(date ,name ,product ,price ,screenshot,approved)values(NOW(),'$name','$product','$price','$screenshot',false)"; ``` ## Examples of SQL Injection - Using common SQL injection strings: - Username: `1' or '1'='1` - Password: `1' or '1'='1` - Bypassing authentication: - Username: `admin'--` - Password: anything ## Additional Resources - **Demo Test Website**: [demo.testfire.net](http://demo.testfire.net) - **Vulnerable PHP Test Site**: [testphp.vulnweb.com](http://testphp.vulnweb.com) ## Additional PHP Functions - `trim()`: Used to remove whitespace or other predefined characters from the beginning and end of a string. - `is_numeric()`: Checks whether a variable is a number or a numeric string.
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:test_teknikal_fan/cubit/auth_cubit.dart'; import 'package:test_teknikal_fan/cubit/email_varification_cubit.dart'; import 'package:test_teknikal_fan/screens/email_verification_screen.dart'; import 'package:test_teknikal_fan/screens/home_screen.dart'; import 'package:test_teknikal_fan/screens/login_screen.dart'; import 'package:test_teknikal_fan/utils/theme.dart'; import 'package:test_teknikal_fan/utils/validator.dart' as validator; import 'package:test_teknikal_fan/widgets/btn_widget.dart'; import 'package:test_teknikal_fan/widgets/text_form_field.dart'; class RegisterScreen extends StatefulWidget { const RegisterScreen({super.key}); @override State<RegisterScreen> createState() => _RegisterScreenState(); } class _RegisterScreenState extends State<RegisterScreen> { final _formKey = GlobalKey<FormState>(); late bool _obscureText = true; final _usernameController = TextEditingController(); final _emailController = TextEditingController(); final _passwordController = TextEditingController(); @override Widget build(BuildContext context) { final emailVerificationCubit = BlocProvider.of<EmailVarificationCubit>(context); Widget heading() => Container( margin: EdgeInsets.only( top: 30, left: defaultMargin, right: defaultMargin, ), child: Column( children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( width: 50, height: 50, decoration: BoxDecoration( border: Border.all( color: softGreyColor, width: 3, ), borderRadius: BorderRadius.circular(10), ), child: IconButton( onPressed: () { Navigator.pop(context); }, icon: Icon( Icons.arrow_back_ios_rounded, color: blackColor, ), ), ), SizedBox(height: 24), Text( 'Hello! Register to get started', style: txBold.copyWith( color: blackColor, ), ), ], ), const SizedBox(height: 10), Image.asset( 'assets/icon.png', width: 100, height: 100, ) ], ), ); Widget formRegister() { return Container( padding: EdgeInsets.symmetric( horizontal: defaultMargin, ), child: Form( key: _formKey, autovalidateMode: AutovalidateMode.onUserInteraction, child: Wrap( runSpacing: 12, children: [ CustomTextFormField( label: 'Full Name', controller: _usernameController, validator: (validator) { if (validator!.isEmpty) { return 'Username is required'; } else if (!validator.isValidName) { return 'Username must be at least 3 characters and not contains number'; } else { return null; } }, ), CustomTextFormField( label: 'Email', controller: _emailController, validator: (validator) { if (validator!.isEmpty) { return 'Email is required'; } else if (!validator.isValidEmail) { return 'Email is not valid'; } else { return null; } }, ), CustomTextFormField( label: 'Password', controller: _passwordController, isPassword: _obscureText, validator: (validator) { if (validator!.isEmpty) { return 'Password is required'; } else { final password = validator; if (!password.hasUppercase()) { return 'Password must be at least 1 uppercase\nPassword must be at least 1 lowercase\nPassword must be at least 1 number\nPassword must be at least 8 characters'; } else if (!password.hasLowercase()) { return 'Password must be at least 1 lowercase\nPassword must be at least 1 number\nPassword must be at least 8 characters'; } else if (!password.hasDigit()) { return 'Password must be at least 1 number\nPassword must be at least 8 characters'; } else if (!password.hasMinLength(8)) { return 'Password must be at least 8 characters'; } else { return null; } } }, onChanged: (value) { setState(() { _obscureText = !_obscureText; }); }, ), CustomTextFormField( label: 'Confirm Password', // controller: _passwordController, isPassword: _obscureText, validator: (validator) { if (validator!.isEmpty) { return 'Confirm Password is required'; } else if (validator != _passwordController.text) { return 'Confirm Password is not match'; } else { return null; } }, onChanged: (value) { setState(() { _obscureText = !_obscureText; }); }, ), Padding( padding: const EdgeInsets.only(top: 24), child: BlocConsumer<AuthCubit, AuthState>( listener: (context, state) { if (state is AuthSuccess) { Navigator.pushAndRemoveUntil( context, // MaterialPageRoute(builder: (context) => HomeScreen()), MaterialPageRoute( builder: (context) => EmailVerificationScreen()), (route) => false); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('Register Success'), backgroundColor: greenColor.withOpacity(0.5), ), ); } else if (state is AuthFailed) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( // content: Text(state.message), content: Text('Waiting for process'), backgroundColor: greyColor.withOpacity(0.5), ), ); } }, builder: (context, state) { if (state is AuthLoading) { return Center( child: CircularProgressIndicator( color: primaryColor, ), ); } return CustomButtonWidget( btnName: 'Register', width: defaultMargin, statusColor: true, onPressed: () { if (_formKey.currentState!.validate()) { context.read<AuthCubit>().signUp( email: _emailController.text.trim(), password: _passwordController.text.trim(), name: _usernameController.text.trim(), ); emailVerificationCubit.sendVerificationEmail(); } else { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('Please fill the form correctly'), backgroundColor: redColor.withOpacity(0.5), ), ); } }); }, ), ) ], ), ), ); } Widget footer() => Container( margin: EdgeInsets.only( top: 50, left: defaultMargin, right: defaultMargin, ), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Already have an account?', style: txRegular.copyWith( color: greyColor, ), ), InkWell( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (context) => LoginScreen()), ); }, child: Text( 'Sign In', style: txMedium.copyWith( color: primaryColor, ), ), ), ], ), ); return Scaffold( body: SafeArea( child: SingleChildScrollView( child: Column( children: [ heading(), const SizedBox(height: 30), formRegister(), SizedBox(height: 30), footer(), SizedBox( height: 140, ) ], ), ), ), ); } }
// // WorkViewDetails.swift // iosApp // // Created by Sergey Lee on 2022/01/26. // import SwiftUI struct WorkViewDetails: View { @State var adv: Adv @State var service: Service = Service(uid: "", name: "", category: "", city: "", address: "", phone: "", description: "", latitude: "", longitude: "", social: ["","","","",""], images: "") @State var avatar: UIImage = UIImage(named: "avatar")! @State var businessImage: UIImage = UIImage(named: "logo")! @State var name: String = "Контактное лицо" @State var icon: String = "" @State var category: String = "" @State var genderString: String = "" @State var shiftString: String = "" @StateObject var serviceManager = ServiceManager() @StateObject var firestore = FireStore() var body: some View { ScrollView { VStack(alignment: .leading) { Group { if adv.createdAt != "" { Text("Добавлено: \(Util().formatDate(date: adv.updatedAt))") .font(.caption) .foregroundColor(.gray) .padding(.bottom, 5) .padding(.leading, 15) } Text(adv.name) .font(.title) .bold() .padding(.leading, 15).padding(.bottom, 5).padding(.trailing, 15) .lineLimit(3) if adv.city != "admin" && adv.city != "" { HStack { Text("Город") .font(.body) .foregroundColor(.gray) // Divider() Text(adv.city) .font(.body) }.padding(.leading, 15).padding(.bottom, 10) } if adv.price != "" { HStack { Text("ЗП") .font(.body) .foregroundColor(.gray) Text(adv.price) .font(.system(size: 20)) .bold() .minimumScaleFactor(0.1) }.padding(.leading, 15) } Divider() HStack(spacing: 10) { VStack(alignment: .leading, spacing: 10) { Text(icon) Text("Пол: ") .font(.body) .foregroundColor(.gray) Text("Смена: ") .foregroundColor(.gray) Text("Возвраст: ") .foregroundColor(.gray) Text("Визы: ") .foregroundColor(.gray) } VStack(alignment: .leading, spacing: 10) { Text(category) .font(.body) Text(genderString) .font(.body) Text(shiftString) if !adv.age.isEmpty { if adv.age[0] == "20" && adv.age[1] == "70" { Text("Любой") } else { Text(adv.age.joined(separator: "-")) .font(.headline) } } Text(adv.visa.joined(separator: ",")) } } .padding(.leading, 15).padding(.bottom, 5).padding(.trailing, 15) Divider() if adv.description != "" { Text("Описание") .font(.headline) .padding(15) Text(adv.description) // эта штука снизу убрала троеточие в тексте .minimumScaleFactor(0.1) .font(.body) .multilineTextAlignment(.leading) .lineLimit(nil) .padding(.horizontal, 15) .padding(.bottom, 20) .padding(.trailing, 15) Divider().padding(.bottom, 20) } } if adv.phone != "" { HStack { Spacer() Button(action: { Util().call(numberString: adv.phone) }) { Image(systemName: "phone.fill") Text(adv.phone) } .foregroundColor(.white) .padding() .background(Color.accentColor) .cornerRadius(15) .padding(.vertical, 20) Spacer() } } if !adv.uid.contains("aaaaaaaaaaaaaaaaaaaaaaa") { VStack(alignment: .leading) { NavigationLink(destination: OwnerView(ownerUid: String(adv.uid.prefix(28)))) { HStack { UrlImageView(urlString: String(adv.uid.prefix(28)), directory: "avatars") .frame(width: 25, height: 25) .clipShape(Circle()) Text(self.name) .foregroundColor(Color("textColor")) } } .padding(.bottom, 5) .padding(.leading, 15) if service.category != "" { NavigationLink(destination: ExpandedServiceDetails2(service: service, image: UIImage(named: "blank")!, count: service.images)) { HStack { UrlImageView(urlString: String(adv.uid.prefix(28) + "0"), directory: "images") .frame(width: 25, height: 25) .clipShape(Circle()) Text(self.service.name) .foregroundColor(Color("textColor")) } } .padding(.bottom, 5) .padding(.leading, 15) } }.padding(.bottom, 50) } } .navigationBarTitleDisplayMode(.inline) .onAppear { if adv.subcategory == "factory" { self.icon = "🏭" self.category = "Завод" } else if adv.subcategory == "construction" { self.icon = "👷🏻‍♀️" self.category = "Стройка" } else if adv.subcategory == "motel" { self.icon = "🏩" self.category = "Мотель" } else if adv.subcategory == "cafe" { self.icon = "🍽" self.category = "Общепит" } else if adv.subcategory == "farm" { self.icon = "🧑🏽‍🌾" self.category = "Сельхоз работы" } else if adv.subcategory == "delivery" { self.icon = "📦" self.category = "Почта" } else if adv.subcategory == "office" { self.icon = "💼" self.category = "Работа в офисе" } else if adv.subcategory == "otherwork" { self.icon = "👨‍🚀" self.category = "Другая работа" } if adv.gender == "👱🏼‍♂️👩🏻" { self.genderString = "👱🏼‍♂️ Мужчина и 👩🏻 Женщина" } else if adv.gender == "👱🏼‍♂️" { self.genderString = "👱🏼‍♂️ Мужчина" } else if adv.gender == "👩🏻" { self.genderString = "👩🏻 Женщина" } if adv.shift == "🌞🌚" { self.shiftString = "🌞 Чуган и 🌚 Яган" } else if adv.shift == "🌞" { self.shiftString = "🌞 Чуган" } else if adv.shift == "🌚" { self.shiftString = "🌚 Яган" } serviceManager.getMyService(uid: String(adv.uid.prefix(28))) { service in self.service = service DB().getImage(uid: String(adv.uid.prefix(28)) + "0", directory: "images") { image in self.businessImage = image } } firestore.getUser(uid: String(adv.uid.prefix(28))) { user in self.name = user.name ?? "Контактное лицо" if user.name == "" { self.name = "Контактное лицо" } DB().getImage(uid: String(adv.uid.prefix(28)), directory: "avatars") { image in self.avatar = image } } } } } }
<!-- myblog/templates/base.html --> <!DOCTYPE html> {% load static %} {% load static tailwind_tags %} <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" rel="stylesheet" /> <title>{% block title %}Candace{% endblock %}</title> {% tailwind_css %} </head> <body class="bg-blue-300"> <nav class="bg-gray-900 text-white fixed top-0 z-50 w-full"> <div class="mx-auto max-w-5xl px-8"> <div class="flex justify-between"> <div class="flex space-x-4"> <!-- Logo --> <div class="py-5"> <a href="#" class="flex items-center px-5 py-2 text-gray-700 hover:text-gray-900" > <img src="{%static 'lamlard/images/fav.png'%}" /> <span class="font-bold text-white"><i>CANDACE</i></span> </a> </div> <!-- Primary nav --> <div class="flex hidden items-center space-x-1 md:flex"> <a href="{% url 'myblog:home' %}" class="px-5 py-2 text-gray-200 hover:text-gray-500" >Home</a > <a href="{% url 'myblog:post_list' %}" class="px-5 py-2 text-gray-200 hover:text-gray-500" >Blog</a > <a href="#section1" class="px-5 py-2 text-gray-200 hover:text-gray-500 click-scroll" >About Us</a > </div> </div> <!-- secondary nav--> <div class="flex hidden items-center space-x-1 md:flex"> {%if user.is_authenticated%} <p>Welcome {{user}}</p> <a href="{%url 'account_logout' %}" class="px-3 py-5 hover:text-gray-500" >Logout</a > {% else %} <a href="{%url 'account_login' %}" class="px-3 py-5 hover:text-gray-500" >Login</a > <a href="{%url 'account_signup' %}" class="rounded px-3 py-3 font-bold text-yellow-900 transition duration-200 hover:text-gray-500 hover:text-yellow-900" >Sign Up</a > {% endif %} </div> <!-- Mobile button goes here --> <div class="flex items-center md:hidden"> <button class="mobile-menu-button"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="h-6 w-6" > <path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" /> </svg> </button> </div> </div> </div> <!-- mobile menu --> <div class="mobile-menu hidden md:hidden"> <a href="{% url 'myblog:home' %}" class="block px-4 py-2 text-sm hover:bg-gray-200" >Home</a > <a href="{% url 'myblog:post_list' %}" class="block px-4 py-2 text-sm hover:bg-gray-200" >Blog</a > <a href="#section1" class="block px-4 py-2 text-sm hover:bg-gray-200" >About Us</a > <a href="{%url 'account_signup' %}" class="rounded px-3 py-3 font-bold text-blue-300 transition duration-200 hover:text-gray-500 hover:text-white" >Sign Up</a > </div> </nav> <br /> <br /> <br /> <br /> <br /> <div class="container mx-auto mt-4">{% block content %} {% endblock %}</div> <script src="{%static 'lamlard/JS/nav.js' %}"></script> <script> // JavaScript to toggle mobile menu visibility const mobileMenuButton = document.querySelector(".mobile-menu-button") const mobileMenu = document.querySelector(".mobile-menu") mobileMenuButton.addEventListener("click", () => { mobileMenu.classList.toggle("hidden") }) </script> </body> <br /> <footer class="bg-gray-900 text-white py-12"> <div class="container mx-auto"> <div class="flex flex-wrap justify-between"> <div class="w-full md:w-1/2 lg:w-1/4 mb-8 md:mb-0"> <h2 class="text-lg font-semibold mb-4">Developer Contact:</h2> <p>[email protected]</p> </div> <div class="w-full md:w-1/2 lg:w-1/4 mb-8 md:mb-0"> <h2 class="text-lg font-semibold mb-4">Useful Links</h2> <ul> <li> <a href="{% url 'myblog:home' %}" class="text-gray-400 hover:text-white" >Home</a > </li> <li> <a href="#" class="text-gray-400 hover:text-white">About</a> </li> <li> <a href="{% url 'myblog:post_list' %}" class="text-gray-400 hover:text-white" >Blog</a > </li> <li> <a href="#" class="text-gray-400 hover:text-white">Contact</a> </li> </ul> </div> <div class="w-full md:w-1/2 lg:w-1/4 mb-8 md:mb-0"> <h2 class="text-lg font-semibold mb-4"> Social Media: Coming Soon!!!!! </h2> <ul> <li> <a href="#" class="text-gray-400 hover:text-white">Facebook</a> </li> <li> <a href="#" class="text-gray-400 hover:text-white">Twitter</a> </li> <li> <a href="#" class="text-gray-400 hover:text-white">Instagram</a> </li> <li> <a href="#" class="text-gray-400 hover:text-white">LinkedIn</a> </li> </ul> </div> </div> </div> <div class="mt-8 border-t border-gray-800"> <div class="container mx-auto pt-4 text-sm text-center"> <p>&copy; 2024 Your Blog. All rights reserved.</p> </div> </div> </footer> <script src="{%static 'lamlard/JS/nav.js' %}"></script> </html>
<h1 align="center"> <a href="#">Q2 To dos</a> </h1> <p align="center">🚀 To dos</p> <p align="center"> <img src="https://img.shields.io/static/v1?label=react&message=Library&color=blue&style=for-the-badge&logo=react"/> <img src="https://img.shields.io/static/v1?label=expo&message=Run with&color=blue&style=for-the-badge&logo=expo"/> <img src="https://img.shields.io/static/v1?label=firebase&message=Backend&color=blue&style=for-the-badge&logo=firebase"/> </p> ### 🛠 Technology The following tools were used in the construction of the project: - [React Native](https://reactnative.dev/) - [Expo](https://expo.dev/) - [React](https://pt-br.reactjs.org/) - [TypeScript](https://www.typescriptlang.org/) - [Styled Components](https://styled-components.com/) - [Firebase](https://firebase.google.com/?hl=pt-br) - [Zod](https://zod.dev/) - [React Hook Form](https://react-hook-form.com/) ### Getting Started 🚀 #### Cloning ```ps # Clone the repository using git $ git clone https://github.com/JuanPabllo/q2-todos.git # Access the project folder $ cd q2-todos ``` #### Requirements - [Node.js](https://nodejs.org/en/) - [Yarn](https://yarnpkg.com/) or [npm](https://www.npmjs.com/) - [Expo CLI](https://expo.dev/) - [json-server](https://github.com/typicode/json-server) This project use third party dependencies that need to be installed, use that command to install all needed dependencies ```ps $ yarn install or $ npm i ``` #### Running To start the Server run the command ```ps # Entering in directory $ cd q2-todos # Run the APP $ yarn android # or ios or $ npm run android # or ios # Run the backend $ npm install -g json-server $ yarn api or $ npm run api ``` #### Screenshot <img width="300" src=".github/images/login.png" /> <img width="300" src=".github/images/home_1.png" /> <img width="300" src=".github/images/home_2.png" /> <img width="300" src=".github/images/home_3.png" /> <img width="300" src=".github/images/task.png" /> <img width="300" src=".github/images/filter.png" /> <img width="300" src=".github/images/remove.png" />
#include "main.h" /** * read_textfile - reads a text file and prints it to the standard output * @filename: file to be read * @letters: number of letters to read and print * * Return: the number of letters printed, or 0 if it failed */ ssize_t read_textfile(const char *filename, size_t letters) { int fd; int r, w; char *buff; if (!filename) return (0); fd = open(filename, O_RDONLY); if (fd < 0) return (0); buff = malloc(sizeof(char) * letters); if (!buff) return (0); r = read(fd, buff, letters); if (r < 0) { free(buff); return (0); } buff[r] = '\0'; close(fd); w = write(STDOUT_FILENO, buff, r); if (w < 0) { free(buff); return (0); } free(buff); return (w); }
Modulo bibliotecaImpl implementa Biblioteca{ var posicionLibro: dictLog<idLibro,nat> // nat es la posicion var librosSocios: dictDigital<socio, conjLog<idLibro>> // Acá cuando defino en el dictDigital. Estoy definiendo un conjLog también, o no? Esto me agrega el costo de insertar en un conjLog? var posicionesLibres: minHeap<nat> La forma de asegurar que la información registrada es consistente sería que todos los idLibro de posicionLibro no se encuentren los libros de ningun libroSocio[socio] y viceversa. También que no esté ninguna posición de posicionesLibres en las claves de posicionLibro y viceversa. k = cant de posiciones libres en la estanteria ( | minHeap | ) (cantidad de espacios libres que estan en el minHeap) r = cant de libros de un socio ( | conjLog<idLibro> | de librosSocios) L = cant de libros en la colección ( |librosSocios| ) proc AgregarLibroAlCatalogo(inout b: Biblioteca, in l: idLibro){ min := b.posicionesLibres.buscarMinimo // O(1) b.posicionesLibres.borrarMinimo // O(log(k)) b.posicionLibro.definir(l,min) // O(log(L)) } proc PedirLibro(inout b: Biblioteca, in l: idLibro, in s: Socio){ // Complejidad: O(log(r) + log(k) + log(L)) librosAnt := b.librosSocios.obtener(s) -- Ojo porque deberia traer los libros viejos y agregar al conjunto el libro nuevo, y ahi definir la key -- A menos que se pueda definir directamente sobre b.librosSocios[s] . Es posible eso?? b.librosSocios[s].insertar(s,l) // O(1) porque |key| está acotado como max 50 ya que 50 es la longitud del nombre de un socio, osea de cada key posLibro := b.posicionLibro.obtener(l) // O(log(k)) b.posicionLibro.borrar(l) // O(log(n)) b.posicionesLibres.agregar(pos) // O(log(n)) } var productos: dictDigital<dni, conjLog<idProd>> proc agregarAlCarrito(inout m: Mercado, in dni: int, in p: conj<idProd>{ / m.productos.definir(dni,p) // <- Que complejidad tiene? } proc DevolverLibro(inout b: Biblioteca, in l: idLibro, in s: Socio){ a:= b.posicionesLibres.buscarMinimo() // O(1) conj:= b.librosSocios.obtener(s) // O(1) conj.sacar(l) // O(log(r)) b.posicionesLibres.borrarMinimo // O(log(k)) b.posicionLibro.definir(l,a) // O(log(L)) } proc Prestados (in b:Biblioteca, in s: Socio): Conjunto<idLibro>{ res = b.librosSocios.obtener(s) // O(1) porque |key| está acotado como max 50 ya que 50 es la longitud del nombre de un socio, osea de cada key } proc UbicacionDeLibro(in b: Biblioteca, in l: idLibro): Posicion{ res = b.posicionLibro.obtener(l) // O(log(L)) Porque L es la cantidad de keys del dict digital } } Dudas pendientes: // Que es y como funciona el aliasing? Me faltan las aclaraciones sobre aliasing // Según lo que busqué el aliasing es, cuando dos punteros apuntan a la misma dirección de memoria, // lo cual puede generar errores inesperados. Supongo que si cuando inserto en alguna estructura, si inserto // por referencia a memoria en lugar de insertar por valor, cuando inserto en mas de una estructura se produce aliasing // En PedirLibro no estoy seguro como hacer para que me quede O(log(r) + log(k) + log(L)) // Si yo tengo var variable: dictDigital< int, conjLog<int> > // se que el costo de insertar una key en un dictDigital común es O(1) en caso de que ese dict tenga un tamaño constante // pero en este caso cuando yo inserto una key que tiene como value un conjunto de x numeros int, sigue siendo O(1) el costo? // En que parte se usa memoria dinamica? Y new ? En el ejemplo del ej12 de guia 7 usan nuevo // cuando crean un dictLog // En el campus están resueltos los ejercicios 12 y 11 + ejercicio de LU del simulacro de parcial // Cola de prioridad implementada sobre heaps public int size(); // Devuelve el largo de la cola O(1) public boolean vacia(); // Devuelve True si la cola esta vacia O(1) public void encolar(int elem); // Agrega un elemento al final de la cola O(log n) public void desencolar(); // Remueve el elemento mas prioritario O(log n) public int top(); // Devuelve el elemento mas prioritario O(1) public colaDePrioridad heapify(int [] array); // array2heap O(n) crearVacío : O(1) próximo: O(1) Desencolar: O(log n) Encolar: O(log n) *** Nota respecto al aliasing: Comentario de 'Damy' [21:20, 5/12/2023] Los tipos primitivos como int no tiene aliasing. Pero los tipos complejos sip, entonces si tenes una variable interna ponele un heap Y en procedimiento pones: return dichoHeap Te va a devolver ese heap pero habra aliasing, quizas es lo que queres, porqur queres que te devuelva en O(1) Para que no haya aliasing tendrias que poner: Res: Heap = new Heap(DichoHeap) Return res Eso haria una copia del heap y te lo devolveria (pero ya no seria O(1) [21:20, 5/12/2023] Luego con los tipos primitivos si podes poner return VariableDeTipoPrimitivo y claramente no habria aliasing
from __future__ import annotations from django import forms from django.utils.translation import pgettext_lazy from . import models class MessageCreationForm(forms.ModelForm[models.Message]): class Meta: model = models.Message fields = ("content",) widgets = { "content": forms.Textarea( { "class": "form-control border-0 rounded-top-0", "placeholder": models.Message._meta.get_field( "content" ).help_text, "rows": 2, } ) } class MessageSearchForm(forms.Form): q = forms.CharField( widget=forms.Textarea( { "class": "form-control border-0 rounded-bottom-0", "placeholder": pgettext_lazy("noun", "Search messages"), "rows": 2, } ), label="", )
"use strict"; let computerScore = document.querySelector(".computer-score"); let playerScore = document.querySelector(".human-score"); let outcome = document.querySelector(".outcome"); let rockBtn = document.querySelector(".rock"); let paperBtn = document.querySelector(".paper"); let scissorsBtn = document.querySelector(".scissors"); let playerChoiceImg = document.querySelector(".human-choice-img"); let computerChoiceImg = document.querySelector(".computer-choice-img"); let computerChoice; let playerChoice; let cScore = 0; let pScore = 0; function computerScoresPoint() { cScore++; computerScore.textContent = cScore; } function playerScoresPoint() { pScore++; playerScore.textContent = pScore; } function getComputerChoice() { computerChoice = Math.floor(Math.random() * 3) + 1; if (computerChoice === 1) { computerChoice = "rock"; computerChoiceImg.src = "./img/rock.svg"; computerChoiceImg.alt = "rock"; } else if (computerChoice === 2) { computerChoice = "paper"; computerChoiceImg.src = "./img/paper.svg"; computerChoiceImg.alt = "paper"; } else { computerChoice = "scissors"; computerChoiceImg.src = "./img/scissors.svg"; computerChoiceImg.alt = "scissors"; } return computerChoice; } function playRound(computerChoice, playerChoice) { outcome.classList.remove("hidden"); if (computerChoice === playerChoice) { outcome.textContent = "It's a tie"; } else if (computerChoice === "scissors" && playerChoice === "paper") { computerScoresPoint(); outcome.textContent = "You lose! Scissors beat paper"; } else if (computerChoice === "rock" && playerChoice === "scissors") { computerScoresPoint(); outcome.textContent = "You lose! Rock beats scissors"; } else if (computerChoice === "paper" && playerChoice === "rock") { computerScoresPoint(); outcome.textContent = "You lose! Paper beats rock"; } else if (computerChoice === "paper" && playerChoice === "scissors") { playerScoresPoint(); outcome.textContent = "You win! Scissors beats paper"; } else if (computerChoice === "scissors" && playerChoice === "rock") { playerScoresPoint(); outcome.textContent = "You win! Rock beats scissors"; } else if (computerChoice === "rock" && playerChoice === "paper") { playerScoresPoint(); outcome.textContent = "You win! Paper beats rock"; } } rockBtn.addEventListener("click", function () { playerChoiceImg.src = "./img/rock.svg"; playerChoiceImg.alt = "rock"; playerChoice = "rock"; getComputerChoice(); return playRound(computerChoice, playerChoice); }); paperBtn.addEventListener("click", function () { playerChoiceImg.src = "./img/paper.svg"; playerChoiceImg.alt = "paper"; playerChoice = "paper"; getComputerChoice(); return playRound(computerChoice, playerChoice); }); scissorsBtn.addEventListener("click", function () { playerChoiceImg.src = "./img/scissors.svg"; playerChoiceImg.alt = "scissors"; playerChoice = "scissors"; getComputerChoice(); return playRound(computerChoice, playerChoice); });
<?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Mail; use App\Mail\DetachedDevice; use App\Models\Customers\Customer; class ProcessDetachedDeviceMail implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $tries = 5; /** * Create a new job instance. * * @return void */ protected $customer,$devicename; public function __construct(Customer $customer,$devicename) { $this->customer = $customer; $this->devicename = $devicename; } /** * Execute the job. * * @return void */ public function handle() { Mail::to($this->customer->email)->send(new DetachedDevice($this->customer->first_name,$this->devicename)); } }
### 思路 思路整体为先找到每个用户最大月份,然后过滤当前用户的最大月份,查询每个月最近前N月份的数据总和。 方法详情如下: ### 1.查询每个用户的最大月份 sql如下: * ``` SELECT e.Id , MAX(e.Month) AS Month FROM Employee e GROUP BY e.Id ``` 表别名为:e1 ### 2.过滤掉用户的最大月份数,查询用户月份薪水 根据题意需要 ID升序、月份降序,且不能为当前用户最近一个月数据,sql 如下: * ``` SELECT e1.Id,e1.Month,e1.Salary FROM Employee e1 , (SELECT e.Id , MAX(e.Month) AS Month FROM Employee e GROUP BY e.Id ) A where e1.Id = A.Id AND e1.Month < A.Month ORDER BY e1.Id ASC,e1.Month DESC ``` 表别名:B ### 3.查询最近前N月份(题目为3,N换3)的数据总和 对每个用户当前月份往前推N个月份数据总和,并且 条件满足: ID=B.id AND 月份 <= B.月份 and 月份 > B.月份-N sql如下: * ``` SELECT SUM(e2.Salary) FROM Employee e2 WHERE e2.Id = B.Id AND e2.Month <= B.Month AND e2.Month > B.Month-3 ORDER BY e2.Month DESC ``` ### 4.整体sql * ``` SELECT B.Id as id,B.Month as month, (SELECT SUM(e2.Salary) FROM Employee e2 WHERE e2.Id = B.Id AND e2.Month <= B.Month AND e2.Month > B.Month-3 ORDER BY e2.Month DESC LIMIT 3 ) as Salary FROM ( SELECT e1.Id,e1.Month,e1.Salary FROM Employee e1 , (SELECT e.Id , MAX(e.Month) AS Month FROM Employee e GROUP BY e.Id ) A WHERE e1.Id = A.Id AND e1.Month < A.Month ORDER BY e1.Id ASC,e1.Month DESC ) B ```
import os # import random import pickle import genomap as gp import genomap.genoNet as gNet import matplotlib.pyplot as plt import numpy as np import pandas as pd # Please install pandas and matplotlib before you run this example import scipy import seaborn as sns # import matplotlib import torch import torch.nn as nn import torch.nn.functional as F from genomap.genomap import construct_genomap from sklearn.decomposition import PCA # from torchcam.methods import CAM, GradCAM, GradCAMpp, ScoreCAM # from torchcam.methods import SSCAM, ISCAM, XGradCAM, LayerCAM # from torchcam.utils import overlay_mask # from torchvision.transforms.functional import normalize, resize, to_pil_image from sklearn.manifold import TSNE from sklearn.preprocessing import StandardScaler from torchcam.methods import SmoothGradCAMpp # import src.augmentation as aug import config.config_train as config from src.load import LoadData torch.manual_seed(0) torch.use_deterministic_algorithms(True) def findConv2dOutShape(hin, win, conv, pool=2): # get conv arguments kernel_size = conv.kernel_size stride = conv.stride padding = conv.padding dilation = conv.dilation hout = np.floor( (hin + 2 * padding[0] - dilation[0] * (kernel_size[0] - 1) - 1) / stride[0] + 1 ) wout = np.floor( (win + 2 * padding[1] - dilation[1] * (kernel_size[1] - 1) - 1) / stride[1] + 1 ) if pool: hout /= pool wout /= pool print("----->>>> ", hout, wout) return int(hout), int(wout) class genoNet(nn.Module): # Define the convolutional neural network architecture def __init__(self, input_shape, class_num): super(genoNet, self).__init__() input_dim = input_shape[2] Cin, Hin, Win = 1, input_dim, input_dim init_f = 8 num_fc1 = 100 # Cin = 3 self.conv1 = nn.Conv2d(Cin, init_f, kernel_size=3, padding=1) self.num_flatten = 1089 * init_f self.fc1 = nn.Linear(self.num_flatten, num_fc1) self.fc2 = nn.Linear(num_fc1, class_num) self.dropout = nn.Dropout(0.25) self.softmax = nn.Softmax(dim=-1) def forward(self, x): x = F.relu(self.conv1(x)) x = x.contiguous().view(-1, self.num_flatten) x = F.relu(self.fc1(x)) x = self.dropout(x) x = self.fc2(x) return F.log_softmax(x, dim=1) def show_activation_map(model, X_img, y_test): # CAM, GradCAM, GradCAMMpp, SmoothGradCAMpp, XGradCAM, LayerCAM, ScoreCAM, SSCAM, ISCAM cam_extractor = SmoothGradCAMpp( model, input_shape=[X_img.shape[3], X_img.shape[1], X_img.shape[2]] ) n = 25 am = [] targets = [] for ix in range(n): img = X_img[ix] y = y_test[ix] img = img.reshape(img.shape[2], img.shape[0], img.shape[1]) img = torch.from_numpy(img) if img.dim() < 4: # add batch with size 1 img4 = img[None] model_children = list(model.children()) for i in range(len(model_children)): model_children[i] = model_children[i].double() out = model(img4) # Retrieve the CAM by passing the class index and the model output activation_map = cam_extractor(out.squeeze(0).argmax().item(), out) am.append(activation_map[0].squeeze(0).numpy()) targets.append(y) indexes = sorted(range(len(targets)), key=lambda k: targets[k]) indexes = [ indexes[i] for i in [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23, 24] ] sns.set_theme(style="ticks", font_scale=1) fig = plt.figure(figsize=(10, 6)) fig.suptitle(f"Result of activation map") for i in range(len(indexes)): a = fig.add_subplot(3, 5, i + 1) a.axes.get_xaxis().set_ticks([]) a.axes.get_yaxis().set_ticks([]) # Visualize the raw CAM plt.imshow(am[indexes[i]] * 255, interpolation="nearest", aspect="auto") if i == 0 or i == 5 or i == 10: # a.set_title(f'class {targets[indexes[i]]}', fontsize=10) a.set_ylabel(f"class {targets[indexes[i]]}", fontsize=10) plt.tight_layout() plt.savefig("gen_CAM.pdf", format="pdf", bbox_inches="tight") plt.show() def show_genoMap(genoMaps, y_test): indexes = sorted(range(len(y_test)), key=lambda k: y_test[k]) indexes = [ indexes[i] for i in [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23, 24] ] sns.set_theme(style="ticks", font_scale=1) fig = plt.figure(figsize=(10, 6)) fig.suptitle(f"Result of genoMap") for i in range(len(indexes)): a = fig.add_subplot(3, 5, i + 1) a.axes.get_xaxis().set_ticks([]) a.axes.get_yaxis().set_ticks([]) plt.imshow(genoMaps[i] * 255, interpolation="nearest", aspect="auto") if i == 0 or i == 5 or i == 10: a.set_ylabel( f"class {y_test[indexes[i]]}", rotation=90, weight="bold", fontsize=10 ) plt.tight_layout() plt.savefig("genMAP.pdf", format="pdf", bbox_inches="tight") plt.show() def show_all_process(model, X_img, y_test, nump): # print(model) # CAM, GradCAM, GradCAMMpp, SmoothGradCAMpp, XGradCAM, LayerCAM, ScoreCAM, SSCAM, ISCAM cam_extractor = SmoothGradCAMpp( model, input_shape=[X_img.shape[3], X_img.shape[1], X_img.shape[2]] ) n = 25 lbs = [] processed = [] names = [] indexes = sorted(range(len(y_test)), key=lambda k: y_test[k]) indexes = [ indexes[i] for i in [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23, 24] ] indexes_2 = [indexes[0], indexes[7], indexes[12]] for ix in indexes_2: img = X_img[ix] y = y_test[ix] img = img.reshape(img.shape[2], img.shape[0], img.shape[1]) img = torch.from_numpy(img) if img.dim() < 4: # add batch with size 1 img4 = img[None] model_children = list(model.children()) for i in range(len(model_children)): model_children[i] = model_children[i].double() out = model(img4) conv1 = getattr(model, "conv1") fc1 = getattr(model, "fc1") out_conv = conv1(img4) out_fc1 = fc1(out_conv.contiguous().view(-1, nump * 8)).detach().numpy() gray_scale = torch.sum(out_conv, 0) out_conv = gray_scale / out_conv.shape[0] out_conv = out_conv.data.max(dim=0)[1].numpy() # Retrieve the CAM by passing the class index and the model output activation_map = cam_extractor(out.squeeze(0).argmax().item(), out) names.append("Input sample") names.append("CAMpp") names.append("Conv layer") processed.append(img.reshape(img.shape[1], img.shape[2]).detach().numpy()) processed.append(activation_map[0].squeeze(0).numpy()) processed.append(out_conv) # names.append('FC layer') # processed.append(out_fc1) lbs.append(y) sns.set_theme(style="ticks", font_scale=1) fig = plt.figure(figsize=(6, 6)) fig.suptitle(f"Result of genoNet method") num_fig_per_row = int(len(processed) / 3) for i in range(len(processed)): a = fig.add_subplot(3, num_fig_per_row, i + 1) # Visualize the raw CAM print(processed[i].T.shape) plt.imshow(processed[i] * 255, interpolation="nearest", aspect="auto") a.axes.get_xaxis().set_ticks([]) a.axes.get_yaxis().set_ticks([]) a.set_title(names[i].split("(")[0], fontsize=8) if i == 0: a.set_ylabel(f"class {lbs[0]+1}", rotation=90, weight="bold", fontsize=10) elif i == num_fig_per_row: a.set_ylabel(f"class {lbs[1]+1}", rotation=90, weight="bold", fontsize=10) elif i == num_fig_per_row * 2: a.set_ylabel(f"class {lbs[2]+1}", rotation=90, weight="bold", fontsize=10) plt.tight_layout() plt.savefig("gen_all_process.pdf", format="pdf", bbox_inches="tight") plt.savefig("gen_all_process.jpg", dpi=600, bbox_inches="tight") plt.show() def show_tsne(model, X_img, y_, nump): n = 25 imgs = [] targets = [] out_attns = [] out_imgs = [] proc_imgs = [] proc_fcs = [] lbs = [] for i in range(len(X_img)): img = X_img[i] lbs.append(y_[i]) conv1 = getattr(model, "conv1") fc1 = getattr(model, "fc1") img = img.reshape(img.shape[2], img.shape[0], img.shape[1]) img = torch.from_numpy(img) if img.dim() < 4: # add batch with size 1 img4 = img[None] model_children = list(model.children()) for i in range(len(model_children)): model_children[i] = model_children[i].double() out = model(img4) out_conv = conv1(img4) out_fc1 = fc1(out_conv.contiguous().view(-1, nump * 8)).detach().numpy() gray_scale = torch.sum(out_conv, 0) out_conv = gray_scale / out_conv.shape[0] out_conv = out_conv.data.max(dim=0)[1].numpy() print("@@@@@@@@@@@@@") print(img.shape) print(out_fc1.shape) proc_imgs.append( img.reshape(img.shape[0] * img.shape[1] * img.shape[2]).detach().numpy() ) proc_fcs.append(out_fc1.reshape(out_fc1.shape[0] * out_fc1.shape[1])) y = np.array(y_) y = y.reshape(y.shape[0] * y.shape[1]) # initialise the standard scaler sc = StandardScaler() # create a copy of the original dataset X_imgs = np.array(proc_imgs) X_fcs = np.array(proc_fcs) tsns_inputs = tsne_(X_imgs, y) tsns_fcs = tsne_(X_fcs, y) # tsns_ens = tsne_(X_ens, y) # plot the result sns.set_theme(style="ticks", font_scale=1) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5)) im1 = ax1.scatter( tsns_inputs["Dimension 1"], tsns_inputs["Dimension 2"], marker="o", c=y, cmap=plt.cm.get_cmap("viridis", 3), ) fig.colorbar( im1, ax=ax1, ticks=range(3), label="Classes", boundaries=np.arange(4) - 0.5 ) ax1.set_title("t-SNE Visualization of input", fontweight="bold") ax1.get_xaxis().set_ticks([]) ax1.get_yaxis().set_ticks([]) im2 = ax2.scatter( tsns_fcs["Dimension 1"], tsns_fcs["Dimension 2"], marker="o", c=y, cmap=plt.cm.get_cmap("viridis", 3), ) # plt.colorbar(ticks=range(3), label='Classes', boundaries=np.arange(4)-0.5) fig.colorbar( im2, ax=ax2, ticks=range(3), label="Classes", boundaries=np.arange(4) - 0.5 ) ax2.set_title("t-SNE Visualization of output features", fontweight="bold") ax2.get_xaxis().set_ticks([]) ax2.get_yaxis().set_ticks([]) plt.suptitle("TSNE Result (gnmap method)") plt.savefig(f"tsne_proposed.pdf", format="pdf", bbox_inches="tight") plt.savefig(f"tsne_proposed.jpg", dpi=600, bbox_inches="tight") plt.show() def tsne_(X, y): print(X.shape) # create the model tsne = TSNE( n_components=2, perplexity=3, learning_rate="auto", init="random", random_state=21, n_iter=5000, n_jobs=-1, ) # apply it to the data X_dimensions = tsne.fit_transform(X) # create a dataframe from the dataset df = pd.DataFrame(data=X_dimensions, columns=["Dimension 1", "Dimension 2"]) df["class"] = y return df def select_n_features(X, n): # calculate the variance of each feature variances = np.var(X, axis=0) # get the indices of the features sorted by variance (in descending order) indices = np.argsort(variances)[::-1] # select the indices of the top 10 most variable features top_n_indices = indices[:n] # select the top 10 most variable features X_top_n = X[:, top_n_indices] return X_top_n, top_n_indices train_dataset_path = config.params["train_dataset_path"] X_train_path = os.path.join(train_dataset_path, "Xtrain.File") y_train_path = os.path.join(train_dataset_path, "ytrain.File") X_test_path = os.path.join(train_dataset_path, "Xtest.File") y_test_path = os.path.join(train_dataset_path, "ytest.File") ld_tr = LoadData(X_train_path, y_train_path, config.params["num_augmentation"], False) # for test dataset augmentation shoud be set to 0 ld_ts = LoadData(X_test_path, y_test_path, 0) X_train = ld_tr.get_X() X_train = X_train.reshape(X_train.shape[0], X_train.shape[1] * X_train.shape[2]) y_train = ld_tr.get_y() X_test = ld_ts.get_X() X_test = X_test.reshape(X_test.shape[0], X_test.shape[1] * X_test.shape[2]) y_test = ld_ts.get_y() colNum = 36 # Column number of genomap rowNum = 36 # Row number of genomap data = np.concatenate((X_train, X_test), axis=0) y = pd.DataFrame(np.concatenate((y_train, y_test), axis=0)) data_test = X_test num = colNum * rowNum if num < data.shape[1]: data, index = select_n_features(data, num) data_test, index = select_n_features(data_test, num) print(data.shape) # Normalization of the data dataNorm_test = scipy.stats.zscore(data_test, axis=0, ddof=1) # Construction of genomaps genoMaps_test = gp.construct_genomap( dataNorm_test, rowNum, colNum, epsilon=0.0, num_iter=200 ) # Normalization of the data dataNorm = scipy.stats.zscore(data, axis=0, ddof=1) # Construction of genomaps genoMaps = gp.construct_genomap(dataNorm, rowNum, colNum, epsilon=0.0, num_iter=200) print(genoMaps.shape) findI = genoMaps[10, :, :, :] # Plot the first genomap plt.figure(1) plt.imshow(findI, origin="lower", extent=[0, 10, 0, 10], aspect=1) plt.title("Genomap") plt.show() # show genoMaps of each classes show_genoMap(genoMaps, y_test) input_shape = genoMaps class_num = 3 # Construction of genomaps nump = rowNum * colNum if nump < data.shape[1]: data, index = select_n_features(data, nump) dataNorm = scipy.stats.zscore(data, axis=0, ddof=1) genoMaps = construct_genomap(dataNorm, rowNum, colNum, epsilon=0.0, num_iter=200) training_labels = y_train.reshape(y_train.shape[0]) # Split the data for training and testing dataMat_CNNtrain = genoMaps[: training_labels.shape[0]] dataMat_CNNtest = genoMaps[training_labels.shape[0] :] groundTruthTrain = training_labels classNum = len(np.unique(groundTruthTrain)) # Preparation of training and testing data for PyTorch computation XTrain = dataMat_CNNtrain.transpose([0, 3, 1, 2]) XTest = dataMat_CNNtest.transpose([0, 3, 1, 2]) yTrain = groundTruthTrain model = gNet.traingenoNet(XTrain, yTrain, maxEPOCH=100, batchSize=16, verbose=True) with open("geno.pkl", "wb") as f: pickle.dump(model, f) with open("geno.pkl", "rb") as f: model = pickle.load(f) model_saved = torch.jit.load("./results/gnclassify/gnClassify_k2_rand21.pt") model_saved.to("cpu") model_saved.eval() show_all_process(model, genoMaps_test, y_test, nump) show_tsne(model, genoMaps_test, y_test, nump)
package api import ( "go-assignment-bootcamp/internal/app/http/requests" "go-assignment-bootcamp/internal/app/presenters" "github.com/gin-gonic/gin" "net/http" "strconv" ) type OrderUpdateController struct { useCase OrderUpdateUseCaseInterface presenter OrderUpdatePresenterInterface } func NewOrderUpdateController( useCase OrderUpdateUseCaseInterface, presenter OrderUpdatePresenterInterface, ) *OrderUpdateController { return &OrderUpdateController{ useCase: useCase, presenter: presenter, } } func (controller *OrderUpdateController) Update(context *gin.Context) { paramId := context.Param("id") id, errParam := strconv.Atoi(paramId) if errParam != nil { message := "The ID parameter is invalid." presenters.PresentErrorPresenter(context, http.StatusBadRequest, message) return } var request requests.OrderUpdateRequest err := request.Validate(context) if err != nil { presenters.PresentErrorPresenter(context, http.StatusBadRequest, err) return } response, useCaseError := controller.useCase.Execute(&request, id) if useCaseError != nil { presenters.PresentErrorPresenter(context, http.StatusBadRequest, useCaseError) return } controller.presenter.Present(context, response) }
import { test as setup } from "@playwright/test"; import { chromium } from "playwright-extra"; import stealth from "puppeteer-extra-plugin-stealth"; import dotenv from "dotenv"; dotenv.config(); chromium.use(stealth()); const TESTING_AUTH_EMAIL = process.env.TESTING_AUTH_EMAIL; const TESTING_AUTH_PASSWORD = process.env.TESTING_AUTH_PASSWORD; const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL; setup("authentication", async () => { if (typeof TESTING_AUTH_EMAIL === "undefined") throw new Error("TESTING_AUTH_EMAIL missing from env variables"); if (typeof TESTING_AUTH_PASSWORD === "undefined") throw new Error("TESTING_AUTH_PASSWORD missing from env variables"); if (typeof BASE_URL === "undefined") throw new Error("BASE_URL missing from env variables"); const browser = await chromium.launch({ headless: false }); const page = await browser.newPage(); // Navigate to sign-in page await page.goto(BASE_URL); console.log(page.url()); await page.getByRole("button", { name: /sign up/i }).click(); // Sign in await page.getByLabel(/sign in with google/i).click(); // Type in email slowly to simulate an actual user await page.waitForSelector("input[type='email']"); await page.locator("input[type='email']").type(TESTING_AUTH_EMAIL); await Promise.all([ page.waitForLoadState(), await page.keyboard.press("Enter"), ]); // Type in password slowly to simulate an actual user await page.waitForSelector("input[type='password']"); await page.locator("input[type='password']").type(TESTING_AUTH_PASSWORD); await Promise.all([ page.waitForLoadState(), await page.keyboard.press("Enter"), ]); // Wait until the page receives the cookies. // Wait for the final URL to ensure that the cookies are actually set. // This URL is different than testing URL due to how next auth works await page.waitForURL(BASE_URL); // End of authentication steps. const authFile = "./e2e/.auth/user.json"; await page.context().storageState({ path: authFile }); await browser.close(); });
# Lesson 1 - | Irish | English | Phonetic | Sound | | ------| ------- | -------- | ----- | |Bhain mé sult as an lá. | I enjoyed the day. |Mhúscail mé ar a seacht a chlog. | I awoke at seven o’clock. |D’ith mé banana agus úll.| I ate a banana and an apple. |D’ol mé gloine uisce. | I drank a glass of water. |Shiúil mé go dtí an siopa. | I walked to the shop. |Cheannaigh mé an nuachtán. | I bought the newspaper. |Shuigh mé síos. | I sat down. |Léigh mé an nuachtán. | I read the newspaper. |D’amharc mé ar an teilifís. | I watched the television. |D’éist mé le Giota Beag Eile. | I listened to Giota Beag Eile. |D’fhoghlaim mé Gaeilge. | I learnt Irish. | |ard | tall |tanaí | thin | |Tá mé ard. | I am tall.| |Tá mé tanaí. | I am thin. | |cairdiúil | friendly |cainteach | chatty |dearmadach | forgetful | |Tá mé cairdiúil. | I am friendly. |Tá mé cainteach. | I am chatty. | |Tá mé cairdiúil. | I am friendly. |Sílim go bhfuil mé cairdiúil. | I think that I am friendly. | |Tá mé cainteach. | I am chatty. |Sílim go bhfuil mé cainteach. | I think that I am chatty. | |Tá mé tuisceanach. | I am understanding. |Deirtear go bhfuil mé tuisceanach. | It’s said that I am understanding. |Deirtear go bhfuil mé iontach tuisceanach. | It’s said that I’m very understanding. | |This episode’s seanfhocal is: |Is binn béal ina thost. | Silence is golden. # Lesson 2 - | Irish | English | Phonetic | Sound | | ------| ------- | -------- | ----- | |Agus chomh maith leis sin | And as well as that |Ach ar an drochuair | But unfortunately |mar | because |Níl mé pósta mar tá mé óg.| I’m not married because I’m young. |fosta | also, as well |Agus rud eile dó | and furthermore / and another thing |deoch beag | a wee drink |Ná déan dearmad air sin. | Don’t forget about that. | |Seanfhocal Chlár 2 is: | |Níor bhris focal maith fiacail riamh. | Literally, a good word never broke a tooth.(So it doesn’t hurt to say a kind word about someone!) |bean chéile | wife |mo bhean chéile | my wife |cuidiúil | helpful |bríomhar | lively, outgoing, bubbly |siúlóidí | walks |agus caithfidh mise dul léi! | and I have to go with her! |ramhar | fat |giota beag ramhar | a little overweight |ag siúl amach le | going out with, going steady |gealgháireach | cheerful |smutach | huffy, moody |neamhspleách | independent |tarcaisneach | sarcastic |ó am go ham | from time to time |sean | old |níos sine | older |is sine | oldest Try to see if you remember the meaning of following: • agus chomh maith leis sin • ach • ach ar an drochuair • mar • Níl mé pósta mar tá mé óg go fóill. • agus rud eile dó • ná déan dearmad air sin ! • mo bhean chéile • cuidiúil • Mol an óige is tiocfaidh sí! # Lesson 3 - | Irish | English | Phonetic | Sound | | ------| ------- | -------- | ----- | |ríomhaire | computer |ar an ríomhaire | on the computer |ar an idirlíon | on the internet |suíomh | site |suíomh idirlín | internet site |Ponc | dot |stríoc chun tosaigh | forward stroke |sean | old |níos sine | older |is sine | oldest |óg | young |níos óige | younger |is óige | youngest | |an duine is óige | the youngest person, the youngest one |an duine is sine | the oldest person, the oldest one | |fuar | cold |níos fuaire | colder |te | warm or hot |níos teo | warmer |luath | early |níos luaithe | earlier |mall | late |níos moille | later | |Seanfhocal Chlár 3! | |Mar a bhíos an cú, bíonn an coileán! |Like father, like son. Or, indeed, like mother like daughter! | You already know: "Is binn béal ina thost!" agus "Níor bhris focal maith fiacail riamh!" Now see if you remember what the following words mean. You can always listen back to check your answers! • ríomhaire • idirlíon • suíomh idirlín • ponc • is óige • an duine is óige • an duine is sine • fuar - níos fuaire • te - níos teo • luath - níos luaithe • mall - níos moille # Lesson 4 - | Irish | English | Phonetic | Sound | | ------| ------- | -------- | ----- | |maith | good |níos fearr | better |is fearr | best | |olc | bad |níos measa | worse |is measa | worst | |beag | small |níos lú| smaller |is lú | smallest | |mór | large or big |níos mó | bigger |is mó | biggest | |ainmnigh | name |contae | county |club sacair | soccer club |i Sasain | in England |in Albain | in Scotland | |Ainmnigh an contae is mó in Éirinn.|Name the biggest or largest county in Ireland. |Agus an freagra, the answer… Corcaigh, Cork. | |Ainmnigh an contae is lú in Éirinn.|Name the smallest county in Ireland. |Agus an freagra, the answer… Contae Lú, County Louth. | |Ainmnigh an club sacair is fearr i Sasain. |Name the best soccer club in England. | |Ainmnigh an club sacair is fearr in Albain. |Name the best soccer club in Scotland. | |Ainmnigh an club sacair is measa i Sasain. |Name the worst soccer club in England. | |Ainmnigh an club sacair is measa in Albain. |Name the worst soccer club in Scotland. | |Seanfhocal Chlár 4: | |Níl aon leigheas ar an ghrá ach pósadh.|There is no cure for love except marriage. |leigheas | cure |grá | love | |You already know: |Is binn béal ina thost. |Níor bhris focal maith fiacail riamh. |Mar a bhíos an cú, bíonn an coileán. | |bean chéile | wife |deirfiúr | sister |mo bhean chéile | my wife |mo dheirfiúr | my sister |mo phas | my passport |do phas | your passport |a phas | his passport |a pas | her passport | |Now see if you remember the following, without peeking at the translation: • maith / níos fearr /is fearr • olc / níos measa / is measa • beag / níos lú / is lú • mór /níos mó /is mó • ainmnigh • tá tú ar mire • bean chéile • mo bhean chéile • deirfiúr • mo dheirfiúr • mo phas • do phas • a phas • a pas # Lesson 5 - | Irish | English | Phonetic | Sound | | ------| ------- | -------- | ----- | |liom | with me |leat | with you |leis | with him |léi | with her | |Ba mhaith liom | I’d like |Ba mhaith leat | You’d like |Ba mhaith leis | He’d like |Ba mhaith léi | She’d like | |dom | to me |duit | to you |dó | to him |di | to her | |Tabhair dom an leabhar | Give me the book. |Thug mé an leabhar duit | I gave the book to you. |Thug mé an leabhar dó | Literally, I gave the book to him. |Thug mé an leabhar di | Literally, I gave the book to her. Seanfhocal Chlár 5: Is fearr an tsláinte ná na táinte. - Health is better than wealth. |mo | my |do | your |a | his |a | her |ár | our |bhur | your |a | their | |ár scoil | our school |bhur lón | your (plural) lunch |a milseáin | their sweets Try the following phrases and see if you can remember what they mean: |ag éirí níos fuaire |ag éirí i bhfad níos fuaire |dom, duit, dó, di |ár scoil |bhur lón |a milseáin |tá sí nimhneach |guthán póca |Cheannaigh mé bláthanna di. |cúpla irisleabhar. |Tá mé ar mo bhealach abhaile. |Chífidh mé thú! # Lesson 6 - | Irish | English | Phonetic | Sound | | ------| ------- | -------- | ----- | |An dtiocfadh leat? | Could you? |An dtiocfadh leat gar a dhéanamh? | Could you do a favour? |An dtiocfadh leat gar a dhéanamh dom? | Could you do a favour for me? |An dtiocfadh leat gar beag a dhéanamh dom? | Could you do a wee favour for me? |An dtiocfadh leat an litir seo a chur sa phost | Could you post this letter |An dtiocfadh leat mé a thógáil ón bhus? | Could you lift me/collect me from the bus? |An dtiocfadh leat mé a thógáil ón siopa? | Could you collect me from the shop |An dtiocfadh leat £20 punt a thógáil amach? | Could you take out £20? |An dtiocfadh leat scairt a chur ar an gharáiste? | Could you phone the garage? Seanfhocal Chlár 6: |Is fada an bóthar nach mbíonn casadh ann! | |bóthar | road |casadh | a turning or a twist |Is fada an bóthar | It’s a long road |…nach mbíonn casadh ann | …which doesn’t have a turn or a twist | |An dtiocfadh leat cúpla gar a dhéanamh dom? | Could you do a couple of favours for me? |Thiocfadh | Yes I could |Ní thiocfadh | No, I could not |Cad é atá ann? | What is it? In this context, what is it - you want me to do | |Go maire sibh bhur saol úr le chéile | May you live out your new life together. |It’s nice to look at it as “May you have good health to live out a long life together.” |Bainis | wedding reception | |Sláinte is fad saoil agaibh, teach ar bhur mian agaibh |Talamh gan chíos agaibh, fómhar gach bliain agaibh |Leanbh gach bliain agaibh, ón lá seo amach! | |Good health and long life to you both, a house of your dreams, |Land without rent, a harvest each year, |A child every year, from this day on! | |litir | letter |an litir seo | this letter |doras |an doras seo | this door |clár | programme |an clár seo | this programme |cárta | card |an cárta seo | this card # Lesson 7 - | Irish | English | Phonetic | Sound | | ------| ------- | -------- | ----- | |An dtiocfadh leat gar beag a dhéanamh? | Could you do a wee favour? |An dtiocfadh liom gar beag a dhéanamh? | Could I do a wee favour? |An dtiocfadh leis gar beag a dhéanamh? | Could he do a wee favour? |An dtiocfadh léi gar beag a dhéanamh? | Could she do a wee favour? | |An dtiocfadh leat gar beag a dhéanamh dom? | Could you do a wee favour for me? |An dtiocfadh leat gar beag a dhéanamh dó?|Could you do a wee favour for him? |An dtiocfadh leat gar beag a dhéanamh di? | Could you do a wee favour for her? |An dtiocfadh liom gar beag a dhéanamh duit? | Could I do a wee favour for you? | |Is fada an lá. | It is/has been a long time. |Ó, is fada. | Indeed it is/has been a long time. |Is fada anlá ó d’ith mé pizza! | It’s a long time since I’ve eaten pizza! |Is fada an lá ó d’ól mé caife! | It’s a long time since I’ve drunk coffee! | |D’éirigh liom. | I passed/succeeded. |D’éirigh leat. | You passed/succeeded. |D’éirigh leis. | He passed/succeeded. |D’éirigh léi. | She passed/succeeded. |Cad é mar a d’éirigh leat? | How did you get on? | |Theip orm. | I failed. |Theip ort. | You failed. |Theip air.| He failed. |Theip uirthi. | She failed. | |Go maire tú é. | May you have good health to enjoy it. |Go maire tú é is go gcaithe tú é. | May you have good health to enjoy it and wear it. |Go maire tú é is go gcaithe tú é is go stróca tú é. | May you have good health to enjoy it, wear it and tear it. |Go maire tú é is go gcaithe tú é is go stróca tú é is go bpósa tú fear ann. | May you have good health to enjoy it, wear it and tear it and marry a man in it. |an litir sin | that letter |an doras sin | that door |an clár sin | that programme |an gúna sin | that dress |Cé acu is fearr leat? | Which do you prefer? # Lesson 8 - | Irish | English | Phonetic | Sound | | ------| ------- | -------- | ----- | |Cad é do bharúil? | What do you think? |An dtiocfadh leat an dinnéar a dhéanamh? | Could make the dinner? |an lón | the lunch |An dtiocfadh leat an lón a dhéanamh? | Could you make the lunch? |an bricfeasta | the breakfast |An dtiocfadh leat an bricfeasta a dhéanamh? | Could you make the breakfast? |an suipéar | the supper |An dtiocfadh leat an suipéar a dhéanamh? | Could you make the supper? | |Ar mhaith leat? | Would you like? |Ar mhaith leat an dinnéar a dhéanamh? | Would you like to make the dinner? |Ar mhaith leat an lón a dhéanamh? | Would you like to make the lunch? |Ar mhaith leat an bricfeasta a dhéanamh? | Would you like to make the breakfast? | |Ar mhaith leat dul amach ar shiúlóid? | Would you like to go out for a walk? |Ar mhaith leat dul amach anocht? | Would you like to go out tonight? |Ar mhaith leat dul chuig an phictiúrlann? | Would you like to go to the cinema? |Ar mhaith leat dul amach fá choinne béile anocht? | Would you like to go out for a meal tonight? |Ar mhaith leat buidéal fíona a fháil? | Would you like to get a bottle of wine? |Ar mhaith leat pizza a fháil? | Would you like to get a pizza? |Ar mhaith leat tacsaí a fháil? | Would you like to get a taxi? | |Ba mhaith | Yes |Níor mhaith | No | |Seanfhocail Chlár 8: |Beidh a cuid féin ag an fharraige | The sea will have its own. | |eile | another |bus eile | another bus |briosca eile | another biscuit |ceann eile | another one |clár eile | another programme |gúna eile | another dress |Tá mo sháith agam. | I’ve had my fill. / I’ve had enough. |cupán eile tae | another cup of tea |rud ar bith eile | anything else |Ar mhaith leat briosca? | Would you like a biscuit? |Ba mhaith, le do thoil. Tá siad iontach deas. | Yes, please. They’re very nice. |Ar mhaith leat ceann eile? | Would you like another one? |Níor mhaith, go raibh maith agat. Tá mo sháith agam. | No, thanks. I’ve had enough. |Ar mhaith leat cupán eile tae? | Would you like another cup of tea? |Ar mhaith leat rud ar bith eile? | Would you like anything else? # Lesson 9 - | Irish | English | Phonetic | Sound | | ------| ------- | -------- | ----- | |Cad é mar a d’éirigh leat? | How did you get on? |Bain sult as an lá. | Enjoy the day. |Éirigh ar a seacht a chlog. | Get up at 7 o’clock. |Ith banana agus úll. | Eat a banana and an apple. |Ól deoch uisce. | Drink a glass of water. |Siúil go dtí an siopa. | Walk to the shop. |Ceannaigh an nuachtán. | Buy the paper. |Suigh síos. | Sit down. |Léigh an nuachtán. | Read the paper. |Amharc ar an teilifís. | Watch the TV. |Éist le Giota Níos Mó. | Listen to Giota Níos Mó. | |Bain sult as an lá. | Enjoy the day. |Bainim sult as an lá. | I enjoy the day. | |Éirigh ar a seacht a chlog. | Get up at 7 o’clock. |Éirím ar a seacht a chlog. | I get up at 7 o’clock. | |Ith banana agus ull. | Eat a banana and an apple |Ithim banana agus úll gach lá. | I eat a banana and an apple every day. | |Ól gloine uisce. | Drink a glass of water. |Ólaim gloine uisce gach lá. | I drink a glass of water every day. | |Siúil go dtí an siopa. | Walk to the shop |Siúlaim go dtí an siopa | I walk to the shop | |Ceannaigh an nuachtán | Buy the newspaper. |Ceannaím an nuachtán | I buy the newspaper. | |Suigh síos. | Sit down. |Suím síos. | I sit down. | |Léigh an nuachtán | Read the newspaper. |Léim an nuachtán | I read the newspaper. | |Amharc ar an teilifís. | Watch the television. |Amharcaim ar an teilifís. | I watch the television. | |Éist le Giota Níos Mó. | Listen to Giota Níos Mó. |Éistim le Giota Níos Mó gach lá. | I listen to Giota Níos Mó every day. | |Seanfhocal Chlár 9: | |Bíonn blas ar an bheagán. | A little bit of food is very tasty. | |Ba mhaith liom meachán a chailleadh. | I would like to lose weight. | |bus eile | another bus |an bus eile | the other bus |briosca eile | another biscuit |an briosca eile | the other biscuit |ceann eile | another one |an ceann eile | the other one |an chéad cheann eile | the next one |an bus eile | the other bus |an chéad bhus eile | the next bus |an clár eile | the other programme |clár eile | another programme |an chéad chlár eile | the next programme |an chéad uair eile| the next time |an chéad rud eile | the next thing # Lesson 10 - | Irish | English | Phonetic | Sound | | ------| ------- | -------- | ----- | |Ithim torthaí. | I eat fruit. |Ní ithim seacláid. | I don’t eat chocolate. |Ithim glasraí ach ní ithim milseáin. | I eat vegetables but I don’t eat sweets. |Ólaim uisce ach ní ólaim caife.| I drink water but I don’t drink coffee. |Éistim le ceol ach ní éistim leis an nuacht. | I listen to music but I don’t listen to the news. |Amharcaim ar an teilifís ach ní amharcaim ar an nuacht | I watch television but I don’t watch the news. |Éirím go luath ar an Satharn ach ní éirím go luath ar an Domhnach. | I get up early on Saturday but I don’t get up early on Sunday. |Tuigim. | I understand. |Ní thuigim. | I don’t understand. |Tuigim ‘Slán’ ach ní thuigim ‘dochreidte’. | I understand ‘goodbye’ but I don’t understand ‘unbelievable’. |Tuigim ‘coirnéal’ ach ní thuigim ‘off-side’. | I understand ‘corner’ but I don’t understand ‘off-side’. |Tuigim Bríd ag caint Gaeilge ach ní thuigim Hiúdaí ag caint Gaeilge.| I understand Bríd speaking Irish but I don’t understand Hiúdaí speaking Irish. |Tuigim ‘Pythagoras’ ach ní thuigim ‘Trigonometry’. | I understand ‘Pythagoras’ but I don’t understand ‘Trigonometry’. |Ní thuigim. | I don’t understand. |Ní shiúlaim. | I don’t walk. |Ní cheannaím. | I don’t buy. |Ní shuím. | I don’t sit. Seanfhocal Chlár 10: |Is maith an t-anlann an t-ocras. | Hunger is a great sauce. # Lesson 11 - | Irish | English | Phonetic | Sound | | ------| ------- | -------- | ----- | |barraíocht | too much |mórán | many |go minic | often |cuid mhór |a lot |níos mó | more |níos lú | less |a oiread | as much / as many | |“Ghiorsaighe óg,’bhfuil Béarla agat? |Leóga, muise, tá! |Caidé mar a chuirfeá an madadh amach? |Out the dog awa!!” | |“Young girl, can you speak English? |Indeed, I can! |How would you put the dog out? |Out the dog awa!!” | |Ithim. | I eat. |Itheann tú. | You eat. |An itheann tú? | Do you eat? |Tuigim. | I understand. |Tuigeann tú. | You understand. |An dtuigeann tú? | Do you understand? |Téim. | I go. |An dtéann tú? |Do you go? |An bhfuil sé fuar? | Is it cold? |Tá. / Níl. | Yes. / No. |Déanaim. | I do / make. |An ndéanann tú? | Do you do / make? |Díolaim as. | I pay for. |An ndíolann tú as? | Do you pay for? | |An dtéann tú chuig an phictiúrlann go minic?| Do you go to the cinema often? |An dtéann tú chuig cluiche peile go minic? | Do you go to a football match often? |An dtéann tú ag snámh go minic? | Do you go swimming often? |An dtéann tú go Béal Feirste go minic? |Do you go to Belfast often? |An bhfuil airgead agat? | Do you have money? |An ndéanann tú Yoga? | Do you do Yoga? |An ndíolann tú as na ranganna? | Do you pay for the classes? |An ndéanann tú an dinnéar go minic? | Do you make the dinner often? # Lesson 12 - | Irish | English | Phonetic | Sound | | ------| ------- | -------- | ----- | |Creidim. | I believe. |Creideann tú. |You believe. |An gcreideann tú?| Do you believe? | |Ceannaím. | I buy. |Ceannaíonn tú. | You buy. |An gceannaíonn tú? | Do you buy? | |Bím. | I be. |Bíonn tú. | You be. |An mbíonn tú? - Do you be? |An mbíonn tú ag obair gach Aoine? | Do you work every Friday? |An mbíonn tú ag obair gach Satharn? | Do you work every Saturday? |ar an Luan | on Mondays |ach an Satharn agus an Domhnach | except Saturday and Sunday |ag deireadh na seachtaine | at the weekend |trí lá gach seachtain | three days every week | |An nglanann tú an carr gach Aoine? | Do you clean the car every Friday? |Glanaim. | I clean. |Ní glanaim. | I don’t clean. |Glanann tú. | You clean. |anois agus arís | now and again |na fuinneoga | the windows |uair sa mhí | once a month Seanfhocal Chlár 12: Cleachtadh a dhéanann máistreacht. |cleachtadh | practice |máistreacht | a mastery, perfection |Cleachtadh a dhéanann máistreacht. | Practise makes perfect. | |ár scoil | our school |bhur lón | your (pl.) lunch |a milseáin | their sweets |ár bplátaí | our plates |bhur bplátaí | your plates |a bplátaí | their plates # Lesson 13 - | Irish | English | Phonetic | Sound | | ------| ------- | -------- | ----- | |Glan an tábla. | Clean the table |Tá sé glanta. | It’s cleaned. |Déan an lón.| Make the lunch. |Tá sé déanta. |It’s made. |Líon isteach an fhoirm sin. | Fill in that form. |Tá sé líonta. | It’s filled in. |druid | close |druidte | closed |oscail | open |oscailte | opened |léigh | read |léite | read |caill | lose |caillte | lost |Tá an siopa sin druidte ach tá an siopa seo go fóill oscailte. | That shop is closed but this shop is still open |Druid an doras sin, le do thoil, tá sé fuar. | Tá sé druidte. |Close that door please, it’s cold. | It is closed. |Oscail an fhuinneog, le do thoil, tá sé iontach te. | Tá sé oscailte. |Open the window, please, it’s very warm. | It is open. |Tá Bran caillte.| Bran is lost. |Tá an leabhar leite. |The book is read. |Tá an leabhar léite agam. | I have read the book. | |croí | heart, dear or love |a ghrá |love (when speaking to someone) |grá geal mo chroí | the bright love of my heart, my sweetheart |mo chroí | my love |a ruin | loved one |rúin mo chroí | love of my heart |a thaiscigh | my dear, darling | |bris | break |briste | broken |ith | eat |ite | eaten |nite | washed |thart | over, finished | |grma can be text for go raibh maith agat | thank you |eay can be text for oíche mhaith | goodnight |sgf can be text for slán go fóill | goodbye for now |ldt can be text for le do thoil |please |the letter j can be text for cad é | what |the letters an followed by the digit 8, ocht in Irish, can stand for anocht, an8 – tonight |kwul2 can be cá bhfuil tú? | where are you? |gao can be grá agam ort | love you # Lesson 14 - | Irish | English | Phonetic | Sound | | ------| ------- | -------- | ----- | |críochnaigh | finish |críochnaigh an crosfhocal sin.| finish that crossword. |ceannaigh | buy |ceannaigh an nuachtán. | buy the newspaper. |cóirigh |arrange or dress |cóirigh an leaba| make the bed. |ceartaigh | correct |ceartaithe |corrected |sínigh | sign |sínithe | signed |roghnaigh |choose |roghnaithe | chosen |deisigh | repair or fix |deisithe | repaired | |Fuair tú scairt ghutháin; tá do ghuthán póca deisithe. | You got a phone call; your |mobile phone is fixed. |Roghnaigh an dath is fearr leat. | Choose the colour you prefer. |Tá sé roghnaithe agam; gorm. | I have chosen it; blue. |Sínigh an nóta scoile sin, le do thoil, a chroí. | Sign that school note, please, love. |Tá sé sínithe agam. | I have it signed. |Ceartaigh an obair bhaile sin le do thoil. | Correct that homework please. |Tá an obair bhaile sin ceartaithe agam. |I have that homework corrected. | |faoiseamh | relief |seal beag gairid | a short little while |i measc mo dhaoine | among my people |ar oileán mara | on a sea island |ag siúl cois cladaigh | walking by the shore |maidin is tráthnóna |morning and evening |ó Luan go Satharn | from Monday to Saturday |thiar ag baile | back at home, in the west |ó chrá croí | from heart ache |ó bhuairt aigne | from anxiety and work |ó uaigneas duairc | from dark loneliness |ó chaint ghontach | from hurtful talk | |An bhfuil an leabhar sin léite agat? | Have you read that book? |Tá an leabhar sin léite aige. | He has read that book. |Tá an leabhar sin léite aici. | She has read that book. |Tá an leabhar sin léite againn | We have read that book. |Tá an leabhar sin léite agaibh | You (pl) have read that book. |Tá an leabhar sin léite acu | They have read that book. | |Och och mo mhadadh beag | Aw, my wee dog |tá piachán i mo sceadamán | I am hoarse |ag scairtigh ar mo mhadadh beag. | calling my wee dog. | |Luím ar mo leabaidh | I lie in my bed |‘gus ní chodlaím aon néal go maidin | and I don’t sleep a wink |ach ag meabhrú ar mo mhadadh beag | thinking of my wee dog |a d’imigh uaim sa scarthanaigh. | who left me at daybreak. # Lesson 15 - | Irish | English | Phonetic | Sound | | ------| ------- | -------- | ----- | | |Bain sult as an lá. | Enjoy the day. |Bainfidh mé sult as an lá. | I will enjoy the day. Bainfidh mé sult as an lá. |Ól gloine uisce | Drink a glass of water. |Ólfaidh mé gloine uisce. | I will drink a glass of water. |Siúil go dtí an siopa.| Walk to the shop. |Siúlfaidh mé go dtí an siopa. | I will walk to the shop. |Suigh síos. | Sit down. |Suífidh mé síos. | I will sit down. |Léigh an nuachtán. | Read the newspaper. |Léifidh mé an nuachtán. | I will read the newspaper. |Amharc ar an teilifís. | Watch the television. |Amharcfaidh mé ar an teilifís. | I will watch the television. |Éist le Giota Níos Mó | Listen to Giota Níos Mó. |Éistfidh mé le GNM gach lá. | I will listen to Giota Níos Mó every day. | |an carr s’agam | my car |an carr s’agat | your car |an carr s’aige | his car |an carr s’aici | her car |an carr s’againn | our car |an carr s’agaibh | your (pl.) car |an carr s’acu | their car | |Chífidh mé. | I will see. |Chífidh mé thú. | I will see you. |Déanfaidh mé. | I will do. |Déanfaidh mé sin amárach. |I will do that tomorrow. |Rachaidh mé. | I will go. |Rachaidh mé ar ais amárach. |I will go back tomorrow. |Scairtfidh mé. || I will call/shout. |Scairtfidh mé ort amárach. | I will phone you tomorrow. |An rachaidh tú? | Will you go? |An rachaidh tú amach anocht? | Will you go out tonight? |Ní rachaidh | No, I will not go out. |Níl mé cinnte an rachaidh nó nach rachaidh. | I’m not sure if I’ll go or not. Seanfhocal Chlár 15: |Mol an óige is tiocfaidh sí. | Praise the youth and it will come / they will blossom.
import { GetServerSideProps, InferGetServerSidePropsType, NextPage } from 'next'; import { useSession } from 'next-auth/react'; import Head from 'next/head'; import { BiError, BiImages } from 'react-icons/bi'; import { BsCodeSlash } from 'react-icons/bs'; import { MdOutlineVideoLibrary } from 'react-icons/md'; import axios from 'axiosClient'; import StatCard from '@components/Dashboard/StatCard'; import StatLineChart from '@components/Dashboard/StatLineChart'; // Header and Icon data for the stat cards const cards = [ { field: 'GIFs', Icon: BiImages }, { field: 'Videos', Icon: MdOutlineVideoLibrary }, { field: 'Files', Icon: BsCodeSlash } ]; const Dashboard: NextPage = ({ statsData }: InferGetServerSidePropsType<typeof getServerSideProps>) => { // To make sure the user is logged in to access this page useSession({ required: true }); // eslint-disable-next-line console.log('CHART DATA =>', statsData); return ( <div className="w-full p-14 pt-16"> <Head> <title>Dashboard</title> <link rel="icon" href="/thunder-hero.png" /> </Head> <header className="py-5 text-4xl mt-10 mb-5">Dashboard</header> <div className="h-fit w-full bg-red-400 mb-12 p-10 rounded-lg text-lg"> <div className="flex items-center gap-3 mb-5"> <BiError size={35} /> <p className="text-xl font-semibold">Note</p> </div> <p className="text-base"> The data displayed on this page is static and not real time, it is fetched from database on page load and is not correct at this moment. It is only to demonstrate the working of the UI components. The dummy data will be replaced with real data soon. </p> </div> <div className="flex flex-wrap items-center w-full gap-12 mb-20"> {cards.map(({ field, Icon }) => { const value = statsData.aggregate[field.toLowerCase()]; // Value is fetched from api data return ( <StatCard key={field} field={field} value={value} Icon={Icon} /> ); })} </div> <div className="lg:w-1/2 w-full h-fit"> <StatLineChart chartData={statsData.recentActivity} /> </div> </div> ); }; export const getServerSideProps: GetServerSideProps = async () => { const statsData = await axios.get('api/stats').then(res => res.data); return { props: { statsData } }; }; export default Dashboard;
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package main; /** * * @author phatbui */ // Employee Class (subclass of Person) class Employee extends Person { private String employeeNumber; // No-argument constructor public Employee() { super(); this.employeeNumber = ""; } // 4-argument constructor public Employee(String name, String phoneNumber, String emailAddress, String employeeNumber) { super(name, phoneNumber, emailAddress); this.employeeNumber = employeeNumber; } // Getter and setter method for employeeNumber public String getEmployeeNumber() { return employeeNumber; } public void setEmployeeNumber(String employeeNumber) { this.employeeNumber = employeeNumber; } @Override public String toString() { return super.toString() + "\nEmployee Number: " + employeeNumber; } }
import React from "react"; import { Pressable, StyleSheet, Text, View } from "react-native"; const CategoryGridTile = ({ title, color, onPress }) => { return ( <View style={[styles.gridItem, { backgroundColor: color }]}> <Pressable style={styles.button} android_ripple={{ color: "#ccc" }} onPress={onPress}> <View style={styles.innerContainer}> <Text style={styles.title}>{title}</Text> </View> </Pressable> </View> ); }; export default CategoryGridTile; const styles = StyleSheet.create({ gridItem: { flex: 1, margin: 16, height: 150, borderRadius: 8, backgroundColor: "white", elevation: 4, overflow: "hidden", }, button: { flex: 1, }, innerContainer: { flex: 1, padding: 16, justifyContent: "center", alignItems: "center", }, title: { fontWeight: "bold", fontSize: 18, }, });
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "UObject/NoExportTypes.h" #include "DataPlayer.generated.h" class AMyPlayer; class UItemData; class UItemBehavior; USTRUCT(BlueprintType) struct FInventorySlot { GENERATED_BODY() public: UPROPERTY() UItemData* DataItem = nullptr; UPROPERTY() UItemBehavior* ItemBehavior = nullptr; int Nb = 0; }; /** * */ UCLASS() class LABO2UNREAL_API UDataPlayer : public UObject { GENERATED_BODY() private: bool DataIsInit; float Health; UPROPERTY() TArray<FInventorySlot> Inventory; int IndexEquip; int InventorySize = 2; UPROPERTY() TMap<FString, FVector> DictPos; UPROPERTY() TMap<FString, FRotator> DictRotation; void InitData(AMyPlayer* Player); public: UDataPlayer(); void LoadData(AMyPlayer* Player); void SaveData(AMyPlayer* Player); void ResetData(); bool CollectItem(UItemData* item); void PopItemEquip(); FInventorySlot GetInventorySlotEquip(); FInventorySlot GetInventorySlotAt(int index); void SetIndexEquip(int index); int GetInventorySize(); int GetIndexEquip(); bool Contain(UItemData* item); UFUNCTION(BlueprintCallable) void SetSpawn(FString levelName, FVector location, FRotator rotation); FVector GetSpawnLocation(FString levelName); FRotator GetSpawnRotation(FString levelName); };
import React from 'react'; import { ConversationMessages } from '../models/ConversationMessages'; import { useConversation } from '../hooks/useConversation'; import TimeAgo from 'react-timeago'; interface Props { own?: boolean; conversation?: ConversationMessages; } export const ChatMessage: React.FC<Props> = ({ own, conversation }) => { const { friendCredentials } = useConversation(); return ( <div className={`px-7 flex items-center ${own && 'ml-auto'} mb-3`}> {!own && ( <img src={friendCredentials?.photoUrl} alt='Profile pic' referrerPolicy='no-referrer' className='w-9 h-9 rounded-full mr-3' /> )} <div className={`text-white py-2 px-4 rounded-xl w-fit ${ own ? 'bg-[#e8ebfa]' : 'bg-white' }`} > <div className='flex items-center'> {!own && ( <h5 className='mr-2 text-black'>{friendCredentials?.fullName}</h5> )} <div className='text-xs text-gray-400'> <TimeAgo date={conversation?.createdAt!} live={false} /> </div> </div> <p className='text-base text-black font-light'>{conversation?.text}</p> </div> </div> ); };
import { Logger, ValidationPipe } from "@nestjs/common"; import { ConfigService } from "@nestjs/config"; import { NestFactory } from "@nestjs/core"; import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger"; import { Config } from "config/configuration"; import helmet from "helmet"; import { AppModule } from "./app.module"; async function bootstrap() { const app = await NestFactory.create(AppModule); const configService = app.get(ConfigService); const logger = new Logger(); app.use(helmet()); app.enableCors({ origin: configService.get<Config["CORS_ORIGIN"]>("CORS_ORIGIN", { infer: true, }), }); app.useGlobalPipes(new ValidationPipe()); const swaggerConfig = new DocumentBuilder() .setTitle("NestJS API") .setDescription("NestJS API description") .build(); const swaggerDocument = SwaggerModule.createDocument(app, swaggerConfig); SwaggerModule.setup("docs", app, swaggerDocument); const port = configService.get<Config["PORT"]>("PORT") || 8000; await app.listen(port); logger.log(`Server is running on port: ${port}`); } bootstrap().catch((error) => { console.error(error); process.exit(1); });
import { toSpaceCase } from './format' test('simple test toSpaceCase', () => { const cases: Array<{ input: string; expect: string }> = [ { input: 'cameCase', expect: 'came Case', }, { input: 'Capitalize the first letter', expect: 'Capitalize the first letter', }, { input: 'API', expect: 'API', }, { input: 'DMKeeper', expect: 'DM Keeper', }, { input: 'cameCase_34', expect: 'came Case 34', }, { input: 'i18n', expect: 'i18n', }, { input: 'conj-word', // that's compromised, we don't want breaking conj-word, // but no way to spot them exactly expect: 'conj word', }, { input: 'kebab-case-variable', expect: 'kebab case variable', }, { input: 'snake_case', expect: 'snake case', }, { input: 'snake_case_2333:50', expect: 'snake case 2333:50', }, { input: '12:40', expect: '12:40', }, { input: '12:40:00', expect: '12:40:00', }, { input: '12.45', expect: '12.45', }, { input: '1.0.0', expect: '1.0.0', }, { input: 'he said: "hello"', expect: 'he said: "hello"', }, { input: 'colon:in:word', expect: 'colon in word', }, { input: 'localhost:8080', expect: 'localhost 8080', }, { input: 'local---host::::8080', expect: 'local host 8080', }, ] const results: typeof cases = [] cases.forEach((item) => { results.push({ input: item.input, expect: toSpaceCase(item.input), }) }) expect(results).toEqual(cases) })
import React from 'react' import { BarItem } from '../models' import styles from '../styles/ProgressBar.module.scss' interface Props { items: BarItem[] width: number height: number } const ProgressBar: React.FC<Props> = ({ items, width, height }) => { const total = items.reduce((acc, cur) => acc + cur.value, 0) return ( <section className={styles.body}> <h2>Progress bar</h2> <div className={styles.barLine}> {items.map((item) => new Array(Math.floor(item.value / total * 100)).fill(0) .map((_, i) => <div key={i} style={{ width, height, background: item.color }} className={styles.bar} />) )} </div> <div className={styles.barLegend}> {items.map((item) => ( <div className={styles.legend} key={item.name} > <div className={styles.legendCircul} style={{ background: item.color }} /> <span> {`${item.name}: ${item.value} (${(item.value / total * 100).toFixed(1)}%)`} </span> </div> ))} </div> </section> ) } export default React.memo(ProgressBar)
<template> <!-- header --> <header class="common-header"> <div class="common-header__container"> <button type="button" class="btn-mobile-navigation" :class="{ nav_on: navigationOn }" @click="toggleNavigation" aria-label="헤더 메뉴 버튼(모바일 기기 전용)"><i></i><i></i><i></i></button> <h1 class="common-header__logo"> <router-link :to="{ path: '/' }" aria-label="뷰티하우스 로고" title="뷰티하우스 로고"> <img src="~@/assets/images/logo_header_white.png" alt="뷰티하우스 로고 이미지" loading="lazy" /> </router-link> </h1> <div class="float_right"> <nav class="web-gnb"> <ul id="ul_gnb_header"> <li> <router-link :to="{ path: '/products' }">Products</router-link> </li> <li> <router-link :to="{ path: '/events' }">Events</router-link> </li> <li> <router-link :to="{ path: '/contactus' }">Contact us</router-link> </li> <li> <router-link :to="{ path: '/mypage' }">My page</router-link> </li> </ul> </nav> <ul class="header-button-group"> <li> <button type="button" class="btn-login" @click="openLoginModal('login')"> <span>Login</span> </button> </li> <li> <button type="button" class="btn-signup" @click="openLoginModal('signup')"> <span>SignUp</span> </button> </li> <li> <button type="button" class="btn-cart"><span>Cart</span><span class="cart-count">0</span></button> </li> </ul> </div> </div> <!-- aside : mobile-gnb --> <aside class="mobile-gnb" :class="{ nav_on: navigationOn }" id="navigationMobile"> <div class="mobile-gnb__dim" @click="toggleNavigation"></div> <nav class="mobile-gnb__cotainer"> <ul class="menu-list-main"> <li> <router-link :to="{ path: '/products' }">PRODUCTS</router-link> </li> <li> <router-link :to="{ path: '/events' }">EVENTS</router-link> </li> <li> <router-link :to="{ path: '/contactus' }">CONTACT US</router-link> </li> <li> <router-link :to="{ path: '/mypage' }">MY PAGE</router-link> </li> </ul> <ul class="menu-list-sub"> <li> <router-link :to="{ path: '/shipping' }">Shipping</router-link> </li> <li> <router-link :to="{ path: '/returns' }"> Returns / Exchage </router-link> </li> <li> <router-link :to="{ path: '/policy' }">Privacy Policy</router-link> </li> <li> <router-link :to="{ path: '/terms' }"> Terms &amp; Conditions </router-link> </li> <li> <router-link :to="{ path: '/contactus' }">Contact Us</router-link> </li> </ul> </nav> </aside> </header> </template> <script> import { mapActions } from 'vuex'; export default { name: 'common-header', data() { return { navigationOn: false }; }, watch: { $route: function(to, from) { this.navigationOn = false; } }, methods: { toggleNavigation() { this.navigationOn = !this.navigationOn; }, // $store > uiInteraction ...mapActions({ TOGGLE_LOGIN_MODAL: 'uiInteraction/TOGGLE_LOGIN_MODAL', CHANGE_STATE_LOGIN_MODAL: 'uiInteraction/CHANGE_STATE_LOGIN_MODAL' }), openLoginModal(typeString) { this.CHANGE_STATE_LOGIN_MODAL(typeString); this.TOGGLE_LOGIN_MODAL(true); } } }; </script> <style lang="scss" scoped> $modules: 'common-header'; .#{$modules} { width: 100%; height: 52px; overflow: visible; position: relative; z-index: 5; &__container { position: fixed; top: 0; left: 0; width: 100%; height: 52px; background-color: #000; z-index: 5; box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5); @include clearfix; &:after { content: ''; display: table; clear: both; } } &__logo { width: 44px; height: 44px; position: absolute; top: 5px; left: 50%; margin-left: -22px; a, img { display: block; width: 100%; height: auto; } @media only screen and (min-width: 769px) { left: 25px; margin-left: 0; } } } /* moblie - navigation btn-mobile-navigation */ $modules: 'btn-mobile-navigation'; .#{$modules} { position: absolute; width: 22px; height: 14px; top: 18px; left: 12px; background-color: transparent; border: 0; overflow: visible; outline: 0; @media only screen and (min-width: 769px) { display: none; } & > i { position: absolute; width: 22px; height: 2.4px; background-color: #fff; border-radius: 4px; left: 0; top: 0; -webkit-transition: all 0.2s ease-out; transition: all 0.2s ease-out; -webkit-transform: rotate(0deg); transform: rotate(0deg); } & > i:nth-child(2) { top: 49%; } & > i:nth-child(3) { top: 100%; } &.nav_on i:nth-child(1) { transform: rotate(-38deg); width: 12px; top: 25%; } &.nav_on i:nth-child(2) { transform: rotate(-180deg); left: 1px; top: 46.7%; } &.nav_on i:nth-child(3) { transform: rotate(38deg); width: 12px; top: 75%; } } /* web-gnb */ $modules: 'web-gnb'; .#{web-gnb} { float: left; margin-right: 4rem; @media only screen and (max-width: 768px) { display: none; } ul { li { float: left; cursor: pointer; a { display: block; font-size: 16px; color: #fff; transition: color 0.2s ease-out; padding: 1rem; } &:hover a, &.on a { color: #fe708a; } } } } /* header-button-group */ $modules: 'header-button-group'; .#{$modules} { float: left; margin-right: 1rem; @media only screen and (max-width: 768px) { margin-right: 7px; } li { float: left; cursor: pointer; &:nth-child(2) { @media only screen and (max-width: 830px) { display: none; } } button { color: #c0c0c0; font-size: 15px; display: block; padding: 1rem; @media only screen and (max-width: 768px) { font-size: 13px; padding: 1.1rem 0.3rem; } &.btn-login:before { background-image: url('~@/assets/images/icon_login.png'); } &.btn-signup:before { background-image: url('~@/assets/images/icon_join.png'); } &.btn-cart:before { background-image: url('~@/assets/images/icon_cart.png'); } &:before { content: ''; display: inline-block; width: 14px; height: 14px; background-size: cover; vertical-align: middle; @media only screen and (max-width: 768px) { width: 11px; height: 11px; } } span { display: inline-block; vertical-align: middle; padding-left: 5px; &.cart-count { display: inline-block; border-radius: 20px; width: 15px; height: 15px; text-align: center; color: #fff; background-color: #ccc; padding: 0; font-size: 12px; line-height: 1.3; margin-left: 3px; text-shadow: 1px 1px 0 #aaa; } } } &:hover button, &.on button { span { color: #fff; } } } } /* mobile-gnb */ $modules: 'mobile-gnb'; .#{$modules} { position: fixed; z-index: 4; width: 100%; height: 100%; top: 0; right: 100%; @media only screen and (min-width: 769px) { display: none; } &__dim { background-color: rgba(0, 0, 0, 0.5); position: fixed; top: 0; left: 0; width: 100%; height: 100%; display: none; z-index: 2; } &.nav_on &__dim { display: block; } &__cotainer { position: absolute; top: 0; left: 0%; width: 84%; height: 100%; overflow: auto; background-color: #151515; z-index: 3; transition: left 0.3s ease-out; @media only screen and (min-width: 480px) { width: 60%; } ul { width: 80%; margin: 0 auto; li { width: 100%; } &.menu-list-main { padding-top: 52px; & > li { border-bottom: 1px solid #fff; } & > li a { color: #fff; font-size: 1.25rem; font-weight: bold; padding: 1rem 0; display: block; } } &.menu-list-sub { padding-top: 3rem; li { padding: 0.5rem 0; text-align: right; a { color: #fff; font-size: 1rem; } } } } } &.nav_on &__cotainer { left: 100%; } } </style>
<template> <md-card md-with-hover> <md-card-header> <md-card-header-text> <div class="md-title">{{item.name}}</div> <div class="md-subhead">{{item.owner.login}}</div> <p> <md-icon>star</md-icon> <strong>{{item.stargazers_count}}</strong> </p> <p> <md-icon>call_split</md-icon> <strong>{{item.forks_count}}</strong> </p> </md-card-header-text> <md-card-media> <md-avatar class="md-large"> <img :src="item.owner.avatar_url" :alt="item.name" /> </md-avatar> </md-card-media> </md-card-header> <md-card-actions> <md-button :href="item.html_url" :title="'GitHub repo ' + item.full_name" target="_blank" > Visit Github page </md-button> <md-button v-if="isActiveBookmark" @click="() => removeBookmarkItem(item.id)" > <md-icon class="md-primary">star</md-icon> Remove Bookmark </md-button> <md-button v-else @click="() => addBookmarkItem(item)" > <md-icon>star_border</md-icon> Add Bookmark </md-button> </md-card-actions> </md-card> </template> <script> import { mapActions } from 'vuex' export default { name: 'CardComp', props: { item: { type: Object } }, computed: { isActiveBookmark () { return this.$store.state.bookmarks.filter(bookmark => this.item.id === bookmark.id).length > 0 } }, methods: { ...mapActions([ 'addBookmarkItem', 'removeBookmarkItem' ]) } } </script> <style lang="scss"> .md-card { width: 320px; margin: 4px; display: inline-block; vertical-align: top; text-align: left; .md-title { word-break: break-all; } } </style>
package sia.tacocloud.model; import jakarta.persistence.*; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; import lombok.Data; import org.springframework.data.rest.core.annotation.RestResource; import java.util.Date; import java.util.List; @Data @Entity @RestResource(rel = "tacos", path="tacos") public class Taco { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull @Size(min = 5, message = "Name must be at least 5 characters long") private String name; @NotNull @Size(min = 1, message = "You must choose at least 1 ingredient") @ManyToMany private List<Ingredient> ingredients; private Date createdAt = new Date(); }
import React, { useContext, useState } from "react"; import { isInCart } from "../../helpers"; import { CartContext } from "../../context/cart-context"; import { withRouter } from "react-router-dom"; import "./featured-product.styles.scss"; import AddedToBagMessage from "../single-product/Popupmessage"; const FeaturedProduct = (props) => { const [showMessage, setShowMessage] = useState(false); const { title, imageUrl, price, history, id, description } = props; const { addProduct, cartItems, increase } = useContext(CartContext); const product = { title, imageUrl, price, history, id, description }; const itemInCart = isInCart(product, cartItems); return ( <div className="featured-product"> <div className="featured-image" onClick={() => history.push(`/product/${id}`)} > <img src={imageUrl} alt="product" /> </div> <div className="name-price"> <h3>{title}</h3> <p>$ {price}</p> {!itemInCart && ( <button className="button is-black nomad-btn" onClick={() => addProduct(product)} > ADD TO CART {showMessage && ( <AddedToBagMessage onClose={() => setShowMessage(false)} /> )} </button> )} {itemInCart && ( <button className="button is-white nomad-btn" id="btn-white-outline" onClick={() => increase(product)} > ADD MORE </button> )} </div> </div> ); }; export default withRouter(FeaturedProduct);
/* * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com * The software in this package is published under the terms of the CPAL v1.0 * license, a copy of which has been included with this distribution in the * LICENSE.txt file. */ package org.mule.module.apikit; import static com.jayway.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.is; import org.mule.tck.junit4.FunctionalTestCase; import org.mule.tck.junit4.rule.DynamicPort; import com.jayway.restassured.RestAssured; import org.junit.Rule; import org.junit.Test; public class ContentTypeTestCase extends FunctionalTestCase { @Rule public DynamicPort serverPort = new DynamicPort("serverPort"); @Override public int getTestTimeoutSecs() { return 6000; } @Override protected void doSetUp() throws Exception { RestAssured.port = serverPort.getNumber(); super.doSetUp(); } @Override protected String getConfigResources() { return "org/mule/module/apikit/contenttype/content-type-config.xml"; } @Test public void getOnAcceptAnythingAndNullPayload() throws Exception { given().header("Accept", "*/*") .expect() .response().body(is("")) .statusCode(200) .when().get("/api/resources"); } @Test public void getOnAcceptNotSpecified() throws Exception { given().header("Accept", "") .expect() .response().body(is("")) .statusCode(200) .when().get("/api/resources"); } @Test public void getOnAcceptAnythingResponseJson() throws Exception { given() .header("Accept", "") .header("ctype", "json") .expect() .response().contentType(is("application/json")) .body(is("never mind")) .statusCode(200) .when().get("/api/multitype"); } @Test public void getOnAcceptAnythingResponseXml() throws Exception { given() .header("Accept", "") .header("ctype", "xml") .expect() .response().contentType(is("application/xml")) .body(is("never mind")) .statusCode(200) .when().get("/api/multitype"); } @Test public void getOnAcceptAnythingResponseHtml() throws Exception { given() .header("Accept", "") .header("ctype", "default") .expect() .response().contentType(is("text/html")) .body(is("never mind")) .statusCode(200) .when().get("/api/multitype"); } }
# -*- coding: utf-8 -*- """ Created on Thu Jan 4 15:21:29 2024 @author: Stefan Bernegger """ import numpy as np import matplotlib.pyplot as plt plt.rcParams['figure.dpi'] = 600 plt.rcParams['savefig.dpi'] = 600 from GIRF_models import get_patterns from GIRF_plot import save_plot # ****************************************************** def get_pattern(t, Y, t_max=None): # Convert the series Y_i = Y(t_i+) into a step function # Pts = [[0,0], [t_0,0], [t_0,Y_0], [t_1,Y_0], ... , [t_n,Y_n]] where t_n <= T def Pts_append(Pts, ti, Yi): Pts[0].append(ti) Pts[1].append(Yi) return Pts if t_max == None: t_max = max(t) Pts = [[],[]] t_i = 0 Y_i = 0 Pts = Pts_append(Pts, t_i, Y_i) # append start point [0,0] for i, t_i in enumerate(t): if t_i <= t_max: Pts = Pts_append(Pts, t_i, Y_i) # append lower right point of step Y_i = Y[i] Pts = Pts_append(Pts, t_i, Y_i) # append upper left point of step Pts = Pts_append(Pts, t_max, Y_i) # append end point [t_max, P(t_max)] return np.array(Pts) def get_count(Pt): # Count the number of steps in the pattern Pt count = 0 Pt_ = Pt[0] for i, Pt_i in enumerate(Pt): if Pt_i != Pt_: count += 1 Pt_ = Pt_i return count def get_IP_tau(Pt, t): # Evaluate the incurred amaount, the incurred lag, the paid ratio and the paid lag at time t, # given the pattern Pt t_0 = Pt[0] # list time stamps t_i I_0 = Pt[1] # list icurred amounts I_i = I(t_i+) P_0 = Pt[2] # list cumulative paid amounts P_i = P(t_i+) t_lo = t_0 <= t # extract conditional pattern for the period <=T # I_zer = I_0 <= 0. # identify incurred values <= 0 t_max = max(t_0) # get last data point (t_max, I_max, P_max) in P I_max = I_0[len(I_0)-1] P_max = P_0[len(P_0)-1] t_1 = np.roll(t_0, 1) # get list D_t with length of time intervals t_1[0] = 0 D_t = (t_0 - t_1) * t_lo I_1 = np.roll(I_0, 1) # get values of I and P for the time intervals I_1[0] = 0 P_1 = np.roll(P_0, 1) P_1[0] = 0 if t >= t_max: # get values at time T I1 = I_max P1 = P_max else: i0 = min(t_lo.sum(), len(I_1)-1) I1 = I_1[i0] P1 = P_1[i0] I_int = (D_t * I_1).sum() + (t-D_t.sum()) * I1 # Integrate I(t) and P(s)from 0 to t P_int = (D_t * P_1).sum() + (t-D_t.sum()) * P1 if I1 > 0: # Normalize P_rel = P1 / I1 # Paid/Incurred ratio tau_I_t = t - I_int / I1 # Incurred lag tau_P_t = t - P_int / I1 # Paid lag else: P_rel = 0 tau_I_t = 0 tau_P_t = 0 return I1, tau_I_t, P_rel, tau_P_t def get_IP_t(t_IP_tau, Pt, t): # Evaluate the statistics at time t and append data to t_IP_tau I1, tau_I_t, P_rel, tau_P_t = get_IP_tau(Pt, t) t_IP_tau[0].append(t) # time t_IP_tau[1].append(I1) # incurred t_IP_tau[2].append(tau_I_t) # incurred lag t_IP_tau[3].append(P_rel) # Paid / incurred ratio t_IP_tau[4].append(tau_P_t) # paid lag return t_IP_tau def get_polygon(X, Y, Y_max): x = [0] + list(X) # insert origin y = [0] + list(Y) x_last = x[-1] y_last = y[-1] if y_last < Y_max: # case I* > P*: elevate polygon up to I* = Y_max x = x + [x_last, 0] y = y + [Y_max, Y_max] else: if y[-2] == y_last: # case y[-2] == y[-1] == y_last x[-1] = 0 else: x = x + [0] # draw upper bound back to y-axis y = y + [y_last] x = x + [0] # close the loop y = y + [0] return [x, y] def plot_IP(tau_grid, I, P, tau_eval, col_list, fn_ID='dummy_plot'): # Create a chart depicting the reduced variables for: # a) incurred claims # b) paid claims # eps = 0.001 ax_titles = ['a) incurred', 'b) paid'] def m_str(s1, s_lo, s_hi, s2=''): b, k = '{', '}' def bsk(c, s): if s.strip() == '': return '' else: return f'{c}{b}{s}{k}' if s1[0] == ' ': s_m = f"${s1[1:]}" else: s_m = f"$\{s1}" s_lh = f"{bsk('_', s_lo)}{bsk('^', s_hi)}{s2}$" return s_m + s_lh def plt_x_tick(axs, x, c='k', ls='-', lw=0.5, d_x=0.05): axs.plot([x, x], [-d_x, d_x], c=c, ls=ls, lw=lw) def plt_y_tick(axs, y, c='k', ls='-', lw=0.5, d_y=0.05): axs.plot([-d_y, d_y], [y, y], c=c, ls=ls, lw=lw) def plt_xy(axs, x, y, c='k', ls='-', lw=0.5, d_x=0.025, d_y=0.05): axs.plot([x, x], [-d_y, y+d_y], c=c, ls=ls, lw=lw) axs.plot([-d_x, x+d_x], [y, y], c=c, ls=ls, lw=lw) def plt_arrow(axs, x2, y2, x1, y1, arr_st='<->', c='k', ls='-', w=0.5): axs.annotate('', xy=(x1, y1), xytext=(x2, y2), arrowprops=dict(arrowstyle=arr_st, color=c, ls=ls, lw=w)) def disp_arrow(axs, label, x2, x1, y, arr_st='<->', c='k', ls='-', w=0.5): plt_arrow(axs, x2, y, x1, y, arr_st=arr_st, c=c, ls=ls, w=w) axs.text((x1+x2)/2, y+0.05, label, fontsize=fs, color=c, va='bottom', ha='center') s_0 = '$0$' s_t = '$time$' kappa = '\\kappa' s_t_a = m_str(' t', kappa, 'occ') s_t_r = m_str(' t', kappa, 'rep') s_t_s = m_str(' t', '' , 'sub') s_t_c = m_str(' t', kappa, 'clo') s_arsc = [s_t_a, s_t_r, s_t_s, s_t_c, ] s_tau_r = m_str('tau', kappa, 'rep') s_tau_I = m_str('tau', kappa, 'I' ) s_tau_P = m_str('tau', kappa, 'P' ) s_I_t = m_str(' I', kappa, '', '(t)') s_P_t = m_str(' P', kappa, '', '(t)') s_U = m_str(' U', kappa, '') s_I = m_str(' I', kappa, '*') s_P = m_str(' P', kappa, '*') s_N_I = m_str(' N', kappa, 'I' ) s_N_P = m_str(' N', kappa, 'P' ) # time lags: accident date, reported date, submission date, closure date tau_arsc = [0.0, 0.0 , 0.0, 1.0] # placeholder # Paid amount, Incurred amount, Ultimate amount PIU = [0.0 , 0.0 , 1.0] # placeholder IP_pol = [[], []] # Long-tail pattern # tau_grid: list with lags tau_i (>=0) for which I_i and P_i are given tau_r, tau_c = min(tau_grid), max(tau_grid) t_r = tau_r / tau_c # t_rep relative to t_closure t_s = tau_eval / tau_c # t_sub relative to t_closure t_IP = np.array([tau_grid, I, P]) # array with time_grid, incurred and paid I_max = max(I) I1, tau_I_T, P_rel, tau_P_T = get_IP_tau(t_IP, tau_eval) Pt_I = get_pattern(tau_grid, I, tau_eval) Pt_P = get_pattern(tau_grid, P, tau_eval) t_T = Pt_I[0] / tau_c I_T = Pt_I[1] / I_max P_T = Pt_P[1] / I_max N_I = get_count(I_T) N_P = get_count(P_T) IP_pol[0].append(get_polygon(t_T, I_T, I_T[-1])) # Incurred polygon (integrated area) IP_pol[1].append(get_polygon(t_T, P_T, I_T[-1])) # Paid polygon (integrated area) tau_arsc[1] = t_r tau_arsc[2] = t_s PIU[0] = P_T[-1] PIU[1] = I_T[-1] fs = 6 fig, ax = plt.subplots(1,2) ax[0].set_box_aspect(0.5) ax[1].set_box_aspect(0.5) c0 = col_list[0][2] c1 = col_list[0][0] c2 = col_list[0][3] c3 = 'gray' c4 = 'lightgray' j = 0 for i in range(2): axs = ax[i] axs.set_title(ax_titles[i],fontsize=8) axs.set_axis_off() axs.fill(IP_pol[i][j][0], IP_pol[i][j][1], color=c4) plt_arrow(axs, -0.05, 0, 1.05, 0, arr_st='->', c=c0, ls='-', w=0.5) axs.text(-0.075, 0.0, s_0, fontsize=fs, color=c0, va='center', ha='right') axs.text( 1.075, 0.0, s_t, fontsize=fs, color=c0, va='center', ha='left') plt_x_tick(axs, tau_arsc[1]) plt_arrow(axs, 0, -0.075, 0, 1.1, arr_st='->', c=c0, ls='-', w=0.5) axs.text(-0.075, PIU[1], s_I, fontsize=fs, color=c2, va='center', ha='right') plt_xy(axs, tau_arsc[2], PIU[1], c=c2, ls='-', lw=0.5) axs.text(-0.025, PIU[2], s_U, fontsize=fs, color=c3, va='center', ha='right') plt_xy(axs, tau_arsc[3], PIU[2], c=c3, ls='--', lw=0.5) for k, x_k in enumerate(tau_arsc): if k==3: c_k = c3 else: c_k = c0 axs.text(x_k, -0.075, s_arsc[k], fontsize=fs, color=c_k, va='top', ha='center') if i==1: axs.text(-0.075, PIU[0], s_P, fontsize=fs, color=c2, va='center', ha='right') # Long-tail case x1 = tau_arsc[1] x2 = tau_arsc[2] x3 = tau_arsc[3] y0 = PIU[0] y1 = PIU[1] y2 = PIU[2] # Long-tail incurred axs = ax[0] axs.plot(t_T, I_T, color=c1) axs.plot([x2, x3], [y1, y2], color=c3, ls='--') x = tau_I_T / tau_c y = y1*0.6 axs.plot([x,x], (0, y1), color=c2, ls='--', lw=0.5) axs.text(x+0.05, y, s_I_t, fontsize=fs, color=c1, va='center', ha='left') y = y1*3/4 disp_arrow(axs, s_tau_I, 0, x, y, arr_st='<->', c=c2, ls='--', w=0.5) axs.text(x+0.05, 0.05, s_N_I+f'$={N_I}$', fontsize=fs, color=c2, va='bottom', ha='left') # Long-tail paid axs = ax[1] axs.plot(t_T, P_T, color=c1) axs.plot([x2, x3], [y0, y2], color=c3, ls='--') axs.plot([-0.05, x2], [y0, y0], color=c0, ls=':', lw=0.5) x = tau_P_T / tau_c y = y1/2 axs.plot([x,x], (0, y1), color=c2, ls='--', lw=0.5) axs.text(x+0.02, y-0.02, s_P_t, fontsize=fs, color=c1, va='center', ha='left') y = y1/2 disp_arrow(axs, s_tau_P, 0, x, y, arr_st='<->', c=c2, ls='--', w=0.5) disp_arrow(axs, s_tau_r, 0, x1, 0.1, arr_st='<->', c=c2, ls='--', w=0.5) axs.text(x+0.02, 0.05, s_N_P+f'$={N_P}$', fontsize=fs, color=c2, va='bottom', ha='left') file_name, ext_list = save_plot(plt, fn_ID) plt.show() def plot_t_IP(t, L_I, P, index_flat, col_list, lw_list, ls_list, label_list, fn_ID='dummy_plot'): # Create a chart depicting the temporal evolution of patterns and lags: # a) Input: paid and incurred patterns (5 cases with favorable, unbiased and adverse IBNER): # b) resulting temporal evolution of incurred lags # c) resulting temporal evolution of paid ratios # d) resulting temporal evolution of paid lags eps = 0.001 sub_kappa = '_{\\kappa}' ax_titles = [ ['a) paid and incurred patterns', 'c) paid/incurred ratios', ], ['b) incurred lags', 'd) paid lags', ], ] x_label = [ [None, None ], ['$t$ [mos.]', '$t$ [mos.]'], ] y_label = [ [f'$I{sub_kappa}$, $P{sub_kappa}$ [m CHF]', f'$P{sub_kappa}$ / $I{sub_kappa}$' ], [f'$\\tau{sub_kappa}^I$ [mos.]', f'$\\tau{sub_kappa}^P$ [mos.]' ], ] def plot_IP(ax, t_IP_tau, c, lw, ls, label): t_list = t_IP_tau[0] t_max = max(t_list) for k in range(4): i = k % 2 j = k // 2 y_list = t_IP_tau[k+1] y_max = max(y_list) if k == 0: ax_label = label else: ax_label = None axs = ax[i,j] axs.set_title(ax_titles[i][j]) axs.plot([0, t_max], [0, 0], 'k', lw=0.25) axs.plot([0, 0], [0, y_max], 'k', lw=0.25) if k == 2: axs.plot([0, t_max], [1, 1], 'k', lw=0.25) axs.plot(t_list, y_list, c, lw=lw, ls=ls, label=ax_label) axs.set_xlabel(x_label[i][j]) axs.set_ylabel(y_label[i][j]) fig, ax = plt.subplots(2,2, sharex = True, figsize=(10,4)) #Incurred patterns for i, I in enumerate(L_I): T_IP_tau = [[], [], [], [], []] t_IP = np.array([t, I, P]) T_IP_tau = get_IP_t(T_IP_tau, t_IP, 0) for T in t: T_IP_tau = get_IP_t(T_IP_tau, t_IP, T-eps) T_IP_tau = get_IP_t(T_IP_tau, t_IP, T+eps) T_IP_tau = get_IP_t(T_IP_tau, t_IP, max(t)+30) if i == index_flat: T_IP_flat = T_IP_tau plot_IP(ax, T_IP_tau, col_list[0][i], lw_list[0][i], ls_list[0][i], label_list[0][i]) #Incurred flat plot_IP(ax, T_IP_flat, col_list[0][index_flat], lw_list[0][index_flat], ls_list[0][index_flat], None) # Paid pattern pP = get_pattern(t, P) ax[0,0].plot(pP[0], pP[1], color=col_list[1][0], lw=lw_list[1][0], ls=ls_list[1][0], label=label_list[1][0]) ax[0,0].legend(loc='best', frameon=not False, fontsize=4) file_name, ext_list = save_plot(plt, fn_ID) plt.show() # ************************************************************************ if __name__ == "__main__": gray_scale = True time_grid, Inc_list, Paid, index_flat, label_list, color_list, lw_list, ls_list = get_patterns(gray_scale = gray_scale) plot_t_IP(time_grid, Inc_list, Paid, index_flat, color_list, lw_list, ls_list, label_list, fn_ID='patt_lags') t_eval = 75 # lag [month] for the evaluation of reduced variables i_eval = 3 # index of incurred pattern to be evaluated plot_IP(time_grid, Inc_list[i_eval], Paid, t_eval, color_list, fn_ID='red_var')