text
stringlengths 184
4.48M
|
---|
from django.urls import path
from django.views.decorators.cache import cache_page
from catalog.views import ProductListView, ContactDetailView, ProductDetailView, ProductCreateView, ProductUpdateView, \
ProductDeleteView
app_name = 'catalog'
urlpatterns = [
path('', ProductListView.as_view(), name='product_list'),
path('contacts/', ContactDetailView.as_view(), name='contacts'),
path('product/create/', ProductCreateView.as_view(), name='product_create'),
path('product/<str:name>/', cache_page(60)(ProductDetailView.as_view()), name='product_detail'),
path('product/<str:name>/update/', ProductUpdateView.as_view(), name='product_update'),
path('product/<str:name>/delete/', ProductDeleteView.as_view(), name='product_delete'),
]
|
# THIS SCRIPT IS USED FOR THE STATISTICAL COMPUTING OF THE FORECAST FOR THE SETPOINTS
# BASED UPON THE HISTORICAL DATA
args <- commandArgs()
headFilePath <- args[2]
tailFilePath <- args[3]
outputFilePath <- args[4]
library("TTR")
library("forecast")
## The script will need the L2 Sp for the Head and Tail, as well as
## the corresponding value of the grade.
# SCANNING THE PREVIOUS VALUES OF HEAD AND TAIL SETPOINTS
gd_h <- scan(headFilePath, skip=1);
gd_t <- scan(tailFilePath, skip=1);
# FORMULATION OF THE TIME SERIES
gd_hts <- ts(gd_h);
gd_tts <- ts(gd_t);
#PLOTTING THE TIME SERIES CHARTS AND SAVING IT
png(file = "C:/Users/Dewal Agarwal/Desktop/Intern Project/CropShearSetPoint/Resources/Dynamic Plots/gd_hts_plot.jpg");
plot(gd_hts, type="o", col= "black", main = "Time Series Head");
dev.off();
png(file = "C:/Users/Dewal Agarwal/Desktop/Intern Project/CropShearSetPoint/Resources/Dynamic Plots/gd_tts_plot.jpg");
plot(gd_tts, type="o", col= "black", main = "Time Series Tail");
dev.off();
# #[OP] CALCULATION OF MOVING AVERAGES
# gd_htsSMA5 <- SMA(gd_hts, n=5);
# gd_ttsSMA5 <- SMA(gd_tts, n=5);
# Smoothing using Holt-Winters function (SES & DES)
# HEAD & TAIL SES smoothing
# gd_hSES <- HoltWinters(gd_hts, beta = FALSE, gamma = FALSE)
# gd_tSES <- HoltWinters(gd_tts, beta = FALSE, gamma = FALSE)
# HEAD & TAIL DES smoothing
gd_hDES <- HoltWinters(gd_hts, gamma = FALSE, l.start = gd_h[1], b.start = gd_h[2]-gd_h[1]);
gd_tDES <- HoltWinters(gd_tts, gamma = FALSE, l.start = gd_t[1], b.start = gd_t[2]-gd_t[1]);
# [op] Printing the value of the smooth parameters.
# print(gd_hDES);
# print(gd_tDES);
# PLOTTING INPUT V/S THE FITTED VALUES
# This part is working fine
png(file = "C:/Users/Dewal Agarwal/Desktop/Intern Project/CropShearSetPoint/Resources/Dynamic Plots/gd_hDES_plot.jpg");
plot(gd_hDES, type="o",xlab= "Bars", main = "Observed & Fitted Head");
dev.off();
png(file = "C:/Users/Dewal Agarwal/Desktop/Intern Project/CropShearSetPoint/Resources/Dynamic Plots/gd_tDES_plot.jpg");
plot(gd_tDES, type="o",xlab= "Bars", main = "Observed & Fitted Tail");
dev.off();
# FORECASTING THE NEXT 'h' VALUES FOR THE HEAD AND THE TAIL
gd_hDESfc = forecast.HoltWinters(gd_hDES, h=1);
gd_tDESfc = forecast.HoltWinters(gd_tDES, h=1);
# [op] Print the forecast for the head and tail
# print("The Head setpoint is");
# print(gd_hDESfc)
# print("The Tail setpoint is");
# print(gd_tDESfc)
forecastH <- as.numeric(gd_tDESfc$mean)
forecastT <- as.numeric(gd_hDESfc$mean)
# OUTPUTTING THE FORECASTED VALUE IN THE TEXT FILE
sink(outputFilePath)
print(forecastH)
print(forecastT)
sink()
## The output is read from the text file by the C# code
# print("The head setpoint value is:")
# print(forecastH)
# print("The tail setpoint value is:")
# print(forecastT)
## Functions for adding the bias.
#Final_SPH <- function(L2Hinput)
#{ sp = (forecastH + L2Hinput)/2
# There should be a provision for changing the entry from the exixting data base.
#}
#print("Displaying the final setpoint with offset");
#print(Final_SPH(500))
##Final_SPT <- function(L2Tinput)
#{ sp = (forecastT + L2Tinput)/2
# There should be a provision for changing the entry from the exixting data base.
#}
#print("Displaying the final setpoint with offset");
#print(Final_SPT(500))
|
using AutoMapper;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using ShippingSystem.DataAccess.Repository.IRepositories.IBaseRepository;
using ShippingSystem.Model.BaseModel;
using ShippingSystem.Model.DtoModel;
using ShippingSystem.Service.AuthService;
using ShippingSystem.Service.Exceptions.RequestExceptions;
using ShippingSystem.Utility;
using System.Net;
namespace ShippingSystemApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CourierController : ControllerBase
{
private readonly IAuthService _authservice;
private readonly IUnitOfWork _unitOfWork;
private readonly IHttpContextAccessor _httpContextAccessor;
protected readonly BaseResponse _response;
private readonly IMapper _mapper;
public CourierController(IUnitOfWork unitOfWork, IHttpContextAccessor httpContextAccessor, IMapper mapper, IAuthService authService)
{
_authservice = authService;
_unitOfWork = unitOfWork;
_httpContextAccessor = httpContextAccessor;
_mapper = mapper;
this._response = new();
}
[HttpPost("CourierRegister")]
public async Task<IActionResult> CourierRegisterAsync([FromBody] CourierCreateDto model)
{
var courier = _mapper.Map<RegisterDto>(model);
var result = await _authservice.RegisterAsync(courier);
return Ok(result);
}
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult<BaseResponse>> GetCouriers()
{
var couriers = await _unitOfWork.Couriers.GetAllAsync();
_response.Result = _mapper.Map<List<CourierDto>>(couriers);
_response.Message = "Get Couriers Success";
return Ok(_response);
}
[HttpGet]
[Route("{Id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult<BaseResponse>> GetCourier([FromRoute] string Id)
{
var client = await _unitOfWork.Couriers.GetFirstOrDefualtAsync(u => u.Id == Id);
if (client == null)
throw new NotFoundException("this is Courier not found");
_response.Result = _mapper.Map<CourierDto>(client);
_response.Message = "Get Courier Success";
return Ok(_response);
}
[HttpPut]
[Route("{Id}")]
public async Task<ActionResult<BaseResponse>> UpdateCourier([FromRoute] string Id, CourierUpdateDto courierupdate)
{
var courierupdated = await _unitOfWork.Couriers.UpdateCourierAsync(Id, courierupdate);
_response.Result = courierupdated;
_response.Message = "Courier Update Success";
return Ok(_response);
}
[HttpDelete]
[Route("{Id}")]
public async Task<ActionResult<BaseResponse>> DeleteCourier([FromRoute] string Id)
{
var courierexit = await _unitOfWork.Couriers.GetFirstOrDefualtAsync(u => u.Id == Id);
if (courierexit == null)
throw new NotFoundException("this is Courier not found");
await _unitOfWork.Couriers.removeAsync(courierexit);
_unitOfWork.SaveAsync();
_response.Message = "Client Update Success";
return Ok(_response);
}
}
}
|
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using PGenerator.Model.Request;
using PGenerator.Model.Response;
namespace PGenerator.Model.Service.UserManager;
public class UserService(UserManager<UserInformation> userManager) : IUserService
{
public async Task<IList<UserInformation>> ListUsers()
{
try
{
return await userManager.Users.ToListAsync();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public async Task<PublicResponse> Registration(RegistrationRequest request)
{
try
{
var validationResults = new List<ValidationResult>();
if (!Validator.TryValidateObject(request, new ValidationContext(request), validationResults, true))
{
var errorMessages = validationResults.Select(vr => vr.ErrorMessage);
foreach (var errorMessage in errorMessages)
{
switch (errorMessage)
{
case "The field Password must be a string or array type with a minimum length of '8'.":
return new PublicResponse(false, "Password length minimum 8.");
case @"The field Password must match the regular expression '^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*\W).+$'.":
return new PublicResponse(false, "Password should contain number & symbol & uppercase letters.");
case "The Email field is not a valid e-mail address.":
return new PublicResponse(false, "Not a valid e-mail address.");
}
}
}
if (userManager.Users.Any(user => user.Email == request.Email))
{
return new PublicResponse(false, "Email already in use.");
}
if (userManager.Users.Any(user => user.UserName == request.UserName))
{
return new PublicResponse(false, "Username already in use.");
}
var user = new UserInformation
{
UserName = request.UserName,
Email = request.Email
};
await userManager.CreateAsync(user, request.Password!);
return new PublicResponse(true, "Registration successful.");
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public async Task<LoginResponse> Login(LoginRequest request)
{
try
{
var existingUser = await userManager.FindByNameAsync(request.UserName);
if (existingUser == null)
{
return new LoginResponse(null, "Invalid username or password.", false);
}
var isPasswordValid = await userManager.CheckPasswordAsync(existingUser!, request.Password);
if (!isPasswordValid)
{
return new LoginResponse(null, "Invalid username or password.", false);
}
return new LoginResponse(existingUser, "", true);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public async Task<PublicResponse> ChangePassword(string userId, string oldPassword, string newPassword)
{
try
{
var existingUser = await userManager.FindByIdAsync(userId);
if (existingUser == null)
{
return new PublicResponse(false, "User not exist");
}
await userManager.ChangePasswordAsync(existingUser, oldPassword, newPassword);
return new PublicResponse(true, "Successful update.");
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public async Task<PublicResponse> DeleteUser(string userId)
{
try
{
var existingUser = await userManager.FindByIdAsync(userId);
if (existingUser == null)
{
return new PublicResponse(false, "User not exist");
}
await userManager.DeleteAsync(existingUser);
return new PublicResponse(true, "Successful delete.");
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
|
import React from 'react';
interface InputProps {
id: string;
onChange: any;
value: string;
label: string;
type?: string;
}
export const Input: React.FC<InputProps> = ({id , onChange, value, label , type}) => {
return(
<div className="relative">
<input
id={id}
onChange={onChange}
type={type}
value={value}
className="
block
rounded-md
px-6
pt-6
pb-1
w-full
text-md
text-white
bg-zinc-900
appearance-none
focus:outline-none
focus:ring-0
peer
"
placeholder=" "
/>
<label
htmlFor={id}
className="
absolute
text-md
text-zinc-400
duration-150
transform
-translate-y-3
scale-75
top-4
z-10
origin-[0]
left-6
peer-placeholder-shown:scale-100
peer-placeholder-shown:translate-y-0
peer-focus:scale-75
peer-focus: -translate-y-3
"
>
{label}
</label>
</div>
)
}
|
import { Schema, Document, Model, model } from 'mongoose';
// Interface to model User
export interface IUser extends Document {
username: string,
email: string,
password: string,
registeredAt?: Date
}
const UserSchema: Schema = new Schema({
username: {
type: String,
required: true,
},
email: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
registeredAt: {
type: Date,
default: Date.now
}
});
const User: Model<IUser> = model('User', UserSchema);
export default User;
|
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Bootstrap Clone</title>
@vite('resources/sass/app.scss')
</head>
<body>
<!-- Navbar -->
<nav class="navbar fixed-top navbar-expand-lg bg-purple" data-bs-theme="dark">
<!-- Container -->
<div class="container py-2 px-4">
<!-- Navbar Brand -->
<a href="{{ route('home') }}" class="navbar-brand mb-0 h1">
<img class="img-fluid"
src="{{ Vite::asset('resources/images/logo-white.svg') }}"
alt="logo"
style="width: 40px"
/>
</a>
<!-- Navbar Toggler -->
<button type="button"
class="navbar-toggler"
data-bs-toggle="offcanvas"
data-bs-target="#offcanvasNavbar"
>
<span class="navbar-toggler-icon"></span>
</button>
<!-- Offcanvas -->
<div class="offcanvas offcanvas-end bg-purple" id="offcanvasNavbar">
<!-- Offcanvas Header -->
<div class="offcanvas-header pb-0 px-4">
<h5 class="offcanvas-title text-white" id="offcanvasNavbarLabel">
Bootstrap
</h5>
<button
type="button"
class="btn-close"
data-bs-dismiss="offcanvas"
aria-label="Close"
></button>
</div>
<!-- Offcanvas Body -->
<div class="offcanvas-body pt-0 px-4">
<hr class="d-md-none text-white-50"/>
<!-- Horizontal Line -->
<!-- Top Menu -->
<ul class="navbar-nav flex-row flex-wrap">
<li class="nav-item col-6 col-md-auto">
<a href="{{ url('https://getbootstrap.com/docs/5.3/getting-started/introduction/') }}" class="nav-link active">Docs</a>
</li>
<li class="nav-item col-6 col-md-auto">
<a href="{{ url('https://getbootstrap.com/docs/5.3/examples/') }}" class="nav-link">Examples</a>
</li>
<li class="nav-item col-6 col-md-auto">
<a href="{{ url('https://icons.getbootstrap.com/') }}" class="nav-link">Icons</a>
</li>
<li class="nav-item col-6 col-md-auto">
<a href="{{ url('https://themes.getbootstrap.com/') }}" class="nav-link">Themes</a>
</li>
<li class="nav-item col-6 col-md-auto">
<a href="{{ url('https://blog.getbootstrap.com/') }}" class="nav-link">Blog</a>
</li>
</ul>
<hr class="d-md-none text-white-50"/>
<!-- Horizontal Line -->
<!-- Social Media -->
<ul class="navbar-nav flex-row flex-wrap ms-md-auto">
<li class="nav-item col-6 col-md-auto">
<a href="#" class="nav-link active">
<i class="bi-github"></i
><small class="ms-2 d-md-none">Github</small>
</a>
</li>
<li class="nav-item col-6 col-md-auto">
<a href="#" class="nav-link active">
<i class="bi-twitter"></i
><small class="ms-2 d-md-none">Twitter</small>
</a>
</li>
<li class="nav-item col-6 col-md-auto">
<a href="#" class="nav-link active">
<i class="bi-slack"></i
><small class="ms-2 d-md-none">Slack</small>
</a>
</li>
<li class="nav-item col-12 col-lg-auto">
<div class="vr d-none d-lg-flex h-100 mx-lg-2 text-white"></div>
<hr class="d-lg-none my-2 text-white-50"/>
</li>
<li class="nav-item">
<!-- Dropdown -->
<div class="dropdown" data-bs-theme="light">
<button
type="button"
class="btn nav-link text-white dropdown-toggle"
data-bs-toggle="dropdown"
aria-expanded="false"
>
<span class="d-lg-none">Bootstrap</span> v5.3
</button>
<ul class="dropdown-menu dropdown-menu-end">
<li><h6 class="dropdown-header">v5 releases</h6></li>
<li>
<button
class="dropdown-item active bg-purple"
type="button"
>
<small>Latest (5.3.x) <i class="bi-check"></i></small>
</button>
</li>
<li>
<button class="dropdown-item" type="button">
<small>v5.2.3</small>
</button>
</li>
<li>
<button class="dropdown-item" type="button">
<small>v5.1.3</small>
</button>
</li>
<li>
<button class="dropdown-item" type="button">
<small>v5.0.2</small>
</button>
</li>
<li>
<hr class="dropdown-divider"/>
</li>
<li><h6 class="dropdown-header">Previous releases</h6></li>
<li>
<button class="dropdown-item" type="button">
<small>v4.6.x</small>
</button>
</li>
<li>
<button class="dropdown-item" type="button">
<small>v3.4.1</small>
</button>
</li>
<li>
<button class="dropdown-item" type="button">
<small>v2.3.2</small>
</button>
</li>
<li>
<hr class="dropdown-divider"/>
</li>
<li>
<button class="dropdown-item" type="button">
<small>All versions</small>
</button>
</li>
</ul>
</div>
</li>
<li class="nav-item col-12 col-lg-auto">
<div class="vr d-none d-lg-flex h-100 mx-lg-2 text-white"></div>
<hr class="d-lg-none my-2 text-white-50"/>
</li>
<li class="nav-item">
<!-- Dropdown -->
<div class="dropdown" data-bs-theme="light">
<button
type="button"
class="btn nav-link text-white dropdown-toggle"
data-bs-toggle="dropdown"
aria-expanded="false"
>
<i class="bi-brightness-high-fill"></i
><span class="d-lg-none">Toggle theme</span>
</button>
<ul class="dropdown-menu dropdown-menu-end">
<li>
<button
class="dropdown-item active bg-purple"
type="button"
>
<small
><i class="bi-brightness-high-fill me-2"></i
>Light</small
>
</button>
</li>
<li>
<button class="dropdown-item" type="button">
<small
><i class="bi-moon-stars-fill me-2"></i>Dark</small
>
</button>
</li>
<li>
<button class="dropdown-item" type="button">
<small><i class="bi-circle-half me-2"></i>Auto</small>
</button>
</li>
</ul>
</div>
</li>
</ul>
</div>
</div>
</div>
</nav>
<!-- Main -->
<div class="bg-light mt-5" id="main">
<!-- Container -->
<div class="container py-5 px-4">
<div class="row">
<div class="col-md-5 order-md-2">
<img
class="img-fluid"
src="{{ Vite::asset('resources/images/main.svg') }}"
alt="main logo"
/>
</div>
<div class="col-md-7 order-md-1">
<h1 class="mt-4 display-3">
Build fast, responsive sites with Bootstrap
</h1>
<p class="fs-5 mt-3">
Quickly design and customize responsive mobile-first sites with
Bootstrap, the world's most popular front-end open source toolkit,
featuring Sass variables and mixins, responsive grid system,
extensive prebuilt components, and powerful JavaScript plugins.
</p>
<div class="row">
<div class="d-flex flex-column flex-md-row">
<button
type="button"
class="btn bg-purple text-white btn-lg mb-3 me-md-3 px-4 py-3"
>
Get Started
</button>
<button
type="button"
class="btn btn-outline-dark btn-lg mb-3 px-4 py-3"
>
Download
</button>
</div>
</div>
<div class="text-muted">
Currently <strong>v5.3.0-alpha2.</strong> •
<a href="#">v4.6.x docs</a> • <a href="#">All releases</a>
</div>
</div>
</div>
</div>
</div>
<!-- Bootstrap Icons - -->
<div id="bs-icons">
<!-- Container -->
<div class="container py-5 px-4">
<div class="row">
<div class="col-lg-6">
<div class="mb-3">
<i
class="bi bi-subtract fs-2 bg-warning py-2 px-3 rounded-3 text-white"
></i>
</div>
<h2 class="display-5 mb-3">
Personalize it with <br/>Bootstrap Icons
</h2>
<p class="fs-5">
<a href="#">Bootstrap Icons</a> is an open source SVG icon library
featuring over 1,800 glyphs, with more added every release.
They're designed to work in any project, whether you use Bootstrap
itself or not. Use them as SVGs or icon fonts--both options give
you vector scaling and easy customization via CSS.
</p>
<a class="icon-link icon-link-hover lead fw-semibold mb-5" href="#">
Get Bootstrap Icons
<i class="bi bi-arrow-right mb-2"></i>
</a>
</div>
<div class="col-lg-6">
<img
class="img-fluid"
src="{{ Vite::asset('resources/images/bs-icons.png') }}"
alt="Bootstrap Icons"
/>
</div>
</div>
</div>
</div>
<!-- Bootstrap Official Themes - -->
<div id="bs-themes">
<!-- Container -->
<div class="container py-5 px-4">
<div class="row">
<div class="col-lg-6">
<div class="mb-3 mt-5">
<i
class="bi bi-droplet-fill fs-2 bg-info py-2 px-3 rounded-3 text-white"
></i>
</div>
<h2 class="display-5">
Make it yours with official Bootstrap Themes
</h2>
<p class="fs-5">
Take Bootstrap to the next level with premium themes from the
<a href="#">official Bootstrap Themes marketplace</a>. Themes are
built on Bootstrap as their own extended frameworks, rich with new
components and plugins, documentation, and powerful build tools.
</p>
<a class="icon-link icon-link-hover lead fw-semibold mb-5" href="#">
Browse Bootstrap Themes
<i class="bi bi-arrow-right mb-2"></i>
</a>
</div>
<div class="col-lg-6">
<img
class="img-fluid"
src="{{ Vite::asset('resources/images/bs-themes.png') }}"
alt="Bootstrap Themes"
/>
</div>
</div>
</div>
</div>
<!-- Footer -->
<div id="footer" class="bg-light py-5">
<!-- Container -->
<div class="container py-5 px-4">
<div class="row">
<div class="col-lg-3 mb-5">
<a href="#" class="logo text-decoration-none">
<div class="d-flex">
<img
class="img-fluid"
src="{{ Vite::asset('resources/images/logo-black.svg') }}"
alt="Bootstrap Logo"
style="width: 40px"
/>
<div class="fs-5 ms-2 text-black">Bootstrap</div>
</div>
</a>
<div class="mt-2 text-muted">
<small
>Designed and built with all the love in the world by the
<a href="#" class="text-black">Bootstrap team</a> with the help
of <a href="#" class="text-black">our contributors</a>.</small
>
</div>
<div class="mt-2 text-muted">
<small
>Code licensed <a href="#" class="text-black">MIT</a>, docs
<a href="#" class="text-black">CC BY 3.0</a>.</small
>
</div>
<div class="mt-2 text-muted">
<small>Currently v5.3.0-alpha2.</small>
</div>
</div>
<div
class="col-2 col-1g-3 offset-1g-2 mb-5"
style="margin-left: 90px"
>
<h5>Links</h5>
<ul class="list-unstyled">
<li class="mb-2"><a href="{{ url('https://getbootstrap.com/') }}">Home</a></li>
<li class="mb-2"><a href="{{ url('https://getbootstrap.com/docs/5.3/getting-started/introduction/') }}">Docs</a></li>
<li class="mb-2"><a href="{{ url('https://getbootstrap.com/docs/5.3/examples/') }}">Examples</a></li>
<li class="mb-2"><a href="{{ url('https://icons.getbootstrap.com/') }}">Icons</a></li>
<li class="mb-2"><a href="{{ url('https://themes.getbootstrap.com/') }}">Themes</a></li>
<li class="mb-2"><a href="{{ url('https://blog.getbootstrap.com/') }}">Blog</a></li>
<li class="mb-2"><a href="{{ url('https://cottonbureau.com/people/bootstrap') }}">Swag Store</a></li>
</ul>
</div>
<div class="col-6 col-lg-2 mb-5">
<h5>Guides</h5>
<ul class="list-unstyled">
<li class="mb-2"><a href="{{ url('https://getbootstrap.com/docs/5.3/getting-started/introduction/') }}">Getting started</a></li>
<li class="mb-2"><a href="{{ url('https://getbootstrap.com/docs/5.3/examples/starter-template/') }}">Starter template</a></li>
<li class="mb-2"><a href="{{ url('https://getbootstrap.com/docs/5.3/getting-started/webpack/') }}">Webpack</a></li>
<li class="mb-2"><a href="{{ url('https://getbootstrap.com/docs/5.3/getting-started/parcel/') }}">Parcel</a></li>
<li class="mb-2"><a href="{{ url('https://getbootstrap.com/docs/5.3/getting-started/vite/') }}">Vite</a></li>
</ul>
</div>
<div class="col-6 col-lg-2 mb-5">
<h5>Projects</h5>
<ul class="list-unstyled">
<li class="mb-2"><a href="{{ url('https://github.com/twbs/bootstrap') }}">Bootstrap 5</a></li>
<li class="mb-2"><a href="{{ url('https://github.com/twbs/bootstrap/tree/v4-dev') }}">Bootstrap 4</a></li>
<li class="mb-2"><a href="{{ url('https://github.com/twbs/icons') }}">Icons</a></li>
<li class="mb-2"><a href="{{ url('https://github.com/twbs/rfs') }}">RFS</a></li>
<li class="mb-2"><a href="{{ url('https://github.com/twbs/examples/') }}">Examples repo</a></li>
</ul>
</div>
<div class="col-6 col-lg-2 mb-5">
<h5>Community</h5>
<ul class="list-unstyled">
<li class="mb-2"><a href="{{ url('https://github.com/twbs/bootstrap/issues') }}">Issues</a></li>
<li class="mb-2"><a href="{{ url('https://github.com/orgs/twbs/discussions') }}">Discussions</a></li>
<li class="mb-2"><a href="{{ url('https://github.com/sponsors/twbs') }}">Corporate sponsors</a></li>
<li class="mb-2"><a href="{{ url('https://opencollective.com/bootstrap') }}">Open Collective</a></li>
<li class="mb-2"><a href="{{ url('https://stackoverflow.com/questions/tagged/bootstrap-5') }}">Stack overflow</a></li>
</ul>
</div>
</div>
</div>
</div>
@vite('resources/js/app.js')
</body>
</html>
|
Clase: 15/11/2022
\begin{teorema}[5K]
Si $F$ es un campo de característica 0 y $a,b\in F$ son algebraicos, entonces exiten $c\in F(a,b)$ tal que $F(a,b)=F(c)$
\begin{dem}
Sean $f(x),g(x)\in F[x]$ ambos irreducibles sobre $F$ y $f(a)=f(b)=0$. Sea $k$ una extensión de $F$ es la que $f(x)$ y $g(x)$ se factorizan como el producto de polinomios lineales en $K[x]$.
Por el corolario al lema 5.6, todas las raíces de $f(x)$ y de $g(x)$ son distintos (i.e. no tienen raíces de multiplicidad 2 o mayor). Sean $\{a=a_1,\cdots, a_{gr(f)}\}\subseteq K$ las raíces de $f(x)$ y $\{b=b_1,\cdots, b_{gr(g)}\}\subseteq K$ las raíces de $g(x)$.\bigbreak
Si $j\neq 1\implies$ la ecuación $a_i+\lambda b_j=a_1+\lambda b_1=a+\lambda b$ tiene una única solución en $K$, $a_i-a=\lambda(b-b_j)\implies \lambda = \frac{a_i-a}{b-b_j}$.
Además, si $F$ es de característica 0 $\implies F$ es infinito $\implies \exists \gamma\in F\ni a_i+\gamma b_j\neq a+\gamma b,\forall i=1,\cdots,gr(f)$ y $j\neq 1$. Sea $c=a+\gamma b$, $c=a+\gamma b\in F(a,b)\implies F(c)\subset F(a,b)$.
Como $g(b)=0$, $b$ es raíz de $g(x)\in F[x]\implies b$ es raíz de $g(x)\in F(c)[x]$. Además, si $h(x)=f(c-\gamma x)\in F(c)[x]$ y $h(b)=f(c-\gamma b)=f(a)=0$. $\implies$ existe una extensión de $F(c)$ sobre la cual $g(x)$ y $h(x)$ tienen a $x-b$ como factor común.
Si $j\neq 1\implies b_j\neq b$ es otra raíz de $g(x)\implies h(b_j)=f(c-\gamma b_j)\neq 0$ ya que $c-\gamma b_j$ no coincide con ninguna raíz de $f(x)$. Además, $(x-b)^2\not| g(x)\implies (x-b)^2\not| (g(x),h(x))\implies x-b=(g(x),h(x))$ sobre alguna extensión de $F(c)$. Por lema previo al lema 5.6, $x-b=(g(x),h(x))$ sobre $F(c)$. Entonces, $x-b\in F(c)[x]\implies b\in F(b)\implies a=c-\gamma b\in F(x)\implies F(a,b)\subseteq F(c)$. En resumen, $F(c)=F(a,b)$.
\end{dem}
\end{teorema}
\begin{corolario}
Toda extensión finita de un campo de característica 0 es simple.
\begin{dem}
Un argumento inductivo (tarea) asegura que si $\alpha_1,\cdots, \alpha_n$ son algebraicos sobre $F$ entonces $\exists c\in F(\alpha_1,\cdots, \alpha_n)\ni F(c)=F(\alpha_1,\cdots, \alpha_n)$
\end{dem}
\end{corolario}
\begin{cajita}
Revisar los problemas, 6,7, 8 de la sección 3.2 asignados en la tarea 12 y resolver los problemas 1,2,3,4,5,14 de la sección 5.5
\end{cajita}
\subsection{Elementos de la teoría de Galois}
\begin{teorema}[5L]
Si $K$ es un campo y $\sigma_1,\cdots, \sigma_n$ son automorfismos distintos de $K$, entonces es imposible encontrar $k_1,\cdots, k_n\in K$, no todos cero, tales que la suma $\sum_{i=1}^n k_i\sigma_i(u)=0$, para todo $u\in K$.
\begin{dem}
Supóngase que existe $\{k_1,\cdots,k_n\}\in K$, por lo menos un $k_i\neq 0\ni \sum_{i=1}^n k_i\sigma_i(u)=0,\forall u\in K$. Elíjase el subconjunto de elementos no nulos de $\{k_1,\cdots, k_n\}$ el subconjunto retiquetado más pequeños de elementos no nulos de $\{k_1,\cdots,k_n\}=\sum_{j=1}^m k_j\sigma_j(u)=0,\forall u\in K$.
Si $m=1\implies k_1\sigma_1(u)=0,\forall u\in K\implies k_1=0(\to\gets)$
Si $m>1$, como $\sigma_1,\cdots, \sigma_n$ son distintos, $\exists c\in K\ni \sigma_1(c)\neq \sigma_m(c)$. Ahora bien, $\sum_{j}^m k_j\sigma_j(u)=0,\forall u\in K\implies 0\sum_{j=1}^m k_j\sigma_j(cu)=\sum_{j=1}^m k_j \sigma_j(c)\sigma_j(u),\forall u\in K$. Además, $0=\sigma_1(c)\left(\sum_{j=1}^m k_j \sigma_j(u)\right) = \sum_{j=1}^m k_j \sigma_j(u)=0=0\cdot 0=\sum_{j=1}^m k_j -\sum_{j=1}^mk_j\sigma_1(c)\sigma_j(u)=\sum_{j=1}^n k_j(\sigma_1(c)-\sigma_j(c))\sigma_j(u)=\sum_{j=2}^m k_j(\sigma_1(c)-\sigma_j(c))\sigma(u)$.
Como $k_j(\sigma_1(c)-\sigma_j(c))\in K,k_m\neq 0, \sigma_1(c)-\sigma_m(c)\neq 0\implies k_m(\sigma_1(c)-\sigma_m(c))\neq 0\implies \{k_1,\cdots,k_m\}$ no es el subconjunto de elementos no nulos de $\{k_1,\cdots,k_n\}$ tales que $\sum_{j=1}^m k_j \sigma_j(u)=0,\forall u\in K$
\begin{definicion}
Si $K$ es un campo y $G$ es un subgrupo de $\mathbb{A}(K)$ (i.e $G$ es un grupo de automorfismos de $K$), entonces el subcampo de $K$ fijado por $G$ es $\{k\in K:\sigma(k)=k,\forall \sigma\in G\}$.
\begin{nota}
La definición sigue teniendo sentido si, en vez de un subgrupo de $\mathbb{A}(k)$, se considera un subconjunto no vacío de $\mathbb{A}(K)$. El problema 1 de la tarea 24 se verifica que el subcampo fijado de un conjunto de automorfismos y del subgrupo de $\mathbb{A}(k)$ generado por ese subconjunto, en efecto son iguales.
\end{nota}
\end{definicion}
\end{dem}
\end{teorema}
\begin{lema}
Si $K$ es un campo, $G$ es un subgrupo de $\mathbb{A}(K)$, entonces el subcampo de $K$ fijado por $G$, en efecto es un subcampo de $K$.
\begin{dem}
Sean $k_1,k_2$ elementos del subcampo de $k$ fijado por $G\implies \sigma(k_1)=k_1$ y $\sigma(k_2)=k_2,\forall \sigma\in G$.
\end{dem}
\end{lema}
|
package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class LoginActivity extends AppCompatActivity {
//声明控件
//登陆界面的控件
EditText user_name;
EditText user_password;
Button denglu;
Button zhuce;
HashMap<String, String> stringHashMap;
String TAG = MainActivity.class.getCanonicalName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//找到当且xml文件内的控件ID
//数据编辑框的ID
user_name = this.findViewById(R.id.user_name);
user_password = this.findViewById(R.id.user_password);
//按键属性的ID
denglu = this.findViewById(R.id.denglu);
zhuce = this.findViewById(R.id.zhuce);
stringHashMap = new HashMap<>();
//登录按键按下之后处理的事情
denglu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//提交到服务器验证
//获取用户名,密码,并放入HashMap中,准备传入服务器,进行验证
loginPOST(view);
}
});
//注册按键按下之后,响应的事件
zhuce.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//实现界面跳转,从登录界面跳转到注册界面
Intent intent = null; //这个变量初始申明为空
intent = new Intent(LoginActivity.this, RegisterActivity.class);//跳转界面
startActivity(intent);
}
});
}
public void loginPOST(View view){//post请求
stringHashMap.put("username",user_name.getText().toString());//获取用户名,密码,并放入HashMap中,准备传入服务器,进行验证
stringHashMap.put("password",user_password.getText().toString());
new Thread(postRun).start();//开启线程
}
/**
* post请求
*/
Runnable postRun = new Runnable() {
@Override
public void run() {
requestPost(stringHashMap);
}
};
/**
* post提交数据
* @param paramsMap
*/
private void requestPost(HashMap<String,String>paramsMap){
try{
String baseUrl = "http://localhost:8080/AndroidTest_war_exploded/LoginServlet";
//合成参数
StringBuilder tempParams = new StringBuilder();
int pos = 0;
for(String key :paramsMap.keySet()){
if(pos>0){
tempParams.append("&");
}
tempParams.append(String.format("%s=%s",key, URLEncoder.encode(paramsMap.get(key),"utf-8")));
pos++;
}
String params = tempParams.toString();
Log.e(TAG,"请求的参数为:"+params);
//请求的参数转换为byte数组
byte[] postData = params.getBytes();
//新建一个URL对象
URL url = new URL(baseUrl);
//打开一个HttpURLConnection连接
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
//设置连接超时时间
urlConn.setConnectTimeout(5*1000);
//设置从主机读取数据超时
urlConn.setReadTimeout(5*1000);
//Post请求必须设置允许输出
urlConn.setDoOutput(true);
//Post请求不能使用缓存
urlConn.setUseCaches(false);
//设置请求允许输入
urlConn.setDoInput(true);
//设置为Post请求
urlConn.setRequestMethod("POST");
//设置本次连接是否自动处理重定向
urlConn.setInstanceFollowRedirects(true);
//配置请求Content-Type
urlConn.setRequestProperty("Content-Type","application/json");
//开始连接
urlConn.connect();
//发送请求参数
PrintWriter dos = new PrintWriter(urlConn.getOutputStream());
dos.write(params);
dos.flush();
dos.close();
//判断请求是否成功
if(urlConn.getResponseCode()==200){
//获取返回的数据
String result = streamToString(urlConn.getInputStream());
Log.e(TAG,"Post方式请求成功,result--->"+result);
}else {
Log.e(TAG,"Post方式请求失败");
}
//关闭连接
urlConn.disconnect();
}catch (Exception e){
Log.e(TAG,e.toString());
}
}
/**
* 将输入流转换成字符串,返回字符串信息
* @param is
* @return
*/
private String streamToString(InputStream is) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.close();
is.close();
byte[] byteArray = baos.toByteArray();
return new String(byteArray);
} catch (IOException e) {
Log.e(TAG, e.toString());
return null;
}
}
}
|
<mat-expansion-panel class="py-3" [expanded]="expand">
<mat-expansion-panel-header class="pt-1 pb-2">
<mat-panel-title>
Competitive Edge
</mat-panel-title>
<mat-panel-description>
Fill to Convince Customers to Choose Your Products/Services over Others
</mat-panel-description>
</mat-expansion-panel-header>
<div class="card">
<div class="card-header text-secondary">
"Why Choose Us Form"
</div>
<div class="card-body" >
<form novalidate [formGroup]="landingPageForm" >
<div formArrayName="services">
<mat-expansion-panel *ngFor="let eachservice of sections.controls;
let i = index;" class="mb-5 mx-lg-3">
<mat-expansion-panel-header class="py-3">
<mat-panel-title>
{{'Point '+(i+1)}}
</mat-panel-title>
<mat-panel-description>
{{'Fill for Point Number '+(i+1)+" Why Customers Should Choose Your Products/Services"}}
</mat-panel-description>
</mat-expansion-panel-header>
<div [formGroupName] ="i">
<div class="eachinput my-3 p-2">
<label for="headertitle">
Title of Point
</label>
<span class="alaye my-2">
Enter a brief title for the point you want to explain e.g. "Best Customer Care"
</span>
<mat-form-field appearance="fill">
<mat-label>Title of Point</mat-label>
<input id="{{'headertitle'+i}}" type="text" matInput formControlName="serviceTitle">
</mat-form-field>
</div>
<div class="eachinput my-3" id="{{'whyus'+i}}">
<div class="p-2" novalidate>
<label for="upload" class="form-label my-3">
{{landingPageForm.value.services[i].serviceTitle?'Upload Images that Illustrate Your Point for "'+landingPageForm.value.services[i].serviceTitle+'"':'Upload Images that Illustrate Your Point'}}
</label>
<span class="alaye my-2">
You can upload as many as you want at the same time.
</span>
<button class="alaye my-2" mat-button (click)="opendialog();">
Click here to see an example
</button>
<input type="file" multiple id="uploadinput" class="my-2">
<button class="btn btn-sm d-block btn-danger mb-3"
(click)="upload('whyus'+i, 'multiple', geteachimage(i).controls[0].get('eachimage')!,
'headerImages', 'eachimage', geteachimage(i))">
Upload
</button>
<mat-progress-bar [mode]="progressmode['headerImages'][i]" value="{{progressvalue['headerImages'][i]}}"
*ngIf="progressbar['headerImages'][i]"></mat-progress-bar>
<div class="alert alert-success" *ngIf="successfulUpload['headerImages'][i]">
Your Upload(s) is/are Successfull
</div>
<div class="smallimage overflow-auto d-flex " *ngIf="
landingPageForm.value.services[i].serviceImageUrl[0]?.eachimage"
>
<div class="eachimage m-3 position-relative" *ngFor="let eachimag of landingPageForm.
value.services[i].serviceImageUrl; let j = index; "
>
<img [src]="eachimag.eachimage" alt="" width="100" height="100">
<div (click)="reveal('deleteDialog', j, i)"
class="tr text-danger rounded-circle position-absolute mt-n2 top-0 end-0 d-flex justify-content-center align-items-center">
x
</div>
<a [attr.href]="eachimag.eachimage" target="blank"
class="bl rounded-circle position-absolute mt-n2 bottom-0 start-0 d-flex justify-content-center align-items-center">
->
</a>
<div class="visit position-absolute bottom-0 mb-5 w-auto end-2 bg-secondary text-light p-2 d-none">
Click to see this image in another tab.
</div>
<div class="deleteDialog position-fixed d-flex justify-content-center align-items-center" *ngIf="show.deleteDialog[i][j]">
<div class="p-3">
<div class="card">
<div class="card-header text-danger">
Confirm Delete
</div>
<div class="card-body">
<div class="m-2 text-secondary">
Are You Sure You Want To Delete This Image
</div>
<div class="m-2">
<img [src]="eachimag.eachimage" alt="" width="100" height="100">
</div>
<div class="gp d-flex justify-content-end align-items-center">
<div class="btn btn-secondary mr-2" (click)="hide('deleteDialog', j, i)">
Cancel
</div>
<div class="btn btn-danger mr-3" (click)="delete(geteachimage(i), j, 'deleteDialog', 'eachimage', i)">
Delete
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="eachinput my-3 p-2">
<label >
{{landingPageForm.value.services[i].serviceTitle?'Point Details for "'+landingPageForm.value.services[i].serviceTitle+'"':'Point Details'}}
</label>
<span class="alaye my-2">
Provide Explanation and Details of Your Point
</span>
<div class="eachinput my-3 p-2" id="{{'description'+i}}">
<ckeditor [editor]="Editor" (change)="onChange($event, i)" [data]='sections.controls[i].get("serviceDescription")?sections.controls[i].get("serviceDescription")!.value!:"We Offer ....."' (ready)="onReady($event)"></ckeditor>
</div>
</div>
</div>
</mat-expansion-panel>
</div>
<button mat-button (click)="addServices()" class="text-primary"> ADD ANOTHER POINT </button>
<!-- <div class="eachinput my-3 p-2" id="logoUrl">
<label for="logourl">
Upload An Image of The Product/Service
</label>
<span class="alaye">
Upload an image of the product OR
an image to illustrate the service you offer<br>
You can change the one you have uploaded by simply uploading another one
</span>
<input type="file" id="uploadinput" class="my-2">
<button class="btn btn-sm d-block btn-danger mb-3"
(click)="upload('logoUrl', 'not', landingPageForm.get('logoUrl')!,
'logoUrl', 'logoUrl' )">
Upload
</button>
<mat-progress-bar [mode]="progressmode['logoUrl']" value="{{progressvalue['logoUrl']}}"
*ngIf="progressbar['logoUrl']"></mat-progress-bar>
<div class="alert alert-success" *ngIf="successfulUpload['logoUrl']">
Your Upload(s) is/are Successfull
</div>
<div class="smallimage overflow-auto d-flex " *ngIf="
landingPageForm.value.logoUrl">
<div class="eachimage m-3 position-relative"
>
<img [src]="landingPageForm.value.logoUrl" alt="" width="100" height="100">
<a [attr.href]="landingPageForm.value.logoUrl" target="blank"
class="bl rounded-circle position-absolute mt-n2 bottom-0 start-0 d-flex justify-content-center align-items-center">
->
</a>
<div class="visit position-absolute bottom-0 mb-5 w-auto end-2 bg-secondary text-light p-2 d-none">
Click to see this image in another tab.
</div>
</div>
</div>
</div> -->
<div *ngIf="activateOverlay" class="position-fixed overlayi w-100 h-100 justify-content-center align-items-center">
</div>
<!-- <div>
<ckeditor [editor]="Editor" (change)="onChange($event)" data="<p>Hello, world!</p>" (ready)="onReady($event)"></ckeditor>
</div>
<div class="formaray" formArrayName="sections">
<div class="sectionformgroup" *ngFor = "let eacharray of sections.controls;
let i = index;" [formGroupName] = "i">
<mat-form-field appearance="fill">
<mat-label>Title</mat-label>
<input matInput type="text" id="{{'sectionTitle' + i}}" formControlName="sectionTitle">
</mat-form-field>
</div>
</div> -->
<input type="submit" value="Submit" (click)="save();"
class="btn mt-4 d-block w-50 btn-danger text-light">
</form>
</div>
</div>
</mat-expansion-panel>
<div *ngIf="alertMessage" class="p-3 zindex d-flex position-fixed w-100 h-100 start-0 top-0 justify-content-center align-items-center">
<div class="p-3 w-80 w-lg-50 bg-light position-relative insidezindex" [ngClass]="{
'text-danger': typeOfMessage == 'error',
'text-success': typeOfMessage == 'success'
}">
{{alertMessage}}
<div class="position-absolute top-0 end-0 pe-2 text-danger" (click)="closeMessage()">
<i class="fas fa-times"></i>
</div>
</div>
</div>
|
import React, {useState} from 'react';
import {Image, Text, View} from 'react-native';
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
import {COLORS, FONTS, SIZES, icons} from '../../constants';
import {FormInput, Header, IconButton, TextButton} from '../../components';
const SetupNewPassword = ({navigation}) => {
// State
const [password, setPassword] = useState('');
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
const [confirmPassword, setConfirmPassword] = useState('');
const [isConfirmPasswordVisible, setIsConfirmPasswordVisible] =
useState(false);
// Render
function renderHeader() {
return <Header />;
}
function renderTitleAndDescription() {
return (
<View>
<Text
style={{
...FONTS.h2,
color: COLORS.contentPrimary,
}}>
Setup new password
</Text>
<Text
style={{
...FONTS.ps2,
color: COLORS.contentSecondary,
}}>
Password must be 8 characters long and contain a number
</Text>
</View>
);
}
function renderFormInputs() {
return (
<View>
{/* Password */}
<FormInput
rootContainerStyle={{
marginTop: SIZES.padding * 3,
}}
label="Password"
placeholder={'Enter your password'}
value={password}
secureTextEntry={!isPasswordVisible}
onChange={value => setPassword(value)}
prependComponent={
<Image
source={icons.lock}
style={{
width: 25,
height: 25,
marginRight: SIZES.base,
}}
/>
}
appendComponent={
<IconButton
containerStyle={{
alignItems: 'flex-end',
}}
icon={isPasswordVisible ? icons.eye_off : icons.eye}
iconStyle={{
tintColor: COLORS.contentPrimary,
}}
onPress={() => {
setIsPasswordVisible(!isPasswordVisible);
}}
/>
}
/>
{/* Confirm Password */}
<FormInput
rootContainerStyle={{
marginTop: SIZES.padding,
}}
label="Confirm Password"
placeholder={'Enter your password'}
value={confirmPassword}
secureTextEntry={!isConfirmPasswordVisible}
onChange={value => setConfirmPassword(value)}
prependComponent={
<Image
source={icons.lock}
style={{
width: 25,
height: 25,
marginRight: SIZES.base,
}}
/>
}
appendComponent={
<IconButton
containerStyle={{
alignItems: 'flex-end',
}}
icon={isConfirmPasswordVisible ? icons.eye_off : icons.eye}
iconStyle={{
tintColor: COLORS.contentPrimary,
}}
onPress={() => {
setIsConfirmPasswordVisible(!isConfirmPasswordVisible);
}}
/>
}
/>
</View>
);
}
function renderFooter() {
return (
<View
style={{
paddingHorizontal: SIZES.padding,
marginBottom: SIZES.padding,
}}>
<TextButton
label={'Confirm'}
contentContainerStyle={{
marginTop: SIZES.padding,
borderRadius: SIZES.radius,
}}
onPress={() => {
navigation.navigate('Success', {
title: 'Your password was successfully changed!',
description: 'You can now login with your new password.',
btnLabel: 'Login',
onPress: () => {
navigation.navigate('Welcome');
},
});
}}
/>
</View>
);
}
return (
<View
style={{
flex: 1,
backgroundColor: COLORS.backgroundPrimary,
}}>
{/* Header */}
{renderHeader()}
<KeyboardAwareScrollView
enableOnAndroid={true}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
contentContainerStyle={{
flexGrow: 1,
marginTop: SIZES.radius,
paddingHorizontal: SIZES.padding,
paddingBottom: SIZES.padding,
}}>
{/* Titke and Description */}
{renderTitleAndDescription()}
{/* Form Inputs */}
{renderFormInputs()}
</KeyboardAwareScrollView>
{/* Footer */}
{renderFooter()}
</View>
);
};
export default SetupNewPassword;
|
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { JwtType } from 'src/common/constants/jwt';
type JwtPayload = {
sub: string;
username: string;
};
@Injectable()
export class AccessTokenStrategy extends PassportStrategy(
Strategy,
JwtType.JWT_ACCESS_TOKEN,
) {
constructor(configService: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: configService.get<string>('JWT_ACCESS_SECRET'),
});
}
validate(payload: JwtPayload) {
return payload;
}
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.privateAdd = exports.deriveChildKey = exports.publicKeyToEthAddress = exports.privateKeyToEthAddress = void 0;
const sha3_1 = require("@noble/hashes/sha3");
const hmac_1 = require("@noble/hashes/hmac");
const sha512_1 = require("@noble/hashes/sha512");
const utils_1 = require("@metamask/utils");
const constants_1 = require("../constants");
const utils_2 = require("../utils");
const curves_1 = require("../curves");
const SLIP10Node_1 = require("../SLIP10Node");
/**
* Converts a BIP-32 private key to an Ethereum address.
*
* **WARNING:** Only validates that the key is non-zero and of the correct
* length. It is the consumer's responsibility to ensure that the specified
* key is a valid BIP-44 Ethereum `address_index` key.
*
* @param key - The `address_index` private key bytes to convert to an Ethereum
* address.
* @returns The Ethereum address corresponding to the given key.
*/
function privateKeyToEthAddress(key) {
(0, utils_1.assert)(key instanceof Uint8Array && (0, utils_2.isValidBytesKey)(key, constants_1.BYTES_KEY_LENGTH), 'Invalid key: The key must be a 32-byte, non-zero Uint8Array.');
const publicKey = curves_1.secp256k1.getPublicKey(key, false);
return publicKeyToEthAddress(publicKey);
}
exports.privateKeyToEthAddress = privateKeyToEthAddress;
/**
* Converts a BIP-32 public key to an Ethereum address.
*
* **WARNING:** Only validates that the key is non-zero and of the correct
* length. It is the consumer's responsibility to ensure that the specified
* key is a valid BIP-44 Ethereum `address_index` key.
*
* @param key - The `address_index` public key bytes to convert to an Ethereum
* address.
* @returns The Ethereum address corresponding to the given key.
*/
function publicKeyToEthAddress(key) {
(0, utils_1.assert)(key instanceof Uint8Array &&
(0, utils_2.isValidBytesKey)(key, curves_1.secp256k1.publicKeyLength), 'Invalid key: The key must be a 65-byte, non-zero Uint8Array.');
return (0, sha3_1.keccak_256)(key.slice(1)).slice(-20);
}
exports.publicKeyToEthAddress = publicKeyToEthAddress;
/**
* Derive a BIP-32 child key with a given path from a parent key.
*
* @param path - The derivation path part to derive.
* @param node - The node to derive from.
* @param curve - The curve to use for derivation.
* @returns A tuple containing the derived private key, public key and chain
* code.
*/
async function deriveChildKey({ path, node, curve = curves_1.secp256k1, }) {
const isHardened = path.includes(`'`);
if (!isHardened && !curve.deriveUnhardenedKeys) {
throw new Error(`Invalid path: Cannot derive unhardened child keys with ${curve.name}.`);
}
if (!node) {
throw new Error('Invalid parameters: Must specify a node to derive from.');
}
if (isHardened && !node.privateKey) {
throw new Error('Invalid parameters: Cannot derive hardened child keys without a private key.');
}
const indexPart = path.split(`'`)[0];
const childIndex = parseInt(indexPart, 10);
if (!/^\d+$/u.test(indexPart) ||
!Number.isInteger(childIndex) ||
childIndex < 0 ||
childIndex >= constants_1.BIP_32_HARDENED_OFFSET) {
throw new Error(`Invalid BIP-32 index: The index must be a non-negative decimal integer less than ${constants_1.BIP_32_HARDENED_OFFSET}.`);
}
if (node.privateKeyBytes) {
const secretExtension = await deriveSecretExtension({
privateKey: node.privateKeyBytes,
childIndex,
isHardened,
curve,
});
const { privateKey, chainCode } = await generateKey({
privateKey: node.privateKeyBytes,
chainCode: node.chainCodeBytes,
secretExtension,
curve,
});
return SLIP10Node_1.SLIP10Node.fromExtendedKey({
privateKey,
chainCode,
depth: node.depth + 1,
masterFingerprint: node.masterFingerprint,
parentFingerprint: node.fingerprint,
index: childIndex + (isHardened ? constants_1.BIP_32_HARDENED_OFFSET : 0),
curve: curve.name,
});
}
const publicExtension = await derivePublicExtension({
parentPublicKey: node.compressedPublicKeyBytes,
childIndex,
});
const { publicKey, chainCode } = generatePublicKey({
publicKey: node.compressedPublicKeyBytes,
chainCode: node.chainCodeBytes,
publicExtension,
curve,
});
return SLIP10Node_1.SLIP10Node.fromExtendedKey({
publicKey,
chainCode,
depth: node.depth + 1,
masterFingerprint: node.masterFingerprint,
parentFingerprint: node.fingerprint,
index: childIndex,
curve: curve.name,
});
}
exports.deriveChildKey = deriveChildKey;
// the bip32 secret extension is created from the parent private or public key and the child index
/**
* @param options
* @param options.privateKey
* @param options.childIndex
* @param options.isHardened
*/
async function deriveSecretExtension({ privateKey, childIndex, isHardened, curve, }) {
if (isHardened) {
// Hardened child
const indexBytes = new Uint8Array(4);
const view = new DataView(indexBytes.buffer);
view.setUint32(0, childIndex + constants_1.BIP_32_HARDENED_OFFSET, false);
return (0, utils_1.concatBytes)([new Uint8Array([0]), privateKey, indexBytes]);
}
// Normal child
const parentPublicKey = await curve.getPublicKey(privateKey, true);
return derivePublicExtension({ parentPublicKey, childIndex });
}
async function derivePublicExtension({ parentPublicKey, childIndex, }) {
const indexBytes = new Uint8Array(4);
const view = new DataView(indexBytes.buffer);
view.setUint32(0, childIndex, false);
return (0, utils_1.concatBytes)([parentPublicKey, indexBytes]);
}
/**
* Add a tweak to the private key: `(privateKey + tweak) % n`.
*
* @param privateKeyBytes - The private key as 32 byte Uint8Array.
* @param tweakBytes - The tweak as 32 byte Uint8Array.
* @param curve - The curve to use.
* @throws If the private key or tweak is invalid.
* @returns The private key with the tweak added to it.
*/
function privateAdd(privateKeyBytes, tweakBytes, curve) {
const privateKey = (0, utils_1.bytesToBigInt)(privateKeyBytes);
const tweak = (0, utils_1.bytesToBigInt)(tweakBytes);
if (tweak >= curve.curve.n) {
throw new Error('Invalid tweak: Tweak is larger than the curve order.');
}
const added = (0, curves_1.mod)(privateKey + tweak, curve.curve.n);
const bytes = (0, utils_1.hexToBytes)(added.toString(16).padStart(64, '0'));
if (!curve.isValidPrivateKey(bytes)) {
throw new Error('Invalid private key or tweak: The resulting private key is invalid.');
}
return bytes;
}
exports.privateAdd = privateAdd;
/**
* @param options
* @param options.privateKey
* @param options.chainCode
* @param options.secretExtension
*/
async function generateKey({ privateKey, chainCode, secretExtension, curve, }) {
const entropy = (0, hmac_1.hmac)(sha512_1.sha512, chainCode, secretExtension);
const keyMaterial = entropy.slice(0, 32);
const childChainCode = entropy.slice(32);
// If curve is ed25519: The returned child key ki is parse256(IL).
// https://github.com/satoshilabs/slips/blob/133ea52a8e43d338b98be208907e144277e44c0e/slip-0010.md#private-parent-key--private-child-key
if (curve.name === 'ed25519') {
const publicKey = await curve.getPublicKey(keyMaterial);
return { privateKey: keyMaterial, publicKey, chainCode: childChainCode };
}
const childPrivateKey = privateAdd(privateKey, keyMaterial, curve);
const publicKey = await curve.getPublicKey(childPrivateKey);
return { privateKey: childPrivateKey, publicKey, chainCode: childChainCode };
}
function generatePublicKey({ publicKey, chainCode, publicExtension, curve, }) {
const entropy = (0, hmac_1.hmac)(sha512_1.sha512, chainCode, publicExtension);
const keyMaterial = entropy.slice(0, 32);
const childChainCode = entropy.slice(32);
// This function may fail if the resulting key is invalid.
const childPublicKey = curve.publicAdd(publicKey, keyMaterial);
return {
publicKey: childPublicKey,
chainCode: childChainCode,
};
}
//# sourceMappingURL=bip32.js.map
|
import React, { useState, useEffect, useRef } from 'react';
import { Slider, Button } from 'antd';
import styles from './PredictBusyness.module.css';
import { useNavigate } from 'react-router-dom';
const PredictBusyness = ({ setHour }) => {
const [selectedHour, setSelectedHour] = useState(0);
const navigate = useNavigate();
const handleSubmit = () => {
// console.log(`Selected time point: ${formatTime(selectedHour)}`);
navigate('/map/predict', { state: { selectedHour } });
};
useEffect(() => {
setHour(selectedHour);
}, [selectedHour, setHour]);
const formatTime = (hour) => {
return `${hour.toString().padStart(2, '0')}:00`; // Format to "00:00" (e.g., "08:00")
};
const debounceTimeoutRef = useRef(null); // Ref to hold the timeout ID
const onChange = value => {
// Clear any existing timeout
if (debounceTimeoutRef.current) {
clearTimeout(debounceTimeoutRef.current);
}
// Set a new timeout to call setSelectedHour after a delay of 100ms
debounceTimeoutRef.current = setTimeout(() => {
setSelectedHour(value);
}, 100);
};
return (
<div className={styles.playbackControl}>
<h3 className={styles.playbackTitle}>Busyness Forecast</h3>
<Slider
min={0}
max={23}
defaultValue={selectedHour}
onChange={onChange}
// tipFormatter={value => formatTime(value)} // Format tooltip to "00:00"
// tooltip.formatter = {value => formatTime(value)}
tooltip={{ formatter: value => `${value}` }}
marks={{
0: { style: { fontSize: '14px', fontWeight: 'bold', color:'white'}, label: formatTime(0) },
24: { style: { fontSize: '14px', fontWeight: 'bold', color:'white' }, label: formatTime(24) },
}}
/>
<br />
<div className={styles.playbackContent}>
Selected time point: {formatTime(selectedHour)}
</div>
<br />
<Button type="primary" className={styles.playbackBtn} onClick={handleSubmit}>
Predict
</Button>
</div>
);
};
export default PredictBusyness;
|
#pragma once
#include <vector>
#include "helpers.hpp"
#include "kernel/kernel_types.hpp"
#include "memory.hpp"
#include "result/result.hpp"
namespace Applets {
namespace AppletIDs {
enum : u32 {
None = 0,
SysAppletMask = 0x100,
HomeMenu = 0x101,
AltMenu = 0x103,
Camera = 0x110,
Friends = 0x112,
GameNotes = 0x113,
Browser = 0x114,
InstructionManual = 0x115,
Notifications = 0x116,
Miiverse = 0x117,
MiiversePosting = 0x118,
AmiiboSettings = 0x119,
SysLibraryAppletMask = 0x200,
SoftwareKeyboard = 0x201,
MiiSelector = 0x202,
PNote = 0x204, // TODO: What dis?
SNote = 0x205, // What is this too?
ErrDisp = 0x206,
EshopMint = 0x207,
CirclePadProCalib = 0x208,
Notepad = 0x209,
Application = 0x300,
EshopTiger = 0x301,
LibraryAppletMask = 0x400,
SoftwareKeyboard2 = 0x401,
MiiSelector2 = 0x402,
Pnote2 = 0x404,
SNote2 = 0x405,
ErrDisp2 = 0x406,
EshopMint2 = 0x407,
CirclePadProCalib2 = 0x408,
Notepad2 = 0x409,
};
}
enum class APTSignal : u32 {
None = 0x0,
Wakeup = 0x1,
Request = 0x2,
Response = 0x3,
Exit = 0x4,
Message = 0x5,
HomeButtonSingle = 0x6,
HomeButtonDouble = 0x7,
DspSleep = 0x8,
DspWakeup = 0x9,
WakeupByExit = 0xA,
WakeupByPause = 0xB,
WakeupByCancel = 0xC,
WakeupByCancelAll = 0xD,
WakeupByPowerButtonClick = 0xE,
WakeupToJumpHome = 0xF,
RequestForSysApplet = 0x10,
WakeupToLaunchApplication = 0x11,
};
struct Parameter {
u32 senderID; // ID of the parameter sender
u32 destID; // ID of the app to receive parameter
u32 signal; // Signal type (eg request)
u32 object; // Some applets will also respond with shared memory handles for transferring data between the sender and called
std::vector<u8> data; // Misc data
};
class AppletBase {
protected:
Memory& mem;
std::optional<Parameter>& nextParameter;
public:
virtual const char* name() = 0;
// Called by APT::StartLibraryApplet and similar
virtual Result::HorizonResult start(const MemoryBlock* sharedMem, const std::vector<u8>& parameters, u32 appID) = 0;
// Transfer parameters from application -> applet
virtual Result::HorizonResult receiveParameter(const Parameter& parameter) = 0;
virtual void reset() = 0;
AppletBase(Memory& mem, std::optional<Parameter>& nextParam) : mem(mem), nextParameter(nextParam) {}
};
} // namespace Applets
|
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="knockout-3.2.0.js"></script>
<script>
// function MyViewModel() {
// this.produce = [ 'Apple', 'Banana', 'Celery', 'Corn', 'Orange', 'Spinach' ];
// this.selectedProduce = ko.observableArray([ 'Corn', 'Orange' ]);
// this.selectedAllProduce = ko.pureComputed({
// read: function () {
// // Comparing length is quick and is accurate if only items from the
// // main array are added to the selected array.
// return this.selectedProduce().length === this.produce.length;
// },
// write: function (value) {
// this.selectedProduce(value ? this.produce.slice(0) : []);
// },
// owner: this
// });
// }
function ViewModel(){
this.produce=['Apple', 'Banana', 'Celery', 'Corn', 'Orange', 'Spinach'];
this.selectedProduce=ko.observableArray([ 'Celery', 'Corn', 'Orange']);
//这里是绑定的值,用值的改变事件调用方法,不知道有没有直接绑定方法的。
this.selectedAllProduce=ko.pureComputed({
read:function(){
return this.selectedProduce().length===this.produce.length;
},
write:function(value){
// alert(value);
this.selectedProduce(value?this.produce:[]);
}
, owner:this
//无OWNER 报错
//Uncaught TypeError: Unable to process binding "checked: function (){return selectedAllProduce }"
// Message: undefined is not a function
});
}
</script>
</head>
<body>
<div>
<input type="checkbox" data-bind="checked:selectedAllProduce">Produce
</div>
checkedValue:$data,checked:$parent.selectedProduce 用当前项是否在父列表里判断???
<div data-bind="foreach:produce">
<label>
<input type="checkbox" data-bind="checkedValue:$data,checked:$parent.selectedProduce">
<span data-bind="text: $data"></span>
</label><br>
</div>
</body>
<script>
ko.applyBindings(new ViewModel());
</script>
</html>
|
import { serve } from "@hono/node-server";
import { Hono } from "hono";
import { cors } from "hono/cors";
import { PrismaClient, User } from "database";
const client = new PrismaClient();
const app = new Hono();
app.use(
"*",
cors({
origin: ["http://localhost:3000"],
})
);
app.get("/users", async (c) => {
const users = await client.user.findMany();
return c.json(users);
});
app.get("/users/:id", async (c) => {
const user = await client.user.findUnique({
where: { id: Number(c.req.param("id")) },
});
return c.json(user);
});
app.post("/users", async (c) => {
const data = await c.req.json();
const user = await client.user.create({ data: data as User });
return c.json(user);
});
app.put("/users/:id", async (c) => {
const data = await c.req.json();
const user = await client.user.update({
where: { id: Number(c.req.param("id")) },
data: data as User,
});
return c.json(user);
});
app.delete("/users/:id", async (c) => {
const user = await client.user.delete({
where: { id: Number(c.req.param("id")) },
});
return c.json(user);
});
serve(app);
|
import React from 'react';
import Link from "next/link";
import { AppBar, Toolbar, Typography, Button, createTheme, ThemeProvider } from '@material-ui/core'; // 스타일
import { makeStyles } from '@material-ui/core/styles'; // 스타일 객체
const theme = createTheme({
palette: {
primary: {
main: '#32a89d', // Replace with your desired color
},
},
});
const useStyles = makeStyles((theme) => ({
toolbar: {
display: 'flex',
justifyContent: 'space-between',
padding: '8px 8px',
},
title: {
flexGrow: 1,
marginRight: theme.spacing(2),
color: 'white',
},
button: {
marginLeft: theme.spacing(2),
color: 'white',
},
}));
const Header = () => {
const classes = useStyles(); // 스타일 객체 생성
return (
<ThemeProvider theme={theme}>
<AppBar position="static">
<Toolbar className={classes.toolbar}>
<Link href="/">
<Typography variant="h6" className={classes.title}>
ALBUM.BIRD89
</Typography>
</Link>
<div>
<Link href="/signup">
<Button className={classes.button} color="inherit">
회원가입
</Button>
</Link>
<Link href="/login">
<Button className={classes.button} color="inherit">
로그인
</Button>
</Link>
</div>
</Toolbar>
</AppBar>
</ThemeProvider>
);
};
export default Header;
|
<script setup>
import { Line } from "vue-chartjs";
import zoomPlugin from "chartjs-plugin-zoom";
import moment from "moment";
import { ref, watchEffect } from "vue";
import {
Chart as ChartJS,
Title,
Tooltip,
Legend,
PointElement,
LineElement,
CategoryScale,
LinearScale,
Colors,
} from "chart.js";
ChartJS.register(
Title,
Tooltip,
Legend,
PointElement,
LineElement,
CategoryScale,
LinearScale,
Colors,
zoomPlugin
);
const props = defineProps({
icon: String,
title: String,
value: String,
unit: String,
description: String,
chart: {
type: Object,
default: {},
},
chartDot: {
type: Boolean,
default: false,
},
hideMinMax: {
type: Boolean,
default: false,
},
});
const chartOptions = {
responsive: true,
mantainAspectRatio: false,
scales: {
x: {
border: {
display: false
},
grid: {
display: false
},
display: true,
title: {
display: false,
},
ticks: {
mirror: false,
color: convertToHSL(
getComputedStyle(document.querySelector(":root")).getPropertyValue(
"--p"
)
),
},
},
y: {
border: {
display: false
},
display: true,
title: {
display: false,
},
grid: {
display: true,
color: convertToHSL(
getComputedStyle(document.querySelector(":root")).getPropertyValue(
"--b3"
)
)
},
ticks: {
display: true,
mirror: false,
color: convertToHSL(
getComputedStyle(document.querySelector(":root")).getPropertyValue(
"--p"
)
),
},
},
},
plugins: {
legend: {
display: false,
},
tooltip: {
enabled: true,
position: "nearest",
},
zoom: {
zoom: {
wheel: {
enabled: true,
modifierKey: "ctrl",
},
pinch: {
enabled: true,
},
mode: "xy",
},
limits: {
x: { min: 0, max: "original" },
y: { min: 0, max: "original" },
},
},
},
};
const chartData = ref();
function convertToHSL(input) {
const values = input.split(" ").map((val) => parseFloat(val));
const h = values[0];
const s = values[1];
const l = values[2];
return `hsl(${h}, ${s}%, ${l}%)`;
}
watchEffect(() => {
chartData.value = {
labels: Object.keys(props.chart).map((label) => {
return moment.unix(label).format("HH:mm");
}),
datasets: [
{
label: props.title,
data: Object.values(props.chart),
tension: 0.4,
pointStyle: props.chartDot ? true : false,
cubicInterpolationMode: "monotone",
borderColor: convertToHSL(
getComputedStyle(document.querySelector(":root")).getPropertyValue(
"--p"
)
),
},
],
};
});
</script>
<template>
<div class="card xl:card-side shadow-none rounded-lg border-2 border-base-300">
<div class="card-body w-full p-2 m-4 sm:p-4 pb-2">
<div class="card-title items-center mb-2">
<img
:src="'https://img.icons8.com/fluency/' + icon + '.png'"
:alt="icon"
class="block pr-1 h-12"
/>
{{ title }}
</div>
<div class="text-4xl font-bold">{{ value }}{{ unit }}</div>
<div class="text-sm" v-html="description"></div>
<div class="text-sm" v-if="!hideMinMax"> 24h min max: <span class="text-info">{{Math.min(...Object.values(props.chart))}}{{ unit }}</span> <span class="text-error">{{Math.max(...Object.values(props.chart))}}{{ unit }}</span></div>
</div>
<figure class="w-full p-2 h-full" v-if="Object.keys(chart).length">
<Line :data="chartData" :options="chartOptions" id="Line" />
</figure>
</div>
</template>
|
package com.zylitics.btbr.webdriver.session;
import com.google.common.base.Preconditions;
import com.zylitics.btbr.config.APICoreProperties;
import com.zylitics.btbr.model.Build;
import com.zylitics.btbr.model.BuildCapability;
import com.zylitics.btbr.runner.provider.BrowserProvider;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxDriverLogLevel;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.GeckoDriverService;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.nio.file.Path;
public class FirefoxDriverSessionProvider extends AbstractDriverSessionProvider {
public FirefoxDriverSessionProvider(Build build, APICoreProperties.Webdriver wdProps
, BuildCapability buildCapability, Path buildDir, BrowserProvider browserProvider) {
super(build, wdProps, buildCapability, buildDir, browserProvider);
}
@Override
public RemoteWebDriver createSession() {
setDriverExe();
Preconditions.checkNotNull(System.getProperty(GeckoDriverService.GECKO_DRIVER_EXE_PROPERTY),
"gecko driver exe path must be set as system property");
GeckoDriverService driverService = new GeckoDriverService.Builder()
.usingAnyFreePort()
.withLogFile(getDriverLogFile())
.build();
FirefoxOptions firefox = new FirefoxOptions();
firefox.merge(commonCapabilities);
String browserBinary = getBrowserBinaryPath();
if (browserBinary != null) {
firefox.setBinary(browserBinary);
}
if (build.isCaptureDriverLogs()) {
FirefoxDriverLogLevel logLevel =
FirefoxDriverLogLevel.fromString(buildCapability.getWdFirefoxLogLevel());
if (logLevel != null) {
firefox.setLogLevel(logLevel);
}
} else {
firefox.setLogLevel(FirefoxDriverLogLevel.FATAL);
}
// add more browser specific arguments
return new FirefoxDriver(driverService, firefox);
}
@Override
protected String getDriverExeSysProp() {
return GeckoDriverService.GECKO_DRIVER_EXE_PROPERTY;
}
@Override
protected String getDriverWinExeName() {
return "geckodriver.exe";
}
}
|
import 'package:bdp_payment_app/common/widgets/common_widgets.dart';
import 'package:bdp_payment_app/utils/constants/colors.dart';
import 'package:bdp_payment_app/utils/constants/image_strings.dart';
import 'package:flutter/material.dart';
import '../../../features/authentication/screens/onboarding/widgets/onboarding_next_button.dart';
import '../../../utils/constants/sizes.dart';
import '../../../utils/constants/text_strings.dart';
import '../../styles/spacing_styles.dart';
import '../button/button.dart';
class SuccessScreen extends StatelessWidget {
const SuccessScreen(
{super.key,
required this.image,
required this.title,
required this.onPressed,
required this.buttonName,
this.isLoading = false,
required this.imageButton, });
final String image, title,buttonName, imageButton;
final bool? isLoading;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Padding(
padding: BDPSpacingStyle.paddingWithAppBarHeight * 2,
child: Column(
children: [
Text(
title,
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 20,
color: BDPColors.primary,
),
textAlign: TextAlign.center,
),
const SizedBox(
height: BDPSizes.spaceBtwSections,
),
Image(
image: AssetImage(image),
width: 390,
height: 291 ,
),
const SizedBox(
height: BDPSizes.spaceBtwItems*9,
),
SizedBox(
width: 193,
child: ElevatedButton(
onPressed: onPressed,
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
backgroundColor: BDPColors.primary,
padding: const EdgeInsets.only(left: 26),
),
child: isLoading!
? Center(
child: loader(),
)
: Row(
children: [
Text(
buttonName,
style: const TextStyle(
fontSize: 16,
color: Colors.white,
),
),
const SizedBox(
width: 8,
),
Image.asset(
imageButton,
width: 24, // Adjust width as needed
height: 24, // Adjust height as needed
),
],
),
),
),
],
),
),
),
);
}
}
|
import React, { useState, useRef } from 'react';
export default function ContactForm() {
const scriptURL = 'https://script.google.com/macros/s/AKfycbwqGFxJ0D9CJT0Sc2v1udvYJ2PTsv1PFGxLJ7AuQO3gtjibNpv8i_wk6_ZNA60pTPdo/exec';
const btnKirimRef = useRef(null);
const btnLoadingRef = useRef(null);
const [formData, setFormData] = useState({
nama: '',
email: '',
pesan: ''
});
const [showAlert, setShowAlert] = useState(false);
const handleSubmit = e => {
e.preventDefault();
btnLoadingRef.current.classList.toggle("d-none");
btnKirimRef.current.classList.toggle("d-none");
fetch(scriptURL, { method: 'POST', body: new FormData(e.target) })
.then(response => {
if (response.ok) {
btnLoadingRef.current.classList.toggle("d-none");
btnKirimRef.current.classList.toggle("d-none");
setShowAlert(true);
console.log('Form berhasil dikirim ke Google Sheet');
} else {
console.error('Terjadi kesalahan saat mengirim formulir');
}
})
.catch(error => {
console.error('Terjadi kesalahan:', error);
});
};
const handleChange = e => {
const { name, value } = e.target;
setFormData(prevData => ({
...prevData,
[name]: value
}));
};
const handleCloseAlert = () => {
setShowAlert(false);
};
return (
<>
<form name="submit-to-google-sheet" onSubmit={handleSubmit}>
<div className="w-full lg:w-2/3 lg:mx-auto">
<div className="w-full px-4 mb-8">
<label className="text-base font-bold text-dark" htmlFor="nama">Nama</label>
<input
name="nama"
type="text"
value={formData.nama}
onChange={handleChange}
className="p-3 w-full bg-slate-200 text-dark rounded-md focus:outline-none focus:ring-primary focus:ring-1 focus:border-primary"
/>
</div>
<div className="w-full px-4 mb-8">
<label className="text-base font-bold text-dark" htmlFor="email">Email</label>
<input
name="email"
type="email"
value={formData.email}
onChange={handleChange}
className="p-3 w-full bg-slate-200 text-dark rounded-md focus:outline-none focus:ring-primary focus:ring-1 focus:border-primary"
/>
</div>
<div className="w-full px-4 mb-8">
<label className="text-base font-bold text-dark" htmlFor="pesan">Pesan</label>
<textarea
name="pesan"
type="text"
value={formData.pesan}
onChange={handleChange}
className="p-3 h-32 w-full bg-slate-200 text-dark rounded-md focus:outline-none focus:ring-primary focus:ring-1 focus:border-primary"
/>
</div>
{/* Anda dapat menambahkan bagian lain dari formulir (seperti email dan pesan) di sini */}
</div>
<div className="w-full px-4">
<button type="submit" className="btn-kirim text-base font-semibold bg-kedua py-3 px-8 rounded-full text-white w-full hover:opacity-80 hover:shadow-lg transition duration-500">
Kirim
</button>
<button className="d-none btn-loading text-base font-semibold bg-emerald-400 py-3 px-8 rounded-full text-white w-full" type="button" disabled>
<span className="spinner-border spinner-border-sm" aria-hidden="true"></span>
<span role="status">Loading...</span>
</button>
</div>
</form>
<div className={`my-alert alert alert-success alert-dismissible fade show ${showAlert ? '' : 'd-none'}`} role="alert">
<strong>Terima kasih!</strong> Pesan anda sudah terkirim.
<button className="btn-close" onClick={handleCloseAlert} aria-label="Close"></button>
</div>
</>
);
}
|
import { useContext, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Box, Button, Container, TextField, Typography } from '@mui/material';
import logo from '../assets/icons/logo.svg';
import './logo.css';
import { UserContext } from '../App';
import LoadingComponent from '../components/LoadingComponent';
import WarningComponent from '../components/WarningComponent';
import ErrorComponent from '../components/ErrorComponent';
const Login = () => {
const { login } = useContext(UserContext);
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
const [warning, setWarning] = useState(null);
const [error, setError] = useState(null);
const userName = useRef('');
const userPassword = useRef('');
const handleLogin = async () => {
// reset upozorenja
setLoading(true);
setWarning(null);
setError(null);
try {
// validacija unosa
if (userName.current === '' || userPassword.current === '') {
return setWarning('Molim Vas da upišete korisničko ime i lozinku!');
}
// fetch korisnika sa bekenda
let response = await fetch(`http://localhost:8080/api/v1/login?username=${userName.current}&password=${userPassword.current}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
});
if (response.ok) {
const user = await response.json();
login(user);
navigate('/');
}
else {
// hvatanje neuspesnog HTTP odgovora
if (response.status === 401) {
setWarning(`Pogrešno korisničko ime ili lozinka (HTTP kod: ${response.status})`);
}
else {
setWarning(`Zahtev ka serveru nije bio uspešan (HTTP kod: ${response.status})`);
}
}
} catch (error) {
// hvatanje greski van HTTP odgovora
setError(new Error(error));
}
finally {
// reset upozorenja
setLoading(false);
}
};
return (
<Container
sx={{
display: 'flex',
flexDirection: 'column',
flexWrap: 'wrap',
justifyContent: 'center',
alignContent: 'center',
mt: 5,
}}
>
<Box
sx={{
display: 'flex',
flexDirection: 'column',
flexWrap: 'wrap',
justifyContent: 'center',
alignContent: 'center',
mb: 5,
}}
>
<img src={logo} className='logo' alt='logo' />
<Typography variant='h4' textAlign={'center'} mb={6}>Dobrodošli u eDnevnik</Typography>
<TextField
id='username'
label='korisničko ime'
variant='outlined'
sx={{ mb: 3 }}
onChange={(e) => userName.current = e.target.value}
/>
<TextField
id='password'
label='lozinka'
type='password'
variant='outlined'
sx={{ mb: 3 }}
onChange={(e) => userPassword.current = e.target.value}
/>
<Button onClick={handleLogin}>Login</Button>
</Box>
<Box
sx={{ alignSelf: 'center' }}
>
{loading && <LoadingComponent loading={loading} />}
{warning && <WarningComponent warning={warning} />}
{error && <ErrorComponent error={error.message} />}
</Box>
</Container>
);
};
export default Login;
|
import React from 'react';
import { useState } from 'react';
function ClickButtonPost() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
alert('You like me!');
}
return (
<button onClick={handleClick}>
On_On -- It's me!
Give likes {count} times
</button>
);
}
function submitForm() {
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const formData = { name, email };
console.log('FormData:', formData);
fetch('http://localhost:3001/submit-form', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
})
.then(response => response.json())
.then(data => console.log('Server response:', data))
.catch(error => console.error('Error:', error));
}
function UserPost({ username, image, caption, id }) {
return (
<div className="post">
<div className="post-image-container">
<img
src={image}
alt={caption}
style={{ width: '200px', height: '200px', objectFit: 'cover' }}
/>
</div>
<div className="post-content">
<p className="post-username">
<strong>{username}</strong>:
</p>
<p className="post-caption">{caption}</p>
<div className="Profile">
<ClickButtonPost />
<ClickButtonPost />
</div>
</div>
<p>
<strong>{username}</strong>: {caption}{id}
</p>
</div>
);
}
export default UserPost;
|
package com.example.myroom.activities
import com.example.myroom.helpclasses.MeetingRoomAdapter
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.myroom.database.DatabaseManager
import com.example.myroom.database.repositories.MeetingRoomRepository
import com.example.myroom.modelfactories.ListViewModelFactory
import com.example.myroom.viewmodels.ListViewModel
import android.content.Intent
import com.example.myroom.R
class ListActivity : AppCompatActivity() {
private lateinit var viewModel: ListViewModel
private lateinit var recyclerView: RecyclerView
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_list)
val meetingRoomDao = DatabaseManager.getDatabase(this).meetingRoomDao()
val repository = MeetingRoomRepository(meetingRoomDao)
viewModel = ViewModelProvider(this, ListViewModelFactory(repository)).get(ListViewModel::class.java)
viewModel.initializeData()
recyclerView = findViewById(R.id.roomsList)
recyclerView.layoutManager = LinearLayoutManager(this)
val adapter = MeetingRoomAdapter { room ->
val intent = Intent(this, RoomDetailsActivity::class.java)
intent.putExtra("roomId", room.id)
startActivity(intent)
}
recyclerView.adapter = adapter
viewModel.meetingRooms.observe(this, { meetingRooms ->
adapter.submitList(meetingRooms)
})
}
}
|
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="root" value="${pageContext.request.contextPath}" />
<!DOCTYPE html>
<html lang="fr">
<head>
<jsp:include page="includes/head.jsp">
<jsp:param name="title" value="Mes offres" />
</jsp:include>
<link rel="stylesheet" href="${root}/css/pickadate.css">
<link rel="stylesheet" href="${root}/css/pickadate.date.css">
</head>
<body class="mCustomScrollbar" data-mcs-theme="dark">
<jsp:include page="includes/header.jsp" />
<div class="ui grid container">
<jsp:include page="includes/nav.jsp">
<jsp:param name="offres" value="active" />
<jsp:param name="userId" value="${currentUser.id}" />
</jsp:include>
<section id="main-section">
<h2 class="ui center aligned icon header offer-modal-link" id="add-offer">
<i class="circular configure icon"></i>
Ajouter une offre
</h2>
<div class="ui middle aligned divided list">
<c:forEach items="${listService}" var="item">
<div class="item">
<div class="right floated content">
<div id="list-elt-${item.id}-button" class="ui inverted orange button list-elt-button">Afficher</div>
<div class="ui inverted brown button offer-modal-link">Modifier</div>
<div class="ui inverted red button delete-btn">Supprimer</div>
<input type="hidden" value="${item.id}">
</div>
<i class="large configure middle aligned icon"></i>
<div class="content">
<span class="bold">${item.name}</span>
<div class="description">Ajouté récemment</div>
</div>
</div>
</c:forEach>
</div>
<c:forEach items="${listService}" var="item">
<div id="list-elt-${item.id}" class="ui segment list-elt" style="display:none;">
<h3>${item.name}</h3>
<p>${item.description}</p>
</div>
</c:forEach>
</section>
</div>
<!-- Pop-ups -->
<div id="offer-modal" class="ui small modal">
<div class="ui icon header">
Ajouter/Modifier une offre
</div>
<div class="content">
<form method="post" action="ajoutService" class="ui form">
<div class="field">
<label>Type <span class="mandatory">*</span></label>
<div class="ui search">
<div class="ui icon input">
<input name="type" class="prompt" placeholder="Type de service que vous pouvez rendre" type="text">
<i class="search icon"></i>
</div>
</div>
</div>
<div class="field">
<label>Description <span class="mandatory">*</span></label>
<textarea name="description" placeholder="Description du service que vous pouvez rendre"></textarea>
</div>
<div class="field">
<label>Date limite</label>
<input class="datepicker" name="deadline" placeholder="Date limite du service que vous pouvez rendre" type="text">
</div>
<span class="mandatory">* Champs requis</span>
<input type="hidden" name="needOrOffer" value="offer">
<input type="hidden" name="publicationDate" value="12/01/2016">
<input type="hidden" id="serviceId" name="serviceId">
<input type="hidden" name="mode" value="insert">
</form>
</div>
<div class="actions ui grid container">
<div class="ui black cancel button">
<i class="remove icon"></i>
Annuler
</div>
<div class="ui orange ok button">
<i class="checkmark icon"></i>
Valider
</div>
</div>
</div>
<div class="ui small modal delete-list-elt">
<div class="ui icon header">
<i class="warning sign icon"></i>
Voulez-vous vraiment supprimer cette offre ?
</div>
<div class="actions ui grid container">
<div class="ui black cancel button">
<i class="remove icon"></i>
Non
</div>
<div class="ui orange ok button">
<i class="checkmark icon"></i>
Oui
</div>
</div>
</div>
<jsp:include page="includes/modals.jsp" />
<jsp:include page="includes/scripts.jsp" />
<script src="${root}/js/formValidation.js"></script>
<script src="${root}/js/pickadate-legacy.js"></script>
<script src="${root}/js/pickadate.js"></script>
<script src="${root}/js/pickadate.date.js"></script>
<script src="${root}/js/pickadate-fr_FR.js"></script>
<script>
$( document ).ready(function() {
$( ".datepicker" ).pickadate();
});
</script>
</body>
</html>
|
package cn.feng.thinkInJava.a7_3_持有对象.holding.b_11_10_00.Map.b_11_10_02.exercise;// holding/Ex25.java
// TIJ4 Chapter Holding, Exercise 25, page 423
/* Create a Map<String, ArrayList<Integer>>. Use net.mindview.TextFile
* to open a text file and read it in a word at a time (use "\\W+\" as
* the second argument to the TextFile constructor). Count the words as
* you read them in, and for each word in the file, record in the
* ArrayList<Integer> the word count associated with that word - that is,
* in effect, the location in the file where that word was found.
*/
import net.mindview.util.TextFile;
import java.util.*;
/**
* 创建一个Map<String.ArrayList<Integer>>使用net.mindview.TextFile来打开一个文本文件,并一次读入一个单词 (use "\\W+\" as
* the second argument to the TextFile constructor).在读入单词时对他们进行技术,并且对文件中的每一个单词,都在ArrayList<Integer>
* 中记录下与单词相关联的单词计数,实际上它记录的是该单词在文件中被发现的位置
* <p>
* <p>
* *
*/
public class Ex25 {
public static void main(String[] args) {
Map<String, ArrayList<Integer>> m = new LinkedHashMap<String, ArrayList<Integer>>();
List<String> words = new LinkedList<String>();
words.addAll(new TextFile("SetOperations.java", "\\W+"));
System.out.println("Words in file: " + words);
Iterator itWords = words.iterator();
int count = 0;
while (itWords.hasNext()) {
String s = (String) itWords.next();
count++;
if (!m.keySet().contains(s)) {
ArrayList<Integer> ai = new ArrayList<Integer>();
ai.add(0, count);
m.put(s, ai);
} else {
m.get(s).add(count);
m.put(s, m.get(s));
}
}
System.out.println("Map of word locations: " + m);
}
}
|
package L12_ExamPreparation.Prep3;
import java.util.*;
public class P03NeedForSpeed {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Map<String, List<Integer>> carsMap = new LinkedHashMap<>();
int n = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < n; i++) {
String[] carInfo = scanner.nextLine().split("\\|");
carsMap.put(carInfo[0], new ArrayList<>());
carsMap.get(carInfo[0]).add(Integer.parseInt(carInfo[1]));
carsMap.get(carInfo[0]).add(Integer.parseInt(carInfo[2]));
}
String command = scanner.nextLine();
while (!command.equals("Stop")){
String[] commandLine = command.split(" : ");
switch (commandLine[0]){
case "Drive":
int distance = Integer.parseInt(commandLine[2]);
int fuel = Integer.parseInt(commandLine[3]);
if (carsMap.get(commandLine[1]).get(1) < fuel){
System.out.println("Not enough fuel to make that ride");
} else {
carsMap.get(commandLine[1]).set(0, carsMap.get(commandLine[1]).get(0) + distance);
carsMap.get(commandLine[1]).set(1, carsMap.get(commandLine[1]).get(1) - fuel);
System.out.printf("%s driven for %d kilometers. %d liters of fuel consumed.%n", commandLine[1],distance, fuel);
}
if (carsMap.get(commandLine[1]).get(0) >= 100000){
carsMap.remove(commandLine[1]);
System.out.printf("Time to sell the %s!%n", commandLine[1]);
}
break;
case "Refuel":
int fuelToRefill = Integer.parseInt(commandLine[2]);
if (carsMap.get(commandLine[1]).get(1) + fuelToRefill > 75){
int maxFuel = 75 - carsMap.get(commandLine[1]).get(1);
carsMap.get(commandLine[1]).set(1, 75);
System.out.printf("%s refueled with %d liters%n", commandLine[1], maxFuel);
} else {
carsMap.get(commandLine[1]).set(1,carsMap.get(commandLine[1]).get(1) + fuelToRefill);
System.out.printf("%s refueled with %s liters%n", commandLine[1], fuelToRefill);
}
break;
case "Revert":
int kilometers = Integer.parseInt(commandLine[2]);
carsMap.get(commandLine[1]).set(0, carsMap.get(commandLine[1]).get(0) - kilometers);
if (carsMap.get(commandLine[1]).get(0) < 10000){
carsMap.get(commandLine[1]).set(0, 10000);
} else {
System.out.printf("%s mileage decreased by %d kilometers%n", commandLine[1], kilometers);
}
break;
}
command = scanner.nextLine();
}
carsMap.entrySet().stream().forEach(e -> System.out.printf("%s -> Mileage: %d kms, Fuel in the tank: %d lt.%n",
e.getKey(), e.getValue().get(0), e.getValue().get(1)));
}
}
|
import { ArgumentParser } from 'argparse'
import kleur from 'kleur'
import prompts from 'prompts'
import ProgressBar from 'progress'
import { getFileTransactions, getTransactions, Transaction } from './bank'
import { getAccounts, importTransaction } from './firefly'
import { convertTransaction } from './convert'
import { getAccountList, getConfigForIBAN } from './config'
import { formatIBAN } from './utils'
const parser = new ArgumentParser({description: 'Firefly III importer'})
parser.add_argument('--config', { help: 'config file in YAML format', required: true })
parser.add_argument('--months', { help: 'count of past months to import' })
parser.add_argument('--start_date', { help: 'start date to import from Bank (YYYY-MM-DD)' })
parser.add_argument('--end_date', { help: 'end date to import from Bank (YYYY-MM-DD)' })
parser.add_argument('--import_file', { help: '', })
parser.add_argument('-n', { action: 'store_const', const: true, help: 'run non-interactively', })
const group = parser.add_mutually_exclusive_group({required: true})
group.add_argument('--iban', { help: 'The Account to select' })
group.add_argument('--all', { action: 'store_const', const: true, help: 'run all configured accounts', })
const args = parser.parse_args()
async function runAccount(iban: string, startDate: Date, endDate: Date) {
const config = getConfigForIBAN(iban, args.config)
const fireflyAccounts = await getAccounts(config.firefly.url, config.firefly.token)
const fireflyAccount = fireflyAccounts.find(a => parseInt(a.id) == config.firefly.accountId)
if(!fireflyAccount) {
throw new Error(`No Firefly III account found with id '${args.account_id}'`)
}
console.log(kleur.bold(' Config: ')+config.name)
console.log(kleur.bold(' IBAN: ')+formatIBAN(iban))
console.log(kleur.bold('Firefly-Account: ')+fireflyAccount.attributes.name+` (${config.firefly.accountId})`)
console.log(kleur.bold(' Firefly-Server: ')+config.firefly.url)
if(fireflyAccount.attributes.iban !== iban) {
console.log(kleur.bold(' Firely-IBAN: ')+formatIBAN(fireflyAccount.attributes.iban))
throw new Error('IBAN of firefly account does not match the bank IBAN. wrong account configured?')
}
let txs: Transaction[] = []
if(args.import_file) {
console.log(`loading transactions from ${args.import_file}`)
txs = getFileTransactions(args.import_file)
} else {
console.log(`get transactions from bank (${config.bank.blz})`)
txs = await getTransactions(config.bank, startDate, endDate, iban)
}
txs = txs.filter(tx => tx.amount)
if(!txs.length) {
console.log('No transactions found')
return
}
const first = txs[0]
const last = txs[txs.length-1]
console.log(`found ${txs.length} transactions (${first.valueDate} - ${last.valueDate})`)
if(!args.n) {
const con = await prompts({
type: 'confirm',
name: 'value',
message: 'Execute import?',
initial: true
})
if(!con.value) {
process.exit()
}
}
const bar = new ProgressBar('importing :bar :current/:total', {
width: 20,
total: txs.length,
complete: '\u2588',
incomplete: '\u2591'
})
let newlyCount = 0
for(let tx of txs) {
const convertedTx = convertTransaction(tx, config.firefly.accountId)
const newly = await importTransaction(
config.firefly.url,
config.firefly.token,
convertedTx
)
if(newly) newlyCount++
bar.tick()
}
console.log(kleur.bold('Result: ')+`${newlyCount} new, ${txs.length-newlyCount} duplicated`)
}
void async function main() {
try {
let endDate = new Date();
let startDate = new Date(endDate);
if(args.months && (args.start_date || args.end_date)) {
throw new Error(`can't use argument --months together with --start_date or --end_date`)
}
startDate.setMonth(startDate.getMonth()-(parseInt(args.months) || 3))
startDate.setDate(startDate.getDate()+2)
if(!args.months) {
if(args.start_date) {
if(!args.start_date.match(/^\d{4}-\d{2}-\d{2}$/)) throw new Error('invalid start date provided. it must be in form YYYY-MM-DD')
startDate = new Date(args.start_date)
}
if(args.end_date) {
if(!args.end_date.match(/^\d{4}-\d{2}-\d{2}$/)) throw new Error('invalid end date provided. it must be in form YYYY-MM-DD')
endDate = new Date(args.end_date)
}
}
if(args.all) {
if(args.import_file) {
throw new Error(`importing a file to all accounts doesn't make any sense. please specify a single one with --iban`)
}
const accounts = getAccountList(args.config)
for(let account of accounts) {
await runAccount(account.bank_iban, startDate, endDate)
}
} else {
await runAccount(args.iban, startDate, endDate)
}
} catch(err) {
console.log(kleur.red().bold(err.name+': ')+err.message)
console.log(kleur.blue().dim(err.stack.split('\n').slice(1,4).join('\n')))
}
}()
|
%%%-------------------------------------------------------------------
%%% @author Sergey Penkovsky
%%% @copyright (C) 2015, Sergey Penkovsky <[email protected]>
%%% @doc
%%% Erlymon is an open source GPS tracking system for various GPS tracking devices.
%%%
%%% Copyright (C) 2015, Sergey Penkovsky <[email protected]>.
%%%
%%% This file is part of Erlymon.
%%%
%%% Erlymon is free software: you can redistribute it and/or modify
%%% it under the terms of the GNU Affero General Public License, version 3,
%%% as published by the Free Software Foundation.
%%%
%%% Erlymon is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
%%% GNU Affero General Public License for more details.
%%%
%%% You should have received a copy of the GNU Affero General Public License
%%% along with this program. If not, see <http://www.gnu.org/licenses/>.
%%% @end
%%%-------------------------------------------------------------------
-module(erlymon_sup).
-author("Sergey Penkovsky <[email protected]>").
-behaviour(supervisor).
%% API
-export([start_link/0]).
%% Supervisor callbacks
-export([init/1]).
-define(SERVER, ?MODULE).
%% API functions
-spec start_link() -> supervisor:startlink_ret().
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
%% Supervisor callbacks
%% Child :: {Id,StartFunc,Restart,Shutdown,Type,Modules}
-spec init(Args :: list()) -> {ok, tuple()}.
init([]) ->
{ok, EmStorageEnv} = application:get_env(erlymon, em_storage),
StorageType = proplists:get_value(type, EmStorageEnv),
StorageSettings = proplists:get_value(settings, EmStorageEnv),
{ok, EmGeocoderEnv} = application:get_env(erlymon, em_geocoder),
GeocoderType = proplists:get_value(type, EmGeocoderEnv),
GeocoderSettings = proplists:get_value(settings, EmGeocoderEnv),
SupFlags = #{strategy => one_for_one, intensity => 1000, period => 3600},
ChildSpecs = [
#{
id => em_regexp_sup,
start => {em_regexp_sup, start_link, []},
restart => permanent,
shutdown => 3000,
type => supervisor,
modules => dynamic
},
#{
id => em_timer,
start => {em_timer, start_link, []},
restart => permanent,
shutdown => 3000,
type => worker,
modules => [em_timer]
},
#{
id => em_storage_sup,
start => {em_storage_sup, start_link, [StorageType, StorageSettings]},
restart => permanent,
shutdown => 3000,
type => supervisor,
modules => dynamic
},
#{
id => em_manager_sup,
start => {em_manager_sup, start_link, []},
restart => permanent,
shutdown => 3000,
type => supervisor,
modules => dynamic
},
#{
id => em_geocoder_sup,
start => {em_geocoder_sup, start_link, [GeocoderType, GeocoderSettings]},
restart => permanent,
shutdown => 3000,
type => supervisor,
modules => dynamic
},
#{
id => em_stats,
start => {em_stats, start_link, []},
restart => permanent,
shutdown => 3000,
type => worker,
modules => [em_stats]
}
],
{ok, {SupFlags, ChildSpecs}}.
%% Internal functions
|
import { FC, useEffect, useState } from "react";
import { Box, ImageList, ImageListItem } from "@mui/material";
import { motion } from "framer-motion";
import PhotoItem from "../PhotoItem";
import NoItemsFound from "./NoItemsFound";
import { Photo } from "../../types/types";
type P = {
items: Photo[];
};
const muiBreakPoints = [
{ size: 0 },
{ size: 600 },
{ size: 900 },
{ size: 1200 },
{ size: 1536 },
];
const ImageListWrapper: FC<P> = ({ items }) => {
const getViewW = () => {
const { innerWidth: width } = window;
return width;
};
const [w, setw] = useState(0);
const [decideColCount, setdecideColCount] = useState(1);
useEffect(() => {
const handleResize = () => setw(getViewW());
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
const calcColCount = () => {
muiBreakPoints.forEach(({ size }, index: number, muiBreakPoints) => {
const lastItem = () => {
if (muiBreakPoints[index + 1]) {
return muiBreakPoints[index + 1].size;
}
return muiBreakPoints[index - 1].size;
};
if (w > size && w < lastItem()) {
setdecideColCount(index + 1);
} else if (w > size && w > lastItem()) {
setdecideColCount(muiBreakPoints.length);
}
});
};
useEffect(() => {
calcColCount();
}, [w]);
useEffect(() => {
setw(getViewW());
calcColCount();
}, []);
const initialLoad = {
start: { opacity: 0 },
end: { opacity: 1 },
};
return (
<motion.div
variants={initialLoad}
initial={initialLoad.start}
animate={initialLoad.end}
>
{items ? (
<Box width="100%">
<ImageList
variant="masonry"
cols={decideColCount}
sx={{ px: 3, py: 1 }}
>
{items.map((item) => (
<ImageListItem key={item.id}>
<PhotoItem item={item} />
</ImageListItem>
))}
</ImageList>
</Box>
) : (
<NoItemsFound />
)}
</motion.div>
);
};
export default ImageListWrapper;
|
package com.jskako.permission
import android.Manifest.permission.*
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.jskako.permission.ui.theme.PermissionTheme
class MainActivity : ComponentActivity() {
private val permissionsToRequest = arrayOf(
RECORD_AUDIO,
CALL_PHONE,
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
PermissionTheme {
val viewModel = viewModel<MainViewModel>()
val dialogQueue = viewModel.visiblePermissionDialogQueue
val cameraPermissionResultLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission(),
onResult = { isGranted ->
viewModel.onPermissionResult(
permission = CAMERA,
isGranted = isGranted
)
}
)
val multiplePermissionResultLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestMultiplePermissions(),
onResult = { perms ->
permissionsToRequest.forEach { permission ->
viewModel.onPermissionResult(
permission = permission,
isGranted = perms[permission] == true
)
}
}
)
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Button(onClick = {
cameraPermissionResultLauncher.launch(
CAMERA
)
}) {
Text(text = "Request one permission")
}
Spacer(modifier = Modifier.height(16.dp))
Button(onClick = {
multiplePermissionResultLauncher.launch(permissionsToRequest)
}) {
Text(text = "Request multiple permission")
}
}
dialogQueue
.reversed()
.forEach { permission ->
PermissionDialog(
permissionTextProvider = when (permission) {
CAMERA -> {
CameraPermissionTextProvider()
}
RECORD_AUDIO -> {
RecordAudioPermissionTextProvider()
}
CALL_PHONE -> {
PhoneCallPermissionTextProvider()
}
else -> return@forEach
},
isPermanentlyDeclined = !shouldShowRequestPermissionRationale(
permission
),
onDismiss = viewModel::dismissDialog,
onOkClick = {
viewModel.dismissDialog()
multiplePermissionResultLauncher.launch(
arrayOf(permission)
)
},
onGoToAppSettingsClick = ::openAppSettings
)
}
}
}
}
}
fun Activity.openAppSettings() {
Intent(
ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", packageName, null)
).also(::startActivity)
}
|
<template>
<div>
<Header />
<h1>Welcome {{ username }}</h1>
<table id="customers">
<tr>
<th>Name</th>
<th>Address</th>
<th>Contact</th>
<th>Actions</th>
</tr>
<tr v-for="(res,index) in restaurants" :key="index">
<td>{{ res.name }}</td>
<td>{{ res.address }}</td>
<td>{{ res.contact }}</td>
<td><router-link :to="`/update/${res.id}`">Update</router-link>
<button @click.prevent="removeRestaurant(res.id)">Delete</button>
</td>
</tr>
</table>
</div>
</template>
<script>
import Header from "./Header.vue";
import axios from "axios";
export default {
name: "Home",
data() {
return {
username: null,
restaurants: [],
};
},
components: { Header },
methods: {
async removeRestaurant(id)
{
let response = await axios.delete(`http://localhost:3000/restaurants/${id}`);
if(response.status == 200)
{
this.fetchRestaurants("http://localhost:3000/restaurants");
}else{
alert("Delete Error! ");
}
},
checkLogin() {
let user = localStorage.getItem("user-info");
user = JSON.parse(user);
if (user) {
this.username = user.name;
console.log(this.username);
}
return user ? true : false;
},
async fetchRestaurants(url) {
let response = await axios.get(url);
let restaurants = await response.data;
this.restaurants = restaurants;
console.log(restaurants);
},
},
mounted() {
let login = this.checkLogin();
if (!login) {
this.$router.push({ name: "SignUp" });
}
this.fetchRestaurants("http://localhost:3000/restaurants");
},
watcher:{
}
};
</script>
<style >
h1{
text-align: center;
}
div {
padding: 0px;
margin: 0px;
}
#customers {
font-family: Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 80%;
margin-left: 10%;
}
#customers td,
#customers th {
border: 1px solid #ddd;
padding: 8px;
}
#customers tr:nth-child(even) {
background-color: #f2f2f2;
}
#customers tr:hover {
background-color: #ddd;
}
#customers th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #04aa6d;
color: white;
}
</style>
|
//
// ViewController.swift
// CollectionViewTest
//
// Created by Craig Clayton on 6/30/17.
// Copyright © 2017 Cocoa Academy. All rights reserved.
//
import UIKit
class ExploreViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
let manager = ExploreDataManager()
var selectedCity: LocationItem?
var headerView: ExploreHeaderView!
fileprivate let minItemSpacing: CGFloat = 7
override func viewDidLoad() {
super.viewDidLoad()
initialize()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: false)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case Segue.locationList.rawValue:
showLocationList(segue: segue)
case Segue.restaurantList.rawValue:
showRestaurantList(segue: segue)
default:
print("Segue not added")
}
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if identifier == Segue.restaurantList.rawValue {
guard selectedCity != nil else {
showAlert()
return false
}
return true
}
return true
}
}
//MARKER: private extension
private extension ExploreViewController {
func initialize() {
manager.fetch()
setupCollectionView()
}
func setupCollectionView() {
let flow = UICollectionViewFlowLayout()
flow.sectionInset = UIEdgeInsets(top: 7, left: 7, bottom: 7, right: 7)
flow.minimumInteritemSpacing = 0
flow.minimumLineSpacing = 7
collectionView?.collectionViewLayout = flow
}
func showLocationList(segue: UIStoryboardSegue) {
guard let navController = segue.destination as? UINavigationController,
let viewController = navController.topViewController as? LocationViewController
else { return }
guard let city = selectedCity else { return }
viewController.selectedCity = city
}
func showRestaurantList(segue: UIStoryboardSegue) {
if let desViewController = segue.destination as? RestaurantListViewController,
let city = selectedCity, let index = collectionView.indexPathsForSelectedItems?.first {
desViewController.selectedType = manager.getItem(at: index).name
desViewController.selectedCity = city
}
}
func showAlert() {
let alertContoller = UIAlertController(title: "Location Needed", message: "Please select a location", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertContoller.addAction(okAction)
present(alertContoller, animated: true, completion: nil)
}
// Add Unwind here
@IBAction func unwindLocationCancel(segue:UIStoryboardSegue) {}
@IBAction func unwindLocationDone(segue: UIStoryboardSegue) {
if let viewController = segue.source as? LocationViewController {
selectedCity = viewController.selectedCity
if let location = selectedCity {
headerView.locationLabel.text = location.full
}
}
}
}
//MARKER: data source
extension ExploreViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath)
headerView = header as? ExploreHeaderView
return headerView
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "exploreCell", for: indexPath) as! ExploreCell
let item = manager.getItem(at: indexPath)
cell.categoryName.text = item.name
cell.imgExplore.image = UIImage(named: item.image)
return cell
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return manager.numberOfItems()
}
}
//MARKER: delegate
extension ExploreViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if Device.isPad {
let factor = traitCollection.horizontalSizeClass == .compact ? 2 : 3
let screenRect = collectionView.frame.size.width
let screenWidth = screenRect - (CGFloat(minItemSpacing) * CGFloat(factor + 1))
let cellWidth = screenWidth / CGFloat(factor)
return CGSize(width: cellWidth, height: 195)
} else {
let screenRect = collectionView.frame.size.width
let screenWidth = screenRect - 21
let cellWidth = screenWidth / 2.0
return CGSize(width: cellWidth, height: 195)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: self.collectionView.frame.width, height: 100)
}
}
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class TextApp extends StatelessWidget {
final String text;
final double fontSize;
final FontWeight fontWeight;
TextApp({
required this.text,
this.fontSize = 16,
this.fontWeight = FontWeight.normal,
});
@override
Widget build(BuildContext context) {
return Text(
text,
style: TextStyle(
fontFamily: 'Sport',
fontSize: fontSize,
fontWeight: fontWeight,
),
);
}
}
|
package com.uniroma3.esamesiw2024.security;
import com.uniroma3.esamesiw2024.entity.Credentials;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.session.HttpSessionEventPublisher;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.sql.DataSource;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Autowired
DataSource datasource;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((authz) -> authz
.requestMatchers(HttpMethod.GET,"/","/index", "/static/**", "/css/**", "/js/**", "/images/**", "/squadra/get-all-squadra-ui/**", "/squadra/get-squadra/**", "/register", "/giocatore/get-all-giocatore-ui/**").permitAll()
.requestMatchers(HttpMethod.POST, "/login", "/register").permitAll()
.requestMatchers(HttpMethod.GET, "/squadra/form-squadra-update-admin/{id}/").hasRole(Credentials.ADMIN_ROLE)
.requestMatchers(HttpMethod.POST, "/squadra/update-squadra-ui/{id}/").hasRole(Credentials.ADMIN_ROLE)
.requestMatchers(HttpMethod.GET, "/squadra/formPlayer/{idSquadra}/").hasRole(Credentials.PRESIDENTE_ROLE)
.requestMatchers(HttpMethod.POST, "/squadra/add-player-ui/{idSquadra}/").hasRole(Credentials.PRESIDENTE_ROLE)
.anyRequest().authenticated());
/*.requestMatchers(HttpMethod.POST,"/basic/**", "/basic/login", "/basic/register").permitAll()
//.requestMatchers(HttpMethod.GET, "/user/**", "/**").hasAnyAuthority(DEFAULT_ROLE)
//.requestMatchers(HttpMethod.POST, "/user/**", "/user/formNewPersonaggio").hasAnyAuthority(DEFAULT_ROLE)
.anyRequest().authenticated());*/
http.formLogin((form) ->form
.loginPage("/login")
.defaultSuccessUrl("/success")
.permitAll());
http.logout((logout) -> logout
.logoutSuccessUrl("/")
.logoutUrl("/logout")
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.invalidateHttpSession(true)
.clearAuthentication(true)
.deleteCookies("JSESSIONID")
.permitAll());
HttpSessionRequestCache req = new HttpSessionRequestCache();
req.setMatchingRequestParameterName(null);
http.requestCache((cache) -> cache
.requestCache(req));
http.exceptionHandling((exceptionHandling) -> exceptionHandling
.accessDeniedPage("/login"));
http.csrf(AbstractHttpConfigurer::disable);
return http.build();
}
//---------- SINGOLO UTENTE SCOLPITO ----------------------------
@Bean
public UserDetailsService userDetailsService() {
UserDetails user =
User.withUsername("presidente")
.username("presidente")
.password(passwordEncoder().encode("password"))
.roles("PRESIDENTE")
.build();
return new InMemoryUserDetailsManager(user);
}
//---------- FINE SINGOLO UTENTE SCOLPITO ----------------------------
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SessionRegistry sessionRegistry() {
return new SessionRegistryImpl();
}
@Bean
public HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
@Bean
@Primary
public AuthenticationManagerBuilder configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.dataSource(this.datasource)
//query per recuperare username e ruolo
.authoritiesByUsernameQuery("SELECT username, role FROM credentials WHERE username=?")
//query per username e password. Il flag boolean flag specifica se l'utente user è abilitato o no (va sempre a true)
.usersByUsernameQuery("SELECT username, password, 1 as enabled FROM credentials WHERE username=?");
return auth;
}
}
|
require 'spec_helper'
describe "Authentication" do
subject { page }
describe "signin page" do
before { visit signin_path }
it { should have_content('Sign in') }
it { should have_title('Sign in') }
it { should have_selector('div.alert.alert-error')}
it { should respond_to(:password_confirmation) }
it { should respond_to(:remember_token) }
it { should respond_to(:authenticate) }
describe "after visiting another page" do
before { click_link "Home" }
it { should_not have_selector('div.alert.alert-error') }
end
describe "with valid information" do
let(:user) {FactoryGirl.create(:user)}
before do
fill_in "Email", with: user.email.upcase
fill_in "Password", with: user.password
click_button "Sign in"
end
it { should have_title(user.name) }
it { should have_link('Profile', href: user_path(user)) }
it { should have_link('Sign out', href: signout_path) }
it { should_not have_link('Sign in', href: signin_path) }
end
end
end
|
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<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>Demo</title>
<style>
body {
background-color:black;
color:white;
}
.main {
text-align:center;
position: fixed;
top:50%;
left:50%;
transform: translate(-50%, -50%);
border: 1px solid gray;
border-radius:10px;
min-width: 500px;
width:25%;
padding:5%;
}
.main input{
font-family: monospace;
}
.main .btn {
font-family: monospace;
}
.answers {
text-align: center;
font-family: monospace;
background-color: white;
color:white;
background-color:gray;
border-radius:3px;
padding:5px;
min-width:300px;
width: 20%;
position:absolute;
top:80%;
left:50%;
transform: translate(-50%, -50%)
}
.answers h4 {
font-weight: bold;
}
</style>
</head>
<body>
<div class='main'>
<h1 id="header">
Quadratic Calculator
</h1>
<div class="form was-validated">
<form class='input'>
<div>
<div class="form-group">
<label for='x'>Coefficient of x^2</label>
<input class='form-control' id='var_x' type="number" name='x' placeholder='x'>
</div>
<div class="form-group">
<label for='y'>Coefficient of x</label>
<input class='form-control' id='var_y' type="number" name='y' placeholder='y'>
</div>
<div class="form-group">
<label for='z'>Constant</label>
<input class='form-control' id='var_z' type="number" name='z' placeholder='z'>
</div>
<button class='btn btn-primary' type="button" onclick="run_quad()">Calculate</button>
</div>
</div>
</form>
</div>
<div class="answers">
<h4 id="value">Value = 0</h4>
</div>
</div>
</body>
<script>
let statement = 'Kindly Input the following variables...';
let header_change = function(new_header) {
let item = document.getElementById('header');
item.innerHTML = new_header;
console.log('header changed! to ' + new_header);
}
function val_change(new_val) {
var item = document.getElementById('value');
console.log(item.innerHTML);
item.innerHTML = `Value(s) = ${new_val[0]} and ${new_val[1]}`;
console.log(`value changed! to ${new_val}`);
}
function quadratic(a,b,c) {
let positive_ans = ((-b) + ((b**2)-(4*a*c)**-1) /2*c);
let negative_ans = ((-b) - ((b**2)-(4*a*c)**-1) /2*c);
return [positive_ans, negative_ans];
}
function run_quad() {
let var_x = document.getElementById('var_x').value;
let var_y = document.getElementById('var_y').value;
let var_z= document.getElementById('var_z').value;
let item = document.getElementById('value')
if (var_x == 0 || var_y == 0 || var_z == 0){
item.innerHTML = 'Provide an integer other than \'0\''
}
else if (var_x && var_y && var_z) {
let ans = quadratic(var_x, var_y, var_z);
val_change(ans);
console.log('Success!');
}
else {
item.innerHTML = 'Provide all values as integers and retry';
}
}
</script>
</html>
|
import { useEffect, useCallback, MutableRefObject } from 'react';
export function useClickOutside(
subject: Element | MutableRefObject<Element> | HTMLElement | null,
callback: () => void
) {
const getElement = (elementOrRef: Element | MutableRefObject<Element>) => {
if (elementOrRef instanceof Element) {
return elementOrRef;
}
return elementOrRef.current;
};
const handleClick = useCallback(
(event: MouseEvent) => {
const element = subject && getElement(subject);
if (element && !element.contains(event.target as Element)) {
callback();
}
},
[callback, subject]
);
useEffect(
() => {
document.addEventListener('mousedown', handleClick);
return () => {
document.removeEventListener('mousedown', handleClick);
};
},
[subject, callback, handleClick]
);
}
|
import { useEffect, useState } from 'react';
import { useMovies } from './useMovies';
import { useLocalStorageState } from './useLocalStorageState';
import NavBar from './components/NavBar';
import Search from './components/Search';
import NumResults from './components/NumResults';
import Main from './components/Main';
import MovieList from './components/MovieList';
import Loader from './components/Loader';
import Box from './components/Box';
import MovieDetails from './components/MovieDetails';
import WatchedSummary from './components/WatchedSummary';
import WatchedMovieList from './components/WatchedMovieList';
import ErrorMessage from './components/ErrorMessage';
const KEY = 'f84fc31d';
export default function App() {
const [query, setQuery] = useState('');
const [selectedId, setSelectedId] = useState(null);
const { movies, isLoading, error } = useMovies(query, handleCloseMovie);
const [watched, setWatched] = useLocalStorageState([], 'watched');
// const [watched, setWatched] = useState(function () {
// const storedValue = localStorage.getItem('watched');
// return JSON.parse(storedValue);
// });
//
// useEffect(
// function () {
// localStorage.setItem('watched', JSON.stringify(watched));
// },
// [watched]
// );
function handleSelectMovie(id) {
setSelectedId((selectedId) => (id === selectedId ? null : id));
}
function handleCloseMovie() {
setSelectedId(null);
}
function handleAddWatch(movie) {
setWatched((watched) => [...watched, movie]);
// localStorage.setItem('watched', JSON.stringify([...watched, movie]));
}
function handleDeleteWatched(id) {
setWatched((watched) => watched.filter((movie) => movie.imdbID !== id));
}
return (
<>
<NavBar>
<Search query={query} setQuery={setQuery} />
<NumResults movies={movies} />
</NavBar>
<Main>
<Box>
{/* {isLoading ? <Loader /> : <MovieList movies={movies} />} */}
{isLoading && <Loader />}
{!isLoading && !error && (
<MovieList movies={movies} onSelectMovie={handleSelectMovie} />
)}
{error && <ErrorMessage message={error} />}
</Box>
<Box>
{selectedId ? (
<MovieDetails
selectedId={selectedId}
onCloseMovie={handleCloseMovie}
onAddWatched={handleAddWatch}
watched={watched}
KEY={KEY}
/>
) : (
<>
<WatchedSummary watched={watched} />
<WatchedMovieList
watched={watched}
onDeleteWatched={handleDeleteWatched}
/>
</>
)}
</Box>
{/* <Box element={<MovieList movies={movies} />} />
<Box
element={
<>
<WatchedSummary watched={watched} />
<WatchedMovieList watched={watched} />
</>
}
/> */}
</Main>
</>
);
}
|
//Identity Functor
const identityFunctor = (x) => ({
map: (f) => identityFunctor(f(x)),
valueOf: () => x,
});
//恒等性
const arr = [1, 2, 3];
const identity = (x) => x;
const identityArr = identityFunctor(arr).map(identity).valueOf();
console.log(identityArr); // [1,2,3]
//可组合性
const initNum = 0;
function add4(x) {
return x + 4;
}
function divide2(x) {
return x - 2;
}
const compose = function (g, f) {
return function (x) {
return g(f(x));
};
};
const identityNum = identityFunctor(initNum).map(add4).map(divide2).valueOf();
const composeNum = identityFunctor(initNum)
.map(compose(add4, divide2))
.valueOf();
console.log(identityNum === composeNum); //true
//Maybe Functor
const isEmpty = (x) => x === undefined || x === null;
const Maybe = (x) => ({
map: (f) => (isEmpty(x) ? Maybe(null) : Maybe(f(x))),
valueOf: () => x,
inspect: () => `Maybe {${x}}`,
});
|
package maze;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Abstract dungeon implementation that captures common functionality in both wrapping and
* non-wrapping dungeon.
* Each location in the dungeon is represented in row * column format, with 0,0 indicating
* first location and row-1,col-1 indicating the last location.
* Uses kruskal's algorithm to generate the grid.
* If Interconnectivity specified is too large for the dungeon, will stop at maximum
* interconnectivity possible with the dungeon configuration.
* dungeon creation fails when it cannot be configured with given percentage of treasure locations.
* The minimum distance between start to end is at least 5.
* Game ends when the player reaches the end location.
* Treasure at the end location will be picked automatically when the player reaches end.
* for other caves, player must pick the treasure before leaving the location (it is not automatic).
* uses {@link RandomInteger} to make random choices while constructing dungeon.
* even when predictable random generator is used, will switch to a true random generation for:
* selecting start and end locations of the dungeon.
* placing the treasure in the caves.
* Intentionally making the class package private so that it is not available outside the package.
*/
abstract class AbstractDungeon implements Dungeon {
private Player player;
private Location playerLocation;
protected List<List<Integer>> allEdges;
private final List<List<Integer>> selectedEdges;
private final List<List<Integer>> leftOverEdges;
private Location start;
private Location end;
private boolean started;
private boolean ended;
private final RandomInteger rand;
private final RandomInteger trueRandom;
protected final int row;
protected final int col;
private final Map<String, Map<String, Integer>> shortestPath;
private final int treasureP;
protected final int numMonsters;
protected Location[][] dungeon;
private List<Location> treasureCollected;
private List<Location> arrowsCollected;
private static final int MIN_START_END_DIST = 5;
private static final int INJURED_OTYUGH_HEALTH = 1;
private static final int HEALTH_OTYUGH_HEALTH = 2;
/**
* operation not permitted.
*
* @throws IllegalStateException when calling default constructor.
*/
protected AbstractDungeon() throws IllegalStateException {
throw new IllegalStateException("dungeon cannot be created without any arguments.");
}
/**
* initializes the dungeon with provided row, col, treasure configuration.
*
* @param pName name of the player.
* @param treasureP percentage of caves that should hold the treasure.
* @param rand {@link RandomInteger} to use for random generation.
* @param row number of rows that should be in the dungeon.
* @param col number of columns that should be in the dungeon.
* @param difficulty number of monsters to be configured in the dungeon.
* @throws IllegalArgumentException when player name is null or empty;
* when percentage of caves to place treasure in is less than
* or equal to 0 / greater than 100.
* when percentage of caves to place treasure is too small to
* select caves in the dungeon.
*/
protected AbstractDungeon(
String pName, int treasureP, RandomInteger rand, int row, int col, int difficulty)
throws IllegalArgumentException {
if ((pName == null) || (pName.length() == 0)) {
throw new IllegalArgumentException("player name cannot be null or empty.");
}
if (treasureP <= 0) {
throw new IllegalArgumentException(
"percentage of caves to place treasure in, cannot be negative or 0.");
}
if (treasureP > 100) {
throw new IllegalArgumentException(
"percentage of caves to place treasure in, cannot be > 100.");
}
if (Math.round((treasureP / 100f) * (row * col)) < 1) {
throw new IllegalArgumentException(
"cannot configure treasure of given percentage with this size of dungeon.");
}
if (difficulty < 0) {
throw new IllegalArgumentException(
"difficulty cannot be less than 0");
}
this.player = new PlayerImpl(pName);
if (rand == null) {
rand = new CustomRandomInteger();
}
this.rand = rand;
this.allEdges = new ArrayList<>();
this.selectedEdges = new ArrayList<>();
this.leftOverEdges = new ArrayList<>();
this.row = row;
this.col = col;
this.dungeon = new Location[row][col];
this.shortestPath = new HashMap<>();
this.trueRandom = new CustomRandomInteger();
this.treasureP = treasureP;
this.treasureCollected = new ArrayList<>();
this.numMonsters = difficulty;
this.arrowsCollected = new ArrayList<>();
}
@Override
public String getStart() {
return String.format("%d,%d", start.getRow(), start.getColumn());
}
@Override
public String getEnd() {
return String.format("%d,%d", end.getRow(), end.getColumn());
}
@Override
public void enter() throws IllegalStateException {
try {
checkGameStatus(false, false);
} catch (IllegalStateException ill) {
throw new IllegalStateException("error while entering the dungeon:" + ill.getMessage());
}
playerLocation = start;
started = true;
if (numMonsters != 0) {
try {
player.addWeapon(WeaponType.CROOKEDARROW, 3);
} catch (IllegalStateException | IllegalArgumentException exp) {
throw new IllegalStateException("error while initializing player with weapons");
}
}
}
@Override
public int getRow() {
return this.row;
}
@Override
public int getCol() {
return this.col;
}
@Override
public Map<PlayerDescription, List<String>> describePlayer() {
return player.getPlayerSign();
}
@Override
public Map<LocationDescription, List<String>> describeLocation() throws IllegalStateException {
try {
checkGameStatus(true, null);
} catch (IllegalStateException ill) {
throw new IllegalStateException("error while describing player location:" + ill.getMessage());
}
Map<LocationDescription, List<String>> result = playerLocation.getLocationSign();
SmellIntensity smell = getLocationSmell();
List<String> smellVal = new ArrayList<>();
if (smell != null) {
smellVal.add(smell.name());
} else {
smellVal.add("null");
}
result.put(LocationDescription.SMELL, smellVal);
return result;
}
@Override
public void move(Direction dir) throws IllegalArgumentException, IllegalStateException {
try {
checkGameStatus(true, false);
} catch (IllegalStateException ill) {
throw new IllegalStateException("error while making a move:" + ill.getMessage());
}
if (dir == null) {
throw new IllegalArgumentException("direction to move cannot be null.");
}
Map<Direction, Location> pMoves = playerLocation.getPossibleMoves();
Location reqLoc = pMoves.get(dir);
if (reqLoc != null) {
playerLocation = reqLoc;
Monster m = playerLocation.getMonster();
if (m != null) {
if (m.getCurrentHealth() == HEALTH_OTYUGH_HEALTH) {
player.setPlayerStatus(PlayerStatus.DECEASED);
ended = true;
} else if (m.getCurrentHealth() == INJURED_OTYUGH_HEALTH) {
int randomNum = rand.nextInt(0, 2);
if (randomNum == 0) {
// survives
if (reqLoc == end) {
ended = true;
}
} else {
player.setPlayerStatus(PlayerStatus.DECEASED);
ended = true;
}
} else {
if (reqLoc == end) {
collectTreasure();
ended = true;
}
}
} else {
if (reqLoc == end) {
collectTreasure();
ended = true;
}
}
} else {
throw new IllegalStateException("invalid move.");
}
}
/*
helper to check game status.
throws exception when the states provided doesn't match.
isEnded can be null, in which case, checking end status is skipped.
*/
private void checkGameStatus(boolean isStarted, Boolean isEnded) throws IllegalStateException {
if (started != isStarted) {
throw new IllegalStateException("player has not entered dungeon.");
}
if (isEnded != null) {
if (ended != isEnded) {
throw new IllegalStateException("player reached end, reset to play again.");
}
}
}
@Override
public Map<Treasure, Integer> collectTreasure() throws IllegalStateException {
try {
checkGameStatus(true, false);
} catch (IllegalStateException ill) {
throw new IllegalStateException("error while collecting treasure:" + ill.getMessage());
}
if (treasureCollected.contains(playerLocation)) {
return null;
}
Map<Treasure, Integer> treasureL = playerLocation.getTreasure();
try {
for (Treasure t : Treasure.values()) {
int treasureQ = treasureL.get(t);
if (treasureQ != 0) {
player.addTreasure(t, treasureQ);
treasureCollected.add(playerLocation);
playerLocation.placeTreasure(t, -treasureQ);
}
}
} catch (IllegalArgumentException | IllegalStateException exp) {
throw new IllegalStateException("error while collecting treasure." + exp.getMessage());
}
return treasureL;
}
private int countCaves() {
int caves = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (dungeon[i][j].getType() == LocationType.CAVE) {
caves++;
}
}
}
return caves;
}
/*
configure treasure in the dungeon.
throws exception when there aren't enough caves to place treasure.
*/
protected void configureTreasure() throws IllegalStateException, IllegalArgumentException {
int caves = countCaves();
int treasureRooms = Math.round((treasureP / 100f) * (caves));
if (treasureRooms < 1) {
throw new IllegalArgumentException(
"cannot configure treasure of given percentage with this size of dungeon.");
}
List<Location> treasureLoc = new ArrayList<>();
List<List<Integer>> allNodes = new ArrayList<>();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
List<Integer> edge = new ArrayList<>();
edge.add(i);
edge.add(j);
allNodes.add(edge);
}
}
int consecutiveM = 0;
RandomInteger rGen = trueRandom;
while (treasureLoc.size() != treasureRooms) {
int randomN = rGen.nextInt(0, allNodes.size());
Location locToPlace = dungeon[allNodes.get(randomN).get(0)][allNodes.get(randomN).get(1)];
int randomT = rand.nextInt(0, Treasure.values().length);
int randomQ = rand.nextInt(20, 100);
try {
if (randomT == 0) {
configureTreasureHelper(Treasure.DIAMONDS, randomQ, locToPlace, rand, treasureLoc);
if (consecutiveM > 0) {
consecutiveM = 0;
}
}
if (randomT == 1) {
configureTreasureHelper(Treasure.RUBIES, randomQ, locToPlace, rand, treasureLoc);
if (consecutiveM > 0) {
consecutiveM = 0;
}
}
if (randomT == 2) {
configureTreasureHelper(Treasure.SAPPHIRES, randomQ, locToPlace, rand, treasureLoc);
if (consecutiveM > 0) {
consecutiveM = 0;
}
}
} catch (IllegalStateException ill) {
consecutiveM++;
if (consecutiveM > 1000) {
throw new IllegalStateException("unable to place treasure." + ill.getMessage());
}
} catch (IllegalArgumentException illArg) {
throw new IllegalStateException("invalid argument while placing treasure."
+ illArg.getMessage());
}
}
}
/*
helper to configure treasure.
validates whether the given location can be placed with treasure and places it if true.
*/
private void configureTreasureHelper(Treasure treasure, int treasureQ,
Location locToPlace, RandomInteger rGen,
List<Location> treasureLoc)
throws IllegalArgumentException, IllegalStateException {
if (locToPlace.getType() != LocationType.TUNNEL) {
locToPlace.placeTreasure(treasure, treasureQ);
if (!treasureLoc.contains(locToPlace)) {
treasureLoc.add(locToPlace);
}
}
}
/*
configure arrows in the dungeon.
throws exception when there aren't enough caves to place arrows.
*/
protected void configureArrows() throws IllegalStateException {
int numLocations = row * col;
int arrowRooms = Math.round((treasureP / 100f) * (numLocations));
if (arrowRooms < 1) {
throw new IllegalArgumentException(
"cannot configure treasure of given percentage with this size of dungeon.");
}
List<Location> arrowLoc = new ArrayList<>();
List<List<Integer>> allNodes = new ArrayList<>();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
List<Integer> edge = new ArrayList<>();
edge.add(i);
edge.add(j);
allNodes.add(edge);
}
}
int consecutiveM = 0;
RandomInteger rGen = trueRandom;
while (arrowLoc.size() != arrowRooms) {
int randomN = rGen.nextInt(0, allNodes.size());
Location locToPlace = dungeon[allNodes.get(randomN).get(0)][allNodes.get(randomN).get(1)];
int randomQ = rand.nextInt(1, 3);
try {
if (!arrowLoc.contains(locToPlace)) {
locToPlace.placeWeapon(WeaponType.CROOKEDARROW, randomQ);
arrowLoc.add(locToPlace);
if (consecutiveM > 0) {
consecutiveM = 0;
}
}
} catch (IllegalStateException ill) {
consecutiveM++;
if (consecutiveM > 1000) {
throw new IllegalStateException("unable to place arrows." + ill.getMessage());
}
}
}
}
/*
configure monsters in the dungeon.
throws exception when there aren't enough caves to place arrows.
*/
protected void configureMonsters() throws IllegalStateException {
if (numMonsters == 0) {
return;
}
int caves = countCaves();
if (numMonsters > (caves - 1)) {
throw new IllegalArgumentException(
"cannot configure monsters of required quantity with this size of dungeon.");
}
List<Location> monsterLoc = new ArrayList<>();
List<List<Integer>> allNodes = new ArrayList<>();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
List<Integer> edge = new ArrayList<>();
edge.add(i);
edge.add(j);
allNodes.add(edge);
}
}
end.placeMonster();
monsterLoc.add(end);
int consecutiveM = 0;
RandomInteger rGen = trueRandom;
while (monsterLoc.size() != numMonsters) {
int randomN = rGen.nextInt(0, allNodes.size());
Location locToPlace = dungeon[allNodes.get(randomN).get(0)][allNodes.get(randomN).get(1)];
try {
if (!monsterLoc.contains(locToPlace)) {
if (configureMonsterHelper(locToPlace)) {
monsterLoc.add(locToPlace);
if (consecutiveM > 0) {
consecutiveM = 0;
}
}
}
} catch (IllegalStateException ill) {
consecutiveM++;
if (consecutiveM > 1000) {
throw new IllegalStateException("unable to place monsters." + ill.getMessage());
}
}
}
}
/*
helper to configure monster.
validates whether the given location can be placed with monster and places it if true.
*/
private boolean configureMonsterHelper(Location locToPlace)
throws IllegalArgumentException, IllegalStateException {
if ((locToPlace.getType() != LocationType.TUNNEL)
&& (locToPlace != start)) {
locToPlace.placeMonster();
return true;
}
return false;
}
@Override
public String getPlayerLocation() throws IllegalStateException {
try {
checkGameStatus(true, null);
} catch (IllegalStateException ill) {
throw new IllegalStateException("error while getting player location:" + ill.getMessage());
}
return String.format("%d,%d", playerLocation.getRow(), playerLocation.getColumn());
}
@Override
public boolean gameStarted() {
return started;
}
@Override
public boolean gameEnded() {
return ended;
}
@Override
public void reset() throws IllegalStateException {
try {
checkGameStatus(true, null);
} catch (IllegalStateException ill) {
throw new IllegalStateException("game hasn't started yet:" + ill.getMessage());
}
player = new PlayerImpl(player.getName());
playerLocation = null;
started = false;
ended = false;
treasureCollected = new ArrayList<>();
arrowsCollected = new ArrayList<>();
}
@Override
public Map<WeaponType, Integer> pickWeapon() {
try {
checkGameStatus(true, false);
} catch (IllegalStateException ill) {
throw new IllegalStateException("error while collecting weapon:" + ill.getMessage());
}
if (arrowsCollected.contains(playerLocation)) {
return null;
}
Map<WeaponType, Integer> weaponAtLoc = playerLocation.getWeaponInfo();
try {
for (WeaponType t : WeaponType.values()) {
int weaponQ = weaponAtLoc.get(t);
if (weaponQ != 0) {
player.addWeapon(t, weaponQ);
arrowsCollected.add(playerLocation);
playerLocation.placeWeapon(t, -weaponQ);
}
}
} catch (IllegalArgumentException | IllegalStateException exp) {
throw new IllegalStateException("error while collecting weapon." + exp.getMessage());
}
return weaponAtLoc;
}
@Override
public boolean shootArrow(Direction dir, int distance)
throws IllegalArgumentException, IllegalStateException {
if (dir == null) {
throw new IllegalArgumentException("direction to shoot cannot be null.");
}
if (distance <= 0) {
throw new IllegalArgumentException("distance to shoot cannot be <= 0.");
}
int playerArr = player.getWeaponInfo().get(WeaponType.CROOKEDARROW);
if (playerArr <= 0) {
throw new IllegalStateException("player does not have arrows to shoot.");
}
boolean result = false;
int distToTravel = distance;
Location tempLocation = playerLocation;
Direction tempDir = dir;
while (distToTravel != 0) {
Map<Location, Direction> nextPossible = getNextPossibleLoc(tempLocation, tempDir);
if (nextPossible == null) {
break;
}
for (Map.Entry<Location, Direction> mapEntry : nextPossible.entrySet()) {
if (mapEntry.getKey() != null) {
tempLocation = mapEntry.getKey();
tempDir = mapEntry.getValue();
if (tempLocation.getLocationSign().get(LocationDescription.TYPE).get(0)
.equals(LocationType.CAVE.name())) {
distToTravel--;
}
} else {
break;
}
}
}
if (distToTravel == 0) {
// check if temp location has monster, if so, slay it.
Monster m = tempLocation.getMonster();
if ((m != null) && (m.getCurrentHealth() != 0)) {
m.slay();
result = true;
}
}
// loose the arrow from the player.
player.addWeapon(WeaponType.CROOKEDARROW, -1);
return result;
}
private Map<Location, Direction> getNextPossibleLoc(Location location, Direction dir) {
Map<Direction, Direction> compDir = new HashMap<>();
compDir.put(Direction.NORTH, Direction.SOUTH);
compDir.put(Direction.SOUTH, Direction.NORTH);
compDir.put(Direction.EAST, Direction.WEST);
compDir.put(Direction.WEST, Direction.EAST);
Location nextLocation;
Map<Direction, Location> possMoves = location.getPossibleMoves();
if (possMoves.get(dir) != null) {
nextLocation = possMoves.get(dir);
} else {
return null;
}
possMoves = nextLocation.getPossibleMoves();
Direction nextDir = null;
if (nextLocation.getType() == LocationType.TUNNEL) {
for (Map.Entry<Direction, Location> entry : possMoves.entrySet()) {
if (entry.getKey() != compDir.get(dir)) {
if (entry.getValue() != null) {
nextDir = entry.getKey();
}
}
}
} else {
nextDir = dir;
}
Map<Location, Direction> result = new HashMap<>();
result.put(nextLocation, nextDir);
return result;
}
@Override
public PlayerStatus getPlayerStatus() {
return player.getPlayerStatus();
}
@Override
public SmellIntensity getLocationSmell() {
Map<Direction, Location> possMoves = playerLocation.getPossibleMoves();
Map<Direction, Direction> compDir = new HashMap<>();
compDir.put(Direction.NORTH, Direction.SOUTH);
compDir.put(Direction.SOUTH, Direction.NORTH);
compDir.put(Direction.EAST, Direction.WEST);
compDir.put(Direction.WEST, Direction.EAST);
if (gameStarted()) {
Monster m = playerLocation.getMonster();
if ((m != null) && (m.getCurrentHealth() != 0)) {
return SmellIntensity.HIGH;
}
}
int monsAtNextL = 0;
List<Location> nextNeighbor = new ArrayList<>();
// immediate neighbors
for (Direction d : Direction.values()) {
if (possMoves.get(d) != null) {
Monster m = possMoves.get(d).getMonster();
if ((m != null) && (m.getCurrentHealth() > 0)) {
return SmellIntensity.HIGH;
}
Map<Direction, Location> tempMoves = possMoves.get(d).getPossibleMoves();
for (Direction di : Direction.values()) {
Location neigh = tempMoves.get(di);
if ((di != compDir.get(d)) && (neigh != null) && (!nextNeighbor.contains(neigh))) {
Monster nextLevel = neigh.getMonster();
if ((nextLevel != null) && (nextLevel.getCurrentHealth() > 0)) {
monsAtNextL++;
nextNeighbor.add(neigh);
if (monsAtNextL == 2) {
return SmellIntensity.HIGH;
}
}
}
}
}
}
if (monsAtNextL == 0) {
return null;
} else if (monsAtNextL == 1) {
return SmellIntensity.LOW;
}
return null;
}
/*
creates bare location objects in the dungeon.
*/
protected void createLocations() {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
Location loc = new LocationImpl(i, j);
dungeon[i][j] = loc;
}
}
}
/*
runs the kruskal algorithm to generate the grid.
also sets neighbours between locations in dungeon.
interconnectivity is handled by adding leftover edges after kruskal algorithm, the number of
leftover edges added is the same as the value of interconnectivity.
*/
protected void runKruskal(int interConn) {
List<List<Integer>> allEdgesCopy = new ArrayList<>(allEdges);
List<String> selectedE = new ArrayList<>();
int random = 0;
while (selectedEdges.size() < (row * col) - 1) {
random = rand.nextInt(0, allEdgesCopy.size());
List<Integer> edge = allEdgesCopy.get(random);
String source = String.format("%d,%d", edge.get(0), edge.get(1));
String dest = String.format("%d,%d", edge.get(2), edge.get(3));
boolean edgeSelected = false;
int sourceInd = -1;
int destInd = -1;
// union-find for kruskal is done based on string comparison.
if (selectedEdges.size() == 0) {
edgeSelected = true;
} else {
for (int i = 0; i < selectedE.size(); i++) {
if (selectedE.get(i).contains(source.subSequence(0, source.length()))) {
sourceInd = i;
}
if (selectedE.get(i).contains(dest.subSequence(0, dest.length()))) {
destInd = i;
}
}
if (sourceInd != destInd) {
edgeSelected = true;
} else {
if (sourceInd == -1) {
edgeSelected = true;
} else {
edgeSelected = false;
}
}
}
if (edgeSelected) {
StringBuffer sb = new StringBuffer();
sb.append(source);
sb.append("-");
sb.append(dest);
StringBuffer temp = new StringBuffer();
if (selectedEdges.size() != 0) {
if (sourceInd != -1) {
temp.append(selectedE.get(sourceInd));
temp.append("->");
}
temp.append(sb.toString());
if (destInd != -1) {
temp.append("->");
temp.append(selectedE.get(destInd));
}
if ((sourceInd == destInd) && (sourceInd != -1)) {
selectedE.remove(sourceInd);
} else {
if (sourceInd != -1) {
selectedE.remove(sourceInd);
if (sourceInd < destInd) {
destInd--;
}
}
if (destInd != -1) {
selectedE.remove(destInd);
}
}
selectedE.add(temp.toString());
} else {
selectedE.add(sb.toString());
}
setNeighbours(edge.get(0), edge.get(1), edge.get(2), edge.get(3));
allEdgesCopy.remove(random);
selectedEdges.add(edge);
} else {
allEdgesCopy.remove(random);
leftOverEdges.add(edge);
}
}
// handling interconnectivity.
leftOverEdges.addAll(allEdgesCopy);
interConn = Math.min(interConn, leftOverEdges.size());
for (int i = 0; i < interConn; i++) {
if (countCaves() <= 2) {
break;
}
random = rand.nextInt(0, leftOverEdges.size());
List<Integer> edge = leftOverEdges.get(random);
setNeighbours(edge.get(0), edge.get(1), edge.get(2), edge.get(3));
leftOverEdges.remove(random);
selectedEdges.add(edge);
}
}
/*
set neighbours between two location objects represented by their row,column position.
@param sourceR source location row.
@param sourceC source location column.
@param destR destination location row.
@param destC destination location column.
*/
protected abstract void setNeighbours(int sourceR, int sourceC, int destR, int destC);
/**
* Fills up non wrapping edges in this.allEdges
* To support testing using predictable random numbers, sets up few edges to
* the front of the list.
*/
protected void setupNonWrappingEdges() {
int i = 0;
int j = 0;
int a = 0;
int b = 1;
// sets up few edges towards the front of the allEdges data structure so that we know how the
// grid will be formed when using predictable random numbers to construct the dungeon.
// the pattern that is setup is a mirror image of 5,
// e.g., 0,0-0,1 -> 0,1-0,2 -> ... -> 0,(column-2)-0,(column-1) -> 0,(column-1)-1,(column-1) ...
List<String> selectedEdges = new ArrayList<>();
for (int k = 0; k < row; k++) {
for (int m = 0; m < col; m++) {
List<Integer> edge = new ArrayList<>();
if (!((k == row - 1) && (m == col - 1))) {
if ((i <= a) && (j <= b)) {
edge.add(i);
edge.add(j);
edge.add(a);
edge.add(b);
allEdges.add(edge);
selectedEdges.add(String.format("%d%d%d%d", i, j, a, b));
} else {
edge.add(a);
edge.add(b);
edge.add(i);
edge.add(j);
allEdges.add(edge);
selectedEdges.add(String.format("%d%d%d%d", a, b, i, j));
}
}
i = a;
j = b;
if ((k % 2) == 0) {
if (m < (col - 2)) {
b++;
} else {
if (m == col - 2) {
b = col - 1;
} else {
b--;
}
if (k != row - 1) {
a = k + 1;
} else {
//do nothing.
}
}
} else {
if (m < (col - 2)) {
b--;
} else {
if (m == col - 2) {
b = 0;
} else {
b++;
}
if (k != row - 1) {
a = k + 1;
} else {
//do nothing.
}
}
}
}
}
// fills remaining non-wrapping edges.
for (int k = 0; k < row; k++) {
for (int l = 0; l < col; l++) {
List<Integer> edge = new ArrayList<>();
String pEdge1 = "";
String pEdge2 = "";
if (l != col - 1) {
pEdge1 = String.format("%d%d%d%d", k, l, k, l + 1);
}
if (k != row - 1) {
pEdge2 = String.format("%d%d%d%d", k, l, k + 1, l);
}
if ((pEdge1.length() > 0) && (!(selectedEdges.contains(pEdge1)))) {
edge = new ArrayList<>();
edge.add(k);
edge.add(l);
edge.add(k);
edge.add(l + 1);
allEdges.add(edge);
}
if ((pEdge2.length() > 0) && (!(selectedEdges.contains(pEdge2)))) {
edge = new ArrayList<>();
edge.add(k);
edge.add(l);
edge.add(k + 1);
edge.add(l);
allEdges.add(edge);
}
}
}
}
/*
selects start and end location in the dungeon.
uses the all pair shortest path algorithm between randomly selected source and end to
ensure that the minimum distance between them is at least MIN_START_END_DIST.
*/
protected void selectStartEnd() {
List<String> allNodes = new ArrayList<>();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
allNodes.add(String.format("%d,%d", i, j));
}
}
RandomInteger rGen = trueRandom;
int random = rGen.nextInt(0, allNodes.size());
String possStart = allNodes.get(random);
int pStartI = Integer.parseInt(possStart.split(",")[0]);
int pStartJ = Integer.parseInt(possStart.split(",")[1]);
start = dungeon[pStartI][pStartJ];
List<String> possEndsChecked = new ArrayList<>();
while (start.getType() != LocationType.CAVE) {
random = rGen.nextInt(0, allNodes.size());
possStart = allNodes.get(random);
pStartI = Integer.parseInt(possStart.split(",")[0]);
pStartJ = Integer.parseInt(possStart.split(",")[1]);
start = dungeon[pStartI][pStartJ];
}
while (end == null) {
if (possEndsChecked.size() == allNodes.size()) {
throw new IllegalStateException("start and end location cannot be selected "
+ "for the provided row and column values.");
}
random = rGen.nextInt(0, allNodes.size());
String possEnd = allNodes.get(random);
int pEndI = Integer.parseInt(possEnd.split(",")[0]);
int pEndJ = Integer.parseInt(possEnd.split(",")[1]);
end = dungeon[pEndI][pEndJ];
while (end.getType() != LocationType.CAVE) {
random = rGen.nextInt(0, allNodes.size());
possEnd = allNodes.get(random);
pEndI = Integer.parseInt(possEnd.split(",")[0]);
pEndJ = Integer.parseInt(possEnd.split(",")[1]);
end = dungeon[pEndI][pEndJ];
}
if (!possEndsChecked.contains(possEnd)) {
possEndsChecked.add(possEnd);
}
Map<String, Integer> pathFromEnd;
if ((!shortestPath.isEmpty()) && (shortestPath.get(possEnd) != null)) {
pathFromEnd = shortestPath.get(possEnd);
if (pathFromEnd.get(possStart) < MIN_START_END_DIST) {
end = null;
}
} else {
runAllPairShortestPath(possEnd, allNodes);
pathFromEnd = shortestPath.get(possEnd);
if (pathFromEnd.get(possStart) != null) {
if (pathFromEnd.get(possStart) < MIN_START_END_DIST) {
end = null;
}
} else {
throw new IllegalStateException("cannot determine distance between start to end.");
}
}
}
}
/*
all pair shortest path algorithm implementation.
for the given target node "possEnd" finds distance from all other location.
results are stored in shortestPath map.
*/
protected void runAllPairShortestPath(String possEnd, List<String> allNodes) {
int[][] opt = new int[selectedEdges.size()][allNodes.size()];
for (int i = 0; i < allNodes.size(); i++) {
opt[0][i] = Integer.MAX_VALUE - 100000;
}
int endIndex = allNodes.indexOf(possEnd);
opt[0][endIndex] = 0;
Location temp;
Map<Direction, Location> p;
for (int i = 1; i < selectedEdges.size(); i++) {
for (int j = 0; j < allNodes.size(); j++) {
opt[i][j] = opt[i - 1][j];
String[] iJ = allNodes.get(j).split(",");
temp = dungeon[Integer.parseInt(iJ[0])][Integer.parseInt(iJ[1])];
p = temp.getPossibleMoves();
List<String> moves = new ArrayList<>();
List<Integer> neighbour = new ArrayList<>();
for (Direction dir : Direction.values()) {
if (p.get(dir) != null) {
moves.add(String.format("%d,%d", p.get(dir).getRow(), p.get(dir).getColumn()));
neighbour.add(allNodes.indexOf(
String.format("%d,%d", p.get(dir).getRow(), p.get(dir).getColumn())));
}
}
for (int neigh : neighbour) {
opt[i][j] = Math.min(opt[i][j], opt[i - 1][neigh] + 1);
}
}
}
Map<String, Integer> shortP = new HashMap<>();
for (int j = 0; j < allNodes.size(); j++) {
shortP.put(allNodes.get(j), opt[selectedEdges.size() - 1][j]);
}
shortestPath.put(allNodes.get(endIndex), shortP);
}
/**
* String representation of the dungeon comprised of:
* the location details of each cell will have neighbours represented with = (or) ||.,
* treasure information at each location detailed separately.
* location which has the player will be denoted by "P".
*
* @return String with dungeon information as explained above.
*/
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < row; i++) {
for (int k = 0; k < 4; k++) {
for (int j = 0; j < col; j++) {
Map<Direction, Location> p = dungeon[i][j].getPossibleMoves();
/*
case 0: information about neighbours to north.
case 1: information about neighbours to west and east.
case 2: information about neighbours to south.
*/
switch (k) {
case 0: {
if (p.get(Direction.NORTH) != null) {
sb.append(" | | ");
} else {
sb.append(" ");
}
}
break;
case 1: {
if (p.get(Direction.WEST) != null) {
sb.append(" = ");
} else {
sb.append(" ");
}
sb.append(dungeon[i][j].toString());
if (end == dungeon[i][j]) {
sb.append("E");
} else if (start == dungeon[i][j]) {
sb.append("S");
} else {
sb.append(" ");
}
int monsterHealth;
if (dungeon[i][j].getMonster() != null) {
monsterHealth = dungeon[i][j].getMonster().getCurrentHealth();
if (monsterHealth == 2) {
sb.append("M*");
} else if (monsterHealth == 1) {
sb.append("M+");
} else if (monsterHealth == 0) {
sb.append("M-");
}
} else {
sb.append(" ");
}
if (playerLocation == dungeon[i][j]) {
sb.append("P");
} else {
sb.append(" ");
}
if (p.get(Direction.EAST) != null) {
sb.append(" = ");
} else {
sb.append(" ");
}
}
break;
case 2: {
if (p.get(Direction.SOUTH) != null) {
sb.append(" | | ");
} else {
sb.append(" ");
}
}
break;
default:
// do nothing;
break;
}
}
sb.append("\n");
}
sb.append("\n");
}
StringBuffer strB = new StringBuffer();
strB.append("\n\nTreasure map\n");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
strB.append(dungeon[i][j].toString());
strB.append(": ");
String treasureS = getTreasureString(dungeon[i][j]);
if (treasureS.length() > 0) {
strB.append(treasureS);
}
strB.append("\n");
}
strB.append("\n");
}
sb.append(strB);
if (numMonsters > 0) {
strB = new StringBuffer();
strB.append("\n\nArrows map\n");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
strB.append(dungeon[i][j].toString());
strB.append(": ");
String arrowS = getWeaponString(dungeon[i][j]);
if (arrowS.length() > 0) {
strB.append(arrowS);
}
strB.append("\n");
}
strB.append("\n");
}
sb.append(strB);
}
return sb.toString();
}
private String getWeaponString(Location location) {
StringBuffer sb = new StringBuffer();
Map<WeaponType, Integer> weaponInfo = location.getWeaponInfo();
int crookQ = weaponInfo.get(WeaponType.CROOKEDARROW);
if (crookQ > 0) {
sb.append(String.format("%S %d ", WeaponType.CROOKEDARROW, crookQ));
}
return sb.toString();
}
/*
helper for toSting() to get the treasure information at the location.
each treasure will be represented by its first letter.
*/
private String getTreasureString(Location location) {
StringBuffer sb = new StringBuffer();
Map<Treasure, Integer> treasureL = location.getTreasure();
int diaQ = treasureL.get(Treasure.DIAMONDS);
if (diaQ > 0) {
sb.append(String.format("D %d ", diaQ));
}
int rubyQ = treasureL.get(Treasure.RUBIES);
if (rubyQ > 0) {
sb.append(String.format("R %d ", rubyQ));
}
int sapQ = treasureL.get(Treasure.SAPPHIRES);
if (sapQ > 0) {
sb.append(String.format("S %d ", sapQ));
}
return sb.toString();
}
}
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'image',
'image_url',
'file_driver'
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'image',
'file_driver'
];
/**
* The relationship with the Podcast model
*/
public function podcasts()
{
return $this->hasMany(Podcast::class);
}
/**
* The relationship with the Show model
*/
public function shows()
{
return $this->hasMany(Show::class);
}
}
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Person
{
public:
string name;
int age;
virtual void getdata()=0;
virtual void putdata()=0;
};
class Professor : public Person
{
public:
int publications;
static int cur_id;
void getdata()
{
cin>>name>>age>>publications;
}
void putdata()
{
cout<<name<<" "<<age<<" "<<publications<<" "<<cur_id<<endl;
cur_id++;
}
};
int Professor :: cur_id=1;
class Student : public Person
{
public:
int marks[6];
static int cur_id;
int sum=0;
void getdata()
{
cin>>name>>age ;
for(int x:marks)
{
cin>>x;
sum+=x;
}
}
void putdata()
{
cout<<name<<" "<<age<<" "<<sum<<" "<<cur_id<<endl;
cur_id++;
}
};
int Student :: cur_id=1;
int main(){
int n, val;
cin>>n; //The number of objects that is going to be created.
Person *per[n];
for(int i = 0;i < n;i++){
cin>>val;
if(val == 1){
// If val is 1 current object is of type Professor
per[i] = new Professor;
}
else per[i] = new Student; // Else the current object is of type Student
per[i]->getdata(); // Get the data from the user.
}
for(int i=0;i<n;i++)
per[i]->putdata(); // Print the required output for each object.
return 0;
}
|
<template>
<div id="systemRole-page" class="container-fluid">
<!--v-table-->
<div class="row text-center">
<!--调用v-table全局组件事,将本页面请求的columns传给该组件进行数据的渲染, :xx表示正向传值-->
<v-table :title="translate.tableTitle" :url="url" pagesize="10" idField="id" :order="true" :columns="columns">
</v-table>
</div>
<!-- 点击“添加”的模态框(Modal) -->
<v-modal :show="showUserModal" effect="fade" width="420">
<div slot="modal-header" class="modal-header">
<h5 class="modal-title">
{{ translate.user }}
</h5>
</div>
<div slot="modal-body" class="modal-body">
<input type="hidden" id="role-id" v-model="newRoleUser.roleId">
<div class="form-group">
<label class="input-label" >{{translate.userNo}}</label>
<input id="user-no" type="text" :placeholder="translate.checkUserTip" class="form-control search-input modal-form-style" @change="checkUser" v-model="newRoleUser.userNo">
<button type="button" class="btn check-btn clearBtnBorder" @click="checkUser">{{ translate.check }}</button>
<p class="error-message">{{errorMessage}}</p>
</div>
<div class="form-group">
<div class="form-group">
<label class="input-label" >{{translate.username}}</label>
<input type="text" class="form-control name-input modal-form-style" readonly="readonly" v-model="newRoleUser.name">
<button type="button" class="btn check-btn clearBtnBorder" @click="addNewUser">{{ translate.add }}</button>
</div>
</div>
<div class="user-list">
<p class="" v-for="(com,cIndex) in userInfoArr" :key="cIndex">
<span class="user-name">{{com.userName}}</span> <i class="maticon pull-right remove-icon" v-html="icons('cancel')" @click="removeUser(com.userId)">cancel</i>
</p>
</div>
</div>
<div slot="modal-footer" class="modal-footer">
<button type="button" class="btn cancel-btn clearBtnBorder" @click="cancelAddUser">{{translate.cancel}}</button>
<button type="button" class="btn submit-btn clearBtnBorder" @click="addUser">{{translate.submit}}</button>
</div>
</v-modal>
</div>
</template>
<script>
import Vue from 'vue'
import { sAjax, translation } from '../../assets/utils/utils.js'
export default {
created: function () {
var la = localStorage.getItem('lang')
var that = this
if (translation(la)) {
this.lang = la
}
// columns对象数组用来填充表格
this.columns = [{
id: 'name',
title: this.translate.roleName,
// 单独设置某一列的样式
className: 'text-left',
// 某一列是否隐藏
hidden: false
}, {
title: this.translate.user,
className: 'text-left',
hidden: false,
hover: false,
formatter: function (record) {
if (!record.users) {
return ''
}
var userString = ''
record.users.forEach(function (e) {
userString += '<span title='+ e.userNo +'>' + e.name + '</span>' + ','
})
return userString.substring(0, userString.length - 1)
}
}, {
id: 'opt',
className: 'text-center',
width: '130px',
title: this.translate.operation,
hidden: false,
// 对最后变的td进行格式化,用两个a标签填充
formatter: function () {
return [{
tag: 'a',
// “清空”
text: '授权',
className: 'opt-btn',
callback: function (record, index) {
that.userInfoArr.splice(0, that.userInfoArr.length)
record.users.forEach((ele, i) => {
that.userInfoArr.push({
userId: ele.userId,
userName: ele.name
})
})
that.newRoleUser.roleId = record.id
that.newRoleUser.userNo = ''
that.newRoleUser.name = ''
that.showUserModal = true
that.isCheck = false
}
}]
}
}]
},
data: function () {
return {
columns: [],
url: '/table-data/authorities/systemRoles/pages',
showUserModal: false,
newRoleUser: {
roleId: 0,
userId: '',
name: '',
userNo: ''
},
errorMessage: '',
userInfoArr: [],
isCheck: false,
lang: 'zh-cn'
}
},
computed: {
translate: function () {
return translation(this.lang).systemRoleManage
}
},
methods: {
// 取消增加用户
cancelAddUser: function () {
this.newRoleUser = {
roleId: 0,
userId: '',
name: '',
userNo: ''
}
this.showUserModal = false
},
// 检测输入的工号是否已存在
checkUser: function () {
var that = this
if (!this.newRoleUser.userNo) {
that.errorMessage = this.translate.checkUserTip
return
}
sAjax({
url: '/api/users/' + this.newRoleUser.userNo,
dataType: 'json',
data: {},
type: 'GET',
success: function (data) {
if (data.state) {
// 如果该工号不存在,则新增工号和姓名
that.newRoleUser.userId = data.data.userId
that.newRoleUser.name = data.data.name
that.errorMessage = ''
that.isCheck = true
} else {
// 如果该工号已经存在则提示
that.errorMessage = that.translate.userNoExistedTip
that.isCheck = false
}
}
})
},
// 填写完工号和姓名 点击“提交”
addUser: function () {
var that = this
sAjax({
url: '/api/authorities/systemRoles/' + this.newRoleUser.roleId + '/users',
dataType: 'json',
data: {
users: this.userInfoArr
},
type: 'post',
success: function (data) {
if (data.state) {
that.showUserModal = false
that.url = that.url + '?time=' + new Date().getTime()
that.$toast('提交成功')
} else {
that.$toast(data.message)
}
}
})
},
addNewUser: function () {
if (!this.isCheck) {
return this.$toast('请先检测学工号!')
}
this.userInfoArr.push({
userId: this.newRoleUser.userId,
userName: this.newRoleUser.name
})
},
removeUser: function (userId) {
this.userInfoArr.forEach((ele, i) => {
if (ele.userId === userId) {
this.userInfoArr.splice(i, 1)
}
})
}
}
}
</script>
<style lang="less">
//通用样式
@import url("../../assets/common.less");
#systemRole-page {
/*清空和增加按钮*/
.opt-btn {
border-radius: 3px;
margin-right: 5px;
}
.modal-body {
.user-no-input {
width: 70%;
}
.checkBtn {
float: right;
margin-top: -33px;
margin-right: 8px;
font-weight: 500;
}
}
.add {
background: @-90ThemeColor;
border: none;
border-radius: 100px;
}
.name-input {
border-radius: 0;
border-top: 0 solid #ffffff;
border-left: 0 solid #ffffff;
border-right: 0 solid #ffffff;
border-bottom: 2px solid #e0e0e0;
box-shadow: inset 0 0px 0px rgba(0, 0, 0, 0.075);
padding: 0;
}
.form-control[readonly] {
background: #fff;
}
.error-message {
font-size: 13px;
color: #ff5252;
line-height: 13px;
margin: 8px 0 0 50px;
}
.user-name {
font-size: 14px;
display: inline-block;
margin-top: 3px;
}
.remove-icon {
color: rgba(0, 0, 0, 0.4);
cursor: pointer;
margin-right: 20px;
}
.user-list {
margin-top: 30px;
}
}
</style>
|
#ifndef COMMANDCONTROLLER_H
#define COMMANDCONTROLLER_H
#include <QObject>
#include <SCALMIS-LIB_global.h>
#include <QScopedPointer>
#include <controllers/navigationcontroller.h>
#include <flow/commands.h>
#include <network/IServerRequest.h>
#include <models/authlogin.h>
#include <models/stock.h>
#include <models/requests.h>
#include <models/accounts.h>
#include <models/invoiceperiod.h>
#include <validators/validators.h>
using namespace SCALMIS::models;
namespace SCALMIS {
namespace controllers {
class SCALMISLIB_EXPORT CommandController : public QObject
{
Q_OBJECT
Q_PROPERTY(QQmlListProperty<SCALMIS::flow::Commands> ui_contextCommands READ contextCommands NOTIFY contextCommandsChanged)
public:
explicit CommandController(QObject *parent = nullptr, NavigationController *navigator = nullptr, AuthLogin *authLogin = nullptr, network::IServerRequest *iServerRequest = nullptr, Stock *stock = nullptr, Requests *requests = nullptr, Accounts *accounts = nullptr, InvoicePeriod *invoicePeriod = nullptr);
~CommandController();
QQmlListProperty<flow::Commands> contextCommands();
void setToken(QJsonObject &json);
QJsonArray modifyRequest(QJsonArray requests, bool isItem);
void requestHelper(bool isItem);
void setChecked(QJsonObject update);
QJsonArray getChecked();
bool checkOfficeValidity(bool allowEmpty);
void checkServerVersion();
void passVersion();
public slots:
void resetCommands();
void signin();
void signout_admin();
void newStock();
void newService();
void displayReqItemsPage();
void displayReqServicePage();
void requestItems();
void setContextCommands(QString context);
void cBoxItems();
void cBoxDesc(const QString &item);
void cBoxAuths();
void cboxServices();
void getStockTakes();
void getStockData(const QString ObjId);
void setUpStockItems(const QJsonArray json, const QString &context);
void setUpdateStockId(const QString &updateId);
void saveItem();
void deleteItem();
void createUser();
void getApproved(bool ref, QString text);
void doApproval(bool approval, QString objId);
void downloadStock();
void generateInvoice(const QJsonObject &obj);
void proceedToGetInvoice();
void generateInvoicePeriod();
void useApprContext();
QString getContext();
void postRequestService();
void initiateDeleteUser();
void saveUser();
void editUser(QJsonObject user , bool del);
void changePassword(QJsonObject user);
void ResetPassword();
bool validateAccount();
void checkUpdates(QString text, QString key);
void downloadUpdate(int app);
private:
class Implementation;
QScopedPointer<Implementation> implementation;
signals:
void serverResponse(const QString message);
void contextCommandsChanged();
};
}
}
#endif // COMMANDCONTROLLER_H
|
<?php
/**
* Bigace - a PHP and MySQL based Web CMS.
*
* LICENSE
*
* This source file is subject to the new GNU General Public License
* that is bundled with this package in the file LICENSE.
* It is also available through the world-wide-web at this URL:
* http://www.bigace.de/license.html
*
* Bigace is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* @category Bigace
* @copyright Copyright (c) 2009-2010 Keleo (http://www.keleo.de)
* @license http://www.bigace.de/license.html GNU Public License
* @version $Id$
*/
require_once dirname(__FILE__).'/MultiSelect.php';
/**
* A ViewHelper for selecting one or multiple user.
* The default implementation displays all user, but you can pass in
* a list to display a different start set of available user.
*
* @category Bigace
* @copyright Copyright (c) 2009-2010 Keleo (http://www.keleo.de)
* @license http://www.bigace.de/license.html GNU Public License
*/
class Admin_View_Helper_UserList extends Admin_View_Helper_MultiSelect
{
/**
* Options will be ignored, as it is populated from all available
* user in the system.
*
* Pass 'systemUser' with the value "true" in $attribs if you want
* the anonymous and super-admin as well.
*
* @see Admin_View_Helper_MultiSelect::multiselect()
*/
public function userList($name, $value = null, $attribs = null,
$options = null, $listsep = "<br />\n")
{
$systemUser = (isset($attribs['systemUser']) && $attribs['systemUser'] === true);
$options = array();
$services = Bigace_Services::get();
$principalService = $services->getService(Bigace_Services::PRINCIPAL);
$userInfo = $principalService->getAllPrincipals($systemUser);
foreach($userInfo as $user)
$options[$user->getID()] = $user->getName();
return parent::multiselect($name, $value, $attribs, $options, $listsep);
}
}
|
"use client";
import SubTitle from "@/components/SubTitle"
import teamsdata from "@/data/teamsdata"
import useTeam from "@/hook/useTeam";
import Image from "next/image"
import iconTwitter from "@/public/assets/icon-twitter.png"
import iconLinkedin from "@/public/assets/icon-linkedin.png"
import Link from "next/link";
const Team: React.FC = () =>{
const seed = "foobar";
const { teamData } = useTeam(teamsdata.length, seed);
return(
<>
<div className="flex gap-10 flex-col team pt-[20vh] py-14 px-20 max-xl:px-14 max-lg:px-10 max-sm:px-5 font-raleway relative h-full">
<div className=" relative h-fit z-[1] flex flex-col gap-5 max-md:gap-2 items-start">
<SubTitle># Full Team Here!</SubTitle>
<h2 className="text-heading2 max-lg:text-heading3 max-md:text-pXXL font-dmBricolage font-semibold mb-5 max-md:mb-2">Our Team</h2>
<p className="text-pLg md:text-pXL xl:text-pXXL text-gray-300">The people behind our great works.</p>
</div>
<div className=" flex flex-col gap-5 xl:gap-10">
<div className="flex flex-col gap-5">
<hr className="w-[50px] border-2 rounded-full " />
<p className="text-pSm md:text-pLg xl:text-pXL text-gray-300">At DMRTech, we are proud to have a diverse and talented team of professionals dedicated to delivering top-notch web development services. Our team consists of experts in front end and back end development, UI/UX design, brand and product design, and search engine optimization..</p>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-10 team-box">
{teamsdata.map((data, index) => (
<div key={index} className=" shadow-shadowStripe team-member rounded-3xl pt-10 flex flex-col gap-2 items-start bg-dspBlack text-white ">
{teamData[index] && (
<>
<Image
src={teamData[index].picture.large}
alt={`${teamData[index].name.first} ${teamData[index].name.last}'s picture`}
width={200}
height={200}
className="rounded-full self-center "
/>
<div className="p-5 w-full">
<div className="bg-dspLimeGreen shadow-lg shadow-gray-800 w-full p-5 text-black rounded-3xl">
<h3 className="text-pXXL font-bold font-dmBricolage">{teamData[index].name.first}-{teamData[index].name.last}</h3>
<p className="text-pSm">{data.job}</p>
<p className="lg:text-pXL text-pMd font-medium "> {teamData[index].email} </p>
<p className="lg:text-pXL text-pMd font-medium ">{teamData[index].phone}</p>
</div>
</div>
</>
)}
<div className=" flex flex-col p-5 gap-5">
<p className="w-fit text-pLg line-clamp-5 ">{data.experience}</p>
<div className="flex gap-5">
<div className="bg-dspGray rounded-full p-3 hover:bg-dspLightGray cursor-pointer">
<Link href="https://linkedin.com">
<Image
src={iconLinkedin}
width={30}
alt="linkedin"
className=""/>
</Link>
</div>
<div className="bg-dspGray rounded-full p-3 hover:bg-dspLightGray cursor-pointer">
<Link href="https://twitter.com">
<Image
width={30}
src={iconTwitter}
alt="twitter"
className=""/>
</Link>
</div>
</div>
</div>
</div>
))}
</div>
</div>
</div>
</>
)
}
export default Team
|
const express = require("express");
const createError = require("http-errors");
const subCategory = require("../models/SubCategory");
const { id } = require("../utilities/validation-schemas/subCategorySchema");
const subCategorySchema = require('../utilities/validation-schemas/subCategorySchema');
const resS = require('../utilities/sendFormat');
module.exports = {
//Add New Sub Category
Create: async (req, res, next) => {
try {
let body = req.body;
const result = await subCategorySchema.validateAsync(body);
const subcategory = new subCategory({ ...result, createdBy: req.user._id });
subcategory.catId = req.body.catId;
const newSubCat = await subcategory.save();
return resS.send(res, `SUb Category Created`, newSubCat);
} catch (error) {
if (error.isJoi === true) error.status = 422
next(error);
}
},
// Get All Sub Category
Get: async (req, res, next) => {
try {
const data = await subCategory.aggregate([
{ $match: { isDeleted: false } },
{
$lookup: {
from: 'category',
localField: 'catId',
foreignField: '_id',
as: 'catId'
}
},
{
$lookup: {
from: 'users',
localField: 'createdBy',
foreignField: '_id',
as: 'createdBy'
}
}, {
$unwind: {
path: '$createdBy',
preserveNullAndEmptyArrays: true
}
},
{
$lookup: {
from: 'users',
localField: 'updatedBy',
foreignField: '_id',
as: 'updatedBy'
}
}, {
$unwind: {
path: '$updatedBy',
preserveNullAndEmptyArrays: true
}
},
{
$project: {
catId: { name: 1, _id: 1 },
name: 1,
createdBy: { fullName: 1, _id: 1 },
updatedBy: { fullName: 1, _id: 1 },
createdAt: { $dateToString: { date: '$createdAt', format: '%Y-%m-%d %H:%M' } },
updatedAt: { $dateToString: { date: '$updatedAt', format: '%Y-%m-%d %H:%M' } }
}
},
]);
return resS.send(res, `SubCategory Fetch`, data);
} catch (error) {
if (error.isJoi === true) error.status = 422;
next(error);
}
},
// Get Sub Category By Id
GetById: async (req, res, next) => {
try {
const { subCatId } = req.params
if (!subCatId) throw createError.NotFound(`Sub CatId Not Found`);
const data = await subCategory.findOne({ _id: subCatId, isDeleted: false }).populate('catId', 'name').populate('createdBy', 'fullName');
if (data)
return resS.send(res, `Fetch Data`, data);
else return resS.sendError(res, 404, `Sub Category Not Found`, {});
} catch (error) {
if (error.isJoi === true) error.status = 422
next(error);
}
},
// Get Sub Category By Cat Id
GetByCatId: async (req, res, next) => {
try {
const { catId } = req.params
if (!catId) throw createError.NotFound(`CatId Not Found`);
const data = await subCategory.find({ catId, isDeleted: false }).populate('catId', 'name').populate('createdBy', 'fullName ');
if (data.length > 0) {
return resS.send(res, `Fetch Data`, data);
} else {
return resS.sendError(res, 404, `Sub Category Not Found`, {});
}
} catch (error) {
if (error.isJoi === true) error.status = 422
next(error);
}
},
// Get Sub Category By StoreId
GetByStoreId: async (req, res, next) => {
try {
const { storeId } = req.params
if (!storeId) throw createError.NotFound(`Store Id Not Found`);
const data = await subCategory.find({ storeId, isDeleted: false }).populate('catId', 'name').populate('createdBy', 'firstName lastName');
res.status(200).send(data);
} catch (error) {
if (error.isJoi === true) error.status = 422
next(error);
}
},
// Update Sub Category
Update: async (req, res, next) => {
try {
const { subCatId } = req.params;
if (!subCatId) throw createError.NotFound(`Please provide sub-category id`);
const result = await subCategorySchema.validateAsync(req.body);
const data = await subCategory.findOneAndUpdate({ _id: subCatId }, { $set: result, updatedBy: req.user._id }, { new: true }).populate('catId', 'name').populate('updatedBy', 'fullName');
return resS.send(res, `SubCategory Update`, data);
} catch (error) {
console.log('Error while updating Sub Category', error)
if (error.isJoi === true) error.status = 422
next(error);
}
},
// Delete Sub Category By Id
Delete: async (req, res, next) => {
try {
const { id } = req.params
if (!id) throw createError.NotFound(`Sub Cat Id Not Found`);
const data = await subCategory.findByIdAndUpdate({ _id: id }, { isDeleted: true, updatedBy: req.user._id });
if (data) {
if (data.isDeleted == false) {
return resS.send(res, `SubCategory Deteled`);
} else {
return resS.sendError(res, 202, `SubCategory Already Deleted`, {});
}
} else {
return resS.sendError(res, 404, `SubCategory Not Found`, {});
}
} catch (error) {
if (error.isJoi === true) error.status = 422
next(error);
}
}
}
|
import * as React from 'react';
import { useState } from 'react';
import AppBar from '@mui/material/AppBar';
import { styled } from '@mui/material/styles';
import { Toolbar, Box, Typography, IconButton, Drawer } from '@mui/material';
import Search from './Search'
import CustomButtons from './CustomButtons'
import { Link } from 'react-router-dom';
import { Menu } from '@mui/icons-material';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
const CustomizedSlider = styled(AppBar)`
color: #20b2aa;
background: #2874f0;
height: 55px;
`;
const Components = styled(Link)`
margin-left: 12%;
line-height: 0;
color: #FFFFFF;
text-decoration: none;
`;
const SubHeading = styled(Typography)`
font-size: 10px;
font-style: italic;
color: #eee;
`;
const PlusImage = styled(`img`)({
width: 14,
height: 14,
marginLeft: 6
})
const MenuButton = styled(IconButton)(({ theme }) => ({
display: 'none',
[theme.breakpoints.down('md')]: {
display: 'block',
color: '#fff'
}
}));
const CustomButtonsWrapper = styled('Box')(({ theme }) => ({
margin: '0 0 0 auto',
[theme.breakpoints.down('md')]: {
display: 'none'
}
}));
const Header = () => {
const handleOpen = () => {
setOpen(true);
}
const handleClose = () => {
setOpen(false);
}
const [open, setOpen] = useState(false)
const logoURL = 'https://static-assets-web.flixcart.com/www/linchpin/fk-cp-zion/img/flipkart-plus_8d85f4.png';
const subURL = 'https://static-assets-web.flixcart.com/www/linchpin/fk-cp-zion/img/plus_aef861.png';
return (
<CustomizedSlider>
<Toolbar style={{ minHeight: 55 }}>
<MenuButton
color="inherit"
onClick={handleOpen}
>
<Menu />
</MenuButton>
<Drawer open={open} onClose={handleClose}>
<Box style={{ width: 200 }} onClose={handleClose}>
<List>
<ListItem button>
<CustomButtons />
</ListItem>
</List>
</Box>
</Drawer>
<Components to='/'>
<img src={logoURL} alt='logo' style={{ width: 76 }} />
<Box style={{ display: 'flex' }}>
<SubHeading>Explore
<Box component='span' style={{ color: `#ffe500` }}> Plus</Box>
</SubHeading >
<PlusImage src={subURL} alt='sub-logo' />
</Box>
</Components>
<Search />
<CustomButtonsWrapper>
<CustomButtons />
</CustomButtonsWrapper>
</Toolbar>
</CustomizedSlider>
)
}
export default Header;
|
# Jenkins + Gitlab Execises
### Configuração inicial do Jenkins
1 - Na tela inicial do Jenkins acessar a opção Credentials
2 - Em Stores scoped to Jenkins selecione (global)
3 - Clique em Add Credentials
4 - Mantenha as opções Kind e Scope como estão (Username with password / Global)
5 - Em Username insira root
6 - Em Password coloque a senha da sua instância do Gitlab
7 - Em Description coloque Credenciais do Gitlab
8 - Clique em OK.
### Criar pipeline no Jenkins
1 - Criar um projeto novo no gitlab chamado testapp em modo privado e inicialize com um arquivo README.md
2 - Criar no jenkins um novo item do tipo pipeline com nome testapp
3 - Em Description insira test Application
4 - Na parte do Pipeline > Definition selecione Pipeline script from SCM
4.1 - SCM selecione Git
4.2 - Em repository URL coloque a URL HTTP de clone do projeto que consta no Gitlab.
4.3 - Em Credentials selecione a credencial criada no passo de configuração inicial do Jenkins.
4.4 - Em Branche to build mantenha com a opção */master
4.5 - Repository Browser mantenha como (Auto)
4.6 - Manteha Script Path como está: Jenkinsfile
4.7 - Clique em Save
5 - Faça o clone do repositório do projeto na raiz da pasta 02: `git clone http://192.168.197.100:8088/root/testapp.git`
6 - Crie uma arquivo vazio chamado Jenkinsfile dentro da pasta testapp: `touch Jenkinsfile`
7 - Insira o conteúdo abaixo no arquivo Jenkinsfile:
### Exemplo de pipeline as code com parâmetros
pipeline {
agent any
parameters {
string(
name: 'Parametro1',
defaultValue: '',
description: 'Exenplo de parametro.'
)
}
environment {
var1 = "EXEMPLO DE VARIAVEL"
}
stages {
stage('Pergunta') {
input {
message "Devo continuar?"
ok "Sim, deve."
parameters {
string(name: 'PERSON', defaultValue: 'Sr Jenkins', description: 'Para quem eu digo olá?')
}
}
steps {
echo "Olá, ${PERSON}, prazer em conhecê-lo."
}
}
stage ("Prepare") {
when {
expression {
return "${params.Parametro1}" != '';
}
}
steps {
sh("echo ${var1}")
sh("ls -Rla")
sh("hostname")
sh("ping -c10 google.com")
sh("[ -e /tmp/teste ] || mkdir /tmp/teste")
sh("echo ${params.Parametro1}")
}
}
stage ("Validate") {
when {
expression {
return "${params.Parametro1}" != '';
}
}
steps {
sh("echo Acabou o Pipeline!!!!!")
}
}
}
}
### Configurar jenkins para build automático ao receber updates no gitlab
No jenkins exeute os passos abaixo:
1 - Acessar o pipeline testapp
2 - Clicar em configure
3 - Em Build Triggers habilitar a opção Build when a change is pushed to GitLab. GitLab webhook URL: http://192.168.197.100:8080/project/testapp
4 - Clicar em advanced e em Generate para gerar o Secret Token
No Gitlab execute os passos abaixo:
1 - Acessa aárea de administração do Gitlab e libere o acesso a hooks oriundos da rede local indo em Settings > Network > Outbound requests
2 - Habilite a opção Allow requests to the local network from hooks and services
3 - Volte ao projeto testapp e acesse o menu Settings > Integrations
4 - Em URL insira a URL que aparece no Jenkins como webhook do pipeline
5 - Em Secret Token insira o token gerado no Jenkins para esta conexão
6 - Em Trigger habilite os eventos de Push insira master no campo de texto informando o branch que irá enviar os eventos de push para o Jenkins
7 - Role a página para baixo e desmrque a opção Enable SSL verfication
8 - Por fim clique em Add webhook
9 - Envie um evento de teste de Push clicando em Test logo ao lado do hook recém criado e verificque no Jenkins se o pipeline foi disparado com
a mensagem "Started by Gitlab push by Administrator"
### Slack - Integrations
1º criar conta Slack
Adcionar app do Jenkins ci e escolher canal
Seguir passo-a-passo do site do Slack
Efetuar teste de conexão depois de configurado o canal
def call(Map options = [:]) {
node {
cleanWs()
stage ('Checkout') {
checkout scm
}
stage('Prepare') {
sh("echo Prepare stage...")
sh("ls -Rla")
}
stage('Build') {
sh("echo Build stage...")
sh("hostname")
}
stage('Test') {
sh("echo Test stage...")
sh("ping -c10 google.com")
}
stage('Deploy') {
sh("echo Deploy stage...")
sh("[ -e /tmp/teste ] || mkdir /tmp/teste")
}
stage('Notify') {
buildStatus = currentBuild.currentResult ?: 'SUCCESS'
def emoji = buildStatus == 'SUCCESS' ? ':wink:' : ':sob:';
try {
slackSend (
channel: '#jenkins',
message: """${emoji} *${env.JOB_NAME}* build#${env.BUILD_NUMBER} ${buildStatus}
Details: ${env.BUILD_URL}""",
rawMessage: true
)
} catch (e) {
echo 'Error trying to send Slack notification: ' + e.toString()
}
}
}
}
|
import {useEffect, useState} from "react";
import {ILang} from "../context/LanguageContext";
const storageName = 'userLanguage'
interface IStorageLang {
currentLanguage: ILang
}
export const useLanguage = () => {
const [language, setLanguage] = useState<ILang>(null)
useEffect(() => {
const storageLang: IStorageLang = JSON.parse(localStorage.getItem(storageName) || '{}')
if (storageLang && storageLang.currentLanguage) {
setLanguage(storageLang.currentLanguage)
} else {
setLanguage('RU')
}
}, [])
useEffect(() => {
if (language !== null) {
const newStorageLang: IStorageLang = {
currentLanguage: language
}
localStorage.setItem(storageName, JSON.stringify(newStorageLang))
}
}, [language])
return {language, setLanguage}
}
|
package category
import (
"api/app/config"
"api/app/lib"
"api/app/middleware"
"api/app/model"
"api/app/services"
"testing"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/utils"
"github.com/spf13/viper"
)
func TestGetCategory(t *testing.T) {
db := services.DBConnectTest()
lib.LoadEnvironment(config.Environment)
app := fiber.New()
app.Use(middleware.TokenValidator())
app.Get("/categories", GetCategory)
initial := model.Category{
CategoryAPI: model.CategoryAPI{
Code: nil,
Name: nil,
},
}
db.Create(&initial)
headers := map[string]string{
viper.GetString("HEADER_TOKEN_KEY"): viper.GetString("VALUE_TOKEN_KEY"),
}
uri := "/categories?page=0&size=1"
response, body, err := lib.GetTest(app, uri, headers)
utils.AssertEqual(t, nil, err, "sending request")
utils.AssertEqual(t, 200, response.StatusCode, "getting response code")
utils.AssertEqual(t, false, nil == body, "validate response body")
utils.AssertEqual(t, float64(1), body["total"], "getting response body")
// test invalid token
response, _, err = lib.GetTest(app, uri, nil)
utils.AssertEqual(t, nil, err, "sending request")
utils.AssertEqual(t, 401, response.StatusCode, "getting response code")
sqlDB, _ := db.DB()
sqlDB.Close()
}
|
### **1. Operational Analysis**
- **Identify Operational Scenarios**: Define how users will interact with the app. For example, monitoring changes in MongoDB, processing new entries, and managing files.
- **Use Cases**: Document use cases such as "monitoring new conversations," "extracting code snippets," and "saving file metadata."
### **2. System Need Analysis**
- **System Requirements**: Based on the operational scenarios, identify the key requirements. For example, "The system must handle MongoDB change streams," "The system must extract and save code snippets," etc.
- **Functional Analysis**: Break down these requirements into functional components. Identify functions such as "watch for changes," "process new entries," and "save file metadata."
### **3. Logical Architecture**
- **Logical Components**: Define the logical components required for your app. For instance, "MongoDBWatcher," "CodeSnippetExtractor," and "MetadataManager."
- **Interactions**: Model how these components interact. For example, the **`MongoDBWatcher`** triggers the **`CodeSnippetExtractor`**, which then uses **`MetadataManager`** to save the data.
### **4. Physical Architecture**
- **Physical Components**: Map the logical components to actual implementation classes and modules. For example, the **`MongoDBWatcher`** class, the **`extract_code_snippets`** function, etc.
- **Infrastructure**: Define the physical infrastructure, such as the MongoDB instance, file system for saving snippets, and any external APIs or services.
### **5. Component Design**
- **Detailed Design**: Specify the design of each component. For instance, the **`MongoDBWatcher`** class needs methods for watching changes and registering handlers.
- **Interfaces**: Define the interfaces between components. For example, the format of the data passed from the watcher to the extractor.
### **6. Validation and Verification**
- **Validation**: Ensure the architecture meets the initial requirements. This might include testing the end-to-end flow of monitoring changes and processing entries.
- **Verification**: Verify that each component performs as expected. For instance, ensure that code snippets are correctly extracted and saved, and metadata is accurately recorded.
### **Example: Refining Data Workflow**
### **Step 1: Define Operational Scenarios**
- Monitoring new entries in MongoDB.
- Processing new conversation documents to extract code snippets.
- Saving the extracted snippets and recording metadata.
### **Step 2: Identify Key Requirements**
- The app must handle change streams from MongoDB.
- The app must extract code snippets accurately.
- The app must save snippets to files and record metadata.
### **Step 3: Develop Logical Architecture**
- **Components**:
- **`MongoDBWatcher`**: Monitors MongoDB for new entries.
- **`CodeSnippetExtractor`**: Extracts code snippets from conversation content.
- **`FileManager`**: Saves snippets to files and manages directories.
- **`MetadataManager`**: Saves metadata about the snippets to MongoDB.
- **Interactions**:
- **`MongoDBWatcher`** -> **`CodeSnippetExtractor`** -> **`FileManager`**
- **`FileManager`** -> **`MetadataManager`**
### **Step 4: Create Physical Architecture**
- Implement classes for each logical component.
- Set up MongoDB collections and file storage infrastructure.
### **Step 5: Detail Component Design**
- Design **`MongoDBWatcher`** with methods to handle change streams.
- Implement **`CodeSnippetExtractor`** with logic to identify and extract code blocks.
- Develop **`FileManager`** to create directories and save files.
- Implement **`MetadataManager`** to record file metadata.
### **Step 6: Validate and Verify**
- Test the overall system by simulating new entries in MongoDB.
- Validate that snippets are extracted and saved correctly.
- Verify that metadata is recorded accurately in the database.
|
/* eslint-disable prefer-const */
import { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common';
import { isNumberString } from 'class-validator';
import { PrismaFindManyDto } from 'src/globalDtos/prisma-find-many.dto';
@Injectable()
export class ParsePrismaFindManyParamsPipe implements PipeTransform {
async transform(value: any, metadata: ArgumentMetadata): Promise<any | PrismaFindManyDto> {
if (metadata.type !== 'query') return value;
let { page, skip, take, sort_by } = value;
if (skip == undefined) {
skip = 0;
}
value.where = await this.transformFilters(value);
if (sort_by) {
const sort = await this.transformSort(sort_by);
value.orderBy = sort;
}
value.skip = !page || page === 1 ? skip : skip + take * (page - 1);
delete value.page;
delete value.sort_by;
return value;
}
async transformSort(sort_by: string) {
const query = sort_by.split('.');
let orderBy = {};
orderBy[query[0]] = query[1];
return orderBy;
}
async transformFilters(value: any) {
let where = {};
let mainParams = ['page', 'skip', 'take', 'sort_by', 'filter'];
for (let [key, values] of Object.entries(value)) {
if (!mainParams.includes(key)) {
where[key] = isNumberString(values) ? Number(values) : values;
if (key == 'name' || key == 'description') {
where[key] = { startsWith: values.toString() };
}
delete value[key];
}
if (key == 'filter') {
for (let [filterName, filterValue] of Object.entries(values)) {
let splittedOptions = filterName.split(':');
if (splittedOptions.length == 3) {
filterValue = eval(filterValue);
let [name, keyName, operand] = splittedOptions;
where[name] = { some: { [keyName]: { [operand]: filterValue } } };
} else if (splittedOptions.length == 2) {
let searchValue;
try {
searchValue = eval(filterValue);
} catch {
searchValue = filterValue;
}
let [name, keyName] = splittedOptions;
where[name] = { [keyName]: searchValue };
}
}
delete value[key];
}
}
return where;
}
}
|
<template>
<div class="app-features-details">
<AppFeatureDetail v-for="appFeature in appFeatures"
:imagePositionStart=appFeature.imagePositionStart
:image=appFeature.image
:imageDescription=appFeature.imageDescription
:title=appFeature.title
:description=appFeature.description
/>
</div>
</template>
<script>
export default {
data() {
return {
appFeatures: [
{
imagePositionStart: false,
image: "/images/eventfahrplan-tablet-events-640x480.png",
imageDescription: "Grid schedule view on a tablet",
title: "View program by day and rooms (side by side)",
description: "You are looking for guidance at an event? We've got you prepared. The schedule screen presents all sessions in a neatly arranged grid, one column for each virtual or physical room. You can navigate between the rooms by swiping horizontally. A vertical swipe takes you to sessions at an earlier or later point in time.\n\n" +
"You never loose track. This grid presentation allows you to intuitively understand which session take place in parallel or overlap so you can plan your day.\n\n" +
"You can focus. The screen only renders one day at a time. You can simply select another day by tapping the dropdown menu at the top."
},
{
imagePositionStart: true,
image: "/images/eventfahrplan-tablet-phone-layout-640x480.png",
imageDescription: "Six columns on a tablet in landscape mode and the four columns on a smartphone in landscape mode",
title: "Custom grid layout for smartphones and tablets",
description: "You choose your device - the app automatically adapts. Regardless of whether you run the app on a tablet, phablet or smartphone the layout is optimized to the available screen estate.\n\n" +
"On tablets sessions are shown in up to six columns in landscape and four columns in portrait mode. On smartphones one column is shown in portrait and four columns in landscape mode."
},
{
imagePositionStart: false,
image: "/images/eventfahrplan-tablet-smartphone-details-640x480.png",
imageDescription: "Details screen on a tablet and a smartphone",
title: "Read detailed descriptions",
description: "You have a place to rest. On the details screen you can comfortably read through the abstract and the long description of the session. Website links and email addresses are clickable right in the text. Additional website links are listed below the text if provided by the authors. At the bottom you find a link to the specific website of the selected session.\n\n" +
"You get all the information in one place. Title, subtitle, speaker names, room name and of course the start time are there so you don't have to search for them.\n\n" +
"While the session details are shown as a separate screen on a smartphone they open as an integrated view on the right side of your tablet in landscape mode."
},
{
imagePositionStart: true,
image: "/images/eventfahrplan-tablet-smartphone-favorites1-640x480.png",
imageDescription: "Add to favorites menu on a smartphone and star icon button on a tablet",
title: "Add events to favorites list",
description: "You create your personal program. In preparation for the event, during the happening or afterwards you can browse and choose sessions of your interest to compile a very personal program.\n\n" +
"You can mark a session as a favorite wherever you are. On the schedule screen long-tap a session to open the context menu and add it to your favorites. It will be highlighted once it is favored. On the details screen you can favor the opened session with one tap on the star icon at the top bar."
},
{
imagePositionStart: false,
image: "/images/eventfahrplan-tablet-smartphones-favorites2-640x480.png",
imageDescription: "Share event menu on a smartphone and favorites on a tablet",
title: "Manage your favorites",
description: "Your selection in one place. Once you have marked all your sessions they are visually highlighted on the schedule screen. Additionally, the favorites screen shows them in chronological order separated by days.\n\n" +
"You can easily share. Do you want to advertise a very interesting talk on social media or notify a friend of an upcoming workshop? No problem! Long-tap a session on the schedule screen to open the context menu and share the session - or tap the share icon at the top bar if you have the details screen open.\n\n" +
"Your data is available. If you have the favorites screen open and you tap the share icon at top bar then you can export all your favorites in one step."
},
{
imagePositionStart: true,
image: "/images/eventfahrplan-tablet-smartphones-alarms-640x480.png",
imageDescription: "Set alarm menu and choose alarm times on a smartphone and alarms screen on a tablet",
title: "Setup alarms for individual events",
description: "You won't miss a session. It can be challenging to remember all talks and workshops at a larger conference. No worries - we've got you covered. You can setup alarms for individual sessions.\n\n" +
"You choose your alarm time. On the schedule screen long-tap a session to open the context menu and set an alarm. On the details screen tap the bell icon at the top bar.\n\n" +
"You customize alarms to your taste. On the settings screen you can select the default alarm time, enable insistent alarms and pick the alarm tone."
},
{
imagePositionStart: false,
image: "/images/eventfahrplan-tablet-smartphone-calendar-640x480.png",
imageDescription: "Calendar icon on a smartphone and on a tablet",
title: "Add events to your personal calendar",
description: "You have the full session information available to add it to your calendar if you like to. The start and end time of the session are automatically used to construct the correct time and duration of the calendar entry.\n\n" +
"On the schedule screen long-tap a session and choose add to calendar. On the details screen tap the calendar icon at the top bar."
},
{
imagePositionStart: true,
image: "/images/eventfahrplan-tablet-smartphone-settings-updates-640x480.png",
imageDescription: "Automatic updates settings on a smartphone and on a tablet ",
title: "Make use of automatic program updates",
description: "You are up-to-date at all times. Regardless whether a session is added, moved to a new room or even canceled - you are informed. The app periodically checks for program updates and loads them from the server if needed.\n\n" +
"You decide. You can disable automatic updates on the settings screen. To manually retrieve program updates visit the schedule screen and tap the refresh item in the overflow menu at the top bar."
},
{
imagePositionStart: false,
image: "/images/eventfahrplan-tablet-smartphone-changes-640x480.png",
imageDescription: "Schedule changes on a smartphone and on a tablet",
title: "Keep track of program changes",
description: "You know what changed. Whenever the program changes then the app notifies you about it.\n\n" +
"You won't miss it. There are three places where changes are communicated: the app shows a notification at the top status bar, a dialog with a short summary of the changes and the schedule changes screen.\n\n" +
"You know what changes. The schedule changes screen lists all sessions which changed since the last program update. You can easily spot if a speaker was added, the language was specified or a session was moved to the afternoon."
},
{
imagePositionStart: true,
image: "/images/eventfahrplan-tablet-smartphone-vote-640x480.png",
imageDescription: "Feedback icon on a smartphone and on a tablet",
title: "Vote and leave comments on talks and workshops",
description: "Your opinion will be heard. You enjoyed a session so much that you want to tell the speakers? Please do so.\n\n" +
"Depending on the backend system you can leave a textual comment for the speakers and rate the talk via a five-stars system. Your response is only accessible to the speakers and the conference organizers.\n\n" +
"To provide feedback open the session details screen and tap the feedback icon at the top bar."
}
]
}
}
}
</script>
|
import {Component} from "react";
import {CarList} from "../components/CarList/CarList";
import initialCarList from "../components/Data/data.json";
import {SearchBar} from "../components/SearchBar/SearchBar";
class CatalogPage extends Component {
state = {
carsList: initialCarList,
filters: {
brand: "all",
price: "all",
distanceFrom: "",
distanceTo: "",
},
};
changeFilter = (key, value) => {
this.setState((prevState) => ({
filters: {...prevState.filters, [key]: value},
}));
};
getVisibleItem = () => {
const {carsList, filters} = this.state;
return carsList.filter(
(item) =>
(item.make === filters.brand || filters.brand === "all") &&
(item.rentalPrice === filters.price || filters.price === "all") &&
item.mileage >= filters.distanceFrom &&
(item.mileage <= filters.distanceTo || filters.distanceTo === "")
);
};
render() {
console.log(this.state);
const {filters} = this.state;
const visibleItems = this.getVisibleItem();
return (
<div>
<h2>Catalog Page</h2>
<SearchBar filters={filters} onChangeFilter={this.changeFilter} />
<CarList items={visibleItems} />
</div>
);
}
}
export default CatalogPage;
|
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Admins Page</title>
<link rel="stylesheet" th:href="@{/resources/css/bootstrap.css}">
</head>
<body>
<div th:replace="page/admin/adminHeader.html :: header"></div>
<table class="table table-striped table-bordered">
<caption>Admins table</caption>
<thead class="table-dark">
<tr>
<th scope="col" th:text="ID">ID</th>
<th scope="row" th:text="#{th.username}">Username</th>
<th scope="row" th:text="#{th.role}">Role</th>
<th scope="row" th:text="#{label.name}">Name</th>
<th scope="row" th:text="#{label.surname}">Surname</th>
<th scope="row" th:text="#{label.phone}">Phone</th>
<th scope="row" th:text="#{label.email}">Email</th>
<th scope="col" th:text="#{th.level}">level</th>
</tr>
</thead>
<tbody>
<tr th:each="user:${allLibrarians}">
<td th:text="${user.id}"></td>
<td th:text="${user.username}"></td>
<td th:text="${user.role}"></td>
<td th:text="${user.userData.name}"></td>
<td th:text="${user.userData.surname}"></td>
<td th:text="${user.userData.phoneNumber}"></td>
<td th:text="${user.userData.emailAddress}"></td>
<td th:text="${user.level}"></td>
</tr>
</tbody>
</table>
<nav aria-label="Page navigation example">
<ul class="pagination">
<li class="page-item" th:each="page,iterStat:${countPages}">
<a class="page-link" th:href="@{'?offset='+${page}}" th:text="${iterStat.count}"></a>
</li>
</ul>
</nav>
<div th:replace="page/admin/adminFooter.html :: footer"></div>
<script th:src="@{/resources/js/bootstrap.js}"></script>
</body>
</html>
|
import { useEffect, useState } from 'react';
export type ColorTheme = 'dark' | 'light';
export const usePreferredTheme = (): ColorTheme => {
const isDarkPreferred =
typeof window === 'object' && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
const [theme, setTheme] = useState<ColorTheme>(() => (isDarkPreferred ? 'dark' : 'light'));
useEffect(() => {
const handler = (event: MediaQueryListEvent): void => {
setTheme(event.matches ? 'dark' : 'light');
};
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', handler);
return () => {
window.matchMedia('(prefers-color-scheme: dark)').removeEventListener('change', handler);
};
}, []);
return theme;
};
|
package ru.protei.portal.core.model.api;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
import ru.protei.portal.core.model.dict.En_Currency;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@JsonAutoDetect(
getterVisibility = JsonAutoDetect.Visibility.NONE,
setterVisibility = JsonAutoDetect.Visibility.NONE,
fieldVisibility = JsonAutoDetect.Visibility.ANY
)
public class ApiContract implements Serializable {
@JsonProperty("ref_key")
private String refKey;
@JsonProperty("date_signing")
private Date dateSigning;
@JsonProperty("cost")
private Double cost;
@JsonProperty("cost_currency")
private En_Currency currency;
@JsonProperty("cost_vat")
private Long vat;
@JsonProperty("subject")
private String description;
@JsonProperty("directions")
private String directions;
@JsonProperty("is_ministry_of_defence")
private Boolean isMinistryOfDefence;
@JsonProperty("dates")
private List<ApiContractDate> dates;
@JsonProperty("calculation_type")
private String calculationType;
public ApiContract() {
}
public String getRefKey() {
return refKey;
}
public void setRefKey(String refKey) {
this.refKey = refKey;
}
public Date getDateSigning() {
return dateSigning;
}
public void setDateSigning(Date dateSigning) {
this.dateSigning = dateSigning;
}
public Double getCost() {
return cost;
}
public void setCost(Double cost) {
this.cost = cost;
}
public En_Currency getCurrency() {
return currency;
}
public void setCurrency(En_Currency currency) {
this.currency = currency;
}
public Long getVat() {
return vat;
}
public void setVat(Long vat) {
this.vat = vat;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDirections() {
return directions;
}
public void setDirections(String directions) {
this.directions = directions;
}
public Boolean getMinistryOfDefence() {
return isMinistryOfDefence;
}
public void setMinistryOfDefence(Boolean ministryOfDefence) {
isMinistryOfDefence = ministryOfDefence;
}
public List<ApiContractDate> getDates() {
return dates;
}
public void setDates(List<ApiContractDate> dates) {
this.dates = dates;
}
public String getCalculationType() {
return calculationType;
}
public void setCalculationType(String calculationType) {
this.calculationType = calculationType;
}
@Override
public String toString() {
return "ApiContract{" +
"refKey='" + refKey + '\'' +
", dateSigning=" + dateSigning +
", cost=" + cost +
", currency=" + currency +
", vat=" + vat +
", description='" + description + '\'' +
", directions='" + directions + '\'' +
", isMinistryOfDefence=" + isMinistryOfDefence +
", dates=" + dates +
", calculationType='" + calculationType + '\'' +
'}';
}
}
|
# Write a function called count_primes() that requires a single
# numeric argument.
# This function must display on the screen how many prime
# numbers there are in the range from zero to that number
# included, and then return the number of prime numbers found.
# Note: By convention 0 and 1 are not considered prim
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def count_primes(n):
prime_count = 0
for i in range(n + 1):
if is_prime(i):
prime_count += 1
print(f"There are {prime_count} prime numbers in the range from 0 to {n}.")
return prime_count
result = count_primes(10)
print(f"Number of prime numbers: {result}")
|
import os
def clear_screen():
os.system("cls") #for windows#
class Users:
def __init__(self):
self.name = ""
self.symbol = ""
def Check_name(self):
while True:
name = input("enter your name(letters only) : ")
if name.isalpha():
self.name = name
break
print("please Cheack your name ")
def Check_symbol(self):
while True:
symbol = input(f"{self.name}, Enter a single letter X or O : ").upper()
if symbol.isalpha() and len(symbol) == 1:
if symbol != "X" and symbol != "O":
print("Only X or O are allowed.")
else:
self.symbol = symbol
break
else:
print("Invalid symbol. Please enter a single letter.")
class Menu:
def Display_main_menu(self):
print("welcome to Tic Tac Toe Game")
print("1.Start Game")
print("2.Quit Game")
while True:
choice = input("Enter your choice 1 or 2 : ")
if choice == "1" or choice == "2":
return choice
else :
print("invalid please check your choice")
def Display_end_game(self):
print("Game is over")
print("1.Restart Game")
print("2.Quit Game")
while True:
choice = input("Enter your choice 1 or 2 : ")
if choice == "1" or choice == "2":
return choice
else :
print("invalid please check your choice")
class Board:
def __init__(self):
self.board = [str(i)for i in range(1,10)]
def Display_board(self):
for i in range(0, 9, 3):
print("|".join(self.board[i:i+3]))
if i < 6 : ##
print("-"*5)
def Update_board(self,choice,symbol):
if self.Is_valid_move(choice):
self.board[choice-1] = symbol
return True
return False
def Is_valid_move(self,choice):
return self.board[choice-1].isdigit() #SOLID Principles Single Responsibility Principle (SRP):
def reset_board(self):
self.board = [str(i)for i in range(1,10)]
class game:
def __init__(self):
self.players = [Users(),Users()]
self.menu = Menu()
self.board = Board()
self.player_index = 0
def Start_game(self):
choice = self.menu.Display_main_menu()
if choice == "1":
clear_screen()
self.set_up_player()
self.Play_game()
else:
self.Quit_game()
def set_up_player(self):
for number, player in enumerate(self.players, start=1): #search about this function in loop
print(f"player{number}, Please enter your Details :")
player.Check_name()
player.Check_symbol()
clear_screen()
def Play_game(self):
while True:
self.turn_game()
if self.check_win():
print("Congratulations.you win")
choice = self.menu.Display_end_game()
if choice == "1":
self.restart_game()
else:
self.Quit_game()
break
elif self.check_draw():
print("Draw!!")
choice = self.menu.Display_end_game()
if choice == "1":
self.restart_game()
else:
self.Quit_game()
break
def turn_game(self):
player = self.players[self.player_index]
self.board.Display_board()
print(f"{player.name}'s turn ({player.symbol})")
while True:
try:
cell_choice = int(input("enter between 1 and 9 : " ))
if 1<= cell_choice <= 9 and self.board.Update_board(cell_choice,player.symbol):
break
else:
print("invalid move.try again") #if th cell is filled
except ValueError :
print("error. please choose between only 1 and 9") # if he does not enter between one and nin 1/9
clear_screen()
self.Switch()
def Switch(self):
self.player_index = 1 - self.player_index
def check_win(self):
win_comb = [
[0,1,2],[3,4,5],[6,7,8],
[0,3,6],[1,4,7],[2,5,8],
[0,4,8],[2,4,6]
]
for comb in win_comb:
if (self.board.board[comb[0]] == self.board.board[comb[1]] == self.board.board[comb[2]]):
return True
return False
def check_draw(self):
return all(not cell.isdigit() for cell in self.board.board)
def restart_game(self):
self.board.reset_board()
self.player_index = 0
self.Play_game()
def Quit_game(self):
print("Thank you for your playing!!")
|
package com.poohxx.uslovie
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.poohxx.uslovie.constance.Constance
import com.poohxx.uslovie.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
lateinit var bindingClass : ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
bindingClass = ActivityMainBinding.inflate(layoutInflater)
setContentView(bindingClass.root)
bindingClass.btResult.setOnClickListener {
Log.d("MyLog","id resource = ${R.drawable.director}")
val resultValue = bindingClass.edValue.text.toString()
bindingClass.userPic.visibility = View.VISIBLE
when(resultValue){
Constance.DIRECTOR -> {
bindingClass.tvResult.visibility = View.VISIBLE
val tempText = "Hello, Mr. Director" +
"Your salary is ${Constance.DIRECTOR_Salary}"
if (bindingClass.edValue2.text.toString() == Constance.DIRECTOR_PASSWORD){
bindingClass.tvResult.text = tempText
bindingClass.userPic.setImageResource(R.drawable.director)
}
else {
bindingClass.tvResult.text = "Wrong Name Employer or PIN-Code"
}
}
Constance.MANAGER -> {
bindingClass.tvResult.visibility = View.VISIBLE
val tempText = "Hello, Mr. Manager!" +
"Your salary is ${Constance.MANAGER_Salary}"
if (bindingClass.edValue2.text.toString() == Constance.MANAGER_PASSWORD){
bindingClass.tvResult.text = tempText
bindingClass.userPic.setImageResource(R.drawable.manager)
}
else {
bindingClass.tvResult.text = "Wrong Name Employer or PIN-Code"
}
}
Constance.ENGINEER -> {
bindingClass.tvResult.visibility = View.VISIBLE
val tempText= "Hello, Mr. Engineer!" +
" Your salary is ${Constance.ENGINEER_Salary}"
if (bindingClass.edValue2.text.toString() == Constance.ENGINEER_PASSWORD){
bindingClass.tvResult.text = tempText
bindingClass.userPic.setImageResource(R.drawable.engineer)
}
else {
bindingClass.tvResult.text = "Wrong Name Employer or PIN-Code"
}
}
Constance.OPERATOR -> {
bindingClass.tvResult.visibility = View.VISIBLE
val tempText= "Hello, Mr. Operator!" +
" Your salary is ${Constance.OPERATOR_Salary}"
if (bindingClass.edValue2.text.toString() == Constance.OPERATOR_PASSWORD){
bindingClass.tvResult.text = tempText
bindingClass.userPic.setImageResource(R.drawable.operator)
}
else {
bindingClass.tvResult.text = "Wrong Name Employer or PIN-Code"
}
}
else -> {
bindingClass.tvResult.visibility = View.VISIBLE
bindingClass.tvResult.text = "Employee isn't on the nameList"
}
}
}
}
}
|
import { CleverTapAnalyticsServiceOptions, kCleverTapId } from './types';
import {
AnalyticsService,
InternalUserProperties,
} from '@artsiombarouski/rn-analytics';
import clevertap from 'clevertap-web-sdk';
export class CleverTapAnalyticsService extends AnalyticsService {
private currentSiteParams: { [key: string]: any } = {};
constructor(readonly options: CleverTapAnalyticsServiceOptions) {
super('clevertap', options);
}
async init() {
clevertap.init(
this.options.accountId,
this.options.region,
this.options.domain,
);
}
async identifyUser(
id: string | undefined,
email: string | undefined = undefined,
): Promise<void> {
if (id) {
this.currentSiteParams.Identity = id;
}
if (email) {
this.currentSiteParams.Email = email;
}
clevertap.onUserLogin.push({
Site: this.currentSiteParams,
});
}
async onUserLogout(): Promise<void> {
this.currentSiteParams = {
Email: this.currentSiteParams.Email,
Identity: this.currentSiteParams.Identity,
};
}
async setUserProperties(
params: { [p: string]: any } & InternalUserProperties,
): Promise<void> {
const { name, first_name, last_name, phone, ...restParams } = params;
if (name) {
this.currentSiteParams['Name'] = name;
} else if (first_name || last_name) {
this.currentSiteParams['Name'] = `${first_name} ${last_name}`.trim();
}
if (phone) {
this.currentSiteParams['Phone'] = phone;
}
Object.assign(this.currentSiteParams, restParams);
clevertap.onUserLogin.push({
Site: this.currentSiteParams,
});
}
async event(name: string, params: { [p: string]: any }): Promise<void> {
clevertap.event.push(name, params);
}
async screen(name: string, params: { [p: string]: any }): Promise<void> {
clevertap.event.push('viewPage', params);
}
async collectUniqueIds(): Promise<{ [p: string]: string }> {
return {
[kCleverTapId]: clevertap.getCleverTapID(),
};
}
}
|
# Turtle Graphics Dog Drawing
This Python script uses the turtle module to create a drawing of a dog using various shapes and colors. The turtle graphics library provides an interactive way to create drawings and designs.
## Usage
- Ensure you have Python installed on your computer.
- Copy the provided code into a .py file, for example, dog_drawing.py.
- Open a terminal or command prompt and navigate to the directory containing the .py file.
- Run the script using the following command:
### python dog_drawing.py
The turtle graphics window will open, and you'll see a drawing of a dog.
## Description
The script uses various elements to create the dog drawing, including the head, eyes, mouth, feet, body, legs, and tail. Each element is defined with its position, size, and color. The rectangle function is used to draw the different shapes.
## Drawing the Dog
The turtle is set up with the initial position and settings.
The draw_dog function is defined to iterate through a list of dog elements, each with its position, size, and color. The rectangle function is called to draw each element.
After defining the draw_dog function, it's invoked to draw the complete dog.
## Example
For a visual example of the dog drawing created by the script, please refer to the turtle graphics window that opens when you run the script.
## License
This project is open-source and available under the MIT License.
|
import React from "react";
import * as CH from "@chakra-ui/react";
import { useTranslation } from "react-i18next";
import { GameContext, Player } from "duck";
import { AnimatePresence } from "framer-motion";
import { getWaitingList } from "./duck";
import { WaitingItem } from "./components";
const WaitingList = () => {
const { t } = useTranslation();
const {
state: {
currentRound,
game: { players },
},
} = React.useContext(GameContext);
const [waitingPlayers, setWaitingPlayers] = React.useState<Player[]>([]);
React.useEffect(() => {
setWaitingPlayers(getWaitingList(players, currentRound));
}, [players, currentRound]);
return (
<CH.Flex>
<CH.Text fontWeight="bold" fontSize="0.75rem" pt="0.125rem">
{!currentRound.phrase
? t("game.waitingStoryteller")
: t("game.waiting")}
:
</CH.Text>
<CH.Flex ml={2} gap={1} flexWrap="wrap">
{!currentRound.phrase && (
<WaitingItem
key={currentRound.narrator.nickname}
nickname={currentRound.narrator.nickname}
/>
)}
<AnimatePresence>
{currentRound.phrase &&
waitingPlayers.map((player: Player) => (
<WaitingItem
key={player.user.id}
nickname={player.user.nickname}
/>
))}
</AnimatePresence>
</CH.Flex>
</CH.Flex>
);
};
export default WaitingList;
|
/*
* Engineering Ingegneria Informatica S.p.A.
*
* Copyright (C) 2023 Regione Emilia-Romagna
* <p/>
* This program is free software: you can redistribute it and/or modify it under the terms of
* the GNU Affero General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
* <p/>
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
* <p/>
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see <https://www.gnu.org/licenses/>.
*/
package it.eng.parer.fascicoli.helper;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.Query;
import org.apache.commons.lang3.StringUtils;
import it.eng.parer.entity.DecModelloXsdFascicolo;
import it.eng.parer.entity.DecUsoModelloXsdFasc;
import it.eng.parer.entity.constraint.DecModelloXsdFascicolo.TiModelloXsd;
import it.eng.parer.entity.constraint.DecModelloXsdFascicolo.TiUsoModelloXsd;
import it.eng.parer.helper.GenericHelper;
import it.eng.parer.slite.gen.form.ModelliFascicoliForm;
import it.eng.spagoCore.error.EMFError;
/**
* @author DiLorenzo_F
*/
@SuppressWarnings({ "unchecked" })
@Stateless
@LocalBean
public class ModelliFascicoliHelper extends GenericHelper {
/**
* Ottiene la lista di modelli xsd abilitati per l'ambiente
*
* @param filtriModelliXsdTipiFasc
* filtro modelli xsd tipo fascicolo
* @param idAmbienteList
* lista id ambiente
* @param tiUsoModelloXsd
* tipo modello in uso xsd
* @param filterValid
* true per prendere i record attivi attualmente
*
* @return lista di modelli xsd
*
* @throws EMFError
* errore generico
*/
public List<DecModelloXsdFascicolo> retrieveDecModelloXsdTipoFascicolo(
ModelliFascicoliForm.FiltriModelliXsdTipiFascicolo filtriModelliXsdTipiFasc,
List<BigDecimal> idAmbienteList, String tiUsoModelloXsd, boolean filterValid) throws EMFError {
return retrieveDecModelloXsdTipoFascicolo(idAmbienteList, tiUsoModelloXsd, filterValid,
new Filtri(filtriModelliXsdTipiFasc));
}
/**
* Ottiene la lista di modelli xsd abilitati per l'ambiente
*
* @param idAmbienteList
* lista di ID ambiente
* @param tiUsoModelloXsd
* tipo uso del modello Xsd
* @param filterValid
* true per prendere i record attivi attualmente
* @param filtri
* filtri di ricerca
*
* @return lista di modelli xsd
*/
public List<DecModelloXsdFascicolo> retrieveDecModelloXsdTipoFascicolo(List<BigDecimal> idAmbienteList,
String tiUsoModelloXsd, boolean filterValid, Filtri filtri) {
StringBuilder queryStr = new StringBuilder(
"SELECT modelloXsdFascicolo FROM DecModelloXsdFascicolo modelloXsdFascicolo ");
String whereClause = " WHERE ";
if (!idAmbienteList.isEmpty()) {
queryStr.append(whereClause).append("modelloXsdFascicolo.orgAmbiente.idAmbiente IN (:idAmbienteList) ");
whereClause = " AND ";
}
if (!StringUtils.isEmpty(filtri.getFlAttivo())) {
if (filtri.getFlAttivo().equals("1")) {
queryStr.append(whereClause)
.append("(modelloXsdFascicolo.dtIstituz <= :data AND modelloXsdFascicolo.dtSoppres >= :data) ");
} else {
queryStr.append(whereClause)
.append("(modelloXsdFascicolo.dtIstituz > :data OR modelloXsdFascicolo.dtSoppres < :data) ");
}
whereClause = " AND ";
}
if (!StringUtils.isEmpty(filtri.getCdXsd())) {
queryStr.append(whereClause).append("UPPER(modelloXsdFascicolo.cdXsd) LIKE :cdXsd ");
whereClause = " AND ";
}
if (!StringUtils.isEmpty(filtri.getDsXsd())) {
queryStr.append(whereClause).append("UPPER(modelloXsdFascicolo.dsXsd) LIKE :dsXsd ");
whereClause = " AND ";
}
if (!StringUtils.isEmpty(filtri.getFlDefault())) {
queryStr.append(whereClause).append("modelloXsdFascicolo.flDefault = :flDefault ");
whereClause = " AND ";
}
if (!StringUtils.isEmpty(tiUsoModelloXsd)) {
queryStr.append(whereClause).append("modelloXsdFascicolo.tiUsoModelloXsd = :tiUsoModelloXsd ");
whereClause = " AND ";
}
if (!StringUtils.isEmpty(filtri.getTiModelloXsd())) {
queryStr.append(whereClause).append("modelloXsdFascicolo.tiModelloXsd = :tiModelloXsd ");
whereClause = " AND ";
}
if (filterValid) {
queryStr.append(whereClause).append(
"(modelloXsdFascicolo.dtIstituz <= :filterDate AND modelloXsdFascicolo.dtSoppres >= :filterDate) ");
}
Query query = getEntityManager().createQuery(queryStr.toString());
if (!idAmbienteList.isEmpty()) {
query.setParameter("idAmbienteList", longListFrom(idAmbienteList));
}
if (!StringUtils.isEmpty(filtri.getFlAttivo())) {
Calendar dataOdierna = Calendar.getInstance();
dataOdierna.set(Calendar.HOUR_OF_DAY, 0);
dataOdierna.set(Calendar.MINUTE, 0);
dataOdierna.set(Calendar.SECOND, 0);
dataOdierna.set(Calendar.MILLISECOND, 0);
query.setParameter("data", dataOdierna.getTime());
}
if (!StringUtils.isEmpty(filtri.getCdXsd())) {
query.setParameter("cdXsd", filtri.getCdXsd() + "%");
}
if (!StringUtils.isEmpty(filtri.getDsXsd())) {
query.setParameter("dsXsd", "%" + filtri.getDsXsd().toUpperCase() + "%");
}
if (!StringUtils.isEmpty(filtri.getFlDefault())) {
query.setParameter("flDefault", filtri.getFlDefault());
}
if (!StringUtils.isEmpty(tiUsoModelloXsd)) {
query.setParameter("tiUsoModelloXsd", TiUsoModelloXsd.valueOf(tiUsoModelloXsd));
}
if (!StringUtils.isEmpty(filtri.getTiModelloXsd())) {
query.setParameter("tiModelloXsd", TiModelloXsd.valueOf(filtri.getTiModelloXsd()));
}
if (filterValid) {
query.setParameter("filterDate", Calendar.getInstance().getTime());
}
return query.getResultList();
}
/**
* Ottiene la lista di modelli xsd in uso per l'ambiente e il tipo passati in input
*
* @param idAmbiente
* id ambiente
* @param tiModelloXsd
* tipo modello xsd
* @param filterValid
* true per prendere i record attivi attualmente
*
* @return lista di modelli xsd
*/
public List<DecModelloXsdFascicolo> retrieveDecModelloXsdFascicolo(BigDecimal idAmbiente, String tiModelloXsd,
boolean filterValid) {
StringBuilder queryStr = new StringBuilder("SELECT m FROM DecModelloXsdFascicolo m "
+ "WHERE m.orgAmbiente.idAmbiente = :idAmbiente AND m.tiModelloXsd = :tiModelloXsd ");
if (filterValid) {
queryStr.append("AND m.dtIstituz <= :filterDate AND m.dtSoppres >= :filterDate ");
}
Query query = getEntityManager().createQuery(queryStr.toString());
query.setParameter("idAmbiente", longFromBigDecimal(idAmbiente));
query.setParameter("tiModelloXsd", tiModelloXsd);
if (filterValid) {
query.setParameter("filterDate", Calendar.getInstance().getTime());
}
return query.getResultList();
}
/**
* Ottiene il modello xsd di tipo fascicolo dati i dati di chiave unique
*
* @param idAmbiente
* id ambiente
* @param tiModelloXsd
* tipo modello xsd
* @param tiUsoModelloXsd
* tipo modello xsd in uso
* @param cdXsd
* codice xsd
*
* @return modello entity DecModelloXsdFascicolo
*/
public DecModelloXsdFascicolo getDecModelloXsdFascicolo(BigDecimal idAmbiente, String tiModelloXsd,
String tiUsoModelloXsd, String cdXsd) {
Query query = getEntityManager()
.createQuery("SELECT m FROM DecModelloXsdFascicolo m WHERE m.orgAmbiente.idAmbiente = :idAmbiente "
+ "AND m.tiModelloXsd = :tiModelloXsd AND m.tiUsoModelloXsd = :tiUsoModelloXsd AND m.cdXsd = :cdXsd");
query.setParameter("idAmbiente", longFromBigDecimal(idAmbiente));
query.setParameter("tiModelloXsd", TiModelloXsd.valueOf(tiModelloXsd));
query.setParameter("tiUsoModelloXsd", TiUsoModelloXsd.valueOf(tiUsoModelloXsd));
query.setParameter("cdXsd", cdXsd);
List<DecModelloXsdFascicolo> list = query.getResultList();
DecModelloXsdFascicolo modello = null;
if (!list.isEmpty()) {
modello = list.get(0);
}
return modello;
}
/**
* Ritorna la lista di associazioni del modello xsd agli ambienti
*
* @param idModelloXsdFascicolo
* id modello xsd fascicolo
*
* @return lista oggetti di tipo {@link DecUsoModelloXsdFasc}
*/
public List<DecUsoModelloXsdFasc> retrieveDecUsoModelloXsdFasc(BigDecimal idModelloXsdFascicolo) {
Query query = getEntityManager().createQuery(
"SELECT u FROM DecUsoModelloXsdFasc u WHERE u.decModelloXsdFascicolo.idModelloXsdFascicolo = :idModelloXsdFascicolo");
query.setParameter("idModelloXsdFascicolo", longFromBigDecimal(idModelloXsdFascicolo));
return query.getResultList();
}
public boolean existDecUsoModelloXsdFasc(BigDecimal idModelloXsdFascicolo) {
Query query = getEntityManager().createQuery(
"SELECT d FROM DecUsoModelloXsdFasc d WHERE d.decModelloXsdFascicolo.idModelloXsdFascicolo = :idModelloXsdFascicolo");
query.setParameter("idModelloXsdFascicolo", longFromBigDecimal(idModelloXsdFascicolo));
List<DecUsoModelloXsdFasc> list = query.getResultList();
return !list.isEmpty();
}
public static class Filtri {
String flAttivo;
String cdXsd;
String dsXsd;
String flDefault;
String tiModelloXsd;
public Filtri() {
}
public Filtri(ModelliFascicoliForm.FiltriModelliXsdTipiFascicolo filtriModelliXsdTipiFasc) throws EMFError {
flAttivo = filtriModelliXsdTipiFasc.getAttivo_xsd().parse();
cdXsd = filtriModelliXsdTipiFasc.getCd_xsd().parse();
dsXsd = filtriModelliXsdTipiFasc.getDs_xsd().parse();
flDefault = filtriModelliXsdTipiFasc.getFl_default().parse();
tiModelloXsd = filtriModelliXsdTipiFasc.getTi_modello_xsd().parse();
}
public String getFlAttivo() {
return flAttivo;
}
public void setFlAttivo(String flAttivo) {
this.flAttivo = flAttivo;
}
public String getCdXsd() {
return cdXsd;
}
public void setCdXsd(String cdXsd) {
this.cdXsd = cdXsd;
}
public String getDsXsd() {
return dsXsd;
}
public void setDsXsd(String dsXsd) {
this.dsXsd = dsXsd;
}
public String getFlDefault() {
return flDefault;
}
public void setFlDefault(String flDefault) {
this.flDefault = flDefault;
}
public String getTiModelloXsd() {
return tiModelloXsd;
}
public void setTiModelloXsd(String tiModelloXsd) {
this.tiModelloXsd = tiModelloXsd;
}
}
}
|
package com.cg.security;
import com.cg.service.user.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private IUserService userService;
@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter();
}
@Bean(BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
@Bean
public RestAuthenticationEntryPoint restServicesEntryPoint() {
return new RestAuthenticationEntryPoint();
}
@Bean
public CustomAccessDeniedHandler customAccessDeniedHandler() {
return new CustomAccessDeniedHandler();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(10);
}
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().ignoringAntMatchers("/**").disable();
// http.httpBasic().authenticationEntryPoint(restServicesEntryPoint());
http.authorizeRequests()
.antMatchers(
"/api/v1/auth/**"
).permitAll()
.antMatchers(
"/api/v1/customers/**",
"/api/v1/staffs/**",
"/api/v1/staff-serviceAreas/**",
"/api/v1/maintenances/**",
"/api/v1/maintenance-items/**",
"/api/v1/maintenance-item-accessories/**",
"/api/v1/maintenance-maintenance-items/**",
"/api/v1/repairs/**",
"/api/v1/repair-items/**",
"/api/v1/repair-repair-items/**",
"/api/v1/service-areas/**",
"/api/v1/storage/**",
"/api/v1/car-queues/**",
"/api/v1/car-plates/**",
"/api/v1/car-plate-car-queues/**",
"/api/v1/order-services/**",
"/api/v1/order-maintenances/**",
"/api/v1/order-maintenance-items/**",
"/api/v1/order-maintenance-item-accessories/**",
"/api/v1/order-repair-items/**",
"/api/v1/order-repair-item-accessories/**",
"/api/v1/order-service-current-service-areas/**",
"/api/v1/bill-services/**",
"/api/v1/bill-service-details/**",
"/api/v1/bill-service-detail-accessories/**",
"/api/v1/dashboards/**"
).hasAnyAuthority("ADMIN","RECEPTION","TECHNICAL","CASHIER")
.antMatchers(
"/api/v1/cars/**",
"/api/v1/auth/**",
"/api/v1/auth/**",
"/api/v1/customers/**",
"/api/v1/staffs/**",
"/api/v1/staff-serviceAreas/**",
"/api/v1/maintenances/**",
"/api/v1/maintenance-items/**",
"/api/v1/maintenance_item-accessories/**",
"/api/v1/maintenance-maintenance-items/**",
"/api/v1/repairs/**",
"/api/v1/repair-items/**",
"/api/v1/repair-repair-items/**",
"/api/v1/service-areas/**",
"/api/v1/car-plates/**",
"/api/v1/car-plate-car-queues/**",
"/api/v1/order-services/**",
"/api/v1/service-areas/**",
"/api/v1/storage/**",
"/api/v1/vehicle/**",
"/api/v1/car-queues/**",
"/api/v1/cars/**"
).permitAll()
.antMatchers(
"/login",
"/cp/login",
"/forgot",
"/logout",
"/forget-password",
"/update-password/*",
"/error/*",
"/temp/*"
).permitAll()
.antMatchers(
"/static/**",
"/resources/**",
"/assets/**"
).permitAll()
.antMatchers(
"/v3/api-docs",
"/swagger-resources/configuration/ui",
"/configuration/ui",
"/swagger-resources",
"/swagger-resources/configuration/security",
"/configuration/security",
"/swagger-ui/**"
).permitAll()
.anyRequest().authenticated()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/cp/login")
.deleteCookies("JWT")
.invalidateHttpSession(true)
;
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.exceptionHandling().authenticationEntryPoint(new MyAuthenticationEntryPoint());
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.cors();
}
}
|
import React from 'react';
import { List, Drawer, Avatar, Popover } from 'antd';
import { ListSite, ListItem } from '../../index';
import { flatten } from '../../../../utils/flatten';
const MyFavorList = ({ favor, leftVisible, onCloseLeft }) => {
const renderData = flatten(favor)?.filter(item => item.type === 'site')
return (
<Drawer
width="350px"
placement="right"
onClose={onCloseLeft}
visible={leftVisible}
closable={false}
bodyStyle={{
padding: "0px"
}}
drawerStyle={{
backgroundColor: " var(--card-bg)",
// boxShadow: " 5px 5px 10px var(--card-sd),- 5px - 5px 10px var(--card-sf)",
color: "var(--font-fg)"
}}
>
<ListSite
itemLayout="horizontal"
dataSource={renderData}
size="large"
bordered={false}
header={<h2 style={{ textAlign: "center", color: "var(--font-fg)" }}>收藏的网站列表</h2>}
renderItem={item => (
<ListItem>
<List.Item.Meta
avatar={<Avatar src={item.icon} />}
title={
<Popover content={item.name}>
<a style={{ color: "var(--font-fg)" }} href={item.href}>{item.name.substr(0, 35)}</a>
</Popover>
}
/>
</ListItem>
)}
/>
</Drawer>
);
};
export default MyFavorList;
|
import { RouterContext } from "./RouterContext";
/**
* withRouter 是一个高阶段组件,用于解决子孙组件无法拿到 route props 的场景
*
* 什么情况下,子孙组件无法拿到 route props
*
* Route 组件使用 render 属性来接受渲染组件时
*/
export const withRouter = (Com) => (props) => {
return (
<RouterContext.Consumer>
{(context) => {
return <Com {...props} {...context} />;
}}
</RouterContext.Consumer>
);
};
|
import React, { useState, useRef } from 'react';
import Button from '@mui/material/Button';
import AudioPlayer from '@mui/icons-material/Audiotrack';
function AudioRecorder() {
const [isRecording, setIsRecording] = useState(false);
const [recordings, setRecordings] = useState([]);
const mediaRecorderRef = useRef(null);
function startRecording() {
return new Promise((resolve, reject) => {
navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => {
const mediaRecorder = new MediaRecorder(stream);
const audioContext = new AudioContext();
const analyser = audioContext.createAnalyser();
const microphone = audioContext.createMediaStreamSource(stream);
microphone.connect(analyser);
analyser.fftSize = 2048;
let dataArray = new Uint8Array(analyser.frequencyBinCount);
let silenceCounter = 0;
let animationFrameId;
mediaRecorder.start();
const checkSilence = () => {
analyser.getByteFrequencyData(dataArray);
let sum = dataArray.reduce((a, b) => a + b, 0);
let average = sum / dataArray.length;
console.log('average: ',average);
// זיהוי שתיקה בהתבסס על עוצמה ממוצעת נמוכה
if (average < 5) { // SILENCE_THRESHOLD יש להתאים
silenceCounter++;
if (silenceCounter > 100) {
console.log('in if');
mediaRecorder.stop();
audioContext.close();
cancelAnimationFrame(animationFrameId);
return;
}
} else {
silenceCounter = 0;
}
animationFrameId = requestAnimationFrame(checkSilence);
};
// התחלת בדיקת השתיקה
animationFrameId = requestAnimationFrame(checkSilence);
// התחלת הקלטת האודיו
mediaRecorder.ondataavailable = async (e) => {
const audioBlob = new Blob([e.data], { type: 'audio/wav' });
const formData = new FormData();
formData.append('audioFile', audioBlob, Date.now()+'.wav');
try {
const response = await fetch('http://192.168.1.195:8000/audio_manager/uploade', {
method: 'POST',
body: formData,
});
if (response.ok) {
console.log('Recording uploaded');
} else {
console.error('Upload failed');
}
} catch (error) {
console.error('Error in upload: ', error);
}
};
// כאשר ההקלטה מסתיימת
mediaRecorder.onstop = () => {
stream.getTracks().forEach(track => track.stop());
resolve();
// טיפול בסיום ההקלטה, לדוגמה הצגת הקלטה למשתמש
};
mediaRecorder.onerror = (e) => reject(e);
}).catch(err => {
console.error('Error in starting recording: ', err);
});
}
)}
function playAudioFile(filePath) {
return new Promise((resolve, reject) => {
const audio = new Audio(filePath);
audio.onended = resolve; // כאשר הנגינה תסתיים, הבטחה תתממש
audio.onerror = reject; // במקרה של שגיאה בנגינה
audio.play();
});
}
const voiceChat=async()=>{
let voiceFiles=['voice_files/1703533449.8110383.wav', 'voice_files/1703533462.9922378.wav', 'voice_files/1703533465.917387.wav', 'voice_files/1703530981.7942042.wav', 'voice_files/1703530985.1124084.wav', 'voice_files/1703530990.303712.wav', 'voice_files/1703530993.1538754.wav', 'voice_files/1703531000.7579093.wav', 'voice_files/1703531004.640988.wav', 'voice_files/1703531009.1521485.wav', 'voice_files/1703531012.083384.wav', 'voice_files/1703531015.6642942.wav', 'voice_files/1703531018.9017708.wav', 'voice_files/1703531024.6664872.wav', 'voice_files/1703531028.385587.wav', 'voice_files/1703531037.1895192.wav', 'voice_files/1703531040.257128.wav', 'voice_files/1703531044.783376.wav', 'voice_files/1703531048.0661132.wav']
await playAudioFile(voiceFiles[0])
for (let i=1;i<voiceFiles.length;i=i+2){
let dt1=Date.now()
await startRecording()
let dt2=Date.now()
if (dt2-dt1<3000){
await playAudioFile('voice_files/1703535158.978147.wav')
await startRecording()
}
await playAudioFile(voiceFiles[i])
await playAudioFile(voiceFiles[i+1])
}
}
return (
<div>
{recordings.map((recording, index) => (
<div key={index} style={{ marginBottom: '16px' }}>
<audio src={recording} controls style={{ width: '100%' }} />
</div>
))}
<Button
variant="contained"
startIcon={<AudioPlayer />}
onClick={voiceChat}
style={{ marginTop: '20px', backgroundColor: '#4caf50', color: 'white' }}
>
Play AI Voice
</Button>
</div>
);
}
export default AudioRecorder;
|
from django.db.models.signals import post_save, m2m_changed
from django.dispatch import receiver
from .models import Appointment
def print_appointment_details(appointment):
dogs = ', '.join([str(dog) for dog in appointment.dogs.all()])
services = ', '.join([service.name for service in appointment.services.all()])
print(f"""
[
To: {appointment.customer.email}
Subject: Appointment Confirmation Email
Body: This email is to confirm that we have received your appointment! Your appointment details are below.
Appointment time: {appointment.start_date.strftime('%Y-%m-%d'), "-", appointment.end_date.strftime('%Y-%m-%d')}
Client: {appointment.customer}
Dog(s): {dogs if dogs else "No dogs listed"}
Service(s): {services if services else "No services listed"}
We look forward to seeing you then!
]
Admin: Email Confirmation Message Delivered to {appointment.customer}
""")
@receiver(post_save, sender=Appointment)
def appointment_post_save(sender, instance, created, **kwargs):
if created:
# Marca el appointment para verificar si necesita imprimirse después,
# ya que inicialmente los M2M no estarán listos.
instance._print_on_m2m_completed = True
instance._m2m_changed = {'dogs': False, 'services': False}
@receiver(m2m_changed, sender=Appointment.dogs.through)
@receiver(m2m_changed, sender=Appointment.services.through)
def send_confirmation_email(sender, instance, action, **kwargs):
if action == "post_add" and hasattr(instance, '_print_on_m2m_completed'):
# Marca qué relación M2M ha cambiado.
if sender == Appointment.dogs.through:
instance._m2m_changed['dogs'] = True
elif sender == Appointment.services.through:
instance._m2m_changed['services'] = True
# Verifica si ambas relaciones M2M han sido modificadas y si es necesario imprimir.
if all(instance._m2m_changed.values()):
print_appointment_details(instance)
instance.email_confirmation = True
instance.save(update_fields=['email_confirmation'])
# Limpia los atributos temporales para evitar ejecuciones futuras en el mismo ciclo de vida.
del instance._print_on_m2m_completed
del instance._m2m_changed
|
import { RouterProvider, createBrowserRouter } from "react-router-dom";
import Resume from "./Components/Resume/Resume";
import Projects from "./Components/Projects/Projects";
import Contact from "./Components/Contact/Contact";
import "./App.css";
import AppLayout from "./Components/UI/AppLayout";
import Home from "./Components/Home/Home";
const router = createBrowserRouter([
{
element:<AppLayout/>,
children:[
{
path:'/',
element:<Home/>
},
{
path:'/resume',
element:<Resume/>
},
{
path:'/projects',
element:<Projects/>
},
{
path:'/contact',
element:<Contact/>
}
]
}
])
function App(){
return <RouterProvider router={router}/>;
}
export default App;
|
#' getControlList
#'
#' Load a control list based on user input in the xml generated configurators.
#'
#' @param input shiny server input
#' @param strID group name in xml file
#' @param asText for log generation set 'asText' = TRUE
#'
#' @return controlList
#'
#' @keywords internal
getControlList <- function(input, strID, asText = FALSE){
rootName <- "xml_"
xmlRoot <- xmlGetRootElement()
xmlFilteredForID <- xmlRoot[which(names(xmlRoot)==strID)]
if(strID == "general"){
selected <- "general"
}else{
selected <- input[[paste0(strID,"Selector")]]
}
rootName <- paste0(rootName,selected)
indexSelected <- NULL
for(i in 1:length(xmlFilteredForID)){
element <- xmlFilteredForID[[i]]
if(element$name == selected){
indexSelected <- i
}
}
settingsSelectedElement <- xmlFilteredForID[[indexSelected]]$variableList
resList <- getXMLVarListUI(input,rootName,settingsSelectedElement,asText)
resList <- c(resList, getExtraParametersList(input,strID,asText))
return(resList)
}
#' getXMLVarListUI
#'
#' Load values of a variablelist from ui based on its xml name
#'
#' @param input shiny server input
#' @param rootName xml root name group name in xml file
#' @param varList the variable name to get
#' @param asText for log generation set 'asText' = TRUE
#'
#' @return varList
#'
#' @keywords internal
getXMLVarListUI <- function(input, rootName, varList, asText = FALSE){
rootName <- paste0(rootName, varList$name)
indVars <- which(names(varList) == "variable")
indVarLists <- which(names(varList) == "variableList")
l <- list()
for(ind in indVarLists){
l<- c(l,getXMLVarListUI(input, rootName, input))
}
for(var in indVars){
l <- c(l,getXMLVariableUI(input,rootName,varList[[var]],asText))
}
l
}
#' getXMLVariableUI
#'
#' Load values of a variablelist from ui based on its xml name
#'
#' @param input shiny server input
#' @param rootName xml root name group name in xml file
#' @param var the variable name to get
#' @param asText for log generation set 'asText' = TRUE
#'
#' @return var
#'
#' @keywords internal
getXMLVariableUI <- function(input, rootName, var, asText = FALSE){
uiName <- paste0(rootName,var$name)
l <- list()
if(var$type == "string" & asText){
l[[var$name]] <- paste0("\"",input[[uiName]],"\"")
}else if(var$type == "closure"){
l[[var$name]] <- getClosureVariableFromUI(input,uiName,asText)
}else if(var$type == "numeric"){
num <- as.numeric(input[[uiName]])
if(is.na(num)){
if(asText){
num <- "NULL"
}else{
num <- NULL
}
}
l[[var$name]] <- num
}else{
l[[var$name]] <- input[[uiName]]
}
if(!(length(l) == 0)){
names(l) <- var$name
}
l
}
#' getExtraParametersList
#'
#' Get value of extra field below normal setup in gui
#'
#' @param input shiny server input
#' @param strID group name in xml file
#' @param asText for log generation set 'asText' = TRUE
#'
#' @return extraValue
#'
#' @keywords internal
getExtraParametersList <- function(input, strID, asText = FALSE){
inputName <- paste0(strID,"ExtraParameters")
if(input[[inputName]] == ""){
return(NULL)
}else{
return(getClosureVariableFromUI(input, inputName, asText))
}
}
#' getClosureVariableFromUI
#'
#' Missing Docu
#'
#' @param input shiny server input
#' @param inputName missing docu
#' @param asText for log generation set 'asText' = TRUE
#'
#' @return closureVar
#'
#' @keywords internal
getClosureVariableFromUI <- function(input, inputName, asText = FALSE){
if((input[[inputName]] == "NULL")){
if(asText){
return("NULL")
}else{
return(NULL)
}
}else if((input[[inputName]] == "NA")){
if(asText){
return("NA")
}else{
return(NA)
}
}else if(is.numeric(input[[inputName]])){
return(as.numeric(input[[inputName]]))
}else{
if(!asText){
tryCatch(return(get(input[[inputName]])),
error=return(eval(parse(text=input[[inputName]]))))
}else{
return(input[[inputName]])
}
}
}
|
import { AxiosInstance } from "axios";
export interface IBroker {
// To fetch a list of assets available for trading
listTradableAssets(): Promise<Array<{ tickerSymbol: string }>>
// To fetch the latest price for a single asset
getLatestPrice(tickerSymbol: string): Promise<{ sharePrice: number }>
// To check if the stock market is currently open or closed
isMarketOpen(): Promise<{ open: boolean, nextOpeningTime: string, nextClosingTime: string }>
// To purchase shares into a customer's account using Emma's funds
placeBuyOrderUsingEmmaFunds(accountId: string, tickerSymbol: string, quantity: number): Promise<{ id: string }>
// To view the shares that are purchased in the customer's account
getAccountPositions(accountId: string): Promise<Array<{ tickerSymbol: string, quantity: number, sharePrice: number }>>
// To view the orders of the customer's account. Returns the status of each order and what share price the order was executed at.
getAllOrders(accountId: string): Promise<Array<{ id: string, tickerSymbol: string, quantity: number, side: 'buy'|'sell', status: 'open'|'filled'|'failed', filledPrice: number }>>
getOrder(orderId: string): Promise<{ id: string, tickerSymbol: string, quantity: number, side: 'buy'|'sell', status: 'open'|'filled'|'failed', filledPrice: number }>
}
export type Position = {
tickerSymbol: string
quantity: number
sharePrice: number
}
export type Market = {
open: boolean
nextOpeningTime: string
nextClosingTime: string
}
export type Asset = { tickerSymbol: string }
export type Order = {
id: string;
tickerSymbol: string;
quantity: number;
side: "buy" | "sell";
status: "open" | "filled" | "failed";
filledPrice: number
}
export class Broker implements IBroker {
constructor(
private readonly http: AxiosInstance,
) { }
async getAccountPositions(accountId: string): Promise<Array<Position>> {
const response = await this.http.get<Array<Position>>(`/accounts/${accountId}/positions`)
return response.data
}
async getAllOrders(accountId: string): Promise<Array<Order>> {
const response = await this.http.get<Array<Order>>(`accounts/${accountId}/orders`)
return response.data
}
async getOrder(orderId: string): Promise<Order> {
const response = await this.http.get<Order>(`orders/${orderId}`)
return response.data
}
async getLatestPrice(tickerSymbol: string): Promise<Pick<Position, 'sharePrice'>> {
const response = await this.http.get<Pick<Position, 'sharePrice'>>(`/assets/${tickerSymbol}/price`)
return response.data
}
async isMarketOpen(): Promise<Market> {
const response = await this.http.get<Market>('/market/status')
return response.data
}
async listTradableAssets(): Promise<Array<Asset>> {
const response = await this.http.get<Array<Asset>>('/assets')
return response.data
}
async placeBuyOrderUsingEmmaFunds(accountId: string, tickerSymbol: string, quantity: number): Promise<Pick<Order, 'id'>> {
const response = await this.http.post<Pick<Order, 'id'>>(`/accounts/${accountId}/orders`, {
tickerSymbol,
quantity,
side: 'buy'
})
return response.data
}
}
|
@extends('layouts.app')
@section( 'title', 'Switches' )
@section('content')
@include('layouts.headers.cards', [ 'title' => 'Switches' ])
<switches-view v-cloak :campuses="{{ $campuses }}" inline-template>
<div class="container-fluid mt--7">
<div class="row">
<div class="col">
<div class="card shadow">
<div class="card-header border-0">
<div class="row align-items-center">
<div class="col-12 text-right">
@if( Auth::user()->hasAnyPermission( 'admin', 'edit network' ) )
<base-button
tag="a"
href="{{ url('/network/switches/form') }}"
type="primary"
size="sm"
>Add Switch</base-button>
@endif
</div>
</div>
</div>
<tabs fill class="flex-column flex-md-row">
<card shadow>
<tab-pane v-for="campus in campuses">
<span slot="title" v-text="campus.name"></span>
<div class="table-responsive" v-for="(switches, location) in groupBy(campus.switches, 'location')">
<h1 v-text="location"></h1>
<table class="table align-items-center table-flush">
<thead class="thead-light">
<tr>
<th scope="col">IP</th>
<th scope="col">MAC</th>
<th scope="col">Model</th>
<th scope="col">Ethernet</th>
<th scope="col">Fiber</th>
<th scope="col">Location</th>
<th scope="col">Uptime</th>
<th scope="col">Last Sync</th>
<th scope="col" class="text-right">Options</th>
</tr>
</thead>
<tbody>
<tr class='myTableRow' v-for="(s, index) in switches">
<td><a :href="`{{url( '/network/switch' ) }}/${s.id}`" v-text="s.ip_address"></a></td>
<td v-text="s.mac_address"></td>
<td v-text="s.model"></td>
<td v-text="s.ports_count"></td>
<td v-text="s.fiber_ports"></td>
<td v-text="s.sub_location"></td>
<td v-text="s.active ? moment(s.uptime).format('DD-MM-YYYY') : 'Inactive'"></td>
<td v-text="s.checked_in ? moment(s.checked_in).format('DD-MM-YYYY') : ''"></td>
<td class="text-right">
<base-button
v-if="s.logs_count > 0"
tag="a"
:href="`{{ url( '/' )}}/network/switch/${s.id}/logs`"
icon='fas fa-history'
size='sm'
type='default'
:tooltip="{ title: 'View Logs', placement: 'top' }"
></base-button>
@if( Auth::user()->hasAnyPermission( 'admin', 'edit network' ) )
<base-button
tag="a"
:href="`{{ url( '/' )}}/network/switches/form/${s.id}`"
icon='fas fa-pencil-alt'
size='sm'
type='primary'
:tooltip="{ title: 'Edit', placement: 'top' }"
></base-button>
<base-button
icon='fas fa-trash'
@click='deleteSwitch(s)'
size='sm'
type='danger'
:tooltip="{ title: 'Delete', placement: 'top' }"
></base-button>
@endif
</td>
</tr>
</tbody>
</table>
</div>
</tab-pane>
</card>
</tabs>
</div>
</div>
</div>
@include('layouts.footers.auth')
</div>
</campus-view>
@endsection
|
/*
! tailwindcss v3.4.3 | MIT License | https://tailwindcss.com
*/
/*
1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4)
2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116)
*/
*,
::before,
::after {
box-sizing: border-box;
/* 1 */
border-width: 0;
/* 2 */
border-style: solid;
/* 2 */
border-color: #e5e7eb;
/* 2 */
}
::before,
::after {
--tw-content: '';
}
/*
1. Use a consistent sensible line-height in all browsers.
2. Prevent adjustments of font size after orientation changes in iOS.
3. Use a more readable tab size.
4. Use the user's configured `sans` font-family by default.
5. Use the user's configured `sans` font-feature-settings by default.
6. Use the user's configured `sans` font-variation-settings by default.
7. Disable tap highlights on iOS
*/
html,
:host {
line-height: 1.5;
/* 1 */
-webkit-text-size-adjust: 100%;
/* 2 */
-moz-tab-size: 4;
/* 3 */
-o-tab-size: 4;
tab-size: 4;
/* 3 */
font-family: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
/* 4 */
font-feature-settings: normal;
/* 5 */
font-variation-settings: normal;
/* 6 */
-webkit-tap-highlight-color: transparent;
/* 7 */
}
/*
1. Remove the margin in all browsers.
2. Inherit line-height from `html` so users can set them as a class directly on the `html` element.
*/
body {
margin: 0;
/* 1 */
line-height: inherit;
/* 2 */
}
/*
1. Add the correct height in Firefox.
2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655)
3. Ensure horizontal rules are visible by default.
*/
hr {
height: 0;
/* 1 */
color: inherit;
/* 2 */
border-top-width: 1px;
/* 3 */
}
/*
Add the correct text decoration in Chrome, Edge, and Safari.
*/
abbr:where([title]) {
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
}
/*
Remove the default font size and weight for headings.
*/
h1,
h2,
h3,
h4,
h5,
h6 {
font-size: inherit;
font-weight: inherit;
}
/*
Reset links to optimize for opt-in styling instead of opt-out.
*/
a {
color: inherit;
text-decoration: inherit;
}
/*
Add the correct font weight in Edge and Safari.
*/
b,
strong {
font-weight: bolder;
}
/*
1. Use the user's configured `mono` font-family by default.
2. Use the user's configured `mono` font-feature-settings by default.
3. Use the user's configured `mono` font-variation-settings by default.
4. Correct the odd `em` font sizing in all browsers.
*/
code,
kbd,
samp,
pre {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
/* 1 */
font-feature-settings: normal;
/* 2 */
font-variation-settings: normal;
/* 3 */
font-size: 1em;
/* 4 */
}
/*
Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/*
Prevent `sub` and `sup` elements from affecting the line height in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
/*
1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297)
2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016)
3. Remove gaps between table borders by default.
*/
table {
text-indent: 0;
/* 1 */
border-color: inherit;
/* 2 */
border-collapse: collapse;
/* 3 */
}
/*
1. Change the font styles in all browsers.
2. Remove the margin in Firefox and Safari.
3. Remove default padding in all browsers.
*/
button,
input,
optgroup,
select,
textarea {
font-family: inherit;
/* 1 */
font-feature-settings: inherit;
/* 1 */
font-variation-settings: inherit;
/* 1 */
font-size: 100%;
/* 1 */
font-weight: inherit;
/* 1 */
line-height: inherit;
/* 1 */
letter-spacing: inherit;
/* 1 */
color: inherit;
/* 1 */
margin: 0;
/* 2 */
padding: 0;
/* 3 */
}
/*
Remove the inheritance of text transform in Edge and Firefox.
*/
button,
select {
text-transform: none;
}
/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Remove default button styles.
*/
button,
input:where([type='button']),
input:where([type='reset']),
input:where([type='submit']) {
-webkit-appearance: button;
/* 1 */
background-color: transparent;
/* 2 */
background-image: none;
/* 2 */
}
/*
Use the modern Firefox focus style for all focusable elements.
*/
:-moz-focusring {
outline: auto;
}
/*
Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737)
*/
:-moz-ui-invalid {
box-shadow: none;
}
/*
Add the correct vertical alignment in Chrome and Firefox.
*/
progress {
vertical-align: baseline;
}
/*
Correct the cursor style of increment and decrement buttons in Safari.
*/
::-webkit-inner-spin-button,
::-webkit-outer-spin-button {
height: auto;
}
/*
1. Correct the odd appearance in Chrome and Safari.
2. Correct the outline style in Safari.
*/
[type='search'] {
-webkit-appearance: textfield;
/* 1 */
outline-offset: -2px;
/* 2 */
}
/*
Remove the inner padding in Chrome and Safari on macOS.
*/
::-webkit-search-decoration {
-webkit-appearance: none;
}
/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Change font properties to `inherit` in Safari.
*/
::-webkit-file-upload-button {
-webkit-appearance: button;
/* 1 */
font: inherit;
/* 2 */
}
/*
Add the correct display in Chrome and Safari.
*/
summary {
display: list-item;
}
/*
Removes the default spacing and border for appropriate elements.
*/
blockquote,
dl,
dd,
h1,
h2,
h3,
h4,
h5,
h6,
hr,
figure,
p,
pre {
margin: 0;
}
fieldset {
margin: 0;
padding: 0;
}
legend {
padding: 0;
}
ol,
ul,
menu {
list-style: none;
margin: 0;
padding: 0;
}
/*
Reset default styling for dialogs.
*/
dialog {
padding: 0;
}
/*
Prevent resizing textareas horizontally by default.
*/
textarea {
resize: vertical;
}
/*
1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300)
2. Set the default placeholder color to the user's configured gray 400 color.
*/
input::-moz-placeholder, textarea::-moz-placeholder {
opacity: 1;
/* 1 */
color: #9ca3af;
/* 2 */
}
input::placeholder,
textarea::placeholder {
opacity: 1;
/* 1 */
color: #9ca3af;
/* 2 */
}
/*
Set the default cursor for buttons.
*/
button,
[role="button"] {
cursor: pointer;
}
/*
Make sure disabled buttons don't get the pointer cursor.
*/
:disabled {
cursor: default;
}
/*
1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14)
2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210)
This can trigger a poorly considered lint error in some tools but is included by design.
*/
img,
svg,
video,
canvas,
audio,
iframe,
embed,
object {
display: block;
/* 1 */
vertical-align: middle;
/* 2 */
}
/*
Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14)
*/
img,
video {
max-width: 100%;
height: auto;
}
/* Make elements with the HTML hidden attribute stay hidden by default */
[hidden] {
display: none;
}
*, ::before, ::after {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
--tw-contain-size: ;
--tw-contain-layout: ;
--tw-contain-paint: ;
--tw-contain-style: ;
}
::backdrop {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
--tw-contain-size: ;
--tw-contain-layout: ;
--tw-contain-paint: ;
--tw-contain-style: ;
}
.container {
width: 100%;
margin-right: auto;
margin-left: auto;
padding-right: 2rem;
padding-left: 2rem;
}
@media (min-width: 1400px) {
.container {
max-width: 1400px;
}
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border-width: 0;
}
.pointer-events-auto {
pointer-events: auto;
}
.fixed {
position: fixed;
}
.absolute {
position: absolute;
}
.relative {
position: relative;
}
.inset-0 {
inset: 0px;
}
.inset-x-0 {
left: 0px;
right: 0px;
}
.inset-y-0 {
top: 0px;
bottom: 0px;
}
.bottom-0 {
bottom: 0px;
}
.bottom-6 {
bottom: 1.5rem;
}
.left-0 {
left: 0px;
}
.left-2 {
left: 0.5rem;
}
.left-6 {
left: 1.5rem;
}
.left-\[50\%\] {
left: 50%;
}
.right-0 {
right: 0px;
}
.right-2 {
right: 0.5rem;
}
.right-4 {
right: 1rem;
}
.top-0 {
top: 0px;
}
.top-2 {
top: 0.5rem;
}
.top-4 {
top: 1rem;
}
.top-\[50\%\] {
top: 50%;
}
.z-50 {
z-index: 50;
}
.z-\[100\] {
z-index: 100;
}
.m-0 {
margin: 0px;
}
.-mx-1 {
margin-left: -0.25rem;
margin-right: -0.25rem;
}
.mx-4 {
margin-left: 1rem;
margin-right: 1rem;
}
.mx-auto {
margin-left: auto;
margin-right: auto;
}
.my-1 {
margin-top: 0.25rem;
margin-bottom: 0.25rem;
}
.mb-1 {
margin-bottom: 0.25rem;
}
.mb-10 {
margin-bottom: 2.5rem;
}
.mb-12 {
margin-bottom: 3rem;
}
.mb-2 {
margin-bottom: 0.5rem;
}
.mb-4 {
margin-bottom: 1rem;
}
.mb-5 {
margin-bottom: 1.25rem;
}
.mb-6 {
margin-bottom: 1.5rem;
}
.mb-8 {
margin-bottom: 2rem;
}
.mt-2 {
margin-top: 0.5rem;
}
.mt-3 {
margin-top: 0.75rem;
}
.mt-4 {
margin-top: 1rem;
}
.mt-6 {
margin-top: 1.5rem;
}
.mt-7 {
margin-top: 1.75rem;
}
.mt-8 {
margin-top: 2rem;
}
.flex {
display: flex;
}
.inline-flex {
display: inline-flex;
}
.grid {
display: grid;
}
.hidden {
display: none;
}
.aspect-square {
aspect-ratio: 1 / 1;
}
.aspect-video {
aspect-ratio: 16 / 9;
}
.h-10 {
height: 2.5rem;
}
.h-11 {
height: 2.75rem;
}
.h-12 {
height: 3rem;
}
.h-14 {
height: 3.5rem;
}
.h-2 {
height: 0.5rem;
}
.h-2\.5 {
height: 0.625rem;
}
.h-3 {
height: 0.75rem;
}
.h-3\.5 {
height: 0.875rem;
}
.h-4 {
height: 1rem;
}
.h-8 {
height: 2rem;
}
.h-9 {
height: 2.25rem;
}
.h-\[50px\] {
height: 50px;
}
.h-\[var\(--radix-select-trigger-height\)\] {
height: var(--radix-select-trigger-height);
}
.h-full {
height: 100%;
}
.h-px {
height: 1px;
}
.h-screen {
height: 100vh;
}
.max-h-10 {
max-height: 2.5rem;
}
.max-h-96 {
max-height: 24rem;
}
.max-h-\[125px\] {
max-height: 125px;
}
.max-h-\[365px\] {
max-height: 365px;
}
.max-h-\[70px\] {
max-height: 70px;
}
.max-h-\[calc\(100vh-20px\)\] {
max-height: calc(100vh - 20px);
}
.max-h-screen {
max-height: 100vh;
}
.min-h-\[200px\] {
min-height: 200px;
}
.min-h-\[217px\] {
min-height: 217px;
}
.min-h-\[calc\(100vh-100px\)\] {
min-height: calc(100vh - 100px);
}
.min-h-screen {
min-height: 100vh;
}
.w-10 {
width: 2.5rem;
}
.w-12 {
width: 3rem;
}
.w-14 {
width: 3.5rem;
}
.w-2 {
width: 0.5rem;
}
.w-2\.5 {
width: 0.625rem;
}
.w-3 {
width: 0.75rem;
}
.w-3\.5 {
width: 0.875rem;
}
.w-3\/4 {
width: 75%;
}
.w-4 {
width: 1rem;
}
.w-40 {
width: 10rem;
}
.w-5 {
width: 1.25rem;
}
.w-6 {
width: 1.5rem;
}
.w-72 {
width: 18rem;
}
.w-9 {
width: 2.25rem;
}
.w-full {
width: 100%;
}
.w-max {
width: -moz-max-content;
width: max-content;
}
.min-w-\[200px\] {
min-width: 200px;
}
.min-w-\[217px\] {
min-width: 217px;
}
.min-w-\[300px\] {
min-width: 300px;
}
.min-w-\[8rem\] {
min-width: 8rem;
}
.min-w-\[var\(--radix-select-trigger-width\)\] {
min-width: var(--radix-select-trigger-width);
}
.max-w-20 {
max-width: 5rem;
}
.max-w-\[1140px\] {
max-width: 1140px;
}
.max-w-\[125px\] {
max-width: 125px;
}
.max-w-\[300px\] {
max-width: 300px;
}
.max-w-\[480px\] {
max-width: 480px;
}
.max-w-\[500px\] {
max-width: 500px;
}
.max-w-\[650px\] {
max-width: 650px;
}
.max-w-\[70px\] {
max-width: 70px;
}
.max-w-lg {
max-width: 32rem;
}
.max-w-md {
max-width: 28rem;
}
.flex-1 {
flex: 1 1 0%;
}
.shrink-0 {
flex-shrink: 0;
}
.translate-x-\[-50\%\] {
--tw-translate-x: -50%;
transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
}
.translate-y-\[-50\%\] {
--tw-translate-y: -50%;
transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
}
.transform {
transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
}
@keyframes pulse {
50% {
opacity: .5;
}
}
.animate-pulse {
animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}
.cursor-default {
cursor: default;
}
.touch-none {
touch-action: none;
}
.select-none {
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
.flex-row {
flex-direction: row;
}
.flex-col {
flex-direction: column;
}
.flex-col-reverse {
flex-direction: column-reverse;
}
.items-end {
align-items: flex-end;
}
.items-center {
align-items: center;
}
.justify-end {
justify-content: flex-end;
}
.justify-center {
justify-content: center;
}
.justify-between {
justify-content: space-between;
}
.gap-1 {
gap: 0.25rem;
}
.gap-10 {
gap: 2.5rem;
}
.gap-3 {
gap: 0.75rem;
}
.gap-4 {
gap: 1rem;
}
.gap-6 {
gap: 1.5rem;
}
.gap-8 {
gap: 2rem;
}
.gap-2 {
gap: 0.5rem;
}
.gap-x-7 {
-moz-column-gap: 1.75rem;
column-gap: 1.75rem;
}
.space-x-4 > :not([hidden]) ~ :not([hidden]) {
--tw-space-x-reverse: 0;
margin-right: calc(1rem * var(--tw-space-x-reverse));
margin-left: calc(1rem * calc(1 - var(--tw-space-x-reverse)));
}
.space-y-1 > :not([hidden]) ~ :not([hidden]) {
--tw-space-y-reverse: 0;
margin-top: calc(0.25rem * calc(1 - var(--tw-space-y-reverse)));
margin-bottom: calc(0.25rem * var(--tw-space-y-reverse));
}
.space-y-1\.5 > :not([hidden]) ~ :not([hidden]) {
--tw-space-y-reverse: 0;
margin-top: calc(0.375rem * calc(1 - var(--tw-space-y-reverse)));
margin-bottom: calc(0.375rem * var(--tw-space-y-reverse));
}
.space-y-2 > :not([hidden]) ~ :not([hidden]) {
--tw-space-y-reverse: 0;
margin-top: calc(0.5rem * calc(1 - var(--tw-space-y-reverse)));
margin-bottom: calc(0.5rem * var(--tw-space-y-reverse));
}
.overflow-hidden {
overflow: hidden;
}
.whitespace-nowrap {
white-space: nowrap;
}
.rounded-\[inherit\] {
border-radius: inherit;
}
.rounded-full {
border-radius: 9999px;
}
.rounded-lg {
border-radius: 0.5rem;
}
.rounded-md {
border-radius: 0.375rem;
}
.rounded-sm {
border-radius: 0.125rem;
}
.rounded-xl {
border-radius: 0.75rem;
}
.rounded-t-xl {
border-top-left-radius: 0.75rem;
border-top-right-radius: 0.75rem;
}
.border {
border-width: 1px;
}
.border-2 {
border-width: 2px;
}
.border-b {
border-bottom-width: 1px;
}
.border-b-2 {
border-bottom-width: 2px;
}
.border-b-4 {
border-bottom-width: 4px;
}
.border-b-8 {
border-bottom-width: 8px;
}
.border-l {
border-left-width: 1px;
}
.border-l-2 {
border-left-width: 2px;
}
.border-r {
border-right-width: 1px;
}
.border-t {
border-top-width: 1px;
}
.border-t-2 {
border-top-width: 2px;
}
.border-cyan-500 {
--tw-border-opacity: 1;
border-color: rgb(6 182 212 / var(--tw-border-opacity));
}
.border-green-600 {
--tw-border-opacity: 1;
border-color: rgb(22 163 74 / var(--tw-border-opacity));
}
.border-indigo-600 {
--tw-border-opacity: 1;
border-color: rgb(79 70 229 / var(--tw-border-opacity));
}
.border-red-500 {
--tw-border-opacity: 1;
border-color: rgb(239 68 68 / var(--tw-border-opacity));
}
.border-sky-300 {
--tw-border-opacity: 1;
border-color: rgb(125 211 252 / var(--tw-border-opacity));
}
.border-slate-200 {
--tw-border-opacity: 1;
border-color: rgb(226 232 240 / var(--tw-border-opacity));
}
.border-sky-400 {
--tw-border-opacity: 1;
border-color: rgb(56 189 248 / var(--tw-border-opacity));
}
.border-b-sky-600\/60 {
border-bottom-color: rgb(2 132 199 / 0.6);
}
.border-l-transparent {
border-left-color: transparent;
}
.border-t-transparent {
border-top-color: transparent;
}
.bg-black\/80 {
background-color: rgb(0 0 0 / 0.8);
}
.bg-cyan-500 {
--tw-bg-opacity: 1;
background-color: rgb(6 182 212 / var(--tw-bg-opacity));
}
.bg-gray-50 {
--tw-bg-opacity: 1;
background-color: rgb(249 250 251 / var(--tw-bg-opacity));
}
.bg-green-300 {
--tw-bg-opacity: 1;
background-color: rgb(134 239 172 / var(--tw-bg-opacity));
}
.bg-green-500 {
--tw-bg-opacity: 1;
background-color: rgb(34 197 94 / var(--tw-bg-opacity));
}
.bg-indigo-500 {
--tw-bg-opacity: 1;
background-color: rgb(99 102 241 / var(--tw-bg-opacity));
}
.bg-neutral-200 {
--tw-bg-opacity: 1;
background-color: rgb(229 229 229 / var(--tw-bg-opacity));
}
.bg-neutral-400 {
--tw-bg-opacity: 1;
background-color: rgb(163 163 163 / var(--tw-bg-opacity));
}
.bg-red-500 {
--tw-bg-opacity: 1;
background-color: rgb(239 68 68 / var(--tw-bg-opacity));
}
.bg-sky-400 {
--tw-bg-opacity: 1;
background-color: rgb(56 189 248 / var(--tw-bg-opacity));
}
.bg-sky-500 {
--tw-bg-opacity: 1;
background-color: rgb(14 165 233 / var(--tw-bg-opacity));
}
.bg-sky-500\/15 {
background-color: rgb(14 165 233 / 0.15);
}
.bg-slate-100 {
--tw-bg-opacity: 1;
background-color: rgb(241 245 249 / var(--tw-bg-opacity));
}
.bg-slate-200 {
--tw-bg-opacity: 1;
background-color: rgb(226 232 240 / var(--tw-bg-opacity));
}
.bg-slate-900 {
--tw-bg-opacity: 1;
background-color: rgb(15 23 42 / var(--tw-bg-opacity));
}
.bg-transparent {
background-color: transparent;
}
.bg-white {
--tw-bg-opacity: 1;
background-color: rgb(255 255 255 / var(--tw-bg-opacity));
}
.object-cover {
-o-object-fit: cover;
object-fit: cover;
}
.p-0 {
padding: 0px;
}
.p-1 {
padding: 0.25rem;
}
.p-16 {
padding: 4rem;
}
.p-3 {
padding: 0.75rem;
}
.p-4 {
padding: 1rem;
}
.p-6 {
padding: 1.5rem;
}
.p-\[1px\] {
padding: 1px;
}
.p-2 {
padding: 0.5rem;
}
.px-1 {
padding-left: 0.25rem;
padding-right: 0.25rem;
}
.px-2 {
padding-left: 0.5rem;
padding-right: 0.5rem;
}
.px-3 {
padding-left: 0.75rem;
padding-right: 0.75rem;
}
.px-4 {
padding-left: 1rem;
padding-right: 1rem;
}
.px-6 {
padding-left: 1.5rem;
padding-right: 1.5rem;
}
.px-8 {
padding-left: 2rem;
padding-right: 2rem;
}
.py-1 {
padding-top: 0.25rem;
padding-bottom: 0.25rem;
}
.py-1\.5 {
padding-top: 0.375rem;
padding-bottom: 0.375rem;
}
.py-10 {
padding-top: 2.5rem;
padding-bottom: 2.5rem;
}
.py-2 {
padding-top: 0.5rem;
padding-bottom: 0.5rem;
}
.py-4 {
padding-top: 1rem;
padding-bottom: 1rem;
}
.py-5 {
padding-top: 1.25rem;
padding-bottom: 1.25rem;
}
.py-6 {
padding-top: 1.5rem;
padding-bottom: 1.5rem;
}
.py-3 {
padding-top: 0.75rem;
padding-bottom: 0.75rem;
}
.pb-10 {
padding-bottom: 2.5rem;
}
.pb-3 {
padding-bottom: 0.75rem;
}
.pb-6 {
padding-bottom: 1.5rem;
}
.pl-2 {
padding-left: 0.5rem;
}
.pl-2\.5 {
padding-left: 0.625rem;
}
.pl-8 {
padding-left: 2rem;
}
.pr-10 {
padding-right: 2.5rem;
}
.pr-2 {
padding-right: 0.5rem;
}
.pr-2\.5 {
padding-right: 0.625rem;
}
.pr-8 {
padding-right: 2rem;
}
.pt-16 {
padding-top: 4rem;
}
.text-center {
text-align: center;
}
.text-end {
text-align: end;
}
.text-2xl {
font-size: 24px;
}
.text-3xl {
font-size: 30px;
}
.text-\[14px\] {
font-size: 14px;
}
.text-\[16px\] {
font-size: 16px;
}
.text-\[70px\] {
font-size: 70px;
}
.text-base {
font-size: 18px;
}
.text-sm {
font-size: 16px;
}
.text-xl {
font-size: 20px;
}
.font-bold {
font-weight: 700;
}
.font-light {
font-weight: 300;
}
.font-medium {
font-weight: 500;
}
.font-semibold {
font-weight: 600;
}
.leading-none {
line-height: 1;
}
.tracking-tight {
letter-spacing: -0.025em;
}
.text-cyan-500 {
--tw-text-opacity: 1;
color: rgb(6 182 212 / var(--tw-text-opacity));
}
.text-gray-600 {
--tw-text-opacity: 1;
color: rgb(75 85 99 / var(--tw-text-opacity));
}
.text-green-600 {
--tw-text-opacity: 1;
color: rgb(22 163 74 / var(--tw-text-opacity));
}
.text-neutral-400 {
--tw-text-opacity: 1;
color: rgb(163 163 163 / var(--tw-text-opacity));
}
.text-neutral-500 {
--tw-text-opacity: 1;
color: rgb(115 115 115 / var(--tw-text-opacity));
}
.text-neutral-600 {
--tw-text-opacity: 1;
color: rgb(82 82 82 / var(--tw-text-opacity));
}
.text-neutral-700 {
--tw-text-opacity: 1;
color: rgb(64 64 64 / var(--tw-text-opacity));
}
.text-red-500 {
--tw-text-opacity: 1;
color: rgb(239 68 68 / var(--tw-text-opacity));
}
.text-sky-500 {
--tw-text-opacity: 1;
color: rgb(14 165 233 / var(--tw-text-opacity));
}
.text-slate-50 {
--tw-text-opacity: 1;
color: rgb(248 250 252 / var(--tw-text-opacity));
}
.text-slate-500 {
--tw-text-opacity: 1;
color: rgb(100 116 139 / var(--tw-text-opacity));
}
.text-slate-900 {
--tw-text-opacity: 1;
color: rgb(15 23 42 / var(--tw-text-opacity));
}
.text-slate-950 {
--tw-text-opacity: 1;
color: rgb(2 6 23 / var(--tw-text-opacity));
}
.text-slate-950\/50 {
color: rgb(2 6 23 / 0.5);
}
.text-white {
--tw-text-opacity: 1;
color: rgb(255 255 255 / var(--tw-text-opacity));
}
.underline-offset-4 {
text-underline-offset: 4px;
}
.opacity-0 {
opacity: 0;
}
.opacity-50 {
opacity: 0.5;
}
.opacity-70 {
opacity: 0.7;
}
.opacity-90 {
opacity: 0.9;
}
.shadow-lg {
--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);
box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
}
.shadow-md {
--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);
box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
}
.outline-none {
outline: 2px solid transparent;
outline-offset: 2px;
}
.outline {
outline-style: solid;
}
.ring-offset-white {
--tw-ring-offset-color: #fff;
}
.drop-shadow-md {
--tw-drop-shadow: drop-shadow(0 4px 3px rgb(0 0 0 / 0.07)) drop-shadow(0 2px 2px rgb(0 0 0 / 0.06));
filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow);
}
.filter {
filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow);
}
.transition {
transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, -webkit-backdrop-filter;
transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter;
transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter, -webkit-backdrop-filter;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 150ms;
}
.transition-all {
transition-property: all;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 150ms;
}
.transition-colors {
transition-property: color, background-color, border-color, text-decoration-color, fill, stroke;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 150ms;
}
.transition-opacity {
transition-property: opacity;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 150ms;
}
.duration-200 {
transition-duration: 200ms;
}
.ease-in-out {
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}
@keyframes enter {
from {
opacity: var(--tw-enter-opacity, 1);
transform: translate3d(var(--tw-enter-translate-x, 0), var(--tw-enter-translate-y, 0), 0) scale3d(var(--tw-enter-scale, 1), var(--tw-enter-scale, 1), var(--tw-enter-scale, 1)) rotate(var(--tw-enter-rotate, 0));
}
}
@keyframes exit {
to {
opacity: var(--tw-exit-opacity, 1);
transform: translate3d(var(--tw-exit-translate-x, 0), var(--tw-exit-translate-y, 0), 0) scale3d(var(--tw-exit-scale, 1), var(--tw-exit-scale, 1), var(--tw-exit-scale, 1)) rotate(var(--tw-exit-rotate, 0));
}
}
.duration-200 {
animation-duration: 200ms;
}
.ease-in-out {
animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}
@layer {
@media (prefers-reduced-motion: no-preference) {
html {
scroll-behavior: smooth;
}
}
html, body {
font-family: "Alexandria", sans-serif;
box-sizing: border-box;
}
.container {
padding-top: 2.5rem;
padding-bottom: 2.5rem;
padding-left: 2rem;
padding-right: 2rem;
}
}
.file\:border-0::file-selector-button {
border-width: 0px;
}
.file\:bg-transparent::file-selector-button {
background-color: transparent;
}
.file\:text-sm::file-selector-button {
font-size: 16px;
}
.file\:font-medium::file-selector-button {
font-weight: 500;
}
.placeholder\:text-slate-500::-moz-placeholder {
--tw-text-opacity: 1;
color: rgb(100 116 139 / var(--tw-text-opacity));
}
.placeholder\:text-slate-500::placeholder {
--tw-text-opacity: 1;
color: rgb(100 116 139 / var(--tw-text-opacity));
}
.hover\:border:hover {
border-width: 1px;
}
.hover\:bg-black\/5:hover {
background-color: rgb(0 0 0 / 0.05);
}
.hover\:bg-green-500\/90:hover {
background-color: rgb(34 197 94 / 0.9);
}
.hover\:bg-indigo-500\/90:hover {
background-color: rgb(99 102 241 / 0.9);
}
.hover\:bg-red-500\/90:hover {
background-color: rgb(239 68 68 / 0.9);
}
.hover\:bg-sky-500\/20:hover {
background-color: rgb(14 165 233 / 0.2);
}
.hover\:bg-sky-500\/80:hover {
background-color: rgb(14 165 233 / 0.8);
}
.hover\:bg-slate-100:hover {
--tw-bg-opacity: 1;
background-color: rgb(241 245 249 / var(--tw-bg-opacity));
}
.hover\:bg-slate-100\/80:hover {
background-color: rgb(241 245 249 / 0.8);
}
.hover\:bg-slate-900\/90:hover {
background-color: rgb(15 23 42 / 0.9);
}
.hover\:bg-transparent:hover {
background-color: transparent;
}
.hover\:bg-sky-400\/90:hover {
background-color: rgb(56 189 248 / 0.9);
}
.hover\:bg-sky-400:hover {
--tw-bg-opacity: 1;
background-color: rgb(56 189 248 / var(--tw-bg-opacity));
}
.hover\:text-red-500:hover {
--tw-text-opacity: 1;
color: rgb(239 68 68 / var(--tw-text-opacity));
}
.hover\:text-sky-500:hover {
--tw-text-opacity: 1;
color: rgb(14 165 233 / var(--tw-text-opacity));
}
.hover\:text-slate-900:hover {
--tw-text-opacity: 1;
color: rgb(15 23 42 / var(--tw-text-opacity));
}
.hover\:text-slate-950:hover {
--tw-text-opacity: 1;
color: rgb(2 6 23 / var(--tw-text-opacity));
}
.hover\:text-white:hover {
--tw-text-opacity: 1;
color: rgb(255 255 255 / var(--tw-text-opacity));
}
.hover\:underline:hover {
text-decoration-line: underline;
}
.hover\:opacity-100:hover {
opacity: 1;
}
.focus\:bg-slate-100:focus {
--tw-bg-opacity: 1;
background-color: rgb(241 245 249 / var(--tw-bg-opacity));
}
.focus\:text-slate-900:focus {
--tw-text-opacity: 1;
color: rgb(15 23 42 / var(--tw-text-opacity));
}
.focus\:opacity-100:focus {
opacity: 1;
}
.focus\:outline-none:focus {
outline: 2px solid transparent;
outline-offset: 2px;
}
.focus\:ring-2:focus {
--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);
box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
}
.focus\:ring-slate-950:focus {
--tw-ring-opacity: 1;
--tw-ring-color: rgb(2 6 23 / var(--tw-ring-opacity));
}
.focus\:ring-offset-2:focus {
--tw-ring-offset-width: 2px;
}
.focus-visible\:outline-none:focus-visible {
outline: 2px solid transparent;
outline-offset: 2px;
}
.focus-visible\:ring-2:focus-visible {
--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);
box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
}
.focus-visible\:ring-slate-950:focus-visible {
--tw-ring-opacity: 1;
--tw-ring-color: rgb(2 6 23 / var(--tw-ring-opacity));
}
.focus-visible\:ring-offset-2:focus-visible {
--tw-ring-offset-width: 2px;
}
.active\:border-b-0:active {
border-bottom-width: 0px;
}
.active\:border-b-2:active {
border-bottom-width: 2px;
}
.disabled\:pointer-events-none:disabled {
pointer-events: none;
}
.disabled\:cursor-not-allowed:disabled {
cursor: not-allowed;
}
.disabled\:opacity-50:disabled {
opacity: 0.5;
}
.group:hover .group-hover\:opacity-100 {
opacity: 1;
}
.group.destructive .group-\[\.destructive\]\:border-slate-100\/40 {
border-color: rgb(241 245 249 / 0.4);
}
.group.destructive .group-\[\.destructive\]\:text-red-300 {
--tw-text-opacity: 1;
color: rgb(252 165 165 / var(--tw-text-opacity));
}
.group.destructive .group-\[\.destructive\]\:hover\:border-red-500\/30:hover {
border-color: rgb(239 68 68 / 0.3);
}
.group.destructive .group-\[\.destructive\]\:hover\:bg-red-500:hover {
--tw-bg-opacity: 1;
background-color: rgb(239 68 68 / var(--tw-bg-opacity));
}
.group.destructive .group-\[\.destructive\]\:hover\:text-red-50:hover {
--tw-text-opacity: 1;
color: rgb(254 242 242 / var(--tw-text-opacity));
}
.group.destructive .group-\[\.destructive\]\:hover\:text-slate-50:hover {
--tw-text-opacity: 1;
color: rgb(248 250 252 / var(--tw-text-opacity));
}
.group.destructive .group-\[\.destructive\]\:focus\:ring-red-400:focus {
--tw-ring-opacity: 1;
--tw-ring-color: rgb(248 113 113 / var(--tw-ring-opacity));
}
.group.destructive .group-\[\.destructive\]\:focus\:ring-red-500:focus {
--tw-ring-opacity: 1;
--tw-ring-color: rgb(239 68 68 / var(--tw-ring-opacity));
}
.group.destructive .group-\[\.destructive\]\:focus\:ring-offset-red-600:focus {
--tw-ring-offset-color: #dc2626;
}
.peer:disabled ~ .peer-disabled\:cursor-not-allowed {
cursor: not-allowed;
}
.peer:disabled ~ .peer-disabled\:opacity-70 {
opacity: 0.7;
}
.data-\[disabled\]\:pointer-events-none[data-disabled] {
pointer-events: none;
}
.data-\[side\=bottom\]\:translate-y-1[data-side=bottom] {
--tw-translate-y: 0.25rem;
transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
}
.data-\[side\=left\]\:-translate-x-1[data-side=left] {
--tw-translate-x: -0.25rem;
transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
}
.data-\[side\=right\]\:translate-x-1[data-side=right] {
--tw-translate-x: 0.25rem;
transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
}
.data-\[side\=top\]\:-translate-y-1[data-side=top] {
--tw-translate-y: -0.25rem;
transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
}
.data-\[swipe\=cancel\]\:translate-x-0[data-swipe=cancel] {
--tw-translate-x: 0px;
transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
}
.data-\[swipe\=end\]\:translate-x-\[var\(--radix-toast-swipe-end-x\)\][data-swipe=end] {
--tw-translate-x: var(--radix-toast-swipe-end-x);
transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
}
.data-\[swipe\=move\]\:translate-x-\[var\(--radix-toast-swipe-move-x\)\][data-swipe=move] {
--tw-translate-x: var(--radix-toast-swipe-move-x);
transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
}
.data-\[state\=open\]\:bg-slate-100[data-state=open] {
--tw-bg-opacity: 1;
background-color: rgb(241 245 249 / var(--tw-bg-opacity));
}
.data-\[state\=open\]\:text-slate-500[data-state=open] {
--tw-text-opacity: 1;
color: rgb(100 116 139 / var(--tw-text-opacity));
}
.data-\[disabled\]\:opacity-50[data-disabled] {
opacity: 0.5;
}
.data-\[swipe\=move\]\:transition-none[data-swipe=move] {
transition-property: none;
}
.data-\[state\=closed\]\:duration-300[data-state=closed] {
transition-duration: 300ms;
}
.data-\[state\=open\]\:duration-500[data-state=open] {
transition-duration: 500ms;
}
.data-\[state\=open\]\:animate-in[data-state=open] {
animation-name: enter;
animation-duration: 150ms;
--tw-enter-opacity: initial;
--tw-enter-scale: initial;
--tw-enter-rotate: initial;
--tw-enter-translate-x: initial;
--tw-enter-translate-y: initial;
}
.data-\[state\=closed\]\:animate-out[data-state=closed] {
animation-name: exit;
animation-duration: 150ms;
--tw-exit-opacity: initial;
--tw-exit-scale: initial;
--tw-exit-rotate: initial;
--tw-exit-translate-x: initial;
--tw-exit-translate-y: initial;
}
.data-\[swipe\=end\]\:animate-out[data-swipe=end] {
animation-name: exit;
animation-duration: 150ms;
--tw-exit-opacity: initial;
--tw-exit-scale: initial;
--tw-exit-rotate: initial;
--tw-exit-translate-x: initial;
--tw-exit-translate-y: initial;
}
.data-\[state\=closed\]\:fade-out-0[data-state=closed] {
--tw-exit-opacity: 0;
}
.data-\[state\=closed\]\:fade-out-80[data-state=closed] {
--tw-exit-opacity: 0.8;
}
.data-\[state\=open\]\:fade-in-0[data-state=open] {
--tw-enter-opacity: 0;
}
.data-\[state\=closed\]\:zoom-out-95[data-state=closed] {
--tw-exit-scale: .95;
}
.data-\[state\=open\]\:zoom-in-95[data-state=open] {
--tw-enter-scale: .95;
}
.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom] {
--tw-enter-translate-y: -0.5rem;
}
.data-\[side\=left\]\:slide-in-from-right-2[data-side=left] {
--tw-enter-translate-x: 0.5rem;
}
.data-\[side\=right\]\:slide-in-from-left-2[data-side=right] {
--tw-enter-translate-x: -0.5rem;
}
.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top] {
--tw-enter-translate-y: 0.5rem;
}
.data-\[state\=closed\]\:slide-out-to-bottom[data-state=closed] {
--tw-exit-translate-y: 100%;
}
.data-\[state\=closed\]\:slide-out-to-left[data-state=closed] {
--tw-exit-translate-x: -100%;
}
.data-\[state\=closed\]\:slide-out-to-left-1\/2[data-state=closed] {
--tw-exit-translate-x: -50%;
}
.data-\[state\=closed\]\:slide-out-to-right[data-state=closed] {
--tw-exit-translate-x: 100%;
}
.data-\[state\=closed\]\:slide-out-to-right-full[data-state=closed] {
--tw-exit-translate-x: 100%;
}
.data-\[state\=closed\]\:slide-out-to-top[data-state=closed] {
--tw-exit-translate-y: -100%;
}
.data-\[state\=closed\]\:slide-out-to-top-\[48\%\][data-state=closed] {
--tw-exit-translate-y: -48%;
}
.data-\[state\=open\]\:slide-in-from-bottom[data-state=open] {
--tw-enter-translate-y: 100%;
}
.data-\[state\=open\]\:slide-in-from-left[data-state=open] {
--tw-enter-translate-x: -100%;
}
.data-\[state\=open\]\:slide-in-from-left-1\/2[data-state=open] {
--tw-enter-translate-x: -50%;
}
.data-\[state\=open\]\:slide-in-from-right[data-state=open] {
--tw-enter-translate-x: 100%;
}
.data-\[state\=open\]\:slide-in-from-top[data-state=open] {
--tw-enter-translate-y: -100%;
}
.data-\[state\=open\]\:slide-in-from-top-\[48\%\][data-state=open] {
--tw-enter-translate-y: -48%;
}
.data-\[state\=open\]\:slide-in-from-top-full[data-state=open] {
--tw-enter-translate-y: -100%;
}
.data-\[state\=closed\]\:duration-300[data-state=closed] {
animation-duration: 300ms;
}
.data-\[state\=open\]\:duration-500[data-state=open] {
animation-duration: 500ms;
}
.dark\:border-red-900:is(.dark *) {
--tw-border-opacity: 1;
border-color: rgb(127 29 29 / var(--tw-border-opacity));
}
.dark\:border-slate-800:is(.dark *) {
--tw-border-opacity: 1;
border-color: rgb(30 41 59 / var(--tw-border-opacity));
}
.dark\:bg-gray-700:is(.dark *) {
--tw-bg-opacity: 1;
background-color: rgb(55 65 81 / var(--tw-bg-opacity));
}
.dark\:bg-red-900:is(.dark *) {
--tw-bg-opacity: 1;
background-color: rgb(127 29 29 / var(--tw-bg-opacity));
}
.dark\:bg-slate-50:is(.dark *) {
--tw-bg-opacity: 1;
background-color: rgb(248 250 252 / var(--tw-bg-opacity));
}
.dark\:bg-slate-800:is(.dark *) {
--tw-bg-opacity: 1;
background-color: rgb(30 41 59 / var(--tw-bg-opacity));
}
.dark\:bg-slate-950:is(.dark *) {
--tw-bg-opacity: 1;
background-color: rgb(2 6 23 / var(--tw-bg-opacity));
}
.dark\:text-gray-100:is(.dark *) {
--tw-text-opacity: 1;
color: rgb(243 244 246 / var(--tw-text-opacity));
}
.dark\:text-red-900:is(.dark *) {
--tw-text-opacity: 1;
color: rgb(127 29 29 / var(--tw-text-opacity));
}
.dark\:text-slate-400:is(.dark *) {
--tw-text-opacity: 1;
color: rgb(148 163 184 / var(--tw-text-opacity));
}
.dark\:text-slate-50:is(.dark *) {
--tw-text-opacity: 1;
color: rgb(248 250 252 / var(--tw-text-opacity));
}
.dark\:text-slate-50\/50:is(.dark *) {
color: rgb(248 250 252 / 0.5);
}
.dark\:text-slate-900:is(.dark *) {
--tw-text-opacity: 1;
color: rgb(15 23 42 / var(--tw-text-opacity));
}
.dark\:ring-offset-slate-950:is(.dark *) {
--tw-ring-offset-color: #020617;
}
.dark\:placeholder\:text-slate-400:is(.dark *)::-moz-placeholder {
--tw-text-opacity: 1;
color: rgb(148 163 184 / var(--tw-text-opacity));
}
.dark\:placeholder\:text-slate-400:is(.dark *)::placeholder {
--tw-text-opacity: 1;
color: rgb(148 163 184 / var(--tw-text-opacity));
}
.dark\:hover\:bg-red-900\/90:hover:is(.dark *) {
background-color: rgb(127 29 29 / 0.9);
}
.dark\:hover\:bg-slate-50\/90:hover:is(.dark *) {
background-color: rgb(248 250 252 / 0.9);
}
.dark\:hover\:bg-slate-800:hover:is(.dark *) {
--tw-bg-opacity: 1;
background-color: rgb(30 41 59 / var(--tw-bg-opacity));
}
.dark\:hover\:bg-slate-800\/80:hover:is(.dark *) {
background-color: rgb(30 41 59 / 0.8);
}
.dark\:hover\:text-slate-50:hover:is(.dark *) {
--tw-text-opacity: 1;
color: rgb(248 250 252 / var(--tw-text-opacity));
}
.dark\:focus\:bg-slate-800:focus:is(.dark *) {
--tw-bg-opacity: 1;
background-color: rgb(30 41 59 / var(--tw-bg-opacity));
}
.dark\:focus\:text-slate-50:focus:is(.dark *) {
--tw-text-opacity: 1;
color: rgb(248 250 252 / var(--tw-text-opacity));
}
.dark\:focus\:ring-slate-300:focus:is(.dark *) {
--tw-ring-opacity: 1;
--tw-ring-color: rgb(203 213 225 / var(--tw-ring-opacity));
}
.dark\:focus-visible\:ring-slate-300:focus-visible:is(.dark *) {
--tw-ring-opacity: 1;
--tw-ring-color: rgb(203 213 225 / var(--tw-ring-opacity));
}
.group.destructive .dark\:group-\[\.destructive\]\:border-slate-800\/40:is(.dark *) {
border-color: rgb(30 41 59 / 0.4);
}
.group.destructive .dark\:group-\[\.destructive\]\:hover\:border-red-900\/30:hover:is(.dark *) {
border-color: rgb(127 29 29 / 0.3);
}
.group.destructive .dark\:group-\[\.destructive\]\:hover\:bg-red-900:hover:is(.dark *) {
--tw-bg-opacity: 1;
background-color: rgb(127 29 29 / var(--tw-bg-opacity));
}
.group.destructive .dark\:group-\[\.destructive\]\:hover\:text-slate-50:hover:is(.dark *) {
--tw-text-opacity: 1;
color: rgb(248 250 252 / var(--tw-text-opacity));
}
.group.destructive .dark\:group-\[\.destructive\]\:focus\:ring-red-900:focus:is(.dark *) {
--tw-ring-opacity: 1;
--tw-ring-color: rgb(127 29 29 / var(--tw-ring-opacity));
}
.dark\:data-\[state\=open\]\:bg-slate-800[data-state=open]:is(.dark *) {
--tw-bg-opacity: 1;
background-color: rgb(30 41 59 / var(--tw-bg-opacity));
}
.dark\:data-\[state\=open\]\:text-slate-400[data-state=open]:is(.dark *) {
--tw-text-opacity: 1;
color: rgb(148 163 184 / var(--tw-text-opacity));
}
@media (min-width: 450px) {
.xs\:grid-cols-2 {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (min-width: 640px) {
.sm\:bottom-0 {
bottom: 0px;
}
.sm\:right-0 {
right: 0px;
}
.sm\:top-auto {
top: auto;
}
.sm\:max-h-\[80vh\] {
max-height: 80vh;
}
.sm\:max-w-sm {
max-width: 24rem;
}
.sm\:flex-row {
flex-direction: row;
}
.sm\:flex-col {
flex-direction: column;
}
.sm\:justify-end {
justify-content: flex-end;
}
.sm\:space-x-2 > :not([hidden]) ~ :not([hidden]) {
--tw-space-x-reverse: 0;
margin-right: calc(0.5rem * var(--tw-space-x-reverse));
margin-left: calc(0.5rem * calc(1 - var(--tw-space-x-reverse)));
}
.sm\:rounded-lg {
border-radius: 0.5rem;
}
.sm\:text-left {
text-align: left;
}
.data-\[state\=open\]\:sm\:slide-in-from-bottom-full[data-state=open] {
--tw-enter-translate-y: 100%;
}
}
@media (min-width: 768px) {
.md\:max-w-\[420px\] {
max-width: 420px;
}
}
@media (min-width: 1024px) {
.lg\:block {
display: block;
}
.lg\:flex {
display: flex;
}
.lg\:hidden {
display: none;
}
.lg\:max-w-\[450px\] {
max-width: 450px;
}
.lg\:grid-cols-\[repeat\(auto-fill\2c minmax\(210px\2c 1fr\)\)\] {
grid-template-columns: repeat(auto-fill,minmax(210px,1fr));
}
.lg\:flex-row {
flex-direction: row;
}
.lg\:justify-between {
justify-content: space-between;
}
.lg\:gap-14 {
gap: 3.5rem;
}
.lg\:px-14 {
padding-left: 3.5rem;
padding-right: 3.5rem;
}
.lg\:px-32 {
padding-left: 8rem;
padding-right: 8rem;
}
.lg\:px-8 {
padding-left: 2rem;
padding-right: 2rem;
}
.lg\:pt-4 {
padding-top: 1rem;
}
.lg\:text-3xl {
font-size: 30px;
}
}
.\[\&\>\*\]\:bg-sky-400>* {
--tw-bg-opacity: 1;
background-color: rgb(56 189 248 / var(--tw-bg-opacity));
}
.\[\&\>span\]\:line-clamp-1>span {
overflow: hidden;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 1;
}
|
<template>
<div>
<div class="flex mb-1">
<button
class="btn btn-green mr-2 flex items-center justify-center"
@click="toggleTorch"
>
<light-bulb-icon class="w-5 h-5 mr-1"></light-bulb-icon>
Licht
</button>
<button
class="w-full btn btn-red flex items-center justify-center"
@click="$emit('cancel')"
>
<x-circle-icon class="w-5 h-5 mr-1"></x-circle-icon>
Cancel
</button>
</div>
<div id="interactive" class="viewport scanner">
<video />
<canvas class="drawingBuffer" />
</div>
</div>
</template>
<script>
import Quagga from "@ericblade/quagga2";
import { LightBulbIcon, XCircleIcon } from "@heroicons/vue/24/outline";
export default {
name: "QuaggaScanner",
components: {
LightBulbIcon,
XCircleIcon,
},
props: {
onDetected: {
type: Function,
default(result) {
console.log("detected: ", result);
},
},
onProcessed: {
type: Function,
default(result) {
let drawingCtx = Quagga.canvas.ctx.overlay;
let drawingCanvas = Quagga.canvas.dom.overlay;
if (result) {
if (result.boxes) {
drawingCtx.clearRect(
0,
0,
parseInt(drawingCanvas.getAttribute("width")),
parseInt(drawingCanvas.getAttribute("height"))
);
result.boxes
.filter(function (box) {
return box !== result.box;
})
.forEach(function (box) {
Quagga.ImageDebug.drawPath(box, { x: 0, y: 1 }, drawingCtx, {
color: "green",
lineWidth: 2,
});
});
}
if (result.box) {
Quagga.ImageDebug.drawPath(result.box, { x: 0, y: 1 }, drawingCtx, {
color: "#00F",
lineWidth: 2,
});
}
if (result.codeResult && result.codeResult.code) {
Quagga.ImageDebug.drawPath(
result.line,
{ x: "x", y: "y" },
drawingCtx,
{ color: "red", lineWidth: 3 }
);
}
}
},
},
readerTypes: {
type: Array,
default: () => ["code_128_reader"],
},
readerSize: {
type: Object,
default: () => ({
width: 640,
height: 480,
}),
validator: (o) =>
typeof o.width === "number" && typeof o.height === "number",
},
aspectRatio: {
type: Object,
default: () => ({
min: 1,
max: 2,
}),
validator: (o) => typeof o.min === "number" && typeof o.max === "number",
},
facingMode: {
type: String,
default: () => "environment",
},
},
emits: ["cancel"],
data: function () {
return {
quaggaState: {
inputStream: {
type: "LiveStream",
constraints: {
width: { min: this.readerSize.width },
height: { min: this.readerSize.height },
facingMode: this.facingMode,
aspectRatio: { min: 1, max: 2 },
},
},
locator: {
patchSize: "medium",
halfSample: true,
},
numOfWorkers: 2,
frequency: 10,
decoder: {
readers: this.readerTypes,
},
locate: true,
},
torch: false,
};
},
watch: {
onDetected: function (oldValue, newValue) {
if (oldValue) Quagga.offDetected(oldValue);
if (newValue) Quagga.onDetected(newValue);
},
onProcessed: function (oldValue, newValue) {
if (oldValue) Quagga.offProcessed(oldValue);
if (newValue) Quagga.onProcessed(newValue);
},
},
mounted: function () {
Quagga.init(this.quaggaState, function (err) {
if (err) {
return console.error(err);
}
Quagga.start();
});
Quagga.onDetected(this.onDetected);
Quagga.onProcessed(this.onProcessed);
},
unmounted: function () {
if (this.onDetected) Quagga.offDetected(this.onDetected);
if (this.onProcessed) Quagga.offProcessed(this.offProcessed);
Quagga.stop();
},
methods: {
getCapabilities: function () {
const caps = Quagga.CameraAccess.getActiveTrack()?.getCapabilities();
console.log(caps);
},
toggleTorch: function () {
this.torch = !this.torch;
const track = Quagga.CameraAccess.getActiveTrack();
if (track) {
track
.applyConstraints({
advanced: [{ torch: this.torch }],
})
.catch((e) => console.log(e));
}
},
},
};
</script>
<style scoped>
.viewport {
position: relative;
}
.viewport canvas,
.viewport video {
position: absolute;
left: 0;
top: 0;
}
</style>
|
import { promises as fs } from "fs"
import { getExamplePackages, getWorkspacePackages } from "./get-packages"
function sortObject(obj: Record<string, any>) {
return Object.keys(obj)
.sort()
.reduce((acc, key) => {
acc[key] = obj[key]
return acc
}, {} as Record<string, any>)
}
async function main() {
const pkgs = await getWorkspacePackages()
const pkgsWithoutFrameworks = pkgs.filter((pkg) => !pkg.dir.includes("frameworks")).map((pkg) => pkg.manifest.name)
const workspaceDeps = pkgsWithoutFrameworks.reduce((deps, name) => {
deps[name!] = "workspace:*"
return deps
}, {} as any)
const examples = await getExamplePackages()
await Promise.all(
examples.map(({ manifest, dir }) => {
const newManifest = {
...manifest,
dependencies: sortObject({
...manifest.dependencies,
...workspaceDeps,
}),
}
return fs.writeFile(`${dir}/package.json`, JSON.stringify(newManifest, null, 2))
}),
)
}
main()
|
import React from 'react'
import { Container } from '@design/container'
import { useListsContext, useUIContext } from '@ui/contexts'
import {Text} from '@design/text'
import styled, { useTheme, css } from 'styled-components'
interface ITodoListBackground {
children?: JSX.Element | JSX.Element[] | string;
listId?: string;
}
export const ListsBackground = (props: ITodoListBackground) => {
const { dispatch, state } = useUIContext()
const { selectedTodoListId } = state
const { dispatch: listsDispatch, state: listsState } = useListsContext()
const { listsData } = listsState
const theme = useTheme()
if (!listsData) {
return (
<Container
flexDirection = { 'column'}
background = { theme.colors.neutral.surface }
width = {'100%'}
height = {'100%'}
>
<Text text={"Loading Lists Data"} color={theme.colors.neutral.onBackground} fontSize={'xs'} fontFamily={'Albert_Sans'} />
</Container >
)
}else{
return (
<Container
background={selectedTodoListId === listsData._id ? theme.colors.neutral.surface : theme.colors.neutral.surfaceLow}
width = {'100%'}
height = {'fit-content'}
justifyContent = {'space-between'}
alignItems = {'center'}
pl = {'10%'}
>
{props.children}
</Container>
)
}
}
|
# Configuración de Python
[Instalación](#instalacion)
[Creación del Hola Mundo](#creación-del-hola-mundo)
[Configuración del servidor web](#configuración-del-servidor-web)
[Supervisor](#supervisor)
El objetivo de esta sección es configurar nuestro servidor web para que responda a peticiones que procesen código *Python*.
## Instalación
Lo primero será instalar la última versión de Python disponible para el sistema:
~~~console
sdelquin@claseando:~$ sudo apt install -y python3.7
Leyendo lista de paquetes... Hecho
Des:4 http://mirrors.digitalocean.com/ubuntu bionic-updates/universe amd64 python3.7 amd64 3.7.0-1~18.04 [264 kB]
Descargados 4.245 kB en 1s (5.154 kB/s)
Seleccionando el paquete libpython3.7-minimal:amd64 previamente no seleccionado.
(Leyendo la base de datos ... 95040 ficheros o directorios instalados actualmente.)
Preparando para desempaquetar .../libpython3.7-minimal_3.7.0-1~18.04_amd64.deb ...
Desempaquetando libpython3.7-minimal:amd64 (3.7.0-1~18.04) ...
Seleccionando el paquete python3.7-minimal previamente no seleccionado.
Preparando para desempaquetar .../python3.7-minimal_3.7.0-1~18.04_amd64.deb ...
Desempaquetando python3.7-minimal (3.7.0-1~18.04) ...
Seleccionando el paquete libpython3.7-stdlib:amd64 previamente no seleccionado.
Preparando para desempaquetar .../libpython3.7-stdlib_3.7.0-1~18.04_amd64.deb ...
Desempaquetando libpython3.7-stdlib:amd64 (3.7.0-1~18.04) ...
Seleccionando el paquete python3.7 previamente no seleccionado.
Preparando para desempaquetar .../python3.7_3.7.0-1~18.04_amd64.deb ...
Desempaquetando python3.7 (3.7.0-1~18.04) ...
Procesando disparadores para mime-support (3.60ubuntu1) ...
Configurando libpython3.7-minimal:amd64 (3.7.0-1~18.04) ...
Configurando python3.7-minimal (3.7.0-1~18.04) ...
Procesando disparadores para man-db (2.8.3-2) ...
Configurando libpython3.7-stdlib:amd64 (3.7.0-1~18.04) ...
Configurando python3.7 (3.7.0-1~18.04) ...
sdelquin@claseando:~$
~~~
Vamos ahora a probar que la instalación fue correcta. Ejecutamos lo siguiente:
~~~console
sdelquin@claseando:~$ python3.7
Python 3.7.0 (default, Sep 12 2018, 18:30:08)
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()
sdelquin@claseando:~$
~~~
Para no tener que estarnos acordando de la versión a la hora de lanzar el intérprete de Python, podemos añadir un *alias* en el fichero `~/.bashrc`:
~~~console
sdelquin@claseando:~$ echo 'alias python=python3.7' >> .bashrc
sdelquin@claseando:~$ tail -1 .bashrc
alias python=python3.7
sdelquin@claseando:~$ source .bashrc
sdelquin@claseando:~$ python
Python 3.7.0 (default, Sep 12 2018, 18:30:08)
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()
sdelquin@claseando:~$
~~~
### Librerías de desarrollo para Python
Los paquetes de *Python* necesitan ciertas librerías para su funcionamiento. Por ello debemos instalar lo siguiente:
~~~console
sdelquin@claseando:~$ sudo apt install -y python3.7-dev python3-distutils
Leyendo lista de paquetes... Hecho
Creando árbol de dependencias
Leyendo la información de estado... Hecho
El paquete indicado a continuación se instaló de forma automática y ya no es necesario.
grub-pc-bin
Utilice «sudo apt autoremove» para eliminarlo.
Preparando para desempaquetar .../4-libpython3.7_3.7.0-1~18.04_amd64.deb ...
Desempaquetando libpython3.7:amd64 (3.7.0-1~18.04) ...
Seleccionando el paquete libpython3.7-dev:amd64 previamente no seleccionado.
Preparando para desempaquetar .../5-libpython3.7-dev_3.7.0-1~18.04_amd64.deb ...
Desempaquetando libpython3.7-dev:amd64 (3.7.0-1~18.04) ...
Seleccionando el paquete manpages-dev previamente no seleccionado.
Preparando para desempaquetar .../6-manpages-dev_4.15-1_all.deb ...
Desempaquetando manpages-dev (4.15-1) ...
Seleccionando el paquete python3.7-dev previamente no seleccionado.
Preparando para desempaquetar .../7-python3.7-dev_3.7.0-1~18.04_amd64.deb ...
Desempaquetando python3.7-dev (3.7.0-1~18.04) ...
Configurando linux-libc-dev:amd64 (4.15.0-36.39) ...
Procesando disparadores para libc-bin (2.27-3ubuntu1) ...
Configurando libpython3.7:amd64 (3.7.0-1~18.04) ...
Procesando disparadores para man-db (2.8.3-2) ...
Configurando libc-dev-bin (2.27-3ubuntu1) ...
Configurando manpages-dev (4.15-1) ...
Configurando libc6-dev:amd64 (2.27-3ubuntu1) ...
Configurando libexpat1-dev:amd64 (2.2.5-3) ...
Configurando libpython3.7-dev:amd64 (3.7.0-1~18.04) ...
Configurando python3.7-dev (3.7.0-1~18.04) ...
Procesando disparadores para libc-bin (2.27-3ubuntu1) ...
sdelquin@claseando:~$
~~~
Para la compilación de muchos paquetes, también necesitaremos un compilador de *C*:
~~~console
sdelquin@claseando:~$ sudo apt install -y gcc
Leyendo lista de paquetes... Hecho
Creando árbol de dependencias
Leyendo la información de estado... Hecho
El paquete indicado a continuación se instaló de forma automática y ya no es necesario.
grub-pc-bin
Utilice «sudo apt autoremove» para eliminarlo.
Se instalarán los siguientes paquetes adicionales:
binutils binutils-common binutils-x86-64-linux-gnu cpp cpp-7 gcc-7 gcc-7-base gcc-8-base libasan4
libatomic1 libbinutils libcc1-0 libcilkrts5 libgcc-7-dev libgcc1 libgomp1 libisl19 libitm1 liblsan0
libmpc3 libmpx2 libquadmath0 libstdc++6 libtsan0 libubsan0
Paquetes sugeridos:
binutils-doc cpp-doc gcc-7-locales gcc-multilib make autoconf automake libtool flex bison gdb gcc-doc
gcc-7-multilib gcc-7-doc libgcc1-dbg libgomp1-dbg libitm1-dbg libatomic1-dbg libasan4-dbg liblsan0-dbg
libtsan0-dbg libubsan0-dbg libcilkrts5-dbg libmpx2-dbg libquadmath0-dbg
Se instalarán los siguientes paquetes NUEVOS:
binutils binutils-common binutils-x86-64-linux-gnu cpp cpp-7 gcc gcc-7 gcc-7-base libasan4 libatomic1
libbinutils libcc1-0 libcilkrts5 libgcc-7-dev libgomp1 libisl19 libitm1 liblsan0 libmpc3 libmpx2
libquadmath0 libtsan0 libubsan0
Se actualizarán los siguientes paquetes:
gcc-8-base libgcc1 libstdc++6
3 actualizados, 23 nuevos se instalarán, 0 para eliminar y 46 no actualizados.
Se necesita descargar 21,5 MB de archivos.
Se utilizarán 85,9 MB de espacio de disco adicional después de esta operación.
Des:1 http://ams2.mirrors.digitalocean.com/ubuntu bionic-updates/main amd64 gcc-8-base amd64 8.2.0-1ubuntu2~18.04 [18,3 kB]
Des:2 http://ams2.mirrors.digitalocean.com/ubuntu bionic-updates/main amd64 libstdc++6 amd64 8.2.0-1ubuntu2~18.04 [398 kB]
Des:3 http://ams2.mirrors.digitalocean.com/ubuntu bionic-updates/main amd64 libgcc1 amd64 1:8.2.0-1ubuntu2~18.04 [40,7 kB]
Des:4 http://ams2.mirrors.digitalocean.com/ubuntu bionic-updates/main amd64 binutils-common amd64 2.30-21ubuntu1~18.04 [193 kB]
Des:5 http://ams2.mirrors.digitalocean.com/ubuntu bionic-updates/main amd64 libbinutils amd64 2.30-21ubuntu1~18.04 [502 kB]
Des:6 http://ams2.mirrors.digitalocean.com/ubuntu bionic-updates/main amd64 binutils-x86-64-linux-gnu amd64 2.30-21ubuntu1~18.04 [1.855 kB]
Des:7 http://ams2.mirrors.digitalocean.com/ubuntu bionic-updates/main amd64 binutils amd64 2.30-21ubuntu1~18.04 [3.392 B]
Des:8 http://ams2.mirrors.digitalocean.com/ubuntu bionic-updates/main amd64 gcc-7-base amd64 7.3.0-27ubuntu1~18.04 [18,9 kB]
Des:9 http://ams2.mirrors.digitalocean.com/ubuntu bionic/main amd64 libisl19 amd64 0.19-1 [551 kB]
Des:10 http://ams2.mirrors.digitalocean.com/ubuntu bionic/main amd64 libmpc3 amd64 1.1.0-1 [40,8 kB]
Des:11 http://ams2.mirrors.digitalocean.com/ubuntu bionic-updates/main amd64 cpp-7 amd64 7.3.0-27ubuntu1~18.04 [6.738 kB]
Des:12 http://ams2.mirrors.digitalocean.com/ubuntu bionic-updates/main amd64 cpp amd64 4:7.3.0-3ubuntu2.1 [27,6 kB]
Des:13 http://ams2.mirrors.digitalocean.com/ubuntu bionic-updates/main amd64 libcc1-0 amd64 8.2.0-1ubuntu2~18.04 [39,5 kB]
Des:14 http://ams2.mirrors.digitalocean.com/ubuntu bionic-updates/main amd64 libgomp1 amd64 8.2.0-1ubuntu2~18.04 [76,4 kB]
Des:15 http://ams2.mirrors.digitalocean.com/ubuntu bionic-updates/main amd64 libitm1 amd64 8.2.0-1ubuntu2~18.04 [28,1 kB]
Configurando libtsan0:amd64 (8.2.0-1ubuntu2~18.04) ...
Configurando liblsan0:amd64 (8.2.0-1ubuntu2~18.04) ...
Configurando gcc-7-base:amd64 (7.3.0-27ubuntu1~18.04) ...
Configurando binutils-common:amd64 (2.30-21ubuntu1~18.04) ...
Configurando libmpx2:amd64 (8.2.0-1ubuntu2~18.04) ...
Procesando disparadores para libc-bin (2.27-3ubuntu1) ...
Procesando disparadores para man-db (2.8.3-2) ...
Configurando libmpc3:amd64 (1.1.0-1) ...
Configurando libitm1:amd64 (8.2.0-1ubuntu2~18.04) ...
Configurando libisl19:amd64 (0.19-1) ...
Configurando libasan4:amd64 (7.3.0-27ubuntu1~18.04) ...
Configurando libbinutils:amd64 (2.30-21ubuntu1~18.04) ...
Configurando libcilkrts5:amd64 (7.3.0-27ubuntu1~18.04) ...
Configurando libubsan0:amd64 (7.3.0-27ubuntu1~18.04) ...
Configurando libgcc-7-dev:amd64 (7.3.0-27ubuntu1~18.04) ...
Configurando cpp-7 (7.3.0-27ubuntu1~18.04) ...
Configurando binutils-x86-64-linux-gnu (2.30-21ubuntu1~18.04) ...
Configurando cpp (4:7.3.0-3ubuntu2.1) ...
Configurando binutils (2.30-21ubuntu1~18.04) ...
Configurando gcc-7 (7.3.0-27ubuntu1~18.04) ...
Configurando gcc (4:7.3.0-3ubuntu2.1) ...
Procesando disparadores para libc-bin (2.27-3ubuntu1) ...
sdelquin@claseando:~$
~~~
Comprobamos la instalación del compilador `gcc`:
~~~console
sdelquin@claseando:~$ gcc --version
gcc (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
sdelquin@claseando:~$
~~~
### Gestión de paquetes
Existe una herramienta que permite instalar paquetes *python*. Se llama `pip`. Para su instalación hacemos lo siguiente:
~~~console
sdelquin@claseando:~$ mkdir tmp
sdelquin@claseando:~$ cd tmp
sdelquin@claseando:~/tmp$ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 1622k 100 1622k 0 0 6338k 0 --:--:-- --:--:-- --:--:-- 6314k
sdelquin@claseando:~/tmp$ sudo -H python3.7 get-pip.py
Collecting pip
Downloading https://files.pythonhosted.org/packages/c2/d7/90f34cb0d83a6c5631cf71dfe64cc1054598c843a92b400e55675cc2ac37/pip-18.1-py2.py3-none-any.whl (1.3MB)
100% |████████████████████████████████| 1.3MB 8.9MB/s
Installing collected packages: pip
Found existing installation: pip 18.1
Uninstalling pip-18.1:
Successfully uninstalled pip-18.1
Successfully installed pip-18.1
sdelquin@claseando:~/tmp$
~~~
Comprobamos la instalación de `pip` lanzando el siguiente comando:
~~~console
sdelquin@claseando:~$ pip --version
pip 18.1 from /usr/local/lib/python3.7/dist-packages/pip (python 3.7)
sdelquin@claseando:~$
~~~
### Entornos virtuales
La forma más extendida de trabajar con aplicaciones *Python* es usar entornos virtuales (*virtualenvs*). Se trata de un mecanismo para aislar las librerías y crear un ambiente de trabajo independiente.
Antes de nada vamos a añadir a nuestro `PATH` la carpeta `~/.local/bin` porque ahí se van a instalar ciertos ficheros ejecutables (para los entornos virtuales):
~~~console
sdelquin@claseando:~$ vi .bashrc
...
~~~
> Añadir al final del fichero:
~~~bash
export PATH=$PATH:~/.local/bin
~~~
Recargamos el fichero de configuración:
~~~console
sdelquin@claseando:~$ source .bashrc
sdelquin@claseando:~$
~~~
La herramienta más moderna que permite trabajar con entornos virtuales es `pipenv`. Vamos a realizar su instalación:
~~~console
sdelquin@claseando:~$ sudo -H pip install pipenv
Collecting pipenv
Downloading https://files.pythonhosted.org/packages/7a/44/36bc7dc1c15b17419e36dd8e9c0b4b42fd5761071c7a171d7351c4ad49bd/pipenv-2018.10.9-py3-none-any.whl (5.1MB)
100% |████████████████████████████████| 5.1MB 5.2MB/s
Requirement already satisfied: setuptools>=36.2.1 in /usr/lib/python3/dist-packages (from pipenv) (39.0.1)
Requirement already satisfied: pip>=9.0.1 in /usr/local/lib/python3.7/dist-packages (from pipenv) (18.1)
Collecting virtualenv-clone>=0.2.5 (from pipenv)
Downloading https://files.pythonhosted.org/packages/6d/c2/dccb5ccf599e0c5d1eea6acbd058af7a71384f9740179db67a9182a24798/virtualenv_clone-0.3.0-py2.py3-none-any.whl
Collecting virtualenv (from pipenv)
Downloading https://files.pythonhosted.org/packages/b6/30/96a02b2287098b23b875bc8c2f58071c35d2efe84f747b64d523721dc2b5/virtualenv-16.0.0-py2.py3-none-any.whl (1.9MB)
100% |████████████████████████████████| 1.9MB 10.1MB/s
Requirement already satisfied: certifi in /usr/lib/python3/dist-packages (from pipenv) (2018.1.18)
Installing collected packages: virtualenv-clone, virtualenv, pipenv
Successfully installed pipenv-2018.10.9 virtualenv-16.0.0 virtualenv-clone-0.3.0
sdelquin@claseando:~$
~~~
#### Primer entorno virtual
Creamos la carpeta que va a contener el entorno virtual:
~~~console
sdelquin@claseando:~$ mkdir -p webapps/hellopython
sdelquin@claseando:~$ cd webapps/hellopython
sdelquin@claseando:~/webapps/hellopython$
~~~
A continuación creamos nuestro primer entorno virtual:
~~~console
sdelquin@claseando:~/webapps/hellopython$ pipenv install
Creating a virtualenv for this project…
Pipfile: /home/sdelquin/webapps/hellopython/Pipfile
Using /usr/bin/python3.7 (3.7.0) to create virtualenv…
⠹Already using interpreter /usr/bin/python3.7
Using base prefix '/usr'
/home/sdelquin/.local/lib/python3.7/site-packages/virtualenv.py:1041: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
import imp
New python executable in /home/sdelquin/.local/share/virtualenvs/hellopython-j3yclt1I/bin/python3.7
Also creating executable in /home/sdelquin/.local/share/virtualenvs/hellopython-j3yclt1I/bin/python
Installing setuptools, pip, wheel...done.
Virtualenv location: /home/sdelquin/.local/share/virtualenvs/hellopython-j3yclt1I
Creating a Pipfile for this project…
Pipfile.lock not found, creating…
Locking [dev-packages] dependencies…
Locking [packages] dependencies…
Updated Pipfile.lock (a65489)!
Installing dependencies from Pipfile.lock (a65489)…
🐍 ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 0/0 — 00:00:00
To activate this project's virtualenv, run pipenv shell.
Alternatively, run a command inside the virtualenv with pipenv run.
sdelquin@claseando:~/webapps/hellopython$
~~~
Si miramos en la carpeta, vemos que se han creado dos ficheros `Pipfile` de dependencias:
~~~console
sdelquin@claseando:~/webapps/hellopython$ ls
Pipfile Pipfile.lock
sdelquin@claseando:~/webapps/hellopython$
~~~
¿Pero dónde está realmente el entorno virtual con todas las librerías?
~~~console
sdelquin@claseando:~/webapps/hellopython$ pipenv --venv
/home/sdelquin/.local/share/virtualenvs/hellopython-j3yclt1I
sdelquin@claseando:~/webapps/hellopython$ tree -dL 3 /home/sdelquin/.local/share/virtualenvs/hellopython-j3yclt1I
/home/sdelquin/.local/share/virtualenvs/hellopython-j3yclt1I
├── bin
├── include
│ └── python3.7m -> /usr/include/python3.7m
├── lib
│ └── python3.7
│ ├── collections -> /usr/lib/python3.7/collections
│ ├── config-3.7m-x86_64-linux-gnu -> /usr/lib/python3.7/config-3.7m-x86_64-linux-gnu
│ ├── distutils
│ ├── encodings -> /usr/lib/python3.7/encodings
│ ├── importlib -> /usr/lib/python3.7/importlib
│ ├── lib-dynload -> /usr/lib/python3.7/lib-dynload
│ └── site-packages
└── src
13 directories
sdelquin@claseando:~/webapps/hellopython$
~~~
### uWSGI
*uWSGI* es el encargado de procesar las peticiones *http* para aplicaciones con código *python*. Se puede ver como el *php-fpm* de *php*.

Dado que vamos a utilizarlo en todos nuestros sitios web Python, lo vamos a instalar de manera global:
~~~console
sdelquin@claseando:~$ sudo -H pip install uwsgi
[sudo] password for sdelquin:
Collecting uwsgi
Downloading https://files.pythonhosted.org/packages/a2/c9/a2d5737f63cd9df4317a4acc15d1ddf4952e28398601d8d7d706c16381e0/uwsgi-2.0.17.1.tar.gz (800kB)
100% |████████████████████████████████| 808kB 9.2MB/s
Building wheels for collected packages: uwsgi
Running setup.py bdist_wheel for uwsgi ... done
Stored in directory: /root/.cache/pip/wheels/32/d6/90/0239cc69219013d9f402b098b7c5ef7454792c21acd1d6c24e
Successfully built uwsgi
Installing collected packages: uwsgi
Successfully installed uwsgi-2.0.17.1
sdelquin@claseando:~$
~~~
## Creación del "Hola Mundo"
Lo primero será instalar un mini-framework de desarrollo web denominado `flask`:
~~~console
sdelquin@claseando:~/webapps/hellopython$ pipenv install flask
Installing flask…
Collecting flask
Downloading https://files.pythonhosted.org/packages/7f/e7/08578774ed4536d3242b14dacb4696386634607af824ea997202cd0edb4b/Flask-1.0.2-py2.py3-none-any.whl (91kB)
Collecting Jinja2>=2.10 (from flask)
Downloading https://files.pythonhosted.org/packages/7f/ff/ae64bacdfc95f27a016a7bed8e8686763ba4d277a78ca76f32659220a731/Jinja2-2.10-py2.py3-none-any.whl (126kB)
Collecting itsdangerous>=0.24 (from flask)
Downloading https://files.pythonhosted.org/packages/dc/b4/a60bcdba945c00f6d608d8975131ab3f25b22f2bcfe1dab221165194b2d4/itsdangerous-0.24.tar.gz (46kB)
Collecting Werkzeug>=0.14 (from flask)
Downloading https://files.pythonhosted.org/packages/20/c4/12e3e56473e52375aa29c4764e70d1b8f3efa6682bef8d0aae04fe335243/Werkzeug-0.14.1-py2.py3-none-any.whl (322kB)
Collecting click>=5.1 (from flask)
Downloading https://files.pythonhosted.org/packages/fa/37/45185cb5abbc30d7257104c434fe0b07e5a195a6847506c074527aa599ec/Click-7.0-py2.py3-none-any.whl (81kB)
Collecting MarkupSafe>=0.23 (from Jinja2>=2.10->flask)
Downloading https://files.pythonhosted.org/packages/4d/de/32d741db316d8fdb7680822dd37001ef7a448255de9699ab4bfcbdf4172b/MarkupSafe-1.0.tar.gz
Building wheels for collected packages: itsdangerous, MarkupSafe
Running setup.py bdist_wheel for itsdangerous: started
Running setup.py bdist_wheel for itsdangerous: finished with status 'done'
Stored in directory: /home/sdelquin/.cache/pipenv/wheels/2c/4a/61/5599631c1554768c6290b08c02c72d7317910374ca602ff1e5
Running setup.py bdist_wheel for MarkupSafe: started
Running setup.py bdist_wheel for MarkupSafe: finished with status 'done'
Stored in directory: /home/sdelquin/.cache/pipenv/wheels/33/56/20/ebe49a5c612fffe1c5a632146b16596f9e64676768661e4e46
Successfully built itsdangerous MarkupSafe
Installing collected packages: MarkupSafe, Jinja2, itsdangerous, Werkzeug, click, flask
Successfully installed Jinja2-2.10 MarkupSafe-1.0 Werkzeug-0.14.1 click-7.0 flask-1.0.2 itsdangerous-0.24
Adding flask to Pipfile's [packages]…
Pipfile.lock (662286) out of date, updating to (a65489)…
Locking [dev-packages] dependencies…
Locking [packages] dependencies…
Updated Pipfile.lock (662286)!
Installing dependencies from Pipfile.lock (662286)…
🐍 ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 6/6 — 00:00:05
To activate this project's virtualenv, run pipenv shell.
Alternatively, run a command inside the virtualenv with pipenv run.
sdelquin@claseando:~/webapps/hellopython$
~~~
A continuación creamos un pequeño fichero en *Python* que va a contener el código de la aplicación web:
~~~console
sdelquin@claseando:~/webapps/hellopython$ vi main.py
...
~~~
~~~python
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
~~~
En este punto podemos lanzar el proceso que escuchará peticiones:
~~~console
sdelquin@claseando:~/webapps/hellopython$ uwsgi --socket :8080 --protocol http --home $(pipenv --venv) -w main:app
*** Starting uWSGI 2.0.17.1 (64bit) on [Tue Oct 9 18:35:49 2018] ***
compiled with version: 7.3.0 on 09 October 2018 18:20:35
os: Linux-4.15.0-34-generic #37-Ubuntu SMP Mon Aug 27 15:21:48 UTC 2018
nodename: claseando
machine: x86_64
clock source: unix
detected number of CPU cores: 1
current working directory: /home/sdelquin/webapps/hellopython
detected binary path: /usr/local/bin/uwsgi
!!! no internal routing support, rebuild with pcre support !!!
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 3841
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uwsgi socket 0 bound to TCP address :8080 fd 3
Python version: 3.7.0 (default, Sep 12 2018, 18:30:08) [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]]
Set PythonHome to /home/sdelquin/.local/share/virtualenvs/hellopython-j3yclt1I
*** Python threads support is disabled. You can enable it with --enable-threads ***
Python main interpreter initialized at 0x5613675e6020
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 72904 bytes (71 KB) for 1 cores
*** Operational MODE: single process ***
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x5613675e6020 pid: 26417 (default app)
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI worker 1 (and the only) (pid: 26417, cores: 1)
~~~
Vamos a analizar cada uno de los parámetros utilizados:
- `--socket :8080`: estamos utilizando el puerto 8080.
- `--protocol=http`: estamos utilizando protocolo *http*.
- `--home $(pipenv --venv)`: estamos especificando a dónde debe ir a buscar el intérprete de Python para este entorno virtual.
- `-w main:app`: estamos indicando que dentro del fichero `main.py` debe ejecutar la aplicación Flask denominada `app`.
Si ahora accedemos con un navegador al puerto 8080 de nuestra máquina de producción, veremos lo siguiente:

> Para detener el proceso `uwsgi` basta con <kbd>CONTROL-C</kbd>.
## Configuración del servidor web
En primer lugar creamos un script que sintetize el largo comando utilizando anteriormente:
~~~console
sdelquin@claseando:~/webapps/hellopython$ vi run.sh
...
~~~
~~~console
#!/bin/bash
cd "$(dirname "$0")"
PYTHON_VENV=$(pipenv --venv)
uwsgi --socket :8080 --home $PYTHON_VENV -w main:app
~~~
> **OJO**: Hemos eliminado el flag `--protocol http` porque cuando usamos `uwsgi` junto a `Nginx` no tenemos que hablar directamente `http`.
Ahora le damos permisos de ejecución al script que hemos creado:
~~~console
sdelquin@claseando:~/webapps/hellopython$ chmod +x run.sh
sdelquin@claseando:~/webapps/hellopython$ ls -l run.sh
-rwxrwxr-x 1 sdelquin sdelquin 132 oct 9 18:42 run.sh
sdelquin@claseando:~/webapps/hellopython$
~~~
En este punto, podríamos lanzar el script `run.sh` sin tener que activar el entorno virtual previamente, ya que el propio script realiza esta tarea:
~~~console
sdelquin@claseando:~/webapps/hellopython$ ./run.sh
*** Starting uWSGI 2.0.17.1 (64bit) on [Tue Oct 9 18:43:05 2018] ***
compiled with version: 7.3.0 on 09 October 2018 18:20:35
os: Linux-4.15.0-34-generic #37-Ubuntu SMP Mon Aug 27 15:21:48 UTC 2018
nodename: claseando
machine: x86_64
clock source: unix
detected number of CPU cores: 1
current working directory: /home/sdelquin/webapps/hellopython
detected binary path: /usr/local/bin/uwsgi
...
~~~
> Para detener el script `run.sh` basta con <kbd>CONTROL-C</kbd>.
### `Nginx`
Vamos a crear un *virtual host* para nuestra aplicación *Python*. Queremos que responda a peticiones a la url `http://hellopython.vps.claseando.es`. Para ello haremos lo siguiente:
~~~console
sdelquin@claseando:~$ sudo vi /etc/nginx/sites-available/hellopython.vps.claseando.es
...
~~~
~~~nginx
server {
server_name hellopython.vps.claseando.es;
location / {
uwsgi_pass 127.0.0.1:8080; # puerto al que reenviamos las peticiones
include uwsgi_params;
}
location /static {
root /home/sdelquin/webapps/hellopython; # para servir ficheros estáticos
}
}
~~~
Enlazamos el *virtual host* para habilitarlo:
~~~console
sdelquin@claseando:~$ cd /etc/nginx/sites-enabled/
sdelquin@claseando:/etc/nginx/sites-enabled$ sudo ln -s ../sites-available/hellopython.vps.claseando.es
sdelquin@claseando:/etc/nginx/sites-enabled$ ls -l
total 0
lrwxrwxrwx 1 root root 47 oct 9 18:48 hellopython.vps.claseando.es -> ../sites-available/hellopython.vps.claseando.es
lrwxrwxrwx 1 root root 41 sep 16 15:32 hello.vps.claseando.es -> ../sites-available/hello.vps.claseando.es
lrwxrwxrwx 1 root root 41 sep 16 15:50 share.vps.claseando.es -> ../sites-available/share.vps.claseando.es
lrwxrwxrwx 1 root root 35 sep 16 15:35 vps.claseando.es -> ../sites-available/vps.claseando.es
sdelquin@claseando:/etc/nginx/sites-enabled$
~~~
Ahora recargamos el servidor web:
~~~console
sdelquin@claseando:~$ sudo systemctl reload nginx
sdelquin@claseando:~$
~~~
En este momento, las peticiones que lleguen a nuestro servidor *Nginx* en la url definida serán derivados a un servicio que debería estar escuchando en nuestra máquina en el puerto 8080. Si probamos a acceder en este momento a nuestro servidor web, nos aparece lo siguiente:

Se debe a que nos falta lanzar nuestra aplicación *uWSGI* para que escuche en el socket especificado y devuelva el sencillo *html* que hemos preparado en nuestra aplicación *python*:
~~~console
sdelquin@claseando:~$ webapps/hellopython/run.sh
*** Starting uWSGI 2.0.17.1 (64bit) on [Tue Oct 9 18:52:32 2018] ***
compiled with version: 7.3.0 on 09 October 2018 18:20:35
os: Linux-4.15.0-34-generic #37-Ubuntu SMP Mon Aug 27 15:21:48 UTC 2018
nodename: claseando
machine: x86_64
clock source: unix
detected number of CPU cores: 1
current working directory: /home/sdelquin/webapps/hellopython
detected binary path: /usr/local/bin/uwsgi
...
~~~
Sin parar de ejecutar el comando anterior, volvemos a probar el acceso a través del navegador, y obtenemos lo siguiente:

> Para detener el proceso `uwsgi` basta con <kbd>CONTROL-C</kbd>.
## Supervisor
Para mantener nuestra aplicación "viva" y poder gestionar su arranque/parada de manera sencilla, necesitamos un proceso coordinador. Para este cometido se ha desarrollado [supervisor](http://supervisord.org/).
### Instalación
~~~console
sdelquin@claseando:~$ sudo apt install -y supervisor
Leyendo lista de paquetes... Hecho
Creando árbol de dependencias
Leyendo la información de estado... Hecho
Los paquetes indicados a continuación se instalaron de forma automática y ya no son necesarios.
dh-python grub-pc-bin libpython3-dev libpython3.6-dev python-pip-whl python3-dev python3-keyring
python3-keyrings.alt python3-secretstorage python3-wheel python3-xdg python3.6-dev
Utilice «sudo apt autoremove» para eliminarlos.
Se instalarán los siguientes paquetes adicionales:
libpython-stdlib libpython2.7-minimal libpython2.7-stdlib python python-meld3 python-minimal
python-pkg-resources python2.7 python2.7-minimal
Paquetes sugeridos:
Desempaquetando python-pkg-resources (39.0.1-2) ...
Seleccionando el paquete python-meld3 previamente no seleccionado.
Preparando para desempaquetar .../python-meld3_1.0.2-2_all.deb ...
Desempaquetando python-meld3 (1.0.2-2) ...
Seleccionando el paquete supervisor previamente no seleccionado.
Preparando para desempaquetar .../supervisor_3.3.1-1.1_all.deb ...
Desempaquetando supervisor (3.3.1-1.1) ...
Procesando disparadores para mime-support (3.60ubuntu1) ...
Procesando disparadores para ureadahead (0.100.0-20) ...
Procesando disparadores para systemd (237-3ubuntu10.3) ...
Procesando disparadores para man-db (2.8.3-2) ...
Configurando libpython2.7-stdlib:amd64 (2.7.15~rc1-1) ...
Configurando python2.7 (2.7.15~rc1-1) ...
Configurando libpython-stdlib:amd64 (2.7.15~rc1-1) ...
Configurando python (2.7.15~rc1-1) ...
Configurando python-meld3 (1.0.2-2) ...
Configurando python-pkg-resources (39.0.1-2) ...
Configurando supervisor (3.3.1-1.1) ...
Created symlink /etc/systemd/system/multi-user.target.wants/supervisor.service → /lib/systemd/system/supervisor.service.
Procesando disparadores para ureadahead (0.100.0-20) ...
Procesando disparadores para systemd (237-3ubuntu10.3) ...
sdelquin@claseando:~$
~~~
Comprobamos que el servicio está correctamente instalado y funcionando:
~~~console
sdelquin@claseando:~$ sudo systemctl status supervisor
● supervisor.service - Supervisor process control system for UNIX
Loaded: loaded (/lib/systemd/system/supervisor.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2018-10-09 19:05:41 UTC; 31s ago
Docs: http://supervisord.org
Main PID: 27787 (supervisord)
Tasks: 1 (limit: 1152)
CGroup: /system.slice/supervisor.service
└─27787 /usr/bin/python /usr/bin/supervisord -n -c /etc/supervisor/supervisord.conf
oct 09 19:05:41 claseando systemd[1]: Started Supervisor process control system for UNIX.
oct 09 19:05:41 claseando supervisord[27787]: 2018-10-09 19:05:41,853 CRIT Supervisor running as root (no user
oct 09 19:05:41 claseando supervisord[27787]: 2018-10-09 19:05:41,859 WARN No file matches via include "/etc/s
oct 09 19:05:41 claseando supervisord[27787]: 2018-10-09 19:05:41,894 INFO RPC interface 'supervisor' initiali
oct 09 19:05:41 claseando supervisord[27787]: 2018-10-09 19:05:41,894 CRIT Server 'unix_http_server' running w
oct 09 19:05:41 claseando supervisord[27787]: 2018-10-09 19:05:41,894 INFO supervisord started with pid 27787
lines 1-15/15 (END)
~~~
## Configuración
Para que nuestro programa `hellopython` sea gestionado por *supervisor*, debemos añadir un fichero de configuración:
~~~console
sdelquin@claseando:~$ sudo vi /etc/supervisor/conf.d/hellopython.conf
...
~~~
~~~ini
[program:hellopython]
user = sdelquin
command = /home/sdelquin/webapps/hellopython/run.sh
autostart = true
autorestart = true
stopsignal = INT
killasgroup = true
stderr_logfile = /home/sdelquin/webapps/hellopython/hellopython.err.log
stdout_logfile = /home/sdelquin/webapps/hellopython/hellopython.out.log
~~~
### Permitir la gestión de procesos por usuarios no privilegiados
Nos puede interesar que los usuarios no privilegiados controlen sus propios procesos. Para controlar el arranque/parada/consulta de los procesos, existe una herramienta de *supervisor* llamada `supervisorctl`. Si un usuario no privilegiado intenta ejecutarla, pasa lo siguiente:
~~~console
sdelquin@claseando:~$ supervisorctl status
error: <class 'socket.error'>, [Errno 13] Permission denied: file: /usr/lib/python2.7/socket.py line: 228
sdelquin@claseando:~$
~~~
Esto es así porque el *socket* que usa *supervisord* para funcionar no permite su lectura a usuarios no privilegiados. Para solucionar esto debemos seguir varios pasos. La idea es crear un grupo `supervisor` en el que incluiremos a todos aquellos "desarrolladores":
~~~console
sdelquin@claseando:~$ sudo groupadd supervisor
sdelquin@claseando:~$
~~~
Ahora debemos modificar la configuración inicial de *supervisor*. Hacemos lo siguiente:
~~~console
sdelquin@claseando:~$ sudo vi /etc/supervisor/supervisord.conf
~~~
> Cambiar (y añadir) lo siguiente a partir de la línea 5:
~~~nginx
...
chmod=0770 ; socket file mode (default 0700)
chown=root:supervisor ; grupo 'supervisor' para usuarios no privilegiados
...
~~~
> **OJO**: Las líneas deben acabar con `;`. Tiene que haber al menos un espacio antes del punto y coma.
Reiniciamos el servicios para que surtan efectos los cambios realizados:
~~~console
sdelquin@claseando:~$ sudo systemctl restart supervisor
sdelquin@claseando:~$
~~~
Comprobamos que el servicio está funcionando con normalidad:
~~~console
sdelquin@claseando:~$ sudo systemctl status supervisor
● supervisor.service - Supervisor process control system for UNIX
Loaded: loaded (/lib/systemd/system/supervisor.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2018-10-09 19:11:13 UTC; 16s ago
Docs: http://supervisord.org
Process: 28119 ExecStop=/usr/bin/supervisorctl $OPTIONS shutdown (code=exited, status=0/SUCCESS)
Main PID: 28120 (supervisord)
Tasks: 1 (limit: 1152)
CGroup: /system.slice/supervisor.service
└─28120 /usr/bin/python /usr/bin/supervisord -n -c /etc/supervisor/supervisord.conf
~~~
> En el caso de que hubieran errores debemos mirar en los ficheros `/var/log/supervisor/supervisord.log` y `/var/log/syslog`.
A continuación tenemos que añadir al usuario de la aplicación (`sdelquin`) al grupo que hemos creado para supervisord (`supervisor`):
~~~console
sdelquin@claseando:~$ sudo usermod -a -G supervisor sdelquin
sdelquin@claseando:~$
~~~
> Para que el cambio de grupo sea efectivo, **HABRÁ QUE SALIR Y VOLVER A ENTRAR EN LA SESIÓN**.
Ahora, desde la *máquina de producción*, pero con un usuario no privilegiado, vemos que ya podemos hacer uso de la gestión de nuestros procesos:
~~~console
sdelquin@claseando:~$ supervisorctl status
hellopython RUNNING pid 28710, uptime 0:00:11
sdelquin@claseando:~$
~~~
En este punto, podemos comprobar que el acceso a la aplicación está funcionando:

## Control de la aplicación
~~~console
sdelquin@claseando:~$ supervisorctl status
hellopython RUNNING pid 28710, uptime 0:00:44
sdelquin@claseando:~$ supervisorctl stop hellopython
hellopython: stopped
sdelquin@claseando:~$ supervisorctl status
hellopython STOPPED Oct 09 07:20 PM
sdelquin@claseando:~$ supervisorctl start hellopython
hellopython: started
sdelquin@claseando:~$ supervisorctl restart hellopython
hellopython: stopped
hellopython: started
sdelquin@claseando:~$ supervisorctl status
hellopython RUNNING pid 28793, uptime 0:00:04
sdelquin@claseando:~$
~~~
Si accedemos al servidor y a la ruta especificada, tendremos disponible nuestra aplicación.
> NOTA: En el caso de que se añadan nuevos procesos que controlar con `supervisor`, tendremos que reiniciar el servicio, tras añadir la nueva configuración `/etc/supervisor/conf.d/<proceso>.conf`. Para ello necesitaremos permisos de superusuario.
> `$ systemctl restart supervisor`
|
package usermod_test
import (
"testing"
"github.com/chayim/usermod"
"github.com/stretchr/testify/assert"
)
var testPassword = []byte("iamapasword")
func (s *UserModTestSuite) newUser() *usermod.User {
u := usermod.NewUserWithDetails(s.db, "Chayim", "[email protected]", testPassword)
err := u.Insert()
assert.Nil(s.T(), err)
return u
}
func (s *UserModTestSuite) newActivatedUser() *usermod.User {
u := s.newUser()
usermod.Activate(s.db, u.ID.String())
return u
}
func (s *UserModTestSuite) TestUserCreateGetDelete() {
u := s.newUser()
dRes := u.DeleteByUID(u.ID.String())
assert.Nil(s.T(), dRes)
_, err := usermod.GetUserByID(s.db, u.ID.String())
assert.NotNil(s.T(), err)
u2 := s.newUser()
err = u2.SoftDeleteByUID(u2.ID.String())
assert.Nil(s.T(), err)
u3, err := usermod.GetUserByID(s.db, u2.ID.String())
assert.Nil(s.T(), err)
assert.Equal(s.T(), u3.ID, u2.ID)
assert.Equal(s.T(), u3.Name, u2.Name)
assert.Equal(s.T(), u3.Email, u2.Email)
assert.Equal(s.T(), u3.IsDeleted, true)
// now get by email
u4, err := usermod.GetUserByEmail(s.db, u2.Email)
assert.Nil(s.T(), err)
assert.Equal(s.T(), u4.ID, u2.ID)
assert.Equal(s.T(), u4.Name, u2.Name)
assert.Equal(s.T(), u4.Email, u2.Email)
}
func (s *UserModTestSuite) TestActivateUser() {
u := s.newUser()
assert.False(s.T(), u.IsActivated)
err := usermod.Activate(s.db, u.ID.String())
assert.Nil(s.T(), err)
found, err := usermod.GetUserByID(s.db, u.ID.String())
assert.Nil(s.T(), err)
assert.True(s.T(), found.IsActivated)
}
func (s *UserModTestSuite) TestUserCreateUpdateGet() {
u := s.newUser()
err := u.Update("", "[email protected]", "")
assert.Nil(s.T(), err)
u2, err := usermod.GetUserByID(s.db, u.ID.String())
assert.Nil(s.T(), err)
assert.Equal(s.T(), u2.Email, "[email protected]")
assert.Equal(s.T(), u2.Name, u.Name)
assert.Equal(s.T(), u2.PhoneNumber, u.PhoneNumber)
}
func (s *UserModTestSuite) TestUserChangePassword() {
u := s.newUser()
original := u.Password
err := u.ChangePassword([]byte("potatofurby"))
assert.Nil(s.T(), err)
found, err := usermod.GetUserByID(s.db, u.ID.String())
assert.Nil(s.T(), err)
assert.NotEqual(s.T(), string(original), string(found.Password))
}
func (s *UserModTestSuite) TestUserAuthenticationByUID() {
user := s.newActivatedUser()
tests := []struct {
name string
val string
password []byte
expected bool
}{{}, {
name: "ID auth should work",
val: user.ID.String(),
password: testPassword,
expected: true,
}, {
name: "Right ID, wrong password",
val: user.ID.String(),
password: []byte("notthepassword"),
expected: false,
}, {
name: "Invalid ID",
val: "just-a-bad-id",
password: testPassword,
expected: false,
}}
for _, tc := range tests {
s.T().Run(tc.name, func(t *testing.T) {
u, err := usermod.AuthenticateByUID(s.db, tc.val, tc.password)
if tc.expected {
assert.Nil(t, err)
assert.Equal(t, user.Email, u.Email)
} else {
assert.NotNil(t, err)
assert.Equal(t, "", u.Email)
}
})
}
}
func (s *UserModTestSuite) TestUserAuthenticationByEmail() {
user := s.newActivatedUser()
tests := []struct {
name string
val string
password []byte
expected bool
}{{
name: "Email auth should work",
val: user.Email,
password: testPassword,
expected: true,
}, {
name: "Right email, bad password",
val: user.Email,
password: []byte("notthepassword"),
expected: false,
}, {
name: "Invalid email",
val: "[email protected]",
password: testPassword,
expected: false,
}}
for _, tc := range tests {
s.T().Run(tc.name, func(t *testing.T) {
u, err := usermod.AuthenticateByEmail(s.db, tc.val, tc.password)
if tc.expected {
assert.Nil(t, err)
assert.Equal(t, user.Email, u.Email)
} else {
assert.NotNil(t, err)
assert.Equal(t, "", u.Email)
}
})
}
}
|
//@ts-check
import assert from "node:assert";
import { describe, it, before, after } from "node:test";
/** @typedef {import("./users/entities/Users").User} UserData */
const BASE_URL = "http://localhost:3000";
describe("/users", () => {
/** @type {import("node:http").Server} */
let _server;
before(async () => {
_server = (await import("./index.js")).app;
await new Promise((resolve) => _server.once("listening", resolve));
});
after(() => _server.close());
it("should create a user given valid data", async () => {
const data = {
id: "123",
username: "Eduardo",
password: "123456",
};
const request = await fetch(`${BASE_URL}/users`, {
method: "POST",
body: JSON.stringify(data),
});
/** @type {UserData} */
const result = await request.json();
const [salt, hash] = result.password.split(":");
assert.strictEqual(request.status, 201);
assert.notDeepStrictEqual(result, data);
assert.ok(salt);
assert.ok(hash);
assert.notStrictEqual(result.password, data.password);
});
it("should not create a user given username or password are empty", async () => {
const data = {
id: "123",
username: "",
password: "123456",
};
const request = await fetch(`${BASE_URL}/users`, {
method: "POST",
body: JSON.stringify(data),
});
const result = await request.json();
assert.strictEqual(request.status, 400);
assert.deepStrictEqual(result, {
error: "invalid username or password!",
});
const data2 = {
id: "123",
username: "Eduardo",
password: "",
};
const request2 = await fetch(`${BASE_URL}/users`, {
method: "POST",
body: JSON.stringify(data2),
});
const result2 = await request2.json();
assert.strictEqual(request2.status, 400);
assert.deepStrictEqual(result2, {
error: "invalid username or password!",
});
});
it("should not create a user that already exists", async () => {
const data = {
id: "123",
username: "Eduardo",
password: "123456",
};
const request = await fetch(`${BASE_URL}/users`, {
method: "POST",
body: JSON.stringify(data),
});
const result = await request.json();
assert.strictEqual(request.status, 400);
assert.deepStrictEqual(result, {
error: "user already exists!",
});
});
it("should return a list of users", async () => {
const request = await fetch(`${BASE_URL}/users`);
const result = await request.json();
assert.strictEqual(request.status, 200);
assert.notDeepStrictEqual(result, [
{ id: "123", username: "Eduardo", password: "123456" },
]);
assert.notDeepEqual(result[0].password, "123456");
});
it("should login given valid username and password", async () => {
const data = {
username: "Eduardo",
password: "123456",
};
const request = await fetch(`${BASE_URL}/users/login`, {
method: "POST",
body: JSON.stringify(data),
});
const result = await request.json();
assert.strictEqual(request.status, 200);
assert.deepStrictEqual(result, { message: "Welcome, Eduardo!" });
});
// todo
it.todo(
"should give a JWT access and refresh token to a authenticated user",
() => {}
);
it("should delete a user given valid id if user is authenticated", async () => {
const data = {
id: "123",
};
const request = await fetch(`${BASE_URL}/users`, {
method: "DELETE",
body: JSON.stringify(data),
});
const users = await (await fetch(`${BASE_URL}/users`)).json();
assert.strictEqual(request.status, 204);
assert.deepStrictEqual(users, []);
});
// todo
it.todo(
"should not delete a user if authenticated user is deleting itself",
async () => {
const data = {
id: "1234",
};
const request = await fetch(`${BASE_URL}/users`, {
method: "DELETE",
body: JSON.stringify(data),
});
const users = await (await fetch(`${BASE_URL}/users`)).json();
assert.strictEqual(request.status, 204);
assert.deepStrictEqual(users, []);
}
);
// todo
it.todo("should not delete a user given invalid id", async () => {
const data = {
id: "123",
};
const request = await fetch(`${BASE_URL}/users`, {
method: "DELETE",
body: JSON.stringify(data),
});
const users = await (await fetch(`${BASE_URL}/users`)).json();
assert.strictEqual(request.status, 204);
assert.deepStrictEqual(users, []);
});
});
|
defmodule Communicasts do
use Application
# See http://elixir-lang.org/docs/stable/elixir/Application.html
# for more information on OTP Applications
def start(_type, _args) do
import Supervisor.Spec
# Define workers and child supervisors to be supervised
children = [
# Start the Ecto repository
supervisor(Communicasts.Repo, []),
# Start the endpoint when the application starts
supervisor(Communicasts.Endpoint, []),
# Start your own worker by calling: Communicasts.Worker.start_link(arg1, arg2, arg3)
# worker(Communicasts.Worker, [arg1, arg2, arg3]),
]
# See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Communicasts.Supervisor]
Supervisor.start_link(children, opts)
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
def config_change(changed, _new, removed) do
Communicasts.Endpoint.config_change(changed, removed)
:ok
end
end
|
#pragma once
#include <SFML/Graphics.hpp>
#include <vector>
namespace owo
{
class GraphicElement
{
private:
std::vector<GraphicElement*> elements;
protected:
sf::Sprite sprite;
sf::RenderTexture renderTexture;
sf::IntRect dimensions, absDims, parentAbsDims;
sf::Color clearColor;
bool hovered;
bool clicked;
bool focused;
bool receiveEvents;
void calculateAbsDims()
{
this->absDims = sf::IntRect(
this->dimensions.left + this->parentAbsDims.left,
this->dimensions.top + this->parentAbsDims.top,
this->dimensions.width,
this->dimensions.height
);
}
public:
/**
* @brief Construct a new Graphic Element object
*/
GraphicElement()
{
this->clearColor = CONSTANT::COLOR_TRANS;
this->hovered = false;
this->clicked = false;
this->focused = false;
this->receiveEvents = false;
this->parentAbsDims = sf::IntRect(0, 0, CONSTANT::WINDOW_WIDTH, CONSTANT::WINDOW_HEIGHT);
this->calculateAbsDims();
}
/**
* @brief Set the Dimensions of the element
* @param x position in the x axis
* @param y position in the y axis
* @param width width of the element
* @param height height of the element
*/
void setDimensions(int x, int y, int width, int height)
{
this->dimensions = sf::IntRect(x, y, width, height);
this->calculateAbsDims();
this->propagateParentAbsPos();
this->renderTexture.create(this->dimensions.width, this->dimensions.height);
this->sprite.setPosition(this->dimensions.left, this->dimensions.top);
}
/**
* @brief Returns the list of child elements of this element
*/
std::vector<GraphicElement*> getElements()
{
return this->elements;
}
/**
* @brief Add a GraphicElement to the UI
* @param el The GraphicElement to add
*/
void addElement(GraphicElement* el)
{
this->elements.push_back(el);
}
/**
* @brief Remove a GraphicElement from the UI
* @param el The GraphicElement to remove
*/
void removeElement(GraphicElement* el)
{
int index = -1;
int counter = 0;
for(GraphicElement* element: this->elements)
{
if (element == el)
{
index = counter;
break;
}
counter++;
}
this->removeElement(index);
}
/**
* @brief Remove a GraphicElement from the UI
* @param index The index of the element to remove
*/
void removeElement(int index)
{
if (index >= this->elements.size() || index < 0)
return;
this->elements.erase(this->elements.begin()+index);
}
void clearElements()
{
if (this->elements.size() <= 0) return;
for(int i = this->elements.size()-1; i >= 0; i--)
this->removeElement(i);
}
/**
* @brief Returns the sprite correponding to the element's UI
* @return The Sprite correponding to the element's UI
*/
virtual sf::Sprite getSprite(float dt) = 0;
/**
* @brief OnHover event callback when mouse is hovering the object
* @param hovering the mouse is hovering or not the object
*/
virtual void onHover(bool hovered) = 0;
/**
* @brief OnFocus event callback when the element is in focus
* @param hovering Is the element focused or not
*/
virtual void onFocus(bool focused) = 0;
/**
* @brief OnClick event callback when mouse is pressed or released
* @param code The mouse button code
* @param pressed Is the mouse pressed or released
*/
virtual void onClick(int btn, bool clicked) = 0;
/**
* @brief OnKey event callback when a keyboard key is pressed or released
* @param code The pressed/released key code
* @param pressed Is the key pressed or released
*/
virtual void onKey(int key, char c, bool pressed) = 0;
/**
* @brief OnScroll event callback when a mouse scroll is made
* @param delta The amount of scroll
*/
virtual void onScroll(int delta) = 0;
/**
* @brief Updates the element's components
* @param dt Update delta time
* @param mousePos Current mouse position
*/
virtual void update(float dt, sf::Vector2i mousePos) = 0;
/**
* @brief Redraws the element's texture
*/
virtual void generateTexture() = 0;
/**
* @brief Returns if the position is in the element's hitbox
*
* @param pos Position to test
* @return If the position is in the element's hitbox
*/
bool collides(sf::Vector2i pos)
{
return this->absDims.contains(pos);
}
/**
* @brief Applies parent absolute position to all
* child GraphicElement of this element
*/
void propagateParentAbsPos()
{
for(GraphicElement* el: this->getElements())
el->setParentAboluteDimensions(this->absDims);
}
/**
* @brief Returns if the element is hovered or not
* @return Is the element hovered or not
*/
bool isHovered()
{
return this->hovered;
}
/**
* @brief Returns if the element is clicked or not
* @return Is the element clicked or not
*/
bool isClicked()
{
return this->clicked;
}
/**
* @brief Returns if the element is focused or not
* @return Is the element focused or not
*/
bool isFocused()
{
return this->focused;
}
bool doesReceiveEvents()
{
return this->receiveEvents;
}
void setClearColor(sf::Color color)
{
this->clearColor = color;
}
void setDimensions(sf::IntRect dims)
{
this->setDimensions(dims.left, dims.top, dims.width, dims.height);
}
void setPosition(sf::Vector2i pos)
{
this->setDimensions(pos.x, pos.y, this->dimensions.width, this->dimensions.height);
}
void setSize(sf::Vector2i size)
{
this->setDimensions(this->dimensions.left, this->dimensions.top, size.x, size.y);
}
void setReceiveEvents(bool state)
{
this->receiveEvents = state;
}
sf::Color getClearColor()
{
return this->clearColor;
}
sf::RenderTexture* getRenderTexture()
{
return &this->renderTexture;
}
sf::IntRect getDimensions()
{
return this->dimensions;
}
void setParentAboluteDimensions(sf::IntRect dims)
{
this->parentAbsDims = dims;
this->calculateAbsDims();
this->propagateParentAbsPos();
}
sf::IntRect getAbsoluteDimensions()
{
return this->absDims;
}
sf::Vector2i getPosition()
{
return sf::Vector2i(this->dimensions.left, this->dimensions.top);
}
sf::Vector2i getSize()
{
return sf::Vector2i(this->dimensions.width, this->dimensions.height);
}
virtual ~GraphicElement()
{
}
};
}
|
<template>
<BkPopover
placement="right-start"
:popover-delay="0"
theme="light">
<span class="spec-name">{{ data.name }}</span>
<template #content>
<div class="info-wrapper">
<strong class="info-name">{{ data.name }}</strong>
<div class="info">
<span class="info-title">CPU:</span>
<span class="info-value">({{ data.cpu.min }} ~ {{ data.cpu.max }}) {{ $t('核') }}</span>
</div>
<div class="info">
<span class="info-title">{{ $t('内存') }}:</span>
<span class="info-value">({{ data.mem.min }} ~ {{ data.mem.max }}) G</span>
</div>
<div
class="info"
style="align-items: start;">
<span class="info-title">{{ $t('磁盘') }}:</span>
<span class="info-value">
<DbOriginalTable
:border="['row', 'col', 'outer']"
class="custom-edit-table mt-8"
:columns="columns"
:data="data.storage_spec" />
</span>
</div>
</div>
</template>
</BkPopover>
</template>
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { type InstanceSpecInfo } from '@services/model/spider/tendbCluster';
interface Props {
data: InstanceSpecInfo
}
defineProps<Props>();
const { t } = useI18n();
const columns = [
{
field: 'mount_point',
label: t('挂载点'),
},
{
field: 'size',
label: t('最小容量G'),
},
{
field: 'type',
label: t('磁盘类型'),
},
];
</script>
<style lang="less" scoped>
.spec-name {
line-height: 18px;
border-bottom: 1px dashed #979797;
}
.info-wrapper {
width: 530px;
padding: 9px 2px;
font-size: 12px;
color: @default-color;
.info {
display: flex;
align-items: center;
line-height: 32px;
}
.info-name {
display: inline-block;
padding-bottom: 12px;
}
.info-title {
width: 60px;
text-align: right;
flex-shrink: 0;
}
.info-value {
color: @title-color;
}
}
</style>
|
// routes/highlightRoutes.js
const express = require('express');
// Import the Highlight model, assuming it's correctly defined in '../models/Highlight'
const Highlight = require('../models/Highlight');
const router = express.Router();
// Assuming mongoose is used in your Highlight model, no need to import it here unless directly used.
// Endpoint to save a new highlight
router.post('/highlights', async (req, res) => {
try {
// Create a new highlight document from the request body
const highlight = new Highlight(req.body);
// Save the highlight document to the database
const savedHighlight = await highlight.save();
// Respond with the saved document and HTTP status 201 (Created)
res.status(201).json(savedHighlight);
} catch (error) {
// If an error occurs, respond with HTTP status 400 (Bad Request) and the error message
res.status(400).json({ message: error.message });
}
});
// Endpoint to get highlights for a specific book
router.get('/highlights/:bookId', async (req, res) => {
try {
// Fetch highlights from the database that match the given bookId
const highlights = await Highlight.find({ bookId: req.params.bookId });
// Respond with the fetched highlights
res.json(highlights);
} catch (error) {
// If an error occurs, respond with HTTP status 500 (Internal Server Error) and the error message
res.status(500).json({ message: error.message });
}
});
// Export the router to be used in server.js or other parts of the application
module.exports = router;
|
<?php
namespace App\Jobs;
use App\Services\UserService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class HandleUserStatus implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $user, $type;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($type, $user)
{
$this->user = $user;
$this->type = $type;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
app(UserService::class)->updateAccountStatus($this->type, $this->user);
}
}
|
import { FC } from 'react'
import { useTranslation } from 'react-i18next'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import { CommentDto } from '../../services/comment-service'
import {
EditableText,
useEditableText
} from '../../shared/components/editable-text'
import {
useCommentDeleteMutation,
useCommentUpdateMutation
} from '../../query-hooks/comment-hooks'
import { UserIcon } from '../../shared/components/icons'
import { Popconfirm } from '../../shared/components/popconfirm'
import { deleteMutationOptions } from '../../shared/query-utils'
import { useUser } from '../../query-hooks/user-hooks'
dayjs.extend(relativeTime)
export interface CommentListItemProps {
comment: CommentDto
}
export const CommentListItem: FC<CommentListItemProps> = ({ comment }) => {
const { t } = useTranslation()
const userQuery = useUser()
const commentUpdateMutation = useCommentUpdateMutation()
const commentDeleteMutation = useCommentDeleteMutation()
const editableComment = useEditableText()
const enableActions = comment.memberCreator.id === userQuery.data?.id
return (
<div className="p-1 mb-3 flex flex-col">
<div className="my-2 flex items-center">
<div className="bg-gray-400 w-8 h-8 rounded-full mr-2 flex justify-center items-center">
{comment.memberCreator.avatarUrl ? (
<img
className="w-full h-full rounded-full"
src={comment.memberCreator.avatarUrl}
alt={comment.memberCreator.username}
/>
) : (
<UserIcon />
)}
</div>
<div className="flex items-center">
<h3 className="font-bold mr-2">
{comment.memberCreator?.username ?? '...'}
</h3>
<span className="text-gray-500 text-xs">
{dayjs(comment.date).fromNow()}
</span>
</div>
</div>
<EditableText
disabled={!enableActions}
as="textarea"
className="px-2 bg-white rounded"
controlledState={editableComment}
text={comment.data.text}
onChange={text =>
commentUpdateMutation.mutate({
text,
cardId: comment.data.card.id,
...comment
})
}
/>
{enableActions && (
<div className="flex my-2 items-baseline">
<span
className="cursor-pointer border-b border-gray-700 text-gray-700 text-xs"
onClick={event => {
event.preventDefault()
event.stopPropagation()
editableComment.setShowForm(v => !v)
}}
>
{editableComment.showForm ? t('commons.cancel') : t('commons.edit')}
</span>
<div className="mx-1">{'-'}</div>
<span className="cursor-pointer border-b border-gray-700 text-gray-700 text-xs">
<Popconfirm
title="comments.deleteCommentConfirm"
description="comments.deleteCommentPrompt"
okText="comments.deleteCommentConfirm"
onConfirm={() =>
commentDeleteMutation.mutate(comment, {
...deleteMutationOptions()
})
}
>
{t('commons.delete')}
</Popconfirm>
</span>
</div>
)}
</div>
)
}
|
import React, { useCallback } from 'react';
import { OrderCard, StopIcon, Order, ConfirmModal, OrderStatus, useOpen, OrderTimer, SelectOption } from 'phoqer';
import { useReduceAnimations } from 'phoqer-shared';
import { useTranslation } from 'react-i18next';
import { useErrorToast } from 'src/hook/error-toast.hook';
import { useNavigate } from 'src/hook/navigate.hook';
import { useSuccessToast } from 'src/hook/success-toast.hook';
import { CardActions } from 'src/pages/home/shared/card-actions';
import { ordersService } from 'src/services/orders.service';
import { ordersEvent } from 'src/utils/orders.utils';
interface Props {
order: Order;
}
export const InProgressOrdersItem = ({ order }: Props): JSX.Element => {
const { t, i18n } = useTranslation();
const errorToast = useErrorToast();
const successToast = useSuccessToast();
const { isReduceAnimations } = useReduceAnimations();
const navigate = useNavigate();
const { open, onOpen, onClose } = useOpen();
const handleUpdate = useCallback((): void => {
ordersService
.updateOrder([order.id], OrderStatus.DONE)
.then(ordersEvent.submit)
.then(() =>
successToast(t('You have successfully stopped the rent'), {
label: t('View orders'),
onClick: () => {
navigate('/author/orders', { state: { status: OrderStatus.DONE } });
},
}),
)
.then(onClose)
.catch(errorToast);
}, [errorToast, navigate, onClose, order.id, successToast, t]);
return (
<>
<ConfirmModal
open={open}
onClose={onClose}
onSubmit={handleUpdate}
confirmLabel={t('Confirm')}
cancelLabel={t('Cancel')}
>
{t('Are you sure you want to mark this rent as Done')}
</ConfirmModal>
<OrderCard
order={order}
locale={i18n.language}
options={
<>
<SelectOption onClick={onOpen}>
<StopIcon />
{t('Stop Rent')}
</SelectOption>
<CardActions order={order} />
</>
}
>
<OrderTimer
order={order}
label={t('time has passed')}
locale={i18n.language}
isReduceAnimations={isReduceAnimations}
/>
</OrderCard>
</>
);
};
|
require 'rails_helper'
RSpec.describe ApplicationController, type: :controller do
describe "#encode_user_data" do
context "when encoding is successful" do
it "returns an encoded token and creates a JwtToken" do
payload = { user_data: 1, exp: Time.now.to_i + 60 }
allow(JWT).to receive(:encode).with(payload, ENV["AUTHENTICATION_SECRET"], "HS256").and_return("encoded_token")
expect(JwtToken).to receive(:create).with(token: "encoded_token", exp_date: payload[:exp], user_id: payload[:user_data])
token = subject.encode_user_data(payload)
expect(token).to eq("encoded_token")
end
end
context "when encoding fails" do
it "logs the error and renders an error response" do
payload = { user_id: 1, exp: Time.now.to_i + 60 }
allow(JWT).to receive(:encode).and_raise(RuntimeError, "Encoding failed")
allow(Rails.logger).to receive(:error)
# Utiliza expect para capturar la excepción y manejarla en tu prueba
expect { subject.encode_user_data(payload) }.to raise_error(RuntimeError, "Encoding failed")
# No intentes acceder a response aquí, ya que la excepción se manejará antes de llegar a este punto
# No necesitas la siguiente línea:
# expect(response).to have_http_status(:unprocessable_entity)
end
end
end
describe "#decode_user_data" do
context "with a valid token" do
it "returns decoded user data" do
valid_token = JWT.encode({ user_id: 1, exp: Time.now.to_i + 60 }, ENV["AUTHENTICATION_SECRET"], "HS256")
decoded_data = subject.decode_user_data(valid_token)
expect(decoded_data[0]["user_id"]).to eq(1)
end
end
context "when token has expired" do
it "renders unauthorized status" do
expired_token = JWT.encode({ user_id: 1, exp: Time.now.to_i - 60 }, ENV["AUTHENTICATION_SECRET"], "HS256")
allow(Rails.logger).to receive(:error)
expect { subject.decode_user_data(expired_token) }.to raise_error(Exception)
end
end
context "when decoding fails for other reasons" do
it "renders unauthorized status" do
invalid_token = "invalid_token"
allow(Rails.logger).to receive(:error)
expect { subject.decode_user_data(invalid_token) }.to raise_error(Exception)
end
end
end
end
# describe "GET #index" do
# it "returns a successful response" do
# get :index
# expect(response).to be_successful
# end
# end
# describe "POST #create" do
# it "creates a new record" do
# post :create, params: { some_param: "some_value" }
# expect(response).to have_http_status(:redirect)
# # Otras expectativas y aserciones
# end
# end
# describe "DELETE #destroy" do
# it "destroys the record" do
# record = create(:record) # Ejemplo de creación de un registro de prueba con FactoryBot
# delete :destroy, params: { id: record.id }
# expect(response).to have_http_status(:redirect)
# # Otras expectativas y aserciones
# end
# end
|
<template>
<tr>
<td class="tw-p-2 tw-text-sm tw-font-medium tw-whitespace-nowrap">
<div class="tw-max-w-[25px]">
<div class="tw-inline-flex tw-items-center">
<label
class="tw-relative tw-flex tw-cursor-pointer tw-items-center tw-rounded-full tw-p-3"
for="checkbox"
data-ripple-dark="true"
>
<input
type="checkbox"
:checked="isSelected"
@change="handleSelected"
class="before:tw-content[''] tw-border-solid tw-bg-white tw-peer tw-relative tw-h-5 tw-w-5 tw-cursor-pointer tw-appearance-none tw-rounded-md tw-border tw-border-blue-gray-200 tw-transition-all before:tw-absolute before:tw-top-2/4 before:tw-left-2/4 before:tw-block before:tw-h-12 before:tw-w-12 before:-tw-translate-y-2/4 before:-tw-translate-x-2/4 before:tw-rounded-full before:bg-blue-gray-500 before:tw-opacity-0 before:tw-transition-opacity checked:tw-border-orange-500 checked:tw-bg-orange-500 checked:before:tw-bg-orange-500 hover:before:tw-opacity-10"
:id="'checkbox-' + item.id"
/>
<div
class="tw-pointer-events-none tw-absolute tw-top-2/4 tw-left-2/4 -tw-translate-y-2/4 -tw-translate-x-2/4 tw-text-white tw-opacity-0 tw-transition-opacity peer-checked:tw-opacity-100"
>
<svg
xmlns="http://www.w3.org/2000/svg"
class="tw-h-3.5 tw-w-3.5"
viewBox="0 0 20 20"
fill="currentColor"
stroke="currentColor"
stroke-width="1"
>
<path
fill-rule="evenodd"
d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
clip-rule="evenodd"
></path>
</svg>
</div>
</label>
</div>
</div>
</td>
<td
class="tw-px-4 tw-py-2 tw-text-sm tw-font-medium tw-whitespace-nowrap"
>
<div>
<h2 class="tw-font-medium tw-text-gray-800 darkx:tw-text-white">{{ item.id }}</h2>
</div>
</td>
<td
class="tw-px-4 tw-py-2 tw-text-sm tw-font-medium tw-whitespace-nowrap"
>
<div>
<h2 class="tw-font-medium tw-text-gray-800 darkx:tw-text-white tw-flex tw-items-center tw-gap-2">
<!-- {{ getDate(item.created_at) }} -->
<p>{{ moment(item.created_at).format("DD[/]MM[/]YY") }}</p>
<p v-if="false">{{ moment(item.created_at).format("HH[:]mm[:]ss") }}</p>
</h2>
</div>
</td>
<td
class="tw-px-4 tw-py-2 tw-text-sm tw-font-medium tw-whitespace-nowrap"
>
<div>
<h2 class="tw-font-medium tw-text-gray-800 darkx:tw-text-white tw-font-[cairo]">
{{ item.fullname }}
</h2>
</div>
</td>
<td
class="tw-px-4 tw-py-2 tw-text-sm tw-font-medium tw-whitespace-nowrap"
>
<div>
<h2 class="tw-font-medium tw-text-gray-800 darkx:tw-text-white tw-font-[cairo]">
{{ item.phone }}
</h2>
</div>
</td>
<td
class="tw-px-12 tw-py-2 tw-text-sm tw-font-medium tw-whitespace-nowrap"
>
<div>
<ul class="tw-space-y-1">
<li dir="rtl" class=" tw-font-[cairo] tw-flex tw-items-center tw-gap-1 " v-for="p in item.items" :key="p.id"> <span class="tw-font-bold tw-text-green-500">{{ p.quantity }} x </span> <span class="tw-block tw-max-w-[150px] tw-truncate">{{ p.product.name }}</span> <span class="tw-font-bold tw-text-orange-500 tw-bg-orange-100 tw-rounded-lg tw-px-2 tw-text-sm" v-if="!!p.product_variation.color && !['/', '-'].includes(p.product_variation.color)">{{ p.product_variation.color }}</span> <span class="tw-font-bold tw-text-orange-500 tw-bg-orange-100 tw-rounded-lg tw-px-2 tw-text-sm" v-if="!!p.product_variation.size && !['/', '-'].includes(p.product_variation.size)">{{ p.product_variation.size }}</span></li>
</ul>
</div>
</td>
<td
class="tw-px-12 tw-py-2 tw-text-sm tw-font-medium tw-whitespace-nowrap"
>
<span
:class="[confirmation.bgLight, confirmation.textLight]"
class="tw-text-xs tw-font-medium tw-mr-2 tw-px-2.5 tw-py-0.5 tw-rounded ">{{ (confirmation.name) }}</span>
</td>
<td
class="tw-px-12 tw-py-2 tw-text-sm tw-font-medium tw-whitespace-nowrap"
>
<span
:class="[deliveryState.bgLight, deliveryState.textLight]"
class="tw-text-xs tw-font-medium tw-mr-2 tw-px-2.5 tw-py-0.5 tw-rounded ">{{ (!deliveryState.value ? 'Not Selected' : deliveryState.name ) }}</span>
</td>
<td class="tw-px-4 tw-py-2 tw-text-sm tw-whitespace-nowrap">
<div>
<TableActions @update="newItem => $emit('update', newItem)" :item="item" />
</div>
</td>
</tr>
</template>
<script>
import moment from 'moment';
import { confirmations, deliveryStatus } from '@/config/orders';
import TableActions from '@/views/seller/partials/table/TableActions'
export default {
components: {TableActions},
props: {
item: {
required: true,
},
selected: {
required: true
},
},
data() {
return {
moment: moment
}
},
computed: {
confirmation() {
return confirmations.find(c => c.value == this.item.confirmation)
},
deliveryState() {
return deliveryStatus.find(v => v.value == this.item.delivery)
},
isSelected() {
return this.selected.includes(this.item.id)
}
},
methods: {
handleSelected(e) {
if(e.target.checked) {
const newSelected = [...this.selected];
newSelected.push(this.item.id);
this.$emit('update:selected', newSelected)
return false;
}
const newSelected = this.selected.filter(i => i!= this.item.id)
this.$emit('update:selected', newSelected)
}
}
};
</script>
<style>
</style>
|
# -*- coding:utf-8 -*-
"""
# SSIM loss
# https://github.com/Po-Hsun-Su/pytorch-ssim
使用新的 Tensor.requires_grad_() API 实现
"""
from math import exp
import torch
from torch import Tensor
import torch.nn.functional as F
class Window:
@staticmethod
def gaussian(window_size: int, sigma: float):
gauss = torch.Tensor([exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)])
return gauss / gauss.sum()
@classmethod
def create(cls, window_size: int, channel: int, sigma: float = 1.5):
_1D_window = cls.gaussian(window_size, sigma).unsqueeze(1)
_2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)
window = _2D_window.expand(channel, 1, window_size, window_size)\
.contiguous()\
.requires_grad_()
return window
class SSIMFunc:
def __init__(self, window_size: int, size_average: bool = True):
self.window_size = window_size
self.size_average = size_average
self._window = None
def __call__(self, image1: Tensor, image2: Tensor):
if len(image1.shape) != 4:
raise ValueError(f"Invalid Input Image({image1.shape}), 4 dimensions required.")
_, channel, _, _ = image1.shape
if self._window is None:
self._window = Window.create(self.window_size, channel)
self._window = self._window.to(image1.device)
mu1 = F.conv2d(image1, self._window, padding=self.window_size // 2, groups=channel)
mu2 = F.conv2d(image2, self._window, padding=self.window_size // 2, groups=channel)
mu1_sq = mu1.pow(2)
mu2_sq = mu2.pow(2)
mu1_mu2 = mu1 * mu2
sigma1_sq = F.conv2d(image1 * image1, self._window, padding=self.window_size // 2, groups=channel) - mu1_sq
sigma2_sq = F.conv2d(image2 * image2, self._window, padding=self.window_size // 2, groups=channel) - mu2_sq
sigma12 = F.conv2d(image1 * image2, self._window, padding=self.window_size // 2, groups=channel) - mu1_mu2
C1 = 0.01 ** 2
C2 = 0.03 ** 2
ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))
if self.size_average:
return ssim_map.mean()
else:
return ssim_map.mean(1).mean(1).mean(1)
class SSIMLoss(torch.nn.Module):
def __init__(self, window_size: int = 11, size_average: bool = True):
super().__init__()
self.window_size = window_size
self.size_average = size_average
self.ssim_fn = SSIMFunc(window_size, size_average)
def forward(self, image: Tensor, target: Tensor):
return 1 - self.ssim_fn(image, target)
if __name__ == '__main__':
from PIL import Image
from torchvision.transforms import ToPILImage, ToTensor
from torch.optim import Adam
import torch
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
to_tensor = ToTensor()
to_pil = ToPILImage()
ssim_fn = SSIMFunc(window_size=11)
with Image.open("./einstein.png") as image_pil:
target = to_tensor(image_pil).unsqueeze(0)
image = torch.rand(size=target.shape).requires_grad_()
print(image)
ssim_value = ssim_fn(image, target)
print(f"SSIM Value: {ssim_value}")
ssim_loss_fn = SSIMLoss()
optimizer = Adam([image], lr=0.01)
last_ssim = 0
while abs(ssim_value) < 0.98:
optimizer.zero_grad()
ssim_loss = ssim_loss_fn(image, target)
ssim_value = ssim_fn(image, target)
print(f"SSIM Value: {ssim_value}")
ssim_loss.backward()
optimizer.step()
if abs(ssim_value - last_ssim) > 0.02:
img_pil = to_pil(image.squeeze(0))
img_pil.show()
last_ssim = ssim_value
|
<script>
// IMPORTS
import { createEventDispatcher } from 'svelte';
import Textfield from './Textfield.svelte';
import Events from '../Utils/Events';
// PUBLIC ATTRIBUTES
export let value = "";
export let disable = false;
export let width = 290;
export let iconLeft = "";
export let iconRight = "";
export let label = "";
export let errorMessage = "";
export let required = false;
export let readonly = false;
export let filled = true;
export let style = "";
export let decimal = 2;
export let integer = 7;
export let min = null;
export let max = null;
// PRIVATE ATTRIBUTES
$: pattern = decimal > 0 ? "^" + (max != null & min < 0 ? "(-?)" : "") + "[0-9]{1," + integer + "}((\\\.|,)[0-9]{1," + decimal + "})?$" : "^(-?)[0-9]{1," + integer + "}$";
$: format = (min != null & min < 0 ? "-" : "") + "".padStart(integer, "X") + (decimal > 0 ? ".".padEnd(parseInt(decimal) + 1, "x") : "");
// EVENTS
const dispatch = createEventDispatcher();
function onChange(evt){
let event = evt.detail;
if(errorMessage == "" && value != ""){
if(min != null && max != null && (parseFloat(value.replace(",",".")) < parseFloat(min.replace(",",".")) || parseFloat(value.replace(",",".")) > parseFloat(max.replace(",",".")))){
errorMessage = "La donnée " + label + " doit etre comprise entre " + min + " et " + max;
} else if(min != null && parseFloat(value.replace(",",".")) < parseFloat(min.replace(",","."))) {
errorMessage = "La donnée " + label + " doit etre supérieure à " + min;
} else if(max != null && parseFloat(value.replace(",",".")) > parseFloat(max.replace(",","."))){
errorMessage = "La donnée " + label + " doit etre inférieure à " + max;
}
}
let params = Events.copy(event);
params.value = parseFloat(value.replace(",","."));
dispatch('change', {
...params
});
}
// METHODS
</script>
<Textfield
bind:value={value}
{disable}
{width}
{iconLeft}
{required}
{readonly}
{format}
type="number"
{pattern}
{iconRight}
{label}
{filled}
{style}
bind:errorMessage={errorMessage}
on:change={onChange}
on:blur
on:clickIcon
on:focus
on:focusout
on:input
on:keydown
on:keyup
/>
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* minirt.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsouhar <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/09/26 01:16:23 by aet-tass #+# #+# */
/* Updated: 2023/10/08 08:08:10 by bsouhar ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef MINIRT_H
# define MINIRT_H
# include "get_next_line/get_next_line.h"
# include "intersection/intersection.h"
# include "matrix/matrix.h"
# include "minirt.h"
# include "tuples/tuples.h"
# include "world/world.h"
# include <ctype.h>
# include <fcntl.h>
# include <limits.h>
# include <math.h>
# include <mlx.h>
# include <stdbool.h>
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <unistd.h>
# include "ray/ray.h"
# define SCREEN_HEIGHT 800
# define SCREEN_WIDTH 800
enum e_type
{
SPHERE,
PLANE,
CYLINDER,
CONE,
TRIANGLE,
};
typedef struct s_color
{
double red;
double green;
double blue;
int merged;
} t_color;
typedef struct s_camera_rt
{
t_point point_of_view;
t_vector vector;
double field_of_view;
} t_camera_rt;
typedef struct s_ambient
{
double ratio;
t_color color;
} t_ambient;
typedef struct s_mlx
{
void *mlx;
void *window;
void *image;
char *address;
int bits_per_pixel;
int size_line;
int endian;
} t_mlx;
typedef enum e_bool
{
FALSE,
TRUE
} t_bool;
typedef struct s_sphere
{
t_point origin;
float radius;
t_color color;
} t_sphere;
typedef struct s_cylinder
{
t_point origin;
t_vector normal;
float radius;
float height;
float minimum;
float maximum;
t_color color;
t_bool closed;
} t_cylinder;
typedef struct s_data
{
double det;
double f;
double u;
double v;
double t;
} t_triangle_data;
typedef struct s_triangle
{
t_point p1;
t_point p2;
t_point p3;
t_vector e1;
t_vector e2;
t_vector normal;
t_color color;
} t_triangle;
typedef struct s_cone
{
t_point origin;
t_vector normal;
float radius;
float height;
float minimum;
float maximum;
t_color color;
t_bool closed;
} t_cone;
typedef struct s_cone_data
{
double t;
double t1;
double t2;
double y1;
double y2;
} t_cone_data;
typedef struct s_plane
{
t_point origin;
t_vector normal;
t_color color;
} t_plane;
typedef struct s_material
{
t_color color;
t_color ambient;
float diffuse;
float specular;
float shininess;
} t_material;
typedef struct s_shape
{
enum e_type type;
t_sphere sphere;
t_plane plan;
t_cone cone;
t_triangle triangle;
t_cylinder cylinder;
t_matrix transform;
t_material material;
t_matrix transpose;
t_matrix inverse;
t_vector orientation;
} t_shape;
typedef struct s_light
{
t_point coord;
double brightness;
} t_light;
typedef struct s_light_point
{
t_point position;
t_color intensity;
double brightness;
} t_light_point;
typedef struct s_shearing
{
double xy;
double xz;
double yx;
double yz;
double zx;
double zy;
} t_shearing;
typedef struct s_lighting
{
t_light_point *light_point;
t_shape *shape;
t_vector eyev;
t_vector normalv;
t_point position;
t_point over_point;
t_material material;
double light_normal;
t_bool in_shadow;
} t_lighting;
typedef struct s_camera
{
double hsize;
double vsize;
double fov;
double half_width;
double half_height;
double pixel_size;
t_matrix transform;
t_matrix inverse;
} t_camera;
typedef struct s_minirt
{
t_ambient *ambient;
t_camera_rt *camera;
t_list *shapes;
t_list *lights;
} t_minirt;
void free_elements(char **elements);
t_bool compare_float(double a, double b);
t_tuple create_tuple(double x, double y, double z, double w);
t_tuple point(double x, double y, double z);
t_tuple vector(double x, double y, double z);
t_tuple tuple_add(t_tuple a, t_tuple b);
t_tuple tuple_subtract(t_tuple a, t_tuple b);
t_tuple tuple_negate(t_tuple t);
t_tuple tuple_multiply(t_tuple t, double scalar);
t_tuple tuple_divide(t_tuple t, double scalar);
t_tuple vector_cross(t_tuple a, t_tuple b);
double tuple_dot(t_tuple a, t_tuple b);
double tuple_magnitude(t_tuple t);
t_tuple tuple_normalize(t_tuple t);
t_bool compare_tuples(t_tuple a, t_tuple b);
t_matrix create_matrix(double values[MATRIX_SIZE][MATRIX_SIZE],
size_t size);
void print_matrix(t_matrix matrix);
t_matrix identity_matrix(void);
t_matrix matrix_multiply(t_matrix A, t_matrix B);
t_tuple multiply_tuple_matrix(t_matrix A, t_tuple b);
t_matrix transpose(t_matrix A);
double get_minor(t_matrix m, size_t row, size_t col);
double cofactor(t_matrix m, size_t row, size_t col);
double determinant(t_matrix t);
t_matrix get_submatrix(t_matrix matrix, size_t row, size_t column);
bool is_invertible(t_matrix t);
t_matrix inverse(t_matrix matrix);
t_matrix translation(double x, double y, double z);
t_matrix scaling(double x, double y, double z);
t_matrix rotation_x(double radians);
t_matrix rotation_y(double radians);
t_matrix rotation_z(double radians);
t_matrix shearing(t_shearing shear);
t_color create_parameter_color(char *elements);
t_ray ray(t_point origin, t_vector direction);
void create_vector_coordinates(char *line, t_vector *point);
double radians(double degree);
void set_shape_color_material(t_color color, t_shape *shape);
t_ray ray(t_point origin, t_vector direction);
t_ray transform_ray(t_ray ray, t_matrix matrix);
t_point position(t_ray ray, double time);
t_lighting lighting(t_lighting light_attr, t_computations comps,
t_list *light_list, t_world *world);
t_color shade_hit(t_world *world, t_computations comps,
t_list *light_list);
t_color color_at(t_world *world, t_ray ray);
t_ray set_ray(t_point origin, t_vector direction);
void set_transform(t_shape *shapes, t_matrix transform);
t_ray transform(t_ray ray, t_matrix matrix);
void create_point_coordinates(char *line, t_point *point);
t_material create_material(void);
int merge_colors(double r, double g, double b);
double normalize_color(double color);
t_color create_color(double r, double g, double b);
t_color set_color(double r, double g, double b);
t_color adding_color(t_color a, t_color b);
t_color sub_color(t_color a, t_color b);
t_color multiply_color_scalar(t_color c, double mult);
t_color multiply_color(t_color a, t_color b);
t_lighting init_lighting(void);
t_color phong_model(t_lighting phong_lighting);
t_bool get_shadowed(t_world *world, t_ray ray, double distance);
t_bool is_shadowed(t_world *world, t_point point,
t_light_point *light_p);
t_light_point *create_point_light(t_point position, t_color intensity);
int count_elements(char **elements);
t_world *create_world(void);
void intersect_world(t_world *world, t_ray ray,
t_intersections **intersect);
t_computations prepare_computation(t_intersection *i, t_ray ray);
t_bool is_shadowed(t_world *world, t_point p,
t_light_point *light_p);
t_world *launch_world(t_minirt *s);
t_vector reflect(t_vector in, t_vector normal);
void parse_camera(char **elements, t_minirt *s);
void parse_sphere(char **elements, t_minirt *s);
t_matrix rotation_matrix(t_vector orientation);
void *ft_calloc(size_t count, size_t size);
void parse_cone(char **elements, t_minirt *s);
void parse_light(char **elements, t_minirt *s);
void parse_plane(char **elements, t_minirt *s);
t_mlx create_window(int height, int width);
void write_pixel(t_mlx canvas, int x, int y, int color);
t_matrix view_transformation(t_point camera_position,
t_point look_at_point, t_vector up_direction);
void parse_cylinder(char **elements, t_minirt *s);
void ft_lstadd_front(t_list **lst, t_list *new);
char *ft_strjoin(char *s1, char *s2);
int ft_strcmp(const char *s1, const char *s2);
t_list *ft_lstnew(void *content);
t_list *ft_lstlast(t_list *lst);
void ft_lstadd_back(t_list **lst, t_list *new);
void ft_lstclear(t_list **lst, void (*del)(void *));
int read_rt_file(char *file, t_minirt *s);
void ft_bzero(void *s, size_t n);
void *ft_memset(void *str, int c, size_t len);
t_camera create_camera(double hsize, double vsize, double fov);
t_mlx render(t_camera camera, t_world *world);
t_camera launch_camera(t_minirt *s);
t_vector normal_at(t_shape *shape, t_point world_point);
double ft_atof(const char *str);
int ft_isdigit(char c);
void ft_putstr_fd(char *s, int fd);
char **ft_split(char const *s, char c);
char *ft_strtrim(char const *s1, char const *set);
char *ft_substr(char const *s, unsigned int start, size_t len);
t_shape *create_sphere(void);
char *get_next_line(int fd);
char *ft_substr(char const *s, unsigned int start, size_t len);
char *ft_strchr(const char *str, int c);
unsigned int ft_strlen(const char *str);
t_shape *create_shape(void);
t_shape *create_plane(void);
void intersect_plane(t_shape *plane, t_ray ray,
t_intersections **intersec);
t_vector normal_at_cylinder(t_shape *cylinder, t_tuple point);
void intesect_cylinder(t_shape *cylinder, t_ray _ray,
t_intersections **intersec);
t_shape *create_cylinder(void);
void intersect_cone(t_shape *cone, t_ray _ray,
t_intersections **intersec);
t_vector normal_at_cone(t_shape *cone, t_tuple point);
t_shape *create_cone(void);
void interset_cone_cap(t_shape *cone, t_ray ray,
t_intersections **intersec);
void intersect_triangle(t_shape *triangle, t_ray _ray,
t_intersections **intersec);
t_vector normal_at_triangle(t_shape *triangle, t_tuple point);
t_shape *create_triangle(void);
void parse_triangle(char **elements, t_minirt *rt);
void parse_ambient(char **elements, t_minirt *s);
void swap_double(double *a, double *b);
double check_cap(t_ray _ray, double t, double radius);
int ft_strncmp(const char *s1, const char *s2, size_t n);
void swap_double(double *a, double *b);
double check_cap(t_ray _ray, double t, double radius);
t_shape *create_cone(void);
void interset_cone_cap(t_shape *cone, t_ray ray,
t_intersections **intersec);
void intersect_cone_cap(t_shape *cone, t_ray _ray,
t_intersections **intersec, t_cone_data data);
int ft_close(t_mlx *mlx);
#endif
|
package org.trainopia.pms.features.project.dto;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import lombok.Getter;
import lombok.Setter;
import org.trainopia.pms.features.projectDetails.dto.ProjectDetailsDTO;
@Getter
@Setter
public class UpsertProjectDTO {
@NotBlank(message = "title shouldn't be empty")
private String title;
@Min(value = 1, message = "minAge must be greater than 1")
private int minAge;
@Min(value = 1, message = "maxAge must be greater than 1")
private int maxAge;
@Positive(message = "price must be positive number")
private double price;
@NotBlank(message = "location shouldn't be empty")
private String location;
@Valid
@NotNull
private ProjectDetailsDTO projectDetails;
public UpsertProjectDTO(
String title,
int minAge,
int maxAge,
double price,
String location,
ProjectDetailsDTO projectDetails) {
this.title = title;
this.minAge = minAge;
this.maxAge = maxAge;
this.price = price;
this.location = location;
this.projectDetails = projectDetails;
}
}
|
*** Settings ***
Resource resource.robot
Suite Setup Open And Configure Browser
Suite Teardown Close Browser
Test Setup Go To Register Page
*** Test Cases ***
Register With Valid Username And Password
Set Username jami
Set Password jami1234
Set Password Confirmation jami1234
Submit Registeration
Registration Should Succeed
Register With Too Short Username And Valid Password
Set Username ja
Set Password jami1234
Set Password Confirmation jami1234
Submit Registeration
Registration Should Fail With Message name must be atleast 3 chr
Register With Valid Username And Invalid Password
# salasana ei sisällä halutunlaisia merkkejä
Set Username jami
Set Password jamijami
Set Password Confirmation jamijami
Submit Registeration
Registration Should Fail With Message Insufficient password
Register With Nonmatching Password And Password Confirmation
Set Username jami
Set Password jami1234
Set Password Confirmation jami12345
Submit Registeration
Registration Should Fail With Message password and password confirmation do not match
Login After Successful Registration
Set Username jami
Set Password jami1234
Set Password Confirmation jami1234
Submit Registeration
Go To Login Page
Set Username jami
Set Password jami1234
Submit Credentials
Login Should Succeed
Login After Failed Registration
Set Username jamii
Set Password jami1234
Set Password Confirmation jami12345
Submit Registeration
Go To Login Page
Set Username jamii
Set Password jami1234
Submit Credentials
Login Should Fail With Message Invalid username or password
*** Keywords ***
Login Should Succeed
Main Page Should Be Open
Login Should Fail With Message
[Arguments] ${message}
Login Page Should Be Open
Page Should Contain ${message}
Submit Credentials
Click Button Login
Submit Registeration
Click Button Register
Set Username
[Arguments] ${username}
Input Text username ${username}
Set Password
[Arguments] ${password}
Input Password password ${password}
Set Password Confirmation
[Arguments] ${password_confirmation}
Input Password password_confirmation ${password_confirmation}
Registration Should Fail With Message
[Arguments] ${message}
Register Page Should Be Open
Page Should Contain ${message}
Registration Should Succeed
Welcome Page Should Be Open
Create User And Go To Register Page
Create User kalle kalle123
Go To Login Page
Login Page Should Be Open
|
package acme.features.auditor.auditRecord;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import acme.client.data.models.Dataset;
import acme.client.services.AbstractService;
import acme.entities.audits.AuditRecord;
import acme.entities.audits.CodeAudit;
import acme.roles.Auditor;
@Service
public class AuditorAuditRecordListService extends AbstractService<Auditor, AuditRecord> {
@Autowired
private AuditorAuditRecordRepository repository;
@Override
public void authorise() {
boolean status;
int id;
CodeAudit codeAudit;
id = super.getRequest().getData("codeAuditId", int.class);
codeAudit = this.repository.findOneCodeAuditById(id);
status = codeAudit != null && super.getRequest().getPrincipal().hasRole(codeAudit.getAuditor());
super.getResponse().setAuthorised(status);
}
@Override
public void load() {
Collection<AuditRecord> objects;
int id;
id = super.getRequest().getData("codeAuditId", int.class);
objects = this.repository.findAllAuditRecordByCodeAuditId(id);
super.getBuffer().addData(objects);
}
@Override
public void unbind(final AuditRecord object) {
assert object != null;
Dataset dataset;
String published = object.isPublished() ? "✔️" : "❌";
dataset = super.unbind(object, "code", "auditPeriodStart", "auditPeriodEnd", "mark");
dataset.put("isPublished", published);
super.getResponse().addData(dataset);
}
@Override
public void unbind(final Collection<AuditRecord> objects) {
assert objects != null;
int codeAuditId;
CodeAudit codeAudit;
final boolean showCreate;
codeAuditId = super.getRequest().getData("codeAuditId", int.class);
codeAudit = this.repository.findOneCodeAuditById(codeAuditId);
showCreate = !codeAudit.isPublished() && super.getRequest().getPrincipal().hasRole(codeAudit.getAuditor());
super.getResponse().addGlobal("codeAuditId", codeAuditId);
super.getResponse().addGlobal("showCreate", showCreate);
}
}
|
<!--The content below is only a placeholder and can be replaced.-->
<app-header></app-header>
<router-outlet></router-outlet>
<div class="appSummary">
<h3 class="app-summary">Expert in information technology and services industry with advanced skills expected in a {{jobPosition}}</h3>
</div>
<hr class="horLine">
<ul class="skilllist cf">
<h3 class="appSkill" #skilltitle>Skills:</h3>
<li class="skilllist cf" *ngFor='let skill of skills'>
{{skill.name}}
</li>
</ul>
<hr class="horLine">
<ul class="schoollist cf">
<h3 class="school-title" #schooltitle>Schools:</h3>
<li class="schoollist cf" *ngFor='let school of schools'>
<h3 class="school-name">{{school.name}}</h3>
<h4 class="school-name">{{school.major}}</h4>
</li>
</ul>
<div class="card search">
<h2 class="search-headlines">{{projectTitle}}</h2>
<label class="search-label">Please enter space bar to see the list of Project...Search
<span *ngIf="query"
[innerHTML]="' for: ' + query"></span></label>
<input class="search-input"
[(ngModel)]="query" placeholder="Enter Space Bar">
</div>
<ul class="projectlist cf" *ngIf="query">
<li class="projectlist-item cf"
(click)="showProject(item); query=''"
*ngFor="let item of (projects | search: query)">
<project-item class="content" [project]=item></project-item>
</li>
</ul>
<project-details *ngIf="currentProject" [project]="currentProject"></project-details>
<button [disabled]="buttonState">Project Definition</button>
<img [src]="logoUrl" *ngIf="toggbtnState">
<input type="text" (keyup.enter)="keyPress($event.target.value)">
<p>{{ typed }}</p>
|
from django.db.models import Sum
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema
from rest_framework import viewsets
from rest_framework.response import Response
from apps.deals.models import Deals
from apps.deals.serializers import DealsSerializer
@extend_schema(tags=["deals"])
class DealsViewSet(viewsets.GenericViewSet):
filter_backends = (DjangoFilterBackend,)
queryset = Deals.objects.all()
serializer_class = DealsSerializer
def list(self, request, *args, **kwargs):
queryset = self.get_queryset()
serializer = self.get_serializer(queryset, many=True)
return Response({"response": serializer.data})
def get_queryset(self):
queryset = super().get_queryset()
queryset = queryset.values('customer').annotate(spent_money=Sum('total')).order_by('-spent_money')[:5]
return queryset
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.