text
stringlengths
184
4.48M
import { Post } from './entities/post.entity'; import { BarsService } from '../bars/bars.service'; import { UsersService } from '../users/users.service'; import { Repository } from 'typeorm'; import { CreatePostDto } from './dto/create-post.dto'; import { UpdatePostDto } from './dto/update-post.dto'; import { ResponsePostDto } from './dto/response-post.dto'; export declare class PostsService { private postRepository; private usersService; private barsService; constructor(postRepository: Repository<Post>, usersService: UsersService, barsService: BarsService); create(createPostDto: CreatePostDto, userId: string): Promise<Post>; findOne(id: string): Promise<ResponsePostDto>; findAll(): Promise<ResponsePostDto[]>; findAllByBar(barId: string): Promise<ResponsePostDto[] | ResponsePostDto | null>; findAllByUser(userId: string): Promise<ResponsePostDto[] | ResponsePostDto | null>; update(id: string, updatePostDto: UpdatePostDto): Promise<Post>; remove(id: string): Promise<void>; }
import React, { useState } from "react"; import { Modal, Button, Form } from "react-bootstrap"; import FloatingLabel from "react-bootstrap/FloatingLabel"; import axios from "axios"; function ChangePasswordModal({ userId, token, handleClose }) { const [currentPassword, setCurrentPassword] = useState(""); const [newPassword, setNewPassword] = useState(""); const [newPasswordAgain, setNewPasswordAgain] = useState(""); const [feedback, setFeedback] = useState(""); const [passwordChanged, setPasswordChanged] = useState(false); const handleChangePassword = () => { const data = { old_password: currentPassword, password: newPassword, password_confirmation: newPasswordAgain, }; const config = { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }; axios .put( `https://www.s3.syntradeveloper.be/backend/api/users/${userId}/pass`, data, config ) .then((response) => { console.log(response.data); // You can do something with the response data here setFeedback("Password has been changed"); setPasswordChanged(true); }) .catch((error) => { console.error(error); setFeedback("Failed to change password"); }); }; const handleSubmit = (event) => { event.preventDefault(); handleChangePassword(); }; return ( <div> <Modal show={!passwordChanged} onHide={handleClose} style={{ backdropFilter: "blur(5px)", }} > <Modal.Header closeButton> <Modal.Title>Change Password</Modal.Title> </Modal.Header> <Modal.Body> <Form className="d-flex flex-column" onSubmit={handleSubmit}> <FloatingLabel controlId="floatingPassword" label="Current Password" className="mb-3" > <Form.Control type="password" placeholder="Current Password" value={currentPassword} onChange={(e) => setCurrentPassword(e.target.value)} /> </FloatingLabel> <FloatingLabel controlId="floatingPassword" label="New Password" className="mb-3" > <Form.Control type="password" placeholder="New Password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} /> </FloatingLabel> <FloatingLabel controlId="floatingPassword" label="New Password"> <Form.Control type="password" placeholder="New Password Again" value={newPasswordAgain} onChange={(e) => setNewPasswordAgain(e.target.value)} /> </FloatingLabel> <Button variant="dark" type="submit" className="mt-3"> Save Changes </Button> </Form> <div>{feedback}</div> </Modal.Body> <Modal.Footer> </Modal.Footer> </Modal> </div> ); } export default ChangePasswordModal;
import { Store } from './store'; export class Product { constructor( readonly id: string, readonly name: string, /// The price of the product in cents readonly price: number, readonly category: string | null ) {} static fromRow(row: ProductRow): Product { return new Product(row.id, row.name, row.price, row.category); } } interface ProductRow { id: string; name: string; price: number; category: string | null; } export type ProductInput = { name: string; price: number; category: string | null; }; export function isProductInput(body: unknown): body is ProductInput { return ( typeof body === 'object' && body !== null && 'name' in body && typeof body.name === 'string' && 'price' in body && typeof body.price === 'number' && ('category' in body ? typeof body.category === 'string' || body.category === null : true) ); } export class ProductStore extends Store { // returns all products ordered by name async index(): Promise<Product[]> { const conn = await super.connectToDB(); try { const sql = 'SELECT * FROM products ORDER BY name'; const result = await conn.query(sql); return result.rows.map(Product.fromRow); } catch (err) { throw new Error(`Unable to get products: ${err}`); } finally { conn.release(); } } async show(id: string): Promise<Product> { const conn = await super.connectToDB(); try { const sql = 'SELECT * FROM products WHERE id=($1)'; const result = await conn.query(sql, [id]); if (result.rows.length === 0) { throw new Error(`Product ${id} not found`); } return Product.fromRow(result.rows[0]); } catch (err) { throw new Error(`Unable to get product ${id}: ${err}`); } finally { conn.release(); } } async create(productInput: ProductInput): Promise<Product> { const conn = await super.connectToDB(); try { const sql = 'INSERT INTO products (name, price, category) VALUES($1, $2, $3) RETURNING *'; const result = await conn.query(sql, [productInput.name, productInput.price, productInput.category]); const newProduct = result.rows[0]; return Product.fromRow(newProduct); } catch (err) { throw new Error(`Unable to create product: ${err}`); } finally { conn.release(); } } async byCategory(category: string): Promise<Product[]> { const conn = await super.connectToDB(); try { const sql = 'SELECT * FROM products WHERE category=($1)'; const result = await conn.query(sql, [category]); return result.rows.map(Product.fromRow); } catch { throw new Error(`Unable to get products in category ${category}`); } finally { conn.release(); } } }
package enumColores2; enum Color { ROJO, VERDE, AZUL; } public class Test { // Tambien podemos declararlo dentro de la clase: // enum Color { // ROJO, VERDE, AZUL; // } public static void main(String[] args) { // Llamando a values() Color arr[] = Color.values(); // enum con bucle for each for (Color col : arr) { // Llamando a ordinal() para encontrar el indice // de color. System.out.println(col + " en el indice " + col.ordinal()); } // Usando valueOf(). Devuelve un objeto de // Color con la constante dada. // La segunda linea comentada causa la excepcion // IllegalArgumentException (Implementa el tratamiento de la excepcion para practicar) System.out.println(Color.valueOf("ROJO")); // El system.out.println obliga la conversion a String //System.out.println(Color.valueOf("BLANCO")); } }
import { ICountry } from '../../types'; import styled from 'styled-components'; import { BoxShadow, BoxShadowHovered } from '../mixins/Mixins'; import { Property, Value, Title } from '../elements/Typography'; import { Link } from 'react-router-dom'; const StyledLink = styled(Link)` text-decoration: none; `; const CardContainer = styled.div` display: flex; flex-direction: column; height: 17rem; background: ${(props) => props.theme.colors.elements}; border-radius: 3px; overflow: hidden; ${BoxShadow}; color: ${(props) => props.theme.colors.text}; &:hover { ${BoxShadowHovered}; } `; const CardSubContainer = styled.div` padding: 1rem; `; interface IFlag { source: string; } const Flag = styled.div<IFlag>` width: 100%; height: 60%; background-image: ${(props) => `url('${props.source}')`}; background-size: cover; background-repeat: no-repeat; background-position: center center; `; interface ICountryCardProps { country: ICountry; } const CountryCard = ({ country }: ICountryCardProps): JSX.Element => { return ( <StyledLink to={`/country/${country.cca3}`}> <CardContainer> <Flag source={country.flags.png} /> <CardSubContainer> <Title>{country.name.common}</Title> <div> <Property>Population: </Property> <Value>{country.population.toLocaleString()}</Value> </div> <div> <Property>Region: </Property> <Value>{country.region}</Value> </div> <div> <Property>Capital: </Property> <Value>{country.capital}</Value> </div> </CardSubContainer> </CardContainer> </StyledLink> ); }; export default CountryCard;
import { Autocomplete, TextField } from "@mui/material"; import { useSelector } from "react-redux"; import { selectors } from "../../../store"; import { Set } from "../../../domain/encyclopedia"; import { SetSymbol } from "../../common"; import { SyntheticEvent, useCallback, useMemo } from "react"; type SetSelectorOption = { label: string; parent: Set; }; const SetSelectorOption = ( props: any, option: SetSelectorOption, state: any ) => { const classes = state.selected ? ["autocomplete-option", "selected", "set-container"] : ["autocomplete-option", "set-container"]; return ( <li {...props} key={option.parent.code} classes={classes}> <SetSymbol setAbbrev={option.parent.code} /> <div>{`${option.parent.name} (${option.parent.code.toUpperCase()})`}</div> </li> ); }; const SetSelector = (props: { selectedSetCode: string | null; setSelectedSetCode: (code: string | null) => void; }) => { const setGroupsInBoxes = useSelector(selectors.setGroupsInBoxes); const options = useMemo<SetSelectorOption[]>( () => setGroupsInBoxes.map((s) => ({ label: s.parent.name, parent: s.parent })), [setGroupsInBoxes] ); const selectedOption = options.find((o) => o.parent.code === props.selectedSetCode) ?? null; const onSelection = useCallback( (e: SyntheticEvent<Element, Event>, value: SetSelectorOption | null) => props.setSelectedSetCode(value?.parent.code ?? null), [props.setSelectedSetCode] ); return ( <Autocomplete className="control" options={options} sx={{ width: 300 }} renderInput={(params) => ( <TextField {...params} label="Set" onFocus={(e) => e.target.select()} /> )} onChange={onSelection} value={selectedOption} autoSelect autoHighlight selectOnFocus openOnFocus renderOption={SetSelectorOption} /> ); }; export default SetSelector;
part of 'register_cubit.dart'; class RegisterState extends Equatable { final String? phoneNumberValidationMsg; final DioError? error; final bool? isApiSuccess; final bool? isApiError; final bool? isOtpVerified; final bool? isTermsConditionChecked; final bool? isPhoneNumberValid; final bool? isAllValid; final bool? isUserRegistered; final bool? isUserLogin; final bool? isLoading; final UserResponse? user; const RegisterState({ this.error, this.isApiError, this.phoneNumberValidationMsg = "", this.isApiSuccess = false, this.isOtpVerified = false, this.isTermsConditionChecked = false, this.isAllValid = false, this.isPhoneNumberValid = false, this.user, this.isUserRegistered, this.isUserLogin, this.isLoading, }); @override List<Object?> get props => [ error, phoneNumberValidationMsg, isApiSuccess, isOtpVerified, isTermsConditionChecked, isAllValid, isPhoneNumberValid, user, isUserLogin, isUserRegistered, isLoading, isApiError, ]; RegisterState copyWith({ String? phoneNumberValidationMsg, DioError? error, bool? isApiSuccess, bool? isOtpVerified, bool? isTermsConditionChecked, bool? isAllValid, bool? isPhoneNumberValid, UserResponse? user, bool? isUserRegistered, bool? isUserLogin, bool? isLoading, bool? isApiError, }) { return RegisterState( phoneNumberValidationMsg: phoneNumberValidationMsg ?? this.phoneNumberValidationMsg, error: error ?? this.error, isApiSuccess: isApiSuccess ?? this.isApiSuccess, isOtpVerified: isOtpVerified ?? this.isOtpVerified, isTermsConditionChecked: isTermsConditionChecked ?? this.isTermsConditionChecked, isAllValid: isAllValid ?? this.isAllValid, isPhoneNumberValid: isPhoneNumberValid ?? this.isPhoneNumberValid, user: user ?? this.user, isUserLogin: isUserLogin ?? this.isUserLogin, isUserRegistered: isUserRegistered ?? this.isUserRegistered, isLoading: isLoading ?? this.isLoading, isApiError: isApiError ?? this.isApiError); } } class RegisterStateInitial extends RegisterState { const RegisterStateInitial(); } class RegisterStateLoading extends RegisterState { const RegisterStateLoading(); } class RegisterStateSuccess extends RegisterState { const RegisterStateSuccess( {super.phoneNumberValidationMsg, super.isApiSuccess, super.user}); } class RegisterStateFailed extends RegisterState { const RegisterStateFailed({super.error, super.phoneNumberValidationMsg}); }
import crypto from "node:crypto"; import { Entity, RecoveryToken, RecoveryTokenModel, User } from "../models"; import path from "path"; import { promises as fs } from "fs"; import { sendMail } from "../config/email"; import Handlebars from "handlebars"; export const randomTokenString = () => crypto.randomBytes(40).toString("hex"); export const readFile = (path: string) => fs.readFile(path, { encoding: "utf-8" }); export const generateRecoveryToken = (user: string) => { let expiredAt = new Date(); expiredAt.setHours( expiredAt.getHours() + parseInt(process.env.ACTIVATION_TOKEN_MAX_AGE!) ); return new RecoveryTokenModel({ user, token: randomTokenString(), expires: expiredAt.getTime(), }); }; // Function for sending a recovery password email to the user export const sendMailRecoveryPassword = async ( user: User, recoveryToken: RecoveryToken ) => { try { const htmlTemplatePath = path.join( __dirname, "..", "public", "template", "recoveryPassword.html" ); const htmlTemplate = await readFile(htmlTemplatePath); const template = Handlebars.compile(htmlTemplate); const replacements = { firstName: (user.entity as Entity).firstname, token: recoveryToken.token, expires: new Date(recoveryToken.expires).toLocaleDateString(), // TODO: Change URL on production frontendUri: "https://cafeterias.dev", actionType: "Crear nueva contraseña", }; const htmlToSend = template(replacements); await sendMail({ to: user.email, html: htmlToSend, }); } catch (error) { console.error(error); } };
package com.dicoding.appstorysub2.data.remote.retrofit import com.dicoding.appstorysub2.data.local.sharedpref.SessionManager import okhttp3.Interceptor import okhttp3.Response import javax.inject.Inject import javax.inject.Singleton @Singleton class AuthInterceptor @Inject constructor( private val sessionManager: SessionManager, ) : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val requestBuilder = chain.request().newBuilder() sessionManager.fetchAuthToken()?.let { requestBuilder.addHeader("Authorization", "Bearer $it") } return chain.proceed(requestBuilder.build()) } }
package ticTacToeGame; import java.util.Scanner; //manager class public class TicTacToe { private Player player1, player2; private Board board; public static void main(String [] args) { TicTacToe t = new TicTacToe(); t.startGame(); } public void startGame() { Scanner sc = new Scanner(System.in); //To: //Players input player1 = takePlayerInput(1); player2 = takePlayerInput(2); while(player1.getSymbol() == player2.getSymbol()) { System.out.println("Symbol already taken !! Pick another Symbol !!"); char symbol = sc.next().charAt(0); player2.setSymbol(symbol); } //create a board board = new Board(player1.getSymbol(),player2.getSymbol()); //conduct the game boolean player1Turn = true; int status = Board.INCOMPLETE; while(status == Board.INCOMPLETE || status == Board.INVALID) { if(player1Turn) { System.out.println("Player 1 - "+player1.getName()+"'s turn"); System.out.println("Enter x: "); int x = sc.nextInt(); System.out.println("Enter y: "); int y = sc.nextInt(); status = board.move(player1.getSymbol(), x, y); if(status != Board.INVALID) { player1Turn = false; board.print(); }else { System.out.println("Invalid Move !! Try Again !!"); } }else { System.out.println("Player 2 - "+player2.getName()+"'s turn"); System.out.println("Enter x: "); int x = sc.nextInt(); System.out.println("Enter y: "); int y = sc.nextInt(); status = board.move(player2.getSymbol(), x, y); if(status != Board.INVALID) { player1Turn = true; board.print(); }else { System.out.println("Invalid Move !! Try Again !!"); } } } if(status == Board.PLAYER_1_WINS) { System.out.println("Player 1 - "+player1.getName()+" wins !!"); }else if(status == Board.PLAYER_2_WINS) { System.out.println("Player 1 - "+player2.getName()+" wins !!"); }else { System.out.println("Draw !!"); } } private Player takePlayerInput(int num) { Scanner sc = new Scanner(System.in); System.out.println("Enter Player "+ num + " name: "); String name = sc.nextLine(); System.out.println("Enter Player "+ num + " symbol: "); char symbol = sc.next().charAt(0); Player p = new Player(name,symbol); return p; } }
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.contrib.auth.models import User from lkusers.models import ContribUsers from django import forms class UserLoginForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'class': 'name-quiz'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'name-quiz'})) class Meta: model = User fields = ('username', 'password') class UserRegistrationForm(UserCreationForm): username = forms.CharField(widget=forms.TextInput(attrs={'class': 'name-quiz'})) password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'name-quiz'})) password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'name-quiz'})) class Meta: model = User fields = ('username', 'password1', 'password2')
/* * Code adapted from basicZeroFun.hpp in Examples/LinearAlgebraUtil */ #include "../include/solver.hpp" #include <iostream> #include <string> SolverTraits::FullResultType QuasiNewton::solve() { SolverTraits::ResultType a = m_a; double ya = m_f(a); double res = std::abs(ya); unsigned int it{0u}; double check = m_tol * res + m_tola; bool go_on = res > check; while(go_on && it < m_max_it) { ++it; a += - ya / m_df(a); ya = m_f(a); res = std::abs(ya); go_on = res > check; } m_result.zero = a; m_result.conv_status = it < m_max_it; m_result.n_it = it; return m_result; } void QuasiNewton::printFullResult() const { std::cout << "--- Quasi-Newton ---" << std::endl; std::cout << "Zero: " << m_result.zero << std::endl; std::cout << "Convergence status: " << (m_result.conv_status ? "converged" : "not converged") << std::endl; std::cout << "Number of iterations: " << m_result.n_it << std::endl; std::cout << std::endl; } SolverTraits::FullResultType Bisection::solve() { SolverTraits::ResultType a = m_a; SolverTraits::ResultType b = m_b; double ya = m_f(a); double yb = m_f(b); double delta = b - a; if(ya * yb >= 0) std::cerr << "Function must change sign at the two end values." <<std::endl; double yc{ya}; SolverTraits::ResultType c{a}; unsigned int it{0u}; while(std::abs(delta) > 2 * m_tol && it < m_max_it) { ++it; c = (a + b) / 2.; yc = m_f(c); if(yc * ya < 0.0) { yb = yc; b = c; } else { ya = yc; a = c; } delta = b - a; } m_result.zero = (a + b) / 2.; m_result.conv_status = it < m_max_it; m_result.n_it = it; return m_result; } void Bisection::printFullResult() const { std::cout << "--- Bisection ---" << std::endl; std::cout << "Zero: " << m_result.zero << std::endl; std::cout << "Convergence status: " << (m_result.conv_status ? "converged" : "not converged") << std::endl; std::cout << "Number of iterations: " << m_result.n_it << std::endl; std::cout << std::endl; } SolverTraits::FullResultType Secant::solve() { SolverTraits::ResultType a = m_a; SolverTraits::ResultType b = m_b; SolverTraits::ResultType c{a}; double ya = m_f(a); double res = std::abs(ya); unsigned int it{0u}; double check = m_tol * res + m_tola; bool go_on = res > check; while(go_on && it < m_max_it) { ++it; double yb = m_f(b); c = a - ya * (b - a) / (yb - ya); double yc = m_f(c); res = std::abs(yc); go_on = res > check; ya = yc; a = c; } m_result.zero = c; m_result.conv_status = it < m_max_it; m_result.n_it = it; return m_result; } void Secant::printFullResult() const { std::cout << "--- Secant ---" << std::endl; std::cout << "Zero: " << m_result.zero << std::endl; std::cout << "Convergence status: " << (m_result.conv_status ? "converged" : "not converged") << std::endl; std::cout << "Number of iterations: " << m_result.n_it << std::endl; std::cout << std::endl; }
The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. #include "QmitkConvertGeometryDataToROIAction.h" #include <mitkGeometryData.h> #include <mitkImage.h> #include <mitkNodePredicateDataType.h> #include <mitkROI.h> #include <QMessageBox> namespace { void handleInvalidNodeSelection() { auto message = QStringLiteral("All selected bounding boxes must be child nodes of a single common reference image with a non-rotated geometry!"); MITK_ERROR << message; QMessageBox::warning(nullptr, QStringLiteral("Convert to ROI"), message); } bool isRotated(const mitk::BaseGeometry* geometry) { const auto* matrix = geometry->GetVtkMatrix(); for (int j = 0; j < 3; ++j) { for (int i = 0; i < 3; ++i) { if (i != j && matrix->GetElement(i, j) > mitk::eps) return true; } } return false; } std::pair<std::vector<const mitk::DataNode*>, mitk::DataNode*> getValidInput(const QList<mitk::DataNode::Pointer>& selectedNodes, const mitk::DataStorage* dataStorage) { std::pair<std::vector<const mitk::DataNode*>, mitk::DataNode*> result; result.first.reserve(selectedNodes.size()); std::copy_if(selectedNodes.cbegin(), selectedNodes.cend(), std::back_inserter(result.first), [](const mitk::DataNode* node) { return node != nullptr && dynamic_cast<mitk::GeometryData*>(node->GetData()) != nullptr; }); for (auto node : result.first) { auto sourceNodes = dataStorage->GetSources(node, mitk::TNodePredicateDataType<mitk::Image>::New()); if (sourceNodes->size() != 1) mitkThrow(); if (result.second == nullptr) { if (isRotated(sourceNodes->front()->GetData()->GetGeometry())) mitkThrow(); result.second = sourceNodes->front(); } else if (result.second != sourceNodes->front()) { mitkThrow(); } } return result; } } QmitkConvertGeometryDataToROIAction::QmitkConvertGeometryDataToROIAction() { } QmitkConvertGeometryDataToROIAction::~QmitkConvertGeometryDataToROIAction() { } void QmitkConvertGeometryDataToROIAction::Run(const QList<mitk::DataNode::Pointer>& selectedNodes) { try { auto [nodes, referenceNode] = getValidInput(selectedNodes, m_DataStorage); auto roi = mitk::ROI::New(); roi->SetClonedGeometry(referenceNode->GetData()->GetGeometry()); unsigned int id = 0; for (auto node : nodes) { mitk::ROI::Element element(id++); element.SetProperty("name", mitk::StringProperty::New(node->GetName())); if (auto* color = node->GetProperty("Bounding Shape.Deselected Color"); color != nullptr) element.SetProperty("color", color); const auto* geometry = node->GetData()->GetGeometry(); const auto origin = geometry->GetOrigin() - roi->GetGeometry()->GetOrigin(); const auto spacing = geometry->GetSpacing(); const auto bounds = geometry->GetBounds(); mitk::Point3D min; mitk::Point3D max; for (size_t i = 0; i < 3; ++i) { min[i] = origin[i] / spacing[i] + bounds[2 * i]; max[i] = origin[i] / spacing[i] + bounds[2 * i + 1] - 1; } element.SetMin(min); element.SetMax(max); roi->AddElement(element); } auto roiNode = mitk::DataNode::New(); roiNode->SetName(referenceNode->GetName() + " ROI" + (roi->GetNumberOfElements() > 1 ? "s" : "")); roiNode->SetData(roi); m_DataStorage->Add(roiNode, referenceNode); } catch (const mitk::Exception&) { handleInvalidNodeSelection(); } } void QmitkConvertGeometryDataToROIAction::SetDataStorage(mitk::DataStorage* dataStorage) { m_DataStorage = dataStorage; } void QmitkConvertGeometryDataToROIAction::SetFunctionality(berry::QtViewPart*) { } void QmitkConvertGeometryDataToROIAction::SetSmoothed(bool) { } void QmitkConvertGeometryDataToROIAction::SetDecimated(bool) { }
package com.engicodes.backend.model; import jakarta.persistence.*; import lombok.Builder; import lombok.Getter; import lombok.Setter; import java.time.LocalDate; @Entity @Getter @Setter @Builder public class Recipe { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Integer recipeId; @Column( columnDefinition = "TEXT" ) private String title; @Column( columnDefinition = "TEXT" ) private String ingredients; @Column( columnDefinition = "TEXT" ) private String instructions; @Column( columnDefinition = "TEXT" ) private String cuisine; @Column @Temporal(TemporalType.DATE) private LocalDate date; public Recipe() { } public Recipe(Integer id, String title, String ingredients, String instructions, String cuisine, LocalDate date) { this.recipeId = id; this.title = title; this.ingredients = ingredients; this.instructions = instructions; this.cuisine = cuisine; this.date = date; } public Recipe(String title, String ingredients, String instructions, String cuisine, LocalDate date) { this.title = title; this.ingredients = ingredients; this.instructions = instructions; this.cuisine = cuisine; this.date = date; } }
#ifndef TRANSPORTWIDGET_H #define TRANSPORTWIDGET_H #include <QWidget> #include <QLayout> #include <QPushButton> #include <QSpinBox> #include <QLabel> #include <QDebug> #include <QTimer> #include <QCheckBox> #include <QPainter> #include <QStyleOption> #include "transport.h" #include "mastervolumeslider.h" using namespace sow; class TransportWidget : public QWidget { Q_OBJECT public: explicit TransportWidget(QWidget *parent = 0); void setTransport(Transport* qtTransport); float speed(); void setSpeed(float speed); private: bool pause_; bool record_; bool looping_; bool mute_; float speed_; float masterVolume_; QIcon playIcon_; QIcon pauseIcon_; QIcon recordOnIcon_; QIcon recordOffIcon_; QIcon loopOnIcon_; QIcon loopOffIcon_; QIcon muteOnIcon_; QIcon muteOffIcon_; QPushButton* pauseButton_; QPushButton* recordButton_; QPushButton* loopButton_; QPushButton* muteButton_; QSpinBox* speedBox_; MasterVolumeSlider* masterVolumeSlider_; protected: void paintEvent(QPaintEvent* event) override; signals: void pausedChanged(bool pause); void recordChanged(bool record); void loopingChanged(bool loop); void speedChanged(float speed); void muteChanged(bool mute); void masterVolumeChanged(float vol); public slots: void onSpeedChanged(int speed); void onDatasetChanged(sow::Dataset *dataset); void onPauseButtonReleased(); void onRecordButtonReleased(); void onLoopButtonReleased(); void onMuteButtonReleased(); void onSpeedIncrementedUp(); void onSpeedIncrementedDown(); void onLargeSpeedIncrementedUp(); void onLargeSpeedIncrementedDown(); void onVolumeUp(); void onVolumeDown(); private slots: void onSpeedBoxValueChanged(int speed); void onMasterVolumeChanged(int vol); }; #endif // TRANSPORTWIDGET_H
import Head from "next/head"; //Components import { PostCard, PostWidget, Categories } from "../components"; //API import { getPosts } from "../services"; //Sections import { FeaturedPosts } from "../sections/index"; export default function Home({ posts }) { return ( <div className="container mx-auto px-10 mb-8"> <Head> <title>CMS</title> <link rel="icon" href="/favicon.ico" /> </Head> <FeaturedPosts /> <div className=" grid lg:grid-cols-12 grid-cols-1 gap-12"> <div className=" lg:col-span-8 col-span-1"> {posts.map((post) => ( <PostCard ksy={post.title} post={post.node} /> ))} </div> <div className="lg:col-span-4 col-span-1"> <div className="lg:sticky relative top-8"> <PostWidget /> <Categories /> </div> </div> </div> </div> ); } // Fetch data at build time export async function getStaticProps() { const posts = (await getPosts()) || []; return { props: { posts }, }; }
from UndirectedGraph import UndirectedGraph from Exceptions import undirected_exception class Console: def __init__(self): self.__fileName = "graph.txt" self.__options = {"1": self.__loadGraph, "2": self.__connectedComponentsWithDFS, "3": self.__addEdge, "4": self.__addVertex} def __printMenu(self): print("Options: ") print("1.load graph from file") print("2.Print the connected components of the graph using DFS") print("3.Add an edge") print("4.Add a vertex") print("exit - quit the program") def __loadGraph(self): try: with open(self.__fileName, "r") as file: firstLine = file.readline() firstLine = firstLine.strip().split() vertices, edges = int(firstLine[0]), int(firstLine[1]) self.__graph = UndirectedGraph(vertices) for times in range(edges): line = file.readline() line = line.strip().split() start, end, cost = int(line[0]), int(line[1]), int(line[2]) try: self.__graph.addEdge(start, end) except undirected_exception as me: continue print("Graph loaded.") except IOError: raise undirected_exception("File Reading Error") def __connectedComponentsWithDFS(self): self.__graph.connectedComponents() print("The connected components consist of the following lists of vertices:") self.__graph.printSubgraphs() print("Each list of vertices is now a subgraph, stored in a list of subgraphs as a private field of the Undirected Graph class") def __addEdge(self): print("x:") x = int(input()) print("y:") y = int(input()) try: self.__graph.addEdge(x, y) except undirected_exception as me: print(me) def __addVertex(self): print("x:") x = int(input()) try: self.__graph.addVertex(x) except undirected_exception as me: print(me) def main(self): print(">>") while True: self.__printMenu() cmd = input() if cmd == "exit": return elif cmd in self.__options: self.__options[cmd]() c = Console() c.main()
package com.example.demo.redis; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import java.time.Duration; @Configuration @EnableCaching public class RedisConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Bean public RedisConnectionFactory redisConnectionFactory() { return new LettuceConnectionFactory(host, port); } @Bean public RedisCacheConfiguration cacheConfiguration() { return RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofMinutes(2)) .disableCachingNullValues() .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); } }
import numpy as np class GradientDescentLinearRegression: """ Linear Regression with gradient-based optimization. Parameters ---------- learning_rate : float Learning rate for the gradient descent algorithm. max_iterations : int Maximum number of iteration for the gradient descent algorithm. eps : float Tolerance level for the Euclidean norm between model parameters in two consequitive iterations. The algorithm is stopped when the norm becomes less than the tolerance level. """ def __init__(self, learning_rate=1, max_iterations=10000, eps=1e-6): self.learning_rate = learning_rate self.max_iterations = max_iterations self.eps = eps def predict(self, X): """Returns predictions array of shape [n_samples,1]""" return np.dot(X, self.w.T) def cost(self, X, y): """Returns the value of the cost function as a scalar real number""" y_pred = self.predict(X) loss = (y - y_pred) ** 2 return np.mean(loss) def grad(self, X, y): """Returns the gradient vector""" y_pred = self.predict(X) d_intercept = -2 * sum(y - y_pred) # dJ/d w_0. d_x = -2 * sum(X[:, 1:] * (y - y_pred).reshape(-1, 1)) # dJ/d w_i. g = np.append(np.array(d_intercept), d_x) # Gradient. return g / X.shape[0] # Average over training samples. def adagrad(self, g): self.G += g ** 2 # Update cache. step = self.learning_rate / (np.sqrt(self.G + self.eps)) * g return step def fit(self, X, y, method="adagrad", verbose=True): """ Fit linear model with gradient descent. Parameters ---------- X : numpy array or sparse matrix of shape [n_samples,n_predictors] Training data y : numpy array of shape [n_samples,1] Target values. method : string Defines the variant of gradient descent to use. Possible values: "standard", "adagrad". verbose: boolean If True, print the gradient, parameters and the cost function for each iteration. Returns ------- self : returns an instance of self. """ self.w = np.zeros(X.shape[1]) # Initialization of params. if method == "adagrad": self.G = np.zeros(X.shape[1]) # Initialization of cache for AdaGrad. w_hist = [self.w] # History of params. cost_hist = [self.cost(X, y)] # History of cost. for iter in range(self.max_iterations): g = self.grad(X, y) # Calculate the gradient. if method == "standard": step = self.learning_rate * g # Calculate standard gradient step. elif method == "adagrad": step = self.adagrad(g) # Calculate AdaGrad step. else: raise ValueError("Method not supported.") self.w = self.w - step # Update parameters. w_hist.append(self.w) # Save to history. J = self.cost(X, y) # Calculate the cost. cost_hist.append(J) # Save to history. if verbose: print(f"Iter: {iter}, gradient: {g}, params: {self.w}, cost: {J}") # Stop if update is small enough. if np.linalg.norm(w_hist[-1] - w_hist[-2]) < self.eps: break # Final updates before finishing. self.iterations = iter + 1 # Due to zero-based indexing. self.w_hist = w_hist self.cost_hist = cost_hist self.method = method return self
import React, { useState, useEffect, ChangeEvent } from "react"; import axios, { AxiosResponse } from 'axios'; import Select from 'react-select'; import { ArrowsCounterClockwise } from "phosphor-react"; type Currency = { value: string; label: string; }; type ExchangeRates = { [key: string]: number; }; function App(): JSX.Element { const [baseCurrency, setBaseCurrency] = useState<string>('EUR'); const [targetCurrency, setTargetCurrency] = useState<string>('USD'); const [amount, setAmount] = useState<number>(1); const [exchangeRates, setExchangeRates] = useState<ExchangeRates>({}); const accessKey: string = 'efee33b5965ef65cd7229ba0521a2241'; const currencies: Currency[] = [ { value: 'EUR', label: 'Euro' }, { value: 'USD', label: 'US Dollar' }, { value: 'CZK', label: 'Czech Koruna' }, { value: 'GBP', label: 'British Pound' }, ]; useEffect(() => { fetchExchangeRates(); }, []); const fetchExchangeRates = (): void => { axios .get(`http://api.exchangeratesapi.io/v1/latest?access_key=${accessKey}`) .then((response: AxiosResponse<{ rates: ExchangeRates }>) => { setExchangeRates(response.data.rates); }) .catch((error: Error) => { console.error('Error fetching data', error); }); }; const baseCurrencyOption = currencies.find(curr => curr.value === baseCurrency); const targetCurrencyOption = currencies.find(curr => curr.value === targetCurrency); const handleBaseCurrencyChange = (selectedOption: Currency | null): void => { if (selectedOption && 'value' in selectedOption) { setBaseCurrency(selectedOption.value); } }; const handleTargetCurrencyChange = (selectedOption: Currency | null): void => { if (selectedOption && 'value' in selectedOption) { setTargetCurrency(selectedOption.value); } }; const handleAmountChange = (event: ChangeEvent<HTMLInputElement>): void => { setAmount(parseFloat(event.target.value)); }; const convertedAmount = convertCurrency(); function convertCurrency(): string { const baseRate = exchangeRates[baseCurrency]; const targetRate = exchangeRates[targetCurrency]; if (baseRate && targetRate) { const convertAmount = (amount / baseRate) * targetRate; return convertAmount.toLocaleString(undefined, { maximumFractionDigits: 2, }) + ' ' + targetCurrency; } return 'Invalid currency'; } return ( <div className="flex items-center justify-center m-[200px]"> <div className="flex flex-col items-center justify-center text-center h-[400px] w-[600px] bg-white rounded-md"> <h1 className="text-3xl font-bold mb-5">Currency Converter</h1> <div className="flex"> <div className="currency-select px-10 text-2xl "> <label className="font-bold">Base Currency:</label> <Select<Currency> options={currencies} value={baseCurrencyOption} onChange={handleBaseCurrencyChange} /> </div> <div className="currency-select px-10 text-2xl "> <label className="font-bold">Target Currency:</label> <Select<Currency> options={currencies} value={targetCurrencyOption} onChange={handleTargetCurrencyChange} /> </div> </div> <div className="flex flex-col md:flex-row justify-center items-center text-2xl font-bold"> <div className="relative flex items-center"> <input className="py-4 pl-10 border hover:border-lime-700 flex justify-center items-center text-center pr-10" type="number" value={amount.toString()} onChange={handleAmountChange} /> <span className="absolute inset-y-0 left-0 flex items-center pl-2 text-gray-400"> {baseCurrency} </span> <div className="absolute inset-y-0 right-0 flex items-center pr-2 pointer-events-none"> <svg className="w-10 h-10 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" /> </svg> </div> </div> <div className="mx-10"> <ArrowsCounterClockwise size={100} color="#170707" /> </div> <div className="relative flex items-center"> <input className="py-4 pl-10 border hover:border-lime-700 flex justify-center items-center text-center pr-10" type="text" readOnly value={`${convertedAmount} `} /> <div className="absolute inset-y-0 right-0 flex items-center pr-2 pointer-events-none"> </div> </div> </div> </div> </div> ); } export default App;
import { Post } from './post.model'; import { Subject } from 'rxjs'; import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { map } from 'rxjs/operators'; import { Title } from '@angular/platform-browser'; import { Router } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class PostService { private posts: Post[] = []; private PostsUpdated = new Subject<Post[]>(); constructor(private http: HttpClient, private router: Router) { } getPost() { this.http.get<{ message: string, Myposts: any }>('http://localhost:3000/api/posts') .pipe(map((postData) => { console.log(postData.Myposts); return postData.Myposts.map(post => { const newpost = { title: post.title, content: post.content, id: post._id } return newpost; }); })) .subscribe((transformedPosts) => { this.posts = transformedPosts; this.PostsUpdated.next([...this.posts]); }); } getPostUpdateListener() { return this.PostsUpdated.asObservable(); } addPost(Title: string, Content: string) { const post: Post = { id: null, title: Title, content: Content }; this.http.post<{ message: string }>('http://localhost:3000/api/posts', post) .subscribe((responseData) => { console.log(responseData.message); this.posts.push(post); this.PostsUpdated.next([...this.posts]); this.router.navigate(["/"]); }); } deletePost(postId: string) { this.http.delete('http://localhost:3000/api/posts/' + postId) .subscribe(() => { console.log("Deleted!"); }); } GetPost(id: string) { return this.http.get<{ _id: string, title: string, content: string }>("http://localhost:3000/api/posts/" + id); } UpdatePost(id: string, title: string, content: string) { const post: Post = { id: id, title: title, content: content }; this.http.put('http://localhost:3000/api/posts/' + id, post) .subscribe(response => { const UpdatedPosts = [...this.posts]; const OldPostIndex = UpdatedPosts.findIndex(p => p.id === post.id); UpdatedPosts[OldPostIndex] = post; this.posts = UpdatedPosts; this.PostsUpdated.next([...this.posts]); this.router.navigate(["/"]); }); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>justcereal.com</title> <!---------- LINKS ----------> <link rel="shortcut icon" href="imagenes/favicon.png"> <link href='https://unpkg.com/[email protected]/css/boxicons.min.css' rel='stylesheet'> <link rel="stylesheet" href="css/styles.css"> <link rel="stylesheet" href="css/media-query.css"> </head> <body> <!--------- HEADER ---------> <header class="header-home"> <nav class="nav container"> <a href="/index.html" class="nav-logo"> <img src="imagenes/logo-black.png" > </a> <!-- MENU DE CATEGORÍAS --> <div class="nav-menu" id="nav-menu"> <ul class="nav-categorias"> <li class="nav-tema"> <a href="/index.html" class="nav-link">Home</a> </li> <li class="nav-tema"> <a href="#conócenos" class="nav-link">Conócenos</a> </li> <li class="nav-tema"> <a href="#empresas" class="nav-link">Empresas</a> </li> <li class="nav-tema"> <a href="#tienda" class="nav-link">Tienda</a> </li> <li class="nav-tema"> <a href="#contacto" class="nav-link">Contacto</a> </li> </ul> <!-- CERRAR MENU EN MOBILE --> <div class="nav-cerrar" id="nav-cerrar"> <i class='bx bx-x'></i> </div> <!-- INTERACCIONES TIPO ECOMMERCE --> </div> <div class="nav-acciones"> <ul class="nav-tienda"> <li class="nav-toggle" id="nav-toggle"> <i class='bx bx-menu'></i> <a href="hamburger" class="nav-service"></a> </li> <li class="nav-iconos"> <a href="#carrito" class="nav-service"> <i class='bx bxs-shopping-bag-alt' ></i> </a> </li> <li class="nav-iconos"> <a href="/perfil.html" class="nav-service"> <i class='bx bxs-user'></i> </a> </li> </ul> </div> </nav> </header> <!-------- FIN HEADER --------> <main> <!-------- BANNER HOME ---------> <section class="banner grid" id="banner"> <div class="banner-container"> <div class="banner-contenido container"> <!-- ETIQUETA PREVIA --> <div class="banner-tag"> <i class='bx bx-star'></i> <a href="" class="text-tag">Sólo cereales de calidad</a> </div> <!-- TEXTOS H BANNER --> <h1 class="home-title"> Diviértete y Prueba tus Cereales Preferidos </h1> <p class="home-descripcion"> Lorem ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's... </p> <button class="btn-home button" type=""> Pedir ahora </button> <img src="imagenes/extras/star-blue.png" class="star-blue__home"> <img src="imagenes/extras/star-yellow.png" class="star-yellow__home"> </div> <div class="banner-imagen"> <!-- SECCIÓN DE CANTIDAD DE VISITAS --> <div class="banner-logros"> <hgroup class="banner-logros__grupo"> <h2 class="home-logros__numero">120K</h2> <p class="home-logros__descripcion">Visitantes</p> </hgroup> <hgroup class="banner-logros__grupo"> <h2 class="home-logros__numero">65K</h2> <p class="home-logros__descripcion">Compran online</p> </hgroup> <hgroup class="banner-logros__grupo"> <h2 class="home-logros__numero">45K</h2> <p class="home-logros__descripcion">5 estrellas</p> </hgroup> </div> <!-- IMAGEN DEL BANNER --> <img src="imagenes/header-banner.png" class="banner-picture"> </div> </div> </section> <!-------- FIN BANNER HOME ---------> <!-------- QUE NOS HACE ESPECIALES ---------> <section class="especial section" id="special"> <div class="especial-contenido container"> <!-- TEXTOS DEL BANNER --> <img src="imagenes/extras/star-yellow.png" class="star-yellow__special"> <div class="especial-texto"> <h1 class="bestcereal-title"> ¿Qué nos hace la Mejor Tienda de Cereal existente? </h1> <p class="bestcereal-description"> <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. </p> <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since. </p> </p> <button class="btn-bestcereal button" type=""> Conoce más </button> </div> <img src="imagenes/extras/star-yellow.png" class="star-yellow__special2"> <div class="especial-bullet"> <div class="bullet-group__first"> <div class="bullet-single"> <img src="imagenes/icons/bestcereal-1.png" class="bullet-icons"> <hgroup> <h3 class="bullet-titles"> Fácil de pedir </h3> <p class="bullet-texts"> Lorem Ipsum is simply dummy text of the printing </p> </hgroup> </div> <div class="bullet-single"> <img src="imagenes/icons/bestcereal-2.png" class="bullet-icons"> <hgroup> <h3 class="bullet-titles"> Envío fugaz </h3> <p class="bullet-texts"> Lorem Ipsum is simply dummy text of the printing </p> </hgroup> </div> <div class="bullet-single"> <img src="imagenes/icons/bestcereal-3.png" class="bullet-icons"> <hgroup> <h3 class="bullet-titles"> Mejor calidad </h3> <p class="bullet-texts"> Lorem Ipsum is simply dummy text of the printing </p> </hgroup> </div> </div> <div class="bullet-group__second"> <div class="bullet-single"> <img src="imagenes/icons/bestcereal-4.png" class="bullet-icons"> <hgroup> <h3 class="bullet-titles"> A la puerta de tu casa </h3> <p class="bullet-texts"> Lorem Ipsum is simply dummy text of the printing </p> </hgroup> </div> <div class="bullet-single"> <img src="imagenes/icons/bestcereal-5.png" class="bullet-icons"> <hgroup> <h3 class="bullet-titles"> Abiertos 24/7 </h3> <p class="bullet-texts"> Lorem Ipsum is simply dummy text of the printing </p> </hgroup> </div> <div class="bullet-single"> <img src="imagenes/icons/bestcereal-6.png" class="bullet-icons"> <hgroup> <h3 class="bullet-titles"> Grandes descuentos </h3> <p class="bullet-texts"> Lorem Ipsum is simply dummy text of the printing </p> </hgroup> </div> </div> </div> </div> </section> <!-------- FIN QUE NOS HACE ESPECIALES ---------> <!-------- PRODUCTOS ---------> <section class="productos section" id="products"> <div class="productos-contenido container"> <!-- TEXTOS --> <div class="productos--textos"> <h1 class="bestcereal-title"> En gustos de cereal no hay nada escrito... </h1> <p class="bestcereal-description"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's... </p> </div> <!-- CATEGORÍAS --> <div class="productos--categorias"> <ul class="categorias-filtros"> <li class="categorias-single active-product" data-filter=".frutales">Frutales</li> <li class="categorias-single" data-filter=".integrales">Integrales</li> <li class="categorias-single" data-filter=".chocolatados">Chocolatados</li> <li class="categorias-single" data-filter=".azucarados">Azucarados</li> <li class="categorias-single" data-filter=".variedades">Variedades</li> </ul> </div> <!-- MUESTRAS DE PRODUCTOS --> <div class="productos--cards grid"> <!-------- FRUTALES --------> <article class="cards-item frutales"> <div class="item-forma"> <img src="imagenes/productos-cereales/frutales-1.png" class="item--imagen"> <div class="item--tag"> <i class='bx bxs-star'></i> <span>4.9</span> </div> </div> <div class="item-data"> <div class="item-data__textos"> <h2 class="item--nombre">Froot Loops Kellogs</h2> </div> <div class="item-data__valor"> <h3 class="item--precio">$2.500</h3> <button class="btn-card button">Añadir al carrito</button> </div> </div> </article> <article class="cards-item frutales"> <div class="item-forma"> <img src="imagenes/productos-cereales/frutales-2.png" class="item--imagen"> <div class="item--tag"> <i class='bx bxs-star'></i> <span>4.9</span> </div> </div> <div class="item-data"> <div class="item-data__textos"> <h2 class="item--nombre">Fruity Pebbles Post</h2> </div> <div class="item-data__valor"> <h3 class="item--precio">$3.000</h3> <button class="btn-card button">Añadir al carrito</button> </div> </div> </article> <article class="cards-item frutales"> <div class="item-forma"> <img src="imagenes/productos-cereales/frutales-3.png" class="item--imagen"> <div class="item--tag"> <i class='bx bxs-star'></i> <span>4.9</span> </div> </div> <div class="item-data"> <div class="item-data__textos"> <h2 class="item--nombre">Trix Nestlé</h2> </div> <div class="item-data__valor"> <h3 class="item--precio">$1.890</h3> <button class="btn-card button">Añadir al carrito</button> </div> </div> </article> <!-------- INTEGRALES --------> <article class="cards-item integrales"> <div class="item-forma"> <img src="imagenes/productos-cereales/integrales-1.jpg" class="item--imagen"> <div class="item--tag"> <i class='bx bxs-star'></i> <span>4.9</span> </div> </div> <div class="item-data"> <div class="item-data__textos"> <h2 class="item--nombre">Quadritos Quaker</h2> </div> <div class="item-data__valor"> <h3 class="item--precio">$2.500</h3> <button class="btn-card button">Añadir al carrito</button> </div> </div> </article> <article class="cards-item integrales"> <div class="item-forma"> <img src="imagenes/productos-cereales/integrales-2.jpg" class="item--imagen"> <div class="item--tag"> <i class='bx bxs-star'></i> <span>4.9</span> </div> </div> <div class="item-data"> <div class="item-data__textos"> <h2 class="item--nombre">Fitness almendra</h2> </div> <div class="item-data__valor"> <h3 class="item--precio">$1.890</h3> <button class="btn-card button">Añadir al carrito</button> </div> </div> </article> <article class="cards-item integrales"> <div class="item-forma"> <img src="imagenes/productos-cereales/integrales-3.jpg" class="item--imagen"> <div class="item--tag"> <i class='bx bxs-star'></i> <span>4.9</span> </div> </div> <div class="item-data"> <div class="item-data__textos"> <h2 class="item--nombre">Kellogs frutos rojos</h2> </div> <div class="item-data__valor"> <h3 class="item--precio">$3.200</h3> <button class="btn-card button">Añadir al carrito</button> </div> </div> </article> <!-------- CHOCOLATADOS --------> <article class="cards-item chocolatados"> <div class="item-forma"> <img src="imagenes/productos-cereales/chocolatado-1.jpg" class="item--imagen"> <div class="item--tag"> <i class='bx bxs-star'></i> <span>4.9</span> </div> </div> <div class="item-data"> <div class="item-data__textos"> <h2 class="item--nombre">Cookie Crisp Nestlé</h2> </div> <div class="item-data__valor"> <h3 class="item--precio">$2.150</h3> <button class="btn-card button">Añadir al carrito</button> </div> </div> </article> <article class="cards-item chocolatados"> <div class="item-forma"> <img src="imagenes/productos-cereales/chocolatado-2.jpg" class="item--imagen"> <div class="item--tag"> <i class='bx bxs-star'></i> <span>4.9</span> </div> </div> <div class="item-data"> <div class="item-data__textos"> <h2 class="item--nombre">Mono Roll Costa</h2> </div> <div class="item-data__valor"> <h3 class="item--precio">$1.990</h3> <button class="btn-card button">Añadir al carrito</button> </div> </div> </article> <article class="cards-item chocolatados"> <div class="item-forma"> <img src="imagenes/productos-cereales/chocolatado-3.jpg" class="item--imagen"> <div class="item--tag"> <i class='bx bxs-star'></i> <span>4.9</span> </div> </div> <div class="item-data"> <div class="item-data__textos"> <h2 class="item--nombre">Cola Cao Pillows</h2> </div> <div class="item-data__valor"> <h3 class="item--precio">$2.560</h3> <button class="btn-card button">Añadir al carrito</button> </div> </div> </article> <!-------- AZUCARADOS --------> <article class="cards-item azucarados"> <div class="item-forma"> <img src="imagenes/productos-cereales/azucarados-1.jpg" class="item--imagen"> <div class="item--tag"> <i class='bx bxs-star'></i> <span>4.9</span> </div> </div> <div class="item-data"> <div class="item-data__textos"> <h2 class="item--nombre">Zucaritas Kellogs</h2> </div> <div class="item-data__valor"> <h3 class="item--precio">$2.150</h3> <button class="btn-card button">Añadir al carrito</button> </div> </div> </article> <article class="cards-item azucarados"> <div class="item-forma"> <img src="imagenes/productos-cereales/azucarados-2.jpg" class="item--imagen"> <div class="item--tag"> <i class='bx bxs-star'></i> <span>4.9</span> </div> </div> <div class="item-data"> <div class="item-data__textos"> <h2 class="item--nombre">Zucosos Nestlé</h2> </div> <div class="item-data__valor"> <h3 class="item--precio">$2.000</h3> <button class="btn-card button">Añadir al carrito</button> </div> </div> </article> <article class="cards-item azucarados"> <div class="item-forma"> <img src="imagenes/productos-cereales/azucarados-3.jpg" class="item--imagen"> <div class="item--tag"> <i class='bx bxs-star'></i> <span>4.9</span> </div> </div> <div class="item-data"> <div class="item-data__textos"> <h2 class="item--nombre">Cheerios Nestlé</h2> </div> <div class="item-data__valor"> <h3 class="item--precio">$1.890</h3> <button class="btn-card button">Añadir al carrito</button> </div> </div> </article> <!-------- VER MÁS --------> <article class="cards-item variedades"> <div class="item-forma"> <img src="imagenes/productos-cereales/mas-1.jpg" class="item--imagen"> <div class="item--tag"> <i class='bx bxs-star'></i> <span>4.9</span> </div> </div> <div class="item-data"> <div class="item-data__textos"> <h2 class="item--nombre">Chocapic Nestlé</h2> </div> <div class="item-data__valor"> <h3 class="item--precio">$1.990</h3> <button class="btn-card button">Añadir al carrito</button> </div> </div> </article> <article class="cards-item variedades"> <div class="item-forma"> <img src="imagenes/productos-cereales/mas-2.jpg" class="item--imagen"> <div class="item--tag"> <i class='bx bxs-star'></i> <span>4.9</span> </div> </div> <div class="item-data"> <div class="item-data__textos"> <h2 class="item--nombre">Choco Krispis Kellogs</h2> </div> <div class="item-data__valor"> <h3 class="item--precio">$3.100</h3> <button class="btn-card button">Añadir al carrito</button> </div> </div> </article> <article class="cards-item variedades"> <div class="item-forma"> <img src="imagenes/productos-cereales/mas-3.jpg" class="item--imagen"> <div class="item--tag"> <i class='bx bxs-star'></i> <span>4.9</span> </div> </div> <div class="item-data"> <div class="item-data__textos"> <h2 class="item--nombre">Estrellitas Nestlé</h2> </div> <div class="item-data__valor"> <h3 class="item--precio">$1.790</h3> <button class="btn-card button">Añadir al carrito</button> </div> </div> </article> </div> <!-- BOTÓN DE VER MÁS PRODUCTOS --> <div class="productos--mas"> <button class="btn-productos button"> Ver Más Productos </button> </div> </div> </section> <!-------- FIN PRODUCTOS ---------> </main> <!-------- FOOTER ---------> <footer class="footer"> <div class="footer-contenedor container"> <div class="footer-contenido--logored"> <img src="imagenes/logo-black.png" class="footer--logo"> <div class="footer-redes"> <ul class="footer--plataformas"> <a href="" class="footer--redes-link"> <i class='bx bxl-facebook'></i> </a> <a href="" class="footer--redes-link"> <i class='bx bxl-twitter'></i> </a> <a href="" class="footer--redes-link"> <i class='bx bxl-linkedin'></i> </a> <a href="" class="footer--redes-link"> <i class='bx bxl-dribbble'></i> </a> </ul> </div> </div> <div class="footer-contenido grid"> <div class="footer--info"> <h3 class="footer--info-subtitulo">Servicios</h3> <ul class="footer--info-categorias"> <li class="footer--info-items">Fácil de Pedir</li> <li class="footer--info-items">Envío Fugaz</li> <li class="footer--info-items">Mejor Calidad</li> <li class="footer--info-items">A la puerta de tu casa</li> <li class="footer--info-items">Abiertos 24/7</li> <li class="footer--info-items">Grandes Descuentos</li> </ul> </div> <div class="footer--info"> <h3 class="footer--info-subtitulo">Nosotros</h3> <ul class="footer--info-categorias"> <li class="footer--info-items">Home</li> <li class="footer--info-items">Conócenos</li> <li class="footer--info-items">Empresas</li> <li class="footer--info-items">Tienda</li> <li class="footer--info-items">Contacto</li> </ul> </div> <div class="footer--info"> <h3 class="footer--info-subtitulo">Háblanos</h3> <div class="footer--iconos"> <div class="footer--info-iconos"> <i class='bx bxs-envelope'></i> <p class="footer--info-items">[email protected]</p> </div> <div class="footer--info-iconos"> <i class='bx bxs-phone-call'></i> <p class="footer--info-items">+569 0000 0000</p> </div> <div class="footer--info-iconos"> <i class='bx bxs-been-here'></i> <p class="footer--info-items">Calle Wallaby 42 Sydney</p> </div> </div> </div> </div> </div> </footer> <script src="js/mixitup.min.js"></script> <!-------- JAVASCRIPT --------> <script src="js/script.js"></script> </body> </html>
import styled from "styled-components"; import { COLOR } from "../../../styles/color"; import { Box, CircularProgress, SvgIcon, Typography } from "@mui/material"; import CheckRoundedIcon from "@mui/icons-material/CheckRounded"; import WarningAmberOutlinedIcon from "@mui/icons-material/WarningAmberOutlined"; import propTypes from "prop-types"; const ReviewItem = (props) => { const data = props.data; const ItemIcon = { default: ( <> <IconWrapper /> <ItemProgress progresscolor={COLOR.MAIN_SKYBLUE} /> </> ), true: ( <> <IconWrapper component={CheckRoundedIcon} iconcolor={COLOR.MAIN_NAVY} /> <ItemProgress variant="determinate" value={100} progresscolor={COLOR.MAIN_SKYBLUE} /> </> ), false: ( <> <IconWrapper component={data.icon} iconcolor={COLOR.MAIN_NAVY} /> <ItemProgress variant="determinate" value={100} progresscolor={COLOR.MAIN_ROSE} /> </> ), null: ( <> <IconWrapper component={WarningAmberOutlinedIcon} iconcolor={COLOR.MAIN_ORANGE} /> <ItemProgress variant="determinate" value={100} progresscolor={COLOR.MAIN_ORANGE} /> </> ), }; return ( <StItemBox> <ItemIconBox> {props.isLoading ? ItemIcon["default"] : ItemIcon[props.reviewData[data.item]]} </ItemIconBox> <TextContainer> <ItemTitle variant="h4">{data.title}</ItemTitle> <DecsText variant="subtitle1">{data.desc}</DecsText> </TextContainer> </StItemBox> ); }; ReviewItem.propTypes = { data: propTypes.object, isLoading: propTypes.bool, reviewData: propTypes.object, }; export const ReviewList = (props) => { return ( <StReviewList> {props.data.map((it) => { return ( <ReviewItem key={it.item} data={it} isLoading={props.isLoading} reviewData={props.reviewData} /> ); })} </StReviewList> ); }; ReviewList.propTypes = { data: propTypes.array, isLoading: propTypes.bool, reviewData: propTypes.object, }; const StReviewList = styled.div` display: flex; justify-content: space-between; flex-direction: row; `; //default const StItemBox = styled.div` display: flex; justify-content: space-evenly; flex-direction: column; width: 23rem; height: 22rem; padding: 1.5rem; /* gap: 1rem; */ /* border: 0.1rem solid lightgrey; */ border-radius: 2rem; background-color: ${COLOR.MAIN_WHITE}; box-shadow: 0rem 0.1rem 2rem lightgrey; `; const ItemIconBox = styled(Box)` display: flex; align-items: center; justify-content: center; position: relative; top: 0; width: 5rem; height: 5rem; margin: 0.1rem; `; const IconWrapper = styled(SvgIcon)` position: absolute; color: ${(props) => props.iconcolor}; font-size: 2.7rem; `; const TextContainer = styled.div` display: flex; flex-direction: column; gap: 0.5rem; `; const ItemTitle = styled(Typography)` font-weight: bolder; text-align: left; `; const DecsText = styled(Typography)` color: ${COLOR.FONT_GRAY}; font-size: 1.2rem; text-align: justify; `; const ItemProgress = styled(CircularProgress)` display: flex; justify-content: center; align-items: center; color: ${(props) => props.progresscolor}; .MuiCircularProgress-svg { width: 5rem; height: 5rem; } `;
<template> <div> <CartNum :cart-num="cartNum" /> <Alert /> <div class="container pt-5 pb-5 mb-5 mt-72"> <router-link class="back" to="/CustomerProduct/0" > <i class="fas fa-reply" /> BACK </router-link> <div class="product-wrap row"> <div class="col-lg-5 col-10 img-wrap mr-5 mb-5"> <div class="img-thumbnail img" :style="{'backgroundImage': `url(${productData.imageUrl})`}" /> <div class="mask" /> </div> <div class="col-lg-6 col-12 data mt-5"> <h2 class="mb-3 title text-color"> {{ productData.title }} </h2> <span class="badge badge-warning mb-3"> {{ productData.category }} </span> <p class="mb-3 description"> {{ productData.description }} </p> <h5 class="text-content"> 【產品說明】 </h5> <p>{{ productData.content }}</p> <p class="mt-5 price"> <span class="h2 text-danger mr-3">NT$ {{ productData.price }}</span> <del class="h6 text-muted">NT$ {{ productData.origin_price }}</del> </p> <p class="pt-3"> <button type="button" class="btn btn-info mr-2" @click="selectQty('del')" > - </button> <input type="text" class="qty" v-model="qty" disabled > <button type="button" class="btn btn-info ml-2" @click="selectQty('add')" > + </button> <span class="ml-2">{{ productData.unit }}</span> <button @click="addtoCart(productData.id, qty)" type="button" class="btn btn-info float-right" > 加入購物車 </button> <span class="total text-color float-right mt-2 mr-3">小計 NT$ {{ nowPrice }}</span> </p> </div> </div> </div> </div> </template> <script> import { mapGetters, mapActions } from 'vuex'; import CartNum from '../../components/frontend/CartNum.vue'; import Alert from '../../components/AlertMessage.vue'; export default { components: { CartNum, Alert, }, data() { return { action: '', qty: 1, productId: '', }; }, computed: { nowPrice() { const vm = this; return vm.productData.price * vm.qty; }, ...mapGetters('productsModules', ['productData']), ...mapGetters('cartModules', ['cart', 'cartNum', 'cartSuccess']), }, watch: { cartSuccess: { handler: 'showMessage', immediate: true, }, }, created() { this.productId = this.$route.params.id; this.getCart(); this.getProductData(); }, methods: { ...mapActions('productsModules', ['getAllProducts']), ...mapActions('cartModules', ['getCart', 'resetSuccess']), addtoCart(id, qty = 1) { this.$store.dispatch('cartModules/addtoCart', { id, qty }); }, selectQty(action) { if (action === 'add') { this.qty += 1; } else { if (this.qty <= 0) return; this.qty -= 1; } }, getProductData() { const id = this.productId; this.$store.dispatch('productsModules/getProductData', id); }, showMessage(val) { if (val === 'success') { this.$bus.$emit('message:push', '成功加入購物車', 'success'); this.resetSuccess(); } else if (val === 'failure') { this.$bus.$emit('message:push', '加入購物車失敗', 'danger'); this.resetSuccess(); } }, }, }; </script> <style scope> .product-wrap{ margin-top: 3rem; min-height: 60vh; } .img-wrap{ position: relative; height: 350px; } .img{ position: absolute; width: 100%; height: 100%; background-size: contain; background-position: center; background-repeat: no-repeat; z-index: 2; } .mask{ position: absolute; bottom: -50px; right: -45px; width: 140%; height: 100%; clip-path: polygon(100% 0, 0% 100%, 100% 100%); background-color: rgb(40, 126, 140); z-index: 1; } .back{ position: absolute; top: 100px; left: 30px; padding: 5px 5px; width: 100px; height: 55px; color: #fff; clip-path: polygon(100% 0, 0 0, 0 100%); background-color: rgb(40, 126, 140); z-index: 4; } .back:hover{ color: #fff; text-shadow: 1px 1px 1px black; text-decoration: none; background-color: rgba(40, 126, 140, 0.7); } .data{ min-height: 400px; } .title{ position: relative; } .title::before{ content: ''; position: absolute; bottom: -8px; width: 73px; height: 2px; border-bottom: 3px solid rgb(119, 117, 117); } .description{ color: rgb(85, 84, 84); position: relative; } .description::before{ content: ''; position: absolute; bottom: -8px; width: 100%; height: 2px; border-bottom: 1px dashed rgb(119, 117, 117); } .text-content{ color: rgb(35, 124, 146); } .price{ position: relative; } .price::after{ content: ''; position: absolute; bottom: -10px; left:0; width: 100%; height: 2px; border-bottom: 1px dashed rgb(119, 117, 117); } .qty{ width: 60px; padding: 5px 5px; outline: none; border-radius: 5px; text-align: center; } .total{ font-size: 20px; } @media screen and (max-width: 768px) { .mask { width: 120%; right: -100px; } } @media screen and (max-width: 480px) { .img-wrap{ height: 230px; } .back{ left: 10px; } .mask { width: 110%; right: -40px; } } @media screen and (max-width: 320px) { .img-wrap{ height: 200px; } } </style>
package com.example.phonebook.ui.main; import android.content.Context; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; import com.example.phonebook.LiaisonMan; import com.example.phonebook.R; public class SectionsLiaisonAdapter extends FragmentPagerAdapter { @StringRes private static final int[] TAB_TITLES = new int[]{R.string.liaison_tab1,R.string.liaison_tab2}; private final Context mContext; private LiaisonMan liaisonMan; public LiaisonDetailFragment liaisonDetailFragment; public SectionsLiaisonAdapter(Context context, FragmentManager fm, LiaisonMan liaisonMan) { super(fm); mContext = context; this.liaisonMan = liaisonMan; } @Override public Fragment getItem(int position) { switch (position) { case 0: liaisonDetailFragment = new LiaisonDetailFragment(liaisonMan); return liaisonDetailFragment; case 1: return new LiaisonPhoneRecordFragment(mContext, liaisonMan); } return null; } @Nullable @Override public CharSequence getPageTitle(int position) { return mContext.getResources().getString(TAB_TITLES[position]); } @Override public int getCount() { return 2; } }
import 'package:dio/dio.dart'; import 'package:teslo_shop/config/config.dart'; import 'package:teslo_shop/features/products/domain/domain.dart'; import 'package:teslo_shop/features/products/infraestructure/errors/product_errors.dart'; import 'package:teslo_shop/features/products/infraestructure/mappers/product_mapper.dart'; class ProductsDatasourceImpl extends ProductsDatasource { late final Dio dio; final String accessToken; ProductsDatasourceImpl({ required this.accessToken }) : dio = Dio( BaseOptions( baseUrl: Environment.apiUrl, headers: { 'Authorization': 'Bearer $accessToken' } )); Future<String> _uploadFile(String path) async{ // Subida de una imagen try { final fileName = path.split('/').last; // Nombre de la imagen desde el path. final FormData data = FormData.fromMap({ // Data a subir al server que contiene el file. 'file': MultipartFile.fromFileSync(path, filename: fileName) }); final response = await dio.post('/files/product', data:data); // Subimos al backend la imagen. return response.data['image']; // Respuesta del backend con la imagen renombrada. } catch (e) { throw Exception(); } } Future<List<String>> _uploadPhotos( List<String> photos ) async { // Subida de las imagenes de la cámara o galería. final photosToUpload = photos.where((element) => element.contains('/')).toList(); // Imagenes de la cámara o galería. final photosToIgnore = photos.where((element) => !element.contains('/')).toList();// Imagenes que ya estaban. final List<Future<String>> uploadJob = photosToUpload.map( // Multiples subidas de fotos en forma de Future (e) => _uploadFile(e) ).toList(); final newImages = await Future.wait(uploadJob); // Cuando terminan las subidas se ejecutan en una sola (wait()) return[...photosToIgnore, ...newImages]; // Se devuelven las fotos que ya existían más las nuevas renombradas. } @override Future<Product> createUpdateProduct(Map<String, dynamic> productLike) async { try { final String? productId = productLike['id']; // El id que nos ocupa es el del pto del formulario final String method = (productId == null) ? 'POST':'PATCH'; // Sino viene es para crear, y si viene es para actualizar final String url = (productId == null) ? '/products' :'/products/$productId'; // para crear la ruta no lleva id // para actualizar la ruta lleva el id del pto productLike.remove('id'); // El backend no quiere que el id este presente productLike['images'] = await _uploadPhotos(productLike['images']); // Subimos al backend las fotos de la cámara o galería final response = await dio.request( url, data: productLike, options: Options( method: method ) ); final product = ProductMapper.jsonToEntity(response.data); return product; } catch (e) { throw Exception(); } } @override Future<Product> getProductById(String id) async{ try { final response = await dio.get('/products/$id'); final product = ProductMapper.jsonToEntity(response.data); return product; } on DioException catch(e){ if( e.response!.statusCode == 404 ) throw ProductNotFound(); throw Exception(); } catch (e) { throw Exception(); } } @override Future<List<Product>> getProductsByPage({int limit = 10, int offset = 0}) async { final response = await dio.get<List>('/products?limit=$limit&offset=$offset'); final List<Product> products = []; for (var product in response.data ?? []){ products.add( ProductMapper.jsonToEntity(product)); } return products; } @override Future<List<Product>> searchProductByTerm(String term) { // TODO: implement searchProductByTerm throw UnimplementedError(); } }
import { CommonObj, CommonSize } from "@/vite-env"; import btnsMap from "."; // export type BtnAllNames = keyof typeof btnsMap; export type BtnAllNames = keyof InstanceType<typeof btnsMap>; export interface BtnsAllMap { // [key in keyof btnsMap]: BtnItem; [key: string]: BtnItem; } export interface BtnCfg { name: string; text?: string; type?: string; icon?: string; size?: string; plain?: boolean; popconfirm?: string; } export type BtnName = BtnAllNames | string; //常用基础按钮或其他自定义按钮 export type ButtonType = "primary" | "success" | "warning" | "danger" | "info"; //按钮类型。注"text" 已弃用 export interface BtnAttrs { icon?: any; text?: string; type?: ButtonType; size?: CommonSize; plain?: boolean; disabled?: boolean; link?: boolean; } export interface PopconfirmAttrs { title?: string; icon?: any; iconColor?: any; description?: string; cancel?: () => void; okText?: string; cancelText?: string; confirmButtonType?: ButtonType; disabled?: boolean; [key: string]: any; } export interface BtnItem { name?: BtnName; //可以不传值 text?: string; //按钮文本 order?: number; //按钮顺序 auth?: number[]; //权限 to?: string | CommonObj | ((row: CommonObj) => string | CommonObj); //点击按钮时要跳转的页面地址 customRules?: boolean; //是否自定义该按钮的逻辑规则(目前只有导出按钮用到了此属性) attrs?: BtnAttrs; //按钮属性 validate?: boolean; //是否需要进行表单校验(仅当出现在表单项的底部更多按钮中时才生效) popconfirm?: boolean | PopconfirmAttrs; } export type BtnFn = (row: CommonObj) => BtnName | BtnItem; export type BaseBtnType = BtnName | BtnItem | BtnFn;
import React, { useEffect, useRef, useState } from "react"; import TodoNode from "../../../classes/nodes/members/TodoNode"; import useClassName from "../../../hooks/useClassName"; import useStateListener from "../../../hooks/useStateListener"; import Selection from "../../../managers/Selection"; import Triggers from "../../../managers/Triggers"; import FabButton from "../../ui/buttons/FabButton"; import ContentEditable from "../../ui/ContentEditable"; import NodeComponent, { INodeComponent, INodePreviewComponent, NodePreviewComponent } from "../NodeComponent"; import Checkbox from "../../ui/inputs/Checkbox"; interface ITodoNodeComponent extends INodeComponent<TodoNode> { } const TodoNodeComponent: React.FC<ITodoNodeComponent> = props=> { const node = props.node; const [done] = useStateListener(node.done.State); const [content, setContent] = useState<string>(node.content); const [isEditing, setIsEditing] = useState<boolean>(false); const textRef = useRef<HTMLDivElement>(); const className = useClassName([ "todo-node", done && "done", content.length == 0 && "empty" ]) useEffect(()=> { const unlistenEdit = Triggers.editNode.listen(({ targetsId })=> { if (targetsId.includes(node.id)) { setIsEditing(true); } }) return ()=> { unlistenEdit(); } }, []); useEffect(()=> { node.isEditing = isEditing; }, [isEditing]); function toggleDone() { node.done.toggleDone(); } function onContentDoubleClick() { if (!Selection.isMultipleSelectionKey) setIsEditing(true); } function onTextInput(value: string) { setContent(value); } function onTextBlur(e: React.FocusEvent<HTMLDivElement>) { const value = (e.target as HTMLDivElement).innerHTML; node.setTextContent(value); } return ( <NodeComponent { ...props } className={ className } > <div className="todo-checkbox-wrapper"> <Checkbox className="todo-checkbox" value={ done } onClick={ toggleDone } /> </div> <main className="todo-content" onDoubleClick={ onContentDoubleClick } > <ContentEditable myRef={ el=> textRef.current = el } className="todo-content-text" initialContent={ node.content } isActive={ isEditing } setIsActive={ setIsEditing } content={ content } setContent={ setContent } placeholder="Todo something" preventFromScroll textContent textFormat={ c=> c.trim().replace(/\s{2,}/gm, " ") } onInput={ onTextInput } onBlur={ onTextBlur } /> </main> </NodeComponent> ); }; export const TodoNodePreviewComponent: React.FC<INodePreviewComponent & { done?: boolean }> = props=> { return ( <NodePreviewComponent { ...props } className="todo-node"> <div className="todo-checkbox-wrapper"> <Checkbox className="todo-checkbox" value={ props.done || false } /> </div> <main className="todo-content"> <div className="todo-content-text content-editable" { ...{ "data-placeholder": "Todo something" } } /> </main> </NodePreviewComponent> ); }; export default TodoNodeComponent;
# %% from PIL import Image import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [15, 10] plt.rcParams["figure.autolayout"] = True # %% imgPath = './Lenna.png' img = Image.open(imgPath) colorCounts = set() colors = [] # %% for x in range(img.size[0]): for y in range(img.size[1]): colorCounts.add(img.getpixel((x, y))) colors.append(img.getpixel((x, y))) # print("Total colors:", len(colorCounts)) # Create plot grid figure, axis = plt.subplots(2, 2) axis[0, 0].hist([color[0] for color in colors], range=(0, 255), bins=256, color='red') axis[0, 0].set_title("Red Channel") axis[0, 1].hist([color[1] for color in colors], range=(0, 255), bins=256, color='green') axis[0, 1].set_title("Green Channel") axis[1, 0].hist([color[2] for color in colors],range=(0, 255), bins=256, color='blue') axis[1, 0].set_title("Blue Channel") axis[1, 1].hist([round((color[0]+color[1]+color[2])/3) for color in colors], range=(0, 255), bins=256, color='black', alpha=0.5) axis[1, 1].set_title("Luminance level") plt.savefig(f'{imgPath[2:-4]}_histogram.png') # %%
import {Component, Input, OnInit} from '@angular/core'; import {Hero} from '../interfaces/hero'; import {HeroService} from "../hero.service"; import {delay, Observable} from "rxjs"; @Component({ selector: 'app-heroes', templateUrl: './heroes.component.html', styleUrls: ['./heroes.component.scss'] }) export class HeroesComponent implements OnInit { public heroes: Hero[] = []; @Input() offset: number = 0; @Input() limit: number = 20; @Input() total: number = 0; constructor( //Indica a Angular que se requiere el uso de la instancia HeroService //Y en el mismo paso, crea una propiedad privada de nombre HeroService para //contener dicha instancia private heroService: HeroService, ) { } ngOnInit(): void { //obtenemos los //this.heroes = this.heroService.getHeroes(); this.getHeroes(); } //Por defecto una propiedad es pública //strig no sería necesario si inicializamos la variable directamente public getHeroes(): void { this.heroService.getAllHeroes(this.limit, this.offset).subscribe(heroes => { this.heroes = heroes; this.total = this.heroService.getTotal(); }); } public previousPage(): void { this.offset -= this.limit; this.getHeroes(); } public nextPage(): void { this.offset += this.limit; this.getHeroes(); } }
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'; import { getProducts } from '../../api/products'; export default createSlice({ name: 'newProductList', // đổi initialState từ array // => // 1 object có 2 field // { status : 'trang thai của request api/todos' , todo : []} initialState: { status: 'idle', productList: [] }, reducers: {}, extraReducers: (builder) => { // Trường hợp pending builder .addCase(fetchProductList.pending, (state, action) => { //update lại status state.status = 'loading'; }) .addCase(fetchProductList.fulfilled, (state, action) => { // trường hợp fullfilled - đã request xong , đang rảnh dỗi state.productList = action.payload; state.status = 'idle'; }); }, }); // action (JS object) và action creator () => { return action } // thunk action (function) và thunk action creator () => { return thunk action } // thunk action creator trả về 1 thunk action // Mỗi createAsyncThunk tạo ra 3 action tương ứng giống 3 trạng thái của promise : // - todos/fetchTodos/pending : action khi ta vừa gửi request // - todos/fetchTodos/fullfilled // - todos/fetchTodos/rejected export const fetchProductList = createAsyncThunk('productList/fetchProductList', async () => { try { //gọi tới API 'api//products const res = await getProducts(); if (res.status === 200 && res.data) { return res.data; //trả về response } } catch (err) { console.log(err); } }); // export const fetchProductList = createAsyncThunk()
import { useState } from "react"; import "../style/UserCard.css"; import { useAtom } from "jotai"; import { Link } from "react-router-dom"; import { Avatar } from "@mui/material"; import { UserInfoType } from "../lib/type/UserInfoType"; import FollowSwitch from "./FollowSwitch"; import { userInfoAtom } from "../lib/jotai/atoms/user"; type Props = { user: UserInfoType; }; const UserCard = ({ user }: Props) => { const [userInfoJotai] = useAtom(userInfoAtom); const [followFlag, setFollowFlag] = useState( userInfoJotai.userInfo?.followings?.includes(user.id!) || false ); return ( <> <Link to={`/profile/${user.id}`} style={{ textDecoration: "none" }}> <div className="userCard"> <div className="userCard__content"> <div className="userCard__avatar"> <Avatar src={user.userImg || "/assets/default_profile_400x400.png"} /> </div> <div className="userCard__body"> <div className="userCard__header"> <div className="userCard__headerText"> <h3> <span className="userCard__headerSpecial">{user.name}</span> </h3> </div> {userInfoJotai.userInfo?.id !== user.id && ( <FollowSwitch followFlag={followFlag} setFollowFlag={setFollowFlag} followUserId={user.id!} /> )} </div> <div className="userCard__headerDescription"> <p>{user.introduction}</p> </div> </div> </div> </div> </Link> </> ); }; export default UserCard;
import React from 'react'; import {addPostAC, PostType, updateNewPostTextAC} from '../../../redux/profileReducer'; import {MyPosts} from './MyPosts'; import {AppRootSTateType} from '../../../redux/reduxStore'; import {connect} from 'react-redux'; import {Dispatch} from 'redux'; type MapStateToPropsType = { posts: PostType[], newPostText: string } type MapDispatchToPropsType={ updateNewPostText: (text: string)=>void, addPost:()=>void } export type MyPostsContainerPropsType =MapStateToPropsType & MapDispatchToPropsType // функция которая всего принимает СТЕЙТ всего приложения. // Запускается каждый раз когда меняется Стейт и формирует новый объект, // который сравнивается с старым объектом( сравниваются внутренности объектов) // поэт чтобы был ререндер компоненты надо чтобы редьюсор возвращал копию const mapStateToProps = (state: AppRootSTateType): MapStateToPropsType => { return { posts: state.profilePage.posts, newPostText: state.profilePage.newPostText } } const mapDispatchToProps = (dispatch: Dispatch):MapDispatchToPropsType => { return { updateNewPostText: (text: string) => { dispatch(updateNewPostTextAC(text)) }, addPost: () => { dispatch(addPostAC()) } } } // используем connect export const MyPostsContainer = connect(mapStateToProps, mapDispatchToProps)(MyPosts)
export interface IUsuario{ email: string; chave: string; requisicoes: { atual: number; limite: number; } } export interface IContext{ usuarioLogado: IUsuario; setUsuarioLogado: (usuarioLogado:IUsuario) => void; listaDePaises: IPaises[]; setListaDePaises: (listaDePaises:IPaises[]) => void; listaDeTemporadas: number[]; setListaDeTemporadas: (listaDeTemporadas:number[]) => void; listaDeLigas: ILigas[]; setListaDeLigas: (listaDeLigas:ILigas[]) => void; listaDeTimes: ITimes[]; setListaDeTimes: (listaDeTimes:ITimes[]) => void paisSelecionado: IPaises; setPaisSelecionado: (paisSelecionado:IPaises) => void; temporadaSelecionada: number; setTemporadaSelecionada: (temporadaSelecionada:number) => void; ligaSelecionada: ILigas; setLigaSelecionada: (ligaSelecionada:ILigas) => void; timeSelecionado: ITimes; setTimeSelecionado: (timeSelecionado:ITimes) => void; estatisticasDoTime: IEstatisticas; setEstatisticasDoTime: (estatisticasDoTime: IEstatisticas) => void; } export interface IPaises { name: string, code: string, flag: string } export interface ILigas { id: number, name: string, type: string, logo: string, country: IPaises, seasons: number[] } export interface ITimes { id: number, name: string, code: string, country: string, logo: string } export interface IJogadores { id: number, name: string, age: number, nationality: string, photo: string, position: string, number: number | null, } export interface IEstatisticas { jogos: number, vitorias: number, empates: number, derrotas: number, gols: number, golsPorMinuto: { "0-15": number | null, "16-30": number | null, "31-45": number | null, "46-60": number | null, "61-75": number | null, "76-90": number | null, "91-105": number | null, "106-120": number | null }, formacao: string, jogadores: IJogadores[] }
import React, { useEffect, useState } from 'react'; import axios from 'axios'; import { useLocation } from 'react-router-dom'; import './Css/ProductReviews.css'; const ProductReviews = () => { const [reviews, setReviews] = useState([]); const { search } = useLocation(); const queryParams = new URLSearchParams(search); const productId = queryParams.get('productId'); useEffect(() => { const fetchData = async () => { try { const response = await axios.get(`http://localhost:3001/getReviewsByProductId?productId=${productId}`); setReviews(response.data); } catch (error) { console.error('Error fetching reviews:', error); } }; fetchData(); }, [productId]); return ( <div> <h2>Product Reviews</h2> {reviews.length === 0 ? ( <h3>There are no reviews for this product.</h3> ) : ( reviews.map((review, index) => ( <div key={index}> <table className="gridtable"> <tr> <td>Product Name:</td> <td>{review.productName}</td> </tr> <tr> <td>User Name:</td> <td>{review.username}</td> </tr> <tr> <td>Product Type:</td> <td>{review.productType}</td> </tr> <tr> <td>Product Price:</td> <td>{review.productPrice}</td> </tr> <tr> <td>Product Maker:</td> <td>{review.productMaker}</td> </tr> <tr> <td>Manufacturer Rebates:</td> <td>{review.manufacturerRebates}</td> </tr> <tr> <td>Product On Sale:</td> <td>{review.productOnSale}</td> </tr> <tr> <td>Review Rating:</td> <td>{review.reviewRating}</td> </tr> <tr> <td>Store ID:</td> <td>{review.storeID}</td> </tr> <tr> <td>Zip Code:</td> <td>{review.zipCode}</td> </tr> <tr> <td>Retailer City:</td> <td>{review.retailerCity}</td> </tr> <tr> <td>Retailer State:</td> <td>{review.retailerState}</td> </tr> <tr> <td>User Age:</td> <td>{review.userAge}</td> </tr> <tr> <td>User Gender:</td> <td>{review.userGender}</td> </tr> <tr> <td>User Occupation:</td> <td>{review.userOccupation}</td> </tr> <tr> <td>Review Date:</td> <td>{review.reviewDate}</td> </tr> <tr> <td>Review Text:</td> <td>{review.reviewText}</td> </tr> </table> </div> )) )} </div> ); }; export default ProductReviews;
import {createSlice, PayloadAction} from "@reduxjs/toolkit" import {securityAPI, securityType } from "../api/auth-api" import { AppDispatch } from "./store" import {authAPI} from "../api/auth-api" import {IAuthMeAPI, ILogin, ResultCode} from "../api/api" import { ILoginMe } from "../interface" export interface initialStateInterface { data: { id: number | null email: string | null login: string | null } isAuth: boolean messages: Array<string> captcha?: string } const initialState: initialStateInterface = { data: { id: null, email: null, login: null, }, isAuth: false, messages: [], captcha: "", } const authMeSlice = createSlice({ name: "authMeReducer", initialState, reducers: { getAuthMe(state, action: PayloadAction<ILogin<IAuthMeAPI>>) { state.data = action.payload.data state.isAuth = true }, getAuthMeError(state, action: PayloadAction<Array<string>>) { state.isAuth = false state.messages = action.payload }, setSecurity(state, action: PayloadAction<securityType>) { state.captcha = action.payload.url }, getOutLogin(state) { state.data = {id: null, email: null, login: null,} state.isAuth = false }, } }) const {getAuthMe, setSecurity, getOutLogin, getAuthMeError} = authMeSlice.actions export const getAuthMeServer = () => async (dispatch: AppDispatch) => { try { const res = await authAPI.getMe() if (res.resultCode === ResultCode.Success) { dispatch(getAuthMe(res)) } else if (res.resultCode === ResultCode.Error) { dispatch(getAuthMeError(res.messages)) } } catch (error) { alert("Шибка при аутентификации") console.error(error) } } export const setAuthMeLogin = (obj: ILoginMe) => async (dispatch: AppDispatch) => { try { const res = await authAPI.loginMe(obj) if (res.resultCode === ResultCode.Success) { dispatch(getAuthMeServer()) } else if (res.resultCode === ResultCode.captcha) { const res = await securityAPI.security() dispatch(setSecurity(res)) } else if (res.resultCode === ResultCode.Error) { dispatch(getAuthMeError([res.messages.length > 0 ? res.messages[0] : "Не правильный Email или пароль"])) } } catch (error) { alert("Шибка при авторизации") console.error(error) } } export const setIsOutLogin = () => async (dispatch: AppDispatch) => { try { await authAPI.logOut() dispatch(getOutLogin()) } catch (error) { alert("Шибка при выходе из приложения") console.error(error) } } export default authMeSlice.reducer
/* Created by Yvan / https://Brainy-Bits.com This code is in the public domain... You can: copy it, use it, modify it, share it or just plain ignore it! Thx! */ // NRF24L01 Module Tutorial - Code for Receiver using Arduino UNO //Include needed Libraries at beginning #include "nRF24L01.h" // NRF24L01 library created by TMRh20 https://github.com/TMRh20/RF24 #include "RF24.h" #include "SPI.h" #define LED_PIN1 5 // Digital In (DI) of RGB Stick connected to pin 5 of the UNO #define LED_PIN2 4 #define LED_PIN3 3 int ReceivedMessage[1] = { 000 }; // Used to store value received by the NRF24L01 RF24 radio(7, 8); // NRF24L01 used SPI pins + Pin 7 and 8 on the UNO const uint64_t pipe = 0xE6E6E6E6E6E6; // Needs to be the same for communicating between 2 NRF24L01 void setup(void) { Serial.begin(9600); radio.begin(); // Start the NRF24L01 radio.openReadingPipe(1, pipe); // Get NRF24L01 ready to receive radio.startListening(); // Listen to see if information received pinMode(LED_PIN1, OUTPUT); // Set RGB Stick UNO pin to an OUTPUT pinMode(LED_PIN2, OUTPUT); pinMode(LED_PIN3, OUTPUT); } void loop(void) { while (radio.available()) { Serial.write("Radio Ready\n"); radio.read(ReceivedMessage, 1); // Read information from the NRF24L01 if (ReceivedMessage[0] == 001) // Indicates switch is pressed { digitalWrite(LED_PIN1, HIGH); } else { digitalWrite(LED_PIN1, LOW); } if (ReceivedMessage[0] == 010) // Indicates switch is pressed { digitalWrite(LED_PIN2, HIGH); } else { digitalWrite(LED_PIN2, LOW); } if (ReceivedMessage[0] == 011) // Indicates switch is pressed { digitalWrite(LED_PIN3, HIGH); } else { digitalWrite(LED_PIN3, LOW); } delay(10); } }
# Project_Hajek_Tomsu This is a repository for our Data Processing in Python project. Collaborative work of Jiří Hájek and Vojtěch Tomšů. # Netflix cinematographics database analysis + movie recommendation application First part of our code is dedicated to work with data, cleaning and inspecting it. Then, we proceed in deeper analysis and visualization and third part of our work is program, that recommends user a movie based on the inputs given by the user. After a movie is recommended, user can watch trailer of it directly on our streamlit website, without the need of leaving it, as we use API request to import the trailer from Youtube. We obtained our dataset from https://www.kaggle.com/datasets/ariyoomotade/netflix-data-cleaning-analysis-and-visualization?datasetId=2437124&sortBy=voteCount - here is brief introduction to it: Netflix is a popular streaming service that offers a vast catalog of movies, TV shows, and original contents. This dataset is a cleaned version of the original version which can be found here. The data consist of contents added to Netflix from 2008 to 2021. The oldest content is as old as 1925 and the newest as 2021. # Obtaining API key For the trailer you will have obtain your own API key via https://console.cloud.google.com, where you will create a project a than in the sidebar click on credentials. On the credentials side you will click the "Create credentials" button and select "API key.". You will have create your own ".env" file on your device and insert API_KEY= 'your_API_key'. ## Project structure ``` │ main.ipynb # main script │ website.py # final application with data visualization and movie recommender; final product │ README.md # guide to our project code and structure │ requirements.txt # requirements │ └───data ├───netflix_titles.csv # raw dataset ├───proccessed_data.csv # final dataset ``` ## Arguments * "type" * This argument lets you pick Movie or TV Show * "countries" * Argument lets you choose desired country of cinematographic origin * "year interval" * Argument for picking a decade in which was the movie made * We decided to split years in decades, as it provides more user-friendly solution * "genre" * Argument that offers various kinds of genres of either TV Shows and Movies * The offer of genres differ based on user's choice in "type" argument
import { ObjectType, Field, Int } from '@nestjs/graphql'; import { ProductCategory } from 'src/apis/productCategory/entites/productCategory.entity'; import { ProductSaleslocation } from 'src/apis/productsSaleslocation/entites/productsSaleslocation.entity'; import { ProductTag } from 'src/apis/productTags/entites/productTags.entity'; import { User } from 'src/apis/users/entites/user.entity'; import { Column, DeleteDateColumn, Entity, JoinColumn, JoinTable, ManyToMany, ManyToOne, OneToOne, PrimaryGeneratedColumn, } from 'typeorm'; @ObjectType() @Entity() export class Product { @PrimaryGeneratedColumn('uuid') @Field(() => String) id: string; @Column() @Field(() => String) name: string; @Column({ type: 'text' }) @Field(() => String) description: string; @Column() @Field(() => Int) price: number; @Column({ default: false }) @Field(() => Boolean) isSoldout: boolean; @DeleteDateColumn() deletedAt: Date; @JoinColumn() @OneToOne(() => ProductSaleslocation) @Field(() => ProductSaleslocation) productSaleslocation: ProductSaleslocation; @Field(() => ProductCategory) @ManyToOne(() => ProductCategory) productCategory: ProductCategory; @ManyToOne(() => User) @Field(() => User) user: User; @JoinTable() @ManyToMany(() => ProductTag, (productTags) => productTags.products) @Field(() => [ProductTag]) productTags: ProductTag[]; }
<!DOCTYPE html> <html> <head> <title>Ethiopia on Rails</title> <%= csrf_meta_tags %> <%= csp_meta_tag %> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %> <%= stylesheet_link_tag 'reset', media: 'all', 'data-turbolinks-track': 'reload' %> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="icon" type="image/png" href="https://res.cloudinary.com/ethiopia-on-rails/image/upload/v1603732397/logo_fk0ggu.png"/> </head> <body class="h-auto"> <% if flash[:notice]%> <div class="alert alert-info alert-dismissible bg-info text-info text-center bg-light w-75 mx-auto shadow-sm py-5 bg-white alert-custom form-border"> <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a> <strong><%= notice.html_safe%></strong> </div> <%end%> <% if flash[:alert]%> <div class="alert alert-info alert-dismissible text-center text-danger bg-light m-0 w-75 mx-auto shadow-sm py-5 bg-white alert-custom form-border"> <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a> <strong class="h5"><%= alert.html_safe%></strong> <div> <a href="#" class="btn btn-light border mt-4 px-2" data-dismiss="alert" aria-label="close">Ok</a> </div> </div> <%end%> <header> <nav class="nav-custom w-100 fixed-top d-flex justify-content-between"> <div class="pl-3 d-md-none"> <label for="toggle" class="toggle-label mt-4"></label> </div> <input id="toggle" class="toggle-checkbox" type="checkbox" name="toggle"> <%= link_to articles_path, class: 'd-flex align-items-center logo__container mb-1' do%> <h4 class="theme-color-2 h3 align-self-end mb-0">ET<ins class="text-dark text-decoration-none">on</ins>Rails</h4> <%end%> <div class="d-flex flex-column flex-md-row h-100 align-self-md-center justify-content-md-center align-items-md-center text-size-sm font-weight-bolder ml-md-2 nav__links"> <div class="ml-3 mx-md-auto theme-color-lg theme-color-sm d-flex flex-column flex-md-row flex-wrap"> <%= navigation_buttons%> </div> <div class="ml-3 ml-md-auto d-flex flex-column flex-md-row justify-content-center align-items-md-center theme-color-lg theme-color-sm access__btns"> <%=access_buttons%> </div> </div> <div class="d-flex justify-content-center align-items-center h6 text-size-sm mx-2"> <button type="button" class="btn" data-toggle="modal" data-target="#search_modal"> <i class="fa fa-2x fa-search theme-color-1"></i> </button> <div class="modal fade" id="search_modal" tabindex="-1" role="dialog" aria-labelledby="search_modalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="search_modalLabel">Search</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <%= render '/articles/search'%> </div> </div> </div> </div> </div> </nav> </header> <main class="container-fluid main mt-5 pt-1 px-0 mb-7"> <%= yield %> </main> <footer class="theme-bg-2 row d-none d-lg-flex justify-content-between align-items-center px-3 mt-5 footer"> <div class="text-white"> <%= link_to articles_path, class: 'd-flex align-items-center mb-1' do%> <h4 class=" h3 align-self-end mb-0">ET<ins class="text-white text-decoration-none">on</ins>Rails</h4> <%end%> </div> <div class="d-flex"> <a class="theme-color-3" href="#">Privacy Policy</a> <a class="theme-color-3" href="#">Terms & conditions</a> <p class="ml-3 text-white">Copyright 2020. All right reserved</p> </div> <div class="d-flex align-items-center"> <p class="text-white mr-3">Connect with us</p> <i class="fa fa-2x fa-twitter theme-color-3"></i> <i class="fa fa-2x fa-instagram ml-3 theme-color-3"></i> <i class="fa fa-2x fa-facebook ml-3 theme-color-3"></i> </div> </footer> </body> </html>
155. Min Stack https://leetcode.com/problems/min-stack/ class MinStack { // use two stacks: // counterStack: is used to record current min values Deque<Integer> stack; Deque<Integer> counterStack; public MinStack() { stack = new ArrayDeque<>(); counterStack = new ArrayDeque<>(); } public void push(int val) { stack.offerFirst(val); if (counterStack.isEmpty() || counterStack.peekFirst() > val) { counterStack.offerFirst(val); } else { counterStack.offerFirst(counterStack.peekFirst()); } } public void pop() { stack.pollFirst(); counterStack.pollFirst(); } public int top() { return stack.peekFirst(); } public int getMin() { return counterStack.peekFirst(); } } /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(val); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */
using System.Linq; using Unity.Burst; using Unity.Collections; using Unity.Jobs; using UnityEngine; public class SnakingTorus : MonoBehaviour { public int numSpheres = 100; // Total number of spheres public Vector2 RadiusRange = new Vector2(.0000001f, 1f); private Vector2 lastRadiusRange = new Vector2(0f, 1f); public Vector2 OscillationRange = new Vector2(0.1f, 0.2f); // Range of oscillation for inner and outer radius public float OscillationSpeed = 1.0f; // Speed of oscillation public float wraps = 1.0f; // Controls the density of the snaking line public Material baseMaterial; public float alpha = 1.0f; private GameObject[] sphereObjects; private float[] gradientValues; // Array to hold the gradient values public float updateSpeed; private float timeSinceLastUpdate = 0f; void Start() { sphereObjects = new GameObject[numSpheres]; gradientValues = new float[numSpheres]; InitializeGradientValues(); RadiusRange.x = RadiusRange.x == 0 ? .00001f : RadiusRange.x; RadiusRange.y = RadiusRange.y == 0 ? .00001f : RadiusRange.y; lastRadiusRange = RadiusRange; StartVisualization(true); } void InitializeGradientValues() { float minValue = 0.1f; // Specify the minimum value of the gradient at the outer radius float maxDistance = RadiusRange.y + RadiusRange.x; // Maximum distance from the center line of the torus tube float minDistance = RadiusRange.x; // Minimum distance (at the inner radius) for (int i = 0; i < numSpheres; i++) { // Calculate the position along the path float t = (float)i / (numSpheres - 1); // Map the position to angles on the torus float theta = t * 2 * Mathf.PI * wraps; // Angle around the major radius float phi = theta * (RadiusRange.y / RadiusRange.x); // Angle around the minor radius, adjusted for the number of MajorWraps // Calculate radial distance from the center line of the torus tube float radialDistance = Mathf.Abs(RadiusRange.y + RadiusRange.x * Mathf.Cos(phi)) - RadiusRange.y; // Normalize the radial distance to [0, 1] float normalizedDistance = (radialDistance - minDistance) / (maxDistance - minDistance); // Compute the gradient value based on the radial distance gradientValues[i] = minValue + (1 - minValue) * (1 - normalizedDistance); } } void StartVisualization(bool createNewSpheres) { float totalAngle = 2 * Mathf.PI * wraps; // Total angle for a complete wrap for (int i = 0; i < numSpheres; i++) { GameObject sphere = createNewSpheres || sphereObjects[i] == null ? GameObject.CreatePrimitive(PrimitiveType.Sphere) : sphereObjects[i]; if (createNewSpheres || sphereObjects[i] == null) { sphere.transform.localScale = transform.localScale; // Adjust as needed Destroy(sphere.GetComponent<Collider>()); sphereObjects[i] = sphere; sphere.GetComponent<Renderer>().material = new Material(baseMaterial); } // Calculate angular positions with an adjustment to ensure closure float theta = i * totalAngle / (numSpheres - 1); // Ensures the last sphere aligns with the first float minorWraps = RadiusRange.y / RadiusRange.x; float phi = i * totalAngle * minorWraps / (numSpheres - 1); // Synchronized with major MajorWraps // Calculate position on the torus float x = (RadiusRange.y + RadiusRange.x * Mathf.Cos(phi)) * Mathf.Cos(theta); float y = (RadiusRange.y + RadiusRange.x * Mathf.Cos(phi)) * Mathf.Sin(theta); float z = RadiusRange.x * Mathf.Sin(phi); Vector3 position = new Vector3(x, y, z) + transform.position; sphere.transform.position = position; // Set color based on gradient values Color color = new Color(gradientValues[i], gradientValues[i], gradientValues[i], alpha); sphere.GetComponent<Renderer>().material.color = color; sphereObjects[i] = sphere; } } // The Update and OnDestroy methods can remain largely the same. // You may remove or modify the UpdateGrid and UpdateGridJob methods as the Game of Life logic is no longer needed. void Update() { timeSinceLastUpdate += Time.deltaTime; // Oscillate the RadiusRange //float oscillation = Mathf.Sin(Time.time * Random.Range(00001,1f) * OscillationSpeed) * 0.5f + 0.5f; // Normalized sine wave oscillation //RadiusRange.x = Mathf.Lerp(OscillationRange.x, OscillationRange.y, oscillation); // Oscillate inner radius //oscillation = Mathf.Sin((Time.time + .5f) * OscillationSpeed) * 0.5f + 0.5f; // Normalized sine wave oscillation //RadiusRange.y = Mathf.Lerp(OscillationRange.y, OscillationRange.x, oscillation); // Oscillate outer radius if (timeSinceLastUpdate >= updateSpeed) { if (lastRadiusRange != RadiusRange) { RadiusRange.x = RadiusRange.x == 0 ? .00001f : RadiusRange.x; RadiusRange.y = RadiusRange.y == 0 ? .00001f : RadiusRange.y; lastRadiusRange = RadiusRange; InitializeGradientValues(); StartVisualization(false); } else { timeSinceLastUpdate = 0f; RotateGradientValues(); ApplyGradient(); } } } void RotateGradientValues() { // Rotate the gradient values array by one position float lastValue = gradientValues[numSpheres - 1]; for (int i = numSpheres - 1; i > 0; i--) { gradientValues[i] = gradientValues[i - 1]; } gradientValues[0] = lastValue; } void ApplyGradient() { for (int i = 0; i < numSpheres; i++) { // Apply the gradient value to each sphere Color color = new Color(gradientValues[i], gradientValues[i], gradientValues[i], alpha); sphereObjects[i].GetComponent<Renderer>().material.color = color; } } void OnDestroy() { // Clean up the resources foreach (var sphere in sphereObjects) { if (sphere != null) Destroy(sphere); } } }
<script setup lang="ts"> defineProps({ id: { type: String, required: true, }, label: { type: String, required: true, }, required: { default: false, type: Boolean, }, value: { type: Boolean, default: false, }, }); const emit = defineEmits<{ (event: "update:value", value: boolean): void }>(); const onInput = (evt: Event) => { const input = evt.target as HTMLInputElement; emit("update:value", input.checked); }; </script> <template> <div class="mb-3"> <div class="form-check"> <input class="form-check-input" type="checkbox" :id="id" :checked="value" :name="id" @input="onInput" :required="required" /> <label class="form-check-label" :for="id">{{ label }}</label> </div> </div> </template>
<p style="color: green"><%= notice %></p> <div class="container mx-auto pt-5"> <h1 class="mb-2 text-5xl text-center font-bold tracking-tight text-gray-800">Games</h1> <% if current_user.admin? %> <%= link_to 'New game', new_game_path, class:"mb-2 text-2xl font-bold tracking-tight text-gray-900 dark:text-black" %> <% end %> <hr> <br> <div id="games" > <% @games.each do |game| %> <%= link_to game do%> <div class="flex flex-col items-center border rounded-lg shadow-xl md:flex-row md:max-w-3xl border-gray-700 bg-gray-800 hover:bg-gray-700"> <div> <%if game.image.attached?%> <div class="h-50 w-full rounded-t-lg object-cover md:h-auto md:w-48 md:rounded-none md:rounded-l-lg"> <%= image_tag game.image%> </div> <%end%> </div> <div class="flex flex-col justify-start p-6"> <h3 class="mb-2 text-2xl font-bold tracking-tight text-gray-900 dark:text-white"><%= game.name %></h3> <div> <%if game.release_date%> <div class="text-xl text-white"> <%= game.release_date.year %> </div> <%end%> </div> <p class="mb-3 font-normal text-gray-700 dark:text-gray-400"><%= game.rating %></p> <p class="mb-3 font-normal text-gray-700 dark:text-gray-400"><%= game.summary %></p> <% if current_user.admin? %> <%= link_to 'Edit', edit_game_path(game), class:"mb-4 block items-center px-4 py-2 text-sm font-medium text-center text-gray-900 bg-white border border-gray-300 rounded-lg hover:bg-blue-500 focus:ring-4 focus:outline-none focus:ring-gray-200 dark:bg-gray-800 dark:text-white dark:border-gray-600 dark:hover:bg-gray-400 dark:hover:border-gray-700 dark:focus:ring-gray-700" %> <%= link_to 'Destroy', game, data: { turbo_method: :delete, turbo_confirm: 'Are you sure?' }, class:"block items-center px-4 py-2 text-sm font-medium text-center text-gray-900 bg-white border border-gray-300 rounded-lg hover:bg-gray-100 focus:ring-4 focus:outline-none focus:ring-gray-200 dark:bg-gray-800 dark:text-white dark:border-gray-600 dark:hover:bg-gray-400 dark:hover:border-gray-700 dark:focus:ring-gray-700" %> <% end %> </div> </div> <br> <% end %> <%end%> </div> </div>
module.exports.config = { name: 'dall-e', version: '1.0.0', hasPermssion: 0, credits: 'Hadestia', description: 'An AI image generator prompter from openAI', commandCategory: 'artificial intelligence', usages: '< prompt >', aliases: [ 'imggen' ], cooldowns: 10, dependencies: { 'openai': '', 'fs-extra': '', 'axios': '' }, envConfig: { requiredArgument: 1, inProcessReaction: true } } module.exports.run = async function({ api, event, args, returns, textFormat, Prefix }) { const axios = require('axios'); const { threadID, messageID } = event; const { unlinkSync, writeFileSync, createReadStream } = require('fs-extra'); const { Configuration, OpenAIApi } = require('openai'); const configuration = new Configuration({ apiKey: process.env.OPENAI_API }); const openai = new OpenAIApi(configuration); try { //global.sendReaction.inprocess(api, event); const response = await openai.createImage({ prompt: args.join(' '), n: 1, size: '1024x1024' }); const path = `${__dirname}/../../cache/ai-generatedImages.png`; const img_req = (await axios.get(response.data.data[0].url, { responseType: 'arraybuffer' })).data; writeFileSync(path, Buffer.from(img_req, 'utf-8')); const messageBody = { body: args.join(' '), attachment: createReadStream(path) } return api.sendMessage( messageBody, threadID, (err) => { try { unlinkSync(path); } catch {} if (!err) return global.sendReaction.success(api, event); }, messageID ); } catch (err) { returns.remove_usercooldown(); global.sendReaction.failed(api, event); /*if ((err.toString()).indexOf('status code 400') !== -1) { return api.sendMessage(textFormat('error', 'errOccured', `Inappropriate request, try another one that's valid.`), threadID, messageID); }*/ if (err.response) { console.log('DALL-E STATUS', err.response.status); console.log('DATA', err.response.data); // ALL TOKENS ARE USED UP if (err.response.data.error.code == 'billing_hard_limit_reached') { api.sendMessage(textFormat('error', 'errOccured', 'Sorry, it seems like all api tokens are used up, I couldn\'t process your request. This error was already sent to the admins, kindly wait for them to recharge :)'), event.threadID, event.messageID); return global.logModuleErrorToAdmin(err.response.data.error.message, __filename, event); } else { api.sendMessage(textFormat('error', 'errOccured', err.response.data.error.message), event.threadID, event.messageID); return global.logModuleErrorToAdmin(err.response.data.error.message, __filename, event); } } else { global.logger(err.message, 'error'); global.logModuleErrorToAdmin(err.message, __filename, event); return api.sendMessage(textFormat('error', 'errCmdExceptionError', err.message, Prefix), threadID, messageID); } } }
<?php class RescueAnimalsPostType { // Constructor to hook into WordPress actions public function __construct() { global $post; // Register custom post type and taxonomy add_action('init', array($this, 'register_rescue_animals_cpt')); add_action('init', array($this, 'register_animal_types_taxonomy')); // Add meta boxes add_action('add_meta_boxes', array($this, 'add_post_type_meta_box')); add_action('save_post', array($this, 'save_post_type_meta_box')); } // Register the custom post type public function register_rescue_animals_cpt() { $args = array( 'label' => 'Rescue Animals', 'public' => true, 'has_archive' => true, 'supports' => array('title', 'editor', 'thumbnail', 'excerpt'), 'show_in_rest' => true, // for Gutenberg editor compatibility ); register_post_type('rescue_animals', $args); } // Register the custom taxonomy public function register_animal_types_taxonomy() { $args = array( 'labels' => array( 'name' => 'Animal Types', 'singular_name' => 'Animal Type', ), 'public' => true, 'hierarchical' => true, // Enables category-style taxonomy ); register_taxonomy('animal_types', 'rescue_animals', $args); } // Add a custom meta box for Custom Post Type public function add_post_type_meta_box() { add_meta_box( 'resident_type_meta_box', // ID 'Resident Type', // Title array($this, 'resident_type_meta_box_callback'), // Callback 'rescue_animals', // Post type 'side', // Context 'high' // Priority ); add_meta_box( 'exclusive_content_meta_box', // ID 'Exclusive Content', // Title array($this, 'exclusive_content_meta_box_callback'), // Callback 'rescue_animals', // Post type 'normal', // Context 'high' // Priority ); } // Callback to render the meta box public function resident_type_meta_box_callback($post) { // Get the current value of the meta field $resident_type = get_post_meta($post->ID, '_resident_type', true); // Use a nonce for security wp_nonce_field('save_post_type_meta_box', 'resident_type_nonce'); echo '<label for="resident_type">Resident Type: </label>'; echo '<select name="resident_type"><option value="permanent"'. selected($resident_type, 'permanent', false) .'>Permanent</option><option value="adoption" '. selected($resident_type, 'adoption', false) .'>Available for adoption</option></select>'; } public function exclusive_content_meta_box_callback($post) { $exclusive_content = get_post_meta($post->ID, '_exclusive_content', true); // Use a nonce for security wp_nonce_field('save_post_type_meta_box', 'exclusive_content_nonce'); echo '<div id="repeater-container">'; if ($exclusive_content && is_array($exclusive_content)) { foreach ($exclusive_content as $key => $data) { $this->render_repeater_item($key, $data); } } else { // Render one empty repeater item initially $this->render_repeater_item(0, null); } echo '</div>'; // Button to add more items echo '<button type="button" id="add-repeater-item" class="button">Add More</button>'; // JavaScript to handle repeater functionality $this->enqueue_repeater_script(); } // Enqueue the JavaScript for the repeater functionality private function enqueue_repeater_script() { // Inline script to add repeater functionality echo '<script> (function($){ $("#add-repeater-item").on("click", function(){ const newItem = $(".repeater-item:first").clone(); const newIndex = index = $("#repeater-container > .repeater-item").length; newItem.attr("data-index", newIndex); inputs = newItem[0].querySelectorAll("input, textarea, select"); newItem.find("input, textarea").val(""); newItem.find(".remove-repeater-item").show(); newItem.find("textarea").html(""); inputs.forEach(input => { const name = input.getAttribute("name"); if (name) { const updatedName = name.replace(/\[\d+\]/, `[${newIndex}]`); input.setAttribute("name", updatedName); } }); $("#repeater-container").append(newItem); }); $(document).on("click", ".remove-repeater-item", function(){ if ($("#repeater-container > .repeater-item").length > 1) { $(this).closest(".repeater-item").remove(); // Remove item } }); $(".upload-image-button").on("click", function(e) { e.preventDefault(); // Store a reference to the current button var button = $(this); // Create a new media frame for the image uploader var frame = wp.media({ title: "Select or Upload an Image", button: { text: "Use this image" }, multiple: false // Single image upload }); // When an image is selected in the media uploader frame.on("select", function() { var attachment = frame.state().get("selection").first().toJSON(); // Example: Store the attachment ID in a hidden field button.siblings("input[type=hidden]").val(attachment.id); // Optionally display a preview of the image var imagePreview = button.siblings(".image-preview"); imagePreview.html(`<img src="${attachment.url}" style="max-width: 100px;">`); }); // Open the media frame frame.open(); }); })(jQuery); </script>'; } // Render a single repeater item private function render_repeater_item($index, $data) { $image_id = isset($data['image_id']) ? $data['image_id'] : ''; $content = isset($data['content']) ? $data['content'] : ''; $date = isset($data['date']) ? $data['date'] : ''; echo '<div class="repeater-item" data-index="' . esc_attr($index) . '">'; echo '<div style="margin-bottom: 10px;">'; echo '<label>Image: </label>'; echo '<button class="button upload-image-button">Upload Image</button>'; echo '<input type="hidden" name="exclusive_content[' . $index . '][image_id]" value="' . esc_attr($image_id) . '" />'; echo '<div class="image-preview" style="margin-top: 10px;">' . ($image_id ? wp_get_attachment_image($image_id) : '') . '</div>'; echo '</div>'; echo '<div>'; echo '<label>Content: </label>'; echo '<textarea name="exclusive_content[' . $index . '][content]" class="large-text">' . esc_textarea($content) . '</textarea>'; echo '</div>'; echo '<div>'; echo '<label>Date: </label>'; echo '<input name="exclusive_content[' . $index . '][date]" type="date" value="'. esc_textarea($date) .'">'; echo '</div>'; echo '<button type="button" class="button remove-repeater-item" style="margin-top: 10px;">Remove</button>'; echo '</div>'; } // Save the meta box data public function save_post_type_meta_box($post_id) { // Check if the nonce is valid if ( (!isset($_POST['resident_type_nonce']) || !wp_verify_nonce($_POST['resident_type_nonce'], 'save_post_type_meta_box')) && !isset($_POST['exclusive_content_nonce']) || !wp_verify_nonce($_POST['exclusive_content_nonce'], 'save_post_type_meta_box') ) { return; } // Check if the current user has permission to edit the post if (!current_user_can('edit_post', $post_id)) { return; } // Update the meta field if (isset($_POST['resident_type'])) { update_post_meta($post_id, '_resident_type', sanitize_text_field($_POST['resident_type'])); } // Update the meta field with sanitized data if (isset($_POST['exclusive_content']) && is_array($_POST['exclusive_content'])) { $sanitized_data = array(); foreach ($_POST['exclusive_content'] as $index => $data) { $sanitized_data[$index] = array( 'image_id' => isset($data['image_id']) ? sanitize_text_field($data['image_id']) : '', 'content' => isset($data['content']) ? sanitize_textarea_field($data['content']) : '', 'date' => isset($data['date']) ? sanitize_textarea_field($data['date']) : '', ); } update_post_meta($post_id, '_exclusive_content', $sanitized_data); } } }
import argparse import os from src import clubs, events, fighters, ratings def clear(): # for windows if os.name == "nt": os.system("cls") # for mac and linux(here, os.name is 'posix') else: os.system("clear") def main(): parser = argparse.ArgumentParser( description="The program scrapes the lists of clubs, events, fighters and ratings, and writes the info in a SQLite database in a 'data' directory. If no flags are given, nothing will be scraped." ) parser.add_argument("-f", "--fighters", action="store_true", help="scrape fighters") parser.add_argument("-c", "--clubs", action="store_true", help="scrape clubs") parser.add_argument("-e", "--events", action="store_true", help="scrape events") parser.add_argument("-r", "--ratings", action="store_true", help="scrape ratings") parser.add_argument( "--history", action="store_true", help="scrape the full history of ratings (only works if -r is active)", ) fighters_on = parser.parse_args().fighters clubs_on = parser.parse_args().clubs events_on = parser.parse_args().events ratings_on = parser.parse_args().ratings history_on = parser.parse_args().history clear() print("Initialising...") if not os.path.exists("data"): os.mkdir("data") if clubs_on: # process_clubs = Process(target=clubs.clubs) # process_clubs.start() clubs.clubs() print("Club scraping completed.") if events_on: # process_events = Process(target=events.events) # process_events.start() events.events() print("Event scraping completed.") if fighters_on: fighters.fighters() print("Fighters scraping completed.") if ratings_on: ratings.ratings(history=history_on) print("Ratings scraping completed.") print() print("Scrape complete.") if __name__ == "__main__": main()
#include <DHT.h> // Including library for dht #include <ESP8266WiFi.h> String apiKey1 = "L796O3A1M0WEGEYI"; // Enter your Write API key from ThingSpeak //String apiKey2 = "1AYIFNP3C1XVY8YL"; // Enter your Write API key from ThingSpeak const char *ssid = "POCO"; // replace with your wifi ssid and wpa2 key const char *pass = "23456789"; const char* server = "api.thingspeak.com"; #define DHTPIN D4 //pin where the dht11 is connec DHT dht(DHTPIN, DHT11); WiFiClient client; void setup() { Serial.begin(9600); delay(10); dht.begin(); Serial.println("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, pass); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); } void loop() { float g = analogRead(A0); float h = dht.readHumidity(); float t = dht.readTemperature(); if (isnan(h) || isnan(t)||isnan(g)) { Serial.println("Failed to read from sensor!"); return; } if(client.connect(server,80)) { String postStr=apiKey1; //String postStr2 = apiKey2; postStr +="&field1="; postStr += String(t); postStr +="&field2="; postStr += String(h); postStr += "\r\n\r\n"; postStr += "&field3="; postStr += String(g/1023*100); postStr += "r\n"; client.print("POST /update HTTP/1.1\n"); client.print("Host: api.thingspeak.com\n"); client.print("Connection: close\n"); // client.print("X-THINGSPEAKAPIKEY: " + apiKey2 + "\n"); client.print("X-THINGSPEAKAPIKEY: "+apiKey1+"\n"); client.print("Content-Type: application/x-www-form-urlencoded\n"); client.print("Content-Length: "); client.print(postStr.length()); //client.print(postStr2.length()); client.print("\n\n"); client.print(postStr); Serial.print("Temperature: "); Serial.print(t); Serial.print(" degrees Celcius, Humidity: "); Serial.print(h); Serial.println("%. Send to Thingspeak."); client.print("\n\n"); //client.print(postStr); Serial.print("Gas Level: "); Serial.println(g/1023*100); Serial.println("Data Send to Thingspeak"); } delay(500); client.stop(); Serial.println("Waiting..."); // thingspeak needs minimum 15 sec delay between updates. delay(1500); }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>J-learning</title> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css?family=Montserrat|Ubuntu" rel="stylesheet"> <!-- CSS Stylesheets --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" href="./style.css/index.css"> <!-- Font Awesome --> <script defer src="https://use.fontawesome.com/releases/v5.0.7/js/all.js"></script> <!-- Bootstrap Scripts --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </head> <body> <section class="colored-section" id="title"> <div class="container-fluid"> <!-- Nav Bar --> <nav class="navbar navbar-expand-lg navbar-dark"> <a class="navbar-brand" href="">J-LEARNING</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo02"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo02"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="./login.html">Login</a> </li> <li class="nav-item"> <a class="nav-link" href="./register.html">Sign-Up</a> </li> </ul> </div> </nav> <!-- Title --> <div class="row"> <div class="col-lg-6"> <h1 class="big-heading">Come to Learn ,Go With Skills</h1> </div> <div class="col-lg-6"> <img class="title-image" src="./asserts/iphone.jpg" alt="iphone-mockup"> </div> </div> </div> </section> <!-- Features --> <section class="white-section" id="features"> <div class="container-fluid"> <div class="row"> <div class="feature-box col-lg-4"> <i class="icon fas fa-check-circle fa-4x"></i> <h3 class="feature-title">Easy to Learn.</h3> <p>It is very easy to learn.even kids also.</p> </div> <div class="feature-box col-lg-4"> <i class="icon fas fa-bullseye fa-4x"></i> <h3 class="feature-title">Large pool of courses.</h3> <p>We have More than 1000+ courses</p> </div> <div class="feature-box col-lg-4"> <i class="icon fas fa-heart fa-4x"></i> <h3 class="feature-title">Skilled Person.</h3> <p>We assure that you become a SkillFull person</p> </div> </div> </div> </section> <!-- Testimonials --> <section class="colored-section" id="testimonials"> <div id="testimonial-carousel" class="carousel slide" data-ride="false"> <div class="carousel-inner"> <div class="carousel-item active container-fluid"> <h2 class="testimonial-text">"If I had six hours to chop down a tree, I’d spend the first four hours sharpening the axe."</h2> <em>-Abraham Lincoln</em> </div> <div class="carousel-item container-fluid"> <h2 class="testimonial-text"> "Learning is not the product of teaching. Learning is the product of the activity of learners."</h2> <em>-John Holt</em> </div> </div> <a class="carousel-control-prev" href="#testimonial-carousel" role="button" data-slide="prev"> <span class="carousel-control-prev-icon"></span> </a> <a class="carousel-control-next" href="#testimonial-carousel" role="button" data-slide="next"> <span class="carousel-control-next-icon"></span> </a> </div> </section> <section class="white-section" id="pricing"> <h2 class="section-heading">Launch your career with our Courses with a 100% Job Guarantee</h2> <p>Simple and affordable price plans for All the Courses</p> <div class="row"> <div class="pricing-column col-lg-4 col-md-6"> <div class="card"> <div class="card-header"> <h3>JAVAPROGRAMMING</h3> </div> <div class="card-body"> <h2 class="price-text">Free</h2> <p>6 Months</p> <p>At 10-15 hours/week</p> <p>Start today improve your skills</p> <button class="btn btn-lg btn-block btn-outline-dark" type="button" ><a class="nav-link" href="./register.html">Sign-Up</a></button> </div> </div> </div> <div class="pricing-column col-lg-4 col-md-6"> <div class="card"> <div class="card-header"> <h3>C Programming</h3> </div> <div class="card-body"> <h2 class="price-text">Free</h2> <p>6 Months</p> <p>Every WeekEnd 3-4 Hours</p> <p>Utilize the opportunity</p> <button class="btn btn-lg btn-block btn-outline-dark" type="button"><a class="nav-link" href="./register.html">Sign-Up</a></button> </div> </div> </div> <div class="pricing-column col-lg-4"> <div class="card"> <div class="card-header"> <h3>Web Development</h3> </div> <div class="card-body"> <h2 class="price-text">Rs.4350</h2> <p>8 Months</p> <p>2 Hours Daily</p> <p>Front End/Back End</p> <p>It Makes you a Complete Full Stack Developer</p> <button class="btn btn-lg btn-block btn-outline-dark" type="button"> <a class="nav-link" href="./register.html">Sign-Up</a></button> </div> </div> </div> </div> </section> <!-- Call to Action --> <section class="colored-section" id="cta"> <div class="container-fluid"> <h3 class="big-heading">Find the Courses And Improve Your Skills.</h3> <button class="download-button btn btn-lg btn-light" type="button"><a class="nav-link" href="./register.html">Sign-Up</a></button> <button class="download-button btn btn-lg brn-light" type="button"> <a class="nav-link" href="./login.html">Login</a></button> </div> </section> <!-- Footer --> <footer class="white-section" id="footer"> <div class="container-fluid"> <i class="social-icon fab fa-facebook-f"></i> <i class="social-icon fab fa-twitter"></i> <i class="social-icon fab fa-instagram"></i> <i class="social-icon fas fa-envelope"></i> <p>© Copyright J-LEARNING</p> </div> </footer> </body> </html>
/* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Written by Frederic PONT. (c) Frederic Pont 2023 */ package ui import ( "fyne.io/fyne/v2" "fyne.io/fyne/v2/container" "fyne.io/fyne/v2/data/binding" "fyne.io/fyne/v2/dialog" "fyne.io/fyne/v2/theme" "fyne.io/fyne/v2/widget" ) // getfilePath create a file button and stores the file path using databinding func getfilePath(window fyne.Window, buttonlabel string, url binding.String) *fyne.Container { // label to display file path label := widget.NewLabel("") // file choosing function chooseFile := func() { // dialog to open a file dialog.ShowFileOpen(func(file fyne.URIReadCloser, err error) { if err != nil { // show error on pop up dialog.ShowError(err, window) return } if file == nil { // do nothing when no file is selected return } // close the file file.Close() // display file path in label label.SetText(cleanFileURI(file.URI())) //path = file.URI().String() url.Set(cleanFileURI(file.URI())) }, window) } // button to trigger file pickup button := widget.NewButtonWithIcon(buttonlabel, theme.FileIcon(), chooseFile) return container.NewVBox(button, label) } // getfileSave create a file button and stores the file path entered by the user and refresh the path label func getfileSave(window fyne.Window, buttonlabel string, url binding.String, outFileLabel *widget.Label) *widget.Button { // file choosing function chooseFile := func() { // dialog to open a file dialog.ShowFileSave(func(file fyne.URIWriteCloser, err error) { if err != nil { // show error on pop up dialog.ShowError(err, window) return } if file == nil { // do nothing when no file is selected return } // close the file file.Close() url.Set(cleanFileURI(file.URI())) outFileLabel.Text = insertNewlines(cleanFileURI(file.URI()), 45) outFileLabel.Refresh() }, window) } // button to trigger file pickup button := widget.NewButtonWithIcon(buttonlabel, theme.FileIcon(), chooseFile) return button } // getdirPath create a file button and stores the dir path using databinding and refresh the path label func getdirPath(window fyne.Window, buttonlabel string, url binding.String, outDirLabel *widget.Label) *widget.Button { // dir choosing function chooseDir := func() { // dialog to open a dir dialog.ShowFolderOpen(func(dir fyne.ListableURI, err error) { if err != nil { // show error on pop up dialog.ShowError(err, window) return } if dir == nil { // do nothing when no file is selected return } outDirLabel.SetText(insertNewlines(cleanDirURI(dir), 45)) url.Set(cleanDirURI(dir)) outDirLabel.Refresh() }, window) } // button to trigger dir pickup button := widget.NewButtonWithIcon(buttonlabel, theme.FolderOpenIcon(), chooseDir) return button } // getDatabasePath stores the SQLIte database path func getDatabasePath(window fyne.Window, buttonlabel string, url binding.String, outFileLabel *widget.Label) *widget.Button { // file choosing function chooseFile := func() { // dialog to open a file dialog.ShowFileOpen(func(file fyne.URIReadCloser, err error) { if err != nil { // show error on pop up dialog.ShowError(err, window) return } if file == nil { // do nothing when no file is selected return } url.Set(cleanFileURI(file.URI())) outFileLabel.Text = insertNewlines(cleanFileURI(file.URI()), 100) outFileLabel.Refresh() }, window) } // button to trigger file pickup button := widget.NewButtonWithIcon(buttonlabel, theme.FileIcon(), chooseFile) return button }
// Event data when filtering occurs on lists export default class FilterEvent { // Constructor constructor(filter: string, pageSize: number, page: number, sortField: string, sortAscending: boolean) { this.filter = filter; this.pageSize = pageSize; this.page = page; this.sortField = sortField; this.sortAscending = sortAscending; } // Filter string public filter: string; // Number of items to display public pageSize: number; // Page number (starts at 0) public page: number; // Sort field public sortField: string; // Should this sort ascending? public sortAscending: boolean; }
import * as nodemailer from 'nodemailer' export const sendEmail = async ( recipient: string, url: string, linkText: string ) => { const transporter = nodemailer.createTransport({ host: 'smtp.ethereal.email', port: 587, auth: { user: process.env.NODEMAILER_USER, pass: process.env.NODEMAILER_PASSWORD }, tls: { rejectUnauthorized: false } }) const message = { from: 'Sender Name <[email protected]>', to: `Recipient <${recipient}>`, subject: 'Confirm Account', text: 'Please click the link below to confirm your account', html: ` <html> <body> <a href="${url}">${linkText}</a> </body> </html> ` } transporter.sendMail(message, (err, info) => { if (err) { console.log('Error occurred. ' + err.message) } console.log('Message sent: %s', info.messageId) console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info)) }) }
import React from 'react' import { Select, Input, Tooltip } from 'antd' import { components } from '@C4/CommonComponents' import i18n from '../../../i18n' import { MARK_TYPE } from '../../../constants/drawLines' import { MAX_LENGTH_TEXT, MAX_ROW } from '../../../constants/InputText' import { typeOption } from './render' import { SUBORDINATION_LEVEL_PATH } from './WithSubordinationLevel' import './WithIntermediateAmplifiers.css' import { MOUSE_ENTER_DELAY } from '../../../constants/tooltip' const { FormRow } = components.form const PAIRS = { TOP: { id: 'top', name: 'H1' }, MIDDLE: { id: 'middle', name: 'B' }, BOTTOM: { id: 'bottom', name: 'H2' }, } export const NAME_OF_AMPLIFIERS = `${PAIRS.TOP.name}/${PAIRS.MIDDLE.name}/${PAIRS.BOTTOM.name}` const TYPES = { NONE: 'none', LEVEL: 'level', TEXT: 'text', ARROW: MARK_TYPE.ARROW_90, ARROW_FILED: MARK_TYPE.ARROW_30_FILL, } const TYPE_LIST = [ { id: '0', text: i18n.NO_ONE, value: TYPES.NONE }, { id: '1', text: i18n.TEXT_2, value: TYPES.TEXT }, { id: '2', text: i18n.SHOW_LEVEL, value: TYPES.LEVEL }, { id: '3', text: i18n.ARROW_FILLED, value: TYPES.ARROW_FILED }, { id: '4', text: i18n.ARROW_LEFT, value: TYPES.ARROW }, ] export const PATH = [ 'attributes', 'intermediateAmplifier' ] export const TYPE_PATH = [ 'attributes', 'intermediateAmplifierType' ] const WithIntermediateAmplifiers = (Component) => class IntermediateAmplifiersComponent extends Component { intermediateAmplifierTypeHandler = (type) => { this.setResult((result) => { return result .setIn(TYPE_PATH, type) .setIn([ ...PATH, PAIRS.MIDDLE.id ], null) }) } createIntermediateAmplifierHandler = (id) => (event) => { const strs = event.target.value.split('\n') if (strs.length > MAX_ROW.INTERMEDIATE_AMP) { return } return this.setResult((result) => result.setIn([ ...PATH, id ], event.target.value)) } renderIntermediateAmplifiers (svg) { const state = this.getResult() const currentValue = state.getIn(PATH) const type = state.getIn(TYPE_PATH) const subordinationLevel = state.getIn(SUBORDINATION_LEVEL_PATH) const canEdit = this.isCanEdit() const renderAmplifierInput = ({ id, name }) => ( <div className="line-container__itemWidth" key={id}> <FormRow title={null} label={svg ? <Tooltip overlayClassName='shape-form-svg-tooltip' mouseEnterDelay={MOUSE_ENTER_DELAY} placement={'left'} title={() => svg}> {`${i18n.AMPLIFIER} "${name}"`} </Tooltip> : `${i18n.AMPLIFIER} "${name}"`}> <Input.TextArea autoSize={{ maxRows: 3 }} value={currentValue[id] ?? ''} onChange={this.createIntermediateAmplifierHandler(id)} className={!canEdit ? 'modals-input-disabled' : ''} readOnly={!canEdit} rows={1} maxLength={MAX_LENGTH_TEXT.TEXTAREA} /> </FormRow> </div> ) return ( <div className="intermediate-amplifiers__item"> <div className="intermediate-amplifiers__itemWidth"> <div className="intermediate-amplifiers__item-B"> <FormRow title={null} label={svg ? <Tooltip overlayClassName='shape-form-svg-tooltip' mouseEnterDelay={MOUSE_ENTER_DELAY} placement={'left'} title={() => svg}> {`${i18n.AMPLIFIER} "${PAIRS.MIDDLE.name}"`} </Tooltip> : `${i18n.AMPLIFIER} "${PAIRS.MIDDLE.name}"`}> <Select value={type} onChange={this.intermediateAmplifierTypeHandler} disabled={!canEdit} className={!canEdit ? 'modals-input-disabled' : ''} >{TYPE_LIST.map(({ text, value }) => { const level = value === TYPES.LEVEL ? subordinationLevel : null let borderStyle switch (value) { case TYPES.ARROW: case TYPES.ARROW_FILED: borderStyle = value break default: borderStyle = 'solid' } return typeOption(value, borderStyle, text, level) })} </Select> <Input className={!canEdit ? 'modals-input-disabled' : ''} disabled={!canEdit || type !== TYPES.TEXT} value={currentValue[PAIRS.MIDDLE.id] ?? ''} onChange={this.createIntermediateAmplifierHandler(PAIRS.MIDDLE.id)} maxLength={MAX_LENGTH_TEXT.INPUT} /> </FormRow> </div> </div> {renderAmplifierInput(PAIRS.TOP)} {renderAmplifierInput(PAIRS.BOTTOM)} </div> ) } } export default WithIntermediateAmplifiers
#include <iostream> // stdio.h 와 같은 것 #include <vector> #include <string> #include <algorithm> #include <stack> #include <queue> #include <cstring> #include <cmath> #include <functional> #include <map> #include <unordered_map> #include <set> #include <sstream> // control i #define MAX 987654321 #define mod 10007 #define pii pair<int, int> using ll = long long; using namespace std; int n,m,k; int l,r,t; int h; int arr[11]; bool check[11]; void DFS(int num){ if(num == m){ for(int i=0;i<m;i++){ cout << arr[i] << ' '; } cout << '\n'; return; } // 숫자는 1부터 n까지 for(int i=1;i<=n;i++){ if(check[i]) continue; // i가 아직 방문하지 않은 경우 true로 바꾸고, arr[num]에 현재 i를 넣어주고 // num+1 을 해서 DFS로 들어간다. // num을 계속 증가시키면서 arr에 가능한 수들을 전부 넣어준다. check[i] = true; arr[num] = i; DFS(num+1); check[i] = false; } } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> m; DFS(0); return 0; }
class Solution { public: bool PredictTheWinner(vector<int>& nums) { /* 1 5 2 take 1-->5 2 take 2-->1 5 1+2 2+1 dp[i][j]-->states what maximum sum can player 1 bring (from the range i-->j) if both players play optimally */ int n=nums.size(); int dp[n][n]; for(int g=0;g<n;g++) { for(int i=0,j=i+g;j<n;i++,j++) { if(g==0) dp[i][j]=nums[i]; else if(g==1) dp[i][j]=max(nums[i],nums[j]); else { //for player2 to earn max sum he has to make player1 have min sum //from the set he would leave //optimal way by which player2 can pickup ele from set(i+1,j) int op1=min(dp[i+1][j-1],dp[i+2][j]); //optimal way by which player2 can pickup ele from set(i,j-1) int op2=min(dp[i+1][j-1],dp[i][j-2]); dp[i][j]=max(nums[i]+op1,nums[j]+op2); } } } int sum=0; for(int i=0;i<n;i++)sum+=nums[i]; return (2*dp[0][n-1])>=sum; } };
class Animal { name: string; constructor(name: string) { this.name = name; } getAnimalName() {} } const animals: Array<Animal> = [new Animal('lion'), new Animal('mouse')]; /* The function AnimalSound does not conform to the open-closed principle because it cannot be closed against new kinds of animals. If we add a new animal - we have to modify the AnimalSound function. */ function AnimalSound(animals: Array<Animal>) { for (let i = 0; i <= animals.length; i++) { if (animals[i].name == 'lion') console.log('roar'); if (animals[i].name == 'mouse') console.log('squeak'); } } AnimalSound(animals); class AnimalSolution { makeSound() {} } class Lion extends Animal { makeSound() { return 'roar'; } } class Squirrel extends Animal { makeSound() { return 'squeak'; } } class Snake extends Animal { makeSound() { return 'hiss'; } } function AnimalSoundSolution(animals: Array<AnimalSolution>) { for (let i = 0; i <= animals.length; i++) { console.log(animals[i].makeSound()); } } const animalsSolution: Array<AnimalSolution> = [ new Lion('lion'), new Squirrel('squirrel'), ]; AnimalSoundSolution(animalsSolution);
import { useRef } from "react"; import Button from "../ui/Button"; function EventsSearch({ onSearch }) { const yearInputRef = useRef(); const monthInputRef = useRef(); const submitHandler = (e) => { e.preventDefault(); const selectedYear = yearInputRef.current.value; const selectedMonth = monthInputRef.current.value; onSearch(selectedYear, selectedMonth); }; return ( <form onSubmit={submitHandler} className="my-[2rem] mx-auto shadow p-4 bg-white rounded-md w-[90%] max-w-[40rem] flex justify-between flex-col gap-4 md:flex-row" > <div className="flex flex-col w-full gap-4 md:w-[80%] md:flex-row"> <div className="flex-[1] flex gap-4 items-center justify-between"> <label htmlFor="year" className="font-bold"> Year </label> <select ref={yearInputRef} id="year" className="text-inherit bg-white rounded-md w-[70%] p-1 md:w-full border border-solid border-gray-600" > <option value="2021">2021</option> <option value="2022">2022</option> </select> </div> <div className="flex-[1] flex gap-4 items-center justify-between"> <label htmlFor="month" className="font-bold"> Month </label> <select ref={monthInputRef} id="month" className="text-inherit bg-white rounded-md w-[70%] p-1 md:w-full border border-solid border-gray-600" > <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> </div> </div> <Button>Find Events</Button> </form> ); } export default EventsSearch;
import { apiSlice } from "../api/apiSlice"; import { userLoggedIn } from "./authSlice"; export const authApi = apiSlice.injectEndpoints({ endpoints: (builder) => ({ register: builder.mutation({ query: (data) => ({ url: "/register", method: "POST", body: data }), async onQueryStarted(arg, { queryFulfilled, dispatch }) { try { const result = await queryFulfilled; // set loggedInd user data on localStorage localStorage.setItem("auth", JSON.stringify({ accessToken: result.data.accessToken, user: result.data.user }) ); // set loggedInd user data on redux storage dispatch(userLoggedIn({ accessToken: result.data.accessToken, user: result.data.user })); } catch (error) { // not need to do anything here for error } } }), login: builder.mutation({ query: (data) => ({ url: "/login", method: "POST", body: data }), async onQueryStarted(arg, { queryFulfilled, dispatch }) { try { const result = await queryFulfilled; // set loggedInd user data on localStorage localStorage.setItem("auth", JSON.stringify({ accessToken: result.data.accessToken, user: result.data.user }) ); // set loggedInd user data on redux storage dispatch(userLoggedIn({ accessToken: result.data.accessToken, user: result.data.user })) } catch (error) { // not need to do anything here for error } } }), }) }); export const { useRegisterMutation, useLoginMutation } = authApi
const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const { signUpSchema, loginSchema } = require('../validators/auth-validator'); const prisma = require('../models/prisma'); const createError = require('../utils/create-error'); exports.signUp = async (req, res, next) => { try { const { value, error } = signUpSchema.validate(req.body); if (error) { return next(error); } value.password = await bcrypt.hash(value.password, 14); const user = await prisma.user.create({ data: value, }); const payload = { userId: user.id }; const accessToken = jwt.sign( payload, process.env.JWT_SECRET_KEY || 'DoNotTellAnyone', { expiresIn: process.env.JWT_EXPIRE } ); res.status(201).json({ user, accessToken }); } catch (error) { next(error); } }; exports.login = async (req, res, next) => { try { const { value, error } = loginSchema.validate(req.body); if (error) { return next(error); } const user = await prisma.user.findUnique({ where: { email: value.email, }, }); if (!user) { return next(createError('SOMETHING WRONG PLEASE TRY AGAIN', 400)); } const match = await bcrypt.compare(value.password, user.password); if (!match) { return next(createError('SOMETHING WRONG PLEASE TRY AGAIN', 400)); } const payload = { userId: user.id, role: user.role }; const accessToken = jwt.sign( payload, process.env.JWT_SECRET_KEY || 'DoNotTellAnyOne', { expiresIn: process.env.JWT_EXPIRE } ); delete user.password; res.status(201).json({ user, accessToken }); } catch (error) { next(error); } }; exports.getMe = (req, res, next) => { res.status(200).json({ user: req.user }); };
<?php namespace App\Http\Controllers; use App\Models\Project; use Illuminate\Http\Request; use App\Http\Requests\Project\AddNewRequest; use App\Http\Requests\Project\UpdateRequest; use Exception; use File; class ProjectController extends Controller { /** * Display a listing of the resource. */ public function index() { $project = Project::all(); return view('backend.project.index', compact('project')); } /** * Show the form for creating a new resource. */ public function create() { $project = Project::all(); return view('backend.project.create', compact('project')); } /** * Store a newly created resource in storage. */ public function store(AddNewRequest $request) { try { $project = new Project; $project->name = $request->name; $project->category = $request->category; // Handle file upload if ($request->hasFile('file')) { $fileName = rand(111, 999) . time() . '.' . $request->file->extension(); $request->file->move(public_path('uploads/project'), $fileName); $project->file = $fileName; } if ($project->save()) { $this->notice::success('Successfully saved'); return redirect()->route('project.index'); } else { $this->notice::error('Please try again!'); return redirect()->back()->withInput(); } } catch (Exception $e) { $this->notice::error('Please try again'); return redirect()->back()->withInput(); } } /** * Display the specified resource. */ public function show(Project $project) { // } /** * Show the form for editing the specified resource. */ public function edit( $id) { $project = Project::findOrFail(encryptor('decrypt', $id)); return view('backend.project.edit',compact('project')); } /** * Update the specified resource in storage. */ public function update(UpdateRequest $request, $id) { try { $project = Project::findOrFail(encryptor('decrypt', $id)); $project->name = $request->name; $project->category = $request->category; // Handle file upload if ($request->hasFile('file')) { $fileName = rand(111, 999) . time() . '.' . $request->file->extension(); $request->file->move(public_path('uploads/project'), $fileName); $project->file = $fileName; } if ($project->save()) { $this->notice::success('Successfully saved'); return redirect()->route('project.index'); } else { $this->notice::error('Please try again!'); return redirect()->back()->withInput(); } } catch (Exception $e) { $this->notice::error('Please try again'); return redirect()->back()->withInput(); } } /** * Remove the specified resource from storage. */ public function destroy( $id) { $project= Project::findOrFail(encryptor('decrypt', $id)); if($project->delete()){ $this->notice::warning('Deleted Permanently!'); return redirect()->back(); } } }
import unittest import json from app.api import app class TestAPI(unittest.TestCase): def setUp(self): app.testing = True self.app = app.test_client() def test_get_client_data(self): response = self.app.get('/client_data') self.assertEqual(response.status_code, 200) data = json.loads(response.get_data(as_text=True)) self.assertIn('client_data', data) def test_get_list_features(self): response = self.app.get('/get_list_features') self.assertEqual(response.status_code, 200) data = json.loads(response.get_data(as_text=True)) self.assertIn('list_features', data) def test_predict(self): data = { 'features': { 'SK_ID_CURR': 100167 } } response = self.app.post('/predict', json=data) self.assertEqual(response.status_code, 200) data = json.loads(response.get_data(as_text=True)) self.assertIn('prediction', data) def test_get_shap(self): data = { 'features': { 'SK_ID_CURR': 100167 } } response = self.app.post('/get_shap', json=data) self.assertEqual(response.status_code, 200) data = json.loads(response.get_data(as_text=True)) self.assertIn('shap_values', data) if __name__ == '__main__': app.load_client_data() unittest.main()
#include"Texture.h" Texture::Texture(std::string image, std::string texType, GLuint slot, bool flip) { SetupTexture(image, texType, slot, flip); } void Texture::SetupTexture(std::string image, std::string texType, GLuint slot, bool flip) { // Assigns the type of the texture ot the texture object type = texType; fileDir = image; // The width and height is obtained from the image itself. int widthImg, heightImg, numColCh; stbi_set_flip_vertically_on_load(flip); // STBI has inverse axis to OpenGl so flip the image. unsigned char* bytes = stbi_load(image.c_str(), &widthImg, &heightImg, &numColCh, 0); // Convert the image into bytes if (bytes) { GLenum format = GL_RGBA; if (numColCh == 1) format = GL_RED; else if (numColCh == 3) format = GL_RGB; else if (numColCh == 4) format = GL_RGBA; glGenTextures(1, &ID); // Gen a texture object //glActiveTexture(GL_TEXTURE0 + slot); // Activate the texture object unit = slot; glBindTexture(GL_TEXTURE_2D, ID);// Bind it so we can edit it glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR); // Add properties to the texture. Such as nearest Neighbour glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // STL is XYZ // Set the wrapping types. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, widthImg, heightImg, 0, format, GL_UNSIGNED_BYTE, bytes);// Apply the image bytes to the texture to display. glGenerateMipmap(GL_TEXTURE_2D); // Generate mipmaps from the texture. So it can be displayed at different distances etc. // Deletes the image data as it is already in the OpenGL Texture object stbi_image_free(bytes); // Unbinds the OpenGL Texture object so that it can't accidentally be modified glBindTexture(GL_TEXTURE_2D, 0); std::cout << "-------------- Texture [Loaded] : " << fileDir << std::endl; } else std::cout << "Failed to load texture" << std::endl; } void Texture::texUnit(Shader& shader, const char* uniform, GLuint unit) { // Gets the location of the uniform GLuint texUni = glGetUniformLocation(shader.ID, uniform); // Shader needs to be activated before changing the value of a uniform shader.Activate(); // Sets the value of the uniform glUniform1i(texUni, unit); } void Texture::Bind() { glActiveTexture(GL_TEXTURE0 + unit); glBindTexture(GL_TEXTURE_2D, ID); } void Texture::Unbind() { glBindTexture(GL_TEXTURE_2D, 0); } void Texture::Delete() { glDeleteTextures(1, &ID); }
#!/usr/bin/python3 """Creates a model for storing object creation to mysql database """ import models from models.parent_model import Base from sqlalchemy.orm import sessionmaker, scoped_session from sqlalchemy import create_engine from os import getenv from models.user import User from models.event import Event from models.hair_style import HairStyle from models.dress import Dress from models.makeup_style import MakeupStyle classes = {"Dress": Dress, "Event": Event, "MakeupStyle": MakeupStyle, "HairStyle": HairStyle, "User": User} class DBStorage: """Creates a storage class using ORM and MySQLdb """ __session = None __engine = None def __init__(self): """Instantiate object with state attributes""" password = getenv("DRESS_ME_MYSQL_PWD") localhost = getenv("DRESS_ME_MYSQL_HOST") db_name = getenv("DRESS_ME_MYSQL_DB") db_user = getenv("DRESS_ME_MYSQL_USER") self.__engine = create_engine( 'mysql+mysqldb://{}:{}@{}/{}'.format( db_user, password, localhost, db_name), pool_pre_ping=True) def all(self, cls=None): """A method that returns all class object""" db_object = {} if cls is not None: # Querying all the objects of a particular class objs = self.__session.query(cls).all() for obj in objs: class_name = obj.__class__.__name__ key = f"{class_name}.{obj.id}" db_object[key] = obj else: for key, value in models.classes.items(): objs = self.__session.query(value).all() for obj in objs: obj_key = f"{key}.{obj.id}" db_object[obj_key] = obj return db_object def reload(self): """Starts a session for the sqlalchemy""" Base.metadata.create_all(self.__engine) session_factory = sessionmaker(bind=self.__engine, expire_on_commit=False) self.__session = scoped_session(session_factory) def new(self, obj=None): """Adds an instance to a database""" self.__session.add(obj) def save(self): """Stores an object in the database""" self.__session.commit() def delete(self, obj=None): """Removes an object from the database""" self.__session.delete(obj) def close(self): """Closes an open session""" self.__session.close() def get(self, cls, name): """ Returns the object based on the class name and its ID, or None if not found """ if cls not in classes.values(): return None all_cls = models.storage.all(cls) for value in all_cls.values(): if (value.name == name): return value return None
import Head from 'next/head' import { GetServerSideProps } from 'next' import WritersCarousel from '@/components/WritersCarousel' import { httpService } from '@/services/http.service' import { Writer } from '@/interfaces/writer.model' import { writerService } from '@/services/writer.service' interface Props { writers: Writer[] totalPages: number currentPage: number } export default function Home(props: Props) { return ( <> <Head> <title>WritersCarousel</title> <meta name='description' content='A Challange given by Israel-Hayom' /> <meta name='viewport' content='width=device-width, initial-scale=1' /> <link rel='icon' href='/favicon.ico' /> </Head> <main> <WritersCarousel writers={props.writers} totalPages={props.totalPages} currPage={props.currentPage} /> </main> </> ) } export const getServerSideProps: GetServerSideProps = async () => { try { const data = await writerService.loadWriters() return { props: { writers: data.writers || [], totalPages: data.totalPages || 0, currentPage: data.currentPage || 0, }, } } catch (err) { return { props: { writers: [], totalPages: 0, currentPage: 0, }, } } }
import UserModel from '../../models/user.model' import db from '../../database' import User from '../../types/user.type' const userModel = new UserModel() describe('User Model', () => { describe('Test Methods exists', () => { it('should have Create user method', () => { expect(userModel.create).toBeDefined() }) it('should have Update one user method', () => { expect(userModel.updateOne).toBeDefined() }) it('should have Delete one user method', () => { expect(userModel.deleteOne).toBeDefined() }) it('should have Get many Users method', () => { expect(userModel.getMany).toBeDefined() }) it('should have Get one user method', () => { expect(userModel.getOne).toBeDefined() }) }) }) describe('Test User Model ', () => { const testuser = { email: '[email protected]', user_name: 'testUser', first_name: 'Test', last_name: 'User', password: 'test@123', } as User beforeAll(async () => { const newuser = await userModel.create(testuser) testuser.id = newuser.id }) afterAll(async () => { const connection = await db.connect() const sql = 'DELETE FROM users;\n ALTER SEQUENCE users_id_seq RESTART WITH 1;' await connection.query(sql) connection.release() }) it('Create method should return a New User', async () => { const seconduser = await userModel.create({ email: '[email protected]', user_name: 'testUser2', first_name: 'second', last_name: 'User', password: 'test@123', } as User) expect(seconduser).toEqual({ id: 2, email: '[email protected]', user_name: 'testUser2', first_name: 'second', last_name: 'User', } as User) }) it('Check Get many method to return All users in DB', async () => { const users = await userModel.getMany() expect(users.length).toBe(2) }) it('Check Get one method to return testuser from DB', async () => { const calluser = await userModel.getOne(1) expect(calluser.id).toBe(1) expect(calluser.email).toBe(testuser.email) expect(calluser.user_name).toBe(testuser.user_name) expect(calluser.first_name).toBe(testuser.first_name) expect(calluser.last_name).toBe(testuser.last_name) }) it('Check Update one method to update user', async () => { const updatedUser = await userModel.updateOne( { ...testuser, user_name: 'normaluser', first_name: 'new test', }, 1 ) expect(updatedUser.id).toBe(1) expect(updatedUser.email).toBe(testuser.email) expect(updatedUser.user_name).toBe('normaluser') expect(updatedUser.first_name).toBe('new test') expect(updatedUser.last_name).toBe(testuser.last_name) }) it('Check Delete one method to delete the user from DB', async () => { const deleteduser = await userModel.deleteOne(1) expect(deleteduser.id).toBe(1) }) })
import React from 'react' import { useState } from 'react' import { useParams } from 'react-router-dom' import Main from '../layouts/Main' import { ventaDetalleAPI } from '../api/detalleVenta.js' import { useEffect } from 'react' import moment from 'moment' export default function DetalleVenta(props) { const { id } = useParams() const [isLoading, setIsLoading] = useState(true) const [infoVenta, setInfoVenta] = useState([]) const getDetalleVenta = async () => { let result = await ventaDetalleAPI.getProductById(id) setInfoVenta(result.body) } useEffect(() => { if (isLoading) { getDetalleVenta(); setIsLoading(false) } }, [isLoading]) //Impirmir PDF const Imprimir = ()=> { const btnPDF = document.getElementById('btn-pdf'); btnPDF.style.display = "none" window.print() } /* <td>{moment.utc(item.fecha_venta).format('DD/MM/YYYY')}</td> <td>{item.clienteNombre + ' ' + item.clienteApellido}</td> */ var total = 0; var cliente = ''; var fechaVenta = '' return ( <Main title={'Detalle de la venta'} description={'Administrar ventas'}> <div className="tile"> <button className='btn btn-outline-success' id='btn-pdf' onClick={() => Imprimir()}>Imprimir</button> <div className="row"> <div className="col-md-8"> <h3>Factura del cliente</h3> <p>La siguiente factura contiene los productos comprados en esta farmacia</p> </div> <div className="col-md-4"> Fecha de emisión: {moment().format()} </div> </div> <div className="row"> <div className="col-sm-12 col-md-12"> <table className="table table-responsive-sm"> <thead> <tr> <th>#</th> <th>Producto</th> <th>Descripción</th> <th>Precio unitario</th> <th>Descuento</th> </tr> </thead> <tbody> { infoVenta.map((item, index) => { total = item.total_pago cliente = item.nombre + ' ' + item.apellido fechaVenta = item.fecha_venta return <tr key={index}> <td>{item.id}</td> <td>{item.producto}</td> <td>{item.descripcion}</td> <td>${item.precio_venta}</td> <td>{item.descuento}</td> </tr> }) } <tr> <th colSpan={3}> <h5>Total a pagar</h5> </th> <th><h4>${total}</h4></th> </tr> <tr> <th colSpan={0}> <h6>Cliente: </h6> </th> <th><h6>{cliente}</h6></th> </tr> <tr> <th colSpan={0}> <h6>Fecha de venta: </h6> </th> <th><h6>{moment.utc(fechaVenta).format('DD/MM/YYYY')}</h6></th> </tr> </tbody> </table> </div> </div> </div> </Main> ) }
#모집단 3개 이상 # 정규성o ANOVA 분석 # 정규성X 크루스칼-왈리스 검정 #가설검정 순서 # 1. 가설설정 # 2. 유의수준 설정 # 3. 정규성 검정 (집단 모두 정규성을 따를 경우!) # 4. 등분산 검정 # 5. 검정 실시(통계량,p-value 확인) (등분산 여부 확인) # 6. 귀무가설 기각여부 결정 import pandas as pd import numpy as np df = pd.read_csv() #H0: A=B=C #H1: Not H1 from scipy import stats as stats # 3. 정규성 검정 print(stats.shapiro(df['A'])) print(stats.shapiro(df['B'])) print(stats.shapiro(df['C'])) # 4. 등분산성 검정 print(stats.bartlett(df['A'],df['B'],df['C'])) # 5. 검정 실시 statistic, pvalue = stats.f_oneway(df['A'],df['B'],df['C']) ## 정규성X import scipy.stats as stats statistic, pvalue = stats.kruskal(df['A'],df['B'],df['C']) #-----------------------------------------------------------------
{% load static %} <!-- Navbar --> <nav class="main-header navbar navbar-expand-md navbar-light navbar-white"> <div class="container"> <a href="{% url 'dashboard' %}" class="navbar-brand"> <img src="{% static 'images/logobee.png' %}" alt="Bee ERP" class="brand-image img-circle elevation-3" style="opacity: .8"> <span class="brand-text font-weight-light">Bee ERP</span> </a> <button class="navbar-toggler order-1" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse order-3" id="navbarCollapse"> <!-- Left navbar links --> <ul class="navbar-nav"> <li class="nav-item"> <a href="{% url 'dashboard' %}" class="nav-link"><i class="fas fa-home"></i> Inicio</a> </li> <li class="nav-item dropdown"> <a id="dropdownSubMenu1" href="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="nav-link dropdown-toggle"><i class="fas fa-folder-open"></i> Mantenimientos</a> <ul aria-labelledby="dropdownSubMenu1" class="dropdown-menu border-0 shadow"> <li> <a href="{% url 'category_list' %}" class="dropdown-item"><i class="fas fa-truck-loading"></i> Categorías</a> </li> <li> <a href="{% url 'product_list' %}" class="dropdown-item"><i class="fas fa-boxes"></i> Productos</a> </li> <li> <a href="{% url 'client_list' %}" class="dropdown-item"><i class="fas fa-users"></i> Clientes</a> </li> <li> <a href="{% url 'sale_list' %}" class="dropdown-item"><i class="fas fa-shopping-cart"></i> Ventas</a> </li> <li> <a href="{% url 'sale_report' %}" class="dropdown-item"><i class="fas fa-chart-bar"></i> Reportes</a> </li> <li> <a href="{% url 'user:user_list' %}" class="dropdown-item"><i class="fas fa-users"></i> Usuarios</a> </li> </ul> </li> <li class="nav-item"> <a href="/admin" target="_blank" class="nav-link"><i class="fas fa-lock"></i> Admin</a> </li> </ul> <!-- SEARCH FORM --> <form class="form-inline ml-0 ml-md-3"> <div class="input-group input-group-sm"> <input class="form-control form-control-navbar" type="search" placeholder="Buscar" aria-label="Search"> <div class="input-group-append"> <button class="btn btn-navbar" type="submit"> <i class="fas fa-search"></i> </button> </div> </div> </form> </div> <!-- Right navbar links --> <ul class="order-1 order-md-3 navbar-nav navbar-no-expand ml-auto"> {% if request.user.groups.all %} <!-- Permisos Dropdown Menu --> <li class="nav-item dropdown"> <a id="dropdownSubMenu1" href="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="nav-link{% if request.user.groups.all.count > 1 %} dropdown-toggle{% endif %}">{{ request.session.group.name }}</a> {% if request.user.groups.all.count > 1 %} <ul aria-labelledby="dropdownSubMenu1" class="dropdown-menu border-0 shadow"> {% for g in request.user.groups.all %} {% if g.id != request.session.group.id %} <li><a href="{% url 'user:user_change_group' g.id %}" class="dropdown-item">{{ g.name }}</a></li> {% endif %} {% endfor %} </ul> {% endif %} </li> {% endif %} <!-- User Dropdown Menu --> <li class="nav-item dropdown"> <a class="nav-link" data-toggle="dropdown" href="#"> <i class="fas fa-user"></i> {{ request.user.username }} </a> <div class="dropdown-menu dropdown-menu-lg dropdown-menu-right"> <span class="dropdown-header"> Último Acceso: {{ request.user.last_login|date:'d \d\e b \d\e Y' }} a hrs. {{ request.user.last_login|date:'H:i' }} </span> <div class="dropdown-divider"></div> <a href="{% url 'user:user_profile' %}" class="dropdown-item"> <i class="fas fa-edit mr-2"></i> Editar perfil </a> <div class="dropdown-divider"></div> <a href="{% url 'user:user_change_password' %}" class="dropdown-item"> <i class="fas fa-lock mr-2"></i> Editar contraseña </a> <div class="dropdown-divider"></div> <a href="{% url 'logout' %}" class="dropdown-item"> <i class="fas fa-power-off mr-2"></i> Cerrar sesión </a> <div class="dropdown-divider"></div> <a href="#" class="dropdown-item dropdown-footer"> <p>Este sistema te permitira realizar diferentes actividades</p> </a> </div> </li> <li class="nav-item"> <a class="nav-link" data-widget="fullscreen" href="#" role="button"> <i class="fas fa-expand-arrows-alt"></i> </a> </li> <li class="nav-item"> <a class="nav-link" data-widget="control-sidebar" data-slide="true" href="#" role="button"> <i class="fas fa-th-large"></i> </a> </li> </ul> </div> </nav> <!-- /.navbar -->
# Input load. Please do not change # setwd("C:/Users/ryanw/OneDrive - Diesel Analytics/Professional/Clients/Apress/Book/Part2_ShapingData/Chapter09/Forecast") `dataset` = read.csv('input.csv', check.names = FALSE, encoding = "UTF-8", blank.lines.skip = FALSE); # Original Script. Please update your script content here and once completed copy below section back to the original editing window # # The following code to create a dataframe and remove duplicated rows is always executed and acts as a preamble for your script: # dataset <- data.frame(Year, Quarter, Month, Day, Lamar Jackson) # dataset <- unique(dataset) # Paste or type your script code here: library(tidyverse) library(prophet) library(ggthemes) library(gridExtra) library(lubridate) library(rlang) # I needed to load rlang. Look into this package. currentColumns <- sort(colnames(dataset)) requiredColumns <- c("Date", "Page Views", "Page Views (Log10)", "Quarterback") columnTest <- isTRUE(all.equal(currentColumns, requiredColumns)) qb <- unique(dataset$Quarterback) if (length(qb) == 1 & columnTest) { chartTitle <- paste0(qb, "'s Wikipedia page views forecast analysis") dfPageViews <- dataset %>% mutate(Date = ymd(Date)) %>% rename(ds = Date, y = `Page Views (Log10)`) m <- prophet(dfPageViews, yearly.seasonality=TRUE) future <- make_future_dataframe(m, periods = 365) forecast <- predict(m, future) p1 <- plot(m, forecast) + ggtitle(chartTitle) + theme_few() p <- prophet_plot_components(m, forecast) p2 <- p[[1]] + theme_few() p3 <- p[[2]] + theme_few() p4 <- p[[3]] + theme_few() p5 <- grid.arrange(p1, p2, p3, p4, nrow =4) p5 } else { plot.new() title("The data supplied did not meet the requirements of the chart.") }
// ignore_for_file: avoid_print, unused_field import 'package:flutter/foundation.dart'; import 'package:logger/logger.dart'; enum _Colors { black('\x1B[30m'), red('\x1B[31m'), green('\x1B[32m'), yellow('\x1B[33m'), blue('\x1B[34m'), magent('\x1B[35m'), cyan('\x1B[36m'), white('\x1B[37m'), reset('\x1B[0m'); final String ansiCode; const _Colors(this.ansiCode); } mixin LoggerMixin<T> on Object { late final logger = Logger(printer: _MyPrinter(runtimeType.toString())); } class _MyPrinter extends LogPrinter { _MyPrinter(this.printerName); final String printerName; @override List<String> log(LogEvent event) { final isImportant = event.level.value > 3000; final message = isImportant ? '${_Colors.red.ansiCode}${event.message.toString()}${_Colors.reset.ansiCode}' : event.message.toString(); final text = (kDebugMode || isImportant) ? ['➡ $printerName', message, '\r\n'] : <String>[]; return text; } }
package com.multicampus.matchcode.controller.keitian; import com.multicampus.matchcode.model.entity.MemberDTO; import com.multicampus.matchcode.model.request.keitian.LoginRequest; import com.multicampus.matchcode.model.request.keitian.RegisterRequest; import com.multicampus.matchcode.service.keitian.MemberService; import com.multicampus.matchcode.util.component.MailComponent; import com.multicampus.matchcode.util.constants.SessionConstant; import com.multicampus.matchcode.util.constants.StringConstant; import com.nimbusds.jose.shaded.gson.JsonObject; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; @Controller public class MemberController { @Autowired MemberService service; @Autowired MailComponent mailComponent; @GetMapping("login") public String gMemberLogin(@SessionAttribute(name = SessionConstant.MEMBER_DTO, required = false) MemberDTO dto) { if (dto == null) { return "keitian/login"; } else { return "index"; } } @GetMapping("register") public String gMemberRegister(@SessionAttribute(name = SessionConstant.MEMBER_DTO, required = false) MemberDTO dto) { if (dto == null) { return "keitian/register"; } else { return "redirect:"; } } @GetMapping("logout") public String gMemberLogout(HttpServletRequest request) { request .getSession() .setAttribute(SessionConstant.MEMBER_DTO, null); return "redirect:"; } @PostMapping("login") public String pMemberLogin(HttpServletRequest hRequest, LoginRequest request) { HttpSession session = hRequest.getSession(true); MemberDTO dto = service.getId(request.getAccount(), request.getPassword()); if (dto != null) { session.setAttribute(SessionConstant.MEMBER_DTO, dto); } else { return "keitian/login"; } return "redirect:"; } @PostMapping("register") public String pMemberRegister(RegisterRequest request) { if (request.isVerifyied() && request.isAccountNotDup()) { service.insert(request); return "redirect:"; } return "keitian/register"; } @PostMapping("register/accountduplicationcheck") @ResponseBody public boolean pAccountNotDupe(@RequestParam String account) { return service .isAccountDup(account) .isEmpty(); } @PostMapping("register/emailverifying") @ResponseBody public String pMemberRegisterEmailVerify(HttpServletRequest hRequest, @RequestParam String mailAddress) { String verifyString = mailComponent.sendVerifyingMail(mailAddress); if (verifyString != null) { hRequest .getSession(false) .setAttribute(SessionConstant.VERIFY_STRING, verifyString); return "메일이 정상 발송되었습니다."; } return "메일 발송중 오류가 발생했습니다."; } @PostMapping("register/verifyingcheck") @ResponseBody public Boolean pMemberVerifyingCheck( @SessionAttribute(name = SessionConstant.VERIFY_STRING, required = true) String verifyString, @RequestParam String inputString ) { return verifyString.equals(inputString); } @GetMapping("findpassword") public String gFindpw() { return "keitian/findpw"; } @PostMapping("findpassword/requestpassword") @ResponseBody public String pFindpw(String account, String mailAddress) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("noAccount", StringConstant.NO_ACCOUNT); jsonObject.addProperty("noMatchEmail", StringConstant.NO_MATCH_EMAIL); jsonObject.addProperty("tempPassword", service.findPassword(account, mailAddress)); return jsonObject.toString(); } @GetMapping("changepassword") public String gChangePassword() { return "keitian/changepassword"; } @PostMapping("changepassword/requestchange") @ResponseBody public boolean pChangePassword( @SessionAttribute(name = SessionConstant.MEMBER_DTO) MemberDTO dto, String oldPassword, String newPassword ) { return service.changePassword(dto, oldPassword, newPassword); } }
import { Component, OnInit } from '@angular/core'; import {DiaDiemService} from "../service/dia-diem.service"; import {CarService} from "../service/car.service"; import {DiaDiem} from "../model/dia-diem"; import {FormControl, FormGroup, Validators} from "@angular/forms"; import {Router} from "@angular/router"; import {Car} from "../model/car"; @Component({ selector: 'app-car-create', templateUrl: './car-create.component.html', styleUrls: ['./car-create.component.css'] }) export class CarCreateComponent implements OnInit { address: DiaDiem[] = []; carCreate: FormGroup; constructor(private diaDiemService: DiaDiemService, private carService: CarService, private router: Router) { this.carCreate = new FormGroup({ id: new FormControl(""), soXe: new FormControl(""), loaiXe: new FormControl("", [Validators.required]), tenNhaXe: new FormControl("", [Validators.required]), diemDi: new FormGroup({ id: new FormControl("", [Validators.required]) }), diemDen: new FormGroup({ id: new FormControl("", [Validators.required]) }), soDienThoai: new FormControl("", [Validators.required]), email: new FormControl("", [Validators.required, Validators.email]), gioDi: new FormControl("", [Validators.required]), gioDen: new FormControl("", [Validators.required]), trangThai: new FormControl(""), }) } ngOnInit(): void { this.getAllAddress() } getAllAddress(){ this.diaDiemService.findAll().subscribe(n => { this.address = n; }) } create() { const createCar: Car = this.carCreate.value; this.carService.create(createCar).subscribe(n => { this.router.navigateByUrl(""); },error => { console.log(1321) }) } }
import { HttpClient } from "@angular/common/http"; import { Injectable } from "@angular/core"; import { environment } from "@fridge-to-plate/app/environments/utils"; import { IMealPlan } from "@fridge-to-plate/app/meal-plan/utils"; import { Store } from "@ngxs/store"; import { ShowError } from "@fridge-to-plate/app/error/utils"; import { Observable } from "rxjs"; import { IIngredient } from "@fridge-to-plate/app/ingredient/utils"; @Injectable({ providedIn: 'root' }) export class MealPlanAPI { private baseUrl = environment.API_URL + '/meal-plans'; constructor( private http: HttpClient, private store: Store ){ } saveMealPlan(mealPlan: IMealPlan){ const url = this.baseUrl + '/save'; return this.http.post<IMealPlan>(url, mealPlan).subscribe({ error: error => { this.store.dispatch(new ShowError('Error occured when updating meal plan')); } }); } getMealPlanShoppingList(mealPlan: IMealPlan | null): Observable<IIngredient[]> { const url = `${this.baseUrl}/ingredients`; return this.http.post<IIngredient[]>(url, mealPlan); } getMealPlan(date: string, username: string) { const url = `${this.baseUrl}/${username}/${date}`; return this.http.get<IMealPlan>(url); } }
<?php namespace App\Models; use App\Models\Scope\TranslationScope; use Dimsav\Translatable\Translatable; use Baum\Node; use File; use Image; class Category extends Node { use Translatable; use TranslationScope; protected $table = 'dv_categories'; protected $fillable = [ 'parent_id', 'lft', 'rgt', 'depth', 'slug', 'image', 'show_block_1', 'show_block_2', 'show_block_3', 'gradient', ]; public $translatedAttributes = [ 'name', 'body', 'meta_title', 'meta_keywords', 'meta_description', ]; protected static $res = []; public function products() { return $this->hasMany('App\Models\ProductsCategories', 'category_id'); } public static function categories_tree() { $categories = self::all(); foreach ($categories as &$item) { $categories_tree[$item->parent_id][] = &$item; } unset($item); foreach ($categories as &$item) { if (isset($categories_tree[$item->id])) { $item['subcategories'] = $categories_tree[$item->id]; } } return reset($categories_tree); } public static function clearRes() { self::$res = []; } public static function get_parent_categories($id) { $category = self::find($id); if (isset($category->parent_id) && $category->parent_id != 0) { array_push(self::$res, $category); self::get_parent_categories($category->parent_id); } else { array_push(self::$res, $category); } return array_reverse(self::$res); } public static function saveImage($image, $id) { $filename = time().'.'.$image->getClientOriginalExtension(); $img = Image::make($image->getRealPath()); $img->fit(263, 325)->save(public_path('uploads/category/'.$filename)); self::find($id)->update(['image' => $filename]); } public static function updateImage($image, $id) { $old_filename = self::find($id)->image; File::delete(public_path().'/uploads/category/'.$old_filename); self::saveImage($image, $id); } public static function destroy($ids) { $post = self::whereIn('id', $ids)->get(); foreach ($post as $p) { File::delete(public_path().'/uploads/category/'.$p->image); } parent::destroy($ids); } }
import { Global, Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { SignupModule } from './modules/signup/signup.module'; import { PrismaService } from './modules/prisma/prisma.service'; import { SigninModule } from './modules/signin/signin.module'; import { JwtStrategy } from './modules/strategies/jwt.strategy'; import { SignoutModule } from './modules/signout/signout.module'; import { DashboardModule } from './modules/dashboard/dashboard.module'; import { HomeModule } from './modules/home/home.module'; import { ForgetemailModule } from './modules/forgetemail/forgetemail.module'; import { MailerModule } from '@nestjs-modules/mailer'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { EjsAdapter } from '@nestjs-modules/mailer/dist/adapters/ejs.adapter'; import { join } from 'path'; @Global() @Module({ imports: [SignupModule, SigninModule, SignoutModule, DashboardModule, HomeModule, ForgetemailModule , ConfigModule.forRoot({ isGlobal: true, }), // MailerModule.forRoot({ // transport: 'smtps://[email protected]:[email protected]', // template: { // dir: join(__dirname, 'templates'), // adapter: new EjsAdapter(), // options: { // strict: false, // }, // }, // }) ], controllers: [AppController], providers: [AppService, PrismaService, JwtStrategy], }) export class AppModule { }
// Copyright (c) 2012, Unwrong Ltd. http://www.unwrong.com // All rights reserved. package core.appEx.managers.fileSystemProviders.azureAIR { import flash.events.ErrorEvent; import flash.events.Event; import flash.net.URLLoader; import core.app.core.managers.fileSystemProviders.operations.IDoesFileExistOperation; import core.app.core.managers.fileSystemProviders.operations.IGetDirectoryContentsOperation; import core.app.entities.URI; import core.app.events.FileSystemErrorCodes; internal class DoesFileExistOperation extends AzureFileSystemProviderOperation implements IDoesFileExistOperation { private var loader :URLLoader; private var _fileExists :Boolean; public function DoesFileExistOperation( uri:URI, endPoint:String, sas:String, fileSystemProvider:AzureFileSystemProviderAIR ) { super(uri, endPoint, sas, fileSystemProvider); } override public function execute():void { var folder:URI = _uri.getParentURI(); var getDirectoryContentsOperation:IGetDirectoryContentsOperation = _fileSystemProvider.getDirectoryContents(folder); getDirectoryContentsOperation.addEventListener(Event.COMPLETE, doesFileExistCompleteHandler); getDirectoryContentsOperation.addEventListener(ErrorEvent.ERROR, doesFileExistErrorHandler); getDirectoryContentsOperation.execute(); } private function doesFileExistErrorHandler( event:ErrorEvent ):void { dispatchEvent( new ErrorEvent( ErrorEvent.ERROR, false, false, event.text, FileSystemErrorCodes.DOES_FILE_EXIST_ERROR ) ); } private function doesFileExistCompleteHandler( event:Event ):void { var contents:Vector.<URI> = IGetDirectoryContentsOperation(event.target).contents; _fileExists = false; for each ( var childURI:URI in contents ) { if ( childURI.path == _uri.path ) { _fileExists = true; break; } } dispatchEvent( new Event( Event.COMPLETE ) ); } public function get fileExists():Boolean { return _fileExists; } override public function get label():String { return "Does File Exist : " + _uri.path; } } }
import { Component, OnInit, ViewChild } from '@angular/core'; import { UntypedFormBuilder, UntypedFormControl, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { ApiItemResponse } from '@frontend/common'; import { Dictionary } from '@frontend/models/dictionary.model'; import { ReadingContent, ReadingContentType } from '@frontend/models/reading-content.model'; import * as ShellSelectors from '@frontend/shell/shell.selectors'; import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy'; import { Store } from '@ngrx/store'; import { TranslateService } from '@ngx-translate/core'; import { NgxFormManager, NgxFormrAnchorComponent } from '@ngxform/platform'; import { NotificationService } from '@shared/components/notification/notification.service'; import { SelectControlComponent, TextControlComponent, TinymceControlComponent } from '@webpress/form'; import { plainToInstance } from 'class-transformer'; import { filter } from 'rxjs'; import { ReadingContentService } from '../../../service/reading-content.service'; import { UpdateReadingContentDto } from '../../types'; @UntilDestroy() @Component({ selector: 'app-edit-reading-content', templateUrl: './edit-reading-content.component.html', styleUrls: ['./edit-reading-content.component.scss'], }) export class EditReadingContentComponent implements OnInit { public readingContentId!: number; public readingContent!: ReadingContent; public form = this.fb.group({ title: new UntypedFormControl(null, [Validators.required]), content: new UntypedFormControl(null, [Validators.required]), category: new UntypedFormControl(null, [Validators.required]), type: new UntypedFormControl(null, [Validators.required]), }); public dictionary!: Dictionary; @ViewChild('formInputs', { static: true }) formInputs!: NgxFormrAnchorComponent; constructor( private router: Router, private activatedRoute: ActivatedRoute, private fb: UntypedFormBuilder, private ngxFormManager: NgxFormManager, private readingContentService: ReadingContentService, private store: Store, private notificationService: NotificationService, private translate: TranslateService, ) { } ngOnInit(): void { this.store.select(ShellSelectors.getDictionary) .pipe( untilDestroyed(this), filter(dictionary => dictionary !== undefined) ) .subscribe((dictionary) => { this.dictionary = plainToInstance(Dictionary, dictionary); this.readingContentId = Number(this.activatedRoute.snapshot.params['readingContentId']); this.readingContentService.show(this.readingContentId) .subscribe((result: ApiItemResponse<ReadingContent>) => { this.readingContent = plainToInstance(ReadingContent, result.data); this.form.setValue({ title: this.readingContent.title, content: this.readingContent.content, category: this.dictionary.category.find(item => item.id === this.readingContent.categoryId) ?? null, type: this.readingContent.type, }) const ngxForm = this.ngxFormManager.init(this.form, { title: { component: TextControlComponent, option: { nzSize: 'large', label: 'Tiêu đề', className: ['col-12', 'p-1'] } }, content: { component: TinymceControlComponent, option: { nzSize: 'large', label: "Nội dung", className: ['col-12', 'p-1'] } }, category: { component: SelectControlComponent, option: { nzSize: 'large', type: 'text', label: 'Danh mục', className: ['col-12', 'p-1'], nzOptions: this.dictionary.category.map(item => ({ label: item.name, value: item })) } }, type: { component: SelectControlComponent, option: { nzSize: 'large', type: 'text', label: 'Phân loại', className: ['col-12', 'p-1'], nzOptions: [{ label: 'Điền từ', value: ReadingContentType.fillWord }, { label: 'Bài đọc', value: ReadingContentType.readings }] } }, }); this.ngxFormManager.render(ngxForm, this.formInputs.viewContainerRef); }) }); } onSubmit() { if (this.form.invalid) { this.ngxFormManager.markAllAsDirty(this.form); } else { const data: UpdateReadingContentDto = { title: this.form.get('title')?.value, content: this.form.get('content')?.value, categoryId: this.form.get('category')?.value?.id, type: this.form.get('type')?.value, } this.readingContentService.update<UpdateReadingContentDto>(this.readingContentId, data) .subscribe(() => { this.notificationService.success( this.translate.instant('success.title'), this.translate.instant('success.update'), { nzDuration: 3000 } ) this.router.navigate(['/', 'admin', 'exam-manager', 'reading-content']); }) } } }
import { NgModule } from '@angular/core' import { RouterModule } from '@angular/router' import { PlaceListComponent } from 'src/app/pages/operation/place/place-list/place-list.component' import { PlaceEditComponent } from 'src/app/pages/operation/place/place-edit/place-edit.component' import { AuthGuard } from 'src/app/services/auth.guard' const routesPlace = [ { path: "", component: PlaceListComponent, canActivate: [AuthGuard], }, { path: "new", component: PlaceEditComponent, canActivate: [AuthGuard], }, { path: "new/:id", component: PlaceEditComponent, canActivate: [AuthGuard], }, { path: "edit/:id", component: PlaceEditComponent, canActivate: [AuthGuard], }, { path: "view/:id", component: PlaceEditComponent, canActivate: [AuthGuard], }, ] @NgModule({ declarations: [], imports: [ [RouterModule.forChild(routesPlace)] ], exports: [RouterModule] }) export class PlaceModule { }
package com.uogames.foodiestest.domain.model import androidx.annotation.DrawableRes import androidx.annotation.StringRes import com.uogames.foodiestest.R enum class PriceTag(@DrawableRes val icon: Int, @StringRes val description: Int, val id: Int) { DEFAULT(0, R.string.default_type, 0), DISCOUNT(R.drawable.ic_discount, R.string.newest, 1), SPICY(R.drawable.ic_spicy, R.string.spicy, 4), VEGETARIAN(R.drawable.ic_vegetarian, R.string.vegetarian, 2), HIT(R.drawable.ic_discount, R.string.hit, 3), EXPRESS(R.drawable.ic_discount, R.string.express, 5); companion object { fun getByName(string: String): PriceTag = runCatching { valueOf(string) }.getOrNull() ?: DEFAULT fun getByID(id: Int): PriceTag = entries.firstOrNull { it.id == id } ?: DEFAULT } }
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package alloydbconn import ( "context" "crypto/rand" "crypto/rsa" "crypto/tls" _ "embed" "encoding/binary" "errors" "fmt" "net" "strings" "sync" "sync/atomic" "time" alloydbadmin "cloud.google.com/go/alloydb/apiv1beta" "cloud.google.com/go/alloydb/connectors/apiv1beta/connectorspb" "cloud.google.com/go/alloydbconn/errtype" "cloud.google.com/go/alloydbconn/internal/alloydb" "cloud.google.com/go/alloydbconn/internal/trace" "github.com/google/uuid" "golang.org/x/net/proxy" "golang.org/x/oauth2" "golang.org/x/oauth2/google" "google.golang.org/api/option" "google.golang.org/protobuf/proto" ) const ( // defaultTCPKeepAlive is the default keep alive value used on connections // to a AlloyDB instance defaultTCPKeepAlive = 30 * time.Second // serverProxyPort is the port the server-side proxy receives connections on. serverProxyPort = "5433" // ioTimeout is the maximum amount of time to wait before aborting a // metadata exhange ioTimeout = 30 * time.Second ) var ( // versionString indicates the version of this library. //go:embed version.txt versionString string userAgent = "alloydb-go-connector/" + strings.TrimSpace(versionString) // defaultKey is the default RSA public/private keypair used by the clients. defaultKey *rsa.PrivateKey defaultKeyErr error keyOnce sync.Once ) func getDefaultKeys() (*rsa.PrivateKey, error) { keyOnce.Do(func() { defaultKey, defaultKeyErr = rsa.GenerateKey(rand.Reader, 2048) }) return defaultKey, defaultKeyErr } // A Dialer is used to create connections to AlloyDB instance. // // Use NewDialer to initialize a Dialer. type Dialer struct { lock sync.RWMutex // instances map instance URIs to *alloydb.Instance types instances map[alloydb.InstanceURI]*alloydb.Instance key *rsa.PrivateKey refreshTimeout time.Duration client *alloydbadmin.AlloyDBAdminClient // defaultDialCfg holds the constructor level DialOptions, so that it can // be copied and mutated by the Dial function. defaultDialCfg dialCfg // dialerID uniquely identifies a Dialer. Used for monitoring purposes, // *only* when a client has configured OpenCensus exporters. dialerID string // dialFunc is the function used to connect to the address on the named // network. By default it is golang.org/x/net/proxy#Dial. dialFunc func(cxt context.Context, network, addr string) (net.Conn, error) useIAMAuthN bool iamTokenSource oauth2.TokenSource userAgent string buffer *buffer } // NewDialer creates a new Dialer. // // Initial calls to NewDialer make take longer than normal because generation of an // RSA keypair is performed. Calls with a WithRSAKeyPair DialOption or after a default // RSA keypair is generated will be faster. func NewDialer(ctx context.Context, opts ...Option) (*Dialer, error) { cfg := &dialerConfig{ refreshTimeout: alloydb.RefreshTimeout, dialFunc: proxy.Dial, userAgents: []string{userAgent}, } for _, opt := range opts { opt(cfg) if cfg.err != nil { return nil, cfg.err } } userAgent := strings.Join(cfg.userAgents, " ") // Add this to the end to make sure it's not overridden cfg.adminOpts = append(cfg.adminOpts, option.WithUserAgent(userAgent)) if cfg.rsaKey == nil { key, err := getDefaultKeys() if err != nil { return nil, fmt.Errorf("failed to generate RSA keys: %v", err) } cfg.rsaKey = key } // If no token source is configured, use ADC's token source. ts := cfg.tokenSource if ts == nil { var err error ts, err = google.DefaultTokenSource(ctx, CloudPlatformScope) if err != nil { return nil, err } } client, err := alloydbadmin.NewAlloyDBAdminRESTClient(ctx, cfg.adminOpts...) if err != nil { return nil, fmt.Errorf("failed to create AlloyDB Admin API client: %v", err) } dialCfg := dialCfg{ tcpKeepAlive: defaultTCPKeepAlive, } for _, opt := range cfg.dialOpts { opt(&dialCfg) } if err := trace.InitMetrics(); err != nil { return nil, err } d := &Dialer{ instances: make(map[alloydb.InstanceURI]*alloydb.Instance), key: cfg.rsaKey, refreshTimeout: cfg.refreshTimeout, client: client, defaultDialCfg: dialCfg, dialerID: uuid.New().String(), dialFunc: cfg.dialFunc, useIAMAuthN: cfg.useIAMAuthN, iamTokenSource: ts, userAgent: userAgent, buffer: newBuffer(), } return d, nil } // Dial returns a net.Conn connected to the specified AlloyDB instance. The // instance argument must be the instance's URI, which is in the format // projects/<PROJECT>/locations/<REGION>/clusters/<CLUSTER>/instances/<INSTANCE> func (d *Dialer) Dial(ctx context.Context, instance string, opts ...DialOption) (conn net.Conn, err error) { startTime := time.Now() var endDial trace.EndSpanFunc ctx, endDial = trace.StartSpan(ctx, "cloud.google.com/go/alloydbconn.Dial", trace.AddInstanceName(instance), trace.AddDialerID(d.dialerID), ) defer func() { go trace.RecordDialError(context.Background(), instance, d.dialerID, err) endDial(err) }() cfg := d.defaultDialCfg for _, opt := range opts { opt(&cfg) } inst, err := alloydb.ParseInstURI(instance) if err != nil { return nil, err } var endInfo trace.EndSpanFunc ctx, endInfo = trace.StartSpan(ctx, "cloud.google.com/go/alloydbconn/internal.InstanceInfo") i, err := d.instance(inst) if err != nil { endInfo(err) return nil, err } addr, tlsCfg, err := i.ConnectInfo(ctx) if err != nil { d.removeInstance(i) endInfo(err) return nil, err } endInfo(err) var connectEnd trace.EndSpanFunc ctx, connectEnd = trace.StartSpan(ctx, "cloud.google.com/go/alloydbconn/internal.Connect") defer func() { connectEnd(err) }() addr = net.JoinHostPort(addr, serverProxyPort) f := d.dialFunc if cfg.dialFunc != nil { f = cfg.dialFunc } conn, err = f(ctx, "tcp", addr) if err != nil { // refresh the instance info in case it caused the connection failure i.ForceRefresh() return nil, errtype.NewDialError("failed to dial", i.String(), err) } if c, ok := conn.(*net.TCPConn); ok { if err := c.SetKeepAlive(true); err != nil { return nil, errtype.NewDialError("failed to set keep-alive", i.String(), err) } if err := c.SetKeepAlivePeriod(cfg.tcpKeepAlive); err != nil { return nil, errtype.NewDialError("failed to set keep-alive period", i.String(), err) } } tlsConn := tls.Client(conn, tlsCfg) if err := tlsConn.HandshakeContext(ctx); err != nil { // refresh the instance info in case it caused the handshake failure i.ForceRefresh() _ = tlsConn.Close() // best effort close attempt return nil, errtype.NewDialError("handshake failed", i.String(), err) } // The metadata exchange must occur after the TLS connection is established // to avoid leaking sensitive information. err = d.metadataExchange(tlsConn) if err != nil { _ = tlsConn.Close() // best effort close attempt return nil, err } latency := time.Since(startTime).Milliseconds() go func() { n := atomic.AddUint64(&i.OpenConns, 1) trace.RecordOpenConnections(ctx, int64(n), d.dialerID, i.String()) trace.RecordDialLatency(ctx, instance, d.dialerID, latency) }() return newInstrumentedConn(tlsConn, func() { n := atomic.AddUint64(&i.OpenConns, ^uint64(0)) trace.RecordOpenConnections(context.Background(), int64(n), d.dialerID, i.String()) }), nil } // metadataExchange sends metadata about the connection prior to the database // protocol taking over. The exchange consists of four steps: // // 1. Prepare a MetadataExchangeRequest including the IAM Principal's OAuth2 // token, the user agent, and the requested authentication type. // // 2. Write the size of the message as a big endian uint32 (4 bytes) to the // server followed by the marshaled message. The length does not include the // initial four bytes. // // 3. Read a big endian uint32 (4 bytes) from the server. This is the // MetadataExchangeResponse message length and does not include the initial // four bytes. // // 4. Unmarshal the response using the message length in step 3. If the // response is not OK, return the response's error. If there is no error, the // metadata exchange has succeeded and the connection is complete. // // Subsequent interactions with the server use the database protocol. func (d *Dialer) metadataExchange(conn net.Conn) error { tok, err := d.iamTokenSource.Token() if err != nil { return err } authType := connectorspb.MetadataExchangeRequest_DB_NATIVE if d.useIAMAuthN { authType = connectorspb.MetadataExchangeRequest_AUTO_IAM } req := &connectorspb.MetadataExchangeRequest{ UserAgent: d.userAgent, AuthType: authType, Oauth2Token: tok.AccessToken, } m, err := proto.Marshal(req) if err != nil { return err } b := d.buffer.get() defer d.buffer.put(b) buf := *b reqSize := proto.Size(req) binary.BigEndian.PutUint32(buf, uint32(reqSize)) buf = append(buf[:4], m...) // Set IO deadline before write err = conn.SetDeadline(time.Now().Add(ioTimeout)) if err != nil { return err } defer conn.SetDeadline(time.Time{}) _, err = conn.Write(buf) if err != nil { return err } // Reset IO deadline before read err = conn.SetDeadline(time.Now().Add(ioTimeout)) if err != nil { return err } defer conn.SetDeadline(time.Time{}) buf = buf[:4] _, err = conn.Read(buf) if err != nil { return err } respSize := binary.BigEndian.Uint32(buf) resp := buf[:respSize] _, err = conn.Read(resp) if err != nil { return err } var mdxResp connectorspb.MetadataExchangeResponse err = proto.Unmarshal(resp, &mdxResp) if err != nil { return err } if mdxResp.GetResponseCode() != connectorspb.MetadataExchangeResponse_OK { return errors.New(mdxResp.GetError()) } return nil } const maxMessageSize = 16 * 1024 // 16 kb type buffer struct { pool sync.Pool } func newBuffer() *buffer { return &buffer{ pool: sync.Pool{ New: func() any { buf := make([]byte, maxMessageSize) return &buf }, }, } } func (b *buffer) get() *[]byte { return b.pool.Get().(*[]byte) } func (b *buffer) put(buf *[]byte) { b.pool.Put(buf) } // newInstrumentedConn initializes an instrumentedConn that on closing will // decrement the number of open connects and record the result. func newInstrumentedConn(conn net.Conn, closeFunc func()) *instrumentedConn { return &instrumentedConn{ Conn: conn, closeFunc: closeFunc, } } // instrumentedConn wraps a net.Conn and invokes closeFunc when the connection // is closed. type instrumentedConn struct { net.Conn closeFunc func() } // Close delegates to the underlying net.Conn interface and reports the close // to the provided closeFunc only when Close returns no error. func (i *instrumentedConn) Close() error { err := i.Conn.Close() if err != nil { return err } go i.closeFunc() return nil } // Close closes the Dialer; it prevents the Dialer from refreshing the information // needed to connect. Additional dial operations may succeed until the information // expires. func (d *Dialer) Close() error { d.lock.Lock() defer d.lock.Unlock() for _, i := range d.instances { i.Close() } return nil } func (d *Dialer) instance(instance alloydb.InstanceURI) (*alloydb.Instance, error) { // Check instance cache d.lock.RLock() i, ok := d.instances[instance] d.lock.RUnlock() if !ok { d.lock.Lock() // Recheck to ensure instance wasn't created between locks i, ok = d.instances[instance] if !ok { // Create a new instance var err error i = alloydb.NewInstance(instance, d.client, d.key, d.refreshTimeout, d.dialerID) if err != nil { d.lock.Unlock() return nil, err } d.instances[instance] = i } d.lock.Unlock() } return i, nil } func (d *Dialer) removeInstance(i *alloydb.Instance) { d.lock.Lock() defer d.lock.Unlock() // Stop all background refreshes i.Close() delete(d.instances, i.InstanceURI) }
#pragma once #include <iostream> #include <vector> #include <stdexcept> #include <chrono> #include <thread> #include <cmath> #include <curl/curl.h> #include <nlohmann/json.hpp> #include <nopayloadclient/config.hpp> #include <nopayloadclient/exception.hpp> #include <nopayloadclient/curlwrapper.hpp> namespace nopayloadclient { using nlohmann::json; using std::string; struct Answer { CURLcode res; string readBuffer; long httpCode = 0; }; static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp){ ((std::string*)userp)->append((char*)contents, size * nmemb); return size * nmemb; } class CurlRequest{ public: CurlRequest(const string& url, const json& data = json{}) { url_ = url; json_str_ = data.dump(); curl_ = curl_easy_init(); curl_easy_setopt(curl_, CURLOPT_URL, url_.c_str()); curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &ans_.readBuffer); }; json parseResponse(); int execute(); Answer ans_; protected: CURL *curl_; string url_; string json_str_; }; class GetRequest: public CurlRequest { public: GetRequest(const string& url, const json& data = json{}) : CurlRequest(url, data) { }; }; class DeleteRequest: public CurlRequest { public: DeleteRequest(const string& url, const json& data = json{}) : CurlRequest(url, data) { curl_easy_setopt(curl_, CURLOPT_CUSTOMREQUEST, "DELETE"); }; }; class PostRequest: public CurlRequest { public: PostRequest(const string& _url, const json& data = json{}) : CurlRequest(_url, data) { struct curl_slist *slist = NULL; slist = curl_slist_append(slist, "Content-Type: application/json"); curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, slist); curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, json_str_.c_str()); }; }; class PutRequest: public PostRequest { public: PutRequest(const string& url, const json& data = json{}) : PostRequest(url, data) { curl_easy_setopt(curl_, CURLOPT_CUSTOMREQUEST, "PUT"); }; }; class RealWrapper : public CurlWrapper { private: void sleep(int retry_number); string base_url_; int n_retries_; public: RealWrapper() {}; RealWrapper(const json& config); // Reading json get(const string& url); // Writing json del(const string& url); json put(const string& url); json put(const string& url, const json& data); json post(const string& url, const json& data); template <typename Request> json getResponse(const string& url, const json& data = json{}) { for(int i=0; i<n_retries_; i++) { Request req = Request(base_url_ + url, data); if (req.execute() == 0) return req.parseResponse(); sleep(i); } throw DataBaseException("Request failed after " + std::to_string(n_retries_) + " tries"); } }; } // nopayloadclient namespace
/* eslint-disable import/extensions */ import { PaginationTyping } from '@/types/Pagination'; const usePaginationLogic = ( currentPage: number, postsPerPage: number, totalPosts: number | undefined, ) => { const showingFrom = currentPage * postsPerPage - (postsPerPage - 1); const showingTo = currentPage * postsPerPage; const disableBackBtn = currentPage * postsPerPage - (postsPerPage - 1) === 1; const disableFrontBtn = totalPosts ? (currentPage * postsPerPage >= totalPosts) : true; return { showingFrom, showingTo, disableBackBtn, disableFrontBtn, }; }; export default function Pagination({ postsPerPage, totalPosts, paginateFront, paginateBack, currentPage, isLoading, }: PaginationTyping) { const { showingFrom, showingTo, disableBackBtn, disableFrontBtn, } = usePaginationLogic(currentPage, postsPerPage, totalPosts); return ( <div className={`flex justify-between ${isLoading ? 'hidden' : 'visible'} space-x-1 md:space-x-4 items-center px-2 md:px-0 py-2 mt-4`}> <div> <p className="text-sm text-white"> Showing {' '} <span className="font-medium">{showingFrom}</span> {' '} to <span className="font-medium"> {' '} {showingTo} {' '} </span> of <span className="font-medium"> {' '} {totalPosts} {' '} </span> Results </p> </div> <div> <div className="relative z-0 flex items-center rounded-md bg-cyan-300 shadow-sm" aria-label="Pagination" > <button type="button" onClick={() => { paginateBack(); }} disabled={disableBackBtn} className="pagination_btn rounded-l-md" > Previous </button> <span className="text-blue-900">|</span> <button type="button" onClick={() => { paginateFront(); }} disabled={disableFrontBtn} className="pagination_btn rounded-r-md text-right" > Next </button> </div> </div> </div> ); }
<div class="page-wrapper"> <app-header></app-header> <div class="page-container"> <app-common-page-header [refresh]="refresh" (goBack)="backTo($event)" (sendonClickDirectory)="navigateTo($event)" (refreshOption)="checkcurrentFolder()" ></app-common-page-header> <!-- <div class="folder-wrap row" *ngIf="modulesData.length"> <div class="folder-item col-md-3" *ngFor="let item of modulesData; let i = index" > <div class="folder-card" (click)="isFileView = true"> <div class="folder-card-icon"> <i class="fa-solid fa-folder"></i> </div> <div class="folder-card-text"> {{ item.name }} </div> </div> </div> </div> --> <div class="table-card" *ngIf="!valuePicked"> <table class="table" *ngIf="!spinner && modulesData.length != 0"> <thead> <tr> <!-- <th>#</th> --> <th>Module</th> <!-- class="table-col-width" --> <!-- <th>Size</th> --> <th>Status</th> <th class="table-action"></th> </tr> </thead> <tbody [ngStyle]="{ 'max-height': _sharedService.getTableMaxHeight() + 'px', 'min-height': '200px' }" > <tr *ngFor="let item of modulesData; let i = index"> <!-- <td>{{i + 1}}</td> --> <td> <!-- class="table-col-width" --> <div class="icon-text-set"> <div class="icon"><i class="fa-regular fa-folder"></i></div> <div class="text"> {{ item.name }} </div> </div> </td> <!-- <td> <span class="text-small"> 200 MB </span> </td> --> <td> <span class="badge success" [ngClass]="{ success: item.status == 1, failed: item.status != 1 }" > {{ item.status == 1 ? "Active" : "Inactive" }}</span > <!-- <span class="badge failed">Failed</span> <span class="badge pending">Pending</span> --> </td> <td class="table-action"> <div class="table-action-dropdown dropdown"> <a class="" data-bs-toggle="dropdown" aria-expanded="false"> <button class="btn btn-tertiary btn-xs btn-toggle"> Actions </button> </a> <div class="dropdown-menu dropdown-menu-end"> <ul> <li> <a class="dropdown-item" (click)="clickOnView(item)" >View </a> </li> <li *ngIf="loginType == '1'"> <a class="dropdown-item" data-bs-toggle="modal" data-bs-target="#addNewModal" (click)="clickToAction('update', item)" > Update </a> </li> <li *ngIf="loginType == '1'"> <a class="dropdown-item" data-bs-toggle="modal" data-bs-target="#acdcNewModal" (click)="clickToAction('acdc', item)" > {{ item.status == 1 ? "Deactivate" : "Activate" }} </a> </li> </ul> </div> </div> </td> </tr> </tbody> <tfoot> <div class="pagination-set"> <div class="pagination-set-results"> Entries 1 to {{ modulesData.length }} out of {{ modulesData.length }} </div> <div class="pagination-set-center"> <!-- <ul class="pagination-stage-set"> <li class="pagination-stage-set-item"> </li> </ul> --> <!-- <ul class="pagination"> <li class="page-item"> <a class="page-link" href="#" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> <li class="page-item"><a class="page-link" href="#">1</a></li> <li class="page-item"><a class="page-link" href="#">2</a></li> <li class="page-item"><a class="page-link" href="#">3</a></li> <li class="page-item"> <a class="page-link" href="#" aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> </ul> --> </div> </div> </tfoot> </table> <!-- <app-shimmers *ngIf="spinner"></app-shimmers> --> <app-shimmers type="full" *ngIf="spinner"></app-shimmers> <app-empty-states *ngIf="!spinner && modulesData.length == 0" ></app-empty-states> </div> <app-files [inputData]="valuePicked" *ngIf="valuePicked" (sendData)="filleEmitter()" ></app-files> </div> <app-footer></app-footer> </div> <!-- Modal --> <div class="modal fade" id="addNewModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="addNewModal" aria-hidden="true" > <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="addNewModal"> {{ selectedItem ? "Update" : "Add" }} Module </h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" ></button> </div> <div class="modal-body" *ngIf="!modalSpinner"> <form [formGroup]="moduleForm"> <div class="form-group"> <label for="module-name" class="form-label field-required" >Module name</label > <input type="text" class="form-control" formControlName="name" placeholder="Enter module name" [ngClass]="{ 'is-invalid': moduleForm.controls['name'].invalid && (moduleForm.controls['name'].touched || moduleForm.controls['name'].dirty) }" /> <div class="invalid-feedback" *ngIf=" moduleForm.controls['name'].invalid && (moduleForm.controls['name'].touched || moduleForm.controls['name'].dirty) " > <span *ngIf="moduleForm.controls['name'].errors.required"> Module name is required. </span> <span *ngIf="moduleForm.controls['name'].errors.maxlength"> Module name should not be more than 100 characters. </span> <span *ngIf="moduleForm.controls['name'].errors.minlength"> Module name should be atleast 2 characters. </span> </div> </div> </form> </div> <div class="modal-body" *ngIf="modalSpinner"> <app-shimmers contentText="uploading..."></app-shimmers> </div> <div class="modal-footer" *ngIf="!modalSpinner"> <button type="button" class="btn btn-tertiary-gray btn-sm" data-bs-dismiss="modal" > Cancel </button> <button type="button" class="btn btn-primary btn-sm" (click)="addUpdateModules()" > Submit </button> </div> </div> </div> </div> <!-- Modal --> <div class="modal fade" id="acdcNewModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="acdcNewModal" aria-hidden="true" > <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5"> {{ selectedItem && selectedItem.status == 1 ? "Deactivate" : "Activate" }} Module </h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" ></button> </div> <div class="modal-body" *ngIf="!modalSpinner"> <p>Are you sure you want to change the status of the module?</p> </div> <div class="modal-body" *ngIf="modalSpinner"> <app-shimmers contentText="uploading..."></app-shimmers> </div> <div class="modal-footer" *ngIf="!modalSpinner"> <button type="button" class="btn btn-tertiary-gray btn-sm" data-bs-dismiss="modal" > Cancel </button> <button type="button" class="btn btn-primary btn-sm" (click)="acdcSubmit()" > Submit </button> </div> </div> </div> </div>
/* Purpose: Creating table objects in Flix database */ /* Script Date: June 10, 2022 Developed by: Jingyu An */ -- switch to Flix database -- Syntax: use database_name; use jgflix2022 ; /* create table object - Partial syntax: create table table_name ( column_name data_type constraint(s), column_name data_type constraint(s), ... column_name data_type constraint(s), ) where constraint defines the business rules: not not, null, primary key (pk_), default (df_), check (ck_), unique (uq_), foreign key (fk_) */ /* character data type: char(length) - fixed length varchar(length) - variable length */ /* ***** Table No. 1 - Customers ***** */ create table Customers ( CustID smallint auto_increment not null primary key, CustFN varchar(20) not null, CustMN varchar(20) null, CustLN varchar(20) not null ) ; -- return the definition of the table Customers show columns from Customers ; -- or using describe comman describe Customers ; /* creating the lookup tables */ /* ***** Table No. 2 - Roles ***** */ create table Roles ( RoleID varchar(4) not null, RoleDescrip varchar(30) not null, -- constraint constraint_name constraint_type constraint pk_Roles primary key (RoleID asc) ) ; describe Roles ; /* ***** Table No. 3 - MovieTypes ***** */ create table MovieTypes ( MTypeID varchar(4) not null , MTypeDescrip varchar(30) not null , constraint pk_MovieTypes primary key ( MTypeID asc ) ) ; /* ***** Table No. 4 - Studios ***** */ create table Studios ( StudID varchar(4) not null , StudDescrip varchar(40) not null , constraint pk_Studios primary key (StudID asc ) ) ; /* ***** Table No. 5 - Ratings ***** */ create table Ratings ( RatingID varchar(4) not null , RatingDescrip varchar(30) not null , constraint pk_Ratings primary key (RatingID asc ) ) ; /* ***** Table No. 6 - Formats ***** */ create table Formats ( FormID char(2) not null , FormDescrip varchar(15) not null , constraint pk_Formats primary key (FormID asc ) ) ; /* ***** Table No. 7 - Status ***** */ create table Status ( StatID char(3) not null , StatDescrip varchar(20) not null , constraint pk_Status primary key (StatID asc ) ) ; /* ***** Table No. 8 - Participants ***** */ create table Participants ( PartID smallint auto_increment not null primary key , PartFN varchar(20) not null , PartMN varchar(20) null , PartLN varchar(20) not null ) ; /* ***** Table No. 9 - DVDs ***** */ create table DVDs ( DVDID smallint auto_increment not null primary key, DVDName varchar(60) not null, NumDisks tinyint not null, YearRlsd year not null, MTypeID varchar(4) not null, -- foreign key references to MovieTypes table StudID varchar(4) not null, -- foreign key references to Studios table RatingID varchar(4) not null, -- foreign key references to Ratings table FormID char(2) not null, -- foreign key references to Formats table StatID char(3) not null -- foreign key references to Status table ) ; /* ***** Table No. 10 - DVDParticipants ***** */ create table DVDParticipants ( DVDID smallint not null, -- foreign key references to DVDs table PartID smallint not null, -- foreign key references to Participants table RoleID varchar(4) not null, -- foreign key references to Roles table constraint pk_DVDParticipants primary key ( DVDID asc, PartID asc, RoleID asc ) ) ; describe DVDParticipants ; /* ***** Table No. 11 - Employees ***** */ create table Employees ( EmpID smallint auto_increment not null primary key, EmpFN varchar(20) not null , EmpMN varchar(20) not null , EmpLN varchar(20) not null ) ; /* ***** Table No. 12 - Orders ***** */ create table Orders ( OrderID int auto_increment not null primary key, CustID smallint not null , -- foreign key references to Customers table EmpID smallint not null -- foreign key references to Employees table ) ; /* ***** Table No. 13 - Transactions ***** */ create table Transactions ( TransID int auto_increment not null primary key, OrderID int not null , -- foreign key references to Orders table DVDID smallint not null , -- foreign key references to DVDs table DateOut date not null , DateDue date not null , DateIn date not null ) ;
import Field from "../interfaces/Field"; import escreverArquivo from "../lib/escreverArquivo"; export default class CriadorEvenDispatcher { private dono: string; private aggregate: string; private pacote: string; private importAggregate: string; private path: string; private fields: Field[]; constructor(dono: string, pacote: string, fields: Field[]) { this.dono = dono; this.aggregate = `${this.dono}Aggregate`; this.pacote = `package ${pacote}.event;`; this.importAggregate = `import ${pacote}.aggregate.${dono}Aggregate;`; this.path = `./dados/${dono}/event`; this.fields = fields; } public criar() { const nomeClasse = `${this.dono}Dispatcher`; let eventos: string = ""; this.fields.forEach((field) => { if (field.nome !== "DadosCadastrais") { eventos += this.stringEventos(field); } else { eventos += this.StringEventosDadosCadastrais(field); } }); let str: string = ` ${this.pacote} ${this.importAggregate}; public class ${nomeClasse} { public ${nomeClasse} () {} public static ${nomeClasse} dispatcher(${this.aggregate} aggregate) { return new ${nomeClasse}(); } ${eventos} }`; escreverArquivo(this.path, nomeClasse, str); } private stringEventos(field: Field): string { return ` public void notifyEvent(final ${field.nome}${ field.lista ? "Adicionado" : "Criado" }Event evt) {}${ field.lista ? ` public void notifyEvent(final ${field.nomePlural}AdicionadosEvent evt) {}` : "" } public void notifyEvent(final ${field.nome}AtualizadoEvent evt) {}${ field.lista ? ` public void notifyEvent(final ${field.nomePlural}AtualizadosEvent evt) {}` : "" } public void notifyEvent(final ${field.nome}RemovidoEvent evt) {}${ field.lista ? ` public void notifyEvent(final ${field.nomePlural}RemovidosEvent evt) {}` : "" } `; } private StringEventosDadosCadastrais(field: Field): string { return ` public void notifyEvent(final ${this.dono}CriadoEvent evt) {} public void notifyEvent(final ${field.nome}AtualizadoEvent evt) {} `; } }
package anotacoes.tratamentoDeExcecoes.criacaoDeExcecoes.solucaoRuim; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; import anotacoes.tratamentoDeExcecoes.criacaoDeExcecoes.solucaoRuim.model.entities.ReservationRuim; public class SolucaoRuim { public static void main(String[] args) throws ParseException { Scanner sc = new Scanner(System.in); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); System.out.print("Room number: "); int roomNumber = sc.nextInt(); System.out.print("Check-in date (dd/MM/yyyy): "); Date checkIn = sdf.parse(sc.next()); System.out.print("Check-out date (dd/MM/yyyy): "); Date checkOut = sdf.parse(sc.next()); if (!checkOut.after(checkIn)) { System.out.println("Erro in reservation: Check-out date must be after check-in date"); } else { ReservationRuim reservation = new ReservationRuim(roomNumber, checkIn, checkOut); System.out.println(reservation); System.out.println(); System.out.println("Enter data to update the reservation:"); System.out.print("Check-in date (dd/MM/yyyy): "); checkIn = sdf.parse(sc.next()); System.out.print("Check-out date (dd/MM/yyyy): "); checkOut = sdf.parse(sc.next()); // Solução muito ruim - Lógica inserida no método, que retorna uma String String error = reservation.updateDate(checkIn, checkOut); if (error != null) { System.out.println("Error in reservation: " + error); } else { System.out.println(reservation); } /* * A semântica da operação é prejudicada * *Retornar string não tem nada haver com atualização de reserva * *E se a operação tivesse que retornar uma String? * Ainda não é possível tratar exceções em construtores * Ainda não há auxílio do compilador: o programador deve "lembrar" de verificar * se houve erro * A lógica fica estruturada em condicionais aninhadas */ } sc.close(); } }
<script setup> import { ref, computed, onMounted } from "vue"; import { modifyUserInfo, modifyPassword, userConfirm } from "@/api/user"; import { useMemberStore } from "@/stores/member"; import { httpStatusCode } from "@/util/http-status"; // toRef: pinia 안의 userInfo 가져올 때, 반응형으로 감싸서 가져옴 const memberStore = useMemberStore(); const userInfo = computed(() => memberStore.userInfo); const isUserModify = ref(false); const isPwModify = ref(false); // userInfo 최신화 로직 const fetchUserInfo = async () => { let token = sessionStorage.getItem("accessToken"); await memberStore.getUserInfo(token); }; // 회원정보 클릭 const onUserModify = () => { if(isPwModify.value) isPwModify.value = false; isUserModify.value = !isUserModify.value; }; // 비밀번호 클릭 const onPwModify = () => { if(isUserModify.value) isUserModify.value = false; isPwModify.value = !isPwModify.value; }; // 초기화 클릭 const resetForm = () => { formUserData.value.userName = userInfo.value.userName; formUserData.value.emailId = userInfo.value.emailId; formUserData.value.emailDomain = userInfo.value.emailDomain; formPwData.value.currentPwd = ''; formPwData.value.newPwd = ''; formPwData.value.newPwdcheck = ''; } // 수정 버튼 관련 폼 const formUserData = ref({ userId: userInfo.value.userId, userName: userInfo.value.userName, emailId: userInfo.value.emailId, emailDomain: userInfo.value.emailDomain, }); // 회원정보 -------------------------------------------------- // 회원정보 수정하기 클릭 const onModifyUserInfo = async () => { // 비어있는 input값이 있는 경우 if( formUserData.value.userName === '' || formUserData.value.emailId === '' || formUserData.value.emailDomain === '' ) { alert('회원 정보를 입력해주세요.'); return; } await modifyUserInfo( formUserData.value, async (response) => { alert("회원 정보 수정 완료!"); // userInfo 강제 업데이트 // let token = sessionStorage.getItem("accessToken"); // useMemberStore.getUserInfo(token); await fetchUserInfo(); isUserModify.value = !isUserModify.value; }, (error) => { console.error(error); } ) }; // 비밀번호 -------------------------------------------------------- const formPwData = ref({ currentPwd: '', newPwd: '', newPwdcheck: '', }); // 비밀번호 변경하기 클릭 const onModifyPassword = async () => { // 비어있는 input값이 있는 경우 if( formPwData.value.currentPwd === '' || formPwData.value.newPwd === '' || formPwData.value.newPwdcheck === '' ) { alert('비밀번호를 입력해주세요.'); return; } // 비밀번호 일치하지 않는 경우 if (formPwData.value.newPwd !== formPwData.value.newPwdcheck) { alert('비밀번호를 다시 확인해주세요.'); return; } await modifyPassword( { "userId": userInfo.userId, "currentPwd": formPwData.value.currentPwd, "newPwd": formPwData.value.newPwd, }, (response) => { if (response.status = httpStatusCode.OK) { alert("비밀번호 수정 완료!"); resetForm(); isPwModify.value = !isPwModify.value; } }, (error) => { alert("비밀번호를 확인해주세요."); console.error(error); } ) }; </script> <template> <div class="container"> <div class="row justify-content-center"> <div class="col-lg-8"> <h2 class="my-4 py-3 shadow bg-primary text-white text-center rounded"> 마이페이지 </h2> </div> <div class="col-lg-8"> <div class="card m-auto px-2 py-2"> <div class="row g-2"> <!-- 이미지 부분 --> <div class="col-md-4 d-flex align-items-center justify-content-center"> <img src="@/assets/img/profile-icon.png" class="img-fluid rounded" alt="..." /> </div> <!-- 정보 리스트 부분 --> <div class="col-md-8 d-flex align-items-center"> <div class="w-100"> <ul class="list-group list-group-flush text-center"> <li class="list-group-item">아이디: {{ userInfo.userId }}</li> <li class="list-group-item">이름: {{ userInfo.userName }}</li> <li class="list-group-item">이메일: {{ userInfo.emailId }}@{{ userInfo.emailDomain }}</li> </ul> <div class="mt-auto p-2 d-flex justify-content-end"> <button class="btn btn-outline-primary btn-sm mx-2" @click="onUserModify">회원정보 수정</button> <button class="btn btn-outline-danger btn-sm mx-2" @click="onPwModify">비밀번호 변경</button> </div> </div> </div> </div> </div> </div> <!-- 회원 정보 수정 --> <div class="col-lg-8 mt-4 mb-2" v-show="isUserModify"> <div class="card m-auto px-2 py-2"> <form class="row g-2 p-4"> <!-- 정보 리스트 부분 --> <div class="mb-3 text-start"> <label for="username" class="form-label">이름:</label> <input type="text" class="form-control" id="username" v-model="formUserData.userName" placeholder="이름..." /> </div> <div class="mb-3 text-start"> <label for="emailid" class="form-label">이메일:</label> <div class="input-group"> <input type="text" class="form-control" id="emailid" v-model="formUserData.emailId" placeholder="이메일 아이디" /> <span class="input-group-text">@</span> <select class="form-select" v-model="formUserData.emailDomain" aria-label="이메일 도메인 선택"> <option selected >선택</option> <option value="ssafy.com">싸피</option> <option value="google.com">구글</option> <option value="naver.com">네이버</option> <option value="kakao.com">카카오</option> </select> </div> </div> <div class="text-center"> <button type="button" class="btn btn-warning mb-3" @click="onModifyUserInfo">수정하기</button> <button type="button" class="btn btn-secondary ms-2 mb-3" @click="resetForm">초기화</button> </div> </form> </div> </div> <!-- 비밀번호 변경 --> <div class="col-lg-8 mt-4 mb-2" v-show="isPwModify"> <div class="card m-auto px-2 py-2"> <form class="row g-2 p-4"> <!-- 정보 리스트 부분 --> <div class="mb-3 text-start"> <label for="currentpass" class="form-label">기존 비밀번호:</label> <input type="password" class="form-control" id="currentpass" v-model="formPwData.currentPwd" placeholder="비밀번호..." /> </div> <div class="mb-3 text-start"> <label for="newpass" class="form-label">새 비밀번호:</label> <input type="password" class="form-control" id="newpass" v-model="formPwData.newPwd" placeholder="새 비밀번호..." /> </div> <div class="text-start"> <label for="newpass-check" class="form-label">새 비밀번호 확인:</label> <input type="password" class="form-control" id="newpass-check" v-model="formPwData.newPwdcheck" placeholder="새 비밀번호 확인..." /> </div> <div v-if="formPwData.newPwd === '' || formPwData.newPwdcheck === ''"></div> <div v-else-if="formPwData.newPwd === formPwData.newPwdcheck" class="text-success mb-3">비밀번호가 일치합니다.</div> <div v-else class="text-danger mb-3">비밀번호가 일치하지 않습니다.</div> <div class="text-center"> <button type="button" class="btn btn-warning mb-3" @click="onModifyPassword">변경하기</button> <button type="button" class="btn btn-secondary ms-2 mb-3" @click="resetForm">초기화</button> </div> </form> </div> </div> </div> </div> </template> <style scoped> </style>
import React, { PropsWithChildren } from "react"; import { MemoryRouter } from "react-router-dom"; type Props = { path?: string; } & PropsWithChildren; export const TEST_WRAPPER_ID = "test-wrapper"; const TestWrapper: React.FC<Props> = (props) => { return ( <div data-testid={TEST_WRAPPER_ID}> <MemoryRouter initialEntries={[props.path as string]}> {props.children} </MemoryRouter> </div> ); }; TestWrapper.defaultProps = { path: "/", }; export default TestWrapper;
// iniciarlizar Array com [] vazio -> melhor prática e recomendado var idades = [] // inicializar Array com new Array() -> não é a melhor prática e não recomendado // inicializar Array com new Array() - sem tamanho e valores var daysOfWeek = new Array(); daysOfWeek[0] = 'Sunday' console.log(daysOfWeek[0]) // Sunday // saber tamanho do array console.log(daysOfWeek.length) // 1 // inicializando o Array com new Array() - com tamanho definido var months = new Array(12); console.log(months.length) // 12 // inicializando o Array com new Array() - já com valores var seasons = new Array("Summer", "Fall", "Winter", "Spring"); console.log(seasons.length) // 4 console.log(seasons[2]) // Winter
package com.dotcms.rest.api.v1.apps.view; import com.dotcms.security.apps.AppDescriptor; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import java.util.List; /** * Represents a service integration. Which serves as the top level entry for all the endpoints. * The view unfolds itself in the specifics for the associated sites. */ public class AppView { private final int configurationsCount; private final String key; private final String name; private final String description; private final String iconUrl; private final boolean allowExtraParams; @JsonInclude(Include.NON_NULL) private final Integer sitesWithWarnings; @JsonInclude(Include.NON_NULL) private final List<SiteView> sites; /** * Used to build a site-less integration view * @param appDescriptor * @param configurationsCount */ public AppView(final AppDescriptor appDescriptor, final int configurationsCount, final int sitesWithWarnings) { this.key = appDescriptor.getKey(); this.name = appDescriptor.getName(); this.description = appDescriptor.getDescription(); this.iconUrl = appDescriptor.getIconUrl(); this.allowExtraParams = appDescriptor.isAllowExtraParameters(); this.configurationsCount = configurationsCount; this.sitesWithWarnings = sitesWithWarnings == 0 ? null : sitesWithWarnings; this.sites = null; } /** * Use to build a more detailed integration view * Including site specific config info. * @param appDescriptor * @param configurationsCount * @param sites */ public AppView(final AppDescriptor appDescriptor, final int configurationsCount, final List<SiteView> sites) { this.key = appDescriptor.getKey(); this.name = appDescriptor.getName(); this.description = appDescriptor.getDescription(); this.iconUrl = appDescriptor.getIconUrl(); this.allowExtraParams = appDescriptor.isAllowExtraParameters(); this.configurationsCount = configurationsCount; this.sites = sites; this.sitesWithWarnings = null; } /** * number of configuration (Total count) * @return */ public long getConfigurationsCount() { return configurationsCount; } /** * Service unique identifier * @return */ public String getKey() { return key; } /** * any given name * @return */ public String getName() { return name; } /** * Any given description * @return */ public String getDescription() { return description; } /** * The url of the avatar used on the UI * @return */ public String getIconUrl() { return iconUrl; } /** * Whether or not extra params are supported * @return */ public boolean isAllowExtraParams() { return allowExtraParams; } /** * Number of potential issues per site (warnings) * @return */ public Integer getSitesWithWarnings() { return sitesWithWarnings; } /** * All site specific configurations * @return */ public List<SiteView> getSites() { return sites; } }
import axios from 'axios' import React, { useState } from 'react' import { Button, Card, Form } from 'react-bootstrap' import { useNavigate } from 'react-router-dom' import SideBar from './SideBar' function AddTeam() { const [Name, setName] = useState() const [Email, setEmail] = useState() const [DateOfBirth, setDateOfBirth] = useState() const [Gender, setGender] = useState() const [Description, setDescription] = useState() const [Role, setRole] = useState() const [PhoneNumber, setPhoneNumber] = useState() const [ProfilePicture, setProfilePicture] = useState() const history=useNavigate() const AddTeam=async()=>{ const addteammem=await axios.post('http://localhost:4000/createteam',{Name,Email,DateOfBirth,Gender,Description,Role,PhoneNumber,ProfilePicture}) console.log(addteammem.data); history('/TeamTable.js') } const handleClose = () => { history(`/TeamTable.js`) }; return ( <div style={{display:"flex"}}> <SideBar/> <Card className="card border-secondary mx-auto mt-3 " style={{width:"80%"}}> <Card.Body className="d-flex flex-column align-items-center"> <div className="text-center mb-4"> <h1 className="card-title">Add Team Members</h1> <p className="" style={{ color: "white" }}> ___enter team members___ </p> </div> <Form className="w-100"> <Form.Group controlId="Name"> <Form.Label> Name</Form.Label> <Form.Control type="text" placeholder="Enter Member Name" value={Name} onChange={(e)=>setName(e.target.value)} required /> </Form.Group> <Form.Group controlId="email"> <Form.Label>Email</Form.Label> <Form.Control type="email" placeholder="Enter email" value={Email} onChange={(event) => setEmail(event.target.value)} required /> </Form.Group> <Form.Group controlId="dob"> <Form.Label>Date Of Birth</Form.Label> <Form.Control type="date" placeholder="Enter Date Of Birth" value={DateOfBirth} onChange={(event) => setDateOfBirth(event.target.value)} required /> </Form.Group> <Form.Group controlId="formBasicSignedstatus"> <Form.Label style={{ color: "white" }}>Gender</Form.Label> <div> <Form.Check inline label="male" type="radio" name="radio" id="male" value="true" checked={Gender ==="true"} onChange={(e) => { setGender(e.target.value); }} /> <Form.Check inline label="female" type="radio" name="radio" id="female" value="false" checked={Gender === "false"} onChange={(e) => { setGender(e.target.value); }} /> </div> </Form.Group> <Form.Group controlId="formBasicrole"> <Form.Label style={{ color: "white" }}>Role</Form.Label> <Form.Control as="select" value={Role} onChange={(e) => setRole(e.target.value)}> <option value="">Select a Role</option> <option value="Super Admin"> Super Admin</option> <option value="Only By Admin">Only By Admin</option> </Form.Control> </Form.Group> <Form.Group controlId="description"> <Form.Label>Description</Form.Label> <Form.Control type="text" placeholder="Enter Description" value={Description} onChange={(event) => setDescription(event.target.value)} required /> </Form.Group> <Form.Group controlId="phone"> <Form.Label>Phone Number</Form.Label> <Form.Control type="text" placeholder="Enter Phone Number" value={PhoneNumber} onChange={(event) => setPhoneNumber(event.target.value)} required /> </Form.Group> <Form.Group controlId="formBasicPicture"> <Form.Label style={{ color: "white" }}>Profile Picture</Form.Label> <Form.Control type="file" accept="image/*" onChange={(e) => { setProfilePicture(e.target.files[0]); }} /> </Form.Group> <Button variant="light" type="submit" className="btn-lg btn-block mt-4" onClick={AddTeam}> Submit </Button>{" "} <Button variant="danger" type="submit" className="btn-lg btn-block mt-4" onClick={handleClose} >Cancel</Button> </Form> </Card.Body> </Card> </div> ) } export default AddTeam
package com.huflit.doanmobile.activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.huflit.doanmobile.R; import com.huflit.doanmobile.SqlHelper.Mydatabase; import com.huflit.doanmobile.adapter.AdapterCart; import com.huflit.doanmobile.classs.Cart; import com.huflit.doanmobile.classs.Loginstatus; import java.util.ArrayList; import java.util.List; public class GioHangActivity extends AppCompatActivity { Toolbar toolbar; private RecyclerView recyclerView; private AdapterCart adapter; private List<Cart> cartList; private TextView totalTextView; private Mydatabase mydb; private String username; int userid; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_giohang); Anhxa(); toolbar = findViewById(R.id.toolbargiohang); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onBackPressed(); } }); Bundle p = getIntent().getExtras(); if (p != null){ username = p.getString("username"); } userid = mydb.getUserIdByUsername(username); cartList = mydb.getCartByUserID(userid); adapter = new AdapterCart(cartList, this, mydb); recyclerView.setAdapter(adapter); setTotalPrice(); } private void Anhxa() { recyclerView = findViewById(R.id.rcv_cart); totalTextView = findViewById(R.id.tv_totalprice); toolbar = findViewById(R.id.toolbargiohang); mydb = new Mydatabase(this); cartList = new ArrayList<>(); recyclerView.setLayoutManager(new LinearLayoutManager(this)); } public void setTotalPrice() { int totalPrice = 0; for (int i = 0; i < cartList.size(); i++) { Cart cart = cartList.get(i); int quantity = cart.getQuantity(); int price = cart.getBook().getPrice(); totalPrice += quantity * price; } totalTextView.setText(String.format("%,d", totalPrice) + " VND"); } public void btn_thanhtoan(View view) { if (cartList.size() == 0){ Toast.makeText(this, "Không có sản phẩm nào trong giỏ hàng", Toast.LENGTH_SHORT).show(); }else { String totalStr = totalTextView.getText().toString(); totalStr = totalStr.replace(",", "").replace(" VND", ""); int totalprice = Integer.parseInt(totalStr); Intent intent = new Intent(GioHangActivity.this,InforOrder.class); Bundle b = new Bundle(); b.putString("username", username); b.putInt("totalprice", totalprice); intent.putExtras(b); startActivity(intent); } } @Override protected void onResume() { super.onResume(); cartList.clear(); adapter.notifyDataSetChanged(); cartList = mydb.getCartByUserID(userid); adapter = new AdapterCart(cartList, this, mydb); recyclerView.setAdapter(adapter); } }
""" BOJ 1717 집합의 표현 문제 링크: https://www.acmicpc.net/problem/1717 """ import sys sys.setrecursionlimit(1000000) input = sys.stdin.readline def find_parent(parent, x): if parent[x] != x: parent[x] = find_parent(parent, parent[x]) return parent[x] def union_parent(parent, a, b): a = find_parent(parent, a) b = find_parent(parent, b) if a < b: parent[b] = a else: parent[a] = b if __name__ == "__main__": n, m = map(int, input().split()) parent = [0] * (n+1) result = [] for i in range(1, n + 1): parent[i] = i for _ in range(m): uf, a, b = map(int, input().split()) if uf == 0: union_parent(parent, a, b) elif uf == 1: if find_parent(parent, a) == find_parent(parent, b): result.append("YES") else: result.append("NO") for i in range(len(result)): print(result[i])
#### Project #### # Merge training and test sets X_test <- read.table("D:/Coursera/get_clean_data/getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/test/X_test.txt", quote="\"", comment.char="") X_train <- read.table("D:/Coursera/get_clean_data/getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/train/X_train.txt", quote="\"", comment.char="") #add column names features <- read.table("D:/Coursera/get_clean_data/getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/features.txt", quote="\"", comment.char="") features<-features[,2] names(X_test)<-features names(X_train)<-features # Add labels and subjects y_test <- read.table("D:/Coursera/get_clean_data/getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/test/y_test.txt", quote="\"", comment.char="") y_train <- read.table("D:/Coursera/get_clean_data/getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/train/y_train.txt", quote="\"", comment.char="") names(y_test)<-"label" names(y_train)<-"label" subject_test <- read.table("D:/Coursera/get_clean_data/getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/test/subject_test.txt", quote="\"", comment.char="", col.names = "subject") subject_train <- read.table("D:/Coursera/get_clean_data/getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/train/subject_train.txt", quote="\"", comment.char="", col.names= "subject") X_test<-cbind(subject_test,y_test,X_test) X_train<-cbind(subject_train,y_train,X_train) #merge merged_sample<-rbind(X_test,X_train) # extract only the measurements on the mean and standard deviation library(dplyr) mean_sd <- merged_sample %>% select(subject,label, contains("mean"), contains("std")) #uses descriptive activity names to name the activities in the data set activity_labels <- read.table("D:/Coursera/get_clean_data/getdata_projectfiles_UCI HAR Dataset/UCI HAR Dataset/activity_labels.txt", quote="\"", comment.char="", col.names=c("label", "activity")) mean_sd_act<-merge(activity_labels,mean_sd, by="label") #Appropriately labels the data set with descriptive variable names. #This was done in line 13 and 14, according to the code book # From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject. tidy_data<-mean_sd_act %>% group_by(activity, subject) %>% summarise_all(mean) write.table(tidy_data,"./data/tidy_data.txt", row.names = FALSE)
<?php namespace App\Http\Controllers\API; use App\Http\Controllers\API\BaseController as BaseController; use App\Http\Resources\StatusResource; use App\Http\Resources\TaskResource; use App\Models\Label; use App\Models\Status; use App\Models\Task; use App\Models\Tester; use Validator; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class TesterController extends BaseController { public function showAllTask(Request $request) { $sort_search = null; $sort_created = null; $sort_title = null; $task = Task::where('user_id',Auth::id()); if ($request->has('sort_title')) { $sort_title = $request->sort_title; $task = $task->orderBy('title',$sort_title); } if ($request->has('sort_created')) { $sort_created = $request->sort_created; $task = $task->orderBy('created_at',$sort_created); } if ($request->has('search')){ $sort_search = $request->search; $task = $task->where('title', 'like', '%'.$sort_search.'%'); } if ($request->has('filter_label')){ $label_id = Label::where('title', 'like', '%'.$request->filter_label.'%')->get('task_id'); $task = $task->whereIn('id',$label_id); } $task = $task->get(); return $this->sendResponse(TaskResource::collection($task), 'Task retrieved successfully for the Tester!'); } public function changeTaskStatus(Request $request, Task $task) { $errorMessage = []; // first checke if the task is assigned to this user if ($task->user_id != Auth::id()) { return $this->sendError('unauthorized to do this operatoin', $errorMessage,403); } $input = $request->all(); $request->validate([ 'change_status'=> 'required' ]); if ($task->current_status == 'testing' && $request->change_status == 'dev-review') { //add the record to the change status tables $input['user_name'] = Auth::user()->name; $input['detail'] = 'Change status from '. $task->current_status . ' to ' . $input['change_status'] . '.'; $input['task_id'] = $task->id; $status = Status::create($input); $task->current_status = $request->change_status; $task->save(); return $this->sendResponse(['task' => new TaskResource($task), 'status_changes' => new StatusResource($status)], 'current status have been changed successfully!'); } // if the change status is same the current status elseif ($task->current_status == $request->change_status) { return $this->sendError('The current status value is same the change status!',$errorMessage); } //if the change status is unauthrized to this user elseif ($request->change_status == 'to-do' || $request->change_status == 'in-progress' || $request->change_status == 'close' || $request->change_status == 'done' || ($request->change_status == 'testing' && $task->current_status == 'dev-review')) { return $this->sendError('unauthorized to change ', $errorMessage); }else{ return $this->sendError('There is no changes status like that ', $errorMessage); } } }
<!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <!-- 1. ID로 HTML 요소를 찾는 방법 : document.getElementById('아이디') 2. 태그이름으로 HTML 요소를 찾는 방법 : document.getElementsByTagName("태그") - 배열 3. 클래스 이름으로 HTML 요소를 찾는 법 : document.getElementsByClassName("클래스") - 배열 4. css선택기로 HTML요소를 찾는 법 : document.querySelectorAll("태그.클래스") - 배열 5. HTML 개체 컬렉션으로 HTML요소를 찾는 법 --> <!-- <h2>자바스크립트</h2> <p class="intro pa">태그로 html 요소 찾기</p> <p class="intro pb">두번쨰 html의 p요소 찾기</p> <p id="demo"></p> <script> //getElement - getElements <= 배열로 받는다 const el = document.getElementsByClasName("pb"); document.getElementById("demo").innerHTML = '받은 내용 출력' + el[1].innerHTML; </script> --> <h2>자바스크립트</h2> <h2>회원로그인</h2> <p>회원이시면 로그인 해주세요</p> <form id="login" action="action.html"> <label for="userid">아이디</label> <input type="text" name=" username" id="userid" value="myname"> <br> <label for="userpass">비밀번호</label> <input type="text" name="userpass" id="userpass" value="12345678"> <br> <input type="submit" value=" 로그인 "/> </form> <p> 폼 안에 입력된 정보</p> <p id="demo"></p> <script> const x = document.forms['login']; let text = ""; for (let i = 0; i< x.length; i++){ text += x.elemnts[i].value + "<br>"; } document.getElementById("demo").innerHTML = text; </script> </body> </html>
/* * Copyright 2019-2020 Zheng Jie * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.zhengjie.rest; import me.zhengjie.annotation.Log; import me.zhengjie.domain.StockInTollyItem; import me.zhengjie.service.StockInTollyItemService; import me.zhengjie.service.dto.StockInTollyItemQueryCriteria; import org.springframework.data.domain.Pageable; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import io.swagger.annotations.*; import java.io.IOException; import javax.servlet.http.HttpServletResponse; /** * @website https://el-admin.vip * @author wangm * @date 2021-03-23 **/ @RestController @RequiredArgsConstructor @Api(tags = "入库理货单明细管理") @RequestMapping("/api/stockInTollyItem") public class StockInTollyItemController { private final StockInTollyItemService stockInTollyItemService; @Log("导出数据") @ApiOperation("导出数据") @GetMapping(value = "/download") @PreAuthorize("@el.check('stockInTollyItem:list')") public void download(HttpServletResponse response, StockInTollyItemQueryCriteria criteria) throws IOException { stockInTollyItemService.download(stockInTollyItemService.queryAll(criteria), response); } @GetMapping @Log("查询入库理货单明细") @ApiOperation("查询入库理货单明细") @PreAuthorize("@el.check('stockInTollyItem:list')") public ResponseEntity<Object> query(StockInTollyItemQueryCriteria criteria, Pageable pageable){ return new ResponseEntity<>(stockInTollyItemService.queryAll(criteria,pageable),HttpStatus.OK); } @PostMapping @Log("新增入库理货单明细") @ApiOperation("新增入库理货单明细") @PreAuthorize("@el.check('stockInTollyItem:add')") public ResponseEntity<Object> create(@Validated @RequestBody StockInTollyItem resources){ return new ResponseEntity<>(stockInTollyItemService.create(resources),HttpStatus.CREATED); } @PutMapping @Log("修改入库理货单明细") @ApiOperation("修改入库理货单明细") @PreAuthorize("@el.check('stockInTollyItem:edit')") public ResponseEntity<Object> update(@Validated @RequestBody StockInTollyItem resources){ stockInTollyItemService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @Log("删除入库理货单明细") @ApiOperation("删除入库理货单明细") @PreAuthorize("@el.check('stockInTollyItem:del')") @DeleteMapping public ResponseEntity<Object> delete(@RequestBody Long[] ids) { stockInTollyItemService.deleteAll(ids); return new ResponseEntity<>(HttpStatus.OK); } @Log("更新理货统计") @ApiOperation("更新理货统计") @PreAuthorize("@el.check('stockInTollyItem:edit')") @PostMapping("update-stock-item") public ResponseEntity<Object> updateStockItem(Long stockId) { stockInTollyItemService.updateStockItem(stockId); return new ResponseEntity<>(HttpStatus.OK); } }
#include "FluidSim/FluidSimulation.h" #include <iostream> #include "Kikan/ecs/systems/SpriteRenderSystem.h" #include "Kikan/ecs/components/Texture2DSprite.h" #include "../imgui/imgui_impl_glfw.h" #include "../imgui/imgui_impl_opengl3.h" #include "IconFontAwesome/IconsFontAwesome5.h" #define TEXTURE_SIZE 512 #define TEXTURE_SIZE_HALF (TEXTURE_SIZE / 2.f) #define RESOLUTION 2048 FluidSimulation::FluidSimulation() { //Setup Engine _engine = new Kikan::Engine(); std::string title("Fluid Simulation"); _engine->setTitle(title); _engine->getRenderer()->overrideRender(this); delete _engine->getRenderer()->shader(); _engine->getRenderer()->shader(new Kikan::Shader("shaders/default.vert", "shaders/main.frag")); _engine->getRenderer()->shader()->bind(); _engine->getRenderer()->shader()->uniform1li("u_sampler", 0); //grid Shader _engine->getRenderer()->shader(new Kikan::Shader("shaders/default.vert", "shaders/grid.frag"), _gridShaderName); _engine->getRenderer()->shader(_gridShaderName)->uniform1li("u_sampler", 0); //particle Shader _engine->getRenderer()->shader(new Kikan::Shader("shaders/default.vert", "shaders/particle.frag"), _particleShaderName); _engine->getRenderer()->shader(_particleShaderName)->uniform1li("u_sampler", 0); _engine->getRenderer()->shader(new Kikan::Shader("shaders/default.vert", "shaders/particle2.frag"), _particleShaderName2); _engine->getRenderer()->shader(_particleShaderName2)->uniform1li("u_particle", 0); _engine->getRenderer()->addBatch(new Kikan::ManuelBatch(Kikan::VertexRegistry::getLayout<Kikan::DefaultVertex>(), sizeof(Kikan::DefaultVertex)), 0); _engine->getRenderer()->addBatch(new Kikan::ManuelBatch(Kikan::VertexRegistry::getLayout<Kikan::DefaultVertex>(), sizeof(Kikan::DefaultVertex)), 1); _engine->getRenderer()->addBatch(new Kikan::ManuelBatch(Kikan::VertexRegistry::getLayout<Kikan::DefaultVertex>(), sizeof(Kikan::DefaultVertex)), 2); _engine->getRenderer()->addBatch(new Kikan::ManuelBatch(Kikan::VertexRegistry::getLayout<Kikan::DefaultVertex>(), sizeof(Kikan::DefaultVertex)), 3); // Setup ImGUI ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; ImGui::StyleColorsDark(); ImGui_ImplGlfw_InitForOpenGL(_engine->getRenderer()->getWindow(), true); ImGui_ImplOpenGL3_Init("#version 430"); // Setup Icon Font io.Fonts->AddFontDefault(); // merge in icons from Font Awesome static const ImWchar icons_ranges[] = { ICON_MIN_FA, ICON_MAX_16_FA, 0 }; ImFontConfig icons_config; icons_config.MergeMode = true; icons_config.PixelSnapH = true; std::string fontFile("assets/"); fontFile += FONT_ICON_FILE_NAME_FAS; io.Fonts->AddFontFromFileTTF( fontFile.c_str(), 11.0f, &icons_config, icons_ranges ); // Load maps _maps.push_back(new MapFile("assets/box")); _maps.push_back(new MapFile("assets/tube")); _maps.push_back(new MapFile("assets/slope")); _curr_map = _maps[0]; _engine->getRenderer()->shader()->bind(); _engine->getRenderer()->shader()->uniform1lf("u_pTexture", (float)_maps.size() + 2); _engine->getRenderer()->shader()->uniform1lf("u_renderMode", 0.f); // Setup Widgets glGenFramebuffers(1, &_fbo); _view_space_2D = new Kikan::Texture2D(RESOLUTION, RESOLUTION, (float*)nullptr); _p_txt_2D = new Kikan::Texture2D(RESOLUTION, RESOLUTION, (float*)nullptr); _vs = new ViewSpace(_view_space_2D, _curr_map); _ce = new ConstantsEditor(); _mt = new MapTree(&_maps); _sv = new StatsViewer(); // Engine Stuff _engine->getScene()->addSystem(new Kikan::SpriteRenderSystem()); _g_render_system = new GridRenderSystem(_vs->getControls(), _sv->getStats()); _engine->getScene()->addSystem(_g_render_system); _p_render_system = new ParticleRenderSystem(_vs->getControls(), _ce->getConstants(), _sv->getStats()); _engine->getScene()->addSystem(_p_render_system); _sim_system = new SimulationSystem(_curr_map->getDistanceField(), _ce->getConstants(), _vs->getControls(), _sv->getStats(), _engine->getScene(), _g_render_system); _engine->getScene()->addSystem(_sim_system); //create Texture std::vector<float> data(TEXTURE_SIZE * TEXTURE_SIZE * 4); for (int x = 0; x < TEXTURE_SIZE; ++x) { for (int y = 0; y < TEXTURE_SIZE; ++y) { data[(x + TEXTURE_SIZE * y) * 4] = 0.; data[(x + TEXTURE_SIZE * y) * 4 + 1] = 0.; data[(x + TEXTURE_SIZE * y) * 4 + 2] = 1.; data[(x + TEXTURE_SIZE * y) * 4 + 3] = (float)(1.f - std::sqrt((x - TEXTURE_SIZE_HALF) * (x - TEXTURE_SIZE_HALF) + (y - TEXTURE_SIZE_HALF) * (y - TEXTURE_SIZE_HALF)) / TEXTURE_SIZE_HALF); } } _particle2D = new Kikan::Texture2D(TEXTURE_SIZE, TEXTURE_SIZE, data.data()); _engine->getRenderer()->getBatch(0)->addTexture((int)_particle2D->get(), 0); _ce->getConstants()->TEXTURE_ID = _particle2D->get(); std::vector<GLuint> i = {0, 1, 2, 0, 2, 3}; std::vector<Kikan::DefaultVertex> v(4); v[0].textureCoords = glm::vec2(0, 1); v[1].textureCoords = glm::vec2(1, 1); v[2].textureCoords = glm::vec2(1, 0); v[3].textureCoords = glm::vec2(0, 0); // Render Particles from Texture _engine->getRenderer()->getBatch(2)->addTexture((int)_p_txt_2D->get(), 0); v[0].position = glm::vec3(-1, 1, 0); v[1].position = glm::vec3(1, 1, 0); v[2].position = glm::vec3(1, -1, 0); v[3].position = glm::vec3(-1, -1, 0); _engine->getRenderer()->getBatch(2)->overrideVertices(v, i); // Render Grid from Texture v[0].position = glm::vec3(0, _curr_map->getHeight(), 0); v[1].position = glm::vec3(_curr_map->getWidth(), _curr_map->getHeight(), 0); v[2].position = glm::vec3(_curr_map->getWidth(), 0, 0); v[3].position = glm::vec3(0, 0, 0); _engine->getRenderer()->getBatch(1)->overrideVertices(v, i); // Foreground Batch _engine->getRenderer()->getBatch(3)->overrideVertices(v, i); } FluidSimulation::~FluidSimulation() { _loading_msg = "KILL"; delete _engine; delete _particle2D; delete _view_space_2D; delete _ce; delete _mt; delete _sv; for (auto* map : _maps) { delete map; } glDeleteFramebuffers(1, &_fbo); } void FluidSimulation::update() const { _engine->update(); } bool FluidSimulation::shouldRun() const { return _engine->shouldRun(); } void FluidSimulation::preRender(Kikan::Renderer* renderer, double dt) { Kikan::Renderer::queryErrors("Begin"); _engine->getRenderer()->shader()->uniform1lf("u_renderMode", _vs->getControls()->RENDER_MODE == Controls::RMT::GRID ? 0. : 1.); // Set camera _engine->getScene()->camera()->reset(); if(_curr_map->getHeight() > _curr_map->getWidth()) _engine->getScene()->camera()->scale(1 / ((float)_curr_map->getHeight() * _vs->getZoom() / 2.f), 1 / ((float)_curr_map->getHeight() * _vs->getZoom() / 2.f )); else _engine->getScene()->camera()->scale(1 / ((float)_curr_map->getWidth() * _vs->getZoom() / 2.f), 1 / ((float)_curr_map->getWidth() * _vs->getZoom() / 2.f )); _engine->getScene()->camera()->translate(-(float)_curr_map->getWidth() / 2, -(float)_curr_map->getHeight() / 2); // Load different map if(_mt->getLoaded() != nullptr && _curr_map != _mt->getLoaded()){ _curr_map = _mt->getLoaded(); _vs->getControls()->REBUILD = true; _vs->setMapFile(_curr_map); _sim_system->setDistanceField(_curr_map->getDistanceField()); std::vector<Kikan::DefaultVertex> v(4); v[0].position = glm::vec3(0, _curr_map->getHeight(), 0); v[1].position = glm::vec3(_curr_map->getWidth(), _curr_map->getHeight(), 0); v[2].position = glm::vec3(_curr_map->getWidth(), 0, 0); v[3].position = glm::vec3(0, 0, 0); std::vector<GLuint> i = {0, 1, 2, 0, 2, 3}; v[0].textureCoords = glm::vec2(0, 1); v[1].textureCoords = glm::vec2(1, 1); v[2].textureCoords = glm::vec2(1, 0); v[3].textureCoords = glm::vec2(0, 0); _engine->getRenderer()->getBatch(1)->overrideVertices(v, i); _engine->getRenderer()->getBatch(3)->overrideVertices(v, i); } //update FPS STAT _sv->getStats()->FPS = _engine->time.fps; ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); glBindFramebuffer(GL_FRAMEBUFFER, _fbo); glViewport(0, 0, RESOLUTION, RESOLUTION); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _view_space_2D->get(), 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void FluidSimulation::postRender(Kikan::Renderer* renderer, double dt) { // Render background renderer->shader()->bind(); renderer->shader()->uniformM4fv("u_mvp", renderer->mvp); renderer->getBatch(3)->addTexture((int)_curr_map->getTexture()->get(), 0); renderer->getBatch(3)->render(); if(_vs->getControls()->RENDER_MODE == Controls::RMT::PARTICLES){ //Render Particles to Texture glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _p_txt_2D->get(), 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); renderer->shader(_particleShaderName)->bind(); renderer->shader(_particleShaderName)->uniformM4fv("u_mvp", renderer->mvp); renderer->getBatch(0)->render(); //Render Particle Texture over frame texture applying alpha threshold glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _view_space_2D->get(), 0); renderer->shader(_particleShaderName2)->bind(); renderer->shader(_particleShaderName2)->uniformM4fv("u_mvp", glm::mat4x4(1.0f)); renderer->shader(_particleShaderName2)->uniform1lf("u_size", RESOLUTION * _vs->getZoom()); renderer->shader(_particleShaderName2)->uniform1li("u_smoothing", _ce->getConstants()->RENDER_SMOOTHING); renderer->getBatch(2)->render(); } else{ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _p_txt_2D->get(), 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); renderer->shader(_gridShaderName)->bind(); renderer->shader(_gridShaderName)->uniformM4fv("u_mvp", renderer->mvp); renderer->shader(_gridShaderName)->uniform1lf("u_zoom", _vs->getZoom()); renderer->shader(_gridShaderName)->uniform2fv("u_cell_count", glm::vec2(_sim_system->getGrid()->getWidth(), _sim_system->getGrid()->getHeight())); renderer->shader(_gridShaderName)->uniform2fv("u_resolution", glm::vec2(RESOLUTION, RESOLUTION)); renderer->getBatch(1)->render(); //Render Particle Texture over frame texture for smoothing glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _view_space_2D->get(), 0); renderer->shader(_particleShaderName2)->bind(); renderer->shader(_particleShaderName2)->uniformM4fv("u_mvp", glm::mat4x4(1.0f)); renderer->shader(_particleShaderName2)->uniform1lf("u_size", RESOLUTION * _vs->getZoom()); renderer->shader(_particleShaderName2)->uniform1li("u_smoothing", _ce->getConstants()->RENDER_SMOOTHING); renderer->getBatch(2)->render(); } if(_curr_map->getForeground()){ renderer->shader()->bind(); renderer->shader()->uniformM4fv("u_mvp", renderer->mvp); renderer->getBatch(3)->addTexture((int)_curr_map->getForeground()->get(), 0); renderer->getBatch(3)->render(); } glBindFramebuffer(GL_FRAMEBUFFER, 0); render_dockspace(); //bool show_demo_window = true; //ImGui::ShowDemoWindow(&show_demo_window); ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); } void FluidSimulation::render_dockspace() { static bool opt_fullscreen = true; static bool opt_padding = false; static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None; // We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into, // because it would be confusing to have two docking targets within each others. ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDocking; if (opt_fullscreen) { const ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(viewport->WorkPos); ImGui::SetNextWindowSize(viewport->WorkSize); ImGui::SetNextWindowViewport(viewport->ID); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; } else { dockspace_flags &= ~ImGuiDockNodeFlags_PassthruCentralNode; } // When using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our background // and handle the pass-thru hole, so we ask Begin() to not render a background. if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) window_flags |= ImGuiWindowFlags_NoBackground; // Important: note that we proceed even if Begin() returns false (aka window is collapsed). // This is because we want to keep our DockSpace() active. If a DockSpace() is inactive, // all active windows docked into it will lose their parent and become undocked. // We cannot preserve the docking relationship between an active window and an inactive docking, otherwise // any change of dockspace/settings would lead to windows being stuck in limbo and never being visible. if (!opt_padding) ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::Begin("DockSpace Demo", nullptr, window_flags); if (!opt_padding) ImGui::PopStyleVar(); if (opt_fullscreen) ImGui::PopStyleVar(2); // Submit the DockSpace ImGuiIO& io = ImGui::GetIO(); if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) { ImGuiID dockspace_id = ImGui::GetID("DockSpace"); ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags); } // render own ui render_ui(); ImGui::End(); } void FluidSimulation::render_ui() { bool open = false; if(ImGui::BeginMainMenuBar()) { if (ImGui::BeginMenu("File")) { if(ImGui::MenuItem("Load Map")) { open = true; } ImGui::EndMenu(); } ImGui::EndMainMenuBar(); } if(open) ImGui::OpenPopup("Load Map"); if(_fileBrowser.showFileDialog("Load Map", imgui_addons::ImGuiFileBrowser::DialogMode::OPEN, ImVec2(ImGui::GetWindowWidth() * .75f, ImGui::GetWindowHeight() * .75f), ".png")){ std::string path = _fileBrowser.selected_path; path.erase(path.end() - 4, path.end()); _maps.push_back(new MapFile(path, &_loading, &_loading_msg)); } _vs->getControls()->POPUP_OPEN = ImGui::IsPopupOpen("Load Map"); _vs->render(); _ce->render(); _mt->render(); _sv->render(); if(_loading < 1){ _vs->getControls()->LOADING = true; ImGui::OpenPopup("Loading..."); if (ImGui::BeginPopupModal("Loading...", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::Text(_loading_msg.c_str()); ImGui::Separator(); char buf[32]; sprintf(buf, "%.01f%%", _loading * 100 + 0.01f); ImGui::ProgressBar(_loading, ImVec2(0.0f, 0.0f), buf); ImGui::EndPopup(); } } else if(_loading == 1){ _vs->getControls()->LOADING = false; _loading = 2; } }
'use strict'; const request = require('supertest'); const express = require('express'); const expect = require('chai').expect; const app = require('../app.js'); const dbUtils = require('../../db/lib/utils.js'); describe('basic server', function() { beforeEach(function (done) { dbUtils.rollbackMigrate(done); }); it('sends back hello world', function(done) { request(app) .get('/api') .expect(200) .expect(function(res) { expect(res.text).to.equal('Hello World!'); }) .end(done); }); it('accepts POST request', function(done) { request(app) .post('/api') .expect(201) .expect(function(res) { expect(res.body.data).to.equal('Posted!'); }) .end(done); }); it('returns latest images from api call', function(done) { request(app) .get('/api/latest-images') .expect(200) .expect(function(res) { expect(res.body.length).to.equal(6); }) .end(done); }); });
// SharedFunctions.swift // Make books // // © 2023 Nick Berendsen import SwiftUI import SwiftlyFolderUtilities // MARK: Folder selector /// Books folder selection /// - Parameter books: The books model func selectBooksFolder(_ books: Books) async { do { _ = try await FolderBookmark.select( prompt: "Select", message: "Select the folder with your books", bookmark: "BooksPath" ) /// Refresh the list of books await books.getFiles() } catch { print(error.localizedDescription) } } /// Export folder selection /// - Parameter books: The books model func selectExportFolder(_ books: Books) async { do { _ = try await FolderBookmark.select( prompt: "Select", message: "Select the export folder for your books", bookmark: "ExportPath" ) } catch { print(error.localizedDescription) } } // MARK: getCover /// Get the cover of a book /// - Parameter cover: The cover URL /// - Returns: An NSImage with the cover func getCover(cover: URL) -> NSImage { if let imageData = try? Data(contentsOf: cover) { return NSImage(data: imageData)! } /// This should not happen return NSImage() } // MARK: doesFileExists /// Check if a file or folder exists /// - Parameter url: The URL to the item /// - Returns: True or false func doesFileExists(url: URL) -> Bool { if FileManager.default.fileExists(atPath: url.path) { return true } return false } // MARK: romanNumber /// Convert a numer to Roman /// - Parameter number: The number /// - Returns: The number in roman style func romanNumber(number: Int) -> String { let romanValues = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"] let arabicValues = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] var romanValue = "" var startingValue = number for (index, romanChar) in romanValues.enumerated() { let arabicValue = arabicValues[index] let div = startingValue / arabicValue if div > 0 { for _ in 0..<div { romanValue += romanChar } startingValue -= arabicValue * div } } return romanValue }