text
stringlengths
184
4.48M
using Asp.NetCoreWeb_N_Tier_ArchitectureProject.DTOs; using Asp.NetCoreWeb_N_Tier_ArchitectureProject.Models; using Asp.NetCoreWeb_N_Tier_ArchitectureProject.Repositories.Products; using Asp.NetCoreWeb_N_Tier_ArchitectureProject.Service.Exceptions; using Asp.NetCoreWeb_N_Tier_ArchitectureProject.Services; using Asp.NetCoreWeb_N_Tier_ArchitectureProject.UnitofWorks; using AutoMapper; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Memory; using System.Linq.Expressions; namespace Asp.NetCoreWeb_N_Tier_ArchitectureProject.Caching { public class ProductServiceWithCaching : IProductService { private const string CacheProductKey = "Productscache"; private readonly IMapper _mapper; private readonly IMemoryCache _memoryCache; private readonly IProductRepository _productRepository; private readonly IUnitofWork _unitOfWork; public ProductServiceWithCaching(IMapper mapper, IMemoryCache memoryCache, IProductRepository productRepository, IUnitofWork unitOfWork) { _mapper = mapper; _memoryCache = memoryCache; _productRepository = productRepository; _unitOfWork = unitOfWork; if (!_memoryCache.TryGetValue(CacheProductKey, out _)) { _memoryCache.Set(CacheProductKey, _productRepository.GetProductsWithCategory().Result); } } public async Task<Product> AddAsync(Product entity) { await _productRepository.AddAsync(entity); await _unitOfWork.CommitAsync(); await CacheAllProducts(); return entity; } public async Task<IEnumerable<Product>> AddRangeAsync(IEnumerable<Product> entities) { await _productRepository.AddRangeAsync(entities); await _unitOfWork.CommitAsync(); await CacheAllProducts(); return entities; } public Task<bool> AnyAsync(Expression<Func<Product, bool>> expression) { throw new NotImplementedException(); } public async Task DeleteAsync(Product entity) { _productRepository.Delete(entity); await _unitOfWork.CommitAsync(); await CacheAllProducts(); } public Task<IEnumerable<Product>> GetAllAsync() { return Task.FromResult(_memoryCache.Get<IEnumerable<Product>>(CacheProductKey)); } public Task<Product> GetByIDAsync(int id) { var product = _memoryCache.Get<List<Product>>(CacheProductKey).FirstOrDefault(x => x.Id == id); if (product == null) throw new NotFoundException($"{typeof(Product).Name}({id}) not found"); return Task.FromResult(product); } public Task<CustomResponseDTO<List<ProductwithCategoryDTO>>> GetProductsWithCategory() { var products = _memoryCache.Get<IEnumerable<Product>>(CacheProductKey); var productsWithCategoryDTO = _mapper.Map<List<ProductwithCategoryDTO>>(products); return Task.FromResult(CustomResponseDTO<List<ProductwithCategoryDTO>>.Success(200, productsWithCategoryDTO)); } public async Task RemoveRangeAsync(IEnumerable<Product> entities) { _productRepository.RemoveRange(entities); await _unitOfWork.CommitAsync(); await CacheAllProducts(); } public async Task UpdateAsync(Product entity) { _productRepository.Update(entity); await _unitOfWork.CommitAsync(); await CacheAllProducts(); } public IQueryable<Product> Where(Expression<Func<Product, bool>> expression) { return _memoryCache.Get<List<Product>>(CacheProductKey).Where(expression.Compile()).AsQueryable(); } public async Task CacheAllProducts() { _memoryCache.Set(CacheProductKey, _productRepository.GetAll().ToListAsync()); } } }
// SnaX Game Engine - https://github.com/snaxgameengine/snax // Licensed under the MIT License <http://opensource.org/licenses/MIT>. // SPDX-License-Identifier: MIT // Copyright (c) 2013 - 2022 Frank-Vegar Mortensen <franksvm(at)outlook(dot)com>. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "pch.h" #include "AxisAlignedBox.h" #include "Sphere.h" using namespace m3d; AxisAlignedBox::AxisAlignedBox() : _isInfinite(true), _minP(-std::numeric_limits<float32>::max(), -std::numeric_limits<float32>::max(), -std::numeric_limits<float32>::max()), _maxP(std::numeric_limits<float32>::max(), std::numeric_limits<float32>::max(), std::numeric_limits<float32>::max()) {} AxisAlignedBox::AxisAlignedBox(const XMFLOAT3 &minP, const XMFLOAT3 &maxP) : _isInfinite(false), _minP(minP), _maxP(maxP) {} AxisAlignedBox::AxisAlignedBox(const AxisAlignedBox &rhs) : _isInfinite(rhs._isInfinite), _minP(rhs._minP), _maxP(rhs._maxP) {} AxisAlignedBox::AxisAlignedBox(const Sphere &rhs) : _isInfinite(false) { const XMFLOAT3 p = rhs.GetPosition(); FLOAT r = rhs.GetRadius(); _minP = XMFLOAT3(p.x - r, p.y - r, p.z - r); _maxP = XMFLOAT3(p.x + r, p.y + r, p.z + r); } AxisAlignedBox::~AxisAlignedBox() {} AxisAlignedBox &AxisAlignedBox::operator=(const AxisAlignedBox &rhs) { _minP = rhs._minP; _maxP = rhs._maxP; _isInfinite = rhs._isInfinite; return *this; } void AxisAlignedBox::SetInfinite() { _isInfinite = true; _minP = XMFLOAT3(-std::numeric_limits<float32>::max(), -std::numeric_limits<float32>::max(), -std::numeric_limits<float32>::max()); _maxP = XMFLOAT3(std::numeric_limits<float32>::max(), std::numeric_limits<float32>::max(), std::numeric_limits<float32>::max()); } void AxisAlignedBox::SetNull() { _isInfinite = false; _minP = XMFLOAT3(std::numeric_limits<float32>::max(), std::numeric_limits<float32>::max(), std::numeric_limits<float32>::max()); _maxP = XMFLOAT3(-std::numeric_limits<float32>::max(), -std::numeric_limits<float32>::max(), -std::numeric_limits<float32>::max()); } void AxisAlignedBox::Set(const XMFLOAT3 &minP, const XMFLOAT3 &maxP) { _isInfinite = false; _minP = minP; _maxP = maxP; } void AxisAlignedBox::Set(uint32 count, const XMFLOAT3* vertices, uint32 vStride) { XMVECTOR a = XMVectorReplicate(std::numeric_limits<float32>::max()), b = XMVectorReplicate(-std::numeric_limits<float32>::max()); for (uint32 i = 0; i < count; i++) { XMVECTOR c = XMLoadFloat3((XMFLOAT3*)((int8*)vertices + vStride * i)); a = XMVectorMin(a, c); a = XMVectorMax(a, c); } XMStoreFloat3(&_minP, a); XMStoreFloat3(&_maxP, b); _isInfinite = false; } void AxisAlignedBox::Set(uint32 count, const XMFLOAT3* vertices, uint32 vStride, const uint16 *indices) { XMVECTOR a = XMVectorReplicate(std::numeric_limits<float32>::max()), b = XMVectorReplicate(-std::numeric_limits<float32>::max()); for (uint32 i = 0; i < count; i++) { if (indices[i] != -1) { // Could be -1 to indicate restart strip XMVECTOR c = XMLoadFloat3((XMFLOAT3*)((int8*)vertices + vStride * indices[i])); a = XMVectorMin(a, c); b = XMVectorMax(b, c); } } XMStoreFloat3(&_minP, a); XMStoreFloat3(&_maxP, b); _isInfinite = false; } void AxisAlignedBox::Set(uint32 count, const XMFLOAT3* vertices, uint32 vStride, const uint32 *indices) { XMVECTOR a = XMVectorReplicate(std::numeric_limits<float32>::max()), b = XMVectorReplicate(-std::numeric_limits<float32>::max()); for (uint32 i = 0; i < count; i++) { if (indices[i] != -1) { // Could be -1 to indicate restart strip XMVECTOR c = XMLoadFloat3((XMFLOAT3*)((int8*)vertices + vStride * indices[i])); a = XMVectorMin(a, c); b = XMVectorMax(b, c); } } XMStoreFloat3(&_minP, a); XMStoreFloat3(&_maxP, b); _isInfinite = false; } AxisAlignedBox &AxisAlignedBox::Merge(const XMFLOAT3 &p) { if (_isInfinite) return *this; _minP.x = XMMin(_minP.x, p.x); _minP.y = XMMin(_minP.y, p.y); _minP.z = XMMin(_minP.z, p.z); _maxP.x = XMMax(_maxP.x, p.x); _maxP.y = XMMax(_maxP.y, p.y); _maxP.z = XMMax(_maxP.z, p.z); return *this; } AxisAlignedBox &AxisAlignedBox::Merge(const AxisAlignedBox &bb) { if (_isInfinite) return *this; if (bb._isInfinite) SetInfinite(); else { Merge(bb._minP); Merge(bb._maxP); } return *this; } AxisAlignedBox &AxisAlignedBox::Merge(const Sphere &s) { if (_isInfinite) return *this; const XMFLOAT3 p = s.GetPosition(); FLOAT r = s.GetRadius(); Merge(XMFLOAT3(p.x + r, p.y + r, p.z + r)); Merge(XMFLOAT3(p.x - r, p.y - r, p.z - r)); return *this; } AxisAlignedBox &AxisAlignedBox::Transform(CXMMATRIX m) { if (_isInfinite) return *this; XMVECTORF32 corners[8] = // Changed from XMVECTOR do to ARM { { _minP.x, _minP.y, _minP.z, 0.0f }, { _minP.x, _minP.y, _maxP.z, 0.0f }, { _minP.x, _maxP.y, _minP.z, 0.0f }, { _minP.x, _maxP.y, _maxP.z, 0.0f }, { _maxP.x, _minP.y, _minP.z, 0.0f }, { _maxP.x, _minP.y, _maxP.z, 0.0f }, { _maxP.x, _maxP.y, _minP.z, 0.0f }, { _maxP.x, _maxP.y, _maxP.z, 0.0f } }; XMVECTOR a = XMVectorReplicate(std::numeric_limits<float32>::max()), b = XMVectorReplicate(-std::numeric_limits<float32>::max()), c; for (uint32 i = 0; i < 8; i++) { c = XMVector3TransformCoord(corners[i], m); a = XMVectorMin(a, c); b = XMVectorMax(b, c); } XMStoreFloat3(&_minP, a); XMStoreFloat3(&_maxP, b); return *this; } AxisAlignedBox AxisAlignedBox::Intersect(const AxisAlignedBox &aab) const { AxisAlignedBox r; XMStoreFloat3(&r._minP, XMVectorMax(XMLoadFloat3(&_minP), XMLoadFloat3(&aab._minP))); XMStoreFloat3(&r._maxP, XMVectorMin(XMLoadFloat3(&_maxP), XMLoadFloat3(&aab._maxP))); return r; }
import React, { useEffect, useState } from "react"; import logo from "../../../img/Navbar/login.png"; import { Link, useNavigate } from "react-router-dom"; import { useForm } from "react-hook-form"; import { yupResolver } from "@hookform/resolvers/yup"; import * as yup from "yup"; import axios from "axios"; const Signin = () => { const [message, setMessage] = useState(""); const navigate = useNavigate(); const emailRegExp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; const phoneRegExp = /((09|03|07|08|05)+([0-9]{8})\b)/g; const schema = yup.object().shape({ fullName: yup.string().required("Vui long nhap ho va ten"), email: yup .string() .required("Vui long nhap email") .matches(emailRegExp, "Vui long nhap dung dinh dang email."), phone: yup .string() .required("Vui long nhap so dien thoai") .matches(phoneRegExp, "Vui long nhap dung dinh dang"), userName: yup.string().required("Vui long nhap User Name"), password: yup.string().required("Vui long nhap mat khau"), address: yup.string().required("Vui long nhap dia chi"), confirmpassword: yup .string() .required("Vui long nhap lai mat khau") .oneOf([yup.ref("password"), null], "Passwords must match"), }); const { register, handleSubmit, formState: { errors }, getValues, } = useForm({ resolver: yupResolver(schema), mode: "onChange" }); function handleSignin() { // const {fullName,email,phone,userName,password,address} = getValues(); // const dataReq = { // fullName: fullName, // email: email, // phone: phone, // userName: userName, // password: password, // address: address, // }; const {confirmpassword,...rest} = getValues(); axios .post("https://phone-store-server.onrender.com/signin", rest) .then((res) => { if (res.data === "Tạo tài khoản thành công") { alert(res.data); navigate("/login"); } setMessage(res.data); }) .catch((err) => console.log(err)); if (message == "Tạo tài khoản thành công") { alert(message); navigate("/login"); } } return ( <div className="w-screen h-screen bg-[orange]/70 flex items-center justify-center"> <div className="pl-8"> <img src={logo} alt="" className="w-2/5" /> <p className="w-3/5"> Đăng ký ngay để nhận được nhiều khuyến mãi đặc biệt </p> </div> <div className="w-[400px]"> <form className="flex flex-col gap-2 bg-[#333] py-5 px-10 rounded-md" onSubmit={handleSubmit(handleSignin)} > <p className="text-white text-center font-bold text-2xl"> Tạo tài khoản </p> <div className="flex flex-col"> <input type="text" placeholder="Nhập họ và tên" className="pl-6 text-lg rounded" {...register("fullName")} /> {errors.username && ( <span className="text-lg text-white mt-1"> {errors.username.message} </span> )} </div> <div className="flex flex-col"> <input type="text" placeholder="Email" className="pl-6 text-lg rounded" {...register("email")} /> {errors.email && ( <span className="text-lg text-white mt-1"> {errors.email.message} </span> )} </div> <div className="flex flex-col"> <input type="text" placeholder="Số điện thoại" className="pl-6 text-lg rounded" {...register("phone")} /> {errors.phone && ( <span className="text-lg text-white mt-1"> {errors.phone.message} </span> )} </div> <div className="flex flex-col"> <input type="text" placeholder="Tên đăng nhập" className="pl-6 text-lg rounded" {...register("userName")} /> {errors.name && ( <span className="text-lg text-white mt-1"> {errors.name.message} </span> )} </div> <div className="flex flex-col"> <input type="text" placeholder="Địa chỉ" className="pl-6 text-lg rounded" {...register("address")} /> {errors.name && ( <span className="text-lg text-white mt-1"> {errors.name.message} </span> )} </div> <div className="flex flex-col"> <input type="password" placeholder="Mật khẩu" className="pl-6 text-lg rounded" {...register("password")} /> {errors.password && ( <span className="text-lg text-white mt-1"> {errors.password.message} </span> )} </div> <div className="flex flex-col"> <input type="password" placeholder="Xác nhận mật khẩu" className="pl-6 text-lg rounded" {...register("confirmpassword")} /> {errors.confirmpassword && ( <span className="text-lg text-white mt-1"> {errors.confirmpassword.message} </span> )} {message && ( <span className="text-lg text-white mt-1">{message}</span> )} </div> <div className="flex justify-between mt-2"> <Link to="/login" className="bg-[orange]/100 py-1 px-5 rounded-full" > Quay lại </Link> <button type="submit" className="bg-[orange]/100 py-1 px-5 rounded-full" > Đăng kí </button> </div> </form> </div> </div> ); }; export default Signin;
import { requestSignIn } from './api/sign-in.js'; function validateFormInput( $element, errorMessage, validate = (value) => !!value, ) { const $input = $element.querySelector('input'); const $formInputError = $element.querySelector('.form-input-error'); const currentValue = $input.value; const isValid = validate(currentValue); $element.classList.toggle('is-error', !isValid); $formInputError.textContent = isValid ? '' : errorMessage; return [currentValue, isValid]; } function init() { const $form = document.querySelector('.sign-in-form'); const $emailInput = $form.querySelector('.email-input'); const $passwordInput = $form.querySelector('.password-input'); const $formErrorMessage = $form.querySelector('.form-error-message'); $form.addEventListener('submit', async (event) => { event.preventDefault(); const [email, isEmailInputValid] = validateFormInput( $emailInput, '아이디 또는 이메일은 필수 입력값입니다.', ); const [password, isPasswordInputValid] = validateFormInput( $passwordInput, '비밀번호는 필수 입력값입니다.', ); if (!isEmailInputValid || !isPasswordInputValid) { return; } const { ok, errorMessage } = await requestSignIn(email, password); $formErrorMessage.classList.toggle('hidden', ok); if (ok) { window.location.replace('/'); } else { $formErrorMessage.textContent = errorMessage; } }); } init();
import React, {Component} from 'react'; import Aux from '../../hoc/Aux'; import Burger from '../../components/Burger/Burger'; import BuildControls from '../../components/Burger/BuildControls/BuildControls'; import Modal from '../../components/UI/Modal/Modal'; import OrderSummary from '../../components/Burger/OrderSummary/OrderSummary'; import axios from '../../axios-orders'; import Spinner from '../../components/UI/Spinner/Spinner'; import withErrorHandler from '../../hoc/withErrorHandler/withErrorHandler'; import { connect } from 'react-redux'; import * as actionTypes from '../../store/actions'; const INGREDIENT_PRICES = { salad: .5, cheese: .75, meat: 1, bacon: .7 } class BurgerBuilder extends Component{ // constructor(props){ // super(props); // this.state = {...} // } state = { totalPrice: 4, purchasable: false, purchasing: false, } componentDidMount () { // axios.get('https://react-my-burger-c39f5.firebaseio.com/ingredients.json') // .then(response => { // this.setState({ingredients: response.data}); // }); } addIngredientHandler = (type) =>{ const oldCount = this.state.ingredients[type]; const updatedCount = oldCount + 1; const updatedIngredients = { ...this.state.ingredients }; updatedIngredients[type] = updatedCount; const priceAddition = INGREDIENT_PRICES[type]; const oldPrice = this.state.totalPrice; const newPrice = oldPrice + priceAddition; this.setState({totalPrice: newPrice, ingredients: updatedIngredients}); console.log(this.state.totalPrice); this.updatePurchasable(updatedIngredients); } removeIngredientHandler = (type) => { const oldCount = this.state.ingredients[type]; const updatedCount = oldCount - 1; const updatedIngredients = { ...this.state.ingredients }; updatedIngredients[type] = updatedCount; const priceDeduction = INGREDIENT_PRICES[type]; const oldPrice = this.state.totalPrice; const newPrice = oldPrice - priceDeduction; this.setState({totalPrice: newPrice, ingredients: updatedIngredients}); console.log(this.state.totalPrice); this.updatePurchasable(updatedIngredients); } updatePurchasable(ingredients){ const sum = Object.keys(ingredients) .map(igKey => { return ingredients[igKey] }) .reduce( (sum, el) => { return sum+el; }, 0); this.setState({purchasable: sum > 0}); } purchaseHandler = () => { this.setState({purchasing: true}); } purchaseCancelHandler = () => { this.setState({purchasing: false}); } purchaseContinueHandler = () => { const queryParams = []; for(let i in this.state.ingredients){ queryParams.push(i + '=' + encodeURIComponent(this.state.ingredients[i])); } const queryString = queryParams.join('&'); this.props.history.push({ pathname: '/checkout', search: '?' + queryString, }); } render(){ const disabledInfo = { ...this.props.ings }; for(let key in disabledInfo){ disabledInfo[key] = disabledInfo[key] <= 0 } let orderSummary = null; let burger= <Spinner />; if(this.props.ings){ burger = ( <Aux> <Burger ingredients = {this.props.ings}/> <BuildControls ingredientsAdded = {this.props.onIngredientAdded} ingredientsRemoved= {this.props.onIngredientRemoved} disabled = {disabledInfo} price = {this.state.totalPrice} purchasable = {this.state.purchasable} ordered = {this.purchaseHandler} /> </Aux> ); orderSummary = <OrderSummary ingredients = {this.props.ings} purchaseCanceled = {this.purchaseCancelHandler} purchaseContinued = {this.purchaseContinueHandler} price = {this.state.totalPrice}/>; } if(this.state.loading){ orderSummary = <Spinner /> } return ( <Aux> <Modal show = {this.state.purchasing} modalClosed = {this.purchaseCancelHandler}> {orderSummary} </Modal> {burger} </Aux> ) } } const mapStateToProps = state => { return{ ings: state.ingredients } } const mapDispatchToProps = dispatch => { return{ onIngredientAdded: (ingName) => dispatch({type: actionTypes.ADD_INGERDIENT, ingredientName: ingName }), onIngredientRemoved: (ingName) => dispatch({type: actionTypes.REMOVE_INGERDIENT, ingredientName: ingName }) } } export default connect(mapStateToProps, mapDispatchToProps)(withErrorHandler(BurgerBuilder, axios));
<div class="cta-container"> <img src="assets/images/imagectaleft.png" alt="Left Image" class="cta-image left hide-on-mobile" /> <div class="cta-content"> <h2>Miss Rose</h2> <h3>Boutique</h3> <p>Découvrez notre collection exclusive</p> <p>Et mettez à jour votre garde-robe dés aujourd'hui.</p> <button class="cta-button" [routerLink]="'/category/' + nouvelleCollectionCategoryId" > EXPLOREZ NOS NOUVEAUX ARTICLES UNIQUES </button> </div> <img src="assets/images/imagectaright.png" alt="Right Image" class="cta-image right hide-on-mobile" /> </div> <div class="features-container"> <!-- Feature 1: Livraison Rapide --> <div class="feature"> <mat-icon class="feature-icon">local_shipping</mat-icon> <p class="feature-text">Livraison Rapide</p> <p class="feature-description">Expédition rapide de vos commandes</p> </div> <!-- Feature 2: Support 7j/7 --> <div class="feature"> <mat-icon class="feature-icon">support_agent</mat-icon> <p class="feature-text">Support 7j/7</p> <p class="feature-description">Assistance disponible 7 jours sur 7</p> </div> <!-- Feature 3: Échange Possible --> <div class="feature"> <mat-icon class="feature-icon">sync_alt</mat-icon> <p class="feature-text">Échange Possible</p> <p class="feature-description">Possibilité d'échanger vos articles</p> </div> <!-- Feature 4: Bon Rapport Qualité Prix --> <div class="feature"> <mat-icon class="feature-icon">monetization_on</mat-icon> <p class="feature-text">Bon Rapport Qualité Prix</p> <p class="feature-description"> Des articles de qualité à des prix compétitifs </p> </div> </div> <div class="collection-section"> <h1>Nouvelle Collection</h1> <div class="collection-articles"> <mat-card *ngFor="let article of newCollectionArticles" class="mat-card" [routerLink]="'/article/' + article.idArticle" > <mat-card-content class="article-content"> <div class="article-image"> <img src="{{ article.images[0]?.url_image }}" alt="{{ article.nomArticle }}" /> <div class="details-button">voir détails</div> </div> <div class="article-details"> <mat-card-title>{{ article.nomArticle }}</mat-card-title> <p class="prix">Prix : {{ article.prixArticle }} TND</p> <!-- Display Prix Soldé only if it has a non-null value --> <p class="prix" *ngIf="article.prixSolde !== null"> <span class="original-price" [ngClass]="{ discounted: article.prixSolde !== article.prixArticle }" > {{ article.prixArticle }} TND </span> <span *ngIf="article.prixSolde !== article.prixArticle" class="discounted-price" > Prix Soldé: {{ article.prixSolde }} TND </span> </p> </div> </mat-card-content> </mat-card> </div> <button class="cta-button" [routerLink]="'/category/' + nouvelleCollectionCategoryId" > Voir tout les articles </button> </div> <div class="collection-section"> <h1>Vêtements Automne/Hiver</h1> <div class="collection-articles"> <mat-card *ngFor="let article of vetementsAutomneHiverArticles" class="mat-card" [routerLink]="'/article/' + article.idArticle" > <mat-card-content class="article-content"> <div class="article-image"> <img src="{{ article.images[1]?.url_image }}" alt="{{ article.nomArticle }}" /> <div class="details-button">voir détails</div> </div> <div class="article-details"> <mat-card-title>{{ article.nomArticle }}</mat-card-title> <p class="prix">Prix : {{ article.prixArticle }} TND</p> <!-- Display Prix Soldé only if it has a non-null value --> <p class="prix" *ngIf="article.prixSolde !== null"> <span class="original-price" [ngClass]="{ discounted: article.prixSolde !== article.prixArticle }" > {{ article.prixArticle }} TND </span> <span *ngIf="article.prixSolde !== article.prixArticle" class="discounted-price" > Prix Soldé: {{ article.prixSolde }} TND </span> </p> </div> </mat-card-content> </mat-card> </div> <button class="cta-button" [routerLink]="'/category/' + vetementsAutomneHiverCategoryId" > Voir tout les articles </button> </div> <a class="sale-section-link" [routerLink]="'/category/' + soldesCategoryId"> <div class="sale-section"></div> </a> <div class="testimonial-section"> <p class="testimonial-text"> Explorez la mode aux côtés de Miss Rose en découvrant de magnifiques vêtements. </p> <p class="testimonial-text"> Chaque collection est conçue en Turquie avec des tissus performants complexes pour que vous vous sentiez belle, confiante et forte. </p> </div> <div class="avis"> <h2>Avis des clientes par messages en Instagram</h2> <app-image-carousel></app-image-carousel> </div>
library(grid) library(ggplot2) # ggplot2_3.4.0 library(ggrepel) # ggrepel_0.9.2 library(RColorBrewer) # RColorBrewer_1.1-3 library(svglite) # svglite_2.1.0 ### filter rows to common tested gene list, then merge. int.genes = intersect(rownames(Visium.pseudobulk.hippocampus.SOR.for.quadrant), rownames(bulk.RNA.seq.hippocampus.SOR.for.quadrant)) res = cbind(Visium.pseudobulk.hippocampus.SOR.for.quadrantv2[int.genes,], bulk.RNA.seq.hippocampus.SOR.for.quadrant[int.genes, c("logFC", "FDR")]) colnames(res)[2:3] = paste0("visium.", colnames(res)[2:3]) colnames(res)[4:5] = paste0("bulk", colnames(res)[4:5]) # switch logFC sign for experiment1 so CTRL+SOR samples have higher expression of positive fold change genes in both lists. res$visium.logFC = -1 * res$visium.logFC res$bulk.logFC = -1 * res$bulk.logFC # create signed log10(FDR) for visualization. res$visium.slfdr = log10(res$visium.FDR)*sign(res$visium.logFC) res$bulk.slfdr = log10(res$bulk.FDR)*sign(res$bulk.logFC) # create max FDR between both analyses for mapping to color/size. res$max.fdr = pmax(res$visium.FDR, res$bulk.FDR) ### set up color palette. palette.rdylbu = (RColorBrewer::brewer.pal(11, "RdYlBu")) max.fdr = 1 - res$max.fdr # if signs are concordant, use RdYlBu palette. Otherwise, use gray. sign.concord = sign(res$visium.slfdr) * (sign(res$bulk.slfdr) ) sign.direction = sign(res$visium.slfdr) color.data = max.fdr * sign.direction ### function to map numeric to color vectors. Found here: https://stackoverflow.com/questions/15006211/how-do-i-generate-a-mapping-from-numbers-to-colors-in-r/18749392, but unsure of original source. map2color = function (x, pal, limits = NULL) { if (is.null(limits)) limits = range(x) pal[findInterval(x, seq(limits[1], limits[2], length.out = length(pal) + 1), all.inside = TRUE)] } max.fdr.colors = map2color(x=color.data, pal=rev(colorRampPalette(palette.rdylbu)(101)), limits=c(-1, 1)) # change non-concordant genes to grey. idx.discordant = sign.concord == -1 max.fdr.colors[idx.discordant] = scales::alpha(rep("#AAAAAA", sum(idx.discordant)), max.fdr[idx.discordant]) p = ggplot(res, aes(visium.slfdr, bulk.slfdr)) + geom_point(color = ifelse(res$visium.FDR <= 0.05 & res$bulk.FDR <= 0.05, "red", "black")) p1 = p + geom_label_repel( aes(label=gene.name, size=0.1), #nudge_y = 36 - subset(dat, mpg > 30)$mpg, # segment.size = 0.1, segment.color = "grey50", force=.1, max.iter=10000, #direction = "x", seed=777, xlim=c(4.65, 5.45), ylim=c(0.4, 2.95), box.padding=0.18, label.padding=0.05, point.padding=0.09, label.size=0.1, direction="y" ) p2 = p + geom_label_repel( aes(label=gene.name, size=0.2), #nudge_y = 36 - subset(dat, mpg > 30)$mpg, segment.size = 0.1, segment.color = "grey50", force=0.4, max.iter=10000, # direction = "x", seed=777, xlim=c(-2.45, log10(0.05)), ylim=c(-2.95, log10(0.05)), box.padding=0.7, label.padding=0.3, point.padding=0.1, label.size=0.5 ) # Function: get the x and y positions of a single ggrepel label get.xy.pos.labs <- function(n) { grb <- grid.get(n) data.frame( x = xrg[1]+diff(xrg)*convertX(grb$x, "native", valueOnly = TRUE), y = yrg[1]+diff(yrg)*convertY(grb$y, "native", valueOnly = TRUE) ) } # Get x and y plot ranges xrg <- ggplot_build(p1)$layout$panel_params[[1]]$x.range yrg <- ggplot_build(p1)$layout$panel_params[[1]]$y.range # prep color data. channels.min = 0.1 channel.coef = 1.2 palette.rdylbu = (RColorBrewer::brewer.pal(11, "RdBu"))[-6] color.data = max.fdr * sign.direction max.fdr.colors = map2color(x=color.data, pal=rev(colorRampPalette(palette.rdylbu)(101)), limits=c(log10(0.05), -log10(0.05))) # change non-concordant genes to grey. idx.discordant = sign.concord == -1 max.fdr.colors[idx.discordant] = scales::alpha(rep("#AAAAAA" , sum(idx.discordant)), pmax(max.fdr[idx.discordant], channels.min)) # svglite("figures/bulk_bulk_scatterplot.svg", height=9.5, width=10.75, system_fonts = list(sans = "Arial")) par(mar=c(6,6,6,2), xpd=FALSE) plot( x=res$visium.slfdr, y=res$bulk.slfdr, pch=16, cex=0, cex.lab=1.2, cex.main=1.8, col=scales::alpha(max.fdr.colors, pmax(max.fdr, channels.min)*channel.coef), #ylim=c(-20,20), #xlim=c(-10,20), ylab=expression("signed -log"[10]*"(FDR) : bulk RNA-seq hippocampus"), xlab=expression("signed -log"[10]*"(FDR) : pseudobulk visium hippocampal subregions"), main="bulk RNA-seq Vs excitatory neurons" ) # add gridlines. abline(h=0, v=0, lty=1, lwd=1.5, col=scales::alpha("#333333", 0.8)) abline(h=c(log10(0.05), -log10(0.05)), v=c(log10(0.05), -log10(0.05)), col=scales::alpha("#333333", 0.8), lty=3, lwd=1.2) # add points. points( x=res$visium.slfdr, y=res$bulk.slfdr, pch=16, cex=pmax(max.fdr, channels.min)*channel.coef, col=scales::alpha(max.fdr.colors, pmax(max.fdr, channels.min)*channel.coef) ) # add labels. text(res$visium.slfdr, res$bulk.slfdr, res$gene.name, cex = 0.5, col="#444444", font=2, adj=0) # add legend. legend(3.25, -1.27, expression(bold("FDR = 0.05")), lwd=1.3, lty=3, cex=0.9, bty="n") legend(2.8, -1.7, c("discordant between experiments", "concordant: higher in both experiments", "concordant: lower in both experiments"), title=expression(bold("direction of effect")), fill=c("#AAAAAA", palette.rdylbu[c(3,8)]), cex=0.9) dev.off()
from fastapi import APIRouter, Depends, HTTPException from starlette import status from src.databases.model import Users import src.schemas.schema as SCHEMAS from jose import jwt, JWTError from passlib.context import CryptContext from fastapi.security import OAuth2PasswordBearer from typing import Annotated from src.databases.mysqldb import Base, engine from dotenv import load_dotenv import os from src.routers.authentication import db_dependency from sqlalchemy.orm import Session load_dotenv() SECRET_KEY = os.environ["JWT_AUTH_SECRET_KEY"] ALGORITHM = os.environ["JWT_AUTH_ALGORITHM"] router = APIRouter(prefix="/users", tags=["User Management"]) # def get_db(): # db = SessionLocal() # try: # yield db # finally: # db.close() # db_dependency = Annotated[Session, Depends(get_db)] bcrypt_context = CryptContext(schemes=["bcrypt"], deprecated="auto") oauth2_bearer = OAuth2PasswordBearer(tokenUrl="auth/token") async def get_current_user(token: Annotated[str, Depends(oauth2_bearer)]): try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) email: str = payload.get("sub") user_id: int = payload.get("id") if email is None or user_id is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate user", ) return {"email": email, "id": user_id} except JWTError: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate user" ) async def get_current_admin(token: Annotated[str, Depends(oauth2_bearer)]): try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) email: str = payload.get("sub") user_id: int = payload.get("id") role: str = payload.get("role") if email is None or user_id is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate user", ) if role and role.lower() == "admin": return {"email": email, "id": user_id, "role": role} else: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authorized with the current role assigned", ) except JWTError: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate user" ) user_dependency = Annotated[dict, Depends(get_current_user)] admin_dependency = Annotated[dict, Depends(get_current_admin)] @router.post("/create", status_code=status.HTTP_201_CREATED) async def create_user( db: db_dependency, admin: admin_dependency, create_user_request: SCHEMAS.CreateUserRequest, ): #Base.metadata.create_all(bind=engine) if admin: user = db.query(Users).filter(Users.email == create_user_request.email).first() if not user: create_user_model = Users( username=create_user_request.username, email=create_user_request.email, hashed_password=bcrypt_context.hash(create_user_request.password), role=create_user_request.role, scope=create_user_request.scope, status=create_user_request.status, ) db.add(create_user_model) db.commit() return { "success_msg": f"""A new user has been created having the credentials => username = {create_user_request.username}, email = {create_user_request.email}, role = {create_user_request.role}, scope = {create_user_request.scope}, status = {create_user_request.status}""" } else: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"user with email/username : {create_user_request.email} already exists", ) else: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authorized with the current role assigned", ) @router.get("/all", status_code=status.HTTP_200_OK) def get_all(db: db_dependency, admin: admin_dependency): if admin: users = db.query(Users).all() return users else: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authorized with the current role assigned", ) @router.get( "/get/{user_id}", status_code=status.HTTP_302_FOUND, response_model=SCHEMAS.GetUserRequestResponse, ) async def get_user(db: db_dependency, admin: admin_dependency, user_id: int): if admin: user = db.query(Users).filter(Users.id == user_id).first() if not user: raise HTTPException(status_code=404, detail="User not found") return { "user_id": user.id, "username": user.username, "email": user.email, "role": user.role, "scope": user.scope, "status": user.status, } else: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authorized with the current role assigned", ) @router.put( "/update/{user_id}", response_model=SCHEMAS.UpdateUserRequestResponse, status_code=status.HTTP_202_ACCEPTED, ) def update_user( user_update_data: SCHEMAS.UpdateUserRequest, db: db_dependency, admin: admin_dependency, user_id: int, ): if admin: if int(dict(user_update_data)["user_id"]) != int(user_id): raise HTTPException( status_code=404, detail="Request and the system id does not match" ) db_user = db.query(Users).filter(Users.id == user_id).first() if not db_user: raise HTTPException( status_code=404, detail=f"User with the id = {user_id} not found" ) user_update_data_dict = dict(user_update_data) if user_update_data.password: user_update_data_dict["hashed_password"] = bcrypt_context.hash( user_update_data.password ) for var, value in (user_update_data_dict).items(): setattr(db_user, var, value) if value else None db.add(db_user) db.commit() db.refresh(db_user) return { "user_id": db_user.id, "username": db_user.username, "email": db_user.email, "role": db_user.role, "scope": db_user.scope, "status": db_user.status, } else: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authorized with the current role assigned", ) @router.delete("/delete/{user_id}", status_code=status.HTTP_204_NO_CONTENT) def destroy(db: db_dependency, admin: admin_dependency, user_id: int): if admin: db_user = db.query(Users).filter(Users.id == user_id).first() if not db_user: raise HTTPException( status_code=404, detail=f"User with the id = {user_id} not found" ) db.query(Users).filter(Users.id == user_id).delete(synchronize_session=False) db.commit() return f"User with id = {user_id} has been deleted" else: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authorized with the current role assigned", )
set.seed(27) sample_data <- diabetes[sample(nrow(diabetes),25),] sample_mean_glucose <- mean(sample_data$Glucose) sample_highest_glucose <- max(sample_data$Glucose) population_mean_glucose <- mean(diabetes$Glucose) population_highest_glucose <- max(diabetes$Glucose) barplot( c(sample_mean_glucose, sample_highest_glucose, population_mean_glucose, population_highest_glucose), names.arg = c("Sample Mean", " Sample Highest", "Population Mean", "Population Highest"), col = c("green", "blue", "red", "orange"), ylim = c(0, max(sample_highest_glucose, population_highest_glucose) + 20), ylab = "Glucose Value", main = "Comparison of Glucose Statistics" ) legend("topright", legend = c("sample Mean", "Sample Highest", "Population Mean", "Population Highest"), fill = c("green", "blue", "red", "orange") ) sample_98th_percentile <- quantile(sample_data$BMI, 0.98) population_98th_percentile <- quantile(diabetes$BMI, 0.98) barplot(c(sample_98th_percentile, population_98th_percentile), names.arg = c("Sample 98th Percentile", "Population 98th Percentile"), col = c("green","blue") main = "Comparison of 98th Percentile", ylab = "BMI 98th Percentile" ) bootstrap_sampling <- function(diabetes, n_samples=500, sample_size=150){ sample_statistics <- matrix(nrow = n_samples, ncol=3) for(i in 1:n_samples){ sample <- sample(diabetes, size=sample_size, replace = TRUE) sample_statistics[i, 1] <- mean(sample) sample_statistics[i, 2] <- sd(sample) sample_statistics[i, 3] <- quantile(sample, 0.5) } return(sample_statistics) } blood_pressure_population <- diabetes$BloodPressure bootstrap_samples <- bootstrap_sampling(blood_pressure_population) population_mean_bp <- mean(blood_pressure_population) population_std_bp <- sd(blood_pressure_population) population_median_bp <- quantile(blood_pressure_population, 0.5) par(mfrow=c(1,3)) hist(bootstrap_samples[,1], main="Mean Comparision",xlab="Blood Pressure Mean", col = "blue") abline(v=population_mean_bp, col="red") hist(bootstrap_samples[,2], main="Standard Comparision",xlab="Blood Pressure Std", col = "green") abline(v=population_std_bp, col="red") hist(bootstrap_samples[,3], main="Median Comparision",xlab="Blood Pressure Median", col = "orange") abline(v=population_median_bp, col="red")
import numpy as np import matplotlib.pyplot as plt #Para pegar a representação polar vamos precisar da biblioteca numpy pois ela tem a função arctan e np.liang.norm # Definindo os vetores v1 = np.array([2, -1]) v2 = np.array([1, 1]) # Convertendo para representação polar teta1 = np.arctan2(v1[1], v1[0]) teta2 = np.arctan2(v2[1], v2[0]) r1 = np.linalg.norm(v1) r2 = np.linalg.norm(v2) # Calculando a soma dos vetores resultante = v1 + v2 tetares = np.arctan2(resultante[1], resultante[0]) rres = np.linalg.norm(resultante) # Plotando os vetores na representação polar plt.figure(figsize=(8, 8)) # Vetor 1 plt.polar([0, teta1], [0, r1], marker='o', label='Vetor 1') # Vetor 2 plt.polar([0, teta2], [0, r2], marker='o', label='Vetor 2') # Soma dos vetores plt.polar([0, tetares], [0, rres], marker='o', label='Resultante') plt.legend() plt.title('Soma dos vetores em cord polar') plt.grid(True) plt.show()
import { CssBaseline, ThemeProvider, Toolbar } from "@mui/material"; import * as React from "react"; import { Route, Routes } from "react-router-dom"; import { useTheme } from "../core/theme.js"; import { MovieDetails, Movies } from "../routes/index.js"; import { AppToolbar } from "./AppToolbar.js"; import { ErrorBoundary } from "./ErrorBoundary.js"; export function App(): JSX.Element { const theme = useTheme(); return ( <ThemeProvider theme={theme}> <CssBaseline /> <ErrorBoundary> <AppToolbar /> <Toolbar /> <Routes> <Route index element={<React.Suspense children={<Movies />} />} /> <Route path="/movieDetails/:imdbID" element={<React.Suspense children={<MovieDetails />} />} /> </Routes> </ErrorBoundary> </ThemeProvider> ); }
<!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>事件解绑</title> </head> <body> <button>点击</button> <!-- <script> const btn = document.querySelector('button'); btn.onclick = function () { alert('点击了'); // L0 事件移除解绑 btn.onclick = null } </script> --> <script> const btn = document.querySelector('button'); function fn () { alert('点击了'); } btn.addEventListener('click', fn); // L0 事件移除解绑 btn.removeEventListener('click', fn); // 注意:匿名函数无法被解绑 </script> </body> </html>
import "@babel/polyfill"; import "isomorphic-fetch"; import createShopifyAuth, { verifyRequest } from "@shopify/koa-shopify-auth"; import Shopify, { ApiVersion } from "@shopify/shopify-api"; import Koa from "koa"; import nextJS from "next"; import Router from "koa-router"; import bodyParser from "koa-bodyparser"; import serve from "koa-static"; import { receiveWebhook } from "@shopify/koa-shopify-webhooks"; // import middleware, routes, controllers, models, utils import { apiRouteMiddleware, errorHandlerMiddleware, verifyRequestMiddleware, } from "@middleware"; import combineRouters from "../routes/index"; import mongoConnect from "@utils/mongoConnect"; import customSessionStorage from "@utils/customSessionStorage"; import { paymentSuccess } from "@controllers/planController"; import { appUninstalled, getScriptTag, eraseShopData, eraseCustomerData, requestCustomerData, themePublish, } from "@controllers/webhookAndScriptTagController"; import { afterAuth } from "@controllers/authController"; // background process require("../all_background_process"); Shopify.Context.initialize({ // eslint-disable-next-line no-process-env API_KEY: process.env.SHOPIFY_API_KEY, API_SECRET_KEY: process.env.SHOPIFY_API_SECRET, SCOPES: process.env.SCOPES.split(","), HOST_NAME: process.env.HOST.replace(/https:\/\//, ""), API_VERSION: process.env.SHOPIFY_API_VERSION, IS_EMBEDDED_APP: true, SESSION_STORAGE: customSessionStorage, }); const port = parseInt(process.env.PORT, 10) || 8081; const dev = process.env.NODE_ENV !== "production"; const app = nextJS({ dev, }); const handle = app.getRequestHandler(); const webhook = receiveWebhook({ secret: process.env.SHOPIFY_API_SECRET }); app.prepare().then(async () => { const server = new Koa(); const router = new Router(); server.keys = [Shopify.Context.API_SECRET_KEY]; // use middleware server.use(serve("./public")); server.use(bodyParser()); server.use(errorHandlerMiddleware); server.use( createShopifyAuth({ accessMode: "offline", afterAuth, }) ); // Global Error Handler server.on("error", (err, ctx) => { const extraPrams = `[${new Date().toLocaleString([], { timeZone: "Asia/Dhaka", })}] - ${ctx?.request?.method} - ${ctx?.response?.status} - [${ ctx?.request?.url }] ==>`; console.log("\x1b[36m%s\x1b[0m", extraPrams, err); }); // Serve next.js const handleRequest = async (ctx) => { if (ctx.query.shop) { ctx.response.set( "Content-Security-Policy", `frame-ancestors https://${ctx.query.shop} https://admin.shopify.com` ); } await handle(ctx.req, ctx.res); ctx.respond = false; ctx.res.statusCode = 200; }; router.get("/plan", async (ctx) => { await handleRequest(ctx); }); router.get("/payment_success", paymentSuccess); router.get("/get_script", getScriptTag); // Webhook routes // App Uninstall webhook router.post("/app_uninstalled", webhook, appUninstalled); // Theme Publish Webhook router.post("/theme_publish", webhook, themePublish); // erase shop data Webhook router.post("/shop/data-erase", webhook, eraseShopData); // erase customer data Webhook router.post("/customer/data-erase", webhook, eraseCustomerData); // request customer data Webhook router.post("/customer/data-request", webhook, requestCustomerData); // Handle Graphql Request router.post("/graphql", verifyRequest(), async (ctx) => { await Shopify.Utils.graphqlProxy(ctx.req, ctx.res); }); router.use( "/api", apiRouteMiddleware, combineRouters.routes(), combineRouters.allowedMethods() ); router.get("(/_next/static/.*)", handleRequest); // Static content is clear router.get("/_next/webpack-hmr", handleRequest); // Webpack content is clear router.get("(.*)", verifyRequestMiddleware, handleRequest); // Everything else must have sessions server.use(router.allowedMethods()); server.use(router.routes()); // mongodb connect mongoConnect(process.env.MONGO_CONNECT_URI, port, server); });
openapi: 3.0.1 info: title: Service Openapi Yaml version: 2.0.0 servers: - url: "{server}:{port}/" variables: server: default: http://localhost port: default: "9090" paths: /greeting: put: summary: A resource for generating greetings operationId: getGreeting parameters: - name: name in: query description: the input string name required: true schema: type: string requestBody: content: text/plain: schema: $ref: "#/components/schemas/Person" responses: "200": description: Ok components: schemas: Person: type: object required: - id properties: name: type: string pattern: ^(?!(.*[\"\*\\\>\<\?\/\:\|]+.*)|(.*[\.]?.*[\.]+$)|(.*[ ]+$)) # Use case 01 : This pattern can not support via Ballerina regex maxLength: 14 hobby: type: array items: type: string pattern: '[ a-zA-Z0-9/.+!@#$%^&*()+\- ]*' id: type: integer maximum: 5 salary: type: string pattern: ^[a-zA-Z0-9_]+$ net: type: string pattern: ^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$ # Use case 02 : This pattern can not support via Ballerina regex count: type: integer
#include "NetPacket.h" NetPacket::NetPacket(NetMessages type, const uint8_t* data, size_t dataSize) { this->messageType = type; this->dataSize = dataSize; this->data = std::vector<uint8_t>(data, data + dataSize); // Copia i dati nel vettore } NetMessages NetPacket::getMsgType() const { return this->messageType; } const std::vector<uint8_t>& NetPacket::getData() const { return this->data; } size_t NetPacket::getDataSize() { return this->dataSize; } std::vector<uint8_t> NetPacket::serialize() const { std::vector<uint8_t> serializedData(sizeof(messageType) + sizeof(size_t) + dataSize); std::memcpy(serializedData.data(), &messageType, sizeof(messageType)); std::memcpy(serializedData.data() + sizeof(messageType), &dataSize, sizeof(size_t)); std::memcpy(serializedData.data() + sizeof(messageType) + sizeof(size_t), data.data(), dataSize); return serializedData; } std::string NetPacket::getStr() { return std::string(reinterpret_cast<const char*>(&this->data[0]), this->getDataSize()); } NetPacket NetPacket::deserialize(const std::vector<uint8_t>& serializedData) { NetMessages messageType; std::memcpy(&messageType, serializedData.data(), sizeof(messageType)); size_t dataSize; std::memcpy(&dataSize, serializedData.data() + sizeof(messageType), sizeof(size_t)); const uint8_t* dataPtr = serializedData.data() + sizeof(messageType) + sizeof(size_t); return NetPacket(messageType, dataPtr, dataSize); }
import axios from "axios"; import { getDatabase,ref,set } from "firebase/database"; import { useEffect, useState } from "react"; const Crud = () => { const [input,setInput] = useState({ name : '', email : '', password : '' }) const [item,setItem] = useState([]); const [editid,setEditid] = useState(false); const handleChange = (e) => { let name = e.target.name; let value = e.target.value; setInput({ ...input,[name] : value }) } const save = () => { const {name,email,password} = input; if(!name && !email && !password){ alert("All field requirement"); }else if(editid){ axios.put(`https://crud-realtime-db-9c5eb-default-rtdb.firebaseio.com/users/${editid}.json`,{ name : name, email : email, password : password }).then((response)=>{ if(response){ alert("record successfully edit"); } }) setInput({ name : '', email : '', password : '' }) setEditid(false); }else{ axios.post("https://crud-realtime-db-9c5eb-default-rtdb.firebaseio.com/users.json",{ name : name, email : email, password : password }).then((response)=>{ if(response){ alert("record successfully save"); } }) setInput({ name : '', email : '', password : '' }) } } const getAllrecord = () => { axios.get("https://crud-realtime-db-9c5eb-default-rtdb.firebaseio.com/users.json").then((res)=>{ let data = res.data; let record = []; for(let i in data){ record.unshift({ ...data[i],id : i }) } setItem(record); }) } getAllrecord(); const deletedata = (id) => { axios.delete(`https://crud-realtime-db-9c5eb-default-rtdb.firebaseio.com/users/${id}.json`).then((res)=>{ if(res){ alert("record successfully delete"); getAllrecord(); } }) } const editdata = (id) => { axios.get(`https://crud-realtime-db-9c5eb-default-rtdb.firebaseio.com/users/${id}.json`).then((res)=>{ if(res){ setInput(res.data); setEditid(id); } }) } useEffect(()=>{ getAllrecord(); },[]) return ( <> <center> <table border={1}> <tr> <td>Name :- </td> <td> <input type="text" name="name" onChange={ (e) => handleChange(e) } value={input.name} /> </td> </tr> <tr> <td>Email :- </td> <td> <input type="text" name="email" onChange={ (e) => handleChange(e) } value={input.email} /> </td> </tr> <tr> <td>Password :- </td> <td> <input type="text" name="password" onChange={ (e) => handleChange(e) } value={input.password} /> </td> </tr> <tr> <td></td> <td> { editid ? <input type="button" onClick={ () => save() } value="Edii"/> : <input type="button" onClick={ () => save() } value="Submit"/> } </td> </tr> </table><br></br><br></br> <table border={1}> <tr> <td>Name</td> <td>Email</td> <td>Password</td> <td>Action</td> </tr> { item.map((val)=>{ return ( <tr> <td>{val.name}</td> <td>{val.email}</td> <td>{val.password}</td> <td> <button onClick={ () => deletedata(val.id) }>Delete</button> <button onClick={ () => editdata(val.id) }>Edit</button> </td> </tr> ) }) } </table> </center> </> ) } export default Crud;
from django.http import HttpResponseRedirect from django.urls import reverse from django.shortcuts import render from django.views.generic.edit import CreateView from django.contrib.auth import get_user_model from .forms import SignUpForm class SignUpView(CreateView): model = get_user_model() form_class = SignUpForm template_name = "registration/signup.html" def post(self, request, *args, **kwargs): user_form = SignUpForm(request.POST) if user_form.is_valid(): user_form.save() return HttpResponseRedirect(reverse("accounts:login")) return render(request, "registration/signup.html", {"form": user_form})
import { useState, useEffect } from 'react'; import styles from './Treinos.module.css'; import { useFetchDocument } from '../../../hooks/useFetchDocument'; import CardTreino from '../../../components/CardTreino/CardTreino'; import CardTreinoB from '../../../components/CardTreinoB/CardTreinoB'; import { collection, getDocs, addDoc } from 'firebase/firestore'; // Import Firestore functions import { db } from '../../../firebase/config'; // Import the 'db' variable export const Treinos = () => { const { documents: perfil } = useFetchDocument('perfil'); const diasParaTreinar = perfil && +perfil.map((i) => i.disponibilidade); const [historico, setHistorico] = useState([]); useEffect(() => { const fetchHistorico = async () => { const historicoRef = collection(db, 'historico'); const snapshot = await getDocs(historicoRef); const historicoData = snapshot.docs.map((doc) => doc.data()); setHistorico(historicoData); }; fetchHistorico(); }, []); const handleTreinoFeito = async (treino, tempo) => { const data = new Date().toLocaleDateString(); const treinoRealizado = { treino, data, tempo }; const novoHistorico = [...historico, treinoRealizado]; setHistorico(novoHistorico); try { const historicoRef = collection(db, 'historico'); await addDoc(historicoRef, treinoRealizado); } catch (error) { console.error('Erro ao adicionar o treino ao histórico:', error); } }; const renderCardTreino = (cardA, cardB) => { let li = []; for (let i = 1; i <= diasParaTreinar; i++) { if (i % 2 === 0) { li.push( <CardTreinoB key={i} onTreinoFeito={handleTreinoFeito} treino={`Treino B - Dia ${i}`} /> ); } else { li.push( <CardTreino key={i} onTreinoFeito={handleTreinoFeito} treino={`Treino A - Dia ${i}`} /> ); } } return li; }; return ( <div className="container"> <div className={styles.treinos}> <h1>Treinos</h1> <ul className={styles.treinos_lista}> {renderCardTreino( <CardTreino onTreinoFeito={handleTreinoFeito} treino="Treino A - Dia 1" />, <CardTreinoB onTreinoFeito={handleTreinoFeito} treino="Treino B - Dia 2" /> )} </ul> </div> </div> ); };
const { Collection, PermissionFlagsBits } = require('discord.js'); const Guild = require('../structures/GuildSchema'); const User = require('../structures/UserSchema'); const GuildDataCache = require('../structures/cache/GuildDataCache'); const UserDataCache = require('../structures/cache/UserDataCache'); const DatabaseHelper = require('../helpers/DatabaseHelper'); const cooldown = new Collection(); class CommandExecutorService { constructor(interaction, client) { this.interaction = interaction; this.client = client || interaction.client; } async runCommand() { if (this.interaction.user.bot) return; if (!this.interaction.guild?.cache) { const data = await Guild.findOne({ guildId: this.interaction.guild.id }); if (!data) DatabaseHelper.createGuildEntry({ guildId: this.interaction.guild.id }); this.interaction.guild.cache = new GuildDataCache(data); } if (!this.interaction.user?.cache) { const data = await User.findOne({ guildId: this.interaction.guild.id, userId: this.interaction.user.id }); if (!data) DatabaseHelper.createUserEntry({ guildId: this.interaction.guild.id, userId: this.interaction.user.id }); this.interaction.user.cache = new UserDataCache(data); } const command = this.client.commands.get(this.interaction.commandName) || null; if (command) { if (!this.interaction.guild.members.me.permissionsIn(this.interaction.channel).has(PermissionFlagsBits.EmbedLinks)) return this.interaction.reply({ content: 'У меня нет права на встраивание ссылок, пожалуйста, выдайте мне его, чтобы я смог работать корректно!' }); try { command.run(this.client, this.interaction); } catch(error) { console.error(error); } if (command.cooldown != 0) { cooldown.set(this.interaction.user.id, command.name); setTimeout(() => cooldown.delete(this.interaction.user.id), command.cooldown * 1000); } } } } module.exports = CommandExecutorService;
import { NgModule } from '@angular/core' import { RouterModule, Routes } from '@angular/router' import { AuthGuard } from './core/guards/auth.guard' const routes: Routes = [ { path: 'dashboard', canActivate: [AuthGuard], loadChildren: () => import('./features/stacker/stacker.module').then((m) => m.StackerModule), }, { path: 'login', loadChildren: () => import('./features/auth/auth.module').then((m) => m.AuthModule), }, { path: '', redirectTo: '/', pathMatch: 'full', }, ] @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {}
import React, { useEffect, useRef, useState } from 'react'; import { useNavigate, useParams } from 'react-router'; import { SET_CURRENT_ROUTE } from '../../constants'; import { routes } from '../../constants/routes'; import { useDispatch, useSelector } from 'react-redux'; import { Button, Input, Popconfirm, Select } from 'antd'; import { useIsMobile } from '../../utils'; import { FlexSpace } from '../../styles'; import { ArrowUpOutlined, DownloadOutlined } from '@ant-design/icons'; import { MessagesWrapper } from '../../pages/styles'; import { getChats, getUserProfile, getUsers } from '../../store/selectors'; import Message from './Message'; import { message as msg } from 'antd'; import { createChat, deleteChats, updateChat } from '../../actions/ChatsActions'; import status from "http-status"; import { DeleteIcon } from '../../constants/icons'; const Chat = () => { const isMobile = useIsMobile(); const dispatch = useDispatch(); const { id } = useParams(); const [message, setMessage] = useState() const chats = useSelector(getChats); const [loading, setLoading] = useState() const history = useNavigate(); const profile = useSelector(getUserProfile) const [title, setTitle] = useState() const [model, setModel] = useState("GPT") const users = useSelector(getUsers) const messagesRef = useRef(); useEffect(() => { if (chats) { if (id && chats[id]) { dispatch({ type: SET_CURRENT_ROUTE, payload: { ...routes["home"], title: `${chats[id].title}` }, }); setTitle(chats[id].title) } else { if (!id) return msg.error("Chat no encontrado") history("/home") dispatch({ type: SET_CURRENT_ROUTE, payload: routes["home"], }); } } }, [id, dispatch, chats, history]) useEffect(() => { messagesRef.current.scrollTop = messagesRef.current.scrollHeight; if (chats && id && chats[id] && messagesRef.current) { messagesRef.current.scrollTop = messagesRef.current.scrollHeight; } }, [chats, id, messagesRef]) const handleMessage = async () => { if (loading) return if (!message) return setLoading(true) if (id && chats[id]) { const response = await dispatch(updateChat({ _id: chats[id]._id, messages: [...chats[id].messages, { user: profile._id, message }], model: model })) if (status[`${response.status}_CLASS`] === status.classes.SUCCESSFUL) { msg.success("Mensaje enviado") // Hacer scroll al final messagesRef.current.scrollTop = messagesRef.current.scrollHeight; } else { msg.error("Error al enviar el mensaje") setLoading(false) return; } } else { const response = await dispatch(createChat({ user: profile._id, messages: [{ user: profile._id, message }], model: model })) if (status[`${response.status}_CLASS`] === status.classes.SUCCESSFUL) { msg.success("Chat creado y mensaje enviado") history("/" + response.data._id) } else { msg.error("Error al crear el chat y enviar el mensaje") setLoading(false) return; } } setMessage() setLoading(false) } const handleSetTitle = async () => { if (loading) return if (!title) return if (title === chats[id].title) return setLoading(true) if (id && chats[id]) { const response = await dispatch(updateChat({ _id: chats[id]._id, title: title })) if (status[`${response.status}_CLASS`] === status.classes.SUCCESSFUL) { msg.success("Título actualizado") } else { msg.error("Error al actualizar el título") setLoading(false) return; } } setLoading(false) } const confirm = async () => { if (loading) return setLoading(true) history("/home") await dispatch(deleteChats([id])) setLoading(false) } const downloadChatCSV = async () => { if (loading) return setLoading(true) // Convertir los mensajes a CSV const csv = chats[id].messages.map((message) => { return `${message.user ? users[message.user]?.label : message.model},"${message.message}"` }).join("\n") // Descargar el CSV const element = document.createElement("a"); const file = new Blob([csv], { type: 'text/csv;charset=utf-8;' }); element.href = URL.createObjectURL(file); element.download = `${chats[id].title}.csv`; document.body.appendChild(element); element.click(); setLoading(false) } return ( <div style={{ position: "relative", overflow: "hidden" }}> <div style={{ width: "100%", display: "flex", alignItems: "center", position: "absolute", top: 10, padding: "0px 10px 0px 10px", justifyContent: "space-between" }}> {id && title && <div> <Input size='small' value={title} style={{ width: 150 }} placeholder='Título del chat...' onChange={(e) => setTitle(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") { handleSetTitle() } }} suffix={ <Button loading={loading} onClick={handleSetTitle} style={{ border: "none", boxShadow: "none", background: "rgba(255, 255, 255, 0.2)", width: 15, height: 15, fontSize: 10, padding: 0, color: loading ? "#fff" : "#38393F" }}> {!loading && <ArrowUpOutlined />} </Button> }></Input> <Popconfirm title="¿Está seguro de borrar este chat?" onConfirm={confirm} okText="Si" cancelText="No" > <Button className='delete-button-chat' style={{ width: 24, height: 24, padding: 0, marginLeft: 10, fontSize: 12 }} danger> <DeleteIcon></DeleteIcon></Button> </Popconfirm> </div> } <div> <Select style={{ marginLeft: 10, width: 150, }} size="small" value={model} onChange={setModel} options={[ { label: "GPT", value: "GPT" }, { label: "Llama", value: "Llama", disabled: true }, { label: "Mixtral", value: "Mixtral", disabled: true }, ]} placeholder="Modelo" allowClear={false}></Select> <Button style={{ width: 24, height: 24, padding: 0, marginLeft: 10, fontSize: 12 }} onClick={downloadChatCSV}><DownloadOutlined /></Button> </div> </div> <div style={{ width: isMobile ? "80%" : 708, position: "relative", height: isMobile ? "75vh" : "80vh", margin: "auto" }}> <MessagesWrapper ref={messagesRef} style={{ height: isMobile ? "60vh" : "73vh", overflowY: "auto", marginTop: 65 }}> {chats && chats[id] && chats[id].messages.map((message, index) => <Message key={index} user={message.user} message={message.message} model={message.model}></Message> )} </MessagesWrapper> <FlexSpace className='chatsearchwrapper' style={{ position: "absolute", bottom: 0 }}> <Input loading={loading} autoSize={{ minRows: 2, maxRows: 6 }} autoFocus={true} size={'large'} placeholder="Mensaje a Health Assistant..." allowClear onKeyDown={(e) => { if (e.key === "Enter") { handleMessage() } } } onChange={(e) => setMessage(e.target.value)} value={message} style={{ width: isMobile ? "80%" : "100%", margin: "auto", borderRadius: 10 }} suffix={ <Button loading={loading} onClick={handleMessage} style={{ border: "none", boxShadow: "none", background: "rgba(255, 255, 255, 0.2)", width: 30, height: 30, padding: 0, color: loading ? "#fff" : "#38393F" }}> {!loading && <ArrowUpOutlined />} </Button> } /> </FlexSpace> </div> </div> ); }; export default Chat;
package builder.builders import builder.components.Engine import builder.components.Transmission import builder.components.VehicleType interface IVehicleBuilder { fun setVehicleType(type: VehicleType) fun setSeats(seats: Int) fun setTransmission(transmission: Transmission) fun setEngine(engine: Engine) }
# Agenda: Kubernetes Setup Using Kubeadm In AWS EC2 Ubuntu Servers ## Prerequisite: 3 - Ubuntu Serves 1 - Manager (4GB RAM , 2 Core) t2.medium 2 - Workers (1 GB, 1 Core) t2.micro Note: Open Required Ports In AWS Security Groups. For now we will open All trafic. ## COMMON FOR MASTER & SLAVES START First, login as ‘root’ user because the following set of commands need to be executed with ‘sudo’ permissions. ``` sudo su - ``` # Install Required packages and apt keys. ``` apt-get update -y apt-get install -y apt-transport-https curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add - cat <<EOF >/etc/apt/sources.list.d/kubernetes.list deb https://apt.kubernetes.io/ kubernetes-xenial main EOF apt-get update -y ``` ## Turn Off Swap Space ``` swapoff -a sed -i '/ swap / s/^\(.*\)$/#\1/g' /etc/fstab ``` ## Install And Enable Docker ``` apt install docker.io -y usermod -aG docker ubuntu systemctl restart docker systemctl enable docker.service ``` ## Install kubeadm, Kubelet And Kubectl ``` apt-get install -y kubelet kubeadm kubectl kubernetes-cni ``` ## Enable and start kubelet service ``` systemctl daemon-reload systemctl start kubelet systemctl enable kubelet.service ``` ==========COMMON FOR MASTER & SLAVES END===== # Steps Only For Kubernetes Master ## Switch to the root user. ``` sudo su - ``` ## Initialize Kubernates master by executing below commond. ``` kubeadm init ``` ## exit root user & exeucte as normal user ``` exit mkdir -p $HOME/.kube sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config sudo chown $(id -u):$(id -g) $HOME/.kube/config ``` ## To verify, if kubectl is working or not, run the following command. ``` kubectl get pods -o wide --all-namespaces ``` You will notice from the previous command, that all the pods are running except one: ‘kube-dns’. For resolving this we will install a # pod network. To install the weave pod network, run the following command: ``` kubectl apply -f "https://cloud.weave.works/k8s/net?k8s-version=$(kubectl version | base64 | tr -d '\n')" kubectl get nodes kubectl get pods --all-namespaces ``` ## Get token ``` kubeadm token create --print-join-command ``` Add Worker Machines to Kubernates Master Copy kubeadm join token from and execute in Worker Nodes to join to cluster kubectl commonds has to be executed in master machine. Check Nodes kubectl get nodes Deploy Sample Application kubectl run nginx-demo --image=nginx --port=80 kubectl expose deployment nginx-demo --port=80 --type=NodePort Get Node Port details kubectl get services
import { SetStateAction, createContext, useState } from "react"; interface ModalContextProps { setAccept: React.Dispatch<SetStateAction<boolean>>; setAreYouSure: React.Dispatch<SetStateAction<boolean>>; setSendMail: React.Dispatch<SetStateAction<boolean>>; setClean: React.Dispatch<SetStateAction<boolean>>; areYouSure: boolean; accept: boolean; sendMail: boolean; clean: boolean; } export const ModalContext = createContext({} as ModalContextProps); interface ModalProviderProps { children: React.ReactNode; } export function ModalProvider({ children }: ModalProviderProps) { const [accept, setAccept] = useState(true); const [areYouSure, setAreYouSure] = useState(false); const [sendMail, setSendMail] = useState(false); const [clean, setClean] = useState(false); return ( <ModalContext.Provider value={{ areYouSure, setAreYouSure, accept, clean, setClean, setAccept, sendMail, setSendMail, }} > {children} </ModalContext.Provider> ); }
import { expect, test } from '@playwright/test'; test.describe('Single photo page', () => { test.beforeEach(async ({ page }) => { await page.goto('/photo/1'); await expect(page.getByRole('main')).toBeVisible(); }); test('has an accessible title', async ({ page }) => { await expect(page).toHaveTitle(/Photo - \w+/); }); test('lists a single photos', async ({ page }) => { const photos = page.getByRole('img'); await expect(photos).toHaveCount(1); }); test('displays informative error when photo is not found', async ({ page }) => { const alert = page.getByRole('alert'); await page.goto('/photo/invalid'); await expect(alert).toContainText(/Invalid photo ID 'invalid' given/); }); });
import React, { useRef, useEffect} from "react"; import curd from "../../curd/curd"; import Header from "../../components/header/Header"; import { ToastContainer, toast } from "react-toastify"; import "./home.css"; import "react-toastify/dist/ReactToastify.css"; export default function Home() { useEffect(() => { if (!curd.existsCollection("friends")) { const friends = curd.createCollection("friends"); friends.insertData({ allPair: [] }, curd); } },[]); const ref = useRef(null); const add = (e) => { e.preventDefault(); if (ref.current.value === "") { toast.error("Enter a name"); } else { if (curd.readData("users", { name: ref.current.value }).length > 0) { toast.error("Name is already present"); } else { try { let nm = ref.current.value; let col = curd.createCollection("users"); col.insertData( { name: nm, }, curd ); ref.current.value = ""; toast.success("Added", { autoClose: 1000 }); } catch (e) { toast.error("Something went wrong"); } } } }; return ( <> <Header /> <section className="home"> <div className="formcontainer"> <form action=""> <h4>Add Person</h4> <input type="text" placeholder="Enter Name" ref={ref} /> <button className="btn" onClick={add}> Add </button> </form> </div> </section> <ToastContainer /> </> ); }
package com.dorukaneskiceri.kotlincountries.service import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.dorukaneskiceri.kotlincountries.model.Country //might be arrayOf() or [] choose what you want @Database(entities = [Country::class], version = 1) abstract class CountryDatabase : RoomDatabase() { abstract fun countryDao(): CountryDAO //Singleton companion object { @Volatile private var instance: CountryDatabase? = null private val lock = Any() operator fun invoke(context: Context) = instance ?: synchronized(lock) { instance ?: makeDatabase(context).also { instance = it } } private fun makeDatabase(context: Context) = Room.databaseBuilder( context.applicationContext, CountryDatabase::class.java, "countrydatabase" ).build() } }
<?php namespace App\Http\Controllers; use App\Models\Aturan; use App\Models\Kasus; use App\Models\Penyakit; use Illuminate\Http\Request; class PenyakitController extends Controller { public function autoCode() { $lates_evidence = Penyakit::orderby('id', 'desc')->first(); $code = $lates_evidence->kode; $order = (int) substr($code, 1, 4); $order++; $letter = "K"; $code = $letter . sprintf("%04s", $order); return $code; } /** * Display a listing of the resource. */ public function index() { return view('penyakit.index', [ 'title' => 'penyakit', 'penyakit' => Penyakit::orderByDesc('kode')->get() ]); } /** * Show the form for creating a new resource. */ public function create() { return view('penyakit.create', [ 'title' => 'Penyakit', 'get_kode' => $this->autoCode(), ]); } /** * Store a newly created resource in storage. */ public function store(Request $request) { $request->validate([ 'nama' => 'required', 'definisi' => 'required', 'solusi' => 'required', ]); Penyakit::create([ 'kode' => $this->autoCode(), 'nama' => $request->nama, 'definisi' => $request->definisi, 'solusi' => $request->solusi ]); return redirect()->route('penyakit.index')->with('status', 'Data penyakit berhasil tersimpan!'); } /** * Display the specified resource. */ public function show(Penyakit $penyakit) { // } /** * Show the form for editing the specified resource. */ public function edit($id) { return view('penyakit.edit', [ 'title' => 'penyakit', 'get_penyakit' => Penyakit::findOrFail($id), ]); } /** * Update the specified resource in storage. */ public function update(Request $request, $id) { $request->validate([ 'nama' => 'required', 'definisi' => 'required', 'solusi' => 'required', ]); Penyakit::where('id',$id )->update([ 'nama' => $request->nama, 'definisi' => $request->definisi, 'solusi' => $request->solusi, ]); return redirect()->route('penyakit.index')->with('status', 'Data penyakit berhasil diubah!'); } /** * Remove the specified resource from storage. */ public function destroy($id) { $get_penyakit = Penyakit::where('id', $id)->get(); $get_penyakit->each->delete(); return redirect()->route('penyakit.index')->with('status', 'Data penyakit berhasil terhapus!'); } }
/*Author: Isha Gadani *Date: February 17, 2023 *Description: To find the surface area for the bread * * */ public class Hardbread { private double bread_length; private double bread_width; private double bread_height; private boolean isOlivebread; private static final double length_default = 21.5; private static final double width_default = 5.3; private static final double height_default = 5.5; public Hardbread() { this.bread_length = length_default; this.bread_width = width_default; this.bread_height = height_default; } public Hardbread(double bread_length, double bread_width, double bread_height, boolean isOlivebread) { this.bread_length = bread_length; this.bread_width = bread_width; this.bread_height = bread_height; this.setisOlivebread(isOlivebread); } public double getbread_length() { return bread_length; } public void setbread_length(double bread_length) { this.bread_length = bread_length; } public double getbread_width() { return bread_width; } public void setbread_width(double bread_width) { this.bread_width = bread_width; } public double getbread_height() { return bread_height; } public void setbread_height(double bread_height) { this.bread_height = bread_height; } public double calculateTSA() { return 2*((bread_length*bread_width)+(bread_width*bread_height)+(bread_height*bread_length)); } public boolean isOlivebread() { return isOlivebread; } public void setisOlivebread(boolean isOlivebread) { this.isOlivebread = isOlivebread; } public String toString() { return String.format("%.2f. %.2f, %.2f", bread_length, bread_width, bread_height); } }
<ion-header> <ion-toolbar> <ion-buttons slot="start"> <ion-back-button defaultHref="/" text=""></ion-back-button> </ion-buttons> <ion-title>Nouveau compte</ion-title> </ion-toolbar> </ion-header> <ion-content fullscreen="true"> <div id="container"> <form (ngSubmit)="submit()" [formGroup]="form"> <ion-item> <ion-label position="floating">Nom</ion-label> <ion-input formControlName="nom" type="text" autocomplete="family-name"></ion-input> </ion-item> <ion-item> <ion-label position="floating">Prénom</ion-label> <ion-input formControlName="prenom" type="text" autocomplete="given-name"></ion-input> </ion-item> <ion-item> <ion-label position="floating">Nom d'utilisateur</ion-label> <ion-input formControlName="nom_utilisateur" type="text"></ion-input> </ion-item> <ion-item> <ion-label position="floating">Date de naissance</ion-label> <ion-datetime formControlName="naissance" displayFormat="DD/MM/YYYY" autocomplete="bday" cancelText="Annuler" doneText="OK"> </ion-datetime> </ion-item> <ion-item> <ion-label position="floating">Adresse</ion-label> <ion-input formControlName="adresse" type="text" autocomplete="street-address"></ion-input> </ion-item> <ion-item> <ion-label position="floating">Ville</ion-label> <ion-input formControlName="ville" type="text" autocomplete="address-level2"></ion-input> </ion-item> <ion-item> <ion-label position="floating">Code postal</ion-label> <ion-input formControlName="cp" type="text" autocomplete="postal-code"></ion-input> </ion-item> <ion-item> <ion-label position="floating">Email</ion-label> <ion-input formControlName="email" type="mail" autocomplete="email"></ion-input> </ion-item> <ion-item> <ion-label position="floating">Mot de passe</ion-label> <ion-input formControlName="mdp" type="password" autocomplete="new-password" (keyup)="test($event)"></ion-input> </ion-item> <ion-item> <ion-label position="floating">Confirmation du mot de passe</ion-label> <ion-input formControlName="confirm_mdp" type="password" autocomplete="new-password"></ion-input> </ion-item> <ion-item> <ion-label position="stacked">Photo de profil</ion-label> <ion-input type="file" (change)="uploadFile($event)" formControlName="photo"></ion-input> </ion-item> <div *ngIf="pcent | async as pct"> Importation: {{ pct | number }}% <ion-progress-bar value="{{ pct / 100 }}"></ion-progress-bar> </div> <ion-button type="submit" shape="round" [disabled]="!form.valid" class="ion-text-uppercase"> Créer </ion-button> </form> </div> </ion-content>
import React from "react"; import { Box, Avatar, Typography, Divider, Rating, Tooltip, IconButton, CircularProgress, Dialog, DialogTitle, DialogContent, DialogActions, TextField, Button, } from "@mui/material"; import { useNavigate } from "react-router-dom"; import DeleteIcon from "@mui/icons-material/Delete"; import EditIcon from "@mui/icons-material/Edit"; import defaultPic from "../images/remy.jpg"; import fetchData from "../helper.js"; export default function CommentsList({ comments, setUpdateComments, updateComments, }) { const token = localStorage.getItem("token"); const navigate = useNavigate(); const [user, setUser] = React.useState(null); const [loading, setLoading] = React.useState(true); const [openEdit, setOpenEdit] = React.useState(false); const [editedComment, setEditedComment] = React.useState(""); const [editedRating, setEditedRating] = React.useState(0); const [editedId, setEditedId] = React.useState(null); const [picHover, setPicHover] = React.useState(false); async function loadU() { const data = await fetchData("GET", `api/user_details`, {}, token); return data; } React.useEffect(() => { async function loadUser() { if (token) { const userInfo = await loadU(); setUser(userInfo); } setLoading(false); } loadUser(); }, []); const editComment = () => { // post the edited comment console.log(editedRating); fetchData( "PUT", `api/${comments[0].recipeId}/comment`, { token: token, comment: editedComment, rating: editedRating, commentId: editedId, }, token ); setOpenEdit(false); setUpdateComments(!updateComments); }; const deleteComment = (commentId) => { fetchData( "DELETE", `api/${comments[0].recipeId}/comment`, { token: token, commentId: commentId, comment: "" }, null ); setUpdateComments(!updateComments); }; const avatarStyle = { margin: "20px", width: "60px", height: "60px" }; const avatarHoverStyle = { cursor: "pointer", margin: "20px", width: "60px", height: "60px", }; const flexStyle = { display: "flex", padding: "10px 0px" }; const commentBoxStyle = { padding: "20px" }; const ratingStyle = { marginLeft: "10px", marginTop: "-2px" }; const commentInputStyle = { marginTop: "10px" }; return ( <> {loading ? ( <Box sx={{ display: "flex" }}> <CircularProgress /> </Box> ) : ( <Box> {comments.map((comment, index) => { return ( <> <Divider /> <Box style={flexStyle}> {comment.profilePic ? ( <Avatar style={picHover ? avatarHoverStyle : avatarStyle} alt="user's profile picture" onMouseEnter={() => setPicHover(true)} onMouseLeave={() => setPicHover(false)} onClick={() => navigate(`/profile/${comment.userId}`)} src={comment.profilePic} /> ) : ( <Avatar style={picHover ? avatarHoverStyle : avatarStyle} alt="user's profile picture" onMouseEnter={() => setPicHover(true)} onMouseLeave={() => setPicHover(false)} onClick={() => navigate(`/profile/${comment.userId}`)} src={defaultPic} /> )} <Box style={commentBoxStyle}> <Typography variant="body2" onClick={() => navigate(`/profile/${comment.userId}`)} > @ {comment.username} </Typography> <Typography variant="body1">{comment.comment}</Typography> {comment.rating && ( <Box style={flexStyle}> <Divider light /> <Typography variant="body2">Rating: </Typography> <Rating style={ratingStyle} defaultValue={comment.rating} precision={0.5} readOnly /> </Box> )} {token && comment.userId === user.id && ( <Box> <Tooltip title="Edit Comment"> <IconButton> <EditIcon onClick={() => { setOpenEdit(true); setEditedComment(comment.comment); setEditedRating(comment.rating); setEditedId(comment.id); }} /> </IconButton> </Tooltip> <Tooltip title="Delete Comment"> <IconButton> <DeleteIcon onClick={() => { deleteComment(comment.id); }} /> </IconButton> </Tooltip> </Box> )} </Box> </Box> </> ); })} <Dialog open={openEdit} onClose={() => setOpenEdit(false)} aria-labelledby="edit-comments-dialog" aria-describedby="edit-comments-dialog" fullWidth maxWidth="md" > <DialogTitle>Edit Comment</DialogTitle> <DialogContent> <TextField fullWidth label="Edit Your Comment" style={commentInputStyle} value={editedComment} onChange={(e) => setEditedComment(e.target.value)} /> <Rating style={commentInputStyle} size="large" precision={0.5} value={editedRating} onChange={(e, newValue) => { setEditedRating(newValue); }} /> </DialogContent> <DialogActions> <Button variant="contained" onClick={editComment}> Edit Comment </Button> </DialogActions> </Dialog> </Box> )} </> ); }
import React, { useState } from "react"; import { Backdrop, Fade, Grid, IconButton, Modal, Paper, } from "@material-ui/core"; import CancelIcon from "@material-ui/icons/Cancel"; import { SignInForm, SignUpForm, ResetPassword, } from "../../Units/RegisterForm"; import { useStyles } from "./styles"; import signInCover from "../../Assets/PNGs/nftCover.jpg"; const AuthenticationModal = (props) => { const { isRegisterModalOpen, handleRegisterModalClose } = props; const classes = useStyles(); const [currentForm, setCurrentForm] = useState("signin"); const handleDontHaveAccount = () => { setCurrentForm("signup"); }; const handleAlreadyHaveAccount = () => { setCurrentForm("signin"); }; const handleResetPassword = () => { setCurrentForm("resetPass"); }; const handleModalClose = () => { handleRegisterModalClose(); handleAlreadyHaveAccount(); }; return ( <Modal open={isRegisterModalOpen} onClose={handleModalClose} closeAfterTransition BackdropComponent={Backdrop} BackdropProps={{ timeout: 500, }} > <Fade in={isRegisterModalOpen}> <Paper className={classes.modalRoot}> <Grid container> <Grid item lg={6} md={7} sm={12} xs={12} className={classes.formWrap} > {currentForm === "signin" ? ( <> <SignInForm handleResetPassword={handleResetPassword} handleModalClose={handleModalClose} /> <div className={classes.changeLink}> <p> Don't have an account? <button onClick={handleDontHaveAccount} className={classes.click} > Click here </button> </p> </div> </> ) : currentForm === "signup" ? ( <> <SignUpForm handleBack={handleAlreadyHaveAccount} /> <div className={classes.changeLink}> <p> Already have an account? <button onClick={handleAlreadyHaveAccount} className={classes.click} > Click here </button> </p> </div> </> ) : ( <ResetPassword onSignInClick={handleAlreadyHaveAccount} /> )} </Grid> <Grid item lg={6} md={5} className={classes.sideImg} style={{ backgroundImage: `url(${signInCover})` }} > <div className={classes.cancelIcon}> <IconButton className={classes.closeButton} onClick={handleModalClose} > <CancelIcon /> </IconButton> </div> </Grid> </Grid> </Paper> </Fade> </Modal> ); }; export default AuthenticationModal;
export const enum ErrorCode { ConnectionDestroyed = 'ConnectionDestroyed', ConnectionTimeout = 'ConnectionTimeout', } /** * specific error. */ export type PenpalError = Error & { code: ErrorCode }; export function createPenpalError(code: ErrorCode, msg: string): PenpalError { const error = new Error(msg) as PenpalError; error.code = code; return error; } type SerializedError = { name: string; message: string; stack: string | undefined; }; /** * Converts an error object into a plain object. */ export const serializeError = ({ name, message, stack }: Error): SerializedError => ({ name, message, stack, }); /** * Converts a plain object into an error object. */ export const deserializeError = (obj: SerializedError): Error => { const deserializedError = new Error(); Object.keys(obj) .forEach((key) => { // @ts-expect-error 不检测 deserializedError[key] = obj[key]; }); return deserializedError; };
export function LoginForm() { const handleLogin = async (e) => { e.preventDefault(); const loginForm = document.querySelector("#loginForm"); const username = loginForm.querySelector("#inputEmail").value; const password = loginForm.querySelector("#inputPassword").value; if (username === "" || password === "") { alert("Please fill out all fields!"); return; } // verify the user try { const res = await fetch(`/api/auth/login`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username: username, password: password }) }); if (!res.ok) { const data = await res.json(); alert(data.msg); return; } else { localStorage.setItem("user", username); window.location.href = "profile"; } } catch (err) { console.log(err); } } return ( <> <form className={`login-form`} id="loginForm" onSubmit={handleLogin} > <h2 class="title">Login</h2> <div class="mb-3"> <input type="text" class="form-control" id="inputEmail" aria-describedby="usernameHelp" autocomplete="username" placeholder="username" /> </div> <div class="mb-3"> <input type="password" class="form-control" id="inputPassword" placeholder="password" autocomplete="current-password" /> </div> <button type="submit" class="btn btn-primary hover" id="loginFormSubmit">Login</button> </form> </> ); }
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:my_threads/controllers/home_controller.dart'; import 'package:get/get.dart'; import 'package:my_threads/widgets/post_card.dart'; import '../../widgets/loading.dart'; class HomePage extends StatelessWidget { HomePage({Key? key}) : super(key: key); final HomeController controller = Get.put(HomeController()); @override Widget build(BuildContext context) { return Scaffold( body: Padding( padding: EdgeInsets.all(10.0), child: RefreshIndicator( onRefresh: () => controller.fetchThreads(), child: CustomScrollView( slivers: [ SliverAppBar( title: Padding( padding: EdgeInsets.only(top: 10), child: Image.asset("assets/images/logo.png", width: 40, height: 40,),), centerTitle: true, ), SliverToBoxAdapter( child: Obx(()=> controller.loading.value ? Loading () : ListView.builder( shrinkWrap: true, padding: EdgeInsets.zero, physics: BouncingScrollPhysics(), itemCount: controller.posts.length, itemBuilder: (context,index) => PostCard(post: controller.posts[index]),)), ) ], ), ),), ); } }
---- #### Reset --- Reset отлично работает на локальных ветках, в локальных репозиториях. Но этот метод переписывания истории не сработает на удалённых ветках, которые используют другие пользователи. ![[Снимок экрана 2022-10-25 в 01.21.29.png]] ```bash git reset HEAD~1 ``` ![[Снимок экрана 2022-10-25 в 01.21.59.png]] --- #### Revert --- Чтобы отменить изменения и поделиться отменёнными изменениями с остальными, надо использовать `git revert`. Посмотрим, как это работает ![[Снимок экрана 2022-10-25 в 01.23.11.png]] ```bash git revert HEAD ``` ![[Снимок экрана 2022-10-25 в 01.23.45.png]] > Забавно, появился новый коммит. Дело в том, что новый коммит `C2'` просто содержит изменения, полностью противоположные тем, что сделаны в коммите `C2`.
import { UserSchema } from "@modules/users"; import { IConversation, IMessage } from "./conversations.interface"; import SendMessageDto from "./dtos/send_message.dto"; import { HttpException } from "@core/exceptions"; import ConversationSchema from "./conversations.model"; export default class ConversationsService { public async sendMessage( userId: string, dto: SendMessageDto ): Promise<IConversation> { const user = await UserSchema.findById(userId).select('-password').exec(); if (!user) throw new HttpException(400, "User id is not exist"); const toUser = await UserSchema.findById(dto.to).select('-password').exec(); if (!toUser) throw new HttpException(400, "To user id is not exist"); if (!dto.conversationId) { let newConversation = await ConversationSchema.findOne({ $or: [ { $and: [{ user1: userId }, { user2: dto.to }] }, { $and: [{ user1: dto.to }, { user2: userId }] } ] }).exec(); if (newConversation) { newConversation.messages.unshift({ to: dto.to, text: dto.text, from: userId } as IMessage); } else { newConversation = new ConversationSchema({ user1: userId, user2: dto.to, messages: [{ from: userId, to: dto.to, text: dto.text }] }); await newConversation.save(); return newConversation; } await newConversation.save(); return newConversation; } else { const conversation = await ConversationSchema.findById(dto.conversationId).exec(); if (!conversation) throw new HttpException(400, "Conversation id is not exist"); if ((conversation.user1 !== userId && conversation.user2 != dto.to) || (conversation.user1 !== dto.to && conversation.user2 != userId)) throw new HttpException(400, "Conversation id is not exist"); conversation.messages.unshift({ to: dto.to, text: dto.text, from: userId } as IMessage); await conversation.save(); return conversation; } } public async getMyConversation(userId: string): Promise<IConversation[]> { const user = await UserSchema.findById(userId).select('-password').exec(); if (!user) throw new HttpException(400, "User id is not exist"); const conversations = await ConversationSchema.find({ $or: [{ user1: userId }, { user2: userId }] }).sort({ recent_date: -1 }).exec(); return conversations; } }
# Подвиг 3. Пусть имеется следующая модель: # # # --------- models.py ------------------------ # from django.db import models # # class Subject(models.Model): # slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="Слаг") # name = models.CharField(max_length=255, verbose_name="Название") # volume = models.PositiveIntegerField(default=16, verbose_name="Объем часов") # price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="Цена") # time_create = models.DateTimeField(auto_now_add=True, verbose_name="Время создания") # time_update = models.DateTimeField(auto_now=True, verbose_name="Время изменения") # is_active = models.BooleanField(default=False, verbose_name='Доступно') # # def get_absolute_url(self): # return reverse('subject', kwargs={'sub_slug': self.slug}) # # # --------- sitemaps.py ------------------------ # from django.contrib.sitemaps import Sitemap # # from .models import Subject # # # здесь продолжайте программу # Объявите класс SubjectSitemap, унаследованный от класса Sitemap, со следующим функционалом: # # через атрибуты класса: # # частота обновления страниц: ежедневно; # приоритет: 0,85; # через методы класса: # # items: выборка через стандартный менеджер записей (objects) модели Subject всех записей с is_active = 1 и volume > 0; # lastmod: возврат время последнего редактирования страницы (значения поля time_update). # P.S. На экран ничего выводить не нужно. # --------- models.py ------------------------ from django.db import models class Subject(models.Model): slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="Слаг") name = models.CharField(max_length=255, verbose_name="Название") volume = models.PositiveIntegerField(default=16, verbose_name="Объем часов") price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="Цена") time_create = models.DateTimeField(auto_now_add=True, verbose_name="Время создания") time_update = models.DateTimeField(auto_now=True, verbose_name="Время изменения") is_active = models.BooleanField(default=False, verbose_name='Доступно') def get_absolute_url(self): return reverse('subject', kwargs={'sub_slug': self.slug}) # --------- sitemaps.py ------------------------ from django.contrib.sitemaps import Sitemap # from .models import Subject class SubjectSitemap(Sitemap): changefreq = "daily" priority = 0.85 def items(self): return Subject.objects.filter(is_active=True, volume__gt=0) def lastmod(self, obj): return obj.time_update
package com.example.SpringBootProjekat.controllers; import com.example.SpringBootProjekat.entities.Comment; import com.example.SpringBootProjekat.entities.Topic; import com.example.SpringBootProjekat.entities.UserEntity; import com.example.SpringBootProjekat.services.CommentService; import com.example.SpringBootProjekat.services.TopicService; import com.example.SpringBootProjekat.services.UserService; import jakarta.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; @Controller @RequestMapping("/topic") public class TopicController { private final TopicService topicService; private final UserService userService; private final CommentService commentService; public TopicController(TopicService topicService, UserService userService, CommentService commentService) { this.topicService = topicService; this.userService = userService; this.commentService = commentService; } @GetMapping("/{id}") public String getCommentsPage(@PathVariable Long id, Model model) { Topic topic = topicService.getTopicById(id); if (topic == null) { return "redirect:/home"; } model.addAttribute("topic", topic); return "comments"; } @PostMapping("/{id}/addComment") public String addComment(@PathVariable Long id, @RequestParam("content") String content, Model model, HttpSession session){ Integer userid = (Integer) session.getAttribute("userid"); commentService.addCommentToTopic(userid, id, content); return "redirect:/topic/" + id; } }
<template> <Page class="make-plan" :withAppBar="!globalConfig.isWx"> <!-- 导航栏 --> <AppBar class="app-bar" v-if="!globalConfig.isWx"> <img slot="left" src="../../assets/imgs/common/icon/icon_back.png" class="icon icon-back" @click="goBack" /> <template slot="center"> 制作规划书 </template> </AppBar> <!-- 主体 --> <AppContent class="app-content"> <!-- 被保人信息 --> <Insurant ref="insurantRef" @chooseInsurant="chooseInsurant" /> <!-- 投保人信息 --> <Applicant ref="applicantRef" @chooseApplicant="chooseApplicant" @changeRelation="changeRelation" /> <!-- 险种信息 --> <ProductMsg @addProduct="addProduct" @delRisk="delRisk" /> <!-- 按钮组 --> <div class="btns"> <button class="view" @click="viewPlan">查看规划书</button> <button class="send" @click="sendPlan">生成规划书并发送</button> </div> </AppContent> </Page> </template> <script> import Applicant from "@/components/plan/Applicant"; import Insurant from "@/components/plan/Insurant"; import ProductMsg from "@/components/plan/ProductMsg"; import { mapState } from "vuex"; export default { name: "makePlan", components: { Applicant, Insurant, ProductMsg }, computed: { ...mapState({ insurant: state => state.plan.insurant, //被保人 applicant: state => state.plan.applicant, //投保人 mainProposalProductList: state => state.plan.mainProposalProductList, //主险列表 riskProposalProductList: state => state.plan.riskProposalProductList, //附加险列表 totalPremium: state => state.plan.totalPremium, //总保费 totalAmount: state => state.plan.totalAmount //总bao }) }, data() { return {}; }, watch: {}, created() { this.initPage(); }, methods: { //初始化页面 initPage() { //有主险,就要保费试算 if (this.mainProposalProductList.length != 0) { this.calcPremium(); } }, //保费试算 calcPremium() { const params = this.initCalcParams(); // console.log(params); utils.http.post(interfaces.plan.premiumCalc, params).then(res => { //总保费 this.$store.commit("plan/setState", { attr: "totalPremium", data: res.trialPremiumMobile.insurantProductList[0].plan.totalPremium }); //总保额 this.$store.commit("plan/setState", { attr: "totalAmount", data: res.trialPremiumMobile.insurantProductList[0].plan.totalAmount }); }); }, //保费试算参数拼接 initCalcParams() { //处理主险配置 let mainProposalProductItem = this.mainProposalProductList[0]; //主险项 let attList = mainProposalProductItem.attList; //主险的配置项 let mainSetting = { shebao: this.insurant.shebao, premiumDes: mainProposalProductItem.premium }; attList.forEach(element => { switch (element.attCode) { case "drawMode": //领取方式 mainSetting.drawMode = element.attValue; break; case "policyPeriod": //保险期限 mainSetting.policyPeriod = element.attValue; break; case "payPeriod": //交费期间 mainSetting.payPeriod = element.attValue; break; case "payMode": //缴费方式 mainSetting.payMode = element.attValue; break; } }); //处理投保人 let applicant = this.applicant; applicant.birthday = applicant.birthdate; applicant.jobLevel = applicant.cdOccupation.occupationRiskLevel; applicant.job = applicant.cdOccupation.occupationCode; //处理被保人 let insurant = this.insurant; insurant.birthday = insurant.birthdate; insurant.jobLevel = insurant.cdOccupation.occupationRiskLevel; insurant.job = insurant.cdOccupation.occupationCode; //处理附加险种 mainProposalProductItem.extraList = this.riskProposalProductList; mainProposalProductItem.extraList.forEach(item => { item.premiumDes = item.premium; item.isSelect = true; item.attList.forEach(el => { switch (el.attCode) { case "exceptAmt": //次免赔额 item.exceptAmt = el.attValue; break; case "claimRate": //次免赔额 item.claimRate = el.attValue; break; case "policyPeriod": //保险期限 item.policyPeriod = el.attValue; break; case "payPeriod": //交费期间 item.payPeriod = el.attValue; break; case "payMode": //缴费方式 item.payMode = el.attValue; break; } }); }); let params = { proposalPlan: { bookId: this.mainProposalProductList[0].bookId, holder: applicant, //投保人 insurantProductList: [ { insurant: insurant, //被保人 insuredId: "", planId: "", planInsureDate: "", productList: [ Object.assign(mainProposalProductItem, mainSetting) ], //主险种 proposalId: "", totalPremium: "0" } ], //主险 orgAgent: { agent: { email: "", mobile: "", personCode: "", personId: "", personName: "", sex: "", telephone: "" }, channel: "iwechat1", deviceNo: "572032449254344960", loginCode: "", openId: "oT-9Av8nXoxn3qnlDjopfnu8VHyI", token: "" }, totalAmount: this.totalAmount, totalPremium: this.totalPremium } }; return params; }, // 返回 goBack() { //主险清空 this.$store.commit("plan/setState", { attr: "mainProposalProductList", data: [] }); //附加清空 this.$store.commit("plan/setState", { attr: "riskProposalProductList", data: [] }); //总保费清空 this.$store.commit("plan/setState", { attr: "totalPremium", data: "" }); //总保额清空 this.$store.commit("plan/setState", { attr: "totalAmount", data: "" }); //投保人清空 this.$store.commit("plan/setState", { attr: "applicant", data: { name: "", sex: "0", //性别 birthdate: "", //职业信息 cdOccupation: { occupationCode: "", occupationLevel: "", occupationName: "", occupationRiskLevel: "", occupationRiskMetical: "" }, isoldCustomer: "0" //默认是新客户 } }); //被保人清空 this.$store.commit("plan/setState", { attr: "insurant", data: { name: "", sex: "0", birthdate: "", //职业信息 cdOccupation: { occupationCode: "", occupationLevel: "", occupationName: "", occupationRiskLevel: "", occupationRiskMetical: "" }, isoldCustomer: "0", //默认是新客户 holderRelation: "" //关系 } }); this.go("planList"); }, //查看规划书 viewPlan() { if (!this.isMsgEmpty()) return; }, //发送规划书 sendPlan() { if (!this.isMsgEmpty()) return; }, //添加险种 addProduct() { if (!this.isMsgEmpty()) return; let applicant = this.applicant; //投保人信息 let insurant = this.insurant; //被保人信息 this.goWithQuery("insuranceSelect", { applicantBirthday: applicant.birthdate, //投保人生日 insurantBirthday: insurant.birthdate, //被保人生日 insurantSex: insurant.sex, //被保人性别 holderRelation: applicant.holderRelation //关系 }); }, //删除险种 delRisk(data) { if (data.deltType == "main") { //删除的是主险种 //主险清空 this.$store.commit("plan/setState", { attr: "mainProposalProductList", data: [] }); //附加清空 this.$store.commit("plan/setState", { attr: "riskProposalProductList", data: [] }); //总保费清空 this.$store.commit("plan/setState", { attr: "totalPremium", data: "" }); } else { //删除的是附加险种 //附加重置 this.$store.commit("plan/setState", { attr: "riskProposalProductList", data: this.riskProposalProductList.filter((item, index) => { return index != data.delIndex; }) }); //总保费重置 this.$store.commit("plan/setState", { attr: "totalPremium", data: this.totalPremium - data.delObj.premium }); } }, //选择关系 changeRelation(holderRelation) { let isSelf = holderRelation == "00" ? true : false; //是否是本人 if (isSelf) { //本人 this.$nextTick(() => { this.$store.commit("plan/setState", { attr: "applicant", data: Object.assign({ holderRelation: "00" }, this.insurant) }); }); } else { //非本人 this.$nextTick(() => { this.$store.commit("plan/setState", { attr: "applicant", data: { name: "", sex: "0", //性别 birthdate: "", //职业信息 cdOccupation: { occupationCode: "", occupationLevel: "", occupationName: "", occupationRiskLevel: "", occupationRiskMetical: "" }, isoldCustomer: "0", //默认是新客户 holderRelation: holderRelation } }); }); this.chooseApplicant(); } }, //选择被保人 chooseInsurant() { this.goWithQuery("chooseCustomer", { id: 0 }); }, //选择投保人 chooseApplicant() { if (this.insurant.name == "") { utils.ui.confirm("请先选择被保人"); return; } if (this.applicant.holderRelation == "") { utils.ui.confirm("请先选择关系"); return; } if (this.applicant.holderRelation == "00") return; this.goWithQuery("chooseCustomer", { id: 1 }); }, //校验投、被保人信息 isMsgEmpty() { if (this.insurant.name == "") { utils.ui.confirm("请先选择被保人"); return false; } if (this.applicant.holderRelation == "") { utils.ui.confirm("请选择关系"); return false; } if (this.applicant.name == "") { utils.ui.confirm("请选择投保人"); return false; } return true; } }, beforeRouteLeave(to, from, next) { if ( this.$refs.applicantRef.$refs.jobSelector.showSelector || this.$refs.insurantRef.$refs.jobSelector.showSelector ) { // 有选择器为打开状态,先关闭 this.$refs.applicantRef.$refs.jobSelector.close(); this.$refs.insurantRef.$refs.jobSelector.close(); next(false); } else { next(); } } // activated() { // console.log(this.$store.state.plan.insurant); // console.log(this.$store.state.plan.applicant); // } }; </script> <style lang="scss" scoped> .app-bar { .icon { height: auto; &.icon-back { width: 11.5px; } } } .make-plan { .btns { padding: 0 40px 20px 40px; .view { margin-right: 30px; } button { width: 130px; height: 33px; display: inline-block; border: 1px solid $color-theme; border-radius: 16.5px; background: $color-bg; font-size: 13px; } } } </style>
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; class MailController extends Controller { public function sendEmail(Request $request) { $mail = new PHPMailer(true); try { $mail->SMTPDebug = 2; // 0 = off (for production use) - 1 = client messages - 2 = client and server messages $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'mail.bellakeofest.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = 'noreply@bellakeofest.com'; // SMTP username $mail->Password = 'Temporal123'; // SMTP password /*$mail->Host = 'smtp.gmail.com'; $mail->Username = 'ivancitoenano27@gmail.com'; $mail->Password = 'wxka rjwe qjjb dkav';*/ $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; $mail->Port = 465; $mail->setFrom('noreply@bellakeofest.com', 'Bellakeofest'); $mail->addAddress($request->email, $request->name); // Add a recipient $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Here is the subject'; $mail->Body = 'This is the HTML message body <b>in bold!</b>'; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; $mail->send(); return response()->json(['message' => 'Email has been sent']); } catch (Exception $e) { dd($e); return response()->json(['message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo]); } } }
import { RiCloseLine } from "react-icons/ri"; import React, { useReducer, useState } from "react"; import { gigReducer, initialState } from "../../reducers/gigReducer"; import upload from "../../utils/upload"; import { useMutation, useQueryClient } from "@tanstack/react-query"; import { useNavigate } from "react-router-dom"; import newRequest from "../../utils/newRequest"; const Add = () => { const [coverImg, setCoverImg] = useState(undefined); const [gigImages, setGigImages] = useState([]); const [uploading, setUploading] = useState(false); const [feature, setFeature] = useState(); const [state, dispatch] = useReducer(gigReducer, initialState); const navigate = useNavigate(); const queryClient = useQueryClient(); const mutation = useMutation({ mutationFn: (gig) => { return newRequest.post("gigs", gig); }, onSuccess: () => { queryClient.invalidateQueries("myGigs"); }, }); const handleChange = (e) => { dispatch({ type: "CHANGE_INPUT", payload: { name: e.target.name, value: e.target.value } }); }; const handleFeatures = (e) => { dispatch({ type: "ADD_FEATURE", payload: feature }); setFeature(""); }; const handleUpload = async () => { setUploading(true); try { const cover = await upload(coverImg); const images = await Promise.all( [...gigImages].map(async (img) => { const url = await upload(img); return url; }), ); setUploading(false); dispatch({ type: "ADD_IMAGES", payload: { cover, images } }); } catch (error) { console.log(error); } }; const handleSubmit = async (e) => { e.preventDefault(); mutation.mutate(state); navigate("/myGigs"); }; console.log(state); return ( <div className="p-4 lg:p-12"> <h2 className="h2">Add new gig</h2> <div className="border rounded"> <form onSubmit={handleSubmit} className="sections grid md:grid-cols-2 gap-8 "> <div className="md:col-span-1 p-3 rounded"> <div action="#" className="flex flex-col gap-2"> <div className="my-2 flex flex-col"> <Label required>Title</Label> <input type="text" placeholder="I will do something that I'm very good at" name="title" onChange={handleChange} required /> </div> <div className="my-2 flex flex-col"> <Label required>Categore</Label> <select name="cat" id="cat" onChange={handleChange} required> <option value="---">___</option> <option value="design">Design</option> <option value="web">Web Development</option> <option value="animation">Animation</option> <option value="music">Music</option> </select> </div> <div className="grid grid-cols-2 items-end gap-2"> <div> <div className="my-2 flex flex-col"> <Label required>Cover Image</Label> <input type="file" onChange={(e) => setCoverImg(e.target.files[0])} required /> </div> <div className="my-2 flex flex-col"> <label htmlFor="upload-image">Upload Images</label> <input type="file" multiple onChange={(e) => setGigImages(e.target.files)} /> </div> </div> <div className="my-2"> <button className="p-2 bg-[#1dbf73] rounded text-white text-lg hover:bg-green-600 transition duration-300 w-full" onClick={handleUpload} > {uploading ? "Uploading" : "Upload"} </button> </div> </div> <div className="my-2 flex flex-col"> <Label required>Description</Label> <textarea placeholder="A brief description to introduce your product to customer" className="h-52" onChange={handleChange} name="desc" required ></textarea> </div> </div> </div> {/* RIGHT PART */} <div className="md:col-span-1 p-3 rounded flex flex-col"> <div className="my-2 flex flex-col items-stretch"> <label htmlFor="service">Service Title</label> <input type="text" placeholder="(e.g): One page website" onChange={handleChange} name="shortTitle" /> </div> <div className="my-2 flex flex-col items-stretch"> <Label required>Short Description</Label> <textarea placeholder="Short description of you service" name="shortDesc" onChange={handleChange} required></textarea> </div> <div className="my-2 flex flex-col items-stretch"> <Label required>Delivery Time</Label> <input type="number" min={1} onChange={handleChange} name="deliveryTime" required /> </div> <div className="my-2 flex flex-col items-stretch"> <Label required>Revision Number</Label> <input type="number" min={1} onChange={handleChange} name="revisionNumber" required /> </div> <div className="my-2 flex flex-col items-stretch gap-1"> <label htmlFor="add-features">Add Features</label> <div className="flex gap-2"> <input value={feature} type="text" placeholder="e.g page design" className="flex-grow" onChange={(e) => setFeature(e.target.value)} /> <button onClick={handleFeatures} className="p-2 bg-[#1dbf73] rounded text-white text-lg hover:bg-green-600 transition duration-300" > Add </button> </div> <div className="flex gap-2"> {state.features.map((f, index) => ( <div key={index + f}> <div className="h-8 text-sm bg-transparent text-red-600 border border-red-500 rounded-sm px-1 flex gap-3 items-center"> <span>{f}</span> <RiCloseLine cursor="pointer" className="hover:bg-red-200" size={22} onClick={() => dispatch({ type: "REMOVE_FEATURE", payload: f })} /> </div> </div> ))} </div> </div> <div className="my-2 flex flex-col items-stretch"> <Label required>Price</Label> <input type="number" min={1} onChange={handleChange} name="price" required /> </div> <div className="my-2 flex flex-col"> <button type="submit" className="p-3 bg-[#1dbf73] rounded text-white text-lg hover:bg-green-600 transition duration-300" > Create </button> </div> </div> </form> </div> </div> ); }; const Label = ({ children, required }) => { return ( <label> {children} <span className="text-red-500">{required && "*"}</span> </label> ); }; export default Add;
import 'package:flutter/material.dart'; class AccessoryDetailScreen extends StatelessWidget { final String name; final double price; final int stars; final String imagePath; AccessoryDetailScreen({ required this.name, required this.price, required this.stars, required this.imagePath, }); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Détail du Produit'), ), body: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ // Photo de l'accessoire en grand Image.asset( imagePath, width: double.infinity, height: 200, fit: BoxFit.cover, ), // Informations détaillées sur l'accessoire Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // Nom de l'accessoire Text( name, style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold), textAlign: TextAlign.center, ), SizedBox(height: 8), // Prix de l'accessoire Text( '\$$price', style: TextStyle(fontSize: 20, color: Colors.green), textAlign: TextAlign.center, ), SizedBox(height: 8), // Nombre d'étoiles Row( mainAxisAlignment: MainAxisAlignment.center, children: List.generate( stars, (index) => Icon( Icons.star, color: Colors.yellow, ), ), ), SizedBox(height: 16), // Bouton Commander ElevatedButton( onPressed: () { // Ajoutez votre logique de commande ici ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('Commande validée'), duration: Duration(seconds: 2), ), ); Future.delayed(Duration(seconds: 2), () { Navigator.pop(context); }); }, style: ButtonStyle( padding: MaterialStateProperty.all(EdgeInsets.all(20.0)), ), child: Text('Commander'), ), ], ), ), ], ), ); } }
import Head from 'next/head' import Image from 'next/image' import Link from 'next/link' import { gql, useQuery } from "@apollo/client" import { format } from 'date-fns' import ptBR from 'date-fns/locale/pt-BR' import { CardPost } from '@/components/cardPost' import { Header } from '@/components/Header' import { Loading } from '@/components/loading' import { Empty } from '@/components/Empty' import { GetServerSideProps } from 'next' import { client } from '@/lab/apollo' const GET_ALL_POST = gql` query GetsAllPosts { posts(orderBy: createdAt_DESC) { id slug subtitle title createdAt coverimage { url } author { name } } } `; interface AllPosts { posts: { id: string; slug: string; subtitle: string; title: string; createdAt: string; coverimage: { url: string; } author: { name: string; } }[] } export default function Home({ posts }: AllPosts) { // const { loading, data, error } = useQuery<AllPosts>(GET_ALL_POST) // if (loading) return <Loading /> return ( <> <Head> <title>Jefferson Developer - Blog</title> <meta name="description" content="Generated by create next app" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> </Head> <div className="w-full max-w-[1120px] flex flex-col mx-auto pb-12 px-4"> <Header /> {posts ? <> <Link href={`/post/${posts[0].slug}`} className='w-full h-full flex gap-4 lg:gap-8 flex-col sm:flex-row items-center justify-center mt-12 hover:brightness-75 transition-all'> <div className='flex flex-1 w-full h-full min-h-[240px] md:h-[334px] relative rounded-2xl overflow-hidden'> <Image src={posts[0].coverimage.url} alt="" fill={true} style={{ objectFit: "cover" }} /> </div> <div className='flex flex-1 h-full flex-col gap-3 lg:gap-6'> <h1 className='font-bold text-3xl md:text-[40px] text-blue-600'>{posts[0].title}</h1> <p className='text-zinc-600 text-sm md:text-base text-justify lg:text-left'>{posts[0].subtitle}</p> <div> <p className='font-bold text-zinc-900 text-sm md:text-base'>{posts[0].author.name}</p> <p className='text-zinc-600 text-xs md:text-sm'>{format(new Date(posts[0].createdAt), "dd 'de' MMM 'de' yyyy", { locale: ptBR})}</p> </div> </div> </Link> <div className='flex flex-col items-center sm:grid grid-cols-2 md:grid-cols-3 gap-4 lg:gap-8 mt-12'> {posts.map((post, index) => { if (index !== 0) { return ( <CardPost key={post.id} title={post.title} author={post.author.name} createdAt={post.createdAt} subtitle={post.subtitle} urlImage={post.coverimage.url} slug={post.slug} /> ) } })} </div> </> : <Empty /> } </div> </> ) } export const getServerSideProps: GetServerSideProps = async (ctx) => { const {data} = await client.query({query: GET_ALL_POST}) return { props: { posts: data.posts, } } }
require(plyr) require(palmerpenguins) sse_mean = function(x) { sd(x, na.rm=TRUE) / sqrt(sum(!is.na(x))) } sse_mean(penguins$bill_depth_mm) sse_mean(penguins$body_mass_g) sse_mean(mtcars$mpg) two_group_resample = function(x, n_1, n_2) { dat_1 = sample(x, n_1, replace = TRUE) dat_2 = sample(x, n_2, replace = TRUE) difference_in_means = mean(dat_1, na.rm = TRUE) - mean(dat_2, na.rm = TRUE) return(difference_in_means) } two_group_resample(penguins$flipper_length_mm, 68, 152) table(penguins$species) set.seed(87) n = 2000 difference_in_means = c() for (i in 1:n) { difference_in_means = c( difference_in_means, two_group_resample(penguins$flipper_length_mm, 68, 152) ) } hist(difference_in_means, xlab = "Mean Differences") dat_pen = droplevels(subset(penguins, species != "Gentoo")) t_test = t.test(dat_pen$flipper_length_mm ~ dat_pen$species) t_test diff_observed = round(diff(t_test$estimate), digits = 3) print(diff_observed, digits = 3) sum(abs(difference_in_means) >= diff_observed) dat_pen$body_mass_g boxplot(body_mass_g ~ species, data = dat_pen) mass_t_test = t.test(dat_pen$body_mass_g ~ dat_pen$species) mass_t_test mass_diff = round(diff(mass_t_test$estimate), digits = 3) mass_diff
<template> <div class="category-heroshot deviceSearch-heroshot variation-heroshot lozad" data-background-image="https://cdn02.plentymarkets.com/ocqgl0v083vy/frontend/images/cat_bg_dummy_6.jpg" data-loaded="true" role="img" style=" background-image: url('https://cdn02.plentymarkets.com/ocqgl0v083vy/frontend/images/cat_bg_dummy_6.jpg'); " > <div class="container-max"> <div class="row justify-content-center"> <div class="col-12 col-sm-12 col-md-10 col-lg-9"> <div class="category-heroshot-container"> <h2 class="d-block h2 mb-3 mb-lg-4 pb-0"> Wählen Sie hier Ihr Ersatzteil </h2> <span class="d-block heroshot-description mb-3 mb-lg-5 font-weight-normal" >Blitzschnell das passende Ersatzteil finden</span > <div class="dropdown-container" id="seachCategoriesDropdown"> <div class="dropdown pt-4 border-0" :class="[facet.id, { active: activeTitle === facetName }]" v-if="facet.name" > <div class="h3 title py-0" @click="toggleActiveTitle(facetName)" > {{ facetName }} </div> <div class="form-check-container" v-show="activeTitle === facetName" > <div class="form-check-wrapper" v-for="value in facet.values" :key="value.id" > <div class="form-check mb-0 pl-0"> <input :id="'option-' + value.id + '-' + _uid" class="form-check-input d-none" type="checkbox" :checked="isSelected(value.id)" @change="updateFacet(value)" :disabled="isLoading || value.count <= 0" /> <label :for="'option-' + value.id + '-' + _uid" class="form-check-label" :class="[paddingClasses, 'option-' + value.id]" :style="paddingInlineStyles" > <div class="d-flex"> <span class="flex-grow-1">{{ value.name }}</span> <span class="filter-badge">{{ value.count }}</span> </div> </label> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </template> <script> import { mapState } from "vuex"; export default { name: "ItemFilterDeviceSearch", props: { facet: { type: Object, }, paddingClasses: { type: String, default: null, }, paddingInlineStyles: { type: String, default: null, }, }, data() { return { activeTitle: null, }; }, computed: { facetName() { return this.facet.name; }, ...mapState({ selectedFacets: (state) => state.itemList.selectedFacets, isLoading: (state) => state.itemList.isLoading, }), }, methods: { updateFacet(facetValue) { const toolbarElements = document.getElementsByClassName("widget-toolbar"); for (const toolbarElement of toolbarElements) { if (toolbarElement.contains(this.$vnode.elm)) { window.localStorage.setItem("openFilterToolbar", true); } } this.$store.dispatch("selectFacet", { facetValue }); }, isSelected(facetValueId) { return ( this.selectedFacets.findIndex( (selectedFacet) => selectedFacet.id === facetValueId ) > -1 ); }, toggleActiveTitle(title) { if (this.activeTitle === title) { this.activeTitle = null; } else { this.activeTitle = title; } }, }, }; </script>
<div class="min-w-full p-2 add-costfactor-item-overlay"> <form class="flex flex-col w-full"> <div class="pb-1"> <div class="text-3xl font-cairo font-bold mb-6"> Add Cost Factor </div> </div> <mat-dialog-content class="min-w-full relative mb-4"> <!--table component--> <div class="srm-bg mb-4 rounded-lg rounded-t-none"> <div class="p-4"> <div class="flex flex-wrap sm:flex-row align-center max-w-xs sm:max-w-none"> <div class="flex-col flex text-left mr-4"> <span> Cost Factor</span> <mat-form-field style="margin-top: 10px;"> <input matInput class="form-field" #input [(ngModel)]="CostFactorName" name="CostFactorName"> <!-- <mat-icon matSuffix>search</mat-icon> --> </mat-form-field> </div> <div class="flex-col flex text-left mr-4"> <span> Description</span> <mat-form-field style="margin-top: 10px;"> <input matInput class="form-field" #input [(ngModel)]="Description" name="CostFactorName"> <!-- <mat-icon matSuffix>search</mat-icon> --> </mat-form-field> </div> <div class="flex-col flex text-left mr-4"> <span> Cost Type</span> <mat-form-field style="margin-top: 10px;"> <mat-select [(ngModel)]="costTypeSelection" name="costTypeSelection"> <mat-option value="">Select Type</mat-option> <mat-option *ngFor="let cfType of costTypeList" [value]="cfType.id"> {{cfType.text}} </mat-option> </mat-select> </mat-form-field> </div> <button class="sm:inline-flex mt-8" mat-stroked-button [color]="'primary'" (click)="searchGroup()"> <mat-icon matPrefix class="icon-size-5 ml-8" [svgIcon]="'heroicons_solid:search'"> </mat-icon> <span class="mr-8 ml-4">Search</span> </button> </div> </div> </div> <!--base table component--> <mat-form-field class="w-full" appearance="fill"> <mat-label>Selected Cost Factor(s)</mat-label> <mat-chip-list #chipList aria-label="selection"> <mat-chip [disabled]="disabled" *ngFor="let x of selectedCostFactor"> {{x}} </mat-chip> </mat-chip-list> </mat-form-field> <div class="overflow-auto bg-gray-50 rounded-lg"> <div class="flex flex-auto w-full"> <!-- Products list --> <div class="flex flex-col flex-auto w-full"> <ng-container> <ng-container> <div class="grid attribute-items-parent overflow-x-auto w-full"> <!-- Header --> <div class="attribute-items-parent-grid z-10 sticky top-0 grid gap-4 pt-4 pb-2 px-2 text-secondary" matSort matSortDisableClear> <div></div> <div [mat-sort-header]="'Item'">Cost Factor Name</div> <div [mat-sort-header]="'Description'">Description</div> <div [mat-sort-header]="'Description'">Cost Type</div> <div></div> </div> <!-- Rows --> <ng-container *ngIf="costfactorModel && costfactorModel.length > 0"> <ng-container *ngFor="let costFactor of costfactorModel"> <div class="attribute-items-parent-grid grid items-center gap-4 py-px px-2 custom-tbl-row"> <div class="truncate"> <mat-checkbox [color]="'primary'" [checked]="costFactor.isChecked" [(ngModel)]="costFactor.isChecked" (change)="showOptions($event, costFactor.cfName)" name="{{costFactor.id}}-isChecked" [disabled]="costFactor.ischeckdisabled"></mat-checkbox> </div> <div class="truncate">{{costFactor.cfName}}</div> <div class="truncate">{{costFactor.cfDescription}}</div> <div class="truncate">{{costFactor.cfTypeName}}</div> <div class="ml-auto"> <button class="px-2 leading-6" mat-icon-button *ngIf="NewListId.length==0 " (click)=toggleDisplay(costFactor.id)> <mat-icon color="primary" class="icon-size-6" [svgIcon]="detailsDisplayMap.get(costFactor.id)? 'heroicons_outline:arrow-circle-up': 'heroicons_outline:arrow-circle-down'"> </mat-icon> </button> </div> </div> <div> <ng-container *ngIf="getactiveDetailsTab(costFactor.id)"> <div class="overflow-hidden"> <div class="flex"> <!-- Selected product details panel --> <div class="overflow-auto srm-bg2 rounded-lg mt-4 w-full"> <div class="grid pl-8 attribute-items-inner"> <!-- Header --> <div class="attribute-items-inner-grid custom-tbl-header grid gap-4 pt-2 pb-2 px-2 text-secondary" matSort matSortDisableClear> <div></div> <div [mat-sort-header]="'List_Name'"><b>List Name</b> </div> </div> <!-- Rows --> <ng-container> <div *ngFor="let costFactorGroup of costFactor.costFactorGroupModels;let i=index" class="attribute-items-inner-grid grid items-center gap-4 px-2 custom-tbl-row pb-2"> <div class="truncate" *ngIf="costFactorGroup.isDisplay"> <mat-checkbox [color]="'primary'" [checked]="costFactorGroup.isChecked" [(ngModel)]="costFactorGroup.isChecked" name="{{costFactorGroup.id}}-{{costFactor.id}}-isChecked" (change)="setParentIsChecked(costFactor, $event)" [disabled]="costFactorGroup.isdisable"> </mat-checkbox> </div> <div class="truncate" *ngIf="costFactorGroup.isDisplay"> {{costFactorGroup.name}}</div> </div> </ng-container> </div> </div> </div> </div> </ng-container> </div> </ng-container> </ng-container> </div> </ng-container> </ng-container> <ng-template #rowDetailsTemplate> </ng-template> <ng-template #noProducts> <div class="p-8 sm:p-16 text-4xl font-semibold tracking-tight text-center">There are no products!</div> </ng-template> </div> </div> <mat-paginator class="flex text-base justify-end" [length]="costfactorSearchModel.totalItems" [pageSize]="costfactorSearchModel.pageSize" [pageSizeOptions]="[5,10,15,20,25,100]" (page)="pageEvent=$event;OnPaginateChange($event)" showFirstLastButtons> </mat-paginator> </div> <div class="flex flex-col justify-start mt-5"> <div class="flex align-center text-warn font-medium mb-2" *ngIf="iserror"> <mat-icon [svgIcon]="'heroicons_outline:check-circle'" class="mr-2 text-warn"></mat-icon> <span>{{'Successfully saved'}}</span> </div> <div class="flex align-center text-green font-medium mb-2" *ngIf="issuccess"> <mat-icon [svgIcon]="'heroicons_outline:check-circle'" class="mr-2 text-green"></mat-icon> <span>{{'Something went wrong'}}</span> </div> </div> </mat-dialog-content> <mat-dialog-actions class="flex justify-end sticky bottom-0"> <button mat-button mat-dialog-close [color]="'primary'" (click)="doAction()" type="button"> <span class="mx-4">Cancel</span> </button> <button class="sm:inline-flex ml-4" mat-raised-button [color]="'primary'" type="button" (click)="SaveItem()" [disabled]="isSaved"> <span class="mx-4">Add</span> </button> </mat-dialog-actions> </form> </div>
# Constants initial_customers = 1000 churn_rate = 0.1 baseline_revenue_per_customer = 100 months = 24 team_size = 20 new_customers_per_salesperson = 5 revenue_growth_per_account_manager = 0.20 customers_per_account_manager = 25 csat_improvement_per_support = 0.01 churn_reduction_per_csat_point = 0.15 # AI-enhanced system assumptions ai_bot_improvement_factor = 2 ai_customers_per_month = new_customers_per_salesperson * ai_bot_improvement_factor ai_bots_managed_per_human = 5 total_ai_bots = team_size * ai_bots_managed_per_human # Identification phase duration identification_phase_months = 3 # Function to calculate revenue with the new strategy def calculate_revenue_with_strategy(): total_revenue = 0 current_customers = initial_customers revenue_per_customer = baseline_revenue_per_customer for month in range(1, months + 1): if month <= identification_phase_months: # All humans in sales during identification phase new_customers = team_size * new_customers_per_salesperson current_churn_rate = churn_rate else: # AI bots in sales with human oversight humans_in_sales = total_ai_bots // ai_bots_managed_per_human new_customers_from_ai = ai_customers_per_month * total_ai_bots new_customers = new_customers_from_ai + humans_in_sales * new_customers_per_salesperson # Remaining humans in Account Management and Support remaining_humans = team_size - humans_in_sales account_team = remaining_humans // 2 support_team = remaining_humans - account_team # Account Management and Support Adjustments if month <= 6 + identification_phase_months: revenue_per_customer *= (1 + revenue_growth_per_account_manager) csat_increase = support_team * csat_improvement_per_support current_churn_rate = max(churn_rate - (churn_rate * csat_increase * churn_reduction_per_csat_point), 0) current_customers += new_customers current_customers = int(current_customers * (1 - current_churn_rate)) monthly_revenue = current_customers * revenue_per_customer total_revenue += monthly_revenue return total_revenue # Calculating the revenue revenue = calculate_revenue_with_strategy()
<template> <modal-component :show-modal="showEditModal" modal-title="Edit Document Name" modal-type="confirm" @modal-close="closeEditNameModal" @modal-ok="onEditNameConfirm" @modal-cancel="closeEditNameModal" > <div slot="modal-body" class="modal-body"> <input type="text" class="input" :class="{ 'input_invalid': inputError }" @input="onDocumentNameChange" :value="value" > </div> </modal-component> </template> <script> import ModalComponent from '../common/ModalComponent.vue'; export default { props: { showEditModal: { type: Boolean, required: true }, value: { type: String }, closeEditNameModal: { type: Function, required: true }, updateNameAction: { type: Function, required: true } }, data() { return { inputError: false }; }, methods: { onDocumentNameChange(e) { const value = e.target.value; this.$emit('input', value); if (!value.trim() || value.trim().length < 3) { this.inputError = true; } else { this.inputError = false; } }, onEditNameConfirm() { if (!this.inputError) { this.updateNameAction({ name: this.value.trim() }); } }, }, components: { ModalComponent } }; </script>
/** ****************************************************************************** * @file stm32l4xx_nucleo_bus.h * @author MCD Application Team * @brief STM32L4xx_Nucleo board support package ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2017 STMicroelectronics International N.V. * All rights reserved.</center></h2> * * Redistribution and use in source and binary forms, with or without * modification, are permitted, provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific written permission. * 4. This software, including modifications and/or derivative works of this * software, must execute solely and exclusively on microcontroller or * microprocessor devices manufactured by or for STMicroelectronics. * 5. Redistribution and use of this software other than as permitted under * this license is void and will automatically terminate your rights under * this license. * * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef STM32L4xx_NUCLEO_BUS_H #define STM32L4xx_NUCLEO_BUS_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32wlxx_nucleo_conf.h" #include "stm32wlxx_nucleo.h" /** @addtogroup BSP * @{ */ /** @addtogroup STM32L4xx_NUCLEO * @{ */ /** @addtogroup STM32L4xx_NUCLEO_BUS * @{ */ /** @defgroup STM32L4xx_NUCLEO_BUS_Exported_Constants STM32L4xx NUCLEO BUS Exported Constants * @{ */ #ifndef BUS_I2C2_FREQUENCY #define BUS_I2C2_FREQUENCY 100000U /* Frequency of I2Cn = 100 KHz*/ #endif #define BUS_I2C2_INSTANCE I2C2 #define BUS_I2C2_CLK_ENABLE() __HAL_RCC_I2C2_CLK_ENABLE() #define BUS_I2C2_CLK_DISABLE() __HAL_RCC_I2C2_CLK_DISABLE() #define BUS_I2C2_SDA_GPIO_PIN GPIO_PIN_15 #define BUS_I2C2_SCL_GPIO_PIN GPIO_PIN_12 #define BUS_I2C2_SDA_GPIO_PORT GPIOA #define BUS_I2C2_SCL_GPIO_PORT GPIOA #define BUS_I2C2_SDA_GPIO_AF GPIO_AF4_I2C2 #define BUS_I2C2_SCL_GPIO_AF GPIO_AF4_I2C2 #define BUS_I2C2_SDA_GPIO_CLK_ENABLE() __HAL_RCC_GPIOA_CLK_ENABLE() #define BUS_I2C2_SCL_GPIO_CLK_ENABLE() __HAL_RCC_GPIOA_CLK_ENABLE() #ifndef BUS_I2C2_POLL_TIMEOUT #define BUS_I2C2_POLL_TIMEOUT 0x1000U #endif /** * @}STM32L4xx_NUCLEO_BUS_Exported_Constants */ /** @defgroup STM32L4xx_NUCLEO_BUS_Private_Types STM32L4xx NUCLEO BUS Private types * @{ */ #if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) typedef struct { pI2C_CallbackTypeDef pMspInitCb; pI2C_CallbackTypeDef pMspDeInitCb; }BSP_I2C_Cb_t; #endif /* (USE_HAL_I2C_REGISTER_CALLBACKS == 1) */ /** * @}STM32L4xx_NUCLEO_BUS_Private_Types */ /** @defgroup STM32L4XX_NUCLEO_LOW_LEVEL_Exported_Variables LOW LEVEL Exported Constants * @{ */ #ifdef HAL_I2C_MODULE_ENABLED //extern I2C_HandleTypeDef hbus_i2c2; #endif /* HAL_I2C_MODULE_ENABLED */ /** * @}STM32L4XX_NUCLEO_LOW_LEVEL_Exported_Variables */ /** @addtogroup STM32L4xx_NUCLEO_BUS_Exported_Functions * @{ */ int32_t HW_IO_Init(void); #ifdef HAL_I2C_MODULE_ENABLED HAL_StatusTypeDef new_MX_I2C2_Init(I2C_HandleTypeDef *phi2c, uint32_t timing); int32_t BSP_I2C2_Init(void); int32_t BSP_I2C2_DeInit(void); int32_t BSP_I2C2_IsReady(uint16_t DevAddr, uint32_t Trials); int32_t BSP_I2C2_WriteReg(uint16_t DevAddr, uint16_t Reg, uint8_t *pData, uint16_t Length); int32_t BSP_I2C2_ReadReg(uint16_t DevAddr, uint16_t Reg, uint8_t *pData, uint16_t Length); int32_t BSP_I2C2_WriteReg16(uint16_t DevAddr, uint16_t Reg, uint8_t *pData, uint16_t Length); int32_t BSP_I2C2_ReadReg16(uint16_t DevAddr, uint16_t Reg, uint8_t *pData, uint16_t Length); int32_t BSP_I2C2_Send(uint16_t DevAddr, uint8_t *pData, uint16_t Length); int32_t BSP_I2C2_Recv(uint16_t DevAddr, uint8_t *pData, uint16_t Length); #endif /* HAL_I2C_MODULE_ENABLED */ int32_t BSP_GetTick(void); #if defined(HAL_I2C_MODULE_ENABLED) && (USE_HAL_I2C_REGISTER_CALLBACKS == 1) int32_t BSP_I2C2_RegisterDefaultMspCallbacks (void); int32_t BSP_I2C2_RegisterMspCallbacks (BSP_I2C_Cb_t *Callbacks); #endif /* HAL_I2C_MODULE_ENABLED && (USE_HAL_I2C_REGISTER_CALLBACKS == 1) */ /** * @}STM32L4xx_NUCLEO_BUS_Exported_Functions */ /** * @}STM32L4xx_NUCLEO_BUS */ /** * @}STM32L4xx_NUCLEO */ /** * @}BSP */ #ifdef __cplusplus } #endif #endif /* STM32L4xx_NUCLEO_BUS_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
from django.shortcuts import render, redirect from django.contrib.auth import get_user_model from django.contrib import messages from django.contrib.auth.decorators import login_required from entrepreneurs.models import Entrepreneur from .forms import UserRegisterForm from django.contrib.auth.tokens import default_token_generator from django.contrib.sites.shortcuts import get_current_site from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.utils.encoding import force_bytes from django.template.loader import render_to_string from django.core.mail import send_mail from django.conf import settings from users.models import User from django.http import HttpResponse from django.views.decorators.http import require_GET UserModel = get_user_model() @require_GET def robots_txt(request): lines = [ "User-Agent: *", "Disallow: /admin/", "Sitemap: http://127.0.0.1:8000/sitemap.xml" if settings.DEBUG else "Sitemap: https://rafaela-emprende.herokuapp.com/sitemap.xml", ] return HttpResponse("\n".join(lines), content_type="text/plain") def register(request): if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() try: current_site = get_current_site(request) mail_subject = "Rafaela Emprende 💡 | Active su cuenta" message = render_to_string( "users/acc_active_email.html", { "user": user, "domain": current_site.domain, "uid": urlsafe_base64_encode(force_bytes(user.pk)), "token": default_token_generator.make_token(user), }, ) to_email = form.cleaned_data.get("email") send_mail( mail_subject, "", f'"Rafaela Emprende Team" <{settings.EMAIL_HOST_USER}>', [to_email], fail_silently=True, html_message=message, ) messages.success( request, f"¡Su cuenta ha sido creada! Por favor, revise su bandeja de entrada y confirme su dirección de correo electrónico para completar el registro", ) except Exception as e: messages.error(request, f"Falla al enviar el email de verificación.") return redirect("login") else: form = UserRegisterForm() return render(request, "users/register.html", {"form": form}) def activate(request, uidb64, token): try: uid = urlsafe_base64_decode(uidb64).decode() user = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if ( user is not None and default_token_generator.check_token(user, token) and not user.is_active ): user.is_active = True user.save() messages.success( request, f"Gracias por su confirmación por correo electrónico. Ya puede acceder a su cuenta.", ) else: messages.error(request, f"El link de activación es invalido!") return redirect("login") @login_required def profile(request): entrepreneur_selected = None try: entrepreneur_selected = Entrepreneur.objects.select_related().get( user=request.user ) except Entrepreneur.DoesNotExist: pass return render( request, "users/profile.html", {"entrepreneur": entrepreneur_selected}, ) @login_required def user_delete_view(request, pk): user_to_delete = request.user try: entrepreneur_selected = Entrepreneur.objects.select_related().get( user=user_to_delete ) except Entrepreneur.DoesNotExist: pass try: user_to_delete = User.objects.select_related().get(pk=user_to_delete.pk) user_to_delete.delete() messages.success(request, f"Su cuenta ha sido eliminada") return redirect("login") except Entrepreneur.DoesNotExist: messages.error( request, f"Hubo un error al eliminar su cuenta. Por favor intentelo de nuevo más tarde", ) return render( request, "users/profile.html", {"entrepreneur": entrepreneur_selected}, )
import React, { useState } from "react"; import TopProfile from "./TopProfile/TopProfile"; import SystemLogo from "../Logo/SystemLogo/SystemLogo"; import Search from "../../images/search.svg"; import {ReactComponent as Messeges} from "../../images/messeges.svg"; import s from "./Header.module.css"; import { NavLink, useHistory } from "react-router-dom"; import { observer } from "mobx-react-lite"; import photographersList from "../../store/photographersList"; const Header = observer(() => { const [fio, setFio] = useState(""); const history = useHistory(); const handleSubmit = (e) => { e.preventDefault(); history.push("/photographers"); }; return ( <div className={s.block}> <div className={s.content}> <NavLink to="/photographers"> <SystemLogo /> </NavLink> <div className={s.input}> <img className={s.inputIcon} src={Search} alt="" /> <form onSubmit={handleSubmit}> <input className={s.search} value={ document.location.pathname === "/photographers" ? photographersList.filters.fio : fio } onChange={(e) => { setFio(e.target.value); photographersList.setFilters("fio", e.target.value); }} placeholder="Поиск" ></input> </form> </div> <NavLink to="/orders" className={s.orders}> Заказы </NavLink> <NavLink to="/messeges" className={s.messagesButton}> <Messeges className={s.messages}/> </NavLink> <TopProfile /> <></> </div> </div> ); }); export default Header;
"use strict"; import { app, protocol, BrowserWindow, ipcMain, globalShortcut } from "electron"; import { createProtocol } from "vue-cli-plugin-electron-builder/lib"; import installExtension, { VUEJS_DEVTOOLS } from "electron-devtools-installer"; // const cron = require("node-cron"); const isDevelopment = process.env.NODE_ENV !== "production"; const basePath = isDevelopment ? "src/data" : "resources"; let win; import { dbRunner } from "./services/dbRunner"; import { saveToDrive, getBackup } from "./services/backup"; let dbProcess; global.logger = require("./services/logger"); global.user = "System"; logger.info(`Running app in ${process.env.NODE_ENV} mode`); import "./data/db/connection/localConnection"; // Scheme must be registered before the app is ready protocol.registerSchemesAsPrivileged([{ scheme: "app", privileges: { secure: true, standard: true } }]); process.on("uncaughtException", (err) => { logger.error({ message: err }); }); process.on("unhandledRejection", (err) => { logger.error({ message: err }); }); async function createWindow() { try { dbProcess = await dbRunner(isDevelopment ? "src/data" : "../resources"); } catch (err) { console.log("DB already running"); } logger.info(`DB instance start with pid : ${dbProcess.pid}`); let backupStatus = await getBackup(isDevelopment ? "src/data" : "../resources"); // logger.info(JSON.stringify(backupStatus)); // cron // .schedule( // "*/1 * * * *", // () => { // logger.info("Running scheduled Task : Uploading backup"); // saveToDrive(backupStatus.path, backupStatus.filename); // }, { // scheduled: true, // } // ) // .start(); // Create the browser window. win = new BrowserWindow({ title: "De company Biller", show: false, width: 1200, height: 900, backgroundColor: "#000", webPreferences: { // Use pluginOptions.nodeIntegration, leave this alone // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info nodeIntegration: true, contextIsolation: false, enableRemoteModule: true, }, }); win.setMenuBarVisibility(false); win.once("ready-to-show", () => { let systemCheck = verifySystem(); if (systemCheck.status) { logger.info(systemCheck.message); win.show(); } else logger.error(systemCheck.message); }); if (process.env.WEBPACK_DEV_SERVER_URL) { // Load the url of the dev server if in development mode await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL); } else { createProtocol("app"); // Load the index.html when not in development win.loadURL("app://./index.html"); openDevTools(); } } // Quit when all windows are closed. app.on("window-all-closed", () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== "darwin") { logger.info("Application exit"); app.quit(); } }); if (!isDevelopment) { app.on("browser-window-focus", function() { globalShortcut.register("CommandOrControl+R", () => { console.log("CommandOrControl+R is pressed: Shortcut Disabled"); }); globalShortcut.register("F5", () => { console.log("F5 is pressed: Shortcut Disabled"); }); }); app.on("browser-window-blur", function() { globalShortcut.unregister("CommandOrControl+R"); globalShortcut.unregister("F5"); }); } app.on("activate", () => { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (BrowserWindow.getAllWindows().length === 0) createWindow(); }); // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.on("ready", async() => { if (isDevelopment && !process.env.IS_TEST) { // Install Vue Devtools try { await installExtension(VUEJS_DEVTOOLS); } catch (e) { console.error("Vue Devtools failed to install:", e.toString()); } } createWindow(); }); // Exit cleanly on request from parent process in development mode. if (isDevelopment) { if (process.platform === "win32") { process.on("message", (data) => { if (data === "graceful-exit") { app.quit(); } }); } else { process.on("SIGTERM", () => { app.quit(); }); } } // Application business logic---------------------------------------------------------------------------------------------------------------- import customerModel from "./data/db/model/customer"; import vehiclesModel from "./data/db/model/vehicle"; import servicePackagesModel from "./data/db/model/servicePackage"; import billModel from "./data/db/model/bill"; import userModel from "./data/db/model/user"; import convertToObjectId from "./modules/uint8ArrayTo"; import generatePDF from "./services/PDFGenerator"; import mailer from "./services/Mailer"; import verifySystem from "./services/systemCheck"; const fs = require("fs"); const bcrypt = require("bcrypt"); ipcMain.on("create-customer", async(event, data) => { logger.info({ message: `Customer create [${data.name.firstName} ${data.name.middleName} ${data.name.lastName}]`, user }); let customer = new customerModel(data); try { await customer.save(); let res = await mailer.sendAccountCreation({ fullName: `${data.name.firstName} ${data.name.middleName} ${data.name.lastName}`, email: data.email, phone: data.phoneNumber, createdAt: new Date() }, data.email); logger.info(`Customer create [${data.name.firstName} ${data.name.middleName} ${data.name.lastName}] done.`); event.returnValue = { emailStatus: res.status, status: true, message: "Customer created", code: "SUCCESS_200", }; } catch (err) { if (err.code == 11000) { logger.error({ message: `Customer creation failed - Duplicate user found in Database`, user }); event.returnValue = { status: false, message: "Duplicate user found in Database", code: "ERR_DB", }; } else { logger.error({ message: `Customer creation failed - Unknown DB error ${err}`, user }); event.returnValue = { status: false, message: "Unknown DB error" + err, code: "ERR_DB", }; } } }); ipcMain.on("create-vehicle", async(event, data) => { logger.info({ message: `Vehicle create ${data.vehicleDetails.licensePlateNumber}`, user }); data.owner = convertToObjectId(data.owner.id)[1]; data.broughtIn = [data.owner]; let vehicle = new vehiclesModel(data); let result = null; try { result = await vehicle.save(); logger.info({ message: `Vehicle creation done`, user }); event.returnValue = { status: true, message: "Vehicle created", code: "SUCCESS_200", }; } catch (err) { if (err.code == 11000) { logger.error({ message: `Vehicle creation failed - Duplicate vehicle found in Database`, user }); event.returnValue = { status: false, message: "Duplicate vehicle found in Database", code: "ERR_DB", }; } else { logger.error({ message: `Vehicle creation failed - Unknown DB error ${err}`, user }); event.returnValue = { status: false, message: "Unknown DB error" + err, code: "ERR_DB", }; } } }); ipcMain.on("create-bill", async(event, data) => { logger.info({ message: `Bill create ${data.billNo}`, user }); try { data.broughtIn = convertToObjectId(data.broughtIn.id)[1]; data.vehicleID = convertToObjectId(data.vehicleID.id)[1]; for (let service of data.billDetails.servicePackageFinal) { service.package = convertToObjectId(service.package.id)[1]; } let bill = new billModel(data); let result = null; result = await bill.save(); let res = await mailer.sendTracking({ vehicle: data.vehicleName, billNo: data.billNo }, data.email); logger.info({ message: `Vehicle creation done`, user }); event.returnValue = { emailStatus: res.status, status: true, message: "Vehicle created", code: "SUCCESS_200", }; } catch (err) { if (err.code == 11000) { logger.error({ message: `Vehicle creation failed - Duplicate vehicle found in Database`, user }); event.returnValue = { status: false, message: "Duplicate Bill found in Database", code: "ERR_DB", }; } else { logger.error({ message: `Vehicle creation failed - Unknown DB error ${err}`, user }); event.returnValue = { status: false, message: "Unknown DB error" + err, code: "ERR_DB", }; } } }); ipcMain.on("find", async(event, data) => { try { let res = await vehiclesModel.findOne({ "vehicleDetails.licensePlateNumber": data.licensePlateNumber }).populate("broughtIn").lean({ virtuals: true }); if (!res) throw new Error(); event.returnValue = { status: true, message: res, code: 200 }; } catch (err) { logger.error({ message: `Searching ${data.type}-${data.licensePlateNumber} failed ${err}`, user }); event.returnValue = { status: false, message: err, code: 500 }; } }); ipcMain.on("authenticate", async(event, data) => { try { logger.info(`Authenticating user : ${data.username}`); let res = await userModel.findOne({ username: data.username }).lean({ virtuals: true }); if (!res || res.length == 0 || !bcrypt.compareSync(data.password, res.password)) throw new Error(); global.user = data.username; logger.info(`User ${data.username} authenticated`); event.returnValue = { status: true, message: res, code: 200 }; } catch (err) { logger.error("User authentication failed"); logger.error(err); event.returnValue = { status: false, message: err, code: 500 }; } }); ipcMain.on("fetch", async(event, data) => { logger.info({ message: `Fetching details {${data.type}}`, user }); let res = null; try { switch (data.type) { case "customer": { res = await customerModel.find({}).lean({ virtuals: true }); break; } case "vehicle": { res = await vehiclesModel.find({ owner: convertToObjectId(data.customerId.id)[1] }).lean({ virtuals: true }); break; } case "service": { res = await servicePackagesModel.find({}).lean({ virtuals: true }); break; } case "service-by-id": { res = await servicePackagesModel .findById(convertToObjectId(data.id.id)[1]) .populate({ path: "billDetails.servicePackageFinal", populate: { path: "package" }, }) .lean({ virtuals: true }); break; } case "bill-by-open": { res = await billModel.find({ billStatus: "open" }).populate("vehicleID").populate("billDetails.servicePackageFinal.package").populate("broughtIn").lean({ virtuals: true }); break; } case "bill-by-open-vehicle": { res = await billModel.find({ billStatus: "open" }).populate("vehicleID").lean({ virtuals: true }); res = res.some((bill) => { return bill.vehicleID.vehicleDetails.licensePlateNumber == data.licensePlateNumber; }); break; } case "bill-all": { res = await billModel.find({}).populate("vehicleID").populate("broughtIn").populate("billDetails.servicePackageFinal.package").lean({ virtuals: true }); break; } case "bill-by-open-close": { res = { close: await billModel.find({ "vehicleStatus.status": "Ready to Deliver" }).populate("vehicleID").populate("broughtIn").populate("billDetails.servicePackageFinal.package").lean({ virtuals: true }), edit: await billModel .find({ $and: [{ "vehicleStatus.status": { $ne: "Ready to Deliver" } }, { "vehicleStatus.status": { $ne: "Delivered" } }], }) .populate("vehicleID") .populate("billDetails.servicePackageFinal.package") .lean({ virtuals: true }), }; break; } default: { res = []; } } logger.info({ message: `Fetching details {${data.type}} done`, user }); event.returnValue = { status: true, message: res, code: 200 }; } catch (err) { logger.error({ message: `Fetching details failed - {${err}}`, user }); event.returnValue = { status: false, message: err, code: 500 }; } }); ipcMain.on("package", async(event, data) => { logger.info({ message: `Package {${data.type}}-ing`, user }); try { let result = null; switch (data.type) { case "update": { delete data.data._id; delete data.data.createdAt; delete data.data.updatedAt; result = await servicePackagesModel.findOneAndUpdate({ _id: convertToObjectId(data.id.id)[1] }, {...data.data }, { upsert: true }); break; } case "save": { result = new servicePackagesModel(data.data); result = await result.save(); break; } case "delete": { result = await servicePackagesModel.findOneAndDelete({ _id: convertToObjectId(data.id.id)[1] }); break; } } logger.info({ message: `Package {${data.type}}-ing done`, user }); event.returnValue = { status: true, message: JSON.parse(JSON.stringify(result)), code: "SUCCESS_200", }; } catch (err) { logger.error({ message: `Package {${data.type}}-ing failed : Unknown DB error ${err}`, user }); event.returnValue = { status: false, message: "Unknown DB error" + err, code: "ERR_DB", }; } }); ipcMain.on("bill-stats", async(event, data) => { try { let result = { total: 0, pending: { open: 0, close: 0 }, today: { open: 0, close: 0 }, }; let bills = await billModel.find({}).lean(); for (let bill of bills) { ++result.total; if (bill.billStatus == "open") { ++result.pending.open; if (new Date(bill.createdAt).toLocaleDateString().includes(new Date().toLocaleDateString())) ++result.today.open; } else { ++result.pending.close; if (new Date(bill.createdAt).toLocaleDateString().includes(new Date().toLocaleDateString())) ++result.today.close; } } logger.info({ message: `Bill status fetch done`, user }); event.returnValue = { status: true, message: result, code: "SUCCESS_200", }; } catch (err) { logger.error({ message: `Bill status fetch failed : Unknown DB error ${err}`, user }); event.returnValue = { status: false, message: "Unknown DB error" + err, code: "ERR_DB", }; } }); ipcMain.on("update-customer", async(event, data) => { try { await customerModel.findOneAndUpdate({ _id: convertToObjectId(data.id.id)[1] }, data); logger.info({ message: `Customer ${data.name.firstName} ${data.name.middleName} ${data.name.lastName} Update done `, user }); event.returnValue = { status: true, message: "Updated", code: "SUCCESS_200", }; } catch (err) { if (err.code == 11000) { logger.error({ message: `Customer ${data.name.firstName} ${data.name.middleName} ${data.name.lastName} Update failed : Duplicate user found in Database`, user }); event.returnValue = { status: false, message: "Duplicate user found in Database", code: "ERR_DB", }; } else { logger.error({ message: `Customer ${data.name.firstName} ${data.name.middleName} ${data.name.lastName} Update failed : Unknown DB error ${err}`, user }); event.returnValue = { status: false, message: "Unknown DB error : " + err, code: "ERR_DB", }; } } }); ipcMain.on("update-vehicle-status", async(event, data) => { try { await billModel.findOneAndUpdate({ _id: convertToObjectId(data.id.id)[1] }, { "vehicleStatus.status": data.status, "vehicleStatus.time": new Date() }); logger.info({ message: `Vehicle status [${data.status}] update done`, user }); event.returnValue = { emailStatus: data.status == "Ready to Deliver" ? await mailer.sendDelivery({ licensePlateNumber: data.licensePlateNumber }, data.email) : false, status: true, message: "Bill Updated", code: "SUCCESS_200", }; } catch (err) { if (err.code == 11000) { logger.error({ message: `Vehicle status update failed : Duplicate user found in Database`, user }); event.returnValue = { status: false, message: "Duplicate user found in Database", code: "ERR_DB", }; } else { logger.error({ message: `Vehicle status update failed : Unknown DB error ${err}`, user }); event.returnValue = { status: false, message: "Unknown DB error" + err, code: "ERR_DB", }; } } }); ipcMain.on("update-bill", async(event, data) => { try { data.serviceCart = data.serviceCart.map(function(i) { i.package._id = convertToObjectId(i.package._id.id)[1]; return i; }); data.additionalCharges = data.additionalCharges.map(function(i) { if (i._id) i._id = convertToObjectId(i._id.id)[1]; return i; }); await billModel.findOneAndUpdate({ _id: convertToObjectId(data.id.id)[1] }, { "billDetails.additionalCharges": data.additionalCharges, "billDetails.servicePackageFinal": data.serviceCart }); logger.info({ message: `Bill update done`, user }); event.returnValue = { status: true, message: "Bill Updated", code: "SUCCESS_200", }; } catch (err) { if (err.code == 11000) { logger.error({ message: `Bill update failed : Duplicate user found in Database`, user }); event.returnValue = { status: false, message: "Duplicate user found in Database", code: "ERR_DB", }; } else { logger.error({ message: `Bill update failed : Unknown DB error ${err}`, user }); event.returnValue = { status: false, message: "Unknown DB error" + err, code: "ERR_DB", }; } } }); ipcMain.on("close-bill", async(event, data) => { try { let result = await billModel.findOneAndUpdate({ _id: convertToObjectId(data.id.id)[1] }, { billStatus: "close", "payment.method": data.payment.paymentMethod, "payment.data": data.payment.data, "vehicleStatus.status": "Delivered", gst: { gstin: data.gst.gstin, bname: data.gst.bname, place: data.gst.place }, }); let msg = await preprocessAndGeneratePDF(result.billNo); let returnObj = {}; if (msg.status) { returnObj = { billStatus: true, PDFstatus: true, message: "PDF Generated", code: "SUCCESS_200" }; } else returnObj = { billStatus: true, PDFstatus: false, message: msg.msg, code: "ERR_GEN_PDF", }; logger.info({ message: `Bill close done ${JSON.stringify(returnObj)}`, user }); event.returnValue = returnObj; } catch (err) { if (err.code == 11000) { logger.error({ message: `Bill close failed : Duplicate user found in Database`, user }); event.returnValue = { status: false, message: "Duplicate user found in Database", code: "ERR_DB", }; } else { logger.error({ message: `Bill close failed : Unknown error ${err}`, user }); event.returnValue = { status: false, message: "Unknown error" + err, code: "ERR_DB", }; } } }); async function preprocessAndGeneratePDF(billNo) { try { let data = (await billModel.find({ billNo }).populate("vehicleID").populate("broughtIn").populate("billDetails.servicePackageFinal.package").lean({ virtuals: true }))[0]; data.dateOfDelivery = data.invoiceDate = new Date().toLocaleDateString(); data.CGST = 0; data.SGST = 0; data.subtotal = 0; data.total = 0; data.billDetails.servicePackageFinal.every(function(element) { data.CGST += Number(element.tax); data.SGST += Number(element.tax); data.total += Number(element.amt); return true; }); data.billDetails.additionalCharges.every(function(element) { data.CGST += Number(element.tax); data.SGST += Number(element.tax); data.total += Number(element.amt); return true; }); data.CGST = (Number(data.CGST) / 2).toFixed(2); data.SGST = (Number(data.SGST) / 2).toFixed(2); data.subtotal = data.total.toFixed(2); data.createdAt = new Date(data.createdAt).toLocaleDateString(); let res = await generatePDF(basePath, data.billNo, data); if (res.status) { logger.info({ message: `preprocessAndGeneratePDF done`, user }); return { status: true }; } else throw new Error(res.msg); } catch (err) { logger.error({ message: `preprocessAndGeneratePDF failed : Unknown error ${err}`, user }); return { status: false, msg: err }; } } async function PDF_exists(billNo) { let files = fs.readdirSync(path.resolve(`${basePath}/generated/PDFBill/`)); if (files.includes(billNo)) return true; else return false; } ipcMain.on("generate-pdf", async(event, data) => { if (!(await preprocessAndGeneratePDF(data.billNo)).status) event.returnValue = { status: false, msg: "PDF GENERATION FAILED, try after sometime", }; else event.returnValue = { status: true, }; }); ipcMain.on("email-invoice", async(event, data) => { try { if (!PDF_exists(data.billNo)) if (!(await preprocessAndGeneratePDF(data.billNo)).status) event.returnValue = { status: false, msg: "PDF GENERATION FAILED, try after sometime", }; let res = await mailer.sendInvoice({ type: data.type, billNo: data.billNo }, data.email); if (res.status) { logger.info({ message: `Email invoice done`, user }); event.returnValue = { status: true, }; } else { logger.error({ message: `Email invoice failed : ${res.err}`, user }); event.returnValue = { status: false, msg: res.err, }; } } catch (err) { logger.error({ message: `Email invoice failed : Unknown error ${err}`, user }); event.returnValue = { status: false, msg: "Unknown error", }; } });
# 네트워크 연결 import sys import heapq def Solution(): inp = sys.stdin.readline n = int(inp()) m = int(inp()) p = list(range(n + 1)) heap = [] def find_parent(a): while p[a] != a: a = p[a] return a def union_parent(pa, pb): if pa > pb: p[pa] = pb else: p[pb] = pa for _ in range(m): a, b, c = map(int, inp().split()) heapq.heappush(heap, (c, a, b)) res = 0 for _ in range(n - 1): while True: c, a, b = heapq.heappop(heap) pa, pb = find_parent(a), find_parent(b) if pa != pb: union_parent(pa, pb) res += c break print(res) if __name__ == "__main__": Solution() # https://www.acmicpc.net/problem/1922
import React, { useState } from 'react'; import { StyleSheet } from 'react-native'; import styled from 'styled-components/native'; import { Button, Dialog, Text, View } from 'react-native-ui-lib'; import { VoteStar } from './VoteStar'; export type VoteStarType = { position: number; status: 0 | 1; }; type VoteDialogType = { onBackHome: () => void; updateRouteVotes: (x: number) => void; }; const VOTE_STAR: VoteStarType[] = [ { position: 1, status: 0, }, { position: 2, status: 0, }, { position: 3, status: 0, }, { position: 4, status: 0, }, { position: 5, status: 0, }, ]; export const copies = { // eslint-disable-next-line quotes header: "¿Què t'ha semblat aquest itinerari?", close: 'Tanca', done: 'Fet', }; const style = StyleSheet.create({ container: { borderRadius: 12, backgroundColor: 'white', }, }); const StyledFooter = styled(View)` display: flex; flex-direction: row; justify-content: flex-end; `; const StyledContent = styled(View)` display: flex; flex-direction: row; justify-content: space-between; `; const renderPannableHeader = () => { return ( <View> <View margin-15> <Text>{copies.header}</Text> </View> <View height={2} bg-grey70 /> </View> ); }; export const VoteDialog: React.FC<VoteDialogType> = ({ onBackHome, updateRouteVotes, }) => { const [voteIcons, setVoteIcons] = useState<VoteStarType[]>(VOTE_STAR); const getVotes = () => voteIcons.filter(vote => vote.status === 1).length; const setToActive = (vote: VoteStarType): VoteStarType[] => { return VOTE_STAR.map((star, index) => { return index < vote.position ? { ...star, status: 1 } : { ...star, status: 0 }; }); }; const setToPasive = (vote: VoteStarType): VoteStarType[] => { return VOTE_STAR.map((star, index) => { return index >= vote.position ? { ...star, status: 0 } : { ...star, status: 1 }; }); }; // Add or remove votes to the counter const onVoteCounter = (vote: VoteStarType) => { const prevIcon = voteIcons[vote.position - 2]; // manage when clicking first star if (!prevIcon) { setVoteIcons( voteIcons.map((star, index) => index === 0 ? { ...star, status: 1 } : { ...star, status: 0 }, ), ); return; } // manage whe user is adding or removing votes const newVotes = vote.status === 1 && prevIcon.status === 0 ? setToActive(vote) : setToPasive(vote); setVoteIcons(newVotes); }; return ( <Dialog useSafeArea visible renderPannableHeader={renderPannableHeader} containerStyle={style.container} ignoreBackgroundPress={true}> <StyledContent marginH-30 marginV-40 row centerH> {voteIcons.map(star => { return ( <VoteStar key={`vote_star_${star.position}`} onVoteCounter={onVoteCounter} position={star.position} status={star.status} /> ); })} </StyledContent> <View> <View height={2} bg-grey70 /> <StyledFooter margin-15> <Button label={copies.close} link linkColor={'grey'} marginH-15 onPress={onBackHome} /> <Button label={copies.done} marginH-10 onPress={() => updateRouteVotes(getVotes())} /> </StyledFooter> </View> </Dialog> ); };
import {Form,Button,Row,Col} from 'react-bootstrap'; import { useParams,useNavigate } from 'react-router-dom'; import { useState,useEffect } from 'react'; import { FaEdit,FaTrash } from "react-icons/fa"; import { useGetCabDetailQuery, useUpdateCabMutation, useUploadCabImageMutation } from '../../slices/cabApiSlice.js'; import Cab from '../../components/cab.jsx'; import Loading from '../../components/loading.jsx'; import FormContainer from '../../components/formContainer.jsx'; import { toast } from 'react-toastify'; import { LinkContainer } from 'react-router-bootstrap'; const CabEditScreen = ()=>{ const { id:cabId } = useParams(); const [name,setName] = useState(''); const [discription,setDiscription] = useState(''); const [image,setImage] = useState(''); const {data:cab,isLoading,refetch} = useGetCabDetailQuery(cabId); const [updateCab,{isLoading:isUpdating}] = useUpdateCabMutation(); const [uploadCabImage,{isLoading:isImageUploading}] = useUploadCabImageMutation(); const navigate = useNavigate(); const submitHandler = async (e)=>{ e.preventDefault(); try{ console.log('name',name); const result = await updateCab( { _id:cabId, name:name, discription:discription, image:image, }).unwrap(); console.log('update Successfull....'); if(result?.error){ toast.error(result.error); } else{ toast.success('Cab Updated..'); refetch(); navigate(`/admin/cab/${cab._id}/edit`); } } catch(err){ toast.error('Please Try again...'); } } const uploadImageHandler = async (e) =>{ console.log('uploading image'); const formData = new FormData(); formData.append('image',e.target.files[0]); try{ console.log('about to call upload api...... '); const result = await uploadCabImage(formData).unwrap(); console.log('upload compleated....'); toast.success(result.message); console.log('image in result...',result.image); setImage(result.image); } catch(err){ console.log('upload failed...'); toast.error(err?.data?.message || err?.error); } } useEffect(()=>{ if(cab){ setName(cab.name); setDiscription(cab.discription); setImage(cab.image); } }, [cab]) const goToDetailEditPage = () =>{ navigate(`/admin/cab/${cab._id}/editDetails`); } return ( <div className="my-5 mx-3"> {cab&& <Row className='align-items-center'> <Col className='text-end'> <Button onClick={goToDetailEditPage} ><FaEdit />Edit Details Page</Button> </Col> </Row> } <FormContainer > <Form onSubmit={submitHandler}> <Form.Group controlId="name" className="my-3"> <Form.Label>Name</Form.Label> <Form.Control type="text" placeholder="Enter Name" value={name} onChange={(e) => setName(e.target.value)} ></Form.Control> </Form.Group> <Form.Group controlId="discription" className="my-3"> <Form.Label>Description</Form.Label> <Form.Control type="text" placeholder="Enter Description" value={discription} onChange={(e) => setDiscription(e.target.value)} ></Form.Control> </Form.Group> <Form.Group controlId="image" className="my-3"> <Form.Label>Image</Form.Label> <Form.Control type="text" placeholder="Enter Image URL" value={image} onChange={(e) => setImage} ></Form.Control> <Form.Control type="file" placeholder="Choose Image" onChange={uploadImageHandler} ></Form.Control> </Form.Group> <Button type="submit" style={{ backgroundColor: "#68b072", width: "100%", outline: "none", border: "none", }} variant="primary" className="mt-2" disabled={isLoading} > Update Details </Button> {isUpdating && <Loading />} </Form> </FormContainer> <Row className='text-center my-3'> <Col><h2>Preview</h2></Col> </Row> {cab? (<Row className="my-3 justify-content-md-center"> <Col className="my-3" sm={12} md={6} lg={4} xl={3}> <Cab cab={cab}></Cab> </Col> </Row>): ( <Loading /> ) } </div> ) } export default CabEditScreen;
// // LoopScrollView.swift // test // // Created by user on 2020/11/16. // Copyright © 2020 111. All rights reserved. // import UIKit class LoopScrollView: UIViewController{ @IBOutlet var sliderCollectionView: UICollectionView! @IBOutlet var pageControll: UIPageControl! @IBOutlet var spring_btn: UIButton! //봄 테마 관광지 버튼 @IBOutlet var summer_btn: UIButton! //여름 테마 관광지 버튼 @IBOutlet var fall_btn: UIButton! //가을 테마 관광지 버튼 @IBOutlet var winter_btn: UIButton! //겨울 테마 관광지 버튼 @IBOutlet var recom_btn: UIButton! //가볼만한곳 버튼 var imgArr = [ UIImage(named: "여행슬라이드1"), UIImage(named: "여행슬라이드2"), UIImage(named: "여행슬라이드3") ] var timer = Timer() var counter = 0 override func viewDidLoad() { super.viewDidLoad() sliderCollectionView.dataSource = self sliderCollectionView.delegate = self pageControll.numberOfPages = imgArr.count pageControll.currentPage = 0 DispatchQueue.main.async { self.timer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(self.changeImage), userInfo: nil, repeats: true) } //네비게이션바 색 guard let navigationController = navigationController, let flareGradientImage = CAGradientLayer.primaryGradient(on: navigationController.navigationBar) else { print("Error creating gradient color!") return } navigationController.navigationBar.barTintColor = UIColor(patternImage: flareGradientImage) //네비게이션바 로고 let button = UIButton(type: .custom) button.setImage(UIImage(named: "app"), for: .normal) button.contentVerticalAlignment = .fill button.contentHorizontalAlignment = .fill button.imageEdgeInsets = UIEdgeInsets(top: 10, left: 110, bottom: 10, right: 120) button.addTarget(self, action: #selector(clickOnButton), for: .touchUpInside) navigationItem.titleView = button //네비게이션바에 햄버거 아이콘 추가 //addSlideMenuButton() } //로고 버튼 눌렀을때 @objc func clickOnButton(){ let mainStoryboard:UIStoryboard = UIStoryboard(name : "Main", bundle: nil) let DVC = mainStoryboard.instantiateViewController(withIdentifier: "mainpage") as! Main self.navigationController?.pushViewController(DVC, animated: true) } //한국관광공사 버튼 눌렀을때 @IBAction func ktour_click(_ sender: Any) { UIApplication.shared.openURL(NSURL(string:"http://www.visitkorea.or.kr")! as URL) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @objc func changeImage(){ if counter < imgArr.count{ let index = IndexPath.init(item: counter, section: 0) self.sliderCollectionView.scrollToItem(at: index, at: .centeredHorizontally, animated: true) pageControll.currentPage = counter counter += 1 } else { counter = 0 let index = IndexPath.init(item: counter, section: 0) self.sliderCollectionView.scrollToItem(at: index, at: .centeredHorizontally, animated: true) pageControll.currentPage = counter } } } extension LoopScrollView: UICollectionViewDelegate, UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imgArr.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! viewControllerCollectionViewCell cell.IMG.image = imgArr[indexPath.row] return cell } } extension LoopScrollView: UICollectionViewDelegateFlowLayout{ func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let size = sliderCollectionView.frame.size return CGSize(width: size.width, height: size.height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0.0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0.0 } } class viewControllerCollectionViewCell: UICollectionViewCell { @IBOutlet var IMG: UIImageView! }
""" 6.00.2x Problem Set 6 Name: Tri Minh Cao Email: trimcao@gmail.com Date: December 2015 """ #Code shared across examples import pylab, string def stdDev(X): mean = sum(X)/float(len(X)) tot = 0.0 for x in X: tot += (x - mean)**2 return (tot/len(X))**0.5 def scaleFeatures(vals): """Assumes vals is a sequence of numbers""" result = pylab.array(vals) mean = sum(result)/float(len(result)) result = result - mean sd = stdDev(result) result = result/sd return result class Point(object): def __init__(self, name, originalAttrs): """originalAttrs is an array""" self.name = name self.attrs = originalAttrs def dimensionality(self): return len(self.attrs) def getAttrs(self): return self.attrs def distance(self, other): #Euclidean distance metric result = 0.0 for i in range(self.dimensionality()): result += (self.attrs[i] - other.attrs[i])**2 return result**0.5 def getName(self): return self.name def toStr(self): return self.name + str(self.attrs) def __str__(self): return self.name class Cluster(object): """ A Cluster is defines as a set of elements, all having a particular type """ def __init__(self, points, pointType): """ Elements of a cluster are saved in self.points and the pointType is also saved """ self.points = points self.pointType = pointType def singleLinkageDist(self, other): """ Returns the float distance between the points that are closest to each other, where one point is from self and the other point is from other. Uses the Euclidean dist between 2 points, defined in Point.""" # TO DO minDist = float('inf') for point1 in self.members(): for point2 in other.members(): currentDist = point1.distance(point2) if (currentDist < minDist): minDist = currentDist return minDist def maxLinkageDist(self, other): """ Returns the float distance between the points that are farthest from each other, where one point is from self and the other point is from other. Uses the Euclidean dist between 2 points, defined in Point.""" # TO DO maxDist = -float('inf') for point1 in self.members(): for point2 in other.members(): currentDist = point1.distance(point2) if (currentDist > maxDist): maxDist = currentDist return maxDist def averageLinkageDist(self, other): """ Returns the float average (mean) distance between all pairs of points, where one point is from self and the other point is from other. Uses the Euclidean dist between 2 points, defined in Point.""" # TO DO numPairs = 0 sumDist = 0 for point1 in self.members(): for point2 in other.members(): numPairs += 1 sumDist += point1.distance(point2) return (sumDist / numPairs) #dimensions = self.points[0].dimensionality() #numPoints1 = 0 #aveAttrs1 = [0 for idx in range(dimensions)] #for point1 in self.members(): # numPoints1 += 1 # attrs = point1.getAttrs() # for idx in range(dimensions): # aveAttrs1[idx] += attrs[idx] ## find the average #for idx in range(dimensions): # aveAttrs1[idx] = aveAttrs1[idx] / float(numPoints1) #avePoint1 = Point('point1', aveAttrs1) ## find the average point 2 #numPoints2 = 0 #aveAttrs2 = [0 for idx in range(dimensions)] #for point2 in other.members(): # numPoints2 += 1 # attrs = point2.getAttrs() # for idx in range(dimensions): # aveAttrs2[idx] += attrs[idx] ## find the average #for idx in range(dimensions): # aveAttrs2[idx] = aveAttrs2[idx] / float(numPoints2) #avePoint2 = Point('point2', aveAttrs2) #return avePoint1.distance(avePoint2) def members(self): for p in self.points: yield p def isIn(self, name): """ Returns True is the element named name is in the cluster and False otherwise """ for p in self.points: if p.getName() == name: return True return False def toStr(self): result = '' for p in self.points: result = result + p.toStr() + ', ' return result[:-2] def getNames(self): """ For consistency, returns a sorted list of all elements in the cluster """ names = [] for p in self.points: names.append(p.getName()) return sorted(names) def __str__(self): names = self.getNames() result = '' for p in names: result = result + p + ', ' return result[:-2] class ClusterSet(object): """ A ClusterSet is defined as a list of clusters """ def __init__(self, pointType): """ Initialize an empty set, without any clusters """ self.members = [] def add(self, c): """ Append a cluster to the end of the cluster list only if it doesn't already exist. If it is already in the cluster set, raise a ValueError """ if c in self.members: raise ValueError self.members.append(c) def getClusters(self): return self.members[:] def mergeClusters(self, c1, c2): """ Assumes clusters c1 and c2 are in self Adds to self a cluster containing the union of c1 and c2 and removes c1 and c2 from self """ # TO DO newPoints = [] for point in c1.members(): newPoints.append(point) for point in c2.members(): newPoints.append(point) newCluster = Cluster(newPoints, list) self.add(newCluster) self.members.remove(c1) self.members.remove(c2) def findClosest(self, linkage): """ Returns a tuple containing the two most similar clusters in self Closest defined using the metric linkage """ minValue = float('inf') cluster1 = None cluster2 = None for i in range(self.numClusters() - 1): for j in range(i + 1, self.numClusters()): currentValue = linkage(self.members[i], self.members[j]) if (currentValue < minValue): minValue = currentValue cluster1 = self.members[i] cluster2 = self.members[j] return (cluster1, cluster2) def mergeOne(self, linkage): """ Merges the two most simililar clusters in self Similar defined using the metric linkage Returns the clusters that were merged """ # TO DO closestClus = self.findClosest(linkage) c1 = closestClus[0] c2 = closestClus[1] self.mergeClusters(c1, c2) return closestClus def numClusters(self): return len(self.members) def toStr(self): cNames = [] for c in self.members: cNames.append(c.getNames()) cNames.sort() result = '' for i in range(len(cNames)): names = '' for n in cNames[i]: names += n + ', ' names = names[:-2] result += ' C' + str(i) + ':' + names + '\n' return result #City climate example class City(Point): pass def readCityData(fName, scale = False): """Assumes scale is a Boolean. If True, features are scaled""" dataFile = open(fName, 'r') numFeatures = 0 #Process lines at top of file for line in dataFile: #Find number of features if line[0:4] == '#end': #indicates end of features break numFeatures += 1 numFeatures -= 1 featureVals = [] #Produce featureVals, cityNames featureVals, cityNames = [], [] for i in range(numFeatures): featureVals.append([]) #Continue processing lines in file, starting after comments for line in dataFile: dataLine = string.split(line[:-1], ',') #remove newline; then split cityNames.append(dataLine[0]) for i in range(numFeatures): featureVals[i].append(float(dataLine[i+1])) #Use featureVals to build list containing the feature vectors #For each city scale features, if needed if scale: for i in range(numFeatures): featureVals[i] = scaleFeatures(featureVals[i]) featureVectorList = [] for city in range(len(cityNames)): featureVector = [] for feature in range(numFeatures): featureVector.append(featureVals[feature][city]) featureVectorList.append(featureVector) return cityNames, featureVectorList def buildCityPoints(fName, scaling): cityNames, featureList = readCityData(fName, scaling) points = [] for i in range(len(cityNames)): point = City(cityNames[i], pylab.array(featureList[i])) points.append(point) return points #Use hierarchical clustering for cities def hCluster(points, linkage, numClusters, printHistory): cS = ClusterSet(City) for p in points: cS.add(Cluster([p], City)) history = [] while cS.numClusters() > numClusters: merged = cS.mergeOne(linkage) history.append(merged) if printHistory: print '' for i in range(len(history)): names1 = [] for p in history[i][0].members(): names1.append(p.getName()) names2 = [] for p in history[i][1].members(): names2.append(p.getName()) print 'Step', i, 'Merged', names1, 'with', names2 print '' print 'Final set of clusters:' print cS.toStr() return cS def test(): points = buildCityPoints('cityTemps.txt', True) hCluster(points, Cluster.singleLinkageDist, 5, False) #points = buildCityPoints('cityTemps.txt', True) #hCluster(points, Cluster.maxLinkageDist, 10, False) #hCluster(points, Cluster.averageLinkageDist, 10, False) #hCluster(points, Cluster.singleLinkageDist, 10, False) test()
// // WebViewModel.swift // Softgames Test // // Created by Hamza Ahmed on 21/02/2022. // import Foundation import UIKit import WebKit protocol WebViewModel { func minimizeApplication() func sendNotification(title:String, body:String) func fullNameJson(for message: WKScriptMessage) -> String func ageJson(for message: WKScriptMessage) -> String func calculateAge(dateOfBirth: String?) -> Int func createJsonForJavaScript(for data: [String : Any]) -> String } class WebViewModelImplementation:WebViewModel { func calculateAge(dateOfBirth: String?) -> Int { guard dateOfBirth != "" else {return 0} let dateFormater = DateFormatter() dateFormater.dateFormat = "yyyy-mm-dd" let birthdayDate = dateFormater.date(from: dateOfBirth!) let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian) let now = Date() let calcAge = calendar.components(.year, from: birthdayDate!, to: now, options: []) guard let age = calcAge.year else { return 0 } return age } func fullNameJson(for message: WKScriptMessage) -> String { guard let dict = message.body as? [String:AnyObject], let firstName = dict["firstName"] as? String, let lastName = dict["lastName"] as? String else { return "" } let fullName = "\(firstName) \(lastName)" let dic = ["fullName": fullName] return self.createJsonForJavaScript(for: dic) } func ageJson(for message: WKScriptMessage) -> String { guard let dict = message.body as? [String:AnyObject], let dob = dict["dobirth"] as? String else { return "" } let dic = ["age": self.calculateAge(dateOfBirth: dob)] return self.createJsonForJavaScript(for: dic) } func createJsonForJavaScript(for data: [String : Any]) -> String { var jsonString : String? do { let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted) jsonString = String(data: jsonData, encoding: .utf8)! jsonString = jsonString?.replacingOccurrences(of: "\n", with: "").replacingOccurrences(of: "\\", with: "") } catch { print(error.localizedDescription) } return jsonString! } /* Below function is used to minimize the app. */ func minimizeApplication() { DispatchQueue.main.asyncAfter(deadline: .now()) { UIApplication.shared.perform(#selector(NSXPCConnection.suspend)) } } /* Below function is used to trigger local notification */ func sendNotification(title:String, body:String) { let center = UNUserNotificationCenter.current() let content = UNMutableNotificationContent() content.title = title content.body = body content.sound = .default content.userInfo = ["value": "Data with local notification"] let fireDate = Calendar.current.dateComponents([.day, .month, .year, .hour, .minute, .second], from: Date().addingTimeInterval(7)) let trigger = UNCalendarNotificationTrigger(dateMatching: fireDate, repeats: false) let request = UNNotificationRequest(identifier: "reminder", content: content, trigger: trigger) center.add(request) { (error) in if error != nil { print("Error = \(error?.localizedDescription ?? "error local notification")") } } } }
import requests from bs4 import BeautifulSoup import time from send_email import send_info # Define the ScraperAPI request payload def check_product_availability(product_url, recipient_email): api_key = '08787347edb086d69d60b4425f0508fe' scraperapi_endpoint = 'https://api.scraperapi.com/' payload = { 'api_key': api_key, 'url': product_url, 'follow_redirect': True, 'render': True, 'retry_404': True, 'autoparse': True } while True: # Make the API request response = requests.get(scraperapi_endpoint, params=payload) if response.status_code == 200: # Parse the HTML content soup = BeautifulSoup(response.text, 'html.parser') # Check if the product is available based on the presence of a "Buy Now" button buy_now_button = soup.find('button', {'class': '_2KpZ6l _2U9uOA _3v1-ww'}) if buy_now_button: print("Product is available, details has send to you email!!") # flash('Product is available, details has send to you email!!') # Scrape additional details product_name = soup.find('span', {'class': 'B_NuCI'}).text product_price = get_product_price(soup) product_ratings = get_product_ratings(soup) product_reviews = get_product_reviews(soup) send_info(product_name, product_price, product_ratings, product_reviews, recipient_email,product_url) break else: print("Product is currently out of stock. Checking again in 2 seconds...") # flash('Product is currently out of stock. Checking again in 2 seconds...') break # Wait for 1 seconds before checking again else: print(f"Failed to fetch data. Status code: {response.status_code}") # flash('Failed to fetch data.') break # Function to extract product price def get_product_price(soup): price_element = soup.find('div', {'class': '_30jeq3'}) if price_element: return price_element.text else: return "Price not available" # Function to extract product ratings def get_product_ratings(soup): ratings_element = soup.find('div', {'class': '_3LWZlK'}) if ratings_element: return ratings_element.text else: return "Ratings not available" # Function to extract product reviews def get_product_reviews(soup): reviews_element = soup.find('span', {'class': '_2_R_DZ'}) if reviews_element: return reviews_element.text else: return "Reviews not available" # # Check if the user wants to automate availability checking and receive notifications # automate_checking = input("Automate availability checking and receive email notifications? (yes/no): ").lower() # if automate_checking == "yes" or automate_checking == "Yes" or automate_checking == "YES" or automate_checking == "Y" or automate_checking == "y": # check_product_availability(product_url, recipient_email) # else: # print("You chose not to automate availability checking.")
package com.vshyrochuk.tictactoe.viewmodel.manager import com.vshyrochuk.tictactoe.model.CellState import com.vshyrochuk.tictactoe.model.Player /** * Defines the contract for checking the winner in a grid-based game like Tic-Tac-Toe. * * This interface provides a method to analyze the game board and determine if there is a winner. Implementations * should contain the logic to evaluate the board's state and identify a winning condition based on the game rules. */ interface ICheckWinnerManager { /** * Evaluates the game board to determine if there is a winner. * * This method should inspect the provided game board and return the winning player if a winning condition * is met according to the game rules. If there is no winner yet, it should return null. * * @param board A two-dimensional list representing the current state of the game board. Each inner list * represents a row, and each element within that list represents a cell on the game board. * Each cell is of type `CellState`, indicating the cell's occupancy. * @return The winning `Player` if a winning condition is met, or `null` if there is no winner yet. */ fun checkWinner(board: List<List<CellState>>): Player? }
using System; namespace Factory { public enum CoordinateSystem { Cartesian, Polar } public class Point //limited information to communicate to user; have to resort to comment { private double x, y; private Point(double x, double y) { this.x = x; this.y = y; } /* public Point(double a, double b, CoordinateSystem system = CoordinateSystem.Cartesian) //cartesian coordinate { switch(system) { case CoordinateSystem.Cartesian: this.x = a; this.y = b; break; case CoordinateSystem.Polar: this.x = a * Math.Cos(b); this.y = a * Math.Sin(b); break; } }*/ //factory method public static Point NewCartesianPoint(double x, double y) { return new Point(x, y); } public static Point NewPolarPoint(double rho, double theta) { return new Point(rho * Math.Cos(theta), rho * Math.Sin(theta)); } //for polar coordinates? //2 factory patterns //1 proper factory // abstract factory public override string ToString() { return $"{nameof(x)}: {x}, {nameof(y)}: {y}"; } } }
package com.chenmeng.project.config; import com.chenmeng.common.interceptor.MyBatisPrintInterceptor; import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.util.List; /** * mybatis自定义配置 * * @author chenmeng */ @Configuration public class MyBatisConfig { @Resource private List<SqlSessionFactory> sqlSessionFactoryList; @Value("${application.env:dev}") private String env; private static final String ON_LINE = "online"; @PostConstruct public void addMyBatisInterceptor() { if (ON_LINE.equals(env)) { return; } MyBatisPrintInterceptor interceptor = new MyBatisPrintInterceptor(); for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) { // 添加自定义属性 sqlSessionFactory.getConfiguration() .addInterceptor(interceptor); } } }
<?php namespace Tonning\Github\Requests\Dependabot; use Saloon\Enums\Method; use Saloon\Http\Request; /** * dependabot/list-org-secrets * * Lists all secrets available in an organization without revealing their encrypted values. You must * authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must * have the `dependabot_secrets` organization permission to use this endpoint. */ class DependabotListOrgSecrets extends Request { protected Method $method = Method::GET; public function resolveEndpoint(): string { return "/orgs/{$this->org}/dependabot/secrets"; } /** * @param string $org The organization name. The name is not case-sensitive. * @param null|int $page Page number of the results to fetch. */ public function __construct( protected string $org, protected ?int $page = null, ) { } public function defaultQuery(): array { return array_filter(['page' => $this->page]); } }
interface LinkHistory { link: string; title: string; icon?: string; create_at: number; } const MAX_LENGTH = 50; export async function getHistory(): Promise<LinkHistory[]> { return new Promise((resolve, reject) => { chrome.storage.local.get(['links_history'], function (data) { if (data && data.links_history) { resolve(data.links_history); } else { resolve([]); } }); }); } export async function addHistory(link: string, title: string, icon?: string) { return new Promise((resolve, reject) => { chrome.storage.local.get(['links_history'], function (data) { let links_history: LinkHistory[] = []; if (data && data.links_history) { links_history = data.links_history; } // remove duplicate links_history = links_history.filter( (item: LinkHistory) => item.link !== link, ); links_history.push({ link, title, icon, create_at: Date.now(), }); if (links_history.length > MAX_LENGTH) { links_history = links_history.slice(links_history.length - MAX_LENGTH); } chrome.storage.local.set({ links_history }, function () { resolve(links_history); }); }); }); }
import { html, fixture, expect } from '@open-wc/testing'; import { FocusManager, getFocusableEls } from './focus-manager'; describe('utils: focus-trap', () => { it('should return a list of focusable elements sorted by tabindex', async () => { const container = await fixture<HTMLFormElement>(html` <form> <input name="fname" label="First name" tabindex="0" /> <input name="lname" label="Last name" tabindex="1" /> <input name="addr1" label="Address" tabindex="3" /> <input name="addr2" label="Address 2" tabindex="2" /> <button name="cancel-btn">Cancel</button> </form> `); const els = getFocusableEls(container); expect(els.map((el) => el.getAttribute('name'))).to.deep.equal([ 'fname', 'cancel-btn', 'lname', 'addr2', 'addr1', ]); }); it('should exclude elements marked to skip', async () => { const container = await fixture<HTMLFormElement>(html` <form> <input name="fname" label="First name" /> <input name="lname" label="Last name" /> <input name="addr1" label="Address" /> <input name="addr2" label="Address 2" /> <button>Cancel</button> <button data-focus-trap-skip>Submit</button> </form> `); const els = getFocusableEls(container); expect(els.flatMap((el) => Object.keys(el.dataset)).includes('focusTrapSkip')).to.equal(false); }); it('should return the correct first and last focusable element', async () => { const container = await fixture<HTMLFormElement>(html` <form> <input name="fname" label="First name" /> <input name="lname" label="Last name" /> <input name="addr1" label="Address" /> <input name="addr2" label="Address 2" /> <button>Cancel</button> <button>Submit</button> </form> `); const focusTrap = new FocusManager(); focusTrap.start(container); expect(focusTrap.firstFocusableEl?.getAttribute('name')).to.equal('fname'); expect(focusTrap.lastFocusableEl?.innerHTML).to.equal('Submit'); }); it('should return to the top when on the last element', async () => { const container = await fixture<HTMLFormElement>(html` <form> <input name="fname" label="First name" /> <input name="lname" label="Last name" /> <input name="addr1" label="Address" /> <input name="addr2" label="Address 2" /> <button>Cancel</button> <button>Submit</button> </form> `); const focusTrap = new FocusManager(); focusTrap.start(container); focusTrap.lastFocusableEl?.focus(); container.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab' })); expect(document.activeElement?.getAttribute('name')).to.equal('fname'); }); it('should return to bottom if Shift + Tab from top', async () => { const container = await fixture<HTMLFormElement>(html` <form> <input name="fname" label="First name" /> <input name="lname" label="Last name" /> <input name="addr1" label="Address" /> <input name="addr2" label="Address 2" /> <button>Cancel</button> <button>Submit</button> </form> `); const focusTrap = new FocusManager(); focusTrap.start(container); focusTrap.firstFocusableEl?.focus(); container.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab', shiftKey: true })); expect(document.activeElement?.innerHTML).to.equal('Submit'); }); });
/* * Copyright 2023 ByteDance and/or its affiliates. * * 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. */ // the graph is constructed with edges (node, node), where node is their index pub fn sort_nodes_in_dependency_graph(edges: Vec<(usize, usize)>) -> Result<Vec<usize>, usize> { use petgraph::{algo::toposort, graph::Graph, Directed}; if edges.is_empty() { return Ok(Vec::new()); } let g = Graph::<usize, (), Directed, usize>::from_edges(edges.as_slice()); match toposort(&g, None) { Ok(nodes) => { let mut r = Vec::<usize>::new(); for node_id in nodes.iter() { r.push(node_id.index()); } Ok(r) } Err(cycle) => Err(g[cycle.node_id()]), } } #[cfg(test)] mod tests { use super::*; #[test] fn check_dependency_cycle() { let edges = vec![(1, 2), (1, 3)]; assert!(sort_nodes_in_dependency_graph(edges).is_ok()); // duplicated edge is allowed let edges = vec![(1, 2), (1, 2)]; assert!(sort_nodes_in_dependency_graph(edges).is_ok()); let edges = vec![(1, 2), (2, 3), (1, 3)]; assert!(sort_nodes_in_dependency_graph(edges).is_ok()); let edges = vec![(1, 2), (2, 3), (3, 1)]; assert!(sort_nodes_in_dependency_graph(edges).is_err()); } }
''' Воронина Татьяна КН-304 Лабораторная работа 3 Вариант 3 ( −0.10 1.00 0.10 ) A = ( 1.51 −0.20 0.40 ) ( −0.30 −0.10 −0.50 ) ( 2.20 ) B = ( 2.31 ) ( −2.00 ) Решить систему линейных уравнений вида Ax = B, используя точные и итерационные методы: 1. Метод Гаусса; 2. Метод Якоби; 3. Метод Гаусса-Зейделя. В отчете: • Для методов 2, 3 проверить сходимость метода (в том числе при перестановке уравнений местами); в случае сходимости найти решение с точностью 0.5·10−4 ; сравнить количество итераций. ''' import numpy as np # буду использовать библиотеку numpy ( надо прописать в консоли - pip install numpy) # напишу в виде массивов A = np.array([[-0.10, 1.00, 0.10], [1.51, -0.20, 0.40], [-0.30, -0.10, -0.50]]) B = np.array([[2.20], [2.31], [-2.00]]) def gauss_elimination(A, B): # Объединяем матрицы A и B AB = np.column_stack((A, B)) # Прямой ход for i in range(len(AB)): # Находим максимальный элемент в текущем столбце max_index = np.argmax(np.abs(AB[i:, i])) + i # Меняем строки местами AB[[i, max_index]] = AB[[max_index, i]] # Делаем элемент на диагонали равным 1 AB[i] /= AB[i, i] # Обнуляем элементы под и над диагональю for j in range(i + 1, len(AB)): AB[j] -= AB[j, i] * AB[i] # Обратный ход for i in range(len(AB) - 1, 0, -1): for j in range(i - 1, -1, -1): AB[j] -= AB[j, i] * AB[i] return AB[:, -1] # Решаем систему методом Гаусса solution = gauss_elimination(A, B) print(f'Решение системы уравнений методом Гаусса: x1 = {solution[0]}, x2 = {solution[1]}, x3 = {solution[2]}') # Решение системы уравнений методом Гаусса: x1 = 1.0, x2 = 2.0, x3 = 3.0 """ сделаем проверку -0.1 + 2 + 0.3 = 2.2 (верно) 1.51 - 0.4 + 1.2 = 2.31 (верно) -0.3 - 0.2 - 1.5 = -2 (верно) """ """ проверим на сходимость 1) Диагональное преобладание: |-0.1| > |1| + |0.1| - НЕТ однако, если переставить строки местами и сделать матрицу [1.51, -0.20, 0.40], [-0.10, 1.00, 0.10], [-0.30, -0.10, -0.50] тогда диагональное преобладание будет """ A = np.array([[1.51, -0.20, 0.40], [-0.10, 1.00, 0.10], [-0.30, -0.10, -0.50]]) B = np.array([[2.31], [2.20], [-2.00]]) """ Метод Якоби. В методе Якоби матрицу A можно представить в виде суммы трех матриц: диагональной (D), нижнетреугольной (-L), верхнетреугольной (-U). Таким образом, A = D - L - U. Итерационный процесс метода Якоби выглядит следующим образом: x^(k+1) = D^(-1) * (b + (L + U) * x^(k)) где x^(k+1) - новое приближенное решение, x^(k) - текущее приближенное решение, D^(-1) - обратная диагональная матрица, L и U - соответственно нижнетреугольная и верхнетреугольная матрицы, полученные из разложения A = D - L - U. """ def jacobi_method(A, B, tolerance=0.00005, max_iterations=100000): n = len(A) X = np.zeros_like(B) # Начальное приближение # Проверка условия сходимости eigenvalues, _ = np.linalg.eig(A) if np.all(np.abs(eigenvalues) < 1): print("Метод Якоби сходится.") iterations = 0 while iterations < max_iterations: X_new = np.copy(X) for i in range(n): sigma = sum(A[i, j] * X[j] for j in range(n) if j != i) X_new[i] = (B[i] - sigma) / A[i, i] if np.linalg.norm(X_new - X) < tolerance: print(f"Метод Якоби сошелся с точностью 0.00005 за {iterations} итераций.") return X_new, iterations X = np.copy(X_new) iterations += 1 print(f"Метод Якоби не сошелся за {max_iterations} итераций.") return None, iterations # Задаем матрицу A и вектор B (уравнения мы переставили местами, чтобы было диагональное преобладание) A = np.array([[1.51, -0.20, 0.40], [-0.10, 1.00, 0.10], [-0.30, -0.10, -0.50]]) B = np.array([[2.31], [2.20], [-2.00]]) # Решаем систему методом Якоби solution, num_iterations = jacobi_method(A, B) if solution is not None: print( f'Решение системы уравнений методом Якоби: x1 = {solution[0][0]}, x2 = {solution[1][0]}, x3 = {solution[2][0]}' ) # Метод Якоби сошелся с точностью 0.00005 за 13 итераций # Решение системы уравнений методом Якоби: x1 = 0.9999952840150551, x2 = 1.9999989420133117, x3 = 2.9999955326473775 """ Метод Гаусса-Зейделя для него аналогично нужна диагональная сходимость. мы помним, что для этого переставили уравнения местами !!! Итерационный процесс Гаусса-Зейделя записывается следующим образом: x^(k+1)_i = (b_i - sum(A[i, j] * x^(k)_j for j in range(i)) - sum(A[i, j] * x^(k+1)_j for j in range(i+1, n))) / A[i, i] где x^(k+1)_i - новое приближенное значение переменной на i-той позиции, x^(k)_j - текущее приближенное значение переменной на j-той позиции, A[i, j] - элемент матрицы коэффициентов A на позиции (i, j), b_i - элемент вектора правых частей B на позиции i. продолжается до достижения заданной точности или максимального числа итераций. """ """ Для начала проверим сходимость. на практике говорили, что диагональное преобладание нельзя использовать, тогда должно быть |AL + AD + R| = 0 A - лямбда буду использовать сразу переставленную местами матрицу строим матрицу [1.51*A, -0.20, 0.40], [-0.10*A, 1.00*A, 0.10], [-0.30*A, -0.10*A, -0.50*A] посчитаем определитель (1.51*A)*(1.00*A)*(-0.50*A)+(-0.10*A)*(0.40)*(-0.10*A)+(-0.30*A)*(-0.20)*(0.10) A = 0.0918344152028208 A = 0.0 A = -0.0865364019577877 они по модулю меньше 1 -> метод сходится """ def gauss_seidel(A, b, tolerance=0.00005): n = len(A) x = np.zeros(n) iterations = 0 converge = False while not converge: iterations += 1 x_new = np.copy(x) for i in range(n): s1 = np.sum(np.fromiter((A[i, j] * x_new[j] for j in range(i)), float)) s2 = np.sum(np.fromiter((A[i, j] * x[j] for j in range(i + 1, n)), float)) x_new[i] = (b[i] - s1 - s2) / A[i, i] converge = np.sqrt(np.sum((x_new[i] - x[i]) ** 2 for i in range(n))) <= tolerance x = x_new print(f"Метод Гаусса-Зейделя сошелся с точностью 0.00005 за {iterations} итераций") return x # Задаем матрицу A и вектор B (уравнения мы переставили местами, чтобы было диагональное преобладание) A = np.array([[1.51, -0.20, 0.40], [-0.10, 1.00, 0.10], [-0.30, -0.10, -0.50]], dtype=float) B = np.array([2.31, 2.20, -2.00], dtype=float) solution = gauss_seidel(A, B) print( f'Решение системы уравнений методом Гаусса-Зейделя: x1 = {solution[0]}, x2 = {solution[1]}, x3 = {solution[2]}' ) # Метод Гаусса-Зейделя сошелся с точностью 0.00005 за 9 итераций # Решение системы уравнений методом Гаусса-Зейделя: x1 = 1.0000052524481728, x2 = 2.0000020629951623, x3 = 2.999996435932064 """ Итоговый вывод программы Решение системы уравнений методом Гаусса: x1 = 1.0, x2 = 2.0, x3 = 3.0 Метод Якоби сошелся с точностью 0.00005 за 13 итераций. Решение системы уравнений методом Якоби: x1 = 0.9999952840150551, x2 = 1.9999989420133117, x3 = 2.9999955326473775 Метод Гаусса-Зейделя сошелся с точностью 0.00005 за 9 итераций Решение системы уравнений методом Гаусса-Зейделя: x1 = 1.0000052524481728, x2 = 2.0000020629951623, x3 = 2.999996435932064 Можно сделать вывод, что метод Гаусса-Зейделя эффективней метода Якоби """
<template> <div id="term"></div> </template> <script lang="ts"> import * as echarts from 'echarts'; export default { name: "Sciterm", mounted() { type EChartsOption = echarts.EChartsOption; var chartDom = document.getElementById('term')!; var myChart = echarts.init(chartDom); var option: EChartsOption; var datas = [ [ { name: 'SCI 一区', value: 36 }, { name: 'SCI 二区', value: 124 }, { name: 'SCI 三、四区', value: 932 }, { name: 'CSSCI', value: 1170 }, ], [ { name: '学术著作', value: 276 }, { name: '授权发明专利', value: 504 }, { name: '科技成果转化', value: 102 }, ], [ { name: '国家发明奖', value: 1 }, { name: '自然科学和科技进步奖', value: 1 }, { name: '省部级奖励', value: 50 }, { name: '一级学会奖励', value: 38 } ] ]; option = { title: { text: '学术成果', left: 'center', textStyle: { color: '#3f3737', fontWeight: 'normal', fontSize: 14 } }, series: datas.map(function (data, idx) { var top = idx * 33.3; return { type: 'pie', radius: [20, 60], top: top + '%', height: '33.33%', left: 'center', width: 400, itemStyle: { borderColor: '#fff', borderWidth: 1 }, label: { alignTo: 'edge', formatter: '{name|{b}}\n{time|{c} 项}', minMargin: 5, edgeDistance: 10, lineHeight: 15, rich: { time: { fontSize: 10, color: '#999' } } }, labelLine: { length: 15, length2: 0, maxSurfaceAngle: 80 }, labelLayout: function (params) { const isLeft = params.labelRect.x < myChart.getWidth() / 2; const points = params.labelLinePoints as number[][]; // Update the end point. points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width; return { labelLinePoints: points }; }, data: data }; }) }; option && myChart.setOption(option); } } </script> <style scoped> #term{ overflow: hidden; /* width: 100%; height: 100%; */ width: 500px; height: 750px; margin: 0; font-family: "微软雅黑"; top:150px; left:100px; } </style>
use bevy::{ input::mouse::{MouseScrollUnit, MouseWheel}, prelude::*, }; use haalka::*; fn main() { let letters = "abcdefghijklmnopqrstuvwxyz"; let vertical = (0..5) .map(|i| { letters .chars() .cycle() .skip(i) .take(26) .enumerate() .map(|(j, letter)| LetterColor { letter: letter.to_string(), color: ROYGBIV[j % 7], }) .collect::<Vec<_>>() }) .collect::<Vec<_>>(); let horizontal = (0..5) .map(|i| { letters .chars() .cycle() .skip(i) .take(26) .map(|letter| LetterColor { letter: letter.to_string(), color: ROYGBIV[i], }) .collect::<Vec<_>>() }) .collect::<Vec<_>>(); App::new() .add_plugins(( DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { position: WindowPosition::Centered(MonitorSelection::Primary), ..default() }), ..default() }), HaalkaPlugin, )) .add_systems(Startup, (ui_root, camera)) .add_systems(Update, (scroller.run_if(resource_exists::<HoveredCell>), shifter)) .insert_resource(Rails { vertical, horizontal }) .insert_resource(Shifted(false)) .run(); } const LETTER_SIZE: f32 = 65.; #[derive(Clone, Copy)] enum Scroll { Up, Down, } #[derive(Resource)] struct HoveredCell(usize, usize); #[rustfmt::skip] fn letter( x: usize, y: usize, letter_color: impl Signal<Item = LetterColor> + Send + 'static, ) -> impl Element { El::<TextBundle>::new() .on_hovered_change(move |is_hovered| { if is_hovered { spawn(async_world().insert_resource(HoveredCell(x, y))).detach(); } }) .text_signal( letter_color.map(|LetterColor { letter, color }| Text::from_section( letter, TextStyle { font_size: LETTER_SIZE, color, ..default() }, ) ) ) } #[derive(Clone, Default)] struct LetterColor { letter: String, color: Color, } #[derive(Resource)] struct Rails { vertical: Vec<Vec<LetterColor>>, horizontal: Vec<Vec<LetterColor>>, } const ROYGBIV: &[Color] = &[ Color::RED, Color::ORANGE, Color::YELLOW, Color::GREEN, Color::BLUE, Color::INDIGO, Color::VIOLET, ]; static CELLS: Lazy<Vec<Vec<Mutable<LetterColor>>>> = Lazy::new(|| { let cells = (0..5) .map(|_| (0..5).map(|_| Mutable::new(default())).collect::<Vec<_>>()) .collect::<Vec<_>>(); let letters = "abcdefghijklmnopqrstuvwxyz"; for i in 0..5 { for (j, letter) in letters.chars().skip(i).take(5).enumerate() { cells[i][j].set(LetterColor { letter: letter.to_string(), color: ROYGBIV[i], }); } } cells }); fn ui_root(world: &mut World) { El::<NodeBundle>::new() .width(Val::Percent(100.)) .height(Val::Percent(100.)) .align_content(Align::center()) .child( Grid::<NodeBundle>::new() .with_style(|style| style.column_gap = Val::Px(15.)) .on_hovered_change(move |is_hovered| { if !is_hovered { spawn(async_world().remove_resource::<HoveredCell>()).detach(); } }) .row_wrap_cell_width(48.) .width(Val::Px(300.)) .height(Val::Px(5. * LETTER_SIZE)) .align(Align::center()) .cells( CELLS .iter() .enumerate() .map(|(x, cells)| { cells .iter() .enumerate() .map(move |(y, cell)| letter(x, y, cell.signal_cloned())) }) .flatten(), ), ) .spawn(world); } fn scroller( mut mouse_wheel_events: EventReader<MouseWheel>, hovered_cell: Res<HoveredCell>, mut rails: ResMut<Rails>, shifted: Res<Shifted>, ) { for mouse_wheel_event in mouse_wheel_events.read() { let is_negative = match mouse_wheel_event.unit { MouseScrollUnit::Line => mouse_wheel_event.y.is_sign_negative(), MouseScrollUnit::Pixel => mouse_wheel_event.y.is_sign_negative(), }; let scroll = if is_negative { Scroll::Up } else { Scroll::Down }; let HoveredCell(x, y) = *hovered_cell; let Rails { vertical, horizontal } = &mut *rails; match scroll { Scroll::Up => { if shifted.0 { horizontal[x].rotate_left(1); for (v, h) in vertical.iter_mut().zip(horizontal[x].iter()) { v[x] = h.clone(); } for (cell, v) in CELLS[x].iter().zip(horizontal[x].iter()) { cell.set(v.clone()); } } else { vertical[y].rotate_left(1); for (h, v) in horizontal.iter_mut().zip(vertical[y].iter()) { h[y] = v.clone(); } for (cell, v) in CELLS.iter().zip(vertical[y].iter()) { cell[y].set(v.clone()); } } } Scroll::Down => { if shifted.0 { horizontal[x].rotate_right(1); for (v, h) in vertical.iter_mut().zip(horizontal[x].iter()) { v[x] = h.clone(); } for (cell, v) in CELLS[x].iter().zip(horizontal[x].iter()) { cell.set(v.clone()); } } else { vertical[y].rotate_right(1); for (h, v) in horizontal.iter_mut().zip(vertical[y].iter()) { h[y] = v.clone(); } for (cell, v) in CELLS.iter().zip(vertical[y].iter()) { cell[y].set(v.clone()); } } } } } } #[derive(Resource)] struct Shifted(bool); fn shifter(keys: Res<ButtonInput<KeyCode>>, mut shifted: ResMut<Shifted>) { if keys.just_pressed(KeyCode::ShiftLeft) || keys.just_pressed(KeyCode::ShiftRight) { shifted.0 = true; } else if keys.just_released(KeyCode::ShiftLeft) || keys.just_released(KeyCode::ShiftRight) { shifted.0 = false; } } fn camera(mut commands: Commands) { commands.spawn(Camera2dBundle::default()); }
#형변환 -자동형변환 : 컴파일러가 자동으로 작은자료형을 큰자료형으로 변환 -강제형변환 : 큰자료형에서 작은 자료형으로 변환시 데이터손실이 발생할수있음(데이터의 변형,손실 감수) #변수와 메모리 구조 -static = 메소드가 저장되는 공간 #출력메소드 -printf() = 정해져 있는 형식에 맞춰서 그 형식에 맞는 값을 줄바꿈 하지 않고 출력 [잘안씀] #escape 문자 -\ +t=tap (출력에 표기) n=엔터 \=\ '=' "=" u-유니코드표시 1.변수 - 변수를 선언할 수 있다. -변수 선언 방법 -자료형 -변수명 작성 규칙과 관례 -Scanner -sysout 2.연산자 -연산자 종류를 알고, 결과를 예측할 수 있다. #연산자 -증감연산자 : ++,-- -전위연산 : 먼저 연산 후 다른 연산 실행 -후위연산 : 다른 연산 우선 실행 후 연산 -산술연산자 :+,-,*,/,%(나머지연산자) /를 사용할시 정수인가 고민하고 작업하기 /:정수/정수 =>정수 /,% : 2번째 수는 0이 오면 안됨. % : 나누었을때 나머지 값 -비교연산자(==,!=<=,>=,<,>) : 항상 논리값이 결과 값임 -논리연산자 : && : 둘다 참이면 참, ~이고 || : 둘다 거짓이면 거짓, ~이거나 ! : 반대, ~아닌 -대입연산자 : 오른쪽에 있는 값을 왼쪽에 저장 ex) a=2 ,2 =a(오류), a= 1+b, a+1 =b(오류) -삼항연산자 : 조건식? 참 : 거짓; 조건식의 결과 값에 따라 참일경우 식1,거짓일 경우 식2 수행 ex)String str = a>b ? "참" : "거짓"; -비트연산자 : &, |, ~, ^(배타논리, xor) & : 1을 참, 0을 거짓으로 본다 a>>b :a를 비트로 나열한 후 오른쪽으로 b비트만큼 이동, a의 b제곱으로 나눈 효과 << :a의b제곱으로 곱한 효과 #조건문★★★★★★★★ -if(조건식){실행문;}일반적으로 비교연산자가 들어감 -if~else if(조건식){실행문;}else{실행문2;}//실행문이 거짓일시 실행문2 실행 if(조건식){실행문;}else if(조건식2){}//else if문을 사용할시 조건식을 계속 추가가능 #switch문 -switch문 사용하는 경우 1. 식의 값이 제한적일 때 : %연산자 이용하는 경우 2. 사용하는 변수 값이 제한적일 때 : 산술연산자를 이용한 계산 예제 #반복문 -for(초기식; 조건식; 증감식){수행될문장;}//수행식 안에 조건문을 첨가하여 조건식 가능(if) #중첩반복문 -for(초기식; 조건식; 증감식){수행될문장; for(초기식2; 조건식2; 증감식2){수행될문장2}} #분기문 -break : break문 자신이 포함된 가까운 반복문을 빠져나감(if안에서 자주씀) -continue : continue아래 부분은 실행하지 않고 반복문 다시실행 1.변수 -변수 선언을 할 수 있다. -변수 선언 방법 자료형 변수명; 자료형 변수명=초기값; -자료형 종류 -변수명 작성 규칙과 관례 -자료형 변환 -자동/강제 형변환 -Scanner 사용 방법 : 콘솔에서 입력 -sysout 사용 방법 : 콘솔에 출력 2.연산자 -연산자 종류를 알고, 결과를 예측할 수 있다. -연산자 종류 -산술 % : 나누었을 떄 나머지 / : 정수 /정수=>정수,1/2=>0 -비교 대입연산자 == 를 구별, >=와 <=기호를 =>이나=<로 잘못쓰지 말자 -논리 결과가 참 또는 거짓=>조건식 연산자 양 쪽에 조건식 && : ~하고, 둘다 참이면 참 || : ~이거나, 하나라도 참이면 참 -증감 최종적으로 1증가 전위 : 증가 후 동작 후위 : 동작 후 증가 -조건선택 조건식?참:거짓; -비트논리(잘 사용안함) -비트쉬프트(잘 사용안함) -대입★ 오른쪽에 있는 값을 왼쪽에 저장(덮어쓰기) 연산자 우선순위 : 모르면() 3.조건문 -조건에 따라 결과가 달라지는 상황에서 조건문을 쓸 수 있다. -~이면...해라 -if문 모든 조건문은 if문으로 표현 가능 if(조건식){실행문;} -~이면 : 조건식, ...해라 : 실행문 //조건식1이 참이면 실행문1을 실행 if(조건식1){실행문1} //(조선식1이 거짓이고)조건식2가 참이면 실행문2를 실행 else if(조건식2){실행문2;} //(조건식1과 조건식2가 거짓이면)실행문3을 실행 else{실행문3] -switch문 switch(식또는변수){ case 값1: 실행문1; break; case 값2: 실행문2; break; default: 실행문3 4.반복문 -규칙적인 작업을 반복적으로 할 때 반복문을 사용할 수 있다. -반복문은 조건식이 거짓이 되는 순간 반복문을 종료 -for문 for(1.초기화;2.5.8조건식;4.7.증감식){3.6.실행문} -1.초기화 : 조건식에서 사용하는 변수를 초기화, 생략 가능,여러 변수를 초기화 -2.조건식 : 반복문이 실행되는 곳으로 거짓이면 종료,생략 가능,생략시 항상 참 -4.증감식 : 조건식에서 사용하는 변수를 증가/감속하여 반복횟수를 조절 -중첩 반복문 -반복문의 실행문으로 반복문이 오는 경우 -break -반복문을 빠져 나오는 키워드, 반드시 if문 사용 -continue -반복문의 특정 위치로 이동하는 키워드, for문에서는 증감식, while문에서는 조건식 -for문 : 순차적으로 증가/감소해서 반복문이 실행되어야 하는 경우 -while문 : 특정값을 입력받아 활용하는 경우, 값이 순차적이지 않는 경우, 단순 횟수만 사용되는 경우 #배열 -같은 자료형의 변수를 하나의 묶음으로 다루는 것 -배열은 저장된 값이 0부터 시작 -반복문을 이용해 변수들을 효율적으로 활용하기위해 사용 자료형[] 배열명; 자료형 배열명[]; 배열 바깥에 저장할수 없다는 경고문(java.lang. ArrayIndexOutOfBoundsException) #배열 초기화 -인덱스를 이용한 초기화 -for문을 이용한 초기화 배열 - 같은 자료형을 모아놓은 공간(같은 의미) -반복문으로 효율적으로 사용 -한 배열에는 같은 종류에 값을 저장하는 게 좋다 -arr1 : 0번지에는 사과 개수,1번지에는 나이, 2번지에는 학년 -arr2 : 0번지엥 1번학생 국어성적, 1번지에는 2번학생 국어성적 2번지에는 3번학생 국어성적 변수 - 가정집 배열 - 아파트 - 기본 자료형으로 된 변수는 값을 저장 - 배열은 주소를 저장 배열 선언 -자료형[] 배열명; -자료형 배열명[]; 배열 할당 배열명 = new 자료형[크기] 배열 선언과 동시에 할당 자료형[]배열명 = new자료형[크기] 자료형 배열명[] = new자료형[크기] 배열의 시작번지는 0번지부터 크기-1번지까지 접근 가능 배열[번지] 변수복수 int num1 = 10, num2 =20 //num1에 num2의 값을 복사 num1 = num2 num1 = 30 num2;//num1에 상관없이 20 배열 얕은 복사 int arr1[]= new int[4]; int arr2[]; arr2 = arr1//arr1의 배열의 값을 arr2가 가져옴 arr2[0] =4; arr1[0];//4로 같이 바뀜 배열 깊은 복사 system.arraycopy(arr1,0,arr2,0,arr1.length); #클래스 -멤버변수 -메소드 -생성자 -접근제한자 -private, (default), protected, public -클래스 앞에 접근제한자 public은 조건부로 올 수 있다. -클래스 명과 파일명이 동일해야 public을 붙일 수 있다. #변수 -참조변수vs일반변수(기본자료형으로 만들어진 변수) -일반변수 : 기본자료형으로 만들어진 변수 -참조변수 : 기본자료형이 아닌 것들로 만들어진 것 배열,객체(String) 등 -매개변수 : 메소드를 실행하기 위해 필요한 정보를 전달하는 변수 -인자 : 메소드를 실행하기 위해 실제 전달하는 값 -지역변수 : 메소드 안에서 선언되어서 사용되는 변수 -멤버변수(필드) : 클래스 안에 선언하는 변수 -인스턴스 필드 -클래스 필드 #메소드 : [하나의] 기능을 하도록 모아놓은 코드 -재사용을 통해 코드의 길이를 줄임 -기능의 유지보수를 쉽게 하기 위해 -구조를 쉽게 파악할 수 있음 #메소드 오버로딩 : 동일한 메소드가 여러개 있는 것 -매개변수가 다른 경우 : 종류(변수), 개수(변수의 개수) -같은 이름으로 같은 기능을 실행하는데 매개변수의 종류를 다양하게 만들 수 있다. =>편리 -가변인자 => 매개변수의 개수가 미정//자주사용하진 않음 #클래스 => 클래스를 통해 필드를 편리하게 관리하고, 필요한 기능을 구현하여 사용 -메소드 : 기능 -생성자 : 필드를 초기화 -멤버변수(필드) : 정보 #필드 초기화 순서 1.필드 기본값으로 초기화 2.명시적 초기화(필드 선언 후 =을 통해 하는 초기화) 3.초기화 블록 : {} 4.생성자 #static => 클래스 필드/메소드 -같은 클래스로 만들어진 모든 객체들이 공유하는 필드/메소드에 붙이는 예약어 또는 키워드 -클래스명으로 호출 -클래스가 메모리에 로딩이 되면 필드와 메소드가 생성 -static이 안붙은 필드/메소드 => 인스턴스 필드/메소드, 객체 필드/메소드 -각 개체마다 필드/메소드를 가짐 -객체명으로 호출 -객체를 생성하는 시점에 필드와 메소드가 생성 static 필드/메소드 => static메소드/객체메소드에서 사용 가능 객체 필드/메소드 => 객체 메소드에서 사용 가능 #final 필드 : 상수 => 값을 변경할 수 없다. 베스킨 라빈스 31 만들기 1. 플레이 //컴퓨터가 랜덤으로 1~3의 숫자를 부름 //사용자가 몇개의 숫자를 부를지 입력(>2를 누르면 45가 입력되도록) 2. 기록확인 컴퓨터가 몇번이기고 사용자가 몇번이겼는지 3. 종료 123 >2 45 6 >3 789
import { SetupContext, reactive, shallowReactive, ShallowReactive, InjectionKey, inject, provide, } from 'vue' import { SelectService, Config, UnionToIntersection, Fn } from '@/types' import { extractDefaults, isPrimitive, toRefsSafe } from '@/utils' // hooks import phrase from '@/hooks/phrase' import item from '@/hooks/item' import src from '@/hooks/src' import model from '@/hooks/model' import items from '@/hooks/items' import ui from '@/hooks/ui' const symbol: InjectionKey<SelectService> = Symbol('selectService') const map = { phrase, item, src, model, items, ui, } as const export const props = Object.assign( {}, ...Object.values(map).map((e) => e.props) ) as UnionToIntersection<typeof map[keyof typeof map]['props']> // original defaults; they may not reflect current defaults if defineConfig is used export const defaults = extractDefaults(props) declare module '@/types' { export type Config = typeof defaults export interface SelectService { ready: boolean props: Config context: Partial<SetupContext> defaults: Config phrase: ReturnType<typeof phrase['hook']> item: ReturnType<typeof item['hook']> src: ReturnType<typeof src['hook']> model: ReturnType<typeof model['hook']> items: ReturnType<typeof items['hook']> ui: ReturnType<typeof ui['hook']> service: ShallowReactive<SelectService> } } export default useService export function useService( options: (Partial<Config> | Config) & { service?: SelectService } = {}, context: Partial<SetupContext> = {}, forceNew: boolean = false ) { let service = forceNew ? null : options.service || inject(symbol, null) if (!service) { // if(/* typeof options extends Config */) return buildService(localProps, context) // extract actual config from props const config = extractDefaults(props, true) as Config // merge config & options const localProps = reactive({ ...config, ...toRefsSafe(options), }) as Config service = buildService(localProps, context) } provide(symbol, service) return service } export function defineConfig<T extends Partial<Config>>(config: T): T { Object.entries(config).forEach( ([name, value]) => // @ts-ignore (props[name].default = isPrimitive(value) ? value : () => value) ) return config } function buildService(props: Config, context: Partial<SetupContext>) { const service = shallowReactive({ ready: false, props, context, defaults, }) as SelectService service.service = service Object.entries(map).reduce( (m, [name, def]) => Object.assign(m, { [name]: def.hook(props, context, m as SelectService), }), service ) service.ready = true return service }
import React, { useState } from 'react'; import { FaBars, FaTimes, FaMoon, FaSun } from 'react-icons/fa'; import { Link } from 'react-scroll'; import { useDarkMode } from './DarkMode/DarkModeContext'; const Navbar = () => { const [nav, setNav] = useState(false); const { darkMode, toggleDarkMode } = useDarkMode(); const handleClick = () => setNav(!nav); return ( <div className={`fixed w-full h-[80px] flex justify-between items-center px-4 ${darkMode ? 'bg-white text-black' : 'bg-[#0a192f] text-gray-300'}`}> <div> <h1 className={`font-thin text-2xl italic font-serif ${darkMode ? 'text-black' : ''}`}>Ayan M</h1> </div> {/* menu */} <ul className='hidden md:flex gap-x-8'> <li> <Link to='home' smooth={true} duration={500}> Home </Link> </li> <li> <Link to='about' smooth={true} duration={500}> About </Link> </li> <li> <Link to='skills' smooth={true} duration={500}> Skills </Link> </li> <li> <Link to='work' smooth={true} duration={500}> Work </Link> </li> <li> <Link to='contact' smooth={true} duration={500}> Contact </Link> </li> {/* Dark Mode Toggle */} <li> <button onClick={toggleDarkMode} className='text-gray-300'> {darkMode ? <FaSun /> : <FaMoon />} </button> </li> </ul> {/* Hamburger */} <div onClick={handleClick} className='md:hidden z-10'> {!nav ? <FaBars /> : <FaTimes />} </div> {/* Mobile menu */} <ul className={ !nav ? 'hidden' : 'absolute top-0 left-0 w-full h-screen bg-[#0a192f] flex flex-col justify-center items-center' } > <li className='py-6 text-4xl'> <Link onClick={handleClick} to='home' smooth={true} duration={500}> Home </Link> </li> <li className='py-6 text-4xl'> {' '} <Link onClick={handleClick} to='about' smooth={true} duration={500}> About </Link> </li> <li className='py-6 text-4xl'> {' '} <Link onClick={handleClick} to='skills' smooth={true} duration={500}> Skills </Link> </li> <li className='py-6 text-4xl'> {' '} <Link onClick={handleClick} to='work' smooth={true} duration={500}> Work </Link> </li> <li className='py-6 text-4xl'> {' '} <Link onClick={handleClick} to='contact' smooth={true} duration={500}> Contact </Link> </li> </ul> </div> ); }; export default Navbar;
import { Suspense, useEffect, useState } from 'react' import { HiOutlineSquares2X2 } from 'react-icons/hi2' import { Await, defer, useLoaderData, useSearchParams } from 'react-router-dom' import ProductSkeleton from '../components/loading/ProductSkeleton' import Pagination from '../components/Pagination' import ProductCard from '../components/product/ProductCard' import usePagination from '../hooks/usePagination' import { getAllProducts } from '../services/products' export const shopLoader = async () => { const products = getAllProducts() return defer({ products }) } export const Shop = () => { const { products } = useLoaderData() const [searchParams] = useSearchParams([]) const [filteredProducts, setFilteredProducts] = useState(products._data || []) const [categoryfilters, setCategoryFilters] = useState([]) const [priceFilter, setPriceFilter] = useState([]) const itemsPerPage = 10 const totalProducts = filteredProducts.length const { currentItems, currentPage, goToNextPage, goToPrevPage, goToPage, totalPages, indexOfFirstItem, indexOfLastItem } = usePagination(filteredProducts, itemsPerPage) useEffect(() => { const category = searchParams.get('category') ? searchParams.get('category').split('-') : [] const price = searchParams.get('price') ? searchParams.get('price').split('-') : [] setCategoryFilters(category) setPriceFilter(price) }, [searchParams]) useEffect(() => { if (!products._data) return setFilteredProducts(products._data) const filtered = products._data.filter(product => { return [ categoryfilters.length > 0 ? categoryfilters.includes(product.category) : true, !!(product.price >= priceFilter[0] && product.price <= priceFilter[1]) ].every(condition => condition) }) setFilteredProducts(filtered) }, [products, categoryfilters, priceFilter]) return ( <Suspense fallback={<ProductSkeleton />}> <Await resolve={products}> {(() => ( <section> <div className='flex items-center gap-5 mb-5'> <HiOutlineSquares2X2 className='text-3xl text-black self-center' /> { itemsPerPage > totalProducts ? ( <p>Showing {1} - {totalProducts} of {' '} {totalProducts} results </p> ) : ( <p> Showing {' '}{indexOfFirstItem + 1} - {indexOfLastItem} of {' '} {totalProducts} results </p> ) } </div> <div className='grid grid-cols-[repeat(auto-fit,minmax(250px,1fr))] gap-10'> {currentItems.map((product) => ( <ProductCard key={product.id} product={product} /> ))} </div> <Pagination currentPage={currentPage} totalPages={totalPages} goToNextPage={goToNextPage} goToPrevPage={goToPrevPage} goToPage={goToPage} /> </section> ))} </Await> </Suspense> ) }
import { Image, NativeScrollEvent, NativeSyntheticEvent, SafeAreaView, ScrollView, StyleSheet, Text, TouchableOpacity, View, } from "react-native"; import React from "react"; import { HeaderSearch } from "../components/Header"; import { Path, Svg } from "react-native-svg"; import { SIZE } from "../constants/size"; import Search from "../components/Search"; import { COLOR } from "../constants/color"; import { browse, explorer } from "../data/search"; import { LinearGradient } from "expo-linear-gradient"; import { useSharedValue } from "react-native-reanimated"; import AbsolutePlayer from "../components/AbsolutePlayer"; type Props = {}; const SearchScreen = (props: Props) => { const scrollY = useSharedValue(0); return ( <View style={styles.container}> <AbsolutePlayer /> <HeaderSearch contentOffsetY={scrollY} /> <Search /> <ScrollView scrollEventThrottle={16} onScroll={(event: NativeSyntheticEvent<NativeScrollEvent>) => { scrollY.value = event.nativeEvent.contentOffset.y; }} horizontal={false} bounces={false} contentContainerStyle={{ paddingHorizontal: 10, marginTop: 20, alignItems: "center", }} > <Text style={{ color: COLOR.textColor, fontWeight: "bold", fontSize: 18, marginVertical: 20, width: "100%", paddingHorizontal: 10, }} > Explorez vos genres </Text> <View style={{ gap: 10, flexDirection: "row", marginBottom: 10, justifyContent: "center", }} > {explorer.map((item, index) => { return ( <TouchableOpacity key={index} style={{ width: SIZE.width / 3.5, height: SIZE.width / 2.1, borderRadius: 8, backgroundColor: "purple", overflow: "hidden", }} > <LinearGradient colors={["transparent", "#000"]} style={{ width: "100%", height: "100%", position: "absolute", zIndex: 999, justifyContent: "flex-end", }} > <View style={{ width: "100%", flexDirection: "row", alignItems: "flex-end", justifyContent: "space-between", paddingHorizontal: 10, paddingVertical: 10, }} > <Text style={{ width: "60%", fontWeight: "bold", color: COLOR.textColor, }} > {item.title} </Text> <Text style={{ backgroundColor: COLOR.greyLight, paddingVertical: 1, paddingHorizontal: 4, fontSize: 10, borderRadius: 8, }} > E </Text> </View> <Image style={{ width: "100%", height: "100%", position: "absolute", zIndex: -2, }} source={{ uri: item.cover, }} resizeMode="cover" /> </LinearGradient> </TouchableOpacity> ); })} </View> <Text style={{ color: COLOR.textColor, fontWeight: "bold", fontSize: 18, marginVertical: 20, width: "100%", paddingHorizontal: 10, }} > Parcourir tout </Text> <View style={{ gap: 10, flexDirection: "row", flexWrap: "wrap", marginBottom: 10, justifyContent: "center", }} > {browse.map((item, index) => { return ( <View key={index} style={{ width: SIZE.width / 2.3, height: SIZE.width / 3.5, borderRadius: 8, backgroundColor: "purple", flexDirection: "row", justifyContent: "space-between", overflow: "hidden", }} > <Text style={{ padding: 10, color: COLOR.textColor, fontSize: 16, fontWeight: "bold", width: "60%", }} > {item.name} </Text> <View style={{ width: SIZE.width / 5, height: SIZE.width / 5, position: "absolute", bottom: -5, right: -10, transform: [{ rotate: "25deg" }], borderRadius: 4, overflow: "hidden", }} > <Image style={{ width: "100%", height: "100%", }} resizeMode="cover" source={require("../../assets/image/oboy.png")} /> </View> </View> ); })} </View> </ScrollView> </View> ); }; export default SearchScreen; const styles = StyleSheet.create({ container: { flex: 1, alignItems: "center", backgroundColor: COLOR.bgColor, }, });
// // CardDetailView.swift // Cards // // Created by ARobbins on 2/23/23. // import SwiftUI struct CardDetailView: View { @EnvironmentObject var viewState: ViewState @State private var currentModal: CardModal? @State private var stickerImage: UIImage? @Binding var card: Card var body: some View { content .toolbar { ToolbarItem(placement: .navigationBarTrailing) { Button("Done") { viewState.showAllCards.toggle() } } ToolbarItem(placement: .bottomBar) { CardBottomToolbar(cardModal: $currentModal) } } .sheet(item: $currentModal) { item in switch item { case .stickerPicker: StickerPicker(stickerImage: $stickerImage) .onDisappear { if let stickerImage = stickerImage { card.addElement(uiImage: stickerImage) } stickerImage = nil } default: EmptyView() } } } var content: some View { ZStack { card.backgroundColor .edgesIgnoringSafeArea(.all) ForEach(card.elements, id: \.id) { element in CardElementView(element: element) .resizableView(transform: bindingTransform(for: element)) .frame( width: element.transform.size.width, height: element.transform.size.height) .contextMenu { Button(action: { card.remove(element)}) { Label("Delete", systemImage: "trash") } } } } } func bindingTransform(for element: CardElement) -> Binding<Transform> { guard let index = element.index(in: card.elements) else { fatalError("Element does not exist") } return $card.elements[index].transform } } struct CardDetailView_Previews: PreviewProvider { struct CardDetailPreview: View { @State private var card = initialCards[0] var body: some View { CardDetailView(card: $card) .environmentObject(ViewState(card: card)) } } static var previews: some View { CardDetailPreview() } }
package main import ( _ "embed" "fmt" "strconv" "strings" "github.com/sirupsen/logrus" ) //go:embed input.txt var inputDataB []byte type number struct { value string row int startCol int endCol int } func main() { input := string(inputDataB) splitted := strings.Split(input, "\n") n := len(splitted) m := len(splitted[0]) engine := make([]string, n) for j := 0; j < n; j++ { engine[j] = splitted[j] } sum := 0 var num *number for j := 0; j < m; j++ { num = nil // reset number on each line start for i := 0; i < m; i++ { if char := engine[j][i]; isNumber(char) { if num == nil { num = &number{row: j, startCol: i} } num.value = num.value + string(char) } else { if num == nil { continue // no number, just iterating symbols and periods } num.endCol = i - 1 fmt.Printf("end of number: %+v\n", *num) if isAdjacentToSymbol(num, engine) { fmt.Println("is adjacent:", num.value) val, err := strconv.Atoi(num.value) if err != nil { logrus.WithError(err).Errorf("failed to cast `%s` to int\n", num.value) } sum = sum + val } num = nil // reset number } } // end of line if num == nil { continue // no number, just iterating symbols and periods } num.endCol = m - 1 fmt.Printf("end of number: %+v\n", *num) if isAdjacentToSymbol(num, engine) { fmt.Println("is adjacent:", num.value) val, err := strconv.Atoi(num.value) if err != nil { logrus.WithError(err).Errorf("failed to cast `%s` to int\n", num.value) } sum = sum + val } num = nil // reset number } fmt.Println(sum) } func isNumber(b byte) bool { return 48 <= b && b <= 57 } func isAdjacentToSymbol(num *number, engine []string) bool { var x, y int n := len(engine) // num rows m := len(engine[0]) // num cols // top left x = num.startCol - 1 y = num.row - 1 if x >= 0 && y >= 0 && isSymbol(engine[y][x]) { return true } // top right x = num.endCol + 1 y = num.row - 1 if x <= m-1 && y >= 0 && isSymbol(engine[y][x]) { return true } // top y = num.row - 1 if y >= 0 { for i := num.startCol; i <= num.endCol; i++ { if isSymbol(engine[y][i]) { return true } } } // bottom left x = num.startCol - 1 y = num.row + 1 if x >= 0 && y <= n-1 && isSymbol(engine[y][x]) { return true } // bottom right x = num.endCol + 1 y = num.row + 1 if x <= m-1 && y <= n-1 && isSymbol(engine[y][x]) { return true } // bottom y = num.row + 1 if y <= n-1 { for i := num.startCol; i <= num.endCol; i++ { if isSymbol(engine[y][i]) { return true } } } // left x = num.startCol - 1 y = num.row if x >= 0 && isSymbol(engine[y][x]) { return true } // right x = num.endCol + 1 y = num.row if x <= m-1 && isSymbol(engine[y][x]) { return true } return false } func isSymbol(b byte) bool { return b != 46 && (b < 48 || b > 57) // not dot and not a number }
# Given an m x n grid of characters board and a string word, return true if word exists in the grid. # The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once. # Example 1: # Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" # Output: true # Example 2: # Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" # Output: true # Example 3: # Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" # Output: false # Constraints: # m == board.length # n = board[i].length # 1 <= m, n <= 6 # 1 <= word.length <= 15 # board and word consists of only lowercase and uppercase English letters. class Solution: def exist(self, board: List[List[str]], word: str) -> bool: ROWS = len(board) COLS = len(board[0]) cache = set() def dfs(i,j, x): if x == len(word): return True if (i < 0 or j < 0 or i >= ROWS or j >= COLS or (i,j) in cache or board[i][j] != word[x]): return False cache.add((i,j)) res = (dfs(i+1, j, x+1) or dfs(i-1, j, x+1) or dfs(i, j+1, x+1) or dfs(i, j-1, x+1)) cache.remove((i,j)) return res for r in range(ROWS): for c in range(COLS): if dfs(r, c, 0): return True return False # Runtime 7708 ms Beats 49.60% # Memory 16.3 MB Beats 74.74%
package com.unopuntodos.actividad; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Toast; import android.widget.TextView; public class MainActivity2 extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); // MOSTRAR MENSAJE EMERGENTE Toast.makeText(getApplicationContext(),"Usted a ingresado al sistema", Toast.LENGTH_LONG).show(); // AQUI SE ENLAZA LA VISTE DEL TEXTVIEW DESDE EL DISEÑO XML TextView textViewBienvenida = findViewById(R.id.textView); // RECIBIR EL NOMBRE DE USUARIO DESDE LA PRIMERA ACTIVITY // ADEMAS SE OBTIENE EL INTENT QUE INICIO LA ACTIVIDAD Intent intent = getIntent(); //AQUI SE VERIFICA QUE EL INTENT NO SEA NULO if (intent !=null){ //OBTENER EL NOMBRE DE USUARIO DEL INTENT String username = intent.getStringExtra("username"); //AQUI SE VERIFICA QUE EL USUARIO NO SEA NULO NI VACIO if (username != null && !username.isEmpty()){ //AQUI MUESTRA EL MENSAJE DE BIENVENIDA CON EL NOMBRE DE USUARIO textViewBienvenida.setText("Bienvenid@" + username); } } } public void MenuPrincipal(View view){ Intent actividad1 = new Intent(this,MainActivity.class); startActivity(actividad1); } }
import { HttpClient } from '@angular/common/http'; import { Inject, Injectable, InjectionToken } from '@angular/core'; import { IMarketingRepresentation } from '@apollo/api/interfaces'; import { Observable, of } from 'rxjs'; import { catchError, map, shareReplay } from 'rxjs/operators'; import { ICategory, IOppotunitiesMetadata } from './app-metadata.interface'; import { countryList } from './country-list'; export const METADATA_SERVICE_API_URL = new InjectionToken<string>('MetadataServiceApiUrl'); @Injectable({ providedIn: 'root' }) export class MetadataService { private _metadata$: Observable<ICategory[]>; private _regions$: Observable<string[]>; private _marketingLayers$: Observable<IMarketingRepresentation[]>; private _opportunity$: Observable<string[]>; private _opportunitiesMetadata$: Observable<IOppotunitiesMetadata>; private _countryList$: Observable<string[]>; public assetTypesMetadata$: Observable<string[]> = this.opportunitiesMetadata$.pipe(map((res) => { return res.assetTypes; })); public contractTypesMetadata$: Observable<string[]> = this.opportunitiesMetadata$.pipe(map((res) => { return res.contractTypes; })); public deliveryTypesMetadata$: Observable<string[]> = this.opportunitiesMetadata$.pipe(map((res) => { return res.deliveryTypes; })); public offerTypesMetadata$: Observable<string[]> = this.opportunitiesMetadata$.pipe(map((res) => { return res.offerTypes; })); public phaseTypesMetadata$: Observable<string[]> = this.opportunitiesMetadata$.pipe(map((res) => { return res.phaseTypes; })); private readonly CACHE_SIZE = 1; constructor( private httpClient: HttpClient, @Inject(METADATA_SERVICE_API_URL) private readonly metadataServiceApi: string ) {} public getMetadataFromType(type: string): Promise<ICategory> { return this.metadata$.pipe( map((metadata: ICategory[]) => metadata.find((meta) => meta.name === type)) ).toPromise(); } public get metadata$(): Observable<ICategory[]> { if (!this._metadata$) { this._metadata$ = this.getLayerMetadataFromApi().pipe( shareReplay(this.CACHE_SIZE) ); } return this._metadata$; } public get countryList$(): Observable<string[]> { if(!this._countryList$) { this._countryList$ = this.getCountryFromApi().pipe( shareReplay(this.CACHE_SIZE) ); } return this._countryList$; } public get regions$(): Observable<string[]> { if (!this._regions$) { this._regions$ = this.getRegionsMetadataFromApi().pipe( shareReplay(this.CACHE_SIZE) ); } return this._regions$; } public get marketingLayers$(): Observable<IMarketingRepresentation[]> { if (!this._marketingLayers$) { this._marketingLayers$ = this.getMarketingLayersMetadataFromApi().pipe( shareReplay(this.CACHE_SIZE) ); } return this._marketingLayers$; } public get opportunity$(): Observable<string[]> { if (!this._opportunity$) { this._opportunity$ = this.getOpportunityFromApi().pipe( shareReplay(this.CACHE_SIZE) ); } return this._opportunity$; } public get opportunitiesMetadata$(): Observable<IOppotunitiesMetadata> { if(!this._opportunitiesMetadata$) { this._opportunitiesMetadata$ = this.getOpportunitiesMetadataFromApi().pipe( shareReplay(this.CACHE_SIZE) ); } return this._opportunitiesMetadata$; } private getLayerMetadataFromApi(): Observable<ICategory[]> { return this.httpClient.get<ICategory[]>(this.metadataServiceApi + '/layers').pipe( catchError(() => of([])) ); } private getRegionsMetadataFromApi(): Observable<string[]> { return this.httpClient.get<string[]>(this.metadataServiceApi + '/regions').pipe( catchError(() => of([])) ); } private getMarketingLayersMetadataFromApi(): Observable<IMarketingRepresentation[]> { return this.httpClient.get<IMarketingRepresentation[]>(`${this.metadataServiceApi}/marketing-layers`).pipe( catchError(() => of([])) ); } private getOpportunityFromApi(): Observable<string[]> { return of(["Oil & Gas", "Wind", "Solar", "CCUS", "Geothermal", "Carbon Trading"]); } private getCountryFromApi(): Observable<string[]> { return of(countryList) } private getOpportunitiesMetadataFromApi(): Observable<IOppotunitiesMetadata | null> { return this.httpClient.get<IOppotunitiesMetadata>(this.metadataServiceApi + '/opportunities').pipe( catchError(() => of(null)) ); } }
import React, { useState } from 'react'; import { useHistory } from 'react-router-dom'; import axios from 'axios'; import '../styles/CreateAccount.css'; export default function CreateAccount() { const [userName, setUserName] = useState(''); const [userEmail, setUserEmail] = useState(''); const [userDepartament, setUserDepartament] = useState(''); const [userPassword, setUserPassword] = useState(''); const history = useHistory(); const createAccount = () => { const body = { userName, userEmail, userDepartament, userPassword }; axios .post('http://localhost:3030/users', body) .then(() => history.push('/')) .catch((error) => alert(error.response.data.message)); }; const handlerUserName = ({ target }) => { const { value } = target; setUserName(value); }; const handlerUserEmail = ({ target }) => { const { value } = target; setUserEmail(value); }; const handlerUserDepartament = ({ target }) => { const { value } = target; setUserDepartament(value); }; const handlerUserPassword = ({ target }) => { const { value } = target; setUserPassword(value); }; return ( <section className="create-account-section"> <div className="create-account-inputs"> <p className="h4">Cadastrar Usuário</p> <div className="input-group mb-3"> <span className="input-group-text" id="basic-addon1">Nome</span> <input type="text" className="form-control" value={ userName } onChange={ (e) => handlerUserName(e) }/> </div> <div className="input-group mb-3"> <span className="input-group-text" id="basic-addon1">Email</span> <input type="text" className="form-control" value={ userEmail } onChange={ (e) => handlerUserEmail(e) } /> </div> <div className="input-group mb-3"> <span className="input-group-text" id="basic-addon1">Departamento</span> <input type="text" className="form-control" value={ userDepartament } onChange={ (e) => handlerUserDepartament(e) } /> </div> <div className="input-group mb-3"> <span className="input-group-text" id="basic-addon1">Senha</span> <input type="password" className="form-control" value={ userPassword } onChange={ (e) => handlerUserPassword(e) } /> </div> <button type="button" className="btn btn-success" onClick={ () => createAccount() }>Cadastrar</button> </div> </section> ) }
<?php declare(strict_types=1); namespace App\Http\Resources; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; class SupermarketResource extends JsonResource { public static $wrap = 'supermarket'; /** * Transform the resource into an array. * * @return array<string, mixed> */ public function toArray(Request $request): array { return [ 'id' => $this->id, 'name' => $this->name, 'location' => $this->location, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, ]; } }
package model.ObjectsPackage.Weapons; import model.ObjectsPackage.Buildings.BuildingType; import model.ObjectsPackage.Resource; public enum WeaponName { BOW(BuildingType.FLETCHER, Resource.WOOD, 2, 50, true), CROSSBOW(BuildingType.FLETCHER, Resource.WOOD, 3, 70, true), SPEAR(BuildingType.POLETURNER, Resource.WOOD, 1, 1, false), PIKE(BuildingType.POLETURNER, Resource.WOOD, 2, 1, false), MACE(BuildingType.BLACKSMITH, Resource.IRON, 1, 1, false), SWORDS(BuildingType.BLACKSMITH, Resource.IRON, 1, 1, false), METAL_ARMOUR(BuildingType.ARMOURER, Resource.IRON, 1, 1, false), LEATHER_ARMOUR(BuildingType.ARMOURER, Resource.COW, 1, 1, false), HAND(null, null, 0, 0, false), TEETH(null, null, 0, 0, false), BATTERING_RAM(null, null, 0, 1, false), CATAPULT(null, null, 0, 50, false), FIRE_THROWER(null, null, 0, 10, true); private final BuildingType buildingType; private final Resource resource; private final int resourceCount; private final int range; private final boolean canMove; WeaponName(BuildingType buildingType, Resource resource, int resourceCount, int range, boolean canMove) { this.buildingType = buildingType; this.resource = resource; this.resourceCount = resourceCount; this.range = range; this.canMove = canMove; } public BuildingType getBuildingType() { return buildingType; } public Resource getResource() { return resource; } public int getResourceCount() { return resourceCount; } public int getRange() { return range; } public boolean isCanMove() { return canMove; } }
import Auth from './screens/Auth' import Upload from './screens/Upload' import Analysis from './screens/Analysis' import Account from './screens/Account' import Header from './components/Header' import FlashMessages, { flashMessage } from './components/FlashMessages' import AuthService from './services/AuthService' import { RouteComponentProps, BrowserRouter as Router, Route, Redirect, Switch, useHistory, useLocation, } from 'react-router-dom' import { useEffect, useState } from 'react' const App = () => { const [flashMessages, setFlashMessages] = useState<flashMessage[]>([]) const [loggedIn, setLoggedIn] = useState<boolean>(false) const history = useHistory() const location = useLocation() // check if logged in at each route useEffect(() => { const token = localStorage.getItem('authToken') if (token === null) { setLoggedIn(false) } else { AuthService.isAuth(token) .then((isAuth) => { setLoggedIn(isAuth) }) .catch((err) => { setLoggedIn(false) }) } }, [location]) // display flashMessage with information function createFlashMessage(text: string, type = 'success') { const message: flashMessage = { text, type } setFlashMessages(flashMessages?.concat(message)) } // close a flashmessage function deleteFlashMessage(index: number) { setFlashMessages( flashMessages?.filter((e) => flashMessages.indexOf(e) !== index) ) } // log out a user by deleting localstorage function logOutUser(e: Event) { setLoggedIn(false) history.push('/') localStorage.removeItem('authToken') createFlashMessage('You are now logged out') } return ( <div> <Router> <Header loggedIn={loggedIn} logOutUser={logOutUser} /> <FlashMessages messages={flashMessages} deleteFlashMessage={deleteFlashMessage} /> <Switch> <Route path="/register"> {loggedIn ? ( <Redirect to="/upload" /> ) : ( <Auth showLogin={false} createFlashMessage={createFlashMessage} setLoggedIn={setLoggedIn} /> )} </Route> <Route path="/login"> {loggedIn ? ( <Redirect to="/upload" /> ) : ( <Auth showLogin={true} createFlashMessage={createFlashMessage} setLoggedIn={setLoggedIn} /> )} </Route> <Route path="/upload"> {!loggedIn ? ( <Redirect to="/login" /> ) : ( <Upload createFlashMessage={createFlashMessage} /> )} </Route> <Route path="/account"> {!loggedIn ? ( <Redirect to="/login" /> ) : ( <Account createFlashMessage={createFlashMessage} /> )} </Route> <Route path="/analysis" render={({ location, }: RouteComponentProps<{}, {}, any>) => { if (!loggedIn) return <Redirect to="/" /> if (location.state && location.state.file) return ( <Analysis file={location.state.file} analysis={location.state.analysis} /> ) else return <Redirect to="/upload" /> }} /> </Switch> </Router> </div> ) } export default App
import numpy as np import collections import networkx as nx import matplotlib.pyplot as plt import scipy.io as sio import random import glob import pandas as pd import os def load_ego_nets(input_dir, network_type='gplus'): """ Load ego nets from files in input_dir. Returns a dictionary of networkx graphs. """ ego_nets = {} for file in glob.glob(input_dir + '/*.edges'): name = file.split('/')[-1].split('.')[0] if network_type in ['twitter', 'gplus']: ego_net = nx.read_edgelist(file, nodetype=str, create_using=nx.DiGraph) elif network_type == 'facebook': ego_net = nx.read_edgelist(file, nodetype=str, create_using=nx.Graph) ego_net.add_node(name) for n in ego_net.nodes(): if n != name: ego_net.add_edge(name, n) featnames_dir = {} with open(input_dir + '/' + name + '.featnames') as f: featnames = f.read().splitlines() for featname in featnames: id, f = featname.split(' ', 1) if network_type == 'twitter': k, v = f, '' else: k, v = f.split(':', 1) if k not in featnames_dir: featnames_dir[int(id)] = (k, v) feats_dir = {} feats = [] with open(input_dir + '/' + name + '.egofeat') as f: egofeat = [name] + f.read().splitlines()[0].split() feats.append(egofeat) with open(input_dir + '/' + name + '.feat') as f: for feat in f.read().splitlines(): feats.append(feat.split()) with open(input_dir + '/' + name + '.circles') as f: circles = f.read().splitlines() node2circle = collections.defaultdict(list) for circle in circles: _, members = circle.split('\t', 1) members = members.split('\t') for member in members: node2circle[member].append(list(set(members) - set([member]))) for feat in feats: if network_type in ['gplus', 'facebook']: temp = {} for i, f in enumerate(feat[1:]): if int(f) == 1: temp[featnames_dir[i][0]] = featnames_dir[i][1] elif network_type == 'twitter': temp = {'hashtags': [], 'follows': []} for i, f in enumerate(feat[1:]): if int(f) == 1: if featnames_dir[i][0].startswith('#'): temp['hashtags'].append(featnames_dir[i][0]) elif featnames_dir[i][0].startswith('@'): temp['follows'].append(featnames_dir[i][0]) # temp['neighbors'] = list(ego_net.neighbors(feat[0])) temp['social_circles'] = node2circle.get(feat[0], []) feats_dir[feat[0]] = temp nx.set_node_attributes(ego_net, feats_dir, 'features') ego_nets[name] = ego_net ego_nets['combined'] = nx.compose_all(list(ego_nets.values())) nx.write_gml(ego_nets['combined'], f'datasets/{network_type}_combined.gml') return ego_nets def load_facebook100(input_dir, name, num_egonets=10, egonets_radius=2, sample_egonets=True): feat_names = ['status', 'gender', 'major', 'second_major', 'accomodation', 'year', 'high_school'] filename = input_dir + '/' + name + '.mat' mat = sio.loadmat(filename) if 'A' in mat: A = mat['A'] feats_dir = {} if 'local_info' in mat: local_info = mat['local_info'] for i in range(len(local_info)): feat = local_info[i] temp = {} for feat_name, f in zip(feat_names, feat): if f != 0: if feat_name == 'status': if f == 1: temp[feat_name] = 'student' elif f == 2: temp[feat_name] = 'faculty' elif feat_name == 'accomodation': if f == 1: temp[feat_name] = 'house' elif f == 2: temp[feat_name] = 'dorm' elif feat_name == 'gender': continue # if f == 1: # temp[feat_name] = 'male' # elif f == 2: # temp[feat_name] = 'female' else: temp[feat_name] = int(f) feats_dir[i] = temp G = nx.from_numpy_array(A) nx.set_node_attributes(G, feats_dir, 'features') if sample_egonets: networks = sample_ego_nets(G, n_samples=num_egonets, radius=egonets_radius) else: networks = {-1: G} return networks def sample_ego_nets(G, n_samples=10, radius=2, seed=0): """ Sample n_samples ego nets from G. """ random.seed(seed) ego_nets = {} nodes = list(G.nodes()) for i in range(n_samples): ego_net = nx.ego_graph(G, random.choice(nodes), radius=radius) ego_nets[i] = ego_net return ego_nets
<%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Fruitables - Change Password</title> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <meta content="" name="keywords"> <meta content="" name="description"> <!-- Google Web Fonts --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600&family=Raleway:wght@600;800&display=swap" rel="stylesheet"> <!-- Icon Font Stylesheet --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css"/> <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.1/font/bootstrap-icons.css" rel="stylesheet"> <!-- Libraries Stylesheet --> <link href="lib/lightbox/css/lightbox.min.css" rel="stylesheet"> <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet"> <!-- Customized Bootstrap Stylesheet --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Template Stylesheet --> <link href="css/style.css" rel="stylesheet"> </head> <body> <!-- Spinner Start --> <div id="spinner" class="show w-100 vh-100 bg-white position-fixed translate-middle top-50 start-50 d-flex align-items-center justify-content-center"> <div class="spinner-grow text-primary" role="status"></div> </div> <!-- Spinner End --> <!-- Navbar Start --> <div > <div class="container topbar bg-primary d-none d-lg-block"> <div class="d-flex justify-content-between"> <div class="top-info ps-2"> <small class="me-3"><i class="fas fa-map-marker-alt me-2 text-secondary"></i> <a href="#" class="text-white">123 Street, New York</a></small> <small class="me-3"><i class="fas fa-envelope me-2 text-secondary"></i><a href="#" class="text-white">Email@Example.com</a></small> </div> <div class="top-link pe-2"> <a href="#" class="text-white"><small class="text-white mx-2">Privacy Policy</small>/</a> <a href="#" class="text-white"><small class="text-white mx-2">Terms of Use</small>/</a> <a href="#" class="text-white"><small class="text-white ms-2">Sales and Refunds</small></a> </div> </div> </div> <div class="container px-0"> <nav class="navbar navbar-light bg-white navbar-expand-xl"> <a href="index.html" class="navbar-brand"><h1 class="text-primary display-6">Ecourse</h1></a> <button class="navbar-toggler py-2 px-3" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse"> <span class="fa fa-bars text-primary"></span> </button> <div class="collapse navbar-collapse bg-white" id="navbarCollapse"> <div class="navbar-nav mx-auto"> <a href="index.html" class="nav-item nav-link active">Home</a> <a href="shop.html" class="nav-item nav-link">Shop</a> <a href="shop-detail.html" class="nav-item nav-link">Shop Detail</a> <div class="nav-item dropdown"> <a href="#" class="nav-link dropdown-toggle" data-bs-toggle="dropdown">Pages</a> <div class="dropdown-menu m-0 bg-secondary rounded-0"> <a href="cart.html" class="dropdown-item">Cart</a> <a href="checkout.html" class="dropdown-item">Checkout</a> <a href="testimonial.html" class="dropdown-item">Testimonial</a> <a href="404.html" class="dropdown-item">404 Page</a> </div> </div> <a href="contact.html" class="nav-item nav-link">Contact</a> </div> <div class="d-flex m-3 me-0"> <a href="#" class="position-relative me-4 my-auto"> <i class="fa fa-shopping-bag fa-2x"></i> <span class="position-absolute bg-secondary rounded-circle d-flex align-items-center justify-content-center text-dark px-1" style="top: -5px; left: 15px; height: 20px; min-width: 20px;">3</span> </a> <a href="#" class="my-auto"> <i class="fas fa-user fa-2x"></i> </a> </div> </div> </nav> </div> </div> <!-- Navbar End --> <!-- Change Password Form Start --> <div class="container mt-5"> <h2>Change Password</h2> <form action="userprofile" method="post"> <input type="hidden" name="userId" value="${user.userID}" /> <button type="submit" class="btn btn-primary">Back</button> </form><br/> <form action="changepass" method="post"> <div class="mb-3"> <label for="opass" class="form-label">Old Password</label> <input type="password" class="form-control" id="opass" name="opass" required> </div> <div class="mb-3"> <label for="pass" class="form-label">New Password</label> <input type="password" class="form-control" id="pass" name="pass" required> </div> <div class="mb-3"> <label for="re_pass" class="form-label">Confirm New Password</label> <input type="password" class="form-control" id="re_pass" name="re_pass" required> </div> <button type="submit" class="btn btn-primary">Change Password</button> </form> <c:if test="${not empty mess}"> <div class="alert alert-info mt-3">${mess}</div> </c:if> </div> <!-- Change Password Form End --> <!-- Footer Start --> <footer class="bg-dark text-light py-5 mt-5"> <div class="container"> <div class="row"> <div class="col-lg-3 col-md-6 mb-5"> <h4 class="text-primary">Ecourse</h4> <p>123 Street, New York, USA</p> <p>Email@Example.com</p> <p>+012 345 67890</p> <div class="d-flex pt-2"> <a class="btn btn-outline-light btn-social" href=""><i class="fab fa-twitter"></i></a> <a class="btn btn-outline-light btn-social" href=""><i class="fab fa-facebook-f"></i></a> <a class="btn btn-outline-light btn-social" href=""><i class="fab fa-youtube"></i></a> <a class="btn btn-outline-light btn-social" href=""><i class="fab fa-linkedin-in"></i></a> </div> </div> <div class="col-lg-3 col-md-6 mb-5"> <h4 class="text-light">Quick Links</h4> <a class="btn btn-link" href="index.html">Home</a> <a class="btn btn-link" href="shop.html">Shop</a> <a class="btn btn-link" href="shop-detail.html">Shop Detail</a> <a class="btn btn-link" href="contact.html">Contact</a> </div> <div class="col-lg-3 col-md-6 mb-5"> <h4 class="text-light">Pages</h4> <a class="btn btn-link" href="cart.html">Cart</a> <a class="btn btn-link" href="checkout.html">Checkout</a> <a class="btn btn-link" href="testimonial.html">Testimonial</a> <a class="btn btn-link" href="404.html">404 Page</a> </div> <div class="col-lg-3 col-md-6 mb-5"> <h4 class="text-light">Newsletter</h4> <form action=""> <div class="input-group"> <input type="text" class="form-control" placeholder="Your Email"> <button class="btn btn-primary" type="submit">Sign Up</button> </div> </form> </div> </div> </div> </footer> <!-- Footer End --> <!-- JavaScript Libraries --> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js"></script> <script src="lib/easing/easing.min.js"></script> <script src="lib/waypoints/waypoints.min.js"></script> <script src="lib/owlcarousel/owl.carousel.min.js"></script> <script src="lib/counterup/counterup.min.js"></script> <script src="lib/lightbox/js/lightbox.min.js"></script> <!-- Template Javascript --> <script src="js/main.js"></script> </body> </html>
import React, { useState, useEffect } from 'react' import Detail from './Detail'; import { Spinner } from 'react-bootstrap'; import { SpinnerDiv } from '../../Style/PostDetailCss'; import { useParams } from 'react-router-dom' import axios from 'axios'; import RepleArea from '../Reple/RepleArea'; function PostArea() { let params = useParams(); const [PostInfo, setPostInfo] = useState({}); const [Flag, setFlag] = useState(false); useEffect(() => { let body = { postNum: params.postNum } axios.post("/api/post/detail", body).then((res) => { if (res.data.success) { setPostInfo(res.data.post) setFlag(true) } }).catch((err) => { console.log(err) }) }, [params.postNum]) return ( <div> {Flag ? ( <> <Detail PostInfo={PostInfo} /> <RepleArea postId={PostInfo._id}></RepleArea> </> ) : ( <SpinnerDiv> <Spinner animation='border' role="status"> <span className="visually-hidden">Loading..</span> </Spinner> </SpinnerDiv> )} </div> ) } export default PostArea
#include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "shader_s.h" #include "camera.h" #include "model.h" #include<iostream> using namespace std; void framebuffer_size_callback(GLFWwindow* window, int width, int height); void mouse_callback(GLFWwindow* window, double xpos, double ypos); void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); void processInput(GLFWwindow* window); unsigned int loadTexture(char const* path); // settings const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; // camera Camera camera(glm::vec3(0.0f, 0.0f, 3.0f)); float lastX = (float)SCR_WIDTH / 2.0; float lastY = (float)SCR_HEIGHT / 2.0; bool firstMouse = true; // timing float deltaTime = 0.0f; float lastFrame = 0.0f; //lighting glm::vec3 lightPos(1.2f, 1.0f, 2.0f); int main() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } glEnable(GL_DEPTH_TEST); //glDepthFunc(GL_ALWAYS); glDepthFunc(GL_LESS); glEnable(GL_STENCIL_TEST); glStencilFunc(GL_NOTEQUAL,1,0xFF); glStencilOp(GL_KEEP,GL_KEEP,GL_REPLACE); Shader ourShader("./Shaders/9.1.shader.vs", "./Shaders/9.1.shader.fs");// Shader shaderSingleColor("./Shaders/9.3.shader.vs", "./Shaders/9.3.1.shader.fs"); //Model ourModel("./Model/Haku/TDA Lacy Haku.pmx"); Model ourModel("./Model/nanosuit/nanosuit.obj"); //Model ourModel("./Model/ModelUsedforGraphics/ModelforGraphics.fbx"); // float cubeVertices[] = { // // positions // texture Coords // -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, // 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, // 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, // -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, // -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, // 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, // -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, // -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, // 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, // 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, // -0.5f, 0.5f, -0.5f, 0.0f, 1.0f // }; // float planeVertices[] = { // // positions // texture Coords (note we set these higher than 1 (together with GL_REPEAT as texture wrapping mode). this will cause the floor texture to repeat) // 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, // -5.0f, -0.5f, 5.0f, 0.0f, 0.0f, // -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, // 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, // -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, // 5.0f, -0.5f, -5.0f, 2.0f, 2.0f // }; // // cube VAO // unsigned int cubeVAO, cubeVBO; // glGenVertexArrays(1, &cubeVAO); // glGenBuffers(1, &cubeVBO); // glBindVertexArray(cubeVAO); // glBindBuffer(GL_ARRAY_BUFFER, cubeVBO); // glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), &cubeVertices, GL_STATIC_DRAW); // glEnableVertexAttribArray(0); // glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); // glEnableVertexAttribArray(1); // glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); // glBindVertexArray(0); // // plane VAO // unsigned int planeVAO, planeVBO; // glGenVertexArrays(1, &planeVAO); // glGenBuffers(1, &planeVBO); // glBindVertexArray(planeVAO); // glBindBuffer(GL_ARRAY_BUFFER, planeVBO); // glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), &planeVertices, GL_STATIC_DRAW); // glEnableVertexAttribArray(0); // glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); // glEnableVertexAttribArray(1); // glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); // glBindVertexArray(0); // unsigned int cubeTexture = loadTexture("C:\\Users\\taoyijun\\Desktop\\lambda\\container.png"); // unsigned int floorTexture = loadTexture("C:\\Users\\taoyijun\\Desktop\\lambda\\container2_specular.png"); // ourShader.use(); // ourShader.setInt("texture1",0); while (!glfwWindowShouldClose(window)) { float currentFrame = static_cast<float>(glfwGetTime()); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; //intput processInput(window); glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shaderSingleColor.use(); // glm::mat4 model = glm::mat4(1.0f); glm::mat4 view = camera.GetViewMatrix(); glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); shaderSingleColor.setMat4("view", view); shaderSingleColor.setMat4("projection", projection); ourShader.use(); // glm::mat4 view = camera.GetViewMatrix(); // glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("view", view); ourShader.setMat4("projection", projection); glm::mat4 model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(0.0f, 0.0f, 0.0f)); // translate it down so it's at the center of the scene model = glm::scale(model, glm::vec3(1.0f, 1.0f, 1.0f)); // it's a bit too big for our scene, so scale it down ourShader.setMat4("model", model); // ourModel.Draw(ourShader); // draw floor as normal, but don't write the floor to the stencil buffer, we only care about the containers. We set its mask to 0x00 to not write to the stencil buffer. glStencilMask(0x00); // // floor // glBindVertexArray(planeVAO); // glBindTexture(GL_TEXTURE_2D, floorTexture); // ourShader.setMat4("model", glm::mat4(1.0f)); // glDrawArrays(GL_TRIANGLES, 0, 6); // glBindVertexArray(0); //1st glStencilFunc(GL_ALWAYS, 1, 0xFF); glStencilMask(0xFF); // cubes // glBindVertexArray(cubeVAO); // glActiveTexture(GL_TEXTURE0); // glBindTexture(GL_TEXTURE_2D, cubeTexture); ourShader.setMat4("model", model); model = glm::translate(model, glm::vec3(-1.0f, 0.0f, -1.0f)); ourShader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(2.0f, 0.0f, 0.0f)); ourShader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); ourModel.Draw(ourShader); //2nd glStencilFunc(GL_NOTEQUAL, 1, 0xFF); glStencilMask(0x00); glDisable(GL_DEPTH_TEST); shaderSingleColor.use(); float scale = 1.1f; // cubes // glBindVertexArray(cubeVAO); // glBindTexture(GL_TEXTURE_2D, cubeTexture); ourShader.setMat4("model", model); model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(-1.0f, 0.0f, -1.0f)); model = glm::scale(model, glm::vec3(scale, scale, scale)); shaderSingleColor.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(2.0f, 0.0f, 0.0f)); model = glm::scale(model, glm::vec3(scale, scale, scale)); shaderSingleColor.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); glStencilMask(0xFF); glStencilFunc(GL_ALWAYS, 0, 0xFF); glEnable(GL_DEPTH_TEST); ourModel.Draw(ourShader); glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; } unsigned int loadTexture(char const* path) { unsigned int textureID; glGenTextures(1, &textureID); int width, height, nrComponents; unsigned char* data = stbi_load(path, &width, &height, &nrComponents, 0); if (data) { GLenum format; if (nrComponents == 1) format = GL_RED; else if (nrComponents == 3) format = GL_RGB; else if (nrComponents == 4) format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, textureID); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cout << "Texture failed to load at path: " << path << std::endl; stbi_image_free(data); } return textureID; } void framebuffer_size_callback(GLFWwindow* window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } // glfw: whenever the mouse moves, this callback is called // ------------------------------------------------------- void mouse_callback(GLFWwindow* window, double xposIn, double yposIn) { float xpos = static_cast<float>(xposIn); float ypos = static_cast<float>(yposIn); if (firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } float xoffset = xpos - lastX; float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; camera.ProcessMouseMovement(xoffset, yoffset); } void processInput(GLFWwindow* window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) camera.ProcessKeyboard(FORWARD, deltaTime); if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) camera.ProcessKeyboard(BACKWARD, deltaTime); if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) camera.ProcessKeyboard(LEFT, deltaTime); if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) camera.ProcessKeyboard(RIGHT, deltaTime); } void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { camera.ProcessMouseScroll(static_cast<float>(yoffset)); }
<h1>Importar Puntos Turísticos</h1> <mat-card class="tpointContent"> <div class="left"> <p><strong>Elegir Método de importación de Puntos Turísticos:</strong></p> <!-- Dropdown with importation methods available --> <mat-form-field appearance="fill" > <mat-label>Importador</mat-label> <mat-select [(ngModel)]="selectedImporter" (selectionChange)="select(selectedImporter)" required="true" > <mat-option *ngFor="let importer of availableImporters" [value]="importer"> {{importer.importerName}} </mat-option> </mat-select> </mat-form-field> <p><strong>Importar</strong></p> <p>Nota: Utilice los caracteres <strong>' / '</strong> o <strong>' \\ '</strong> como separadores</p> <!-- Campos Variables --> <div *ngIf="selectedImporter!=undefined"> <mat-form-field *ngFor="let param of selectedImporter.parameters" appearance="fill"> <mat-label>{{param.name}}</mat-label> <input matInput [(ngModel)]="param.value" placeholder="{{param.name}}" required="true"> </mat-form-field> </div> <!-- --------- --> <div *ngIf="(availableImporters.length>0 && selectedImporter!=undefined); else elseBlock"> <button mat-raised-button color="primary" class="button-margin" (click)="import()">Importar</button> </div> <ng-template #elseBlock> <button mat-raised-button color="primary" class="button-margin" disabled>Importar</button> </ng-template> </div> <div class="right" *ngIf="importationExecuted"> <h1>Importados</h1> <table mat-table [dataSource]="importationResult.imported" class="mat-elevation-z1"> <!-- Name Column --> <ng-container matColumnDef="name" > <th mat-header-cell *matHeaderCellDef> Nombre </th> <td mat-cell *matCellDef="let element"> {{element.name}} </td> </ng-container> <!-- Tpoint Column --> <ng-container matColumnDef="tpoint" class="mat-column-error"> <th mat-header-cell *matHeaderCellDef> Punto Turístico </th> <td mat-cell *matCellDef="let element"> {{element.touristicPoint.name}} </td> </ng-container> <!-- Description Column --> <ng-container matColumnDef="description" class="mat-column-error"> <th mat-header-cell *matHeaderCellDef> Descripción </th> <td mat-cell *matCellDef="let element"> {{element.description}} </td> </ng-container> <!-- Adress Column --> <ng-container matColumnDef="direction" class="mat-column-error"> <th mat-header-cell *matHeaderCellDef> Dirección </th> <td mat-cell *matCellDef="let element"> {{element.direction}} </td> </ng-container> <!-- phone Column --> <ng-container matColumnDef="phone" class="mat-column-error"> <th mat-header-cell *matHeaderCellDef> Teléfono </th> <td mat-cell *matCellDef="let element"> {{element.phone}} </td> </ng-container> <ng-container matColumnDef="stars" class="mat-column-error"> <th mat-header-cell *matHeaderCellDef> Estrellas </th> <td mat-cell *matCellDef="let element"> {{element.stars}} </td> </ng-container> <ng-container matColumnDef="price" class="mat-column-error"> <th mat-header-cell *matHeaderCellDef> Precio/Noche </th> <td mat-cell *matCellDef="let element"> {{element.price}} </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumnsImported"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumnsImported;"></tr> </table> <h1>No Importados</h1> <table mat-table [dataSource]="importationResult.notImported" class="mat-elevation-z1"> <!-- Name Column --> <ng-container matColumnDef="notImportedname"> <th mat-header-cell *matHeaderCellDef> Nombre </th> <td mat-cell *matCellDef="let element"> {{element.lodging.name}} </td> </ng-container> <!-- Error Column --> <ng-container matColumnDef="error" class="mat-column-error"> <th mat-header-cell *matHeaderCellDef> Error </th> <td mat-cell *matCellDef="let element"> {{element.reason}} </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table> </div> </mat-card>
<template> <div class="container-fluid"> <div class="row g-3"> <div class="col-auto me-auto"> <h5>Automation App Code</h5> </div> <div class="col-auto"> <router-link class="btn btn-outline-secondary" :to="{ name: 'AutomationAppCodeAdd' }" >Add New</router-link > </div> </div> <table class="table"> <thead> <tr> <th>Name</th> <th>Namespace</th> </tr> </thead> <tbody> <tr v-for="aa in sortedCodeList" :key="aa.id"> <td> <router-link :to="{ name: 'AutomationAppCodeEdit', params: { id: aa.id }, }" >{{ aa.name }}</router-link > </td> <td>{{ aa.namespace }}</td> </tr> </tbody> </table> </div> </template> <script> export default { name: "AutomationAppCodeList", data() { return { codeList: [], }; }, computed: { sortedCodeList() { let sortedCodeList = [...this.codeList].sort((a, b) => { const nameA = a.name.toUpperCase(); const nameB = b.name.toUpperCase(); if (nameA < nameB) { return -1; } if (nameA > nameB) { return 1; } return 0; }); return sortedCodeList; }, }, mounted: function () { fetch("/api/automation-apps?filter=user") .then((response) => response.json()) .then((data) => { if (typeof data !== "undefined" && data != null) { this.codeList = data; } }); }, }; </script> <style scoped></style>
package com.app.skillsontario.activities; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import android.util.Log; import android.util.Patterns; import android.view.View; import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebViewClient; import com.app.skillsontario.R; import com.app.skillsontario.baseClasses.BaseActivity; import com.app.skillsontario.constants.AppConstants; import com.app.skillsontario.databinding.NewsDetailAcBinding; import com.app.skillsontario.models.NewsModal; import com.app.skillsontario.utils.MySharedPreference; import com.bumptech.glide.Glide; import com.bumptech.glide.load.DataSource; import com.bumptech.glide.load.engine.GlideException; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.target.Target; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import static com.app.skillsontario.utils.Utils.updatLocalLanguage; public class NewsDetailAc extends BaseActivity { private NewsDetailAcBinding binding; String url, title; NewsModal newsModal; @RequiresApi(api = Build.VERSION_CODES.N) @Override protected void initUi() { overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_from_left); binding = (NewsDetailAcBinding) viewBaseBinding; Bundle extras = getIntent().getExtras(); try { if (extras != null) { url = getIntent().getStringExtra("url"); title = getIntent().getStringExtra("title"); } } catch (Exception e) { } try { newsModal = getIntent().getParcelableExtra("model"); } catch (Exception e) { } if (newsModal != null) { if (TextUtils.isEmpty(newsModal.getNewsTitle())) { return; } else { binding.newsLayout.tvNewsTitle.setText(newsModal.getNewsTitle()); } try { binding.newsLayout.tvNewsDate.setText(changeDate(newsModal.getCreatedAt())); } catch (Exception e) { } if (TextUtils.isEmpty(newsModal.getNewsImage())) { // binding.newsLayout.imageNews.setVisibility(View.GONE); return; } else { try { Glide.with(NewsDetailAc.this) .load(newsModal.getNewsImage()) .centerCrop() .listener(new RequestListener<Drawable>() { @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) { binding.newsLayout.progress.setVisibility(View.GONE); return false; } @Override public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) { binding.newsLayout.progress.setVisibility(View.GONE); return false; } }) .into(binding.newsLayout.imageNews); } catch (Exception e) { } } if (TextUtils.isEmpty(newsModal.getNewsDesc())) { //binding.newsLayout.tvNewsDesc.setVisibility(View.GONE); binding.newsLayout.webViewNewsDesc.setVisibility(View.GONE); return; } else { //binding.newsLayout.tvNewsDesc.setVisibility(View.VISIBLE); binding.newsLayout.webViewNewsDesc.setVisibility(View.VISIBLE); /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { binding.newsLayout.tvNewsDesc.setText(Html.fromHtml(newsModal.getNewsDesc(), Html.FROM_HTML_MODE_COMPACT)); } else { binding.newsLayout.tvNewsDesc.setText(Html.fromHtml(newsModal.getNewsDesc())); }*/ binding.newsLayout.webViewNewsDesc.getSettings().setJavaScriptEnabled(true); binding.newsLayout.webViewNewsDesc.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse(request.getUrl().toString()) ); startActivity(intent); return true; //return super.shouldOverrideUrlLoading(view, request); } }); binding.newsLayout.webViewNewsDesc.loadDataWithBaseURL( "", "<html> <head><style type=\"text/css\"> @font-face { font-family: Poppins; src: url(\"file:///android_asset/fonts/poppins_regular.ttf\") } </style> </head><body>" + newsModal.getNewsDesc() + "</body>", "text/html", "utf-8", null); binding.newsLayout.webViewNewsDesc.setBackgroundColor(Color.TRANSPARENT); } try { if (!Patterns.WEB_URL.matcher(newsModal.getNewsUrl()).matches()) { binding.cvWebsite.setVisibility(View.INVISIBLE); } else { binding.cvWebsite.setVisibility(View.VISIBLE); } } catch (Exception e) { binding.cvWebsite.setVisibility(View.INVISIBLE); } //binding.cvWebsite.setOnClickListener(v -> startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(newsModal.getNewsUrl())))); binding.cvWebsite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(newsModal.getNewsUrl()))); } catch (Exception e) { showToast("Url not supported"); } } }); } /*if (url != null && !url.isEmpty()) { loadData(url); }*/ } @Override protected int getLayoutById() { return R.layout.news_detail_ac; } @Override public void onBackPressed() { super.onBackPressed(); overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_from_right); } @RequiresApi(api = Build.VERSION_CODES.N) public String changeDate(String dateString) { String dateStr = "", timeStr = "", finalDate = ""; try { // .//String dateString = dateN; String inPattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; // String outPatternDate = "yyyy-MM-dd"; String outPatternDate = "LLL dd, yyyy"; String outPatternTime = "hh:mm aa"; SimpleDateFormat inFormat = new SimpleDateFormat(inPattern, Locale.getDefault()); SimpleDateFormat outFormat = new SimpleDateFormat(outPatternDate, Locale.getDefault()); SimpleDateFormat outFormatTime = new SimpleDateFormat(outPatternTime, Locale.getDefault()); try { Date inDate = inFormat.parse(dateString); dateStr = outFormat.format(inDate); timeStr = outFormatTime.format(inDate); Log.e("TEST", dateStr); finalDate = "" + dateStr + " | " + timeStr; } catch (ParseException e) { e.printStackTrace(); finalDate = dateString; } } catch (Exception e) { e.printStackTrace(); finalDate = dateString; } return finalDate; } @Override protected void onResume() { super.onResume(); new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { languageMethod(MySharedPreference.getInstance().getStringData(AppConstants.LANGUAGE)); // binding.tv.setText(R.string.visit_website); try { binding.newsLayout.tvNewsDate.setText(changeDate(newsModal.getCreatedAt())); binding.tv.setText(R.string.visit_website); } catch (Exception e) { } } }, 70); } private void languageMethod(String lang) { if (lang != null) { if (lang.isEmpty()) { updatLocalLanguage("en", getBaseContext()); } else { updatLocalLanguage(lang, getBaseContext()); } } else { updatLocalLanguage("en", getBaseContext()); } } }
export interface DiskState { bSimulated: boolean; velocity: { x: number; y: number; z: number; }; position: { x: number; y: number; z: number; }; rotation: { x: number; y: number; z: number; }; rotationVelocity: { x: number; y: number; z: number; }; speed: number; playerHolding: string; } interface PlayerDiskStates { [key: string]: { [key: number]: DiskState; }; } interface AuthorityHistory { [key: number]: string; } let diskStates: { [gameTimeTick: number]: DiskState; } = { 0: { "bSimulated": false, "velocity":{ "x":0.0000000000000000, "y":0.0000000000000000, "z":0.0000000000000000 }, "position":{ "x":0.0000000000000000, "y":0.0000000000000000, "z":0.0000000000000000 }, "rotation":{ "x":0.0000000000000000, "y":0.0000000000000000, "z":0.0000000000000000 }, "rotationVelocity":{ "x":0.0000000000000000, "y":0.0000000000000000, "z":0.0000000000000000 }, "speed":0.0, "playerHolding": "" } }; let playerDiskStates: PlayerDiskStates = {}; let authorityHistory: AuthorityHistory = {}; let currentAuthorativePlayer: string = ""; let lastDiskState: number = 0; export const disk = { reset() { diskStates = { 0: { "bSimulated": false, "velocity":{ "x":0.0000000000000000, "y":0.0000000000000000, "z":0.0000000000000000 }, "position":{ "x":0.0000000000000000, "y":0.0000000000000000, "z":0.0000000000000000 }, "rotation":{ "x":0.0000000000000000, "y":0.0000000000000000, "z":0.0000000000000000 }, "rotationVelocity":{ "x":0.0000000000000000, "y":0.0000000000000000, "z":0.0000000000000000 }, "speed":0.0, "playerHolding": "" } }; playerDiskStates = {}; authorityHistory = {}; currentAuthorativePlayer = ""; lastDiskState = 0; console.log("Disk reset"); }, addDiskState(playerId: string, gameTick: number, diskState: DiskState) { if(lastDiskState < gameTick) { lastDiskState = gameTick; } if (diskState.playerHolding !== "" && diskState.playerHolding !== currentAuthorativePlayer) { disk.changeDiskAuthority(gameTick, diskState.playerHolding); } if(currentAuthorativePlayer == "") { disk.changeDiskAuthority(gameTick, playerId); } diskState.bSimulated = true; if (currentAuthorativePlayer == playerId) { authorityHistory[gameTick] = playerId; diskState.bSimulated = false; if (Object.keys(diskStates).length == global.gameTicksToKeep) { const sortedKeys: string[] = Object.keys(diskStates).sort((a: string, b: string) => Number(a) - Number(b)); delete diskStates[Number(sortedKeys[0])]; } diskStates[gameTick] = diskState; } if (!diskStates.hasOwnProperty(playerId)) { playerDiskStates[playerId] = { [gameTick]: diskState } } else { if (Object.keys(playerDiskStates[playerId]).length == global.gameTicksToKeep) { const sortedKeys: string[] = Object.keys(playerDiskStates[playerId]).sort((a: string, b: string) => Number(a) - Number(b)); delete playerDiskStates[playerId][Number(sortedKeys[0])]; } playerDiskStates[playerId][gameTick] = diskState; } }, removeAuthority(playerId: string) { if (playerId == currentAuthorativePlayer) { currentAuthorativePlayer = ""; } }, changeDiskAuthority(gameTick: number, playerId: string) { authorityHistory[gameTick] = currentAuthorativePlayer; currentAuthorativePlayer = playerId; for (let tick: number = gameTick + 1; tick < lastDiskState; tick++) { if (diskStates.hasOwnProperty(tick)) { delete diskStates[tick]; } } lastDiskState = gameTick; }, getDiskStatesFrom(fromGameTick: number): {[gameTick:number] : DiskState} { const sortedKeys: string[] = Object.keys(diskStates).sort((a: string, b: string) => Number(a) - Number(b)); let result: {[gameTick:number] : DiskState} = {}; sortedKeys.forEach(gameTick => { if (Number(gameTick) >= fromGameTick) { result[Number(gameTick)] = diskStates[Number(gameTick)]; } }); return result; }, getCurrentAuthority() { return currentAuthorativePlayer; }, IsAuthority(playerId: string) { return currentAuthorativePlayer == playerId; } }
import './App.css'; import $ from 'jquery'; import React from 'react'; class LoginPage extends React.Component{ constructor(props) { super(props) this.state = { inputUserName: "", inputUserPswd: "", errorMsg: "" } this.handleInputChange = this.handleInputChange.bind(this) this.handleOnClickSubmit = this.handleOnClickSubmit.bind(this) } handleInputChange(event){ let target = event.target let name = target.name let value = target.value this.setState({[name]: value}) } handleOnClickSubmit(){ var name = this.state.inputUserName var pswd = this.state.inputUserPswd var user_doc = {name: name, password: pswd} if(name === '' || pswd === ''){ alert("You must enter username and password") }else{ $.ajax({ type: 'POST', url: 'http://localhost:3001/signin', data: user_doc, dataType: 'JSON', xhrFields: { withCredentials: true } }).done(function(response) { if(response.msg === ''){ this.props.handleProcessLogin(false) this.props.handleIsLogin(true) this.setState({showErrorMsg: false}) this.props.handleUserNameChange(name) this.props.handleCartNumChange(response.totalnum) if(this.props.loginFromCart) // only clicking "add to cart" sets it this.props.handleProcessCart(true) }else{ this.setState({errorMsg: response.msg}) } }.bind(this)); } } render(){ return( <div class="loginBox"> <p>{this.state.errorMsg}</p> Username <input type="text" name="inputUserName" value={this.state.inputUserName} onChange={this.handleInputChange} /> <br /> Password <input type="password" name="inputUserPswd" value={this.state.inputUserPswd} onChange={this.handleInputChange} /> <br /> <button onClick={this.handleOnClickSubmit}> Sign in </button> </div> ) } } class UserBar extends React.Component{ constructor(props) { super(props) this.handleOnClickLogin = this.handleOnClickLogin.bind(this) this.handleOnClickLogout = this.handleOnClickLogout.bind(this) this.handleOnClickBarCart = this.handleOnClickBarCart.bind(this) } handleOnClickBarCart(e){ e.preventDefault(); this.props.handleProcessPay(true) this.props.handleProcessCart(true) this.props.handleProcessPaidFlag(false) } handleOnClickLogin(e){ e.preventDefault(); this.props.handleLoginFromCart(false) this.props.handleProcessLogin(true) } handleOnClickLogout(e){ e.preventDefault(); $.ajax({ type: 'GET', url: 'http://localhost:3001/signout', xhrFields: { withCredentials: true } }).done(function(response) { if(response === ''){ // logout: Fig 6 stay the same; Fig 5.7.8, back to initial page this.props.handleIsLogin(false) this.props.handleProcessLogin(false) if(this.props.processCart){ this.props.fetchProductsFromServer("", "") this.props.handleProcessPay(false) this.props.handleProcessCart(false) this.props.handleProcessDetailProd(false) } } }.bind(this)); } render(){ if(this.props.isLogin === false){ return( <div class="userBar"><a href='#' onClick={this.handleOnClickLogin}> Sign in </a></div> ) }else{ return( <div class="userBar"> <div class="cartIcon" onClick={this.handleOnClickBarCart}> <img src="cart.png" width="35" height="23"/> <a href='#'> {this.props.userCartNum} in Cart </a> </div> Hello, <b>{this.props.userName}</b> <a href='#' onClick={this.handleOnClickLogout}> (Sign out)</a> </div> ) } } } class SearchBar extends React.Component{ constructor(props) { super(props) this.state = { categoryOption: "", searchString: "" } this.handleOptionChange = this.handleOptionChange.bind(this) this.handleSearchStrChange = this.handleSearchStrChange.bind(this) this.handleSearchClick = this.handleSearchClick.bind(this) } handleOptionChange(e){ var option = e.target.value this.setState({categoryOption: option}) } handleSearchStrChange(e){ var str = e.target.value this.setState({searchString: str}) } handleSearchClick(){ var category = this.state.categoryOption === "All" ? "" : this.state.categoryOption var searchString = this.state.searchString // back to inital page showing searched products this.props.fetchProductsFromServer(category, searchString) this.props.handleProcessDetailProd(false) this.props.handleProcessCart(false) this.props.handleProcessPay(false) } render(){ return( <div class="searchBar"> <select class="selector" onChange={this.handleOptionChange} > <option value="All">All</option> <option value="Phones">Phones</option> <option value="Tablets">Tablets</option> <option value="Laptops">Laptops</option> </select> <input type="text" placeholder="search a name..." value={this.state.searchString} onChange={this.handleSearchStrChange} /> <div class="searchImg"><img src="search.png" height="28" onClick={this.handleSearchClick}/></div> </div> ) } } class NavBar extends React.Component{ constructor(props) { super(props) this.handleOnclickTitle = this.handleOnclickTitle.bind(this) } handleOnclickTitle(e){ var category = e.target.rel this.props.fetchProductsFromServer(category, "") this.props.handleProcessDetailProd(false) this.props.handleProcessCart(false) this.props.handleProcessPay(false) } render(){ return ( <div class="navBar"> <div class="titleBar"> <a onClick={this.handleOnclickTitle} rel="Phones">Phones </a> <a onClick={this.handleOnclickTitle} rel="Tablets">Tablets </a> <a onClick={this.handleOnclickTitle} rel="Laptops">Laptops</a> </div> <SearchBar fetchProductsFromServer={this.props.fetchProductsFromServer} handleProcessDetailProd={this.props.handleProcessDetailProd} handleProcessCart = {this.props.handleProcessCart} handleProcessPay = {this.props.handleProcessPay}/> <UserBar handleProcessLogin={this.props.handleProcessLogin} isLogin={this.props.isLogin} handleIsLogin = {this.props.handleIsLogin} userName = {this.props.userName} userCartNum = {this.props.userCartNum} handleLoginFromCart = {this.props.handleLoginFromCart} handleProcessCart = {this.props.handleProcessCart} handleProcessPay = {this.props.handleProcessPay} fetchProductsFromServer = {this.props.fetchProductsFromServer} processCart={this.props.processCart} processPay={this.props.processPay} handleProcessDetailProd={this.props.handleProcessDetailProd} handleProcessPaidFlag={this.props.handleProcessPaidFlag}/> </div> ); } } class AddToCart extends React.Component{ constructor(props) { super(props) this.state = { quantity: 1, } this.handleOnClickAddCart = this.handleOnClickAddCart.bind(this) this.handleOnInput = this.handleOnInput.bind(this) } handleOnClickAddCart(e){ e.preventDefault(); if(this.state.quantity !== ''){ var products = [] for(let i = 0; i < this.state.quantity; i++){ products.push(this.props.detailProductObj) } this.props.handleReadyToCart(products) if(this.props.isLogin === false){ this.props.handleProcessLogin(true) this.props.handleLoginFromCart(true) }else{ this.props.handleProcessCart(true) } } } handleOnInput(e){ var value = e.target.value if(value != ''){ // limit number range value = Math.max(Math.min(5, value), 1) // limit integer value = parseInt(value) // natively allow format: 2e0 } this.setState({quantity: value}) } render(){ return ( <div class="addToCart"> <div class="quantityHint">Quantity:</div> <input type="number" min="1" max="5" onInput={this.handleOnInput} value={this.state.quantity} /> <button class="addToCartButton" onClick={this.handleOnClickAddCart}>Add to Cart</button> </div> ); } } class ProductPage extends React.Component{ constructor(props) { super(props) this.handleDetailProductIn = this.handleDetailProductIn.bind(this) this.handleDetailProductOut = this.handleDetailProductOut.bind(this) } handleDetailProductIn(e){ e.preventDefault(); var pid = e.target.dataset.pid $.getJSON(`http://localhost:3001/loadproduct/${pid}`, function(response) { if(response.msg === ''){ var chosenProd = this.props.productsList.filter(prod => prod._id === pid)[0] var chosenProdInfo = { "_id": pid, "name": chosenProd.name, "price": chosenProd.price, "productImage": chosenProd.productImage, "manufacturer": response.manufacturer, "description": response.description } this.props.handleDetailProductObj(chosenProdInfo) this.props.handleProcessDetailProd(true) } }.bind(this)) } handleDetailProductOut(e){ e.preventDefault(); this.props.handleProcessDetailProd(false) this.props.handleDetailProductObj(null) } render(){ // display chosen product if(this.props.processDetailProd){ return( <div class="detailProductPage"> <div class="detailProductContainer"> <div><img src={`http://localhost:3001/${this.props.detailProductObj.productImage}`} height="200"/></div> <div class="detailProductInfo"> <b><p>{this.props.detailProductObj.name}</p></b> <p>${this.props.detailProductObj.price}</p> <p>{this.props.detailProductObj.manufacturer}</p> <p>{this.props.detailProductObj.description}</p> </div> <AddToCart isLogin={this.props.isLogin} handleProcessLogin={this.props.handleProcessLogin} handleProcessCart={this.props.handleProcessCart} handleLoginFromCart={this.props.handleLoginFromCart} detailProductObj={this.props.detailProductObj} handleReadyToCart={this.props.handleReadyToCart}/> </div> <p class="goBack"><a href='#' onClick={this.handleDetailProductOut}> &#60; go back </a></p> </div> ) }else{ // display all products return( <div class="productCards"> { this.props.productsList.map(((product, index) => { return ( <div class="cardItem" data-pid={product._id} onClick={this.handleDetailProductIn}> <img data-pid={product._id} src={`http://localhost:3001/${product.productImage}`} height="130"/> <p data-pid={product._id}>{product.name}</p> <p data-pid={product._id}>${product.price}</p> </div> ) })) } </div> ) } } } class CheckOutPage extends React.Component{ constructor(props){ super(props) this.state = { cartProductsList: [], paidNum: 0, totalPrice: 0, } this.fetchProdsListAndPrice = this.fetchProdsListAndPrice.bind(this) this.updateProdQuantity = this.updateProdQuantity.bind(this) this.deleteProduct = this.deleteProduct.bind(this) this.handleOnInput = this.handleOnInput.bind(this) this.handleOnClickContinue = this.handleOnClickContinue.bind(this) this.handleOnClickPay = this.handleOnClickPay.bind(this) } componentDidMount(){ this.fetchProdsListAndPrice() this.props.handleProcessPaidFlag(false) } // process the corner case that user clicks cart right after paid componentWillReceiveProps (nextProps){ if(nextProps.processPaidFlag === false && this.props.userCartNum == 0 && this.state.cartProductsList.length != 0){ this.fetchProdsListAndPrice() } } fetchProdsListAndPrice(){ $.ajax({ type: 'GET', url: 'http://localhost:3001/loadcart', dataType: 'JSON', xhrFields: { withCredentials: true } }).done(function(response) { if(response.msg === ''){ var totalPrice = 0 var docs = response.prodsList for(let i = 0; i < docs.length; i++){ totalPrice += (docs[i].price * docs[i].quantity) } this.setState({cartProductsList: docs, totalPrice: totalPrice, paidNum: response.totalnum}) } }.bind(this)); } updateProdQuantity(dataUpdate){ $.ajax({ type: 'PUT', url: 'http://localhost:3001/updatecart', data: dataUpdate, dataType: 'JSON', xhrFields: { withCredentials: true }, }).done(function(response){ if(response.msg === ''){ this.fetchProdsListAndPrice() this.props.handleCartNumChange(response.totalnum) } }.bind(this)); } deleteProduct(pid){ $.ajax({ type: 'DELETE', url: 'http://localhost:3001/deletefromcart/' + pid, dataType: 'JSON', xhrFields: { withCredentials: true }, }).done(function(response){ if(response.msg === ''){ this.fetchProdsListAndPrice() this.props.handleCartNumChange(response.totalnum) } }.bind(this)); } handleOnInput(e){ var pid = e.target.name var value = e.target.value if(value != ''){ if(value == 0){ this.deleteProduct(pid) }else{ value = Math.max(Math.min(5, value), 1) value = parseInt(value) var dataUpdate = {"pid": pid, "quantity": value} this.updateProdQuantity(dataUpdate) } }else{ var dataUpdate = {"pid": pid, "quantity": 0} this.updateProdQuantity(dataUpdate) } } handleOnClickContinue(e){ e.preventDefault(); this.props.fetchProductsFromServer("", "") this.props.handleProcessDetailProd(false) this.props.handleProcessPay(false) this.props.handleProcessCart(false) } handleOnClickPay(e){ e.preventDefault(); if(this.state.cartProductsList.length == 0){ this.props.handleProcessPaidFlag(true) }else{ $.ajax({ type: 'GET', url: 'http://localhost:3001/checkout', xhrFields: { withCredentials: true } }).done(function(response) { if(response === ''){ this.props.handleProcessPaidFlag(true) this.props.handleCartNumChange(0) } }.bind(this)); } } render() { if(this.props.processPaidFlag === false){ // process unpaid checkout page var itemMsg = this.props.userCartNum==1 || this.props.userCartNum==0? " item": " items" var header = this.state.cartProductsList.length==0? []: (<div class="cartHeader"> <div class="headerPrice">Price:</div> <div class="headerQuant">Quantity:</div> </div>) return ( <div class="checkoutPage"> <h2> Shopping Cart </h2> {header} { this.state.cartProductsList.map((product)=>{ return( <div class="cartRow"> <div class="cartImg"><img src={`http://localhost:3001/${product.image}`} weight="100" height="130"/></div> <div class="cartName"> {product.name} </div> <div class="cartPrice"> ${product.price} </div> <div class="cartStepper"> <input name={product.pid} type="number" min="0" max="5" onInput={this.handleOnInput} value={product.quantity == 0? '': product.quantity} /> </div> </div> ) }) } <p> Cart subtotal ({this.props.userCartNum}{itemMsg}): ${this.state.totalPrice}</p> <button class="checkButton" onClick={this.handleOnClickPay}>Proceed to check out</button> </div> ) }else{ // process paid checkout page var itemMsg = this.state.paidNum==1 || this.state.paidNum==0? " item": " items" return( <div class="checkoutMsgPage"> <p>&#10004; You have successfully placed order for {this.state.paidNum}{itemMsg}</p> <p>${this.state.totalPrice} paid</p> <p><a href='#' onClick={this.handleOnClickContinue}> continue browsing&#62; </a></p> </div> ) } } } class CartPage extends React.Component{ constructor(props){ super(props) this.handleOnClickCart = this.handleOnClickCart.bind(this) } componentDidMount(){ var numReadyProd = this.props.readyToCart.length if(numReadyProd !== 0){ var putBody = {pid: this.props.readyToCart[0]._id, num: numReadyProd} $.ajax({ type: 'PUT', url: 'http://localhost:3001/addtocart', data: putBody, dataType: 'JSON', xhrFields: { withCredentials: true }, }).done(function(response){ if(response.msg === ''){ this.props.handleCartNumChange(response.totalnum) this.props.handleReadyToCart([]) } }.bind(this)); } } handleOnClickCart(e){ e.preventDefault(); this.props.fetchProductsFromServer("", "") this.props.handleProcessCart(false) this.props.handleProcessDetailProd(false) } render(){ // the only entry is clicking cart in user bar if(this.props.processPay){ return <CheckOutPage userCartNum={this.props.userCartNum} handleCartNumChange={this.props.handleCartNumChange} handleProcessCart={this.props.handleProcessCart} handleProcessPay={this.props.handleProcessPay} handleProcessDetailProd={this.props.handleProcessDetailProd} fetchProductsFromServer={this.props.fetchProductsFromServer} processPaidFlag = {this.props.processPaidFlag} handleProcessPaidFlag={this.props.handleProcessPaidFlag}/> } else{ return( <div class="cartPage"> <div class="addedRow"> <div><img src={`http://localhost:3001/${this.props.detailProductObj.productImage}`} height="200"/></div> <div class="addedHint"> &#10004; Added to Cart </div> </div> <p><a href='#' onClick={this.handleOnClickCart}> continue browsing&#62; </a></p> </div> ) } } } class Shop extends React.Component{ constructor(props) { super(props) this.state = { // used for status productsList: [], isLogin: false, userName: "", userCartNum: -1, readyToCart: [], // used for processing different pages processLogin: false, processCart: false, processPay: false, processDetailProd: false, detailProductObj: null, loginFromCart: false, processPaidFlag: false, } this.fetchProductsFromServer = this.fetchProductsFromServer.bind(this) this.fetchSessionIdFromServer = this.fetchSessionIdFromServer.bind(this) this.handleProcessLogin = this.handleProcessLogin.bind(this) this.handleIsLogin = this.handleIsLogin.bind(this) this.handleUserNameChange = this.handleUserNameChange.bind(this) this.handleCartNumChange = this.handleCartNumChange.bind(this) this.handleProcessCart = this.handleProcessCart.bind(this) this.handleProcessPay = this.handleProcessPay.bind(this) this.handleLoginFromCart = this.handleLoginFromCart.bind(this) this.handleDetailProductObj = this.handleDetailProductObj.bind(this) this.handleProcessDetailProd = this.handleProcessDetailProd.bind(this) this.handleReadyToCart = this.handleReadyToCart.bind(this) this.handleProcessPaidFlag = this.handleProcessPaidFlag.bind(this) } handleProcessPaidFlag(onOff){ this.setState({processPaidFlag: onOff}) } handleReadyToCart(productsList){ this.setState({readyToCart: productsList}) } handleDetailProductObj(obj){ this.setState({detailProductObj: obj}) } handleProcessDetailProd(onOff){ this.setState({processDetailProd: onOff}) } handleProcessLogin(onOff){ this.setState({processLogin: onOff}) } handleIsLogin(onOff){ this.setState({isLogin: onOff}) } handleUserNameChange(name){ this.setState({userName: name}) } handleCartNumChange(num){ this.setState({userCartNum: num}) } handleProcessCart(onOff){ this.setState({processCart: onOff}) } handleProcessPay(onOff){ this.setState({processPay: onOff}) } handleLoginFromCart(onOff){ this.setState({loginFromCart: onOff}) } componentDidMount(){ this.fetchProductsFromServer("", "") this.fetchSessionIdFromServer() } fetchProductsFromServer(category, searchString){ $.getJSON(`http://localhost:3001/loadpage?category=${category}&searchstring=${searchString}`, function(response) { this.setState({"productsList": response.productsList}) }.bind(this) ) } fetchSessionIdFromServer(){ $.ajax({ type: 'GET', url: 'http://localhost:3001/getsessioninfo', xhrFields: { withCredentials: true } }).done(function(response) { if(response !== ''){ this.handleUserNameChange(response.username) this.handleCartNumChange(response.totalnum) this.handleIsLogin(true) } }.bind(this)); } render(){ const navBar = ( <NavBar fetchProductsFromServer={this.fetchProductsFromServer} handleProcessLogin={this.handleProcessLogin} isLogin={this.state.isLogin} handleIsLogin = {this.handleIsLogin} userName = {this.state.userName} userCartNum = {this.state.userCartNum} handleLoginFromCart = {this.handleLoginFromCart} handleProcessCart = {this.handleProcessCart} handleProcessPay = {this.handleProcessPay} processCart={this.state.processCart} processPay={this.state.processPay} handleProcessDetailProd={this.handleProcessDetailProd} handleProcessPaidFlag={this.handleProcessPaidFlag}/> ) if(this.state.processLogin){ // process login page return <LoginPage handleProcessLogin={this.handleProcessLogin} handleIsLogin = {this.handleIsLogin} handleUserNameChange = {this.handleUserNameChange} handleCartNumChange = {this.handleCartNumChange} loginFromCart = {this.state.loginFromCart} handleProcessCart = {this.handleProcessCart}/> }else if(this.state.processCart){ // process cart page, must have login permission return( <div> {navBar} <CartPage readyToCart={this.state.readyToCart} handleReadyToCart={this.handleReadyToCart} userCartNum={this.state.userCartNum} handleCartNumChange={this.handleCartNumChange} handleProcessCart={this.handleProcessCart} handleProcessDetailProd={this.handleProcessDetailProd} handleProcessPay={this.handleProcessPay} processPay={this.state.processPay} fetchProductsFromServer={this.fetchProductsFromServer} detailProductObj={this.state.detailProductObj} processPaidFlag = {this.state.processPaidFlag} handleProcessPaidFlag={this.handleProcessPaidFlag}/> </div> ) } else{ // process products page, non-login permission return( <div> {navBar} <ProductPage productsList={this.state.productsList} isLogin={this.state.isLogin} handleProcessLogin={this.handleProcessLogin} handleProcessCart={this.handleProcessCart} handleLoginFromCart={this.handleLoginFromCart} detailProductObj={this.state.detailProductObj} processDetailProd={this.state.processDetailProd} handleDetailProductObj={this.handleDetailProductObj} handleProcessDetailProd={this.handleProcessDetailProd} handleReadyToCart={this.handleReadyToCart}/> </div> ) } } } export default Shop;
import {TouchableOpacity, TouchableOpacityProps, Text} from 'react-native'; import {moderateScale, verticalScale} from 'react-native-size-matters'; interface LSButtonProps extends TouchableOpacityProps { label?: string; isDisabled?: boolean; width?: any; backgroundColor?: string; } const Button = (props: LSButtonProps) => { const {backgroundColor = '#00b0b0'} = props; return ( <TouchableOpacity delayPressIn={0} onPress={props.onPress} style={{ padding: 15, borderRadius: 10, backgroundColor: props.isDisabled ? '#D9DBE0' : backgroundColor, justifyContent: 'center', borderColor: props.isDisabled ? '#D9DBE0' : backgroundColor, alignItems: 'center', width: props.width, }} disabled={props.isDisabled}> <Text style={[ { fontSize: moderateScale(14), lineHeight: verticalScale(18), }, {color: '#F9FDFE'}, ]}> {props.label} </Text> </TouchableOpacity> ); }; export default Button;
import React, {FC} from 'react'; import './reviews.scss' import {Link} from "react-router-dom"; import {useAppSelector} from "../../../../Store/store"; import {ResultsReviewsType} from "../../../../Store/tmdbService/@types"; export type ReviewsType = { reviews: ResultsReviewsType[] | undefined, } export const Reviews: FC<ReviewsType> = ({reviews}) => { const {base_url, avatarSize} = useAppSelector((state) => state.config) return ( <div className='reviews'> {reviews ?.map((review) => ( <div key={review.id} className='reviews-block'> <div className='reviews-icon'> {review.author_details.avatar_path ? <img src={!review.author_details.avatar_path .match(/https/i) ? `${base_url}${avatarSize}${review.author_details.avatar_path}` : review.author_details.avatar_path ?.substring(1) } alt="icon" /> : <div className='reviews-icon-alt'> {review.author .substring(0, 1) .toUpperCase() } </div> } </div> <div className='reviews-text'> <div className='reviews-user'> <h3>{review.author}</h3> <span> {review.created_at .match(/\d{4}.\d{2}.\d{2}/) } </span> </div> <div className='reviews-text'> <p>{review.content}</p> </div> <div className='reviews-link'> <Link to={review.url}>Link to review site TMDB</Link> </div> </div> </div> )) } </div> ); };
import 'package:flutter/material.dart'; import '../../../../auth/presentation/providers/auth_state_provider.dart'; import '../../../../core/presentation/helpers/localization_helper.dart'; import '../../../../core/presentation/styles/styles.dart'; import '../../../../core/presentation/utils/riverpod_framework.dart'; import '../../../../core/presentation/widgets/custom_elevated_button.dart'; import '../../../home/domain/orders_service.dart'; import '../../../home/domain/update_delivery_status.dart'; import '../../../home/domain/value_objects.dart'; import '../../../home/presentation/providers/selected_order_provider.dart'; import '../../../home/presentation/widgets/order_dialogs.dart'; import '../providers/is_arrived_target_location_provider.dart'; import '../providers/map_confirm_order_provider.dart'; class MapConfirmButtonComponent extends ConsumerWidget { const MapConfirmButtonComponent({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final arrivedTargetLocation = ref.watch(isArrivedTargetLocationProvider); Future<void> confirmOrder() async { final authority = ref.read(ordersServiceProvider).orderAuthority( userId: ref.read(currentUserProvider).id, orderDeliveryId: ref.read(selectedOrderProvider).toNullable()?.id, ); switch (authority) { case (canProceed: true, isLoading: true): return OrderDialogs.confirmChoiceDialog( context, tr(context).doYouWantToConfirmTheOrder, ).then((confirmChoice) { if (confirmChoice) { final order = ref.read(selectedOrderProvider); order.match( () {}, (order) { final params = UpdateDeliveryStatus( orderId: order.id, deliveryStatus: DeliveryStatus.delivered, ); ref.read(mapConfirmOrderStatusProvider.notifier).confirmOrder(params); }, ); } }); case (canProceed: false, isLoading: _): OrderDialogs.showCanNotProceedDialog(context); case _: return; } } return arrivedTargetLocation ? Positioned( bottom: 36, left: 36, child: CustomElevatedButton( padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 88), buttonColor: Theme.of(context).colorScheme.primary, elevation: 2, onPressed: confirmOrder, child: Text( tr(context).confirm, style: TextStyles.coloredElevatedButton(context).copyWith(fontSize: Sizes.font18), ), ), ) : const SizedBox(); } }
import { Block } from '@ethereumjs/block' import { TransactionFactory } from '@ethereumjs/tx' import { bytesToPrefixedHexString } from '@ethereumjs/util' import * as tape from 'tape' import { INTERNAL_ERROR, INVALID_PARAMS } from '../../../src/rpc/error-code' import genesisJSON = require('../../testdata/geth-genesis/debug.json') import { baseRequest, baseSetup, dummy, params, runBlockWithTxs, setupChain } from '../helpers' import { checkError } from '../util' const method = 'debug_traceTransaction' tape(`${method}: call with invalid configuration`, async (t) => { const { server } = baseSetup({ engine: false, includeVM: true }) const req = params(method, ['0xabcd', {}]) const expectRes = checkError(t, INTERNAL_ERROR, 'missing receiptsManager') await baseRequest(t, server, req, 200, expectRes) }) tape(`${method}: call with invalid parameters`, async (t) => { const { server } = await setupChain(genesisJSON, 'post-merge') let req = params(method, ['abcd', {}]) let expectRes = checkError(t, INVALID_PARAMS, 'hex string without 0x prefix') await baseRequest(t, server, req, 200, expectRes, false) req = params(method, ['0xabcd', { enableReturnData: true }]) expectRes = checkError(t, INVALID_PARAMS, 'enabling return data not implemented') await baseRequest(t, server, req, 200, expectRes, false) req = params(method, ['0xabcd', { tracerConfig: { some: 'value' } }]) expectRes = checkError( t, INVALID_PARAMS, 'custom tracers and tracer configurations are not implemented' ) await baseRequest(t, server, req, 200, expectRes, false) req = params(method, ['0xabcd', { tracer: 'someTracer' }]) expectRes = checkError(t, INVALID_PARAMS, 'custom tracers not implemented') await baseRequest(t, server, req, 200, expectRes, false) req = params(method, ['0xabcd', { timeout: 1000 }]) expectRes = checkError(t, INVALID_PARAMS, 'custom tracer timeouts not implemented') await baseRequest(t, server, req, 200, expectRes, false) }) tape(`${method}: call with valid parameters`, async (t) => { const { chain, common, execution, server } = await setupChain(genesisJSON, 'post-merge', { txLookupLimit: 0, }) // construct block with tx const tx = TransactionFactory.fromTxData( { type: 0x2, gasLimit: 0xfffff, maxFeePerGas: 10, maxPriorityFeePerGas: 1, value: 10000, data: '0x60AA', }, { common, freeze: false } ).sign(dummy.privKey) tx.getSenderAddress = () => { return dummy.addr } const block = Block.fromBlockData({}, { common }) block.transactions[0] = tx await runBlockWithTxs(chain, execution, [tx], true) const req = params(method, [bytesToPrefixedHexString(tx.hash()), {}]) const expectRes = (res: any) => { t.equal(res.body.result.structLogs[0].op, 'PUSH1', 'produced a correct trace') } await baseRequest(t, server, req, 200, expectRes, true) }) tape(`${method}: call with reverting code`, async (t) => { const { chain, common, execution, server } = await setupChain(genesisJSON, 'post-merge', { txLookupLimit: 0, }) // construct block with tx const tx = TransactionFactory.fromTxData( { type: 0x2, gasLimit: 0xfffff, maxFeePerGas: 10, maxPriorityFeePerGas: 1, value: 10000, data: '0x560FAA', }, { common, freeze: false } ).sign(dummy.privKey) tx.getSenderAddress = () => { return dummy.addr } const block = Block.fromBlockData({}, { common }) block.transactions[0] = tx await runBlockWithTxs(chain, execution, [tx], true) const req = params(method, [bytesToPrefixedHexString(tx.hash()), {}]) const expectRes = (res: any) => { t.equal(res.body.result.failed, true, 'returns error result with reverting code') } await baseRequest(t, server, req, 200, expectRes, true) }) tape(`${method}: call with memory enabled`, async (t) => { const { chain, common, execution, server } = await setupChain(genesisJSON, 'post-merge', { txLookupLimit: 0, }) // construct block with tx const tx = TransactionFactory.fromTxData( { type: 0x2, gasLimit: 0xfffff, maxFeePerGas: 10, maxPriorityFeePerGas: 1, value: 10000, data: '0x604260005260206000F3', }, { common, freeze: false } ).sign(dummy.privKey) tx.getSenderAddress = () => { return dummy.addr } const block = Block.fromBlockData({}, { common }) block.transactions[0] = tx await runBlockWithTxs(chain, execution, [tx], true) const req = params(method, [bytesToPrefixedHexString(tx.hash()), { enableMemory: true }]) const expectRes = (res: any) => { t.equal( res.body.result.structLogs[5].memory[0], '0x0000000000000000000000000000000000000000000000000000000000000042', 'produced a trace with correct memory value returned' ) } await baseRequest(t, server, req, 200, expectRes, true) }) tape(`${method}: call with stack disabled`, async (t) => { const { chain, common, execution, server } = await setupChain(genesisJSON, 'post-merge', { txLookupLimit: 0, }) // construct block with tx const tx = TransactionFactory.fromTxData( { type: 0x2, gasLimit: 0xfffff, maxFeePerGas: 10, maxPriorityFeePerGas: 1, value: 10000, data: '0x600F6000', }, { common, freeze: false } ).sign(dummy.privKey) tx.getSenderAddress = () => { return dummy.addr } const block = Block.fromBlockData({}, { common }) block.transactions[0] = tx await runBlockWithTxs(chain, execution, [tx], true) const req = params(method, [bytesToPrefixedHexString(tx.hash()), { disableStack: true }]) const expectRes = (res: any) => { t.ok(res.body.result.structLogs[1].stack === undefined, 'returns no stack with trace') } await baseRequest(t, server, req, 200, expectRes, true) })
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { environment } from 'src/environments/environment'; import { Conta } from 'src/models/models'; @Injectable({ providedIn: 'root' }) export class ContaService { private API = environment.API constructor(private http: HttpClient) { } public get_all(): Observable<Array<Conta>> { return this.http.get<Array<Conta>>(`${this.API}conta`) } public get(id: number): Observable<Conta>{ return this.http.get<Conta>(`${this.API}conta/${id}`) } public post(conta: Conta): Observable<Conta>{ return this.http.post<Conta>(`${this.API}conta`, conta) } public put(conta: Conta): Observable<void>{ return this.http.put<void>(`${this.API}conta`, conta) } public delete(id: number): Observable<void>{ return this.http.delete<void>(`${this.API}conta/${id}`) } }
import React, { useEffect, useMemo } from 'react'; import AICard from '~/components/AICard'; import UserInfo from './UserInfo'; import CardInfo from './CardInfo'; import useAICard from '~/helpers/hooks/useAICard'; import moment from 'moment'; import { useNavigate } from 'react-router-dom'; import { css } from '@emotion/css'; import { Color, mobileMaxWidth } from '~/constants/css'; export default function SummonActivity({ card, isLastActivity, myId, onReceiveNewActivity, onSetScrollToBottom }: { card: any; isLastActivity: boolean; myId: number; onReceiveNewActivity: () => void; onSetScrollToBottom: () => void; }) { const navigate = useNavigate(); const displayedTime = useMemo( () => moment.unix(card.timeStamp).format('hh:mm a'), [card.timeStamp] ); const displayedDate = useMemo( () => moment.unix(card.timeStamp).format('MMM D'), [card.timeStamp] ); useEffect(() => { if (isLastActivity && !userisAdmin) { onReceiveNewActivity(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const userisAdmin = myId === card.creator.id; useEffect(() => { if (isLastActivity && userisAdmin) { onSetScrollToBottom(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const { promptText } = useAICard(card); return ( <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', height: '100%' }} > <div style={{ width: '30%', display: 'flex', flexDirection: 'column', alignItems: 'flex-start', paddingLeft: '1rem' }} > <UserInfo style={{ marginTop: '3rem' }} user={card.creator} /> <CardInfo quality={card.quality} style={{ marginTop: '3rem' }} /> <div className={css` font-size: 1.2rem; margin-top: 0.5rem; color: ${Color.darkGray()}; @media (max-width: ${mobileMaxWidth}) { font-size: 0.8rem; } `} > at {displayedTime}, {displayedDate} </div> </div> <div className={css` width: 35rem; @media (max-width: ${mobileMaxWidth}) { width: 15rem; } `} > <AICard card={card} onClick={() => navigate(`./?cardId=${card.id}`)} /> </div> <div style={{ width: '35%', height: '100%', padding: '1rem', display: 'flex', flexDirection: 'column', justifyContent: 'center' }} > <div style={{ width: '100%', textAlign: 'center', fontWeight: 'bold' }} className={css` font-size: 1.6rem; @media (max-width: ${mobileMaxWidth}) { font-size: 1rem; } `} > #{card.id} </div> <div className={css` text-align: center; font-size: 1.6rem; padding: 5rem 0 6rem 1rem; @media (max-width: ${mobileMaxWidth}) { font-size: 1.1rem; } `} > <span style={{ fontFamily: 'Roboto Mono, monospace' }} dangerouslySetInnerHTML={{ __html: `"${promptText}"` }} /> </div> <div className={css` text-align: center; font-size: 1.2rem; font-family: helvetica, sans-serif; text-transform: capitalize; font-weight: bold; color: ${Color.darkerGray()}; @media (max-width: ${mobileMaxWidth}) { font-size: 1rem; } `} > {card.style} </div> </div> </div> ); }
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-primary"> <div class="container"> <a class="navbar-brand" routerLink="/">Dating app</a> <ul class="navbar-nav me-auto mb-2 mb-md-0" > <ng-container *ngIf="accountService.currentUser$| async"> <li class="nav-item"> <a class="nav-link active" routerLink="/members" routerLinkActive="active">Matches</a> </li> <li class="nav-item"> <a class="nav-link" routerLink="/lists" routerLinkActive="active">Lists</a> </li> <li class="nav-item"> <a class="nav-link" routerLink="/messages" routerLinkActive="active">Messages</a> </li> </ng-container> <li class="nav-item"> <a class="nav-link" routerLink="/errors" routerLinkActive="active">Errors</a> </li> </ul> <div dropdown class="dropdown" *ngIf="(accountService.currentUser$| async) as user"> <a dropdownToggle class="dropdown-toggle text-white text-decoration-none">Welcome {{user.username | titlecase}}</a> <div *dropdownMenu class="dropdown-menu"> <a class="dropdown-item">Edit profile</a> <a class="dropdown-item" (click)="logout()">Logout</a> </div> </div> <form class="d-flex" #loginForm="ngForm" (ngSubmit)="login()" *ngIf="!(accountService.currentUser$| async)" autocomplete="off"> <input name="username" [(ngModel)]="model.username" class="form-control me-2" type="text" placeholder="Username"> <input name="password" [(ngModel)]="model.password" class="form-control me-2" type="password" placeholder="Password"> <button class="btn btn-success" type="submit">Login</button> </form> </div> </nav>