text
stringlengths
184
4.48M
import React, { ComponentProps, Fragment, useContext, useMemo } from "react"; import { CheckboxGroupLayout, Layout } from "../types"; import styled from "styled-components"; import FormContext from "../FormContext"; type FormData = string[]; export default function CheckboxGroup(props: { layout: CheckboxGroupLayout }) { const meta = props.layout.meta; const { data, update, showValidationErrors } = useContext(FormContext); const selected = data[meta.dataId] as FormData | undefined; function isChecked(dataId: string) { return selected?.includes(dataId); } function toggle(dataId: string) { const prev = selected || []; let newSelected; if (isChecked(dataId)) newSelected = prev.filter((id) => id !== dataId); else newSelected = prev.concat([dataId]); update(meta.dataId, newSelected); } const validationError = meta.required && showValidationErrors && !selected?.length; return ( <> {meta.label && <GroupLabel error={validationError}>{meta.label}</GroupLabel>} {validationError && <ErrorText>This field is required.</ErrorText>} {meta.options.map((option) => ( <Fragment key={option.dataId}> <SemanticCheckbox type="checkbox" id={option.dataId} name={option.dataId} onChange={() => toggle(option.dataId)} /> <Label htmlFor={option.dataId}> <CheckboxIcon checked={isChecked(option.dataId)} /> <div> <LabelText>{option.label}</LabelText> {option.description && <DescriptionText>{option.description}</DescriptionText>} </div> </Label> </Fragment> ))} </> ); } const GroupLabel = styled.label<{ error?: boolean }>` display: block; font-size: 16px; margin: 40px 0 5px; font-weight: 500; ${({ error }) => (error ? "color: red;" : "")} `; const SemanticCheckbox = styled.input` visibility: hidden; position: absolute; width: 0; height: 0; `; const Label = styled.label` display: flex; align-items: center; cursor: pointer; padding: 10px 0; `; const ErrorText = styled.p` margin-top: 8px; margin-bottom: 0; color: red; `; function CheckboxIcon(props: ComponentProps<"input">) { return <CheckboxWrapper>{props.checked ? <CheckboxChecked /> : <CheckboxUnchecked />}</CheckboxWrapper>; } const CheckboxWrapper = styled.div` margin-right: 10px; display: flex; `; const LabelText = styled.span` display: block; font-size: 16px; font-weight: normal; `; const DescriptionText = styled.span` display: block; font-size: 14px; color: #6f6f6f; `; function CheckboxChecked() { return ( <svg width="20" height="20" viewBox="0 0 72 72" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M64 0H8C3.56 0 0 3.6 0 8V64C0 68.4 3.56 72 8 72H64C68.44 72 72 68.4 72 64V8C72 3.6 68.44 0 64 0ZM28 56L8 36L13.64 30.36L28 44.68L58.36 14.32L64 20L28 56Z" fill="#E86C00" /> </svg> ); } function CheckboxUnchecked() { return ( <svg width="20" height="20" viewBox="0 0 72 72" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M64 8V64H8V8H64ZM64 0H8C3.6 0 0 3.6 0 8V64C0 68.4 3.6 72 8 72H64C68.4 72 72 68.4 72 64V8C72 3.6 68.4 0 64 0Z" fill="#6F6F6F" /> </svg> ); } export function isCheckboxGroupLayout(layout: Layout): layout is CheckboxGroupLayout { if (layout.type === "checkboxgroup") return true; return false; }
import "package:flutter/material.dart"; import "package:lottie/lottie.dart"; import "package:weather/design/atom/temperature.dart"; import "package:weather/utils/app_color.dart"; import "package:weather/utils/wmo_description.dart"; class HourCard extends StatelessWidget { const HourCard({ super.key, required this.temperature, required this.wmo, required this.hour, }); final double temperature; final int wmo; final String hour; @override Widget build(BuildContext context) { return IntrinsicWidth( child: Container( padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 24), decoration: BoxDecoration( color: AppColor.bluePastel.withOpacity(0.3), borderRadius: BorderRadius.circular(32)), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [ Temperature( temperature: temperature.ceil().toString(), fontSize: 22, unit: false, ), const SizedBox( height: 4, ), Container( width: 48, height: 48, decoration: BoxDecoration( boxShadow: [ BoxShadow( color: AppColor.brownDark.withOpacity(0.08), blurRadius: 24), ], ), child: Center( child: Lottie.asset(weatherLottie(wmo, true), animate: false), ), ), Text( "$hour:00", style: const TextStyle(fontSize: 12, color: AppColor.blueDark, fontWeight: FontWeight.bold), ) ]), ), ); } }
use Test::Spec; use constant A_TEST_WITH_FAILURES => 'data/t/failing.t'; use constant A_TEST_WITHOUT_FAILURES => 'data/t/succeeding.t'; use App::autotest; describe 'autotest' => sub { describe 'tells that things just got better' => sub { it 'if we go from red to green' => sub { my $autotest = App::autotest->new; $autotest->run_tests(A_TEST_WITH_FAILURES); $autotest->expects('print')->with("Things just got better.\n"); $autotest->run_tests(A_TEST_WITHOUT_FAILURES); ok 1; # expectation doesn't count as test }; }; describe 'will not tell that things just got better' => sub { it 'if we stay red' => sub { my $autotest = App::autotest->new; $autotest->run_tests(A_TEST_WITH_FAILURES); $autotest->expects('print')->never; $autotest->run_tests(A_TEST_WITH_FAILURES); ok 1; # expectation doesn't count as test }; it 'if we go from green to green' => sub { my $autotest = App::autotest->new; $autotest->run_tests(A_TEST_WITHOUT_FAILURES); $autotest->expects('print')->never; $autotest->run_tests(A_TEST_WITHOUT_FAILURES); ok 1; # expectation doesn't count as test }; it 'if we go from green to red' => sub { my $autotest = App::autotest->new; $autotest->run_tests(A_TEST_WITHOUT_FAILURES); $autotest->expects('print')->never; $autotest->run_tests(A_TEST_WITHOUT_FAILURES); ok 1; # expectation doesn't count as test }; }; }; runtests unless caller;
@extends('layouts.app') @section('title') Alta Menú @endsection @section('content') <section class="section"> <div class="section-header"> <h3 class="page__heading">Alta Menú</h3> </div> <div class="section-body"> <div class="row"> <div class="col-lg-12"> <div class="card"> <div class="card-body"> @if ($errors->any()) <div class="alert alert-dark alert-dismissible fade show" role="alert"> <strong>¡Revisa los campos!</strong> @foreach ($errors->all() as $error) <span class="badge badge-danger">{{ $error }}</span> @endforeach <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> @endif {!! Form::open(['route' => 'menu-items.store']) !!} <div class="row"> <div class="col-md-12 col-xl-12"> <div class="form-group"> {!! Form::label('name', 'Nombre') !!} {!! Form::text('name', null, ['class' => 'form-control']) !!} </div> </div> <div class="col-md-12 col-xl-12"> <div class="form-group"> {!! Form::label('description', 'Descripción') !!} {!! Form::text('description', null, ['class' => 'form-control']) !!} </div> </div> <div class="col-md-12 col-xl-12"> <div class="form-group"> {!! Form::label('price', 'Precio') !!} {!! Form::text('price', null, ['class' => 'form-control']) !!} </div> </div> <div class="col-md-12 col-xl-12"> <div class="form-group"> {!! Form::label('category_item_id', 'Categoría') !!} {!! Form::select('category_item_id', $categoryItems, null, ['class' => 'form-control']) !!} </div> </div> <div class="col-md-12 col-xl-12"> <div class="form-group"> {!! Form::label('business_id', 'Negocio') !!} {!! Form::select('business_id', $businesses, null, ['class' => 'form-control']) !!} </div> </div> <div class="col-md-12 col-xl-12"> {!! Form::submit('Guardar', ['class' => 'btn btn-primary']) !!} <a href="{{ route('menu-items.index') }}" class="btn btn-danger">Cancelar</a> </div> </div> {!! Form::close() !!} </div> </div> </div> </div> </div> </section> @endsection
<?php use Firebase\JWT\JWT; use Firebase\JWT\Key; if (Flight::get('IN_DEVELOPMENT')) { $requestHeaders = apache_request_headers(); $authHeader = $requestHeaders['Authorization'] ?? null; } else { $authHeader = $_SERVER["REDIRECT_HTTP_AUTHORIZATION"] ?? null; } $token = isset($authHeader) ? str_replace('Bearer ', '', $authHeader) : null; $secret = Flight::get('secretKey'); if ( (!isset(Flight::request()->data->first_name) || Flight::request()->data->first_name == "") || (!isset(Flight::request()->data->last_name) || Flight::request()->data->last_name == "") || (!isset(Flight::request()->data->user_name) || Flight::request()->data->user_name == "") || (!isset(Flight::request()->data->email) || Flight::request()->data->email == "") ) { Flight::response()->header("Content-Type", "application/json"); Flight::response()->status(400); Flight::response()->write(json_encode(array( 'status' => 400, 'message' => 'All fields are required: first_name, last_name, user_name, and email.' ))); Flight::response()->send(); } elseif (isset($token)) { try { // Verify the JWT $decodedToken = JWT::decode($token, new Key(Flight::get('secretKey'), 'HS256')); if (isset($decodedToken->exp) && ($decodedToken->exp > time())) { if (isset($decodedToken->user->username) && isset($decodedToken->user->signedIn) && $decodedToken->user->signedIn) { $db = Flight::db(); $get_user_statement = $db->prepare(" UPDATE USERS SET F_NAME = ?, L_NAME = ?, USERNAME = ?, EMAIL = ? WHERE USERS.USERNAME = ? " ); $get_user_statement->execute([ Flight::request()->data->first_name, Flight::request()->data->last_name, Flight::get('currentUser'), Flight::request()->data->email, Flight::get('currentUser') ]); Flight::response()->header("Content-Type", "application/json"); Flight::response()->status(200); echo Flight::json(array( "status" => 200, "message" => Flight::get('currentUser') . " updated" )); } else { Flight::response()->header("Content-Type", "application/json"); Flight::response()->status(401); Flight::response()->write(json_encode(array( "message" => "Please sign in." ) )); Flight::response()->send(); } } else { // Set the JWT $user = [ 'signedIn' => false, 'username' => "", 'permLevel' => "" ]; $payload = [ 'user' => $user, 'exp' => time(), // Token expiration time (45 min from now) ]; // Generate the JWT $jwt = JWT::encode($payload, Flight::get('secretKey'), 'HS256'); Flight::response()->header("Content-Type", "application/json"); Flight::response()->status(401); Flight::response()->write(json_encode(array( "token" => $jwt, "message" => "Your session expired. Please sign back in." ) )); Flight::response()->send(); } } catch (Exception $e) { Flight::response()->header("Content-Type", "application/json"); Flight::response()->status(401); Flight::response()->write(json_encode(array( "message" => "Please sign in." ) )); Flight::response()->send(); } $db = null; } else { Flight::response()->header("Content-Type", "application/json"); Flight::response()->status(401); Flight::response()->write(json_encode(array( "message" => "You are not authorized to view this content." ) )); Flight::response()->send(); } die();
function [out, groups] = deprecated_shuffle_within_condition(beh, spikes, groupby, varargin) % Circularly shuffles within times per some conditioned group % % % Uses: % (1) Sarel 2017 and Dotson 2021 each requires circular spike time shuffles % within trials. Doable by setting groupby to your relevent trial var name in % the behavior table. % % ------- % Inputs % ------- % % beh : table-type % This is a time length table, where columns are properties of the animal's % behavior % % spikes : struct % This is the spikes struct emitted by the units.getRate() method. It contains % all of the information that we will use about spiking % % % groupby : list[string] % This is a list of propertiees to shuffle within. We shuffle within the % logical and of unique elements of these properties. % % % --------- % Optionals % --------- % % Descriptions of the optional inputs can be found in the optional section % below. % % ------- % Outputs % ------- % % out : % % contains the ram or matfile based cache if those methods are seelceteed % % groups : % % the groups struct from util.findgroups(beh, props) % % ----- % Notes % ----- % % % This is an extremely flexible method that can be used for overall shuffles % or within property % % If you're using a shifts property in your shuffles, be aware that the set of % tables can be very large. 100 shuffles of just x/y/time data for all neurons % takes up 70GB on my machine. if you have those shuffles resampled for time-shifts % (not shuffle-time shifts, but time-shifts as in the dotson and yartsev paper), % then you will take up 1400GB of space. % % In order to scale to that level, there's an option for the atBehavior method % that allows returning the indices of the beh table to sample rather % than the actual behavior/time at those indices. This is a much more compressed % way of doing things. % % ,---. | o % | |,---.|--- .,---.,---. % | || || || || | % `---'|---'`---'``---'` ' % | ip = inputParser; ip.KeepUnmatched = true; % Any UNMATCHED go to the called method units.atBehavior.m % Usual params for that: % CHARACTERISTICS OF THE SHUFFLE ip.addParameter('shuffleCount', 100, @isnumeric); ip.addParameter('shuffleunits', 'unitwise'); % shuffle neurons so that {unitwise}|uniform ip.addParameter('shiftstatistic', 'uniform'); % what statistic of shift? {uniform}|normal ip.addParameter('width', 'whole'); % draw the 'whole' period of time, or some specified amount or standard deviation ip.addParameter('shiftWhat', 'behavior'); % It's equibalent to shift behavior times repeatedly per cell or spike times per cell, but my estimate is that it's less memory intense for behavior % SAVE space? ip.addParameter('throwOutNonGroup', false); ip.addParameter('preallocationSize', 100); % number of shuffles to run at a time ip.addParameter('props',[]); ip.addParameter('dropGroupby', true); ip.addParameter('cacheToDisk', {}); % if out to disk, this takes the parameters for coding.file.shufflefilename or coding.file.parquetfoldername ip.addParameter('cacheMethod', 'parquet'); ip.addParameter('groups', []); %ip.addParameter('lazy', false); % instead save the parameters needed to yield shuffles on the fly ip.parse(varargin{:}) Opt = ip.Results; Opt.shuffleunits = string(Opt.shuffleunits); Opt.shiftstatistic = char(Opt.shiftstatistic); kws_atBehavior = ip.Unmatched; if ~isempty(Opt.props) Opt.props = union("time", string(Opt.props)); Opt.props = union(groupby, string(Opt.props)); beh = beh(:, Opt.props); end % ,-.-. o % | | |,---..,---. % | | |,---||| | % ` ' '`---^`` ' %---------------------------------------- % Create set of shuffle times %---------------------------------------- % S x G x 1 if uniform or S x G x N if unit-based if isempty(Opt.groups) groups = util.table.findgroups(beh, groupby); else groups = Opt.groups; end if Opt.dropGroupby beh(:, groupby) = []; end checksum = all(ismember(unique(diff(groups.time.groups(groups.time.groups~=-1))), [0,1])); assert(checksum, 'Non-contiguous regions in your conditionals!') [measure] = measuretimeperiods(Opt); [shifts] = calculateshifts(measure, Opts); [out, outfolder] = prepareOuts(Opt); switch Opt.shiftWhat % ,---. | o % |---.,---.|---.,---.. ,.,---.,---. % | ||---'| |,---| \ / || || % `---'`---'` '`---^ `' ``---'` % | ,---.,---. o % ,---.|---.. .|__. |__. ,-.-.,---..,---. % `---.| || || | | | |,---||| | % `---'` '`---'` ` ` ' '`---^`` ' % case 'behavior' shuffle = behaviorbasedshuffle(shifts, spikes, beh, Opts); [shuffle, out] = concatonatelabelAndCache(shuffle, outfolder); beh.time = original_time; end case 'spikes' end if iscell(out.beh) && istable(out.beh{1}) out.beh = util.table.icat(out.beh); end function measuretimeperiods(beh, groups nG = groups.nGroups; measure = table(nan(nG,1), nan(nG,1), nan(nG,1), 'VariableNames', ["start","stop","len"]); for g = groups.uGroups' measure.start(g) = beh.time(find(groups.time.groups == g, 1, 'first')); measure.stop(g) = beh.time(find(groups.time.groups == g, 1, 'last')); end measure.len = measure.stop - measure.start; function [shifts] = calculateshifts(measure, Opts) % Calculate shifts if strcmp(Opt.shuffleunits, 'uniform') shifts = nan(Opt.shuffleCount, 1, groups.nGroups, 'single'); elseif strcmp(Opt.shuffleunits, 'unitwise') shifts = nan(Opt.shuffleCount, height(spikes.cellTable), groups.nGroups, 'single'); end nNeurons = height(spikes.cellTable); [S, N, G] = util.ndgrid.coord(shifts); if Opt.width == "whole" W = measure.len(G); else error("Not implemented") end switch Opt.shiftstatistic case 'uniform' shifts = W .* (rand(size(shifts)) - 0.5); case 'normal' shifts = W .* randn(size(shifts)); end function [out, outfolder] = prepareOuts(Opt) % SET UP OUTPUTS outfolder = char([]); if ~isempty(Opt.cacheToDisk) switch Opt.cacheToDisk case 'matfile' out = coding.file.shufflematfile(Opt.cacheToDisk{:}); case 'parquet' out = struct(); outfolder = coding.file.parquetfolder(Opt.cacheToDisk{:}); otherwise error("Bad method") end else out = struct(); end out.Groups = groups; out.shuffleCount = Opt.shuffleCount; out.nNeurons = nNeurons; out.nGroups = groups.nGroups; out.groupby = groupby; out.shifts = shifts; out.Opt = Opt; function behaviorbasedshuffle(shift, spikes, beh, Opt) beh = util.table.castefficient(beh, 'negativeNan', true); original_time = beh.time; Opt.preallocationSize = min(Opt.shuffleCount, Opt.preallocationSize); if ismember('shuffle', fieldnames(out)) util.matfile.rmsinglevar(out.Properties.Source, 'shuffle'); end count = 0; for s = progress(1:Opt.preallocationSize:Opt.shuffleCount,... 'Title', 'Shuffling behavior') endPoint = min(s+Opt.preallocationSize-1, Opt.shuffleCount); piece.shifts = shifts(s:endPoint,:,:); beh.time = original_time; %% ------------------------------------- %% %% THE MAGIC : where group-shuffle happens %% %% ------------------------------------- %% piece.newtimes = ... units.shuffle.helper.preallocateBehaviorShifts(piece.shifts,... beh, groups); %% ------------------------------------- %% %% ------------------------------------- %% clear shuffle % ------------------------------------ % QUERY shuffle times from neural data % ------------------------------------ SN = util.indicesMatrixForm([endPoint-s+1, nNeurons]); for sn = progress(SN', 'Title', 'Shifting cells') iShuff = sn(1); iNeuron = sn(2); beh.time = squeeze(piece.newtimes(iShuff, iNeuron, :)); tmp = ... units.atBehavior_singleCell(spikes.spikeTimes{iNeuron}, ... beh, kws_atBehavior); if iscell(tmp) shuffle(iShuff, iNeuron, :) = tmp; else shuffle{iShuff, iNeuron} = tmp; end end % ------------------------------------ function concatonatelabelAndCache() % ------------------------------------ % Concatonate and label and cache % ------------------------------------ shuffle = nd.dimLabel(shuffle, 1:2, ["shuffle","neuron"], ... {s:endPoint, 1:nNeurons}); shuffle = util.cell.icat(shuffle, 2); shuffle = shuffle{1}; if ~isempty(Opt.cacheToDisk) switch lower(char(Opt.cacheMethod)) case 'matfile' for shuff = progress(unique(shuffle.shuffle)',... 'Title', 'Storing shuffle') thing = table2struct(shuffle(shuffle.shuffle==shuff, :),... 'ToScalar', true); out.beh(shuff, 1) = thing; end case 'parquet' for shuff = progress(unique(shuffle.shuffle)',... 'Title', 'Storing shuffle') parquetwrite(outfolder, shuffle(shuffle.shuffle==shuff, :)); end out.beh = shuffle; end else out.beh = shuffle; end % ------------------------------------
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction import type { NextApiRequest, NextApiResponse } from "next"; import prepareConnection from "src/lib/db"; import { getCustomRepository } from "typeorm"; import { Friend, getFriendDate } from "src/interfaces/Friend"; import { SiegeRepository } from "src/repository/SiegeRepository"; import { PhaseRepository } from "src/repository/PhaseRepository"; import { getEquipments } from "pages/api/player/equipments/get"; import { UserRepository } from "src/repository/UserRepository"; import { readToken } from "src/lib/jwt"; import { selectHonored } from "pages/api/player/achievement/select"; type Data = { ranking?: Friend[]; damages?: number[]; groups?: number[]; message?: string; }; export default async function handler( req: NextApiRequest, res: NextApiResponse<Data> ) { await prepareConnection(); const userRepository = getCustomRepository(UserRepository); const token = req.cookies["token"]; const siegeRepository = getCustomRepository(SiegeRepository); const phaseRepository = getCustomRepository(PhaseRepository); try { const payload = readToken(token); const studentId = payload.studentId; const user = await userRepository.findOne( { studentId: studentId, }, { relations: ["player", "player.location"] } ); if (user === undefined) { throw new Error("해당 학번에 해당하는 유저가 없습니다."); } const phase = (await phaseRepository.findOneOrFail()).phase; const siegeRanking = await siegeRepository .createQueryBuilder() .where({ phase: phase }) .andWhere({ cell: user.player.location }) .orderBy("damage", "DESC") .getMany(); let playerRanking = []; let damages = []; let groups = []; for (let i = 0; i < Math.min(3, siegeRanking.length); i++) { const siege = await siegeRepository.findOne(siegeRanking[i].id, { relations: ["player", "player.location", "player.group", "player.honored"], }); if (siege === undefined) { throw new Error("no siege"); } if (siege.player.group.num === 0) { continue } playerRanking.push({ name: siege.player.name, honored: selectHonored(siege.player.honored.names,siege.player.honored.honoredInd), equipments: await getEquipments(siege.player.id), location: siege.player.location, recentAccessedAt: getFriendDate(siege.player.updatedAt), }); damages.push(siege.damage) groups.push(siege.player.group.num) } return res.status(200).json({ ranking: playerRanking, damages: damages, groups: groups }); } catch (err) { if (err instanceof Error) { return res.status(400).json({ message: err.message, }); } else { console.error(err); return res.status(500).json({ message: "알 수 없는 오류가 발생했습니다.", }); } } }
const User = require("../model/User"); const Business = require("../model/Business"); const crypto = require('crypto'); const jwt = require("jsonwebtoken"); const nodemailer = require("nodemailer"); const TOKEN_SECRET = process.env.TOKEN_SECRET; const bcrypt = require("bcrypt"); const cookieParser = require("cookie-parser"); const resetToken = process.env.reset_Token; // const passport = require('passport'); // const passportJwt = require('passport-jwt'); // const secret_key = crypto.randomBytes(32).toString('hex'); // console.log(secret_key); // // REGISTER const signUp = async (req, res) => { const { fullname, email, businessname, phonenumber, businessaddress, password, bvn } = req.body; try { const newUser = await User.findOne({ email }); const salt = await bcrypt.genSalt(10); const hashedPassword = await bcrypt.hash(req.body.password, salt); if (!newUser) { // User does not exist, create a new one const user = await User.create({ email, fullname, phonenumber, businessname, businessaddress, password: hashedPassword, bvn }); res.json({ msg: 'New User Created!!!' }); } else { // User already exists res.status(409).json({ msg: 'User Already Exists' }); } } catch (error) { console.error(error); res.status(500).json({ msg: 'Server Error' }); } }; // LOGIN const login = async (req, res) => { const { email, password } = req.body; try { const user = await User.findOne({ email }); if (!user) { return res.status(404).json("User not found"); } const validPassword = await bcrypt.compare(password, user.password); if (!validPassword) { return res.status(400).json("Wrong password"); } const token= jwt.sign({email,_id: user._id}, process.env.TOKEN_SECRET); res.send(token); } catch (err) { res.status(500).json(err); } }; // RESET PASSWORD const generateResetToken = () => { const resetToken = crypto.randomBytes(32).toString('hex'); // Generate a random token return resetToken; }; const resetPassword = async (req, res) => { const { email } = req.body; try { const user = await User.findOne({ email }); if (user) { // Generate a secure and unique reset token const resetToken = generateResetToken(); // Update the user document with the reset token and expiration date user.resetToken = resetToken; user.resetTokenExpiration = Date.now() + 3600000; // Token expires in 1 hour await user.save(); // Send an email with the reset link const resetLink = `http://localhost:8000/reset-password/${resetToken}`; // Use Nodemailer to send the reset email const transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: process.env.EMAIL_USERNAME, pass: process.env.EMAIL_PASSWORD } }); const mailOptions = { from: process.env.EMAIL_USERNAME, to: email, subject: 'Password Reset', text: `Click the following link to reset your password: ${resetLink}`, }; await transporter.sendMail(mailOptions); res.json({ msg: "Password reset instructions sent to your email." }); } else { res.status(404).json({ msg: "Email Not Registered" }); } } catch (error) { console.error(error); res.status(500).json({ msg: "Server Error" }); } }; // Update Paasword const updatePassword = async (req, res) => { const { newPassword } = req.body; const userId = req.user._id; try { const user = await User.findById(userId); if (!user) { return res.status(404).json({ msg: 'User not found' }); } // hashing password const hashedPassword = await bcrypt.hash(newPassword, 10); user.password = hashedPassword; await user.save(); res.json({ msg: 'Password updated successfully' }); } catch (error) { console.error(error); res.status(500).json({ msg: 'Server Error' }); } }; // LOGOUT const logoutMiddleware = (req, res, next) => { const token = req.header('auth-token'); if (!token) { return res.status(401).json({ message: "No token found" }); } // Clear the token by setting it to an empty string and expiring it res.cookie("token", " ", { expires: new Date(0) }); // Continue to the next middleware or route handler next(); }; const logOut = (req, res) => { const token = req.header('auth-token'); if (!token) { return res.status(401).json("No token found"); } res.cookie("token", " ", { expires: new Date(0) }).json({ message: "User successfully logged out" }); }; module.exports = { signUp, login, resetPassword, logoutMiddleware, logOut, updatePassword, }
import { shortenHashString } from "@/utils/age-restricted-example/short-hash-string"; import CopyToClipboard from "react-copy-to-clipboard"; import { DocumentDuplicateIcon } from "@heroicons/react/24/outline"; type StatProps = { stat: string; title: string; }; const Stat = (props: StatProps) => { return ( <div className="stat"> <div className="stat-figure text-secondary"> <CopyToClipboard text={props.stat}> <DocumentDuplicateIcon className="ml-1.5 text-xl font-normal h-5 w-5 text-slate-50 cursor-pointer" aria-hidden="true" /> </CopyToClipboard> </div> <div className="stat-title">{props.title}</div> <div className="stat-value text-base">{shortenHashString(props.stat)}</div> </div> ); }; export default Stat;
<nav class="navbar navbar-expand-md navbar-light bg-light"> <div class="container"> <a class="navbar-brand" routerLink="/">Socialbook</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" routerLink="/">Home</a> </li> <li *ngIf="(isLoggedIn | async) == true" class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" > Welcome {{ userData.user }} </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" [routerLink]="['/user/' + userData.user]"> Profile </a> <a class="dropdown-item" routerLink="/add">Create Post</a> <div class="dropdown-divider"></div> <button class="btn text-danger dropdown-item" (click)="logout()"> Logout </button> </div> </li> <li *ngIf="(isLoggedIn | async) == false" class="nav-item"> <a class="nav-link" routerLink="/login">Login</a> </li> <li class="nav-item" *ngIf="(isLoggedIn | async) == false"> <a class="nav-link" routerLink="/register">Signup</a> </li> </ul> <form class="d-flex"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search" /> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> </nav>
from typing import Any, Dict, List, Optional import asyncio from enum import Enum from llama_index.core import ( StorageContext, VectorStoreIndex, get_response_synthesizer, load_index_from_storage, ) from llama_index.core.base.response.schema import Response from llama_index.core.base.base_retriever import BaseRetriever, QueryType from llama_index.core.bridge.pydantic import BaseModel, Field from llama_index.core.embeddings import BaseEmbedding from llama_index.core.ingestion import run_transformations from llama_index.core.llama_pack.base import BaseLlamaPack from llama_index.core.llms.llm import LLM from llama_index.core.response_synthesizers import BaseSynthesizer from llama_index.core.schema import ( BaseNode, NodeWithScore, QueryBundle, TextNode, TransformComponent, ) from llama_index.core.vector_stores.types import ( MetadataFilter, MetadataFilters, VectorStore, ) from llama_index.packs.raptor.clustering import get_clusters DEFAULT_SUMMARY_PROMPT = ( "Summarize the provided text, including as many key details as needed." ) class QueryModes(str, Enum): """Query modes.""" tree_traversal = "tree_traversal" collapsed = "collapsed" class SummaryModule(BaseModel): response_synthesizer: BaseSynthesizer = Field(description="LLM") summary_prompt: str = Field( default=DEFAULT_SUMMARY_PROMPT, description="Summary prompt.", ) num_workers: int = Field( default=4, description="Number of workers to generate summaries." ) show_progress: bool = Field(default=True, description="Show progress.") class Config: arbitrary_types_allowed = True def __init__( self, llm: Optional[LLM] = None, summary_prompt: str = DEFAULT_SUMMARY_PROMPT, num_workers: int = 4, ) -> None: response_synthesizer = get_response_synthesizer( response_mode="tree_summarize", use_async=True, llm=llm ) super().__init__( response_synthesizer=response_synthesizer, summary_prompt=summary_prompt, num_workers=num_workers, ) async def generate_summaries( self, documents_per_cluster: List[List[BaseNode]] ) -> List[str]: """Generate summaries of documents per cluster. Args: documents_per_cluster (List[List[BaseNode]]): List of documents per cluster Returns: List[str]: List of summary for each cluster """ jobs = [] for documents in documents_per_cluster: with_scores = [NodeWithScore(node=doc, score=1.0) for doc in documents] jobs.append( self.response_synthesizer.asynthesize(self.summary_prompt, with_scores) ) lock = asyncio.Semaphore(self.num_workers) responses = [] # run the jobs while limiting the number of concurrent jobs to num_workers for job in jobs: async with lock: responses.append(await job) return [str(response) for response in responses] class RaptorRetriever(BaseRetriever): """Raptor indexing retriever.""" def __init__( self, documents: List[BaseNode], tree_depth: int = 3, similarity_top_k: int = 2, llm: Optional[LLM] = None, embed_model: Optional[BaseEmbedding] = None, vector_store: Optional[VectorStore] = None, transformations: Optional[List[TransformComponent]] = None, summary_module: Optional[SummaryModule] = None, existing_index: Optional[VectorStoreIndex] = None, mode: QueryModes = "collapsed", **kwargs: Any, ) -> None: """Init params.""" super().__init__( **kwargs, ) self.mode = mode self.summary_module = summary_module or SummaryModule(llm=llm) self.index = existing_index or VectorStoreIndex( nodes=[], storage_context=StorageContext.from_defaults(vector_store=vector_store), embed_model=embed_model, transformations=transformations, ) self.tree_depth = tree_depth self.similarity_top_k = similarity_top_k if len(documents) > 0: asyncio.run(self.insert(documents)) def _get_embeddings_per_level(self, level: int = 0) -> List[float]: """Retrieve embeddings per level in the abstraction tree. Args: level (int, optional): Target level. Defaults to 0 which stands for leaf nodes. Returns: List[float]: List of embeddings """ filters = MetadataFilters(filters=[MetadataFilter("level", level)]) # kind of janky, but should work with any vector index source_nodes = self.index.as_retriever( similarity_top_k=10000, filters=filters ).retrieve("retrieve") return [x.node for x in source_nodes] async def insert(self, documents: List[BaseNode]) -> None: """Given a set of documents, this function inserts higher level of abstractions within the index. For later retrieval Args: documents (List[BaseNode]): List of Documents """ embed_model = self.index._embed_model transformations = self.index._transformations cur_nodes = run_transformations(documents, transformations, in_place=False) for level in range(self.tree_depth): # get the embeddings for the current documents if self._verbose: print(f"Generating embeddings for level {level}.") embeddings = await embed_model.aget_text_embedding_batch( [node.get_content(metadata_mode="embed") for node in cur_nodes] ) assert len(embeddings) == len(cur_nodes) id_to_embedding = { node.id_: embedding for node, embedding in zip(cur_nodes, embeddings) } if self._verbose: print(f"Performing clustering for level {level}.") # cluster the documents nodes_per_cluster = get_clusters(cur_nodes, id_to_embedding) if self._verbose: print( f"Generating summaries for level {level} with {len(nodes_per_cluster)} clusters." ) summaries_per_cluster = await self.summary_module.generate_summaries( nodes_per_cluster ) if self._verbose: print( f"Level {level} created summaries/clusters: {len(nodes_per_cluster)}" ) # replace the current nodes with their summaries new_nodes = [ TextNode( text=summary, metadata={"level": level}, excluded_embed_metadata_keys=["level"], excluded_llm_metadata_keys=["level"], ) for summary in summaries_per_cluster ] # insert the nodes with their embeddings and parent_id nodes_with_embeddings = [] for cluster, summary_doc in zip(nodes_per_cluster, new_nodes): for node in cluster: node.metadata["parent_id"] = summary_doc.id_ node.excluded_embed_metadata_keys.append("parent_id") node.excluded_llm_metadata_keys.append("parent_id") node.embedding = id_to_embedding[node.id_] nodes_with_embeddings.append(node) self.index.insert_nodes(nodes_with_embeddings) # set the current nodes to the new nodes cur_nodes = new_nodes self.index.insert_nodes(cur_nodes) async def collapsed_retrieval(self, query_str: str) -> Response: """Query the index as a collapsed tree -- i.e. a single pool of nodes.""" return await self.index.as_retriever( similarity_top_k=self.similarity_top_k ).aretrieve(query_str) async def tree_traversal_retrieval(self, query_str: str) -> Response: """Query the index as a tree, traversing the tree from the top down.""" # get top k nodes for each level, starting with the top parent_ids = None nodes = [] level = self.tree_depth - 1 while level >= 0: # retrieve nodes at the current level if parent_ids is None: nodes = await self.index.as_retriever( similarity_top_k=self.similarity_top_k, filters=MetadataFilters( filters=[MetadataFilter(key="level", value=level)] ), ).aretrieve(query_str) parent_ids = [node.id_ for node in nodes] if self._verbose: print(f"Retrieved parent IDs from level {level}: {parent_ids!s}") # retrieve nodes that are children of the nodes at the previous level elif parent_ids is not None and len(parent_ids) > 0: nested_nodes = await asyncio.gather( *[ self.index.as_retriever( similarity_top_k=self.similarity_top_k, filters=MetadataFilters( filters=[MetadataFilter(key="parent_id", value=id_)] ), ).aretrieve(query_str) for id_ in parent_ids ] ) nodes = [node for nested in nested_nodes for node in nested] if self._verbose: print(f"Retrieved {len(nodes)} from parents at level {level}.") level -= 1 parent_ids = None return nodes def _retrieve(self, query_bundle: QueryBundle) -> List[NodeWithScore]: """Retrieve nodes given query and mode.""" # not used, needed for type checking def retrieve( self, query_str_or_bundle: QueryType, mode: Optional[QueryModes] = None ) -> List[NodeWithScore]: """Retrieve nodes given query and mode.""" if isinstance(query_str_or_bundle, QueryBundle): query_str = query_str_or_bundle.query_str else: query_str = query_str_or_bundle return asyncio.run(self.aretrieve(query_str, mode or self.mode)) async def aretrieve( self, query_str_or_bundle: QueryType, mode: Optional[QueryModes] = None ) -> List[NodeWithScore]: """Retrieve nodes given query and mode.""" if isinstance(query_str_or_bundle, QueryBundle): query_str = query_str_or_bundle.query_str else: query_str = query_str_or_bundle mode = mode or self.mode if mode == "tree_traversal": return await self.tree_traversal_retrieval(query_str) elif mode == "collapsed": return await self.collapsed_retrieval(query_str) else: raise ValueError(f"Invalid mode: {mode}") def persist(self, persist_dir: str) -> None: self.index.storage_context.persist(persist_dir=persist_dir) @classmethod def from_persist_dir( cls: "RaptorRetriever", persist_dir: str, embed_model: Optional[BaseEmbedding] = None, **kwargs: Any, ) -> "RaptorRetriever": storage_context = StorageContext.from_defaults(persist_dir=persist_dir) return cls( [], existing_index=load_index_from_storage( storage_context, embed_model=embed_model ), **kwargs, ) class RaptorPack(BaseLlamaPack): """Raptor pack.""" def __init__( self, documents: List[BaseNode], llm: Optional[LLM] = None, embed_model: Optional[BaseEmbedding] = None, vector_store: Optional[VectorStore] = None, similarity_top_k: int = 2, mode: QueryModes = "collapsed", verbose: bool = True, **kwargs: Any, ) -> None: """Init params.""" self.retriever = RaptorRetriever( documents, embed_model=embed_model, llm=llm, similarity_top_k=similarity_top_k, vector_store=vector_store, mode=mode, verbose=verbose, **kwargs, ) def get_modules(self) -> Dict[str, Any]: """Get modules.""" return { "retriever": self.retriever, } def run( self, query: str, mode: Optional[QueryModes] = None, ) -> Any: """Run the pipeline.""" return self.retriever.retrieve(query, mode=mode)
/* * Copyright (C) 2013 Near Infinity Corporation * * This file is part of Honeycomb Storage Engine. * * Honeycomb Storage Engine is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * Honeycomb Storage Engine is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Honeycomb Storage Engine. If not, see <http://www.gnu.org/licenses/>. */ #include "HoneycombHandler.h" #include "TableSchema.h" #include "ColumnSchema.h" #include "IndexSchema.h" #include "JNISetup.h" #include "Java.h" #include "Macros.h" #include "JavaFrame.h" #include "JNICache.h" #include <jni.h> /** * @brief Stop creation of table and return message to user. */ #define ABORT_CREATE(message) \ do { \ errno = ER_CANT_CREATE_TABLE; \ my_errno = errno; \ my_printf_error(ER_CANT_CREATE_TABLE, "Can't create table '%s'", MYF(0), message); \ DBUG_RETURN(HA_WRONG_CREATE_OPTION); \ } while(0) const int YEAR2_NOT_SUPPORTED = 0; const int ODD_TYPES_NOT_SUPPORTED = 1; const int UTF_REQUIRED = 2; const char* table_creation_errors[] = { "YEAR(2) is not supported.", "Bit, set and geometry are not supported.", "Required: character set utf8 collate utf8_bin" }; /** * @brief Called by MySQL during CREATE TABLE statements. Converts the table's * schema into a TableSchema object and hands it off to the HandlerProxy. * * @param path path to file MySQL assumes we will use. We use it to extract * the database/tablename. * @param table TABLE object associated with this thread and query. Holds most * of the information we need. See sql/table.h. * @param create_info contains info specified during table creation such as * initial auto_increment value. */ int HoneycombHandler::create(const char *path, TABLE *table, HA_CREATE_INFO *create_info) { const char* location = "HoneycombHandler::create"; DBUG_ENTER(location); attach_thread(jvm, &env, location); if(table->part_info != NULL) { ABORT_CREATE("Partitions are not supported."); } int ret = 0; { // Destruct frame before calling detach_thread JavaFrame frame(env, 3); TableSchema table_schema; ColumnSchema column_schema; IndexSchema index_schema; for (Field **field_ptr = table->field; *field_ptr; field_ptr++) { Field* field = *field_ptr; int error_number; if(!is_allowed_column(field, &error_number)) { ABORT_CREATE(table_creation_errors[error_number]); } column_schema.reset(); if (pack_column_schema(&column_schema, field)) { ABORT_CREATE("Error while creating column schema."); } table_schema.add_column(field->field_name, &column_schema); } for (uint i = 0; i < table->s->keys; i++) { if (pack_index_schema(&index_schema, &table->key_info[i])) { ABORT_CREATE("Error while creating index schema."); } table_schema.add_index(table->key_info[i].name, &index_schema); } jstring jtable_name = string_to_java_string(env, extract_table_name_from_path(path)); jlong jauto_inc_value = max(1, create_info->auto_increment_value); jbyteArray jserialized_schema = serialize_to_java(env, table_schema); this->env->CallVoidMethod(handler_proxy, cache->handler_proxy().create_table, jtable_name, jserialized_schema, jauto_inc_value); ret |= check_exceptions(env, cache, "HoneycombHandler::create_table"); } detach_thread(jvm); DBUG_RETURN(ret); } /** * Test if the column is valid in a Honeycomb table. */ bool HoneycombHandler::is_allowed_column(Field* field, int* error_number) { bool allowed = true; switch (field->real_type()) { case MYSQL_TYPE_YEAR: if (field->field_length == 2) { *error_number = YEAR2_NOT_SUPPORTED; allowed = false; } break; case MYSQL_TYPE_BIT: case MYSQL_TYPE_SET: case MYSQL_TYPE_GEOMETRY: *error_number = ODD_TYPES_NOT_SUPPORTED; allowed = false; break; case MYSQL_TYPE_STRING: case MYSQL_TYPE_VARCHAR: case MYSQL_TYPE_BLOB: if (strncmp(field->charset()->name, "utf8_bin", 8) != 0 && field->binary() == false) { *error_number = UTF_REQUIRED; allowed = false; } break; default: break; } return allowed; } /** * Add column to the column schema. * * @param schema The schema being filled out * @param field The column that is being added to the schema */ int HoneycombHandler::pack_column_schema(ColumnSchema* schema, Field* field) { int ret = 0; switch (field->real_type()) { case MYSQL_TYPE_TINY: case MYSQL_TYPE_SHORT: case MYSQL_TYPE_LONG: case MYSQL_TYPE_LONGLONG: case MYSQL_TYPE_INT24: case MYSQL_TYPE_YEAR: if (is_unsigned_field(field)) { ret |= schema->set_type(ColumnSchema::ULONG); } else { ret |= schema->set_type(ColumnSchema::LONG); } break; case MYSQL_TYPE_FLOAT: case MYSQL_TYPE_DOUBLE: ret |= schema->set_type(ColumnSchema::DOUBLE); break; case MYSQL_TYPE_DECIMAL: case MYSQL_TYPE_NEWDECIMAL: { uint precision = ((Field_new_decimal*) field)->precision; uint scale = ((Field_new_decimal*) field)->dec; ret |= schema->set_type(ColumnSchema::DECIMAL); ret |= schema->set_precision(precision); ret |= schema->set_scale(scale); } break; case MYSQL_TYPE_DATE: case MYSQL_TYPE_NEWDATE: ret |= schema->set_type(ColumnSchema::DATE); break; case MYSQL_TYPE_TIME: ret |= schema->set_type(ColumnSchema::TIME); break; case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_TIMESTAMP: ret |= schema->set_type(ColumnSchema::DATETIME); break; case MYSQL_TYPE_STRING: case MYSQL_TYPE_VARCHAR: { long long max_char_length = (long long) field->field_length; ret |= schema->set_max_length(max_char_length); if (field->binary()) { ret |= schema->set_type(ColumnSchema::BINARY); } else { ret |= schema->set_type(ColumnSchema::STRING); } } break; case MYSQL_TYPE_BLOB: case MYSQL_TYPE_TINY_BLOB: case MYSQL_TYPE_MEDIUM_BLOB: case MYSQL_TYPE_LONG_BLOB: ret |= schema->set_type(ColumnSchema::BINARY); break; case MYSQL_TYPE_ENUM: ret |= schema->set_type(ColumnSchema::ULONG); break; case MYSQL_TYPE_NULL: case MYSQL_TYPE_BIT: case MYSQL_TYPE_SET: case MYSQL_TYPE_GEOMETRY: case MYSQL_TYPE_VAR_STRING: default: break; } if (field->real_maybe_null()) { ret |= schema->set_is_nullable(true); } if(field->table->found_next_number_field != NULL && field == field->table->found_next_number_field) { ret |= schema->set_is_auto_increment(true); } return ret; }; /** * Add columns in the index to the index schema. * * @param schema The schema being filled out * @param key The index whose schema is being copied. */ int HoneycombHandler::pack_index_schema(IndexSchema* schema, KEY* key) { int ret = 0; ret |= schema->reset(); for (uint i = 0; i < key->key_parts; i++) { ret |= schema->add_column(key->key_part[i].field->field_name); } if (key->flags & HA_NOSAME) { ret |= schema->set_is_unique(true); } return ret; }; int HoneycombHandler::delete_table(const char *path) { const char* location = "HoneycombHandler::delete_table"; DBUG_ENTER(location); int ret = 0; attach_thread(jvm, &env, location); { // destruct frame before detaching JavaFrame frame(env, 2); jstring table_name = string_to_java_string(env, extract_table_name_from_path(path)); this->env->CallVoidMethod(handler_proxy, cache->handler_proxy().drop_table, table_name); ret |= check_exceptions(env, cache, location); } detach_thread(jvm); DBUG_RETURN(ret); } int HoneycombHandler::rename_table(const char *from, const char *to) { const char* location = "HoneycombHandler::rename_table"; DBUG_ENTER(location); int ret = 0; attach_thread(jvm, &env, location); { JavaFrame frame(env, 2); jstring old_table_name = string_to_java_string(env, extract_table_name_from_path(from)); jstring new_table_name = string_to_java_string(env, extract_table_name_from_path(to)); env->CallVoidMethod(handler_proxy, cache->handler_proxy().rename_table, old_table_name, new_table_name); ret |= check_exceptions(env, cache, location); } detach_thread(jvm); DBUG_RETURN(ret); } /** * Initialize table share to table located at path. This should only be used * when table share access is needed and the table share off of the * HoneycombHandler is uninitialized. The caller must clean up the returned * TABLE_SHARE by calling free_table_share(&table_share). * * @param table_share pointer to uninitialized table share * @param path path to table * @return error code */ int HoneycombHandler::init_table_share(TABLE_SHARE* table_share, const char* path) { THD* thd = ha_thd(); init_tmp_table_share(thd, table_share, "", 0, "", path); return open_table_def(thd, table_share, 0); } /** * Called during alter table statements by the optimizer. */ void HoneycombHandler::update_create_info(HA_CREATE_INFO* create_info) { const char* location = "HoneycombHandler::update_create_info"; DBUG_ENTER(location); //show create table if (!(create_info->used_fields & HA_CREATE_USED_AUTO)) { HoneycombHandler::info(HA_STATUS_AUTO); create_info->auto_increment_value = stats.auto_increment_value; } //alter table else if (create_info->used_fields == 1) { env->CallVoidMethod(handler_proxy, cache->handler_proxy().set_auto_increment, create_info->auto_increment_value); check_exceptions(env, cache, location); } DBUG_VOID_RETURN; } /** * Called by MySQL to determine if an alter table command requires a full table * rebuild. Return COMPATIBLE_DATA_NO to require a rebuild. */ bool HoneycombHandler::check_if_incompatible_data(HA_CREATE_INFO *create_info, uint table_changes) { // unclear what table_changes means. When in doubt, copy inno. if (table_changes != IS_EQUAL_YES) { return COMPATIBLE_DATA_NO; } // If a column is renamed we are forced to rebuild, because we are not given // enough information to simply rename the column (AFAIK we are not given the // new name). if (this->check_column_being_renamed(table)) { return COMPATIBLE_DATA_NO; } /* Check that row format didn't change */ if ((create_info->used_fields & HA_CREATE_USED_ROW_FORMAT) && create_info->row_type != ROW_TYPE_DEFAULT && create_info->row_type != get_row_type()) { return COMPATIBLE_DATA_NO; } return COMPATIBLE_DATA_YES; } /** * Check if a column is being renamed during an alter table operation */ bool HoneycombHandler::check_column_being_renamed(const TABLE* table) { const Field* field; for (uint i = 0; i < table->s->fields; i++) { field = table->field[i]; if (field->flags & FIELD_IS_RENAMED) { return true; } } return false; } int HoneycombHandler::add_index(TABLE *table_arg, KEY *key_info, uint num_of_keys, handler_add_index **add) { const char* location = "HoneycombHandler::add_index"; DBUG_ENTER(location); attach_thread(jvm, &env, location); int ret = 0; IndexSchema schema; for(uint k = 0; k < num_of_keys; k++) { JavaFrame frame(env, 2); KEY* key = key_info + k; jstring index_name = string_to_java_string(env, key->name); pack_index_schema(&schema, key); if (key->flags & HA_NOSAME) { // We don't support adding unique indices without a table rebuild DBUG_RETURN(HA_ERR_WRONG_COMMAND); } jbyteArray serialized_schema = serialize_to_java(env, schema); this->env->CallVoidMethod(handler_proxy, cache->handler_proxy().add_index, index_name, serialized_schema); ret |= check_exceptions(env, cache, location); } detach_thread(jvm); DBUG_RETURN(ret); } int HoneycombHandler::prepare_drop_index(TABLE *table, uint *key_num, uint num_of_keys) { const char* location = "HoneycombHandler::prepare_drop_index"; DBUG_ENTER(location); attach_thread(jvm, &env, location); int ret = 0; for (uint i = 0; i < num_of_keys; i++) { JavaFrame frame(env, 1); jstring index_name = string_to_java_string(env, (table->key_info + key_num[i])->name); this->env->CallVoidMethod(handler_proxy, cache->handler_proxy().drop_index, index_name); ret |= check_exceptions(env, cache, location); } detach_thread(jvm); DBUG_RETURN(ret); }
@extends('layout.mainlayout_admin') @section('content') <!-- Page Wrapper --> <div class="page-wrapper"> <div class="content container-fluid"> <!-- Page Header --> <div class="page-header"> <div class="row"> <div class="col"> <h3 class="page-title">Profile</h3> <ul class="breadcrumb"> <li class="breadcrumb-item"><a href="{{route('admin.dashboard')}}">Dashboard</a></li> <li class="breadcrumb-item"><a href="{{route('admin.doctors-list')}}">Doctors</a></li> <li class="breadcrumb-item active">Profile</li> </ul> </div> </div> </div> <!-- /Page Header --> <?php $name = \App\User::userNameFormat($user);$name = \App\User::userNameFormat($user); if (($profile->country ?? null) !== null and ($profile->city ?? null) !== null) { $location = $profile->city . ', ' . $profile->country; } else { $location = 'Not set'; } ?> <div class="row"> <div class="col-md-12"> <div class="profile-header"> <div class="row align-items-center"> <div class="col-auto profile-image"> <a href="#"> <img class="rounded-circle" alt="User Image" src="{{($profile->photo??false)?Storage::url($profile->photo):'/assets_admin/img/profiles/avatar-01.jpg'}}"> </a> </div> <div class="col ml-md-n2 profile-user-info"> <h4 class="user-name mb-0">{{$name}}</h4> <h6 class="text-muted">{{$user->email}}</h6> <form action="{{route('admin.seller-set')}}" method="Post"> @csrf <input type="hidden" name="id" value="{{$user->id}}"> <label> <input type="checkbox" name="seller" id="check-input-seller" @if($user->hasRole('Seller')){{'checked'}}@endif> Manager for Sales </label> </form> <script> document.getElementById('check-input-seller').onchange = (event) => { event.target.closest('form').submit() } </script> <div class="user-Location"><i class="fa fa-map-marker"></i> {{$location}}</div> <div class="about-text">{{$profile->biography??null}}</div> </div> </div> </div> <div class="profile-menu"> <ul class="nav nav-tabs nav-tabs-solid"> <li class="nav-item"> <a class="nav-link active" data-toggle="tab" href="#per_details_tab">About</a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#per_patients">Patients</a> </li> </ul> </div> <div class="tab-content profile-tab-cont"> <!-- Personal Details Tab --> <div class="tab-pane fade show active" id="per_details_tab"> <!-- Personal Details --> <div class="row"> <div class="col-lg-12"> <div class="card"> <div class="card-body"> <h5 class="card-title d-flex justify-content-between"> <span>Personal Details</span> <!-- <a class="edit-link" data-toggle="modal" href="#edit_personal_details"><i class="fa fa-edit mr-1"></i>Edit</a> --> </h5> <div class="row"> <p class="col-sm-2 text-muted text-sm-right mb-0 mb-sm-3">Name</p> <p class="col-sm-10">{{$name}}</p> </div> <div class="row"> <p class="col-sm-2 text-muted text-sm-right mb-0 mb-sm-3">Date of Birth</p> <p class="col-sm-10">{{$profile->birth??null}}</p> </div> <div class="row"> <p class="col-sm-2 text-muted text-sm-right mb-0 mb-sm-3">Email ID</p> <p class="col-sm-10">{{$user->email}}</p> </div> <div class="row"> <p class="col-sm-2 text-muted text-sm-right mb-0 mb-sm-3">Mobile</p> <p class="col-sm-10">{{$profile->phone??null}}</p> </div> <div class="row"> <p class="col-sm-2 text-muted text-sm-right mb-0">Address</p> <p class="col-sm-10 mb-0"> {{$profile->zip_code??null}}, {{$profile->address??null}} </p> </div> </div> </div> <!-- Edit Details Modal --> <div class="modal fade" id="edit_personal_details" aria-hidden="true" role="dialog"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Personal Details</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form> <div class="row form-row"> <div class="col-12 col-sm-6"> <div class="form-group"> <label>First Name</label> <input type="text" class="form-control" value="John"> </div> </div> <div class="col-12 col-sm-6"> <div class="form-group"> <label>Last Name</label> <input type="text" class="form-control" value="Doe"> </div> </div> <div class="col-12"> <div class="form-group"> <label>Date of Birth</label> <div class="cal-icon"> <input type="text" class="form-control" value="24-07-1983"> </div> </div> </div> <div class="col-12 col-sm-6"> <div class="form-group"> <label>Email ID</label> <input type="email" class="form-control" value="johndoe@example.com"> </div> </div> <div class="col-12 col-sm-6"> <div class="form-group"> <label>Mobile</label> <input type="text" value="+1 202-555-0125" class="form-control"> </div> </div> <div class="col-12"> <h5 class="form-title"><span>Address</span></h5> </div> <div class="col-12"> <div class="form-group"> <label>Address</label> <input type="text" class="form-control" value="4663 Agriculture Lane"> </div> </div> <div class="col-12 col-sm-6"> <div class="form-group"> <label>City</label> <input type="text" class="form-control" value="Miami"> </div> </div> <div class="col-12 col-sm-6"> <div class="form-group"> <label>State</label> <input type="text" class="form-control" value="Florida"> </div> </div> <div class="col-12 col-sm-6"> <div class="form-group"> <label>Zip Code</label> <input type="text" class="form-control" value="22434"> </div> </div> <div class="col-12 col-sm-6"> <div class="form-group"> <label>Country</label> <input type="text" class="form-control" value="United States"> </div> </div> </div> <button type="submit" class="btn btn-primary btn-block">Save Changes </button> </form> </div> </div> </div> </div> <!-- /Edit Details Modal --> </div> </div> <!-- /Personal Details --> </div> <!-- /Personal Details Tab --> <!-- Patients Tab --> <div class="tab-pane fade" id="per_patients"> <div class="row"> <div class="col-lg-12"> <div class="card"> <div class="card-body"> <form action="{{route('admin.doctor-add-patient')}}" method="Post" id="add-patient-to-doc"> @csrf <input type="hidden" name="id" value="{{$user->id}}"> <div class="input-group col-4"> <input type="text" class="form-control" name="patient_id" placeholder="Patient ID (P2, P12, etc.)" required> <div class="input-group-append"> <button type="submit" class="btn btn-primary">Add Patient </button> </div> </div> </form> </div> </div> </div> </div> <!-- Patients Details --> <div class="row"> <div class="col-lg-12"> <div class="card"> <div class="card-body"> <div class="table-responsive"> <table class="datatable table table-hover table-center mb-0"> <thead> <tr> <th>Patient ID</th> <th>Patient Name</th> <th>Member Since</th> </tr> </thead> <tbody> @foreach($patients??[] as $patient) <?php $patient = App\User::find($patient->user_id); $name = 'deleted'; unset($profile); if (($patient ?? null) !== null) { $profile = $patient->patientProfile()->first(); $name = \App\User::userNameFormat($patient); } ?> <tr> <td>P{{$patient->id??null}}</td> <td> <h2 class="table-avatar"> <a href="{{route('admin.patient-profile', ['id' => $patient->id??0])}}" class="avatar avatar-sm mr-2"><img class="avatar-img rounded-circle" src="{{($profile->photo??false)?Storage::url($profile->photo):'/assets_admin/img/doctors/doctor-thumb-01.jpg'}}" alt="User Image"></a> <a href="{{route('admin.patient-profile', ['id' => $patient->id??0])}}">{{$name}}</a> </h2> </td> <?php $date = date('j M Y', strtotime($patient->created_at ?? null)); $time = date('g:i a', strtotime($patient->created_at ?? null)); ?> <td>{{$date??null}} <br><small>{{$time??null}}</small></td> </tr> @endforeach </tbody> </table> </div> </div> </div> </div> <!-- /Patients Details --> </div> <!-- /Patients Tab --> </div> </div> </div> </div> </div> <!-- /Page Wrapper --> </div> <!-- /Main Wrapper --> @endsection
/* * MIT License * * Copyright (c) 2022-present Alan Yeh <alan@yeh.cn> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package central.sql; import central.sql.builder.*; import lombok.AllArgsConstructor; import lombok.Getter; /** * 数据库方言 * * @author Alan Yeh * @since 2022/08/03 */ @Getter @AllArgsConstructor public enum SqlDialect { /** * MySql */ MySql("MySql", new MySqlBuilder()), /** * Oracle */ Oracle("Oracle", new OracleBuilder()), /** * 达梦 */ Dameng("Dameng", new DamengBuilder()), /** * 人大金仓 */ Kingbase("Kingbase", new KingbaseBuilder()), /** * 神舟 */ Oscar("Oscar", new OscarBuilder()), /** * 翰高 */ HighGo("HighGo", new HighGoBuilder()), /** * H2 */ H2("H2", new H2Builder()), /** * PostgreSql */ PostgreSql("PostgreSql", new PostgreSqlBuilder()), /** * 海量数据 */ Vastbase("Vastbase", new VastbaseBuilder()), /** * 未知的数据 */ Unknown("Unknown", new UnknownBuilder()); private final String name; private final SqlBuilder builder; public static SqlDialect resolve(String jdbcUrl) { if (jdbcUrl == null) { return null; } if (jdbcUrl.startsWith("jdbc:mysql:")) { return MySql; } else if (jdbcUrl.startsWith("jdbc:oracle:")) { return Oracle; } else if (jdbcUrl.startsWith("jdbc:dm:")) { return Dameng; } else if (jdbcUrl.startsWith("jdbc:kingbase8:")) { return Kingbase; } else if (jdbcUrl.startsWith("jdbc:oscar:")) { return Oscar; } else if (jdbcUrl.startsWith("jdbc:highgo:")) { return HighGo; } else if (jdbcUrl.startsWith("jdbc:h2:")) { return H2; } else if (jdbcUrl.startsWith("jdbc:postgresql:")) { return PostgreSql; } else if (jdbcUrl.startsWith("jdbc:vastbase:")) { return Vastbase; } else { return Unknown; } } }
import React, { useState, useRef } from "react"; import { Plus as PlusIcon } from "@styled-icons/boxicons-regular/Plus"; import { Minus as MinusIcon } from "@styled-icons/evaicons-solid/Minus"; import "./bottom-menu.scss"; const Collapsible = (props) => { const [setActive, setActiveState] = useState(""); const [setHeight, setHeightState] = useState("0px"); const [setPlusIcon, setPlusIconState] = useState(""); const [setMinusIcon, setMinusIconState] = useState("none"); const accordion = useRef(null); function toggleAccordion() { setActiveState(setActive === "" ? "active" : ""); setHeightState( setActive === "active" ? "0px" : `${accordion.current.scrollHeight}px` ); setPlusIconState(setActive === "active" ? "" : "none"); setMinusIconState(setActive === "active" ? "none" : ""); } return ( <div className="bottomMenu"> <button type="button" className={`collapsible ${setActive}`} onClick={toggleAccordion} > <PlusIcon className="plus-icon" style={{ display: `${setPlusIcon}` }} /> <MinusIcon className="minus-icon" style={{ display: `${setMinusIcon}` }} /> {props.title} </button> <div ref={accordion} className="accordion_content" style={{ maxHeight: `${setHeight}` }} > <form> <ul style={{ listStyle: `none`, padding: "inherit" }}> <li> <input type="checkbox" name="cat1"></input> <label for="cat1">{props.cat1}</label> </li> <li> <input type="checkbox" name="cat2"></input> <label for="cat2">{props.cat2}</label> </li> <li> <input type="checkbox" name="cat3"></input> <label for="cat3">{props.cat3}</label> </li> <li> <input type="checkbox" name="cat4"></input> <label for="cat4">{props.cat4}</label> </li> </ul> </form> </div> </div> ); }; export default Collapsible;
package fr.uphf.a3ddy.service.model3d; import org.intellij.lang.annotations.Language; import org.rajawali3d.materials.Material; import org.rajawali3d.materials.shaders.FragmentShader; import org.rajawali3d.materials.shaders.VertexShader; public final class FadeMaterial extends Material { public static final String MVP_MATRIX = "uMVPMatrix"; public static final String POSITION = "vPosition"; public static final String TEXTURE_COORDINATE = "vTextureCoordinate"; public static final String NORMAL = "aNormal"; // Ajout de l'attribut normal // Ajout des uniforms pour les matrices et le temps public static final String NORMAL_MATRIX = "uNormalMatrix"; public static final String MODEL_MATRIX = "uModelMatrix"; public static final String MODEL_VIEW_MATRIX = "uModelViewMatrix"; public static final String TIME = "uTime"; private static final String VERTEX_SHADER = "" + "uniform mat4 " + MVP_MATRIX + ";\n" + "uniform mat4 " + NORMAL_MATRIX + ";\n" + "uniform mat4 " + MODEL_MATRIX + ";\n" + "uniform mat4 " + MODEL_VIEW_MATRIX + ";\n" + "uniform float " + TIME + ";\n" + "attribute vec4 " + POSITION + ";\n" + "attribute vec2 " + TEXTURE_COORDINATE + ";\n" + "attribute vec4 " + NORMAL + ";\n" + "varying vec2 vTextureCoord;\n" + "varying vec4 vColor;\n" + "\n" + "void main() {\n" + " gl_Position = " + MVP_MATRIX + " * " + POSITION + ";\n" + " vTextureCoord = " + TEXTURE_COORDINATE + ";\n" + " vColor = " + NORMAL + ";\n" + "}\n"; private static final String FRAGMENT_SHADER = "" + "precision mediump float;\n" + "varying vec2 vTextureCoord;\n" + "uniform sampler2D uTexture;\n" + "varying vec4 vColor;\n" + "\n" + "void main() {\n" + " vec4 textureColor = texture2D(uTexture, vTextureCoord);\n" + " gl_FragColor = textureColor * vColor;\n" + "}\n"; public FadeMaterial() { super(new VertexShader(VERTEX_SHADER), new FragmentShader(FRAGMENT_SHADER)); } }
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.dlc.v20210125.models; import com.tencentcloudapi.common.AbstractModel; import com.tencentcloudapi.common.SSEResponseModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class DescribeSparkAppTasksRequest extends AbstractModel { /** * Spark job ID */ @SerializedName("JobId") @Expose private String JobId; /** * Paginated query offset */ @SerializedName("Offset") @Expose private Long Offset; /** * Paginated query limit */ @SerializedName("Limit") @Expose private Long Limit; /** * Execution instance ID */ @SerializedName("TaskId") @Expose private String TaskId; /** * The update start time in the format of yyyy-MM-dd HH:mm:ss. */ @SerializedName("StartTime") @Expose private String StartTime; /** * The update end time in the format of yyyy-MM-dd HH:mm:ss. */ @SerializedName("EndTime") @Expose private String EndTime; /** * Filter by this parameter, which can be `task-state`. */ @SerializedName("Filters") @Expose private Filter [] Filters; /** * Get Spark job ID * @return JobId Spark job ID */ public String getJobId() { return this.JobId; } /** * Set Spark job ID * @param JobId Spark job ID */ public void setJobId(String JobId) { this.JobId = JobId; } /** * Get Paginated query offset * @return Offset Paginated query offset */ public Long getOffset() { return this.Offset; } /** * Set Paginated query offset * @param Offset Paginated query offset */ public void setOffset(Long Offset) { this.Offset = Offset; } /** * Get Paginated query limit * @return Limit Paginated query limit */ public Long getLimit() { return this.Limit; } /** * Set Paginated query limit * @param Limit Paginated query limit */ public void setLimit(Long Limit) { this.Limit = Limit; } /** * Get Execution instance ID * @return TaskId Execution instance ID */ public String getTaskId() { return this.TaskId; } /** * Set Execution instance ID * @param TaskId Execution instance ID */ public void setTaskId(String TaskId) { this.TaskId = TaskId; } /** * Get The update start time in the format of yyyy-MM-dd HH:mm:ss. * @return StartTime The update start time in the format of yyyy-MM-dd HH:mm:ss. */ public String getStartTime() { return this.StartTime; } /** * Set The update start time in the format of yyyy-MM-dd HH:mm:ss. * @param StartTime The update start time in the format of yyyy-MM-dd HH:mm:ss. */ public void setStartTime(String StartTime) { this.StartTime = StartTime; } /** * Get The update end time in the format of yyyy-MM-dd HH:mm:ss. * @return EndTime The update end time in the format of yyyy-MM-dd HH:mm:ss. */ public String getEndTime() { return this.EndTime; } /** * Set The update end time in the format of yyyy-MM-dd HH:mm:ss. * @param EndTime The update end time in the format of yyyy-MM-dd HH:mm:ss. */ public void setEndTime(String EndTime) { this.EndTime = EndTime; } /** * Get Filter by this parameter, which can be `task-state`. * @return Filters Filter by this parameter, which can be `task-state`. */ public Filter [] getFilters() { return this.Filters; } /** * Set Filter by this parameter, which can be `task-state`. * @param Filters Filter by this parameter, which can be `task-state`. */ public void setFilters(Filter [] Filters) { this.Filters = Filters; } public DescribeSparkAppTasksRequest() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public DescribeSparkAppTasksRequest(DescribeSparkAppTasksRequest source) { if (source.JobId != null) { this.JobId = new String(source.JobId); } if (source.Offset != null) { this.Offset = new Long(source.Offset); } if (source.Limit != null) { this.Limit = new Long(source.Limit); } if (source.TaskId != null) { this.TaskId = new String(source.TaskId); } if (source.StartTime != null) { this.StartTime = new String(source.StartTime); } if (source.EndTime != null) { this.EndTime = new String(source.EndTime); } if (source.Filters != null) { this.Filters = new Filter[source.Filters.length]; for (int i = 0; i < source.Filters.length; i++) { this.Filters[i] = new Filter(source.Filters[i]); } } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "JobId", this.JobId); this.setParamSimple(map, prefix + "Offset", this.Offset); this.setParamSimple(map, prefix + "Limit", this.Limit); this.setParamSimple(map, prefix + "TaskId", this.TaskId); this.setParamSimple(map, prefix + "StartTime", this.StartTime); this.setParamSimple(map, prefix + "EndTime", this.EndTime); this.setParamArrayObj(map, prefix + "Filters.", this.Filters); } }
const inputKeywoard = document.querySelector('#keywoard') const searchButton = document.querySelector('#search') const API_KEY = 'cf16fe3bca02efc84a2c2b0fee237e66' //Helper functions const formatData = async (data) => { const cityName = data.name const weather = data.weather[0].main const temperature = data.main.temp const feelsLike = data.main.feels_like return {cityName, weather, temperature, feelsLike} } const fetchData = async (keywoard) => { const endpoint = `https://api.openweathermap.org/data/2.5/weather?q=${keywoard}&units=metric&appid=${API_KEY}` try{ const response = await fetch(endpoint, {mode: 'cors'}) const data = await response.json() const formatedData = await formatData(data) return formatedData }catch(err){ console.log(err) return null } } const clearSearch = () => { inputKeywoard.value = '' } const getDateFormatted = () =>{ const day = new Date() const date = `${day.getDate()}-${day.getMonth() + 1}-${day.getFullYear()}` return date } const drawSearch = (inSearch) => { const search = document.createElement('div') search.classList.add('recent__search') const searchTitle = document.createElement('h3') searchTitle.classList.add('recent__search__title') searchTitle.textContent = inSearch.getName() const searchClose = document.createElement('i') searchClose.classList.add('fa-solid', 'fa-xmark' , 'recent__search__close') search.appendChild(searchTitle) search.appendChild(searchClose) return search } //Search button event searchButton.addEventListener('click', async (e) => { const keywoard = inputKeywoard.value if(Storage.alreadySerched(keywoard)){ if(Storage.getSearch(keywoard).getDay() !== getDateFormatted()){ try{ const data = new Search(await fetchData(keywoard),getDateFormatted()) Storage.updateSearch(keywoard, data) UI.displayWeather(data) clearSearch() }catch(err){ console.log(err) } }else{ UI.displayWeather(Storage.getSearch(keywoard)) clearSearch() } }else{ try{ const data = new Search(await fetchData(keywoard), getDateFormatted()) Storage.setSearch(data) UI.displaySearch(data) UI.newSearchDeleteEvent() UI.displayWeather(data) clearSearch() }catch(err){ console.log(err) } } }) // Search class definition class Search { data = null day = null constructor(data, day){ this.data = data this.day = day } getDay(){ return this.day } getName(){ return this.data.cityName } getWeather(){ return this.data.weather } getTemperature(){ return this.data.temperature } getFeelsLike(){ return this.data.feelsLike } getData(){ return this.data } updateSearch(search){ this.data = search.getData() this.day = search.getDay() } } //Recent searches class definition class RecentSearches { recentSearches = [] constructor(inSearches){ if(inSearches === undefined){ this.recentSearches = [] }else{ this.recentSearches = inSearches } } setSearches(data){ this.recentSearches = data } addSearch(inSearch){ if(!this.alreadySerched(inSearch.getName())){ if(this.recentSearches.length >= 6){ this.recentSearches.shift() this.recentSearches.push(inSearch) }else{ this.recentSearches.push(inSearch) } }else{ return null } } getRecentSearches(){ return this.recentSearches } alreadySerched(keywoard){ return this.recentSearches.some((search) => search.getName() === keywoard) } deleteSearch(keywoard){ this.recentSearches = this.recentSearches.filter((search) => search.getName() !== keywoard) } getSearch(keywoard){ return this.recentSearches.find((search) => search.getName() === keywoard) } } //Storage class definition class Storage{ static setSearches(searches){ localStorage.setItem('searches', JSON.stringify(searches)) } static getSearches(){ const searches = Object.assign(new RecentSearches,JSON.parse(localStorage.getItem('searches'))) searches.setSearches(searches.getRecentSearches().map((search) => Object.assign(new Search, search))) return searches } static setSearch(keywoard){ const searches = Storage.getSearches() searches.addSearch(keywoard) Storage.setSearches(searches) } static deleteSearch(keywoard){ const searches = Storage.getSearches() searches.deleteSearch(keywoard) Storage.setSearches(searches) } static alreadySerched(keywoard){ const searches = Storage.getSearches() return searches.alreadySerched(keywoard) } static getSearch(keywoard){ const searches = Storage.getSearches() return searches.getSearch(keywoard) } static updateSearch(keywoard, inSearche){ const searches = Storage.getSearches() searches.getSearch(keywoard).updateSearch(inSearche) Storage.setSearches(searches) } } //UI class definition class UI{ static initialize(){ UI.displaySearches() UI.deleteSearchEvent() UI.searchEvent() } static displayWeather(inSearch){ const possibleIcons = { 'Thunderstorm': 'fa-cloud-bolt', 'Drizzle': 'fa-cloud-drizzle', 'Rain': 'fa-cloud-rain', 'Snow': 'fa-cloud-snow', 'Atmosphere': 'fa-cloud-fog', 'Clear': 'fa-sun', 'Clouds': 'fa-cloud' } const weatherContainer = document.querySelector('#weather-container') const weeatherTitle = document.querySelector('#city-name') const weatherTemperature = document.querySelector('#temperature') const weatherFeelsLike = document.querySelector('#feels-like') const weatherIcon = document.querySelector('#weather-icon') const icon = document.createElement('i') icon.classList.add('fa-solid', possibleIcons[inSearch.getWeather()]) weeatherTitle.textContent = inSearch.getName() weatherTemperature.textContent = `${inSearch.getTemperature()}°C` weatherFeelsLike.textContent = `${inSearch.getFeelsLike()}°C` weatherIcon.innerHTML = '' weatherIcon.appendChild(icon) weatherContainer.classList.remove('hidden') } static displaySearches(){ const searchesContainer = document.querySelector('#recent-searches') searchesContainer.innerHTML = '' const searches = Storage.getSearches().getRecentSearches() searches.forEach((search) =>{ searchesContainer.appendChild(drawSearch(search)) }) } static displaySearch(search){ const searchesContainer = document.querySelector('#recent-searches') searchesContainer.appendChild(drawSearch(search)) } static deleteSearchEvent(){ const deleteSearches = document.querySelectorAll('.recent__search__close') deleteSearches.forEach((deleteSearch) => { deleteSearch.addEventListener('click', (e) =>{ const name = e.target.parentElement.firstChild.textContent Storage.deleteSearch(name) e.target.parentElement.remove() this.clearWeather() }) }) } static newSearchDeleteEvent(){ const deleteSearches = document.querySelectorAll('.recent__search__close') const newSearch = deleteSearches[deleteSearches.length - 1] newSearch.addEventListener('click', (e) =>{ const name = e.target.parentElement.firstChild.textContent Storage.deleteSearch(name) e.target.parentElement.remove() this.clearWeather() }) } static searchEvent(){ const searches = document.querySelectorAll('.recent__search') searches.forEach((search) => { search.addEventListener('click', async (e) =>{ const name = e.target.firstChild.textContent const data = Storage.getSearch(name) if(data.getDay() !== getDateFormatted()){ try{ const data = new Search(await fetchData(name),getDateFormatted()) Storage.updateSearch(name, data) UI.displayWeather(Storage.getSearch(name)) }catch(err){ console.log(err) } }else{ UI.displayWeather(data) } }) }) } static clearWeather(){ const weatherContainer = document.querySelector('#weather-container') weatherContainer.classList.add('hidden') } } //UI initialization UI.initialize()
%-------------------------------------------------- % DOCUMENT IMPORTS %-------------------------------------------------- \documentclass{beamer} \usetheme{CambridgeUS} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage[french]{babel} \usepackage{graphicx} \usepackage{xcolor} \usepackage{tikz} \usepackage{tkz-graph} \usepackage{amsmath, amssymb, mathtools, amsthm} \usepackage{tikz-uml} %----------------------------------------------- % DOCUMENT CONFIG %----------------------------------------------- \graphicspath{ {figures/} } \useinnertheme{rectangles} \setbeamertemplate{blocks}[default] \usefonttheme[onlymath]{serif} % Tikz \tikzstyle{vertex}=[circle, draw, inner sep=2pt, minimum size=8pt, thick] \newcommand{\vertex}{\node[vertex]} \usetikzlibrary{arrows,petri,topaths,calc} % Commands \newcommand{\yy}[1]{\colorbox{yellow!70}{#1}} \newcommand{\bb}[1]{\colorbox{blue!30}{#1}} \newcommand{\rr}[1]{\colorbox{red!30}{#1}} \newcommand{\gr}[1]{\colorbox{green!30}{#1}} \title[Pas de jaloux]{Pas de jaloux, un jeu de partage équitable} \author[Bontems, Mottola, Thirunavukarasu]{Alexandre Bontems \and Gualtiero Mottola \and Hans Thirunavukarasu} \institute[]{Faculté des Sciences, Sorbonne Université\\Université Pierre et Marie Curie} \date{5 juin 2018} \setcounter{tocdepth}{1} \AtBeginSection[] { \begin{frame} \frametitle{Table des matières} \tableofcontents[currentsection] \end{frame} } \begin{document} \frame{\maketitle} \section{Introduction} \begin{frame} \frametitle{Présentation du problème LEF} \begin{center} Agents : $\{a_1, a_2, a_3, a_4\}$\\ Objets : $\{o_1, o_2, o_3, o_4\}$ \end{center} \begin{columns} \begin{column}{.49\textwidth} \begin{center} \begin{tikzpicture} % Agents \vertex (a1) at (0,0) {$a_1$}; \vertex (a2) at (1.5,0) {$a_2$}; \vertex (a3) at (3,0) {$a_3$}; \vertex (a4) at (4.5,0) {$a_4$}; % Prefs \node (a1o1) at (0,2.2) {$o_2$}; \node (a1o2) at (0,1.7) {$o_4$}; \node (a1o3) at (0,1.2) {$o_1$}; \uncover<2->{\node (a1o3) at (0,1.2) {\yy{$o_1$}};} \node (a1o4) at (0,0.7) {$o_3$}; \node (a2o1) at (1.5,2.2) {$o_3$}; \uncover<2->{\node (a2o1) at (1.5,2.2) {\yy{$o_3$}};} \node (a2o2) at (1.5,1.7) {$o_4$}; \node (a2o3) at (1.5,1.2) {$o_2$}; \node (a2o4) at (1.5,0.7) {$o_1$}; \node (a3o1) at (3.0,2.2) {$o_2$}; \uncover<2->{\node (a3o1) at (3.0,2.2) {\yy{$o_2$}};} \node (a3o2) at (3.0,1.7) {$o_1$}; \node (a3o3) at (3.0,1.2) {$o_4$}; \node (a3o4) at (3.0,0.7) {$o_3$}; \node (a4o1) at (4.5,2.2) {$o_3$}; \node (a4o2) at (4.5,1.7) {$o_4$}; \uncover<2->{\node (a4o2) at (4.5,1.7) {\yy{$o_4$}};} \node (a4o3) at (4.5,1.2) {$o_2$}; \node (a4o4) at (4.5,0.7) {$o_1$}; \path (a1) edge[thick] (a2) (a2) edge[thick] (a3) (a3) edge[thick] (a4) ; \end{tikzpicture} \end{center} \end{column}~ \begin{column}{.49\textwidth} \begin{itemize} \item Agents liés dans un réseau \item Un objet par agent \item Préférences distinctes \item Problème de satisfaction NP-complet \end{itemize} \end{column} \end{columns} \end{frame} \begin{frame} \frametitle{Objectifs} \begin{center} Développement d'un jeu puzzle basé sur le problème et offrant une progression de difficulté.\\[0.5cm] \end{center} \begin{columns} \centering \begin{column}{.49\textwidth} \uncover<2->{ \begin{block}{Exigences} \begin{itemize} \item Produire un jeu, \item Obtenir des niveaux possédant au moins une solution, \item Connaître la difficulté des niveaux, \end{itemize} \end{block} } \end{column} \begin{column}{0.49\textwidth} \uncover<2->{ \begin{block}{Solutions} \begin{itemize} \item Application Android \item Outils d'analyse de difficulté \item Taille des instances bornée \end{itemize} \end{block} } \end{column} \end{columns} \end{frame} \section{Application} \subsection{Conception de l'interface} \begin{frame} \frametitle{Analyse des besoins utilisateurs} \begin{itemize} \item Qui sont nos utilisateurs? \begin{itemize} \item Public visé large \item Ne pas introduire de biais \end{itemize} \item Récoltes de données sur nos utilisateurs \begin{itemize} \item Interviews \item Analyse d'applications de jeux connues \end{itemize} \item Emergence des tâches systèmes de notre application \end{itemize} \end{frame} \begin{frame} \frametitle{Objectifs de notre interface} \begin{itemize} \item Une interface claire et épurée \item Le nombre d'informations affichées à l'écran \item Rapidité et fluidité de notre interface \end{itemize} \end{frame} \begin{frame} \frametitle{Critères d'évaluation} \begin{itemize} \item Facilité d'usage "Easy to use" \item Facilité d'apprentissage "Easy to learn" \item Satisfaction personnelle \end{itemize} \end{frame} \begin{frame} \frametitle{Evolution des designs de notre interface} \begin{center} \includegraphics[width=0.29\textwidth]{maquette}~ \raisebox{.65\height}{\includegraphics[width=0.29\textwidth]{prototype1}}~ \includegraphics[width=0.29\textwidth]{g1} \end{center} \end{frame} \begin{frame} \frametitle{Fonctionnement de l'interface finale} \begin{columns} \begin{column}{0.45\textwidth} \begin{itemize} \item Nom du niveau et bouton d'affichage d'envie \item Affichage des selections doubles \item Surbrillance des acteur envieux \end{itemize} \end{column}~ \begin{column}{0.49\textwidth} \begin{center} \includegraphics[width=0.49\textwidth]{g2} ~ \includegraphics[width=0.49\textwidth]{g3} \end{center} \end{column} \end{columns} \end{frame} \begin{frame} \frametitle{Notation des niveaux} \begin{columns} \begin{column}{0.49\textwidth} \begin{itemize} \item Détection de la victoire automatique \item Popup d'affichage \item Système a base d'etoiles \item Notation du niveau obligatoire \end{itemize} \end{column}~ \begin{column}{0.49\textwidth} \begin{center} \includegraphics[width=0.55\textwidth]{g4} \end{center} \end{column} \end{columns} \end{frame} \begin{frame} \frametitle{Tutoriel} \begin{columns} \begin{column}{0.49\textwidth} \begin{itemize} \item Description de l'interface \item Explication du concept de jalousie \item Conditions de victoire \end{itemize} \end{column}~ \begin{column}{0.49\textwidth} \begin{center} \includegraphics[width=0.55\textwidth]{tuto} \end{center} \end{column} \end{columns} \end{frame} \begin{frame} \frametitle{Structure de l'interface} \centering \resizebox{12cm}{!}{ \begin{tikzpicture} \umlsimpleclass{MainMenuActivity} \umlsimpleclass[x=6]{LevelMenuActivity} \umlsimpleclass[x=12]{GameActivity} \umlsimpleclass[y=2]{TutorialActivity} \umlsimpleclass[y=-2]{UserProfileActivity} \umlsimpleclass[y=-2, x=6]{AboutActivity} \umlassoc{MainMenuActivity}{TutorialActivity} \umlassoc{MainMenuActivity}{UserProfileActivity} \umlassoc{MainMenuActivity}{LevelMenuActivity} \umlassoc{MainMenuActivity}{AboutActivity} \umlassoc{LevelMenuActivity}{GameActivity} \end{tikzpicture} } \end{frame} \begin{frame} \frametitle{Autres Activités} \begin{columns} \begin{column}{0.49\textwidth} \begin{itemize} \item Entrée des informations testeurs \item Première Activité lors de l'ouverture l'application \item Acessible depuis le menu principal \item Affichage des niveaux complétés \item Affichage des niveaux en cours \end{itemize} \end{column}~ \begin{column}{0.49\textwidth} \begin{center} \includegraphics[width=0.49\textwidth]{infor} ~ \includegraphics[width=0.49\textwidth]{levelmenu} \end{center} \end{column} \end{columns} \end{frame} \subsection{Architecture} \begin{frame} \frametitle{Structure du Back-End} \centering \resizebox{6cm}{!}{ \begin{tikzpicture} \begin{umlpackage}{Models} \umlsimpleclass{Grid} \umlsimpleclass[y=-2]{Model} \umlassoc[mult2=1, mult1=1]{Model}{Grid} \umlsimpleclass[y=-4]{Level} \umlassoc[mult2=1, mult1=1]{Model}{Level} \umlsimpleinterface[x=3,y=-2]{IPiece} \umlassoc[mult1=1,mult2=*]{Model}{IPiece} \umlsimpleclass[x=2.5, y=-4]{Actor} \umlsimpleclass[x=5, y=-4]{Preference} \umlimpl{Actor}{IPiece} \umlimpl{Preference}{IPiece} \umlsimpleclass[x=4, y=-6.5]{Position} \umlassoc[mult1=1, mult2=1]{Actor}{Position} \umlassoc[mult1=1, mult2=1]{Preference}{Position} \end{umlpackage} \end{tikzpicture} } \end{frame} \begin{frame} \frametitle{Intégration GoogleSheets} \centering \resizebox{12cm}{!}{ \begin{tikzpicture} \begin{umlpackage}[fill=red!20]{GoogleSheets} \umlsimpleclass{GoogleSheetsWriteUtil} \umlsimpleclass[y=-1.5]{SheetsServiceUtil} \umluniassoc{GoogleSheetsWriteUtil}{SheetsServiceUtil} \umlsimpleclass[x=6, type=abstract]{AsyncTask} \umluniassoc{GoogleSheetsWriteUtil}{AsyncTask} \umlsimpleclass[y=-2, x=4]{WriteUserInfo} \umlimpl{WriteUserInfo}{AsyncTask} \umlsimpleclass[y=-2, x=8]{WriteUserEvaluation} \umlimpl{WriteUserEvaluation}{AsyncTask} \umlsimpleclass[x=10]{ModifyUserProfile} \umlimpl{ModifyUserProfile}{AsyncTask} \end{umlpackage} \end{tikzpicture} } \end{frame} \subsection{Récupération des données} \begin{frame} \frametitle{Intégration GoogleSheets} \includegraphics[width=1\textwidth]{Sheets} \end{frame} \section{Analyse} \begin{frame} \frametitle{Génération d'instances solvables} \centering \begin{tikzpicture} % Agents \vertex (a1) at (0,0) {$a_1$}; \vertex (a2) at (1.5,0) {$a_2$}; \vertex (a3) at (3,0) {$a_3$}; \vertex (a4) at (4.5,0) {$a_4$}; % Prefs \node (a1o1) at (0,2.2) {$o_3$}; \node (a1o2) at (0,1.7) {$o_4$}; \node (a1o3) at (0,1.2) {\fbox{$o_1$}}; \node (a1o4) at (0,0.7) {\bb{$o_2$}}; \node (a2o1) at (1.5,2.2) {\fbox{$o_2$}}; %\uncover<2->{\node (a2o1) at (1.5,2.2) {\yy{$o_3$}};} \node (a2o2) at (1.5,1.7) {$o_4$}; \node (a2o3) at (1.5,1.2) {\bb{$o_3$}}; \node (a2o4) at (1.5,0.7) {\bb{$o_1$}}; \node (a3o1) at (3.0,2.2) {\fbox{$o_3$}}; %\uncover<2->{\node (a3o1) at (3.0,2.2) {\yy{$o_2$}};} \node (a3o2) at (3.0,1.7) {$o_1$}; \node (a3o3) at (3.0,1.2) {\bb{$o_4$}}; \node (a3o4) at (3.0,0.7) {\bb{$o_2$}}; \node (a4o1) at (4.5,2.2) {$o_2$}; \node (a4o2) at (4.5,1.7) {\fbox{$o_4$}}; %\uncover<2->{\node (a4o2) at (4.5,1.7) {\yy{$o_4$}};} \node (a4o3) at (4.5,1.2) {\bb{$o_3$}}; \node (a4o4) at (4.5,0.7) {$o_1$}; \path (a1) edge[thick] (a2) (a2) edge[thick] (a3) (a3) edge[thick] (a4) ; \end{tikzpicture} \vspace{1cm} \begin{columns} \centering \begin{column}{.6\textwidth} \begin{itemize} \item Choix d'une allocation \item Placement des objets voisins \item Placement aléatoire des objets restants \end{itemize} \end{column} \end{columns} \end{frame} \begin{frame} \frametitle{Résolution par backtrack} \centering \begin{tabular}{c|c c c c c c c} \textbf{Index} \\ \hline 0& 2 & \yy{3} & \yy{2} & \yy{5} & \yy{7} & \yy{4} & \yy{6} \\ 1& \yy{1} & 4 & 6 & 6 & 3 & \bb{5}& 1 \\ 2& 3 & 2 & \bb{1}& 7 & \bb{2}& 6 & \bb{3}\\ 3& \bb{6} & 5 & 3 & 3 & 1 & 7 & 7 \\ 4& 5 & \bb{7}& 4 & \bb{4}& 6 & 1 & 5 \\ 5& 3 & 1 & 7 & 2 & 4 & 2 & 2 \\ 6& 7 & 6 & 5 & 1 & 5 & 3 & 4 \\ \hline \end{tabular}\\[0.8cm] Regret minimum, regret moyen, regret extrêmité, nombre d'affectation, solutions Pareto-optimales. \end{frame} \begin{frame} \frametitle{Résolution ASP} \centering Récupération de l'ensemble des solutions d'une instance\\[0.2cm] \begin{itemize} \item Génération: un objet par agent\\[.1cm] \texttt{1\{ aff(A, O) : object(O) \}1 :- agent(A).} \uncover<2->{\item Un agent par objet\\[.1cm] \texttt{:- aff(A1, O), aff(A2, O), A1 != A2.}} \uncover<3->{\item Pas de jalousie\\[.1cm] \texttt{:- aff(A1, O1), aff(A2, O2),\\ position(A1, O1, P1), \\ position(A1, O2, P2), \\ P2 < P1, voisins(A1,A2).}} \end{itemize} \uncover<4->{Nombre total de solutions, nombre de variables frozen.} \end{frame} \begin{frame} \frametitle{Analyse de fitness landscape} \centering \includegraphics<1>[width=0.8\textwidth]{basin-5-2} \includegraphics<2>[width=0.8\textwidth]{basin_7-6} \end{frame} \begin{frame} \frametitle{Apprentissage} \end{frame} \section{Conclusion} \begin{frame} \frametitle{Travail futur} \begin{itemize} \item Plus de mesures \item Ameliorer les modèles d'apprentissage \item Déploiement de l'application sur PlayStore \item Chargement des niveaux à distance \item Changer la disposition des agents \item Obstruer la visibilité de certains agents \item Implementation iOS \end{itemize} \end{frame} \begin{frame} \frametitle{Merci} \begin{itemize} \item Mottola Gualtiero (\url{gualt1995@gmail.com}) \item Bontems Alexandre (\url{alexandre.bontems@gmail.com}) \item Thirunavukarasu Hans (\url{hans.thiru@gmail.com}) \end{itemize} \end{frame} \end{document}
package ru.poplaukhin.springcourse.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import ru.poplaukhin.springcourse.models.Person; import java.util.List; import java.util.Optional; @Component public class PersonDAO { private final JdbcTemplate jdbcTemplate; @Autowired public PersonDAO(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public List<Person> index() { // вывод всей коллекции людей return jdbcTemplate.query("SELECT * FROM Person", new BeanPropertyRowMapper<>(Person.class)); } public Optional<Person> show(String address) { return jdbcTemplate.query("SELECT * FROM person WHERE address=?", new Object[]{address}, new BeanPropertyRowMapper<>(Person.class)).stream().findAny(); // сделали в этой строке условие, что если человек не найден, будет null } public Person show(int id) { // вытягиваем человека по его id return jdbcTemplate.query("SELECT * FROM person WHERE id=?", new Object[]{id}, new BeanPropertyRowMapper<>(Person.class)).stream().findAny().orElse(null); } public void save(Person person) { // сохранение человека jdbcTemplate.update("INSERT INTO Person(name, age, email, address) VALUES(?, ?, ?, ?)", person.getName(), person.getAge(), person.getEmail(), person.getAddress()); } public void update(int id, Person updatePerson) { // обновление(перезапись) человека jdbcTemplate.update("UPDATE Person SET name=?, age=?, email=? WHERE id=?", updatePerson.getName(), updatePerson.getAge(), updatePerson.getEmail(), id); } public void delete(int id) { // удаление jdbcTemplate.update("DELETE FROM Person WHERE id=?", id); } } // public void testMultipleUpdate() { // List<Person> people = create1000People(); // // long before = System.currentTimeMillis(); // время до вставки в миллисекундах // // for (Person person: people) { // jdbcTemplate.update("INSERT INTO Person VALUES(?, ?, ?, ?)", person.getId(), person.getName(), person.getAge(), // person.getEmail()); // } // // long after = System.currentTimeMillis(); // время после вставки в миллисекундах // System.out.println("Time: " + (after - before)); // } // private List<Person> create1000People() { // List<Person> people = new ArrayList<>(); // for (int i = 0; i < 1000; i++) { // people.add(new Person(i, "Name" + i, 30, "test"+i + "mail.ru")); // } // // return people; // } // public void testBatchUpdate() { // List<Person> people = create1000People(); // // long before = System.currentTimeMillis(); // // jdbcTemplate.batchUpdate("INSERT INTO Person VALUES(?, ?, ?, ?)", // new BatchPreparedStatementSetter() { // @Override // public void setValues(PreparedStatement preparedStatement, int i) throws SQLException { // preparedStatement.setInt(1, people.get(i).getId()); // preparedStatement.setString(2, people.get(i).getName()); // preparedStatement.setInt(3, people.get(i).getAge()); // preparedStatement.setString(4, people.get(i).getEmail()); // } // @Override // public int getBatchSize() { // return people.size(); // здесь нужно возвращать размер нашего предстоящего Batch Update // } // }); // // long after = System.currentTimeMillis(); // System.out.println("Time: " + (after - before)); // } ////////// Тестируем производительность пакетное вставки
'use client'; import React, { createContext, useContext, useEffect, useState, Dispatch, SetStateAction, } from 'react'; import WebApp from '@twa-dev/sdk'; type AuthContextType = { userID: number | null; username: string | null; windowHeight: number; photo_url: string | null; token: string; setToken: Dispatch<SetStateAction<string>>; }; const AuthContext = createContext<AuthContextType | undefined>(undefined); export const AuthContextProvider = ({ children, }: { children: React.ReactNode; }) => { const [windowHeight, setWindowHeight] = useState<number>(0); const [userID, setUserID] = useState<number | null>(null); const [username, setUsername] = useState<string | null>(null); const [photo_url, setPhotoUrl] = useState<string | null>(null); const [token, setToken] = useState(''); useEffect(() => { // Ensure this code only runs on the client side if (typeof window !== 'undefined' && WebApp) { WebApp.isVerticalSwipesEnabled = false; setWindowHeight(WebApp.viewportStableHeight || window.innerHeight); WebApp.ready(); WebApp.expand(); // Set Telegram user data const user = WebApp.initDataUnsafe.user; setUserID(user?.id || null); setUsername(user?.username || null); setPhotoUrl(user?.photo_url || null); } setToken(localStorage.getItem('token') ?? ''); }, []); const contextValue = { userID, username, windowHeight, photo_url, token, setToken, }; return ( <AuthContext.Provider value={contextValue}> {children} </AuthContext.Provider> ); }; export const useAuth = () => { const context = useContext(AuthContext); if (context === undefined) { throw new Error('useAuth must be used within an AuthContextProvider'); } return context; };
import React, { useState } from "react"; const CustomApp = () => { const tabs: Tab[] = [ { id: 1, title: "Tab 1" }, { id: 2, title: "Tab 2" }, { id: 3, title: "Tab 3" }, ]; const images: Image[] = [ { id: 1, url: "https://img.freepik.com/free-photo/painting-mountain-lake-with-mountain-background_188544-9126.jpg", tabId: 1 }, { id: 2, url: "https://t3.ftcdn.net/jpg/05/85/86/44/360_F_585864419_kgIYUcDQ0yiLOCo1aRjeu7kRxndcoitz.jpg", tabId: 1 }, { id: 3, url: "https://img.freepik.com/free-photo/snowy-mountain-peak-starry-galaxy-majesty-generative-ai_188544-9650.jpg", tabId: 2 }, { id: 4, url: "https://img.freepik.com/free-photo/snowy-mountain-peak-starry-galaxy-majesty-generative-ai_188544-9650.jpg", tabId: 3 }, { id: 5, url: "https://t4.ftcdn.net/jpg/05/55/71/83/360_F_555718315_XAi4cgO4s2uBRshlJZ8wXjAWkptX8023.jpg", tabId: 3 }, ]; return ( <> <div className="container mx-auto mt-8"> <h1 className="text-3xl font-bold mb-4">Tab Gallery</h1> <TabGallery tabs={tabs} images={images} /> </div> </> ) } export default CustomApp interface Tab { id: number; title: string; } interface Image { id: number; url: string; tabId: number; } interface TabGalleryProps { tabs: Tab[]; images: Image[]; } const TabGallery: React.FC<TabGalleryProps> = ({ tabs, images }) => { const [activeTab, setActiveTab] = useState<number>(tabs[0].id); const handleTabClick = (tabId: number) => { setActiveTab(tabId); }; return ( <div> <div className="flex"> {tabs.map((tab) => ( <div key={tab.id} className={`cursor-pointer px-4 py-2 ${ activeTab === tab.id ? "bg-gray-600 text-white" : "bg-gray-300" }`} onClick={() => handleTabClick(tab.id)} > {tab.title} </div> ))} </div> <div className="grid grid-cols-3 gap-4 mt-4"> {images .filter((image) => image.tabId === activeTab) .map((image) => ( <img key={image.id} src={image.url} alt={`Image ${image.id}`} /> ))} </div> </div> ); };
package com.tk; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class HttpServer extends Thread{ private ExecutorService service = Executors.newCachedThreadPool(); private int port; public HttpServer(int port){ this.port = port; } @Override public void run() { try (ServerSocket server = new ServerSocket(port)) { while (true) { this.serverProcess(server); } } catch (Exception e) { e.printStackTrace(); } } private void serverProcess(ServerSocket server) throws IOException { Socket socket = server.accept(); this.service.execute(() -> { try ( InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); ) { HttpRequest request = new HttpRequest(in); HttpHeader header = request.getHeader(); if (header.isGetMethod()) { File file = null; if(header.getPath().equalsIgnoreCase("/")){ file = new File(".", "/index.html"); } else { file = new File(".", header.getPath()); } if (file.exists() && file.isFile()) { this.respondLocalFile(file, out); } else { this.respondNotFoundError(out); } } else { this.respondOk(out); } } catch (EmptyRequestException e) { } catch (IOException e) { throw new UncheckedIOException(e); } finally { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } }); } private void respondNotFoundError(OutputStream out) throws IOException { HttpResponse response = new HttpResponse(Status.NOT_FOUND); response.addHeader("Content-Type", ContentType.TEXT_PLAIN); response.setBody(Status.NOT_FOUND.getText()); response.writeTo(out); } private void respondLocalFile(File file, OutputStream out) throws IOException { HttpResponse response = new HttpResponse(Status.OK); response.setBody(file); response.writeTo(out); } private void respondOk(OutputStream out) throws IOException { HttpResponse response = new HttpResponse(Status.OK); response.writeTo(out); } }
package ru.kazantsev.nsd.configMigrator.config import org.slf4j.LoggerFactory import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.BadCredentialsException import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.Authentication import org.springframework.security.core.AuthenticationException import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.stereotype.Component import ru.kazantsev.nsd.configMigrator.data.repo.UserRepo @Component class AuthenticationManagerImpl( private val passwordEncoder: PasswordEncoder, private val userRepo: UserRepo ) : AuthenticationManager { @Throws(AuthenticationException::class) override fun authenticate(auth: Authentication): Authentication { val username: String = auth.name val password: String = auth.credentials.toString() val user = userRepo.findByUsername(username).orElse(null) if (user != null && passwordEncoder.matches(auth.credentials as String, user.password)) { return UsernamePasswordAuthenticationToken(user, password, user.authorities) } else throw BadCredentialsException("Authentication failed") } }
import { datesOnSameDay, dateIsBeforeOtherDate, dateIsAfterOtherDate, isRecentDate, isValidDate, diffDates, milestoneToDate, } from '../date' import { SECONDS_PER_MILESTONE } from '../../network/constants' import { MILLISECONDS_PER_SECOND } from '../constants' describe('datesOnSameDay', () => { test('returns true for the same date', () => { const date = new Date() expect(datesOnSameDay(date, date)).toBe(true) }) test('returns true for different date objects on the same day', () => { const date1 = new Date('2023-04-28T10:00:00') const date2 = new Date('2023-04-28T22:00:00') expect(datesOnSameDay(date1, date2)).toBe(true) }) test('returns false for dates on different days', () => { const date1 = new Date('2023-04-28') const date2 = new Date('2023-04-29') expect(datesOnSameDay(date1, date2)).toBe(false) }) }) describe('dateIsBeforeOtherDate', () => { test('returns true when the first date is before the second date', () => { const date1 = new Date('2023-04-28') const date2 = new Date('2023-04-29') expect(dateIsBeforeOtherDate(date1, date2)).toBe(true) }) test('returns false when the first date is after the second date', () => { const date1 = new Date('2023-04-29') const date2 = new Date('2023-04-28') expect(dateIsBeforeOtherDate(date1, date2)).toBe(false) }) test('returns false when the dates are on the same day', () => { const date1 = new Date('2023-04-28T10:00:00') const date2 = new Date('2023-04-28T22:00:00') expect(dateIsBeforeOtherDate(date1, date2)).toBe(false) }) }) describe('dateIsAfterOtherDate', () => { test('returns true when the first date is after the second date', () => { const date1 = new Date('2023-04-29') const date2 = new Date('2023-04-28') expect(dateIsAfterOtherDate(date1, date2)).toBe(true) }) test('returns false when the first date is before the second date', () => { const date1 = new Date('2023-04-28') const date2 = new Date('2023-04-29') expect(dateIsAfterOtherDate(date1, date2)).toBe(false) }) test('returns false when the dates are on the same day', () => { const date1 = new Date('2023-04-28T10:00:00') const date2 = new Date('2023-04-28T22:00:00') expect(dateIsAfterOtherDate(date1, date2)).toBe(false) }) }) describe('isRecentDate', () => { test('returns true for lessThanAMonth and lessThanThreeMonths for a date within a month', () => { const date = new Date() date.setDate(date.getDate() - 10) const result = isRecentDate(date) expect(result.lessThanAMonth).toBe(true) expect(result.lessThanThreeMonths).toBe(true) }) test('returns false for lessThanAMonth and true for lessThanThreeMonths for a date within three months but more than a month', () => { const date = new Date() date.setDate(date.getDate() - 45) const result = isRecentDate(date) expect(result.lessThanAMonth).toBe(false) expect(result.lessThanThreeMonths).toBe(true) }) test('returns false for lessThanAMonth and false for lessThanThreeMonths for a date older than three months', () => { const date = new Date() date.setDate(date.getDate() - 100) const result = isRecentDate(date) expect(result.lessThanAMonth).toBe(false) expect(result.lessThanThreeMonths).toBe(false) }) test('returns null for a future date', () => { const date = new Date() date.setDate(date.getDate() + 10) const result = isRecentDate(date) expect(result).toBe(null) }) }) describe('isValidDate', () => { it('should return true for a past date', () => { expect(isValidDate(new Date(Date.now() - 100_000_000))).toBe(true) }) it('should return true for a future date', () => { expect(isValidDate(new Date(Date.now() + 100_000_000))).toBe(true) }) it('should return true for a present date', () => { expect(isValidDate(new Date())).toBe(true) }) it('should return false if date is instantiated with a string', () => { expect(isValidDate(new Date(''))).toBe(false) }) }) describe('diffDates', () => { test('returns difference in days for dates within the same week', () => { const firstDate = new Date('2023-04-28T12:00:00Z') const secondDate = new Date('2023-04-30T12:00:00Z') const result = diffDates(firstDate, secondDate) expect(result.unit).toBe('daysAgo') expect(result.value).toBe(2) }) test('returns difference in weeks for dates within the same month but different weeks', () => { const firstDate = new Date('2023-04-01T12:00:00Z') const secondDate = new Date('2023-04-22T12:00:00Z') const result = diffDates(firstDate, secondDate) expect(result.unit).toBe('weeksAgo') expect(result.value).toBe(3) }) test('returns difference in months for dates within the same year but different months', () => { const firstDate = new Date('2023-04-01T12:00:00Z') const secondDate = new Date('2023-07-01T12:00:00Z') const result = diffDates(firstDate, secondDate) expect(result.unit).toBe('monthsAgo') expect(result.value).toBe(3) }) test('returns difference in years for dates in different years', () => { const firstDate = new Date('2025-04-01T12:00:00Z') const secondDate = new Date('2023-04-01T12:00:00Z') const result = diffDates(firstDate, secondDate) expect(result.unit).toBe('yearsAgo') expect(result.value).toBe(2) }) test('returns yesterday for dates with a one-day difference', () => { const firstDate = new Date('2023-04-27T12:00:00Z') const secondDate = new Date('2023-04-28T12:00:00Z') const result = diffDates(firstDate, secondDate) expect(result.unit).toBe('yesterday') }) test('returns today for dates on the same day', () => { const firstDate = new Date('2023-04-28T12:00:00Z') const secondDate = new Date('2023-04-28T15:00:00Z') const result = diffDates(firstDate, secondDate) expect(result.unit).toBe('today') }) }) describe('milestoneToDate', () => { test('returns the correct date for a past milestone based on the current milestone', () => { const baseMilestone = 10 const milestone = 5 const currentMillis = Date.now() const expectedMillis = currentMillis - (baseMilestone - milestone) * SECONDS_PER_MILESTONE * MILLISECONDS_PER_SECOND const expectedDate = new Date(expectedMillis) const result = milestoneToDate(baseMilestone, milestone) expect(result.getTime()).toBeCloseTo(expectedDate.getTime(), -2) // Tolerating a 100ms difference }) test('returns the correct date for the current milestone', () => { const baseMilestone = 10 const milestone = 10 const currentMillis = Date.now() const expectedDate = new Date(currentMillis) const result = milestoneToDate(baseMilestone, milestone) expect(result.getTime()).toBeCloseTo(expectedDate.getTime(), -2) // Tolerating a 100ms difference }) test('returns the correct date for a future milestone based on the current milestone', () => { const baseMilestone = 10 const milestone = 15 const currentMillis = Date.now() const expectedMillis = currentMillis + (milestone - baseMilestone) * SECONDS_PER_MILESTONE * MILLISECONDS_PER_SECOND const expectedDate = new Date(expectedMillis) const result = milestoneToDate(baseMilestone, milestone) expect(result.getTime()).toBeCloseTo(expectedDate.getTime(), -2) // Tolerating a 100ms difference }) })
<!DOCTYPE html> <html lang="jp" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link th:href="@{/css/reset.css}" rel="stylesheet" type="text/css"> <link th:href="@{/css/stylesheet.css}" rel="stylesheet" type="text/css"> <title>staffEditPage</title> </head> <body> <div id="editPage"> <div class="toptitle">社員情報管理</div> <div class="staffwrapper"> <div class="employee"> <form method="post" action="/new"> <input type="submit" value="新規登録" class="btn newbtn"> </form> <div class="subtitle">社員情報</div> <div class="container"> <table th:if="${staffList ne null}"> <thead class="editList"> <tr> <th>id</th> <th>社員コード</th> <th>姓名</th> <th>姓 名 ローマ字</th> <th>入社年月日</th> <th>編集</th> <th>削除</th> </tr> </thead> <tbody th:each="staff, stat :${staffList}" class="editList"> <tr> <td th:text="${stat.count}"></td> <td th:text="${staff.staffCode}"></td> <td th:text="${staff.lastName} + ' ' + ${staff.firstName}"></td> <td th:text="${staff.lastNameRomaji} + ' ' + ${staff.firstNameRomaji}"></td> <td th:text="${staff.joinedYear}"></td> <td class=""> <form th:action="@{'/edit/' + ${staff.staffCode}}" method="get"> <input type="submit" value="更新" class="uptatebtn"> </form> </td> <td> <form th:action="@{'/delete/' + ${staff.staffCode}}" method="get"> <input type="submit" value="削除" class="deletebtn"> </form> </td> </tr> </tbody> </table> <div class="nullData" th:if="${staffList == null}">社員情報が存在しません。</div> <div class="backbtn"> <form method="post" action="/backHome"> <input type="submit" value="戻る" class="btn"> </form> </div> </div> </div> </div> </div> </body> </html>
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const express_1 = __importDefault(require("express")); const body_parser_1 = __importDefault(require("body-parser")); const cors_1 = __importDefault(require("cors")); const routes_1 = require("./routes"); const database_async_1 = require("./database-async"); const app = (0, express_1.default)(); const PORT = process.env['PORT'] || 3000; app.use((0, cors_1.default)()); app.use(body_parser_1.default.json()); app.use(body_parser_1.default.urlencoded({ extended: false })); const db = new database_async_1.DB(); async function initializeServer() { try { // Migrate and seed the database await db.migrate(); console.log('📂 Database migrated successfully.'); await db.seed(); console.log('🌱 Database seeded successfully.'); // Start the server after the database is ready app.use('/api', (0, routes_1.createRouter)(db)); } catch (error) { console.error('❌ Failed to initialize the server:', error); process.exit(1); // Exit the process with a failure code } } initializeServer(); app.listen(PORT, () => { console.log(`⚡ Server is running on port ${PORT}`); }); //# sourceMappingURL=app.js.map
import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import reportWebVitals from './reportWebVitals'; import Home from './component/template/home'; import store from './handler/store' import { Provider } from 'react-redux'; import { BrowserRouter, Route, Routes } from 'react-router-dom'; import NotFound from './component/page/errorPage/404'; import Layout from './component/page/layout'; import Task from './component/page/task'; import Register from './component/page/register/register'; import Login from './component/page/login/login'; import Employee from './component/page/employee/employee'; import ForgotPassword from './component/page/forgotPassword/forgotPassword'; import GanttChart from './component/template/gantt'; import ProjectApprovePage from './component/template/approval_project'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <Provider store = {store}> <BrowserRouter> <Routes> <Route path='/' element={<Layout/>}> <Route index element={<Home/>}/> <Route path='task/:project_id' element={<Task/>}/> <Route path='gantt' element={<GanttChart/>}/> <Route path='employee' element={<Employee/>}/> <Route path='login' element={<Login/>}/> <Route path='register' element={<Register/>}/> <Route path='forgotpassword' element={<ForgotPassword/>}/> <Route path='approval_project' element={<ProjectApprovePage/>} /> <Route path='*' element={<NotFound/>}/> </Route> <Route index element={<Home/>}/> <Route path='approval_project' element={<ProjectApprovePage/>}/> </Routes> </BrowserRouter> </Provider> ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();
const express = require('express'); const User = require('../models/user'); const auth = require('../middleware/auth'); const sharp = require('sharp'); const multer = require('multer'); const sendWelcomeEmail = require('../emails/account') const router = new express.Router; router.post('/users/login',async (req,res) => { try { const user = await User.findByCredentials(req.body.email,req.body.password); const token = await user.generateAuthToken(); res.send({user, token}); } catch (error) { res.status(400).send(error.message); } }) router.post('/users',async (req,res) =>{ const user = new User(req.body); try { await user.save(); const token = await user.generateAuthToken(); sendWelcomeEmail(user.email, user.name) res.status(201).send({user, token}) } catch (error) { res.status(500).send(error.message) } }) router.post('/users/logout',auth,async (req,res) => { try { req.user.tokens = req.user.tokens.filter((token) => { return token.token !== req.token }) await req.user.save(); res.send(); } catch (error) { res.status(500).send(); } }) router.post('/users/logoutAll',auth,async (req,res) => { try { req.user.tokens = []; await req.user.save(); res.send('You have logged out of all accounts.'); } catch (error) { res.status(500).send(); } }) router.get('/users/me',auth,async (req,res) => { res.send(req.user); }) // router.get('/users/:id',async (req,res)=>{ // const _id = req.params.id; // try { // const loser = await User.findById(_id); // if(!loser){ // return res.status(404).send(); // } // res.status(200).send(loser); // } catch (error) { // res.status(500).send(error.message); // } // }) router.patch('/users/me',auth,async(req,res) => { const updates = Object.keys(req.body); //name const allowedUpdate = ['name','age','email','password']; const isValidOperation = updates.every((update) => { return allowedUpdate.includes(update); }) if (!isValidOperation) { return res.status(400).send(); } try { updates.forEach((update) => {req.user[update] = req.body[update];}) await req.user.save(); res.send(req.user); } catch (error) { res.status(500).send(error.message); } }) router.delete('/users/me',auth, async(req,res)=>{ try { await req.user.remove(); res.status(200).send(req.user); } catch (error) { res.status(500).send(); } }) const upload = multer({ limits:{ fileSize: 1000000 }, fileFilter(req,file,cb){ if (!file.originalname.match(/.(jpg|jpeg|png)$/)) { return cb(new Error('Only .jpg,.jpeg or .png is allowed')); } cb(undefined, true); } }) router.post('/users/me/avatar',auth,upload.single('avatar'),async (req,res)=> { const buffer = await sharp(req.file.buffer).resize({width:250, height:250}).png().toBuffer(); console.log(buffer); req.user.avatar = buffer; await req.user.save(); res.status(200).send(); },(error,req,res,next) => { res.status(400).send({error: error.message}) }) router.get('/users/:id/avatar',async (req,res) => { try { const user = await User.findById(req.params.id); if (!user || !user.avatar) { throw new Error('idk why this isnt working'); } res.set('Content-Type','image/png'); res.send(user.avatar) } catch (error) { res.status(500).send(error.message) } }) router.delete('/users/me/avatar',auth,async (req,res)=>{ req.user.avatar = undefined; await req.user.save(); res.status(200).send(); },(error,req,res,next) => { res.status(400).send({error: error.message}) }) module.exports = router;
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { _transferOwnership(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } contract ERC20 is Context, Ownable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 public _decimals; event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); constructor( string memory name_, string memory symbol_, uint8 decimals_, uint256 totalSupply_ ) { _name = name_; _symbol = symbol_; _decimals = decimals_; _mint(_msgSender(), totalSupply_ * 10 ** decimals_); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address to, uint256 amount) public returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } function allowance( address owner, address spender ) public view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require( currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero" ); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } function _transfer(address from, address to, uint256 amount) internal { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require( fromBalance >= amount, "ERC20: transfer amount exceeds balance" ); unchecked { _balances[from] = fromBalance - amount; _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; unchecked { _balances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; _totalSupply -= amount; } emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _spendAllowance( address owner, address spender, uint256 amount ) internal { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require( currentAllowance >= amount, "ERC20: insufficient allowance" ); unchecked { _approve(owner, spender, currentAllowance - amount); } } } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal {} function _afterTokenTransfer( address from, address to, uint256 amount ) internal {} }
import 'package:chatting/chatting/chat/chat_bubble.dart'; import 'package:flutter/material.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; class Messages extends StatelessWidget { const Messages({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final user = FirebaseAuth.instance.currentUser; return StreamBuilder( stream: FirebaseFirestore.instance.collection('chat').orderBy('time',descending: true).snapshots(), builder: (context, AsyncSnapshot<QuerySnapshot<Map<String,dynamic>>> snapshot){ if(snapshot.connectionState == ConnectionState.waiting){ return Center( child: CircularProgressIndicator(), ); } final chatDocs = snapshot.data!.docs; return ListView.builder( reverse: true, itemCount: chatDocs.length, itemBuilder: (context, index){ return ChatBubbles( chatDocs[index].data()['text'], chatDocs[index].data()['userID'].toString()==user!.uid, chatDocs[index].data()['userName'], chatDocs[index].data()['userImage'] ); } ); } ); } }
export function algoStockTrade1(input: number[]): number { let maxProfit = 0; for (let i = 0; i < input.length; i++) { for (let j = i + 1; j < input.length; j++) { maxProfit = Math.max(maxProfit, input[j] - input[i]); } } return maxProfit; } // algoStockTrade2 - sum all increases in value /** * @param {number[]} input */ export function algoStockTrade2(input: number[]): number { // Using `reduce` isn't any more concise... let sum = 0; for (let i = 1; i < input.length; i++) { sum += Math.max(0, input[i] - input[i - 1]); } return sum; } class StockTrade { buyValue: number = 0; buyIndex: number = 0; sellValue: number = 0; sellIndex: number = 0; constructor(buyValue: number, buyIndex: number, sellValue: number, sellIndex: number) { this.buyValue = buyValue; this.buyIndex = buyIndex; this.sellValue = sellValue; this.sellIndex = sellIndex; } get profit(): number { return this.sellValue - this.buyValue; } toString(): string { // eslint-disable-next-line @typescript-eslint/restrict-template-expressions return `[${this.buyIndex},${this.buyValue}] => [${this.sellIndex},${this.sellValue}] = ${this.profit}`; } } /** * @param {number[]} input * @param {NS} ns */ export function algoStockTrade3(input: number[], ns: NS): number { return algoStockTrade4([2, input], ns); } /** * @param {[number, number[]]} input * @param {NS} ns */ export function algoStockTrade4(input: [number, number[]], ns: NS): number { // This WILL be used for the final implementation // eslint-disable-next-line @typescript-eslint/no-unused-vars const numTrades: number = input[0]; const prices: number[] = input[1]; let numPrices = prices.length; // REFINE Implement the comparison that MaxMinMedian shared: https://discord.com/channels/415207508303544321/923282733332054126/1321371942304874496 // (y - x) * (y - z) <=0 // Trim out any entries that will not be picked // If we have [1, 2, 3], we won't buy or sell at 2 for (let i = 0; i + 2 < numPrices; i++) { while (i + 2 < numPrices && prices[i] <= prices[i + 1] && prices[i + 1] <= prices[i + 2]) { prices.splice(i + 1, 1); numPrices = prices.length; } } // Same for decreasing values for (let i = 0; i + 2 < numPrices; i++) { while (i + 2 < numPrices && prices[i] >= prices[i + 1] && prices[i + 1] >= prices[i + 2]) { prices.splice(i + 1, 1); numPrices = prices.length; } } // Remove leading high prices while (numPrices > 1 && prices[0] >= prices[1]) { prices.splice(0, 1); numPrices = prices.length; } // Remove trailing low prices while (numPrices > 1 && prices[numPrices - 1] <= prices[numPrices - 2]) { prices.pop(); numPrices = prices.length; } if (numPrices <= 1) { ns.print("All lose money"); return 0; } //ns.print(prices); /** @type {StockTrade[]} */ let trades: StockTrade[] = []; // Find each pair of POSSIBLE transactions prices.forEach((startPrice: number, i: number) => { let maxGain = 0; for (let j = i + 1; j < numPrices; j++) { // Ignore later options that have lower gain const curGain = Math.max(0, prices[j] - startPrice); if (maxGain < curGain) { maxGain = curGain; trades.push(new StockTrade(prices[i], i, prices[j], j)); } } }); //trades.forEach(t => ns.print(t.toString())) // Scanning from the last sell price, remove any trades that have lower profit for (let i = numPrices - 1; i > 0; i--) { const sellAtIndex: StockTrade[] = trades.filter(t => t.sellIndex === i).sort((a, b) => a.buyIndex - b.buyIndex); if (sellAtIndex.length > 0) { // @ts-expect-error We just ensured that there are elements in the array let lastTradeValue = sellAtIndex.pop().profit; let tempTrade = sellAtIndex.pop(); while (tempTrade) { if (tempTrade.profit <= lastTradeValue) { // Spans more days, for no better profit; remove trades = trades.filter(t => t !== tempTrade); } else { lastTradeValue = tempTrade.profit; } tempTrade = sellAtIndex.pop(); } } } trades.forEach(t => ns.print(t.toString())); // TODO Find the groups on overlapping trades // This will further segment the problem space // Find the highest value trade for a starting point, and ignore any after // E.g. if we have [1,5,2,3], we wouldn't be buying at one and selling at 3 // But, if we have [1,4,2,5], we need to consider the 4, since we can buy at 2 // This doesn't fully solve, but it reduces the problem space // Actually, do this for ANY trade values; if any later trades <= val, ignore // For each index, ignore later trades with lower values // From the tail end, ignore any trades with the upper day that have a lower profit // Determine the set of non-overlapping transactions with the highest value return Number.NaN; }
package com.example.thopcinema.movies.adapter; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.thopcinema.MainActivity; import com.example.thopcinema.R; import com.example.thopcinema.music.MusicActivity; public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ViewHolder> { Context context; int[] image; String[] name; public ListAdapter(Context context, int[] image, String[] name) { this.context = context; this.image = image; this.name = name; } @NonNull @Override public ListAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item_movie_image,parent,false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ListAdapter.ViewHolder holder, @SuppressLint("RecyclerView") int position) { holder.textView.setText(""+name[position]); holder.imageView.setImageResource(image[position]); holder.imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(context , MusicActivity.class); intent.putExtra("image",image[position]); context.startActivity(intent); } }); } @Override public int getItemCount() { return image.length; } public class ViewHolder extends RecyclerView.ViewHolder { ImageView imageView; TextView textView; public ViewHolder(@NonNull View itemView) { super(itemView); imageView = itemView.findViewById(R.id.ivImage); textView = itemView.findViewById(R.id.tvName); } } }
require_relative "../classes/Wardrobe.rb" describe "Wardrobe" do it "should be defined" do expect(defined?(initialize)).to eql("method") end it "should have class variable called @@user_type to hold user type of either \"Clerk\" or \"Customer\"" do expect(Wardrobe.class_variable_get(:@@user_type)).to eql("") end describe "@@clothes" do it "should be a Hash object to hold data from database" do expect(Wardrobe.class_variable_get(:@@clothes).class).to eql(Hash) end end describe "object" do before :each do @wardrobe = Wardrobe.new end it "should have four different categories like Hat, Top, Pants and Shoes when data is retrived" do @wardrobe.retrive_data_from_files clothes = Wardrobe.class_variable_get(:@@clothes) expect(clothes.size).to eql(4) expect(clothes[:hat].class).to eql(Array) expect(clothes[:top].class).to eql(Array) expect(clothes[:pants].class).to eql(Array) expect(clothes[:shoes].class).to eql(Array) end it "should update database (.txt) when new item is added" do clothes = Wardrobe.class_variable_get(:@@clothes) old_database = clothes.clone clothes[:hat] << Hat.new("NY Hat", "Nike", "Snapback", "Grey", 5, 10, 59.99) @wardrobe.update_database @wardrobe.retrive_data_from_files expect(old_database[:hat].size).not_to be eq(clothes[:hat].size) end it "should update database (.txt) when item is removed" do clothes = Wardrobe.class_variable_get(:@@clothes) old_database = clothes.clone clothes[:hat].delete_at(-1) @wardrobe.update_database @wardrobe.retrive_data_from_files expect(old_database[:hat].size).not_to be eq(clothes[:hat].size) end end end
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Major project</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> .button{ font-family:Georgia, serif ; } .course-btn{ color: black; } a, u { text-decoration: none; } a:hover{ color: black; } </style> </head> <body style="background-color: grey;"> <div class="row" > <div class="container-fluid"> <div class="row"> <div class="col-md-12" > <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="#"> <i class="fa fa-car"></i> </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#about">About us</a> </li> <li class="nav-item"> <a class="nav-link" href="#contact">Contact us</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Courses </a> <ul class="dropdown-menu " aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="ug courses.html">Undergraduate</a></li> <li><a class="dropdown-item" href="g courses.html">Graduate</a></li> </ul> </li> </ul> </div> </div> </nav> </div> </div> </div> </div> <div class="row container-fluid mt-3" > <div class="col-md-12"> <div id="carouselExampleSlidesOnly" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="images/1.jpg" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="images/2.jpg" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="images/3.jfif" class="d-block w-100" alt="..."> </div> </div> </div> </div> </div> <div class="row container-fluid mt-2"> <div class="col-md-12 "> <h3 class="text-warning text-center" id="about">ABOUT US</h3> <p class="text-center">Lorem ipsum dolor sit amet consectetur adipisicing elit. Officia quo dolorum perspiciatis ratione tempora. Blanditiis dolore consectetur, accusamus modi deserunt ad magnam itaque libero repellat excepturi. Quis, eius odit! Nesciunt necessitatibus, modi harum temporibus fugiat dolore labore nobis iusto cupiditate nostrum maxime ratione dignissimos ex voluptatum atque! Reiciendis, unde harum!</p> </div> </div> <div class="row"> <div class="col-md-12"> <h3 class="text-warning text-center" id="contact">CONTACT US</h3> </div> </div> <div class="row container-fluid"> <div class="col-md-4"> <div class="card" style="width: 18rem;"> <img src="images/4.jpg" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title text-center"><i class="fa fa-instagram"> design</i></h5> </div> </div> </div> <div class="col-md-4"> <div class="card" style="width: 18rem;"> <img src="images/4.jpg" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title text-center"><i class="fa fa-envelope"></i> design@gmail.com</h5> </div> </div> </div> <div class="col-md-4"> <div class="card" style="width: 18rem;"> <img src="images/4.jpg" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title text-center"><i class="fa fa-phone"></i> 011-22002116</h5> </div> </div> </div> </div> <div class="row mt-3 container-xl"> <div class="col-md-6 bg-warning p-2"></div> <div class="col-md-6 p-2">Lorem ipsum dolor sit amet consectetur adipisicing elit. Eaque et obcaecati non facere dolores pariatur ad saepe sapiente veritatis, placeat, itaque fugiat maiores adipisci temporibus sequi tempore optio sunt. Aliquam neque, molestiae sequi laboriosam sunt quod. Temporibus quisquam, provident ab at error dicta asperiores dignissimos quidem officia doloremque laborum impedit facilis nostrum. Perspiciatis ipsa ipsum sit, deserunt minima eaque, labore quia possimus impedit vel iure, ducimus maiores blanditiis voluptatum. Delectus, cupiditate! Maxime, amet accusamus, corrupti ipsa eum, quasi quaerat nulla veritatis earum enim vitae et officiis totam est dolor vel? Corporis, modi rem officia voluptatem veniam suscipit dolorum id deleniti!</div> </div> <div class="row text-center container-xxl mt-3"> <!--<button class="button btn-warning btn"><a href="services.html" class="text-dark">Register</a></button>--> <!-- Button trigger modal --> <button type="button" class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#staticBackdrop"> Register </button> <!-- Modal --> <div > <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog "> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel">Choose</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <button type="button" class="btn btn-warning" data-bs-dismiss="modal"><a class="course-btn" href="ug courses.html">Undergraduate course</a></button> <button type="button" class="btn btn-warning"><a class="course-btn" href="g courses.html">Graduate course</a></button> </div> </div> </div> </div> </div> <div class="row bg-dark text-light mt-3 container-xxl"> <div><i class="fa fa-copyright"></i> copyright mukul</div> </div> </body> </html>
// Copyright (c) 2023 Sandro Cavazzoni // This code is licensed under MIT license (see LICENSE.txt for details) #pragma once #include "pch.h" #include "Common/Common.h" namespace chronicle { /// @brief Informations used to create a sampled texture. struct SampledTextureInfo { /// @brief Enabled the mipmap generation for the texture. bool generateMipmaps = true; /// @brief image data used to fill the texture. std::vector<uint8_t> data = {}; /// @brief Texture width. uint32_t width = 0; /// @brief Texture height. uint32_t height = 0; }; /// @brief Informations used to create a sampled texture. struct ColorTextureInfo { /// @brief Texture width. uint32_t width = 0; /// @brief Texture height. uint32_t height = 0; /// @brief Surface format. Format format = Format::undefined; /// @brief MSAA sample count. MSAA msaa = MSAA::sampleCount1; /// @brief The texture will be used as an input attachment. bool isInputAttachment = false; /// @brief Generate mipmaps for the texture. bool generateMipmaps = false; }; /// @brief Informations used to create a sampled texture. struct DepthTextureInfo { /// @brief Texture width. uint32_t width = 0; /// @brief Texture height. uint32_t height = 0; /// @brief Depth format. Format format = Format::undefined; /// @brief MSAA sample count. MSAA msaa = MSAA::sampleCount1; }; } // namespace chronicle
# Serverless Machine Learning This repository contains resources and code for implementing serverless machine learning solutions, with a special focus on integrating models from Hugging Face, a popular hub for machine learning models. ## Overview Serverless architectures enable the deployment of applications and services without managing the underlying infrastructure. This project focuses on deploying machine learning models as serverless functions, which can scale automatically with demand and minimize operational costs. Special emphasis is given to Hugging Face models due to their wide usage and versatility in the machine learning community. ## Getting Started ### Prerequisites - Knowledge of machine learning concepts. - Familiarity with serverless architecture. - Experience with Python, as many Hugging Face models are Python-based. - An account on Hugging Face (optional, for accessing certain models). ## Installation 1. Clone the repository: ```git clone https://github.com/MischaRauch/serverless_machine_learning.git``` 2. Navigate to the repository directory. 3. Install the required dependencies, including Hugging Face libraries: ```pip install -r requirements.txt``` ## Datasets in 01_Assignment ### Flower Dataset The Flower dataset, commonly used for classification tasks in machine learning, is featured in this part of the project. It typically consists of images of various flower species, making it ideal for testing image recognition algorithms. #### Dataset Characteristics: - **Type**: Image classification. - **Classes**: Multiple, usually including species like roses, daisies, sunflowers, etc. - **Usage**: Demonstrates the application of convolutional neural networks (CNNs) or other image processing techniques. #### Implementation Details: - Code snippets for loading and preprocessing the dataset. - Description of the model architecture used for classification. - Instructions for training and evaluating the model on this dataset. ### Wine Dataset The Wine dataset is another classic dataset used for regression or classification tasks. It usually contains chemical analysis results of different wine samples, aiming to classify them into various types. #### Dataset Characteristics: - **Type**: Classification or regression. - **Features**: Chemical properties like alcohol content, acidity, etc. - **Target**: Wine type or quality rating. #### Implementation Details: - Steps for data preprocessing and feature selection. - Description of the machine learning model used (e.g., decision trees, random forests). - Instructions for model training, testing, and evaluation. ### Enviornment Both datasets are hosted on Hopsworks. ## License Apache 2.0.
import { Injectable } from "@nestjs/common"; import {Scholarship, FinancialDetails ,notice,StudentLoginDTO, StudentDTO, StudentUpdateDTO, CourseStudentDto, Student, faculty, ProfileUpdateDTO} from "./student.dto"; import { InjectRepository } from "@nestjs/typeorm"; import { StudentEntity } from "./student.entity"; import { Repository } from "typeorm"; import { CourseEntity } from "src/course/course.entity"; import * as bcrypt from 'bcrypt'; import * as fs from 'fs'; import { NotFoundException } from "@nestjs/common"; import { NoticeEntity } from './student.entity'; import { CoursefEntity } from "./coursef.entity"; import { FeedbackEntity } from "src/feedback/feedback.entity"; import { StudentProfile } from "./student.entity"; import { MailerService } from '@nestjs-modules/mailer'; import * as nodemailer from 'nodemailer'; @Injectable() export class StudentService{ private criteria: string; constructor( @InjectRepository(StudentEntity) private studentRepo: Repository<StudentEntity>, private readonly mailerService: MailerService, @InjectRepository(CourseEntity) private courseRepo: Repository<CourseEntity>, @InjectRepository(NoticeEntity) private readonly noticeRepo: Repository<NoticeEntity>, @InjectRepository(CoursefEntity) private readonly coursefRepo: Repository<CoursefEntity>, @InjectRepository(FeedbackEntity) private readonly feedbackRepo: Repository<FeedbackEntity>, @InjectRepository(StudentProfile) private readonly studentProfileRepository: Repository<StudentProfile>, ) { } async sendEmail(subject: string, recipient: string, content: string): Promise<void> { try{ await this.mailerService.sendMail({ to: recipient, subject, text: content, }); } catch(error){ throw error; } } getScholarshipCriteria() { const filePath = "src/Student/criteria.json"; try { const criteriaData = fs.readFileSync(filePath, 'utf8'); const criteria = JSON.parse(criteriaData); return criteria; } catch (err) { console.error('Error reading criteria file:', err); return null; } } async updateFeedback(cfid: number, id: number, feedbackData: Partial<FeedbackEntity>): Promise<FeedbackEntity> { const courseFeedback = await this.coursefRepo.findOneBy({cfid}); const student = await this.studentRepo.findOneBy({id}); if (!courseFeedback) { throw new NotFoundException('Course feedback not found'); } const feedback = new FeedbackEntity(); feedback.comment = feedbackData.comment; feedback.rating = feedbackData.rating; feedback.courseFeedback = courseFeedback; feedback.student = student; const savedFeedback = await this.feedbackRepo.save(feedback); if (courseFeedback.feedbacks) { courseFeedback.feedbacks.push(savedFeedback); } else { courseFeedback.feedbacks = [savedFeedback]; } await this.coursefRepo.save(courseFeedback); return savedFeedback; } async getIndex(): Promise<StudentEntity[]> { return this.studentRepo.find(); } async getStudentById(id: number): Promise<StudentEntity> { return this.studentRepo.findOneBy({ id }); } async getStudentbyIDAndName(id, name): Promise<StudentEntity> { return this.studentRepo.findOneBy({ id: id, name: name }); } async addStudent(data: StudentDTO): Promise<StudentEntity> { return this.studentRepo.save(data); } async updateStudent(email:string, data: StudentUpdateDTO): Promise<StudentEntity> { await this.studentRepo.update(data.id, data); return this.studentRepo.findOneBy({ id: data.id }); } async updateStudentById(id: number, data: StudentDTO): Promise<StudentEntity> { await this.studentRepo.update(id, data); return this.studentRepo.findOneBy({ id }); } /* async deleteUser(id: number): Promise<StudentEntity[]> { await this.studentRepo.delete(id); return this.studentRepo.find(); } */ //course async addCourse(course): Promise<CourseEntity> { return this.courseRepo.save(course); } async getAllCourses(): Promise<CourseEntity[]> { return this.courseRepo.find(); } async getCoursesByStudent(studentid: number): Promise<StudentEntity[]> { return this.studentRepo.find({ where: { id: studentid }, relations: { courses: true, }, }); } async getCourseById(cid: number): Promise<CourseEntity> { return this.courseRepo.findOneBy({cid}); } async deleteCourse(cid: number): Promise<string> { await this.courseRepo.delete(cid); return "Course deleted successfully"; } //updtecourse async updateCourse( cid: number, updatedCourse: Partial<CourseEntity> ): Promise<CourseEntity> { await this.courseRepo.update({ cid }, updatedCourse); return this.courseRepo.findOneBy({ cid }); } //studentprofile async createStudentWithProfile(studentData: Partial<StudentEntity>, profileData: Partial<StudentProfile>): Promise<StudentEntity> { const profile = this.studentProfileRepository.create(profileData); const student = this.studentRepo.create({ ...studentData, profiles: [profile], }); await this.studentProfileRepository.save(profile); return this.studentRepo.save(student); } async getProfileById(id: number): Promise<StudentProfile> { return this.studentProfileRepository.findOneBy({id}); } async updateProfile( id: number, updatedProfile: Partial<StudentProfile> ): Promise<StudentProfile> { await this.studentProfileRepository.update({ id }, updatedProfile); return this.studentProfileRepository.findOneBy({ id }); } //signup async signup(data: StudentDTO): Promise<StudentEntity> { const salt = await bcrypt.genSalt(); console.log(data); data.password = await bcrypt.hash(data.password,salt); return this.studentRepo.save(data); } //login // async signIn(data:StudentLoginDTO) { // const userdata= await this.studentRepo.findOneBy({email:data.email}); // const match:boolean = await bcrypt.compare(data.password, userdata.password); // return match; // } async signIn(data: StudentLoginDTO) { const userdata = await this.studentRepo.findOneBy({ email: data.email }); if (!userdata) { return false; } const match = await bcrypt.compare(data.password, userdata.password); return match; } async getimagebystudentid(studentid:number) { const mydata:StudentDTO =await this.studentRepo.findOneBy({ id:studentid}); console.log(mydata); return mydata.filenames; } getCourse(id):Promise<StudentEntity[]> { return this.studentRepo.find({ where:{id:id}, relations: { courses: true, }, }); } //notice async getNoticeById(id: number): Promise<NoticeEntity> { return this.noticeRepo.findOneBy({id}); } }
import * as React from "react"; import { Button, Menu, MenuItem } from "@material-ui/core"; import "./commentHandelPopup.css"; import axios from "axios"; import { MoreVert } from "@material-ui/icons"; import { useState } from "react"; import Modal from "../modal/Modal"; export default function CommentHandlePopup({ comment, currentUser,listComments,setListComments,setNoCmts }) { const [anchorEl, setAnchorEl] = React.useState(null); const baseUrl = process.env.REACT_APP_BASE_URL; const open = Boolean(anchorEl); const [isEditComment, setIsEditComment] = useState(false); const handleClick = (event) => { setAnchorEl(event.currentTarget); }; const handleClose = () => { setAnchorEl(null); }; const handleDelete = async () => { try { const opts = { headers: { "Content-Type": "application/json", }, }; opts.headers.Authorization = "Bearer " + currentUser.token; const uri = `${baseUrl}/comments/${comment.id}`; console.log("uri: ", uri); const deleteResp = await axios.delete(uri, opts); console.log("deleteResp: ", deleteResp); setAnchorEl(null); setListComments(listComments.filter(cmt=> cmt.id != comment.id)) setNoCmts(listComments.filter(cmt=> cmt.id != comment.id).length) // window.location.reload(true); } catch (err) { console.log(err); } }; const checkOwner = (comment, currentUser) => { if (comment?.userId === currentUser.id) return true; return false; }; return ( <> {checkOwner(comment, currentUser) && ( <Button id="basic-button" aria-controls={open ? "basic-menu" : undefined} aria-haspopup="true" aria-expanded={open ? "true" : undefined} onClick={handleClick} > <MoreVert /> </Button> )} <Menu id="basic-menu" anchorEl={anchorEl} open={open} onClose={handleClose} MenuListProps={{ "aria-labelledby": "basic-button", }} > <MenuItem onClick={handleDelete}>Delete Comment</MenuItem> </Menu> {isEditComment && ( <Modal comment={comment} currentUser={currentUser} setIsOpen={setIsEditComment} /> )} </> ); }
#variables x = 5 y = "John" bool_var = True print(x) #receive input from user name = input("Enter your name: ") #this will print the message and wait for user input and return what is entered print("Hello, " + name) #type conversion birth_year = input("Enter your birth year: ") #will return value as string like "2002" age = 2023 - int(birth_year) #convert the value and return value in integer datatype print(age) #conversion built-in function #int() #float() #bool() #str() #sum of two numbers given by user first_num = float(input("Enter first number: ")) second_num = float(input("Enter second number: ")) sum = first_num + second_num print("Sum of two numbers = " + str(sum)) #string operations hello_world = "Hello World" print(hello_world.upper()) #HELLO WORLD print(hello_world) #Hello World print(hello_world.find('l')) #return the first occurance of l in the string, if the character is not found it will return -1, we can also pass the substring in find method print(hello_world.replace('World', 'Universe')) #replace the first argument with second argument in the string #in keyword python print('Hello' in hello_world) #return true if the first argument is present in the second argument else return false #arithmetic operations # / division operator print(10 / 3) #3.3333333333333335, return full answer with floating points print(10 // 3) #3, return only the integer part of the answer print(2 ** 3) #8, return 2 to the power 3 #augmented assignment operator +=, -=, *=, /=, //=, **=, %= #weight converter weight = float(input("Enter your weight: ")) unit = input("Enter the unit (L)bs or (K)g: ") if unit.upper() == 'L': converted_weight = weight/2.20462 print("Weight in Kg = " + str(converted_weight)) elif unit.upper() == 'K': converted_weight = weight * 2.20462 print("Weight in Lbs = " + str(converted_weight)) # * with string and integer i = 5 print(i * 'A') #will print 'AAAAA' #lists courses = ['IT', 'ICT'] print(courses[-1]) #will print the last element of the list print(courses[-2]) #will print the second last element of the list #list operations courses.append('CS') #add element to the end of the list courses.insert(4, 'CS') #add element to the specified index of the list print(courses) courses.remove('CS') #remove the element from the list courses.clear() #remove all the elements from the list #in operator also works in list also print(len(courses)) #return the length of the list print(courses[0:2]) #will print the elements from index 0 to 1, 2 is excluded print(courses[:2]) #same as upper line #for loop #item is loop variable for item in courses: print(item) #will print all the elements of the list i = 0 while i < len(courses): print(courses[i]) #i++ #python does not support i++ or i-- operator i = i + 1 #range function #we can also iterate over a range of numbers with range function numbers = range(5, 10) for number in numbers: print(number) #will print 5 to 9 numbers = range(5, 10, 2) for number in numbers: print(number) #will print 5 to 9 #tuples #tuples are immutable, we can not change the values of tuples numbers = (1, 2, 3) # numbers[0] = 20 #this will give error
import { createSlice, PayloadAction } from '@reduxjs/toolkit'; export interface CartItem { id: number; name: string; price: number; quantity: number; image: string; } interface CartState { items: CartItem[]; totalAmount: number; totalItems: number; isOpen: boolean; } const initialState: CartState = { items: [], totalAmount: 0, totalItems: 0, isOpen: false, }; const cartSlice = createSlice({ name: 'cart', initialState, reducers: { addItem: (state, action: PayloadAction<CartItem>) => { const existingItem = state.items.find(item => item.id === action.payload.id); if (existingItem) { existingItem.quantity += 1; } else { state.items.push({ ...action.payload, quantity: 1 }); } state.totalItems = state.items.reduce((total, item) => total + item.quantity, 0); state.totalAmount = state.items.reduce((total, item) => total + (item.price * item.quantity), 0); }, removeItem: (state, action: PayloadAction<number>) => { state.items = state.items.filter(item => item.id !== action.payload); state.totalItems = state.items.reduce((total, item) => total + item.quantity, 0); state.totalAmount = state.items.reduce((total, item) => total + (item.price * item.quantity), 0); }, updateQuantity: (state, action: PayloadAction<{ id: number; quantity: number }>) => { const item = state.items.find(item => item.id === action.payload.id); if (item) { item.quantity = action.payload.quantity; state.totalItems = state.items.reduce((total, item) => total + item.quantity, 0); state.totalAmount = state.items.reduce((total, item) => total + (item.price * item.quantity), 0); } }, clearCart: (state) => { state.items = []; state.totalItems = 0; state.totalAmount = 0; }, toggleCart: (state) => { state.isOpen = !state.isOpen; }, }, }); export const { addItem, removeItem, updateQuantity, clearCart, toggleCart } = cartSlice.actions; export default cartSlice.reducer;
defmodule HelloDockerHerokuWeb.ChannelCase do @moduledoc """ This module defines the test case to be used by channel tests. Such tests rely on `Phoenix.ChannelTest` and also import other functionality to make it easier to build common data structures and query the data layer. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with channels use Phoenix.ChannelTest # The default endpoint for testing @endpoint HelloDockerHerokuWeb.Endpoint end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(HelloDockerHeroku.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(HelloDockerHeroku.Repo, {:shared, self()}) end :ok end end
package main import ( "fmt" "fyne.io/fyne/v2/widget" "time" ) // Timer struct for managing game timer. type Timer struct { ticker *time.Ticker startTime time.Time timeElapsedLabel *widget.Label } // NewTimer creates a new Timer instance with a label for displaying time. func NewTimer(label *widget.Label) *Timer { return &Timer{ timeElapsedLabel: label, } } // Start begins or resumes the timer. func (t *Timer) Start() { if t.ticker != nil { return // Timer is already running } t.startTime = time.Now() t.ticker = time.NewTicker(time.Second) go func() { for range t.ticker.C { elapsed := time.Since(t.startTime) t.timeElapsedLabel.SetText(fmt.Sprintf("Time: %v", elapsed.Round(time.Second))) } }() } // Stop halts the timer. func (t *Timer) Stop() { if t.ticker != nil { t.ticker.Stop() t.ticker = nil } } // Reset stops the current timer and starts it anew. func (t *Timer) Reset() { t.Stop() t.Start() } // Additional methods for handling timer functionalities // ...
#+TITLE: Automatic darkmode for iTerm [[file:iterm2.org][iTerm2]] supports dark and light mode, but it won't change the colors automatically. But we're lucky! iTerm has great scripting support. See the [[https://iterm2.com/documentation-scripting.html][Scripting Documentation]]. We can use that to automatically switch profiles based on the system appearance. Here's how: 1. Launch iTerm, then in the menubar click =Scripts= → =AutoLaunch= → =Install Python runtime= 2. Create two profiles and name them =Light= and =Dark=. It probably makes sense to create one profile to your liking with a light theme, duplicate it and set the dark theme on the duplicate. 3. Copy the script below into ~$HOME/Library/ApplicationSupport/iTerm2/Scripts/AutoLaunch/auto_darkmode.py~: #+begin_src python #!/usr/bin/env python3.7 import asyncio import time import subprocess import iterm2 def is_dark_mode(): cmd = 'defaults read -g AppleInterfaceStyle' p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) return bool(p.communicate()[0]) async def set_profile(connection): app = await iterm2.async_get_app(connection) profile = "Light" if is_dark_mode(): profile = "Dark" partialProfiles = await iterm2.PartialProfile.async_query(connection) for partial in partialProfiles: if partial.name == profile: full = await partial.async_get_full_profile() # Set profile in _all_ sessions for window in app.terminal_windows: for tab in window.tabs: for session in tab.sessions: await session.async_set_profile(full) return async def main(connection): await set_profile(connection) while True: time.sleep(2) await set_profile(connection) iterm2.run_forever(main) #+end_src If you run into issues, try running the script via the menubar =Scripts= → =AutoLaunch= → =auto_darkmode.py= Similar to [[file:automatic-darkmode-for-vim.org][Automatic darkmode for Vim]], this will check the system appearance every two seconds and set the profile accordingly.
class Solution: # O(log(n)) time | O(1) space def searchInsert(self, nums: List[int], target: int) -> int: left = 0 right = len(nums) while left < right: middle = (left + right) // 2 num = nums[middle] if num < target: left = middle + 1 elif num > target: right = middle else: return middle return left
import React from "react"; import DevelopersPage from "./pages/Developers"; const User = React.lazy(() => import("./pages/User")); const About = React.lazy(() => import("./pages/About")); const Home = React.lazy(() => import("./pages/Home")); interface IRoutes { path: string; Element: React.ReactNode; protected?: boolean; } const routes: IRoutes[] = [ { path: "/users", Element: <User/>, // Auth pages protected: true, }, { path: "/about", Element: <About />, }, { path: "/developers", Element: <DevelopersPage /> }, { path: "/", Element: <Home />, }, ]; export default routes;
import React, {useEffect} from 'react'; import {Button, Container, Image, Nav, Navbar, NavLink} from "react-bootstrap"; import logo from '../../assets/images/logo_evernote.png'; const Header = () => { const [loggedIn, setLoggedIn] = React.useState(false); useEffect(() => { const getUser = localStorage.getItem('user'); if (getUser) { return setLoggedIn(true) } }, []); const handleLogout = () => { localStorage.removeItem('user'); window.location.href = '/auth/login'; } return ( <Navbar className="navbar navbar-expand-lg navbar-dark bg-dark"> <Container fluid={true} className="mx-2"> <Navbar.Brand> <NavLink className="navbar-brand" href="/"> <Image src={logo} alt="logo" width={40} /> Evernote Clone </NavLink> </Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav" className="justify-content-end"> <Nav className="mr-auto"> {loggedIn ? ([ <Button variant="outline-success" onClick={handleLogout} key={0}>Logout</Button>, <Nav.Link href="/notes" className="text-light" key={1}>Notes</Nav.Link> ] ) : ( [ <Button variant="outline-success" href="/auth/register" key={0}>Register</Button>, <Nav.Link href="/auth/login" className="text-light" key={1}>Login</Nav.Link> ] ) } </Nav> </Navbar.Collapse> </Container> </Navbar> ) } export default Header;
import React, { useState, Fragment } from "react"; import { nanoid } from "nanoid"; import "./Companystats.css"; import EditableRow from "./EditableRow"; import ReadOnlyRow from "./ReadOnlyRow"; import axios from "axios"; import { useEffect } from "react"; import { stream } from "xlsx"; import { useSelector } from "react-redux"; import exportFromJSON from 'export-from-json'; const Companystats = () => { const [flag,setFlag]= useState(false); const [contacts, setContacts] = useState({}); const [active,isActive] = useState(false); const [editFormData, setEditFormData] = useState({ company_id: "", company_name: "", location: "", email_id: "", enquiry_no:"", list:"" }); const [editContactId, setEditContactId] = useState(null); const info = useSelector((state) => state.User.info); useEffect(async() => { const res=await axios.get('http://127.0.0.1:8000/company/add'); console.log(res.data); setContacts(res.data); setFlag(true); console.log(typeof(contacts)) }, []) const handleEditFormChange = (event) => { event.preventDefault(); const fieldName = event.target.getAttribute("name"); const fieldValue = event.target.value; const newFormData = { ...editFormData }; newFormData[fieldName] = fieldValue; setEditFormData(newFormData); }; const handleEditFormSubmit = async (event) => { event.preventDefault(); const editedContact = { company_id: editFormData.company_id, company_name: editFormData.company_name, location: editFormData.location, email_id: editFormData.email_id, enquiry_no:editFormData.enquiry_no, list:editFormData.list }; const newContacts = [...contacts]; const index = contacts.findIndex((contact) => contact.company_id === editContactId); newContacts[index] = editedContact; console.log(newContacts[index].company_id); const pk =newContacts[index].company_id setEditContactId(null); const req=await axios.put('http://127.0.0.1:8000/company/edit/'+pk,editedContact,{headers: { "Authorization" : `Token ${info.token}` }}); if (req.status==200) setContacts(newContacts); console.log(req); }; const handleEditClick = (event, contact) => { event.preventDefault(); setEditContactId(contact.company_id); const formValues = { company_id: contact.company_id, company_name: contact.company_name, location: contact.location, email_id: contact.email_id, enquiry_no:contact.enquiry_no, list:contact.list }; setEditFormData(formValues); }; const handleCancelClick = () => { setEditContactId(null); }; const handleDeleteClick = async(contactId) => { const newContacts = [...contacts]; const index = contacts.findIndex((contact) => contact.company_id === contactId); newContacts.splice(index, 1); const req= await axios.delete('http://127.0.0.1:8000/company/delete/'+contactId,{headers: { "Authorization" : `Token ${info.token}` }}); console.log(req); setContacts(newContacts); console.log(typeof(contacts)) }; const handlePrint =()=>{ isActive(true); setTimeout(printReport,300); } const printReport=()=>{ window.print(); isActive(false); } const handleCSV = async() =>{ const res=await axios.get('http://127.0.0.1:8000/company/add'); var data =res.data; const fileName = 'download' const exportType = 'csv' exportFromJSON({ data, fileName, exportType }) } return ( <div className="app-container"> <h1 className="stats_head">Company Stats <button className={active ? "remove-action" : "print_button"} onClick={handlePrint}>Print</button><button className={active ? "remove-action" : "print_button"} onClick={handleCSV}>CSV</button></h1> <form className="stats_form" onSubmit={handleEditFormSubmit}> <table className="stats_table"> <thead> <tr> <th>Company ID</th> <th>Company Name</th> <th>Location</th> <th>Email</th> <th>Enquiry No</th> <th>Contributions</th> <th className={active ? "remove-action" : "action"}>Actions</th> </tr> </thead> <tbody> {flag && contacts.map((contact) => ( <Fragment> {editContactId === contact.company_id ? ( <EditableRow editFormData={editFormData} handleEditFormChange={handleEditFormChange} handleCancelClick={handleCancelClick} /> ) : ( <ReadOnlyRow active={active} contact={contact} handleEditClick={handleEditClick} handleDeleteClick={handleDeleteClick} /> )} </Fragment> ))} </tbody> </table> </form> </div> ); }; export default Companystats;
import curses from curses import textpad import socket import threading import time import sys from board import Board from audio_system import Background_music from client_protocol import Protocol_client from enums import Squares as sq from enums import Directions as dir from enums import ChangeVolume as vol from enums import PlayerCaracters as pchar from visual_effects.snow_screen import display_snow from visual_effects.fire_screen import display_fire from consts import * strDir = { '0' : dir.RIGHT, '1' : dir.UP, '2' : dir.LEFT, '3' : dir.DOWN } dirStr = { dir.RIGHT : '0', dir.UP : '1', dir.LEFT : '2', dir.DOWN : '3' } strPlayer = { '1' : sq.P1, '2' : sq.P2 } playerStr = { sq.P1 : '1', sq.P2 : '2' } intPchar = { 0 : pchar.OP1, 1 : pchar.OP2, 2 : pchar.OP3, 3 : pchar.OP4 } pcharInt = { pchar.OP1 : 0, pchar.OP2 : 1, pchar.OP3 : 2, pchar.OP4 : 3 } class Game: def __init__( self, port ): self.running = True self.loser = sq.EMPTY self.ip = socket.gethostbyname( socket.gethostname() ) self.port = port self.addr = ( self.ip, self.port ) self.conn = socket.socket() self.player = sq.EMPTY self.lock = threading.Lock() self.screen_idx = 0 self.screens = [ self.menu, self.waiting, self.settings, self.quit, self.start, self.end ] self.back_music = Background_music( DEFAULT_VOLUME ) self.volume = DEFAULT_VOLUME self.pchar = pchar.OP1 def update_direction( self, new_direction ): self.b.set_direction( new_direction, who=self.player ) def send_move( self ): protocol = Protocol_client( destination=self.player, direction=int( dirStr[ self.b.get_direction( who=self.player ) ] ), who=self.player ) protocol_msg = playerStr[ self.player ] + str( protocol ) self.lock.acquire() self.conn.send( protocol_msg.encode('utf-8') ) self.lock.release() def process_input( self, msg ): dir_idx = strDir[ msg[1] ] who_moved = strPlayer[ msg[2] ] end_game = True game_status = self.b.move( who_moved, dir_idx ) if( game_status == 1 ): end_game = False self.running = not end_game if( end_game ): self.loser = who_moved def handle_input( self ): while( self.running ): bytes_received = 0 server_msg = "" while( bytes_received < PROTOCOL_SIZE ): tmp_msg = self.conn.recv( PROTOCOL_SIZE ) tmp_msg = tmp_msg.decode('utf-8') bytes_received += len(tmp_msg) server_msg += tmp_msg self.process_input( server_msg ) def assign_player( self, msg ): self.player = strPlayer[ msg[0] ] def set_game( self ): curses.start_color() curses.curs_set( 0 ) curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE) curses.init_pair(4,curses.COLOR_GREEN,curses.COLOR_BLACK) def menu_window( self, screen ): self.set_game() self.back_music.play(0) screen.nodelay( False ) k = 0 height, width = screen.getmaxyx() start_y_first_button = int(height // 12) cursor_x = (width // 2) - ( 1 - (width % 2) ) cursor_y = 0 first_start_y = 9 while ( k != ord('\n') ): screen.clear() if k == curses.KEY_DOWN: cursor_y = cursor_y + 5 elif k == curses.KEY_UP: cursor_y = cursor_y - 5 cursor_x = max(0, cursor_x) cursor_x = min(width-1, cursor_x) cursor_y = max(first_start_y, cursor_y) cursor_y = min(first_start_y + ( ( N_BUTTONS - 1 ) * 5 ), cursor_y) choicebutton = [] for i in range(N_BUTTONS): if ( i == ( ( cursor_y - first_start_y ) / 5 ) ): choicebutton.append("X") else: choicebutton.append(" ") # Declaration of strings title = "[TRON]"[:width-1] subtitle = "Feito por PBPJ, Ganso e Pinkuschu"[:width-1] statusbarstr = "Press 'q' to exit | STATUS BAR | Pos: {}, {}".format(cursor_x, cursor_y) button = [] button.append( "Conectar ao Jogo"[:width-1] ) button.append( "Configurações"[:width-1] ) button.append( "Sair"[:width-1] ) # Getting the max len between all buttons max_len_of_button = 0 for butt in button: max_len_of_button = max ( max_len_of_button, len(butt) ) for i in range( len(button) ): spacestr = ( (max_len_of_button - len(button[i]) + 1) // 2 ) * " " button_size = 3 + 2*len( spacestr ) + len( button[i] ) # Centering calculations start_x_title = int((width // 2) - (len(title) // 2) - len(title) % 2) start_x_subtitle = int((width // 2) - (len(subtitle) // 2) - len(subtitle) % 2) start_y = int((height // 5) - 2) start_x_text = [] for i in range(N_BUTTONS): start_x_text.append( int((width // 2) - (len(button[i]) // 2) - (len(button[i]) % 2)) ) start_x_button = int((width // 2) - (max_len_of_button // 2) - (max_len_of_button % 2)) - 2 start_y_first_button = start_y + 3 whstr = "Width: {}, Height: {}".format(width, height) screen.addstr(0, 0, whstr, curses.color_pair(1)) # Render status bar screen.attron(curses.color_pair(3)) screen.addstr(height-1, 0, statusbarstr) screen.addstr(height-1, len(statusbarstr), " " * (width - len(statusbarstr) - 1)) screen.attroff(curses.color_pair(3)) # Turning on attributes for title screen.attron(curses.color_pair(2)) screen.attron(curses.A_BOLD) # Rendering title screen.addstr(start_y, start_x_title, title) # Turning off attributes for title screen.attroff(curses.color_pair(2)) screen.attroff(curses.A_BOLD) # Print rest of text screen.addstr(start_y + 1, start_x_subtitle, subtitle) for i in range( len(button) ): textpad.rectangle(screen, start_y_first_button + (i*5), start_x_button , start_y_first_button + (i*5) + 3, start_x_button + button_size ) if choicebutton[i] == "X": screen.attron(curses.color_pair(3)) screen.addstr( start_y_first_button + (i*5) + 1, start_x_text[i], button[i] ) screen.addstr( start_y_first_button + (i*5) + 2, (width // 2) - ( 1 - (width % 2) ) - 1, ( "[" + choicebutton[i] + "]") ) if choicebutton[i] == "X": screen.attroff(curses.color_pair(3)) screen.move(cursor_y, cursor_x) screen.refresh() k = screen.getch() screen.clear() screen.refresh() index = ( cursor_y - first_start_y ) / 5 return int( index ) + 1 def waiting_window( self, screen ): self.back_music.play(1) self.conn.connect( self.addr ) screen.nodelay( True ) k = 0 ready = False height, width = screen.getmaxyx() waitstr = "Aguardando o 2o Jogador se Conectar..." exitqstr = "Pressione 'q' para cancelar a CONEXAO" start_x_wait = int((width // 2) - (len(waitstr) // 2) - (len(waitstr) % 2)) - 2 start_x_exit = int((width // 2) - (len(exitqstr) // 2) - (len(exitqstr) % 2)) - 2 while ( not ready and k != ord('q') ): screen.clear() textpad.rectangle(screen, height // 2 - 1, start_x_wait-1, height // 2 + 1, start_x_wait + len(waitstr) ) screen.addstr( height // 2, start_x_wait, waitstr ) screen.addstr( 2*height // 3, start_x_exit, exitqstr ) k = screen.getch() screen.refresh() msg = self.conn.recv( 4 ) msg = msg.decode( 'utf-8' ) if(len(msg) != 0): screen.clear() textpad.rectangle(screen, height // 2 - 1, start_x_wait-1, height // 2 + 1, start_x_wait + len(waitstr) ) screen.addstr( height // 2, start_x_wait + 10, "Jogadores conectados" ) screen.addstr( 2*height // 3, start_x_exit + 15, "Prepare-se" ) screen.refresh() curses.napms(500) self.assign_player( msg ) ready = True return 4 def game_window( self, screen ): self.b = Board( N ) self.set_game() screen.keypad( True ) screen.nodelay( True ) self.render( screen ) key_pressed = 0 thread = threading.Thread(target=self.handle_input) thread.name = "server_io" thread.start() acc = 0.0 while( self.running ): t1 = time.time() key_pressed = screen.getch() if( key_pressed == -1 ): pass elif(key_pressed == curses.KEY_UP): screen.addch(1, 0, '^') self.update_direction( dir.UP ) self.send_move() elif(key_pressed == curses.KEY_RIGHT): screen.addch(1, 0, '>') self.update_direction( dir.RIGHT ) self.send_move() elif(key_pressed == curses.KEY_LEFT): screen.addch(1, 0, '<') self.update_direction( dir.LEFT ) self.send_move() elif(key_pressed == curses.KEY_DOWN): screen.addch(1, 0, 'v') self.update_direction( dir.DOWN ) self.send_move() dt = time.time() - t1 acc += dt if( acc >= 1.0/FPS ): self.render( screen ) acc = 0.0 return 5 def winner_window( self, screen ): display_fire( screen ) return 0 def loser_window( self, screen ): self.back_music.play(2) display_snow( screen ) return 0 def change_volume( self, change ): if change == vol.DECREASE: self.volume = self.volume - 1 self.volume = max( MIN_VOLUME, self.volume ) elif change == vol.INCREASE: self.volume = self.volume + 1 self.volume = min( MAX_VOLUME, self.volume ) elif change == vol.MUTE and self.volume >= 0: self.volume = self.volume * ( -1 ) elif change == vol.DESMUTE and self.volume <= 0: self.volume = self.volume * ( -1 ) self.back_music.set_volume( self.volume ) def settings_window( self, screen ): self.set_game() screen.nodelay( False ) k = 0 height, width = screen.getmaxyx() start_y_first_button = int(height // 12) cursor_x = (width // 2) - ( 1 - (width % 2) ) cursor_y = 0 first_start_y = 9 while ( k != ord('\n') ): screen.clear() if k == curses.KEY_DOWN: cursor_y = cursor_y + 5 elif k == curses.KEY_UP: cursor_y = cursor_y - 5 elif cursor_y == first_start_y: if k == curses.KEY_LEFT: self.change_volume( vol.DECREASE ) elif k == curses.KEY_RIGHT: self.change_volume( vol.INCREASE ) elif cursor_y == first_start_y + 5: if k == curses.KEY_LEFT and pcharInt[ self.pchar ] != 0: self.pchar = intPchar[ pcharInt[ self.pchar ] - 1 ] elif k == curses.KEY_RIGHT and pcharInt[ self.pchar ] != (CHAR_OPTIONS - 1): self.pchar = intPchar[ pcharInt[ self.pchar ] + 1 ] cursor_y = max(first_start_y, cursor_y) cursor_y = min(first_start_y + ( ( N_CONFIG - 1 ) * 5 ), cursor_y) choicebutton = [] for i in range(N_CONFIG): if ( i == ( ( cursor_y - first_start_y ) / 5 ) ): choicebutton.append("X") else: choicebutton.append(" ") # Declaration of strings title = "[TRON]"[:width-1] subtitle = "Configuracoes do Usuario"[:width-1] statusbarstr = "Press 'q' to exit | STATUS BAR | Pos: {}, {}".format(cursor_x, cursor_y) button = [] button.append( "Ajustar volume do audio: " + str(self.volume) + "."[:width-1] ) button.append( "Alterar caracter do personagem:"[:width-1] ) button.append( "Retornar ao Menu"[:width-1] ) # Getting the max len between all buttons max_len_of_button = 0 for butt in button: max_len_of_button = max ( max_len_of_button, len(butt) ) for i in range( len(button) ): spacestr = ( (max_len_of_button - len(button[i]) + 1) // 2 ) * " " button_size = 3 + 2*len( spacestr ) + len( button[i] ) # Centering calculations start_x_title = int((width // 2) - (len(title) // 2) - len(title) % 2) start_x_subtitle = int((width // 2) - (len(subtitle) // 2) - len(subtitle) % 2) start_y = int((height // 5) - 2) start_x_text = [] for i in range(N_CONFIG): start_x_text.append( int((width // 2) - (len(button[i]) // 2) - (len(button[i]) % 2)) ) start_x_button = int((width // 2) - (max_len_of_button // 2) - (max_len_of_button % 2)) - 2 start_y_first_button = start_y + 3 whstr = "Width: {}, Height: {}".format(width, height) screen.addstr(0, 0, whstr, curses.color_pair(1)) # Render status bar screen.attron(curses.color_pair(3)) screen.addstr(height-1, 0, statusbarstr) screen.addstr(height-1, len(statusbarstr), " " * (width - len(statusbarstr) - 1)) screen.attroff(curses.color_pair(3)) # Turning on attributes for title screen.attron(curses.color_pair(2)) screen.attron(curses.A_BOLD) # Rendering title screen.addstr(start_y, start_x_title, title) # Turning off attributes for title screen.attroff(curses.color_pair(2)) screen.attroff(curses.A_BOLD) # Print rest of text screen.addstr(start_y + 1, start_x_subtitle, subtitle) for i in range( len(button) ): textpad.rectangle(screen, start_y_first_button + (i*5), start_x_button , start_y_first_button + (i*5) + 3, start_x_button + button_size ) if choicebutton[i] == "X": screen.attron(curses.color_pair(3)) screen.addstr( start_y_first_button + (i*5) + 1, start_x_text[i], button[i] ) if i == 0: volume_bar = "[" + ( "x" * self.volume ) + ( " " * ( MAX_VOLUME - self.volume ) ) + "]" screen.addstr( start_y_first_button + (i*5) + 2, int((width // 2) - (len(volume_bar) // 2) - (len(volume_bar) % 2)), volume_bar ) elif i == 1: char_choice = "" for j in range( CHAR_OPTIONS ): if self.pchar == intPchar[ j ]: char_choice = char_choice + "[" else: char_choice = char_choice + " " char_choice = char_choice + intPchar[ j ].value if self.pchar == intPchar[ j ]: char_choice = char_choice + "] " else: char_choice = char_choice + " " screen.addstr( start_y_first_button + (i*5) + 2, #int((width // 2) - (len(char_choice) // 2) - (len(char_choice) % 2)) - ( 4 * ), int((width // 2) - (len(char_choice) % 2)) - ( 4 * pcharInt[ self.pchar ]) - 2, char_choice ) elif i == 2: screen.addstr( start_y_first_button + (i*5) + 2, (width // 2) - ( 1 - (width % 2) ) - 1, ( "[" + choicebutton[i] + "]") ) if choicebutton[i] == "X": screen.attroff(curses.color_pair(3)) screen.move(cursor_y, cursor_x) screen.refresh() k = screen.getch() screen.clear() screen.refresh() return 0 def quit_window( self, screen ): self.set_game() screen.clear() screen.addstr(20, 20, "bye :)") screen.refresh() curses.napms( 2000 ) def render( self, screen ): t1 = time.time() screen.erase() sh, sw = screen.getmaxyx() box = [ [ 3, 3 ], [ sh - 3, sw - 3 ] ] textpad.rectangle( screen, box[0][0], box[0][1], box[1][0], box[1][1] ) y_start, x_start = sh // 2 - N // 2, sw // 2 - (2*N-1) // 2 y, x = y_start, x_start for line in self.b.board: for element in line: if element == sq.EMPTY: screen.addch(y,x,element.value, curses.color_pair(1)) elif element == sq.P1: screen.addch(y,x,self.pchar.value, curses.color_pair(2)) elif element == sq.P2: screen.addch(y,x,self.pchar.value, curses.color_pair(4)) x += 2 x = x_start y += 1 dt = time.time() - t1 screen.addstr(0, 0, str(dt)) screen.refresh() def run( self ): while( True ): next_idx = self.screens[ self.screen_idx ]() self.screen_idx = next_idx def menu( self ): return curses.wrapper( self.menu_window ) def waiting( self ): return curses.wrapper( self.waiting_window ) def start( self ): return curses.wrapper( self.game_window ) def disconnect( self ): self.conn.send( b"****" ) self.conn.close() def end( self ): self.disconnect() if( self.loser == self.player ): return curses.wrapper( self.loser_window ) else: return curses.wrapper( self.winner_window ) def quit( self ): curses.wrapper( self.quit_window ) sys.exit() def settings( self ): return curses.wrapper( self.settings_window ) def main(): g = Game(5050) g.start() if __name__ == '__main__': main()
# 智能BI项目文档 ## 项目效果预览 登录界面 ![image-20231018163437013](https://github.com/Liumingyao666/github-img/blob/master/img/image-20231018163437013.png?raw=true) 智能分析界面 ![image-20231018163608684](https://github.com/Liumingyao666/github-img/blob/master/img/image-20231018163608684.png?raw=true) 智能分析(异步)界面 ![image-20231018163652897](https://github.com/Liumingyao666/github-img/blob/master/img/image-20231018163652897.png?raw=true) 异步任务会给前端一个状态(图表生成中),在图表管理页面可以预览生成状态,等待AICG平台处理。 ![image-20231018163742361](https://github.com/Liumingyao666/github-img/blob/master/img/image-20231018163742361.png?raw=true) 图表管理页面 查看已生成的表格 ![image-20231018163823936](https://github.com/Liumingyao666/github-img/blob/master/img/image-20231018163823936.png?raw=true) ## 项目介绍 BI(商业智能):数据可视化,报表可视化系统 主流BI平台:帆软BI,小马BI,微软Power BI 传统BI平台: 1. 需要人工上传数据 2. 需要人工托选分析要用到的数据行和列(数据分析师) 3. 需要人工选择图表类型(数据分析师) 4. 生成图表并保存配置 智能BI平台: 区别于传统的BI,用户(数据分析者)只需要导入最原始的数据集,输入想要进行分析的目标(比如帮我分析一下网站的增长趋势),就能利用AI自动生成一个符合要求的图标以及结论。 优点:让不会数据分析的同学也能通过输入目标快速完成数据分析,大幅节约人力成本。 会用到AI接口。 ## 需求分析 1. 智能分析:用户输入目标和原始数据(图表类型),可以自动生成图表和分析结论 2. 图表管理 3. 图表生成的异步化(消息队列) 4. 对接AI能力 ## 架构图 基础流程:客户端输入分析诉求和原始数据,向业务后端发送请求。业务后端利用 AI 服务处理客户端数据,保持到数据库,并生成图表。处理后的数据由业务后端发送给 AI 服务,AI 服务生成结果并返回给后端,最终将结果返回给客户端展示。 ![image-20231005150042006](D:\liumingyao\study\文档\智能BI项目文档.assets\image-20231005150042006.png) 假设一个 AI 服务生成图表和分析结果要等 50 秒,如果有大量用户需要生成图表,每个人都需要等待 50 秒,那么 AI 服务可能无法承受这种压力。为了解决这个问题,可以采用消息队列技术。通过消息队列,用户可以提交生成图表的请求,这些请求会进入队列,AI 服务会依次处理队列中的请求,从而避免了同时处理大量请求造成的压力,同时也能更好地控制资源的使用。 优化流程(异步化):客户端输入分析诉求和原始数据,向业务后端发送请求。业务后端将请求事件放入消息队列,并为客户端生成取餐号,让要生成图表的客户端去排队,消息队列根据 AI 服务负载情况,定期检查进度,如果 AI 服务还能处理更多的图表生成请求,就向任务处理模块发送消息。 任务处理模块调用 AI 服务处理客户端数据,AI 服务异步生成结果返回给后端并保存到数据库,当后端的 AI 服务生成完毕后,可以通过向前端发送通知的方式,或者通过业务后端监控数据库中图表生成服务的状态,来确定生成结果是否可用。若生成结果可用,前端即可获取并处理相应的数据,最终将结果返回给客户端展示。(在此期间,用户可以去做自己的事情) ![image-20231005150112288](D:\liumingyao\study\文档\智能BI项目文档.assets\image-20231005150112288.png) ## 技术栈 前端 1. React 2. Umi + Ant Design Pro 3. 可视化开发库(Echarts + HighCharts + AntV) 4. umi openapi代码生成(自动生成后端调用代码) 后端: 1. Spring Boot(万用Java后端项目模板,快速搭建基础框架 https://github.com/Liumingyao666/springboot-init) 2. MySQL数据库 3. MyBatis Plus数据访问框架 4. 消息队列 RabbitMQ 5. AI能力 6. Excel的上传和数据的解析(Easy Excel) 7. Swagger + Knife4j项目接口文档 8. Hutool工具库 ## 项目计划 ### Day 1 前端项目初始化 后端项目初始化 前端开发 - 快速开发登录功能 - 图标分析页面的开发 - 图标管理页面的开发 后端开发 - 库表设计 - 图表管理开发 - 文件上传接口开发 前后端业务流程跑通 #### 前端项目初始化 官方文档:https://pro.ant.design/ Node.js18版本 1. 官网下载:https://nodejs.org/en (选则LTS稳定版本) 2. **nvm工具可以快捷切换node.js版本** https://nvm.uihtm.com/download.html ​ 安装node.js版本 ​ `nvm -v` 查看nvm版本 ​ `nvm list available`显示可下载版本的部分列表 ​ `nvm install latest`安装最新版本 ​ `nvm install` 版本号 安装指定的node.js版本 ​ `nvm list`或`nvm ls`查看目前已经安装的版本 ​ `nvm use`版本号 使用指定版本的node.js nvm切换国内镜像 (切换之后再安装nodejs) 阿里云镜像 ~~~bash nvm npm_mirror https://npmmirror.com/mirrors/npm/ nvm node_mirror https://npmmirror.com/mirrors/node/ ~~~ 腾讯云镜像 ~~~ nvm npm_mirror http://mirrors.cloud.tencent.com/npm/ nvm node_mirror http://mirrors.cloud.tencent.com/nodejs-release/ ~~~ 步骤: 1. 按照官方文档初始化 2. 项目试允许(npm run dev/start) 3. 代码托管 4. 移除不需要的能力(比如国际化) 移除国际化问题解决: > 任何开源项目的报错,都可以直接问作者(官方团队)或者搜 github issues 区 > > 1. 找到开源地址:https://github.com/ant-design/ant-design-pro > 2. 搜索issues:https://github.com/ant-design/ant-design-pro/issues/10452 > 3. 前端本地执行:yarn add eslint-config-prettier --dev yarn add eslint-plugin-unicorn --dev > 4. 修改 node_modules/@umijs/lint/dist/config/eslint/index.js, 注释掉 es2022 路由不显示名称 > 给 config/route.ts 的路由加 name #### 后端初始化 使用后端项目模板: https://github.com/Liumingyao666/springboot-init 用法参考README.md,默认情况下只要执行 create_table.sql 文件创建数据库表,然后修改 application.yml 中的数据库地址为你自己的数据库即可。 端口占用问题 > 查看进程 > > netstat -ano|findstr xxx > > 关闭进程 > > taskkill -pid xxx-f #### 库表设计 --图表信息表 ~~~sql -- 图表表 create table if not exists chart ( id bigint auto_increment comment 'id' primary key, goal text null comment '分析目标', chartData text null comment '图表数据', chartType varchar(128) null comment '图表类型', genChart text null comment '生成的图表数据', genResult text null comment '生成的分析结论', userId bigint null comment '创建用户 id', createTime datetime default CURRENT_TIMESTAMP not null comment '创建时间', updateTime datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', isDelete tinyint default 0 not null comment '是否删除' ) comment '图表信息表' collate = utf8mb4_unicode_ci; ~~~ #### 前后端基础开发 1. 图表信息的crud 2. 前端调用后端: 使用 ant design pro 自带的 openapi 工具,根据后端的 swagger 接口文档数据自动生成对应的请求 service 代码。 ~~~js openAPI: [ { requestLibPath: "import { request } from '@umijs/max'", // 或者使用在线的版本 schemaPath: "http://localhost:8101/api/v2/api-docs", projectName: 'yubi', // schemaPath: join(__dirname, 'oneapi.json'), mock: false, }, ~~~ 注意:前端须更改对应的请求地址为你的后端地址,方法:在 app.tsx 里修改 request.baseURL ~~~js /** * app.tsx文件 * @name request 配置,可以配置错误处理 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。 * @doc https://umijs.org/docs/max/request#配置 */ export const request = { baseURL: 'http://localhost:8101', withCredentials: true, ...errorConfig, }; ~~~ ### Day2 #### 后端启动项目端口冲突问题解决 原因:Windows Hyper-V 虚拟化平台占用了端口 先使用:netsh interface ipv4 show excludedportrange protocol=tcp 查看被占用的端口,然后选择一个没被占用的端口启动项目 #### 智能分析业务开发 业务流程: 1. 用户输入 - 分析目标 - 上传原始数据(excel) - 更精细化的控制图表:比如图表类型,图表名称等 2. 后端校验 - 校验用户的输入是否合法(比如长度) - 成本控制(次数统计和校验,鉴权等) 3. 把处理后的数据输入给AI模型(调用AI接口),让AI模型给我们提供图标信息,结论文本 4. 调用时加系统预设(提前告诉他职责、功能、回复格式要求) + 分析目标 + 压缩后的数据 5. 图标信息(是一段json配置,是一段代码),结论文本在前端进行展示 #### 使用csv对excel文件的数据进行提取和压缩 开源库:https://easyexcel.opensource.alibaba.com/docs/current/ ~~~java /** * excel 转 csv * * @param multipartFile * @return */ public static String excelToCsv(MultipartFile multipartFile){ // File file = null; // try { // file = ResourceUtils.getFile("classpath:网站数据.xlsx"); // } catch (FileNotFoundException e) { // throw new RuntimeException(e); // } // 读取数据 List<Map<Integer, String>> list = null; try { list = EasyExcel.read(multipartFile.getInputStream()) .excelType(ExcelTypeEnum.XLSX) .sheet() .headRowNumber(0) .doReadSync(); } catch (IOException e) { log.error("excel读取失败", e); } if (CollUtil.isEmpty(list)) { return ""; } // 转化为csv StringBuilder stringBuilder = new StringBuilder(); // 读取表头 LinkedHashMap<Integer, String> headerMap = (LinkedHashMap<Integer, String>) list.get(0); List<String> headerList = headerMap.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList()); stringBuilder.append(StringUtils.join(headerList, ",")).append("\n"); // 读取数据 for (int i = 1; i < list.size(); i++) { LinkedHashMap<Integer, String> dataMap = (LinkedHashMap<Integer, String>) list.get(i); List<String> dataList = dataMap.values().stream().filter(data -> ObjectUtils.isNotEmpty(data)).collect(Collectors.toList()); stringBuilder.append(StringUtils.join(dataList, ",")).append("\n"); } return stringBuilder.toString(); } ~~~ ~~~java /** * 智能分析 * * @param multipartFile * @param genChartByAiRequest * @param request * @return */ @PostMapping("/gen") public BaseResponse<String> genChartByAi(@RequestPart("file") MultipartFile multipartFile, GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) { String name = genChartByAiRequest.getName(); String goal = genChartByAiRequest.getGoal(); String chartType = genChartByAiRequest.getChartType(); // 校验 ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空"); ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名称过长"); // 用户输入 StringBuilder userInput = new StringBuilder(); userInput.append("你是一名数据分析师,接下来我会给你我的分析目标和原始数据,请告诉我分析结论").append("\n"); userInput.append("分析目标: ").append(goal).append("\n"); //压缩后的数据 String result = ExcelUtils.excelToCsv(multipartFile); userInput.append("原始数据: ").append(result).append("\n"); return ResultUtils.success(userInput.toString()); } ~~~ ### Day3 #### 3种AI调用方式 1. 直接调用官方接口 比如OpenAI或者其他AI原始大模型官网的接口 官方文档:https://platform.openai.com/docs/api-reference 优点:不经封装,最灵活,最原始 缺点:要钱,要魔法 本质上OpenAI就是提供了HTTP接口,我们可以用任何语言去调用 1)在请求头中指定OPENAI_API_KEY Authorization: Bearer OPENAI_API_KEY 2)找到你要使用的接口,比如 AI 对话接口:https://platform.openai.com/docs/api-reference/chat/create 3)按照接口文档的示例,构造 HTTP 请求,比如用 Hutool 工具类、或者 HTTPClient ~~~java /** * AI 对话(需要自己创建请求响应对象) * * @param request * @param openAiApiKey * @return */ public CreateChatCompletionResponse createChatCompletion(CreateChatCompletionRequest request, String openAiApiKey) { if (StringUtils.isBlank(openAiApiKey)) { throw new BusinessException(ErrorCode.PARAMS_ERROR, "未传 openAiApiKey"); } String url = "https://api.openai.com/v1/chat/completions"; String json = JSONUtil.toJsonStr(request); String result = HttpRequest.post(url) .header("Authorization", "Bearer " + openAiApiKey) .body(json) .execute() .body(); return JSONUtil.toBean(result, CreateChatCompletionResponse.class); } ~~~ 2. 使用云服务商提供的封装接口 比如:Azure云 优点:本地都能用 缺点:依然要钱,而且可能比调用原始接口更贵 3. 鱼聪明AI开发平台 鱼聪明 AI 提供了现成的 SDK 来让大家更方便地使用 AI 能力。 鱼聪明 AI 网站:https://yucongming.com/ 参考 sdk 项目文档快速使用:https://github.com/liyupi/yucongming-java-sdk #### 智能接口实现 后端流程 1. 构造用户请求(用户消息,csv数据, 图表类型) 2. 调用鱼聪明sdk,得到AI的响应结果 3. 从AI响应结果中,取出需要的信息 4. 保存图表到数据库 ### Day4 #### 系统优化 现在的网站足够安全吗? 1. 如果用户上传一个超大的文件怎么办? 2. 如果用户用科技疯狂点击提交,怎么办? 3. 如果AI的生成太慢(比如需要一分钟),又有很多用户要同时生成,给系统造成了压力,怎么兼顾用户体验和系统的可用性? 安全性 如果用户上传一个超大的文件怎么办?比如 1000 G? **只要涉及到用户自主上传的操作,一定要校验文件(图像)** 校验的维度: - 文件的大小 - 文件的后缀 - 文件的内容(成本要高一些) - 文件的合规性(比如敏感内容,建议用第三方的审核功能) ~~~java // 文件校验 long size = multipartFile.getSize(); String originalFilename = multipartFile.getOriginalFilename(); // 校验文件大小 final long ONE_MB = 1024 * 1024L; ThrowUtils.throwIf(size > ONE_MB, ErrorCode.PARAMS_ERROR, "文件超过1MB"); // 校验文件后缀 String suffix = FileUtil.getSuffix(originalFilename); final List<String> validFileSuffixList = Arrays.asList("xlsx", "xls"); ThrowUtils.throwIf(!validFileSuffixList.contains(suffix), ErrorCode.PARAMS_ERROR, "文件后缀非法"); ~~~ 扩展点:接入腾讯云的图片万象数据审核(COS 对象存储的审核功能) #### 数据存储 现状:我们把每个图表的原始数据全部存放在了同一个数据表(chart 表)的字段里。 问题: 1. 如果用户上传的原始数据量很大、图表数日益增多,查询 Chart 表就会很慢。 2. 对于 BI 平台,用户是有查看原始数据、对原始数据进行简单查询的需求的。现在如果把所有数据存放在一个 字段(列)中,查询时,只能取出这个列的所有内容。 解决方案 => 分库分表: 把每个图表对应的原始数据单独保存为一个新的数据表,而不是都存在一个字段里。 优点: 1. 存储时,能够分开存储,互不影响(也能增加安全性) 2. 查询时,可以使用各种sql语句灵活取出需要的字段,插叙性能更快 实现 分开存储: 1. 存储图表信息时,不把数据存储为字段,而是新建一个chart_{图表id} 的数据表 通过图表 id、数据列名、数据类型等字段,生成以下 SQL 语句,并且执行即可: ~~~sql -- auto-generated definition create table chart_1659210482555121666 ( 日期 int null, 用户数 int null ); ~~~ 分开查询 1. 以前直接查询图表,取 chartData 字段;现在改为读取 chart_{图表id} 的数据表 ~~~sql select * from chart_{1659210482555121666} ~~~ 具体实现:MyBatis的动态SQL(根据代码灵活的动态生成) 1. 想清楚哪些是需要动态替换的,比如要查询的数据表名 chart_{1659210482555121666} 2. 在 ChartMapper.xml 中定义 sql 语句 以下这种方式最灵活,但是要小心 SQL 注入风险: 比如:select * from chart_12345 where id = 1 or 1 = 1; ~~~xml <select id="queryChartData" parameterType="string" resultType="map"> ${querySql} </select> ~~~ 在 ChartMapper 中定义方法,方法名和上一步的 select 的 id 相同: ~~~java List<Map<String, Object>> queryChartData(String querySql); ~~~ 测试调用 ~~~java String chartId = "1659210482555121666"; String querySql = String.format("select * from chart_%s", chartId); List<Map<String, Object>> resultData = chartMapper.queryChartData(querySql); System.out.println(resultData); ~~~ 分库分表 - 水平分表 - 垂直分库在大型互联网应用中,为了应对高并发、海量数据等挑战,往往需要对数据库进行拆分。常见的拆分方式有水平分表和垂直分库两种。 水平分表(Sharding) 水平分表是将同一张表中的数据按一定的规则划分到不同的物理存储位置上,以达到分摊单张表的数据及访问压力的目的。对于SQL分为两类:id-based分表和range-based分表。 水平分表的优点: - 单个表的数据量减少,查询效率提高; - 可以通过增加节点,提高系统的扩展性和容错性。 水平分表的缺点: - 事务并发处理复杂度增加,需要增加分布式事务的管理,性能和复杂度都有所牺牲; - 跨节点查询困难,需要设计跨节点的查询模块。 垂直分库(Vertical Partitioning) 垂直分库,指的是根据业务模块的不同,将不同的字段或表分到不同的数据库中。垂直分库基于数据库内核支持,对应用透明,无需额外的开发代码,易于维护升级。 垂直分库的优点: - 减少单个数据库的数据量,提高系统的查询效率 - 增加了系统的可扩展性,比水平分表更容易实现。 垂直分库的缺点: - 不同数据库之间的维护和同步成本较高; - 现有系统的改造存在一定的难度; - 系统的性能会受到数据库之间互相影响的影响。 需要根据实际的业务场景和技术架构情况,综合考虑各种因素来选择适合自己的分库分表策略。 #### 限流 现在的问题:使用系统是需要消耗成本的,用户有可能疯狂刷量,让你破产。 解决问题: 1. 控制成本 => 限制用户调用总次数 2. 用户在短时间内疯狂使用,导致服务器资源被占满,其他用户无法使用 => 限流 思考限流阈值多大合适?参考正常用户的使用,比如限制单个用户在每秒只能使用 1 次。 限流的几种算法 建议阅读文章:https://juejin.cn/post/6967742960540581918 1)固定窗口限流 单位时间内允许部分操作 1 小时只允许 10 个用户操作 优点:最简单 缺点:可能出现流量突刺 比如:前 59 分钟没有 1 个操作,第 59 分钟来了 10 个操作;第 1 小时 01 分钟又来了 10 个操作。相当于 2 分钟内执行了 20 个操作,服务器仍然有高峰危险。 2)滑动窗口限流 单位时间内允许部分操作,但是这个单位时间是滑动的,需要指定一个滑动单位 比如滑动单位 1min: 开始前: 0s 1h 2h 一分钟后: 1min 1h1min 优点:能够解决上述流量突刺的问题,因为第 59 分钟时,限流窗口是 59 分 ~ 1小时 59 分,这个时间段内只能接受 10 次请求,只要还在这个窗口内,更多的操作就会被拒绝。 缺点:实现相对复杂,限流效果和你的滑动单位有关,滑动单位越小,限流效果越好,但往往很难选取到一个特别合适的滑动单位。 3)漏桶限流(推荐) 以 固定的速率 处理请求(漏水),当请求桶满了后,拒绝请求。 每秒处理 10 个请求,桶的容量是 10,每 0.1 秒固定处理一次请求,如果 1 秒内来了 10 个请求;都可以处理完,但如果 1 秒内来了 11 个请求,最后那个请求就会溢出桶,被拒绝。 优点:能够一定程度上应对流量突刺,能够固定速率处理请求,保证服务器的安全 缺点:没有办法迅速处理一批请求,只能一个一个按顺序来处理(固定速率的缺点) 4)令牌桶限流(推荐) 管理员先生成一批令牌,每秒生成 10 个令牌;当用户要操作前,先去拿到一个令牌,有令牌的人就有资格执行操作、能同时执行操作;拿不到令牌的就等着 优点:能够并发处理同时的请求,并发性能会更高 需要考虑的问题:还是存在时间单位选取的问题 限流粒度 1. 针对某个方法限流,即单位时间内最多允许同时 XX 个操作使用这个方法 2. 针对某个用户限流,比如单个用户单位时间内最多执行 XX 次操作 3. 针对某个用户 x 方法限流,比如单个用户单位时间内最多执行 XX 次这个方法 限流的实现 Redisson 内置了一个限流工具类,可以帮助你利用 Redis 来存储、来统计。 官方项目仓库和文档:https://github.com/redisson/redisson 步骤: 1. 引入 Redisson 代码包: ~~~xml <dependency> <groupId>org.redisson</groupId> <artifactId>redisson</artifactId> <version>3.21.3</version> </dependency> ~~~ 2. 创建 RedissonConfig 配置类,用于初始化 RedissonClient 对象单例: ~~~java @Configuration @ConfigurationProperties(prefix = "spring.redis") @Data public class RedissonConfig { private Integer database; private String host; private Integer port; private String password; @Bean public RedissonClient redissonClient() { Config config = new Config(); config.useSingleServer() .setDatabase(database) .setAddress("redis://" + host + ":" + port); RedissonClient redisson = Redisson.create(config); return redisson; } } ~~~ 3. 编写 RedisLimiterManager: 什么是 Manager?专门提供 RedisLimiter 限流基础服务的( 提供了通用的能力,可以放到任何一个项目里 ) ~~~java /** * 专门提供 RedisLimiter 限流基础服务的(提供了通用的能力) */ @Service public class RedisLimiterManager { @Resource private RedissonClient redissonClient; /** * 限流操作 * * @param key 区分不同的限流器,比如不同的用户 id 应该分别统计 */ public void doRateLimit(String key) { // 创建一个名称为user_limiter的限流器,每秒最多访问 2 次 RRateLimiter rateLimiter = redissonClient.getRateLimiter(key); rateLimiter.trySetRate(RateType.OVERALL, 2, 1, RateIntervalUnit.SECONDS); // 每当一个操作来了后,请求一个令牌 boolean canOp = rateLimiter.tryAcquire(1); if (!canOp) { throw new BusinessException(ErrorCode.TOO_MANY_REQUEST); } } } ~~~ 4. 单元测试: ~~~java @SpringBootTest class RedisLimiterManagerTest { @Resource private RedisLimiterManager redisLimiterManager; @Test void doRateLimit() throws InterruptedException { String userId = "1"; for (int i = 0; i < 2; i++) { redisLimiterManager.doRateLimit(userId); System.out.println("成功"); } Thread.sleep(1000); for (int i = 0; i < 5; i++) { redisLimiterManager.doRateLimit(userId); System.out.println("成功"); } } } ~~~ 5. 应用到要限流的方法中,比如智能分析接口: ~~~java User loginUser = userService.getLoginUser(request); // 限流判断,每个用户一个限流器 redisLimiterManager.doRateLimit("genChartByAi_" + loginUser.getId()); // 后续操作 xxxxx ~~~ ### Day5 1. 系统问题分析 2. 异步化业务流程分析 3. 线程池 4. 系统异步化改造开发 #### 系统问题分析 问题场景:调用的服务处理能力有限,或者接口的处理(或返回)时长较长时,就应该考虑异步化了。 1. 用户等待时间有点长(因为要等 AI 生成) 2. 业务服务器可能会有很多请求在处理,导致系统资源紧张,严重时导致服务器宕机或者无法处理新的请求 3. 调用的第三方服务(AI 能力)的处理能力是有限的,比如每 3 秒只能处理 1 个请求,会导致 AI 处理不过来,严重时 AI 可能会对咱们的后台系统拒绝服务。 #### 业务流程分析 标准异步化的业务流程 1. 当用户要进行耗时很长的操作时,点击提交后,不需要在界面傻等,而是应该把这个任务保存到数据库中记录下来 2. 用户要执行新任务时: ​ a任务提交成功: ​ ⅰ如果我们的程序还有多余的空闲线程,可以立刻去做这个任务 ​ ⅱ如果我们的程序的线程都在繁忙,无法继续处理,那就放到等待队列里 ​ b任务提交失败:比如我们的程序所有线程都在忙, 任务队列满了 ​ ⅰ拒绝掉这个任务,再也不去执行 ​ ⅱ通过保存到数据库中的记录来看到提交失败的任务,并且在程序闲的时候,可以把任务从数据库中捞到程 序里,再去执行 3. 我们的程序(线程)从任务队列中取出任务依次执行,每完成一件事情要修改一下的任务的状态。 4. 用户可以查询任务的执行状态,或者在任务执行成功或失败时能得到通知(发邮件、系统消息提示、短信),从而优化体验 5. 如果我们要执行的任务非常复杂,包含很多环节,在每一个小任务完成时,要在程序(数据库中)记录一下任务的执行状态(进度) 我们系统的业务流程 1. 用户点击智能分析页的提交按钮时,先把图表立刻保存到数据库中(作为一个任务) 2. 用户可以在图表管理页面查看所有图表(已生成的、生成中的、生成失败)的信息和状态 3. 用户可以修改生成失败的图表信息,点击重新生成 优化流程(异步化): ![image-20231008211712048](D:\liumingyao\study\文档\智能BI项目文档.assets\image-20231008211712048.png) 问题: 1. 任务队列的最大容量应该设置为多少? 2. 程序怎么从任务队列中取出任务去执行?这个任务队列的流程怎么实现?怎么保证程序最多同时执行多少个任务? #### 线程池 为什么需要线程池? 1. 线程的管理比较复杂(比如什么时候新增线程、什么时候减少空闲线程) 2. 任务存取比较复杂(什么时候接受任务、什么时候拒绝任务、怎么保证大家不抢到同一个任务) 线程池的作用:帮助你轻松管理线程、协调任务的执行过程。 线程池的实现 不用自己写,如果是在 Spring 中,可以用 ThreadPoolTaskExecutor 配合 @Async 注解来实现。(不太建议) 如果是在 Java 中,可以使用 JUC 并发编程包中的 ThreadPoolExecutor 来实现非常灵活地自定义线程池。 线程池参数 ~~~java public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {} ~~~ 怎么确定线程池参数呢?结合实际情况(实际业务场景和系统资源)来测试调整,不断优化。 回归到我们的业务,要考虑系统最脆弱的环节(系统的瓶颈)在哪里? 现有条件:比如 AI 生成能力的并发是只允许 4 个任务同时去执行,AI 能力允许 20 个任务排队。 corePoolSize(核心线程数 => 正式员工数):正常情况下,我们的系统应该能同时工作的线程数(随时就绪的状态) maximumPoolSize(最大线程数 => 哪怕任务再多,你也最多招这些人):极限情况下,我们的线程池最多有多少个线程? keepAliveTime(空闲线程存活时间):非核心线程在没有任务的情况下,过多久要删除(理解为开除临时工),从而释放无用的线程资源。 TimeUnit unit(空闲线程存活时间的单位):分钟、秒 workQueue(工作队列):用于存放给线程执行的任务,存在一个队列的长度(一定要设置,不要说队列长度无限,因为也会占用资源) threadFactory(线程工厂):控制每个线程的生成、线程的属性(比如线程名) RejectedExecutionHandler(拒绝策略):任务队列满的时候,我们采取什么措施,比如抛异常、不抛异常、自定义策略 > 资源隔离策略:比如重要的任务(VIP 任务)一个队列,普通任务一个队列,保证这两个队列互不干扰。 线程池的参数如何设置? 现有条件:比如 AI 生成能力的并发是只允许 4 个任务同时去执行,AI 能力允许 20 个任务排队。 corePoolSize(核心线程数 => 正式员工数):正常情况下,可以设置为 2 - 4 maximumPoolSize:设置为极限情况,设置为 <= 4 keepAliveTime(空闲线程存活时间):一般设置为秒级或者分钟级 TimeUnit unit(空闲线程存活时间的单位):分钟、秒 workQueue(工作队列):结合实际请况去设置,可以设置为 20 threadFactory(线程工厂):控制每个线程的生成、线程的属性(比如线程名) RejectedExecutionHandler(拒绝策略):抛异常,标记数据库的任务状态为 “任务满了已拒绝” 一般情况下,任务分为 IO 密集型和计算密集型两种。 计算密集型:吃 CPU,比如音视频处理、图像处理、数学计算等,一般是设置 corePoolSize 为 CPU 的核数 + 1(空余线程),可以让每个线程都能利用好 CPU 的每个核,而且线程之间不用频繁切换(减少打架、减少开销) IO 密集型:吃带宽/内存/硬盘的读写资源,corePoolSize 可以设置大一点,一般经验值是 2n 左右,但是建议以 IO 的能力为主。 考虑导入百万数据到数据库,属于 IO 密集型任务、还是计算密集型任务? IO密集型;导入数据到数据库涉及到大量的I/O操作,需要读取源数据文件并将其写入目标数据库中,尤其是百万条记录的数据导入,需要频繁的磁盘读写操作。因此,该任务需要大量的磁盘l/O和网络传输,而不涉及太多的计算操作。 相比之下,计算密集型任务更侧重于对数据进行大量的计算,例如复杂的数学运算、模拟、统计分析和图像处理等任务,这些任务需要耗费大量的CPU和内存资源。 开发 自定义线程池: ~~~java @Configuration public class ThreadPoolExecutorConfig { @Bean public ThreadPoolExecutor threadPoolExecutor() { ThreadFactory threadFactory = new ThreadFactory() { private int count = 1; @Override public Thread newThread(@NotNull Runnable r) { Thread thread = new Thread(r); thread.setName("线程" + count); count++; return thread; } }; ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 4, 100, TimeUnit.SECONDS, new ArrayBlockingQueue<>(4), threadFactory); return threadPoolExecutor; } } ~~~ #### 图表异步化开发 实现工作流程 1. 给 chart 表新增任务状态字段(比如排队中、执行中、已完成、失败),任务执行信息字段(用于记录任务执行中、或者失败的一些信息) 2. 用户点击智能分析页的提交按钮时,先把图表立刻保存到数据库中,然后提交任务 3. 任务:先修改图表任务状态为 “执行中”。等执行成功后,修改为 “已完成”、保存执行结果;执行失败后,状态修改为 “失败”,记录任务失败信息。 4. 用户可以在图表管理页面查看所有图表(已生成的、生成中的、生成失败)的信息和状态 库表设计 chart表新增字段: ~~~sql status varchar(128) not null default 'wait' comment 'wait,running,succeed,failed', execMessage text null comment '执行信息', ~~~ 任务执行逻辑 先修改任务状态为执行中,减少重复执行的风险、同时让用户知道执行状态。 ~~~java CompletableFuture.runAsync(() -> { // 先修改图表任务状态为 “执行中”。等执行成功后,修改为 “已完成”、保存执行结果;执行失败后,状态修改为 “失败”,记录任务失败信息。 Chart updateChart = new Chart(); updateChart.setId(chart.getId()); updateChart.setStatus("running"); boolean b = chartService.updateById(updateChart); if (!b) { handleChartUpdateError(chart.getId(), "更新图表执行中状态失败"); return; } // 调用 AI String result = aiManager.doChat(biModelId, userInput.toString()); String[] splits = result.split("【【【【【"); if (splits.length < 3) { handleChartUpdateError(chart.getId(), "AI 生成错误"); return; } String genChart = splits[1].trim(); String genResult = splits[2].trim(); Chart updateChartResult = new Chart(); updateChartResult.setId(chart.getId()); updateChartResult.setGenChart(genChart); updateChartResult.setGenResult(genResult); updateChartResult.setStatus("succeed"); boolean updateResult = chartService.updateById(updateChartResult); if (!updateResult) { handleChartUpdateError(chart.getId(), "更新图表成功状态失败"); } }, threadPoolExecutor); ~~~ #### @TODO 1. 给任务的执行增加 guava Retrying 重试机制,保证系统可靠性。 2. 提前考虑到 AI 生成错误的情况,在后端进行异常处理(比如 AI 说了多余的话,提取正确的字符串) 3. 如果说任务根本没提交到队列中(或者队列满了),是不是可以用定时任务把失败状态的图表放到队列中(补偿) 4. 建议给任务的执行增加一个超时时间,超时自动标记为失败(超时控制) 5. 反向压力:https://zhuanlan.zhihu.com/p/404993753,通过调用的服务状态来选择当前系统的策略(比如根据 AI 服务的当前任务队列数来控制咱们系统的核心线程数),从而最大化利用系统资源。 6. 我的图表页面增加一个刷新、定时自动刷新的按钮,保证获取到图表的最新状态(前端轮询) 7. 任务执行成功或失败,给用户发送实时消息通知(实时:websocket、server side event) ### Day6 1. 分析系统的不足 2. 分布式消息队列 3. 分布式消息队列RabbitMQ入门实战 #### 分析系统现状不足 > 单机系统的问题 已经经过了同步到异步的改造? 现状:目前的异步是通过本地的线程池实现的。 1. 无法集中限制,智能单机限制 假如AI服务限制智能有2个用户同时使用,单个线程池可以限制最大核心线程数为2来实现。 假设系统用户量增大,改为分布式,多台服务器,每个服务器都要有2个线程,就有可能有2N个线程,超过了AI服务的限制。 2. 任务由于是放在内存中执行的,可能会丢失 虽然可以人工从数据库捞出来再重试,但是其实需要额外开发(比如定时任务)。这种重试的场景是非常典型的,其实是不需要我们开发者过于关心,或者自己实现的。 解决方案:把任务放在一个可以持久化存储的硬盘 3. 优化:如果你的系统功能越来越多,长耗时任务越来越多,系统会越来越复杂(比如要开多个线程池,资源可能会出现项目抢占) 服务拆分(应用解耦):其实我们可以把长耗时,消耗很多的任务把它单独抽成一个程序,不要影响主业务。 解决方案:可以有一个中间人,让中间人帮我们去连接两个系统(比如核心系统和智能生成业务) #### 分布式消息队列 中间件 连接多个系统,帮助多个系统紧密协作的技术(或者组件)。 比如:Redis,消息队列,分布式存储Etcd ![image-20231014100213687](D:\liumingyao\study\文档\智能BI项目文档.assets\image-20231014100213687.png) 消息队列 存储消息的队列。 关键词:存储、消息、队列 存储:存数据 消息:某种数据结构,比如字符串、对象、二进制数据、json 等等 队列:先进先出的数据结构 消息队列是特殊的数据库么?可以这么理解。 应用场景(作用):在多个不同的系统、应用之间实现消息的传输(也可以存储)。不需要考虑传输应用的编程语言、系统、框架等等。 可以让 java 开发的应用发消息,让 php 开发的应用收消息,这样就不用把所有代码写到同一个项目里(应用解耦)。 消息队列的模型 生产者:Producer,类比为快递员,发送消息的人(客户端) 消费者:Consumer,类比为取快递的人,接受读取消息的人(客户端) 消息:Message,类比为快递,就是生产者要传输给消费者的数据 消息队列:Queue 为什么不接传输,要用消息队列?生产者不用关心你的消费者要不要消费、什么时候消费,我只需要把东西给消息队列,我的工作就算完成了。 生产者和消费者实现了解耦,互不影响。 ![image-20231014100409701](D:\liumingyao\study\文档\智能BI项目文档.assets\image-20231014100409701.png) 为什么要用消息队列? 1)异步处理 生产者发送完消息之后,可以继续去忙别的,消费者想什么时候消费都可以,不会产生阻塞。 2)削峰填谷 先把用户的请求放到消息队列中,消费者(实际执行操作的应用)可以按照自己的需求,慢慢去取。 原本:12 点时来了 10 万个请求,原本情况下,10万个请求都在系统内部立刻处理,很快系统压力过大就宕机了。 现在:把这 10万个请求放到消息队列中,处理系统以自己的恒定速率(比如每秒 1 个)慢慢执行,从而保护系统、稳定处理。 分布式消息队列的优势 1)数据持久化:它可以把消息集中存储到硬盘里,服务器重启就不会丢失 2)可扩展性:可以根据需求,随时增加(或减少)节点,继续保持稳定的服务 3)应用解耦:可以连接各个不同语言、框架开发的系统,让这些系统能够灵活传输读取数据 应用解耦的优点: 以前,把所有功能放到同一个项目中,调用多个子功能时,一个环节错,系统就整体出错: ![image-20231014100726391](D:\liumingyao\study\文档\智能BI项目文档.assets\image-20231014100726391.png) 使用消息队列进行解耦: 1. 一个系统挂了,不影响另一个系统 2. 系统挂了并恢复后,仍然可以取出信息,继续执行业务逻辑 3. 只要发送消息到队列,就可以立刻返回,不用同步调用所有系统,性能更高 ![image-20231014100959870](D:\liumingyao\study\文档\智能BI项目文档.assets\image-20231014100959870.png) 4)发布订阅 如果一个非常大的系统要给其他子系统发送通知,最简单直接的方式是大系统直接依次调用小系统: 问题: 1. 每次发通知都要调用很多系统,很麻烦,有可能失败 2. 新出现的项目(或者说大项目感知不到的项目)无法得到通知 ![image-20231014101315142](D:\liumingyao\study\文档\智能BI项目文档.assets\image-20231014101315142.png) 解决方案:大的核心系统始终往一个地方(消息队列)去发消息,其它系统都去订阅这个消息队列(读取这个消息队列中的信息) ![image-20231014101445433](D:\liumingyao\study\文档\智能BI项目文档.assets\image-20231014101445433.png) 应用场景 1. 耗时的场景(异步) 2. 高并发场景(异步、削峰填谷) 3. 分布式系统协作(尤其是跨团队、跨业务协作,应用解耦) 4. 强稳定性的场景(比如金融业务,持久化、可靠性、削峰填谷) 消息队列的缺点 要给系统引入额外的中间件,系统会更复杂、额外维护中间件、额外的费用(部署)成本 消息队列:消息丢失、顺序性、重复消费、数据的一致性(分布式系统就要考虑) 也可以叫分布式场景下需要考虑的问题 主流分布式消息队列选型 主流技术 1. activemq 2. rabbitmq 3. kafka 4. rocketmq 5. zeromq 6. pulsar(云原生) 7. Apache InLong (Tube) #### RabbitMQ入门实战 特点:生态好,好学习、易于理解,时效性强,支持很多不同语言的客户端,扩展性、可用性都很不错。 学习性价比非常高的消息队列,适用于绝大多数中小规模分布式系统。 官方网站:[https://www.rabbitmq.com](https://www.rabbitmq.com/getstarted.html) 基本概念 AMQP 协议:https://www.rabbitmq.com/tutorials/amqp-concepts.html 高级消息队列协议(Advanced Message Queue Protocol) 生产者:发消息到某个交换机 消费者:从某个队列中取消息 交换机(Exchange):负责把消息 转发 到对应的队列 队列(Queue):存储消息的 路由(Routes):转发,就是怎么把消息从一个地方转到另一个地方(比如从生产者转发到某个队列) ![img](D:\liumingyao\study\文档\智能BI项目文档.assets\1686835103366-bdb220cd-b177-4f41-982d-8451e5f6ebfe.png) 快速入门 MQ官方教程:https://www.rabbitmq.com/getstarted.html 单向发送 > Hello World 文档:https://www.rabbitmq.com/tutorials/tutorial-one-java.html 一个生产者给一个队列发消息,一个消费者从这个队列取消息。1对1 ![image.png](D:\liumingyao\study\文档\智能BI项目文档.assets\1686836521822-053f7420-498d-4539-9721-ae0bc6e5b012.png) 引入消息队列Java客户端: ~~~xml <!-- https://mvnrepository.com/artifact/com.rabbitmq/amqp-client --> <dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>5.17.0</version> </dependency> ~~~ 生产者代码 ~~~java import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import java.nio.charset.StandardCharsets; public class Send { private final static String QUEUE_NAME = "hello"; public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) { channel.queueDeclare(QUEUE_NAME, false, false, false, null); String message = "Hello World!"; channel.basicPublish("", QUEUE_NAME, null, message.getBytes(StandardCharsets.UTF_8)); System.out.println(" [x] Sent '" + message + "'"); } } } ~~~ Channel 频道:理解为操作消息队列的 client(比如 jdbcClient、redisClient),提供了和消息队列 server 建立通信的传输方法(为了复用连接,提高传输效率)。程序通过 channel 操作 rabbitmq(收发消息) 创建消息队列: 参数: queueName:消息队列名称(注意,同名称的消息队列,只能用同样的参数创建一次) durabale:消息队列重启后,消息是否丢失 exclusive:是否只允许当前这个创建消息队列的连接操作消息队列 autoDelete:没有人用队列后,是否要删除队列 执行程序后,可以看到有1条消息: ![image.png](D:\liumingyao\study\文档\智能BI项目文档.assets\1686837082571-81894d7d-eaac-444e-9ccd-601d226f2c9c.png) 消费者代码: ~~~java public class SingleConsumer { private final static String QUEUE_NAME = "hello"; public static void main(String[] argv) throws Exception { // 创建连接 ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); // 创建队列 channel.queueDeclare(QUEUE_NAME, false, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); // 定义了如何处理消息 DeliverCallback deliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), StandardCharsets.UTF_8); System.out.println(" [x] Received '" + message + "'"); }; // 消费消息,会持续阻塞 channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { }); } } ~~~ 启动消费者后,可以看到消息被消费了: ![image.png](D:\liumingyao\study\文档\智能BI项目文档.assets\1686837388735-5aead597-0ee7-4221-81a2-9f41f4666c07.png) 多消费者 官方教程:https://www.rabbitmq.com/tutorials/tutorial-two-java.html 场景:多个机器同时去接收并处理任务(尤其是每个机器的处理能力有限) 一个生产者给一个队列发消息,多个消费者从这个队列取消息。1对多 ![image.png](D:\liumingyao\study\文档\智能BI项目文档.assets\1686837446793-34600b8b-907d-4c0a-8200-f077b3175c32.png) 1)队列持久化 durable参数设置为true,服务器重启后队列不丢失: ~~~java channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null); ~~~ 2)消息持久化 指定 MessageProperties.PERSISTENT_TEXT_PLAIN 参数: ~~~java channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes("UTF-8")); ~~~ 生产者代码: 使用Scanner接受用户输入,便于发送多条消息 ~~~java public class MultiProducer { private static final String TASK_QUEUE_NAME = "multi_queue"; public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) { channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null); Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { String message = scanner.nextLine(); channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes("UTF-8")); System.out.println(" [x] Sent '" + message + "'"); } } } } ~~~ 控制单个消费者的处理任务积压数: 每个消费者最多同时处理1个任务 ~~~java channel.basicQos(1); ~~~ 消息确认机制: 为了保证消息成功被消费,rabbitmq提供了消息确认机制,当消费者接收到消息后,比如要给一个反馈: - ack:消费成功 - nack:消费失败 - reject:拒绝 如果告诉rabbitmq服务器消费成功,服务器才会放心的移除消息。 支持配置autoack,会自动执行ack命令,接收到消息立刻就成功了。 ~~~java channel.basicConsume(TASK_QUEUE_NAME, false, deliverCallback, consumerTag -> { }); ~~~ 建议autoack改为false,根据实际情况,去手动确认。 指定确认某条消息: ~~~java channel.basicAck(delivery.getEnvelope().getDeliveryTag(), ); ~~~ 第二个参数 multiple 批量确认:是指是否要一次性确认所有的历史消息直到当前这条 指定拒绝某条消息: ~~~java channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, false) ~~~ 第3个参数表示是否重新入队,可用于重试。 消费者代码: ~~~java public class MultiConsumer { private static final String TASK_QUEUE_NAME = "multi_queue"; public static void main(String[] argv) throws Exception { // 建立连接 ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); final Connection connection = factory.newConnection(); for (int i = 0; i < 2; i++) { final Channel channel = connection.createChannel(); channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); channel.basicQos(1); // 定义了如何处理消息 int finalI = i; DeliverCallback deliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); try { // 处理工作 System.out.println(" [x] Received '" + "编号:" + finalI + ":" + message + "'"); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); // 停 20 秒,模拟机器处理能力有限 Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, false); } finally { System.out.println(" [x] Done"); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } }; // 开启消费监听 channel.basicConsume(TASK_QUEUE_NAME, false, deliverCallback, consumerTag -> { }); } } } ~~~ 2个小技巧: 1. 使用Scanner接受用户输入,便于快速发送多条消息 2. 使用for循环创建多个消费者,便于快速验证队列模型工作机制。 交换机 一个生产者给多个队列发消息,1个生产者对多个队列。 交换机的作用:提供消息转发功能,类似于网络路由器 要解决的问题:怎么把消息转发到不同的队列上,好让消费者从不同的队列消费。 绑定:交换机和队列关联起来,也可以叫路由,算是一个算法或转发策略 绑定代码: ~~~java channel.queueBind(queueName, EXCHANGE_NAME, "绑定规则"); ~~~ ![image.png](D:\liumingyao\study\文档\智能BI项目文档.assets\1686839285368-841c3ded-965b-4ed7-8214-091ac7f2c922.png) 教程:https://www.rabbitmq.com/tutorials/tutorial-three-java.html 交换机有多种类别;fanout, direct,topic,headers fanout 扇出,广播 特点:消息会被转发到所有绑定到该交换机的队列 场景:很适用于发布订阅的场景。比如写日志,可以多个系统间共享 ![image.png](D:\liumingyao\study\文档\智能BI项目文档.assets\1686839285368-841c3ded-965b-4ed7-8214-091ac7f2c922-169726500464113.png) ![image-20231014143015575](D:\liumingyao\study\文档\智能BI项目文档.assets\image-20231014143015575.png) 生产者代码: ~~~java public class FanoutProducer { private static final String EXCHANGE_NAME = "fanout-exchange"; public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) { // 创建交换机 channel.exchangeDeclare(EXCHANGE_NAME, "fanout"); Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { String message = scanner.nextLine(); channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes("UTF-8")); System.out.println(" [x] Sent '" + message + "'"); } } } } ~~~ 消费者代码 注意: 1. 消费者和生产者要绑定同一个交换机 2. 要先有队列,才能绑定 ~~~java public class FanoutConsumer { private static final String EXCHANGE_NAME = "fanout-exchange"; public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel1 = connection.createChannel(); Channel channel2 = connection.createChannel(); // 声明交换机 channel1.exchangeDeclare(EXCHANGE_NAME, "fanout"); // 创建队列,随机分配一个队列名称 String queueName = "xiaowang_queue"; channel1.queueDeclare(queueName, true, false, false, null); channel1.queueBind(queueName, EXCHANGE_NAME, ""); String queueName2 = "xiaoli_queue"; channel2.queueDeclare(queueName2, true, false, false, null); channel2.queueBind(queueName2, EXCHANGE_NAME, ""); channel2.queueBind(queueName2, EXCHANGE_NAME, ""); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); DeliverCallback deliverCallback1 = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); System.out.println(" [小王] Received '" + message + "'"); }; DeliverCallback deliverCallback2 = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); System.out.println(" [小李] Received '" + message + "'"); }; channel1.basicConsume(queueName, true, deliverCallback1, consumerTag -> { }); channel2.basicConsume(queueName2, true, deliverCallback2, consumerTag -> { }); } } ~~~ 效果:所有的消费者都能收到消息 Direct交换机 官方教程:https://www.rabbitmq.com/tutorials/tutorial-four-java.html 绑定:可以让交换机和队列进行关联,可以指定让交换机把什么样的消息发送给哪个队列(类似于计算机网络中,两个路由器,或者网络设备相互连接,也可以理解为网线) routingKey:路由键,控制消息要转发给那个队列的(IP地址) 特点:消息会根据路由键转发到指定的队列 场景:特定的消息只交给特定的系统(程序来处理) 绑定关系:完全匹配字符串 ![img](D:\liumingyao\study\文档\智能BI项目文档.assets\1687007686788-76df21d6-428d-4d2d-abb7-4da819faf775.png) 可以绑定同样的路由键。 比如发日志的场景,希望用独立的程序来处理不同级别的日志,比如 C1 系统处理 error 日志,C2 系统处理其他级别的日志 ![img](D:\liumingyao\study\文档\智能BI项目文档.assets\1687007976055-a38c33d2-490f-4582-b9ea-36b881c2101e.png) ![image-20231014144559541](D:\liumingyao\study\文档\智能BI项目文档.assets\image-20231014144559541.png) 生产者代码: ~~~java public class DirectProducer { private static final String EXCHANGE_NAME = "direct-exchange"; public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) { channel.exchangeDeclare(EXCHANGE_NAME, "direct"); Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { String userInput = scanner.nextLine(); String[] strings = userInput.split(" "); if (strings.length < 1) { continue; } String message = strings[0]; String routingKey = strings[1]; channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes("UTF-8")); System.out.println(" [x] Sent '" + message + " with routing:" + routingKey + "'"); } } } } ~~~ 消费者代码: ~~~java public class DirectConsumer { private static final String EXCHANGE_NAME = "direct-exchange"; public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "direct"); // 创建队列,随机分配一个队列名称 String queueName = "xiaoyu_queue"; channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, EXCHANGE_NAME, "xiaoyu"); // 创建队列,随机分配一个队列名称 String queueName2 = "xiaopi_queue"; channel.queueDeclare(queueName2, true, false, false, null); channel.queueBind(queueName2, EXCHANGE_NAME, "xiaopi"); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); DeliverCallback xiaoyuDeliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); System.out.println(" [xiaoyu] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'"); }; DeliverCallback xiaopiDeliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); System.out.println(" [xiaopi] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'"); }; channel.basicConsume(queueName, true, xiaoyuDeliverCallback, consumerTag -> { }); channel.basicConsume(queueName2, true, xiaopiDeliverCallback, consumerTag -> { }); } } ~~~ topic交换机 官方教程:https://www.rabbitmq.com/tutorials/tutorial-five-java.html 特点:消息会根据一个 模糊的 路由键转发到指定的队列 场景:特定的一类消息可以交给特定的一类系统(程序)来处理 绑定关系:可以模糊匹配多个绑定 - *:匹配一个单词,比如 *.orange,那么 a.orange、b.orange 都能匹配 - \#:匹配 0 个或多个单词,比如 a.#,那么 a.a、a.b、a.a.a 都能匹配 注意,这里的匹配和 MySQL 的like 的 % 不一样,只能按照单词来匹配,每个 '.' 分隔单词,如果是 '#.',其实可以忽略,匹配 0 个词也 ok ![image.png](D:\liumingyao\study\文档\智能BI项目文档.assets\1687009111794-08bd54bb-234d-4280-a604-852e2b01840c.png) 应用场景: 老板要下发一个任务,让多个组来处理 ![image-20231014145031412](D:\liumingyao\study\文档\智能BI项目文档.assets\image-20231014145031412.png) 生产者代码: ~~~java public class TopicProducer { private static final String EXCHANGE_NAME = "topic-exchange"; public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) { channel.exchangeDeclare(EXCHANGE_NAME, "topic"); Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { String userInput = scanner.nextLine(); String[] strings = userInput.split(" "); if (strings.length < 1) { continue; } String message = strings[0]; String routingKey = strings[1]; channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes("UTF-8")); System.out.println(" [x] Sent '" + message + " with routing:" + routingKey + "'"); } } } } ~~~ 消费者代码: ~~~java public class TopicConsumer { private static final String EXCHANGE_NAME = "topic-exchange"; public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic"); // 创建队列 String queueName = "frontend_queue"; channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, EXCHANGE_NAME, "#.前端.#"); // 创建队列 String queueName2 = "backend_queue"; channel.queueDeclare(queueName2, true, false, false, null); channel.queueBind(queueName2, EXCHANGE_NAME, "#.后端.#"); // 创建队列 String queueName3 = "product_queue"; channel.queueDeclare(queueName3, true, false, false, null); channel.queueBind(queueName3, EXCHANGE_NAME, "#.产品.#"); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); DeliverCallback xiaoaDeliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); System.out.println(" [xiaoa] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'"); }; DeliverCallback xiaobDeliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); System.out.println(" [xiaob] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'"); }; DeliverCallback xiaocDeliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); System.out.println(" [xiaoc] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'"); }; channel.basicConsume(queueName, true, xiaoaDeliverCallback, consumerTag -> { }); channel.basicConsume(queueName2, true, xiaobDeliverCallback, consumerTag -> { }); channel.basicConsume(queueName3, true, xiaocDeliverCallback, consumerTag -> { }); } } ~~~ Headers交换机 类似主题和直接交换机,可以根据 headers 中的内容来指定发送到哪个队列 由于性能差、比较复杂,一般不推荐使用。 ![image.png](D:\liumingyao\study\文档\智能BI项目文档.assets\1687011466810-28a7cdc5-e42c-45f5-aa8c-2635c41e0a89.png) RPC 支持用消息队列来模拟 RPC 的调用,但是一般没必要,直接用 Dubbo、GRPC 等 RPC 框架就好了。 #### 核心特性 消息过期机制 官方文档:https://www.rabbitmq.com/ttl.html 可以给每条消息指定一个有效期,一段时间内未被消费者处理,就过期了。 示例场景:消费者(库存系统)挂了,一个订单 15 分钟还没被库存系统处理,这个订单其实已经失效了,哪怕库存系统再恢复,其实也不用扣减库存。 适用场景:清理过期数据、模拟延迟队列的实现(不开会员就慢速)、专门让某个程序处理过期请求 1)给队列中的所有消息指定过期时间 ~~~java // 创建队列,指定消息过期参数 Map<String, Object> args = new HashMap<String, Object>(); args.put("x-message-ttl", 5000); // args 指定参数 channel.queueDeclare(QUEUE_NAME, false, false, false, args); ~~~ ![image.png](D:\liumingyao\study\文档\智能BI项目文档.assets\1687012172430-53fff46b-6383-40c9-99ae-bc96667f71d4.png) 如果在过期时间内,还没有消费者取消息,消息才会过期。 注意,如果消息已经接收到,但是没确认,是不会过期的。 > 如果消息处于待消费状态并且过期时间到达后,消息将被标记为过期。但是,如果消息已经被消费者消费,并且正在处理过程中,即使过期时间到达,消息仍然会被正常处理 消费者代码: ~~~java public class TtlConsumer { private final static String QUEUE_NAME = "ttl_queue"; public static void main(String[] argv) throws Exception { // 创建连接 ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); // 创建队列,指定消息过期参数 Map<String, Object> args = new HashMap<String, Object>(); args.put("x-message-ttl", 5000); // args 指定参数 channel.queueDeclare(QUEUE_NAME, false, false, false, args); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); // 定义了如何处理消息 DeliverCallback deliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), StandardCharsets.UTF_8); System.out.println(" [x] Received '" + message + "'"); }; // 消费消息,会持续阻塞 channel.basicConsume(QUEUE_NAME, false, deliverCallback, consumerTag -> { }); } } ~~~ 生产者代码: ~~~java public class TtlProducer { private final static String QUEUE_NAME = "ttl_queue"; public static void main(String[] argv) throws Exception { // 创建连接工厂 ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); // factory.setUsername(); // factory.setPassword(); // factory.setPort(); // 建立连接、创建频道 try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) { // 发送消息 String message = "Hello World!"; channel.basicPublish("", QUEUE_NAME, null, message.getBytes(StandardCharsets.UTF_8)); System.out.println(" [x] Sent '" + message + "'"); } } } ~~~ 2)给某条消息指定过期时间 语法: ~~~java // 给消息指定过期时间 AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder() .expiration("1000") .build(); channel.basicPublish("my-exchange", "routing-key", properties, message.getBytes(StandardCharsets.UTF_8)); ~~~ 实例代码: ~~~java public class TtlProducer { private final static String QUEUE_NAME = "ttl_queue"; public static void main(String[] argv) throws Exception { // 创建连接工厂 ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); // factory.setUsername(); // factory.setPassword(); // factory.setPort(); // 建立连接、创建频道 try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) { // 发送消息 String message = "Hello World!"; // 给消息指定过期时间 AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder() .expiration("1000") .build(); channel.basicPublish("my-exchange", "routing-key", properties, message.getBytes(StandardCharsets.UTF_8)); System.out.println(" [x] Sent '" + message + "'"); } } } ~~~ 消息确认机制 官方文档:https://www.rabbitmq.com/confirms.html 为了保证消息成功被消费(快递成功被取走),rabbitmq 提供了消息确认机制,当消费者接收到消息后,比如要给一个反馈: - ack:消费成功 - nack:消费失败 - reject:拒绝 如果告诉 rabbitmq 服务器消费成功,服务器才会放心地移除消息。 支持配置 autoack,会自动执行 ack 命令,接收到消息立刻就成功了。 ~~~java channel.basicConsume(TASK_QUEUE_NAME, false, deliverCallback, consumerTag -> { }); ~~~ **一般情况,建议 autoack 改为 false,根据实际情况,去手动确认。** 指定确认某条消息: ~~~java channel.basicAck(delivery.getEnvelope().getDeliveryTag(), ); ~~~ 第二个参数 multiple 批量确认:是指是否要一次性确认所有的历史消息直到当前这条 指定拒绝某条消息: ~~~java channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, false); ~~~ 第 3 个参数表示是否重新入队,可用于重试 死信队列 官方文档:https://www.rabbitmq.com/dlx.html 为了保证消息的可靠性,比如每条消息都成功消费,需要提供一个容错机制,即:失败的消息怎么处理? 死信:过期的消息、拒收的消息、消息队列满了、处理失败的消息的统称 死信队列:专门处理死信的队列(注意,它就是一个普通队列,只不过是专门用来处理死信的,你甚至可以理解这个队列的名称叫 “死信队列”) 死信交换机:专门给死信队列转发消息的交换机(注意,它就是一个普通交换机,只不过是专门给死信队列发消息而已,理解为这个交换机的名称就叫 “死信交换机”)。也存在路由绑定 死信可以通过死信交换机绑定到死信队列。 ![image-20231014145949831](D:\liumingyao\study\文档\智能BI项目文档.assets\image-20231014145949831.png) 实现: 1)创建死信交换机和死信队列,并且绑定关系 ![image.png](D:\liumingyao\study\文档\智能BI项目文档.assets\1687013888188-1bde4fc6-73c1-48e4-b9c8-7d231a4e5a72.png) 2)给失败之后需要容错处理的队列绑定死信交换机 ~~~java // 指定死信队列参数 Map<String, Object> args = new HashMap<>(); // 要绑定到哪个交换机 args.put("x-dead-letter-exchange", DEAD_EXCHANGE_NAME); // 指定死信要转发到哪个死信队列 args.put("x-dead-letter-routing-key", "waibao"); // 创建队列,随机分配一个队列名称 String queueName = "xiaodog_queue"; channel.queueDeclare(queueName, true, false, false, args); channel.queueBind(queueName, EXCHANGE_NAME, "xiaodog"); ~~~ 3)可以给要容错的队列指定死信之后的转发规则,死信应该再转发到哪个死信队列 ~~~java // 指定死信要转发到哪个死信队列 args.put("x-dead-letter-routing-key", "waibao"); ~~~ 4)可以通过程序来读取死信队列中的消息,从而进行处理 ~~~java // 创建队列,随机分配一个队列名称 String queueName = "laoban_dlx_queue"; channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, DEAD_EXCHANGE_NAME, "laoban"); String queueName2 = "waibao_dlx_queue"; channel.queueDeclare(queueName2, true, false, false, null); channel.queueBind(queueName2, DEAD_EXCHANGE_NAME, "waibao"); DeliverCallback laobanDeliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); // 拒绝消息 channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, false); System.out.println(" [laoban] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'"); }; DeliverCallback waibaoDeliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); // 拒绝消息 channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, false); System.out.println(" [waibao] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'"); }; channel.basicConsume(queueName, false, laobanDeliverCallback, consumerTag -> { }); channel.basicConsume(queueName2, false, waibaoDeliverCallback, consumerTag -> { }); ~~~ 完整生产者代码: ~~~java public class DlxDirectProducer { private static final String DEAD_EXCHANGE_NAME = "dlx-direct-exchange"; private static final String WORK_EXCHANGE_NAME = "direct2-exchange"; public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) { // 声明死信交换机 channel.exchangeDeclare(DEAD_EXCHANGE_NAME, "direct"); // 创建队列,随机分配一个队列名称 String queueName = "laoban_dlx_queue"; channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, DEAD_EXCHANGE_NAME, "laoban"); String queueName2 = "waibao_dlx_queue"; channel.queueDeclare(queueName2, true, false, false, null); channel.queueBind(queueName2, DEAD_EXCHANGE_NAME, "waibao"); DeliverCallback laobanDeliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); // 拒绝消息 channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, false); System.out.println(" [laoban] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'"); }; DeliverCallback waibaoDeliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); // 拒绝消息 channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, false); System.out.println(" [waibao] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'"); }; channel.basicConsume(queueName, false, laobanDeliverCallback, consumerTag -> { }); channel.basicConsume(queueName2, false, waibaoDeliverCallback, consumerTag -> { }); Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { String userInput = scanner.nextLine(); String[] strings = userInput.split(" "); if (strings.length < 1) { continue; } String message = strings[0]; String routingKey = strings[1]; channel.basicPublish(WORK_EXCHANGE_NAME, routingKey, null, message.getBytes("UTF-8")); System.out.println(" [x] Sent '" + message + " with routing:" + routingKey + "'"); } } } } ~~~ 完整消费者代码: ~~~java public class DlxDirectConsumer { private static final String DEAD_EXCHANGE_NAME = "dlx-direct-exchange"; private static final String WORK_EXCHANGE_NAME = "direct2-exchange"; public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(WORK_EXCHANGE_NAME, "direct"); // 指定死信队列参数 Map<String, Object> args = new HashMap<>(); // 要绑定到哪个交换机 args.put("x-dead-letter-exchange", DEAD_EXCHANGE_NAME); // 指定死信要转发到哪个死信队列 args.put("x-dead-letter-routing-key", "waibao"); // 创建队列,随机分配一个队列名称 String queueName = "xiaodog_queue"; channel.queueDeclare(queueName, true, false, false, args); channel.queueBind(queueName, WORK_EXCHANGE_NAME, "xiaodog"); Map<String, Object> args2 = new HashMap<>(); args2.put("x-dead-letter-exchange", DEAD_EXCHANGE_NAME); args2.put("x-dead-letter-routing-key", "laoban"); // 创建队列,随机分配一个队列名称 String queueName2 = "xiaocat_queue"; channel.queueDeclare(queueName2, true, false, false, args2); channel.queueBind(queueName2, WORK_EXCHANGE_NAME, "xiaocat"); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); DeliverCallback xiaoyuDeliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); // 拒绝消息 channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, false); System.out.println(" [xiaodog] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'"); }; DeliverCallback xiaopiDeliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); // 拒绝消息 channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, false); System.out.println(" [xiaocat] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'"); }; channel.basicConsume(queueName, false, xiaoyuDeliverCallback, consumerTag -> { }); channel.basicConsume(queueName2, false, xiaopiDeliverCallback, consumerTag -> { }); } } ~~~ #### RabbitMQ重点知识 1. 消息队列的概念,模型,应用场景 2. 交换机的类别,路由绑定的关系 3. 消息可靠性 - 消息确认机制(ack,nack, reject) - 消息持久化(durable) - 消息过期机制 - 死信队列 4. 延迟队列(类似死信队列) 5. 顺序消费,消息幂等性 6. 可扩展性(仅作了解) - 集群 - 故障的恢复机制 - 镜像 7. 运维监控警告(仅作了解) 相关资源推荐: 神光 Node.js RabbitMQ 入门文档:https://juejin.cn/post/7225474899480526885 推荐星球嘉宾 Yes 的专栏:https://t.zsxq.com/0fq7F1WAa #### RabbitMQ项目实战 选择客户端 怎么在项目中使用 RabbitMQ? 1)使用官方的客户端。 优点:兼容性好,换语言成本低,比较灵活 缺点:太灵活,要自己去处理一些事情。比如要自己维护管理链接,很麻烦。 2)使用封装好的客户端,比如 Spring Boot RabbitMQ Starter 优点:简单易用,直接配置直接用,更方便地去管理连接 缺点:封装的太好了,你没学过的话反而不知道怎么用。不够灵活,被框架限制。 根据场景来选择,没有绝对的优劣:类似 jdbc 和 MyBatis 本次使用 Spring Boot RabbitMQ Starter(因为我们是 Spring Boot 项目) 如果你有一定水平,有基础,英文好,建议看官方文档,不要看过期博客! https://spring.io/guides/gs/messaging-rabbitmq/ 基础实战: 1)引入依赖 注意,使用的版本一定要和你的 springboot 版本一致!!!!!!! ~~~xml <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-amqp --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> <version>2.7.2</version> </dependency> ~~~ 2)在yml中引入配置: ~~~properties spring: rabbitmq: host: localhost port: 5672 password: guest username: guest ~~~ 3)创建交换机和队列 ~~~java /** * 用于创建测试程序用到的交换机和队列(只用在程序启动前执行一次) */ public class MqInitMain { public static void main(String[] args) { try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); String EXCHANGE_NAME = "code_exchange"; channel.exchangeDeclare(EXCHANGE_NAME, "direct"); // 创建队列,随机分配一个队列名称 String queueName = "code_queue"; channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, EXCHANGE_NAME, "my_routingKey"); } catch (Exception e) { } } } ~~~ 4)生产者代码 ~~~java @Component public class MyMessageProducer { @Resource private RabbitTemplate rabbitTemplate; public void sendMessage(String exchange, String routingKey, String message) { rabbitTemplate.convertAndSend(exchange, routingKey, message); } } ~~~ 5)消费者代码 ~~~java @Component @Slf4j public class MyMessageConsumer { // 指定程序监听的消息队列和确认机制 @SneakyThrows @RabbitListener(queues = {"code_queue"}, ackMode = "MANUAL") public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) { log.info("receiveMessage message = {}", message); channel.basicAck(deliveryTag, false); } } ~~~ 6)单元测试执行 ~~~java @SpringBootTest class MyMessageProducerTest { @Resource private MyMessageProducer myMessageProducer; @Test void sendMessage() { myMessageProducer.sendMessage("code_exchange", "my_routingKey", "你好呀"); } } ~~~ #### BI项目改造 以前是把任务提交到线程池,然后在线程池提交中编写处理程序的代码,线程池内排队。 如果程序中断了,任务就没了,就丢了。 改造后的流程: 1. 把任务提交改为向队列发送消息 2. 写一个专门的接受消息的程序,处理任务 3. 如果程序中断了,消息未被确认,还会重发 4. 现在,消息全部集中发到消息队列,你可以部署多个后端,都从同一个地方取任务,从而实现了分布式负载均衡 实现步骤 1)创建交换机和队列 2)将线程池中的执行代码移到消费者类中 3)根据消费者的需求来确认消息的格式(chartId) 4)将提交线程池改造为发送消息到队列 验证 验证发现,如果程序中断了,没有 ack、也没有 nack(服务中断,没有任何响应),那么这条消息会被重新放到消息队列中,从而实现了每个任务都会执行。 #### 更多优化点 1. 支持用户查看图表原始数据 2. 图表数据分表存储,提高查询灵活性和性能 3. 支持分组(分标签)查看和检索图表 4. 增加更多可选参数来控制图表的生成,比如图表配色等 5. 支持用户对失败的图表进行手动重试 6. 限制用户同时生成图表的数量,防止单用户抢占系统资源 7. 统计用户生成图表的次数,甚至可以添加积分系统,消耗积分来智能分析 8. 支持编辑生成后的图表的信息。比如可以使用代码编辑器来编辑 Echarts 图表配置代码 9. 由于图表数据是静态的,很适合使用缓存来提高加载速度。 10. 使用死信队列来处理异常情况,将图表生成任务置为失败 11. 补充传统 BI 拥有的功能,把智能分析作为其中一个子模块。
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {OrderTypes} from "../libraries/OrderTypes.sol"; import {IExecutionStrategy} from "../interfaces/IExecutionStrategy.sol"; /** * @title StrategyDutchAuction * @notice Strategy to launch a Dutch Auction for a token where the price decreases linearly * until a specified timestamp and end price defined by the seller. */ contract StrategyDutchAuction is IExecutionStrategy, Ownable { uint256 public immutable PROTOCOL_FEE; // Minimum auction length in seconds uint256 public minimumAuctionLengthInSeconds; event NewMinimumAuctionLengthInSeconds(uint256 minimumAuctionLengthInSeconds); /** * @notice Constructor * @param _protocolFee protocol fee (200 --> 2%, 400 --> 4%) * @param _minimumAuctionLengthInSeconds minimum auction length in seconds */ constructor(uint256 _protocolFee, uint256 _minimumAuctionLengthInSeconds) { require(_minimumAuctionLengthInSeconds >= 15 minutes, "Owner: Auction length must be > 15 min"); PROTOCOL_FEE = _protocolFee; minimumAuctionLengthInSeconds = _minimumAuctionLengthInSeconds; } /** * @notice Check whether a taker bid order can be executed against a maker ask * @param takerBid taker bid order * @param makerAsk maker ask order * @return (whether strategy can be executed, tokenId to execute, amount of tokens to execute) */ function canExecuteTakerBid(OrderTypes.TakerOrder calldata takerBid, OrderTypes.MakerOrder calldata makerAsk) external view override returns ( bool, uint256, uint256 ) { uint256 startPrice = abi.decode(makerAsk.params, (uint256)); uint256 endPrice = makerAsk.price; uint256 startTime = makerAsk.startTime; uint256 endTime = makerAsk.endTime; // Underflow checks and auction length check require(endTime >= (startTime + minimumAuctionLengthInSeconds), "Dutch Auction: Length must be longer"); require(startPrice > endPrice, "Dutch Auction: Start price must be greater than end price"); uint256 currentAuctionPrice = startPrice - (((startPrice - endPrice) * (block.timestamp - startTime)) / (endTime - startTime)); return ( (startTime <= block.timestamp) && (endTime >= block.timestamp) && (takerBid.price >= currentAuctionPrice) && (takerBid.tokenId == makerAsk.tokenId), makerAsk.tokenId, makerAsk.amount ); } /** * @notice Check whether a taker ask order can be executed against a maker bid * @return (whether strategy can be executed, tokenId to execute, amount of tokens to execute) * @dev It cannot execute but it is left for compatibility purposes with the interface. */ function canExecuteTakerAsk(OrderTypes.TakerOrder calldata, OrderTypes.MakerOrder calldata) external pure override returns ( bool, uint256, uint256 ) { return (false, 0, 0); } /** * @notice Return protocol fee for this strategy * @return protocol fee */ function viewProtocolFee() external view override returns (uint256) { return PROTOCOL_FEE; } /** * @notice Update minimum auction length (in seconds) * @param _minimumAuctionLengthInSeconds minimum auction length in seconds * @dev It protects against auctions that would be too short to be executed (e.g., 15 seconds) */ function updateMinimumAuctionLength(uint256 _minimumAuctionLengthInSeconds) external onlyOwner { require(_minimumAuctionLengthInSeconds >= 15 minutes, "Owner: Auction length must be > 15 min"); minimumAuctionLengthInSeconds = _minimumAuctionLengthInSeconds; emit NewMinimumAuctionLengthInSeconds(_minimumAuctionLengthInSeconds); } }
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>girldevelopit-reveal.js - The GDI HTML Presentation Framework</title> <meta name="description" content="Girl Develop It framework for easily creating beautiful presentations using HTML in GDI theme. Forked from Hakim El Hattab's reveal.js"> <meta name="author" content="Girl Develop It"> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" /> <link rel="stylesheet" href="css/reveal.css"> <link rel="stylesheet" href="css/theme/gdidefault.css" id="theme"> <!-- For syntax highlighting --> <!-- light editor<link rel="stylesheet" href="lib/css/light.css">--> <!-- dark editor--><link rel="stylesheet" href="lib/css/dark.css"> <!-- If use the PDF print sheet so students can print slides--> <link rel="stylesheet" href="css/print/pdf.css" type="text/css" media="print"> <link rel="icon" type="image/x-icon" href="favicon.ico" /> <!--[if lt IE 9]> <script src="lib/js/html5shiv.js"></script> <![endif]--> </head> <body> <div class="reveal"> <!-- Any section element inside of this container is displayed as a slide --> <div class="slides"> <!-- Opening --> <section> <h1>GDI Reveal.js</h1> <h3>Girl Develop It's Framework for HTML Presentations</h3> <p> <small>Found at <a href ="http://github.com/girldevelopit/reveal.js">Girl Develop It reveal.js fork</a>.</small> </p> <p> <small>Original Created by <a href="http://hakim.se">Hakim El Hattab</a> / <a href="http://twitter.com/hakimel">@hakimel</a></small> </p> </section> <!-- Compatibility--> <section> <h2>Heads Up</h2> <p> reveal.js is a framework for easily creating beautiful presentations using HTML. You'll need a browser with support for CSS 3D transforms to see it in its full glory.</p> <p>We highly recommend using Chrome, currently, however, the latest version of Safari, mobile Safari (iPad), Firefox and IE9 will work. </p> </section> <section> <h2>Works in Mobile Safari</h2> <p> Try it out! You can swipe through the slides and pinch your way to the overview. </p> </section> <!-- Examples of basic html based slides --> <section> <h2>Marvelous Unordered List</h2> <ul> <li>No order here</li> <li>Or here</li> <li>Or here</li> <li>Or here</li> </ul> </section> <section> <h2>Fantastic Ordered List</h2> <ol> <li>One is smaller than...</li> <li>Two is smaller than...</li> <li>Three!</li> </ol> </section> <!-- Examples of code slides--> <section> <h2>But wait! We teach code</h2> <p>For HTML -- Surround your code with a div class "xml", then pre, then code.</p> <pre> <code> &lt;ul> &lt;li>No order here&lt;/li> &lt;li>Or here&lt;/li> &lt;li>Or here&lt;/li> &lt;li>Or here&lt;/li> &lt;/ul&gt; </code> </pre> </section> <section> <h2>But wait! We teach code</h2> <p>We can also make code editable</p> <pre> <code contenteditable> &lt;ul> &lt;li>No order here&lt;/li> &lt;li>Or here&lt;/li> &lt;li>Or here&lt;/li> &lt;li>Or here&lt;/li> &lt;/ul&gt; </code> </pre> </section> <section> <h2>But wait! We teach code</h2> <p>CSS</p> <pre> <code contenteditable class ="css"> body{ background-color: #ffffff; } </code> </pre> </section> <section> <h2>But wait! We teach code</h2> <p>Javascript</p> <pre> <code contenteditable class ="javascript"> function helloWorld(){ var name = 'GDI'; alert("Hi, " + name) } </code> </pre> </section> <section> <h2>But wait! We teach code</h2> <p>PHP</p> <pre> <code contenteditable class ="php"> function helloWorld(){ $name = 'GDI'; echo "Hi, " . $name; } </code> </pre> </section> <section> <h2>But wait! We teach code</h2> <p>Ruby</p> <pre> <code contenteditable class ="ruby"> def hello_world @name = 'GDI' puts "Hi, #{@name}" end </code> </pre> </section> <section> <h2>But wait! We teach code</h2> <p>Python</p> <pre> <code contenteditable class ="python"> def hello_world(): name = "GDI" print 'Hi, ' + name return </code> </pre> </section> <section> <h2>But wait! We teach code</h2> <p>Java</p> <pre> <code contenteditable class ="java"> public void helloWorld(){ String name = "GDI"; System.out.println("Hi," + name) } </code> </pre> </section> <!-- Elements entering one at a time--> <section> <section> <h2>Fragmented Views</h2> <p>Hit the next arrow...</p> <p class="fragment">... to step through ...</p> <ol> <li class="fragment"><code>any type</code></li> <li class="fragment"><em>of view</em></li> <li class="fragment"><strong>fragments</strong></li> </ol> <aside class="notes"> This slide has fragments which are also stepped through in the notes window. </aside> </section> <section> <h2>Fragment Styles</h2> <p>There's a few styles of fragments, like:</p> <p class="fragment grow">grow</p> <p class="fragment shrink">shrink</p> <p class="fragment roll-in">roll-in</p> <p class="fragment fade-out">fade-out</p> <p class="fragment highlight-red">highlight-red</p> <p class="fragment highlight-green">highlight-green</p> <p class="fragment highlight-blue">highlight-blue</p> </section> </section> <!-- Example of nested vertical slides --> <section> <section> <h2>Vertical Slides</h2> <p> Slides can be nested inside of other slides, try pressing <a href="#/14/1">down</a>. </p> <a href="#/14/1" class="image"> <img width="178" height="238" src="https://s3.amazonaws.com/hakim-static/reveal-js/arrow.png" alt="Down arrow"> </a> </section> <section> <h2>Basement Level 1</h2> <p>Press down or up to navigate.</p> <a href="#/14/2" class="image"> <img width="178" height="238" src="https://s3.amazonaws.com/hakim-static/reveal-js/arrow.png" alt="Down arrow"> <a href="#/14" class="image"> <img width="178" height="238" src="https://s3.amazonaws.com/hakim-static/reveal-js/arrow.png" alt="Up arrow" style="-webkit-transform: rotate(180deg);"> </a> </section> <section> <h2>Basement Level 2</h2> <a href="#/14/3" class="image"> <img width="178" height="238" src="https://s3.amazonaws.com/hakim-static/reveal-js/arrow.png" alt="Down arrow"> <a href="#/14/1" class="image"> <img width="178" height="238" src="https://s3.amazonaws.com/hakim-static/reveal-js/arrow.png" alt="Up arrow" style="-webkit-transform: rotate(180deg);"> </a> </section> <section> <h2>Basement Level 3</h2> <p>That's it, time to go back up.</p> <a href="#/14" class="image"> <img width="178" height="238" src="https://s3.amazonaws.com/hakim-static/reveal-js/arrow.png" alt="Up arrow" style="-webkit-transform: rotate(180deg);"> </a> </section> </section> <section> <h2>Point of View</h2> <p> Press <strong>ESC</strong> to enter the slide overview. Hold down alt and click on any element to zoom in on it using <a href="http://lab.hakim.se/zoom-js">zoom.js</a>. Alt + click anywhere to zoom back out. </p> </section> <section> <h2>rvl.io</h2> <p> You know, we are nerds after all and will probably get a kick out of all of this HTML. BUT, if you really don't like writing slides in HTML you can use the online editor <a href="http://www.rvl.io" target="_blank">rvl.io</a>. </p> </section> <section id="transitions"> <h2>Transition Styles</h2> <p> You can select from different transitions, like: <br> <a href="?transition=cube#/transitions">Cube</a> - <a href="?transition=page#/transitions">Page</a> - <a href="?transition=concave#/transitions">Concave</a> - <a href="?transition=zoom#/transitions">Zoom</a> - <a href="?transition=linear#/transitions">Linear</a> - <a href="?transition=none#/transitions">None</a> - <a href="?#/transitions">Default</a> </p> </section> <section id="themes"> <h2>Themes</h2> <p> Reveal.js comes with a few themes built in: <br> <a href="?theme=gdicool#/themes">GDI Cool</a> - <a href="?theme=gdilight#/themes">GDI Light</a> - <a href="?theme=gdisunny#/themes">GDI Sunny</a> - <a href="?theme=gdidefault#/themes">Default</a> </p> <p> <small> * Theme demos are loaded after the presentation which leads to flicker. In production you should load your theme in the <code>&lt;head&gt;</code> using a <code>&lt;link&gt;</code>. </small> </p> </section> <section data-state="customevent"> <h2>Custom Events</h2> <p> Additionally custom events can be triggered on a per slide basis by binding to the <code>data-state</code> name. </p> <pre><code contenteditable style="font-size: 18px; margin-top: 20px;">Reveal.addEventListener( 'customevent', function() { console.log( '"customevent" has fired' ); } ); </code></pre> </section> <section> <h2>Clever Quotes</h2> <p> These guys come in two forms, inline: <q cite="http://searchservervirtualization.techtarget.com/definition/Our-Favorite-Technology-Quotations"> The nice thing about standards is that there are so many to choose from</q> and block: </p> <blockquote cite="http://searchservervirtualization.techtarget.com/definition/Our-Favorite-Technology-Quotations"> For years there has been a theory that millions of monkeys typing at random on millions of typewriters would reproduce the entire works of Shakespeare. The Internet has proven this theory to be untrue. </blockquote> </section> <section> <h2>Intergalactic Interconnections</h2> <p> You can link between slides internally, <a href="#/1">like this</a>. </p> </section> <section> <h2>Take a Moment</h2> <p> Press b or period on your keyboard to enter the 'paused' mode. This mode is helpful when you want to take distracting slides off the screen during a presentation. </p> </section> <section> <h1>THE END</h1> <h3>BY Girl Develop It</h3> <h4>Special thanks to: Hakim El Hattab / hakim.se</h4> </section> </div> <footer> <div class="copyright"> Official class name here -- Chapter name here (if content modified from original) -- <a rel="license" href="http://creativecommons.org/licenses/by-nc/3.0/deed.en_US"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-nc/3.0/80x15.png" /></a> </div> </footer> </div> <script src="lib/js/head.min.js"></script> <script src="js/reveal.min.js"></script> <script> // Full list of configuration options available here: // https://github.com/hakimel/reveal.js#configuration Reveal.initialize({ controls: true, progress: true, history: true, theme: Reveal.getQueryHash().theme, // available themes are in /css/theme transition: Reveal.getQueryHash().transition || 'default', // default/cube/page/concave/zoom/linear/none // Optional libraries used to extend on reveal.js dependencies: [ { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, { src: 'plugin/markdown/showdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, { src: 'plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } }, { src: 'plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } } ] }); </script> </body> </html>
import unittest from ltl.syntax import * class SyntaxTest(unittest.TestCase): def setUp(self) -> None: self.f1 = Or(Finally(Var('a')), Top()) self.f2 = Then(Var(1), Until(Var("b"), Or(Var("b"), Var(1)))) self.f3 = Next(And(Bottom(), Var('a'))) def test_show(self): self.assertEqual('"a"', Var('a').show()) self.assertEqual('(F("a") | True)', self.f1.show()) assert self.f2.show() == '("1" -> ("b" U ("b" | "1")))' def test_get_atoms(self): assert self.f1.get_atoms() == {'a'} assert self.f2.get_atoms() == {1, 'b'} def test_get_vars(self): self.assertEqual({Var('a')}, self.f1.get_vars()) self.assertEqual({Var(1), Var('b')}, self.f2.get_vars()) @dataclass(frozen=True, eq=True) class IntVar(Var): data: int self.assertEqual({IntVar(5)}, IntVar(5).get_vars()) def test_typed_variables(self): @dataclass(frozen=True, eq=True) class IntVar(Var): data: int i1 = Or(IntVar(1), IntVar(2)) # print(Or(IntVar('a'), IntVar(2)).show()) def test_replace(self): assert Var('a').replace(Var('a'), Var(1)) == Var(1) assert Not(Var('a')).replace(Var('a'), Var(1)) == Not(Var(1)) assert self.f1.replace(Finally(Var('a')), Var(['a', 'b'])) == Or(Var(['a', 'b']), Top()) assert And(Var('a'), Var('a')).replace(Var('a'), Top()) == And(Top(), Top()) def test_dsl(self): assert Or(Not(Var('a')), Top()) == ~Var('a') | Top() assert self.f1 == Finally(Var('a')) | Top() assert self.f2 == (Var(1) > Until(Var("b"), Var("b") | Var(1))) assert self.f3 == Next(Bottom() & Var('a')) if __name__ == '__main__': unittest.main()
import { User } from "@prisma/client"; import { AppError } from "../../../../errors/AppError"; import { prisma } from "../../../../prisma/client"; import { CreateUserDTO } from "../../dtos/CreateUserDTO"; export class CreateUserUseCase { async execute({name, email} : CreateUserDTO): Promise<User>{ //verificar se o usuario ja existe const userAlreadyExist = await prisma.user.findUnique({ where:{ email, } }); if(userAlreadyExist){ throw new AppError("Usuario ja existente!"); } //Criar usuario const user =await prisma.user.create({ data: { name, email } }) return user; } }
'use client'; import React, { useCallback, useEffect, useState } from 'react'; import DialogCustom from '@/components/ui/dialogCustom'; import { Label } from '@/components/ui/label'; import { Button } from '@/components/ui/button'; import { useSelectedProduct } from '@/hooks/useSelectedProduct'; import { parseJSON } from '@/lib/utils'; import Image from 'next/image'; import { Controller, useForm } from 'react-hook-form'; import { Input } from '@nextui-org/react'; import { zodResolver } from '@hookform/resolvers/zod'; import { z } from 'zod'; import { useCart } from '@/hooks/useCart'; import toast from 'react-hot-toast'; import { Skeleton } from '@/components/ui/skeleton'; // import { FaCheckCircle } from 'react-icons/fa'; // import { useQueryClient } from '@tanstack/react-query'; const schema = z.object({ quantity: z .string() .refine((val) => val.length > 0, { message: 'Quantity is required' }) .transform(Number) .refine((value) => Number.isInteger(value) && value >= 0, { message: 'Quantity must be a nonnegative integer', }), }); const AddProductDialog = () => { const { isShowDialog, selectedProduct, onToggleDialog, onToggleSuccess, // onUnselectProduct, } = useSelectedProduct(); const [selectedSize, setSizeSelected] = useState(null); const [selectedQuantity, setSelectedQuantity] = useState(null); const [showError, setShowError] = useState(false); // const [showSuccess, setShowSuccess] = useState(false); const [isLoading, setIsLoading] = useState(true); const { onAddToCart } = useCart(); const { control, handleSubmit, reset, formState: { errors, isValid }, } = useForm({ resolver: zodResolver(schema), mode: 'onChange', }); const onSubmit = handleSubmit(async (data) => { if (errors.quantity) { return; } // Kiểm tra xem người dùng đã chọn đủ thông tin chưa if (!selectedSize) { return Promise.reject('Size selection is required'); } else if (!selectedQuantity) { return Promise.reject('Quantity selection is required'); } if (data.quantity > selectedQuantity) { return Promise.reject('Quantity cannot exceed available stock'); } try { onToggleDialog(); await new Promise((resolve) => setTimeout(resolve, 4000)); onToggleSuccess(); resetFormAndState(); await onAddToCart({ data: selectedProduct, quantity: data.quantity, selectedSize: selectedSize, }); } catch (error) { console.error('Failed to add product to cart:', error); return Promise.reject(error); } }); useEffect(() => { setIsLoading(!selectedProduct); }, [selectedProduct]); // useEffect(() => { // if (!isShowDialog) { // onUnselectProduct(); // } // }, [isShowDialog, onUnselectProduct]); const resetFormAndState = useCallback(() => { reset(); setSizeSelected(null); setSelectedQuantity(null); // setShowSuccess(false); setIsLoading(true); }, []); return isShowDialog ? ( <DialogCustom warningOnClose={true} className="flex justify-center items-center w-[90%] lg:w-[60%] h-[90%]" isModalOpen={isShowDialog} setIsModalOpen={onToggleDialog} callBack={resetFormAndState} > <div className="flex flex-col w-full h-auto pr-4 gap-6"> <div className="w-full h-fit flex flex-col pt-2 items-center gap-3"> <span className="text-[12px] sm:text-sm md:text-base font-semibold"> Thông tin Sản phẩm </span> <span className="text-[10px] sm:text-sm text-gray-500"> Chọn thông tin chi tiết của sản phẩm </span> <div className="w-full h-fit mt-2 flex flex-row gap-3 items-center"> {isLoading ? ( <Skeleton className="h-20 w-20 rounded-lg" /> ) : ( <Image src={parseJSON(selectedProduct.images)[0].url} alt={selectedProduct?.name} width={60} height={50} className="rounded-md object-cover object-center" /> )} {isLoading ? ( <Skeleton className="w-20 h-10" /> // Sử dụng component Skeleton từ thư viện react-loading-skeleton ) : ( <span className="text-[10px] sm:text-sm text-gray-700"> {selectedProduct?.name} </span> )} </div> </div> <div className="mb-10"> {/* Heading */} <div className="flex justify-between mb-2"> <div className="text-md font-semibold">Chọn kích cỡ</div> <div className="text-md font-medium text-black/[0.5] cursor pointer"> Kích cỡ </div> </div> {/* Heading */} {/* Size start */} <div id="sizesGrid" className="grid grid-cols-4 gap-2"> {isLoading ? ( <> <div className="col-span-1"> <Skeleton className="h-10 border-2 rounded-md py-2.5" /> </div> <div className="col-span-1"> <Skeleton className="h-10 border-2 rounded-md py-2.5" /> </div> <div className="col-span-1"> <Skeleton className="h-10 border-2 rounded-md py-2.5" /> </div> <div className="col-span-1"> <Skeleton className="h-10 border-2 rounded-md py-2.5" /> </div> </> ) : ( selectedProduct.productSizes?.map((size, index) => ( <div onClick={ size.quantity > 0 ? () => { setSizeSelected(size.size); setSelectedQuantity(size.quantity); setShowError(false); } : () => {} } key={index} className={`border-2 rounded-md text-center py-2.5 font-medium hover:bg-slate-300 cursor-pointer ${ size.quantity > 0 ? 'hover:border-black cursor-pointer' : 'cursor-not-allowed disabled bg-black/[0.1] opacity-50' } ${selectedSize === size.size ? 'border-black' : ''} `} > {size.size} </div> )) )} </div> {/* Size end */} {/* Show error */} {showError && ( <div className="text-red-600 mt-1"> Vui lòng chọn kích cỡ sản phẩm </div> )} {/* Show error */} </div> <div className="flex w-full flex-col flex-wrap md:flex-nowrap gap-3"> <Label className="font-semibold text-[10px] sm:text-[14px]"> Số lượng </Label> <Controller control={control} defaultValue={''} name="quantity" render={({ field }) => { return ( <div> <Input radius="sm" type="text" size="sm" value={field.value} onChange={field.onChange} /> {errors.quantity && ( <p className="text-red-500">{errors.quantity.message}</p> )} </div> ); }} /> {/* Start In Inventory */} <Label className="font-normal italic text-[10px] sm:text-[14px]"> Tồn kho: {selectedQuantity} </Label> {/* End In Inventory */} </div> <div className="flex w-full mt-5 justify-center items-center"> <Button className="w-[50%] inset-0 border-transparent hover:scale-105 hover:transition text-[13px] sm:text-[16px] hover:duration-200 font-semibold text-white rounded-md" onClick={() => { toast.promise( onSubmit(), { loading: 'Đang thêm vào giỏ hàng ...', success: 'Thêm vào giỏ hàng thành công!', error: (err) => `${err}`, }, { style: { minWidth: '200px', minHeight: '50px', }, position: 'bottom-right', } ); }} disabled={!isValid} > Xác nhận </Button> </div> </div> <div className="flex flex-col gap-3 items-center justify-center"> {/* Loading Dialog */} {/* {isAddingToCart && selectedSize && selectedQuantity && ( <DialogCustom className="w-[90%] lg:w-[50%] h-fit items-center justify-center" isModalOpen={isAddingToCart} notShowClose={true} > <div className="flex flex-col gap-3 items-center justify-center"> <Spinner size="lg" /> <div className="text-center font-semibold text-xs sm:text-sm"> Adding to cart ... </div> </div> </DialogCustom> )} */} {/* Success Dialog */} {/* {successAdded && ( <DialogCustom className="w-[90%] lg:w-[50%] h-fit items-center justify-center" isModalOpen={isAddingToCart} notShowClose={true} > <div className="flex flex-col gap-3 items-center justify-center"> <FaCheckCircle className="text-gray-700" size={35} /> <div className="text-center font-semibold text-xs sm:text-sm"> Added to cart! </div> </div> </DialogCustom> )} */} </div> </DialogCustom> ) : null; }; export default AddProductDialog;
/** * @addtogroup Group * @{ * @file GenericParser/ReadingPosition.hh * @author Massimiliano Pagani * @version 1.0 * @date 27/05/2010 * */ #if !defined( GENERICPARSER_READINGPOSITION_HH ) #define GENERICPARSER_READINGPOSITION_HH #include <string> namespace GenericParser { /** ReadingPosition * * * */ class ReadingPosition { public: ReadingPosition( std::string const& fileName ="", int line = 1, int column = 1 ); ReadingPosition( ReadingPosition const& copy ) = default; ReadingPosition& operator=( ReadingPosition const& copy ); void swap( ReadingPosition& other ); ~ReadingPosition() = default; std::string const& getFileName() const; int getLineNumber() const; int getColumnNumber() const; std::string const& getLineText() const; void newLine(); void moveColumn( int offset ); void setCurrentLine( std::string const& currentLine ); private: std::string fileName_; int line_; int column_; std::string lineText_; }; } #endif ///@}
import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.GregorianCalendar; public class GreenHouseNursery extends AbsGreenHouse implements Sensible { public GreenHouseNursery(GregorianCalendar calendar) { super(calendar); } /** * Reads an ordered sequence of data from the weather sensors to store in the * greenhouse * When called multiple times, appends the new readings after the current sensor * readings * * @param values An ordered sequence of [datetime, temperature, humidity, * temperature, humidity, ..., datetime, temperature, * humidity,....] * - a date and time in yyyymmddHHMMSS format. E.g. 20231106183930 * for Nov 11, 2023, 6:39:30pm * - temperature is either degrees Fahrenheit or -999 for an error * case * - humidity is either % from 0.0 to 100.0 or -999 for an error * case * Assume the sensor data always starts with a valid date * The multiple temperature humidity pairs for a single datetime * come from different plant sensors * The values may skip dates and times when the sensors are off * (you cannot assume that the date/time intervals will be * regular) * You *may* assume that the datetimes will be in ascending order */ public void pollSensorData(List<Double> values) { if (values == null || values.isEmpty()) { return; } int i = 0; while (i < values.size()) { double dateTime = values.get(i++); if (isDateTime(dateTime)) { if (isDate(dateTime) && dateTime >= calendar.getTimeInMillis()) { while (i < values.size() && isDateTime(values.get(i))) { double temperature = values.get(i++); double humidity = values.get(i++); double dateKey = toDate(dateTime); temperatures.computeIfAbsent(dateKey, k -> new ArrayList<>()).add(temperature); humidities.computeIfAbsent(dateKey, k -> new ArrayList<>()).add(humidity); } calendar.setTimeInMillis((long) dateTime); } else { i += (values.size() - i); } } else { i++; } } } /** * produces a pair of the middle temperature and humidity (respectively) from * the stored readings ignoring error values (-999s) * * @return a new SensorReading object that has the middle temperature of all the * sensor values (value at index (size() / 2) of the sorted * temperatures) * and the middle humidity of the sorted humidities * If there are no valid temperature or humidity values, respectively, * then the resulting sensor reading should have -999 for that data */ public TempHumidReading middleReading() { double middleTemperature = -999; double middleHumidity = -999; List<Double> validTemperatures = new ArrayList<>(); List<Double> validHumidities = new ArrayList<>(); for (List<Double> tempList : temperatures.values()) { for (Double temperature : tempList) { if (temperature != -999) { validTemperatures.add(temperature); } } } for (List<Double> humidityList : humidities.values()) { for (Double humidity : humidityList) { if (humidity != -999) { validHumidities.add(humidity); } } } Collections.sort(validTemperatures); Collections.sort(validHumidities); if (!validTemperatures.isEmpty()) { middleTemperature = validTemperatures.get(validTemperatures.size() / 2); } if (!validHumidities.isEmpty()) { middleHumidity = validHumidities.get(validHumidities.size() / 2); } return new TempHumidReading(middleTemperature, middleHumidity); } /** * produces a pair of the middle temperature and humidity (respectively) from * the stored readings ignoring error values (-999s) * * @param onDate the date which to consider medianReadings for (inclusive) with * the format YYYYMMDD.0 * @return a new SensorReading object that has the middle temperature of all the * sensor values (value at index (size() / 2) of the sorted * temperatures) * and the middle humidity of the sorted humidities * If there are no valid temperature or humidity values, respectively, * then the resulting sensor reading should have -999 for that data */ public TempHumidReading middleReading(double onDate) { double middleTemperature = -999; double middleHumidity = -999; List<Double> temperatureValues = temperatures.getOrDefault(onDate, new ArrayList<>()); List<Double> humidityValues = humidities.getOrDefault(onDate, new ArrayList<>()); List<Double> validTemperatures = new ArrayList<>(); List<Double> validHumidities = new ArrayList<>(); for (Double temperature : temperatureValues) { if (temperature != -999) { validTemperatures.add(temperature); } } for (Double humidity : humidityValues) { if (humidity != -999) { validHumidities.add(humidity); } } Collections.sort(validTemperatures); Collections.sort(validHumidities); if (!validTemperatures.isEmpty()) { middleTemperature = validTemperatures.get(validTemperatures.size() / 2); } if (!validHumidities.isEmpty()) { middleHumidity = validHumidities.get(validHumidities.size() / 2); } return new TempHumidReading(middleTemperature, middleHumidity); } }
import { createAction, props } from '@ngrx/store'; export enum ActionType { INCREMENT = '[Counter] Increment', DECREMENT = '[Counter] Decrement', INIT = '[Counter] Init', SET = '[Counter] Set', } export const init = createAction(ActionType.INIT); export const set = createAction(ActionType.SET, props<{ value: number }>()); export const increment = createAction( ActionType.INCREMENT, props<{ value: number }>() ); export const decrement = createAction( ActionType.DECREMENT, props<{ value: number }>() );
<?php namespace App\Http\Requests; use App\Http\Requests\Request; class StorePetRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'animal' => 'required|in:dog,cat', 'gender' => 'in:male,female', 'has_collar' => 'required|boolean', 'has_tags' => 'required|boolean', 'has_microchip' => 'boolean', ]; } }
<template> <transition name="slide"> <music-list :title="title" :bg-image="bgImage" :songs="songs"></music-list> </transition> </template> <script type="text/ecmascript-6"> import {mapGetters} from 'vuex' import {getSingerDetail} from 'api/singer' import {ERR_OK} from 'api/config' import {createSong} from 'common/js/song' import MusicList from 'components/music-list/music-list' // mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性 export default { data() { return { songs: [] } }, // 使用对象展开运算符将 getter 混入 computed 对象中 computed: { title() { return this.singer.name }, bgImage() { return this.singer.avatar }, // 从store中取数据,对应store里的getters.js ...mapGetters([ 'singer' ]) }, created() { this._getDetail() console.log(this.singer) }, methods: { _getDetail() { // 获取不到数据,就返回歌手页 if (!this.singer.id) { this.$router.push('/singer') return } // 获取歌手详情数据 getSingerDetail(this.singer.id).then((res) => { if (res.code === ERR_OK) { this.songs = this._normalizeSongs(res.data.list) console.log(this.songs) } }) }, // 处理数据 _normalizeSongs(list) { let ret = [] list.forEach((item) => { let {musicData} = item if (musicData.songid && musicData.albummid) { ret.push(createSong(musicData)) } }) return ret } }, components: { MusicList } } </script> <style scoped lang="stylus" rel="stylesheet/stylus"> @import "~common/stylus/variable" .slide-enter-active, .slide-leave-active transition: all 0.3s .slide-enter, .slide-leave-to transform: translate3d(100%, 0, 0) </style>
import { Text } from '@/styles' import { useTheme } from 'styled-components/native' import type { BaseButtonType } from 'components' import { ArrowIcon } from '@/assets/arrow-icon' import * as S from './style' type ButtonProps = { isLoading?: boolean } & BaseButtonType export const Button = ({ backgroundColor, borderColor, borderRadius, height, width, children, isLoading, ...rest }: ButtonProps) => { const theme = useTheme() return ( <S.Button backgroundColor={backgroundColor} borderColor={borderColor} borderRadius={borderRadius} height={height} width={width} disabled={isLoading} {...rest} > <Text color={theme.colors.cyan300}>{children}</Text> <S.IconWrapper> <ArrowIcon color={theme.colors.cyan300} width={24} height={16} /> </S.IconWrapper> </S.Button> ) }
import { IAchievement, IEducation, IExperience, INavItem, IProject, IService, ISkill } from './type'; import { BsCircleFill, BsCreditCard2FrontFill, BsStar, BsStarFill } from 'react-icons/bs'; import { ImDatabase, ImAirplane } from 'react-icons/im'; import { MdExplore } from 'react-icons/md'; import { FaLaptopCode, FaMedal, FaTrophy, FaGlobe, FaArtstation } from 'react-icons/fa'; import { AiFillHome } from 'react-icons/ai'; import { GiElephant, GiFruitBowl, GiElephantHead, GiSevenPointedStar } from 'react-icons/gi'; export const services: IService[] = [ { title: 'Exploring Tech & Development Stuff', about: 'I love to explore all sort of tech and development stuff, anything that grasp my interest, I\'ll try to explore it', Icon: MdExplore, }, { title: 'Backend Development', about: 'I focus primarily on backend development. I have worked on several projects on the backend side, ' + 'I think it\'s interesting to manage all sort of data in the background', Icon: ImDatabase, }, { title: 'Frontend Development', about: 'I like to try frontend development too, it\'s always a challenge to code frontend side and deliver a great design interface and experience for users', Icon: BsCreditCard2FrontFill, }, { title: 'Competitive Programming', about: 'I like to compete in programming,' + ' it\'s fun to learn and getting better at algorithms, data structure, and mostly problem solving', Icon: FaLaptopCode, }, ]; export const navItems: INavItem[] = [ { name: 'about', route: '/', }, { name: 'resume', route: '/resume', }, { name: 'projects', route: '/projects', }, ]; export const languages: ISkill[] = [ { name: 'Python', level: '67%', Icon: BsCircleFill, }, { name: 'C++', level: '88%', Icon: BsCircleFill, }, { name: 'Java', level: '70%', Icon: BsCircleFill, }, { name: 'Javascript', level: '80%', Icon: BsCircleFill, }, { name: 'Golang', level: '53%', Icon: BsCircleFill, }, { name: 'SQL', level: '70%', Icon: BsCircleFill, }, { name: 'React', level: '73%', Icon: BsCircleFill, }, { name: 'NextJs', level: '60%', Icon: BsCircleFill, }, { name: 'Spring Boot', level: '63%', Icon: BsCircleFill, }, { name: 'ExpressJs', level: '65%', Icon: BsCircleFill, }, { name: 'Flask', level: '45%', Icon: BsCircleFill, }, { name: 'MongoDB', level: '50%', Icon: BsCircleFill, }, ]; const CDN_PATH = 'https://ik.imagekit.io/2louui6ojn7/portofolio'; const EDUCATION_PATH = `${CDN_PATH}/educations`; export const educations: IEducation[] = [ { school: 'Institut Teknologi Bandung', role: 'Informatics Engineering Student', logoPath: `${EDUCATION_PATH}/itb.png`, logoWidth: 35, logoHeight: 35, SchoolIcon: GiElephant, schoolIconSize: 25, duration: '(2018 - 2022)', description: 'I received my bachelor degree in Informatics Engineering from Institut Teknologi Bandung with Cum Laude Honor', }, { school: 'Alfa Centauri SHS', role: 'Mathematics & Science Student', logoPath: `${EDUCATION_PATH}/alcent.png`, logoWidth: 35, logoHeight: 30, SchoolIcon: BsStarFill, schoolIconSize: 23, duration: '(2015 - 2018)', description: 'I became The Most Outstanding Student for the school year 2017/2018. ' + 'Activities includes mathematics olympics and CMA (Centaurian Moslem\'s Atmosphere) activity', }, { school: 'Alfa Centauri JHS', role: 'Student', logoPath: `${EDUCATION_PATH}/alcent.png`, logoWidth: 35, logoHeight: 30, SchoolIcon: BsStar, schoolIconSize: 23, duration: '(2012 - 2015)', description: 'I Got the Highest National Junior High School Exam on Batch 2012. Activities includes mathematics olympics', }, ]; const EXPERIENCE_PATH = `${CDN_PATH}/experiences`; export const experiences: IExperience[] = [ { company: 'GoTo Financial', role: 'Associate Software Engineer', logoPath: `${EXPERIENCE_PATH}/goto.png`, logoWidth: 60, logoHeight: 25, CompanyIcon: FaArtstation, companyIconSize: 23, duration: '(Aug. 2022 - Now)', description: 'Working as a Full-time Software Enginner at GoTo (Gojek Tokopedia) Financial in Clearing & Settlements Team', }, { company: 'AdaKerja', role: 'Software Engineer Part Time', logoPath: `${EXPERIENCE_PATH}/adakerja.png`, logoWidth: 40, logoHeight: 40, CompanyIcon: FaArtstation, companyIconSize: 23, duration: '(May. 2022 - Aug. 2022)', description: 'Working as a Full Stack Engineer to develop various AdaKerja applications using React, ExpressJs, and MongoDB', }, { company: 'Mekari', role: 'Software Engineer Intern', logoPath: `${EXPERIENCE_PATH}/mekari.webp`, logoWidth: 40, logoHeight: 40, CompanyIcon: GiSevenPointedStar, companyIconSize: 23, duration: '(Feb. 2022 - May. 2022)', description: 'Working as a Full Stack Engineer in Account and Launchpad Team using Ruby on Rails, VueJs, Docker, and Kong API Gateway', }, { company: 'Traveloka', role: 'Backend Engineer Intern', logoPath: `${EXPERIENCE_PATH}/traveloka.png`, logoWidth: 40, logoHeight: 40, CompanyIcon: ImAirplane, companyIconSize: 20, duration: '(Aug. 2021 - Jan. 2022)', description: 'Working on Software API Testing using Karate Framework, Mountebank, and AWS', }, { company: 'Sayurbox', role: 'Software Developer Engineer Intern', logoPath: `${EXPERIENCE_PATH}/sayurbox.png`, logoWidth: 45, logoHeight: 45, CompanyIcon: GiFruitBowl, companyIconSize: 23, duration: '(May. 2021 - Aug. 2021)', description: 'Mainly Working on Backend services using Java ' + 'Spring Boot, MySQL, MongoDB, Jenkins, and OKD.', }, { company: 'Pinhome', role: 'Software Engineer Intern', logoPath: `${EXPERIENCE_PATH}/pinhome.png`, logoWidth: 40, logoHeight: 40, CompanyIcon: AiFillHome, companyIconSize: 23, duration: '(Jan. 2021 - Mar. 2021)', description: 'Created backend services for CMS (Content Management System) to ' + 'deliver forum threads within the internal people. Created using Golang, PostgreSQL, GORM and Kubernetes', }, ]; export const achievements: IAchievement[] = [ { title: 'National Gold Medalist ACM ICPC 2021<br/>Asia Jakarta Regional', issuedBy: 'Associating Computing Machinery', description: 'International Collegiate Programming Contest is ' + 'an annual multi-tiered computer programming competition among the universities of the world', Icon: FaMedal, }, { title: 'National Gold Medalist ACM ICPC 2020<br/>Asia Jakarta Regional', issuedBy: 'Associating Computing Machinery', description: 'International Collegiate Programming Contest is ' + 'an annual multi-tiered computer programming competition among the universities of the world', Icon: FaMedal, }, { title: 'Gold Medalist GEMASTIK XIII<br/>Programming Category', issuedBy: 'Kemendikbud', description: 'GEMASTIK is an annual national IT competition ' + 'event. It has multiple competitions, one of them is the programming category', Icon: FaMedal, }, { title: '1st Winner IYCL Vol. 1', issuedBy: 'Mekari x Money Forward', description: 'IYCL (Indonesian Young Coder League) is a competition for young engineers to show off and\n' + 'prove their coding skills with others from around Indonesia', Icon: FaTrophy, }, { title: 'Top 10 in IEEEXtreme 15.0', issuedBy: 'IEEE', description: 'IEEEXtreme is a global challenge in which teams of student members compete in a 24-hour ' + 'time span against each other to solve a set of programming problems.', Icon: FaGlobe, }, { title: 'Top 15 in Shopee Code League 2021', issuedBy: 'Shopee', description: 'Shopee Code League is a 3-week coding challenge consisting of 3 coding competitions (data analytics, data science, and algorithms) ' + 'open to all students and professionals across the region.', Icon: FaGlobe, }, { title: 'Ganesha Karsa Awardee 2022', issuedBy: 'Institut Teknologi Bandung', description: 'Ganesha Karsa is an award given by Institut Teknologi Bandung every year for ' + 'getting national or international achievement representing ITB in the field of scientific or social community.', Icon: GiElephantHead, }, { title: 'Ganesha Karsa Awardee 2021', issuedBy: 'Institut Teknologi Bandung', description: 'Ganesha Karsa is an award given by Institut Teknologi Bandung every year for ' + 'getting national or international achievement representing ITB in the field of scientific or social community.', Icon: GiElephantHead, }, { title: '2nd Winner in Code Run 2021', issuedBy: 'Algobash', description: 'Code Run is the biggest open programming competition in Indonesia. Open to all Indonesian code activists without age, ' + 'profession and experience restrictions.', Icon: FaMedal, }, ]; const PROJECT_PATH = `${CDN_PATH}/projects`; export const projectData: IProject[] = [ { id: 1, name: 'My Wedding Website', description: 'Wedding Website of Ismi Dinda Muslimah & Muhammad Hasan.', imagePath: `${PROJECT_PATH}/ismi-and-hasan-wedding.webp`, deployedUrl: 'https://ismi.mhasan01.com/', githubUrl: 'https://github.com/muhammadhasan01/the-wedding-of-ismi-and-hasan', keyTechs: ['React', 'NextJs', 'DaisyUI', 'TailwindCSS', 'TypeScript'], }, { id: 2, name: 'Compete HMIF Tech', description: 'Compete HMIF Tech is a website to give Competition and Community info to the world, ' + 'this website includes starting guide to compete in competitions including ' + 'Competitive Programming, Capture The Flag, Data Science, UI/UX Competition, and Game Development', imagePath: `${PROJECT_PATH}/compete-hmif-tech-web.webp`, deployedUrl: 'https://compete.hmif.tech/', githubUrl: 'https://github.com/hmif-itb/compete.hmif.tech', keyTechs: ['React', 'NextJs', 'GatsbyJs', 'TailwindCSS', 'Markdown', 'LaTeX'], }, { id: 3, name: 'Fitness Android Application', description: 'Fitness Android Application is an android application that can support exercise activities that contain ' + 'several features such as Sport News, Training Tracker, Training History, and Training Scheduler.', imagePath: `${PROJECT_PATH}/fitness-android.webp`, deployedUrl: null, githubUrl: 'https://github.com/muhammadhasan01/fitness-android-application', keyTechs: ['Android', 'Kotlin'], }, { id: 4, name: 'Tanks Game Extended', description: 'Tanks Unity Game Extended! is a Tanks Game made with Unity. This game is a development of the Game Tanks Tutorial! ' + 'so that in our game there are several additional features, such as LAN multiplayer, room system, bots, new weapons, ' + 'money rush mode, and others.', imagePath: `${PROJECT_PATH}/tanks-extended.webp`, deployedUrl: null, githubUrl: 'https://github.com/muhammadhasan01/tanks-extended', keyTechs: ['Unity', 'C#'], }, { id: 5, name: 'Academic Information System', description: 'This Academic Information System application was developed to meet the needs of academic administration activities on the STEI campus (School of Electrical and Informatics Engineering). ' + 'This Academic Information System is managed by the admin and can be used by students and lecturers.', imagePath: `${PROJECT_PATH}/SIAK.webp`, deployedUrl: null, githubUrl: 'https://github.com/muhammadhasan01/aplikasi-sistem-informasi-akademik', keyTechs: ['MySQL', 'Python', 'PyQt', 'GUI'], }, { id: 6, name: 'Money Monitoring Application', description: 'Money Monitoring Application is an application to monitor the finances of units and subunits at ' + 'the School of Electrical and Informatics Engineering ITB. ' + 'This app is built with ReactJS, React-Bootstrap, and several additional libraries.', imagePath: `${PROJECT_PATH}/stei-anggaran.webp`, deployedUrl: 'https://stei-monitoring-anggaran-15.herokuapp.com/', githubUrl: 'https://github.com/muhammadhasan01/aplikasi-monitor-keuangan-frontend', keyTechs: ['MongoDB', 'ExpressJs', 'ReactJs', 'NodeJs', 'Bootstrap', 'JWT'], }, { id: 7, name: 'Avatar Duel Game Card', description: 'Avatar Duel Game Card is a card game application created with JavaFX. ' + 'This game can be played by two people, each person has a card containing 3 types, ' + 'namely land, character, and skill cards. Each of these dueling avatar cards has its own function, ' + 'and of course, the contents of these cards are based on Avatar: The Last Airbender. ' + 'The main objective of this game is to defeat the opposing player by reducing the opponent\'s health point to 0 or less.', imagePath: `${PROJECT_PATH}/avatar-dual.webp`, deployedUrl: null, githubUrl: 'https://github.com/muhammadhasan01/AvatarDuelGameCard', keyTechs: ['Java', 'JavaFX', 'OOP', 'GUI'], }, { id: 8, name: 'Halma AI', description: 'Halma is a strategy board game. The core of the project is implementing AI in the bot (computer player), ' + 'using Minimax Algorithm, Local Search Algorithms (Hill Climbing or Simulated Annealing), ' + 'and both, and finding out how good each algorithm performs.', imagePath: `${PROJECT_PATH}/halma-ai.webp`, deployedUrl: 'https://halma-euy.netlify.app/', githubUrl: 'https://github.com/muhammadhasan01/halma-AI', keyTechs: ['AI', 'HTML', 'CSS', 'Javascript'], }, { id: 9, name: 'Discord Bot', description: 'Simple discord bot that can give you quotes and handle your todo tasks', imagePath: `${PROJECT_PATH}/discord-bot.webp`, deployedUrl: null, githubUrl: 'https://github.com/muhammadhasan01/discord-bot', keyTechs: ['Discord API', 'Python', 'MySQL', 'Docker'], }, { id: 10, name: 'Calculator Application', description: 'Calculator application is an application created using the Java programming language with GUI Swing. ' + 'This Calculator application, as the name implies, is a calculator that can perform operations on mathematical expressions such as addition, subtraction, multiplication, and division.', imagePath: `${PROJECT_PATH}/calculator.webp`, deployedUrl: null, githubUrl: 'https://github.com/muhammadhasan01/Kalkulator_Java_Swing', keyTechs: ['Java', 'GUI', 'Java Swing'], }, { id: 11, name: 'Golang RESTful API Forum', description: 'Golang RESTful API project provides the backend for a discussion forum with Users, Threads and Posts', imagePath: `${PROJECT_PATH}/golang.webp`, deployedUrl: null, githubUrl: 'https://github.com/muhammadhasan01/go-rest-api-forum', keyTechs: ['Golang', 'RESTful API', 'PostgreSQL'], }, { id: 12, name: 'Conway Game Of Life', description: 'Conway Game of Life Implementation in Java.', imagePath: `${PROJECT_PATH}/conway.webp`, deployedUrl: null, githubUrl: 'https://github.com/muhammadhasan01/conway-game-of-life-java', keyTechs: ['Java', 'TDD', 'Gradle', 'Game'], }, { id: 13, name: 'Chat Application', description: 'Simple Realtime Chat Application', imagePath: `${PROJECT_PATH}/chat.webp`, deployedUrl: null, githubUrl: 'https://github.com/muhammadhasan01/chat-application', keyTechs: ['React', 'ExpressJs', 'Socket.io', 'Vite', 'TypeScript'], }, { id: 14, name: 'URL Shortener', description: 'Fullstack URL Shortener', imagePath: `${PROJECT_PATH}/url-shortener.webp`, deployedUrl: null, githubUrl: 'https://github.com/muhammadhasan01/url-shortener', keyTechs: ['MongoDB', 'ExpressJs', 'React', 'NodeJs', 'Vite', 'TypeScript', 'Docker'], }, { id: 15, name: 'Notal Autograder', description: 'Control Flow Graph (CFG) Based Notasi Algoritmik Autograder is a system that can grade student Notasi Algoritmik submission by comparing its CFG structure with instructor Notasi Algoritmik submission\'s CFG structure.', imagePath: `${PROJECT_PATH}/notal-autograder.webp`, deployedUrl: null, githubUrl: 'https://github.com/muhammadhasan01/notal-autograder', keyTechs: ['Autograder', 'Python', 'Flask', 'Docker', 'CFG', 'AST'], }, { id: 16, name: 'Personal Website', description: 'This is my personal website where I my put my information including activities, ' + 'resume, and projects. Created with NextJs, Typescript, React, Framer Motion, and Tailwind CSS. ' + '(This is what you are seeing right now :D)', imagePath: `${PROJECT_PATH}/personal-website.webp`, deployedUrl: 'https://mhasan01.com/', githubUrl: 'https://github.com/muhammadhasan01/portofolio', keyTechs: ['NextJs', 'React', 'Framer Motion', 'Tailwind CSS'], }, { id: 17, name: 'Competitive Programming Repo', description: 'Collection of my competitive programming codes including libraries and competition solutions', imagePath: `${PROJECT_PATH}/cp.webp`, deployedUrl: null, githubUrl: 'https://github.com/muhammadhasan01/cp', keyTechs: ['C++', 'Algorithms', 'Data Structure'], }, { id: 18, name: 'Willy Wangky Web', description: 'Willi Wangky Choco Factory is a web-based online chocolate trading application.' + ' This application is made using PHP on the backend and HTML, CSS, and Javascript on the frontend.', imagePath: `${PROJECT_PATH}/willy-wangky.webp`, deployedUrl: null, githubUrl: 'https://github.com/muhammadhasan01/willy-wangky-web', keyTechs: ['HTML', 'CSS', 'Javascript', 'PHP'], }, ];
import config from './config.js'; export default { fetch(searchText) { const indexHtml = `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{{title}}</title> <style> body { font-family: Arial, sans-serif; background-color: #ffffff; /* 白色背景 */ color: #333; /* 主要文本颜色 */ margin: 0; padding: 0; } .container { max-width: 800px; margin: 0 auto; padding: 20px; } .button-container { display: grid; grid-template-columns: repeat(5, 100px); /* 列数和宽度 */ grid-gap: 8px; /* 按钮间距 */ } .button { padding: 6px; text-align: center; background-color: #f0f8ff; /* 淡蓝色背景 */ border-radius: 5px; cursor: pointer; /* 鼠标悬停时显示手型光标 */ transition: background-color 0.3s; /* 添加过渡效果 */ } .button:hover { background-color: #add8e6; /* 悬停时的背景颜色变化 */ } a { text-decoration: none; /* 移除链接下划线 */ color: #333; /* 链接文本颜色 */ display: block; /* 将链接元素设置为块级元素,使其占据整个列表项空间 */ padding: 10px; /* 为链接添加内边距,使整个列表项可点击 */ } input[type="text"] { width: 92.3%; height: 30px; padding: 10px; border: 1px solid #ccc; border-radius: 5px; } </style> </head> <body> <div class="container"> <h1> 搜索 <form id="searchForm" action="/" method="GET"> <input type="text" id="searchInput" name="query" placeholder="输入搜索内容并按回车" value="{{keyword}}"/> </form> </h1> <div class="button-container"> {{button_list}} </div> </div> <script> document.getElementById("searchInput").addEventListener("keypress", function(e) { if (e.key === "Enter") { e.preventDefault(); // 阻止默认提交行为 var query = document.getElementById("searchInput").value; var url = "{{base}}" + query; window.location.href = url; } }); </script> </body> </html> `; let title = config.title; const base = config.base; const resourceList = config.urls; const keyword = searchText || ''; let html = indexHtml.replace('{{base}}', base).replace('{{keyword}}', keyword); const encodeSearchText = encodeURIComponent(searchText); const buttonList = []; if (searchText) { for (const resource of resourceList) { const finalUrl = resource.url.replace('%s', encodeSearchText); buttonList.push(`<div class="button"><a href="${finalUrl}">${resource.name}</a></div>`); } title += ' - ' + searchText; } return html.replace('{{title}}', title).replace('{{button_list}}', buttonList.join('\n')); }, };
import {Schema, Prop, SchemaFactory} from '@nestjs/mongoose'; import mongoose, { HydratedDocument } from 'mongoose'; import { Bakery } from 'src/bakeries/bakery.schema'; import { Review } from 'src/bakeries/reviews.schema'; import { Like } from 'src/likes/like.schema'; import { Transform } from 'class-transformer'; export type UserDocument = HydratedDocument<User>; export enum Platform { GOOGLE = 'google', KAKAO = 'kakao', NAVER = 'naver', } @Schema() export class User { @Transform(({ value }) => value.toString()) _id: string; @Prop() platform: Platform; @Prop() email: string; @Prop() name: string; @Prop() thumbnail: string; @Prop({ default: Date.now }) createdAt: Date; @Prop() deletedAt?: Date; @Prop() reviewCount?: number @Prop() visitied?: Bakery[] @Prop({ default: 0 }) temperature: number; @Prop() refreshToken?: string; @Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Like' }] }) likes: Like[]; } export const UserSchema = SchemaFactory.createForClass(User);
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_atoi.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: omoreno- <omoreno-@student.42barcel> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2022/08/17 09:35:56 by omoreno- #+# #+# */ /* Updated: 2022/12/01 13:08:25 by omoreno- ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft_mand.h" static int ft_isspace(char c) { int ret; ret = ((c == ' ') || (c == '\n') || (c == '\t') || (c == '\v') || (c == '\f') || (c == '\r')); return (ret); } static int ft_take_sign(char **p) { int sign; sign = 1; if (**p == '+') (*p)++; else if (**p == '-') { (*p)++; sign = -1; } return (sign); } int ft_atoi(const char *str) { int ret; int s; char *p; p = (char *)str; ret = 0; while (*p && ft_isspace(*p)) p++; s = ft_take_sign(&p); while (*p && ft_isdigit(*p)) { ret *= 10; ret += *p - '0'; p++; } ret *= s; return (ret); }
<?php /** * IRC Server Connection Class * * @author Viper-7 * @date 2009/08/27 * @package V7IRCFramework * @example channels/Simplechannel.php * * Handles the connection and communication to an IRC server */ class IRCServerConnection { /** * Static reference to the connection object */ public static $server_connection; /** * The active connection handle to the server * * @var Resource */ private $conn; /** * The output buffer for outbound data * FIFO Stack held in memory * * @var Array */ private $buffer; /** * The currently connected server * * @var String */ public $server; /** * The currently connected server's port * * @var Int */ public $port; /** * The bot's current Nickname * * @var String */ public $nick; /** * Flag to allow connection and polling * * @var Boolean */ public $connected; /** * Flag to send identification information on connection * * @var Boolean */ public $authenticated; /** * Flag to tell if we're 100% online and ready to roll * * @var Boolean */ public $online; /** * Object to pass messages to * * @var Object */ public $messageHandler; /** * Time to wait between polls * * @var Int */ public $pollInterval = 1; /** * Flag to control dumping of debugging information to the console * * @var Boolean */ public $debug; /** * Cycles since startup * * @var Int */ public $cycles; /** * Tracks the last time the bot was pinged, to reconnect if everything else fails */ private $lastping = PHP_INT_MAX; /** * Creates a new outbound buffer resource and connects to the server * * @param String Server to connect to * @param String Port to connect to * @param String Nickname to use * @param Array List of channels to join */ public function __construct($server, $port, $nickname, $channels, $debug = FALSE) { if(!empty(self::$server_connection) && self::$server_connection->connected) { $this->online = FALSE; $this->connected = FALSE; throw new IRCServerException('You cannot connect to more than one server at a time!'); } set_time_limit(0); register_shutdown_function(Array('IRCServerConnection', 'destroy')); $this->buffer = Array(); $this->server = $server; $this->port = $port; $this->nick = $nickname; $this->debug = $debug; self::$server_connection = $this; try { $this->connect($channels); } catch(IRCServerException $e) { $this->online = FALSE; $this->connected = FALSE; throw $e; } } /** * (re)Connects to the server */ private function connect($channels) { if($this->connected) { $this->online = FALSE; $this->connected = FALSE; throw new IRCServerException('Already connected to a server!'); } $this->conn = fsockopen($this->server,$this->port,$errno,$errstr,30); if(empty($this->conn)) { $this->online = FALSE; $this->connected = FALSE; throw new IRCServerException('Failed to connect to server'); } $this->connected = TRUE; foreach($channels as $channel) { IRCServerChannel::getChannel($channel); } $this->serverLoop(); } public static function destroy() { self::$server_connection->connected = FALSE; self::$server_connection->online = FALSE; self::$server_connection->sendImmediate('QUIT'); } /** * Process an incoming message * * @param string Raw line from the server */ private function processIncoming($message) { $parts = explode(' ', trim($message,": \r\n")) + array('', ''); switch($parts[0]) { case 'NOTICE': if(!$this->authenticated && $parts[1] == 'AUTH') { $this->send_line("NICK {$this->nick}"); $this->send_line("USER {$this->nick} localhost {$this->server} :{$this->nick}"); $this->authenticated = TRUE; } break; case 'PING': $this->lastping = time(); $this->send_line('PONG ' . $parts[1]); } switch($parts[1]) { case 'PRIVMSG': $content = trim(implode(' ', array_slice($parts, 3)), ": "); if(substr($content,0,1) == "\001") { $ctcp = true; $content = trim($content, "\001"); } if($content == 'VERSION' && $ctcp) { $this->sendCTCP(IRCServerUser::getByHostmask($parts[0])->nick, 'VERSION V7IRC'); } else { if($parts[2] != $this->nick) { // Process channel text $user = IRCServerUser::getByHostmask($parts[0]); $chan = IRCServerChannel::getChannel($parts[2]); $chan->event_msg($user, $content); } else { // Process private message } } break; case 'KICK': $content = trim(implode(' ', array_slice($parts, 4)), ": "); if($parts[3] == $this->nick) { $user = IRCServerUser::getByHostmask($parts[0]); $chan = IRCServerChannel::getChannel($parts[2]); $chan->online = FALSE; $chan->event_kicked($user, $content); } else { $user = IRCServerUser::getByHostmask($parts[0]); $victim = IRCServerUser::getUser($parts[3]); $chan = IRCServerChannel::getChannel($parts[2]); unset($victim->channels[$chan->channel]); $chan->event_kick($user, $content, $victim); } break; case 'JOIN': $chan = IRCServerChannel::getChannel($parts[2]); $user = IRCServerUser::getByHostmask($parts[0], $chan->channel); $chan->event_join($user); break; case 'PART': $user = IRCServerUser::getByHostmask($parts[0]); $chan = IRCServerChannel::getChannel($parts[2]); unset($user->channels[$chan->channel]); $chan->event_part($user); break; case 'QUIT': $content = trim(implode(' ', array_slice($parts, 3)), ": "); $user = IRCServerUser::getByHostmask($parts[0]); foreach(IRCServerChannel::$channels as $chan) { foreach($chan->users as $chanuser) { if($chanuser == $user) { unset($user->channels[$chan->channel]); $chan->event_quit($user, $content); } } } break; case 'NOTICE': $content = trim(implode(' ', array_slice($parts, 3)), ": \001"); $user = IRCServerUser::getByHostmask($parts[0]); if($parts[2] != $this->nick) { $chan = IRCServerChannel::getChannel($parts[2]); $chan->event_notice($user, $content); } break; case 'MODE': $content = trim(implode(' ', array_slice($parts, 3)), ": \001"); $user = IRCServerUser::getByHostmask($parts[0]); if($parts[2] != $this->nick) { $chan = IRCServerChannel::getChannel($parts[2]); $chan->event_mode($user, $content); $chan->add_modes($content); } break; case '005': $this->online = TRUE; break; case '332': $content = trim(implode(' ', array_slice($parts, 4)), ": "); $chan = IRCServerChannel::getChannel($parts[3]); $chan->topic = $content; break; case '353': $channel_obj = IRCServerChannel::getChannel(strtolower($parts[4])); $channel_obj->event_names(trim(implode(' ', array_slice($parts, 5)), ": ")); break; case '366': $channel_obj = IRCServerChannel::getChannel(strtolower($parts[3])); $channel_obj->event_names_end(); break; } } /** * Primary server loop */ private function serverLoop() { while($this->connected) { $this->cycles++; // If we havent been pinged in the last 5 minutes, exit if($this->lastping < time() - 300) { $this->connected = FALSE; } // If our connection has dropped, exit the loop if(!is_resource($this->conn)) { $this->connected = FALSE; } if(!$this->connected) { return; } if($this->online) { foreach(IRCServerChannel::$channels as $channel) { if(!$channel->online && time() % 2 == 0) { $channel->autojoin(); } if(method_exists($channel, 'poll')) { $channel->poll($this->cycles); } } } if(count($this->buffer)) { // Process outbound data $message = array_shift($this->buffer); fputs($this->conn, $message); if($this->debug) { echo ' >>> ' . $message; } } $connections = Array($this->conn); $write = NULL; $expect = NULL; if(stream_select($connections, $write, $expect, 1, 0)) { // There is data to process if(!empty($connections)) { // Process inbound data foreach($connections as $connection) { $message = fgets($connection); } if($message == '') { // If our connection has dropped, exit the loop $this->connected = FALSE; return; } if($this->debug) { echo '<<< ' . str_replace("\001", '**', $message); } $this->processIncoming($message); } } } } /** * Send a line to the server without using the message buffer * * @param String The line of text to send to the server */ public function sendImmediate($message) { if(!$this->connected) { $this->online = FALSE; $this->connected = FALSE; throw new IRCServerException('Not connected! Unable to send a message'); } fputs($this->conn, trim($message) . "\n"); } /** * Send a line to the server * * @param String The line of text to send to the server */ public function send_line($message) { if(!$this->connected) { $this->online = FALSE; $this->connected = FALSE; throw new IRCServerException('Not connected! Unable to send a message'); } $this->buffer[] = trim($message) . "\n"; } /** * Send a message to a channel or user * * @param String Destination user or channel for the message * @param String The message itself */ public function send_msg($dest, $message) { $this->send_line("PRIVMSG $dest :$message"); } /** * Send a CTCP message to a channel or user * * @param String Destination user or channel for the CTCP message * @param String The message itself */ public function sendCTCP($dest, $message) { $this->send_line("PRIVMSG $dest :\001$message\001"); } }
/* * Copyright (c) 2024 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.element.android.libraries.preferences.impl.store import androidx.datastore.core.DataMigration import androidx.datastore.preferences.core.Preferences class SessionPreferencesStoreMigration( private val sharePresenceKey: Preferences.Key<Boolean>, private val sendPublicReadReceiptsKey: Preferences.Key<Boolean>, ) : DataMigration<Preferences> { override suspend fun cleanUp() = Unit override suspend fun shouldMigrate(currentData: Preferences): Boolean { return currentData[sharePresenceKey] == null } override suspend fun migrate(currentData: Preferences): Preferences { // If sendPublicReadReceiptsKey was false, consider that sharing presence is false. val defaultValue = currentData[sendPublicReadReceiptsKey] ?: true return currentData.toMutablePreferences().apply { set(sharePresenceKey, defaultValue) }.toPreferences() } }
import { Post } from "@/types/post"; import { MongoClient } from "mongodb"; import { LocalPostRepository } from "./local"; export default class MongoLocalPostRepository implements LocalPostRepository { private mongoClient: MongoClient = new MongoClient(process.env.MONGODB_URI as string, {}); private db = this.mongoClient.db(process.env.MONGODB_DBNAME as string); constructor() { } async loadPosts(): Promise<Post[]> { try { await this.mongoClient.connect(); const collection = this.db.collection("posts"); const posts = await collection .find({ published: true }) .sort({ date: -1, lastEditedAt: -1 }) .toArray(); return posts.map((r) => ({ id: r.id.toString(), slug: r.slug, title: r.title, categories: r.categories, cover: r.cover, date: new Date(r.date).toDateString(), published: r.published, lastEditedAt: r.lastEditedAt, })); } catch (error) { console.error("Error fetching data:", error); throw new Error(`Error fetching posts`); } finally { await this.mongoClient.close(); } } async savePosts(posts: Post[]): Promise<void> { try { await this.mongoClient.connect(); const collection = this.db.collection("posts"); for (const post of posts) { const postExists = await collection.findOne({ id: post.id }); if (postExists) { await collection.updateOne( { id: post.id }, { $set: { slug: post.slug, title: post.title, cover: post.cover, date: new Date(post.date), published: post.published, lastEditedAt: post.lastEditedAt, }, } ); } else { await collection.insertOne({ id: post.id, slug: post.slug, title: post.title, cover: post.cover, categories: post.categories, date: new Date(post.date), published: post.published, lastEditedAt: post.lastEditedAt, }); } } } catch (error) { console.error("Error saving posts:", error); throw new Error(`Error saving posts`); } finally { await this.mongoClient.close(); } } async getAllPosts(): Promise<Post[]> { try { const collection = this.db.collection("posts"); const filter = { published: true }; const posts = await collection .find(filter) .sort({ date: -1, lastEditedAt: -1 }) .toArray(); return posts.map((r) => ({ id: r.id.toString(), slug: r.slug, title: r.title, categories: r.categories, cover: r.cover, date: new Date(r.date).toDateString(), published: r.published, lastEditedAt: Number(r.lastEditedAt), })); } catch (error) { console.error('Error fetching data:', error); throw new Error(`Error fetching posts`); } } async getAllPostCategories(): Promise<string[]> { try { const collection = this.db.collection("posts"); const pipeline = [ { $match: { published: true } }, { $project: { _id: 0, categories: 1 } }, { $unwind: "$categories" }, { $group: { _id: "$categories" } }, { $sort: { _id: 1 } }, ]; const result = await collection.aggregate(pipeline).toArray(); return result.map((r) => r._id); } catch (error) { console.error('Error fetching data:', error); throw new Error(`Error fetching post categories`); } } async getAllPostsSlugs(): Promise<string[]> { try { const collection = this.db.collection("posts"); const filter = { published: true }; const result = await collection.find(filter).project({ slug: 1, _id: 0 }).toArray(); return result.map((r) => r.slug); } catch (error) { console.error('Error fetching data:', error); throw new Error(`Error fetching slugs`); } } async getPostWithSlug(slug: string): Promise<Post | undefined> { try { const collection = this.db.collection("posts"); const filter = { published: true, slug: slug }; const post = await collection.findOne(filter); if (post) { return { id: post.id.toString(), slug: post.slug, title: post.title, categories: post.categories, cover: post.cover, date: new Date(post.date).toDateString(), published: post.published, lastEditedAt: Number(post.lastEditedAt), }; } else { return undefined; } } catch (error) { console.error('Error fetching data:', error); throw new Error(`Error fetching post with slug ${slug}`); } } async getRelatedPosts(post: Post): Promise<Post[]> { try { const collection = this.db.collection("posts"); const filter = { published: true, slug: { $ne: post.slug }, categories: { $in: post.categories }, }; const posts = await collection.find(filter).toArray(); return posts.map((r) => ({ id: r.id.toString(), slug: r.slug, title: r.title, categories: r.categories, cover: r.cover, date: new Date(r.date).toDateString(), published: r.published, lastEditedAt: Number(r.lastEditedAt), })); } catch (error) { console.error('Error fetching data:', error); throw new Error(`Error fetching related posts for ${post.slug}`); } } }
import { useCallback } from "react"; import Particles from "react-tsparticles"; //import { loadFull } from "tsparticles"; // if you are going to use `loadFull`, install the "tsparticles" package too. import { loadSlim } from "tsparticles-slim"; const Particle = () => { const particlesInit = useCallback(async engine => { // console.log(engine); // you can initiate the tsParticles instance (engine) here, adding custom shapes or presets // this loads the tsparticles package bundle, it's the easiest method for getting everything ready // starting from v2 you can add only the features you need reducing the bundle size //await loadFull(engine); await loadSlim(engine); }, []); const particlesLoaded = useCallback(async container => { // await console.log(container); }, []); return ( <Particles id="tsparticles" init={particlesInit} loaded={particlesLoaded} options={{ background: { // color: { // value: "#ffffff", // }, }, fpsLimit: 120, "particles": { "number": { "value": 58, "density": { "enable": true, "value_area": 800 } }, "color": { "value": "#fff" }, "shape": { "type": "bubble", "stroke": { "width": 0, "color": "#fff" }, "polygon": { "nb_sides": 5 }, // "image": { // "src": "img/github.svg", // "width": 100, // "height": 100 // } }, "opacity": { "value": 0.2244776885211732, "random": false, "anim": { "enable": false, "speed": 1, "opacity_min": 0.1, "sync": false } }, "size": { "value": 4.008530152163807, "random": false, "anim": { "enable": false, "speed": 40, "size_min": 0.1, "sync": false } }, "line_linked": { "enable": false, "distance": 128.27296486924183, "color": "#fff", "opacity": 0.4, "width": 2.0844356791251797 }, "move": { "enable": true, "speed": 3.206824121731046, "direction": "none", "random": false, "straight": false, "out_mode": "out", "bounce": false, "attract": { "enable": false, "rotateX": 600, "rotateY": 641.3648243462092 } } }, "interactivity": { "detect_on": "window", "events": { "onhover": { "enable": true, "mode": "repulse" }, "onclick": { "enable": false, "mode": "push" }, "resize": true }, "modes": { "grab": { "distance": 400, "line_linked": { "opacity": 1 } }, "bubble": { "distance": 400, "size": 80, "duration": 2, "opacity": 8, "speed": 3, "color":"#fff" }, "repulse": { "distance": 200, "duration": 0.4 }, "push": { "particles_nb": 4 }, "remove": { "particles_nb": 2 } } }, "retina_detect": true }} /> ); }; export default Particle;
<?php namespace ASENHA\Classes; /** * Class for Redirect After Login module * * @since 6.9.5 */ class Redirect_After_Login { /** * Redirect to custom internal URL after login for user roles * * @param string $redirect_to_url URL to redirect to. Default is admin dashboard URL. * @param string $origin_url URL the user is coming from. * @param object $user logged-in user's data. * @since 1.5.0 */ public function redirect_after_login( $username, $user ) { $options = get_option( ASENHA_SLUG_U, array() ); $this->redirect_to_single_url( $username, $user ); } /** * Redirect all applicable user roles to a single URL * * @since 7.3.3 */ public function redirect_to_single_url( $username, $user ) { $options = get_option( ASENHA_SLUG_U, array() ); $redirect_after_login_to_slug_raw = ( isset( $options['redirect_after_login_to_slug'] ) ? $options['redirect_after_login_to_slug'] : '' ); $relative_path = $this->get_redirect_relative_path( $redirect_after_login_to_slug_raw ); $redirect_after_login_for = ( isset( $options['redirect_after_login_for'] ) ? $options['redirect_after_login_for'] : array() ); if ( isset( $redirect_after_login_for ) && count( $redirect_after_login_for ) > 0 ) { // Assemble single-dimensional array of roles for which custom URL redirection should happen $roles_for_custom_redirect = array(); foreach ( $redirect_after_login_for as $role_slug => $custom_redirect ) { if ( $custom_redirect ) { $roles_for_custom_redirect[] = $role_slug; } } // Does the user have roles data in array form? if ( isset( $user->roles ) && is_array( $user->roles ) ) { $current_user_roles = $user->roles; } // Set custom redirect URL for roles set in the settings. Otherwise, leave redirect URL to the default, i.e. admin dashboard. foreach ( $current_user_roles as $role ) { if ( in_array( $role, $roles_for_custom_redirect ) ) { wp_safe_redirect( home_url( $relative_path ) ); exit; } } } } /** * Get the relative path to redirect to based on the raw redirect slug * * @since 7.3.3 */ public function get_redirect_relative_path( $redirect_after_login_to_slug_raw ) { if ( !empty( $redirect_after_login_to_slug_raw ) ) { $redirect_after_login_to_slug = trim( trim( $redirect_after_login_to_slug_raw ), '/' ); if ( false !== strpos( $redirect_after_login_to_slug, '.php' ) ) { $slug_suffix = ''; } else { $slug_suffix = '/'; } $relative_path = $redirect_after_login_to_slug . $slug_suffix; } else { $relative_path = ''; } return $relative_path; } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\HttpCache; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\HttpKernelInterface; /** * Abstract class implementing Surrogate capabilities to Request and Response instances. * * @author Fabien Potencier <fabien@symfony.com> * @author Robin Chalas <robin.chalas@gmail.com> */ abstract class AbstractSurrogate implements SurrogateInterface { protected $contentTypes; protected $phpEscapeMap = array( array('<?', '<%', '<s', '<S'), array('<?php echo "<?"; ?>', '<?php echo "<%"; ?>', '<?php echo "<s"; ?>', '<?php echo "<S"; ?>'), ); /** * Constructor. * * @param array $contentTypes An array of content-type that should be parsed for Surrogate information * (default: text/html, text/xml, application/xhtml+xml, and application/xml) */ public function __construct(array $contentTypes = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/xml')) { $this->contentTypes = $contentTypes; } /** * Returns a new cache strategy instance. * * @return ResponseCacheStrategyInterface A ResponseCacheStrategyInterface instance */ public function createCacheStrategy() { return new ResponseCacheStrategy(); } /** * {@inheritdoc} */ public function hasSurrogateCapability(Request $request) { if (null === $value = $request->headers->get('Surrogate-Capability')) { return false; } return false !== strpos($value, sprintf('%s/1.0', strtoupper($this->getName()))); } /** * {@inheritdoc} */ public function addSurrogateCapability(Request $request) { $current = $request->headers->get('Surrogate-Capability'); $new = sprintf('symfony="%s/1.0"', strtoupper($this->getName())); $request->headers->set('Surrogate-Capability', $current ? $current.', '.$new : $new); } /** * {@inheritdoc} */ public function needsParsing(Response $response) { if (!$control = $response->headers->get('Surrogate-Control')) { return false; } $pattern = sprintf('#content="[^"]*%s/1.0[^"]*"#', strtoupper($this->getName())); return (bool) preg_match($pattern, $control); } /** * {@inheritdoc} */ public function handle(HttpCache $cache, $uri, $alt, $ignoreErrors) { $subRequest = Request::create($uri, Request::METHOD_GET, array(), $cache->getRequest()->cookies->all(), array(), $cache->getRequest()->server->all()); try { $response = $cache->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true); if (!$response->isSuccessful()) { throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %s).', $subRequest->getUri(), $response->getStatusCode())); } return $response->getContent(); } catch (\Exception $e) { if ($alt) { return $this->handle($cache, $alt, '', $ignoreErrors); } if (!$ignoreErrors) { throw $e; } } } /** * Remove the Surrogate from the Surrogate-Control header. * * @param Response $response */ protected function removeFromControl(Response $response) { if (!$response->headers->has('Surrogate-Control')) { return; } $value = $response->headers->get('Surrogate-Control'); $upperName = strtoupper($this->getName()); if (sprintf('content="%s/1.0"', $upperName) == $value) { $response->headers->remove('Surrogate-Control'); } elseif (preg_match(sprintf('#,\s*content="%s/1.0"#', $upperName), $value)) { $response->headers->set('Surrogate-Control', preg_replace(sprintf('#,\s*content="%s/1.0"#', $upperName), '', $value)); } elseif (preg_match(sprintf('#content="%s/1.0",\s*#', $upperName), $value)) { $response->headers->set('Surrogate-Control', preg_replace(sprintf('#content="%s/1.0",\s*#', $upperName), '', $value)); } } }
{% extends "includes/layout.html" %} {% block title %} Project Page {% endblock %} {% block main %} <div class="container" id="projectPageContainer"> <!-- Image card --> <div class="row"> <div class="col-lg-5 mb-3"> <div class="card project-card"> <img src="/{{ project['image_path'] }}" class="card-img" alt="project image" /> <button disabled class="btn-orange w-100"> {% if project["public_key"] == session["public_key"] %} Your project {% endif %} </button> <div class="card-body d-flex w-100 justify-content-center"> <p class="card-text fs-6 text-dark ms-2 my-auto"> ID {{ project["project_id"] }} | {{ project["name"] }} | {{ project["category"] | capitalize }} </p> </div> <div class="card-footer"> {% if project["status"].lower() == "active" %} <button disabled class="btn btn-primary btn-sm"> {{ "Active" | capitalize }} </button> <button disabled class="btn btn-outline-dark btn-sm"> {{ project["days_left"] }} </button> {% else %} <button disabled class="btn btn-danger btn-sm"> {{ project["status"] | capitalize }} </button> {% endif %} <button disabled class="btn btn-success btn-sm"> {{ project["funding_progress"] }} funded </button> </div> </div> </div> <div class="col-lg-7"> <!-- Info cards with project data --> <div class="row align-items-center"> <div class="col justify-content-center"> <div class="info-card"> <div class="info-card-title">{{ project['total_donations'] }}</div> <p class="info-card-text">Donated</p> </div> </div> <div class="col justify-content-center"> <div class="info-card"> <div class="info-card-title">{{ project['goal'] }}</div> <p class="info-card-text">Goal</p> </div> </div> </div> <!-- Project description --> <div class="row text-start mt-4"> <div class="col"> <p class="fs-5"> {{ project["description"] }} </p> </div> </div> <hr class="hr"> <!-- Customized info for active projects --> {% if project["status"] == "active" %} <!-- Customized info and donation collapse for non-owner users --> {% if project["public_key"] != session["public_key"] %} <div class="row"> <div class="col"> <p class="fs-5"> This project is {{ project["funding_progress"] }} funded and you can donate until {{ project["expire_date"] }}. </p> </div> </div> <div class="d-flex flex-column flex-md-row"> <div class="col-sm my-auto"> <button type="button" class="btn btn-white p-3" id="backProjectButton" data-bs-toggle="collapse" data-bs-target="#donationCollapse" aria-expanded="false" aria-controls="collapseExample" name="{{ session['public_key'] }}" onclick="checkUser(this)" > BACK THIS PROJECT </button> </div> <div class="vr"></div> <div class="col-sm"> <div class="collapse pe-1" id="donationCollapse"> <form class="d-flex p-2"> <input required type="number" class="form-control mx-3 w-50" id="donationAmount" name="donationAmount" min="1" placeholder="Amount" > <button type="submit" class="btn btn-white" id="donateButton" onclick="processDonation()" > DONATE </button> </form> </div> </div> </div> <!-- Customized info for owners --> {% else %} <div class="row"> <div class="col"> <p class="fs-5"> Your project's goal wasn't reached yet, but you have until {{ project["expire_date"] }} to receive donations. </p> <button class="btn btn-outline-orange mx-auto btn-medium" data-bs-toggle="modal" data-bs-target="#editProjectModal" > EDIT PROJECT </button> <button class="btn btn-outline-orange mx-auto btn-medium ms-5" data-bs-toggle="modal" data-bs-target="#cancelProjectModal" > CANCEL PROJECT </button> </div> </div> {% endif %} <!-- Customized info for owners of expired projects --> {% else %} <div class="row"> <div class="col"> <p class="fs-5"> {% if project["status"] == "funded" %} Congrats! Your project expired at {{ project["expire_date"] }} and reached <b>{{ project["donations"] }} donations</b>. {% elif project["status"] == "fund" %} Congrats! Your project expired at {{ project["expire_date"] }} and reached <b>{{ project["donations"] }} donations</b>. Soon your funds will be tranfered to your Stellar account. {% else %} Unfortunally your project <b>expired at {{ project["expire_date"] }} </b> and didn't reached the goal. {% endif %} </p> </div> </div> {% endif %} <hr class="mt-4"> </div> </div> <!-- Modal to edit project data --> <div class="modal fade mx-auto" id="editProjectModal" tabindex="-1" aria-labelledby="editProjectModal" aria-hidden="true" > <div class="modal-dialog modal-dialog-scrollable modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Edit project</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" > </button> </div> <div class="modal-body"> <form action="/edit_project" method="post" id="editProjectForm"> <input hidden type="text" class="form-control-plaintext" id="projectId" name="projectId" value="{{ project['project_id'] }}" > <div class="input-group flex-nowrap"> <span class="input-group-text">NAME</span> <input required type="text" class="form-control" id="newName" name="newName" value="{{ project['name'] }}" minlength="3" maxlength="20" > </div> <div class="input-group flex-nowrap"> <span class="input-group-text">CATEGORY</span> <select required class="form-select" id="newCategory" name="newCategory" > <option disabled selected>Select a new category</option> {% for category in categories_list %} <option> {{ category | capitalize }} </option> {% endfor %} </select> </div> <div class="input-group flex-nowrap"> <span class="input-group-text">GOAL</span> <input required type="number" min="1" class="form-control" id="newGoal" name="newGoal" value="{{ project['goal'] }}" > </div> <div class="input-group flex-nowrap"> <span class="input-group-text">EXPIRE DATE</span> <input required type="date" class="form-control" id="newExpireDate" name="newExpireDate" value="{{ project['expire_date'] }}" min="" onclick="getCurrentDate(this)" > </div> <div class="input-textarea"> <span class="span-textarea" minlength="5" maxlength="150" > DESCRIPTION </span> <textarea required type="text" class="form-control" id="newDescription" name="newDescription" > {{ project['description'] }} </textarea> </div> </div> <div class="modal-footer align-self-center w-25"> <button type="submit" form="editProjectForm" class="btn btn-darkblue" id="editProjectButton" > SAVE CHANGES </button> </div> </form> </div> </div> </div> <!-- Modal to cancel the project --> <div class="modal fade mx-auto" id="cancelProjectModal" tabindex="-1" aria-labelledby="cancelProjectModal" aria-hidden="true" > <div class="modal-dialog modal-dialog-scrollable"> <div class="modal-content"> <div class="modal-header align-self-center"> <h5 class="modal-title"> Are you sure you want to cancel this project? </h5> </div> <div class="modal-body"> <p class="w-100"> This action cannot be undone. All your funding will be transferred back to doners. </p> </div> <div class="modal-footer d-flex"> <form action="/project/{{ project['project_id'] }}" method="post" id="cancelProjectForm" > <input hidden type="text" class="form-control-plaintext" id="projectId" value="{{ project['project_id'] }}" > <button type="submit" form="cancelProjectForm" class="btn btn-darkblue" id="cancelProjectButton" > CONFIRM </button> </form> <div> <button type="button" class="btn btn-outline-darkblue btn-darkblue" data-bs-dismiss="modal" aria-label="Close" > CLOSE </button> </div> </div> </div> </div> </div> {% block scripts %} <script src="{{ url_for('.static', filename='project.js') }}" async></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.js" integrity="sha512-6lplKUSl86rUVprDIjiW8DuOniNX8UDoRATqZSds/7t6zCQZfaCe3e5zcGaQwxa8Kpn5RTM9Fvl3X2lLV4grPQ==" crossorigin="anonymous" referrerpolicy="no-referrer" ></script> {% endblock %} {% endblock %}
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>회원 가입 page</title> <link rel="stylesheet" href="${css}"> <style> .display_none{ display:none; } .color_blue{ color : blue; } .color_red{ color : red; } #loadingimg{ height : 20px; } </style> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script> $(document).ready(function(){ $('#memberId').focusin(function(){ $('#msg').addClass('display_none'); $('#msg').removeClass('color_blue'); $('#msg').removeClass('color_red'); $(this).val(''); }); $('#memberId').focusout(function(){ // ajax 비동기 통신 > id를 서버로 보내고 사용 가능 유무의 응답 코드를 받는다. -> 화면에 메세지 출력 $.ajax({ url : 'idcheck.do', type : 'post', data : { mid : $(this).val() }, beforSend : function(){ $('#loadingimg').removeClass('display_none'); }, success : function(data){ // data : y / n if(data == 'Y'){ $('#msg').html('사용가능'); $('#msg').addClass('color_blue'); $('#msg').removeClass('display_none'); }else{ $('#msg').html('사용불가'); $('#msg').addClass('color_red'); $('#msg').removeClass('display_none'); } }, error : function(request,status,error){ alert('서버 통신에 문제가 발생했습니다. 다시 실행해주새요.'); console.log(request); console.log(status); console.log(error); }, complete : function(){ $('#loadingimg').addClass('display_none'); } }); }); }); </script> </head> <body> <%-- <c:import url="${head}" /> <c:import url="${nav}" /> --%> <%@ include file="/WEB-INF/frame/header.jsp" %> <%@ include file="/WEB-INF/frame/nav.jsp" %> <div class="contents"> <h2>${result}</h2> <hr> <form action="<c:url value="memberReg.do"/>" method="post" enctype="multipart/form-data"> <table> <tr> <td>아이디</td> <td> <input type="text" name="memberId" id="memberId"> <span id="msg" class="display_none"></span> <img id="loadingimg" class="display_none" alt="loading" src="<c:url value="/image/loading.gif"/>"> </td> </tr> <tr> <td>비밀번호</td> <td><input type="password" name="memberPw"></td> </tr> <tr> <td>이름</td> <td><input type="text" name="memberName"></td> </tr> <tr> <td>사진</td> <td><input type="file" name="memberPhoto"></td> </tr> <tr> <td></td> <td><input type="submit"> <input type="reset"> </td> </tr> </table> </form> </div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Register Page</title> @vite(['resources/css/app.css', 'resources/js/app.js']) <script> if ( localStorage.getItem('color-theme') === 'dark' || (!('color-theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches) ) { document.documentElement.classList.add('dark'); } else { document.documentElement.classList.remove('dark'); } </script> </head> <body class="bg-gray-50 dark:bg-gray-800 scrollbar scrollbar-w-3 scrollbar-thumb-rounded-[0.25rem] scrollbar-track-slate-200 scrollbar-thumb-gray-400 dark:scrollbar-track-gray-900 dark:scrollbar-thumb-gray-700"> <div class="flex overflow-hidden bg-gray-50 dark:bg-gray-900"> <div id="main-content" class="relative w-full max-w-screen-2xl mx-auto h-full bg-gray-50 dark:bg-gray-900 max-h-screen"> <div class="px-4 2xl:px-0"> <div class="min-h-screen align-middle flex pb-[12vh]"> <div class="w-full flex flex-col items-center justify-center px-6 pt-8 mx-auto pt:mt-0 dark:bg-gray-900"> <div class="w-full max-w-xl p-6 space-y-8 sm:p-8 bg-white rounded-lg shadow dark:bg-gray-800"> <h2 class="text-2xl font-bold text-gray-900 dark:text-white"> Create an Account </h2> <form class="mt-8 space-y-6" action="{{ route('register.store') }}" method="POST"> @csrf <div> <label for="name" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Your Name</label> <input type="text" name="name" id="name" placeholder="Name" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" required> </div> <div> <label for="username" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Your Username</label> <input type="username" name="username" id="username" placeholder="johndoe" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" required> </div> <div> <label for="email" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Your email</label> <input type="email" name="email" id="email" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" placeholder="name@example.com" required> </div> <div> <label for="password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Your password</label> <input type="password" name="password" id="password" placeholder="••••••••" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" required> </div> <div class="flex items-start"> <div class="flex items-center h-5"> <input id="remember" aria-describedby="remember" name="remember" type="checkbox" class="w-4 h-4 border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-primary-300 dark:focus:ring-primary-600 dark:ring-offset-gray-800 dark:bg-gray-700 dark:border-gray-600" required> </div> <div class="ml-3 text-sm"> <label for="remember" class="font-medium text-gray-900 dark:text-white">I accept the <a href="#" class="text-primary-700 hover:underline dark:text-primary-500">Terms and Conditions</a></label> </div> </div> <button type="submit" class="w-full px-5 py-3 text-base font-medium text-center text-white bg-primary-700 rounded-lg hover:bg-primary-800 focus:ring-4 focus:ring-primary-300 sm:w-auto dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800">Create account</button> <div class="text-sm font-medium text-gray-500 dark:text-gray-400"> Already have an account? <a href="{{ route('login') }}" class="text-primary-700 hover:underline dark:text-primary-500">Login here</a> </div> </form> </div> </div> </div> </div> </div> </div> </body> </html> {{-- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Register</title> @include('include.style') </head> <body> <script src="{{ asset('dist/assets/static/js/initTheme.js') }}"></script> <div id="auth"> <div class="row h-100"> <div class="col-lg-5 col-12"> <div id="auth-left"> <h1 class="auth-title">Register</h1> <form action="{{ route('register.store') }}" method="POST"> @csrf <div class="form-group position-relative has-icon-left mb-4"> <input type="text" name="name" id="name" class="form-control @error('name') is invalid @enderror form-control-xl" placeholder="Name"> <div class="form-control-icon"> <i class="bi bi-person"></i> </div> @error('name') <small class="btn btn-danger">{{ $message }}</small> @enderror </div> <div class="form-group position-relative has-icon-left mb-4"> <input type="text" name="username" id="username" class="form-control @error('username') is invalid @enderror form-control-xl" placeholder="Username"> <div class="form-control-icon"> <i class="bi bi-person"></i> </div> @error('username') <small class="btn btn-danger">{{ $message }}</small> @enderror </div> <div class="form-group position-relative has-icon-left mb-4"> <input type="email" name="email" id="email" class="form-control @error('email') is invalid @enderror form-control-xl" placeholder="Email"> <div class="form-control-icon"> <i class="bi bi-envelope"></i> </div> @error('email') <small class="btn btn-danger">{{ $message }}</small> @enderror </div> <div class="form-group position-relative has-icon-left mb-4"> <input type="password" name="password" id="password" class="form-control @error('password') is invalid @enderror form-control-xl" placeholder="Password"> <div class="form-control-icon"> <i class="bi bi-shield-lock"></i> </div> @error('password') <small class="btn btn-danger">{{ $message }}</small> @enderror </div> <button class="btn btn-primary btn-block btn-lg shadow-lg mt-5">Sign Up</button> </form> <div class="text-center mt-5 text-lg fs-4"> <p class='text-gray-600'>Already have an account? <a href="{{ route('login') }}" class="font-bold">Log in</a>.</p> </div> </div> </div> <div class="col-lg-7 d-none d-lg-block"> <div id="auth-right"> </div> </div> </div> </div> </body> </html> --}}
/** * This file defines the contract for the services in k.IM that create and operate on networks. */ @klab 0.10.0 @version 0.10.0 @namespace klab.network export object connect "Connects subjects by building relationships using configurable deterministic or stochastic methods. Each relationship can optionally be assigned a spatial context connecting the space of the related subjects with configurable methods." { optional number p "The parameter that defines the network being created. Its meaning changes according to the method. If the selector expression is passed, this defaults to 1.0." optional boolean expression select "An expression evaluated per each legitimate pair of objects to be connected, returning true or false. If false is returned, the relationship will not be created. The variables 'source' and 'target' are set to the objects to be linked." default "" optional import object source "Artifact providing the source for the relationships. By default all artifacts that incarnate the relationship source type are used." optional import object target "Artifact providing the target for the relationships. By default all artifacts that incarnate the relationship target type are used." optional enum space "Type of spatial link to create if the vertices are spatial and distinct. Possible values are None, Line, LineCentroid, LineEdge, ConvexHull. Default is ConvexHull if the source and target are polygonal, Line if at least one is a point, and None if they are non-spatial." values None, Line, LineCentroid, LineEdge, ConvexHull optional number seed "The random number seed. By default each generation will use a different one." optional boolean selfconnections "If true, self-connections can be created. Default is false" default false optional boolean reciprocal "If true, A->B does not prevent B->A from being created. Default false. Forced to false if the annotated concept is a bond." optional enum method "The method to use to create the random network. Choose between OutDegree, BarabasiAlbert, EppsteinPowerLaw, ErdosRenyi, Lattice2D and KleinbergSmallWorld (the last two restricted to grid space contexts). For non-random networks, Closest will work in spatial contexts to connect the two spatially closest objects. ## TODO Markdown documentation " values OutDegree, BarabasiAlbert, EppsteinPowerLaw, ErdosRenyi, KleinbergSmallWorld, Closest default "ErdosRenyi" class org.integratedmodelling.klab.components.network.services.ConfigurableRelationshipInstantiator } export object route "Connects subjects through routes computed along a specified spatial configuration. Relationships are only created if a route exists." { optional import object source "Semantics for the type of the subjects used as source for the relationships" default "" optional import object target "Semantics for the type of the subjects used as target for the relationships" default "" optional number time_limit "Time threshold to consider a route a valid option" default "No limit" optional number distance_limit "Distance threshold to consider a route a valid option" default "No limit" optional enum transport "Type of transport used to find a route" values Auto, Pedestrian, Bicycle, Bus, Truck, Taxi, MotorScooter, Multimodal default "Auto" optional enum collapse_geometry "Method used to collapse line and polygon sources and targets to a single point or a set of points that allow route finding." values Centroid default "Centroid" // TODO configuration to use class org.integratedmodelling.klab.components.network.services.RoutingRelationshipInstantiator }
import MovieModel from "../models/MovieModel"; import topTenView from "../views/TopTenView"; import searchBoxView from "../views/SearchBoxView"; import searchTypeView from "../views/SearchTypeView"; import topTenSliderView from "../views/TopTenSliderViwe"; import searchTypeView from "../views/SearchTypeView"; import searchResultsView from "../views/SearchResultsView"; import messageView from "../views/messageView"; import overlayMovieView from "../views/OverlayMovieView"; import favoriteMoviesView from "../views/FavoriteMoviesView"; import tabsView from "../views/TabsView"; /** * MovieController class that manages the interaction between the model and views. * It handles user interactions, fetches movie data, and updates the views accordingly. */ export class MovieController { /** * Constructor for the MovieController class. * Initializes the model, and sets up event handlers for user interactions. */ constructor() { this.movieModel = new MovieModel(); this.movieModel.loadFavorites(); this.renderTopTenMovies(); this.setupEventHandlers(); } /** * Sets up event handlers for user interactions. */ setupEventHandlers() { topTenSliderView.addHandlerToSlideButtons(this.handleSlideTopTen); topTenView.addHandlerToSliderResize(this.handleTopTenSlideReset); searchBoxView.addHandlerToSearchFormBtn(); searchBoxView.addHandlerToSearchFormSubmit( this.handleSearchFormSubmit.bind(this) ); searchTypeView.addHandlerSearchTypeSelector( this.handleMovieSearchType.bind(this) ); messageView.addHandleToCloseMessageBox(); searchResultsView.addHandlerShowFullInfo( this.handleShowingMovieOvarlayInfo.bind(this) ); overlayMovieView.addHandleToCloseMovieOverlay(); topTenView.addHandlerShowTopTenOverlay( this.handleShowingTopTenOvarlayInfo.bind(this) ); overlayMovieView.addHandlerToFavoriteBtn( this.handleOverlayFavoriteBtn.bind(this) ); favoriteMoviesView.addHandlerShowFavoriteInfo( this.handleShowingFavoriteOvarlayInfo.bind(this) ); tabsView.addHandlerTabsClick(this.handleTagToggle.bind(this)); } /** * load topTen movies and adjust favorite property according to moveiModel.favorite array * then Renders the top ten movies. */ renderTopTenMovies() { this.movieModel.loadTopTenMovies(); topTenView.render(this.movieModel.topTen); } /** * Handles sliding to the specified top ten movie slide. * @param {number} slideNum - The slide number to slide to. */ handleSlideTopTen(slideNum) { topTenView.slide(slideNum); } /** * Handles the reset of the top ten slider on screen resize. */ handleTopTenSlideReset() { topTenSliderView.resetActiveSliderOnScreenResize(); topTenView.slide(0); } /** * Handles the search form submission, fetches movie information, and updates the view. * * @param {string} searchTerm - The search term entered by the user. * @returns {Promise<void>} Updates the search results view with the fetched movie data. */ async handleSearchFormSubmit(searchTerm) { try { searchResultsView.toggleSpinner(); await this.movieModel.loadMoviInformation(searchTerm); await this.movieModel.fetchMovies(this.movieModel.searchIds); searchResultsView.render(this.movieModel.searchResults); searchResultsView.toggleSpinner(); searchResultsView.scrollToResults(); } catch (err) { searchResultsView.toggleSpinner(); messageView.toggleMessageBox(); messageView.render({ title: err.Error, message: "Double check search term and try again.", }); } } /** * Handles setting the movie search type. * @param {string} type - The type of search (movie or series). */ handleMovieSearchType(type) { if (type !== this.movieModel.searchType) this.movieModel.setSearchType(type); } /** * Handles showing the overlay with movie information. * adds/removes clicked movie from favorites. * * @param {string} movieId - The ID of the movie to show in the overlay. * @param {string} action - identifier that specify add/remove movie from favorite or just show overlay information. */ handleShowingMovieOvarlayInfo(movieId, action) { //find the index number of clicked movie box const indexNum = this.movieModel.searchResults.findIndex( (movie) => movie.imdbID === movieId ); if (action === "favorite") { if (this.movieModel.searchResults[indexNum].favorite === true) { this.movieModel.searchResults[indexNum].favorite = false; this.movieModel.favorites = this.movieModel.favorites.filter( (movie) => movie.imdbID !== movieId ); } else { this.movieModel.searchResults[indexNum].favorite = true; this.movieModel.favorites.push(this.movieModel.searchResults[indexNum]); } this.movieModel.storageFavorites(); searchResultsView.render(this.movieModel.searchResults); } else { //copy clicked data object to movieModel.searchResults property this.movieModel.ovelayedMovieInfo = { ...this.movieModel.searchResults[indexNum], }; overlayMovieView.toggleOverlay(); overlayMovieView.render(this.movieModel.ovelayedMovieInfo); } console.log(this.movieModel.favorites); } /** * Handles showing the overlay with Top ten information * adds/removes clicked movie from favorites. * * @param {string} movieId - The ID of the movie to show in the overlay. * @param {string} action - identifier that specify add/remove movie from favorite or just show overlay information. */ handleShowingTopTenOvarlayInfo(movieId, action) { //find the index number of clicked top ten movies const indexNum = this.movieModel.topTen.findIndex( (movie) => movie.imdbID === movieId ); if (action === "favorite") { if (this.movieModel.topTen[indexNum].favorite === true) { this.movieModel.topTen[indexNum].favorite = false; this.movieModel.favorites = this.movieModel.favorites.filter( (movie) => movie.imdbID !== movieId ); } else { this.movieModel.topTen[indexNum].favorite = true; this.movieModel.favorites.push(this.movieModel.topTen[indexNum]); } this.movieModel.storageFavorites(); topTenView.render(this.movieModel.topTen); favoriteMoviesView.render(this.movieModel.favorites); } else { //copy clicked data object to movieModel.searchResults property this.movieModel.ovelayedMovieInfo = { ...this.movieModel.topTen[indexNum], }; overlayMovieView.toggleOverlay(); overlayMovieView.render(this.movieModel.ovelayedMovieInfo); } console.log(this.movieModel.favorites); } /** * Handles the favorite button click in the overlay to add/remove movie in overlay form favorites. */ handleOverlayFavoriteBtn() { //get movie id rendering in overlay section const movieId = this.movieModel.ovelayedMovieInfo.imdbID; //revert favorite property in overlay this.movieModel.ovelayedMovieInfo.favorite = !this.movieModel.ovelayedMovieInfo.favorite; //if the movie is already in favorites array remove it otherwise add movie to favorites if (this.movieModel.favorites.some((movie) => movie.imdbID === movieId)) { this.movieModel.favorites = [ ...this.movieModel.favorites.filter( (movie) => movie.imdbID !== movieId ), ]; } else { this.movieModel.favorites.push(this.movieModel.ovelayedMovieInfo); } this.movieModel.storageFavorites(); //modify favorite property of topTen and searchResults this.movieModel.topTen.forEach((movie) => { if (movie.imdbID === movieId) movie.favorite = !movie.favorite; }); this.movieModel.searchResults.forEach((movie) => { if (movie.imdbID === movieId) movie.favorite = !movie.favorite; }); overlayMovieView.render(this.movieModel.ovelayedMovieInfo); searchResultsView.render(this.movieModel.searchResults); favoriteMoviesView.render(this.movieModel.favorites); topTenView.render(this.movieModel.topTen); } /** * Handles showing the overlay with movie information. * adds/removes clicked movie from favorites. * * @param {string} movieId - The ID of the movie to show in the overlay. * @param {string} action - identifier that specify add/remove movie from favorite or just show overlay information. */ handleShowingFavoriteOvarlayInfo(movieId, action) { //find the index number of clicked movie box const indexNum = this.movieModel.favorites.findIndex( (movie) => movie.imdbID === movieId ); if (action === "favorite") { this.movieModel.favorites = this.movieModel.favorites.filter( (movie) => movie.imdbID !== movieId ); this.movieModel.storageFavorites(); favoriteMoviesView.render(this.movieModel.favorites); } else { //copy clicked data object to movieModel.searchResults property this.movieModel.ovelayedMovieInfo = { ...this.movieModel.favorites[indexNum], }; overlayMovieView.toggleOverlay(); overlayMovieView.render(this.movieModel.ovelayedMovieInfo); } } /** * Handles toggling between the favorite movies tab and the search results tab. * @param {string} identifier - The identifier to determine which tab to show. */ handleTagToggle(identifier) { if (identifier === "favorite") { favoriteMoviesView.showFavoritesTab(); searchResultsView.hideResultsTab(); favoriteMoviesView.render(this.movieModel.favorites); } else { favoriteMoviesView.hideFavoritesTab(); searchResultsView.showResultsTab(); } } }
#!/usr/bin/env node /** * Module dependencies. */ var app = require('../app'); var debug = require('debug')('shopping-cart:server'); var http = require('http'); var db = require('../config/connection'); // Add the database connection module /** * Get port from environment and store in Express. */ var port = normalizePort(process.env.PORT || '3000'); app.set('port', port); db.connect((err) => { if (err) { console.error('Error connecting to the database:', err); //process.exit(1); // Exit the application on connection error } else { console.log('Connected to the database successfully'); /** * Create HTTP server. */ var server = http.createServer(app); /** * Listen on provided port, on all network interfaces. */ server.listen(port); server.on('error', onError); server.on('listening', onListening); console.info(`Application started and listening at ${port}`); /** * Event listener for HTTP server "listening" event. */ function onListening() { var addr = server.address(); var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; debug('Listening on ' + bind); } } }); /** * Normalize a port into a number, string, or false. */ function normalizePort(val) { var port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } /** * Event listener for HTTP server "error" event. */ function onError(error) { if (error.syscall !== 'listen') { throw error; } var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use'); process.exit(1); break; default: throw error; } }
"use client"; import Avatar from "@/app/components/Avatar"; import useCurrentUser from "@/app/hooks/useCurrentUser"; import useOtherUsers from "@/app/hooks/useOtherUsers"; import { IMessage, IUser } from "@/schemas"; import clsx from "clsx"; import { format } from "date-fns"; import { useParams } from "next/navigation"; interface UserChatItemProps { title: string; users: IUser[]; chatId: string; lastMessage: IMessage; image?: string; isGroup?: boolean; } export default function UserChatItem({ title, users, chatId, image, lastMessage, isGroup, }: UserChatItemProps) { const params = useParams(); const user = useCurrentUser(); const otherUser = useOtherUsers(user, users); const openChatId = params.chatId[0]; const isOpen = openChatId === chatId; return ( <div className={clsx( ` relative inline-flex rounded-l-md px-4 py-2 w-full items-center hover:bg-white cursor-pointer mb-2 transition `, isOpen && "bg-white" )} > <Avatar isGroup={isGroup} name={otherUser[0].name} image={image} /> <div className="overflow-hidden"> <div className="font-medium">{isGroup ? title : otherUser[0].name}</div> <div className="overflow-hidden text-ellipsis whitespace-nowrap text-sm text-stone-600"> {lastMessage.body} </div> </div> <div className="absolute text-xs text-stone-600 right-3 top-3"> {format(new Date(lastMessage.createdAt), "p")} </div> </div> ); }
import React, { Fragment } from 'react' import { Metadata } from 'next' import { Settings } from '../../../payload/payload-types' import { fetchSettings } from '../../_api/fetchGlobals' import { Gutter } from '../../_components/Gutter' import { Message } from '../../_components/Message' import { LowImpactHero } from '../../_heros/LowImpact' import { getMeUser } from '../../_utilities/getMeUser' import { mergeOpenGraph } from '../../_utilities/mergeOpenGraph' import { CheckoutPage } from './CheckoutPage' import classes from './index.module.scss' export default async function Checkout() { await getMeUser({ nullUserRedirect: `/login?error=${encodeURIComponent( 'You must be logged in to checkout.', )}&redirect=${encodeURIComponent('/checkout')}`, }) let settings: Settings | null = null try { settings = await fetchSettings() } catch (error) { // no need to redirect to 404 here, just simply render the page with fallback data where necessary console.error(error) // eslint-disable-line no-console } return ( <Fragment> {!process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY && ( <Gutter> <Message className={classes.message} warning={ <Fragment> {'To enable checkout, you must '} <a href="https://dashboard.stripe.com/test/apikeys" target="_blank" rel="noopener noreferrer" > {'obtain your Stripe API Keys'} </a> {' then set them as environment variables. See the '} <a href="https://github.com/payloadcms/payload/blob/main/templates/ecommerce/README.md#stripe" target="_blank" rel="noopener noreferrer" > {'README'} </a> {' for more details.'} </Fragment> } /> </Gutter> )} <LowImpactHero type="lowImpact" media={null} richText={[ { type: 'h1', children: [ { text: 'Checkout', }, ], }, { type: 'paragraph', children: [ { text: `This is a self-hosted, secure checkout using Stripe's Payment Element component. To create a mock purchase, use a `, }, { type: 'link', url: 'https://stripe.com/docs/testing#cards', children: [ { text: 'test credit card', }, ], }, { text: ' like ', }, { text: '4242 4242 4242 4242', bold: true, }, { text: ' with any future date and CVC. An order will be generated in Stripe and will appear in your account. In production, this checkout form will require a real card with sufficient funds.', }, ], }, ]} /> <Gutter className={classes.checkoutPage}> <CheckoutPage settings={settings} /> </Gutter> </Fragment> ) } export const metadata: Metadata = { title: 'Account', description: 'Create an account or log in to your existing account.', openGraph: mergeOpenGraph({ title: 'Account', url: '/account', }), }
class ExperienceCertificatesController < ApplicationController include JsonResponseHelper # Include the concern layout "mindcom" def index if session[:class_table].present? @table_array = session[:class_table] @course_id = session[:table_array_class_id] session[:table_array_employee_id] = nil session[:class_table] = nil end @classes = MgCourse.where(mg_school_id: session[:current_user_school_id], is_deleted: 0).order(:id) @batches = MgBatch.where(mg_school_id: session[:current_user_school_id], is_deleted: 0) @academic_year_data = MgTimeTable.where(mg_school_id: session[:current_user_school_id], is_deleted: 0).order(:id) @wings_data = MgWing.where(mg_school_id: session[:current_user_school_id], is_deleted: 0) @sectionClass = MgBatch.where(is_deleted: 0, mg_school_id: session[:current_user_school_id]) .joins(:mg_course) .pluck( Arel.sql("CONCAT(mg_courses.course_name, '-', mg_batches.name)"), Arel.sql("mg_batches.id"), Arel.sql("mg_batches.mg_employee_id"), Arel.sql("mg_courses.mg_time_table_id"), Arel.sql("mg_courses.mg_wing_id"), Arel.sql("mg_courses.id") ).map do |name, mg_batch_id,mg_employee_id, mg_time_table_id, mg_wing_id, mg_course_id| { name: name, mg_batch_id: mg_batch_id, mg_employee_id:mg_employee_id, mg_time_table_id: mg_time_table_id, mg_wing_id: mg_wing_id, mg_course_id: mg_course_id } end @employees_data = MgEmployee .where(is_deleted: 0, mg_school_id: session[:current_user_school_id], mg_employee_category_id: 2, is_archive: 0) .joins("INNER JOIN mg_users ON mg_users.id = mg_employees.mg_user_id") .joins("INNER JOIN mg_employee_departments ON mg_employee_departments.id = mg_employees.mg_employee_department_id") .select("mg_employees.*, mg_users.user_name AS user_name, mg_employee_departments.department_name AS department_name") @archive_data = MgEmployee .where(is_deleted: 0, mg_school_id: session[:current_user_school_id], mg_employee_category_id: 2, is_archive: 1) .joins("INNER JOIN mg_users ON mg_users.id = mg_employees.mg_user_id") .joins("INNER JOIN mg_employee_departments ON mg_employee_departments.id = mg_employees.mg_employee_department_id") .select("mg_employees.*, mg_users.user_name AS user_name, mg_employee_departments.department_name AS department_name") @reasons_data =MgArchiveReason.where(is_deleted: 0,user_type:"Employee").pluck(:reason_name,:id) @employee_department=MgEmployeeDepartment.where(:is_deleted=>0,:mg_school_id=>session[:current_user_school_id]).pluck(:department_name,:id) @react_data = { section_class: @sectionClass, classes: @classes, batches: @batches, academic_year_data:@academic_year_data, wings_data:@wings_data, employees_data:@employees_data, reasons_data:@reasons_data, employee_department:@employee_department, archive_data:@archive_data } end def issue_certificates employee_id = params[:id] @employee = MgEmployee.find_by(id: employee_id, is_deleted: 0, mg_school_id: session[:current_user_school_id]) if @employee.present? emp_number = @employee.employee_number first_name = @employee.first_name last_name = @employee.last_name middle_name = @employee.middle_name full_name = "#{first_name} #{middle_name.to_s} #{last_name}" experience_certificate = MgCertificateTracking.find_by( mg_employee_id: employee_id, certificate_type: "EXPERIENCE", is_deleted: 0, mg_school_id: session[:current_user_school_id] ) certificate_details = if experience_certificate.present? { date_of_issue: experience_certificate.date_of_issue&.strftime("%d/%m/%Y"), issued_times: experience_certificate.issued_times } else { date_of_issue:"", issued_times:"" } end render json: { employee: { employee_number: emp_number, full_name: full_name }, certificate: certificate_details } else render json: { error: "Employee not found or deleted" }, status: :not_found end end def show_employee_certificate if params[:id].present? employee_id = params[:id] employee_exp_certificate = MgEmployeeExperienceCertificate.find_by( is_deleted: 0, mg_school_id: session[:current_user_school_id], mg_employee_id: employee_id ) if employee_exp_certificate.present? render json: { success: true, certificate: { id: employee_exp_certificate.id, employee_id: employee_exp_certificate.mg_employee_id, school_id: employee_exp_certificate.mg_school_id, title: employee_exp_certificate.title, employee_name: employee_exp_certificate.employee_name, guardian_title: employee_exp_certificate.guardian_title, guardian_name: employee_exp_certificate.guardian_name, cnic_number: employee_exp_certificate.cnic_number, subjects: employee_exp_certificate.subjects, designation: employee_exp_certificate.designation, joining_date: employee_exp_certificate.joining_date, last_working_date: employee_exp_certificate.last_working_date, title_sub: employee_exp_certificate.title_sub, title_sub1: employee_exp_certificate.title_sub1, title_sub2: employee_exp_certificate.title_sub2, created_at: employee_exp_certificate.created_at, updated_at: employee_exp_certificate.updated_at } } else render json: { success: false, error: "Experience certificate not found for the given employee." }, status: :not_found end else render json: { success: false, error: "Employee ID is missing." }, status: :bad_request end end def create_experience_certificate ActiveRecord::Base.transaction do # Initialize the certificate emp_exp_certfct = MgEmployeeExperienceCertificate.new( mg_school_id: session[:current_user_school_id], mg_employee_id: params[:employee_id], # Corrected param title: params[:title], employee_name: params[:employee_name], # Corrected param guardian_title: params[:guardian_title], # Corrected param guardian_name: params[:guardian_name], subjects: params[:subjects], designation: params[:designation], joining_date: params[:joining_date], last_working_date: params[:last_working_date], # Corrected param title_sub: params[:title_sub], title_sub1: params[:title_sub1], title_sub2: params[:title_sub2], is_deleted: 0, created_by: session[:user_id], updated_by: session[:user_id] ) # Save the certificate if emp_exp_certfct.save render json: { message: "Employee experience certificate created successfully.", certificate: emp_exp_certfct }, status: :created else raise ActiveRecord::Rollback, emp_exp_certfct.errors.full_messages.join(", ") end end rescue ActiveRecord::Rollback => e render json: { error: e.message }, status: :unprocessable_entity end def update_experience_certificate ActiveRecord::Base.transaction do # Find the existing certificate by its ID (assuming params[:id] is provided) @emp_exp_certfct = MgEmployeeExperienceCertificate.find_by(id: params[:id]) # Check if the certificate exists if @emp_exp_certfct # Parse dates into Date objects if they are not already in the correct format joining_date = Date.strptime(params[:joining_date], "%d/%m/%Y") if params[:joining_date].present? last_working_date = Date.strptime(params[:last_working_date], "%d/%m/%Y") if params[:last_working_date].present? # Attempt to update the certificate attributes unless @emp_exp_certfct.update( mg_school_id: session[:current_user_school_id], mg_employee_id: params[:employee_id], title: params[:title], employee_name: params[:employee_name], guardian_title: params[:guardian_title], guardian_name: params[:guardian_name], cnic_number: params[:cnic_number], # Ensure it's nullable in DB subjects: params[:subjects], designation: params[:designation], joining_date: joining_date, last_working_date: last_working_date, title_sub: params[:title_sub], title_sub1: params[:title_sub1], title_sub2: params[:title_sub2], updated_by: session[:user_id] ) raise ActiveRecord::Rollback, "Failed to update employee experience certificate." end # If update is successful, render a success message render json: { message: "Employee experience certificate updated successfully.", certificate: @emp_exp_certfct }, status: :ok else # If the certificate is not found, return an error message render json: { error: "Employee experience certificate not found." }, status: :not_found end end rescue ActiveRecord::Rollback => e render json: { error: e.message }, status: :unprocessable_entity end def track_and_generate_certificate certificate_type = "EXPERIENCE" mg_employee_id = params[:id] if mg_employee_id.present? @certificate = MgCertificateTracking.find_or_initialize_by( mg_employee_id: mg_employee_id, certificate_type: certificate_type, is_deleted: 0 ) if @certificate.new_record? @certificate.assign_attributes( mg_school_id: session[:current_user_school_id], issued_times: 1, date_of_issue: Date.current.strftime("%d/%m/%Y"), created_by: session[:user_id], updated_by: session[:user_id] ) if @certificate.save render json: { success: true, message: "Certificate generated successfully", certificate: @certificate }, status: :created else render json: { success: false, message: "Failed to generate certificate", errors: @certificate.errors.full_messages }, status: :unprocessable_entity end else @certificate.increment!(:issued_times) render json: { success: true, message: "Certificate issuance count updated", certificate: @certificate }, status: :ok end else render json: { success: false, message: "Employee ID is required to generate the certificate" }, status: :bad_request end rescue => e render json: { success: false, message: e.message }, status: :internal_server_error end end
import { FC, ReactNode } from "react"; import cx from "classnames"; import { Nav } from "@src/components/layout/nav"; import styles from "./layout.module.css"; type Props = { children: ReactNode; }; export const Layout: FC<Props> = ({ children }) => { return ( <div className={cx( "flex min-h-screen flex-col 2xl:h-screen", styles.container )}> <div className="bg-green-700"> <div className="m-auto"> <Nav /> </div> </div> <main className={cx( "flex grow flex-col items-center justify-center bg-slate-100 px-12 2xl:px-36", styles.main )}> {children} </main> </div> ); };
using System; using System.Linq; using System.Linq.Dynamic.Core; using Abp.Linq.Extensions; using System.Collections.Generic; using System.Threading.Tasks; using Abp.Domain.Repositories; using CCPDemo.RiskGroupings.Exporting; using CCPDemo.RiskGroupings.Dtos; using CCPDemo.Dto; using Abp.Application.Services.Dto; using CCPDemo.Authorization; using Abp.Extensions; using Abp.Authorization; using Microsoft.EntityFrameworkCore; using Abp.UI; using CCPDemo.Storage; namespace CCPDemo.RiskGroupings { [AbpAuthorize(AppPermissions.Pages_Administration_RiskGroupings)] public class RiskGroupingsAppService : CCPDemoAppServiceBase, IRiskGroupingsAppService { private readonly IRepository<RiskGrouping> _riskGroupingRepository; private readonly IRiskGroupingsExcelExporter _riskGroupingsExcelExporter; public RiskGroupingsAppService(IRepository<RiskGrouping> riskGroupingRepository, IRiskGroupingsExcelExporter riskGroupingsExcelExporter) { _riskGroupingRepository = riskGroupingRepository; _riskGroupingsExcelExporter = riskGroupingsExcelExporter; } public async Task<PagedResultDto<GetRiskGroupingForViewDto>> GetAll(GetAllRiskGroupingsInput input) { var filteredRiskGroupings = _riskGroupingRepository.GetAll() .WhereIf(!string.IsNullOrWhiteSpace(input.Filter), e => false || e.Name.Contains(input.Filter)) .WhereIf(input.MinValueFilter != null, e => e.Value >= input.MinValueFilter) .WhereIf(input.MaxValueFilter != null, e => e.Value <= input.MaxValueFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.NameFilter), e => e.Name.Contains(input.NameFilter)) .WhereIf(input.MinDefaultFilter != null, e => e.Default >= input.MinDefaultFilter) .WhereIf(input.MaxDefaultFilter != null, e => e.Default <= input.MaxDefaultFilter) .WhereIf(input.MinOrderFilter != null, e => e.Order >= input.MinOrderFilter) .WhereIf(input.MaxOrderFilter != null, e => e.Order <= input.MaxOrderFilter); var pagedAndFilteredRiskGroupings = filteredRiskGroupings .OrderBy(input.Sorting ?? "id asc") .PageBy(input); var riskGroupings = from o in pagedAndFilteredRiskGroupings select new { o.Value, o.Name, o.Default, o.Order, Id = o.Id }; var totalCount = await filteredRiskGroupings.CountAsync(); var dbList = await riskGroupings.ToListAsync(); var results = new List<GetRiskGroupingForViewDto>(); foreach (var o in dbList) { var res = new GetRiskGroupingForViewDto() { RiskGrouping = new RiskGroupingDto { Value = o.Value, Name = o.Name, Default = o.Default, Order = o.Order, Id = o.Id, } }; results.Add(res); } return new PagedResultDto<GetRiskGroupingForViewDto>( totalCount, results ); } public async Task<GetRiskGroupingForViewDto> GetRiskGroupingForView(int id) { var riskGrouping = await _riskGroupingRepository.GetAsync(id); var output = new GetRiskGroupingForViewDto { RiskGrouping = ObjectMapper.Map<RiskGroupingDto>(riskGrouping) }; return output; } [AbpAuthorize(AppPermissions.Pages_Administration_RiskGroupings_Edit)] public async Task<GetRiskGroupingForEditOutput> GetRiskGroupingForEdit(EntityDto input) { var riskGrouping = await _riskGroupingRepository.FirstOrDefaultAsync(input.Id); var output = new GetRiskGroupingForEditOutput { RiskGrouping = ObjectMapper.Map<CreateOrEditRiskGroupingDto>(riskGrouping) }; return output; } public async Task CreateOrEdit(CreateOrEditRiskGroupingDto input) { if (input.Id == null) { await Create(input); } else { await Update(input); } } [AbpAuthorize(AppPermissions.Pages_Administration_RiskGroupings_Create)] protected virtual async Task Create(CreateOrEditRiskGroupingDto input) { var riskGrouping = ObjectMapper.Map<RiskGrouping>(input); if (AbpSession.TenantId != null) { riskGrouping.TenantId = (int?)AbpSession.TenantId; } await _riskGroupingRepository.InsertAsync(riskGrouping); } [AbpAuthorize(AppPermissions.Pages_Administration_RiskGroupings_Edit)] protected virtual async Task Update(CreateOrEditRiskGroupingDto input) { var riskGrouping = await _riskGroupingRepository.FirstOrDefaultAsync((int)input.Id); ObjectMapper.Map(input, riskGrouping); } [AbpAuthorize(AppPermissions.Pages_Administration_RiskGroupings_Delete)] public async Task Delete(EntityDto input) { await _riskGroupingRepository.DeleteAsync(input.Id); } public async Task<FileDto> GetRiskGroupingsToExcel(GetAllRiskGroupingsForExcelInput input) { var filteredRiskGroupings = _riskGroupingRepository.GetAll() .WhereIf(!string.IsNullOrWhiteSpace(input.Filter), e => false || e.Name.Contains(input.Filter)) .WhereIf(input.MinValueFilter != null, e => e.Value >= input.MinValueFilter) .WhereIf(input.MaxValueFilter != null, e => e.Value <= input.MaxValueFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.NameFilter), e => e.Name.Contains(input.NameFilter)) .WhereIf(input.MinDefaultFilter != null, e => e.Default >= input.MinDefaultFilter) .WhereIf(input.MaxDefaultFilter != null, e => e.Default <= input.MaxDefaultFilter) .WhereIf(input.MinOrderFilter != null, e => e.Order >= input.MinOrderFilter) .WhereIf(input.MaxOrderFilter != null, e => e.Order <= input.MaxOrderFilter); var query = (from o in filteredRiskGroupings select new GetRiskGroupingForViewDto() { RiskGrouping = new RiskGroupingDto { Value = o.Value, Name = o.Name, Default = o.Default, Order = o.Order, Id = o.Id } }); var riskGroupingListDtos = await query.ToListAsync(); return _riskGroupingsExcelExporter.ExportToFile(riskGroupingListDtos); } } }
import streamlit as st from faker import Faker from streamlit_ace import st_ace import random import subprocess from scipy.stats import norm,expon #from tink3 import * def colip(coltype, nrows, i, tblcols,colnames): # for cc in colnames: # pass # # eval() j=0 fake = Faker() element=None if coltype == "Number": x = int(st.text_input(label="enter an integer", value=0, key="int"+str(i)+str(j))) return [x]*nrows if coltype == "String": x2 = st.text_input(label="enter a string", value="foo", key="str"+str(i)+str(j)) return [x2]*nrows if coltype == "Sequence": start = int(st.text_input( label="enter start value", value=0, key="sta"+str(i)+str(j))) increment = int(st.text_input( label="enter increment value", value=1, key="inc"+str(i)+str(j))) op = [None]*nrows for i in range(nrows): op[i] = start+(i*increment) return op if coltype == "Names": nametype = st.selectbox( "select name type", ('Full name', 'First name', 'First name - male', 'First name - female', 'Last name'), key="nt"+str(i)+str(j)) op = [None]*nrows if nametype == 'Full name': for i in range(nrows): op[i] = fake.name() elif nametype == 'First name': for i in range(nrows): op[i] = fake.first_name() elif nametype == 'First name - male': for i in range(nrows): op[i] = fake.first_name_male() elif nametype == 'First name - female': for i in range(nrows): op[i] = fake.first_name_female() elif nametype == 'Last name': for i in range(nrows): op[i] = fake.last_name() return op if coltype == "Countries": op = [None]*nrows for i in range(nrows): op[i] = fake.country() return op if coltype == "URL": op = [None]*nrows for i in range(nrows): op[i] = fake.url() return op if coltype == "Bool": op = [None]*nrows ptrue=int(st.text_input(label="Probaility of getting True", value=50, key="ptrue"+str(i)+str(j))) for i in range(nrows): op[i] = fake.boolean(chance_of_getting_true=ptrue) return op if coltype == "Job": op = [None]*nrows for i in range(nrows): op[i] = fake.job() return op if coltype == "ISBN": op = [None]*nrows isbntype=st.selectbox(label="ISBN type",options=("10","13"),key="cctype"+str(i)+str(j)) if isbntype=="10": for i in range(nrows): op[i] = fake.isbn10() if isbntype=="13": for i in range(nrows): op[i] = fake.isbn13() return op if coltype == "Color": op = [None]*nrows for i in range(nrows): op[i] = fake.color_name() return op if coltype == "Email": op = [None]*nrows for i in range(nrows): op[i] = fake.email() return op if coltype == "Credit Card": cctype=st.selectbox(label="value type",options=("Expiry","CVC","Full"), key="cctype"+str(i)+str(j)) op = [None]*nrows if cctype == "Expiry": for i in range(nrows): op[i]=fake.credit_card_expire() if cctype == "CVC": for i in range(nrows): op[i]=fake.credit_card_security_code() if cctype == "Provider": for i in range(nrows): op[i]=fake.credit_card_provider() if cctype == "Full": for i in range(nrows): op[i]=fake.credit_card_full() return op if coltype == "List": lst = st.text_input( label="enter a list of things, comma seperated", value="foo, bar, baz", key="lab"+str(i)+str(j)) howlst = st.selectbox( "how do you want to generate the column", ('random', 'in sequence'), key="howl"+str(i)+str(j)) lst = lst.split(sep=",") llen = len(lst) if howlst == "random": lop = [] for i in range(nrows): lop.append(lst[random.randint(0, llen-1)]) elif howlst == "in sequence": lop = [] for i in range(nrows): lop.append(lst[i % llen]) return lop if coltype == "Distribution": disttype=st.selectbox("Distribution Type",("Normal Distribution","Exponential Distribution","Visual Distribution")) if disttype=="Visual Distribution": xmin = st.text_input("Enter lowest x value", value=0, key="xmn"+str(i)+str(j)) xmax = st.text_input("Enter highest x value", value=1, key="xmx"+str(i)+str(j)) ymin = st.text_input("Enter lowest y value", value=0, key="ymn"+str(i)+str(j)) ymax = st.text_input("Enter highest y value", value=1, key="ymx"+str(i)+str(j)) if st.button("Graph drawing Tool"): subprocess.run(["python", "tink3.py",xmin,xmax,ymin,ymax]) return [None]*nrows if disttype=="Normal Distribution": mean=int(st.text_input(label="enter mean of distribution", value=0, key="ndm"+str(i)+str(j))) scale=int(st.text_input(label="enter scale/std.dev of distribution", value=0, key="nds"+str(i)+str(j))) return norm.rvs(size=nrows,loc=mean,scale=scale) if disttype=="Exponential Distribution": mean=int(st.text_input(label="enter mean of distribution", value=0, key="xdm"+str(i)+str(j))) scale=int(st.text_input(label="enter scale/std.dev of distribution", value=0, key="xds"+str(i)+str(j))) return expon.rvs(size=nrows,loc=mean,scale=scale) if coltype == "Python Expression": def getcol(colname): return tblcols[colnames.index(colname)] op=[None]*nrows st.caption("write a python code or expression to describe the individual element of the column. the code needs to modify the value of op[i] , which is a value of a single element of the column, and i is the row number.") st.caption("the function getcol('colname') allows you to access values of other columns to create relationships, eg:") st.code(""" if (getcol('Gender')[i]=='Male'): op[i]=fake.first_name_male else: op[i]=fake.first_name_female """ ) content = st_ace(language="python", theme="twilight", auto_update=True, wrap=True, min_lines=1, max_lines=2, key="code"+str(i)+str(j)) if st.button("save"): with open('pyexpr'+f'{i}'+'.py', "w") as myfile: myfile.write(content) myfile.close() for i in range(nrows): exec(open('pyexpr'+f'{i}'+'.py').read(),globals(),locals()) return op def page_home(): htmlp1 = ''' <style> .text { color: #000000; -webkit-text-stroke: 0.2px white; text-shadow: 1px 0px 1px #CCCCCC, 0px 1px 1px #EEEEEE, 2px 1px 1px #CCCCCC, 1px 2px 1px #EEEEEE, 3px 2px 1px #CCCCCC, 2px 3px 1px #EEEEEE, 4px 3px 1px #CCCCCC, 3px 4px 1px #EEEEEE, 5px 4px 1px #CCCCCC, 4px 5px 1px #EEEEEE, 6px 5px 1px #CCCCCC, 5px 6px 1px #EEEEEE, 7px 6px 1px #CCCCCC; } del { background: #000; color: #fff; text-decoration:none; } .bruh{ display:inline; margin-right:10px; } </style> <h1 class="text">GENETHOS🧊</h1> <h3 class="text bruh"><i>Synthetic Data & Bias Tools</i></h3> <!-- <del>v0.0.1</del> --> ''' st.markdown(htmlp1, unsafe_allow_html=True) st.subheader("About our App:") st.write("The app is divided into three sections, New Data, More Data, and Bias Detection and Mitigation. On the sidebar on the left you can upload a dataset to generate more columns with synthetic data tools or to detect and eliminate bias with Bias tools. The new data ") st.write("Our Web-based Synthetic data & Bias tools help you to generate more data or create entirely new data and detect and eliminate bias in datasets.") st.subheader("Synthetic Data & it's benefits:") st.write('1. Overcoming real data usage restrictions: Real data may have usage constraints due to privacy rules or other regulations. Synthetic data can replicate all important statistical properties of real data without exposing real data, thereby eliminating the issue.') st.write('2. Creating data to simulate not yet encountered conditions: Where real data does not exist, synthetic data is the only solution.') st.write('3. Immunity to some common statistical problems: These can include item nonresponse, skip patterns, and other logical constraints.') st.write('4. Immunity to some common statistical problems: These can include item nonresponse, skip patterns, and other logical constraints.') st.subheader('Bias Mitigation & Detection:') st.write("For Bias detection our applications utilizes already established metrics and mitigation algorithms by IBM-AIF360. Further In our work we implement those on new datasets. Also we use this tool to interpret if AI models generate bias data. If yes we provide a mitigated data")
# # (C) Tenable Network Security, Inc. # # The descriptive text and package checks in this plugin were # extracted from Debian Security Advisory DSA-4135. The text # itself is copyright (C) Software in the Public Interest, Inc. # include("compat.inc"); if (description) { script_id(108304); script_version("1.6"); script_cvs_date("Date: 2018/11/13 12:30:46"); script_cve_id("CVE-2018-1050", "CVE-2018-1057"); script_xref(name:"DSA", value:"4135"); script_name(english:"Debian DSA-4135-1 : samba - security update"); script_summary(english:"Checks dpkg output for the updated package"); script_set_attribute( attribute:"synopsis", value:"The remote Debian host is missing a security-related update." ); script_set_attribute( attribute:"description", value: "Several vulnerabilities have been discovered in Samba, a SMB/CIFS file, print, and login server for Unix. The Common Vulnerabilities and Exposures project identifies the following issues : - CVE-2018-1050 It was discovered that Samba is prone to a denial of service attack when the RPC spoolss service is configured to be run as an external daemon. https://www.samba.org/samba/security/CVE-2018-1050.html - CVE-2018-1057 Bjoern Baumbach from Sernet discovered that on Samba 4 AD DC the LDAP server incorrectly validates permissions to modify passwords over LDAP allowing authenticated users to change any other users passwords, including administrative users. https://www.samba.org/samba/security/CVE-2018-1057.html https://wiki.samba.org/index.php/CVE-2018-1057" ); script_set_attribute( attribute:"see_also", value:"https://security-tracker.debian.org/tracker/CVE-2018-1050" ); script_set_attribute( attribute:"see_also", value:"https://www.samba.org/samba/security/CVE-2018-1050.html" ); script_set_attribute( attribute:"see_also", value:"https://security-tracker.debian.org/tracker/CVE-2018-1057" ); script_set_attribute( attribute:"see_also", value:"https://www.samba.org/samba/security/CVE-2018-1057.html" ); script_set_attribute( attribute:"see_also", value:"https://wiki.samba.org/index.php/CVE-2018-1057" ); script_set_attribute( attribute:"see_also", value:"https://security-tracker.debian.org/tracker/source-package/samba" ); script_set_attribute( attribute:"see_also", value:"https://packages.debian.org/source/stretch/samba" ); script_set_attribute( attribute:"see_also", value:"https://www.debian.org/security/2018/dsa-4135" ); script_set_attribute( attribute:"solution", value: "Upgrade the samba packages. For the oldstable distribution (jessie), CVE-2018-1050 will be addressed in a later update. Unfortunately the changes required to fix CVE-2018-1057 for Debian oldstable are too invasive to be backported. Users using Samba as an AD-compatible domain controller are encouraged to apply the workaround described in the Samba wiki and upgrade to Debian stretch. For the stable distribution (stretch), these problems have been fixed in version 2:4.5.12+dfsg-2+deb9u2." ); script_set_cvss_base_vector("CVSS2#AV:N/AC:L/Au:S/C:P/I:P/A:P"); script_set_cvss3_base_vector("CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H"); script_set_attribute(attribute:"plugin_type", value:"local"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:debian:debian_linux:samba"); script_set_attribute(attribute:"cpe", value:"cpe:/o:debian:debian_linux:9.0"); script_set_attribute(attribute:"patch_publication_date", value:"2018/03/13"); script_set_attribute(attribute:"plugin_publication_date", value:"2018/03/14"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_copyright(english:"This script is Copyright (C) 2018 and is owned by Tenable, Inc. or an Affiliate thereof."); script_family(english:"Debian Local Security Checks"); script_dependencies("ssh_get_info.nasl"); script_require_keys("Host/local_checks_enabled", "Host/Debian/release", "Host/Debian/dpkg-l"); exit(0); } include("audit.inc"); include("debian_package.inc"); if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED); if (!get_kb_item("Host/Debian/release")) audit(AUDIT_OS_NOT, "Debian"); if (!get_kb_item("Host/Debian/dpkg-l")) audit(AUDIT_PACKAGE_LIST_MISSING); flag = 0; if (deb_check(release:"9.0", prefix:"ctdb", reference:"2:4.5.12+dfsg-2+deb9u2")) flag++; if (deb_check(release:"9.0", prefix:"libnss-winbind", reference:"2:4.5.12+dfsg-2+deb9u2")) flag++; if (deb_check(release:"9.0", prefix:"libpam-winbind", reference:"2:4.5.12+dfsg-2+deb9u2")) flag++; if (deb_check(release:"9.0", prefix:"libparse-pidl-perl", reference:"2:4.5.12+dfsg-2+deb9u2")) flag++; if (deb_check(release:"9.0", prefix:"libsmbclient", reference:"2:4.5.12+dfsg-2+deb9u2")) flag++; if (deb_check(release:"9.0", prefix:"libsmbclient-dev", reference:"2:4.5.12+dfsg-2+deb9u2")) flag++; if (deb_check(release:"9.0", prefix:"libwbclient-dev", reference:"2:4.5.12+dfsg-2+deb9u2")) flag++; if (deb_check(release:"9.0", prefix:"libwbclient0", reference:"2:4.5.12+dfsg-2+deb9u2")) flag++; if (deb_check(release:"9.0", prefix:"python-samba", reference:"2:4.5.12+dfsg-2+deb9u2")) flag++; if (deb_check(release:"9.0", prefix:"registry-tools", reference:"2:4.5.12+dfsg-2+deb9u2")) flag++; if (deb_check(release:"9.0", prefix:"samba", reference:"2:4.5.12+dfsg-2+deb9u2")) flag++; if (deb_check(release:"9.0", prefix:"samba-common", reference:"2:4.5.12+dfsg-2+deb9u2")) flag++; if (deb_check(release:"9.0", prefix:"samba-common-bin", reference:"2:4.5.12+dfsg-2+deb9u2")) flag++; if (deb_check(release:"9.0", prefix:"samba-dev", reference:"2:4.5.12+dfsg-2+deb9u2")) flag++; if (deb_check(release:"9.0", prefix:"samba-dsdb-modules", reference:"2:4.5.12+dfsg-2+deb9u2")) flag++; if (deb_check(release:"9.0", prefix:"samba-libs", reference:"2:4.5.12+dfsg-2+deb9u2")) flag++; if (deb_check(release:"9.0", prefix:"samba-testsuite", reference:"2:4.5.12+dfsg-2+deb9u2")) flag++; if (deb_check(release:"9.0", prefix:"samba-vfs-modules", reference:"2:4.5.12+dfsg-2+deb9u2")) flag++; if (deb_check(release:"9.0", prefix:"smbclient", reference:"2:4.5.12+dfsg-2+deb9u2")) flag++; if (deb_check(release:"9.0", prefix:"winbind", reference:"2:4.5.12+dfsg-2+deb9u2")) flag++; if (flag) { if (report_verbosity > 0) security_warning(port:0, extra:deb_report_get()); else security_warning(0); exit(0); } else audit(AUDIT_HOST_NOT, "affected");
import { createAsyncThunk } from '@reduxjs/toolkit'; import { APIRoute, NameSpace } from '../../../const'; import { AsyncThunkConfig } from '../../../types/state'; import { AuthData } from '../../../types/auth-data'; import { UserData } from '../../../types/user-data'; import { dropToken, saveToken } from '../../../services/token'; import { fetchOffersAction } from '../multiple-offers'; export const checkAuthAction = createAsyncThunk< UserData, undefined, AsyncThunkConfig >(`${NameSpace.User}/checkAuth`, async (_arg, { extra: api }) => { const { data } = await api.get<UserData>(APIRoute.Login); return data; }); export const loginAction = createAsyncThunk< UserData, AuthData, AsyncThunkConfig >( `${NameSpace.User}/login`, async ({ login: email, password }, { dispatch, extra: api }) => { const { data } = await api.post<UserData>(APIRoute.Login, { email, password, }); dispatch(fetchOffersAction()); saveToken(data.token); return data; } ); export const logoutAction = createAsyncThunk<void, undefined, AsyncThunkConfig>( `${NameSpace.User}/logout`, async (_arg, { dispatch, extra: api }) => { await api.delete(APIRoute.Logout); dispatch(fetchOffersAction()); dropToken(); } );
<div class="modal-container"> <mat-icon svgIcon="cross" class="close" (click)="onCloseDialog()"></mat-icon> <div class="header"> <span>{{ text.header }}</span> </div> <div class="controls-container"> <div class="searchText" *ngIf="!secondInput"> <input id="search-name" class="input-search" type="text" name="search" [placeholder]="inputPlaceholder" [(ngModel)]="searchText" /> <mat-icon class="search-icon" [ngClass]="{ black: searchText.length != 0 }" svgIcon="{{ !searchText.length ? 'search' : 'cross' }}" (click)="clearText()"></mat-icon> </div> <!-- <button class="filter-btn-primary" [ngClass]="{ active: isFilterShow }" [matTooltip]="text.tooltip.filter" matTooltipClass="mat-tooltip-dropdown tooltip-star tooltip-margin" matTooltipShowDelay="300" matTooltipPosition="above" (click)="toggleFilter()" > <mat-icon svgIcon="configure"></mat-icon> </button> --> <div class="filter" *ngIf="isFilterShow"> <div class="tab"> <button class="tab-btn" [ngClass]="{ active: suggest === 1 }" (click)="changeSuggest(1)"> {{ text?.freeVoice }} </button> <button class="tab-btn" [ngClass]="{ active: suggest === 4 }" (click)="changeSuggest(4)"> {{ text?.favVoice }} </button> </div> <div class="searchTextSec" *ngIf="secondInput"> <input id="search-name" class="input-search-2" type="text" name="search" [placeholder]="inputPlaceholder" [(ngModel)]="searchText" /> <mat-icon class="search-icon" [ngClass]="{ black: searchText.length != 0 }" svgIcon="{{ !searchText.length ? 'search' : 'cross' }}" (click)="clearText()"></mat-icon> </div> <div class="group-filter"> <div class="dropdown" appClickOutside (clickOutside)="closeLangPopup()"> <button class="filter-btn" [ngClass]="{ active: isLangShow }" (click)="toggleLangDropdown('Lang')"> <span class="filter-text">{{ text.lang }}</span> <mat-icon svgIcon="down" class="down"></mat-icon> </button> <div class="popup-filter popup-lang" *ngIf="isLangShow"> <div class="clear-select"> <p class="select-all" (click)="selectAllFilter('language')"> {{ text.selectAll }} </p> <p class="clear-all" (click)="clearAllFilter('language')"> {{ text.clear }} </p> </div> <div class="list-container"> <span class="list" *ngFor="let lang of allLang" (click)="addRemoveFilter(lang, 'language')" [ngClass]="{ selected: filterKey.language.includes(lang) }"> <img class="flag" src="../../../../assets/icons/toolbar/conversation/flags/{{ getFlagByName(lang) }}" alt="flag" /> {{ lang }}</span> </div> </div> </div> <div class="dropdown" appClickOutside (clickOutside)="closeVoicePopup()"> <button class="filter-btn" [ngClass]="{ active: isVoiceShow }" (click)="toggleLangDropdown('Voice')"> <span class="filter-text">{{ text.style }}</span> <mat-icon svgIcon="down" class="down"></mat-icon> </button> <div class="popup-filter popup-voice" *ngIf="isVoiceShow"> <div class="clear-select"> <p class="select-all" (click)="selectAllFilter('voiceStyle')"> {{ text.selectAll }} </p> <p class="clear-all" (click)="clearAllFilter('voiceStyle')"> {{ text.clear }} </p> </div> <div class="list-container"> <span class="list" *ngFor="let voice of voiceStyle" (click)="addRemoveFilter(voice, 'voiceStyle')" [ngClass]="{ selected: filterKey.voiceStyle.includes(voice) }">{{ lang === "TH" ? voice.replace("เสียง", "") : voice }}</span> </div> </div> </div> <div class="dropdown" appClickOutside (clickOutside)="closeSpeechPopup()"> <button class="filter-btn" [ngClass]="{ active: isSpeechShow }" (click)="toggleLangDropdown('Speech')"> <span class="filter-text">{{ text.categories }}</span> <mat-icon svgIcon="down" class="down"></mat-icon> </button> <div class="popup-filter popup-speech" *ngIf="isSpeechShow"> <div class="clear-select"> <p class="select-all" (click)="selectAllFilter('speechStyle')"> {{ text.selectAll }} </p> <p class="clear-all" (click)="clearAllFilter('speechStyle')"> {{ text.clear }} </p> </div> <div class="list-container"> <span class="list" *ngFor="let speech of speechStyle" (click)="addRemoveFilter(speech, 'speechStyle')" [ngClass]="{ selected: filterKey.speechStyle.includes(speech) }">{{ lang === "TH" ? speech.replace("สไตล์", "") : speech }}</span> </div> </div> </div> <div class="dropdown" appClickOutside (clickOutside)="closeGenderPopup()"> <button class="filter-btn" [ngClass]="{ active: isGenderShow }" (click)="toggleLangDropdown('Gender')"> <span class="filter-text">{{ text.gender }}</span> <mat-icon svgIcon="down" class="down"></mat-icon> </button> <div class="popup-filter popup-gender" *ngIf="isGenderShow"> <div class="clear-select"> <p class="select-all" (click)="selectAllFilter('gender')"> {{ text.selectAll }} </p> <p class="clear-all" (click)="clearAllFilter('gender')"> {{ text.clear }} </p> </div> <div class="list-container"> <span class="list" *ngFor="let gender of allGender" (click)="addRemoveFilter(gender, 'gender')" [ngClass]="{ selected: filterKey.gender.includes(gender) }">{{ gender }}</span> </div> </div> </div> </div> <!-- <div class="group-suggest"> <button class="suggest-btn" [ngClass]="{ active: suggest === 1 }" (click)="changeSuggest(1)" > {{ text.all }} </button> <button class="suggest-btn" [ngClass]="{ active: suggest === 2 }" (click)="changeSuggest(2)" > {{ text.popular }} </button> <button class="suggest-btn" [ngClass]="{ active: suggest === 3 }" (click)="changeSuggest(3)" > {{ text.new }} </button> </div> --> </div> </div> <div class="result" *ngIf="searchText"> <span class="result-text">{{ text.searchResult }} : {{ text.resultAll }} {{ (mutateList | speakerSearch : searchText)?.length }} {{ text.resultList }}</span> </div> <div class="filter-result" *ngIf="filterList.length"> <div class="result-span"> <span class="result-filter-text">Filter Result : </span> <div class="filter-span-container"> <span *ngFor="let filter of filterList" class="filter-span" (click)="removeFilterItem(filter.name, filter.type)">{{ filter.name }}</span> </div> <p class="clear-filter-list" (click)="clearFilterList()"> {{ text.clear }} </p> </div> </div> <div class="speaker-container" *ngIf="isAllShow" [ngClass]="{ expanded: searchText.length > 0 }"> <div class="not-found" *ngIf=" (mutateList | speakerSearch : searchText).length === 0 || (mutateList | speakerFilter : filterKey).length === 0 "> <mat-icon class="not-found-icon" svgIcon="search"></mat-icon> <p class="no-result">{{ text.noResult }}</p> <p class="try">{{ text.try }}</p> </div> <cdk-virtual-scroll-viewport itemSize="45" class="viewport" *ngIf=" (mutateList | speakerSearch : searchText).length !== 0 && (mutateList | speakerFilter : filterKey).length !== 0 "> <ng-container *cdkVirtualFor=" let speaker of mutateList | speakerSearch : searchText | speakerFilter : filterKey; let i = index; trackBy: trackByFunction "> <div class="speaker-card" [ngClass]="{ selected: speaker.speaker_id === selectedVoice }"> <div class="img"> <img src="{{ speaker.premier ? speaker.speaker_image : speaker.square_image }}" alt="speaker-image" loading="lazy" [ngClass]="{ shift_img_down: speaker.premier }" /> <div class="tag-speaker"> <span class="tag-text" *ngIf="!speaker.premier">{{ text?.freeTag }}</span> <span class="tag-text-premium" *ngIf="speaker.premier"><img src="../../../../assets/marketplace/bot_logo.webp" alt="bot_logo" /> <!-- <span>{{ text.premium_tag }}</span> --> <span>Premium</span></span> </div> <div class="sound-btn-container"> <button class="audio-btn" [matTooltip]="text.tooltip.playSound" matTooltipClass="mat-tooltip-dropdown tooltip-margin" matTooltipShowDelay="300" matTooltipPosition="above" (click)=" playSample( speaker.audio, speaker.isPlaying, speaker.speaker_id ) "> <mat-icon class="audio-icon" svgIcon="{{ speaker.isPlaying ? 'pause_filled' : 'play_filled' }}" [ngClass]="{ 'shift-left': !speaker.isPlaying }"></mat-icon> </button> </div> </div> <div class="details"> <mat-icon class="favorite" svgIcon="{{ checkIsInCart(speaker.speaker_id) ? 'star_filled' : 'star' }}" [matTooltip]=" checkIsInCart(speaker.speaker_id) ? text.tooltip.removeFav : text.tooltip.addFav " matTooltipClass="mat-tooltip-dropdown tooltip-star tooltip-margin" matTooltipShowDelay="300" matTooltipPosition="above" (click)="addRemoveFav(speaker.speaker_id)"></mat-icon> <div class="main-row-1"> <div class="col1"> <div class="row1"> <span class="name">{{ lang === "EN" ? speaker.eng_name : speaker.thai_name }}</span> <div> <span class="gender">{{ lang === "TH" ? speaker.gender : speaker.eng_gender }}/</span> <span class="gender">{{ lang === "TH" ? speaker.age_style : speaker.eng_age_style }}</span> </div> </div> <div class="row2"> <span class="style" *ngFor=" let style of lang === 'TH' ? speaker.speech_style : speaker.eng_speech_style " [ngStyle]="{ background: tagColor(style) }">{{ lang === "TH" ? style.replace("สไตล์", "") : style }}</span> </div> </div> </div> <div class="main-row-2"> <div class="flag-list" [appPopupTrigger]="popupElement"> <img (error)="onFlagError(speaker)" class="flag" src="../../../../assets/icons/toolbar/conversation/flags/{{ speaker.flagImg }}" alt="flag" /> @for (flag of speaker.available_language.slice(0, 1); track $index) { <span class="second-flag"> @if (speaker.flagImg != getFlagByValue(flag)?.flag) { <img class="flag" src="../../../../assets/icons/toolbar/conversation/flags/{{ getFlagByValue(flag)?.flag }}" alt="flag" /> } </span> } <span class="other-flags"> {{ text?.other }} </span> <div class="popup-available-lang" #popupElement> <div class="popup-container"> <p class="popup-header"> {{ text?.other_lang }} </p> <div class="popup-wrapper"> <div class="available-lang" *ngFor="let flaglist of speaker.available_language"> <img class="flag" src="../../../../assets/icons/toolbar/conversation/flags/{{ getFlagByValue(flaglist)?.flag }}" alt="flag" /> <span>{{ lang === "TH" ? getFlagByValue(flaglist)?.TH_name : getFlagByValue(flaglist)?.EN_name }}</span> </div> </div> </div> </div> </div> <button class="select-audio" [matTooltip]="text.tooltip.useVoice" matTooltipClass="mat-tooltip-dropdown tooltip-margin" matTooltipShowDelay="300" matTooltipPosition="above" (click)="selectSpeaker(i, speaker)" [ngClass]="{ active: speaker.speaker_id === selectedVoice }"> <mat-icon class="check" svgIcon="check_circle_filled"></mat-icon> <p *ngIf="!isSmallMobile"> {{ speaker.speaker_id === selectedVoice ? text.using : text.useVoice }} </p> </button> </div> </div> </div> </ng-container> </cdk-virtual-scroll-viewport> </div> <!-- <div class="confirm"> <button class="confirm-btn" (click)="onSubmit()">{{ text.confirm }}</button> </div> --> </div>
import React, { useState, useEffect } from "react"; import { ToastContainer, toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; export default function EditAddress() { const [userData, setUserData] = useState(null); const [isEditing, setIsEditing] = useState(false); const [updatedUser, setUpdatedUser] = useState({}); const [addressForm, setAddressForm] = useState(""); const [addresses, setAddresses] = useState([]); const [editAddressIndex, setEditAddressIndex] = useState(null); const [isAddingAddress, setIsAddingAddress] = useState(false); const [updatedLocation, setUpdatedLocation] = useState([]); const useremail = localStorage.getItem("userEmail"); useEffect(() => { async function fetchData() { try { const response = await fetch('https://backend-k4dp.onrender.com/api/userdata', { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ 'email':useremail }), }); if (response.ok) { const users = await response.json(); if (users) { setUserData(users); setUpdatedUser(users); setAddresses(users.location || []); } else { console.error("User with email not found"); } } else { console.error("Failed to fetch user data"); } } catch (error) { console.error("Error fetching user data:", error); } } fetchData(); }, [useremail]); const handleSaveClick = async () => { try { console.log(updatedLocation); const response = await fetch('https://backend-k4dp.onrender.com/api/user', { method: "PATCH", headers: { "Content-Type": "application/json", }, body: JSON.stringify({'email':useremail, location:updatedLocation}), }); if (response.ok) { const updatedUserData = await response.json(); setUserData(updatedUserData); toast.success("Data has been saved successfully.") setIsEditing(false); } else { toast.error("Failed to update data!!!!") console.error("Failed to update user data"); } } catch (error) { toast.error("Error on fetching data!!!!") console.error("Error updating user data:", error); } }; const handleAddressChange = ({ target: { name, value } }) => { setAddressForm(value); }; const handleAddressSubmit = async (e) => { e.preventDefault(); let newAddress = addressForm; if (editAddressIndex !== null) { const newAddresses = [...addresses]; newAddresses[editAddressIndex] = newAddress; setAddresses(newAddresses); setUpdatedLocation(newAddresses); } else { const newLocationArray = [addressForm]; setAddresses([...addresses, newLocationArray]); setUpdatedLocation([...addresses, ...newLocationArray]); } setAddressForm(""); setEditAddressIndex(null); setIsAddingAddress(false); }; const toggleAddAddress = () => { setIsAddingAddress(!isAddingAddress); setAddressForm(""); setEditAddressIndex(null); }; const editAddress = async (index) => { setAddressForm(addresses[index]); setEditAddressIndex(index); setIsEditing(true); setIsAddingAddress(true); }; const deleteAddress = async (index) => { const newAddresses = [...addresses]; newAddresses.splice(index, 1); setAddresses(newAddresses); setUpdatedLocation(newAddresses); }; const renderAddressForm = () => { if (isAddingAddress || isEditing) { return ( <form onSubmit={handleAddressSubmit}> <div className="form-group"> <label htmlFor="location">Location:</label> <input type="text" className="form-control" id="location" name="location" value={addressForm} onChange={handleAddressChange} /> </div> <button type="submit" className="btn btn-primary"> {editAddressIndex !== null ? "Update Address" : "Add Address"} </button> <button type="button" className="btn btn-secondary ml-2 mx-2" onClick={toggleAddAddress} > Cancel </button> </form> ); } else { return ( <div className="text-center font-weight-bold px-2 py-0 rounded"> <button type="button" className="btn bg-danger text-light fs-2 btn-lg rounded" onClick={toggleAddAddress} > + </button> </div> ); } }; return ( <div> <ul className="row"> {addresses.map((address, index) => ( <div className="col-md-6" key={index}> <div className="card mb-3 "> <div className="card-body"> <h5 className="card-title">Address {index + 1}</h5> <p className="card-text text-capitalize">{address}</p> <div className="btn-group" role="group"> <button className="btn btn-primary mx-3 rounded" onClick={() => editAddress(index)} > Edit </button> <button className="btn btn-warning mx-3 rounded" onClick={() => deleteAddress(index)} > Delete </button> </div> </div> </div> </div> ))} </ul> <h2>{renderAddressForm()}</h2> <button className="btn btn-primary my-2" onClick={handleSaveClick}> Save </button> <ToastContainer position="top-center" /> </div> ); }
--- title: "[New] What Is a Parody and How to Make a Parody Video for 2024" date: 2024-06-06T16:27:23.585Z updated: 2024-06-07T16:27:23.585Z tags: - ai video - ai youtube categories: - ai - youtube description: "This Article Describes [New] What Is a Parody and How to Make a Parody Video for 2024" excerpt: "This Article Describes [New] What Is a Parody and How to Make a Parody Video for 2024" keywords: "Parody Basics,Create Parody Vids,Making Fun Videos,Satire in Media,Copyright & Parodies,Humor Video Production,Comedy Film Techniques" thumbnail: https://thmb.techidaily.com/5f19d12263b1224bd46b49560f2a184a0c0f8c0d56bb43f9e5c26e9a6768a6cd.jpg --- ## What Is a Parody and How to Make a Parody Video # What is Parody and How to Make a Parody Video ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) ##### Richard Bennett Mar 27, 2024• Proven solutions **What is the meaning of parody?** Parody is making funny videos. Video editing is not as complicated as it looks. In older days, certain manual processing was required to make the videotape. But today the software industry has given us well-equipped tools for video making or editing. Video editors are on huge demand in various sectors starting from academics to business professions. Whether making a video tutorial or a creative content, video editing software is handy. Creating funny videos is the next big thing after the comedy scenes of the movies. To capture funny moments or to perform a funny act, certain video editing skills can be used. Then one can share these videos on the public platforms and gain praise. Social platforms like Youtube and Instagram are filled with such creative content. It gives the person a unique opportunity to show his/her talent in front of everyone with the help of these tools. The most important thing in the case of **parody video** is there is no requirement of professional editing knowledge to make the creative videos. Click here to see [Songs That Totally Crack You Up.](https://tools.techidaily.com/wondershare/filmora/download/) The “Import” option available on the timeline will do all the procedures alone. The user will not have to worry about anything. Importing is the starting procedure of video editing. There are plenty of additional features available on the same page of the program. Once the array of files is uploaded, the files are dragged and dropped in the timeline where they will be now subjected to be produced and shared. There will be no hassle to get access to the videos. All the imported files are available in the right place. The thumbnail on the left item tray will comprise of all the videos and audio clips. The user can easily obtain them and there will be no confusion. **History of Parody:** The history of Parody is very old, it comes from ancient Greece. At that time Battle of the Frogs and Mice hold in which unknown poet reproduces the epic style of Homer. **Successful influencer of music video parody- Bart Baker** Bart Baker is the king of the video parody. **Bart Baker** has his own YouTube channel and there you can find his videos. Few of his videos have followers more than 100 million. **Few of his videos are as below:** 1. The Chainsmokers ft. Halsey - "Closer" PARODY This is how many times they puffed out smoke in that song **Starboy - The Weeknd ft. Daft Punk** After listening to the vietsub, startboy saw it cursing me. After listening to the start-up bart, I saw the weeknd calling myself happy. Very nice invention. Youtube link: <https://www.youtube.com/watch?v=JOwGMpIv8LU> **Why his videos are the best:** Bart Baker is an American artist, web-based comedian, video producer, singer, and parody artist. He is best known for making parody videos of notable songs, which he posts on his YouTube channel. He was described as one of the most prolific creators of musical parodies by Billboard. In addition to being active on YouTube, Baker is known for his short videos on Vine and also on Live.ly, where he is the most winning broadcaster. His videos are described as "high-quality parodies that keep the originals very well." His videos are famous because they are a great source of entertainment for users. Every age people like his videos. **How to make a parody video?** If you want to know **how to make a parody video** then follow the below steps: * **Finding the perfect song:** * **Getting the correct music:** To get the right music, Youtube will be a suitable platform. * **Recording suitable lyrics:** The lyrics can be recorded with the help of a microphone in-built with computers. In the absence of a microphone, a video camera will do the work as a substitute. The operating system running under Windows will give the option of Windows movie maker as the recording tool. GarageBand and iMovie will serve the purpose if the user has a Mac operating device. The ultimate goal is a smooth recording. The area of the recording should be soundproof or should have minimum external noise interference. The professional studios have soundproof walls of the rooms for recording. But this is not the case here. Any quiet place is sufficiently suitable for the recording. The pitch and quality of the voice must not be too rough or too fast. Practicing for a few cycles before the final recording will be perfect. * **Making a music video:** The newly created parody will get the maximum benefit if it collaborates with a music video. Only with the help of a video camera, the filming can be done. There should be proper sync between the music video and the parody. Before filming everything should be planned. The location of the shoot should be confirmed beforehand. The background should meet the theme of the song and parody. It is required to carry all the costumes and props to the location of the shoot. Once the video is shot, now it is time for attaching the two clips to make a single impactful video. Use powerful video editing tools to get what you want- Filmora can help you make it. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) **Conclusion:** Today Youtube is the most prominent platform where people can utilize their video editing skills. Most of the uploaded videos require the skill of video editing at an expert level. The software does not require professional efficiency or any added degrees. It does not require any kind of paid course. With such amazing software and editing tools, youth can learn the skill and can try for employment opportunities in multimedia companies. Video editing is making good career opportunities for multi-media platforms. The youth should engage themselves in some challenging work and gain a good amount of experience. ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> ## The Endgame: Permanently Blocking Access to YouTube Shorts # How to Disable/Remove YouTube Shorts Permanently? ![author avatar](https://images.wondershare.com/filmora/article-images/shannon-cox.jpg) ##### Shanoon Cox Nov 07, 2023• Proven solutions YouTube Shorts is undoubtedly one of the most trending features, just like TikTok, which has also followed it for many years and created a vast user base. Creating such a short duration video is quick, grabs attention, and gets spread like a fire. But, do you know that inclusion of YouTube shorts replaces the explore option to make proper adjustments for YouTube Shorts under the application. Not only this, many users dislike getting disturbed by such a short duration video while searching for some beneficial, informative, or detailed information. If any of such cases, attune with you, and you want to know **how to disable YouTube Shorts** or **remove Shorts from the YouTube** platform. Then, this is the right place. In this article, you will learn the process of disabling YouTube Shorts or removing YouTube shorts permanently. Just remain stick with the guidelines, and soon you will become able to do the same with easy steps. * Method 1: [Three dots option](#1) * Method 2: [Settings menu of YouTube](#2) * Method 3: [Can go with YouTube browser](#3) * Method 4: [Factory reset](#4) * Method 5: [Link to downgrade the YouTube](#5) * Method 6: [Removing all update](#6) * Method 7: [Try YouTube Vanced](#7) ## Easy Ways to Disable/Remove YouTube Shorts Now, as you have reached this section, you should be curious, what are the steps or methods with the help of which you would be able to disable YouTube Shorts. Don’t worry. Here, we shall cover all the methods of removing shorts from YouTube in detail. You can choose either of them as per your suitability or the one which best suits you. Some of these methods are pretty easy to follow, or you might need to follow some steps for some. But the main essence is, following any method will show how to remove shorts from YouTube. So, now go with the methods one by one and follow the guidelines to remove shorts from YouTube. ### Method 1: Three dots option One of the primary things you can do with any short videos is to click on the three dots next to each of such videos if you are not particularly willing to see something. Doing so will open the pop-up window, which will give you the option of “Not interested”. Click on this option. That’s it. Next time, such a video will not appear to you while surfing videos on YouTube. ![not intereted to ban youtube shorts](https://images.wondershare.com/filmora/disable-youtube-shorts-1.jpg) Here, no doubt the method is simple, but this method needs repetitiveness. As, whenever you see Shorts videos, you need to click on three dots to remove that. ### Method 2: Settings menu of YouTube At your YouTube homepage at the top end, you will see the profile icon. If you click on it, that will lead you towards the **Settings** menu of YouTube. From there, you need to select “General”, which will show up some options. Here, click on the Shorts option to turn it off. ![turn of youtube shorts](https://images.wondershare.com/filmora/article-images/2023/04/turn-off-youtube-shorts.jpg) This way, by simply following and managing settings, you can easily disable YouTube shorts from the platform. Now, restart your device to apply the removal process of YouTube shorts from there entirely. Thus, the next time you open the application, you will find that there exists no such YouTube shorts video as this option will disable YouTube Shorts. Try Filmora to Create Funny yet Trendy YouTube Shorts! As a YouTube fan, you can also create interesting video by yourself with [**Filmora YouTube Video Editor**](https://tools.techidaily.com/wondershare/filmora/download/). You can add cool visual effects and popular emojis to decorate your video. Plus, there is a vast media library to add audio and filter! You are **free to create popular YouTube Shorts** and post it on YouTube or other social media directly. [Create YouTube Shorts Free](https://tools.techidaily.com/wondershare/filmora/download/) [Create YouTube Shorts Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) [![iOS](https://images.wondershare.com/assets/images-common/badges-apple.svg)](https://app.adjust.com/w06dr6m%5F19za1f6) [![Android](https://images.wondershare.com/assets/images-common/badges-google.svg) ](https://app.adjust.com/w06dr6m%5F19za1f6) [Try It Free >>](https://tools.techidaily.com/wondershare/filmora/download/) ### Method 3: Can go with YouTube browser Hey guys, there is one more trick. Whenever you want to access YouTube, instead of going through the application, try to open YouTube website either from your mobile or PC browser window. You would wonder why so and what difference it will make. The fact is that the Shorts tab has not yet been incorporated under the browser version of YouTube. So friends, try this to avoid seeing YouTube Shorts videos either from phone or desktop. This is not only simple but also device-free. And even if you do not have a YouTube application, you can use this trick to solve your concern. ### Method 4: Factory reset If you disagree with the shorts video and want to get off of it entirely. This trick might help you. For this, visit the YouTube app on your mobile and press on it for some time. Doing so will lead you to the info section under the settings. When you click on the **Uninstall** option, the YouTube version will get downgraded to the factory version. This is the version that is a pre-installed version of YouTube that comes with the device. Also, if you have not updated your YouTube app, then don’t go with that. However, you will receive notifications many times that you should update your application. Just ignore it, especially if you are not willing to add the Shorts video option on your YouTube application. ### Method 5: Link to downgrade the YouTube Friends, for every problem, there exists some solution. And, if you are finding it difficult to factory reset the YouTube, you can download the downgraded version of YouTube. This is the version that does not contain the YouTube Shorts feature. Do like this: 1. Visit the [Link](https://www.apkmirror.com/apk/google-inc/youtube/youtube-14-12-56-release/youtube-14-12-56-16-android-apk-download/) and download the downgraded version. 2. Install by allowing unknown resources also. 3. Then, disable the auto-update of the YouTube option also. **Note:** While downloading and installing this version, you need to allow installation from unknown sources. #### Filmora YouTube Video Editor Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! Create YouTube Shorts with ease! [Make YouTube Shorts](https://tools.techidaily.com/wondershare/filmora/download/) [Make YouTube Shorts](https://tools.techidaily.com/wondershare/filmora/download/) [Make YouTube Shorts](https://tools.techidaily.com/wondershare/filmora/download/) [![iOS](https://images.wondershare.com/assets/images-common/badges-apple.svg)](https://app.adjust.com/w06dr6m%5F19za1f6) [![Android](https://images.wondershare.com/assets/images-common/badges-google.svg) ](https://app.adjust.com/w06dr6m%5F19za1f6) [Try It Free >>](https://tools.techidaily.com/wondershare/filmora/download/) ![filmora box](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) ### Method 6: Removing all update There exists one more simple trick to understand how to turn off YouTube Shorts. That is to remove all update options. How to do that, follow the below-mentioned steps you can do so. On your smartphone, open the **Settings** \> **Apps** or **Manage Apps** option > choose **YouTube** app> at the top right end, click on three dots there > click on **Uninstall Updates**. That will replace your YouTube app with that of the older version of YouTube. ![filmora](https://images.wondershare.com/filmora/disable-youtube-shorts-4.jpg) Using this method, you can remove shorts easily from YouTube. And, it is not going to take much amount of time. So, go and follow the steps. ### Method 7: Try YouTube Vanced Wait, the list is not over yet. If none of the previous methods work, try **YouTube Vanced**, the advanced and premium version of YouTube to get rid of YouTube Shorts. Well, not only that, but YouTube Vanced also comes up with multiple services that you can enjoy along with it, such as disabling YouTube Shorts, blocking ads, stories, or any of the sponsored features. If not sure how to go about it, then let’s have a look over the following steps that will guide you to get YouTube Vanced. **Step 1: Download YouTube Vanced** First, download the YouTube Vanced application from its website. **Step 2: Install and complete the setup process** After that, complete the installation process and follow the on-screen direction rightly to make it work effectively for you. **Note:** If you are downloading from the website, not from the app store, then there might appear the warning. So ignore that and go with the downloading and installation process. **Step 3: Open application and visit settings** Once you have launched the application, under the settings, you need to go for the **Vanced settings** option> there opt for "Ad settings" > at the end of the page, switch on the **Shorts shelf**. ![filmora](https://images.wondershare.com/filmora/disable-youtube-shorts-5.jpg) Doing so will disable the YouTube Shorts option from the **Home** screen. Alternatively, remove the **YouTube Shorts** button also from the screen. Under the “Vanced settings” > Visit **Layout settings** \> Switch on the **Comments location** option. That will further remove the Shorts button from the bottom end of the Home screen of the YouTube page. ![filmora](https://images.wondershare.com/filmora/disable-youtube-shorts-6.jpg) Voila, now you can say that you get rid of those shorts videos by removing shorts from YouTube using YouTube Vanced option. Thus, following the methods mentioned above gives you multiple ways to turn off shorts on YouTube. I hope that now you will be able to use YouTube without any concern or interference of YouTube Shorts videos. ![filmora logo](https://neveragain.allstatics.com/2019/assets/icon/logo/filmora-horizontal.svg) ## A cross-platform for making videos anywhere for all creators ![filmora-02](https://images.wondershare.com/filmora/filmora12/side_brand_filmora12.png) Why your video editing isn't good enough? How about some creative inspo? * 100 Million+ Users * 150+ Countries and Regions * 4 Million+ Social Media Followers * 5 Million+ Stock Media for Use [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://apps.apple.com/app/apple-store/id1459336970?pt=169436&ct=official-website&mt=8) [Try It Free](https://app.adjust.com/b0k9hf2%5F4bsu85t) \* Secure Download ![filmora12](https://images.wondershare.com/filmora/12-filmora/img/filmora12-01.png) ### Conclusion YouTube has always been the favorite choice for many users to explain videos under the same platform just a few steps away. Somehow, the YouTube Shorts will not be a good choice for those dedicated users who always explore YouTube for detailed videos or information. Thus, keeping that issue in mind, this article assisted with both the ways to turn off YouTube shorts or remove YouTube shorts with simple steps. So, friends, let’s not wait for anymore. Scroll up the article and get a detailed steps-wise guide and get a good grab of the process. So that your concern will get resolved, and soon you will be able to access the platform with the last look. ![author avatar](https://images.wondershare.com/filmora/article-images/shannon-cox.jpg) Shanoon Cox Shanoon Cox is a writer and a lover of all things video. Follow @Shanoon Cox <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://eaxpv-info.techidaily.com/new-global-leaderboard-top-subscribers-by-youtube-star-for-2024/"><u>[New] Global Leaderboard Top Subscribers by YouTube Star for 2024</u></a></li> <li><a href="https://eaxpv-info.techidaily.com/new-in-2024-how-to-animate-and-make-your-own-effects/"><u>[New] In 2024, How to Animate and Make Your Own Effects</u></a></li> <li><a href="https://eaxpv-info.techidaily.com/new-the-dos-and-donts-of-adding-tags-to-youtube-videos/"><u>[New] The Do's and Don'ts of Adding Tags to YouTube Videos</u></a></li> <li><a href="https://eaxpv-info.techidaily.com/new-high-performance-gpu-picks-for-quality-video-streaming-for-2024/"><u>[New] High-Performance GPU Picks for Quality Video Streaming for 2024</u></a></li> <li><a href="https://eaxpv-info.techidaily.com/updated-2024-approved-how-to-make-your-youtube-animated-subscribe-button-easily-with-filmora/"><u>[Updated] 2024 Approved How to Make Your YouTube Animated Subscribe Button Easily With Filmora</u></a></li> <li><a href="https://eaxpv-info.techidaily.com/updated-harness-the-power-of-youtube-shorts-expert-filming-and-editing-techniques-for-2024/"><u>[Updated] Harness the Power of YouTube Shorts Expert Filming and Editing Techniques for 2024</u></a></li> <li><a href="https://eaxpv-info.techidaily.com/new-fusing-genres-a-youtube-music-strategy-for-2024/"><u>[New] Fusing Genres A YouTube Music Strategy for 2024</u></a></li> <li><a href="https://eaxpv-info.techidaily.com/updated-transform-your-videos-presence-with-youtube-thumbnail-tailoring/"><u>[Updated] Transform Your Video's Presence with YouTube Thumbnail Tailoring</u></a></li> <li><a href="https://eaxpv-info.techidaily.com/new-2024-approved-how-to-seamlessly-integrate-captions-into-youtube-videos/"><u>[New] 2024 Approved How to Seamlessly Integrate Captions Into YouTube Videos</u></a></li> <li><a href="https://extra-information.techidaily.com/guide-to-picking-best-free-online-srt-translation-providers/"><u>Guide to Picking Best Free Online SRT Translation Providers</u></a></li> <li><a href="https://twitter-videos.techidaily.com/from-twitter-to-gifs-a-cost-saving-how-to-guide/"><u>From Twitter to Gifs A Cost-Saving How-To Guide</u></a></li> <li><a href="https://android-location-track.techidaily.com/9-best-phone-monitoring-apps-for-oneplus-ace-2-pro-drfone-by-drfone-virtual-android/"><u>9 Best Phone Monitoring Apps for OnePlus Ace 2 Pro | Dr.fone</u></a></li> <li><a href="https://youtube-videos.techidaily.com/dissecting-youtubes-strategy-to-empower-short-form-content-makers-for-2024/"><u>Dissecting YouTube’s Strategy to Empower Short-Form Content Makers for 2024</u></a></li> <li><a href="https://youtube-video-recordings.techidaily.com/unpacking-youtubes-income-distribution-from-1m-viewers/"><u>Unpacking YouTube's Income Distribution From 1M Viewers</u></a></li> <li><a href="https://smart-video-editing.techidaily.com/updated-filmora-watermark-removal-free-and-paid-methods-for-2024/"><u>Updated Filmora Watermark Removal Free and Paid Methods for 2024</u></a></li> <li><a href="https://extra-guidance.techidaily.com/one-airpod-not-working-how-to-fix-it-for-2024/"><u>One Airpod Not Working How to Fix It for 2024</u></a></li> <li><a href="https://discord-videos.techidaily.com/updated-2024-approved-unleashing-discord-video-talks-desktop-and-mobile-guide/"><u>[Updated] 2024 Approved Unleashing Discord Video Talks - Desktop & Mobile Guide</u></a></li> <li><a href="https://android-location.techidaily.com/getting-the-pokemon-go-gps-signal-not-found-11-error-in-oppo-reno-10-proplus-5g-drfone-by-drfone-virtual/"><u>Getting the Pokemon Go GPS Signal Not Found 11 Error in Oppo Reno 10 Pro+ 5G | Dr.fone</u></a></li> <li><a href="https://change-location.techidaily.com/in-2024-detailed-guide-of-ispoofer-for-pogo-installation-on-vivo-y100i-power-5g-drfone-by-drfone-virtual-android/"><u>In 2024, Detailed guide of ispoofer for pogo installation On Vivo Y100i Power 5G | Dr.fone</u></a></li> </ul></div>
簇状柱形图+折线图组合图由簇状柱形图+折线图组合组成,通过在一个图表内使用柱形图和折线图的组合,绘出多个数据序列,对于突出显示各种数据序列之间的关系非常有用。两个图形合用一个Y轴。分组只针对簇状柱形图进行分组。 簇状柱形图+折线图组合图适用于既需要组合图表示序列的分类有需要表示趋势的场景,且两者的数据大小类似 ### **样式配置说明** 簇状柱形图+折线图组合图的配置项由X轴、Y轴、分组、对比基线、图例、图表样式、颜色7部分组成 #### **X轴** X轴用于配置图形的X轴相关信息 |配置项|说明| |-|-| |字段|X轴的字段,只能选择单个字段| |坐标轴名称|坐标轴名称是否显示设置,默认显示X轴字段,可手动修改| |X轴类型|默认根据选择的X轴字段进行自动识别,可修改。对于X轴为线性、对数、时间类型的可以设置其轴的最小值和最大值| |轴标签显示|标签的显示方式,当标签过多时最好选择自适应| |标签旋转|标签的旋转方式,可以帮助您更美观地展示标签| #### **Y轴** Y轴用于配置图形的Y轴相关信息 |配置项|说明| |-|-| |柱形字段|柱形图字段,只能选择单个字段| |折线字段|折线图字段,只能选择单个字段| |坐标轴名称|坐标轴名称是否显示设置,默认显示Y轴字段,可手动修改| |Y轴类型|默认为线性,对于Y值变化范围差异很大的数据可以选择对数| |最小值|不填写则自动,表示Y轴的最小值| |最大值|不填写则自动,表示Y轴的最大值| |刻度间隔|表示Y轴刻度间隔的方式,可以设置等分的分数或者固定间隔| |数值精度|Y轴的数值单位| |数值单位|Y轴的数值精度| |空值模式|表示存在X,不存在Y的时候,绘图的模式,可以直接展示空值。或者此时Y轴用0代替后连接,还可以直接跳过空值连接存在值的数据点| #### **分组** 分组用于将数据进行分组,支持多个分组字段。会根据配置字段的取值生成不同颜色的柱形。注意:分组只针对柱形图进行分组 #### **对比基线** 对比基线可设置一条基线,通过此基线可以清晰呈现数据与基线的差距。可以设置多个对比基线,一个基线可以设置其基线名称、颜色、基线类型、基线的值 #### **图例** 图例用于配置图表图例相关信息 |配置项|说明| |-|-| |图例位置|图例展示的位置,图例包括了图表的图例和基线的图例| |图表图例|可以设置其显示和隐藏,显示时可以显示数据的当前值、平均值、最小值、最大值、总和、中位数和众数| |基线图例|可以设置其显示和隐藏| #### **图表样式** 图表样式用于配置图表相关样式信息,支持配置柱形图和折线的样式 |配置项|说明| |-|-| |值标签显示|表示是否需要在柱子上面显示具体的标签值,可以选在在柱子的中间或者顶部显示标签值| |线条|可以设置折线的线条是否平滑| |拐点|对于特别强调变化趋势的变化点,可以设置拐点,同时也显示每个点具体的值| #### **颜色** 颜色用于设置图表的的颜色,支持选择颜色模板,即选择系统定义好的不同风格的配色方案,也支持修改单个柱形/折线的颜色。对于某些需要强调颜色的分组,可以自定义颜色,如error用红色表示 ### **示例** 1、查询最近7天除搜索外操作的所有操作类型的操作次数,对比系统到底什么操作是最高频,什么使用低频。同时,呈现每个操作的错误次数趋势 ``` repo="_internal" | eval response.statusName=if(response.statusName="OK",0,1) | stats count() as count,sum(response.statusName) as error by action.name | sort by count | where action.name != "search" | rename count as "操作总次数",error as "错误次数",action.name as "操作类型" ``` - X轴选择操作类型,Y轴柱形字段选择操作总次数、折线字段选择错误次数,绘制簇状柱形图+折线图组合图 ![image.png](https://dn-odum9helk.qbox.me/FqW8fKbYTg5a3qljas3YoNw-He45) 2、查询最近7天除搜索外操作的所有操作类型的操作次数,且操作成功与失败区分显示。同时呈现不同操作类型操作次数的趋势 ``` repo="_internal" | where action.name != "search" | eval response.statusName=if(response.statusName="OK",0,1) | stats count() as count by action.name,response.statusName | eventstats sum(count) as total_count by action.name | sort by count | rename count as "操作次数",action.name as "操作类型",response.statusName as "操作结果",total_count as "操作总次数" ``` - X轴选择操作类型,Y轴柱形字段选择操作次数、折线字段选择操作总次数,分组字段选择操作结果。绘制簇状柱形图+折线图组合图 - 在图表样式中设置折线图的拐点为圆,且显示值标签,能更加清晰呈现为每个操作类型下的操作总次数 - 修改登录失败的柱形颜色为橙色,能够更加明显呈现登录失败情况 ![image.png](https://dn-odum9helk.qbox.me/FuvwbWgf9z2OMSP5iSbLnNTylk5i)
import { IsEmail, IsBoolean, IsString, IsNumber, Length,IsNotEmpty } from 'class-validator'; export class UpdateFormDto { @IsString() @IsNotEmpty() uniqueId: string; @IsString() @Length(1, 255) @IsNotEmpty() name: string; @IsEmail() @IsNotEmpty() email: string; @IsNumber() @IsNotEmpty() phonenumber: number; @IsBoolean() @IsNotEmpty() isGraduate: boolean; }
#ifndef EFEX_LATOME_FIBRE_PACKER_H #define EFEX_LATOME_FIBRE_PACKER_H #include <vector> #include <cstdint> #include "infraL1Calo/FibrePackerBase.h" #include "defsL1Calo/EfexDefs.h" class EfexLatomeFibrePacker : public FibrePackerBase{ /** * \brief Class implementing packing and unpacking data into LAr LATOME eFex format * * The class does heavy lifting of packing and unpacking LATOME data packet. The format * is taken from * https://gitlab.cern.ch/atlas-lar-be-firmware/LATOME/LATOME/raw/master/LATOME/doc/LAr-LATOME-FW/LAr-LATOME-FW.pdf * version from 29th of January 2020 */ public: EfexLatomeFibrePacker() {} virtual ~EfexLatomeFibrePacker() {} /** * \brief Function packing the data into the LATOME format, either standard or alignement frame * * The function expects input data in vector inFrame. For normal frame, this is a vector of supercell energies. * For alignement frame this function expects LATOME meta information in following format: * inFrame[0] ... latome_id * inFrame[1] ... latome_src_id * inFrame[2] ... fiber_id * * FEX_ID is always set to zero because it's eFex */ virtual std::vector<myDataWord> getPackedData(const std::vector<myDataWord>& inFrame,myDataWord bcNumber, InputDataFrameType frameType) const override; virtual std::vector<myDataWord> getPackedControl(const std::vector<myDataWord>& inFrame,myDataWord bcNumber, InputDataFrameType frameType) const override; virtual bool checkCRC(const std::vector<myDataWord>& encodedData, InputDataFrameType frameType) const override; virtual myDataWord getBcNumber(const std::vector<myDataWord>& encodedData, InputDataFrameType frameType) const override; /** * \brief Function unpacking the data from LATOME format, either standard or alignement frame * * For normal frame, the function returns a vector of supercell energies. * For alignement frame the function returns LATOME meta information in following format: * inFrame[0] ... latome_id * inFrame[1] ... latome_src_id * inFrame[2] ... fiber_id * */ virtual std::vector<myDataWord> getUnpackedData(const std::vector<myDataWord>& encodedData, InputDataFrameType frameType) const override; private: }; #endif
import React, { ChangeEvent, lazy, useState } from "react" import isEmpty from "lodash/isEmpty" import Pagination from "@mui/material/Pagination" import Sidebar from "partials/sidebar" import Header from "partials/header" import DeleteButton from "partials/actions/DeleteButton" import SearchForm from "partials/actions/search-box" import BottomNav from "components/bottom-navigation" import CollectionsTable from "partials/collections/collections-table" import useShop from "hooks/use-shop" import { useNavigate } from "react-router-dom" import { ThemeProvider } from "styles/material/theme" import ThreeDots from "components/ui/loaders/three-dots" import useCollectionViews from "hooks/use-collection-views" function Collections() { const navigate = useNavigate() const [sidebarOpen, setSidebarOpen] = useState(false) const [selectedItems, setSelectedItems] = useState<any>([]) const [currentCollectionId, setCurrentCollectionId] = useState< string | undefined >() const { shop } = useShop() const [page, setPage] = useState(1) // eslint-disable-next-line @typescript-eslint/no-unused-vars const [limit, setLimit] = useState<number>(15) const [term, setTerm] = useState<string>("") const { collectionData, isLoading } = useCollectionViews(page, limit, term) const handleSelectedItems = (selectedItems) => { setSelectedItems([...selectedItems]) } const handleShow = (display: Boolean, collectionId: string) => { setCurrentCollectionId(collectionId) } const collections = collectionData?.collections || [] return ( <div className="flex h-screen overflow-hidden"> {/* Sidebar */} <Sidebar sidebarOpen={sidebarOpen} setSidebarOpen={setSidebarOpen} /> {/* Content area */} <div className="relative flex flex-col flex-1 overflow-y-auto overflow-x-hidden"> {/* Site header */} <Header sidebarOpen={sidebarOpen} setSidebarOpen={setSidebarOpen} location="Categories" /> <main className="mb-10 md:mb-0"> <div className="px-4 sm:px-6 lg:px-8 py-2 w-full max-w-9xl mx-auto"> {/* Page header */} <div className="py-2 md:py-8 w-full max-w-9xl mx-auto"> <div className="sm:flex sm:justify-between sm:items-center"> <div className="flex justify-between gap-2 w-full"> {/* Search form */} <div className="flex justify-start gap-2"> <SearchForm placeholder="Search categories..." value={term} onChange={(e: React.FormEvent<HTMLInputElement>) => { setTerm(e.currentTarget.value) }} /> <div className=""> <DeleteButton selectedItems={selectedItems} /> </div> </div> <button onClick={() => navigate("/collections/new")} className="btn bg-purple-600 hover:bg-purple-600 text-white" > <svg className="w-4 h-4 fill-current opacity-50 flex-shrink-0" viewBox="0 0 16 16" > <path d="M15 7H9V1c0-.6-.4-1-1-1S7 .4 7 1v6H1c-.6 0-1 .4-1 1s.4 1 1 1h6v6c0 .6.4 1 1 1s1-.4 1-1V9h6c.6 0 1-.4 1-1s-.4-1-1-1z" /> </svg> <span className="hidden xs:block ml-2"> Create collection </span> </button> </div> </div> </div> {isLoading && ( <div className="sm:flex sm:items-center justify-center"> <ThreeDots /> </div> )} {!isLoading && ( <> <CollectionsTable selectedItems={handleSelectedItems} collections={collections || []} /> {/* Pagination */} {!isEmpty(collections) && (collectionData?.total ?? 0) > limit && ( <ThemeProvider> <Pagination count={ (collectionData?.total ?? 0) > limit ? Math.ceil((collectionData?.total ?? 0) / limit) : 1 } variant="outlined" color="primary" className="mt-4 md:mt-8" page={page} onChange={(event: ChangeEvent<unknown>, page: number) => setPage(page) } /> </ThemeProvider> )} </> )} </div> </main> <BottomNav /> </div> </div> ) } export default Collections
<template> <div class="pb-4"> <Banner /> <ProductList :products="hightlightProducts" class="mt-5" /> <ProductList :products="newestProducts" class="mt-5" /> <CategoryList /> <FounderList /> </div> </template> <script> import Banner from '@/components/TheBanner.vue' import FounderList from '@/components/FounderList.vue' import ProductList from '@/components/Product/ProductList.vue' import CategoryList from '@/components/CategoryList.vue' import { productApi } from '@/api/product.js' export default { components: { Banner, ProductList, FounderList, CategoryList, }, data() { return { categories: [], hightlightProducts: {}, newestProducts: {}, data: [ { name: 'Phạm Xuân Tùng', photo_url: 'https://i.imgur.com/lE89Aey.jpg', content: "If Shai Reznik's TDD videos don't convince you to add automated testing your code, I don't know what will.This was the very best explanation of frameworks for beginners that I've ever seen." }, { name: 'Phạm Minh Tuấn', photo_url: 'https://i.imgur.com/QptVdsp.jpg', content: "If Shai Reznik's TDD videos don't convince you to add automated testing your code, I don't know what will.This was the very best explanation of frameworks for beginners that I've ever seen." }, { name: 'Phạm Văn Lộc', photo_url: 'https://i.imgur.com/jQWThIn.jpg', content: "If Shai Reznik's TDD videos don't convince you to add automated testing your code, I don't know what will.This was the very best explanation of frameworks for beginners that I've ever seen." }, ] } }, created() { productApi .getHotProducts() .then(response => { this.hightlightProducts = response.data this.hightlightProducts.title = "Khóa học nổi bật" }) .catch(error => console.log(error)) productApi .getNewestProducts() .then(response => { this.newestProducts = response.data.data this.newestProducts.title = "Khóa học mới nhất" this.newestProducts.seeAll = true }) .catch(error => console.log(error)) } } </script> <style scoped> .card { background-color: #fff; border-radius: 10px; border: none; position: relative; margin-bottom: 30px; box-shadow: 0 0.46875rem 2.1875rem rgba(90,97,105,0.1), 0 0.9375rem 1.40625rem rgba(90,97,105,0.1), 0 0.25rem 0.53125rem rgba(90,97,105,0.12), 0 0.125rem 0.1875rem rgba(90,97,105,0.1); } .l-bg-cherry { background: linear-gradient(to right, #493240, #f09) !important; color: #fff; } .l-bg-blue-dark { background: linear-gradient(to right, #373b44, #4286f4) !important; color: #fff; } .l-bg-green-dark { background: linear-gradient(to right, #0a504a, #38ef7d) !important; color: #fff; } .l-bg-orange-dark { background: linear-gradient(to right, #a86008, #ffba56) !important; color: #fff; } .card .card-statistic-3 .card-icon-large .fas, .card .card-statistic-3 .card-icon-large .far, .card .card-statistic-3 .card-icon-large .fab, .card .card-statistic-3 .card-icon-large .fal { font-size: 110px; } .card .card-statistic-3 .card-icon { text-align: center; line-height: 50px; margin-left: 15px; color: #000; position: absolute; right: -5px; top: 20px; opacity: 0.1; } .l-bg-cyan { background: linear-gradient(135deg, #289cf5, #84c0ec) !important; color: #fff; } .l-bg-green { background: linear-gradient(135deg, #23bdb8 0%, #43e794 100%) !important; color: #fff; } .l-bg-orange { background: linear-gradient(to right, #f9900e, #ffba56) !important; color: #fff; } .l-bg-cyan { background: linear-gradient(135deg, #289cf5, #84c0ec) !important; color: #fff; } </style>
import { useState, useEffect } from 'react'; import PropTypes from 'prop-types'; import Form, { FormGroup, FormControl, FormPrompt, FormFeedback, } from './common/Form.component'; import Button from './common/Button.component'; import { useAppContext } from '../context/App.context'; import { getClassName, setTestid, Validator, string, isEmptyObject, } from '../utils'; function SignInForm({ visible, clickHandler }) { const { login } = useAppContext(); const [formValues, setFormValues] = useState({ email: '', password: '', }); const [errors, setErrors] = useState({}); const [isSubmitted, setIsSubmitted] = useState(false); const formClassname = getClassName('form--auth', { visible: visible, }); const overlayClassname = getClassName( 'auth-page__overlay bgcolor-info-500 color-light-500', { visible: !visible } ); useEffect(() => { if (isEmptyObject(errors) && isSubmitted) { try { login(formValues); } catch (error) { if (error.code === 404) { setErrors({ email: error.message }); } if (error.code === 400) { setErrors({ password: error.message }); } } finally { setIsSubmitted(false); } } }, [errors, isSubmitted, formValues, login]); function validate(formData) { const err = { email: new Validator(formData.email) .label('Email') .required() .email().error, password: new Validator(formData.password) .label('Password') .required() .alphanum() .min(8) .max(20).error, }; for (const key in err) { if (err[key]) { return { [key]: err[key] }; } } return {}; } function handleChange({ target }) { const { name, value } = target; setFormValues((prevState) => ({ ...prevState, [name]: value, })); } function handleSubmit(e) { e.preventDefault(); const errors = validate(formValues); setErrors(errors); setFormValues((prevState) => ({ email: string(prevState.email).trim(), password: string(prevState.password).trim(), })); setIsSubmitted(true); } return ( <> <Form {...setTestid('signin-form')} onSubmit={handleSubmit} className={formClassname} > <h2 className='h2 text-center mb-24' {...setTestid('sigin-form-title')} > Welcome </h2> <FormGroup> <FormControl {...setTestid('signin-form-email-input')} onChange={handleChange} type='email' name='email' placeholder='Email' value={formValues.email} error={errors.email} /> <FormFeedback variant='invalid' message={errors.email} /> </FormGroup> <FormGroup> <FormControl {...setTestid('signin-form-password-input')} onChange={handleChange} type='password' name='password' placeholder='Password' value={formValues.password} error={errors.password} /> <FormFeedback variant='invalid' message={errors.password} /> </FormGroup> <Button {...setTestid('sigin-form-submit')} variant='info' className='mb-16' block type='submit' > Sign in </Button> <FormPrompt description='Don`t have an account yet?' href='/' onClick={clickHandler} > Sign Up </FormPrompt> </Form> <div {...setTestid('signin-form-overlay')} className={overlayClassname} > <div className='flex flex-column flex-ai-c flex-jc-c h-100'> <h2 className='h2 mb-12'>Welcome back</h2> <p className='mb-40'>Already have an account? Sign in</p> <Button {...setTestid('signin-form-overlay-button')} onClick={clickHandler} variant='text' rounded type='button' > <b>Sign in</b> </Button> </div> </div> </> ); } SignInForm.propTypes = { visible: PropTypes.bool, clickHandler: PropTypes.func, }; export default SignInForm;
#%NASL_MIN_LEVEL 70300 # # (C) Tenable Network Security, Inc. # # The descriptive text and package checks in this plugin were # extracted from Debian Security Advisory DSA-2280. The text # itself is copyright (C) Software in the Public Interest, Inc. # include('deprecated_nasl_level.inc'); include('compat.inc'); if (description) { script_id(55625); script_version("1.12"); script_set_attribute(attribute:"plugin_modification_date", value:"2021/01/04"); script_cve_id("CVE-2011-1486", "CVE-2011-2511"); script_bugtraq_id(47148, 48478); script_xref(name:"DSA", value:"2280"); script_name(english:"Debian DSA-2280-1 : libvirt - several vulnerabilities"); script_summary(english:"Checks dpkg output for the updated package"); script_set_attribute( attribute:"synopsis", value:"The remote Debian host is missing a security-related update." ); script_set_attribute( attribute:"description", value: "It was discovered that libvirt, a library for interfacing with different virtualization systems, is prone to an integer overflow (CVE-2011-2511 ). Additionally, the stable version is prone to a denial of service, because its error reporting is not thread-safe (CVE-2011-1486 )." ); script_set_attribute( attribute:"see_also", value:"https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=633630" ); script_set_attribute( attribute:"see_also", value:"https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=623222" ); script_set_attribute( attribute:"see_also", value:"https://security-tracker.debian.org/tracker/CVE-2011-2511" ); script_set_attribute( attribute:"see_also", value:"https://security-tracker.debian.org/tracker/CVE-2011-1486" ); script_set_attribute( attribute:"see_also", value:"https://packages.debian.org/source/squeeze/libvirt" ); script_set_attribute( attribute:"see_also", value:"https://www.debian.org/security/2011/dsa-2280" ); script_set_attribute( attribute:"solution", value: "Upgrade the libvirt packages. For the stable distribution (squeeze), these problems have been fixed in version 0.8.3-5+squeeze2. For the oldstable distribution (lenny), this problem has been fixed in version 0.4.6-10+lenny2." ); script_set_cvss_base_vector("CVSS2#AV:N/AC:L/Au:S/C:N/I:N/A:P"); script_set_cvss_temporal_vector("CVSS2#E:U/RL:OF/RC:C"); script_set_attribute(attribute:"exploitability_ease", value:"No known exploits are available"); script_set_attribute(attribute:"exploit_available", value:"false"); script_set_attribute(attribute:"plugin_type", value:"local"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:debian:debian_linux:libvirt"); script_set_attribute(attribute:"cpe", value:"cpe:/o:debian:debian_linux:5.0"); script_set_attribute(attribute:"cpe", value:"cpe:/o:debian:debian_linux:6.0"); script_set_attribute(attribute:"patch_publication_date", value:"2011/07/19"); script_set_attribute(attribute:"plugin_publication_date", value:"2011/07/20"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_copyright(english:"This script is Copyright (C) 2011-2021 and is owned by Tenable, Inc. or an Affiliate thereof."); script_family(english:"Debian Local Security Checks"); script_dependencies("ssh_get_info.nasl"); script_require_keys("Host/local_checks_enabled", "Host/Debian/release", "Host/Debian/dpkg-l"); exit(0); } include("audit.inc"); include("debian_package.inc"); if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED); if (!get_kb_item("Host/Debian/release")) audit(AUDIT_OS_NOT, "Debian"); if (!get_kb_item("Host/Debian/dpkg-l")) audit(AUDIT_PACKAGE_LIST_MISSING); flag = 0; if (deb_check(release:"5.0", prefix:"libvirt", reference:"0.4.6-10+lenny2")) flag++; if (deb_check(release:"6.0", prefix:"libvirt-bin", reference:"0.8.3-5+squeeze2")) flag++; if (deb_check(release:"6.0", prefix:"libvirt-dev", reference:"0.8.3-5+squeeze2")) flag++; if (deb_check(release:"6.0", prefix:"libvirt-doc", reference:"0.8.3-5+squeeze2")) flag++; if (deb_check(release:"6.0", prefix:"libvirt0", reference:"0.8.3-5+squeeze2")) flag++; if (deb_check(release:"6.0", prefix:"libvirt0-dbg", reference:"0.8.3-5+squeeze2")) flag++; if (deb_check(release:"6.0", prefix:"python-libvirt", reference:"0.8.3-5+squeeze2")) flag++; if (flag) { if (report_verbosity > 0) security_warning(port:0, extra:deb_report_get()); else security_warning(0); exit(0); } else audit(AUDIT_HOST_NOT, "affected");
"use client" import { Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts" const data = [ { revenue: 400, users: 240, date: "Jan 1", }, { revenue: 300, users: 139, date: "Jan 2", }, { revenue: 200, users: 980, date: "Jan 3", }, { revenue: 278, users: 390, date: "Jan 4", }, { revenue: 189, users: 480, date: "Jan 5", }, { revenue: 239, users: 380, date: "Jan 6", }, { revenue: 349, users: 430, date: "Jan 7", }, ] export function Overview() { return ( <ResponsiveContainer width="100%" height={350}> <LineChart data={data}> <XAxis dataKey="date" stroke="#888888" fontSize={12} tickLine={false} axisLine={false} /> <YAxis stroke="#888888" fontSize={12} tickLine={false} axisLine={false} tickFormatter={(value) => `$${value}`} /> <Tooltip /> <Line type="monotone" dataKey="revenue" stroke="#8884d8" strokeWidth={2} dot={false} /> <Line type="monotone" dataKey="users" stroke="#82ca9d" strokeWidth={2} dot={false} /> </LineChart> </ResponsiveContainer> ) }
import React from "react"; import { ThemeProvider } from "styled-components"; import { motion } from "framer-motion"; import Logo from "../../components/Logo/logo.component"; import PowerButton from "../../components/Power-Button/power-button.component"; import SocialIcons from "../../components/Social-Icon/social-icons.component"; import { darkTheme } from "../../components/Themes/themes.component"; import Title from "../../components/Title/title.component"; import { Box, Item, MainWork } from "./work.styles"; const Work = () => { return ( <ThemeProvider theme={darkTheme}> <Box height={'100vh'}> <Logo theme="dark" /> <SocialIcons theme="dark" /> <PowerButton /> <MainWork initial="hidden" animate="show"> <Item to="/work/frontend"> <motion.h2 initial={{ y: 400, x: -400, transition: { type: "spring", duration: 1.5, delay: 1 }, }} animate={{ y: 70, x: 70, transition: { type: "spring", duration: 1.5, delay: 1 }, }} whileHover={{ scale: 1.4 }} whileTap={{ scale: 1.3 }} > FRONTEND </motion.h2> </Item> <Item to="/work/backend"> <motion.h2 initial={{ y: 400, x: 400, transition: { type: "spring", duration: 1.5, delay: 1.5 }, }} animate={{ y: 70, x: 70, transition: { type: "spring", duration: 1.5, delay: 1.5 }, }} whileHover={{ scale: 1.4 }} whileTap={{ scale: 1.3 }} > BACKEND </motion.h2> </Item> </MainWork> <Title text="WORK" top="10%" right="20%" /> </Box> </ThemeProvider> ); }; export default Work;
import { Injectable } from '@angular/core'; import { HttpClient, JsonpInterceptor } from '@angular/common/http'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class PeliculasService { private apiKey = '1aa0eda58930940bb59170176807b901'; private urlMoviedb = 'https://api.themoviedb.org/3'; peliculas: any[] = []; constructor(private http: HttpClient) { } getCartelera() { let fechaDesde = new Date(); let fechahasta = new Date(); fechahasta.setDate( fechahasta.getDate() + 7 ); let desdeStr = `${fechaDesde.getFullYear()}-${fechaDesde.getMonth() + 1}-${fechaDesde.getDay}`; let hastaStr = `${fechaDesde.getFullYear()}-${fechaDesde.getMonth() + 1}-${fechaDesde.getDay}`; let url = `${this.urlMoviedb}/movie/now_playing?api_key=${this.apiKey}&primary_release_date.get=${desdeStr}&primary_release_date.get=${hastaStr}`; return this.http.get(url).pipe( map( (response: any) => { return response.results; })); } getPopular() { let url = `${this.urlMoviedb}/movie/popular?api_key=${this.apiKey}&language=en-US&sort_by=popularity.desc&language=es&page=1`; return this.http.get(url).pipe( map( (response: any) => { return response.results; })); } getUpcoming() { let url = `${this.urlMoviedb}/movie/upcoming?api_key=${this.apiKey}&language=es-MX&page=1`; return this.http.get(url).pipe( map( (response: any) => { return response.results; })); } searchMovie(text: string) { let url = `${this.urlMoviedb}/search/movie?query=${text}&api_key=${this.apiKey}&language=es`; return this.http.get(url).pipe( map( (resp: any) => { this.peliculas = resp.results; console.log(this.peliculas); return resp.results; } )); } getpelicula(id: string) { let url = `${this.urlMoviedb}/movie/${id}?api_key=${this.apiKey}&language=es`; return this.http.get(url).pipe( map( (response: any) => { return response; })); } }
# # (C) Tenable Network Security, Inc. # include('compat.inc'); if (description) { script_id(73640); script_version("1.13"); script_set_attribute(attribute:"plugin_modification_date", value:"2023/04/25"); script_cve_id("CVE-2014-0160"); script_bugtraq_id(66690); script_xref(name:"CERT", value:"720951"); script_xref(name:"EDB-ID", value:"32745"); script_xref(name:"EDB-ID", value:"32764"); script_xref(name:"EDB-ID", value:"32791"); script_xref(name:"EDB-ID", value:"32998"); script_xref(name:"CISA-KNOWN-EXPLOITED", value:"2022/05/25"); script_name(english:"FileZilla Server < 0.9.44 OpenSSL Heartbeat Information Disclosure (Heartbleed)"); script_set_attribute(attribute:"synopsis", value: "The remote FTP server is affected by an information disclosure vulnerability."); script_set_attribute(attribute:"description", value: "According to its banner, the version of FileZilla Server running on the remote host is prior to 0.9.44. It is, therefore, affected by an information disclosure vulnerability. An information disclosure flaw exists with the OpenSSL included with FileZilla Server. A remote attacker could read the contents of up to 64KB of server memory, potentially exposing passwords, private keys, and other sensitive data. Note that Nessus has not tested for this issue but has instead relied only on the application's self-reported version number."); script_set_attribute(attribute:"see_also", value:"https://filezilla-project.org/"); script_set_attribute(attribute:"see_also", value:"http://www.heartbleed.com"); script_set_attribute(attribute:"see_also", value:"https://eprint.iacr.org/2014/140"); script_set_attribute(attribute:"see_also", value:"https://www.openssl.org/news/vulnerabilities.html#2014-0160"); script_set_attribute(attribute:"see_also", value:"https://www.openssl.org/news/secadv/20140407.txt"); script_set_attribute(attribute:"solution", value: "Upgrade to FileZilla Server version 0.9.44 or later."); script_set_cvss_base_vector("CVSS2#AV:N/AC:L/Au:N/C:P/I:N/A:N"); script_set_cvss_temporal_vector("CVSS2#E:F/RL:OF/RC:C"); script_set_cvss3_base_vector("CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N"); script_set_cvss3_temporal_vector("CVSS:3.0/E:F/RL:O/RC:C"); script_set_attribute(attribute:"cvss_score_source", value:"CVE-2014-0160"); script_set_attribute(attribute:"exploitability_ease", value:"Exploits are available"); script_set_attribute(attribute:"exploit_available", value:"true"); script_set_attribute(attribute:"exploit_framework_core", value:"true"); script_set_attribute(attribute:"in_the_news", value:"true"); script_set_attribute(attribute:"vuln_publication_date", value:"2014/02/24"); script_set_attribute(attribute:"patch_publication_date", value:"2014/04/08"); script_set_attribute(attribute:"plugin_publication_date", value:"2014/04/21"); script_set_attribute(attribute:"plugin_type", value:"remote"); script_set_attribute(attribute:"cpe", value:"cpe:/a:filezilla:filezilla_server"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_family(english:"Windows"); script_copyright(english:"This script is Copyright (C) 2014-2023 and is owned by Tenable, Inc. or an Affiliate thereof."); script_dependencies("ftpserver_detect_type_nd_version.nasl"); script_require_keys("ftp/filezilla"); script_require_ports("Services/ftp", 21); exit(0); } include("audit.inc"); include("ftp_func.inc"); include("global_settings.inc"); include("misc_func.inc"); exit(0, "Temporarily deprecated."); port = get_ftp_port(default: 21); banner = get_ftp_banner(port:port); if (!banner) audit(AUDIT_WEB_BANNER_NOT, port); if ("FileZilla Server" >!< banner) audit(AUDIT_WRONG_WEB_SERVER, port, "FileZilla Server"); banner = strstr(banner, "FileZilla Server"); banner = banner - strstr(banner, '\r\n'); version = eregmatch(pattern:"FileZilla Server version (\d\.\d\.(\d\d[a-e]|\d\d|\d[a-e]|\d))",string:banner); if(isnull(version)) audit(AUDIT_UNKNOWN_WEB_SERVER_VER, "FileZilla Server", port); if ( version[1] =~ "^0\.[0-8]($|[^0-9])" || version[1] =~ "^0\.9\.([0-9]|[1-3][0-9]|4[0-3])($|[^0-9])" ) { if(report_verbosity > 0) { report = '\n Application : FileZilla Server' + '\n Version : ' + version[1] + '\n Fixed : 0.9.44' + '\n Banner : ' + banner + '\n'; security_warning(port:port, extra:report); } else security_warning(port); } else audit(AUDIT_INST_VER_NOT_VULN, "FileZilla Server", version[1]);
<html><head><title>Ordered Lists (HTML &amp; XHTML: The Definitive Guide, 4th Edition)</title><link rel="stylesheet" type="text/css" href="../style/style1.css" /> <meta name="DC.Creator" content="Chuck Musciano and Bill Kennedy" /><meta name="DC.Format" content="text/xml" scheme="MIME" /><meta name="DC.Language" content="en-US" /><meta name="DC.Publisher" content="O'Reilly &amp; Associates, Inc." /><meta name="DC.Source" scheme="ISBN" content="059600026XL" /><meta name="DC.Subject.Keyword" content="stuff" /><meta name="DC.Title" content="HTML &amp; XHTML: The Definitive Guide, 4th Edition" /><meta name="DC.Type" content="Text.Monograph" /> </head><body bgcolor="#ffffff"> <img alt="Book Home" border="0" src="gifs/smbanner.gif" usemap="#banner-map" /><map name="banner-map"><area shape="rect" coords="1,-2,616,66" href="index.htm" alt="HTML &amp; XHTML: The Definitive Guide" /><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map> <div class="navbar"><table width="684" border="0"><tr><td align="left" valign="top" width="228"><a href="ch07_01.htm"><img alt="Previous" border="0" src="../gifs/txtpreva.gif" /></a></td><td align="center" valign="top" width="228"><a href="index.htm">HTML &amp; XHTML: The Definitive Guide, 4th Edition</a></td><td align="right" valign="top" width="228"><a href="ch07_03.htm"><img alt="Next" border="0" src="../gifs/txtnexta.gif" /></a></td></tr></table></div> <hr width="684" align="left" /> <h2 class="sect1">7.2. Ordered Lists</h2> <p><a name="INDEX-1347" /> <a name="INDEX-1348" /> <a name="INDEX-1349" />Use an ordered list when the sequence of the list items is important. A list of instructions is a good example, as are tables of contents and lists of document footnotes or endnotes. </p> <a name="html4-CHP-7-SECT-2.1" /><div class="sect2"> <h3 class="sect2">7.2.1. The &lt;ol&gt; Tag</h3> <p><a name="INDEX-1350" />The typical browser formats the contents of an ordered list just like an unordered list, except that the items are numbered instead of bulleted. The numbering starts at one and is incremented by one for each successive ordered list element tagged with <tt class="literal">&lt;li&gt;</tt>. <a href="ch07_03.htm#html4-CHP-7-SECT-3">Section 7.3, "The &lt;li&gt; Tag"</a> </p> <a name="html4-CHP-7-SIDEBAR-2" /><blockquote><table border="1" cellpadding="6"><tr><td> <h4 class="objtitle">&lt;ol&gt;</h4> <dl> <dt><b>Function:</b></dt> <dd> <p>Define an ordered list</p> </dd> <dt><b>Attributes:</b></dt><dd> <table border="0"> <tr><td><p>CLASS</p></td><td><p>ONMOUSEDOWN</p></td></tr> <tr><td><p>COMPACT</p></td><td><p>ONMOUSEMOVE</p></td></tr> <tr><td><p>DIR</p></td><td><p>ONMOUSEOUT</p></td></tr> <tr><td><p>ID</p></td><td><p>ONMOUSEOVER</p></td></tr> <tr><td><p>LANG</p></td><td><p>ONMOUSEUP</p></td></tr> <tr><td><p>ONCLICK</p></td><td><p>START</p></td></tr> <tr><td><p>ONDBLCLICK</p></td><td><p>STYLE</p></td></tr> <tr><td><p>ONKEYDOWN</p></td><td><p>TITLE</p></td></tr> <tr><td><p>ONKEYPRESS</p></td><td><p>TYPE</p></td></tr> <tr><td><p>ONKEYUP</p></td></tr> </table></dd></dl> <dl> <dt><b>End tag:</b></dt> <dd> <p>&lt;/ol&gt;; never omitted</p> </dd> </dl> <dl> <dt><b>Contains:</b></dt> <dd> <p><em class="emphasis">list_content</em></p> </dd> </dl> <dl> <dt><b>Used in:</b></dt> <dd> <p><em class="emphasis">block</em></p> </dd> </dl> </td></tr></table></blockquote> <p>HTML 3.2 introduced a number of features that provide a wide variety of ordered lists. You can change the start value of the list and select any of five different numbering styles. Here is a sample XHTML ordered list: </p> <blockquote><pre class="code">&lt;h3&gt;Pickled Kumquats&lt;/h3&gt; Here's an easy way to make a delicious batch of pickled 'quats: &lt;ol&gt; &lt;li&gt;Rinse 50 pounds of fresh kumquats&lt;/li&gt; &lt;li&gt;Bring eight gallons white vinegar to rolling boil&lt;/li&gt; &lt;li&gt;Add kumquats gradually, keeping vinegar boiling&lt;/li&gt; &lt;li&gt;Boil for one hour, or until kumquats are tender&lt;/li&gt; &lt;li&gt;Place in sealed jars and enjoy!&lt;/li&gt; &lt;/ol&gt;</pre></blockquote> <p>This is rendered by Netscape as shown in <a href="ch07_02.htm#html4-CHP-7-FIG-2">Figure 7-2</a>. </p> <a name="html4-CHP-7-FIG-2" /><div class="figure"><img height="217" alt="Figure 7-2" src="figs/xhtm.0702.gif" width="361" /></div><h4 class="objtitle">Figure 7-2. An ordered list</h4> <a name="html4-CHP-7-SECT-2.1.1" /><div class="sect3"> <h3 class="sect3">7.2.1.1. The start attribute</h3> <p><a name="INDEX-1351" />Normally, browsers automatically number ordered list items beginning with the Arabic numeral 1. The <tt class="literal">start</tt> attribute for the <tt class="literal">&lt;ol&gt;</tt> tag lets you change that beginning value. To start numbering a list at 5, for example: </p> <blockquote><pre class="code">&lt;ol start=5&gt; &lt;li&gt; This is item number 5.&lt;/li&gt; &lt;li&gt; This is number six!&lt;/li&gt; &lt;li&gt; And so forth...&lt;/li&gt; &lt;/ol&gt;</pre></blockquote> </div> <a name="html4-CHP-7-SECT-2.1.2" /><div class="sect3"> <h3 class="sect3">7.2.1.2. The type attribute</h3> <p><a name="INDEX-1352" />By default, browsers number ordered list items with a sequence of Arabic numerals. Besides being able to start the sequence at some number other than 1, you also can use the <tt class="literal">type</tt> attribute with the <tt class="literal">&lt;ol&gt;</tt> tag to change the numbering style itself. With the <tt class="literal">&lt;ol&gt;</tt> tag, the <tt class="literal">type</tt> attribute may have a value of <tt class="literal">A</tt> for numbering with capital letters, <tt class="literal">a</tt> for numbering with lowercase letters, <tt class="literal">I</tt> for capital Roman numerals, <tt class="literal">i</tt> for lowercase Roman numerals, or <tt class="literal">1</tt> for common Arabic numerals. (See <a href="ch07_02.htm#html4-CHP-7-TABLE-1">Table 7-1</a>.) </p> <a name="html4-CHP-7-TABLE-1" /><h4 class="objtitle">Table 7-1. HTML Type Values for Numbering Ordered Lists </h4><table border="1"> <tr> <th> <p>Type Value</p> </th> <th> <p>Generated Style</p> </th> <th> <p>Sample Sequence</p> </th> </tr> <tr> <td> <p><tt class="literal">A</tt></p> </td> <td> <p>Capital letters</p> </td> <td> <p>A, B, C, D</p> </td> </tr> <tr> <td> <p><tt class="literal">a</tt></p> </td> <td> <p>Lowercase letters</p> </td> <td> <p>a, b, c, d</p> </td> </tr> <tr> <td> <p><tt class="literal">I</tt></p> </td> <td> <p>Capital Roman numerals</p> </td> <td> <p>I, II, III, IV</p> </td> </tr> <tr> <td> <p><tt class="literal">i</tt></p> </td> <td> <p>Lowercase Roman numerals</p> </td> <td> <p>i, ii, iii, iv</p> </td> </tr> <tr> <td> <p><tt class="literal">1</tt></p> </td> <td> <p>Arabic numerals</p> </td> <td> <p>1, 2, 3, 4</p> </td> </tr> </table> <p>The <tt class="literal">start</tt> and <tt class="literal">type</tt> attribute extensions work in tandem. The <tt class="literal">start</tt> attribute sets the starting value of the item integer counter at the beginning of an ordered list. The <tt class="literal">type</tt> attribute sets the actual numbering style. For example, the following ordered list starts numbering items at 8, but because the style of numbering is set to i, the first number is the lowercase Roman numeral "viii." Subsequent items are numbered with the same style, and each value is incremented by 1 as shown in this HTML example:<a href="#FOOTNOTE-46">[46]</a> </p><blockquote class="footnote"> <a name="FOOTNOTE-46" /><p>[46]Notice that we don't include the <tt class="literal">&lt;/li&gt;</tt> end tag in the HTML example, but do in all the XHTML ones? Some end tags are optional with HTML, but must be included in all XHTML documents.</p> </blockquote> <blockquote><pre class="code">&lt;ol start=8 type="i"&gt; &lt;li&gt; This is the Roman number 8. &lt;li&gt; The numerals increment by 1. &lt;li&gt; And so forth... &lt;/ol&gt;</pre></blockquote> <p>The results are shown in <a href="ch07_02.htm#html4-CHP-7-FIG-3">Figure 7-3</a>. </p> <a name="html4-CHP-7-FIG-3" /><div class="figure"><img height="138" alt="Figure 7-3" src="figs/xhtm.0703.gif" width="400" /></div><h4 class="objtitle">Figure 7-3. The start and type attributes work in tandem</h4> <p>The type and value of individual items in a list can be different from the list as a whole, described in <a href="ch07_03.htm#html4-CHP-7-SECT-3.1">Section 7.3.1, "Changing the Style and Sequence of Individual List Items"</a>.<a name="INDEX-1353" /> As mentioned earlier, the <tt class="literal">start</tt> and <tt class="literal">type</tt> attributes are deprecated in HTML 4 and XHTML. Consider using style sheets instead. </p> </div> <a name="html4-CHP-7-SECT-2.1.3" /><div class="sect3"> <h3 class="sect3">7.2.1.3. Compact ordered lists</h3> <p>Like the unordered list, the ordered list has an optional <tt class="literal">compact</tt><a name="INDEX-1354" /> attribute that is deprecated in the HTML 4 and XHTML standards. Unless you absolutely need to use it, don't. </p> </div> <a name="html4-CHP-7-SECT-2.1.4" /><div class="sect3"> <h3 class="sect3">7.2.1.4. The class, dir, id, lang, event, style, and title attributes</h3> <p>These attributes are applicable as well with ordered lists and have identical effects as for unordered lists.<a name="INDEX-1355" /> <a name="INDEX-1356" /> <a name="INDEX-1357" /> <a name="INDEX-1358" /> </p> </div> </div> <hr width="684" align="left" /> <div class="navbar"><table width="684" border="0"><tr><td align="left" valign="top" width="228"><a href="ch07_01.htm"><img alt="Previous" border="0" src="../gifs/txtpreva.gif" /></a></td><td align="center" valign="top" width="228"><a href="index.htm"><img alt="Home" border="0" src="../gifs/txthome.gif" /></a></td><td align="right" valign="top" width="228"><a href="ch07_03.htm"><img alt="Next" border="0" src="../gifs/txtnexta.gif" /></a></td></tr><tr><td align="left" valign="top" width="228">7. Formatted Lists</td><td align="center" valign="top" width="228"><a href="index/index.htm"><img alt="Book Index" border="0" src="../gifs/index.gif" /></a></td><td align="right" valign="top" width="228">7.3. The &lt;li&gt; Tag</td></tr></table></div> <hr width="684" align="left" /> <img alt="Library Navigation Links" border="0" src="../gifs/navbar.gif" usemap="#library-map" /> <p><font size="-1"><a href="copyrght.htm">Copyright &copy; 2002</a> O'Reilly &amp; Associates. All rights reserved.</font></p> <map name="library-map"><area href="../index.htm" coords="0,1,78,93" shape="rect" /><area href="../wdesign/index.htm" coords="80,2,155,96" shape="rect" /><area href="../xhtml/index.htm" coords="158,0,263,97" shape="rect" /><area href="../audio/index.htm" coords="265,1,335,97" shape="rect" /><area href="../css/index.htm" coords="338,1,434,93" shape="rect" /><area href="../action/index.htm" coords="439,0,540,102" shape="rect" /><area href="../infoarch/index.htm" coords="544,0,685,102" shape="rect" /></map> </body></html>