text
stringlengths
184
4.48M
import React from 'react'; import { motion } from 'framer-motion'; import { Link, useNavigate } from 'react-router-dom'; import * as userActions from '../../redux/user/user-actions'; import { FaUserAlt } from 'react-icons/fa'; import { HiHome } from 'react-icons/hi'; import ModalCart from './ModalCart/ModalCart'; import ModalUser from './ModalUser/ModalUser'; import CartIcon from './CartIcon/CartIcon'; import { CartNavStyled, LinkContainerStyled, LinksContainerStyled, NavbarContainerStyled, UserNavStyled, UserContainerStyled, SpanStyled, UserImageStyled, } from './NavbarStyles'; import { useDispatch, useSelector } from 'react-redux'; function Navbar() { const navigate = useNavigate(); const currentUser = useSelector(state => state.user.currentUser); const dispatch = useDispatch(); return ( <NavbarContainerStyled> <ModalCart /> <ModalUser /> <div> <Link to='/'> <img src='https://res.cloudinary.com/dcatzxqqf/image/upload/v1658797659/coding/NucbaZappi/Assets/nucba-zappi-icon_oe3ark_xmvab5.png' alt='Logo' /> </Link> </div> <LinksContainerStyled> <motion.div whileTap={{ scale: 0.97 }}> <Link to='/'> <LinkContainerStyled home> <HiHome /> </LinkContainerStyled> Home </Link> </motion.div> <CartNavStyled> <CartIcon /> </CartNavStyled> <UserNavStyled> <UserContainerStyled onClick={ () => currentUser ? dispatch(userActions.toggleMenuHidden()) : navigate('/register') } > <SpanStyled> { currentUser ? `${currentUser.displayName}` : `Inicia sesión`} </SpanStyled> { currentUser?.photoURL ? ( <UserImageStyled src={ currentUser.photoURL } alt={currentUser.displayName} /> ) : (<FaUserAlt />)} </UserContainerStyled> </UserNavStyled> </LinksContainerStyled> </NavbarContainerStyled> ); } export default Navbar;
package com.example.day09; public class Smartphone { // 내부 인터페이스 public interface Camera { void takePhoto(); } // 내부 인터페이스를 구현하는 내부 클래스 public class BasicCamera implements Camera { @Override public void takePhoto() { System.out.println("Take a picture"); } } public void activateCamera() { Camera camera = new BasicCamera(); camera.takePhoto(); } public static void main(String[] args) { Smartphone phone = new Smartphone(); phone.activateCamera(); } }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>TinDog</title> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"> <script src="https://kit.fontawesome.com/654f6042fa.js" crossorigin="anonymous"></script> <link href="https://fonts.googleapis.com/css2?family=DynaPuff&family=Kanit&family=Merriweather&family=Montserrat:wght@800&family=Sacramento&family=Ubuntu:ital@1&display=swap" rel="stylesheet"> <link rel="stylesheet" href="css/styles.css"> <body> <section id="title"> <div class="container-fluid"> <!-- Nav Bar --> <nav class="navbar navbar-expand-lg navbar-dark"> <a class="navbar-brand wahid" href="">tindog</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarScroll" aria-controls="navbarScroll" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarScroll"> <ul class="navbar-nav ms-auto"> <li class="nav-item navlink"> <a class="nav-link" href="#footer">Contact</a> </li> <li class="nav-item navlink"> <a class="nav-link" href="#pricing">Pricing</a> </li> <li class="nav-item navlink"> <a class="nav-link" href="#cta">Download</a> </li> </ul> </div> </nav> <!-- Title --> <div class="row"> <div class="col-lg-6"> <h1>Meet new and interesting dogs nearby.</h1> <button type="button" class="btn btn-dark btn-lg download-button"><i class="fa-brands fa-apple"></i> Download</button> <button type="button" class="btn btn-outline-light btn-lg download-button"><i class="fa-brands fa-google-play"></i> Download</button> </div> <div class="col-lg-6"> <img class="title-image" src="images/iphone6.png" alt="iphone-mockup"> </div> </div> </div> </section> <!-- Features --> <section id="features"> <div class="row"> <div class="col-lg-4 section"> <i class="fa-solid fa-circle-check fa-4x icons"></i> <h3>Easy to use.</h3> <p>So easy to use, even your dog could do it.</p> </div> <div class="col-lg-4 section"> <i class="fa-solid fa-bullseye fa-4x icons"></i> <h3>Elite Clientele</h3> <p>We have all the dogs, the greatest dogs.</p> </div> <div class="col-lg-4 section"> <i class="fa-solid fa-heart fa-4x icons"></i> <h3>Guaranteed to work.</h3> <p>Find the love of your dog's life or your money back.</p> </div> </div> </section> <!-- Testimonials --> <section id="testimonials"> <div id="carouselExampleControls" class="carousel slide" data-bs-ride="false"> <div class="carousel-inner"> <div class="carousel-item active"> <h2>I no longer have to sniff other dogs for love. I've found the hottest Corgi on TinDog. Woof.</h2> <img class="test-img" src="images/dog-img.jpg" alt="dog-profile"> <em>Pebbles, New York</em> </div> <div class="carousel-item"> <h2 class="testimonial-text">My dog used to be so lonely, but with TinDog's help, they've found the love of their life. I think.</h2> <img class="test-img" class="testimonial-image" src="images/lady-img.jpg" alt="lady-profile"> <em>Beverly, Illinois</em> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> </section> <!-- Press --> <section id="press"> <img class="press-logo" src="images/Danone.png" alt="danone-logo"> <img class="press-logo" src="images/tnw.png" alt="tnw-logo"> <img class="press-logo" src="images/bizinsider.png" alt="biz-insider-logo"> <img class="press-logo" src="images/mashable.png" alt="mashable-logo"> </section> <!-- Pricing --> <section id="pricing"> <div class="txt"> <h2>A Plan for Every Dog's Needs</h2> <p>Simple and affordable price plans for your and your dog.</p> </div> <div class="row"> <div class="pricing-col col-lg-4 col-md-6"> <div class="card"> <div class="card-header"> <h3>Chihuahua</h3> </div> <div class="card-body"> <h2>Free</h2> <p>5 Matches Per Day</p> <p>10 Messages Per Day</p> <p>Unlimited App Usage</p> <button class="btn btn-lg btn-block btn-outline-dark">Sign Up</a> </div> </div> </div> <div class="pricing-col col-lg-4 col-md-6"> <div class="card"> <div class="card-header"> <h3>Labrador</h3> </div> <div class="card-body"> <h2>₹199 / mo</h2> <p>Unlimited Matches</p> <p>Unlimited Messages</p> <p>Unlimited App Usage</p> <button class="btn btn-lg btn-block btn-dark">Sign Up</a> </div> </div> </div> <div class="pricing-col col-lg-4"> <div class="card"> <div class="card-header"> <h3>Mastiff</h3> </div> <div class="card-body"> <h2>₹399 / mo</h2> <p>Pirority Listing</p> <p>Unlimited Matches</p> <p>Unlimited Messages</p> <p>Unlimited App Usage</p> <button class="btn btn-lg btn-block btn-dark">Sign Up</a> </div> </div> </div> </section> <!-- Call to Action --> <section id="cta"> <h2 class="cta-heading">Find the True Love of Your Dog's Life Today.</h2> <button type="button" class="btn btn-dark btn-lg download-button"><i class="fa-brands fa-apple"></i> Download</button> <button type="button" class="btn btn-light btn-lg download-button"><i class="fa-brands fa-google-play"></i> Download</button> </section> <!-- Footer --> <footer id="footer"> <a class="footer-link" href="https://twitter.com/"><i class="fa-brands fa-twitter social"></i></a> <a class="footer-link" href="https://www.facebook.com"><i class="fa-brands fa-facebook-f social"></i></a> <a class="footer-link" href="https://www.instagram.com/"><i class="fa-brands fa-instagram social"></i></a> <a class="footer-link" href="mailto:[email protected]"><i class="fa-solid fa-envelope social"></i></a> <p class="copy">© Copyright &nbsp; 2022 &nbsp; TinDog</p> </footer> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> </body> </html>
// Copyright (C) 2008 Jesse Jones // // 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. using MObjc.Helpers; using System; using System.Runtime.Serialization; namespace MObjc { /// <summary>Thrown if a call to unmanaged code cannot be performed.</summary> /// <remarks>Usually the reason for this is that the unmanaged code is called with /// an argument that cannot be marshaled to unmanaged code or the unmanaged method /// could not be found (e.g. it may be misspelled).</remarks> /// <seealso cref = "CocoaException"/> [Serializable] [ThreadModel(ThreadModel.Concurrent)] public sealed class InvalidCallException : Exception { // Need this for XML serialization. internal InvalidCallException() { } internal InvalidCallException(string text) : base(text) { } internal InvalidCallException(string text, Exception inner) : base(text, inner) { } private InvalidCallException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
import express, { Request, Response } from 'express'; const app = express(); const port = process.env.PORT || 80; import { createServer } from 'http'; import { Server } from 'socket.io'; import Docker from 'dockerode'; var docker = new Docker(); const server = createServer(app); const io = new Server(server, { transports: ['polling'], }); app.use(express.json()); io.on('connection', (socket) => { console.log('a user connected'); // player disconnected socket.on('ping', (data) => { socket.send('ping', data); }); }); setInterval(function () { // io.emit(Defaults.SERVER_GAME_ENEMY_SHOOT, { // id, x, y, angle, damage // }); docker.listContainers({ all: true, // @ts-ignore }, (err: string, containers: Docker.ContainerInfo[]) => { if (err) { console.log(err) return }; let data: { id: any; names: any; image: any; imageID: any; command: any; created: any; ports: any; state: any; status: any; mounts: any; }[] = []; containers.forEach((containerInfo) => { data.push({ id: containerInfo.Id, names: containerInfo.Names, image: containerInfo.Image, imageID: containerInfo.ImageID, command: containerInfo.Command, created: containerInfo.Created, ports: containerInfo.Ports, state: containerInfo.State, status: containerInfo.Status, mounts: containerInfo.Mounts, }); }); io.emit('containerList', data); }); }, 100); app.get('/', async (req: Request, res: Response) => { res.sendFile(__dirname + '/index.html'); }); server.listen(port, () => { console.log(`Server is running on port ${port}`); });
<?php namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; /** * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Proveedor> */ class ProveedorFactory extends Factory { /** * Define the model's default state. * * @return array<string, mixed> */ public function definition(): array { return [ 'nombre'=>$this->faker->text(50), 'contacto' => $this->faker->randomFloat(2, 10, 500), 'telefono' => '9' . $this->faker->numberBetween(10000000, 99999999), 'correo'=>$this->faker->text(50), 'direccion'=>$this->faker->text(50) ]; } }
import 'package:abc_banking/Models/accountClass.dart'; import 'package:abc_banking/Models/customerClass.dart'; import 'package:abc_banking/Provider/auth_provider.dart'; import 'package:abc_banking/Screens/Mobile/AccountSettings.dart'; import 'package:abc_banking/Screens/Mobile/Action.dart'; import 'package:abc_banking/Screens/Mobile/statements_mobile.dart'; import 'package:abc_banking/Services/accountService.dart'; import 'package:abc_banking/Services/transactionService.dart'; import 'package:abc_banking/Styling/appColors.dart'; import 'package:abc_banking/Styling/textStyling.dart'; import 'package:abc_banking/WidgetsCustom/circle_button.dart'; import 'package:abc_banking/utils/keys.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; import 'transactionPage_mobile.dart'; class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key); @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { final GlobalKey<ScaffoldState> _homeScaffoldKey = GlobalKey(); List actionWidgets = [ { "text": "Deposit", "onTap": () { Navigator.of(Keys.navigatorKey.currentContext!).push(CupertinoPageRoute( builder: (context) => const ActionScreen( title: "Deposit", description: "Select an amount to deposit into yor account"))); }, "icon": Icons.add }, { "text": "Withdraw", "onTap": () { Navigator.of(Keys.navigatorKey.currentContext!).push(CupertinoPageRoute( builder: (context) => const ActionScreen( title: "Withdraw", description: "Select an amount to withdraw"))); }, "icon": CupertinoIcons.arrow_down }, { "text": "Send", "onTap": () { Navigator.of(Keys.navigatorKey.currentContext!).push(CupertinoPageRoute( builder: (context) => const ActionScreen( title: "Send", description: "Select an amount to send"))); }, "icon": CupertinoIcons.paperplane }, {"text": "Summary", "onTap": () { Navigator.of(Keys.navigatorKey.currentContext!).push(CupertinoPageRoute( builder: (context) => const StatementsMobile())); }, "icon": CupertinoIcons.ellipsis}, ]; @override Widget build(BuildContext context) { String greeting() { var hour = DateTime.now().hour; if (hour < 12) { return 'Good morning'; } if (hour < 17) { return 'Good afternoon'; } return 'Good evening'; } Customer currentCustomer = Provider.of<AtProvider>(context, listen: false).currCustomer; return Scaffold( key: _homeScaffoldKey, backgroundColor: AppColors.primaryDarken, appBar: AppBar( toolbarHeight: 110, backgroundColor: Colors.white.withOpacity(0.0), automaticallyImplyLeading: false, title: Padding( padding: const EdgeInsets.only(left: 12.0, right: 8), child: Text( "${greeting()}, ${currentCustomer.name.toString().split(' ').first}", style: Styling.mediumTextLight, ), ), centerTitle: false, actions: [ Padding( padding: const EdgeInsets.only(right: 5.0), child: GestureDetector( onTap: () { Navigator.of(context).push(CupertinoPageRoute(builder: (context)=> const AccountSettings())); }, child: Padding( padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 10), child: Icon( Icons.account_circle_sharp, color: AppColors.primaryColor, size: 30, ), ), ), ), Padding( padding: const EdgeInsets.only(right: 12.0), child: GestureDetector( onTap: () { AtProvider().logout(); }, child: Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: Icon( Icons.logout, color: AppColors.primaryColor, size: 30, ), ), ), ), ], ), body: SafeArea( bottom: false, child: SingleChildScrollView( child: StreamBuilder( stream: AccountService().fetchAccount(context), builder: (context, AsyncSnapshot snapshot) { if (snapshot.hasData) { var data = Account.fromJson(snapshot.data.data()); return Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, children: [ const SizedBox( height: 30, ), Text( "Account Balance", style: TextStyle( color: AppColors.primaryColor, fontSize: 16, fontWeight: FontWeight.bold), ), const SizedBox( height: 10, ), Text( "£ ${data.total.toStringAsFixed(2)}", style: TextStyle( color: AppColors.primaryColor, fontSize: 30, fontWeight: FontWeight.bold), ), const SizedBox( height: 20, ), Padding( padding: const EdgeInsets.all(16.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: actionWidgets .map<Widget>((data) => CircleButton( text: data['text'], buttonIcon: data['icon'], onTap: data['onTap'], )) .toList(), ), ), const SizedBox( height: 20, ), ConstrainedBox( constraints: const BoxConstraints( minWidth: double.infinity, minHeight: 500), child: Card( margin: const EdgeInsets.symmetric(horizontal: 0.0), elevation: 1, color: AppColors.brightWhite, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(50), topRight: Radius.circular(50), ), ), child: Column( children: [ Padding( padding: const EdgeInsets.only(top: 30.0), child: Text( "Recent Transactions", style: Styling.largeTextDark, ), ), Padding( padding: const EdgeInsets.symmetric( horizontal: 70.0), child: Divider( color: AppColors.primaryDarken, ), ), StreamBuilder( stream: TransactionService() .fetchTransactions(context), builder: (context, AsyncSnapshot transactionsSnapshot) { if (transactionsSnapshot.connectionState == ConnectionState.waiting) { return Center( child: CircularProgressIndicator( color: AppColors.primaryDarken, ), ); } else if (transactionsSnapshot.hasError) { return Center( child: Column( children: [ const Text('Something went wrong ' 'while retrieving yor ' 'transactions, please check your ' 'internet and refresh below'), GestureDetector( onTap: () { setState(() {}); }, child: const SizedBox( width: 40, height: 40, child: Icon(Icons.refresh), ), ) ], )); } else { return transactionsSnapshot .data.length<1 ? Column( children: [ Container( width: 250.0, height: 250.0, decoration: BoxDecoration( color: AppColors .primaryColor .withOpacity(.3), shape: BoxShape.circle, ), child: Image.asset( 'assets/images/emptyTransactions.png', width: 120, height: 120, alignment: Alignment.center, ), ), const SizedBox( height: 10, ), ConstrainedBox( constraints: const BoxConstraints( maxWidth: 300), child: Text( "You haven't conducted any transactions yet", textAlign: TextAlign.center, style: Styling .normalTextMessage, ), ) ], ) : ListView.builder( physics: const NeverScrollableScrollPhysics(), shrinkWrap: true, itemCount: transactionsSnapshot .data.length, itemBuilder: (context, i) { var data = ABCTransaction.fromJson( transactionsSnapshot .data[i].data()); return Padding( padding: const EdgeInsets .symmetric( horizontal: 16.0, vertical: 6), child: ListTile( onTap: (){ Navigator.of(context).push(MaterialPageRoute(builder: (context)=> TransactionPageMobile(transaction: data))); }, titleAlignment: ListTileTitleAlignment .top, title: Text( data.description, style: Styling .normalTextDark, ), subtitle: Text( DateFormat('(dd-MMM-yyy) ' 'hh:mm') .format(DateTime .parse(data .timestamp)), style: Styling.smallLabel, ), contentPadding: const EdgeInsets .symmetric( horizontal: 8), trailing: Text( "${data.transactionType == "deposit" ? "" : "-"} £ ${data.amount}", style: data.transactionType != "deposit" ? Styling .largeWarningLabel : Styling .largeSuccessLabel, ), ), ); }); } }) ], ), ), ), ], ); } else if (snapshot.connectionState == ConnectionState.waiting) { return Center( child: CircularProgressIndicator( color: AppColors.primaryDarken, ), ); } else { return Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, children: [ const SizedBox( height: 30, ), Text( "Account Balance", style: TextStyle( color: AppColors.primaryColor, fontSize: 16, fontWeight: FontWeight.bold), ), const SizedBox( height: 10, ), Text( "£ 00.00", style: TextStyle( color: AppColors.primaryColor, fontSize: 30, fontWeight: FontWeight.bold), ), const SizedBox( height: 20, ), Padding( padding: const EdgeInsets.all(16.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: actionWidgets .map<Widget>((data) => CircleButton( text: data['text'], buttonIcon: data['icon'], onTap: data['onTap'], )) .toList(), ), ), const SizedBox( height: 20, ), ConstrainedBox( constraints: const BoxConstraints( minWidth: double.infinity, minHeight: 500), child: Card( margin: const EdgeInsets.symmetric(horizontal: 0.0), elevation: 1, color: AppColors.brightWhite, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(50), topRight: Radius.circular(50), ), ), child: Column( children: [ Padding( padding: const EdgeInsets.only(top: 30.0), child: Text( "Recent Transactions", style: Styling.largeTextDark, ), ), Padding( padding: const EdgeInsets.symmetric( horizontal: 70.0), child: Divider( color: AppColors.primaryDarken, ), ), Column( children: [ Container( width: 250.0, height: 250.0, decoration: BoxDecoration( color: AppColors.primaryColor .withOpacity(.3), shape: BoxShape.circle, ), child: Image.asset( 'assets/images/emptyTransactions.png', width: 120, height: 120, alignment: Alignment.center, ), ), const SizedBox( height: 10, ), ConstrainedBox( constraints: const BoxConstraints(maxWidth: 300), child: Text( "You haven't conducted any transactions yet", textAlign: TextAlign.center, style: Styling.normalTextMessage, ), ) ], ) ], ), ), ), ], ); } }), ), ), ); } }
#include <stdlib.h> /* exit, atoi, malloc, free */ #include <stdio.h> #include <unistd.h> /* read, write, close */ #include <string.h> /* memcpy, memset */ #include <sys/socket.h> /* socket, connect */ #include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */ #include <netdb.h> /* struct hostent, gethostbyname */ #include <arpa/inet.h> #include "helpers.hpp" #include "requests.h" char *compute_get_request(char *host, char *url, char *query_params, char **cookies, int cookies_count, char *auth) { char *message = (char*)calloc(BUFLEN, sizeof(char)); char *line = (char*)calloc(LINELEN, sizeof(char)); // Step 1: write the method name, URL, request params (if any) and protocol type if (query_params != NULL) { sprintf(line, "GET %s?%s HTTP/1.1", url, query_params); } else { sprintf(line, "GET %s HTTP/1.1", url); } compute_message(message, line); // Step 2: add the host memset(line, 0, LINELEN); sprintf(line, "Host: %s", host); compute_message(message, line); // Step 3 (optional): add headers and/or cookies, according to the protocol format if (cookies != NULL) { memset(line, 0, LINELEN); strcat(line, "Cookie: "); for (int i = 0; i < cookies_count - 1; i++) { strcat(line, cookies[i]); strcat(line, ";"); } strcat(line, cookies[cookies_count - 1]); compute_message(message, line); } // Step 3.1 (optional): add authorization header if (auth != NULL) { memset(line, 0, LINELEN); strcat(line, "Authorization: Bearer "); strcat(line, auth); compute_message(message,line); } // Step 4: add final new line compute_message(message, ""); return message; } char *compute_post_request(char *host, char *url, char* content_type, char *body_data, char **cookies, int cookies_count, char *auth) { char *message = (char*)calloc(BUFLEN, sizeof(char)); char *line = (char*)calloc(LINELEN, sizeof(char)); char *body_data_buffer = (char*)calloc(LINELEN, sizeof(char)); // Step 1: write the method name, URL and protocol type sprintf(line, "POST %s HTTP/1.1", url); compute_message(message, line); // Step 2: add the host memset(line, 0, LINELEN); sprintf(line, "Host: %s", host); compute_message(message, line); strcat(body_data_buffer, body_data); sprintf(line, "Content-Type: %s\r\nContent-Length: %d", content_type, (int)strlen(body_data)); compute_message(message, line); // Step 4 (optional): add cookies if (cookies != NULL) { memset(line, 0, LINELEN); strcat(line, "Cookie: "); for (int i = 0; i < cookies_count - 1; i++) { strcat(line, cookies[i]); strcat(line, ";"); } strcat(line, cookies[cookies_count - 1]); compute_message(message,line); } // Step 4.1 (optional): add authorization header if (auth != NULL) { memset(line, 0, LINELEN); strcat(line, "Authorization: Bearer "); strcat(line, auth); compute_message(message,line); } // Step 5: add new line at end of header compute_message(message, ""); // Step 6: add data memset(line, 0, LINELEN); strcat(message, body_data_buffer); free(line); return message; } char *compute_delete_request(char *host, char *url, char *query_params, char **cookies, int cookies_count, char *auth) { char *message = (char*)calloc(BUFLEN, sizeof(char)); char *line = (char*)calloc(LINELEN, sizeof(char)); // Step 1: write the method name, URL, request params (if any) and protocol type if (query_params != NULL) { sprintf(line, "DELETE %s?%s HTTP/1.1", url, query_params); } else { sprintf(line, "DELETE %s HTTP/1.1", url); } compute_message(message, line); // Step 2: add the host memset(line, 0, LINELEN); sprintf(line, "Host: %s", host); compute_message(message, line); // Step 3 (optional): add headers and/or cookies, according to the protocol format if (cookies != NULL) { memset(line, 0, LINELEN); strcat(line, "Cookie: "); for (int i = 0; i < cookies_count - 1; i++) { strcat(line, cookies[i]); strcat(line, ";"); } strcat(line, cookies[cookies_count - 1]); compute_message(message, line); } // Step 3.1 (optional): add authorization header if (auth != NULL) { memset(line, 0, LINELEN); strcat(line, "Authorization: Bearer "); strcat(line, auth); compute_message(message,line); } // Step 4: add final new line compute_message(message, ""); return message; }
# 10 7 # 1 3 5 7 9 11 13 15 17 19 def binary_search(array, target, start, end): while start <= end: mid = (start + end) // 2 # divide if array[mid] == target: # 중간 값과 타겟 값이 같을 경우 return mid elif array[mid] > target: # 타겟 값이 중간 값 보다 작을 경우 end = mid - 1 else: # 타겟 값이 중간 값 보다 클 경우 start = mid + 1 return None # 아무 것도 찾지 못했을 경우 n, target = map(int, input().split()) array = list(map(int, input().split())) result = binary_search(array, target, 0, n-1) if result is None: print("원소가 존재하지 않습니다.") else: print("찾고자 하는 값의 인덱스 :", result)
package com.jws.transcomp.api.service.impl; import com.jws.transcomp.api.models.Employee; import com.jws.transcomp.api.repository.EmployeeRepository; import com.jws.transcomp.api.repository.RoleRepository; import com.jws.transcomp.api.service.base.UserService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import javax.persistence.EntityNotFoundException; import java.util.List; @Service public class UserServiceImpl implements UserService { private final EmployeeRepository employeeRepository; private final RoleRepository roleRepository; private final BCryptPasswordEncoder bCryptPasswordEncoder; public UserServiceImpl(EmployeeRepository employeeRepository, RoleRepository roleRepository, BCryptPasswordEncoder bCryptPasswordEncoder) { this.employeeRepository = employeeRepository; this.roleRepository = roleRepository; this.bCryptPasswordEncoder = bCryptPasswordEncoder; } @Override public Employee save(Employee employee) { employee.setPassword(bCryptPasswordEncoder.encode(employee.getPassword())); return employeeRepository.save(employee); } @Override public boolean delete(Long id) { if (this.employeeRepository.existsById(id)) { this.employeeRepository.deleteById(id); return this.employeeRepository.findById(id).isEmpty(); } else { throw new EntityNotFoundException("User with provided id doesn't exist!"); } } @Override public Employee findByUsername(String username) { return employeeRepository.findByUsername(username) .orElseThrow(() -> new EntityNotFoundException("User with username " + username + " doesn't exist.")); } @Override public Employee findById(Long id) { return this.employeeRepository.findById(id) .orElseThrow(() -> new EntityNotFoundException("User id is not valid.")); } @Override public Employee getByIndex(int indx) { return this.employeeRepository.findAll().get(indx); } @Override public List<Employee> findByRole(String roleName) { return employeeRepository.findByRole(roleRepository.findByName(roleName) .orElseThrow(() -> new IllegalArgumentException("No role exists with name: " + roleName))); } @Override public List<Employee> getAll() { return this.employeeRepository.findAll(); } @Override public boolean any() { return employeeRepository.count() > 0; } @Override public long count() { return employeeRepository.count(); } }
import { EnvelopePSGModule } from "./envelope"; import { LengthPSGModule } from "./length"; import { PSG } from "./psg"; const SERIALIZE_FIELDS: (keyof NoisePSG)[] = [ 'enabled', 'phaseClock', 'clockShift', 'clockDivider', 'lfsr', 'lfsr7Bit', ]; export class NoisePSG implements PSG { output: number = 0; enabled: boolean = false; phaseClock: number = 0; clockShift: number = 0; clockDivider: number = 0; lfsr: number = 0; lfsr7Bit: boolean = false; envelope: EnvelopePSGModule; length: LengthPSGModule; constructor() { this.envelope = new EnvelopePSGModule(); this.length = new LengthPSGModule(this); this.reset(); } reset(): void { this.output = 0; this.enabled = false; this.phaseClock = 0; this.clockShift = 0; this.clockDivider = 0; this.lfsr = 0; this.lfsr7Bit = false; this.envelope.reset(); this.length.reset(); } serialize(): any { const output: any = {}; SERIALIZE_FIELDS.forEach((key) => output[key] = this[key]); output.envelope = this.envelope.serialize(); output.length = this.length.serialize(); return output; } deserialize(data: any): void { SERIALIZE_FIELDS.forEach((key) => (this[key] as any) = data[key]); this.envelope.deserialize(data.envelope); this.length.deserialize(data.length); } trigger(): void { this.output = 0; this.enabled = true; this.phaseClock = 0; this.lfsr = 0; this.envelope.trigger(); this.length.trigger(); } getDebugState(): string { let r = this.clockDivider; if (r === 0) r = 0.5; const phaseWidth = 16 * r * (1 << this.clockShift); const hz = Math.floor((4 * 1024 * 1024) / phaseWidth); return [ `E: ${this.enabled ? '1' : '0'} S: ${this.clockShift} D: ${this.clockDivider} (${hz}Hz)`, this.envelope.getDebugState(), this.length.getDebugState(), ].join(' '); } step(clocks: number): void { let remainingClocks = clocks; while (remainingClocks > 0) { if (!this.enabled) break; // Calculate clocks for each trigger // The clock is 262144 / (r * (2^s)) Hz, where r is 0.5 when r = 0 // Meaning that this is triggered every 16 * r * 2^s clocks. let r = this.clockDivider; if (r === 0) r = 0.5; const phaseWidth = 16 * r * (1 << this.clockShift); const phaseRemaining = phaseWidth - this.phaseClock; // Calculate the smallest trigger let consumedClocks = Math.min(phaseRemaining, remainingClocks); consumedClocks = this.envelope.getNextClocks(consumedClocks); consumedClocks = this.length.getNextClocks(consumedClocks); this.phaseClock += consumedClocks; if (this.phaseClock >= phaseWidth) { this.phaseClock = 0; // Update LFSR const setBit = this.lfsr7Bit ? 0x8080 : 0x8000; let lfsr = this.lfsr lfsr = lfsr | (((lfsr & 1) !== ((lfsr >> 1) & 1)) ? 0 : setBit); lfsr = lfsr >>> 1; this.lfsr = lfsr; } this.envelope.step(consumedClocks); this.length.step(consumedClocks); remainingClocks -= consumedClocks; } // Calculate current output if (this.enabled) { const signal = this.lfsr & 1; this.output = (signal ? -1 : 1) * this.envelope.get(); } else { this.output = 0; } } _read(pos: number): number { switch (pos) { case 3: // NR13 - Frequency & randomness let output = 0x100; output |= (this.clockShift & 0xf) << 4; if (this.lfsr7Bit) output |= 0x8; output |= this.clockDivider & 0x7; return output; default: return 0; } } read(pos: number): number { let output = this._read(pos); output |= this.envelope.read(pos); output |= this.length.read(pos); if (output & 0x100) return output; return 0xff; } _write(pos: number, value: number): void { switch (pos) { case 3: // NR13 - Frequency & randomness this.clockShift = (value >> 4) & 0xf; this.lfsr7Bit = (value & 0x8) !== 0; this.clockDivider = value & 0x7; break; case 4: // NR44 - Control if (value & 0x80) this.trigger(); break; } } write(pos: number, value: number): void { this._write(pos, value); this.envelope.write(pos, value); this.length.write(pos, value); } }
// Updating the main window’s tree view // Copyright © 2009 The University of Chicago #include "linguisticamainwindow.h" #include "MiniLexicon.h" #include "Lexicon.h" #include "TreeViewItem.h" #include "LPreferences.h" #include "StateEmitHMM.h" #include "CorpusWord.h" #include "DLHistory.h" #include "Suffix.h" #include "Prefix.h" #include "CorpusWordCollection.h" #include "SignatureCollection.h" #include "TemplateCollection.h" #include "CompoundCollection.h" #include "LinkerCollection.h" #include "SuffixCollection.h" #include "PrefixCollection.h" #include "BiphoneCollection.h" #include "PhoneCollection.h" #include "StemCollection.h" #include "WordCollection.h" #include "POSCollection.h" #include "AffixLocation.h" /** \page page1 How to make a variable be displayed in the Tree View (left window) Most of the functions here are sensitive to what information has been computed in CLexicon and the MiniLexicons. A few are triggered under any conditions, but most are triggered only if certain items have already been computed. \section sec The main screen */ void LinguisticaMainWindow::updateTreeViewSlot() { // Adapted from MFC version: CMyTree::UpdateUpperTree, CMyTree::UpdateStatistics int count, // used for various counts index; // mini-lexicon index index = 0; count = 0; // bool add = TRUE; CStem* pWord; Q3ListViewItem * MiscItem = NULL, * MiscItem1 = NULL, * LexiconItem = NULL, * WordsReadItem = NULL, * PrefixesItem = NULL, * SuffixesItem = NULL, * WordsItem = NULL, * CompoundsItem = NULL, * ComponentItem = NULL, * STRINGEDITITEM = NULL, * CorpusWordsItem = NULL; // Clear the tree m_treeView->clear(); m_treeView->setFont( GetFontPreference( "Main" ) ); m_treeView->hideColumn(1); //************************************************************************************** // A NOTE ON THE ORGANIZATION OF THIS FUNCTION: // The items are inserted into the tree in reverse order respective to their group. They // are organized by depth here, i.e. what is connected to the root is the first group, // then do the groups of items connected to this first group, etc. The only items that // get their own name are those that have children. The rest use MiscItem //************************************************************************************** // START CONNECTED DIRECTLY TO m_treeView count = GetNumberOfTokens(); if( count >= 0 ) { MiscItem = new CTreeViewItem( m_treeView, "Tokens requested: " + IntToStringWithCommas( count ), TOKENS_REQUESTED ); MiscItem->setSelectable(false); } if( m_lexicon->GetWords() && m_lexicon->GetMiniCount() ) { count = m_lexicon->GetTokenCount(); if ( count >= 0 ) { WordsReadItem = new CTreeViewItem( m_treeView, "Tokens read: " + IntToStringWithCommas( count ) ); WordsReadItem->setSelectable(false); WordsReadItem->setOpen(true); } LexiconItem = new CTreeViewItem( m_treeView, "Lexicon : click items to display them" ); LexiconItem->setSelectable(false); LexiconItem->setOpen(true); } if ( m_projectDirectory.length() ) { MiscItem = new CTreeViewItem( m_treeView, "Project directory: " + m_projectDirectory ); MiscItem->setSelectable(false); } else { MiscItem = new CTreeViewItem( m_treeView, "No project directory." ); MiscItem->setSelectable(false); } if ( m_logging ) { MiscItem = new CTreeViewItem( m_treeView, "Log file (now on) " + GetLogFileName() ); MiscItem->setSelectable(false); } else { MiscItem = new CTreeViewItem( m_treeView, "Log file (now off) " + GetLogFileName() ); MiscItem->setSelectable(false); } // END CONNECTED DIRECTLY TO m_treeView // START CONNECTED TO LexiconItem if ( LexiconItem && m_lexicon->GetHMM() ) { MiscItem = new CTreeViewItem( LexiconItem, "HMM", HMM_Document); double dl = m_lexicon->GetHMM()->GetLogProbability(); MiscItem1 = new CTreeViewItem(MiscItem,"HMM description length: " + IntToStringWithCommas(int( dl) ) ); MiscItem1 = new CTreeViewItem(MiscItem, "Iterations: " + IntToStringWithCommas( m_lexicon->GetHMM()->m_NumberOfIterations ) ); MiscItem1 = new CTreeViewItem(MiscItem, "Number of states: " + IntToStringWithCommas( m_lexicon->GetHMM()->m_countOfStates ) ); } MiscItem->setOpen(true); if( LexiconItem ) { if( m_lexicon->GetDLHistory()->count() > 0 ) { MiscItem = new CTreeViewItem( LexiconItem, "Description length history", DESCRIPTION_LENGTH_HISTORY ); } } //// StringEdit Display if ((LexiconItem != NULL) && (m_Words_InitialTemplates != NULL)) { if ( m_Words_InitialTemplates ->GetCount() > 0) { STRINGEDITITEM = new CTreeViewItem( LexiconItem, "StringEditDistanceTemplates: " + IntToStringWithCommas( 2 ), STRINGEDITDISTANCE, -1); count = m_Words_Templates ->GetCount(); if ( count != 0) { MiscItem = new CTreeViewItem( STRINGEDITITEM, "StringEdit_Templates: " + IntToStringWithCommas( count ), WORKINGSTRINGEDITTEMPLATES, -1); } count = m_Words_InitialTemplates ->GetCount(); MiscItem = new CTreeViewItem( STRINGEDITITEM, "StringEdit_InitialTemplates: " + IntToStringWithCommas( count ), INITIALSTRINGEDITTEMPLATES, -1); } } count = 0; Q3DictIterator<PrefixSet> it5( *m_lexicon->GetAllPrefixes() ); for( ; it5.current(); ++it5 ) { count += it5.current()->count(); } if( count > 0 ) { PrefixesItem = new CTreeViewItem( LexiconItem, "All Prefixes " + IntToStringWithCommas( count ), ALL_PREFIXES ); PrefixesItem->setOpen( TRUE ); } count = 0; Q3DictIterator<SuffixSet> it4( *m_lexicon->GetAllSuffixes() ); for( ; it4.current(); ++it4 ) { count += it4.current()->count(); } if( count > 0 ) { SuffixesItem = new CTreeViewItem( LexiconItem, "All Suffixes " + IntToStringWithCommas( count ), ALL_SUFFIXES ); SuffixesItem->setOpen( TRUE ); } count = 0; Q3DictIterator<StemSet> it1( *m_lexicon->GetAllStems() ); for( ; it1.current(); ++it1 ) { count += it1.current()->count(); } if( count > 0 ) { MiscItem = new CTreeViewItem( LexiconItem, "All Stems " + IntToStringWithCommas( count ), ALL_STEMS ); } count = 0; Q3DictIterator<StemSet> it2( *m_lexicon->GetAllWords() ); for( ; it2.current(); ++it2 ) { count += it2.current()->count(); } if( count > 0 ) { WordsItem = new CTreeViewItem( LexiconItem, "All Words " + IntToStringWithCommas( count ), ALL_WORDS ); WordsItem->setOpen( TRUE ); } if( m_lexicon->GetMiniCount() ) { for( index = m_lexicon->GetMiniSize() - 1; index >= 0; index-- ) { if( m_lexicon->GetMiniLexicon( index ) ) MiscItem = GetMiniLexiconSubTree( LexiconItem, index ); } } count = m_lexicon->GetCompounds()->GetCount(); if( count > 0 ) { CompoundsItem = new CTreeViewItem( LexiconItem, "Compounds " + IntToStringWithCommas( count ), COMPOUNDS ); CompoundsItem->setOpen( TRUE ); int count2 = m_lexicon->GetCompounds()->GetComponents()->GetSize(); ComponentItem = new CTreeViewItem( CompoundsItem, "Components "+ IntToStringWithCommas (count2), COMPOUND_COMPONENTS); } count = m_lexicon->GetWords()->GetCount(); if( count > 0 ) { CorpusWordsItem = new CTreeViewItem( LexiconItem, "Corpus Words " + IntToStringWithCommas( count ), CORPUS_WORDS ); CorpusWordsItem->setOpen( TRUE ); } // END CONNECTED TO LexiconItem // START CONNECTED TO CorpusWordsItem count = 0; if( CorpusWordsItem ) { CCorpusWord* pCorpusWord; CCorpusWordCollection* pWords = m_lexicon->GetWords(); pWords->Sort( KEY ); for( int i = 0; i < pWords->GetCount(); i++ ) { pCorpusWord = pWords->GetAtSort(i); if( pCorpusWord->Size() > 1 ) { count++; } } if( count > 0 ) { MiscItem = new CTreeViewItem( CorpusWordsItem, "Analyzed " + IntToStringWithCommas( count ), ANALYZED_CORPUS_WORDS ); } } // END CONNECTED TO CorpusWordsItem // START CONNECTED TO WordsItem count = 0; bool analyzed_exists; Q3DictIterator<StemSet> it3( *m_lexicon->GetAllWords() ); for( ; it3.current(); ++it3 ) { analyzed_exists = FALSE; //for( pWord = it3.current()->first(); pWord; pWord = it3.current()->next() ) for (int z = 0; z < it3.current()->size(); z++) { pWord = it3.current()->at(z); if( pWord->Size() > 1 ) { analyzed_exists = TRUE; count++; } } } if( count > 0 ) { MiscItem = new CTreeViewItem( WordsItem, "Analyzed " + IntToStringWithCommas( count ), ALL_ANALYZED_WORDS ); } // END CONNECTED TO WordsItem // START CONNECTED TO SuffixesItem count = 0; Q3DictIterator<SignatureSet> it7( *m_lexicon->GetAllSuffixSigs() ); for( ; it7.current(); ++it7 ) { count += it7.current()->count(); } if( count > 0 ) { MiscItem = new CTreeViewItem( SuffixesItem, "Signatures " + IntToStringWithCommas( count ), ALL_SUFFIX_SIGNATURES ); } // END CONNECTED TO SuffixesItem // START CONNECTED TO PrefixesItem count = 0; Q3DictIterator<SignatureSet> it6( *m_lexicon->GetAllPrefixSigs() ); for( ; it6.current(); ++it6 ) { count += it6.current()->count(); } if( count > 0 ) { MiscItem = new CTreeViewItem( PrefixesItem, "Signatures " + IntToStringWithCommas( count ), ALL_PREFIX_SIGNATURES ); } // END CONNECTED TO PrefixesItem // START CONNECTED TO WordsReadItem if( WordsReadItem ) { if( m_lexicon->GetWords() ) { count = m_lexicon->GetWords()->GetCount(); if( count > 0 ) { MiscItem = new CTreeViewItem( WordsReadItem, "Distinct types read: " + IntToStringWithCommas( count ) ); MiscItem->setSelectable(false); } } count = m_lexicon->GetCorpusCount(); if( count >= 0 ) { MiscItem = new CTreeViewItem( WordsReadItem, "Tokens included: " + IntToStringWithCommas( count ) ); MiscItem->setSelectable(false); } } // END CONNECTED TO WordsReadItem // START CONNECTED TO CompoundsItem count = m_lexicon->GetLinkers()->GetCount(); if( count > 0 ) { MiscItem = new CTreeViewItem( CompoundsItem, "Linkers " + IntToStringWithCommas( count ), LINKERS, index ); } } Q3ListViewItem* LinguisticaMainWindow::GetMiniLexiconSubTree( Q3ListViewItem* parent, int index) { CMiniLexicon* lexicon = m_lexicon->GetMiniLexicon(index); if (lexicon == 0) // nothing to draw return 0; enum eAffixLocation affixLocation = lexicon->GetAffixLocation(); // Items are inserted into the tree in reverse order // respective to their group. They are organized by depth here, // i.e. what is connected to the root is the first group, // then do the groups of items connected to this first group, etc. // The only items that get their own name are those that have children. Q3ListViewItem* LexiconItem = // owned by parent new CTreeViewItem(parent, QString( m_lexicon->GetActiveMiniIndex() == index ? "Mini-Lexicon %1\t**ACTIVE**" : "Mini-Lexicon %1") .arg(index+1), MINI_LEXICON, index); LexiconItem->setSelectable(false); LexiconItem->setOpen(true); // START CONNECTED TO LexiconItem if (lexicon->GetFSA() != 0) static_cast<void>(new CTreeViewItem( LexiconItem, "FSA", FSA_DOC, index)); // XXX. HMMLexemes, HMM Corpus Tokens? if (LexiconItem != 0) if (m_lexicon->GetDLHistory()->count() > 0) static_cast<void>(new CTreeViewItem( LexiconItem, "Description length", DESCRIPTION_LENGTH)); // Suffixes or prefixes Q3ListViewItem* AffixesItem = 0; if (is_initial(affixLocation)) { // XXX. update to match suffix case const int count = lexicon->GetPrefixes()->GetCount(); if (count > 0) { AffixesItem = new CTreeViewItem(LexiconItem, QString("Prefixes %1").arg( IntToStringWithCommas(count)), PREFIXES, index); AffixesItem->setOpen( true ); } } else { const int count = lexicon->GetSuffixes()->GetCount(); const int usecount = lexicon->GetSuffixes()->GetTotalUseCount(); lexicon->GetSuffixes()->RecomputeCorpusCount(); const int corpuscount = lexicon->GetSuffixes()->GetCorpusCount(); if (count > 0) { AffixesItem = new CTreeViewItem(LexiconItem, QString("Suffixes %1 : %2 : %3").arg( IntToStringWithCommas(count), IntToStringWithCommas(usecount), IntToStringWithCommas(corpuscount)), SUFFIXES, index); AffixesItem->setOpen(true); } } { int dummy; const int count = lexicon->GetWords()->HowManyAreAnalyzed(dummy, this); if (count > 0) { static_cast<void>(new CTreeViewItem(LexiconItem, QString("Analyzed words %1").arg( IntToStringWithCommas(count)), ANALYZED_WORDS, index)); } } Q3ListViewItem* WordsItem = 0; { const int count = lexicon->GetWords()->GetCount(); if (count > 0) { QString caption = QString("Words %1 Z: %2") .arg(IntToStringWithCommas(count)) .arg(lexicon->GetWords()->GetZ_Local()); WordsItem = new CTreeViewItem(LexiconItem, caption, WORDS, index); WordsItem->setOpen(true); } } // END CONNECTED TO LexiconItem // START CONNECTED TO WordsItem { const int count = lexicon->GetWords()->GetTrie()->GetCount(); if (count > 0) { if (lexicon->GetWords()->GetReverseTrie() != 0) { static_cast<void>(new CTreeViewItem( WordsItem, QString("Reverse trie %1") .arg(IntToStringWithCommas(count)), REVERSE_TRIE, index)); } static_cast<void>(new CTreeViewItem( WordsItem, QString("Forward trie %1") .arg(IntToStringWithCommas(count)), TRIE, index)); } } // XXX. lexicon->GetVowels()? { const int tier1_bigrams = lexicon->GetWords() ->GetPhonologicalContentTier1Bigrams(); // XXX. probably a typo. if (tier1_bigrams != 0) { static_cast<void>(new CTreeViewItem( WordsItem, QString("Unigram description length %1") .arg(IntToStringWithCommas( lexicon->GetWords() ->GetPhonologicalContentUnigrams())), UNIGRAM_INFORMATION, index)); } if (tier1_bigrams != 0) { static_cast<void>(new CTreeViewItem( WordsItem, QString("Bigram description length %1") .arg(IntToStringWithCommas(tier1_bigrams)), BIGRAM_INFORMATION, index)); } } if (const int distant_log_pr = lexicon->GetWords()->GetDistantMI_Plog()) static_cast<void>(new CTreeViewItem( WordsItem, QString("Distant MI model plog: %1") .arg(IntToStringWithCommas(distant_log_pr)), BIGRAM_INFORMATION, index)); if (const int local_log_pr = lexicon->GetWords()->GetLocalMI_Plog()) static_cast<void>(new CTreeViewItem( WordsItem, QString("Local MI model plog: %1") .arg(IntToStringWithCommas(local_log_pr)), BIGRAM_INFORMATION, index)); if (const double distant_denom = lexicon->GetWords()->GetZ_Distant()) static_cast<void>(new CTreeViewItem( WordsItem, QString("Z (distant model): %1") .arg(distant_denom), BIGRAM_INFORMATION, index)); if (const double local_denom = lexicon->GetWords()->GetZ_Local()) static_cast<void>(new CTreeViewItem( WordsItem, QString("Z (local) : %1") .arg(local_denom), BIGRAM_INFORMATION, index)); // Phones inside words // Tier 2 if (CPhoneCollection* phones = lexicon->GetWords()->GetPhones_Tier2()) { const int count = phones->GetCount(); const int totalcount = phones->GetCorpusCount(); if (count > 0) { Q3ListViewItem* Tier2Item = // owned by WordsItem new CTreeViewItem(WordsItem, "Tier 2 ", PHONES_Tier2, index); Tier2Item->setOpen(true); static_cast<void>(new CTreeViewItem(Tier2Item, QString("Phones %1 : %2") .arg(IntToStringWithCommas(count), IntToStringWithCommas(totalcount)), PHONES_Tier2, index)); // Tier 2 biphones CBiphoneCollection* biphones = phones->GetMyBiphones(); const int biphone_count = biphones->count(); const int total_biphone_count = biphones->m_TotalCount; if (biphone_count > 0) { static_cast<void>(new CTreeViewItem( Tier2Item, QString("Biphones %1 : %2") .arg(IntToStringWithCommas(biphone_count), IntToStringWithCommas(total_biphone_count)), BIPHONES_Tier2, index)); if (const int local_score = lexicon->GetWords() ->GetTier2_LocalMI_Score()) static_cast<void>(new CTreeViewItem( Tier2Item, QString("Tier 2 Local MI score %1") .arg(IntToStringWithCommas( local_score)), TIER2MI, index)); if (const int distant_score = lexicon->GetWords() ->GetTier2_DistantMI_Score()) static_cast<void>(new CTreeViewItem( Tier2Item, QString("Tier 2 Distant MI score %1") .arg(IntToStringWithCommas( distant_score)), TIER2MI, index)); } } } // Tier 1 Skeleton { CPhoneCollection* phones = lexicon->GetWords()->GetPhones_Tier1_Skeleton(); const int count = phones->GetCount(); const int totalcount = phones->GetCorpusCount(); if (count > 0) { Q3ListViewItem* Tier1Item = // owned by WordsItem new CTreeViewItem(WordsItem, "Tier 1 Skeleton ", PHONES_Tier1_Skeleton, index); Tier1Item->setOpen(true); static_cast<void>(new CTreeViewItem( Tier1Item, QString("Phones (skeleton) %1 : %2") .arg(IntToStringWithCommas(count), IntToStringWithCommas(totalcount)), PHONES_Tier1_Skeleton, index)); CBiphoneCollection* biphones = phones->GetMyBiphones(); const int biphone_count = biphones->count(); const int biphone_totalcount = biphones->m_TotalCount; if (biphone_count > 0) { static_cast<void>(new CTreeViewItem( Tier1Item, QString("Biphones (skeleton) %1 : %2") .arg(IntToStringWithCommas(biphone_count), IntToStringWithCommas(biphone_totalcount)), BIPHONES_Tier1_Skeleton, index)); } } } { // Tier 1 CPhoneCollection* phones = lexicon->GetWords()->GetPhones(); const int count = phones->GetCount(); const int totalcount = phones->GetCorpusCount(); if (count > 0) { Q3ListViewItem* Tier1Item = // owned by WordsItem new CTreeViewItem(WordsItem, "Tier 1 ", PHONES, index); Tier1Item->setOpen(true); static_cast<void>(new CTreeViewItem( Tier1Item, QString("Phones %1 : %2") .arg(IntToStringWithCommas(count), IntToStringWithCommas(totalcount)), PHONES, index)); CBiphoneCollection* biphones = phones->GetMyBiphones(); const int biphone_count = biphones->count(); const int biphone_totalcount = biphones->m_TotalCount; if (biphone_count > 0) { static_cast<void>(new CTreeViewItem( Tier1Item, QString("Biphones %1 : %2") .arg(IntToStringWithCommas(biphone_count), IntToStringWithCommas(biphone_totalcount)), BIPHONES, index)); } } } // END CONNECTED TO WordsItem // START CONNECTED TO AffixesItem { const int count = lexicon->GetStems()->GetCount(); if (count > 0) { static_cast<void>(new CTreeViewItem( AffixesItem, QString("Stems %1") .arg(IntToStringWithCommas(count)), STEMS, index)); } } { const int count = lexicon->GetSignatures()->GetCount(); if (count > 0) { static_cast<void>(new CTreeViewItem( AffixesItem, QString("Signatures %1") .arg(IntToStringWithCommas(count)), SIGNATURES, index)); } } if (LxPoSCollection* parts_of_speech = lexicon->GetPOS()) { const int count = parts_of_speech->count(); static_cast<void>(new CTreeViewItem(AffixesItem, QString("Parts of speech %1") .arg(IntToStringWithCommas(count)), POS, index)); } return LexiconItem; }
import React, { useState, useEffect } from "react"; import { useHistory, useParams, useLocation } from "react-router-dom"; import axios from "axios"; import Form from "react-bootstrap/Form"; import InputGroup from "react-bootstrap/InputGroup"; import Button from "react-bootstrap/Button"; import moment from "moment"; function AbsPreComponentUpdate({ setValidationErrors }) { const history = useHistory(); const { id } = useParams(); // Recupera el valor de id pasado como parte de la ruta const [item, setItem] = useState({ data_absprevista: "", motiu_abs: "", user: "", }); // Variables para rescatar los valores del all const location = useLocation(); const { itemValues } = location.state || {}; useEffect(() => { axios .get("http://localhost:5000/api/absprevistes/update/" + id) .then((response) => { setItem(response.data); }) .catch((error) => { console.log(error); }); }, [id]); // Recuperamos los valores del registro que hemos cogido useEffect(() => { if (itemValues) { setItem(itemValues); } }, [itemValues]); const handleInputChange = (event) => { const { name, value } = event.target; setItem({ ...item, [name]: value, }); }; const handleSubmit = (event) => { event.preventDefault(); axios .put("http://localhost:5000/api/absprevistes/update/"+ id, item) .then((response) => { console.log(response.data); setItem({ data_absprevista: "", motiu_abs: "", user: "", }); setValidationErrors([]); //setAbsNoPreData([...setAbsNoPreData, response.data]); history.push("/absprevistes"); }) .catch((error) => { console.log(error); if ( error.response && error.response.data && error.response.data.errors ) { const validationErrors = error.response.data.errors; setValidationErrors(validationErrors); } }); }; return ( <> <Form onSubmit={handleSubmit}> <InputGroup className="mb-2"> <InputGroup.Text>Data absència</InputGroup.Text> <Form.Control type="date" name="data_absprevista" value={moment(item.data_absprevista).format("YYYY-MM-DD")} onChange={handleInputChange} /> </InputGroup> <InputGroup className="mb-2"> <InputGroup.Text>Motiu absència</InputGroup.Text> <Form.Control as="textarea" name="motiu_abs" value={item.motiu_abs} onChange={handleInputChange} /> </InputGroup> <InputGroup className="mb-2"> <InputGroup.Text>Professor</InputGroup.Text> <Form.Control type="text" name="user" value={item.user} onChange={handleInputChange} /> </InputGroup> <Button type="submit">Actualitzar</Button> </Form> </> ); } export default AbsPreComponentUpdate;
import React, { useEffect, useState } from "react"; import axios from "axios"; import { FiArrowRight, FiLayers } from "react-icons/fi"; import { FaRegEdit } from "react-icons/fa"; import { AiOutlineDelete } from "react-icons/ai"; import Table from "../../../components/Table"; import { useLocation, useNavigate } from "react-router-dom"; import ApiErrorPopUp from "../../../components/ApiErrorPopUp"; import { ToastContainer, toast } from "react-toastify"; const CandidateStore = () => { const [archiveData, setArchiveData] = useState(""); const [contentEdit, setContentEdit] = useState(""); const [apiError,setApiError] = useState('') const [showApiErrorPopUp,setShowApiErrorPopUp] = useState('') const [showEditButton,setShowEditButton] = useState(false) const [showDeleteButton,setShowDeleteButton] = useState(false) const [search,setSearch] = useState("") const [editCertification, setEditCertification] = useState(""); const [showEditCertificationModal, setShowEditCertificationModal] = useState(false); const [selectedRadio, setSelectedRadio] = useState("inhouse"); const baseUrl = process.env.REACT_APP_API_URL; // console.log("baseurl", baseUrl); const data = localStorage.getItem("data"); const jsonData = JSON.parse(data); const accessToken = jsonData?.access_token; // console.log("bearerToken", accessToken); const authorize = "Bearer" + " " + accessToken; // console.log("authorize", authorize); const navigate = useNavigate() const location = useLocation() const getData = async () => { // Determine the endpoint based on the selected radio button const endpoint = selectedRadio === "inhouse" ? "applications-archive/inhouse" : "applications-archive/onsite"; try { // Construct the full URL using the dynamic endpoint const url = `${process.env.REACT_APP_API_URL}${endpoint}`; // Make the API request const request = await axios.get(url, { headers: { 'Authorization': `${authorize}` } }); // Handle the response const response = request.data; if (response) { setArchiveData(response?.data); } } catch (error) { // Handle any errors here console.error("Error fetching data:", error); // Set error states or show error messages as needed } } const handleRadioChange = (event) => { console.log("Radio changed to:", event.target.value); // Debug log setSelectedRadio(event.target.value); } useEffect(() => { getData(); document.title = "CIPLCRM | Candidate Store" }, [showEditCertificationModal,selectedRadio]); useEffect(()=>{ if(jsonData?.data?.userPermissions.find(a=>a === "edit_category")) { setShowEditButton(true)} else{ setShowEditButton(false) } (jsonData?.data?.userPermissions.find(a=>a === "delete_category"))?setShowDeleteButton(true):setShowDeleteButton(false) },[showEditButton,showDeleteButton]) useEffect(()=>{ if(jsonData?.data?.userPermissions.find(a=>a === "view_category")){ return }else{ navigate('/admin') } },[location]) const tableHeading=[ { name: 'S. No.', selector: (row, index) => index + 1, sortable: false, }, { name: 'PID', selector: row => row?.job?.pid, sortable: true, }, { name: 'Name', selector: row => row?.full_name, sortable: true, }, { name: 'Email', selector: row => row?.email, sortable: true, }, { name: 'Phone', selector: row => row?.phone, sortable: true, }, { name: 'Qualification', selector: row => row?.qualification?.name, sortable: true, }, { name: 'Action', selector: row => ( <div className=""> <button onClick={async()=> { try { const request = await fetch(`${process.env.REACT_APP_API_URL}job-applications/unarchive-job-application/${row?.id}`, { method: "post", headers: { Authorization: `${authorize}`, "Content-type": "application/json; charset=UTF-8", }, } ) const response = await request?.json() console.log('response',response) if(response?.code ===200){ toast.success(`${response?.message}`) getData() } } catch (error) { console.log('error', error) if (error?.response?.data?.error) { const errors = Object.values(error?.response?.data?.error) console.log('Errors', errors) errors.map((x) => ( toast.error(`${x}`) )) } if (error?.response?.data?.message) { if (error?.response?.data?.error) { const errors = Object.values(error?.response?.data?.error) console.log('Errors', errors) errors.map((x) => ( toast.error(`${x}`) )) } if (error?.response?.data?.message) { toast.error(`${error?.response?.data?.message}`) } } } } }> <FiLayers size={30} className='bg-gray-800 text-white m-1 w-6 p-1 h-6 hover:cursor-pointer' color='white' title="Unarchive" /> </button> </div> ), sortable: false, allowOverflow: true }, ] console.log("archive data", archiveData) const filteredData = archiveData && archiveData?.filter((data)=>data?.full_name?.toLowerCase().includes(search)) return ( <div> <ToastContainer position="top-center" /> { showApiErrorPopUp? <ApiErrorPopUp setModal={setShowApiErrorPopUp} error={apiError}/>:null } <div className=" mx-11 my-4 "> <label > <input type="radio" value="inhouse" name="btn" checked={selectedRadio === "inhouse"} onChange={handleRadioChange} /> <span className=' px-1 font-medium text-lg '>Inhouse</span> </label> <label className="mx-2"> <input type="radio" value="onsite" name="btn" checked={selectedRadio === "onsite"} onChange={handleRadioChange} /> <span className='px-1 font-medium text-lg '>Project</span> </label> </div> <div className="mt-4 px-4 border border-gray-800 border-t-4 bg-white mx-4"> <div className="flex flex-col"> <div className="overflow-x-auto"> <div className="py-3 flex justify-end pr-2"> <div className="relative max-w-xs flex items-center justify-end"> <label htmlFor="hs-table-search" className="px-2"> Search: </label> <input type="text" className="block w-full p-3 border text-sm border-gray-300 rounded-md " placeholder="Search..." onChange={(e)=>setSearch(e.target.value.toLowerCase())} /> </div> </div> <div className="lg:p-1.5 mb-4 pt-2 w-full inline-block align-middle"> <div className="overflow-hidden border rounded-lg"> <Table columns={tableHeading} data={filteredData} /> </div> </div> </div> </div> </div> </div> ); } export default CandidateStore
import { Book } from '../../../store' import "./BookList.css" import ConfirmationModal from '../confrimationModal/ConfirmationModal' import { useEffect, useState } from 'react' import { DragDropContext, Draggable, DropResult, Droppable } from 'react-beautiful-dnd' import { useStore } from '../../../store' import { MdOutlineDeleteSweep } from "react-icons/md"; import { SlBookOpen } from "react-icons/sl"; import { SiBookstack } from "react-icons/si"; import { FaBookSkull } from "react-icons/fa6"; import { toast } from "react-toastify" const BookList = ({ showDialog, setShowDialog }: any) => { const { books, moveBook, removeBook, reOrderBooks } = useStore(state => state) const moveToList = (book: Book, targetList: Book["status"]) => { moveBook(book, targetList) } const [openConfirmation, setOpenConfirmation] = useState<boolean>(false) const [book, setBook] = useState<Book | any>() useEffect(() => { console.log(books); }, []) const confirmRemove = (book: Book) => { setBook(book) setOpenConfirmation(true) } const onDragEnd = (result: DropResult) => { console.log(result); const { source, destination } = result if (!destination) return const sourceIndex = source.index const destinationIndex = destination.index const listType = source.droppableId as Book["status"] reOrderBooks(listType, sourceIndex, destinationIndex) } const toastAlert = (toastMsg: any) => { toast.success(toastMsg, { position: "bottom-right", autoClose: 2500, pauseOnHover: true, draggable: true, theme: "dark" } ) } return ( <div className='bookListContainer'> <div className="head"> <h2>My Reading List</h2> <button className='add-new-book-btn' onClick={() => setShowDialog(!showDialog)} > Add New Book </button> </div> <div className='box-progress'> <p className='box-sort-heading'>Currently Reading <SlBookOpen style={{ width: '30px', height: '25px' }} /></p> <DragDropContext onDragEnd={onDragEnd}> { books?.filter((book) => book.status == 'inProgress').length > 0 ? ( <div> <Droppable droppableId='inProgress' > {(provided) => ( <div {...provided.droppableProps} ref={provided.innerRef} > {books.filter((book) => book.status == 'inProgress').map((book, index) => { return ( <Draggable draggableId={book.key} key={book.key} index={index} > {(provided) => ( <div {...provided.dragHandleProps} {...provided.draggableProps} ref={provided.innerRef} > <div className='book-item' key={book.key}> <div className="reading-container"> <div className="left"> <h3>{book.title}</h3> <p>{book.author_name}</p> </div> <div className="right"> <p>{book.first_public_year || "-"}</p> </div> </div> <div className="btn-box"> <div className="remove-btn-box"> <button onClick={() => confirmRemove(book)} className='remove-btn' > <MdOutlineDeleteSweep className='icon-del' /> </button> </div> <div className="move-btn-box"> <button onClick={() => { moveToList(book, "inProgress") } } disabled={book.status == "inProgress"} > <SlBookOpen style={{ width: '22px', height: '30px', color: 'grey' }} /> </button> <button onClick={() => { toastAlert(`moved to READ LATER list`) moveToList(book, "backlog") }} > <SiBookstack style={{ width: '25px', height: '35px', color: '#fff' }} /> </button> <button onClick={() => { toastAlert(`moved to DONE READING list`) moveToList(book, "done") }} > <FaBookSkull style={{ width: '22px', height: '30px', color: '#fff' }} /> </button> </div> </div> </div> </div> )} </Draggable> ) })} </div> )} </Droppable> </div> ) : <h2>You are not reading any books currently! search and add your favorite books!</h2> } </DragDropContext> <ConfirmationModal openConfirmation={openConfirmation} setOpenConfirmation={setOpenConfirmation} onRemoveBook={removeBook} book={book} /> </div > <div className='box-backlog'> <p className='box-sort-heading'>To Read Later < SiBookstack style={{ width: '30px', height: '25px' }} /></p> <DragDropContext onDragEnd={onDragEnd}> { books?.filter((book) => book.status == 'backlog').length > 0 ? ( <div> <Droppable droppableId='backlog' > {(provided) => ( <div {...provided.droppableProps} ref={provided.innerRef} > { books?.filter((book) => book.status == 'backlog').map((book, index) => { return ( <Draggable draggableId={book.key} key={book.key} index={index} > {(provided) => ( <div {...provided.dragHandleProps} {...provided.draggableProps} ref={provided.innerRef} > <div className='book-item' key={book.key}> <div className="reading-container"> <div className="left"> <h3>{book.title}</h3> <p>{book.author_name}</p> </div> <div className="right"> <p>{book.first_public_year || "-"}</p> </div> </div> <div className="btn-box"> <div className="remove-btn-box"> <button onClick={() => confirmRemove(book)} > <MdOutlineDeleteSweep className='icon-del' /> </button> </div> <div className="move-btn-box"> <button onClick={() => { toastAlert(`moved to CURRENTLY READING list`) moveToList(book, "inProgress") }} > <SlBookOpen style={{ width: '22px', height: '30px', color: '#fff' }} /> </button> <button onClick={() => moveToList(book, "backlog")} disabled={book.status == "backlog"} > <SiBookstack style={{ width: '25px', height: '35px', color: 'grey' }} /> </button> <button onClick={() => { toastAlert(`moved to DONE READING list`) moveToList(book, "done") }} > <FaBookSkull style={{ width: '22px', height: '30px', color: '#fff' }} /> </button> </div> </div> </div> </div> )} </Draggable> ) }) } </div> ) } </Droppable> </div> ) : <h2>there are no books on this list Currently!</h2> } </DragDropContext> </div > <div className='box-done'> <p className='box-sort-heading'>Done Reading <FaBookSkull style={{ width: '30px', height: '22px' }} /></p> { books.filter((book) => book.status == 'done').length > 0 ? ( <div> {books.filter((book) => book.status == 'done').map((book) => { return ( <div className='book-item' key={book.key}> <div className="reading-container"> <div className="left"> <h3>{book.title}</h3> <p>{book.author_name}</p> </div> <div className="right"> <p>{book.first_public_year || "-"}</p> </div> </div> <div className="btn-box"> <div className="remove-btn-box"> <button onClick={() => confirmRemove(book)} className='remove-btn' > <MdOutlineDeleteSweep className='icon-del' /> </button> </div> <div className="move-btn-box"> <button onClick={() => { toastAlert(`moved to CURRENTLY READING list`) moveToList(book, "inProgress") }} > <SlBookOpen style={{ width: '22px', height: '30px', color: '#fff' }} /> </button> <button onClick={() => { toastAlert(`moved to READ LATER list`) moveToList(book, "backlog") } } > <SiBookstack style={{ width: '25px', height: '35px', color: '#fff' }} /> </button> <button onClick={() => moveToList(book, "done")} disabled={book.status == "done"} > <FaBookSkull style={{ width: '22px', height: '30px', color: 'grey' }} /> </button> </div> </div> </div> ) })} </div> ) : <h2>No books on this list!</h2> } </div > </div > ) } export default BookList
<?php /** * APIEventHandler.php * Copyright (c) 2019 [email protected] * * This file is part of Firefly III (https://github.com/firefly-iii). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ declare(strict_types=1); namespace FireflyIII\Handlers\Events; use Exception; use FireflyIII\Mail\AccessTokenCreatedMail; use FireflyIII\Repositories\User\UserRepositoryInterface; use Laravel\Passport\Events\AccessTokenCreated; use Log; use Mail; use Request; use Session; /** * Class APIEventHandler */ class APIEventHandler { /** * Respond to the creation of an access token. * * @param AccessTokenCreated $event * * @return bool */ public function accessTokenCreated(AccessTokenCreated $event): bool { /** @var UserRepositoryInterface $repository */ $repository = app(UserRepositoryInterface::class); $user = $repository->findNull((int)$event->userId); if (null !== $user) { $email = $user->email; $ipAddress = Request::ip(); Log::debug(sprintf('Now in APIEventHandler::accessTokenCreated. Email is %s, IP is %s', $email, $ipAddress)); try { Log::debug('Trying to send message...'); Mail::to($email)->send(new AccessTokenCreatedMail($email, $ipAddress)); // @codeCoverageIgnoreStart } catch (Exception $e) { Log::debug('Send message failed! :('); Log::error($e->getMessage()); Log::error($e->getTraceAsString()); Session::flash('error', 'Possible email error: ' . $e->getMessage()); } // @codeCoverageIgnoreEnd Log::debug('If no error above this line, message was sent.'); } return true; } }
/* * The MIT License (MIT) Copyright (c) 2020-2023 artipie.com * https://github.com/artipie/artipie/blob/master/LICENSE.txt */ package com.artipie.http; import com.artipie.asto.Content; import com.artipie.asto.Storage; import com.artipie.http.auth.Authentication; import com.artipie.http.auth.BasicAuthzSlice; import com.artipie.http.auth.OperationControl; import com.artipie.http.headers.ContentType; import com.artipie.http.headers.Header; import com.artipie.http.rq.RequestLine; import com.artipie.http.rt.MethodRule; import com.artipie.http.rt.RtRule; import com.artipie.http.rt.RtRulePath; import com.artipie.http.rt.SliceRoute; import com.artipie.http.slice.LoggingSlice; import com.artipie.http.slice.SliceDownload; import com.artipie.http.slice.SliceSimple; import com.artipie.http.slice.SliceWithHeaders; import com.artipie.security.perms.Action; import com.artipie.security.perms.AdapterBasicPermission; import com.artipie.security.policy.Policy; import java.util.concurrent.CompletableFuture; import java.util.regex.Pattern; /** * Slice implementation that provides HTTP API (Go module proxy protocol) for Golang repository. */ public final class GoSlice implements Slice { private final Slice origin; /** * @param storage Storage * @param policy Security policy * @param users Users * @param name Repository name */ public GoSlice(final Storage storage, final Policy<?> policy, final Authentication users, final String name) { this.origin = new SliceRoute( GoSlice.pathGet( ".+/@v/v.*\\.info", GoSlice.createSlice(storage, ContentType.json(), policy, users, name) ), GoSlice.pathGet( ".+/@v/v.*\\.mod", GoSlice.createSlice(storage, ContentType.text(), policy, users, name) ), GoSlice.pathGet( ".+/@v/v.*\\.zip", GoSlice.createSlice(storage, ContentType.mime("application/zip"), policy, users, name) ), GoSlice.pathGet( ".+/@v/list", GoSlice.createSlice(storage, ContentType.text(), policy, users, name) ), GoSlice.pathGet( ".+/@latest", new BasicAuthzSlice( new LatestSlice(storage), users, new OperationControl( policy, new AdapterBasicPermission(name, Action.Standard.READ) ) ) ), new RtRulePath( RtRule.FALLBACK, new SliceSimple(ResponseBuilder.notFound().build()) ) ); } @Override public CompletableFuture<Response> response( final RequestLine line, final Headers headers, final Content body) { return this.origin.response(line, headers, body); } /** * Creates slice instance. * @param storage Storage * @param contentType Content-type * @param policy Security policy * @param users Users * @param name Repository name * @return Slice */ private static Slice createSlice( Storage storage, Header contentType, Policy<?> policy, Authentication users, String name ) { return new BasicAuthzSlice( new SliceWithHeaders(new SliceDownload(storage), Headers.from(contentType)), users, new OperationControl(policy, new AdapterBasicPermission(name, Action.Standard.READ)) ); } /** * This method simply encapsulates all the RtRule instantiations. * @param pattern Route pattern * @param slice Slice implementation * @return Path route slice */ private static RtRulePath pathGet(final String pattern, final Slice slice) { return new RtRulePath( new RtRule.All( new RtRule.ByPath(Pattern.compile(pattern)), MethodRule.GET ), new LoggingSlice(slice) ); } }
const express = require("express"); const dotenv = require("dotenv"); const morgan = require("morgan"); const bodyparser = require("body-parser"); const path = require("path"); const connectDB = require("./server/database/connection"); const { connect } = require("http2"); const app = express(); dotenv.config({ path: "config.env" }); const PORT = process.env.PORT || 3600; //log requests app.use(morgan("tiny")); //connect mongodb connectDB(); //parse request app.use(bodyparser.urlencoded({ extended: true })); //set view engine app.set("view engine", "ejs"); app.use("/css", express.static(path.resolve(__dirname, "assets/css"))); app.use("/img", express.static(path.resolve(__dirname, "assets/img"))); app.use("/js", express.static(path.resolve(__dirname, "assets/js"))); //load routers app.use("/", require("./server/routes/router")); app.listen(PORT, () => console.log(`Server running at http://localhost:${PORT}`) );
"""User model tests.""" import os from unittest import TestCase from sqlalchemy import exc from models import db, User, Message, Follows os.environ['DATABASE_URL'] = "postgresql:///warbler-test" from app import app db.create_all() class UserModelTestCase(TestCase): """Test views for messages.""" def setUp(self): """Create test client, add sample data.""" User.query.delete() Message.query.delete() Follows.query.delete() u1 = User.signup('test1', '[email protected]', 'testpassword', None) u1id = 1111 u1.id = u1id u2 = User.signup('test2', '[email protected]', 'testpassword', None) u2id = 2222 u2.id = u2id db.session.commit() u1 = User.query.get(u1id) u2 = User.query.get(u2id) self.u1 = u1 self.u1id = u1id self.u2 = u2 self.u2id= u2id self.client = app.test_client() def tearDown(self): res = super().tearDown() db.session.rollback() return res def test_user_model(self): """Does basic model work?""" u = User( email="[email protected]", username="testuser", password="HASHED_PASSWORD" ) db.session.add(u) db.session.commit() self.assertEqual(len(u.messages), 0) self.assertEqual(len(u.followers), 0) def test_user_follows(self): self.u1.following.append(self.u2) db.session.commit() self.assertEqual(len(self.u2.following), 0) self.assertEqual(len(self.u2.followers), 1) self.assertEqual(len(self.u1.followers), 0) self.assertEqual(len(self.u1.following), 1) self.assertEqual(self.u2.followers[0].id, self.u1.id) self.assertEqual(self.u1.following[0].id, self.u2.id) def test_is_following(self): self.u1.following.append(self.u2) db.session.commit() self.assertTrue(self.u1.is_following(self.u2)) self.assertFalse(self.u2.is_following(self.u1)) def test_is_followed_by(self): self.u1.following.append(self.u2) db.session.commit() self.assertTrue(self.u2.is_followed_by(self.u1)) self.assertFalse(self.u1.is_followed_by(self.u2)) def test_valid_signup(self): u_test = User.signup('testing', '[email protected]', 'password', None) uid = 99999 u_test.id = uid db.session.commit() u_test = User.query.get(uid) self.assertIsNotNone(u_test) self.assertEqual(u_test.username, 'testing') self.assertEqual(u_test.email, '[email protected]') self.assertNotEqual(u_test.password, "password") self.assertTrue(u_test.password.startswith('$2b$')) def test_invalid_username_signup(self): invalid = User.signup(None, '[email protected]', 'password', None) uid = 99999 invalid.id = uid with self.assertRaises(exc.IntegrityError) as context: db.session.commit() def test_invalid_email_signup(self): invalid = User.signup('testing', None, 'password', None) uid = 99999 invalid.id = uid with self.assertRaises(exc.IntegrityError) as context: db.session.commit() def test_invalid_password_signup(self): with self.assertRaises(ValueError) as context: User.signup("testtest", "[email protected]", "", None) def test_valid_authentication(self): u = User.authenticate(self.u1.username, "testpassword") self.assertIsNotNone(u) self.assertEqual(u.id, self.u1id) def test_invalid_username(self): self.assertFalse(User.authenticate("badusername", "password")) def test_wrong_password(self): self.assertFalse(User.authenticate(self.u1.username, "badpassword"))
package article.command; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import article.model.ArticleData; import article.service.ArticleNotFoundException; import article.service.ModifyArticleService; import article.service.ModifyRequest; import article.service.PermissionDeniedException; import article.service.ReadArticleService; import auth.service.User; import mvc.command.CommandHandler; public class ModifyArticleHandler implements CommandHandler { private static final String FORM_VIEW = "/WEB-INF/view/modifyForm.jsp"; private ReadArticleService readService = new ReadArticleService(); private ModifyArticleService modifyService = new ModifyArticleService(); @Override public String process(HttpServletRequest req, HttpServletResponse res) throws Exception { if (req.getMethod().equalsIgnoreCase("GET")) { return processForm(req, res); } else if (req.getMethod().equalsIgnoreCase("POST")) { return processSubmit(req, res); } else { res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return null; } } private String processForm(HttpServletRequest req, HttpServletResponse res) throws IOException { try { User authUser = (User) req.getSession().getAttribute("authUser"); String noVal = req.getParameter("no"); int article_id = Integer.parseInt(noVal); ArticleData articleData = readService.getArticle(article_id, false); if (!canModify(authUser, articleData)) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return null; } // 수정 폼에 수정할 데이터를 출력해야 한다 ModifyRequest modifyRequest = new ModifyRequest( authUser.getId(), article_id, articleData.getArticle().getTitle(), articleData.getContent()); req.setAttribute("modifyReq", modifyRequest); return FORM_VIEW; } catch (ArticleNotFoundException e) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return null; } } // 수정 권한이 있는지 확인 private boolean canModify(User authUser, ArticleData articleData) { String writerId = articleData.getArticle().getWriter().getId(); return authUser.getId().equals(writerId); } private String processSubmit(HttpServletRequest req, HttpServletResponse res) throws Exception { User authUser = (User) req.getSession().getAttribute("authUser"); String noVal = req.getParameter("no"); int article_id = Integer.parseInt(noVal); ModifyRequest modifyReqeust = new ModifyRequest( authUser.getId(), article_id, req.getParameter("title"), req.getParameter("content")); req.setAttribute("modifyReq", modifyReqeust); Map<String, Boolean> errors = new HashMap<>(); req.setAttribute("errors", errors); modifyReqeust.validate(errors); if (!errors.isEmpty()) { return FORM_VIEW; } try { modifyService.modify(modifyReqeust); return "/WEB-INF/view/modifySuccess.jsp"; } catch (ArticleNotFoundException e) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return null; } catch (PermissionDeniedException e) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return null; } } }
import fs from 'fs-extra' import fg from 'fast-glob' import matter from 'gray-matter' import { resolvePath } from './utils' import { slugify } from '.' export function resolveTags(routes: any[]) { const tagMap: { [key: string]: { path: string; blogs: string[] } } = {} routes .filter(item => item.meta?.layout === 'post') .forEach((item) => { item.meta.frontmatter.tags?.forEach((tag: string) => { if (tag in tagMap) tagMap[tag].blogs.push(item.path) else tagMap[tag] = { path: `/posts/tags/${slugify(tag)}`, blogs: [item.path], } }) }) return routes.map((item) => { if (item.path === '/posts' || item.path.startsWith('/posts/tags/')) { if (!item.meta) item.meta = {} item.meta.tagMap = tagMap } return item }) } export async function getTagPathsFromFiles( sourceDir: string, exclude?: string[], ) { sourceDir = resolvePath(sourceDir) const files = await fg('**/*.md', { cwd: sourceDir, ignore: exclude }) const tags: Set<string> = new Set() await Promise.all( files.map(async (f) => { const raw = await fs.readFile(`${sourceDir}/${f}`) const { data } = matter(raw) data.tags?.forEach((tag: string) => tags.add(`/posts/tags/${slugify(tag)}`), ) }), ) return [...tags] }
package net.javaguides.springboot.usecase; import net.javaguides.springboot.domain.dtos.CampanhaDTO; import net.javaguides.springboot.domain.entity.Campanha; import net.javaguides.springboot.domain.repository.CampanhaRepository; import net.javaguides.springboot.usecase.exceptions.ObjectNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class CampanhaService { @Autowired private CampanhaRepository campanhaRepository; public Campanha findById(Integer id){ Optional<Campanha> obj = campanhaRepository.findById(id); return obj.orElseThrow(() -> new ObjectNotFoundException("Objeto não encontrado para o Id: " + id)); } public List<Campanha> findAll() { return campanhaRepository.findAll(); } public Campanha create(CampanhaDTO dto) { dto.setIdCampanha(null); Campanha newCampanha = new Campanha(dto); return campanhaRepository.save(newCampanha); } public Campanha update(Integer id, CampanhaDTO dto) { dto.setIdCampanha(id); Campanha oldCampanha = findById(id); Campanha newCampanha = atualizarValores(dto, oldCampanha); return campanhaRepository.save(newCampanha); } private Campanha atualizarValores(CampanhaDTO dto, Campanha oldCampanha) { if (dto.getNomeCampanha() != null) { oldCampanha.setNomeCampanha(dto.getNomeCampanha()); } if (dto.getNomeVacina() != null) { oldCampanha.setNomeVacina(dto.getNomeVacina()); } if (dto.getDescricao() != null) { oldCampanha.setDescricao(dto.getDescricao()); } if (dto.getDataCampanha() != null) { oldCampanha.setDataCampanha(dto.getDataCampanha()); } return oldCampanha; } public void delete(Integer id) { campanhaRepository.deleteById(id); } }
import { LayoutService } from './../layout.service'; import { ActivatedRoute, Router } from '@angular/router'; import { LocalStorageService } from './../../Auth/localStorageLogin/local-storage.service'; import { FormGroup, FormBuilder, FormControl, Validators, } from '@angular/forms'; import { OwlOptions } from 'ngx-owl-carousel-o'; import { MessageService } from 'primeng/api'; import { Component, OnInit } from '@angular/core'; import * as moment from 'jalali-moment'; import { CartService } from '../serviceCart/cart.service'; @Component({ selector: 'app-product-details', templateUrl: './product-details.component.html', styleUrls: ['./product-details.component.scss'], providers: [MessageService], }) export class ProductDetailsComponent implements OnInit { public form: FormGroup; public formComment: FormGroup; errorMessages = { count: [{ type: 'required', message: 'تعداد سفارش را وارد کنید.' }], }; commentErrorMessages = { commentText: [{ type: 'required', message: 'متن پیام را وارد کنید.' }], }; customOptions: OwlOptions = { autoplay: true, autoplaySpeed: 1000, autoplayTimeout: 5000, loop: true, mouseDrag: true, touchDrag: true, pullDrag: true, dots: false, navSpeed: 700, nav: true, navText: [ '<i class="fa fa-chevron-left fa-2x"></i>', '<i class="fa fa-chevron-right fa-2x"></i>', ], responsive: { 0: { items: 1, }, 400: { items: 1, }, 740: { items: 2, }, 940: { items: 4, }, }, }; responsiveOptions: any[] = [ { breakpoint: '1600px', numVisible: 3, }, { breakpoint: '1024px', numVisible: 3, }, { breakpoint: '768px', numVisible: 2, }, { breakpoint: '560px', numVisible: 1, }, ]; images: any[] = []; currentIndex: any = -1; showFlag: any = false; featuresValues: any[] = []; product: any; hasDiscountCode: any = false; displayBasic: boolean; isLogged: boolean; productID: string; count: number = 1; commentsCount: any = 0; colorName: any; imageProductColor: any; priceColor: any; remainsNumberColor: any; colorCode: any; infID: any; priceWithDiscount:any; constructor( private router: Router, private formBuilder: FormBuilder, public messageService: MessageService, private service: LayoutService, public localStorage: LocalStorageService, private route: ActivatedRoute, private serviceCart: CartService ) {} ngOnInit(): void { this.isLogged = this.localStorage.getCurrentUser(); this.route.paramMap.subscribe( (params) => (this.productID = params.get('id')) ); this.service.getProduct(this.productID).subscribe((response) => { if (response.success === true) { this.product = response.data[0]; console.log(response); this.colorName = this.product.info[0].color; this.imageProductColor = this.product.info[0].image; this.priceColor = this.product.info[0].price; this.remainsNumberColor = this.product.info[0].remainsNumber; this.colorCode = this.product.info[0].colorCode; this.infID = this.product.info[0]._id; if(this.product.discountStatus){ this.priceWithDiscount=Number(this.priceColor)-Number(this.product.Discount[0].discountPercent* this.priceColor)/100; } this.product.Comment.forEach((element) => { if (element.active) { this.commentsCount++; } }); if (this.product.features.length > 0) { for (let index = 0; index < this.product.features.length; index++) { this.featuresValues.push({ feature: this.product.features[index].feature, value: this.product.features[index].featureValues, }); } if (this.product.image != null) { this.images.push({ image: this.product.image, thumbnailImageSrc: this.product.image, previewImageSrc: this.product.image, }); } if (this.product.gallery.length > 0) { this.product.gallery.forEach((item) => { this.images.push({ image: item, thumbnailImageSrc: item, previewImageSrc: item, }); }); } } } }); this.createform(); } createform(): void { this.form = this.formBuilder.group({ userID: new FormControl(this.localStorage.userJson['id'], [ Validators.required, ]), productID: new FormControl(this.productID, [Validators.required]), discountCode: new FormControl(null), count: new FormControl(1, [Validators.required]), description: new FormControl(null), date: new FormControl(null), }); this.formComment = this.formBuilder.group({ userID: new FormControl(this.localStorage.userJson['id'], [ Validators.required, ]), productID: new FormControl(this.productID, [Validators.required]), commentText: new FormControl(null, [Validators.required]), date: new FormControl(null), }); } submitForm(): void { if (this.isLogged) { const date = moment(Date.now()).locale('fa').format('YYYY/M/D'); this.form.controls.date.setValue(date); this.service.registerOrder(this.form.value).subscribe((response) => { if (response.success === true) { this.messageService.add({ severity: 'success', summary: ' ثبت سفارش ', detail: response.data, }); } else { this.messageService.add({ severity: 'error', summary: ' ثبت سفارش ', detail: response.data, }); } }); } else { this.messageService.add({ severity: 'error', summary: ' کاربر نامعتبر ', detail: 'لطفا ابتدا وارد شوید.', }); } } registerComment() { this.service .registerComment(this.formComment.value) .subscribe((response) => { if (response['success'] === true) { this.ngOnInit(); this.messageService.add({ severity: 'success', summary: 'موفق', detail: response['data'], }); } }); } showLightbox(index) { this.currentIndex = index; this.showFlag = true; } closeEventHandler() { this.showFlag = false; this.currentIndex = -1; } goProduct(categoryId: any, subCategoryId: any, subSubCategoryId: any): any { this.router.navigateByUrl( '/products/' + categoryId + '/' + subCategoryId + '/' + subSubCategoryId ); } getColorName(i: any, j: any) { this.infID = i._id; this.colorName = i.color; this.imageProductColor = i.image; this.priceColor = i.price; this.colorCode = i.colorCode; this.remainsNumberColor = i.remainsNumber; if(this.product.discountStatus){ this.priceWithDiscount=Number(this.priceColor)-Number(this.product.Discount[0].discountPercent* this.priceColor)/100; } } addCart(product: any): void { if (this.remainsNumberColor > 0) { const list = { id: product._id, infoID: this.infID, name: product.title, colorCode: this.colorCode, image: this.imageProductColor, price: this.priceColor, discountCode: product.Discount[0].discountCode, discountPercent: product.Discount[0].discountPercent, number: 1, sendCost: product.sendCost, }; this.displayBasic = true; this.serviceCart.addToCart(list); } else { this.messageService.add({ severity: 'error', summary: ' موجودی کالا ', detail: 'کالا موجود نیست', }); } } goCart(): void { this.displayBasic = !this.displayBasic; this.router.navigate(['/cart']); } }
import { useWeb3React } from "@web3-react/core"; import React from "react"; import Sale from "@components/Sale"; import Spinner from "@components/Spinner"; import RequestAccess from "@components/RequestAccess"; import { useData } from "@hooks/useData"; import "@styles/Sales.scss"; const Sales = () => { const { active } = useWeb3React(); const { sales, loading } = useData(); // If user not logged in, request access. TODO. if (!active) return <RequestAccess />; return ( <> {/* If loading variable return spinner */} {loading ? ( <Spinner /> ) : ( // If not, return sales <div className="market-content"> {sales.map((sale) => // If sale is available, show it !sale.isSold ? ( <Sale key={sale.id} id={sale.id} price={sale.price} amount={sale.amount} wallet={sale.wallet} /> ) : ( "" ) )} </div> )} </> ); }; export default Sales;
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HTTP_INTERCEPTORS } from "@angular/common/http"; import { Injectable } from "@angular/core"; import { AlertController } from "ionic-angular"; import { Observable } from "rxjs/Rx"; import { FieldMessage } from "../models/field_message"; import { StorageService } from "../services/storage.service"; @Injectable() export class ErrorInteceptor implements HttpInterceptor { constructor( public storage: StorageService, public alertCtrl: AlertController) { } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(req) .catch((error, caught) => { let errorObj = error; if (errorObj.error) { errorObj = errorObj.error; } if (!errorObj.status) { errorObj = JSON.parse(errorObj); } console.log("Erro detectado pelo interceptor:"); console.log(errorObj); switch (errorObj.status) { case 401: this.handle401(); break; case 403: this.handle403(); break; case 422: this.handle422(errorObj); break; default: this.handleDefaultError(errorObj); break; } return Observable.throw(errorObj); }) as any; } handle401() { let alert = this.alertCtrl.create({ title: 'Erro 401: Falha de autenticação', message: 'Email ou senha incorrentos', enableBackdropDismiss: false, buttons: [ { text: 'Ok', } ], }); alert.present(); } handle403() { this.storage.setLocalUser(null); } handle422(errorObj) { let alert = this.alertCtrl.create({ title: 'Erro 422: validação!', message: this.listErrors(errorObj.errors), enableBackdropDismiss: false, buttons: [ { text: 'Ok' } ], }); alert.present(); } handleDefaultError(errorObj) { let alert = this.alertCtrl.create({ title: 'Erro ' + errorObj.status + ': ' + errorObj.error, message: errorObj.message, enableBackdropDismiss: false, buttons: [ { text: 'Ok', } ], }); alert.present(); } private listErrors(messages: FieldMessage[]): string { let str: string = ''; for (let msg of messages) { str = str + '<p><strong>' + msg.fieldName + '</strong>: ' + msg.message + '</p>'; } return str; } } export const ErrorInteceptorProvider = { provide: HTTP_INTERCEPTORS, useClass: ErrorInteceptor, multi: true, };
path name matching capability of bash shell - GLOBBING * -any string of O or more characters ? -any single character ~ -current users home directory ~username -usernames home directory ~+ -current working directory ~- -previous working directory [abc...] -any one character in the enclosed class (EG: ls [a]* -it shows files having name starting with 'a' [!abc...] -any one character not in the enclosed class (Eg: ls [!ab] - it shows files having name starting with other than 'a' [[:alpha:]] -any alphabetic character [[:lower:]] -lower case character [[:upper:]] -upper case character [[:alnum:]] -alphabetic character or digit [[:punct:]] -printable character other than space or alphanumeric [[:digit:]] -digit from 0-9 [[:space:]] -whitespace character EXAMPLES: HOME-DESKTOP-MUFEE-APPLE,CAR,DOG,MAN,SEAT user/home/desktop/mufee $ ls a* apple $ls dm* dog man $ls ??? car dog man seat COMMANDS 1.echo -to display line of text 2.BRACE EXPANSION- Eg : user/home/desktop/mufee $ echo {one,two,three}.log one.log two.log three.log user/home/desktop/mufee $ echo file{1..4}.txt file1.txt file2.txt file3.txt file4.txt 3.command substitution ,$ -allows the output of a command to replace the command itself Eg : user/home/desktop/mufee $ echo today is $(date +%A) today is wednesday
package com.example.tracker_presentation.tracker_overview.components import android.os.Build import androidx.annotation.RequiresApi import androidx.compose.runtime.Composable import androidx.compose.ui.res.stringResource import com.example.core.R import java.time.LocalDate import java.time.format.DateTimeFormatter @RequiresApi(Build.VERSION_CODES.O) @Composable fun parseDateText(date: LocalDate): String { val today = LocalDate.now() return when(date) { today -> stringResource(id = R.string.today) today.minusDays(1) -> stringResource(id = R.string.yesterday) today.plusDays(1) -> stringResource(id = R.string.tomorrow) else -> DateTimeFormatter.ofPattern("dd LLLL").format(date) } }
import React from "react"; import { useDispatch } from "react-redux"; import placeholderImg from '../assets/img-placeholder-dark.jpg'; import { fetchVideoDetails, streamTypeAction } from "../features/common/commonSlice"; import { truncateText } from "../helper/helper"; import Ratings from "./Ratings"; function Card(props) { const { video, streamType, isPoster } = props; const dispatch = useDispatch(); const getDetails = () => { dispatch(fetchVideoDetails({ type: streamType, id: video.id })); dispatch(streamTypeAction(streamType)); } return ( <div className="card h-100 rounded-3" onClick={getDetails}> { isPoster ? <img src={video?.backdrop_path ? `https://image.tmdb.org/t/p/original/${video?.poster_path}` : placeholderImg} className="card-img-top" alt="..." /> : <img src={video?.backdrop_path ? `https://image.tmdb.org/t/p/original/${video?.backdrop_path}` : placeholderImg} className="card-img-top" alt="..." /> } <div className="card-body text-white "> <h5 className="card-title">{video?.name || video?.title || video?.original_title}</h5> <p>{truncateText(video?.overview, 60)}</p> <Ratings voteAverage={video?.vote_average} voteCount={video?.vote_count} /> </div> </div> ); } export default Card;
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Event 처리(addEventListener)</title> <script> /* [DOM Event 종류] 1. 마우스 - mouseover, mouseout - mousedown -> mouseup -> click 클릭 한 번에 이렇게 동작함 - mousedown -> mouseup -> click ... mousedown -> mouseup -> click -> duble click 더블 클릭은 이렇게 2. 키보드 - keydown -> keyup -> keypress 3. form - sumit 4. input - focus, blur, change 5. touch(모바일) [DOM Event 용어 정리] 1. Event Name - load, click, mousedown, ... 2. Event Attribute - DOM Event Model Level 0 (속성으로 이벤트를 처리하는 방법) : onload, onclick, onmouseover 3. Event Listener - DOM Event Model Level 2 : callback function 4. DOM Event Model - DOM HTML Element의 Event Handler를 설정하는 방법에 대한 표준 - DOM Event Mode Lv.0 1) inline - 태그 안에 Event Attribute(ex/ onclick)에 자바스크립트 코드를 설정하는 방식 ex/ <h1 onclick='JS code ...'></h1> -> 웹 표준에 위배되는 방식 2) basic - 고전적인 이벤트 처리 방식(기본 이벤트 처리 방식) ex/ element.onclick = function(){ ... } | element: document. 으로 뽑아온 친구들 -> 문제점은 이벤트 핸들러를 하나만 등록할 수 있다..! - DOM Event Model Lv.2 1) Observer 패턴을 적용해서 Listener(함수, 이벤트 핸들러)를 등록하는 방식 2) 다중 event handler를 등록할 수 있다. 3) HTML Element 객체가 이벤트 핸들러를 등록/제거할 수 있는 함수(DOM API)를 제공하여야 한다 : MSIE(<=8) : attachEvent / detachEvent : 표준 브라우저 : element.addEventListener / element.removeEventListener */ window.addEventListener("load", function() { console.log("Window Load!"); document.getElementById("header-2") .onclick = function() { console.log('Event Model Lv.0 - Basic'); } document .getElementById("header-3") .addEventListener('click', function() { console.log('Event Model Level 2'); }); }); </script> </head> <body> <h1>DOM(Document Object Model)</h1> <h2>5. Event 처리</h2> <h3 onClick='console.log("Event Model Lv.0 - inline")'>Event Model Level0 - Inline</h3> <h3 id='header-2'>Event Model Level0 - Basic</h3> <h3 id='header-3'>Event Model Level2</h3> </body> </html>
import React from "react"; import { useSelector } from "react-redux"; import { useParams, Link } from "react-router-dom"; import { Button } from "antd"; import CharacterCard from "../CharacterCard/CharacterCard"; import styles from "./answers.module.css"; function Answers() { const { rightAnswers } = useSelector((store) => store.rightAnswersStore); const { wrongAnswers } = useSelector((store) => store.wrongAnswersStore); const { answersType } = useParams(); return ( <div className={`${styles.answers} container`}> <Link to="/results"> <Button>← К результатам</Button> </Link> {answersType === "right-answers" ? ( <div> <h2 className={styles.answers__title}>Правильные ответы</h2> {rightAnswers.length !== 0 ? ( <> <div className={styles.answers__wrapper}> {rightAnswers.map((el) => ( <CharacterCard key={el.id} name={el.name} image={el.image} /> ))} </div> </> ) : ( <div className={styles.answers__noCards}>У вас нет правильных ответов, попробуйте снова!</div> )} </div> ) : ( <div> <h2 className={styles.answers__title}>Неправильные ответы</h2> {wrongAnswers.length !== 0 ? ( <> <div className={styles.answers__wrapper}> {wrongAnswers.map((el) => ( <CharacterCard key={el.id} name={el.name} image={el.image} /> ))} </div> </> ) : ( <div className={styles.answers__noCards}>Ни одной ошибки, так держать!</div> )} </div> )} </div> ); } export default Answers;
<?php // Define a class Person class Person{ // Properties private string $name; private int $age; //Methods function setName(string $firstName, string $lastName): void { $this->name = $firstName . ' ' . $lastName; } function setAge(int $age): void{ $this->age = $age; } function getName(): string{ return $this->name; } function getAge(): int{ return $this->age; } //Constructor function __construct(){ $this->name = ""; $this->age = 0; } } ?>
<script> import * as THREE from "three"; import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js"; import SplineLoader from "@splinetool/loader"; import { onMount } from "svelte"; // camera onMount(() => { // camera const camera = new THREE.OrthographicCamera( window.innerWidth / -2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / -2, -50000, 10000 ); camera.position.set(0, 0, 0); camera.quaternion.setFromEuler(new THREE.Euler(0, 0, 0)); // scene const scene = new THREE.Scene(); // spline scene const loader = new SplineLoader(); loader.load( "https://prod.spline.design/J5NONTcTO6sOd7mF/scene.splinecode", (splineScene) => { scene.add(splineScene); } ); // renderer const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); renderer.setAnimationLoop(animate); document.body.appendChild(renderer.domElement); // scene settings renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFShadowMap; scene.background = new THREE.Color("#131715"); renderer.setClearAlpha(1); // orbit controls const controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping = true; controls.dampingFactor = 0.05; controls.enableZoom = false; // Disable zooming on scroll let spinCount = 0; const totalSpins = 2; if (spinCount < totalSpins) { // Rotate the camera around the target based on the scroll direction controls.target.applyAxisAngle( new THREE.Vector3(0, 1, 0), event.deltaY * 0.001 ); // Increment the spin count spinCount += event.deltaY; } else { // If the model has completed a full revolution, enable zooming } // Add the custom event listener document.addEventListener("wheel", onDocumentMouseWheel, false); window.addEventListener("resize", onWindowResize); function onWindowResize() { camera.left = window.innerWidth / -2; camera.right = window.innerWidth / 2; camera.top = window.innerHeight / 2; camera.bottom = window.innerHeight / -2; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); } function animate(time) { controls.update(); renderer.render(scene, camera); } }); </script>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>页面布局之三栏中间自适应布局</title> <style> * { padding: 0; margin: 0; } .container>div { min-height: 100px; } .left { width: 300px; background: lightgoldenrodyellow; } .center { background: gray; /* 用来测试高度自适应, 发现只有flex和table */ /* height: 600px; */ } .right { width: 300px; background: pink; } .container { overflow: hidden; } /* 方案一: float + margin */ .layout.float .left { float: left; } .layout.float .right { float: right; } .layout.float .center { margin-left: 300px; margin-right: 300px; } /* 方案二: position + margin */ .layout.position .container { position: relative; } .layout.position .center { margin: 0 300px; } .layout.position .left { position: absolute; top: 0; left: 0; } .layout.position .right { position: absolute; top: 0; right: 0; } /* 方案三: flex */ .layout.flex .container { display: flex; } .layout.flex .center { flex: 1; } /* 方案四: table */ .layout.table .container { width: 100%; display: table; } .layout.table .left, .layout.table .right, .layout.table .center { display: table-cell; } /* 方案五: Grid */ .layout.grid .container { display: grid; width: 100%; grid-template-columns: 300px auto 300px; grid-template-rows: 100px; } /* 方案六: 圣杯布局 */ .layout.cup .container>div { float: left; } .layout.cup .center { box-sizing: border-box; /* 不设比较复杂 */ width: 100%; padding: 0 300px; } .layout.cup .left { margin-left: -100%; } .layout.cup .right { margin-left: -300px; } /* 方案六2: 圣杯布局2 */ .layout.cup2 .container { padding-left:300px; padding-right:300px; } .layout.cup2 .container>div { float: left; } .layout.cup2 .center { width: 100%; } .layout.cup2 .left { margin-left: -100%; position: relative; right: 300px; } .layout.cup2 .right { margin-right: -300px; } /* 方案七: 双飞翼布局 */ .layout.fly .center { width: 100%; } .layout.fly .col { float: left; min-height: 100px; } .layout.fly .inner { margin-left: 300px; margin-right: 300px; } .layout.fly .left { margin-left: -100%; } .layout.fly .right { margin-left: -300px; } </style> </head> <body> <!-- 方案一: float + margin --> <section class="layout float"> <article class="container"> <div class="left">左侧</div> <div class="right">右侧</div> <div class="center"> <h1>方案一: float + margin</h1> 中间部分 </div> </article> </section> <div>------我是分隔符------</div> <!-- 方案二: position + margin--> <section class="layout position"> <article class="container"> <div class="left">左侧</div> <div class="center"> <h1>方案二: position + margin</h1> 中间部分 </div> <div class="right">右侧</div> </article> </section> <div>------我是分隔符------</div> <!-- 方案三: flex --> <section class="layout flex"> <article class="container"> <div class="left">左侧</div> <div class="center"> <h1>方案三: flex</h1> 中间部分 </div> <div class="right">右侧</div> </article> </section> <div>------我是分隔符------</div> <!-- 方案四: table布局 --> <section class="layout table"> <article class="container"> <div class="left">左侧</div> <div class="center"> <h1>方案四: table布局</h1> 中间部分 </div> <div class="right">右侧</div> </article> </section> <div>------我是分隔符------</div> <!-- 方案五: Grid布局 --> <section class="layout grid"> <article class="container"> <div class="left">左侧</div> <div class="center"> <h1>方案五: Grid布局</h1> 中间部分 </div> <div class="right">右侧</div> </article> </section> <div>------我是分隔符------</div> <!-- 方案六: 圣杯布局 --> <section class="layout cup"> <article class="container"> <div class="center"> <h1>方案六: 圣杯布局</h1> 中间部分 </div> <div class="left">左侧</div> <div class="right">右侧</div> </article> </section> <div>------我是分隔符------</div> <!-- 方案六-2: 圣杯布局2 --> <!-- 问题: 页面最小宽度大 --> <section class="layout cup2"> <article class="container"> <div class="center"> <h1>方案六-2: 圣杯布局2</h1> 中间部分 </div> <div class="left">左侧</div> <div class="right">右侧</div> </article> </section> <div>------我是分隔符------</div> <!-- 方案七: 双飞翼布局 --> <section class="layout fly"> <div class="center col"> <div class="inner"> 方案七: 双飞翼布局 </div> </div> <div class="left col">左侧</div> <div class="right col">右侧</div> </section> <div>------我是分隔符------</div> </body> </html>
-- Java array is an object which contains elements of a similar data type. Array in Java is index-based, the first element of the array is stored at the 0th index and so on. In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an array in Java. Advantages-- Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently. Random access: We can get any data located at an index position. Disadvantages-- Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in Java which grows automatically. There are two types of array. Single Dimensional Array - a[] Multidimensional Array a[][] or a[][][]
import { useState } from 'react' import Image from 'next/image' import { useRouter } from 'next/router' import { Paper } from '@mui/material' import Layout from 'components/layout' import { jLeagueTeams } from 'utils/TeamData' import { TeamDataType } from 'types/internal' import Meta from 'components/layout/Head' import SerchInput from 'components/parts/Input/Serch' import style from './index.module.scss' export default function Categories(): JSX.Element { const router = useRouter() const [teamData, setTeamData] = useState<TeamDataType[]>(jLeagueTeams) const [search, setSearch] = useState<string>('') const handleSearch = (e: React.ChangeEvent<HTMLInputElement>): void => { setSearch(e.target.value) const data = jLeagueTeams.filter((teams: TeamDataType) => teams.name.toLowerCase().includes(e.target.value.toLowerCase()), ) setTeamData(data) } return ( <Layout> <Meta title='カテゴリー' /> <div className='bg_blue min_height pb_20'> <div className={style.categories_serch_area}> <SerchInput value={search} placeholder='キーワードを入力...' onChange={handleSearch} /> </div> <div className={style.categories_area}> {teamData.map((team: TeamDataType) => ( <Paper key={team.label} className={style.team_card} onClick={(): void => { router.push(`/categories/${team.label}`) }} > <Image src={team.img} alt={''} width={100} height={70} className={style.team_img} priority /> <span>{team.name}</span> </Paper> ))} </div> </div> </Layout> ) }
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { YearComputerWork } from '../entities/year-computer-work.entity'; import { IYearComputerWorkOptions, YearComputerWorkPaginationResult } from '../types/year-computer-work.options'; import { CreateYearComputerWorkDto, UpdateYearComputerWorkDto, ReadYearComputerWorkDto } from '../dto/year-computer-work.dto'; import { ComputerService } from './computer.service'; import { StatisticsHoursMember } from '../types/statistics.options'; @Injectable() export class YearComputerWorkService { constructor( @InjectRepository(YearComputerWork) private yearComputerWorkRepository: Repository<YearComputerWork>, private computerService: ComputerService, ) {} public async create( createYearComputerWorkDto: CreateYearComputerWorkDto, ): Promise<YearComputerWork> { const { computerId, ...properties } = createYearComputerWorkDto; const computer = await this.computerService.readById(computerId); if(computer === null) { throw new BadRequestException(`Computer with id=${computerId} does not exist`); } const yearComputerWork = { computer, ...properties }; return this.yearComputerWorkRepository.save(yearComputerWork); } public async readAll( options: IYearComputerWorkOptions, ): Promise<YearComputerWorkPaginationResult> { const queryBuilder = this.yearComputerWorkRepository.createQueryBuilder("yearComputerWork"); queryBuilder .select(['yearComputerWork.id', 'yearComputerWork.date', 'yearComputerWork.operatingSystem']) //.from(YearComputerWork, 'yearComputerWork') .leftJoin('yearComputerWork.computer', 'computer') .addSelect([ 'computer.id', 'computer.name', 'computer.ipAddress', 'computer.macAddress', 'computer.audince', ]); if (options.filter) { if (options.filter.date) { queryBuilder.andWhere('yearComputerWork.date = :date', { date: options.filter.date, }); } if (options.filter.dateStart) { queryBuilder.andWhere('yearComputerWork.date >= :dateStart', { dateStart: options.filter.dateStart, }); } if (options.filter.dateEnd) { queryBuilder.andWhere('yearComputerWork.date <= :dateEnd', { date: options.filter.dateEnd, }); } if (options.filter.operatingSystem) { queryBuilder.andWhere('yearComputerWork.operatingSystem LIKE :operatingSystem', { operatingSystem: "%" + options.filter.operatingSystem + "%", }); } if(options.filter.computers) { if(typeof options.filter.computers === "string") { queryBuilder.andWhere('computer.id = :computers', { computers: Number(options.filter.computers), }); } else { queryBuilder.andWhere('computer.id IN (:...computers)', { computers: options.filter.computers, //options.filter.computers.map(id => Number(id)), }); } } } if(options.sorting) { queryBuilder.orderBy(options.sorting.column, options.sorting.direction); } if(options.pagination) { queryBuilder.skip(options.pagination.page * options.pagination.size).take(options.pagination.size); } const entities = await queryBuilder.getMany(); const entitiesCount = await queryBuilder.getCount(); if(options.pagination) { const pageCount = Math.floor(entitiesCount / options.pagination.size) - ((entitiesCount % +options.pagination.size === 0) ? 1: 0); return { meta: { page: +options.pagination.page, maxPage: pageCount, entitiesCount: pageCount === +options.pagination.page ? (entitiesCount % +options.pagination.size) : +options.pagination.size, }, entities: entities, }; } return { meta: null, entities: entities, }; } public async readById( id: number, ): Promise<YearComputerWork> { const yearComputerWork = await this.yearComputerWorkRepository.findOneBy({ id }); if( yearComputerWork === null ) { throw new NotFoundException(`YearComputerWork with id=${id} does not exist`); } return yearComputerWork; } public async readOne( readYearComputerWorkDto: ReadYearComputerWorkDto, ): Promise<YearComputerWork> { return await this.yearComputerWorkRepository.findOne({ select: ['id', 'computer', 'date', 'operatingSystem', 'hours'], where: { computer: await this.computerService.readById(readYearComputerWorkDto.computerId), date: readYearComputerWorkDto.date, operatingSystem: readYearComputerWorkDto.operatingSystem, }, relations: ['computer'], }) //return this.yearComputerWorkRepository.findOneBy({ ...readYearComputerWorkDto }); } public async update( id: number, updateYearComputerWorkDto: UpdateYearComputerWorkDto, ): Promise<YearComputerWork> { const existingYearComputerWork = await this.readById(id); if(existingYearComputerWork === null) { throw new NotFoundException(`YearComputerWork with id=${id} does not exist`); } const { computerId, ...properties } = updateYearComputerWorkDto; if(computerId) { const computer = await this.computerService.readById(computerId); if(computer === undefined) { throw new BadRequestException(`Computer with id=${computerId} does not exist`); } const yearComputerWork = { computer, ...properties }; await this.yearComputerWorkRepository.update(id, yearComputerWork); } else { await this.yearComputerWorkRepository.update(id, { ...properties }); } return this.readById(id); } public async delete( id: number, ): Promise<void> { const existingYearComputerWork = await this.readById(id); if(existingYearComputerWork === null) { throw new NotFoundException(`YearComputerWork with id=${id} does not exist`); } await this.yearComputerWorkRepository.softDelete(id); } }
#if UNITY_EDITOR using System; using System.Collections.Generic; using System.Reflection; using System.Text; using UnityEditor; using UnityEngine.InputSystem.Utilities; namespace UnityEngine.InputSystem.Editor { /// <summary> /// Helpers for working with <see cref="SerializedProperty"/> in the editor. /// </summary> internal static class SerializedPropertyHelpers { // Show a PropertyField with a greyed-out default text if the field is empty and not being edited. // This is meant to communicate the fact that filling these properties is optional and that Unity will // use reasonable defaults if left empty. public static void PropertyFieldWithDefaultText(this SerializedProperty prop, GUIContent label, string defaultText) { GUI.SetNextControlName(label.text); var rt = GUILayoutUtility.GetRect(label, GUI.skin.textField); EditorGUI.PropertyField(rt, prop, label); if (string.IsNullOrEmpty(prop.stringValue) && GUI.GetNameOfFocusedControl() != label.text && Event.current.type == EventType.Repaint) { using (new EditorGUI.DisabledScope(true)) { rt.xMin += EditorGUIUtility.labelWidth; GUI.skin.textField.Draw(rt, new GUIContent(defaultText), false, false, false, false); } } } public static SerializedProperty GetParentProperty(this SerializedProperty property) { var path = property.propertyPath; var lastDot = path.LastIndexOf('.'); if (lastDot == -1) return null; var parentPath = path.Substring(0, lastDot); return property.serializedObject.FindProperty(parentPath); } public static SerializedProperty GetArrayPropertyFromElement(this SerializedProperty property) { // Arrays have a structure of 'arrayName.Array.data[index]'. // Given property should be element and thus 'data[index]'. var arrayProperty = property.GetParentProperty(); Debug.Assert(arrayProperty.name == "Array", "Expecting 'Array' property"); return arrayProperty.GetParentProperty(); } public static int GetIndexOfArrayElement(this SerializedProperty property) { var propertyPath = property.propertyPath; if (propertyPath[propertyPath.Length - 1] != ']') return -1; var lastIndexOfLeftBracket = propertyPath.LastIndexOf('['); if (int.TryParse( propertyPath.Substring(lastIndexOfLeftBracket + 1, propertyPath.Length - lastIndexOfLeftBracket - 2), out var index)) return index; return -1; } public static Type GetArrayElementType(this SerializedProperty property) { Debug.Assert(property.isArray, $"Property {property.propertyPath} is not an array"); var fieldType = property.GetFieldType(); if (fieldType == null) throw new ArgumentException($"Cannot determine managed field type of {property.propertyPath}", nameof(property)); return fieldType.GetElementType(); } public static void ResetValuesToDefault(this SerializedProperty property) { var isString = property.propertyType == SerializedPropertyType.String; if (property.isArray && !isString) { property.ClearArray(); } else if (property.hasChildren && !isString) { foreach (var child in property.GetChildren()) ResetValuesToDefault(child); } else { switch (property.propertyType) { case SerializedPropertyType.Float: property.floatValue = default(float); break; case SerializedPropertyType.Boolean: property.boolValue = default(bool); break; case SerializedPropertyType.Enum: case SerializedPropertyType.Integer: property.intValue = default(int); break; case SerializedPropertyType.String: property.stringValue = string.Empty; break; case SerializedPropertyType.ObjectReference: property.objectReferenceValue = null; break; } } } public static string ToJson(this SerializedObject serializedObject) { return JsonUtility.ToJson(serializedObject, prettyPrint: true); } // The following is functionality that allows turning Unity data into text and text // back into Unity data. Given that this is essential functionality for any kind of // copypaste support, I'm not sure why the Unity editor API isn't providing this out // of the box. Internally, we do have support for this on a whole-object kind of level // but not for parts of serialized objects. /// <summary> /// /// </summary> /// <param name="property"></param> /// <returns></returns> /// <remarks> /// Converting entire objects to JSON is easy using Unity's serialization system but we cannot /// easily convert just a part of the serialized graph to JSON (or any text format for that matter) /// and then recreate the same data from text through SerializedProperties. This method helps by manually /// turning an arbitrary part of a graph into JSON which can then be used with <see cref="RestoreFromJson"/> /// to write the data back into an existing property. /// /// The primary use for this is copy-paste where serialized data needs to be stored in /// <see cref="EditorGUIUtility.systemCopyBuffer"/>. /// </remarks> public static string CopyToJson(this SerializedProperty property, bool ignoreObjectReferences = false) { var buffer = new StringBuilder(); CopyToJson(property, buffer, ignoreObjectReferences); return buffer.ToString(); } public static void CopyToJson(this SerializedProperty property, StringBuilder buffer, bool ignoreObjectReferences = false) { CopyToJson(property, buffer, noPropertyName: true, ignoreObjectReferences: ignoreObjectReferences); } private static void CopyToJson(this SerializedProperty property, StringBuilder buffer, bool noPropertyName, bool ignoreObjectReferences) { var propertyType = property.propertyType; if (ignoreObjectReferences && propertyType == SerializedPropertyType.ObjectReference) return; // Property name. if (!noPropertyName) { buffer.Append('"'); buffer.Append(property.name); buffer.Append('"'); buffer.Append(':'); } // Strings are classified as arrays and have children. var isString = propertyType == SerializedPropertyType.String; // Property value. if (property.isArray && !isString) { buffer.Append('['); var arraySize = property.arraySize; var isFirst = true; for (var i = 0; i < arraySize; ++i) { var element = property.GetArrayElementAtIndex(i); if (ignoreObjectReferences && element.propertyType == SerializedPropertyType.ObjectReference) continue; if (!isFirst) buffer.Append(','); CopyToJson(element, buffer, true, ignoreObjectReferences); isFirst = false; } buffer.Append(']'); } else if (property.hasChildren && !isString) { // Any structured data we represent as a JSON object. buffer.Append('{'); var isFirst = true; foreach (var child in property.GetChildren()) { if (ignoreObjectReferences && child.propertyType == SerializedPropertyType.ObjectReference) continue; if (!isFirst) buffer.Append(','); CopyToJson(child, buffer, false, ignoreObjectReferences); isFirst = false; } buffer.Append('}'); } else { switch (propertyType) { case SerializedPropertyType.Enum: case SerializedPropertyType.Integer: buffer.Append(property.intValue); break; case SerializedPropertyType.Float: buffer.Append(property.floatValue); break; case SerializedPropertyType.String: buffer.Append('"'); buffer.Append(property.stringValue.Escape()); buffer.Append('"'); break; case SerializedPropertyType.Boolean: if (property.boolValue) buffer.Append("true"); else buffer.Append("false"); break; ////TODO: other property types default: throw new NotImplementedException($"Support for {property.propertyType} property type"); } } } public static void RestoreFromJson(this SerializedProperty property, string json) { var parser = new JsonParser(json); RestoreFromJson(property, ref parser); } public static void RestoreFromJson(this SerializedProperty property, ref JsonParser parser) { var isString = property.propertyType == SerializedPropertyType.String; if (property.isArray && !isString) { property.ClearArray(); parser.ParseToken('['); while (!parser.ParseToken(']') && !parser.isAtEnd) { var index = property.arraySize; property.InsertArrayElementAtIndex(index); var elementProperty = property.GetArrayElementAtIndex(index); RestoreFromJson(elementProperty, ref parser); parser.ParseToken(','); } } else if (property.hasChildren && !isString) { parser.ParseToken('{'); while (!parser.ParseToken('}') && !parser.isAtEnd) { parser.ParseStringValue(out var propertyName); parser.ParseToken(':'); var childProperty = property.FindPropertyRelative(propertyName.ToString()); if (childProperty == null) throw new ArgumentException($"Cannot find property '{propertyName}' in {property}", nameof(property)); RestoreFromJson(childProperty, ref parser); parser.ParseToken(','); } } else { switch (property.propertyType) { case SerializedPropertyType.Float: { parser.ParseNumber(out var num); property.floatValue = (float)num.ToDouble(); break; } case SerializedPropertyType.String: { parser.ParseStringValue(out var str); property.stringValue = str.ToString(); break; } case SerializedPropertyType.Boolean: { parser.ParseBooleanValue(out var b); property.boolValue = b.ToBoolean(); break; } case SerializedPropertyType.Enum: case SerializedPropertyType.Integer: { parser.ParseNumber(out var num); property.intValue = (int)num.ToInteger(); break; } default: throw new NotImplementedException( $"Restoring property value of type {property.propertyType} (property: {property})"); } } } public static IEnumerable<SerializedProperty> GetChildren(this SerializedProperty property) { if (!property.hasChildren) yield break; using (var iter = property.Copy()) { var end = iter.GetEndProperty(true); // Go to first child. if (!iter.Next(true)) yield break; // Shouldn't happen; we've already established we have children. // Iterate over children. while (!SerializedProperty.EqualContents(iter, end)) { yield return iter; if (!iter.Next(false)) break; } } } public static FieldInfo GetField(this SerializedProperty property) { var objectType = property.serializedObject.targetObject.GetType(); var currentSerializableType = objectType; var pathComponents = property.propertyPath.Split('.'); FieldInfo result = null; foreach (var component in pathComponents) { // Handle arrays. They are followed by "Array" and "data[N]" elements. if (result != null && currentSerializableType.IsArray) { if (component == "Array") continue; if (component.StartsWith("data[")) { currentSerializableType = currentSerializableType.GetElementType(); continue; } } result = currentSerializableType.GetField(component, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy); if (result == null) return null; currentSerializableType = result.FieldType; } return result; } public static Type GetFieldType(this SerializedProperty property) { return GetField(property)?.FieldType; } public static void SetStringValue(this SerializedProperty property, string propertyName, string value) { var propertyRelative = property?.FindPropertyRelative(propertyName); if (propertyRelative != null) propertyRelative.stringValue = value; } } } #endif // UNITY_EDITOR
import Document, { Html, Head, Main, NextScript } from 'next/document' import { ReactElement } from 'react' class MyDocument extends Document { render(): ReactElement { return ( <Html lang="pt-BR" dir="ltr"> <Head> <meta charSet="utf-8" /> <meta httpEquiv="X-UA-Compatible" content="ie=edge,chrome=1" /> <meta name="author" content="pr333do" /> <meta name="theme-color" content="#1e242a" /> <link rel="shortcut icon" href="/miscellaneous/favicon.ico" /> <link rel="apple-touch-icon" sizes="180x180" href="/miscellaneous/apple-touch-icon.png" /> <link rel="icon" type="image/png" sizes="32x32" href="/miscellaneous/favicon-32x32.png" /> <link rel="icon" type="image/png" sizes="16x16" href="/miscellaneous/favicon-16x16.png" /> <link rel="manifest" href="/miscellaneous/site.webmanifest" /> </Head> <body> <Main /> <NextScript /> </body> </Html> ) } } export default MyDocument
<!DOCTYPE html> <html lang="en"> <head> <link href="styles.css" rel="stylesheet"> <!-- Google tag (gtag.js) --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-M0CHK7VL1R"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-M0CHK7VL1R'); // Inline JavaScript for dark mode toggle function toggleDarkMode() { const body = document.body; body.classList.toggle('dark-mode'); // Save user preference to localStorage const isDarkMode = body.classList.contains('dark-mode'); localStorage.setItem('darkMode', isDarkMode); } document.addEventListener('DOMContentLoaded', function() { const body = document.body; const isDarkMode = localStorage.getItem('darkMode') === 'true'; if (isDarkMode) { body.classList.add('dark-mode'); } }); </script> <style> body { transition: background-color 0.3s ease; } .dark-mode { background-color: #333; color: #fff; } /* Styling for the dark mode toggle button */ .dark-mode-toggle { background-color: #e5c0f3; color: #000000; border: none; padding: 10px 15px; font-size: 14px; cursor: pointer; border-radius: 5px; transition: background-color 0.3s ease; } .dark-mode-toggle:hover { background-color: #a410df; } </style> <title>Sydney's Sojourns - Home</title> <meta charset="UTF-8"> <meta name="description" content="Welcome to Sydney's Sojourns - Your gateway to the world of travel and adventure. Join me while I explore breathtaking destinations, and share my travel tips and experience."> <meta name="keywords" content="home, sojourn, adventure, travel, blog, destination, preparation, experience, airplane, tourism, roadtrip"> <meta name="author" content="Sydney Flowers"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <button class="dark-mode-toggle" onclick="toggleDarkMode()">Toggle Dark Mode</button> <header> <div> <h1 id="title"> <span class="word1">Sydney's </span> <span class="word2">Sojourns</span> <img src="Images/airplane.png" alt="airplane graphic" width="200" height="100" id="header-image"> </h1> <nav> <ul id="navigation"> <li><a href="index.html">Home</a></li> <li><a href="destinations.html">Destinations</a></li> <li><a href="preparation.html">Preparation</a></li> <li><a href="experience.html">Experience</a></li> </ul> </nav> </div> </header> <main> <div> <h2>W e l c o m e !</h2> </div> <div class="home-content"> <img src="Images/homepicture.jpg" alt="home page image" width="400" height="500" class="home-image"> <div class="text-box"> <p> Hi everyone! My name is Sydney Flowers and I’m a current junior at the University of South Carolina. I created this website to keep track of all my travel journeys, and to inform others about the beauty of travel. I haven’t traveled a ton currently, so my intention is to expand the website's content as my journeys unfold and I record my discoveries. </p> <p> On this website, I want to share my travel experiences and the incredible adventures I've had so far. From hiking in the lush rainforests of Costa Rica to exploring the bustling streets of Santiago, I've been fortunate to have some unique and unforgettable experiences that I can't wait share. </p> <p> Traveling has not only broadened my horizons but also taught me some valuable lessons. It has taught me to be adaptable, open-minded, and appreciative of the diversity that our world offers. I've learned to navigate through the challenges of unfamiliar places, languages, and customs, and it's given me the courage to step out of my comfort zone. </p> <p> I'm excited to have you join me on this travel-filled journey, and I look forward to exploring the world together. Thank you for being a part of Sydney's Sojourns! </p> </div> </div> </main> <footer> <div id="links"> <ul> <li><a href="index.html">Home</a></li> <li><a href="destinations.html">Destinations</a></li> <li><a href="preparation.html">Preparation</a></li> <li><a href="experience.html">Experience</a></li> </ul> </div> <div id="socials"> <img src="Images/mail.png" alt="email icon" width="40" height="40"> <img src="Images/instagram.png" alt="instagram icon" width="40" height="40"> <img src="Images/linkedin.png" alt="linkedin icon" width="40" height="40"> </div> <div id="contact"> <p> <h4> Contact Me!</h4> Email: <br> [email protected] <br> Phone: <br> (703)-340-9186 <br> </p> </div> </footer> </body> </html>
// // BugDataService.swift // ProtonMail // // // Copyright (c) 2019 Proton Technologies AG // // This file is part of ProtonMail. // // ProtonMail is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ProtonMail 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 ProtonMail. If not, see <https://www.gnu.org/licenses/>. import Foundation public class BugDataService: Service { private let apiService : API init(api: API) { self.apiService = api } func reportPhishing(messageID : String, messageBody : String, completion: ((NSError?) -> Void)?) { let api = ReportPhishing(msgID: messageID, mimeType: "text/html", body: messageBody) api.call(api: self.apiService) { (task, res, hasError) in completion?(res?.error) } } public func reportBug(_ bug: String, username : String, email: String, completion: ((NSError?) -> Void)?) { let systemVersion = UIDevice.current.systemVersion; let model = UIDevice.current.model let mainBundle = Bundle.main let username = username let useremail = email let butAPI = BugReportRequest(os: model, osVersion: "\(systemVersion)", clientVersion: mainBundle.appVersion, title: "ProtonMail App bug report", desc: bug, userName: username, email: useremail) butAPI.call(api: self.apiService) { (task, response, hasError) -> Void in completion?(response?.error) } } public class func debugReport(_ title: String, _ bug: String, completion: ((NSError?) -> Void)?) { let userInfo = [ NSLocalizedDescriptionKey: "ProtonMail App bug debugging.", NSLocalizedFailureReasonErrorKey: "Parser issue.", NSLocalizedRecoverySuggestionErrorKey: "Parser failed.", "Title": title, "Value": bug ] let errors = NSError(domain: dataServiceDomain, code: -10000000, userInfo: userInfo) Analytics.shared.recordError(errors) } public class func sendingIssue(title: String, bug: String, status: Int, emials: [String], attCount: Int) { let userInfo = [ NSLocalizedDescriptionKey: "ProtonMail App bug debugging.", NSLocalizedFailureReasonErrorKey: "Parser issue.", NSLocalizedRecoverySuggestionErrorKey: "Parser failed.", "Title": title, "Value": bug, ] let errors = NSError(domain: dataServiceDomain, code: -10000000, userInfo: userInfo) Analytics.shared.recordError(errors) } }
{% load static %} {# Necesario para los estilos #} <!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"> <link rel="stylesheet" href="{% static '/styles/main.css' %}"> {# Para jinjear el estilo del main #} <title>Django Projects</title> </head> <body> <nav class="navbar container"> <ul> <li> <a href="{% url 'index' %}">Home</a> {# Nota: Esto sirve para usar el name del urls.py #} </li> <li> <a href="{% url 'about' %}">About</a> </li> <li> <a href="{% url 'projects' %}">Projects</a> </li> <li> <a href="{% url 'tasks' %}">Tasks</a> </li> <li> <a href="{% url 'create_task' %}">Create task</a> </li> <li> <a href="{% url 'create_project' %}">Create project</a> </li> </ul> </nav> <main class="container"> {% block content %} {% endblock %} </main> </body> </html>
Imports System.IO Imports System.Text Imports System.Xml Imports System.Text.RegularExpressions Public Class Form1 Private scriptEncoding As Encoding ' Encoding del file dello script caricato Private Sub LoadScriptButton_Click(sender As Object, e As EventArgs) Handles LoadScriptButton.Click Try Dim openFileDialog As New OpenFileDialog() openFileDialog.Filter = "File di script PowerShell (*.ps1)|*.ps1" openFileDialog.Title = "Seleziona lo script PowerShell" If openFileDialog.ShowDialog() = DialogResult.OK Then ' Leggi il contenuto dello script dal file selezionato Dim scriptPath As String = openFileDialog.FileName scriptEncoding = GetFileEncoding(scriptPath) Dim scriptContent As String = File.ReadAllText(scriptPath, scriptEncoding) ' Visualizza lo script caricato nella RichTextBox ScriptContentRichTextBox.Text = scriptContent ' Abilita il pulsante di generazione solo se il contenuto non contiene "Please load script..." GenerateScriptButton.Enabled = Not ScriptContentRichTextBox.Text.Contains("Please load script...") End If Catch ex As Exception MessageBox.Show("Si è verificato un errore durante il caricamento dello script:" & ex.Message, "Errore", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub Private Sub GenerateScriptButton_Click(sender As Object, e As EventArgs) Handles GenerateScriptButton.Click Try ' Ottieni i valori inseriti dall'utente Dim gotifyServer As String = GotifyServerTextBox.Text Dim gotifyPort As String = GotifyPortTextBox.Text Dim customerName As String = CustomerNameTextBox.Text Dim appToken As String = If(AppTokenCheckBox.Checked, AppTokenTextBox.Text, "APP TOKEN FOR FAILED AND WARNING") Dim primaryToken As String = PrimaryTokenTextBox.Text Dim timeDifference As String = TimeDifferenceTextBox.Text ' Ottieni lo script caricato dalla RichTextBox Dim scriptContent As String = ScriptContentRichTextBox.Text ' Sostituisci i valori nel file dello script con quelli inseriti dall'utente scriptContent = Regex.Replace(scriptContent, "(?<=\$GotifyServer = "").*?(?="")", gotifyServer) scriptContent = Regex.Replace(scriptContent, "(?<=\$GotifyPort = "").*?(?="")", gotifyPort) scriptContent = Regex.Replace(scriptContent, "(?<=title = "").*?(?="")", customerName) scriptContent = Regex.Replace(scriptContent, "(?<=Send-Gotify -Message \$MessageToSend -Token "").*?(?="")", primaryToken) scriptContent = Regex.Replace(scriptContent, "(?<=Send-Gotify -Message ""\$CustomString`r`n\$EventTimeString`r`n\$Message"" -Token "").*?(?="")", appToken) scriptContent = Regex.Replace(scriptContent, "(?<=\$TimeDifference.TotalMinutes -gt )\d+", timeDifference) ' Visualizza lo script generato nella RichTextBox ScriptContentRichTextBox.Text = scriptContent ' Disabilita la casella di testo del token se la casella di controllo non è selezionata AppTokenTextBox.Enabled = AppTokenCheckBox.Checked ' Abilita il pulsante di salvataggio dello script SaveScriptButton.Enabled = True Catch ex As Exception MessageBox.Show("Si è verificato un errore durante la generazione dello script:" & ex.Message, "Errore", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub Private Sub LoadValuesButton_Click(sender As Object, e As EventArgs) Handles LoadValuesButton.Click Try Dim openFileDialog As New OpenFileDialog() openFileDialog.Filter = "File XML (*.xml)|*.xml" openFileDialog.Title = "Carica la configurazione" If openFileDialog.ShowDialog() = DialogResult.OK Then Dim filePath As String = openFileDialog.FileName Dim xmlDoc As New XmlDocument() xmlDoc.Load(filePath) GotifyServerTextBox.Text = GetNodeValue(xmlDoc, "GotifyServer") GotifyPortTextBox.Text = GetNodeValue(xmlDoc, "GotifyPort") CustomerNameTextBox.Text = GetNodeValue(xmlDoc, "CustomerName") AppTokenTextBox.Text = GetNodeValue(xmlDoc, "AppToken") PrimaryTokenTextBox.Text = GetNodeValue(xmlDoc, "PrimaryToken") TimeDifferenceTextBox.Text = GetNodeValue(xmlDoc, "TimeDifference") MessageBox.Show("I valori sono stati caricati correttamente.", "Caricamento completato", MessageBoxButtons.OK, MessageBoxIcon.Information) End If Catch ex As Exception MessageBox.Show("Si è verificato un errore durante il caricamento dei valori:" & ex.Message, "Errore", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub Private Sub SaveValuesButton_Click(sender As Object, e As EventArgs) Handles SaveValuesButton.Click Try Dim saveFileDialog As New SaveFileDialog() saveFileDialog.Filter = "File XML (*.xml)|*.xml" saveFileDialog.Title = "Salva la configurazione" If saveFileDialog.ShowDialog() = DialogResult.OK Then Dim filePath As String = saveFileDialog.FileName Dim xmlDoc As New XmlDocument() Dim xmlDeclaration As XmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", Nothing) xmlDoc.AppendChild(xmlDeclaration) Dim rootNode As XmlNode = xmlDoc.CreateElement("Config") xmlDoc.AppendChild(rootNode) AddNode(xmlDoc, rootNode, "GotifyServer", GotifyServerTextBox.Text) AddNode(xmlDoc, rootNode, "GotifyPort", GotifyPortTextBox.Text) AddNode(xmlDoc, rootNode, "CustomerName", CustomerNameTextBox.Text) AddNode(xmlDoc, rootNode, "AppToken", AppTokenTextBox.Text) AddNode(xmlDoc, rootNode, "PrimaryToken", PrimaryTokenTextBox.Text) AddNode(xmlDoc, rootNode, "TimeDifference", TimeDifferenceTextBox.Text) xmlDoc.Save(filePath) MessageBox.Show("I valori sono stati salvati correttamente.", "Salvataggio completato", MessageBoxButtons.OK, MessageBoxIcon.Information) End If Catch ex As Exception MessageBox.Show("Si è verificato un errore durante il salvataggio dei valori:" & ex.Message, "Errore", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub Private Function GetNodeValue(xmlDoc As XmlDocument, nodeName As String) As String Dim node As XmlNode = xmlDoc.SelectSingleNode($"//Config/{nodeName}") If node IsNot Nothing Then Return node.InnerText End If Return "" End Function Private Sub AddNode(xmlDoc As XmlDocument, parentNode As XmlNode, nodeName As String, nodeValue As String) Dim node As XmlNode = xmlDoc.CreateElement(nodeName) node.InnerText = nodeValue parentNode.AppendChild(node) End Sub Private Sub AppTokenCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles AppTokenCheckBox.CheckedChanged ' Abilita/disabilita la casella di testo del token in base allo stato della casella di controllo AppTokenTextBox.Enabled = AppTokenCheckBox.Checked End Sub Private Sub SaveScriptButton_Click(sender As Object, e As EventArgs) Handles SaveScriptButton.Click Try ' Salva lo script in un file con lo stesso encoding del file caricato Using saveFileDialog As New SaveFileDialog() saveFileDialog.Filter = "File di script PowerShell (*.ps1)|*.ps1" saveFileDialog.Title = "Salva lo script PowerShell" If saveFileDialog.ShowDialog() = DialogResult.OK Then Dim filePath As String = saveFileDialog.FileName File.WriteAllText(filePath, ScriptContentRichTextBox.Text, scriptEncoding) MessageBox.Show("Lo script è stato salvato correttamente.", "Salvataggio completato", MessageBoxButtons.OK, MessageBoxIcon.Information) End If End Using Catch ex As Exception MessageBox.Show("Si è verificato un errore durante il salvataggio dello script:" & ex.Message, "Errore", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub Private Function GetFileEncoding(filePath As String) As Encoding Using reader As New StreamReader(filePath, True) reader.Peek() ' Legge un carattere per determinare l'encoding Return reader.CurrentEncoding End Using End Function Private Sub GroupBox1_Enter(sender As Object, e As EventArgs) Handles GroupBox1.Enter End Sub Private Sub GithubLabel_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles GithubLabel.LinkClicked Process.Start("https://github.com/Leproide") End Sub Private Sub AppTokenTextBox_TextChanged(sender As Object, e As EventArgs) Handles AppTokenTextBox.TextChanged AppTokenCheckBox.Checked = True End Sub End Class
<!DOCTYPE html> <html lang="en" dir="ltr" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/css/register.css"> <link rel="stylesheet" href="/css/loader.css"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div class="container"> <div class="title">Регистрация</div> <div class="content"> <form th:action="@{/portal/users/register}" th:method="post" th:object="${userRegistrationBindingModel}" id="register-form"> <div class="user-details"> <div class="input-box"> <span class="details">Имейл адрес</span> <input th:field="*{username}" type="text" placeholder="Въведете своя имейл адрес" required /> <small th:if="${#fields.hasErrors('username')}" th:errors="*{username}" class="bg-danger text-light rounded"> Грешка </small> </div> <div class="input-box"> <span class="details">Прякор</span> <input th:field="*{nickname}" type="text" placeholder="Въведете своя прякор"/> <small th:if="${#fields.hasErrors('nickname')}" th:errors="*{nickname}" class="bg-danger text-light rounded"> Грешка </small> </div> <div class="input-box"> <span class="details">Парола</span> <input th:field="*{password}" type="password" placeholder="Въведете парола" required/> <small th:if="${#fields.hasErrors('password')}" th:errors="*{password}" class="bg-danger text-light rounded"> Грешка </small> </div> <div class="input-box"> <span class="details">Потвърди парола</span> <input th:field="*{confirmPassword}" type="password" placeholder="Потвърдете вашата парола" required/> <small th:if="${#fields.hasErrors('confirmPassword')}" th:errors="*{confirmPassword}" class="bg-danger text-light rounded"> Грешка </small> </div> <div class="input-box"> <span class="details">Име</span> <input th:field="*{firstName}" type="text" placeholder="Въведете вашето име" required/> <small th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}" class="bg-danger text-light rounded"> Грешка </small> </div> <div class="input-box"> <span class="details">Фамилия</span> <input th:field="*{lastName}" type="text" placeholder="Въведете вашата фамилия" required/> <small th:if="${#fields.hasErrors('lastName')}" th:errors="*{lastName}" class="bg-danger text-light rounded"> Грешка </small> </div> <div id="box" class="input-box" for="groupName"> <span class="details">Група</span> <select name="groupName"> <option selected value="">Изберете група</option> <option th:each="aGroupName : ${groupName}" th:value="${aGroupName}" th:text="${aGroupName}">Group Name </option> </select> <small th:if="${#fields.hasErrors('groupName')}" th:errors="*{groupName}" class="bg-danger text-light rounded"> Грешка </small> </div> <div class="input-box"> <span class="details">Шофьор съм</span> <label class="switch"> <input type="checkbox" th:value="isDriver"> <span class="slider round"></span> </label> </div> </div> <div id="sbm_btn" class="button"> <input type="submit" value="Регистрирай ме"> </div> </form> </div> </div> </body> </html>
$Id$ Setting up the source trees Check out the EDK2 trunk/edk2 to some directory of your choice (the command creates an edk2 subdirectory): svn checkout \ --username guest --password guest \ -r9572 https://edk2.svn.sourceforge.net/svnroot/edk2/trunk/edk2 edk2 Note for giters: r9572 = 1dba456e1a72a3c2d896f25f94ddeaa64d10a3be Enter into the edk2 directory and check out EFI/Firmware2/VBoxPkg into a VBoxPkg subdirectory: svn checkout \ http://www.virtualbox.org/svn/vbox/trunk/src/VBox/Devices/EFI/Firmware2/VBoxPkg VBoxPkg Enter into the VBoxPkg/Include and check out include/iprt and include/VBox: svn checkout http://www.virtualbox.org/svn/vbox/trunk/include/iprt iprt svn checkout http://www.virtualbox.org/svn/vbox/trunk/include/VBox VBox Then copy version-generated.h from <VBox-trunk>/out/win.*/*/version-generated.h (into VBoxPkg/include/). <VBox-trunk>/out/win.*/*/product-generated.h (into VBoxPkg/include/). Symlink alternative for Vista ----------------------------- Say you've got VBox checked out as e:\vbox\trunk and you're on 32-bit Windows and having done a debug build. Check out EDK2 somewhere (see above). Then do: kmk_ln -s %VBOXSVN%\src\VBox\Devices\EFI\Firmware2\VBoxPkg\ edk2\VBoxPkg kmk_ln -s %VBOXSVN%\include\iprt\ edk2\VBoxPkg\Include\iprt kmk_ln -s %VBOXSVN%\include\VBox\ edk2\VBoxPkg\Include\VBox kmk_ln -s %VBOXSVN%\out\win.x86\debug\version-generated.h edk2\VBoxPkg\Include\version-generated.h kmk_ln -s %VBOXSVN%\out\win.x86\debug\product-generated.h edk2\VBoxPkg\Include\product-generated.h MinGW for Linux To install MinGW on Ubuntu systems, just perform apt-get install mingw32-binutils mingw32 mingw32-runtime After that, you can even avoid setting up symlinks, as build script will do that automagically. MinGW-w64 for Linux To build the X64 firmware on Linux, the wimgw-w64 port of mingw is required. The binaries are available at: http://sourceforge.net/projects/mingw-w64/files/ on recent Ubuntu systems mingw-w64 is available in repository: apt-get install mingw-w64 Some non-fatal warnings might appears while compiling on Linux machine so it is recommended to disable -Werror at Conf/tools_def.txt:*_UNIXGCC_X64_CC_FLAGS. While building some versions of wingw-w64/linker might complain that __ModuleEntryPoint wasn't found (and fills entry point field with some default value) to fix that, just split the the definition (IA32 and X64),with removing leading underscore '_' for X64 at Conf/tools_def.txt: *_UNIXGCC_*_DLINK_FLAGS=... -entry _$(IMAGE_ENTRY_POINT) ... to *_UNIXGCC_IA32_DLINK_FLAGS=... -entry _$(IMAGE_ENTRY_POINT) ... *_UNIXGCC_X64_DLINK_FLAGS=... -entry $(IMAGE_ENTRY_POINT) ... Setting up the environment First, enter the VirtualBox environment using tools/env.cmd (and whatever local additions you normally use). Go to the EDK2 source tree you set up in the previous section and run VBoxPkg/env.cmd (Windows) and VBoxPkg/env.sh (Unix). That's it. You can now run build. Patching ======== VBox guests and hardware required some modifications in EDK2 do before building some patches are required: cat VBoxPkg/edk2.patch-pmtimer | patch -p0 cat VBoxPkg/edk2.patch-no_blocking_partition | patch -p0 cat VBoxPkg/edk2.patch-ovmf_pei | patch -p0 cat VBoxPkg/edk2.patch-no_blocking_partition | patch -p0 cat VBoxPkg/edk2.patch-apple | patch -p0 cat VBoxPkg/edk2.patch-rtc | patch -p0 cat VBoxPkg/edk2.patch-mem_acpi | patch -p0 cat VBoxPkg/edk2.patch-idtgdt | patch -p0 Building ======== Edit Cont/target.txt: $ cat Conf/target.txt ACTIVE_PLATFORM = VBoxPkg/VBoxPkgOSE.dsc TARGET = DEBUG TARGET_ARCH = IA32 TOOL_CHAIN_CONF = Conf/tools_def.txt TOOL_CHAIN_TAG = UNIXGCC MAX_CONCURRENT_THREAD_NUMBER = 1 MULTIPLE_THREAD = Disable BUILD_RULE_CONF = Conf/build_rule.txt The make program is called 'build' (edk2\BaseTools\Bin\Win32\build.exe). To start building just execute 'build'. If you have a multicore machine and run into bad build errors, try 'build -n 1' to avoid mixing up errors. For more options try 'build --help'. Running ======= Copy (or symlink) Build\VBoxPkg\DEBUG_MYTOOLS\FV\VBOX.fd to the VirtualBox bin directory as vboxefi.fv. copy e:\edk2\Build\VBoxPkg\DEBUG_MYTOOLS\FV\VBOX.fd e:\vbox\trunk\out\win.x86\debug\bin\VBoxEFI32.fd or kmk_ln -s e:\edk2\Build\VBoxPkg\DEBUG_MYTOOLS\FV\VBOX.fd e:\vbox\trunk\out\win.x86\debug\bin\VBoxEFI32.fd You need to build have a VirtualBox debug build with the following in your Note that these options will not change the VirtualBox behavior only enable the EFI feature. Create a new VM with enabled EFI support. Currently all there is to see is in the log output and debugger. Suggested log setup (debug builds only): set VBOX_LOG=dev_efi.e.l2 set VBOX_LOG_DEST=stderr set VBOX_LOG_FLAGS=unbuffered msprog thread And suggested way of starting the VM: VirtualBox.exe --startvm efi
const { Client } = require('whatsapp-web.js'); const qrcode = require('qrcode-terminal'); const express = require('express'); const bodyParser = require('body-parser'); const axios = require('axios'); const app = express(); const port = process.env.PORT || 8000; app.use(bodyParser.json()); // Criar uma única instância do WhatsApp const client = new Client(); client.on('qr', qr => { console.log(`QR RECEIVED:`); console.log(`QR CODE: ${qr}`); qrcode.generate(qr, { small: true }); }); client.on('ready', () => { console.log('Client is ready!'); }); client.on('message', handleMessage); // Criar uma nova instância do WhatsApp app.post('/new-instance', (req, res) => { return res.status(400).json({ status: 'error', message: 'Instance creation not allowed. Single instance already exists.' }); }); // Enviar mensagem usando a instância única app.post('/send-message', sendMessage); async function sendWebhookMessage(message) { console.log(message); const webhookUrl = 'https://nexusempire.up.railway.app/webhook/webwhatsapp'; try { const response = await axios.post(webhookUrl, { message }); console.log('Webhook message sent successfully', response.data); } catch (error) { console.error('Error sending webhook message:', error.message); } } async function sendWebhookMessageTest(message) { console.log(message); const webhookUrl = 'https://nexusempire.up.railway.app/webhook-test/webwhatsapp'; try { const response = await axios.post(webhookUrl, { message }); console.log('Webhook message sent successfully', response.data); } catch (error) { console.error('Error sending webhook message:', error.message); } } function handleMessage(message) { console.log(`Message received: ${message.body}`); if (message.body.includes("!test")) { sendWebhookMessageTest(message); } else { sendWebhookMessage(message); } } function sendMessage(req, res) { const number = req.body.number; const message = req.body.message; client.sendMessage(`${number}@c.us`, message) .then(response => { res.status(200).json({ status: 'success', response }); }) .catch(err => { res.status(500).json({ status: 'error', response: err }); }); } app.listen(port, () => { console.log('HTTP SERVER RUNNING'); }); // Inicializar a instância única do WhatsApp client.initialize();
<template> <el-card> <el-form :inline="true" class="demo-form-inline"> <el-form-item label="按权限查询"> <el-input v-model="query.permission" placeholder="按权限查询"></el-input> </el-form-item> <el-form-item label="管理员等级"> <el-select v-model="query.mlevel" placeholder="管理员等级"> <el-option label="学校" value="3"></el-option> <el-option label="学院" value="2"></el-option> <el-option label="辅导员" value="1"></el-option> <el-option label="全部" value=""></el-option> </el-select> </el-form-item> <el-form-item> <el-button type="primary" @click="manList">查询</el-button> <el-button type="danger" v-if="ids.length>0" @click="setPers">授权</el-button> </el-form-item> </el-form> <el-upload class="upload-demo" action="/api/manager/importMan" :on-success="(res) => { return uploadSuccess(res); }" multiple> <el-button size="small" type="primary" >点击上传管理员名单</el-button> <div slot="tip" class="el-upload__tip">只能上传excel文件</div> </el-upload> <el-table :data="mans" style="width: 955px" max-height="100%" @selection-change="handleSelectionChange"> <el-table-column type="selection"> </el-table-column> <el-table-column prop="mid" label="编号"> </el-table-column> <el-table-column prop="mname" label="姓名"> </el-table-column> <el-table-column prop="mlevel" label="等级"> </el-table-column> <el-table-column prop="major" label="专业"> </el-table-column> <el-table-column prop="grade" label="年级"> </el-table-column> <el-table-column prop="permission" label="权限"> </el-table-column> </el-table> <el-pagination background @size-change="pageSizeChange" @current-change="pageNoChange" :current-page="query.pageNo" :page-sizes="[10,20]" :page-size="query.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="query.total"> </el-pagination> </el-card> </template> <script> import {manList, setPermissions} from '../../../../api/manList' export default { name: 'whitelist', inject: ['reload'], data () { return { ids: [], mans: [], query: { pageNo: 1, pageSize: 10, total: 0, mlevel: '' }, multipleSelection: [] } }, created () { this.manList() }, methods: { uploadSuccess (res) { console.log(res) // 上传接口返回结果 this.reload() }, manList () { manList(this.query).then(res => { console.info(res) this.mans = res.data.records this.query.total = res.data.total }) }, pageSizeChange (value) { this.query.pageSize = value this.manList() }, pageNoChange (value) { this.query.pageNo = value this.manList() }, toggleSelection (rows) { if (rows) { rows.forEach(row => { this.$refs.multipleTable.toggleRowSelection(row) }) } else { this.$refs.multipleTable.clearSelection() } }, handleSelectionChange (checkedMans) { this.ids = checkedMans.map(man => man.id) }, setPers () { let query = {ids: this.ids} setPermissions(query).then(res => { if (res.status) { this.$message({ message: '授权成功', type: 'success' }) } this.manList() }) } } } </script> <style scoped> .el-main { padding: 0; height: calc(100vh - 70px); margin-left: 300px; margin-right: 300px; } </style>
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; // player moving from side to side public class movement : MonoBehaviour { public float moveSpeed = 5f; public float jumpForce = 10f; private Rigidbody2D rb; private int coinCount = 0; private bool onGround; void Start() { rb = GetComponent<Rigidbody2D>(); UpdateScoreText(); } void Update() { //Left and Right Movement float moveInput = Input.GetAxis("Horizontal"); if (Input.GetKeyDown(KeyCode.D)) { Debug.Log("Pressed the key D"); } if (Input.GetKeyDown(KeyCode.A)) { Debug.Log("Pressed the key A"); } rb.velocity = new Vector2(moveInput * moveSpeed, rb.velocity.y); //Jumping if (Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow) && onGround) { Debug.Log("Pressed the key Jump"); rb.velocity = new Vector2(rb.velocity.x, jumpForce); } } void FixedUpdate() { // Check if the player is grounded RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, 0.1f); onGround = (hit.collider != null); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.tag == "coin") { Debug.Log("Get a coin"); coinCount++; UpdateScoreText(); Destroy(collision.gameObject); if (coinCount == 10) { SceneManager.LoadSceneAsync("EndScreen"); } } } void UpdateScoreText() { GameObject.Find("Number (1)").GetComponent<Text>().text = coinCount.ToString(); Debug.Log("Coin number increase"); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Enemy : MonoBehaviour { //引用 protected Player player; protected Transform playerTrans; protected Vector3 playerLastPos; protected Rigidbody2D rigid; //属性 protected bool follow; public float speed; public float HP; public int reward; protected RaycastHit2D hit; protected float curHP; protected LayerMask layerMask; public bool isBoss; //资源 public GameObject[] bloodGos;//血迹 public GameObject bloodDeadGo; public GameObject bloodParticle; public GameObject explosion; // Start is called before the first frame update protected virtual void Start() { player = GameManager.Instance.player; if (player==null) { return; } playerTrans = player.transform; player.enemyList.Add(this); curHP = HP; rigid = GetComponent<Rigidbody2D>(); layerMask = ~(1 << 10) & ~(1 << 2); } // Update is called once per frame protected virtual void Update() { if (playerTrans==null) { return; } hit = Physics2D.Raycast(transform.position,playerTrans.position-transform.position ,4,layerMask); SearchAndFollowPlayer(); Move(); } /// <summary> /// 搜索跟随玩家 /// </summary> protected void SearchAndFollowPlayer() { if (follow&&Vector3.Distance(playerLastPos,transform.position)<=0.1f) { follow = false; } if (hit.collider!=null) { if (!hit.collider.gameObject.CompareTag("Wall")) { LookAtPlayerAndAttack(); } else if (follow) { Vector3 moveDirection = playerLastPos - transform.position; if (moveDirection != Vector3.zero) { float angle = Mathf.Atan2(-moveDirection.x, moveDirection.y) * Mathf.Rad2Deg; transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward); } } } else if (follow) { Vector3 moveDirection = playerLastPos - transform.position; if (moveDirection != Vector3.zero) { float angle = Mathf.Atan2(-moveDirection.x, moveDirection.y) * Mathf.Rad2Deg; transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward); } } } /// <summary> /// 移动 /// </summary> protected void Move() { if (hit.collider!=null) { if (hit.collider.CompareTag("Player")) { rigid.AddRelativeForce(new Vector2(0,speed)); } } if (follow) { rigid.AddRelativeForce(new Vector2(0,speed*0.5f)); } } /// <summary> /// 看向玩家并攻击 /// </summary> protected virtual void LookAtPlayerAndAttack() { Vector3 moveDirection = playerTrans.transform.position - transform.position; if (moveDirection != Vector3.zero) { float angle = Mathf.Atan2(-moveDirection.x, moveDirection.y) * Mathf.Rad2Deg; transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward); follow = true; playerLastPos = playerTrans.position; } } /// <summary> /// 触发检测 /// </summary> /// <param name="collision"></param> protected void OnTriggerEnter2D(Collider2D collision) { if (collision.CompareTag("Bullet")) { Instantiate(bloodParticle,transform.position,Quaternion.Euler(0,0, collision.transform.rotation.eulerAngles.z+180)); if (collision.gameObject.name.Contains("0")) { curHP -= 8 * GameManager.Instance.gunLevel * 0.5f; Instantiate(bloodGos[0], transform.position, Quaternion.Euler(0, 0, collision.transform.rotation.eulerAngles.z + Random.Range(-15, 15))); } if (collision.gameObject.name.Contains("1")) { curHP -= 70; Instantiate(bloodGos[1], transform.position, Quaternion.Euler(0, 0, collision.transform.rotation.eulerAngles.z)); } if (collision.gameObject.name.Contains("2")) { curHP -= 15; Instantiate(bloodGos[0], transform.position, Quaternion.Euler(0, 0, collision.transform.rotation.eulerAngles.z + Random.Range(-20, 20))); } if (collision.gameObject.name.Contains("3")) { curHP -= 30; Instantiate(bloodGos[2], transform.position, Quaternion.Euler(0, 0, collision.transform.rotation.eulerAngles.z)); } rigid.AddRelativeForce(new Vector2(0,-player.playerShooting.repulsion)); } if (collision.CompareTag("Mine")) { Instantiate(explosion,transform.position,Quaternion.identity); curHP -= 60; Destroy(collision.gameObject); } Die(); } /// <summary> /// 死亡 /// </summary> protected virtual void Die() { if (curHP<=0) { if (isBoss) { player.bossIsDead = true; } Instantiate(bloodDeadGo, transform.position, transform.rotation); GameManager.Instance.player.curKills += 1; GameManager.Instance.money += reward; player.enemyList.Remove(this); Destroy(gameObject); } } /// <summary> /// 僵尸攻击方法 /// </summary> /// <param name="collision"></param> protected void OnCollisionStay2D(Collision2D collision) { if (collision.gameObject.CompareTag("Player")) { player.HP -= 0.5f; player.LimitHP(); player.delayTimer = player.delayRegen; player.Die(); } } }
import os from scipy.special import erfc import sklearn import numpy as np import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt # 数据准备 (X_train_full, y_train_full), (X_test, y_test) = keras.datasets.fashion_mnist.load_data() X_train_full = X_train_full / 255.0 X_test = X_test / 255.0 X_valid, X_train = X_train_full[:5000], X_train_full[5000:] y_valid, y_train = y_train_full[:5000], y_train_full[5000:] # 使用批量归一化层 ''' 该操作对每个输入零中心并归一化,然后每层使用两个新的参数向量 缩放和偏移其结果:一个用于缩放,另一个用于偏移。换句话说,该操作可以使模型学习 各层输入的最佳缩放和均值。在许多情况下,如果你将BN层添加为神经网络的第一层, 则无须归一化训练集(例如,使用StandardScaler);BN层会为你完成此操作(因为它一 次只能查看一个批次,它还可以重新缩放和偏移每个输入特征) ''' model = keras.models.Sequential([ keras.layers.Flatten(input_shape=[28, 28]), keras.layers.BatchNormalization(), keras.layers.Dense(300, activation="relu"), keras.layers.BatchNormalization(), keras.layers.Dense(100, activation="relu"), keras.layers.BatchNormalization(), keras.layers.Dense(10, activation="softmax") ]) bn1 = model.layers[1] print([(var.name, var.trainable) for var in bn1.variables]) print(bn1.updates) model.compile(loss="sparse_categorical_crossentropy", optimizer=keras.optimizers.SGD(lr=1e-3), metrics=["accuracy"]) history = model.fit(X_train, y_train, epochs=10, validation_data=(X_valid, y_valid)) ''' 有时,在激活函数工作得更好之前应用BN(关于这个话题存在争议)。 此外,“BatchNormalization”层之前的层不需要有偏差项, 因为“BatchNormalization”层也有偏差项,这会浪费参数, 所以在创建这些层时可以设置“use_bias=False”: ''' model = keras.models.Sequential([ keras.layers.Flatten(input_shape=[28, 28]), keras.layers.BatchNormalization(), keras.layers.Dense(300, use_bias=False), keras.layers.BatchNormalization(), keras.layers.Activation("relu"), # "relu" tf.nn.relu \tf.nn.elu ...... keras.layers.Dense(100, use_bias=False), keras.layers.BatchNormalization(), keras.layers.Activation("relu"), keras.layers.Dense(10, activation="softmax") ]) model.compile(loss="sparse_categorical_crossentropy", optimizer=keras.optimizers.SGD(lr=1e-3), metrics=["accuracy"]) history = model.fit(X_train, y_train, epochs=10, validation_data=(X_valid, y_valid)) print(np.argmax(model.predict(X_test[:3]), axis=-1)) # [9 2 1]
package main import ( "fmt" "log/slog" "net/http" "runtime/debug" "strings" "bbccdd/internal/response" "bbccdd/internal/validator" ) func (app *application) reportServerError(r *http.Request, err error) { var ( message = err.Error() method = r.Method url = r.URL.String() trace = string(debug.Stack()) ) requestAttrs := slog.Group("request", "method", method, "url", url) app.logger.Error(message, requestAttrs, "trace", trace) } func (app *application) errorMessage(w http.ResponseWriter, r *http.Request, status int, message string, headers http.Header) { message = strings.ToUpper(message[:1]) + message[1:] err := response.JSONWithHeaders(w, status, map[string]string{"Error": message}, headers) if err != nil { app.reportServerError(r, err) w.WriteHeader(http.StatusInternalServerError) } } func (app *application) serverError(w http.ResponseWriter, r *http.Request, err error) { app.reportServerError(r, err) message := "The server encountered a problem and could not process your request" app.errorMessage(w, r, http.StatusInternalServerError, message, nil) } func (app *application) notFound(w http.ResponseWriter, r *http.Request) { message := "The requested resource could not be found" app.errorMessage(w, r, http.StatusNotFound, message, nil) } func (app *application) methodNotAllowed(w http.ResponseWriter, r *http.Request) { message := fmt.Sprintf("The %s method is not supported for this resource", r.Method) app.errorMessage(w, r, http.StatusMethodNotAllowed, message, nil) } func (app *application) badRequest(w http.ResponseWriter, r *http.Request, err error) { app.errorMessage(w, r, http.StatusBadRequest, err.Error(), nil) } func (app *application) failedValidation(w http.ResponseWriter, r *http.Request, v validator.Validator) { err := response.JSON(w, http.StatusUnprocessableEntity, v) if err != nil { app.serverError(w, r, err) } } func (app *application) invalidAuthenticationToken(w http.ResponseWriter, r *http.Request) { headers := make(http.Header) headers.Set("WWW-Authenticate", "Bearer") app.errorMessage(w, r, http.StatusUnauthorized, "Invalid authentication token", headers) } func (app *application) authenticationRequired(w http.ResponseWriter, r *http.Request) { app.errorMessage(w, r, http.StatusUnauthorized, "You must be authenticated to access this resource", nil) }
package AdvanceDataStructure; import java.util.Arrays; public class RangeUpdateSegmentTree { private int[] segmentTree; private int[] lazy; private int[] nums; public RangeUpdateSegmentTree(int[] nums) { this.nums = nums; int n = nums.length; // The size of the segment tree is at most 2 * n - 1 int treeSize = 2 * (int) Math.pow(2, Math.ceil(Math.log(n) / Math.log(2))) - 1; this.segmentTree = new int[treeSize]; this.lazy = new int[treeSize]; buildSegmentTree(0, 0, n - 1); } private void buildSegmentTree(int index, int start, int end) { if (start == end) { segmentTree[index] = nums[start]; return; } int mid = start + (end - start) / 2; buildSegmentTree(2 * index + 1, start, mid); buildSegmentTree(2 * index + 2, mid + 1, end); segmentTree[index] = segmentTree[2 * index + 1] + segmentTree[2 * index + 2]; } public void rangeUpdate(int updateStart, int updateEnd, int value) { rangeUpdate(0, 0, nums.length - 1, updateStart, updateEnd, value); } private void rangeUpdate(int index, int start, int end, int updateStart, int updateEnd, int value) { // Update lazy value for current node if (lazy[index] != 0) { segmentTree[index] += (end - start + 1) * lazy[index]; // Propagate the lazy update to children if (start != end) { lazy[2 * index + 1] += lazy[index]; lazy[2 * index + 2] += lazy[index]; } // Reset lazy update for current node lazy[index] = 0; } // No overlap if (start > updateEnd || end < updateStart) { return; } // Complete overlap if (updateStart <= start && updateEnd >= end) { segmentTree[index] += (end - start + 1) * value; // Propagate the lazy update to children if (start != end) { lazy[2 * index + 1] += value; lazy[2 * index + 2] += value; } return; } // Partial overlap, update both children int mid = start + (end - start) / 2; rangeUpdate(2 * index + 1, start, mid, updateStart, updateEnd, value); rangeUpdate(2 * index + 2, mid + 1, end, updateStart, updateEnd, value); segmentTree[index] = segmentTree[2 * index + 1] + segmentTree[2 * index + 2]; } public int rangeQuery(int queryStart, int queryEnd) { return rangeQuery(0, 0, nums.length - 1, queryStart, queryEnd); } private int rangeQuery(int index, int start, int end, int queryStart, int queryEnd) { // Update lazy value for current node if (lazy[index] != 0) { segmentTree[index] += (end - start + 1) * lazy[index]; // Propagate the lazy update to children if (start != end) { lazy[2 * index + 1] += lazy[index]; lazy[2 * index + 2] += lazy[index]; } // Reset lazy update for current node lazy[index] = 0; } // No overlap if (start > queryEnd || end < queryStart) { return 0; } // Complete overlap if (queryStart <= start && queryEnd >= end) { return segmentTree[index]; } // Partial overlap, query both children int mid = start + (end - start) / 2; int leftSum = rangeQuery(2 * index + 1, start, mid, queryStart, queryEnd); int rightSum = rangeQuery(2 * index + 2, mid + 1, end, queryStart, queryEnd); return leftSum + rightSum; } public static void main(String[] args) { int[] nums = { 1, 3, 5, 7, 9, 11 }; RangeUpdateSegmentTree segmentTree = new RangeUpdateSegmentTree(nums); System.out.println("Original Array: " + Arrays.toString(nums)); int updateStart = 1; int updateEnd = 4; int updateValue = 2; segmentTree.rangeUpdate(updateStart, updateEnd, updateValue); System.out .println("Array after range update [" + updateStart + ", " + updateEnd + "] by " + updateValue + ": " + Arrays.toString(nums)); int queryStart = 1; int queryEnd = 4; int sum = segmentTree.rangeQuery(queryStart, queryEnd); System.out.println("Sum of elements in the range [" + queryStart + ", " + queryEnd + "]: " + sum); } }
"use client"; //The root component for each baySide containing all the info about the viz import WeatherTable from "./weatherTable"; import { useEffect, useState } from "react"; import { BaySide, RawWeatherData, RawTideData, RawSwellData } from "./types"; import LoadingSpinner from "./loadingSpinner"; import VideoViewer from "./videoViewer"; export default function VizIndicator(side: BaySide) { const [weatherData, setWeatherData] = useState<RawWeatherData | null>(null); const [tideData, setTideData] = useState<RawTideData | null>(null); const [swellData, setSwellData] = useState<RawSwellData | null>(null); useEffect(() => { fetchWeatherData(side) .then(({ data }) => { setWeatherData(data); }) .catch((error) => { console.error(error); }); fetchTideData(side) .then(({ data }) => { setTideData(data); }) .catch((error) => { console.error(error); }); fetchSwellData(side) .then((data) => { setSwellData(data); }) .catch((error) => { console.error(error); }); }, [side]); return ( <div className="overflow-x-auto"> {weatherData && tideData && swellData ? ( <WeatherTable //@ts-ignore weatherData={weatherData.properties.timeseries} tideData={tideData} //@ts-ignore swellData={swellData} /> ) : ( <p> <LoadingSpinner /> </p> )} <VideoViewer side={side} /> </div> ); } async function fetchWeatherData(side: BaySide) { try { const queryParams = new URLSearchParams(side).toString(); const response = await fetch(`/api?${queryParams}`, { method: "GET", }); if (!response.ok) { throw new Error("Failed to fetch data"); } const data = await response.json(); return data; } catch (error) { console.error("Error:", error); throw error; } } async function fetchTideData(side: BaySide) { try { const queryParams = new URLSearchParams(side).toString(); const response = await fetch(`/api/tideData?${queryParams}`, { method: "GET", }); if (!response.ok) { throw new Error("Failed to fetch data"); } const data = await response.json(); return data; } catch (error) { console.error("Error:", error); throw error; } } async function fetchSwellData(side: BaySide) { try { const queryParams = new URLSearchParams(side).toString(); const response = await fetch(`/api/swellData?${queryParams}`, { method: "GET", }); if (!response.ok) { throw new Error("Failed to fetch data"); } const data = await response.json(); return data; } catch (error) { console.error("Error:", error); throw error; } }
<script> import { loading, toast } from "$lib/store"; import { onMount } from "svelte"; import { db } from "$lib/db"; import { t } from "$lib/lang"; import { fnSelect } from "$lib/ui/fnSelect"; import { fnModal } from "floeui/dist/directives"; /** * @type {import("pocketbase").ListResult<import("pocketbase").RecordModel>} */ let collections; /** * @type {string | any[]} */ let selections = []; let columns = []; /** * @type {any} */ let modal; onMount(async () => { await refresh(); }); async function refresh() { $loading = true; collections = await db.collection("audits").getList(1, 500, { filter: `template.id="indeks_kami_4_2"`, // filter: `auditsDetails(question).score~"0"`, // filter: `auditsDetails(question).audit="fojf8eguh7na8et"`, expand: "organization,auditee,auditor", sort: "-created", requestKey: "ikami", }); setTimeout(() => ($loading = false), 500); } async function submit() { $loading = true; try { const data = { template: modal.template, question: modal.id, answer: modal.answer, score: modal.score, media: modal.file ? [...modal.file] : undefined, }; console.log(data, modal); if (!modal.aid) { await db.collection("auditsDetails").create(data); } else { await db.collection("auditsDetails").update(modal.aid, data); } $toast = [{ action: $t("action.saved") }]; } catch (/** @type {any} */ e) { /// console.log(e); $toast = [{ error: e?.data }]; } modal = false; refresh(); } </script> <div modal use:fnModal={modal} on:close={() => (modal = false)}> <div w-5xl max-w-full> <button modal-close on:click={() => (modal = false)}> &times; </button> {#if modal} <form on:submit|preventDefault={submit}> <h1 text-lg mb-3>{modal.question} ({modal.score})</h1> <div h-80vh overflow-auto> <p pb-5>{modal.hint}</p> <div grid grid-cols-1 gap-5> <div form-control max-w-full> <span>Opsi Penilaian</span> <div use:fnSelect={modal.options}> <textarea input filter placeholder="Pilih Opsi" min-h-8 rounded-box /> <input type="hidden" selected bind:value={modal.score} /> <div relative w-full> <ul menu top-0 hidden absolute bg-base h-48 z-10 overflow-auto rounded-box shadow > <li option> <label flex gap-2 cursor-pointer> <input type="checkbox" checkbox shrink-0 tabindex="-1" /> <div option-label /> </label> </li> </ul> </div> </div> </div> <div form-control max-w-full> <span>Keterangan</span> <textarea input bind:value={modal.answer} rows="3" h-auto rounded-box /> </div> <div form-control max-w-full> <input type="file" input bind:files={modal.file} multiple /> <div> <div carousel w-full rounded-box min-h-40vh border> {#each modal.media as media} <div> <iframe src={db.files.getUrl(modal, media)} title="SS" /> </div> {/each} </div> </div> </div> </div> <!-- <p whitespace-pre-wrap> {JSON.stringify(modal, null, 2)} </p> --> </div> <div> <button btn="~ primary"> <i class:i-bx-save={!$loading} class:i-bx-refresh={$loading} class:animate-spin={$loading} /> {$t("save.btn")} </button> </div> </form> {/if} </div> </div> <div> <div sticky top-0 z-10 bg-base-a pt-15 pb-3> <div flex gap-5> <h1 text-xl>{$t("audit.indekskami.title")}</h1> <button on:click={refresh} btn="~ sm circle outline" aria-label="Refresh" p-.5 > <i i-bx-refresh animate-reverse class:animate-spin={$loading} /> </button> </div> <div> <div flex> <button btn="~ xs">{$t("all.info")}</button> </div> </div> </div> <div bg-base min-h-70vh relative> {#if $loading} <div absolute top-0 z-20 w-full h-2 bg-neutral animate-pulse animate-count-infinite /> {/if} <div> <table table w-full class:opacity-50={$loading}> <thead> <tr children-bg-base-b sticky top-0> <th sticky left-0 w-1 aria-label="Checkbox" h-15> <input type="checkbox" checkbox checked={selections.length == collections?.items.length} on:click={() => selections.length == collections?.items.length ? (selections = []) : (selections = collections?.items)} /> </th> <th /> <th>Ruang Lingkup</th> <th>Organisasi</th> <th>Auditee</th> <th>Auditor</th> </tr> </thead> <tbody> {#each collections?.items || [] as item} <tr> <td sticky left-0> <input type="checkbox" bind:group={selections} checkbox value={item} /> </td> <td> <a href={"./detail?" + item.id} btn="~ sm"> <i i-bx-detail /> </a> </td> <td> <div>{@html item.scope}</div> </td> <td> {item?.expand?.organization?.name} </td> <td> {#each item?.expand?.auditee || [] as auditee} <div underline> {auditee.name} </div> {/each} </td> <td> {#each item?.expand?.auditor || [] as auditor} <div underline> {auditor.name} </div> <!-- {JSON.stringify(auditee)} --> {/each} </td> </tr> {/each} </tbody> </table> </div> </div> </div>
package br.com.fiap.postech.techchallenge.application.usecase; import br.com.fiap.postech.techchallenge.application.domain.Pedido; import br.com.fiap.postech.techchallenge.application.domain.StatusPedido; import br.com.fiap.postech.techchallenge.application.exception.DominioException; import br.com.fiap.postech.techchallenge.application.port.inbound.PagarPedidoUseCasePort; import br.com.fiap.postech.techchallenge.application.port.outbound.PedidoRepositoryAdapterPort; import br.com.fiap.postech.techchallenge.application.port.outbound.SecurityContextAdapterPort; import java.util.Objects; public class PagarPedidoUseCase implements PagarPedidoUseCasePort { private final PedidoRepositoryAdapterPort pedidoRepositoryAdapterPort; private final SecurityContextAdapterPort securityContextAdapterPort; public PagarPedidoUseCase( PedidoRepositoryAdapterPort pedidoRepositoryAdapterPort, SecurityContextAdapterPort securityContextAdapterPort ) { this.pedidoRepositoryAdapterPort = pedidoRepositoryAdapterPort; this.securityContextAdapterPort = securityContextAdapterPort; } @Override public Pedido executar(Long id) { Pedido pedido = pedidoRepositoryAdapterPort.obterPorId(id); if (pedido == null || (!Objects.equals(pedido.getStatus(), StatusPedido.RECEBIDO) || !Objects.equals(pedido.getCliente().getId(), this.securityContextAdapterPort.obterClienteAutenticado().getId()))) { String mensagem = String.format("Pedido %s não encontrado.", id); throw new DominioException(mensagem); } pedido.setStatus(StatusPedido.PAGAMENTO_CONFIRMADO); return pedidoRepositoryAdapterPort.salvar(pedido); } }
import { DriversRouter } from "@drivers/interfaces"; import { UsersRouter } from "@users/interfaces/http"; import { v4 as uuidV4 } from "uuid"; import express, { NextFunction, Request, Response } from "express"; class App { expressApp: express.Application; constructor() { this.expressApp = express(); this.mountMiddlewares(); this.mountHealthCheck(); this.mountRoutes(); } mountMiddlewares(): void { this.expressApp.use(express.json()); this.expressApp.use(express.urlencoded({ extended: true })); this.expressApp.use((req: Request, res: Response, next: NextFunction) => { req.traceId = uuidV4(); next(); }); } mountRoutes(): void { this.expressApp.use("/users", new UsersRouter().expressRouter); this.expressApp.use("/drivers", new DriversRouter().expressRouter); } mountHealthCheck(): void { this.expressApp.get("/", (req: Request, res: Response) => { res.send("All is good!"); }); this.expressApp.get("/healtcheck", (req: Request, res: Response) => { res.send("All is good!"); }); } } export default new App().expressApp;
sum_group_n <- length(unique(sum_bar_data$group)) sum_legend_title <- paste(toTitleCase(gsub("_"," ",protocol)),"\n",toTitleCase(splice)," ",spikein,"\nNormalised\n",feature,sep="") sum_pie_data$Label <- ifelse(sum_pie_data$Numbers > 0,as.character(sum_pie_data$Numbers),NA) i_group_levels <- unlist(lapply(i_group,function(i) {gsub("exonic ","exonic\n",toTitleCase(gsub("_"," ",ifelse(i=="","All",i))))} ) ) sum_pie_data$group <- factor(sum_pie_data$group, levels=i_group_levels) sum_pie <- ggplot(data = sum_pie_data, aes(x=group, y=Numbers, fill=fct_inorder(Category))) + geom_bar(position="fill",stat="identity", colour="black") + scale_fill_manual(sum_legend_title,values=sum_pie_data$Colours) + scale_x_discrete(breaks=sum_pie_data$group) + scale_y_continuous(labels=scales::percent) + xlab("") + ylab("Percentage") + geom_text_repel( data = sum_pie_data, mapping = aes(y=pos, label=fct_inorder(Label)), size=2.5, # color="black", color="white", fontface=1, bg.color="black", bg.r=0.15, force=0, force_pull=Inf, max.overlaps=Inf ) + theme( panel.background=element_rect(fill="White",colour="white"), strip.text=element_text(face="bold"), strip.background=element_rect(colour="white",fill="white",linewidth=0.1), legend.background=element_rect(fill="White"), legend.key=element_rect(colour="white",fill="White"), legend.title=element_text(size=9), axis.text = element_text(colour="black"), axis.text.x = if (sum_group_n > 3) (element_text(angle = 45, vjust = 1, hjust=1)) else (element_text()), axis.line=element_line(colour="black",linewidth=0.5), axis.title.x=element_blank(), axis.title.y = element_text(size=9) ) bar_cond <- sum_bar_data$condition names(bar_cond) <- sum_bar_data$condition bar_max <- (max(sum_bar_data$mean) + max(sum_bar_data$SD)) bar_min <- (min(sum_bar_data$mean) - max(sum_bar_data$SD)) bar_brks <- signif(c(0,1,bar_max),2) sum_bar_data$Colours <- condition_col[match(bar_cond,names(condition_col))] sum_bar_data$group <- factor(sum_bar_data$group, levels=i_group_levels) sum_bar_data$condition <- factor(sum_bar_data$condition,levels=c(control,treat)) sum_bar <- ggplot(data = sum_bar_data, aes(fill=condition, y=mean, x = group)) + geom_col(width=0.6,position=position_dodge(0.7),colour = "black") + geom_errorbar(aes(ymin=SD_min,ymax=mean+SD),width=0.3,position=position_dodge(0.7)) + scale_fill_manual(sum_legend_title,values=condition_col) + scale_x_discrete(breaks=sum_bar_data$group) + scale_y_continuous(limits=c(0,bar_max),breaks=c(0,bar_brks)) + geom_hline( yintercept=1, alpha=0.3, linetype=5 ) + ylab(paste("Total",toTitleCase(difference))) + theme( panel.background=element_rect(fill="White",colour="white"), strip.text=element_text(face="bold"), strip.background=element_rect(colour="white",fill="white",linewidth=0.1), legend.background=element_rect(fill="White"), legend.key=element_rect(colour="white",fill="White"), legend.title=element_text(size=9), axis.text = element_text(colour="black"), axis.text.x = if (sum_group_n > 3) (element_text(angle = 45, vjust = 1, hjust=1)) else (element_text()), axis.line=element_line(colour="black",linewidth=0.5), axis.title.x=element_blank(), axis.title.y = element_text(size=9) ) sum_violin_data$group <- factor(sum_violin_data$group, levels=i_group_levels) sum_violin_data$condition <- factor(sum_violin_data$condition, levels=c(control,treat)) if (difference=="expression levels") { violin_ymax <- 10^(log10(abs(max(sum_violin_data$value)))^1.2) violin_p_y <- (abs(max(sum_violin_data$value)))^1.1 } else { violin_ymax <- max(sum_violin_data$value) + 0.2*abs(max(sum_violin_data$value)-min(sum_violin_data$value)) violin_p_y <- max(sum_violin_data$value) + 0.1*abs(max(sum_violin_data$value)-min(sum_violin_data$value)) } test_p_i <- compare_means(formula=value ~ condition, data = sum_violin_data, group.by="group", comparisons = compare, method="t.test", paired = TRUE) test_p_i$y.position <- c(violin_p_y) sum_violin <- ggplot(data = sum_violin_data, aes(x=group, group=interaction(group,condition), y=value)) + geom_violin(trim=TRUE,aes(fill=condition),scale="width",width=0.7) + stat_pvalue_manual(data = test_p_i, x="group", label = "p.signif",inherit.aes=F) + scale_fill_manual(sum_legend_title,values=condition_col ) + geom_boxplot(width=0.1,position=position_dodge(0.7)) + scale_x_discrete(breaks=sum_violin_data$group) + geom_hline( yintercept=1, alpha=0.3, linetype=5 ) + ylab(paste(toTitleCase(difference))) + theme( panel.background=element_rect(fill="White",colour="white"), strip.text=element_text(face="bold"), strip.background=element_rect(colour="white",fill="white",linewidth=0.1), legend.background=element_rect(fill="White"), legend.key=element_rect(colour="white",fill="White"), legend.title=element_text(size=9), axis.text = element_text(colour="black"), axis.text.x = if (sum_group_n > 3) (element_text(angle = 45, vjust = 1, hjust=1)) else (element_text()), axis.line=element_line(colour="black",linewidth=0.5), axis.title.x=element_blank(), axis.title.y = element_text(size=9) ) if (difference=="expression levels") { violin_ymin <- min(sum_violin_data$value[!is.infinite(log10(sum_violin_data$value))]) sum_violin <- sum_violin + scale_y_log10(limits = c(violin_ymin, violin_ymax),breaks=c("1x"=1)) } else { sum_violin <- sum_violin + scale_y_continuous(limits = c(0, violin_ymax),breaks=c("1x"=1)) } overview <- ggarrange(plotlist=list(sum_pie,sum_bar,sum_violin),ncol=1,nrow=3,labels="AUTO")
import React from "react"; import { BrowserRouter, Route, Routes } from "react-router-dom"; import Navbar from "./components/Navbar"; import MainPage from "./pages/MainPage"; import AuthPage from "./pages/AuthPage"; import DesktopPage from "./pages/DesktopPage"; import MvpPage from "./pages/MvpPage"; import LabPage from "./pages/LabPage"; function Router() { return ( <BrowserRouter> <Navbar /> <Routes> <Route path="/" element={<MainPage />} /> <Route path="/auth" element={<AuthPage />} /> <Route path="/desktop" element={<DesktopPage />} /> <Route path="/mvp" element={<MvpPage />} /> <Route path="/lab" element={<LabPage />} /> </Routes> </BrowserRouter> ); } export default Router;
// Author : $Author$ // Version: $Revision$ // Date : $Date$ // Url : $URL$ // Copyright: (C) 2012-2013 Gregor Cramer // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. #include "T_AhoCorasick.h" #include "m_string.h" #include "m_vector.h" #include "m_chunk_allocator.h" #include "m_algorithm.h" #include "m_utility.h" #include "m_assert.h" #include <stdlib.h> using namespace TeXt; namespace { typedef mstl::string::value_type Alpha; class Node; struct Edge { Edge(Alpha alpha, Node* next) :m_alpha(alpha), m_next(next) {} Alpha m_alpha; Node* m_next; bool operator==(Alpha alpha) const { return m_alpha == alpha; } bool operator< (Alpha alpha) const { return m_alpha < alpha; } static int compare(void const* lhs, void const* rhs); }; static inline bool operator<(Alpha alpha, Edge const& edge) { return alpha < edge.m_alpha; } int Edge::compare(void const* lhs, void const* rhs) { return int(static_cast<Edge const*>(lhs)->m_alpha) - int(static_cast<Edge const*>(rhs)->m_alpha); } struct Match { Match() :m_index(0), m_length(0), m_tag(0) {} Match(unsigned index, unsigned length, unsigned tag) :m_index(index), m_length(length), m_tag(tag) {} unsigned m_index; unsigned m_length; unsigned m_tag; }; struct Node { typedef mstl::vector<Edge> Edges; typedef mstl::vector<Match> Indices; typedef mstl::vector<Alpha> Alphas; typedef mstl::vector<Node*> Pool; typedef mstl::chunk_allocator<Node> Allocator; Node(); Node* createNext(Allocator& allocator, Pool& pool, Alpha alpha); void unionMatches(); void sortEdges(); void traverse(); void traverse(Node* root, Alphas& alphas); void setFailure(Node* root, Alphas const& alphas); Node* findNext(Alpha alpha); Node* findNextFast(Alpha alpha); bool m_isFinal; Node* m_failureNode; unsigned m_depth; Edges m_outgoing; Indices m_indices; unsigned m_tag; }; Node::Node() :m_isFinal(false) ,m_failureNode(0) ,m_depth(0) ,m_tag(0) { } Node* Node::findNext(Alpha alpha) { M_ASSERT(alpha); Edges::iterator i = mstl::find(m_outgoing.begin(), m_outgoing.end(), alpha); return i == m_outgoing.end() ? 0 : i->m_next; } Node* Node::findNextFast(Alpha alpha) { M_ASSERT(alpha); Edges::iterator i = mstl::binary_search(m_outgoing.begin(), m_outgoing.end(), alpha); return i == m_outgoing.end() ? 0 : i->m_next; } Node* Node::createNext(Allocator& allocator, Pool& pool, Alpha alpha) { M_ASSERT(alpha); Node* next = findNext(alpha); if (next == 0) { pool.push_back(next = allocator.alloc()); next->m_depth = m_depth + 1; m_outgoing.push_back(Edge(alpha, next)); } return next; } void Node::sortEdges() { ::qsort(m_outgoing.begin(), m_outgoing.size(), sizeof(Edges::value_type), Edge::compare); } void Node::unionMatches() { Node* node = this; while ((node = node->m_failureNode)) { m_indices.insert(m_indices.end(), node->m_indices.begin(), node->m_indices.end()); if (node->m_isFinal) m_isFinal = true; } } void Node::setFailure(Node* root, Alphas const& alphas) { M_ASSERT(alphas.size() > m_depth); m_failureNode = root; for (unsigned i = 1; i < m_depth; ++i) { Node* node = root; for (unsigned j = i; j < m_depth && node; ++j) node = node->findNext(alphas[j]); if (node) { m_failureNode = node; return; } } } void Node::traverse(Node* root, Alphas& alphas) { if (alphas.size() <= m_depth) alphas.resize(mstl::mul2(alphas.size())); for (unsigned i = 0; i < m_outgoing.size(); ++i) { Node* next = m_outgoing[i].m_next; alphas[m_depth] = m_outgoing[i].m_alpha; next->setFailure(root, alphas); next->traverse(root, alphas); } } void Node::traverse() { Alphas alphas; alphas.resize(100); traverse(this, alphas); } } // namespace class AhoCorasick::Impl { public: Impl(); bool add(mstl::string const& pattern, unsigned tag); void prepareSearch(); bool search(AhoCorasick& base, mstl::string const& text, Method method); char const* findTag(AhoCorasick& base, char const* text, unsigned& tag); private: typedef mstl::vector<Match> Matches; typedef Node::Allocator Allocator; typedef Node::Pool Pool; Node* m_root; Node* m_current; unsigned m_basePosition; unsigned m_countPatterns; Allocator m_allocator; Pool m_pool; }; AhoCorasick::Impl::Impl() :m_root(0) ,m_current(0) ,m_basePosition(0) ,m_countPatterns(0) ,m_allocator(65536) { m_pool.push_back(m_current = m_root = m_allocator.alloc()); } bool AhoCorasick::Impl::add(mstl::string const& pattern, unsigned tag) { bool multipleMatches = false; if (!pattern.empty()) { Node* node = m_root; for (unsigned i = 0; i < pattern.size(); i++) node = node->createNext(m_allocator, m_pool, pattern[i]); node->m_isFinal = true; node->m_indices.push_back(Match(m_countPatterns, pattern.size(), tag)); if (node->m_indices.size() > 1) multipleMatches = true; } ++m_countPatterns; return multipleMatches; } void AhoCorasick::Impl::prepareSearch() { m_root->traverse(); for (unsigned i = 0; i < m_pool.size(); ++i) { Node* node = m_pool[i]; node->unionMatches(); node->sortEdges(); } } bool AhoCorasick::Impl::search(AhoCorasick& base, mstl::string const& text, Method method) { unsigned position = 0; bool matchFound = false; while (position < text.size()) { Node* next = m_current->findNextFast(text[position]); if (next) { m_current = next; if (m_current->m_isFinal) { M_ASSERT(!m_current->m_indices.empty()); matchFound = true; switch (method) { case LongestMatchOnly: { Match match; for (unsigned i = 0; i < m_current->m_indices.size(); ++i) { Match const& m = m_current->m_indices[i]; if (m.m_length > match.m_length) match = m; } base.match(position + m_basePosition, match.m_index, match.m_length); break; } case AllMatches: for (unsigned i = 0; i < m_current->m_indices.size(); ++i) { Match const& match = m_current->m_indices[i]; base.match(position + m_basePosition, match.m_index, match.m_length); } break; case AnyMatch: { Match const& match = m_current->m_indices[0]; base.match(position + m_basePosition, match.m_index, match.m_length); m_basePosition += position; return true; } } } ++position; } else if (m_current->m_failureNode) { m_current = m_current->m_failureNode; } else { ++position; } } m_basePosition += position; return matchFound; } char const* AhoCorasick::Impl::findTag(AhoCorasick& base, char const* text, unsigned& tag) { m_current = m_root; while (*text) { Node* next = m_current->findNextFast(*text); if (next == 0) break; m_current = next; ++text; } if (m_current->m_isFinal) { M_ASSERT(!m_current->m_indices.empty()); Match match; for (unsigned i = 0; i < m_current->m_indices.size(); ++i) { Match const& m = m_current->m_indices[i]; if (m.m_length > match.m_length) match = m; } tag = match.m_tag; return text; } return 0; } AhoCorasick::AhoCorasick() :m_impl(new Impl) ,m_isPrepared(false) { } AhoCorasick::~AhoCorasick() { delete m_impl; } bool AhoCorasick::isPrepared() const { return m_isPrepared; } bool AhoCorasick::add(mstl::string const& pattern) { M_REQUIRE(!isPrepared()); return m_impl->add(pattern, 0); } bool AhoCorasick::add(mstl::string const& pattern, unsigned tag) { M_REQUIRE(!isPrepared()); M_REQUIRE(tag != 0); return m_impl->add(pattern, tag); } bool AhoCorasick::search(mstl::string const& text, Method method) { if (!m_isPrepared) { m_isPrepared = true; m_impl->prepareSearch(); } return m_impl->search(*this, text, method); } char const* AhoCorasick::findTag(char const* text, unsigned& tag) { M_REQUIRE(text); if (!m_isPrepared) { m_isPrepared = true; m_impl->prepareSearch(); } return m_impl->findTag(*this, text, tag); } void AhoCorasick::match(unsigned position, unsigned index, unsigned length) { // no action } // vi:set ts=3 sw=3:
import edu.princeton.cs.algs4.Graph; import edu.princeton.cs.algs4.In; import edu.princeton.cs.algs4.StdOut; import java.util.TreeSet; import java.util.HashSet; import java.util.Set; import java.util.Stack; public class BoggleSolver { private int maxLen; private TSTDict tst = new TSTDict(); private static int R = 26; private static class Node { private Node[] n; Node() { n = new Node[R]; } private Integer val; } private static class TSTDict { private Node root = new Node(); private int charAt(char c) { return c - 'A'; } public void put(String key, Integer val) { root = put(root, key, val, 0); } private Node put(Node x, String key, Integer val, int d) { if (x == null) x = new Node(); if (d == key.length()) { x.val = val; return x; } x.n[charAt(key.charAt(d))] = put(x.n[charAt(key.charAt(d))], key, val, d + 1); return x; } public boolean containsPrefixNonRecursive(String query) { Node cur = root; int d = 0; while (cur != null && d< query.length()) { if (d == query.length()-1 && cur != null) { return true; } cur = cur.n[charAt(query.charAt(d))]; d++; } return false; } public boolean containsWord(String query) { Node cur = root; int d = 0; while (cur != null) { if (d == query.length() ) { if (cur.val != null) return true; else return false; } cur = cur.n[charAt(query.charAt(d))]; d++; } return false; } } // Initializes the data structure using the given array of strings as the // dictionary. // (You can assume each word in the dictionary contains only the uppercase // letters A through Z.) public BoggleSolver(String[] dictionary) { maxLen = 0; for (String s : dictionary) { maxLen = Math.max(maxLen, s.length()); tst.put(s, 1); } } private int gCol(int idx, BoggleBoard board) { return idx % board.cols(); } private int gRow(int idx, BoggleBoard board) { return idx / board.cols(); } private int gIdx(int row, int col, BoggleBoard board) { return row * board.cols() + col; } private boolean hasEdge(Graph G, int s, int v) { for (int l : G.adj(s)) { if (l == v) return true; } return false; } private Graph createGraph(BoggleBoard board) { int rows = board.rows(); int cols = board.cols(); Graph G = new Graph(rows * cols); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (i > 0) { if (!hasEdge(G, gIdx(i, j, board), gIdx(i - 1, j, board))) G.addEdge(gIdx(i, j, board), gIdx(i - 1, j, board)); } if (j > 0) { if (!hasEdge(G, gIdx(i, j, board), gIdx(i, j - 1, board))) G.addEdge(gIdx(i, j, board), gIdx(i, j - 1, board)); } if (i > 0 && j > 0) { if (!hasEdge(G, gIdx(i, j, board), gIdx(i - 1, j - 1, board))) G.addEdge(gIdx(i, j, board), gIdx(i - 1, j - 1, board)); } if (i > 0 && j < cols - 1) { if (!hasEdge(G, gIdx(i, j, board), gIdx(i - 1, j + 1, board))) G.addEdge(gIdx(i, j, board), gIdx(i - 1, j + 1, board)); } if (i < rows - 1) { if (!hasEdge(G, gIdx(i, j, board), gIdx(i + 1, j, board))) G.addEdge(gIdx(i, j, board), gIdx(i + 1, j, board)); } if (j < cols - 1) { if (!hasEdge(G, gIdx(i, j, board), gIdx(i, j + 1, board))) G.addEdge(gIdx(i, j, board), gIdx(i, j + 1, board)); } if (i < rows - 1 && j < cols - 1) { if (!hasEdge(G, gIdx(i, j, board), gIdx(i + 1, j + 1, board))) G.addEdge(gIdx(i, j, board), gIdx(i + 1, j + 1, board)); } if (i < rows - 1 && j > 0) { if (!hasEdge(G, gIdx(i, j, board), gIdx(i + 1, j - 1, board))) G.addEdge(gIdx(i, j, board), gIdx(i + 1, j - 1, board)); } } } return G; } private Set<Integer> onPath = new HashSet<>(); private Stack<Integer> pathStack = new Stack<>(); private void enumerate(Graph G, int s, int t, BoggleBoard board, Set<String> strings) { onPath.add(s); pathStack.push(s); if (s == t) { StringBuilder sb = new StringBuilder(); for (int x : pathStack) { if (board.getLetter(gRow(x, board), gCol(x, board)) != 'Q') { sb.append(board.getLetter(gRow(x, board), gCol(x, board))); } else { sb.append("QU"); } } String str = sb.toString(); if (tst.containsWord(str) && str.length() >= 3) { strings.add(sb.toString()); } } else { for (int v : G.adj(s)) { if (!onPath.contains(v)) { StringBuilder sb = new StringBuilder(); for (int x : pathStack) { if (board.getLetter(gRow(x, board), gCol(x, board)) != 'Q') { sb.append(board.getLetter(gRow(x, board), gCol(x, board))); } else { sb.append("QU"); } } if (tst.containsPrefixNonRecursive(sb.toString())) { enumerate(G, v, t, board, strings); } } } } pathStack.pop(); onPath.remove(s); } // Returns the set of all valid words in the given Boggle board, as an // Iterable. public Iterable<String> getAllValidWords(BoggleBoard board) { Graph G = createGraph(board); Set<String> q = new TreeSet<>(); // System.out.println(G); for (int i = 0; i < G.V(); i++) { for (int j = 0; j < G.V(); j++) { if (i != j) enumerate(G, i, j, board, q); } } return q; } // Returns the score of the given word if it is in the dictionary, zero // otherwise. // (You can assume the word contains only the uppercase letters A through // Z.) public int scoreOf(String word) { if (tst.containsWord(word)) { int len = word.length(); if (len <= 2) { return 0; } else if (len <= 4) { return 1; } else if (len == 5) { return 2; } else if (len == 6) { return 3; } else if (len == 7) { return 5; } else if (len >= 8) { return 11; } } return 0; } public static void main(String[] args) { In in = new In("src/boggle/dictionary-yawl.txt"); String[] dictionary = in.readAllStrings(); BoggleSolver solver = new BoggleSolver(dictionary); BoggleBoard board = new BoggleBoard("src/boggle/board-points750.txt"); System.out.println(board.toString()); int score = 0; for (String word : solver.getAllValidWords(board)) { StdOut.println(word); score += solver.scoreOf(word); } StdOut.println("Score = " + score); } }
.container - breadcrumb :event_search = breadcrumbs separator: " &rsaquo; " .title %h2= I18n.t('events.search.event-search') .row.card-box .left-content.col-12.col-lg-3.mt-4 .card.mb-3 .card-body = form_tag events_search_path, method: :get do = hidden_field_tag :search, :value => '' %div = label_tag I18n.t('events.search.keyword') .search-content = text_field_tag :q, '', placeholder: I18n.t('events.search.key-place'), class:'form-control' %hr = submit_tag I18n.t('events.search.search-btn'), class:'"btn btn-dark search-button' .card .card-body = search_form_for @q, url: events_search_path do |f| %div = f.label I18n.t('events.search.store') .search-content = f.search_field :store_or_address_cont, class:'form-control',:placeholder => I18n.t('events.search.store-place') %div = f.label I18n.t('events.search.category') .search-content = f.collection_select :category_id_eq, Category.all,:id,:name,{include_blank: I18n.t('events.search.not-set')}, {class:'form-control'} %hr = f.submit I18n.t('events.search.search-btn'), class:'"btn btn-dark search-button' .card.mt-3.mb-3 .card-body .tag %p.tag-title= I18n.t('events.search.tag') - @tag_lists.each do |list| = link_to list.tag_name, events_search_path(tag_id: list.id), class:'border border-dark rounded p-1 d-inline-block mb-1' .right-content.col-12.col-lg-9.mt-4 .sort-container %ul.sort %li= I18n.t('events.search.order') %li = link_to I18n.t('events.search.new'), sort_new_path(new: 'true'), {class: 'sort-link' "#{add_active_class(sort_new_path)}"} %li = link_to I18n.t('events.search.old'), sort_old_path(old: 'true'), {class: 'sort-link' "#{add_active_class(sort_old_path)}"} %li = link_to I18n.t('events.search.join'), sort_join_path(join: 'true'), {class: 'sort-link' "#{add_active_class(sort_join_path)}"} - if @events.present? - @events.each do |event| = render 'commons/event', event: event - else %h3= I18n.t('events.search.result') - if @events.present? .page.mt-3 = paginate @events,theme: 'twitter-bootstrap-4'
<x-layout> <x-section name="styles"> <!-- Some JS and styles --> <title>Hello World</title> <link rel="stylesheet" type="text/css" href="{{ URL::asset('texteditor/trix.css') }}"> <style> .hr-lines:before { content: " "; display: block; height: 5px; width: 130px; position: absolute; top: 50%; left: 0; background: black; } .hr-lines { position: relative; } .hr-lines { position: relative; /* new lines */ max-width: 500px; margin: 100px auto; text-align: center; } .hr-lines:after { content: " "; height: 5px; width: 130px; background: black; display: block; position: absolute; top: 50%; right: 0; } </style> </x-section> <!-- Page Wrapper --> <div id="wrapper"> <!-- Sidebar --> <x-sidebar></x-sidebar> <!-- End of Sidebar --> <!-- Content Wrapper --> <div id="content-wrapper" class="d-flex flex-column"> <!-- Main Content --> <div id="content"> <!-- Topbar --> <x-topbar></x-topbar> <!-- End of Topbar --> <!-- Begin Page Content --> <div class="container-fluid"> <div class="card shadow mb-4 col-md-10 m-auto"> <div class="card-header py-3 flex"> <h6 class="m-0 font-weight-bold d-inline text-primary">Price Create</h6> <a href="{{ route('bulk-prices.index') }}" class="btn btn-sm btn-primary d-inline float-right"><i class="fa fa-list"></i> All Prices</a> </div> <div class="card-body"> <x-response></x-response> <form method="POST" action="{{ route('bulk-prices.store') }}"> @csrf {{-- Specie --}} <div class="form-group row"> <label for="staticEmail" class="col-sm-2 col-form-label">Specie</label> <div class="col-sm-10"> <input type="text" class="form-control" name="specie" placeholder="Specie"> </div> </div> {{-- Thicknessss --}} <div class="form-group row"> <label for="code" class="col-sm-2 col-form-label">Thickness</label> <div class="col-sm-10 d-flex flex-row"> <input type="text" name="thickness" class="form-control" placeholder="Thickness"> </div> </div> {{-- Width --}} <div class="form-group row"> <label for="code" class="col-sm-2 col-form-label">Width</label> <div class="col-sm-10 d-flex flex-row"> <input type="number" name="width" class="form-control" placeholder="Width"> </div> </div> {{-- Height --}} <div class="form-group row"> <label for="code" class="col-sm-2 col-form-label">Height</label> <div class="col-sm-10 d-flex flex-row"> <input type="number" name="height" class="form-control" placeholder="Height"> </div> </div> {{-- Depth --}} <div class="form-group row"> <label for="code" class="col-sm-2 col-form-label">Depth</label> <div class="col-sm-10 d-flex flex-row"> <input type="number" name="depth" class="form-control" placeholder="Depth"> </div> </div> {{-- Price --}} <div class="form-group row"> <label for="code" class="col-sm-2 col-form-label">Price</label> <div class="col-sm-10 d-flex flex-row"> <input type="text" name="price" class="form-control" placeholder="Price"> </div> </div> {{-- Submit Button --}} <div class="form-group row"> <button type="submit" class="btn btn-primary m-auto form-control"><i class="fa fa-paper-plane"></i> Submit</button> </div> </form> <h2 class="hr-lines"> OR </h2> <form method="POST" action="{{ route('bulk-prices.import') }}" enctype="multipart/form-data"> @csrf <div class="form-group row"> <label for="code" class="col-sm-2 col-form-label">Excel File</label> <div class="col-sm-10 d-flex flex-row"> <input type="file" name="file" class="form-control" accept=".csv,.xlx,.xlsx" required> </div> <code>Note: Please Upload only Single Page Excel file</code> </div> {{-- Submit Button --}} <div class="form-group row"> <button type="submit" class="btn btn-primary m-auto">Upload</button> </div> </form> </div> </div> </div> <!-- /.container-fluid --> </div> <!-- End of Main Content --> <!-- Footer --> <x-footer></x-footer> <!-- End of Footer --> </div> <!-- End of Content Wrapper --> </div> <!-- End of Page Wrapper --> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <x-section name="scripts"> <!-- Some JS and styles --> <script type="text/javascript" src="{{ URL::asset('texteditor/trix.js') }}"></script> </x-section> </x-layout>
export interface PlayerInfo { playerId: string; nickname: string; class: string; level: number; unitUid?: number; isOffline?: boolean; isReady?: boolean; } export interface RoomInfo { uid: number; capacity: number; scenarioId: string; joinedUsers: PlayerInfo[]; host: PlayerInfo; inactive?: boolean; } export interface UnitBooty { coins: number; ruby?: number; } export interface UnitState { health: number; stamina: number; mana: number; actionPoints: number; stress: number; isStunned?: boolean; waitingOrder?: number; } export interface Damage { stabbing?: number; cutting?: number; crushing?: number; fire?: number; cold?: number; lightning?: number; poison?: number; exhaustion?: number; manaDrain?: number; bleeding?: number; fear?: number; curse?: number; madness?: number; isCritical?: boolean; isCriticalMiss?: boolean; withStun?: boolean; } export interface UnitBaseAttributes { health: number; stamina: number; mana: number; actionPoints: number; } export interface UnitAttributes { strength: number; physique: number; agility: number; endurance: number; intelligence: number; initiative: number; luck: number; } export interface UnitRequirements extends UnitAttributes { class?: string; } export interface UnitResistance extends Damage { } export interface UnitRecovery extends UnitState, Damage { } export interface UnitModification { baseAttributes?: UnitBaseAttributes; attributes?: UnitAttributes; resistance?: UnitResistance; damage?: Damage; recovery?: UnitRecovery; } export interface DamageImpact extends Damage { duration?: number; chance?: number; deviation?: number; } export interface UnitModificationImpact extends UnitModification { duration?: number; chance?: number; deviation?: number; } export enum ItemType { ARMOR = 'armor', WEAPON = 'weapon', MAGIC = 'magic', DISPOSABLE = 'disposable', AMMUNITION = 'ammunition', NONE = 'none', } export interface Item { uid?: number; code: string; name: string; type: ItemType; canBeThrownAway: boolean; canBeSold: boolean; price: UnitBooty; description?: string; } export enum EquipmentSlot { HEAD = 'head', NECK = 'neck', BODY = 'body', HAND = 'hand', LEG = 'leg', WEAPON = 'weapon', } export interface Equipment extends Item { wearout: number; durability: number; slot: EquipmentSlot; slotsNumber: number; equipped: boolean; requirements: UnitRequirements; modification: UnitModification[]; } export interface ActionRange { minimumX?: number; maximumX?: number; minimumY?: number; maximumY?: number; radius?: number; } export interface Weapon extends Equipment { ammunitionKind?: string; range: ActionRange; useCost: UnitBaseAttributes; damage: DamageImpact[]; } export interface Magic extends Item { requirements: UnitRequirements; range: ActionRange; useCost: UnitBaseAttributes; damage?: DamageImpact[]; modification?: UnitModificationImpact[]; } export interface Armor extends Equipment { } export interface Disposable extends Item { quantity?: number; range: ActionRange; damage?: DamageImpact[]; modification?: UnitModificationImpact[]; } export interface Ammunition extends Item { equipped?: boolean; kind: string; quantity?: number; damage?: DamageImpact[]; } export type InventoryItem = Weapon | Disposable | Ammunition | Magic | Armor; export interface UnitInventory { weapon?: Weapon[]; magic?: Magic[]; armor?: Armor[]; disposable?: Disposable[]; ammunition?: Ammunition[]; } export interface Position { x: number; y: number; } export interface UnitProgress { level: number; experience: number; experienceNext?: number; attributesPoints?: number; baseAttributesPoints?: number; } export interface UnitStats { progress: UnitProgress; baseAttributes: UnitBaseAttributes; attributes: UnitAttributes; resistance: UnitResistance; } export interface Unit { uid?: number; code?: string; class?: string; name: string; booty: UnitBooty; state: UnitState; stats: UnitStats; damage?: DamageImpact[]; modification?: UnitModificationImpact[]; inventory: UnitInventory; slots: Map<EquipmentSlot, number>; achievements: Map<string, number>; position: Position; } export enum GameUnitFaction { PARTY = 0, ENEMY = 1, } export interface GameUnit extends Unit { faction: GameUnitFaction; playerInfo?: PlayerInfo; isDead?: boolean; } export interface GameShopStatus { items: UnitInventory; purchase: Map<string, UnitBooty>; repair: Map<string, UnitBooty>; } export enum GamePhase { PREPARE_UNIT = 'prepareUnit', READY_FOR_START_ROUND = 'readyForStartRound', MAKE_MOVE_OR_ACTION_AI = 'makeMoveOrActionAI', MAKE_ACTION_AI = 'makeActionAI', MAKE_MOVE_OR_ACTION = 'makeMoveOrAction', MAKE_ACTION = 'makeAction', RETREAT_ACTION = 'retreatAction', ACTION_COMPLETE = 'actionComplete', BEFORE_SPOT_COMPLETE = 'beforeSpotComplete', SPOT_COMPLETE = 'spotComplete', SCENARIO_COMPLETE = 'scenarioComplete', } export interface GameState { booty: UnitBooty; activeUnitsQueue: number[]; inactiveUnits: number[]; spotNumber: number; spotsTotal: number; } export enum CellType { SPACE = 0, OBSTACLE = 1, } export interface Cell { code: string; factions: GameUnitFaction[]; type?: CellType; } export interface Battlefield { matrix: Cell[][]; units: GameUnit[]; corpses: GameUnit[]; } export interface Spot { name: string; code: string; battlefield: Battlefield; } export enum ActionType { USE = 'use', EQUIP = 'equip', UNEQUIP = 'unequip', PLACE = 'place', MOVE = 'move', BUY = 'buy', SELL = 'sell', REPAIR = 'repair', THROW_AWAY = 'throwAway', SKIP = 'skip', WAIT = 'wait', LEVEL_UP = 'levelUp', SKILL_UP = 'skillUp', } export enum ActionProperty { STRENGTH = 'strength', PHYSIQUE = 'physique', AGILITY = 'agility', ENDURANCE = 'endurance', INTELLIGENCE = 'intelligence', INITIATIVE = 'initiative', LUCK = 'luck', HEALTH = 'health', STAMINA = 'stamina', MANA = 'mana', } export interface Position { x: number; y: number; } export interface Action { action: ActionType; uid?: number; targetUid?: number; itemUid?: number; quantity?: number; property?: ActionProperty; position?: Position; } export enum ActionResultType { ACCOMPLISHED = 'accomplished', NOT_ACCOMPLISHED = 'notAccomplished', NOT_ALLOWED = 'notAllowed', NOT_FOUND = 'notFound', NOT_EMPTY = 'notEmpty', NOT_EUIPPED = 'notEquipped', NOT_REACHABLE = 'notReachable', CANT_USE = 'cantUse', OUT_OF_BOUNDS = 'outOfBounds', NO_AMMUNITION = 'noAmmunition', NOT_COMPATIBLE = 'notCompatible', ZERO_QUANTITY = 'zeroQuantity', NOT_ENOUGH_SLOTS = 'notEnoughSlots', NOT_ENOUGH_RESOURCES = 'notEnoughResources', IS_BROKEN = 'isBroken', } export interface ActionResult { instantDamage?: { [key: number]: Damage[] }; temporalDamage?: { [key: number]: DamageImpact[] }; instantRecovery?: { [key: number]: UnitRecovery[] }; temporalModification?: { [key: number]: UnitModificationImpact[] }; experience?: { [key: number]: number }; drop?: { [key: number]: UnitBooty }; achievements?: { [key: string]: number }; booty?: UnitBooty; result: ActionResultType; } export interface GameUnitActionResult { action: Action; result: ActionResult; } export interface EndRoundResult { damage?: { [key: number]: Damage }; recovery?: { [key: number]: UnitRecovery }; experience?: { [key: number]: number }; drop?: { [key: number]: UnitBooty }; achievements?: { [key: string]: number }; } export interface SpotCompleteResult { experience?: { [key: number]: number }; booty?: UnitBooty; achievements?: { [key: string]: number }; } export interface GameEvent { phase: GamePhase; nextPhase: GamePhase; phaseTimeout?: number; state: GameState; spot: Spot; players: PlayerInfo[]; unitActionResult?: GameUnitActionResult; endRoundResult?: EndRoundResult; spotCompleteResult?: SpotCompleteResult; } export interface PlayerJob { name: string; code: string; reward: string; duration: number; countdown: number; requirements?: UnitRequirements; description?: string; } export interface EmploymentStatus { currentJob?: PlayerJob; isInProgress?: boolean; isComplete?: boolean; timeLeft?: number; availableJobs: PlayerJob[]; }
/** * @jest-environment jsdom */ /** * @jest-environment jsdom */ import { Observer } from "../types"; import { Observable } from "./observable"; export function fromEvent( el: HTMLElement, eventName: "click" | "change" | "error" | "input" ) { function fromEventProducer(observer: Observer){ try { el.addEventListener(eventName, observer.next); return { unsubscribe(){ el.removeEventListener(eventName, observer.next); observer.complete(); } } } catch (error) { observer.error("You should provide a valid html element"); observer.complete(); } } return new Observable(fromEventProducer); }
import scala.annotation.implicitNotFound @implicitNotFound("You need to define a CompareT for ${T}") abstract class CompareT[T] { def isSmaller(i1: T, i2: T): Boolean def isLarger(i1: T, i2: T): Boolean } def genInsert[T: Ordering](item: T, rest: List[T]): List[T] = { val cmp = implicitly[Ordering[T]] rest match { case Nil => List(item) case head :: _ if cmp.lt(item, head) => item :: rest case head :: tail => head :: genInsert(item, tail) } } def genSort[T: Ordering](xs: List[T]): List[T] = xs match { case Nil => Nil case head :: tail => genInsert(head, genSort(tail)) } val nums = List(1, 4, 3, 2, 6, 5) genSort(nums) def genInsert2[T](item: T, rest: List[T])(implicit cmp: CompareT[T]): List[T] = { rest match { case Nil => List(item) case head :: _ if cmp.isSmaller(item, head) => item :: rest case head :: tail => head :: genInsert2(item, tail) } } def genSort2[T: CompareT](xs: List[T]): List[T] = xs match { case Nil => Nil case head :: tail => genInsert2(head, genSort2(tail)) } implicit object CompareInt extends CompareT[Int] { override def isSmaller(i1: Int, i2: Int) = i1 < i2 override def isLarger(i1: Int, i2: Int) = i1 > i2 } nums genSort2(nums) case class Person(first: String, age: Int) object Person { implicit object PersonOrdering extends Ordering[Person] { override def compare(x: Person, y: Person): Int = x.age - y.age } } implicit object POrdering2 extends Ordering[Person] { override def compare(x: Person, y: Person) = 0 } val people = List( Person("Fred", 25), Person("Sally", 22), Person("George", 53) ) genSort(people)
/* * AsyncWorldEdit a performance improvement plugin for Minecraft WorldEdit plugin. * Copyright (c) 2019, SBPrime <https://github.com/SBPrime/> * Copyright (c) AsyncWorldEdit contributors * * All rights reserved. * * Redistribution in source, use in source and binary forms, with or without * modification, are permitted free of charge provided that the following * conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions of source code, with or without modification, in any form * other then free of charge is not allowed, * 3. Redistributions of source code, with tools and/or scripts used to build the * software is not allowed, * 4. Redistributions of source code, with information on how to compile the software * is not allowed, * 5. Providing information of any sort (excluding information from the software page) * on how to compile the software is not allowed, * 6. You are allowed to build the software for your personal use, * 7. You are allowed to build the software using a non public build server, * 8. Redistributions in binary form in not allowed. * 9. The original author is allowed to redistrubute the software in bnary form. * 10. Any derived work based on or containing parts of this software must reproduce * the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * derived work. * 11. The original author of the software is allowed to change the license * terms or the entire license of the software as he sees fit. * 12. The original author of the software is allowed to sublicense the software * or its parts using any license terms he sees fit. * 13. By contributing to this project you agree that your contribution falls under this * license. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.primesoft.asyncworldedit.playerManager; import com.sk89q.worldedit.util.eventbus.EventBus; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.primesoft.asyncworldedit.api.configuration.IPermissionGroup; import org.primesoft.asyncworldedit.api.inner.IAsyncWorldEditCore; import org.primesoft.asyncworldedit.api.permissions.IPermission; import org.primesoft.asyncworldedit.core.AwePlatform; /** * * @author SBPrime */ public class PlayerEntryTest { @Before public void init() { IAsyncWorldEditCore core = Mockito.mock(IAsyncWorldEditCore.class); EventBus eb = new EventBus(); AwePlatform.getInstance().initialize(core); Mockito.when(core.getEventBus()).thenReturn(eb); } @Test public void shouldChangeSpeedWithinAllowedRange() { // Given IPermissionGroup pg = Mockito.mock(IPermissionGroup.class); Mockito.when(pg.getRendererBlocks()).thenReturn(10); PlayerEntry pe = new TestPlayerEntry(pg); // When pe.setRenderBlocks(5); // Then Assert.assertEquals("Render blocks", 5, pe.getRenderBlocks()); } @Test public void shouldNotChangeSpeedLowerThen1() { // Given IPermissionGroup pg = Mockito.mock(IPermissionGroup.class); Mockito.when(pg.getRendererBlocks()).thenReturn(10); PlayerEntry pe = new TestPlayerEntry(pg); // When pe.setRenderBlocks(0); int s1 = pe.getRenderBlocks(); pe.setRenderBlocks(-1); int s2 = pe.getRenderBlocks(); // Then Assert.assertEquals("Set 1: Render blocks", 10, s1); Assert.assertEquals("Set 2: Render blocks", 10, s2); } @Test public void shouldNotChangeSpeedHigherThenLimit() { // Given IPermissionGroup pg = Mockito.mock(IPermissionGroup.class); Mockito.when(pg.getRendererBlocks()).thenReturn(10); PlayerEntry pe = new TestPlayerEntry(pg); // When pe.setRenderBlocks(100); // Then Assert.assertEquals("Render blocks", 10, pe.getRenderBlocks()); } @Test public void shouldChangeSpeedWhenNoLimit() { // Given IPermissionGroup pg = Mockito.mock(IPermissionGroup.class); Mockito.when(pg.getRendererBlocks()).thenReturn(-1); PlayerEntry pe = new TestPlayerEntry(pg); // When pe.setRenderBlocks(100); // Then Assert.assertEquals("Render blocks", 100, pe.getRenderBlocks()); } private static class TestPlayerEntry extends PlayerEntry { public TestPlayerEntry(IPermissionGroup pg) { super(null, null, pg); } @Override protected boolean sendRawMessage(String msg) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public boolean isAllowed(IPermission permission) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public boolean isPlayer() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public boolean isInGame() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void updatePermissionGroup() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public boolean isFake() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } } }
using SocialNetwork.BLL.Exceptions; using SocialNetwork.BLL.Models; using SocialNetwork.DAL.Entities; using SocialNetwork.DAL.Repositories; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SocialNetwork.BLL.Services { public class UserService { MessageService messageService; IUserRepository userRepository; IFriendRepository friendRepository; public UserService() { userRepository = new UserRepository(); messageService = new MessageService(); friendRepository = new FriendRepository(); } public void Register(UserRegistrationData userRegistrationData) { if (String.IsNullOrEmpty(userRegistrationData.FirstName)) { throw new ArgumentNullException(); } if (String.IsNullOrEmpty(userRegistrationData.LastName)) { throw new ArgumentNullException(); } if (String.IsNullOrEmpty(userRegistrationData.Email)) { throw new ArgumentNullException(); } if (String.IsNullOrEmpty(userRegistrationData.Password)) { throw new ArgumentNullException(); } if (userRegistrationData.Password.Length < 8 ) { throw new ArgumentNullException(); } if (!new EmailAddressAttribute().IsValid(userRegistrationData.Email)) { throw new ArgumentNullException(); } if (userRepository.FindByEmail(userRegistrationData.Email) != null) { throw new ArgumentNullException(); } var userEntity = new UserEntity() { firstname = userRegistrationData.FirstName, lastname = userRegistrationData.LastName, email = userRegistrationData.Email, password = userRegistrationData.Password }; if (this.userRepository.Create(userEntity) == 0) { throw new Exception(); } } public User Authenticate(UserAuthenticationData userAuthenticationData) { var findUserEntity = userRepository.FindByEmail(userAuthenticationData.Email); if (findUserEntity is null) throw new UserNotFoundException(); if (findUserEntity.password != userAuthenticationData.Password) throw new WrongPasswordException(); return ConstructUserModel(findUserEntity); } public void DeleteById(int userId) { var findUserEntity = userRepository.FindById(userId); if (findUserEntity is null) throw new UserNotFoundException(); if (userRepository.DeleteById(userId) == 0) { throw new Exception(); } } public IEnumerable<User> FindAllUser() { return userRepository.FindAll().Select(userEntity => FindById(userEntity.id)); } public User FindByEmail(string email) { var findUserEntity = userRepository.FindByEmail(email); if (findUserEntity is null) throw new UserNotFoundException(); return ConstructUserModel(findUserEntity); } public User FindById(int id) { var findUserEntity = userRepository.FindById(id); if (findUserEntity is null) throw new UserNotFoundException(); return ConstructUserModel(findUserEntity); } public void Update(User user) { var updatableUserEntity = new UserEntity() { id = user.Id, firstname = user.FirstName, lastname = user.LastName, password = user.Password, email = user.Email, photo = user.Photo, favorite_movie = user.FavoriteMovie, favorite_book = user.FavoriteBook }; if (this.userRepository.Update(updatableUserEntity) == 0) { throw new Exception(); } } public IEnumerable<User> GetAllFriendsByUserId(int userId) { return friendRepository.FindAllByUserId(userId) .Select(friendsEntity => FindById(friendsEntity.friend_id)); } public void AddFriend(UserAddingFriendData userAddingFriendData) { var findUserEntity = userRepository.FindByEmail(userAddingFriendData.FriendEmail); if (findUserEntity is null) throw new UserNotFoundException(); var friendEntity = new FriendEntity() { user_id = userAddingFriendData.UserId, friend_id = findUserEntity.id }; if (this.friendRepository.Create(friendEntity) == 0) throw new Exception(); } private User ConstructUserModel(UserEntity userEntity) { var incomingMessages = messageService.GetIncomingMessagesByUserId(userEntity.id); var outgoingMessages = messageService.GetOutcomingMessagesByUserId(userEntity.id); var friends = GetAllFriendsByUserId(userEntity.id); return new User(userEntity.id, userEntity.firstname, userEntity.lastname, userEntity.password, userEntity.email, userEntity.photo, userEntity.favorite_movie, userEntity.favorite_book, incomingMessages, outgoingMessages, friends ); } } }
fin <- read.csv(here::here("Data prep","P3-Future-500-The-Dataset.csv"), stringsAsFactors = TRUE, na.strings = c("")) # Quick EDA ---- head(fin, 10) tail(fin) str(fin) summary(fin) # Data Wrangling # Change from non-factor to factor ---- fin$ID <- factor(fin$ID) fin$Inception <- factor(fin$Inception) # Factor Variable Trap (FVT) ---- #Converting into numerics for characters a <- c("12","13", "14", "12", "12") typeof(a) b <- as.numeric(a) b typeof(b) # Converting into numerics for Factors ---- z <- factor(a) z typeof(z) y <- as.numeric(z) y typeof(y) #--------- Correct method: x <- as.numeric(as.character(z)) x typeof(x) # FVT Example ------------------------- #fin$Profit <- factor(fin$Profit) #head(fin) #str(fin) #summary(fin) # Don't do this: #fin$Profit <- as.numeric(fin$Profit) # gsub() function -------- fin$Expenses <- gsub(" Dollars", "", fin$Expenses, perl = TRUE) fin$Expenses <- gsub(",", "", fin$Expenses, perl = TRUE) fin$Revenue <- gsub("[\\$,]", "", fin$Revenue, perl = TRUE) fin$Growth <- gsub("%", "", fin$Growth, perl = TRUE) library(tidyverse) fin <- fin %>% mutate_if(is.character, as.numeric) fin$Name <- as.character(fin$Name) glimpse(fin) # Deal with missing data ------ # 1. Predict with 100% accuracy # 2. Leave record as is # 3. Remove record entirely # 4. Replace with mean or median # 5. Fill in by exploring correlations and similarities # 6. Introduce dummy variable for "Missingness" # Locate missing data ---- # Updated import to: read.csv(here::here("Data prep","P3-Future-500-The-Dataset.csv"), stringsAsFactors = TRUE, na.strings = c("")) fin[!complete.cases(fin),] # Filtering: using which() for non-missing data ----- head(fin, 24) fin[fin$Revenue == 9746272,] fin[which(fin$Revenue == 9746272),] fin[fin$Employees == 45,] fin[which(fin$Employees == 45),] # Filtering: using is.na() for missing data ---- fin[is.na(fin$Expenses),] # Removing records with missing data ---- # create backup fin_backup <- fin # remove rows fin <- fin[!is.na(fin$Industry),] # Reset the index of the dataframe ---- rownames(fin) <- NULL # Replacing missing data with factual analysis method ---- fin[is.na(fin$State) & fin$City == 'New York', "State"] <- "NY" fin[is.na(fin$State) & fin$City == 'San Francisco', "State"] <- "CA" # Check: fin[c(11,377,82,265),] # Replacing missing data with median imputation method ---- median(fin$Employees, na.rm = TRUE) fin[is.na(fin$Employees),] med_empl_retail <- median(fin[fin$Industry == "Retail", "Employees"], na.rm = TRUE) fin[is.na(fin$Employees) & fin$Industry == 'Retail', "Employees"] <- med_empl_retail med_empl_fin_serv <- median(fin[fin$Industry == "Financial Services", "Employees"], na.rm = TRUE) fin[is.na(fin$Employees) & fin$Industry == 'Financial Services', "Employees"] <- med_empl_fin_serv # check: fin[c(3,330),] fin[!complete.cases(fin),] med_growth_constr <- median(fin[fin$Industry == 'Construction', "Growth"], na.rm = TRUE) fin[is.na(fin$Growth) & fin$Industry == 'Construction', "Growth"] <- med_growth_constr # check: fin[c(8),] med_rev_constr <- median(fin[fin$Industry == 'Construction', "Revenue"], na.rm = TRUE) fin[is.na(fin$Revenue) & fin$Industry == 'Construction', "Revenue"] <- med_rev_constr med_exp_constr <- median(fin[fin$Industry == 'Construction', "Expenses"], na.rm = TRUE) fin[is.na(fin$Expenses) & fin$Industry == 'Construction' & is.na(fin$Profit), "Expenses"] <- med_exp_constr # Replacing missing data: deriving values ---- fin[is.na(fin$Profit), "Profit"] <- fin[is.na(fin$Profit), "Revenue"] - fin[is.na(fin$Profit), "Expenses"] #check: fin[c(8,42),] fin[is.na(fin$Expenses), "Expenses"] <- fin[is.na(fin$Expenses), "Revenue"] - fin[is.na(fin$Expenses), "Profit"] # plot the data ---- # Scatterplot classified by industry showing revenue, expenses, profit fin %>% ggplot() + geom_point(aes(Revenue, Expenses, colour = Industry, size = Profit)) + theme_light() # Scatterplot that includes industry trends for the expenses fin %>% ggplot(aes(Revenue, Expenses, colour = Industry)) + geom_point() + geom_smooth(fill = NA, size = 1.2) + theme_light() # Boxplot of industry growth fin %>% ggplot(aes(Industry, Growth, colour = Industry)) + geom_jitter() + geom_boxplot(size = 1, alpha=0.5, outlier.colour = NA) + theme_light()
//go:build unit || all package sales_test import ( "context" "errors" "testing" "time" "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/uesleicarvalhoo/sorveteria-tres-estrelas/backend/product" productsMocks "github.com/uesleicarvalhoo/sorveteria-tres-estrelas/backend/product/mocks" "github.com/uesleicarvalhoo/sorveteria-tres-estrelas/backend/sales" "github.com/uesleicarvalhoo/sorveteria-tres-estrelas/backend/sales/mocks" ) func TestRegisterSale(t *testing.T) { t.Parallel() t.Run("when all fields are ok", func(t *testing.T) { t.Parallel() // Arrange storedProduct := product.Product{ ID: uuid.New(), Name: "picole de chocolate", PriceVarejo: 7.5, PriceAtacado: 5, AtacadoAmount: 10, } description := "i'm a sale description" paymentType := sales.CashPayment cart := sales.Cart{ Items: []sales.CartItem{ { ItemID: storedProduct.ID, Amount: 5, }, }, } productSvc := productsMocks.NewUseCase(t) productSvc.On("Get", mock.Anything, storedProduct.ID).Return(storedProduct, nil).Once() salesRepo := mocks.NewRepository(t) salesRepo.On("Create", mock.Anything, mock.Anything).Return(nil).Once() sut := sales.NewService(productSvc, salesRepo) // Action sale, err := sut.RegisterSale(context.Background(), description, paymentType, cart) // Assert assert.NoError(t, err) assert.NotEqual(t, uuid.Nil, sale.ID) assert.Equal(t, description, sale.Description) assert.Len(t, sale.Items, len(cart.Items)) assert.Equal(t, storedProduct.Name, sale.Items[0].Name) assert.Equal(t, 37.5, sale.Total) assert.False(t, sale.Date.IsZero()) }) testErrors := []struct { about string cart sales.Cart description string payment sales.PaymentType productRepoReturn product.Product productRepoErr error saleRepoErr error expectedErr string }{ { about: "when cart items are empty", cart: sales.Cart{Items: []sales.CartItem{}}, payment: sales.AnotherPayments, description: "i'm a sale description", expectedErr: "items: a quantidade mínima de items é 1", }, { about: "when product don't exist", description: "i'm a sale description", payment: sales.AnotherPayments, cart: sales.Cart{ Items: []sales.CartItem{ {ItemID: uuid.Nil, Amount: 10}, }, }, productRepoErr: errors.New("record not found"), expectedErr: "record not found", }, { about: "when sale repository return an error when sale is created", description: "i'm a sale description", payment: sales.AnotherPayments, cart: sales.Cart{ Items: []sales.CartItem{ {ItemID: uuid.Nil, Amount: 10}, }, }, saleRepoErr: errors.New("failed to create a new sale"), expectedErr: "failed to create a new sale", }, } for _, tc := range testErrors { tc := tc t.Run(tc.about, func(t *testing.T) { t.Parallel() // Arrange productSvc := productsMocks.NewUseCase(t) productSvc.On("Get", mock.Anything, mock.Anything).Return(tc.productRepoReturn, tc.productRepoErr).Maybe() salesRepo := mocks.NewRepository(t) salesRepo.On("Create", mock.Anything, mock.Anything).Return(tc.saleRepoErr).Maybe() sut := sales.NewService(productSvc, salesRepo) // Action sale, err := sut.RegisterSale(context.Background(), tc.description, tc.payment, tc.cart) // Assert assert.Equal(t, sales.Sale{}, sale) assert.EqualError(t, err, tc.expectedErr) }) } } func TestGetAll(t *testing.T) { t.Parallel() tests := []struct { about string repoSales []sales.Sale repoError error expectedSales []sales.Sale expectedError error }{ { about: "when repository return an error", repoError: errors.New("failed to get all sales"), expectedError: errors.New("failed to get all sales"), }, { about: "when repository return sales, should order by date", repoSales: []sales.Sale{ {PaymentType: sales.CashPayment, Date: time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)}, {PaymentType: sales.CashPayment, Date: time.Date(2021, 1, 2, 0, 0, 0, 0, time.UTC)}, {PaymentType: sales.CashPayment, Date: time.Date(2021, 1, 3, 0, 0, 0, 0, time.UTC)}, }, expectedSales: []sales.Sale{ {PaymentType: sales.CashPayment, Date: time.Date(2021, 1, 3, 0, 0, 0, 0, time.UTC)}, {PaymentType: sales.CashPayment, Date: time.Date(2021, 1, 2, 0, 0, 0, 0, time.UTC)}, {PaymentType: sales.CashPayment, Date: time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)}, }, }, } for _, tc := range tests { tc := tc t.Run(tc.about, func(t *testing.T) { t.Parallel() // Arrange repo := mocks.NewRepository(t) repo.On("GetAll", mock.Anything).Return(tc.repoSales, tc.repoError).Once() productsSvc := productsMocks.NewUseCase(t) sut := sales.NewService(productsSvc, repo) // Action sales, err := sut.GetAll(context.Background()) // Assert assert.Equal(t, tc.expectedSales, sales) assert.Equal(t, tc.expectedError, err) }) } } func TestDeleteByID(t *testing.T) { t.Parallel() tests := []struct { about string id uuid.UUID repoError error expectedError error }{ { about: "when repository return an error", id: uuid.New(), repoError: errors.New("failed to delete sale"), expectedError: errors.New("failed to delete sale"), }, { about: "when repository return nil error", id: uuid.New(), repoError: nil, expectedError: nil, }, } for _, tc := range tests { tc := tc t.Run(tc.about, func(t *testing.T) { t.Parallel() // Arrange repo := mocks.NewRepository(t) repo.On("Delete", mock.Anything, mock.Anything).Return(tc.repoError).Once() productsSvc := productsMocks.NewUseCase(t) sut := sales.NewService(productsSvc, repo) // Action err := sut.DeleteByID(context.Background(), tc.id) // Assert assert.Equal(t, tc.expectedError, err) }) } }
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { environment } from 'environments'; import { Observable } from 'rxjs'; import type { Task } from './models'; const BASE_URL = '/todos'; export type GetTasksListParams = { userId?: number; completed?: boolean; }; export type GetTaskByIdParams = { taskId: number; [key: string]: string | number; }; @Injectable({ providedIn: 'root', }) export class TypicodeService { constructor(private readonly http: HttpClient) {} getTasksList(params?: GetTasksListParams): Observable<Task[]> { return this.http.get<Task[]>(`${environment.apiUrl}${BASE_URL}`, { params, }); } getTaskById({ taskId, ...params }: GetTaskByIdParams): Observable<Task> { return this.http.get<Task>(`${environment.apiUrl}${BASE_URL}/${taskId}`, { params, }); } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <%@ taglib prefix="spform" uri="http://www.springframework.org/tags/form" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://unpkg.com/[email protected]/build/pure-min.css"> <title>Employee Update Form</title> </head> <body style="padding: 20px"> <spform:form modelAttribute="employee" class="pure-form" method="post" action="${pageContext.request.contextPath}/mvc/employee/${ index }"> <fieldset> <legend>Employee Update Form</legend> <input type="hidden" name="_method" value="PUT" /> 姓名: <spform:input path="name" /><p /> 年齡: <spform:input path="age" /><p /> 薪資: <spform:input path="salary" /><p /> 生日: <spform:input type="date" path="birth" /><p /> 學歷: <spform:select path="education"> <spform:option value="">請選擇</spform:option> <spform:option value="國中">國中(含)以下</spform:option> <spform:option value="高中">高中</spform:option> <spform:option value="大學">大學</spform:option> <spform:option value="研究所">研究所(含)以上</spform:option> </spform:select> <p /> 性別: <spform:radiobutton path="sex" value="男"/>男性 <spform:radiobutton path="sex" value="女"/>女性<p /> 興趣: <spform:checkbox path="interest" value="爬山" />爬山 <spform:checkbox path="interest" value="閱讀" />閱讀 <spform:checkbox path="interest" value="打球" />打球 <spform:checkbox path="interest" value="飛控" />飛控 <p /> 履歷: <spform:textarea path="resume" /><p /> <input type="submit" value="修改" class="pure-button pure-button-primary" /> </fieldset> </spform:form> <p /> ${ employees } </body> </html>
<template> <div class="wrapper"> <div class="section"> <div class="flex items-center flex-col my-2"> <h2 class="font-black" @click="editTitle(true)" v-if="!showTitleInput" :style="{ 'font-size': sectionTitleSize + 'px', color: sectionTitleColor, }" > {{ title }} </h2> <input class="outline-none bg-slate-300" type="text" ref="titleInput" v-if="showTitleInput" @keydown.enter="setTitle" @blur="editTitle(false)" v-focus /> <p @click="editDescription(true)" v-if="!showDescriptionInput" :style="{ color: sectionDescriptionColor }" > {{ description }} </p> <input class="outline-none bg-slate-300" type="text" ref="descriptionInput" v-if="showDescriptionInput" @keydown.enter="setDescription" @blur="editDescription(false)" v-focus /> </div> <div v-if="!asCarousel && store.theBlocks.length" class="flex flex-wrap justify-center items-center relative w-full" :style="{ gap: blockGap + 'px' }" > <TheBlock v-for="item in store.theBlocks" :key="item.id" :id-prop="item.id" :img-prop="item.image.url" :color-prop="item.color" :height-prop="item.height" :width-prop="item.width" :opacity-prop="item.image.overlayOpacity" :overlay-color="item.image.overlayColor" ></TheBlock> </div> <div v-if="asCarousel && store.theBlocks.length" class="w-full px-5"> <Carousel class="w-full" :settings="settings"> <Slide class="w-full" v-for="item in store.theBlocks" :key="item.id"> <TheBlock :id-prop="item.id" :img-prop="item.image.url" :color-prop="item.color" :height-prop="item.height" :width-prop="item.width" :opacity-prop="item.image.overlayOpacity" :overlay-color="item.image.overlayColor" /> </Slide> <template #addons> <Pagination /> <Navigation /> </template> </Carousel> </div> </div> <div class="global-settings"> <div> <p>{{ store.theBlocks.length }} items (between 1-8)</p> <button class="btn" @click="displayBlock">Add item</button> <button class="btn" @click="hideBlock">Delete item</button> </div> <div> <p>Gap between blocks</p> <input type="range" min="0" max="18" v-model="blockGap" /> </div> <div> <p>Section title text size</p> <input type="number" v-model="sectionTitleSize" class="outline-none" /> </div> <div> <p>Section title color</p> <input type="text" v-model="sectionTitleColor" class="outline-none" /> </div> <div> <p>Section description color</p> <input type="text" v-model="sectionDescriptionColor" class="outline-none" /> </div> <div> <p>Display as slider</p> <input type="checkbox" v-model="asCarousel" /> </div> </div> </div> </template> <script setup> import "vue3-carousel/dist/carousel.css"; import { ref } from "vue"; import TheBlock from "./TheBlock.vue"; import { Carousel, Slide, Navigation, Pagination } from "vue3-carousel"; import { useStore } from "../../../store"; const title = ref("Edit title"); const description = ref("Edit description"); const titleInput = ref(null); const descriptionInput = ref(null); const showTitleInput = ref(false); const showDescriptionInput = ref(false); const sectionTitleSize = ref("16"); const sectionTitleColor = ref("black"); const sectionDescriptionColor = ref("black"); const blockGap = ref(8); const asCarousel = ref(false); const settings = { itemsToShow: 1, wrapAround: true, transition: 600, mouseDrag: false, touchDrag: false, }; const store = useStore(); const editTitle = (val) => { showTitleInput.value = val; }; const setTitle = () => { title.value = titleInput.value.value; showTitleInput.value = false; }; const editDescription = (val) => { showDescriptionInput.value = val; }; const setDescription = () => { description.value = descriptionInput.value.value; showDescriptionInput.value = false; }; const displayBlock = () => { store.createBlock(); }; const hideBlock = () => { store.deleteBlock(); }; </script> <style scoped> .wrapper { @apply bg-slate-200 max-w-3xl flex justify-between p-2; } .section { @apply flex items-center flex-col w-full; } .global-settings { @apply bg-slate-100 p-2; } .btn { @apply transition-all bg-slate-200 p-1 mx-1 hover:bg-slate-50; } </style>
--- changelog: - 2024-02-03, gpt-4-0125-preview, translated from English date: 2024-02-03 19:04:51.124098-07:00 description: "C\xF3mo hacerlo: Clojure, al ser un lenguaje JVM, te permite utilizar\ \ directamente los m\xE9todos de String de Java. Aqu\xED tienes un ejemplo b\xE1\ sico de c\xF3mo\u2026" lastmod: '2024-03-13T22:44:58.639841-06:00' model: gpt-4-0125-preview summary: "Clojure, al ser un lenguaje JVM, te permite utilizar directamente los m\xE9\ todos de String de Java." title: Capitalizando una cadena de texto weight: 2 --- ## Cómo hacerlo: Clojure, al ser un lenguaje JVM, te permite utilizar directamente los métodos de String de Java. Aquí tienes un ejemplo básico de cómo capitalizar una cadena en Clojure: ```clojure (defn capitalize-string [s] (if (empty? s) s (str (clojure.string/upper-case (subs s 0 1)) (subs s 1)))) (capitalize-string "hello world!") ; => "Hello world!" ``` Clojure no incluye una función integrada específicamente para capitalizar cadenas, pero como se muestra, puedes lograr fácilmente esto combinando las funciones `clojure.string/upper-case`, `subs` y `str`. Para una solución más concisa y para manejar manipulaciones de cadenas más complejas, podrías recurrir a una biblioteca de terceros. Una biblioteca popular en el ecosistema de Clojure es `clojure.string`. Sin embargo, hasta mi última actualización, no ofrece una función directa de `capitalize` más allá de lo demostrado con las funcionalidades básicas de Clojure, por lo que el método mostrado arriba es tu enfoque directo sin necesidad de incluir bibliotecas adicionales específicamente para capitalización. Recuerda, cuando trabajas con cadenas en Clojure que interactúan con métodos de Java, efectivamente estás trabajando con cadenas de Java, lo que te permite aprovechar todo el arsenal de métodos de String de Java directamente en tu código Clojure si es necesario.
from collections import deque import copy from time import sleep from clear import clear from models import RobotDelivery # map -> https://miro.com/welcomeonboard/eG9MVm53TUJYQjRtOTNkSEhnamRWM2RCYVBDUklUckVMN3k3OUdsb2hQVjdJcEhpSmY1NjVJUnc0S3V4OHJZVXwzNDU4NzY0NTM2MDUzNzg0NTg4fDI=?share_link_id=306437873724 maps = [[4, 2, 1, 2, 4, 2, 1, 0, 4, 4], [2, 2, 1, 0, 4, 2, 1, 0, 2, 2], [1, 1, 1, 0, 0, 1, 1, 0, 1, 1], [2, 0, 1, 1, 1, 1, 1, 0, 1, 1], [1, 0, 1, 1, 3, 1, 1, 1, 1, 1], [1, 2, 2, 1, 1, 1, 0, 1, 1, 1], [1, 2, 2, 1, 1, 1, 1, 2, 2, 1], [1, 1, 1, 1, 0, 0, 1, 2, 4, 0], [1, 1, 2, 2, 4, 2, 1, 2, 2, 1], [1, 1, 2, 4, 4, 2, 1, 1, 1, 1]] # 0 - преграда # 1 - дорога для робота # 2 - адреса доставки # 3 - точка отправки # 4 - недоступная зона доставки def print_map(bot): print("Путь робота") for i in bot.route: row = '' for j in i: row += str(j).replace('0', '⬛️').replace('1', '⬜️').replace('2', '🏠').replace('3', '🏪').replace('4', '❌').replace('9', '📍') + ' ' print(row) def find_points(bot_map, start, end): # Определяем возможные направления движения: вправо, вниз, влево, вверх directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # Размеры матрицы rows = 10 cols = 10 # список посещенных ячеек visited = [[False] * cols for _ in range(rows)] # Отмечаем точку отправки как посещенную visited[start[0]][start[1]] = True # Используем очередь для BFS queue = deque([(start, [])]) while queue: current, path = queue.popleft() x, y = current # возвращаем найденный путь if current == end: return path + [current] # ищем соседние доступные ячейки for dx, dy in directions: nx, ny = x + dx, y + dy # можем мы посетить эту ячейку if 0 <= nx < rows and 0 <= ny < cols and bot_map[nx][ny] in [1, 9] and not visited[nx][ny]: visited[nx][ny] = True queue.append(((nx, ny), path + [current])) def find_route(bot: RobotDelivery): start = (4, 4) end = (bot.targetY, bot.targetX) bot.route = copy.deepcopy(maps) bot.route[bot.targetY][bot.targetX] = 9 route = find_points(bot.route, start, end) bot.estimated_delivery_time = len(route) - 1 print_map(bot) print(f'🕒 Примерное время ожидания (в минутах) +- {bot.estimated_delivery_time} 🕒') print('_' * 30) sleep(2) minutes = 1 for point in route[1:]: bot.route[point[0]][point[1]] = '🟩' print_map(bot) print(f'🕒 Примерное время ожидания (в минутах) +- {bot.estimated_delivery_time - minutes} 🕒') if bot.estimated_delivery_time - minutes != 0 else print("✅ Робот прибыл ✅") print('_' * 30) minutes+=1 sleep(2) print("Для получения заказа нажмите 1") while (int(input()) != 1): int(input()) print("✅ Заказ выдан ✅") sleep(1) clear()
package portals.benchmark class BenchmarkConfig: private var config = Map.empty[String, String] private var required = Set.empty[String] def args: List[String] = config.flatMap { case (k, v) => List(k.toString(), v.toString()) }.toList // check if required config parameters are set private def checkRequired(): Boolean = required.forall(config.contains) // internal recursive method private def _parseArgs(args: List[String]): Unit = args match case c :: value :: tail => config += (c -> value) _parseArgs(tail) case Nil => () case _ => ??? def parseArgs(args: List[String]): this.type = _parseArgs(args) if !checkRequired() then val missing = required.diff(config.keys.toSet) throw new IllegalArgumentException("Missing required arguments for BenchmarkConfig: " + missing) this def set(key: String, value: Any): this.type = config += (key -> value.toString) this def setRequired(key: String): this.type = required += key this def get(key: String): String = config(key) def getInt(key: String): Int = config(key).toInt
## ### Set Up a Local Redis Cache: Objective: Learn how to set up and use Redis as a local caching solution. Exercise: Install Redis on your local machine. Cache and retrieve a simple string. Explanation: This demonstrates remote cache and key expiration concepts. Use the SET command with an expiry time and GET command to retrieve the value. ### Implement Browser Caching: Objective: Understand client-side caching by implementing browser caching. Exercise: Configure your server to send caching headers with static assets (like images or CSS files) to instruct the browser to cache them. Explanation: This exercise demonstrates client-side caching and the importance of setting expiration headers to control cache duration. ### Configure a CDN for a Personal Project: Objective: Learn how to set up a CDN for a website or application. Exercise: Sign up for a free CDN service like Cloudflare, and configure it for your personal project or website. Explanation: You will understand how CDNs distribute content globally and the concept of lazy cache population. ### Load Testing with and without CDN: Objective: Observe the performance benefits of using a CDN. Exercise: Use a load testing tool to compare the response times of your website with and without CDN. Explanation: This will give you practical insights into how CDN can affect the load times and quick response delivery. ### Database Caching with Redis: Objective: Learn how to use Redis for database caching. Exercise: Cache a complex query result in Redis and retrieve it on subsequent requests. Explanation: This shows how caching can save expensive computations by storing frequently accessed data, as mentioned in the slides. ### Invalidation Strategy Implementation: Objective: Implement an invalidation strategy for cache data. Exercise: Write a script that updates the cache when the original data changes. Explanation: This simulates real-world scenarios where cached data needs to be invalidated when it becomes stale. ### Client-Side Caching in a Mobile App: Objective: Implement client-side caching in a mobile application. Exercise: Use a mobile development framework to cache data locally on the device. Explanation: This reinforces the concept of storing frequently accessed data on client devices to reduce backend calls. ### Monitor CDN Performance: Objective: Learn to monitor and analyze CDN performance. Exercise: Use CDN analytics to monitor cache hit rates and response times. Explanation: Monitoring CDN performance helps understand the benefits and limitations of CDNs in different regions. ### Cache Purging Mechanism: Objective: Create a mechanism to purge cached data. Exercise: Write a script that purges cache from a CDN when data updates. Explanation: This is a practical application of cache management, ensuring users get the most updated content. ### Implement Edge Side Includes (ESI): Objective: Learn to cache parts of web pages differently using ESI. Exercise: Use ESI in a web application to cache page fragments independently. Explanation: ESI allows for fine-grained caching control, crucial for dynamic content. ### A/B Testing with CDN: Objective: Learn how CDN can be used for A/B testing. Exercise: Use CDN features to serve different versions of a page to different users. Explanation: This demonstrates how CDNs can handle more than just caching but also user experience optimization. ### Setting Up a Reverse Proxy Cache: Objective: Understand reverse proxy caching by setting up one. Exercise: Configure a web server like Nginx or Varnish as a reverse proxy cache. Explanation: This teaches how a reverse proxy can reduce load on application servers by caching content. ### CDN Data Analytics: Objective: Analyze data usage patterns with CDN analytics. Exercise: Use CDN logs to analyze the most frequently accessed content and peak traffic times. Explanation: This helps in understanding content popularity and planning cache strategies accordingly. ### Create a Cache Invalidation API: Objective: Understand cache invalidation through API development. Exercise: Develop an API endpoint that invalidates specific cache keys when called. Explanation: This provides control over cache content and ensures data freshness. ### Simulate a Global CDN: Objective: Understand the distribution of content across different regions. Exercise: Simulate a CDN by setting up multiple server nodes and directing traffic based on geolocation. Explanation: This will help you grasp the concept of serving users from the closest server. ### Database Caching with IndexedDB in the Browser: Objective: Learn how to use IndexedDB for complex client-side database caching. Exercise: Store and retrieve data objects in a browser's IndexedDB. Explanation: This provides a deeper understanding of client-side caching possibilities beyond simple key-value storage. ### Implementing a Service Worker for Caching: Objective: Use service workers to cache dynamic content in a web application. Exercise: Create a service worker script that caches API responses for offline use. Explanation: This demonstrates the power of service workers in creating robust offline experiences. ### Optimizing Cache with GZIP Compression: Objective: Reduce cache size and improve performance with compression. Exercise: Configure your server to compress cached content with GZIP before storing it. Explanation: Compressing cached content can significantly improve load times and reduce bandwidth usage. ### Cache Warm-up Strategy: Objective: Implement a cache warm-up strategy to preload cache. Exercise: Develop a system that preloads the cache with essential data before peak times. Explanation: This ensures that the cache is populated with data before it's needed, avoiding cache misses during critical periods. ### Content Versioning for Cache Busting: Objective: Learn how to manage cache for static assets with content versioning. Exercise: Implement a versioning system that updates asset URLs with each release. Explanation: This technique, known as cache busting, ensures that users always receive the most recent files without having to manually clear their cache.
import { useSelector } from 'react-redux'; import classes from './Calendar.module.css'; import CalendarFooter from './CalendarFooter/CalendarFooter.jsx'; import CalendarBody from './CalendarBody/CalendarBody.jsx'; import { USER_ROLE } from '../core/UserRoleEnum'; import {useEffect, useState} from "react"; import EventCreateModal from "../CreateModal/EventCreateModal/EventCreateModal"; import {getEvents} from "../../store/services/services"; import {getUserToken} from "../../store/selectors/authSelector"; const Calendar = () => { const role = useSelector(state => state.user.role); const id = useSelector(state => state.user._id); const [modalEventCreate, setModalEventCreate] = useState(false); const [events, setEvents] = useState([]); const token = useSelector(getUserToken); useEffect(() => { const fetchData = async () => { const a = await getEvents(token); setEvents(a); }; fetchData(); }, [token]); const toggleEventModal = () => { setModalEventCreate(prev => !prev); } return ( <div style={{ width: '100%' }}> {modalEventCreate ? <EventCreateModal events={events} setEvents={setEvents} closeModal={toggleEventModal} /> : <></>} <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}> <h1 className={classes.title}>Календарь мероприятий</h1> {role !== USER_ROLE.NONE ? <div className='p-2 mt-1' role="button" onClick={toggleEventModal}> <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" fill="currentColor" className="bi bi-plus-circle" viewBox="0 0 16 16"> <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/> <path d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z"/> </svg> </div> : <></> } </div> {role !== USER_ROLE.NONE ? ( <CalendarBody events={events}/> ) : ( <div> <h2 className={classes.warning}> Ваш id: {id}. Сообщите Ваш id администратору / представителю региональной федерации. </h2> </div> )} <CalendarFooter /> </div> ); }; export default Calendar;
/* * Copyright 1999-2023 Percussion Software, Inc. * * 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.percussion.search; import java.util.Collection; import java.util.List; import java.util.Map; /** * This class is part of the pluggable, full text search engine architecture. * <p>Instances of this class must be obtained from the search engine interface. * <p>This class is responsible for providing access to the query engine of the * FTS framework. * * @author paulhoward */ public abstract class PSSearchQuery { /** * Used to control the maximum number of items allowed in the result set. * The default is -1, which means no limit. Pass this as a property in * the <code>controlProps</code> parameter of the <code>performSearch</code> * method. */ public static final String QUERYPROP_MAXRESULTS = "maxresults"; /** * Specifies which language the query should be processed in (word * expansion, etc.). The value should be of the form ll-cc, where ll is * the ISO 2 letter language code and cc is the 2 letter country code. * -cc is optional. If not provided or not supported, "en" is used. */ public static final String QUERYPROP_LANGUAGE = "language"; /** * Convenience method that calls {@link #performSearch(Collection, String, * Map, Map) performSearch(ctypeIds, globalQuery, fieldQueries, null)}. */ public List performSearch(Collection ctypeIds, String globalQuery, Map fieldQueries) throws PSSearchException { return performSearch(ctypeIds, globalQuery, fieldQueries, null); } /** * This method executes a basic search against the current indexes. The * <code>globalQuery</code> is a search string that is generally concept * based and is applied to all fields in an indexed unit. The <code> * fieldQueries</code> are a set of query strings that are generally * 'boolean' based and are applied only to specific fields. The <code> * globalQuery</code> and all field specific search strings are effectively * AND'd together to determine the final results. * <p>The syntax for all query strings is dependent on the implementation. * <p>A concept based search is one that performs various expansions of the * supplied words (such as finding items w/ 'eye' when the search word was * 'vision') and performs various statistics such as how many of the * search words were in the item, how close (physically or logically) * they were to each other to determine a relevancy ranking. * <p>A boolean search is one that looks for exact matches, no expansion * of the supplied words is done except for wildcard expansion. * * @param ctypeIds One of the search query filters. Each entry is a * PSKey. May be <code>null</code> or empty. The search is * limited to item fragments whose type matches one of those supplied. If * none are supplied, all content types are allowed. * * @param globalQuery This search parameter is applied to all fields * that have been indexed. May be empty or <code>null</code>. * * @param fieldQueries 0 or more field specific query strings. Each entry * has a <code>String</code> as the key, which is the field name, and a * <code>String</code> as value, which is the query string. Only item * fragments whose specific field match the query will be considered. May * be <code>null</code>. * * @param controlProps A set of name-value pairs that control how the * search is executed and how big the result set is. See the QUERYPROP_xxx * properties for descriptions of general properties. May be <code>null * </code> or empty to use default values as indicated for each * property. Other allowed properties are determined by the implementation. * Property names are case-insensitive. If invalid values are supplied, the * default will be used. Keys and values are all <code>String</code> objects. * * @return A list w/ 0 or more entries, up to a maximum of maxResults * entries, never <code>null</code>. Each entry is a PSSearchResult. The * locator in the result has the revision set to -1. * * @throws PSSearchException If the query cannot be successfully completed * for any reason. */ public abstract List performSearch(Collection ctypeIds, String globalQuery, Map fieldQueries, Map controlProps) throws PSSearchException; }
import { InMemoryAnswersRepository } from 'test/repositories/in-memory-answers-repository'; import { AnswerQuestionUseCase } from './answer-question'; import { UniqueEntityID } from '@/core/entities/unique-entity-id'; import { InMemoryAnswerAttachmentsRepository } from 'test/repositories/in-memory-answer-attachments-repository'; let inMemoryAnswerRepository: InMemoryAnswersRepository; let inMemoryAnswerAttachmentsRepository: InMemoryAnswerAttachmentsRepository; let sut: AnswerQuestionUseCase; describe('Create Question',() => { beforeEach(() => { inMemoryAnswerAttachmentsRepository = new InMemoryAnswerAttachmentsRepository(); inMemoryAnswerRepository = new InMemoryAnswersRepository(inMemoryAnswerAttachmentsRepository); sut = new AnswerQuestionUseCase(inMemoryAnswerRepository); }); it('should be able to create an answer', async () => { const result = await sut.execute({ questionId: '1', instructorId: '1', content: 'Conteúdo da resposta', attachmentsIds: ['1','2'] }); expect(result.isRight()).toBe(true); expect(inMemoryAnswerRepository.items[0]).toEqual(result.value?.answer); expect(inMemoryAnswerRepository.items[0].attachments.currentItems).toHaveLength(2); expect(inMemoryAnswerRepository.items[0].attachments.currentItems).toEqual([ expect.objectContaining({attachmentId: new UniqueEntityID('1')}), expect.objectContaining({attachmentId: new UniqueEntityID('2')}), ]); }); });
/* * Abstract syntax tree and symbol table for ordinary differential equations. * The datastructures are built by ode-parser, thus available after odeparse(). */ #ifndef AST_H #define AST_H #include <stdio.h> #include <string> #include <vector> #include <map> struct AstNumber; struct AstSymbol; struct AstVariable; struct BinaryOperator; struct UnaryOperator; struct BuiltInFunc; class AstVisitor { public: virtual void visit(AstNumber *node) = 0; virtual void visit(AstSymbol *node) = 0; virtual void visit(AstVariable *node) = 0; virtual void visit(BinaryOperator *node) = 0; virtual void visit(UnaryOperator *node) = 0; virtual void visit(BuiltInFunc *node) = 0; }; struct AST { virtual ~AST() {} virtual void symbol_check() const = 0; virtual void print(FILE *out) const = 0; virtual void accept(AstVisitor *visitor) = 0; }; struct AstNumber : public AST { double value; AstNumber(double v) : value{v} {} void symbol_check() const; void print(FILE *out) const; void accept(AstVisitor *visitor) { visitor->visit(this); }; }; // Symbol defined by equation struct AstSymbol : public AST { std::string name; AstSymbol(std::string n) : name{n} {} void symbol_check() const; void print(FILE *out) const; void accept(AstVisitor *visitor) { visitor->visit(this); }; }; // Variable/parameter not defined by equation struct AstVariable : public AST { std::string name; AstVariable(std::string n) : name{n} {} void symbol_check() const; void print(FILE *out) const; void accept(AstVisitor *visitor) { visitor->visit(this); }; }; struct BinaryOperator : public AST { char operat; AST *left; AST *right; BinaryOperator(char op, AST *l, AST *r) : operat{op}, left{l}, right{r} {} ~BinaryOperator() { delete left; delete right; } void symbol_check() const; void print(FILE *out) const; void accept(AstVisitor *visitor) { visitor->visit(this); }; }; struct UnaryOperator : public AST { char operat; AST *operand; UnaryOperator(char op, AST *oprnd) : operat{op}, operand{oprnd} {} ~UnaryOperator() { delete operand; } void symbol_check() const; void print(FILE *out) const; void accept(AstVisitor *visitor) { visitor->visit(this); }; }; struct BuiltInFunc : public AST { std::string name; AST *argument; BuiltInFunc(std::string n, AST *a) : name{n}, argument{a} {} ~BuiltInFunc() { delete argument; } void symbol_check() const; void print(FILE *out) const; void accept(AstVisitor *visitor) { visitor->visit(this); }; }; // Symbols in the symbol table struct Symbol { std::string name; int index; AST *equation; }; /** * Symbol table as a Singleton: a single instance with a global access point through get_instance(). * * Stores the ASTs of all the differential equations together with the symbols they define. * The index of each symbol corresponds to its index in the system of equations (using 0-based indexing). * * Stores declared parameters by their names with a float value which can be set at a later point. * * symbol_check() checks that all symbols used in equations are defined. Every name that is not declared * as a parameter is treated as a symbol and must be defined by an AST. * * free() deletes all the ASTs and resets the singleton. The AST destructos frees every node recursively */ class SymbolTable { public: static SymbolTable *get_instance(); // returns the signleton instance, and constructs it if it does not exist const Symbol& get_symbol(std::string name) const; const std::vector<Symbol>& get_symbols() const { return symbols; } int get_nr_of_equations() const { return nr_of_equations; } int find_symbol(std::string name) const; // returns the index of a symbol if it is defined, -1 else void add_symbol(std::string name, AST *equation); // makes a new symbol entry void symbol_check() const; void free(); double get_param_value(std::string name) { return parameters[name]; }; bool lookup_param(std::string name) const; void add_param(std::string name); // makes a new param entry with default value 1 void set_param(std::string name, double value); void print_symbols() const; // (debugging tool) prints all the symbol names to stdout void print_params() const; // (debugging tool) prints all the params to stdout SymbolTable(const SymbolTable&) = delete; // prevent copying SymbolTable& operator=(const SymbolTable&) = delete; private: // Private constructor and static instance to restrict access. SymbolTable() {}; static SymbolTable *singleton; std::vector<Symbol> symbols; // the table of symbols int nr_of_equations = 0; std::map<std::string, double> parameters; // the table of parameters }; #endif /* AST_H */
from torchinfo import summary from prettytable import PrettyTable from matplotlib import pyplot as plt import seaborn as sns from sklearn.metrics import roc_curve,auc # Print a Comprehensive Summary of the Model, Modules, Submodules, Parameter Counts def model_summary(model, generator): review_batch, label, mask_batch = next(generator) print(summary(model, input_data=[review_batch.to("cuda:0"), mask_batch.to("cuda:0")])) # Utility function to print the Modules, SubModules and their Corresponding trainable parmeters in a Clean Table Structure def count_parameters(model): table = PrettyTable(["Modules", "Parameters"]) total_params = 0 for name, parameter in model.named_parameters(): if not parameter.requires_grad: continue params = parameter.numel() table.add_row([name, params]) total_params += params print(table) print(f"Total Trainable Params: {total_params}") return total_params # plot the training loss and training, testing accuracy #def plot_metrics(num_epochs, batch_per_epoch_train,batch_per_epoch_test,train_loss, train_acc, test_acc): # # X axis Epoch # train_epochs = list(range(1, (batch_per_epoch_train * num_epochs) + 1)) # test_epochs = list(range(1, (batch_per_epoch_test * num_epochs) + 1)) # # Create subplots for train loss and accuracy # plt.figure(figsize=(24, 3)) # # Plot Train Loss # plt.plot(train_epochs, train_loss, label='Train Loss') # plt.xlabel('Epoch') # plt.ylabel('Loss') # plt.title('Training Loss') # plt.legend() # # Plot Train Accuracy # plt.figure(figsize=(24, 3)) # # plt.subplot(1, 2, 2) # plt.plot(train_epochs, train_acc, label='Train Accuracy') # plt.xlabel('Epoch') # plt.ylabel('Accuracy') # plt.title('Training Accuracy') # plt.legend() # # Plot Test Accuracy # plt.figure(figsize=(24, 3)) # plt.plot(test_epochs, test_acc, label='Test Accuracy') # plt.xlabel('Epoch') # plt.ylabel('Accuracy') # plt.title('Testing Accuracy') # plt.legend() # # Adjust layout # #plt.tight_layout() # # Show the plots # plt.show() #in single frame # def plot_metrics(num_epochs, batch_per_epoch_train, batch_per_epoch_test, train_loss, train_acc, test_acc): # # Calculate epochs # train_epochs = list(range(1, (batch_per_epoch_train * num_epochs) + 1)) # test_epochs = list(range(1, (batch_per_epoch_test * num_epochs) + 1)) # # Create subplots # fig, axes = plt.subplots(3, 1, figsize=(12,12)) # # Plot Train Loss # axes[0].plot(num_epochs, train_loss, label='Train Loss') # axes[0].set_xlabel('Epoch') # axes[0].set_ylabel('Loss') # axes[0].set_title('Training Loss') # axes[0].legend() # # Plot Train Accuracy # axes[1].plot(num_epochs, train_acc, label='Train Accuracy') # axes[1].set_xlabel('Epoch') # axes[1].set_ylabel('Accuracy') # axes[1].set_title('Training Accuracy') # axes[1].legend() # # Plot Test Accuracy # axes[1].plot(num_epochs, test_acc, label='Test Accuracy') # axes[1].set_xlabel('Epoch') # axes[1].set_ylabel('Accuracy') # axes[1].set_title('Testing Accuracy') # axes[1].legend() # # Adjust layout # plt.subplots_adjust(hspace=0.75) # #plt.tight_layout() # # Show the plots # plt.show() def plot_metrics(train_loss, train_acc, test_loss, test_acc): epochs = list(range(1, len(train_acc) + 1)) plt.figure(figsize=(12, 5)) # Plot Training and Testing Accuracy plt.subplot(1, 2, 1) plt.plot(epochs, train_acc, 'b', label='Training acc') plt.plot(epochs, test_acc, 'r', label='Validation acc') plt.title('Training and Validation Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() # Plot Training and Testing Loss plt.subplot(1, 2, 2) plt.plot(epochs, train_loss, 'b', label='Training loss') plt.plot(epochs, test_loss, 'r', label='Validation loss') plt.title('Training and Validation Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() def plot_confusion_matrix(cm): plt.figure(figsize=(8, 6)) sns.heatmap(cm, annot=True, cmap='Blues', fmt='d', cbar=False) plt.xlabel('Predicted labels') plt.ylabel('True labels') plt.title('Confusion Matrix') plt.show() def calculate_metrics(TP,TN,FP,FN): # Calculate accuracy accuracy = (TP + TN) / (TP + TN + FP + FN) print("Accuracy:", accuracy) # Calculate precision precision = TP / (TP + FP) print("Precision:", precision) # Calculate recall recall = TP / (TP + FN) print("Recall:", recall) # Calculate F1 score f1 = (2 * precision * recall) / (precision + recall) print("F1 Score:", f1) def plot_roc_curve(y_true, y_score): """ Function to plot the ROC curve. Parameters: y_true: array-like, true binary labels. y_score: array-like, predicted probabilities or decision function scores. Returns: None (plots ROC curve) """ fpr, tpr, thresholds = roc_curve(y_true, y_score) roc_auc = auc(fpr, tpr) plt.figure(figsize=(8, 6)) plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (area = {roc_auc:.2f})') plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver Operating Characteristic (ROC) Curve') plt.legend(loc='lower right') plt.show()
package com.example.notes; import androidx.annotation.NonNull; import androidx.room.Entity; import androidx.room.Ignore; import androidx.room.PrimaryKey; import java.io.Serializable; @Entity(tableName = "notes") public class Note implements Serializable { @PrimaryKey(autoGenerate = true) private int id; private String title; private String dateTime; private String subtitle; private String noteText; private String color; public Note(int id, String title, String dateTime, String subtitle, String noteText, String color) { this.id = id; this.title = title; this.dateTime = dateTime; this.subtitle = subtitle; this.noteText = noteText; this.color = color; } @Ignore public Note(String title, String dateTime, String subtitle, String noteText, String color) { this.title = title; this.dateTime = dateTime; this.subtitle = subtitle; this.noteText = noteText; this.color = color; } @Ignore public Note(){ } public int getId() {return id;} public String getTitle() {return title;} public String getDateTime() {return dateTime;} public String getSubtitle() {return subtitle;} public String getNoteText() {return noteText;} public String getColor() {return color;} public void setId(int id) {this.id = id;} public void setTitle(String title) {this.title = title;} public void setDateTime(String dateTime) { this.dateTime = dateTime; } public void setSubtitle(String subtitle) { this.subtitle = subtitle; } public void setNoteText(String noteText) { this.noteText = noteText; } public void setColor(String color) { this.color = color; } @NonNull @Override public String toString() { return title + ":" + dateTime; } }
/** * IJA 2018/2019 * Projekt - Šachy/Dáma * * Abstraktní třída pro figurky * * @author Radek Duchoň (xducho07) * @author Jan Juda (xjudaj00) * @author Josef Oškera (xosker03) */ package ija2019.game; /** * Abstraktní třída pro figurky */ public abstract class Figure{ private boolean jeBily; protected Field pole; protected char znakFigurky = 'X'; /** * Vytvoří figurku dané barvy * @param isWhite - true pro bílou figurku, false pro černou */ public Figure(boolean isWhite){ jeBily = isWhite; pole = null; } /** * @return True, pokud je figurka bílá. */ public boolean isWhite(){ return jeBily; } /** * @return Vrací znak reprezentující typ figurky */ public char getChar(){ return znakFigurky; } /** Funkce pro nastavení políčka, na kterém se tenta figurka nachází. Null signalizuje, že se nenachází na žádném políčku. * @param field - nové políčko */ public void setField(Field field){ pole = field; } /** * @return Vrací políčko, na kterém stojí figurka. */ public Field getField() { return pole; } /** Funkce implementovaná u každé figurky, která nám řekne, jestli figurka dokáže dojít na zadané políčko. * * @param moveTo - políčko, kam se má figurka pohnout * @return True, pokud se figurka může ponout na toto políčko. */ abstract public boolean canIGoTo(Field moveTo); /** Funkce která v základu otestuje pohyb na cíl přes canIGoTo a pak se pohne na cílové políčko a popřípadě vyhodí na něm stojící figurku. * * @param moveTo - políčko, kam se má figurka pohnout * @return True, pokud byl pohyb úspěšný. */ public boolean move(Field moveTo){ if(! canIGoTo(moveTo)) return false; pole.remove(this); moveTo.remove(moveTo.get()); //toto nám zajistí správně fungující vyhazování moveTo.put(this); return true; } /** Funkce pro kontrolu volné cesty * Pre-condition: políčka začátek a cíl patří do stejného boardu a leží ve stejném řádku, ve stejném sloupci nebo na diagonálách. * @param zacatek - počáteční políčko cesty * @param cil - koncové políčko cesty * @param smer - směr jakým máme cestovat * @return - Vrací true, pokud na cestě mezi začátkem a cílem v zadaném smětu leží figurka nebo je směr špatný, jinak vrací false. */ protected boolean kamenNaCeste(Field zacatek, Field cil, Field.Direction smer){ while((zacatek = zacatek.nextField(smer)) != cil){ if (zacatek == null) return true; //Pokud figurka uteče z plochy, tak do cíle tímto směrem nedojde if(!zacatek.isEmpty()) return true; //políčko není prázdné - něco je mezi zdrojovým a cílovým = konec } return false; } /** Funkce zkontroluje, zda zadané políčko je prázdné nebo na něm stojí figurka opačné barvy * Pouze pro ŠACHY * @param policko * @return true, pokud je políčko prázné nebo na něm stojí figurka opačné barvy */ protected boolean muzeNa(Field policko){ boolean result = policko.isEmpty() || policko.get().isWhite() != this.isWhite(); return result; } }
import ContactItem from './ContactItem/ContactItem'; import css from './ContactList.module.css'; import { useSelector } from 'react-redux'; import { selectFilteredContacts } from 'redux/selectors'; export default function ContactList() { const contacts = useSelector(selectFilteredContacts); return ( <table className={css.table}> <thead> <tr> <th>Name</th> <th>Phone</th> <th>Delete</th> </tr> </thead> <tbody> {contacts.map(({ id, name, phone }) => { return ( <tr key={id}> <ContactItem id={id} name={name} phone={phone} /> </tr> ); })} </tbody> </table> ); }
""" Copyright 2017 Pedro Santos <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. """ import os, dbus, dbus.service from dbus.mainloop.glib import DBusGMainLoop from dbus.gi_service import ExportedGObject SERVICE_NAME = "io.github.poco" SERVICE_OBJECT_PATH = "/io/github/poco" class NavigatorBusService (ExportedGObject): def __init__(self, stop_function=None): self.stop_function = stop_function self.main_loop = DBusGMainLoop(set_as_default=True) dbus.mainloop.glib.threads_init() self.bus = dbus.Bus() if not self.bus: print("no session") quit() if self.bus.name_has_owner(SERVICE_NAME): pid = RemoteInterface().get_running_instance_id() print("poco is already running, pid: " + pid) quit() bus_name = dbus.service.BusName(SERVICE_NAME, self.bus) super(NavigatorBusService, self).__init__(conn=self.bus, object_path=SERVICE_OBJECT_PATH, bus_name=bus_name) @dbus.service.method("io.github.poco.Service", in_signature='', out_signature='s') def get_id(self): return str(os.getpid()) @dbus.service.method("io.github.poco.Service", in_signature='', out_signature='') def stop_poco(self): self.stop_function() def release(self): self.bus.release_name(SERVICE_NAME) print('poco service were released from bus') class RemoteInterface: def __init__(self): self.bus = dbus.Bus() if not self.bus: print("no session") quit() def get_status(self): if self.bus.name_has_owner(SERVICE_NAME): return "Active, pid: " + self.get_running_instance_id() else: return "Inactive" def get_running_instance_id(self): service = self.bus.get_object(SERVICE_NAME, SERVICE_OBJECT_PATH) get_remote_id = service.get_dbus_method('get_id', 'io.github.poco.Service') return get_remote_id() def stop_running_instance(self): if self.bus.name_has_owner(SERVICE_NAME): service = self.bus.get_object(SERVICE_NAME, SERVICE_OBJECT_PATH) quit_function = service.get_dbus_method('stop_poco', 'io.github.poco.Service') quit_function() print("Remote instance were stopped") else: print("poco is not running")
/******************************************************************** ** Image Component Library (ICL) ** ** ** ** Copyright (C) 2006-2013 CITEC, University of Bielefeld ** ** Neuroinformatics Group ** ** Website: www.iclcv.org and ** ** http://opensource.cit-ec.de/projects/icl ** ** ** ** File : ICLUtils/src/ICLUtils/Rect.h ** ** Module : ICLUtils ** ** Authors: Christof Elbrechter, Robert Haschke ** ** ** ** ** ** GNU LESSER GENERAL PUBLIC LICENSE ** ** This file may be used under the terms of the GNU Lesser General ** ** Public License version 3.0 as published by the ** ** ** ** Free Software Foundation and appearing in the file LICENSE.LGPL ** ** included in the packaging of this file. Please review the ** ** following information to ensure the license requirements will ** ** be met: http://www.gnu.org/licenses/lgpl-3.0.txt ** ** ** ** The development of this software was supported by the ** ** Excellence Cluster EXC 277 Cognitive Interaction Technology. ** ** The Excellence Cluster EXC 277 is a grant of the Deutsche ** ** Forschungsgemeinschaft (DFG) in the context of the German ** ** Excellence Initiative. ** ** ** ********************************************************************/ #pragma once #include <ICLUtils/Macros.h> #include <ICLUtils/Point.h> #include <ICLUtils/Size.h> #include <stdio.h> #include <algorithm> #ifdef ICL_HAVE_IPP #include <ipp.h> #endif namespace icl { namespace utils{ #ifndef ICL_HAVE_IPP /// fallback implementation for the IppiRect struct, defined in the ippi lib \ingroup TYPES struct IppiRect { /// xpos of upper left corner int x; /// ypos of upper left corner int y; /// width int width; /// height int height; }; #else #endif /// Rectangle class of the ICL used e.g. for the Images ROI-rect \ingroup TYPES /** Please take care of the following conventions when using Rects in the ICL library: <pre> |------ width ------>| ............................ ............................ origin(x,y)---->Xooooooooooooooooooooo.... ___ ..oooooooooooooooooooooo.... /|\ ..oooooooooooooooooooooo.... | ..oooooooooooooooooooooo.... height ..oooooooooooooooooooooo.... | ..oooooooooooooooooooooo.... _|_ ............................ ............................ </pre> Please note, that a rect fits a discrete set of points: For instance the Rect (x=2,y=1,width=3,height=4) contains exactly 3x4=12 points i.e. those ones with \f$x \in {2,3,4}\f$ and \f$y \in {1,2,3,4}\f$. Hence a full image roi of an image of size 640x480 has an offset of (0,0), a size of 640x480, but it contains only x-values within the range 0-639 and y-values within range 0-479. */ /** \cond */ class Rect32f; /** \endcond*/ class ICLUtils_API Rect : public IppiRect{ public: /// null Rect is w=0, h=0, x=0, y=0 static const Rect null; /// default constructor Rect(){ this->x = 0; this->y = 0; this->width = 0; this->height = 0; } /// creates a defined Rect Rect(int x, int y, int width, int height){ this->x = x; this->y = y; this->width = width; this->height = height; } /// creates a new Rect with specified offset and size Rect(const Point &p, const Size &s){ this->x = p.x; this->y = p.y; this->width = s.width; this->height = s.height; } /// create a deep copy of a rect Rect(const Rect &r){ this->x = r.x; this->y = r.y; this->width = r.width; this->height = r.height; } /// creates a Rect from given Rect32f instance Rect(const Rect32f &other); /// checks wether the object instance is null, i.e. all elements are zero bool isNull() const { return (*this)==null; } /// checks if two rects are equal bool operator==(const Rect &s) const { return x==s.x && y==s.y && width==s.width && height==s.height; } /// checks if two rects are not equal bool operator!=(const Rect &s) const { return x!=s.x || y!= s.y || width!=s.width || height!=s.height; } /// scales all parameters of the rect by a double value Rect operator*(double d) const { return Rect((int)(d*x),(int)(d*y),(int)(d*width),(int)(d*height)); } /// scales all parameters of the rect by a double value Rect operator/(double d) const { return Rect((int)(x/d),(int)(y/d),(int)(width/d),(int)(height/d)); } /// adds a size to the rects size Rect operator+(const Size &s) const{ return Rect(x,y,width+s.width,height+s.height); } /// substracts a size for the rects size Rect operator-(const Size &s) const{ return Rect(x,y,width-s.width,height-s.height); } /// adds a size to the rects size Rect& operator+=(const Size &s){ width+=s.width; height+=s.height; return *this; } /// substracs a size from the rects size Rect& operator-=(const Size &s){ width-=s.width; height-=s.height; return *this; } /// adds a Point to the rects offset Rect operator+(const Point &p) const{ return Rect(x+p.x,y+p.y,width,height); } /// substracts a Point from the rects offset Rect operator-(const Point &p) const{ return Rect(x-p.x,y-p.y,width,height); } /// adds a Point to the rects offset Rect& operator+=(const Point &p){ x+=p.x; y+=p.y; return *this; } /// substracts a Point from the rects offset Rect& operator-=(const Point &p){ x-=p.x; y-=p.y; return *this; } /// scales all rect params inplace Rect& operator*=(double d){ x=(int)((float)x*d); y=(int)((float)y*d); width=(int)((float)width*d); height=(int)((float)height*d); return *this; } /// scales all rect params inplace Rect& operator/=(double d){ x=(int)((float)x/d); y=(int)((float)y/d); width=(int)((float)width/d); height=(int)((float)height/d); return *this; } /// returns width*height int getDim() const {return width*height;} /// intersection of two Rects Rect operator&(const Rect &r) const { Point ul (iclMax(x, r.x), iclMax(y, r.y)); Point lr (iclMin(right(), r.right()), iclMin(bottom(), r.bottom())); Rect result (ul.x, ul.y, lr.x-ul.x, lr.y-ul.y); if (result.width > 0 && result.height > 0) return result; else return null; } /// inplace intersection of two rects Rect &operator&=(const Rect &r){ (*this)=(*this)&r; return *this; } /// union of two Rects Rect operator|(const Rect &r) const { Point ul (iclMin(x, r.x), iclMin(y, r.y)); Point lr (iclMax(right(), r.right()), iclMax(bottom(), r.bottom())); return Rect (ul.x, ul.y, lr.x-ul.x, lr.y-ul.y); } /// inplace union of two rects Rect &operator|=(const Rect &r){ (*this)=(*this)|r; return *this; } /// rects with negative sizes are normalized to Positive sizes /** e.g. the rect (5,5,-5,-5) is normalized to (0,0,5,5) */ Rect normalized() const { Rect r (*this); if (r.width < 0) {r.x += r.width; r.width = -r.width; } if (r.height < 0) {r.y += r.height; r.height = -r.height; } return r; } /// returns if a Rect containes another rect bool contains(const Rect &r) const { return x<=r.x && y <= r.y && right() >= r.right() && bottom() >= r.bottom(); } /// returns if the Rect contains a given point (pixel-based) /** <b>Note:</b> We are talking here in terms of pixel-based rects: The rect x=5,y=5,width=10,height=20 contains the x-indices withing the interval [5,15[ (half-opened interval). In terms of discrete X-values, the intervall meets the set {5,6,...13,14}. The same is true for Y-values.*/ bool contains(int x, int y) const{ return this->x<=x && right()>x && this->y<=y && bottom()>y; } /// let the rect grow by k pixles into each direction /** if k<0 the rect becomes smaller E.g. Rect(10,10,90,90).enlarge(10) creates a Rect (0,0,100,100) @param k amount of pixel the rectangle is enlarged by @return *this */ Rect &enlarge(int k){ x-=k; y-=k; width+=2*k; height+=2*k; return *this; } /// returns an enlarged instance of this rect /** @see enlarge(int)*/ Rect enlarged(int k) const{ return Rect(*this).enlarge(k); } /// returns upper left point of the rect Point ul() const { return Point(x,y); } /// returns lower left point of the rect Point ll() const { return Point(x,y+height); } /// returns upper right point of the rect Point ur() const { return Point(x+width,y); } /// returns lower right point of the rect Point lr() const { return Point(x+width,y+height); } /// returns the center Point of the rect Point center() const { return Point(x+width/2,y+height/2); } /// returns the left border position int left() const { return x; } /// returns the right border position int right() const { return x+width; } /// returns the position of the bottom border int bottom() const { return y+height; } /// returns the position of the upper border int top() const { return y; } /// returns the size of the rect Size getSize() const { return Size(width,height); } Rect transform(double xfac, double yfac) const { return Rect((int)(xfac*x),(int)(yfac*y),(int)(xfac*width), (int)(yfac*height)); } }; /// ostream operator (x,y)wxy ICLUtils_API std::ostream &operator<<(std::ostream &s, const Rect &r); /// istream operator ICLUtils_API std::istream &operator>>(std::istream &s, Rect &r); } // namespace utils } // namespace icl
import React from "react"; export const useOutsideClick = (callback) => { const ref = React.useRef(); React.useEffect(() => { const handleClick = (event) => { if (ref.current && !ref.current.contains(event.target)) { callback(); } }; document.addEventListener("click", handleClick); return () => { document.removeEventListener("click", handleClick); }; }, [ref]); return ref; };
const express = require('express'); const mongoose = require('mongoose'); const dotenv = require('dotenv'); const morgan = require('morgan'); const passport = require('passport'); const exphbs = require('express-handlebars'); const session = require('express-session'); const MongoStore = require('connect-mongo'); const methodOverride = require('method-override'); const path = require('path'); const connectDB = require('./db.js'); // Load Config dotenv.config({ path: './config/.env' }); // Passport config require('./config/passport-config.js')(passport); //Connect to DB connectDB(); const app = express(); //Body Parser app.use(express.urlencoded({ extended: false })); app.use(express.json()); // Method Override app.use(methodOverride('_method')); // Logging if (process.env.NODE_ENV === 'development') { app.use(morgan('dev')); } // Handlebars Helpers const { formatDate, stripTags, truncate, editIcon, select } = require('./helpers/hbs.js'); // Handlebars app.engine( '.hbs', exphbs.engine({ helpers: { formatDate, stripTags, truncate, editIcon, select, }, defaultLayout: 'main', extname: '.hbs', }), ); app.set('view engine', '.hbs'); // Session middleware app.use( session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false, store: MongoStore.create({ mongoUrl: process.env.MONGODB_URL, }), }), ); // Passport middleware app.use(passport.initialize()); app.use(passport.session()); // Set global var app.use((req, res, next) => { res.locals.user = req.user || null; next(); }); // Static folder app.use(express.static(path.join(__dirname, '/public'))); // Routes app.use('/', require('./routers/index.js')); app.use('/auth', require('./routers/auth.js')); app.use('/stories', require('./routers/stories.js')); const PORT = process.env.PORT || 5000; app.listen(PORT, console.log(`Server is running in ${process.env.NODE_ENV} mode on port ${PORT}`));
# Demo-bug-report-generator Demo to compare bug reports generated by LLM or from scratch # Introduction This is a general demonstration of how we can aid the beginners to create bug reports by simply inputting ONLY 4 parameters, i.e. 2 pairs of request-response for normal-browsing, and that of successfully hacked. The LLM can compare the difference and find out the hacking logic behind, i.e. how the hacker successfully exploited the vulnerability, thus returning details of the reports including `summary`, `step to reproduce` and `recommendation to fix this vulnerability` ## Impact - With this tool, by interview, the beginners said they have saved 1 hour for producing one bug report and agree that they are more attached to our platform because of having this helping tool. - They also said that the tool helped them to write a better report other than saving time: - More Structural (Best practice format: summary, step of reproduction, recommendation), especially most of the beginners usually write too detailed or too brief for step of reproduce - Superior knowledge (Most of the time, inexperienced hackers cannot give recommendations) - More professional (No grammatical mistakes) - Generated in 2 seconds instead of 60 minutes ## Technical details - We will apply `gemini-pro` model from Google as most of our input exceeds `gpt-3.5-turbo` maximum token limit (4,096 tokens), while Gemini-Pro can ingest 32,000 tokens for input. - For generating a prompt template of `generating bug report in your custom style` with input variables of parameters (2 pairs of request-response in this case), please read the steps from my Medium article `Generating a report in a tailored format using Reverse Prompt Engineering` : https://medium.com/@miltonchan_85581/generating-a-report-in-a-tailored-format-using-reverse-prompt-engineering-16d1944a6413 # Further optimization ### User Feedback In real-time endpoint serving, users may report that the latency (waiting time) will be too long as the LLM may process for a few seconds, while the UI shows no response before the LLM completes processing, i.e. output __all the texts__. ### Solution The Latency may lead to users dropping out. To fix this, we can adopt a streaming property which outputs the texts in chunks so the users can see the progress of loading and they will be more willing to wait. ### Technical details By Setting ```stream=True```, LLM will output the texts in chunks ``` python response = model.generate_content(bugreport_prompt , generation_config=genai.types.GenerationConfig(temperature=0), safety_settings=safety_settings, stream=True # output text in chunks ) for response in responses: print(response.text, end="") ``` ![Screenshot of a comment on a GitHub issue showing an image, added in the Markdown, of an Octocat smiling and raising a tentacle.](https://github.com/chanyanhon/Demo-bug-report-generator/blob/main/screencap/LLM_streaming_output.gif) ## Bug Report Before & After using LLM tool ### Example 1 Before tools ![Screenshot of a comment on a GitHub issue showing an image, added in the Markdown, of an Octocat smiling and raising a tentacle.](https://github.com/chanyanhon/Demo-bug-report-generator/blob/main/screencap/eg1_pre.png?raw=true) After tools ![Screenshot of a comment on a GitHub issue showing an image, added in the Markdown, of an Octocat smiling and raising a tentacle.](https://github.com/chanyanhon/Demo-bug-report-generator/blob/main/screencap/eg1_post.png?raw=true) ### Example 2 Before tools ![Screenshot of a comment on a GitHub issue showing an image, added in the Markdown, of an Octocat smiling and raising a tentacle.](https://github.com/chanyanhon/Demo-bug-report-generator/blob/main/screencap/eg2_pre.png?raw=true) After tools ![Screenshot of a comment on a GitHub issue showing an image, added in the Markdown, of an Octocat smiling and raising a tentacle.](https://github.com/chanyanhon/Demo-bug-report-generator/blob/main/screencap/eg2_post.png?raw=true) ### Example 3 Before tools ![Screenshot of a comment on a GitHub issue showing an image, added in the Markdown, of an Octocat smiling and raising a tentacle.](https://github.com/chanyanhon/Demo-bug-report-generator/blob/main/screencap/eg3_pre.png?raw=true) After tools ![Screenshot of a comment on a GitHub issue showing an image, added in the Markdown, of an Octocat smiling and raising a tentacle.](https://github.com/chanyanhon/Demo-bug-report-generator/blob/main/screencap/eg3_post.png?raw=true) ### Example 4 Before tools ![Screenshot of a comment on a GitHub issue showing an image, added in the Markdown, of an Octocat smiling and raising a tentacle.](https://github.com/chanyanhon/Demo-bug-report-generator/blob/main/screencap/eg4_pre.png?raw=true) After tools ![Screenshot of a comment on a GitHub issue showing an image, added in the Markdown, of an Octocat smiling and raising a tentacle.](https://github.com/chanyanhon/Demo-bug-report-generator/blob/main/screencap/eg4_post.png?raw=true)
/* * Copyright (C) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <optional> #include <span> #include <wtf/EnumTraits.h> namespace IPC { class Decoder; class Encoder; template<typename T, typename = void> struct ArgumentCoder; template<> struct ArgumentCoder<bool> { template<typename Encoder> static void encode(Encoder& encoder, bool value) { uint8_t data = value ? 1 : 0; encoder << data; } template<typename Decoder> static std::optional<bool> decode(Decoder& decoder) { auto data = decoder.template decode<uint8_t>(); if (data && *data <= 1) // This ensures that only the lower bit is set in a boolean for IPC messages return !!*data; return std::nullopt; } }; template<typename T> struct ArgumentCoder<T, typename std::enable_if_t<std::is_arithmetic_v<T>>> { template<typename Encoder> static void encode(Encoder& encoder, T value) { encoder.encodeObject(value); } template<typename Decoder> static std::optional<T> decode(Decoder& decoder) { return decoder.template decodeObject<T>(); } }; template<typename T> struct ArgumentCoder<T, typename std::enable_if_t<std::is_enum_v<T>>> { template<typename Encoder> static void encode(Encoder& encoder, T value) { ASSERT(WTF::isValidEnum<T>(WTF::enumToUnderlyingType<T>(value))); encoder << WTF::enumToUnderlyingType<T>(value); } template<typename Decoder> static std::optional<T> decode(Decoder& decoder) { std::optional<std::underlying_type_t<T>> value; decoder >> value; if (value && WTF::isValidEnum<T>(*value)) return static_cast<T>(*value); return std::nullopt; } }; }
// express 라이브러리 기본 셋팅 const express = require('express'); require('dotenv').config() const app = express(); const http = require('http').createServer(app); const {Server} = require('socket.io') const io = new Server(http); const bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: true })) const MongoClient = require('mongodb').MongoClient; const methodOverride = require('method-override') app.use(methodOverride('_method')) app.set('view engine', 'ejs') const {ObjectId} = require('mongodb') // static 파일을 보관하기 위해 public 폴더를 쓸거다 app.use('/public', express.static('public')) var db; MongoClient.connect(process.env.DB_URL, function (error, client) { var db = client.db('todoapp') // 8080 port로 웹서버를 열고 잘 열리면 console 출력 if (error) return console.log(error) app.post('/add', function (request, response) { response.send('전송완료') console.log(request.body.title) console.log(request.body.date) db.collection('counter').findOne({name : '게시물갯수'}, function(error, result){ console.log(result.totalPost) var 총게시물갯수 = result.totalPost var 저장할거 = { _id : (총게시물갯수+1), 제목: request.body.title, 날짜: request.body.date , 작성자 : request.user._id} db.collection('post').insertOne(저장할거, function (error, result) { console.log('저장완료') db.collection('counter').updateOne({name : '게시물갯수'},{ $inc:{totalPost : 1}},function(error, result){ // update operator $set => 바꿀값 if(error) return console.log(error) // increment operator $inc => 기존값에 더해줄 값 }) }); }) }) app.post('/message',isLogin, function(req, res){ var 채팅내용 = { parent : req.body.parent, userid : req.user._id, content : req.body.content, date : new Date() } db.collection('message').insertOne(채팅내용) .then((result)=>{ res.send(result) }).catch(()=>{ }) }) // 여기로 get요청하면 실시간 채널이 오픈이 됨 app.get('/message/:id', isLogin, function(req, res){ res.writeHead(200,{ "Connection" : "keep-alive", "Content-Type" : "text/event-stream", "Cache-Control" : "no-cache" }); db.collection('message').find({parent : req.params.id}).toArray() .then((result)=>{ res.write('event: test\n') res.write('data: ' + JSON.stringify(result) + '\n\n') }) const pipeline = [ { $match : { 'fullDocument.parent': req.params.id}} ]; const collection = db.collection('message'); const changeStream = collection.watch(pipeline); // watch()를 붙이면 실시간 감시해줌 // 해당 컬렉션에 변동생기면 여기 코드 실행됨 changeStream.on('change', (result)=>{ res.write('event: test\n') res.write('data: ' + JSON.stringify([result.fullDocument]) + '\n\n') }) }) http.listen(8080, function () { console.log('listening on 8080') }); app.get('/socket',function(req, res) { res.render('socket.ejs') }) // 누가 웹소켓 접속하면 내부 코드 실행해주세요 io.on('connection', function(socket){ console.log('유저 접속됨') // 채팅방 만들고 입장 socket.on('joinroom',function(data){ socket.join('room1') }) socket.on('room1-send',function(data){ io.to('room1').emit('broadcast',data) }) socket.on('user-send',function(data){ console.log(data) io.emit('broadcast', data) // 모든 유저에게 메세지 보내줌 io.to(socket.id).emit('broadcast', data) // to 특정유저에게만 보내줌 }) }) app.get('/list', function (request, response){ // db에 저장된 post라는 collection 안의 모든 데이터 꺼내기 db.collection('post').find().toArray(function(error, result){ console.log(result) response.render('list.ejs', {posts : result}) }) }) app.delete('/delete', function(request, response){ request.body._id = parseInt(request.body._id) db.collection('post').deleteOne({_id : request.body._id , 작성자 : request.user._id}, function(error, result){ console.log('삭제완료') response.status(200).send({ message : '성공했습니다'}) }) }); app.get('/detail/:id', function(request, response){ db.collection('post').findOne({_id :parseInt(request.params.id)},function(error, result){ console.log(result) response.render('detail.ejs', { data : result}) }) }) app.get('/edit/:id', function(request,response){ db.collection('post').findOne({_id:parseInt(request.params.id)}, function(error, result){ response.render('edit.ejs',{ post : result }) }) }) app.put('/edit', function(request, response){ db.collection('post').updateOne({_id : parseInt(request.body.id)}, {$set : {제목 : request.body.title, 날짜 : request.body.date}}, function(err, res){ console.log("수정완료") response.redirect('/list') }) }) app.get('/login', function(request, response){ response.render('login.ejs') }) app.post('/login', passport.authenticate('local',{ failureRedirect : '/fail' }),function(request, response){ response.redirect('/') }) app.get('/fail', function(request, response){ response.render('fail.ejs') }) passport.use(new LocalStrategy({ usernameField: 'id', passwordField: 'pw', session: true, passReqToCallback: false, }, function (입력한아이디, 입력한비번, done) { console.log(입력한아이디, 입력한비번); db.collection('login').findOne({ id: 입력한아이디 }, function (에러, 결과) { if (에러) return done(에러) if (!결과) return done(null, false, { message: '존재하지않는 아이디요' }) if (입력한비번 == 결과.pw) { return done(null, 결과) } else { return done(null, false, { message: '비번틀렸어요' }) } }) })); passport.serializeUser(function(user,done){ done(null, user.id) }) passport.deserializeUser(function(아이디,done){ db.collection('login').findOne({id: 아이디}, function(err,res){ done(null, res) }) }) app.post('/register', function(req, res){ db.collection('login').insertOne({id : req.body.id , pw : req.body.pw}, function(err, result){ res.redirect('/') }) }) app.get('/mypage', isLogin,function(request,response){ console.log(request.user) response.render('mypage.ejs', {사용자 : request.user}) }) function isLogin(request,response, next){ if(request.user){ next() } else { response.send('로그인 안함') } } app.post('/chatroom', isLogin, function(req, res){ var 채팅게시물 = { title : '땡땡채팅방', member : [ObjectId(req.body.당한사람id), req.user._id], date : new Date() } db.collection('chatroom').insertOne(채팅게시물, function(err, res){ } ).then((result)=>{ res.send('성공') }) }) app.get('/search', (req, res)=>{ var 검색조건 = [ { $search : { index : 'titleSearch', text : { query : req.query.value, path : "제목" // 제목날짜 둘다 찾고 싶으면 ['제목', '날짜'] } } }, { $sort : {_id : -1}}, { $limit : 10 }, // { $project : {제목 : 1, _id : 0, score : {$meta : "searchScore"}}} ] db.collection('post').aggregate(검색조건).toArray((err,result)=>{ console.log(result) res.render('search.ejs', {posts : result}) }) }) app.get('/chat', isLogin, function(req, res){ db.collection('chatroom').find({member : req.user._id}).toArray().then((result)=>{ res.render('chat.ejs', {data : result}) }) }) }) app.get('/upload', function(req, res){ res.render('upload.ejs') }) let multer = require('multer') var storage = multer.diskStorage({ destination : function(req, file, cb){ cb(null, './public/image') }, filename : function(req,file, cb){ cb(null, file.originalname) } }) var upload = multer({ storage : storage, fileFilter : function(req, file, callback){ var ext = path.extname(file.originalname); if(ext !== '.png' && ext !== '.jpg' && ext !== '.jpeg'){ return callback(new Error('PNG, JPG만 업로드하세요')) } callback(null, true) }, limits : { fileSize : 1024 * 1024 } }) app.post('/upload', upload.single('profile') , function(req, res){ res.send('업로드 완료') }) app.get('/image/:imageName', function(req, res){ res.sendFile(__dirname + '/public/image/' + req.params.imageName) }) app.get('/', function (request, response) { response.render('index.ejs') }) app.get('/write', function (request, response) { response.render('write.ejs') }) app.use('/shop', require('./routes/shop')) app.use('/board/sub', require('./routes/board')) const passport = require('passport') const LocalStrategy = require('passport-local').Strategy const session = require('express-session'); const { response } = require('express'); // app.use(미들웨어) : 요청 - 응답 중간에 뭔가 실행되는 코드 *미들웨어 : 요청과 응답 사이에 실행되는 코드 app.use(session({secret : '비밀코드', resave : true, saveUninitialized: false})) app.use(passport.initialize()) app.use(passport.session())
# Today I Learned 📖 ## 목표 🚩 >**오늘 배운, 알게 된, 학습한 내용들을 정제해서 기록한다.** >**내가 이해한 만큼 직접 작성한다.** >**미흡한 부분을 보완한다.** ## 작성 요령 ✍️ 1. Markdown문법으로 작성하며 확장자는 .md로 한다. 2. 분야별로 카테고리를 정리한다. 3. 문체는 간략하게 쓴다. 4. 참조는 반드시 명시한다. 5. 공부한 내용은 어떠한 것이라도 작성한다. ### JavaScript - [변수](JavaScript/변수/README.md) - [표현식과 문](JavaScript/표현식과%20문/README.md) - [데이터 타입](JavaScript/데이터%20타입/README.md) - [연산자](JavaScript/연산자/README.md) ### Node.js - [서버란?](Node.js/서버란/README.md) - [Node.js란?](Node.js/Node.js란/README.md) - [Node.js & Express 라이브러리 설치](Node.js/Node.js%20%26%20Express%20라이브러리%20설치/README.md) - [Basic GET request](Node.js/Basic%20GET%20request/README.md) - [폼을 이용한 POST 요청](Node.js/폼을%20이용한%20POST%20요청/README.md) - [RestAPI란](Node.js/RestAPI란/README.md) - [MongoDB 세팅하기](Node.js/MongoDB%20세팅하기/README.md) - [MongoDB collection & insert](Node.js/MongoDB%20collection%20%26%20insert/README.md) - [HTML에 DB데이터 넣는 법](Node.js/HTML에%20DB데이터%20넣는%20법/README.md) - [DB종류와 특징](Node.js/DB종류와%20특징/README.md) - [게시물마다 번호를 달아 저장](Node.js/게시물마다%20번호를%20달아%20저장/README.md)
import React from 'react' import { render, screen, cleanup } from '@testing-library/react' import { afterEach, describe, it, expect } from 'vitest' import LoadingModal from './LoadingModal' import { BrowserRouter as Router } from 'react-router-dom' import { ThemeProvider } from '@itsrever/design-system' describe('Loading', () => { afterEach(cleanup) it('should render a modal with a spinner if loading = true', () => { render( <Router> <ThemeProvider> <LoadingModal loading={true} /> </ThemeProvider> </Router> ) screen.getByTestId('modal') screen.getByTestId('spinner') }) it('should render nothing if loading = false', () => { render( <Router> <ThemeProvider> <LoadingModal loading={false} /> </ThemeProvider> </Router> ) expect(screen.queryByTestId('modal')).toBeNull() expect(screen.queryByTestId('spinner')).toBeNull() }) })
import { ButtonInteraction, Client, CommandInteraction, Formatters, GuildMember, Message, MessageActionRow, MessageButton, TextChannel, } from "discord.js"; import { createLogger } from "bunyan"; import { CONFIG } from "./utils/config"; import { Ticket } from "./extensions/ticket"; import { reActiveTicket } from "./utils/ticket/reActiveTicket"; import { archivingTicket } from "./utils/ticket/archivingTicket"; import { Shop } from "./extensions/shop"; import { Starboard } from "./extensions/starboard"; import modals from "discord-modals"; import ms from "ms"; class Core extends Client { public logger = createLogger({ name: "MAIN-LOGS" }); public ticket: Ticket; public shop: Shop; public starboard: Starboard; public constructor() { super({ intents: CONFIG.CORE.intents, presence: { activities: CONFIG.CORE.activities, }, }); modals(this); this.ticket = new Ticket({ core: this }); this.shop = new Shop({ core: this }); this.starboard = new Starboard({ core: this }); } public async handleEvents() { await this.on("interactionCreate", this.slashCommandsCallback); await this.on("interactionCreate", this.ticket.handleTicketButton); await this.on("interactionCreate", this.shop.handleSelectMenu); await this.on("modalSubmit", this.ticket.handleTicketModal); await this.on("messageCreate", this.sendCommand); await this.on("interactionCreate", this.handleButtons); await this.on("ready", this.onReady); await this.on("messageCreate", this.starboard.addReactions); await this.on("messageCreate", this.commandsCallback); } public async commandsCallback(message: Message) { var prefix = CONFIG.CORE.prefix; if (!message.content.startsWith(prefix)) return; if (!message.content.includes(" ")) return; var commandName = message.content.slice(prefix.length).trim().split(" ")[0]; var args = message.content.slice(prefix.length).trim().split(" ").slice(1); if (commandName === "t") { if (!message.member.roles.cache.has(CONFIG.ID.roles.moderatorRoleId)) { return; } var user = args[0]; var time = args.slice(1).join(" "); var reason = `Moderatör: ${message.author.id}`; if (!user) return; var member = message.guild.members.cache.get(user); if (!member) return; if (member.id === message.author.id) return; if (!time) return; if (!member.manageable) return; await message.reply({ content: `**${member.user.tag}** kullanıcısı <@${message.author.id}> tarafından susturuldu **[Zaman: ${time}]**`, }); await member.timeout(ms(time)); } else if (commandName === "b") { if (!message.member.roles.cache.has(CONFIG.ID.roles.adminRoleId)) { return; } var user = args[0]; var reason = `Moderatör: ${message.author.id}`; if (!user) return; var member = message.guild.members.cache.get(user); if (!member) return; if (member.id === message.author.id) return; if (!member.bannable) return; await message.reply({ content: `**${member.user.tag}** kullanıcısı <@${message.author.id}> tarafından yasaklandı`, }); await member.ban({ reason, }); } } public rulesButton() { var channel = this.channels.cache.get(CONFIG.ID.channels.rulesChannelId); var content = CONFIG.MESSAGES.filter((x) => x.name === "rules-messages")[0]; var message = content.messages.map((x) => x).join("\n\n"); if (channel.isText()) { channel.send({ content: message, components: [ new MessageActionRow().addComponents([ new MessageButton() .setCustomId("rules-button") .setLabel("Kuralları okudum ve kabul ediyorum") .setStyle("SUCCESS"), ]), ], }); } } public async handleButtons(event: ButtonInteraction) { var channel = this.channels.cache.get(event.channel.id) as TextChannel; var type = channel.name.split("-")[0]; var role = CONFIG.ID.roles.helperRoleId; if (event.isButton()) { if (event.customId === "arsiv") { await archivingTicket(event, { user: event.user, guild: event.guild, role: role, }); } else if (event.customId === "aktifet") { await reActiveTicket(event, { user: event.user, guild: event.guild, role: role, }); } else if (event.customId === "kapat") { if (!event.memberPermissions.has("KICK_MEMBERS")) { await event.deferReply({ ephemeral: true }); await event.followUp({ content: `Yeterli yetkiniz bulunmuyor.`, ephemeral: true, }); return; } event.reply({ content: `Bu talep **5** saniye icerisinde kalıcı olarak kaldırılacak.`, }); var ticketChannel = event.guild.channels.cache.get(event.channel.id); setTimeout(async () => { await ticketChannel.delete(); return; }, 5000); } else if (event.customId === "rules-button") { var IMember = event.guild.members.cache.get(event.member.user.id); if (IMember.manageable) { if (!IMember.roles.cache.get(CONFIG.ID.roles.guildMemberRoleId)) { await IMember.roles.add(CONFIG.ID.roles.guildMemberRoleId); await event.reply({ content: "Başarıyla sunucuya kayıt oldun.", ephemeral: true, }); return; } else { await event.reply({ content: "Zaten sunucuya kayıtlısın", ephemeral: true, }); return; } } else { await event.reply({ content: "Bir hata oluştu lütfen yetkililere bildir.", ephemeral: true, }); } } } } public async sendCommand(event: Message) { if (event.author.id !== CONFIG.ID.developerId) return; if (!event.content.startsWith("!send")) return; var args = event.content.split(" ").slice(1); var arg = args[0]; if (arg) { if (arg.toLowerCase() === "ticket") { await this.ticket.sendTicketMessage(); } else if (arg.toLocaleLowerCase() === "shop") { await this.shop.sendShopMessage(); } else if (arg.toLowerCase() === "rules") { await this.rulesButton(); } } } public async onReady(core: Core) { this.logger.info(core.user.username + " system is ready!"); var commands = [ { name: "role", description: "Bir kullanıcıya rol ekleyip kaldırmanızı sağlayan komutdur.", options: [ { name: "add", type: 1, description: "Bir kullanıcıya belirtilen rolü eklersiniz.", options: [ { name: "user", type: 6, description: "Kullanıcı değeri", required: true, }, { name: "role", type: 3, description: "Rol değeri", required: true, choices: CONFIG.CHOICES, }, ], }, { name: "remove", type: 1, description: "Bir kullanıcıya belirtilen rolü kaldırırsınız.", options: [ { name: "user", type: 6, description: "Kullanıcı değeri", required: true, }, { name: "role", type: 3, description: "Rol değeri", required: true, choices: CONFIG.CHOICES, }, ], }, ], }, ]; await this.application.commands.set(commands).then((cmd) => { this.logger.info(cmd.size + " size command created."); }); } public async init() { await this.login(CONFIG.CORE.token); await this.handleEvents(); } public async slashCommandsCallback(i: CommandInteraction) { if (i.isCommand()) { if (i.commandName === "role") { var user = i.options.get("user").user.id; var member: GuildMember = i.guild.members.cache.get(user); var role = i.options.get("role").value; var roleID: string = CONFIG.ID.roles[`${role.toString()}RoleId`]; var Imember: GuildMember = i.guild.members.cache.get(i.user.id); var args: string = i.options.getSubcommand(true); if (!Imember.roles.cache.has(CONFIG.ID.roles.moderatorRoleId)) { await i.reply({ content: "Bu komutu kullanmak için yeterli yetkin bulunmuyor.", ephemeral: true, }); return; } if (args === "add") { if (member.manageable) { await member.roles.add(roleID); await i.reply({ content: `:tada: <@${member.id}> kullanıcısına <@${i.user.id}> tarafından **${role}** rolü başarıyla verildi.`, ephemeral: false, }); } else { await i.reply({ content: `**${member.user.username}** kullanıcısını yönetemiyorum. Yeterli yetkim bulunmuyor.`, ephemeral: true, }); } } else if (args === "remove") { if (member.manageable) { if (member.roles.cache.has(roleID)) { await member.roles.remove(roleID); await i.reply({ content: `:cowboy: <@${member.id}> kullanıcısına <@${i.user.id}> tarafından **${role}** rolü kaldırırıldı.`, ephemeral: false, }); } else { await i.reply({ content: `**${member.user.username}** kullanıcısında zaten **${role}** rolü bulunmuyor.`, ephemeral: true, }); } } else { await i.reply({ content: `**${member.user.username}** kullanıcısını yönetemiyorum. Yeterli yetkim bulunmuyor.`, ephemeral: true, }); } } } } } } new Core().init(); export { Core };
from rest_framework import serializers from ..fields import LazyChoiceField, NullCoercedTimeField, PositiveIntegerField from ..models import BENTHICPQT_PROTOCOL from .choices import ( benthic_attributes_choices, current_choices, growth_form_choices, reef_slopes_choices, relative_depth_choices, tide_choices, visibility_choices, ) from .serializers import CollectRecordCSVSerializer __all__ = ["BenthicPhotoQTCSVSerializer"] class BenthicPhotoQTCSVSerializer(CollectRecordCSVSerializer): protocol = BENTHICPQT_PROTOCOL sample_unit = "quadrat_transect" observations_fields = ["data__obs_benthic_photo_quadrats"] ordering_field = "data__obs_benthic_photo_quadrats__quadrat_number" additional_group_fields = CollectRecordCSVSerializer.additional_group_fields.copy() additional_group_fields.append("data__quadrat_transect__label") composite_fields = {"data__sample_event__sample_date": ["year", "month", "day"]} data__sample_event__site = serializers.CharField( label="Site", help_text="A unique name of a site where data was collected. Every site must be defined before ingestion and set up in the project in the web app.", ) data__sample_event__management = serializers.CharField( label="Management", help_text="Name of management regime in effect for the site where data was collected on the date of collection. Must be defined before ingestion and set up in the project in the web app.", ) data__sample_event__sample_date = serializers.DateField( label="Sample date: Year,Sample date: Month,Sample date: Day", help_text="Date data was collected: four-digit year (e.g. 2023), two-digit month(e.g. 02), two-digit day (e.g. 28)", ) data__quadrat_transect__sample_time = NullCoercedTimeField( required=False, allow_null=True, label="Sample time", help_text="24-hour time when sample unit began (e.g. 13:15)", ) data__quadrat_transect__depth = serializers.DecimalField( max_digits=3, decimal_places=1, label="Depth", help_text="Depth of sample unit, in meters (e.g. 3)", ) data__quadrat_transect__number = serializers.IntegerField( min_value=0, label="Transect number", help_text="Sample unit number, as integer (e.g. 1)", ) data__quadrat_transect__label = serializers.CharField( allow_blank=True, required=False, default="", label="Transect label", help_text="Arbitrary text to distinguish sample units that are distinct but should be combined analytically (i.e. all other properties are identical). For example: 'little fish'. Rarely used.", ) data__quadrat_transect__len_surveyed = serializers.DecimalField( max_digits=4, decimal_places=1, label="Transect length surveyed", help_text="Length of transect for a sample unit, in meters. May include decimal (e.g. 50.0).", ) data__quadrat_transect__num_quadrats = PositiveIntegerField( label="Number of quadrats", help_text="Total number of quadrats per transect, as an integer (e.g. 10).", ) data__quadrat_transect__quadrat_size = serializers.DecimalField( max_digits=4, decimal_places=2, label="Quadrat size", help_text="Quadrat size used per transect, in square meters (e.g. 1).", ) data__quadrat_transect__quadrat_number_start = PositiveIntegerField( default=1, label="First quadrat number", help_text="Number of the first quadrat/photo along the transect, as an integer (e.g. 1).", ) data__quadrat_transect__num_points_per_quadrat = PositiveIntegerField( label="Number of points per quadrat", help_text="Total number of points per quadrat used in a transect, as an integer (e.g. 100).", ) data__quadrat_transect__reef_slope = LazyChoiceField( choices=reef_slopes_choices, required=False, allow_null=True, allow_blank=True, label="Reef slope", help_text="An indication of coral reef profile of the survey location. Flat is a shallow area that is nearly horizontal; Slope is a submerged sloping lower fore reef area that opens up into the open ocean (between 0 and 45 degrees angle); Wall is any seaward-facing fore reef feature with a near vertical slope (> 45 degrees angle); Crest is the breaking point between the reef flat and reef front. See relevant tab on ingestion template for choices.", ) data__quadrat_transect__visibility = LazyChoiceField( choices=visibility_choices, required=False, allow_null=True, allow_blank=True, label="Visibility", help_text="The horizontal distance at which an object underwater can still be identified. See relevant tab on ingestion template for choices.", ) data__quadrat_transect__current = LazyChoiceField( choices=current_choices, required=False, allow_null=True, allow_blank=True, label="Current", help_text="The current/water speed during the survey. See relevant tab on ingestion template for choices.", ) data__quadrat_transect__relative_depth = LazyChoiceField( choices=relative_depth_choices, required=False, allow_null=True, allow_blank=True, label="Relative depth", help_text="Depth category to distinguish surveys in the same site but at different depths. See relevant tab on ingestion template for choices.", ) data__quadrat_transect__tide = LazyChoiceField( choices=tide_choices, required=False, allow_null=True, allow_blank=True, label="Tide", help_text="The tide characteristics of the survey. Falling tide is when the sea surface height is decreasing after the High tide due to the outgoing tide (ebb current); High tide occurs when the sea surface height is at the highest; Low tide occurs when the sea surface height is at the lowest; Rising tide is when the sea surface height increases after the Low tide due to the incoming tide along the coast (flood current); and Slack water is the weakest current between the flood and ebb currents. See relevant tab on ingestion template for choices.", ) data__quadrat_transect__notes = serializers.CharField( required=False, allow_blank=True, default="", label="Sample unit notes", help_text="Notes recorded by observer for transect", ) data__observers = serializers.ListField( child=serializers.CharField(), allow_empty=False, label="Observer emails", help_text="Comma-separated list of emails of sample unit observers (e.g. '[email protected],[email protected]').", ) data__obs_benthic_photo_quadrats__quadrat_number = PositiveIntegerField( label="Quadrat", help_text="Number of quadrat/photo in transect, as an integer (e.g. 1).", ) data__obs_benthic_photo_quadrats__attribute = LazyChoiceField( choices=benthic_attributes_choices, label="Benthic attribute", help_text="Benthic attribute observed. See relevant tab on ingestion template for choices.", ) data__obs_benthic_photo_quadrats__growth_form = LazyChoiceField( choices=growth_form_choices, required=False, allow_null=True, allow_blank=True, label="Growth form", help_text="Growth form of the observed benthic attribute (if applicable). See relevant tab on ingestion template for choices.", ) data__obs_benthic_photo_quadrats__num_points = PositiveIntegerField( label="Number of points", help_text="Number of points with unique benthic attribute (/growth form) for the quadrat.", ) def validate(self, data): data = super().validate(data) return data
import Foundation import GitLib import Tea import Slowbox struct Model: Equatable, Encodable { let git: Git let views: [View] let info: InfoMessage let menu: Menu let gitLog: GitLogModel func with(buffer: [View]? = nil, info: InfoMessage? = nil, menu: Menu? = nil, gitLog: GitLogModel? = nil) -> Model { Model(git: git, views: buffer ?? self.views, info: info ?? self.info, menu: menu ?? self.menu, gitLog: gitLog ?? self.gitLog) } func navigate(to newView: View) -> Model { with(buffer: views + [newView], menu: Menu.empty()) } func navigate(to newBuffer: Buffer) -> Model { with(buffer: views + [View(buffer: newBuffer)], menu: Menu.empty()) } func replace(buffer newView: View) -> Model { with(buffer: views.dropLast() + [newView]) } func replace(buffer newBuffer: Buffer) -> Model { let last = views.last! return with(buffer: views.dropLast() + [last.with(buffer: newBuffer)]) } func back() -> Model { with(buffer: views.dropLast(), menu: Menu.empty()) } } struct Menu: Equatable, Encodable { let keyMaps: [KeyMap] static func empty() -> Menu { Self(keyMaps: []) } func push(keyMap: KeyMap) -> Menu { Self(keyMaps: keyMaps + [keyMap]) } func pop() -> Menu { Self(keyMaps: keyMaps.dropLast(1)) } func shouldShow() -> Bool { keyMaps.count > 0 } func active() -> KeyMap? { keyMaps.last } subscript(event: KeyEvent) -> Message? { (keyMaps.last ?? commandMap)[event] } } struct View: Equatable, Encodable { let buffer: Buffer let cursor: Cursor init(buffer: Buffer) { self.buffer = buffer cursor = Cursor.initial() } private init(buffer: Buffer, cursor: Cursor) { self.buffer = buffer self.cursor = cursor } func with(buffer: Buffer? = nil, cursor: Cursor? = nil) -> View { Self(buffer: buffer ?? self.buffer, cursor: cursor ?? self.cursor) } } enum Buffer: Equatable, Encodable { case StatusBuffer(StatusModel) case LogBuffer(AsyncData<LogInfo>) case GitLogBuffer case CommitBuffer(DiffModel) } enum InfoMessage: Equatable, Encodable { case None case Message(String) case Query(String, Message) static func == (lhs: InfoMessage, rhs: InfoMessage) -> Bool { switch (lhs, rhs) { case (.None, .None): return true case let (.Message(lhsInfo), .Message(rhsInfo)): return lhsInfo == rhsInfo case let (.Query(lhsQuery, _), .Query(rhsQuery, _)): return lhsQuery == rhsQuery default: return false } } func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() switch self { case .None: try container.encode("None") case let .Message(m): try container.encode("Message(\(m))") case let .Query(m, _): try container.encode("Query(\(m), _)") } } }
-- Copyright 2021 SmartThings -- -- 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. local capabilities = require "st.capabilities" --- @type st.zwave.CommandClass local cc = require "st.zwave.CommandClass" --- @type st.zwave.CommandClass.Battery local Battery = (require "st.zwave.CommandClass.Battery")({ version = 1 }) --- @type st.zwave.CommandClass.Notification local Notification = (require "st.zwave.CommandClass.Notification")({ version = 3 }) --- @type st.zwave.CommandClass.WakeUp local WakeUp = (require "st.zwave.CommandClass.WakeUp")({ version = 1 }) local LAST_BATTERY_REPORT_TIME = "lastBatteryReportTime" local RING_FINGERPRINTS = { { manufacturerId = 0x0346, productType = 0x0201, productId = 0x0301 }, -- Ring contact sensor v2 } --- Determine whether the passed device is RING_FINGERPRINTS --- --- @param driver st.zwave.Driver --- @param device st.zwave.Device --- @return boolean true if the device proper, else false local function can_handle_ring_sensor(opts, driver, device, ...) for _, fingerprint in ipairs(RING_FINGERPRINTS) do if device:id_match(fingerprint.manufacturerId, fingerprint.productType, fingerprint.productId) then return true end end return false end local function call_parent_handler(handlers, self, device, event, args) if type(handlers) == "function" then handlers = { handlers } -- wrap as table end for _, func in ipairs( handlers or {} ) do func(self, device, event, args) end end --- Handler for notification report command class --- --- @param self st.zwave.Driver --- @param device st.zwave.Device --- @param cmd st.zwave.CommandClass.Notification.Report local function notification_report_handler(self, device, cmd) local home_security_notification_events_map = { [Notification.event.home_security.INTRUSION] = { active = capabilities.contactSensor.contact.open(), inactive = capabilities.contactSensor.contact.closed() }, [Notification.event.home_security.TAMPERING_PRODUCT_COVER_REMOVED] = { active = capabilities.tamperAlert.tamper.detected(), inactive = capabilities.tamperAlert.tamper.clear(), }, -- To do: Should this be a separate custom capability? [Notification.event.home_security.MAGNETIC_FIELD_INTERFERENCE_DETECTED] = { active = capabilities.tamperAlert.tamper.detected(), inactive = capabilities.tamperAlert.tamper.clear(), }, } local event if cmd.args.notification_type == Notification.notification_type.HOME_SECURITY then if cmd.args.event == Notification.event.home_security.STATE_IDLE then event = home_security_notification_events_map[string.byte(cmd.args.event_parameter)].inactive else event = home_security_notification_events_map[cmd.args.event].active end elseif cmd.args.notification_type == Notification.notification_type.SYSTEM and cmd.args.event == Notification.event.system.HEARTBEAT then event = capabilities.button.button.pushed() event.state_change = true end if (event ~= nil) then device:emit_event(event) end end -- Request a battery update from the device. -- This should only be called when the radio is known to be listening -- (during initial inclusion/configuration and during Wakeup) local function getBatteryUpdate(device, force) device.log.trace("getBatteryUpdate()") if not force then -- Calculate if its time local last = device:get_field(LAST_BATTERY_REPORT_TIME) if last then local now = os.time() local diffsec = os.difftime(now, last) device.log.debug("Last battery update: " .. os.date("%c", last) .. "(" .. diffsec .. " seconds ago)" ) local wakeup_offset = 60 * 60 * 24 -- Assume 1 day preference if tonumber(device.preferences.batteryInterval) < 100 then -- interval is a multiple of our wakeup time (in seconds) wakeup_offset = tonumber(device.preferences.wakeUpInterval) * tonumber(device.preferences.batteryInterval) end if wakeup_offset > 0 then -- Adjust for about 5 minutes to cover waking up "early" wakeup_offset = wakeup_offset - (60 * 5) -- Has it been longer than our interval? force = diffsec >= wakeup_offset end else force = true -- No last battery report, get one now end end if not force then device.log.debug("No battery update needed") end if force then -- Request a battery update now device:send(Battery:Get({})) end end --- @param self st.zwave.Driver --- @param device st.zwave.Device --- @param cmd st.zwave.CommandClass.WakeUp.Notification local function wakeup_notification(self, device, cmd) device.log.trace("wakeup_notification()") -- Check the contact sensor if it's currently tripped if device:get_latest_state('main',capabilities.contactSensor.ID,'contact','open') == 'open' then device:send(Notification:Get({notification_type=Notification.notification_type.HOME_SECURITY,event=Notification.event.home_security.INTRUSION})) end -- We may need to request a battery update while we're woken up getBatteryUpdate(device) end --- @param self st.zwave.Driver --- @param device st.zwave.Device --- @param cmd st.zwave.CommandClass.Battery.Report local function battery_report(self, device, cmd) -- Save the timestamp of the last battery report received. device:set_field(LAST_BATTERY_REPORT_TIME, os.time(), { persist = true } ) if cmd.args.battery_level == 99 then cmd.args.battery_level = 100 end if cmd.args.battery_level == 0xFF then cmd.args.battery_level = 1 end -- Forward on to the default battery report handlers from the top level call_parent_handler(self.zwave_handlers[cc.BATTERY][Battery.REPORT], self, device, cmd) end local ring_contact_sensor = { zwave_handlers = { [cc.WAKE_UP] = { [WakeUp.NOTIFICATION] = wakeup_notification, }, [cc.BATTERY] = { [Battery.REPORT] = battery_report, }, [cc.NOTIFICATION] = { [Notification.REPORT] = notification_report_handler }, }, NAME = "Ring Contact Sensor 2", can_handle = can_handle_ring_sensor } return ring_contact_sensor
import random from itertools import combinations import time import sys from backgorund_board import QueenBoard class NQueens: exec_solutions = 0 max_iterations = 0 queens_quantity = 0 movement_time = 0 def __init__(self, max_iterations, queens_quantity, movement_time): self.max_iterations = max_iterations self.queens_quantity = queens_quantity self.movement_time = movement_time def objective_func(self, candidate_solution, size_solution): positive_diagonal = [0 for _ in range(size_solution)] negative_diagonal = [0 for _ in range(size_solution)] for index in range(size_solution): k_positive = index - candidate_solution[index] k_negative = index + candidate_solution[index] positive_diagonal[index] = k_positive negative_diagonal[index] = k_negative fit_solution = 0 fit_solution += (len(positive_diagonal) - len(set(positive_diagonal))) fit_solution += (len(negative_diagonal) - len(set(negative_diagonal))) return fit_solution def generate_tabu_matrix(self, size_combinations): tabu_matrix = [[0 for _ in range(size_combinations)], [0 for _ in range(size_combinations)]] return tabu_matrix def generate_next_move(self, current_solution, current_fit, possible_moves, size_moves, tabu_matrix, n_iteration): candidate_solution = current_solution.copy() neighbor_solutions = [] # Retorna os indices de movimentos possíveis de acordo com MOVEMENT_TIME index_moves = [index for index in range(size_moves) if tabu_matrix[0][index] < n_iteration] for move in index_moves: candidate_solution[possible_moves[move][0]] = current_solution[possible_moves[move][1]] candidate_solution[possible_moves[move][1]] = current_solution[possible_moves[move][0]] candidate_fit = self.objective_func(candidate_solution, self.queens_quantity) if candidate_fit < current_fit: # tabu matrix[0] armazena tempo de congelamento; tabu matrix[1] quantidade de vezes do movimento tabu_matrix[0][move] += n_iteration + self.movement_time tabu_matrix[1][move] += 1 return candidate_solution, candidate_fit, tabu_matrix else: if candidate_fit == current_fit: neighbor_solutions.append([candidate_solution, candidate_fit, move]) candidate_solution = current_solution.copy() if len(neighbor_solutions): neighbor_candidate_solution = random.sample(neighbor_solutions, k=1)[0] move = neighbor_candidate_solution[2] tabu_matrix[0][move] += n_iteration + self.movement_time tabu_matrix[1][move] += 1 return neighbor_candidate_solution[0], neighbor_candidate_solution[1], tabu_matrix else: min_move = min(tabu_matrix[1]) min_move_index = tabu_matrix[1].index(min_move) tabu_matrix[1][min_move_index] += 1 candidate_solution[possible_moves[min_move_index][0]] = current_solution[possible_moves[min_move_index][1]] candidate_solution[possible_moves[min_move_index][1]] = current_solution[possible_moves[min_move_index][0]] candidate_fit = self.objective_func(candidate_solution, self.queens_quantity) return candidate_solution, candidate_fit, tabu_matrix def tabu_queens(self): possible_moves = list(combinations(list(range(self.queens_quantity)), r=2)) size_moves = len(possible_moves) initial_seconds = time.time() best_solution = random.sample(range(0, self.queens_quantity), self.queens_quantity) best_fit = self.objective_func(best_solution, self.queens_quantity) tabu_matrix = self.generate_tabu_matrix(size_moves) n_iteration = 0 while n_iteration < self.max_iterations and best_fit != 0: n_iteration += 1 best_solution, best_fit, tabu_matrix = self.generate_next_move( best_solution, best_fit, possible_moves, size_moves, tabu_matrix, n_iteration) final_seconds = time.time() - initial_seconds print('-------------------------------') print('segundos', final_seconds) print('iterações', n_iteration) print('fit final:', best_fit) print('solução final', best_solution) print('-------------------------------') return best_solution if __name__ == '__main__': if sys.argv[1] and sys.argv[2] and sys.argv[3]: MAX_ITERATIONS = int(sys.argv[1]) QUEENS_QUANTITY = int(sys.argv[2]) MOVEMENT_TIME = int(sys.argv[3]) # -- Tabuleiro -- # SIZE = 480 BLUE = (75, 68, 200) WHITE = (255, 255, 255) n_queens = NQueens(max_iterations=MAX_ITERATIONS, queens_quantity=QUEENS_QUANTITY, movement_time=MOVEMENT_TIME) best_sol = n_queens.tabu_queens() board = QueenBoard((SIZE, SIZE), SIZE / QUEENS_QUANTITY, 'imagens/queen.png', BLUE, WHITE) board.loop(QUEENS_QUANTITY, best_sol) else: print('Informe o numero máximo de iterações, quantidade de rainhas e tempo tabu (python main.py iterações qtd_rainhas tempo_tabu')
#ifndef SHADER_H #define SHADER_H #pragma once #include <string> #include <unordered_map> #include <GL/glew.h> #include "glm/glm.hpp" //hold strings for vertex and fragment code struct ShaderProgramSource { std::string VertexSource; std::string FragmentSource; }; //abstraction for creating and maintaining shader programs class Shader { private: std::string m_Filepath; //path for .shader file unsigned int m_RendererID; //program ID std::unordered_map<std::string, int> m_UniformLocationCache; // ShaderProgramSource ParseShader(const std::string& filepath); //read shader unsigned int GetUniformLocation(const std::string& name); //get uniform unsigned int CompileShader(unsigned int type, const std::string& source); //compile shader unsigned int CreateShader(const std::string& vertexShader, const std::string& fragmentShader); //create shader public: //constructor Shader(const std::string& filepath); ~Shader(); //bind/unbind void Bind() const; void UnBind() const; //set shader uniforms void SetUniform1i(const std::string& name, int value); void SetUniform1f(const std::string& name, float value); void SetUniform1fv(const std::string& name, int count, float* value); void SetUniform2f(const std::string& name, float v0, float v1); void SetUniform3f(const std::string& name, float v0, float v1, float v2); void SetUniform4f(const std::string& name, float v0, float v1, float v2, float v3); void SetUniformMat4f(const std::string& name, float v0, float v1, float v2, float v3); void SetUniformMat4f(const std::string& name, const glm::mat4& matrix); void Delete(); }; #endif
package com.github.stefvanschie.inventoryframework.gui.type; import com.github.stefvanschie.inventoryframework.HumanEntityCache; import com.github.stefvanschie.inventoryframework.adventuresupport.TextHolder; import com.github.stefvanschie.inventoryframework.exception.XMLLoadException; import com.github.stefvanschie.inventoryframework.gui.GuiItem; import com.github.stefvanschie.inventoryframework.gui.InventoryComponent; import com.github.stefvanschie.inventoryframework.gui.type.util.InventoryBased; import com.github.stefvanschie.inventoryframework.gui.type.util.MergedGui; import com.github.stefvanschie.inventoryframework.gui.type.util.NamedGui; import com.github.stefvanschie.inventoryframework.pane.Pane; import org.bukkit.entity.HumanEntity; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; /** * Represents a gui in the form of a barrel. * * @since 0.8.0 */ public class BarrelGui extends NamedGui implements MergedGui, InventoryBased { /** * Represents the inventory component for the entire gui */ @NotNull private InventoryComponent inventoryComponent = new InventoryComponent(9, 7); /** * Constructs a new GUI * * @param title the title/name of this gui. * @since 0.8.0 */ public BarrelGui(@NotNull String title) { super(title); } /** * Constructs a new GUI * * @param title the title/name of this gui. * @since 0.10.0 */ public BarrelGui(@NotNull TextHolder title) { super(title); } /** * Constructs a new barrel gui for the given {@code plugin}. * * @param title the title/name of this gui. * @param plugin the owning plugin of this gui * @see #BarrelGui(String) * @since 0.10.8 */ public BarrelGui(@NotNull String title, @NotNull Plugin plugin) { super(title, plugin); } /** * Constructs a new barrel gui for the given {@code plugin}. * * @param title the title/name of this gui. * @param plugin the owning plugin of this gui * @see #BarrelGui(TextHolder) * @since 0.10.8 */ public BarrelGui(@NotNull TextHolder title, @NotNull Plugin plugin) { super(title, plugin); } @Override public void show(@NotNull HumanEntity humanEntity) { if (isDirty()) { this.inventory = createInventory(); markChanges(); } getInventory().clear(); int height = getInventoryComponent().getHeight(); getInventoryComponent().display(); InventoryComponent topComponent = getInventoryComponent().excludeRows(height - 4, height - 1); InventoryComponent bottomComponent = getInventoryComponent().excludeRows(0, height - 5); topComponent.placeItems(getInventory(), 0); if (bottomComponent.hasItem()) { HumanEntityCache humanEntityCache = getHumanEntityCache(); if (!humanEntityCache.contains(humanEntity)) { humanEntityCache.storeAndClear(humanEntity); } bottomComponent.placeItems(humanEntity.getInventory(), 0); } humanEntity.openInventory(getInventory()); } @NotNull @Contract(pure = true) @Override public BarrelGui copy() { BarrelGui gui = new BarrelGui(getTitleHolder(), super.plugin); gui.inventoryComponent = inventoryComponent.copy(); gui.setOnTopClick(this.onTopClick); gui.setOnBottomClick(this.onBottomClick); gui.setOnGlobalClick(this.onGlobalClick); gui.setOnOutsideClick(this.onOutsideClick); gui.setOnClose(this.onClose); return gui; } @NotNull @Override public Inventory getInventory() { if (this.inventory == null) { this.inventory = createInventory(); } return inventory; } @Override public void click(@NotNull InventoryClickEvent event) { getInventoryComponent().click(this, event, event.getRawSlot()); } @Contract(pure = true) @Override public boolean isPlayerInventoryUsed() { return getInventoryComponent().excludeRows(0, getInventoryComponent().getHeight() - 5).hasItem(); } @Override public void addPane(@NotNull Pane pane) { this.inventoryComponent.addPane(pane); } @NotNull @Contract(pure = true) @Override public List<Pane> getPanes() { return this.inventoryComponent.getPanes(); } @NotNull @Contract(pure = true) @Override public Collection<GuiItem> getItems() { return getPanes().stream().flatMap(pane -> pane.getItems().stream()).collect(Collectors.toSet()); } @NotNull @Contract(pure = true) @Override public Inventory createInventory() { return getTitleHolder().asInventoryTitle(this, InventoryType.BARREL); } @Contract(pure = true) @Override public int getViewerCount() { return getInventory().getViewers().size(); } @NotNull @Contract(pure = true) @Override public List<HumanEntity> getViewers() { return new ArrayList<>(getInventory().getViewers()); } @NotNull @Contract(pure = true) @Override public InventoryComponent getInventoryComponent() { return inventoryComponent; } /** * Loads a barrel gui from an XML file. * * @param instance the instance on which to reference fields and methods * @param inputStream the input stream containing the XML data * @param plugin the plugin that will be the owner of the created gui * @return the loaded barrel gui * @see #load(Object, InputStream) * @since 0.10.8 */ @Nullable @Contract(pure = true) public static BarrelGui load(@NotNull Object instance, @NotNull InputStream inputStream, @NotNull Plugin plugin) { try { Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream); Element documentElement = document.getDocumentElement(); documentElement.normalize(); return load(instance, documentElement, plugin); } catch (SAXException | ParserConfigurationException | IOException e) { e.printStackTrace(); return null; } } /** * Loads a barrel gui from the specified element, applying code references to the provided instance. * * @param instance the instance on which to reference fields and methods * @param element the element to load the gui from * @param plugin the plugin that will be the owner of the created gui * @return the loaded barrel gui * @see #load(Object, Element) * @since 0.10.8 */ @NotNull public static BarrelGui load(@NotNull Object instance, @NotNull Element element, @NotNull Plugin plugin) { if (!element.hasAttribute("title")) { throw new XMLLoadException("Provided XML element's gui tag doesn't have the mandatory title attribute set"); } BarrelGui barrelGui = new BarrelGui(element.getAttribute("title"), plugin); barrelGui.initializeOrThrow(instance, element); if (element.hasAttribute("populate")) { return barrelGui; } NodeList childNodes = element.getChildNodes(); for (int index = 0; index < childNodes.getLength(); index++) { Node item = childNodes.item(index); if (item.getNodeType() != Node.ELEMENT_NODE) { continue; } Element componentElement = (Element) item; InventoryComponent inventoryComponent = barrelGui.getInventoryComponent(); if (componentElement.getTagName().equalsIgnoreCase("component")) { inventoryComponent.load(instance, componentElement, plugin); } else { inventoryComponent.load(instance, element, plugin); } break; } return barrelGui; } /** * Loads a barrel gui from an XML file. * * @param instance the instance on which to reference fields and methods * @param inputStream the input stream containing the XML data * @return the loaded barrel gui * @since 0.8.0 */ @Nullable @Contract(pure = true) public static BarrelGui load(@NotNull Object instance, @NotNull InputStream inputStream) { return load(instance, inputStream, JavaPlugin.getProvidingPlugin(BarrelGui.class)); } /** * Loads a barrel gui from the specified element, applying code references to the provided instance. * * @param instance the instance on which to reference fields and methods * @param element the element to load the gui from * @return the loaded barrel gui * @since 0.8.0 */ @NotNull public static BarrelGui load(@NotNull Object instance, @NotNull Element element) { return load(instance, element, JavaPlugin.getProvidingPlugin(BarrelGui.class)); } }
import 'package:flutter/material.dart'; // import 'package:flutter_svg/flutter_svg.dart'; import '/screens/screens.dart'; class CustomAppBar extends StatelessWidget implements PreferredSizeWidget { final String title; final bool hasAction; const CustomAppBar({ Key? key, required this.title, this.hasAction = false, }) : super(key: key); @override Widget build(BuildContext context) { return AppBar( backgroundColor: Colors.transparent, elevation: 0, automaticallyImplyLeading: false, title: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Padding( padding: const EdgeInsets.only(left: 10.0), // child: SvgPicture.asset( // 'assets/logo.svg', // height: 35, // ), child: Image.asset( 'assets/logo.png', height: 40, ), ), Padding( padding: EdgeInsets.only(left: hasAction ? 10 : 0), child: Text( title, style: Theme.of(context) .textTheme .displayMedium ?.copyWith(color: Theme.of(context).primaryColor), ), ), SizedBox( width: hasAction ? 0 : 40, ), ], ), actions: [ hasAction ? IconButton( icon: Icon( title == "PROFILE" ? Icons.settings : Icons.person, color: Theme.of(context).primaryColor, ), onPressed: () { Navigator.of(context).pushReplacementNamed(title == "PROFILE" ? SettingsScreen.routeName : ProfileScreen.routeName); }, ) : Container(), ], ); } @override Size get preferredSize => const Size.fromHeight(40.0); }