text
stringlengths
184
4.48M
import 'package:amplify_auth_cognito/amplify_auth_cognito.dart'; import 'package:amplify_flutter/amplify_flutter.dart'; import 'package:estonedge/amplifyconfiguration.dart'; import 'package:estonedge/ui/auth/login/login_screen.dart'; import 'package:estonedge/ui/auth/signup/signup_screen.dart'; import 'package:estonedge/ui/home/home_screen.dart'; import 'package:estonedge/ui/home/room/add_room/add_room_screen.dart'; import 'package:estonedge/ui/home/room/add_room/room_image_screen.dart'; import 'package:estonedge/ui/introduction/get_started.dart'; import 'package:estonedge/ui/splash/splash_screen.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; Future<void> main() async { try { WidgetsFlutterBinding.ensureInitialized(); await _configureAmplify(); runApp(const ProviderScope(child: MainApp())); } on AmplifyException catch (e) { runApp(Text("Something went wrong: ${e.message}")); } } Future<void> _configureAmplify() async { try { await Amplify.addPlugin(AmplifyAuthCognito()); await Amplify.configure(amplifyconfig); } on Exception catch (e) { safePrint('Error configuring Amplify: $e'); } } class MainApp extends StatelessWidget { const MainApp({super.key}); @override Widget build(BuildContext context) { SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, ]); return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.red), useMaterial3: true, ), initialRoute: '/', routes: { '/': (context) => const SplashScreen(), '/introduction': (context) => const GetStarted(), '/home': (context) => const HomeScreen(), '/login': (context) => const LoginScreen(), '/signup': (context) => const SignupScreen(), '/addRoom': (context) => const AddRoomScreen(), '/selectRoomImage': (context) => const SelectRoomImageScreen() }, ); } }
<!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="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Raleway:wght@700&family=Roboto:wght@400;500;700;900&display=swap" rel="stylesheet" /> <link rel="stylesheet" href="./css/styles.css" /> <title>Главная</title> </head> <body> <header class="page-header"> <a href="./index.html" class="logo link">Web<span class="logo-text-header">Studio</span></a> <nav> <ul class="site-nav"> <li class="site-nav-item"> <a href="./index.html" class="site-nav-link link current">Студия</a> </li> <li class="site-nav-item"> <a href="./portfolio.html" class="site-nav-link link">Портфолио</a> </li> <li class="site-nav-item"> <a href="Контакты" class="site-nav-link link">Контакты</a> </li> </ul> </nav> <ul class="connection"> <li> <a href="mailto:info@devstudio.com" class="contact-link link">info@devstudio.com</a> </li> <li> <a href="tel:+380961111111" class="contact-link link">+38 096 111 11 11</a> </li> </ul> </header> <!--main--> <main> <section class="hero"> <h1 class="hero-title">Эффективные решения для вашего бизнеса</h1> <button type="button" class="button-title">Заказать услугу</button> </section> <section class="section"> <h2 class="section-title">Наши преимущества</h2> <!--потом нужно будет скрыть--> <ul class="feature-list"> <li class="feature-list-item"> <h3 class="feature-list-title">Внимание к деталям</h3> <p class="feature-list-text"> Идейные соображения, а также начало повседневной работы по формированию позиции. </p> </li> <li class="feature-list-item"> <h3 class="feature-list-title">Пунктуальность</h3> <p class="feature-list-text"> Задача организации, в особенности же рамки и место обучения кадров влечет за собой. </p> </li> <li class="feature-list-item"> <h3 class="feature-list-title">Планирование</h3> <p class="feature-list-text"> Равным образом консультация с широким активом в значительной степени обуславливает. </p> </li> <li class="feature-list-item"> <h3 class="feature-list-title">Современные технологии</h3> <p class="feature-list-text"> Значимость этих проблем настолько очевидна, что реализация плановых заданий. </p> </li> </ul> </section> <section class="section"> <h2 class="section-title">Чем мы занимаемся</h2> <ul class="section-list"> <li> <img src="./images/img1.jpg" alt="computer on the table" width="370" height="294" /> </li> <li> <img src="./images/img2.jpg" alt="laptop and phone" width="370" height="294" /> </li> <li> <img src="./images/img3.jpg" alt="drawing on a tablet" width="370" height="294" /> </li> </ul> </section> <section class="section-team"> <h2 class="section-team-title">Наша команда</h2> <ul class="section-team-list"> <li class="section-team-item"> <img src="./images/team_card1.jpg" alt="Product Designer" width="270" height="260" /> <h3 class="section-team-name">Игорь Демьяненко</h3> <p class="section-team-text">Product Designer</p> </li> <li class="section-team-item"> <img src="./images/team_card2.jpg" alt="Frontend Developer" width="270" height="260" /> <h3 class="section-team-name">Ольга Репина</h3> <p class="section-team-text">Frontend Developer</p> </li> <li class="section-team-item"> <img src="./images/team_card3.jpg" alt="Marketer" width="270" height="260" /> <h3 class="section-team-name">Николай Тарасов</h3> <p class="section-team-text">Marketing</p> </li> <li class="section-team-item"> <img src="./images/team_card4.jpg" alt="UI Designer" width="270" height="260" /> <h3 class="section-team-name">Михаил Ермаков</h3> <p class="section-team-text">UI Designer</p> </li> </ul> </section> </main> <!--footer--> <footer class="footer-list"> <a href="#" class="logo link">Web<span class="logo-text-footer">Studio</span></a> <address class="address"> <ul class="address-list"> <li> <a href="https://goo.gl/maps/djX5doPdqR4ijvV3A" target="_blank" rel="noopener noreferrer nofollow" class="address-contact" >г. Киев, пр-т Леси Украинки, 26</a > </li> <li> <a href="mailto:info@devstudio.com" class="contact-link-footer">info@devstudio.com</a> </li> <li> <a href="tel:+380961111111" class="contact-link-footer">+38 096 111 11 11</a> </li> </ul> </address> </footer> </body> </html>
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms'; import { ActivatedRoute } from '@angular/router'; import { BookService } from '../../../../services/book.service'; import { CategoryService } from '../../../../services/category.service'; import { PublisherService } from '../../../../services/publisher.service'; import { Book } from '../../../../../models/book'; import { ResponseModel } from '../../../../../models/responseModel'; import { Category } from '../../../../../models/Category'; import { Publisher } from '../../../../../models/publisher'; import { CommonModule } from '@angular/common'; import { CategoryListComponent } from '../../category/category-list/category-list.component'; import { GetAllBook } from '../../../../../models/getAllBook'; import { Response } from '../../../../../models/response'; @Component({ selector: 'app-book-update', standalone: true, imports: [CommonModule, FormsModule, ReactiveFormsModule, CategoryListComponent,], templateUrl: './book-update.component.html', styleUrl: './book-update.component.css' }) export class BookUpdateComponent implements OnInit { bookUpdateForm!: FormGroup; getBook: Book[] = []; categories: Category[] = []; publishers: Publisher[] = []; bookId!: any; constructor( private formBuilder: FormBuilder, private bookService: BookService, private categoryService: CategoryService, private publisherService: PublisherService, private activeToute: ActivatedRoute) { } ngOnInit(): void { this.getAllCategories(); this.getAllPublishers(); this.getBookById(); this.editBookAddForm(); } editBookAddForm(){ this.bookUpdateForm= this.formBuilder.group({ id:[this.bookId], name:["",[Validators.required, Validators.minLength(2)]], isbn:["",Validators.required], page:["",Validators.required], publisherId:["",Validators.required], categoryId:["",Validators.required], language:["",Validators.required], description:["",Validators.required], unitsInStock:["",[Validators.required,Validators.min(0)]], })} getBookById(){ this.bookId = this.activeToute.snapshot.paramMap.get('id'); this.bookService.getById(this.bookId).subscribe({ next: (response:Response<Book>) => { this.getBook=response.items; console.log("Response:",response) }, error: (error) => { console.log(error); }, complete: () => { } }); } getAllCategories() { this.categoryService.getAll().subscribe( (response: ResponseModel<Category>) => { this.categories = response.items; console.log(this.categories); } ); } getAllPublishers() { this.publisherService.getAllPublisher().subscribe((response: ResponseModel<Publisher>) => { this.publishers = response.items; console.log(this.publishers); }); } onCategoryChange(event: any) { const selectedCategory = event.target.value; const category = this.categories.find(item => item.id == selectedCategory); console.log(category); } onPublisherChange(event: any) { const selectedPublisher = event.target.value; const publisher = this.publishers.find(item => item.id == selectedPublisher); console.log(publisher); } updateToDb(): void { if (this.bookUpdateForm.valid) { const formData: Book = this.bookUpdateForm.value; console.log(formData.name); this.bookService.editBook(formData).subscribe((response) => { console.log("response", response); alert(formData.name.toUpperCase() + " başarıyla güncellendi"); } ); } } }
import { useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Menu, IconButton, Icon } from '@mui/material'; import authSelectors from 'src/modules/auth/authSelectors'; import { getHistory } from 'src/modules/store'; import authActions from 'src/modules/auth/authActions'; import { i18n } from 'src/i18n'; import config from 'src/config'; // Custom styles for Header import { navbarIconButton } from 'src/mui/shared/Navbars/DashboardNavbar/styles'; import { selectMuiSettings } from 'src/modules/mui/muiSelectors'; import NotificationItem from 'src/mui/shared/Items/NotificationItem'; // Declaring prop types for Header interface Props { absolute?: boolean; light?: boolean; isMini?: boolean; } function UserMenu({ absolute, light, isMini, }: Props): JSX.Element { const [anchorEl, setAnchorEl] = useState(null); const dispatch = useDispatch(); const userText = useSelector( authSelectors.selectCurrentUserNameOrEmailPrefix, ); const userAvatar = useSelector( authSelectors.selectCurrentUserAvatar, ); const currentTenant = useSelector( authSelectors.selectCurrentTenant, ); const handleClick = (event) => { setAnchorEl(event.currentTarget); }; const handleClose = () => { setAnchorEl(null); }; const doSignout = () => { dispatch(authActions.doSignout()); }; const doNavigateToProfile = () => { getHistory().push('/profile'); }; const doNavigateToPasswordChange = () => { getHistory().push('/password-change'); }; const doNavigateToTenants = () => { getHistory().push('/tenant'); }; const { transparentNavbar, darkMode } = selectMuiSettings(); // Styles for the navbar icons const iconsStyle = ({ palette: { dark, white, text }, functions: { rgba }, }: { palette: any; functions: any; }) => ({ color: () => { let colorValue = light || darkMode ? white.main : dark.main; if (transparentNavbar && !light) { colorValue = darkMode ? rgba(text.main, 0.6) : text.main; } return colorValue; }, }); return ( <> <IconButton onClick={handleClick} sx={navbarIconButton} size="small" color="inherit" disableRipple > <Icon sx={iconsStyle}>account_circle</Icon> </IconButton> <Menu anchorEl={anchorEl} keepMounted open={Boolean(anchorEl)} onClose={handleClose} > <NotificationItem onClick={doNavigateToProfile} icon={<Icon>person_outline</Icon>} title={i18n('auth.profile.title')} /> <NotificationItem onClick={doNavigateToPasswordChange} icon={<Icon>lock</Icon>} title={i18n('auth.passwordChange.title')} /> {['multi', 'multi-with-subdomain'].includes( config.tenantMode, ) && ( <NotificationItem onClick={doNavigateToTenants} icon={<Icon>apps</Icon>} title={i18n('auth.tenants')} /> )} {config.apiDocumentationUrl && ( <NotificationItem outlink href={config.apiDocumentationUrl} icon={<Icon>code</Icon>} title={i18n('api.menu')} target="_blank" rel="noopener noreferrer" /> )} <NotificationItem onClick={doSignout} icon={<Icon>exit_to_app</Icon>} title={i18n('auth.signout')} /> </Menu> </> ); } // Declaring default props for UserMenu UserMenu.defaultProps = { absolute: false, light: false, isMini: false, }; export default UserMenu;
/* eslint-disable no-new */ import { Cell } from './cell' import { Colors } from './colors' import { Bishop } from './figures/bishop' import { King } from './figures/king' import { Knight } from './figures/knight' import { Pawn } from './figures/pawn' import { Queen } from './figures/queen' import { Rook } from './figures/rook' export class Board { cells: Cell[][] = [] public initCells () { for (let i = 0; i < 8; i++) { const row: Cell[] = [] for (let j = 0; j < 8; j++) { if ((i + j) % 2 !== 0) { row.push(new Cell(this, i, j, Colors.BLACK, null)) } else { row.push(new Cell(this, i, j, Colors.WHITE, null)) } } this.cells.push(row) } } public getCopyBoard (): Board { const newBoard = new Board() newBoard.cells = this.cells return newBoard } public highLiteCells (selectedCell: Cell | null) { for (let i = 0; i < this.cells.length; i++) { const row = this.cells[i] for (let j = 0; j < row.length; j++) { const target = row[j] target.available = !!selectedCell?.figure?.canMove(target) } } } public getCell (x: number, y: number) { return this.cells[y][x] } private addPawn () { for (let i = 0; i < 8; i++) { new Pawn(Colors.BLACK, this.getCell(i, 1)) new Pawn(Colors.WHITE, this.getCell(i, 6)) } } private addBishop () { new Bishop(Colors.BLACK, this.getCell(2, 0)) new Bishop(Colors.BLACK, this.getCell(5, 0)) new Bishop(Colors.WHITE, this.getCell(2, 7)) new Bishop(Colors.WHITE, this.getCell(5, 7)) } private addKing () { new King(Colors.BLACK, this.getCell(4, 0)) new King(Colors.WHITE, this.getCell(4, 7)) } private addKnight () { new Knight(Colors.BLACK, this.getCell(1, 0)) new Knight(Colors.BLACK, this.getCell(6, 0)) new Knight(Colors.WHITE, this.getCell(1, 7)) new Knight(Colors.WHITE, this.getCell(6, 7)) } private addQueen () { new Queen(Colors.BLACK, this.getCell(3, 0)) new Queen(Colors.WHITE, this.getCell(3, 7)) } private addRook () { new Rook(Colors.BLACK, this.getCell(0, 0)) new Rook(Colors.BLACK, this.getCell(7, 0)) new Rook(Colors.WHITE, this.getCell(0, 7)) new Rook(Colors.WHITE, this.getCell(7, 7)) } public addFigures () { this.addPawn() this.addKing() this.addKnight() this.addBishop() this.addQueen() this.addRook() } }
import React, { useState } from "react"; import { ImQuotesRight } from "react-icons/im"; import { FaChevronLeft, FaChevronRight } from "react-icons/fa"; import reviews from "../../data"; const Review = () => { const [index, setIndex] = useState(0); const { name, job, image, text } = reviews[index]; const nextItemHandler = () => { setIndex((prev) => { if (prev === reviews.length - 1) return 0; return prev + 1; }); }; const previousItemHandler = () => { setIndex((prev) => { if (prev === 0) return reviews.length - 1; return prev - 1; }); }; const randomItemHandler = () => { const rand = Math.floor(Math.random() * reviews.length); setIndex(rand); }; return ( <div className="main"> <section className="container"> <div className="title"> <h2>Our Reviews</h2> <div className="underline"></div> </div> <article className="review"> <div className="img-container"> <img src={image} alt="" className="person-img" /> <img src="" alt="" /> <i className="quote-icon"> <ImQuotesRight /> </i> </div> <div> <h4 className="author">{name}</h4> <p className="job">{job}</p> <p className="info">{text}</p> </div> <button className="prev-btn" onClick={previousItemHandler}> <FaChevronLeft /> </button> <button className="next-btn" onClick={nextItemHandler}> <FaChevronRight /> </button> <div> <button className="random-btn" onClick={randomItemHandler}> Surprise Me </button> </div> </article> </section> </div> ); }; export default Review;
import { Controller, Get, Post, Body, Patch, Param, Delete, UploadedFile, UseInterceptors, BadRequestException, Res } from '@nestjs/common'; import { FilesService } from './files.service'; import { FileInterceptor } from '@nestjs/platform-express'; import { diskStorage } from 'multer'; import { fileFilter, fileNamer } from './helpers'; import { Response } from 'express'; import { ConfigService } from '@nestjs/config'; import { ApiTags } from '@nestjs/swagger'; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //mirar como se haria esto con ParseFilePipe que es nuevo en NEST //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! @ApiTags('Files') @Controller('files') export class FilesController { constructor(private readonly filesService: FilesService, private readonly configService: ConfigService) {} @Get('product/:imageName') findProductImage( @Res() res: Response, //Esto hace que tu mismo tengas que emitir la respuesta y no que lo haga nest automaticamente //Tambien se salta interceptores y algunos pasos del ciclo de vida de nest, por lo q hay que estar muy seguroi de usarlo @Param('imageName') imageName: string ){ const path = this.filesService.getStaticProductImage(imageName); res.sendFile(path); } @Post('product') @UseInterceptors( FileInterceptor( 'file', { fileFilter: fileFilter, storage: diskStorage({ destination: './static/products', filename: fileNamer }) } ) ) uploadProductImage(@UploadedFile() file: Express.Multer.File){ //Mejor no subir esta imagen al filesystem, mejor a un servidor distinto, aqui se hará así por simplificar //por ejemplo amazon o cloudinary //Si la imagen no pasa las validaciones del fileFilter en el interceptor entonces llegará undefined y aqui es donde sacaremos la excepcion if( !file ){ throw new BadRequestException('Make sure that the file is an image'); } const secureUrl = `${this.configService.get('HOST_API')}/files/product/${file.filename}`; return {secureUrl}; } }
import React, { Component } from "react"; import { Form, Button } from "react-bootstrap"; import { AiOutlineSend } from "react-icons/ai"; import { GoFileMedia } from "react-icons/go"; import { getDatabase, ref, push, set, child } from "../../firebase-config"; import MediaModal from "./MediaModal"; export default class MessageForm extends Component { state = { msg: "", errorMsg: "", modal: false, }; openModal = () => { this.setState({ modal: true }); }; closeModal = () => { this.setState({ modal: false }); }; handleSubmit = () => { if (this.state.msg) { const db = getDatabase(); const messageRef = ref(db, "message"); const newMessageRef = push(child(messageRef, `${this.props.currentgroup.Id}`)); set(newMessageRef, { userName: this.props.currentuser.displayName, msg: this.state.msg, date: Date(), sender: this.props.currentuser.uid, groupId: this.props.currentgroup.Id, }).then(() => { this.setState({ errorMsg: "" }); this.setState({ msg: "" }); }); } else { this.setState({ errorMsg: "message nai" }); } }; render() { return ( <> <div style={{ display: "flex", justifyContent: "space-between", borderTop: "1px solid #d1d1d1", paddingTop: "10px", }} > <Button onClick={this.openModal} style={{ width: "38px", height: "38px", padding: "0px" }} variant="outline-dark"> <GoFileMedia style={{ fontSize: "20px" }} /> </Button> <Form.Group style={{ width: "86%" }} className="mb-3" controlId="formBasicEmail"> <Form.Control onChange={(e) => this.setState({ msg: e.target.value })} value={this.state.msg} type="text" placeholder="Aa..." style={this.state.errorMsg.includes("message nai") ? styleError : noneError} /> </Form.Group> <Button style={{ width: "38px", height: "38px", padding: "0px" }} variant="outline-primary" onClick={this.handleSubmit}> <AiOutlineSend style={{ fontSize: "20px" }} /> </Button> </div> <MediaModal currentgroup={this.props.currentgroup} currentuser={this.props.currentuser} modal={this.state.modal} closeModal={this.closeModal} /> </> ); } } let styleError = { borderColor: "#f20202", }; let noneError = { borderColor: "#ced4da", };
import DITranquillity import Combine import UIKit final class CatalogPart: DIPart { static func load(container: DIContainer) { container.register(CatalogPresenter.init) .as(CatalogEventHandler.self) .lifetime(.objectGraph) } } // MARK: - Presenter final class CatalogPresenter { private weak var view: CatalogViewBehavior! private var router: CatalogRoutable! private let feedService: FeedService private var activity: ActivityDisposable? private var bag = Set<AnyCancellable>() private var filter: SeriesFilter = SeriesFilter() private lazy var paginator: Paginator = Paginator<Series, IntPaging>(IntPaging()) { [unowned self] in return self.feedService.fetchCatalog(page: $0, filter: self.filter) } init(feedService: FeedService) { self.feedService = feedService } } extension CatalogPresenter: RouterCommandResponder { func respond(command: RouteCommand) -> Bool { if let filterCommand = command as? FilterRouteCommand { if self.filter != filterCommand.value { self.update(filter: filterCommand.value) } return true } if let searchCommand = command as? SearchResultCommand { switch searchCommand.value { case let .series(item): self.select(series: item) case let .google(query): self.router.open(url: .google(query)) case .filter: break } return true } return false } } extension CatalogPresenter: CatalogEventHandler { func bind(view: CatalogViewBehavior, router: CatalogRoutable, filter: SeriesFilter) { self.view = view self.router = router self.filter = filter self.router.responder = self } func didLoad() { self.update(filter: self.filter) self.setupPaginator() self.activity = self.view.showLoading(fullscreen: false) self.paginator.refresh() } func refresh() { self.activity = self.view.showRefreshIndicator() self.paginator.refresh() } func loadMore() { self.paginator.loadNewPage() } func select(series: Series) { self.feedService.series(with: series.code) .manageActivity(self.view.showLoading(fullscreen: false)) .sink(onNext: { [weak self] item in self?.router.open(series: item) }, onError: { [weak self] error in self?.router.show(error: error) }) .store(in: &bag) } func openFilter() { self.feedService.fetchFiltedData() .manageActivity(self.view.showLoading(fullscreen: false)) .sink(onNext: { [weak self] data in self?.router.open(filter: self!.filter, data: data) }, onError: { [weak self] error in self?.router.show(error: error) }) .store(in: &bag) } func search() { self.router.openSearchScreen() } private func update(filter: SeriesFilter) { self.filter = filter self.view.setFilter(active: self.filter != SeriesFilter()) self.refresh() } private func setupPaginator() { var pageActivity: ActivityDisposable? self.paginator.handler .showData { [weak self] value in switch value.data { case let .first(items): self?.view.set(items: items) case let .next(items): self?.view.append(items: items) } self?.activity?.dispose() } .showEmptyError { [weak self] value in if let error = value.error { self?.router.show(error: error) } self?.activity?.dispose() } .showPageProgress { [weak self] show in if show { pageActivity = self?.view.loadPageProgress() } else { pageActivity?.dispose() } } } }
--- title: Updated Ditch the Limits Installing Linux on Your Chromebook (Updated 2023) for 2024 date: 2024-04-29T19:43:34.936Z updated: 2024-04-30T19:43:34.936Z tags: - video editing software - video editing categories: - ai - video description: This Article Describes Updated Ditch the Limits Installing Linux on Your Chromebook (Updated 2023) for 2024 excerpt: This Article Describes Updated Ditch the Limits Installing Linux on Your Chromebook (Updated 2023) for 2024 keywords: get started with linux on your chromebook a comprehensive installation guide,the complete guide to running linux on a chromebook updated 2023,unleash the power of linux on your chromebook an installation guide for 20,ditch the limits installing linux on your chromebook updated 2023,take your chromebook to the next level installing linux made easy,install linux on your chromebook the ultimate how to,the complete guide to installing linux on a chromebook thumbnail: https://www.lifewire.com/thmb/Rjkf6fiPF-oXAs-UqYWshvM3oZ4=/400x300/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/CODA-d4dd2a9b6c3d4a008a05c9718c9bce1e.jpg --- ## Ditch the Limits: Installing Linux on Your Chromebook (Updated 2023) # How to Install Linux on Chromebook ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) ##### Ollie Mattison Mar 27, 2024• Proven solutions Chromebooks are an excellent choice for educational institutions or businesses that require their employees to have constant access to the Internet. Even though these devices are a perfect tool that can accompany you on business trips and enable you to answer important emails or have access to crucial information stored on the cloud, performing more demanding tasks, like video editing, is still a challenge. However, it is far from impossible, although you may have to take a few extra steps before running a video editing software on your Chromebook. Chrome OS is a Linux based environment and for that reason, Chromebook owners who would like to use professional editing software on their Chromebooks can install a Linux OS that will enable them to use programs such as Lightworks that are perfectly suited for high-end video editing. There are two different ways to install Linux on a Chromebook, you can either do it using Gallium OS or ChrUbuntu or in a Chroot environment using Crouton. Each of these methods is relatively easy and we will take you through the process step by step. Here's how you can install Linux on your Chromebook. * [Part 1: Preparing before installing Linux OS on Chromebook](#part1) * [Part 2: How to Install Linux as a Chroot Using Crouton on Chromebook](#part2) * [Part 3: How to Dual-Boot a Chromebook Using ChrUbuntu](#part3) * [Part 4: How to Install Linux as a Chroot Using Crouton on Chromebook](#part4) * [Part 5: Recommended Linux Video Editing Software](#part5) ## Part 1: Preparing before installing Linux OS on Chromebook The first step of the process of installing the Linux OS is the decision itself, and you need to have all the necessary information before you decide to install a Linux OS on your Chromebook. * Make sure that the version of Chromebook you have is capable of supporting a Linux OS. Your device must be equipped with an ARM or Intel chip in order to be able to run the version of Linux OS you want to install. Although both chips will allow you to go through the process, running closed source software such the Steam is only possible with Intel chips. * Regardless of which method of installing Linux OS you choose, you will have to switch to the Developer Mode, a special built-in function that allows you to install the unapproved operating system, among other things. * Now that you are aware of the requirements and risks, you will have to backup all the files you have on your Chromebook because once you switch to the Developer Mode all the information stored locally will be erased. You can save the files on another computer or on the cloud depending on how much data you need to move and which one is more convenient for you. ## Part 2: How to Install Linux as a Chroot Using Crouton on Chromebook After you have stored all your data safely, your Chromebook is ready for the beginning of the installation process of the secondary operating system. You will have to perform a series of actions that will allow you to start the installation, starting from accessing the Developer Mode. #### 1. Acessing the developer mode The first step of the process is to reboot your system, while your Chromebook is on. In order to do so hold Escape and Refresh keys on your keyboard and then hit the power button. Once your device is back online you will find yourself in the recovery mode, and you will see a message telling you to insert a recovery disc. Instead of inserting the disc, hold Ctrl+D and wait for OS verification menu to appear on the screen. At this point, if you are still having second thoughts about this process, you can hit the spacebar to return to recovery mode, or press Enter to proceed. Hitting Enter will delete all the data stored on your device and take you into the Developer Mode. Once your Chromebook lets you know that you are now in the Developer Mode, reboot the system and install a fresh version of the Chrome OS. Insert your login information and follow the instructions until you are looking at the Chrome OS desktop. ![Install Linux on Chromebook](https://images.wondershare.com/filmora/article-images/install-linux-on-chromebook-1.jpg) #### 2. Installing Chroot At this stage of the process, your Chromebook is ready for the installation of the Crouton environment. Crouton is a series of scripts that makes running a Linux OS much easier, especially for inexperienced users. In order to download Crouton, go to [GitHub](https://github.com/dnschneid/crouton) and find the download link, detailed instructions or extensions that can add more functionality to your OS. Once the installation file or files are in the Download folder, your next step is to access the Chromebook's terminal a feature called 'Crosh'. The fastest way to do this is to hold CTRL + ALT keys and then hit the T key. This action will cause the Chrome window to appear on the screen, and you will need to type the 'shell' command without using quotation marks. Afterwards, enter the following command: 'sudo sh \~/Downloads/crouton -t xfce' and if you want to install extensions you will have to add 'xfce,extension' command at the end. ![Install Linux on Chromebook](https://images.wondershare.com/filmora/article-images/install-linux-on-chromebook-2.jpg) Press the Enter key and wait for the system to start setting up the Chroot. This process may take a while, so it is important to be patient, but more importantly, do not interfere with it in any way. Installation of your secondary OS is now on the way, and you may be asked to insert your login data, like your Gmail username and password. Wait patiently until the process is over and then return to shell and enter this command: 'sudo enter-chroot startxfce4'. Your screen will go black for a while, but after the black screen is gone your Chromebook will be in the freshly installed Linux OS. #### 3. Optimizing your new OS You may have to optimize your new OS in order to improve the experience of using it. Enabling your keyboard's brightness and volume keys inside the new OS can be done easily by holding CTRL+ALT+T and then typing shell once you've accessed Chrome OS's shell and hit Enter. Issue the following command: 'sudo sh -e \~/Downloads/crouton-r precise-t keyboard–u' and then press Enter again. Removing the screen saver or installing more extensions may also be a good way to enable more options in the new OS. Most importantly, you can now download and install the video editing software you want to use for editing your footage. #### 4. Remove Chroot from your Chromebook If for some reason you want to uninstall Linux from your Chromebook, simply reboot the system and press the spacebar when the 'OS verification is off' message appears on the screen. In this manner, you will exit the Developer Mode and all locally stored data, including all installed environments, will be deleted. ## Part 3: How to Dual-Boot a Chromebook Using ChrUbuntu An alternative option is available for Chromebook users that have Intel based devices like recently released Haswell models. The ChrUbuntu can be installed on the USB stick or external hard-drive or directly to the local memory of your Chromebook. Even though ARM-based machines can also use ChrUbuntu it isn't advisable because they may perform poorly due to slower processor speeds and less RAM power. Unlike Chroot, ChrUbuntu will not allow you to switch between operating systems without a reboot, and if the system is stored locally, you may need to go through the full system recovery. #### 1. Preparation for the installation Like with the previous method you will have to go into the Developer Mode and make sure that you have access to a WiFi connection. When you are asked to provide your login details, instead of entering them press Ctrl+Alt+Forward and then type 'chronos' and press Enter. The next step will require you to issue the following command: 'curl -L -O <http://goo.gl/9sgchs>; sudo bash 9sgchs' and then once more hit Enter. Again press Enter after the information about the installation is displayed on the screen and then you will be asked to decide how much space you want to allocate for Linux installation. Experts say that 9GB is the upper limit. After you've made your choice press Enter. #### 2. Installing ChrUbuntu Once the partitioning of your hard-drive is completed, you will have to repeat the first several steps from typing 'chronos' to pressing enter when information about the installation is displayed on the screen. The installation process is now in progress and you will be occasionally asked to select a few settings, make sure you always click on default. At the end of the installation process, you will have to choose the location where GRUB should be installed, please select /dev/sda, because the failure to do so may interrupt the installation. Once the installation is completed, restart your Chromebook to finalize the process, and when you see the 'OS Verification is Off' notification press Ctrl+L to access Linux or Ctrl+D boot into Chrome OS. ![Install Linux on Chromebook](https://images.wondershare.com/filmora/article-images/install-linux-on-chromebook-3.jpg) #### 3. Uninstall ChrUbuntu Removing ChrUbuntu is a relatively painless process that can be completed with just a few simple commands. If the OS is stored locally the only way to erase it is to perform a full system recovery. While all your data located on the cloud will re-sync with your Chromebook, the data stored locally will be deleted, which is why it is important to backup all the important files before starting a system recovery process. The fastest and easiest way to perform a system recovery is by creating a recovery disk from your device. Insert 'chrome://imageburner' in your browser's address bar, and carefully read and follow the instructions. This Linux removal method will also require you to have a USB stick with a minimum of 4GB of storage space. After you created the disk, you can go into the Recovery Mode, by holding Esc and Refresh buttons simultaneously and then pressing the Power button. In the Recovery Mode, you will be asked to insert the recovery disk and the process will be on the way. ## Part 4: How to Dual-Boot a Chromebook Using Gallium OS If neither Chroot nor ChrUbuntu work for you, using Gallium OS may be the right choice. The Gallium is Xbuntu-based OS that is equipped with touchpad mouse drivers among other advantages it offers over other operating systems. The installation process isn't complicated, although it may require more effort than installing Crouton. #### 1. Preparation for the installation In order to be aware of all the preparation steps, you need to take, you must first find out your device's Hardware ID number and you can obtain this information by navigating to Chrome://System, Hardware Class within the Chrome OS. [Hardware Compatibility](https://wiki.galliumos.org/Hardware%5FCompatibility) page will provide the information regarding the CPU's family, which can be crucial for the OS' performance. You can run the installation either from an ISO image on an external USB drive or from the Chrome OS command line using Chrx. We will describe how to install Gallium OS from the Chrome OS command line because the other option doesn't allow you to dual-boot your Chromebook. #### 2. Enabling the Legacy Mode Like previously described, enter the Developer Mode and when the ' OS verification is OFF' notification appears on the screen proceed to enable the Legacy Mode. You can do this by holding CTRL+D keys to enable the Chrome OS to boot in the Developer Mode. After you've successfully made this step, press CTRl+ALT+T to access the 'Crosh' terminal and then type 'shell'. At the 'chronos/localhost/$ issue the following command: 'sudo crossystem dev\_boot\_legacy=1'. Update and install all the necessary firmware by running the Firmware Utility Script. #### 3. Installation process If you choose to install Gallium OS through Chrome OS command line using Chrx that will enable you to dual-boot your Chromebook, you should start by booting the device into Chrome OS and configuring networking. The next step you'll need to take is switching to a virtual terminal by holding Ctrl+Alt+F2, and then you should log in as user chronos without a password. Once you've completed this step issue the following command: 'curl -O <https://chrx.org/go> && sh go' and follow the on-screen instructions to repartition your hard-drive and install the Gallium OS. Once the installation is over reboot the device and press Ctrl+L when the 'OS Verification is Off' notification appears on the screen to boot Gallium OS or hold Ctrl+D to access Chrome OS. After the Gallium OS is successfully installed on your Chromebook you can start using programs such as Skype or Lightworks. #### Which Method is the Best? Each of the options to install a Linux OS on your Chromebook we described has its advantages and disadvantages. It is our opinion that the Crouton method is the easiest and the fastest. Furthermore, this method enables you to switch between your primary and secondary OS without the need to reboot the device and the Downloads folder makes working in both environments much easier. On the other hand, other methods require more knowledge about the Linux OS installation process and switching between OS' is not that simple. If you are looking for an easy way to dual-boot your Chromebook that best way to do it is to install Linux as a Chroot using Crouton. ## Part 5: Recommended Linux Video Editing Software: Lightworks **Price:** $24.99/month, although free versions of the software are also available. **What we like:** A powerful video and audio editor perfectly suited for the production of professional video content. **What we don't like:** The software isn't easy to use and inexperienced editors will find it difficult to use at first. Lightworks Resolve may not be as popular as Adobe Premiere Pro or Final Cut Pro, but that doesn't mean that this video editing software isn't as capable as its more popular counterparts. The software is compatible with Mac, Windows, and Linux OS, which makes it a perfect choice for Chromebook users that have a Linux OS installed on their devices. Lightworks features literally every editing tool imaginable and for that reason, it is a perfect choice for editing videos you would like to upload to Vimeo or YouTube or high-end professional projects. This editing software offers plenty of transitions and visual effects that will help its users to create seamless jumps between shots and visually impressive videos. ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) Ollie Mattison Ollie Mattison is a writer and a lover of all things video. Follow @Ollie Mattison ##### Ollie Mattison Mar 27, 2024• Proven solutions Chromebooks are an excellent choice for educational institutions or businesses that require their employees to have constant access to the Internet. Even though these devices are a perfect tool that can accompany you on business trips and enable you to answer important emails or have access to crucial information stored on the cloud, performing more demanding tasks, like video editing, is still a challenge. However, it is far from impossible, although you may have to take a few extra steps before running a video editing software on your Chromebook. Chrome OS is a Linux based environment and for that reason, Chromebook owners who would like to use professional editing software on their Chromebooks can install a Linux OS that will enable them to use programs such as Lightworks that are perfectly suited for high-end video editing. There are two different ways to install Linux on a Chromebook, you can either do it using Gallium OS or ChrUbuntu or in a Chroot environment using Crouton. Each of these methods is relatively easy and we will take you through the process step by step. Here's how you can install Linux on your Chromebook. * [Part 1: Preparing before installing Linux OS on Chromebook](#part1) * [Part 2: How to Install Linux as a Chroot Using Crouton on Chromebook](#part2) * [Part 3: How to Dual-Boot a Chromebook Using ChrUbuntu](#part3) * [Part 4: How to Install Linux as a Chroot Using Crouton on Chromebook](#part4) * [Part 5: Recommended Linux Video Editing Software](#part5) ## Part 1: Preparing before installing Linux OS on Chromebook The first step of the process of installing the Linux OS is the decision itself, and you need to have all the necessary information before you decide to install a Linux OS on your Chromebook. * Make sure that the version of Chromebook you have is capable of supporting a Linux OS. Your device must be equipped with an ARM or Intel chip in order to be able to run the version of Linux OS you want to install. Although both chips will allow you to go through the process, running closed source software such the Steam is only possible with Intel chips. * Regardless of which method of installing Linux OS you choose, you will have to switch to the Developer Mode, a special built-in function that allows you to install the unapproved operating system, among other things. * Now that you are aware of the requirements and risks, you will have to backup all the files you have on your Chromebook because once you switch to the Developer Mode all the information stored locally will be erased. You can save the files on another computer or on the cloud depending on how much data you need to move and which one is more convenient for you. ## Part 2: How to Install Linux as a Chroot Using Crouton on Chromebook After you have stored all your data safely, your Chromebook is ready for the beginning of the installation process of the secondary operating system. You will have to perform a series of actions that will allow you to start the installation, starting from accessing the Developer Mode. #### 1. Acessing the developer mode The first step of the process is to reboot your system, while your Chromebook is on. In order to do so hold Escape and Refresh keys on your keyboard and then hit the power button. Once your device is back online you will find yourself in the recovery mode, and you will see a message telling you to insert a recovery disc. Instead of inserting the disc, hold Ctrl+D and wait for OS verification menu to appear on the screen. At this point, if you are still having second thoughts about this process, you can hit the spacebar to return to recovery mode, or press Enter to proceed. Hitting Enter will delete all the data stored on your device and take you into the Developer Mode. Once your Chromebook lets you know that you are now in the Developer Mode, reboot the system and install a fresh version of the Chrome OS. Insert your login information and follow the instructions until you are looking at the Chrome OS desktop. ![Install Linux on Chromebook](https://images.wondershare.com/filmora/article-images/install-linux-on-chromebook-1.jpg) #### 2. Installing Chroot At this stage of the process, your Chromebook is ready for the installation of the Crouton environment. Crouton is a series of scripts that makes running a Linux OS much easier, especially for inexperienced users. In order to download Crouton, go to [GitHub](https://github.com/dnschneid/crouton) and find the download link, detailed instructions or extensions that can add more functionality to your OS. Once the installation file or files are in the Download folder, your next step is to access the Chromebook's terminal a feature called 'Crosh'. The fastest way to do this is to hold CTRL + ALT keys and then hit the T key. This action will cause the Chrome window to appear on the screen, and you will need to type the 'shell' command without using quotation marks. Afterwards, enter the following command: 'sudo sh \~/Downloads/crouton -t xfce' and if you want to install extensions you will have to add 'xfce,extension' command at the end. ![Install Linux on Chromebook](https://images.wondershare.com/filmora/article-images/install-linux-on-chromebook-2.jpg) Press the Enter key and wait for the system to start setting up the Chroot. This process may take a while, so it is important to be patient, but more importantly, do not interfere with it in any way. Installation of your secondary OS is now on the way, and you may be asked to insert your login data, like your Gmail username and password. Wait patiently until the process is over and then return to shell and enter this command: 'sudo enter-chroot startxfce4'. Your screen will go black for a while, but after the black screen is gone your Chromebook will be in the freshly installed Linux OS. #### 3. Optimizing your new OS You may have to optimize your new OS in order to improve the experience of using it. Enabling your keyboard's brightness and volume keys inside the new OS can be done easily by holding CTRL+ALT+T and then typing shell once you've accessed Chrome OS's shell and hit Enter. Issue the following command: 'sudo sh -e \~/Downloads/crouton-r precise-t keyboard–u' and then press Enter again. Removing the screen saver or installing more extensions may also be a good way to enable more options in the new OS. Most importantly, you can now download and install the video editing software you want to use for editing your footage. #### 4. Remove Chroot from your Chromebook If for some reason you want to uninstall Linux from your Chromebook, simply reboot the system and press the spacebar when the 'OS verification is off' message appears on the screen. In this manner, you will exit the Developer Mode and all locally stored data, including all installed environments, will be deleted. ## Part 3: How to Dual-Boot a Chromebook Using ChrUbuntu An alternative option is available for Chromebook users that have Intel based devices like recently released Haswell models. The ChrUbuntu can be installed on the USB stick or external hard-drive or directly to the local memory of your Chromebook. Even though ARM-based machines can also use ChrUbuntu it isn't advisable because they may perform poorly due to slower processor speeds and less RAM power. Unlike Chroot, ChrUbuntu will not allow you to switch between operating systems without a reboot, and if the system is stored locally, you may need to go through the full system recovery. #### 1. Preparation for the installation Like with the previous method you will have to go into the Developer Mode and make sure that you have access to a WiFi connection. When you are asked to provide your login details, instead of entering them press Ctrl+Alt+Forward and then type 'chronos' and press Enter. The next step will require you to issue the following command: 'curl -L -O <http://goo.gl/9sgchs>; sudo bash 9sgchs' and then once more hit Enter. Again press Enter after the information about the installation is displayed on the screen and then you will be asked to decide how much space you want to allocate for Linux installation. Experts say that 9GB is the upper limit. After you've made your choice press Enter. #### 2. Installing ChrUbuntu Once the partitioning of your hard-drive is completed, you will have to repeat the first several steps from typing 'chronos' to pressing enter when information about the installation is displayed on the screen. The installation process is now in progress and you will be occasionally asked to select a few settings, make sure you always click on default. At the end of the installation process, you will have to choose the location where GRUB should be installed, please select /dev/sda, because the failure to do so may interrupt the installation. Once the installation is completed, restart your Chromebook to finalize the process, and when you see the 'OS Verification is Off' notification press Ctrl+L to access Linux or Ctrl+D boot into Chrome OS. ![Install Linux on Chromebook](https://images.wondershare.com/filmora/article-images/install-linux-on-chromebook-3.jpg) #### 3. Uninstall ChrUbuntu Removing ChrUbuntu is a relatively painless process that can be completed with just a few simple commands. If the OS is stored locally the only way to erase it is to perform a full system recovery. While all your data located on the cloud will re-sync with your Chromebook, the data stored locally will be deleted, which is why it is important to backup all the important files before starting a system recovery process. The fastest and easiest way to perform a system recovery is by creating a recovery disk from your device. Insert 'chrome://imageburner' in your browser's address bar, and carefully read and follow the instructions. This Linux removal method will also require you to have a USB stick with a minimum of 4GB of storage space. After you created the disk, you can go into the Recovery Mode, by holding Esc and Refresh buttons simultaneously and then pressing the Power button. In the Recovery Mode, you will be asked to insert the recovery disk and the process will be on the way. ## Part 4: How to Dual-Boot a Chromebook Using Gallium OS If neither Chroot nor ChrUbuntu work for you, using Gallium OS may be the right choice. The Gallium is Xbuntu-based OS that is equipped with touchpad mouse drivers among other advantages it offers over other operating systems. The installation process isn't complicated, although it may require more effort than installing Crouton. #### 1. Preparation for the installation In order to be aware of all the preparation steps, you need to take, you must first find out your device's Hardware ID number and you can obtain this information by navigating to Chrome://System, Hardware Class within the Chrome OS. [Hardware Compatibility](https://wiki.galliumos.org/Hardware%5FCompatibility) page will provide the information regarding the CPU's family, which can be crucial for the OS' performance. You can run the installation either from an ISO image on an external USB drive or from the Chrome OS command line using Chrx. We will describe how to install Gallium OS from the Chrome OS command line because the other option doesn't allow you to dual-boot your Chromebook. #### 2. Enabling the Legacy Mode Like previously described, enter the Developer Mode and when the ' OS verification is OFF' notification appears on the screen proceed to enable the Legacy Mode. You can do this by holding CTRL+D keys to enable the Chrome OS to boot in the Developer Mode. After you've successfully made this step, press CTRl+ALT+T to access the 'Crosh' terminal and then type 'shell'. At the 'chronos/localhost/$ issue the following command: 'sudo crossystem dev\_boot\_legacy=1'. Update and install all the necessary firmware by running the Firmware Utility Script. #### 3. Installation process If you choose to install Gallium OS through Chrome OS command line using Chrx that will enable you to dual-boot your Chromebook, you should start by booting the device into Chrome OS and configuring networking. The next step you'll need to take is switching to a virtual terminal by holding Ctrl+Alt+F2, and then you should log in as user chronos without a password. Once you've completed this step issue the following command: 'curl -O <https://chrx.org/go> && sh go' and follow the on-screen instructions to repartition your hard-drive and install the Gallium OS. Once the installation is over reboot the device and press Ctrl+L when the 'OS Verification is Off' notification appears on the screen to boot Gallium OS or hold Ctrl+D to access Chrome OS. After the Gallium OS is successfully installed on your Chromebook you can start using programs such as Skype or Lightworks. #### Which Method is the Best? Each of the options to install a Linux OS on your Chromebook we described has its advantages and disadvantages. It is our opinion that the Crouton method is the easiest and the fastest. Furthermore, this method enables you to switch between your primary and secondary OS without the need to reboot the device and the Downloads folder makes working in both environments much easier. On the other hand, other methods require more knowledge about the Linux OS installation process and switching between OS' is not that simple. If you are looking for an easy way to dual-boot your Chromebook that best way to do it is to install Linux as a Chroot using Crouton. ## Part 5: Recommended Linux Video Editing Software: Lightworks **Price:** $24.99/month, although free versions of the software are also available. **What we like:** A powerful video and audio editor perfectly suited for the production of professional video content. **What we don't like:** The software isn't easy to use and inexperienced editors will find it difficult to use at first. Lightworks Resolve may not be as popular as Adobe Premiere Pro or Final Cut Pro, but that doesn't mean that this video editing software isn't as capable as its more popular counterparts. The software is compatible with Mac, Windows, and Linux OS, which makes it a perfect choice for Chromebook users that have a Linux OS installed on their devices. Lightworks features literally every editing tool imaginable and for that reason, it is a perfect choice for editing videos you would like to upload to Vimeo or YouTube or high-end professional projects. This editing software offers plenty of transitions and visual effects that will help its users to create seamless jumps between shots and visually impressive videos. ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) Ollie Mattison Ollie Mattison is a writer and a lover of all things video. Follow @Ollie Mattison ##### Ollie Mattison Mar 27, 2024• Proven solutions Chromebooks are an excellent choice for educational institutions or businesses that require their employees to have constant access to the Internet. Even though these devices are a perfect tool that can accompany you on business trips and enable you to answer important emails or have access to crucial information stored on the cloud, performing more demanding tasks, like video editing, is still a challenge. However, it is far from impossible, although you may have to take a few extra steps before running a video editing software on your Chromebook. Chrome OS is a Linux based environment and for that reason, Chromebook owners who would like to use professional editing software on their Chromebooks can install a Linux OS that will enable them to use programs such as Lightworks that are perfectly suited for high-end video editing. There are two different ways to install Linux on a Chromebook, you can either do it using Gallium OS or ChrUbuntu or in a Chroot environment using Crouton. Each of these methods is relatively easy and we will take you through the process step by step. Here's how you can install Linux on your Chromebook. * [Part 1: Preparing before installing Linux OS on Chromebook](#part1) * [Part 2: How to Install Linux as a Chroot Using Crouton on Chromebook](#part2) * [Part 3: How to Dual-Boot a Chromebook Using ChrUbuntu](#part3) * [Part 4: How to Install Linux as a Chroot Using Crouton on Chromebook](#part4) * [Part 5: Recommended Linux Video Editing Software](#part5) ## Part 1: Preparing before installing Linux OS on Chromebook The first step of the process of installing the Linux OS is the decision itself, and you need to have all the necessary information before you decide to install a Linux OS on your Chromebook. * Make sure that the version of Chromebook you have is capable of supporting a Linux OS. Your device must be equipped with an ARM or Intel chip in order to be able to run the version of Linux OS you want to install. Although both chips will allow you to go through the process, running closed source software such the Steam is only possible with Intel chips. * Regardless of which method of installing Linux OS you choose, you will have to switch to the Developer Mode, a special built-in function that allows you to install the unapproved operating system, among other things. * Now that you are aware of the requirements and risks, you will have to backup all the files you have on your Chromebook because once you switch to the Developer Mode all the information stored locally will be erased. You can save the files on another computer or on the cloud depending on how much data you need to move and which one is more convenient for you. ## Part 2: How to Install Linux as a Chroot Using Crouton on Chromebook After you have stored all your data safely, your Chromebook is ready for the beginning of the installation process of the secondary operating system. You will have to perform a series of actions that will allow you to start the installation, starting from accessing the Developer Mode. #### 1. Acessing the developer mode The first step of the process is to reboot your system, while your Chromebook is on. In order to do so hold Escape and Refresh keys on your keyboard and then hit the power button. Once your device is back online you will find yourself in the recovery mode, and you will see a message telling you to insert a recovery disc. Instead of inserting the disc, hold Ctrl+D and wait for OS verification menu to appear on the screen. At this point, if you are still having second thoughts about this process, you can hit the spacebar to return to recovery mode, or press Enter to proceed. Hitting Enter will delete all the data stored on your device and take you into the Developer Mode. Once your Chromebook lets you know that you are now in the Developer Mode, reboot the system and install a fresh version of the Chrome OS. Insert your login information and follow the instructions until you are looking at the Chrome OS desktop. ![Install Linux on Chromebook](https://images.wondershare.com/filmora/article-images/install-linux-on-chromebook-1.jpg) #### 2. Installing Chroot At this stage of the process, your Chromebook is ready for the installation of the Crouton environment. Crouton is a series of scripts that makes running a Linux OS much easier, especially for inexperienced users. In order to download Crouton, go to [GitHub](https://github.com/dnschneid/crouton) and find the download link, detailed instructions or extensions that can add more functionality to your OS. Once the installation file or files are in the Download folder, your next step is to access the Chromebook's terminal a feature called 'Crosh'. The fastest way to do this is to hold CTRL + ALT keys and then hit the T key. This action will cause the Chrome window to appear on the screen, and you will need to type the 'shell' command without using quotation marks. Afterwards, enter the following command: 'sudo sh \~/Downloads/crouton -t xfce' and if you want to install extensions you will have to add 'xfce,extension' command at the end. ![Install Linux on Chromebook](https://images.wondershare.com/filmora/article-images/install-linux-on-chromebook-2.jpg) Press the Enter key and wait for the system to start setting up the Chroot. This process may take a while, so it is important to be patient, but more importantly, do not interfere with it in any way. Installation of your secondary OS is now on the way, and you may be asked to insert your login data, like your Gmail username and password. Wait patiently until the process is over and then return to shell and enter this command: 'sudo enter-chroot startxfce4'. Your screen will go black for a while, but after the black screen is gone your Chromebook will be in the freshly installed Linux OS. #### 3. Optimizing your new OS You may have to optimize your new OS in order to improve the experience of using it. Enabling your keyboard's brightness and volume keys inside the new OS can be done easily by holding CTRL+ALT+T and then typing shell once you've accessed Chrome OS's shell and hit Enter. Issue the following command: 'sudo sh -e \~/Downloads/crouton-r precise-t keyboard–u' and then press Enter again. Removing the screen saver or installing more extensions may also be a good way to enable more options in the new OS. Most importantly, you can now download and install the video editing software you want to use for editing your footage. #### 4. Remove Chroot from your Chromebook If for some reason you want to uninstall Linux from your Chromebook, simply reboot the system and press the spacebar when the 'OS verification is off' message appears on the screen. In this manner, you will exit the Developer Mode and all locally stored data, including all installed environments, will be deleted. ## Part 3: How to Dual-Boot a Chromebook Using ChrUbuntu An alternative option is available for Chromebook users that have Intel based devices like recently released Haswell models. The ChrUbuntu can be installed on the USB stick or external hard-drive or directly to the local memory of your Chromebook. Even though ARM-based machines can also use ChrUbuntu it isn't advisable because they may perform poorly due to slower processor speeds and less RAM power. Unlike Chroot, ChrUbuntu will not allow you to switch between operating systems without a reboot, and if the system is stored locally, you may need to go through the full system recovery. #### 1. Preparation for the installation Like with the previous method you will have to go into the Developer Mode and make sure that you have access to a WiFi connection. When you are asked to provide your login details, instead of entering them press Ctrl+Alt+Forward and then type 'chronos' and press Enter. The next step will require you to issue the following command: 'curl -L -O <http://goo.gl/9sgchs>; sudo bash 9sgchs' and then once more hit Enter. Again press Enter after the information about the installation is displayed on the screen and then you will be asked to decide how much space you want to allocate for Linux installation. Experts say that 9GB is the upper limit. After you've made your choice press Enter. #### 2. Installing ChrUbuntu Once the partitioning of your hard-drive is completed, you will have to repeat the first several steps from typing 'chronos' to pressing enter when information about the installation is displayed on the screen. The installation process is now in progress and you will be occasionally asked to select a few settings, make sure you always click on default. At the end of the installation process, you will have to choose the location where GRUB should be installed, please select /dev/sda, because the failure to do so may interrupt the installation. Once the installation is completed, restart your Chromebook to finalize the process, and when you see the 'OS Verification is Off' notification press Ctrl+L to access Linux or Ctrl+D boot into Chrome OS. ![Install Linux on Chromebook](https://images.wondershare.com/filmora/article-images/install-linux-on-chromebook-3.jpg) #### 3. Uninstall ChrUbuntu Removing ChrUbuntu is a relatively painless process that can be completed with just a few simple commands. If the OS is stored locally the only way to erase it is to perform a full system recovery. While all your data located on the cloud will re-sync with your Chromebook, the data stored locally will be deleted, which is why it is important to backup all the important files before starting a system recovery process. The fastest and easiest way to perform a system recovery is by creating a recovery disk from your device. Insert 'chrome://imageburner' in your browser's address bar, and carefully read and follow the instructions. This Linux removal method will also require you to have a USB stick with a minimum of 4GB of storage space. After you created the disk, you can go into the Recovery Mode, by holding Esc and Refresh buttons simultaneously and then pressing the Power button. In the Recovery Mode, you will be asked to insert the recovery disk and the process will be on the way. ## Part 4: How to Dual-Boot a Chromebook Using Gallium OS If neither Chroot nor ChrUbuntu work for you, using Gallium OS may be the right choice. The Gallium is Xbuntu-based OS that is equipped with touchpad mouse drivers among other advantages it offers over other operating systems. The installation process isn't complicated, although it may require more effort than installing Crouton. #### 1. Preparation for the installation In order to be aware of all the preparation steps, you need to take, you must first find out your device's Hardware ID number and you can obtain this information by navigating to Chrome://System, Hardware Class within the Chrome OS. [Hardware Compatibility](https://wiki.galliumos.org/Hardware%5FCompatibility) page will provide the information regarding the CPU's family, which can be crucial for the OS' performance. You can run the installation either from an ISO image on an external USB drive or from the Chrome OS command line using Chrx. We will describe how to install Gallium OS from the Chrome OS command line because the other option doesn't allow you to dual-boot your Chromebook. #### 2. Enabling the Legacy Mode Like previously described, enter the Developer Mode and when the ' OS verification is OFF' notification appears on the screen proceed to enable the Legacy Mode. You can do this by holding CTRL+D keys to enable the Chrome OS to boot in the Developer Mode. After you've successfully made this step, press CTRl+ALT+T to access the 'Crosh' terminal and then type 'shell'. At the 'chronos/localhost/$ issue the following command: 'sudo crossystem dev\_boot\_legacy=1'. Update and install all the necessary firmware by running the Firmware Utility Script. #### 3. Installation process If you choose to install Gallium OS through Chrome OS command line using Chrx that will enable you to dual-boot your Chromebook, you should start by booting the device into Chrome OS and configuring networking. The next step you'll need to take is switching to a virtual terminal by holding Ctrl+Alt+F2, and then you should log in as user chronos without a password. Once you've completed this step issue the following command: 'curl -O <https://chrx.org/go> && sh go' and follow the on-screen instructions to repartition your hard-drive and install the Gallium OS. Once the installation is over reboot the device and press Ctrl+L when the 'OS Verification is Off' notification appears on the screen to boot Gallium OS or hold Ctrl+D to access Chrome OS. After the Gallium OS is successfully installed on your Chromebook you can start using programs such as Skype or Lightworks. #### Which Method is the Best? Each of the options to install a Linux OS on your Chromebook we described has its advantages and disadvantages. It is our opinion that the Crouton method is the easiest and the fastest. Furthermore, this method enables you to switch between your primary and secondary OS without the need to reboot the device and the Downloads folder makes working in both environments much easier. On the other hand, other methods require more knowledge about the Linux OS installation process and switching between OS' is not that simple. If you are looking for an easy way to dual-boot your Chromebook that best way to do it is to install Linux as a Chroot using Crouton. ## Part 5: Recommended Linux Video Editing Software: Lightworks **Price:** $24.99/month, although free versions of the software are also available. **What we like:** A powerful video and audio editor perfectly suited for the production of professional video content. **What we don't like:** The software isn't easy to use and inexperienced editors will find it difficult to use at first. Lightworks Resolve may not be as popular as Adobe Premiere Pro or Final Cut Pro, but that doesn't mean that this video editing software isn't as capable as its more popular counterparts. The software is compatible with Mac, Windows, and Linux OS, which makes it a perfect choice for Chromebook users that have a Linux OS installed on their devices. Lightworks features literally every editing tool imaginable and for that reason, it is a perfect choice for editing videos you would like to upload to Vimeo or YouTube or high-end professional projects. This editing software offers plenty of transitions and visual effects that will help its users to create seamless jumps between shots and visually impressive videos. ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) Ollie Mattison Ollie Mattison is a writer and a lover of all things video. Follow @Ollie Mattison ##### Ollie Mattison Mar 27, 2024• Proven solutions Chromebooks are an excellent choice for educational institutions or businesses that require their employees to have constant access to the Internet. Even though these devices are a perfect tool that can accompany you on business trips and enable you to answer important emails or have access to crucial information stored on the cloud, performing more demanding tasks, like video editing, is still a challenge. However, it is far from impossible, although you may have to take a few extra steps before running a video editing software on your Chromebook. Chrome OS is a Linux based environment and for that reason, Chromebook owners who would like to use professional editing software on their Chromebooks can install a Linux OS that will enable them to use programs such as Lightworks that are perfectly suited for high-end video editing. There are two different ways to install Linux on a Chromebook, you can either do it using Gallium OS or ChrUbuntu or in a Chroot environment using Crouton. Each of these methods is relatively easy and we will take you through the process step by step. Here's how you can install Linux on your Chromebook. * [Part 1: Preparing before installing Linux OS on Chromebook](#part1) * [Part 2: How to Install Linux as a Chroot Using Crouton on Chromebook](#part2) * [Part 3: How to Dual-Boot a Chromebook Using ChrUbuntu](#part3) * [Part 4: How to Install Linux as a Chroot Using Crouton on Chromebook](#part4) * [Part 5: Recommended Linux Video Editing Software](#part5) ## Part 1: Preparing before installing Linux OS on Chromebook The first step of the process of installing the Linux OS is the decision itself, and you need to have all the necessary information before you decide to install a Linux OS on your Chromebook. * Make sure that the version of Chromebook you have is capable of supporting a Linux OS. Your device must be equipped with an ARM or Intel chip in order to be able to run the version of Linux OS you want to install. Although both chips will allow you to go through the process, running closed source software such the Steam is only possible with Intel chips. * Regardless of which method of installing Linux OS you choose, you will have to switch to the Developer Mode, a special built-in function that allows you to install the unapproved operating system, among other things. * Now that you are aware of the requirements and risks, you will have to backup all the files you have on your Chromebook because once you switch to the Developer Mode all the information stored locally will be erased. You can save the files on another computer or on the cloud depending on how much data you need to move and which one is more convenient for you. ## Part 2: How to Install Linux as a Chroot Using Crouton on Chromebook After you have stored all your data safely, your Chromebook is ready for the beginning of the installation process of the secondary operating system. You will have to perform a series of actions that will allow you to start the installation, starting from accessing the Developer Mode. #### 1. Acessing the developer mode The first step of the process is to reboot your system, while your Chromebook is on. In order to do so hold Escape and Refresh keys on your keyboard and then hit the power button. Once your device is back online you will find yourself in the recovery mode, and you will see a message telling you to insert a recovery disc. Instead of inserting the disc, hold Ctrl+D and wait for OS verification menu to appear on the screen. At this point, if you are still having second thoughts about this process, you can hit the spacebar to return to recovery mode, or press Enter to proceed. Hitting Enter will delete all the data stored on your device and take you into the Developer Mode. Once your Chromebook lets you know that you are now in the Developer Mode, reboot the system and install a fresh version of the Chrome OS. Insert your login information and follow the instructions until you are looking at the Chrome OS desktop. ![Install Linux on Chromebook](https://images.wondershare.com/filmora/article-images/install-linux-on-chromebook-1.jpg) #### 2. Installing Chroot At this stage of the process, your Chromebook is ready for the installation of the Crouton environment. Crouton is a series of scripts that makes running a Linux OS much easier, especially for inexperienced users. In order to download Crouton, go to [GitHub](https://github.com/dnschneid/crouton) and find the download link, detailed instructions or extensions that can add more functionality to your OS. Once the installation file or files are in the Download folder, your next step is to access the Chromebook's terminal a feature called 'Crosh'. The fastest way to do this is to hold CTRL + ALT keys and then hit the T key. This action will cause the Chrome window to appear on the screen, and you will need to type the 'shell' command without using quotation marks. Afterwards, enter the following command: 'sudo sh \~/Downloads/crouton -t xfce' and if you want to install extensions you will have to add 'xfce,extension' command at the end. ![Install Linux on Chromebook](https://images.wondershare.com/filmora/article-images/install-linux-on-chromebook-2.jpg) Press the Enter key and wait for the system to start setting up the Chroot. This process may take a while, so it is important to be patient, but more importantly, do not interfere with it in any way. Installation of your secondary OS is now on the way, and you may be asked to insert your login data, like your Gmail username and password. Wait patiently until the process is over and then return to shell and enter this command: 'sudo enter-chroot startxfce4'. Your screen will go black for a while, but after the black screen is gone your Chromebook will be in the freshly installed Linux OS. #### 3. Optimizing your new OS You may have to optimize your new OS in order to improve the experience of using it. Enabling your keyboard's brightness and volume keys inside the new OS can be done easily by holding CTRL+ALT+T and then typing shell once you've accessed Chrome OS's shell and hit Enter. Issue the following command: 'sudo sh -e \~/Downloads/crouton-r precise-t keyboard–u' and then press Enter again. Removing the screen saver or installing more extensions may also be a good way to enable more options in the new OS. Most importantly, you can now download and install the video editing software you want to use for editing your footage. #### 4. Remove Chroot from your Chromebook If for some reason you want to uninstall Linux from your Chromebook, simply reboot the system and press the spacebar when the 'OS verification is off' message appears on the screen. In this manner, you will exit the Developer Mode and all locally stored data, including all installed environments, will be deleted. ## Part 3: How to Dual-Boot a Chromebook Using ChrUbuntu An alternative option is available for Chromebook users that have Intel based devices like recently released Haswell models. The ChrUbuntu can be installed on the USB stick or external hard-drive or directly to the local memory of your Chromebook. Even though ARM-based machines can also use ChrUbuntu it isn't advisable because they may perform poorly due to slower processor speeds and less RAM power. Unlike Chroot, ChrUbuntu will not allow you to switch between operating systems without a reboot, and if the system is stored locally, you may need to go through the full system recovery. #### 1. Preparation for the installation Like with the previous method you will have to go into the Developer Mode and make sure that you have access to a WiFi connection. When you are asked to provide your login details, instead of entering them press Ctrl+Alt+Forward and then type 'chronos' and press Enter. The next step will require you to issue the following command: 'curl -L -O <http://goo.gl/9sgchs>; sudo bash 9sgchs' and then once more hit Enter. Again press Enter after the information about the installation is displayed on the screen and then you will be asked to decide how much space you want to allocate for Linux installation. Experts say that 9GB is the upper limit. After you've made your choice press Enter. #### 2. Installing ChrUbuntu Once the partitioning of your hard-drive is completed, you will have to repeat the first several steps from typing 'chronos' to pressing enter when information about the installation is displayed on the screen. The installation process is now in progress and you will be occasionally asked to select a few settings, make sure you always click on default. At the end of the installation process, you will have to choose the location where GRUB should be installed, please select /dev/sda, because the failure to do so may interrupt the installation. Once the installation is completed, restart your Chromebook to finalize the process, and when you see the 'OS Verification is Off' notification press Ctrl+L to access Linux or Ctrl+D boot into Chrome OS. ![Install Linux on Chromebook](https://images.wondershare.com/filmora/article-images/install-linux-on-chromebook-3.jpg) #### 3. Uninstall ChrUbuntu Removing ChrUbuntu is a relatively painless process that can be completed with just a few simple commands. If the OS is stored locally the only way to erase it is to perform a full system recovery. While all your data located on the cloud will re-sync with your Chromebook, the data stored locally will be deleted, which is why it is important to backup all the important files before starting a system recovery process. The fastest and easiest way to perform a system recovery is by creating a recovery disk from your device. Insert 'chrome://imageburner' in your browser's address bar, and carefully read and follow the instructions. This Linux removal method will also require you to have a USB stick with a minimum of 4GB of storage space. After you created the disk, you can go into the Recovery Mode, by holding Esc and Refresh buttons simultaneously and then pressing the Power button. In the Recovery Mode, you will be asked to insert the recovery disk and the process will be on the way. ## Part 4: How to Dual-Boot a Chromebook Using Gallium OS If neither Chroot nor ChrUbuntu work for you, using Gallium OS may be the right choice. The Gallium is Xbuntu-based OS that is equipped with touchpad mouse drivers among other advantages it offers over other operating systems. The installation process isn't complicated, although it may require more effort than installing Crouton. #### 1. Preparation for the installation In order to be aware of all the preparation steps, you need to take, you must first find out your device's Hardware ID number and you can obtain this information by navigating to Chrome://System, Hardware Class within the Chrome OS. [Hardware Compatibility](https://wiki.galliumos.org/Hardware%5FCompatibility) page will provide the information regarding the CPU's family, which can be crucial for the OS' performance. You can run the installation either from an ISO image on an external USB drive or from the Chrome OS command line using Chrx. We will describe how to install Gallium OS from the Chrome OS command line because the other option doesn't allow you to dual-boot your Chromebook. #### 2. Enabling the Legacy Mode Like previously described, enter the Developer Mode and when the ' OS verification is OFF' notification appears on the screen proceed to enable the Legacy Mode. You can do this by holding CTRL+D keys to enable the Chrome OS to boot in the Developer Mode. After you've successfully made this step, press CTRl+ALT+T to access the 'Crosh' terminal and then type 'shell'. At the 'chronos/localhost/$ issue the following command: 'sudo crossystem dev\_boot\_legacy=1'. Update and install all the necessary firmware by running the Firmware Utility Script. #### 3. Installation process If you choose to install Gallium OS through Chrome OS command line using Chrx that will enable you to dual-boot your Chromebook, you should start by booting the device into Chrome OS and configuring networking. The next step you'll need to take is switching to a virtual terminal by holding Ctrl+Alt+F2, and then you should log in as user chronos without a password. Once you've completed this step issue the following command: 'curl -O <https://chrx.org/go> && sh go' and follow the on-screen instructions to repartition your hard-drive and install the Gallium OS. Once the installation is over reboot the device and press Ctrl+L when the 'OS Verification is Off' notification appears on the screen to boot Gallium OS or hold Ctrl+D to access Chrome OS. After the Gallium OS is successfully installed on your Chromebook you can start using programs such as Skype or Lightworks. #### Which Method is the Best? Each of the options to install a Linux OS on your Chromebook we described has its advantages and disadvantages. It is our opinion that the Crouton method is the easiest and the fastest. Furthermore, this method enables you to switch between your primary and secondary OS without the need to reboot the device and the Downloads folder makes working in both environments much easier. On the other hand, other methods require more knowledge about the Linux OS installation process and switching between OS' is not that simple. If you are looking for an easy way to dual-boot your Chromebook that best way to do it is to install Linux as a Chroot using Crouton. ## Part 5: Recommended Linux Video Editing Software: Lightworks **Price:** $24.99/month, although free versions of the software are also available. **What we like:** A powerful video and audio editor perfectly suited for the production of professional video content. **What we don't like:** The software isn't easy to use and inexperienced editors will find it difficult to use at first. Lightworks Resolve may not be as popular as Adobe Premiere Pro or Final Cut Pro, but that doesn't mean that this video editing software isn't as capable as its more popular counterparts. The software is compatible with Mac, Windows, and Linux OS, which makes it a perfect choice for Chromebook users that have a Linux OS installed on their devices. Lightworks features literally every editing tool imaginable and for that reason, it is a perfect choice for editing videos you would like to upload to Vimeo or YouTube or high-end professional projects. This editing software offers plenty of transitions and visual effects that will help its users to create seamless jumps between shots and visually impressive videos. ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) Ollie Mattison Ollie Mattison is a writer and a lover of all things video. Follow @Ollie Mattison <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> ## What's My Aspect Ratio? Calculator and Tutorial ##### How Do You Find the Picture Ratio Calculator? An easy yet powerful editor Numerous effects to choose from Detailed tutorials provided by the official channel [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Aspect ratios are critical elements in photography, although you don't have to go that deep! Still, you are here as you understand the significance of using aspect ratios in your projects and thus are looking to find the best **picture ratio calculator**. ![aspect ratio](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-1.jpg) In this guide, we'll talk about everything you need to know about the **photo ratio calculator**. #### In this article 01 [What is Picture Size Ratio?](#Part 1) 02 [What is 1920x1080 in Ratio?](#Part 2) 03 [How Do You Find the Ratio of an Image?](#Part 3) 04 [1920x1080 Aspect Ratio and 16:9 Aspect Ratio Differences](#Part 4) 05 [The Resolution Calculator (image Ration Calculator)](#Part 5) 06 [A Practical Explanation about Aspect Ratios in Filmora](#Part 6) ## Part 1 What is Picture Size Ratio? As already mentioned, a picture size ratio refers to calculating or determining the Ratio of an image. And, it's accomplished by using a**picture ratio** **calculator**. So, for example, the picture size ratio could vary from 1:1, 4:3, 3:2, 16:9, etc. You can visualize this aspect ratio by allocating an image's width and height units. For example, a 6×4 inch image has a 3:2 aspect ratio, whereas a 1920×1080 pixel video includes a 16:9 aspect ratio. **Fact Check:** An aspect ratio does not contain attached units—instead, it shows how large the width compared to the height, meaning that an image measured in centimeters will have the same aspect ratio even if measured in inches. The relationship between its height and width decides the shape and Ratio instead of the image's actual size. Different aspect ratios consist of varying effects on the image you use. For example, an image set in a 1:1 ratio vs. a 5:4 ratio changes the composition and perception of the photo. **Types of picture size ratios** **1:1 Ratio** ![1:1 aspect ratio](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-2.jpg) A 1:1 ratio includes an image's width and height are square and thus equal. Some standard 1:1 ratios are an 8″x8″ photo, a 1080 x 1080 pixel image generally used for mobile screens, print photographs, and social media platforms. **3:2 Ratio** ![3:2 aspect ratio](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-3.jpg) The 3:2 Ratio is generally 35mm film and photography and is still extensively used for prints. Images framed at 6″x4″ or 1080×720 pixels set within this aspect ratio. **5:4 Ratio** ![5:4 Ratio](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-4.jpg) Last but not least, this Ratio is standard in photography and art prints and photography. In the following sections, let's uncover more about the photo aspect ratio and its related calculator! ## Part 2 What is 1920x1080 in Ratio? ![1920x1080 in Ratio](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-5.jpg) 1920 x 1080 is itself a 16:9 aspect ratio. By default, DSLRs, smartphones, and most modern camcorders record video at 1920 x 1080. ## Part 3 How Do You Find the Ratio of an Image? Before finding the image ratio, understand that there's a difference between image size and image ratio. Unlike aspect ratios, image size shows the actual width and height in pixels. Image size refers to the image dimensions. You can measure its dimensions in any unit, but you'll generally see pixels used for digital or web images and inches used for print images. It's essential to note that two different images containing the same aspect ratio may not have the exact dimensions of an image. For instance, the image has 1920×1080 pixels has 16:9 aspect ratios, and an image sized at 1280×720 pixels has a 16:9 aspect ratio. You can use this[tool](https://calculateaspectratio.com/)to measure the aspect ratio of images. Here, match either ratio width and ratio and height or pixel width and pixel height to find the aspect ratio in this**image size ratio calculator**. ## Part 4 1920x1080 Aspect Ratio and 16:9 Aspect Ratio Differences These are almost the same. The only difference is that of the pixels. If you cancel the numbers 1920 and 1080, they will automatically come as 16 and 9\. 1920 x 1080 is a 16:9 aspect ratio. ## Part 5 The Resolution Calculator (Image Ratio Calculator) To use a picture aspect ratio calculator, you need to understand the following. Understand the following five variables: **●** H1 Height of the initial image **●** W1 Width of the initial image **●** H2 Height of the final image **●** W2 Width of the final image **●** A percentage - the proportion of the initial image's ratio to the final image's ratio. The aspect ratio formulas that sync the quantities mentioned above for the ratio converter are: **H1/W1 = H2/W2,** **H1 \* A% = H2, and** **W1 \* A% = W2** You are not required to understand the details by heart; if the initial resolution is generally used, use the list to select the ideal ratio: **Proportions** **●** 4:3, **●** 3:2, **●** 16:9, **●** 16:10, **●** 1:1, square, in some social networks, **●** 85:1, **Pixels** **●** 2048:1536, iPad with Retina screen; **●** 1920:1080, HD TV, iPhone 6 plus; and **●** 800:600, traditional television & computer monitor standard. ## Part 6 A Practical Explanation about Aspect Ratios in Filmora Want to find the**photo aspect ratio calculator**quickly? Waste no more time calculating formulas and launch [Wondershare Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/) for the purpose. It is a robust video editing platform within which you can change the aspect ratios of images and videos and do the same with different methods. You can even do it under the editing panel as well. However, we won't suggest going much deep when you're looking to find the ideal**picture ratio calculator**. #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![filmora-video-editor](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) The most standard aspect ratios of videos are 4:3 and 16:9\. Despite these two, 9:16 and 1:1 get famous over social media platforms these days. As far as you may know, various media players help you to transform the aspect ratio in real-time when playback. Yet this modification is temporary. You are required to change the aspect ratio again next time you open them. But, changing the aspect ratios is pretty different than other media players. You need to launch the program and create a new project simply. But, before you do a new project, you can easily change it at the beginning panel. The Filmora assists you in changing the aspect ratio of the project after downloading. Hit the drop-down tab, and you will choose the options among 16:9, 4:3, 1:1, 9:16, and 21:9 aspect ratios. ![change aspect ratio filmora](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-6.jpg) ## Key Takeaways from This Episode **●** 1 –An overview of the **picture aspect ratio**. **●** 2 – Formula to measure the aspect ratio of an image. **●** 3 –Practical understanding of aspect ratios with WondershareFilmora **●** So here, we end our topic byusinga **picture ratio calculator**. We’ve described how to measure the image aspect ratio in detail. By now, you must have got how important the concept of aspect ratio is in photography or video editing. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Aspect ratios are critical elements in photography, although you don't have to go that deep! Still, you are here as you understand the significance of using aspect ratios in your projects and thus are looking to find the best **picture ratio calculator**. ![aspect ratio](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-1.jpg) In this guide, we'll talk about everything you need to know about the **photo ratio calculator**. #### In this article 01 [What is Picture Size Ratio?](#Part 1) 02 [What is 1920x1080 in Ratio?](#Part 2) 03 [How Do You Find the Ratio of an Image?](#Part 3) 04 [1920x1080 Aspect Ratio and 16:9 Aspect Ratio Differences](#Part 4) 05 [The Resolution Calculator (image Ration Calculator)](#Part 5) 06 [A Practical Explanation about Aspect Ratios in Filmora](#Part 6) ## Part 1 What is Picture Size Ratio? As already mentioned, a picture size ratio refers to calculating or determining the Ratio of an image. And, it's accomplished by using a**picture ratio** **calculator**. So, for example, the picture size ratio could vary from 1:1, 4:3, 3:2, 16:9, etc. You can visualize this aspect ratio by allocating an image's width and height units. For example, a 6×4 inch image has a 3:2 aspect ratio, whereas a 1920×1080 pixel video includes a 16:9 aspect ratio. **Fact Check:** An aspect ratio does not contain attached units—instead, it shows how large the width compared to the height, meaning that an image measured in centimeters will have the same aspect ratio even if measured in inches. The relationship between its height and width decides the shape and Ratio instead of the image's actual size. Different aspect ratios consist of varying effects on the image you use. For example, an image set in a 1:1 ratio vs. a 5:4 ratio changes the composition and perception of the photo. **Types of picture size ratios** **1:1 Ratio** ![1:1 aspect ratio](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-2.jpg) A 1:1 ratio includes an image's width and height are square and thus equal. Some standard 1:1 ratios are an 8″x8″ photo, a 1080 x 1080 pixel image generally used for mobile screens, print photographs, and social media platforms. **3:2 Ratio** ![3:2 aspect ratio](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-3.jpg) The 3:2 Ratio is generally 35mm film and photography and is still extensively used for prints. Images framed at 6″x4″ or 1080×720 pixels set within this aspect ratio. **5:4 Ratio** ![5:4 Ratio](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-4.jpg) Last but not least, this Ratio is standard in photography and art prints and photography. In the following sections, let's uncover more about the photo aspect ratio and its related calculator! ## Part 2 What is 1920x1080 in Ratio? ![1920x1080 in Ratio](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-5.jpg) 1920 x 1080 is itself a 16:9 aspect ratio. By default, DSLRs, smartphones, and most modern camcorders record video at 1920 x 1080. ## Part 3 How Do You Find the Ratio of an Image? Before finding the image ratio, understand that there's a difference between image size and image ratio. Unlike aspect ratios, image size shows the actual width and height in pixels. Image size refers to the image dimensions. You can measure its dimensions in any unit, but you'll generally see pixels used for digital or web images and inches used for print images. It's essential to note that two different images containing the same aspect ratio may not have the exact dimensions of an image. For instance, the image has 1920×1080 pixels has 16:9 aspect ratios, and an image sized at 1280×720 pixels has a 16:9 aspect ratio. You can use this[tool](https://calculateaspectratio.com/)to measure the aspect ratio of images. Here, match either ratio width and ratio and height or pixel width and pixel height to find the aspect ratio in this**image size ratio calculator**. ## Part 4 1920x1080 Aspect Ratio and 16:9 Aspect Ratio Differences These are almost the same. The only difference is that of the pixels. If you cancel the numbers 1920 and 1080, they will automatically come as 16 and 9\. 1920 x 1080 is a 16:9 aspect ratio. ## Part 5 The Resolution Calculator (Image Ratio Calculator) To use a picture aspect ratio calculator, you need to understand the following. Understand the following five variables: **●** H1 Height of the initial image **●** W1 Width of the initial image **●** H2 Height of the final image **●** W2 Width of the final image **●** A percentage - the proportion of the initial image's ratio to the final image's ratio. The aspect ratio formulas that sync the quantities mentioned above for the ratio converter are: **H1/W1 = H2/W2,** **H1 \* A% = H2, and** **W1 \* A% = W2** You are not required to understand the details by heart; if the initial resolution is generally used, use the list to select the ideal ratio: **Proportions** **●** 4:3, **●** 3:2, **●** 16:9, **●** 16:10, **●** 1:1, square, in some social networks, **●** 85:1, **Pixels** **●** 2048:1536, iPad with Retina screen; **●** 1920:1080, HD TV, iPhone 6 plus; and **●** 800:600, traditional television & computer monitor standard. ## Part 6 A Practical Explanation about Aspect Ratios in Filmora Want to find the**photo aspect ratio calculator**quickly? Waste no more time calculating formulas and launch [Wondershare Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/) for the purpose. It is a robust video editing platform within which you can change the aspect ratios of images and videos and do the same with different methods. You can even do it under the editing panel as well. However, we won't suggest going much deep when you're looking to find the ideal**picture ratio calculator**. #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![filmora-video-editor](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) The most standard aspect ratios of videos are 4:3 and 16:9\. Despite these two, 9:16 and 1:1 get famous over social media platforms these days. As far as you may know, various media players help you to transform the aspect ratio in real-time when playback. Yet this modification is temporary. You are required to change the aspect ratio again next time you open them. But, changing the aspect ratios is pretty different than other media players. You need to launch the program and create a new project simply. But, before you do a new project, you can easily change it at the beginning panel. The Filmora assists you in changing the aspect ratio of the project after downloading. Hit the drop-down tab, and you will choose the options among 16:9, 4:3, 1:1, 9:16, and 21:9 aspect ratios. ![change aspect ratio filmora](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-6.jpg) ## Key Takeaways from This Episode **●** 1 –An overview of the **picture aspect ratio**. **●** 2 – Formula to measure the aspect ratio of an image. **●** 3 –Practical understanding of aspect ratios with WondershareFilmora **●** So here, we end our topic byusinga **picture ratio calculator**. We’ve described how to measure the image aspect ratio in detail. By now, you must have got how important the concept of aspect ratio is in photography or video editing. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Aspect ratios are critical elements in photography, although you don't have to go that deep! Still, you are here as you understand the significance of using aspect ratios in your projects and thus are looking to find the best **picture ratio calculator**. ![aspect ratio](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-1.jpg) In this guide, we'll talk about everything you need to know about the **photo ratio calculator**. #### In this article 01 [What is Picture Size Ratio?](#Part 1) 02 [What is 1920x1080 in Ratio?](#Part 2) 03 [How Do You Find the Ratio of an Image?](#Part 3) 04 [1920x1080 Aspect Ratio and 16:9 Aspect Ratio Differences](#Part 4) 05 [The Resolution Calculator (image Ration Calculator)](#Part 5) 06 [A Practical Explanation about Aspect Ratios in Filmora](#Part 6) ## Part 1 What is Picture Size Ratio? As already mentioned, a picture size ratio refers to calculating or determining the Ratio of an image. And, it's accomplished by using a**picture ratio** **calculator**. So, for example, the picture size ratio could vary from 1:1, 4:3, 3:2, 16:9, etc. You can visualize this aspect ratio by allocating an image's width and height units. For example, a 6×4 inch image has a 3:2 aspect ratio, whereas a 1920×1080 pixel video includes a 16:9 aspect ratio. **Fact Check:** An aspect ratio does not contain attached units—instead, it shows how large the width compared to the height, meaning that an image measured in centimeters will have the same aspect ratio even if measured in inches. The relationship between its height and width decides the shape and Ratio instead of the image's actual size. Different aspect ratios consist of varying effects on the image you use. For example, an image set in a 1:1 ratio vs. a 5:4 ratio changes the composition and perception of the photo. **Types of picture size ratios** **1:1 Ratio** ![1:1 aspect ratio](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-2.jpg) A 1:1 ratio includes an image's width and height are square and thus equal. Some standard 1:1 ratios are an 8″x8″ photo, a 1080 x 1080 pixel image generally used for mobile screens, print photographs, and social media platforms. **3:2 Ratio** ![3:2 aspect ratio](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-3.jpg) The 3:2 Ratio is generally 35mm film and photography and is still extensively used for prints. Images framed at 6″x4″ or 1080×720 pixels set within this aspect ratio. **5:4 Ratio** ![5:4 Ratio](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-4.jpg) Last but not least, this Ratio is standard in photography and art prints and photography. In the following sections, let's uncover more about the photo aspect ratio and its related calculator! ## Part 2 What is 1920x1080 in Ratio? ![1920x1080 in Ratio](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-5.jpg) 1920 x 1080 is itself a 16:9 aspect ratio. By default, DSLRs, smartphones, and most modern camcorders record video at 1920 x 1080. ## Part 3 How Do You Find the Ratio of an Image? Before finding the image ratio, understand that there's a difference between image size and image ratio. Unlike aspect ratios, image size shows the actual width and height in pixels. Image size refers to the image dimensions. You can measure its dimensions in any unit, but you'll generally see pixels used for digital or web images and inches used for print images. It's essential to note that two different images containing the same aspect ratio may not have the exact dimensions of an image. For instance, the image has 1920×1080 pixels has 16:9 aspect ratios, and an image sized at 1280×720 pixels has a 16:9 aspect ratio. You can use this[tool](https://calculateaspectratio.com/)to measure the aspect ratio of images. Here, match either ratio width and ratio and height or pixel width and pixel height to find the aspect ratio in this**image size ratio calculator**. ## Part 4 1920x1080 Aspect Ratio and 16:9 Aspect Ratio Differences These are almost the same. The only difference is that of the pixels. If you cancel the numbers 1920 and 1080, they will automatically come as 16 and 9\. 1920 x 1080 is a 16:9 aspect ratio. ## Part 5 The Resolution Calculator (Image Ratio Calculator) To use a picture aspect ratio calculator, you need to understand the following. Understand the following five variables: **●** H1 Height of the initial image **●** W1 Width of the initial image **●** H2 Height of the final image **●** W2 Width of the final image **●** A percentage - the proportion of the initial image's ratio to the final image's ratio. The aspect ratio formulas that sync the quantities mentioned above for the ratio converter are: **H1/W1 = H2/W2,** **H1 \* A% = H2, and** **W1 \* A% = W2** You are not required to understand the details by heart; if the initial resolution is generally used, use the list to select the ideal ratio: **Proportions** **●** 4:3, **●** 3:2, **●** 16:9, **●** 16:10, **●** 1:1, square, in some social networks, **●** 85:1, **Pixels** **●** 2048:1536, iPad with Retina screen; **●** 1920:1080, HD TV, iPhone 6 plus; and **●** 800:600, traditional television & computer monitor standard. ## Part 6 A Practical Explanation about Aspect Ratios in Filmora Want to find the**photo aspect ratio calculator**quickly? Waste no more time calculating formulas and launch [Wondershare Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/) for the purpose. It is a robust video editing platform within which you can change the aspect ratios of images and videos and do the same with different methods. You can even do it under the editing panel as well. However, we won't suggest going much deep when you're looking to find the ideal**picture ratio calculator**. #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![filmora-video-editor](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) The most standard aspect ratios of videos are 4:3 and 16:9\. Despite these two, 9:16 and 1:1 get famous over social media platforms these days. As far as you may know, various media players help you to transform the aspect ratio in real-time when playback. Yet this modification is temporary. You are required to change the aspect ratio again next time you open them. But, changing the aspect ratios is pretty different than other media players. You need to launch the program and create a new project simply. But, before you do a new project, you can easily change it at the beginning panel. The Filmora assists you in changing the aspect ratio of the project after downloading. Hit the drop-down tab, and you will choose the options among 16:9, 4:3, 1:1, 9:16, and 21:9 aspect ratios. ![change aspect ratio filmora](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-6.jpg) ## Key Takeaways from This Episode **●** 1 –An overview of the **picture aspect ratio**. **●** 2 – Formula to measure the aspect ratio of an image. **●** 3 –Practical understanding of aspect ratios with WondershareFilmora **●** So here, we end our topic byusinga **picture ratio calculator**. We’ve described how to measure the image aspect ratio in detail. By now, you must have got how important the concept of aspect ratio is in photography or video editing. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Aspect ratios are critical elements in photography, although you don't have to go that deep! Still, you are here as you understand the significance of using aspect ratios in your projects and thus are looking to find the best **picture ratio calculator**. ![aspect ratio](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-1.jpg) In this guide, we'll talk about everything you need to know about the **photo ratio calculator**. #### In this article 01 [What is Picture Size Ratio?](#Part 1) 02 [What is 1920x1080 in Ratio?](#Part 2) 03 [How Do You Find the Ratio of an Image?](#Part 3) 04 [1920x1080 Aspect Ratio and 16:9 Aspect Ratio Differences](#Part 4) 05 [The Resolution Calculator (image Ration Calculator)](#Part 5) 06 [A Practical Explanation about Aspect Ratios in Filmora](#Part 6) ## Part 1 What is Picture Size Ratio? As already mentioned, a picture size ratio refers to calculating or determining the Ratio of an image. And, it's accomplished by using a**picture ratio** **calculator**. So, for example, the picture size ratio could vary from 1:1, 4:3, 3:2, 16:9, etc. You can visualize this aspect ratio by allocating an image's width and height units. For example, a 6×4 inch image has a 3:2 aspect ratio, whereas a 1920×1080 pixel video includes a 16:9 aspect ratio. **Fact Check:** An aspect ratio does not contain attached units—instead, it shows how large the width compared to the height, meaning that an image measured in centimeters will have the same aspect ratio even if measured in inches. The relationship between its height and width decides the shape and Ratio instead of the image's actual size. Different aspect ratios consist of varying effects on the image you use. For example, an image set in a 1:1 ratio vs. a 5:4 ratio changes the composition and perception of the photo. **Types of picture size ratios** **1:1 Ratio** ![1:1 aspect ratio](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-2.jpg) A 1:1 ratio includes an image's width and height are square and thus equal. Some standard 1:1 ratios are an 8″x8″ photo, a 1080 x 1080 pixel image generally used for mobile screens, print photographs, and social media platforms. **3:2 Ratio** ![3:2 aspect ratio](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-3.jpg) The 3:2 Ratio is generally 35mm film and photography and is still extensively used for prints. Images framed at 6″x4″ or 1080×720 pixels set within this aspect ratio. **5:4 Ratio** ![5:4 Ratio](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-4.jpg) Last but not least, this Ratio is standard in photography and art prints and photography. In the following sections, let's uncover more about the photo aspect ratio and its related calculator! ## Part 2 What is 1920x1080 in Ratio? ![1920x1080 in Ratio](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-5.jpg) 1920 x 1080 is itself a 16:9 aspect ratio. By default, DSLRs, smartphones, and most modern camcorders record video at 1920 x 1080. ## Part 3 How Do You Find the Ratio of an Image? Before finding the image ratio, understand that there's a difference between image size and image ratio. Unlike aspect ratios, image size shows the actual width and height in pixels. Image size refers to the image dimensions. You can measure its dimensions in any unit, but you'll generally see pixels used for digital or web images and inches used for print images. It's essential to note that two different images containing the same aspect ratio may not have the exact dimensions of an image. For instance, the image has 1920×1080 pixels has 16:9 aspect ratios, and an image sized at 1280×720 pixels has a 16:9 aspect ratio. You can use this[tool](https://calculateaspectratio.com/)to measure the aspect ratio of images. Here, match either ratio width and ratio and height or pixel width and pixel height to find the aspect ratio in this**image size ratio calculator**. ## Part 4 1920x1080 Aspect Ratio and 16:9 Aspect Ratio Differences These are almost the same. The only difference is that of the pixels. If you cancel the numbers 1920 and 1080, they will automatically come as 16 and 9\. 1920 x 1080 is a 16:9 aspect ratio. ## Part 5 The Resolution Calculator (Image Ratio Calculator) To use a picture aspect ratio calculator, you need to understand the following. Understand the following five variables: **●** H1 Height of the initial image **●** W1 Width of the initial image **●** H2 Height of the final image **●** W2 Width of the final image **●** A percentage - the proportion of the initial image's ratio to the final image's ratio. The aspect ratio formulas that sync the quantities mentioned above for the ratio converter are: **H1/W1 = H2/W2,** **H1 \* A% = H2, and** **W1 \* A% = W2** You are not required to understand the details by heart; if the initial resolution is generally used, use the list to select the ideal ratio: **Proportions** **●** 4:3, **●** 3:2, **●** 16:9, **●** 16:10, **●** 1:1, square, in some social networks, **●** 85:1, **Pixels** **●** 2048:1536, iPad with Retina screen; **●** 1920:1080, HD TV, iPhone 6 plus; and **●** 800:600, traditional television & computer monitor standard. ## Part 6 A Practical Explanation about Aspect Ratios in Filmora Want to find the**photo aspect ratio calculator**quickly? Waste no more time calculating formulas and launch [Wondershare Filmora Video Editor](https://tools.techidaily.com/wondershare/filmora/download/) for the purpose. It is a robust video editing platform within which you can change the aspect ratios of images and videos and do the same with different methods. You can even do it under the editing panel as well. However, we won't suggest going much deep when you're looking to find the ideal**picture ratio calculator**. #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![filmora-video-editor](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) The most standard aspect ratios of videos are 4:3 and 16:9\. Despite these two, 9:16 and 1:1 get famous over social media platforms these days. As far as you may know, various media players help you to transform the aspect ratio in real-time when playback. Yet this modification is temporary. You are required to change the aspect ratio again next time you open them. But, changing the aspect ratios is pretty different than other media players. You need to launch the program and create a new project simply. But, before you do a new project, you can easily change it at the beginning panel. The Filmora assists you in changing the aspect ratio of the project after downloading. Hit the drop-down tab, and you will choose the options among 16:9, 4:3, 1:1, 9:16, and 21:9 aspect ratios. ![change aspect ratio filmora](https://images.wondershare.com/filmora/article-images/2021/how-do-you-find-the-picture-ratio-calculator-6.jpg) ## Key Takeaways from This Episode **●** 1 –An overview of the **picture aspect ratio**. **●** 2 – Formula to measure the aspect ratio of an image. **●** 3 –Practical understanding of aspect ratios with WondershareFilmora **●** So here, we end our topic byusinga **picture ratio calculator**. We’ve described how to measure the image aspect ratio in detail. By now, you must have got how important the concept of aspect ratio is in photography or video editing. <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> ## There We Introduce You 3 Simple Options for Recording Video Games with Ease # 3 Simple Options for Recording Video Games ![author avatar](https://lh5.googleusercontent.com/-AIMmjowaFs4/AAAAAAAAAAI/AAAAAAAAABc/Y5UmwDaI7HU/s250-c-k/photo.jpg) ##### Liza Brown Mar 27, 2024• Proven solutions Whether Middle Earth: Shadow of Mordor, Titanfall or Destiny is your favorite video game or you prefer more nostalgic style game play like Mario Kart 8 or NBA 2K15, chances are you want to record something fantastic that happens (or that you do!) within the game. YouTube is filled with videos of gamers killing the newest games or reviewing new editions on brand new platforms. How do they make those awesome videos and capture all of their great plays? Simple—when you know which programs to use to take advantage of some of the latest software tools that can record your gaming screen effortlessly as you play! [Wondershare Filmstock Gaming Video Editing Skils](https://images.wondershare.com/filmora/article-images/learn-gaming-video-editing-skills-banner.png)](https://filmstock.wondershare.com/creative-theme-game?source%5Fchannel=seo%5Farticle&spm=rs.filmora%5Fweb) ## Record Video Games with Fraps [Fraps](http://www.fraps.com/) is the old standby that is easy to use, even for recording newbies, and remains the most popular choice for recording video gameplay. Aside from its simple user interface, it can display game benchmarks and easily make adjustments for framerates and sizing. Fraps was designed specifically to run while your games are playing and record in high quality, and it does a great job at that dedicated task. While some users complain that the size of Fraps files are huge, you can use a different application to compress the files for uploading and sharing. ![wondershare video editor](https://images.wondershare.com/images/multimedia/video-editor/fraps.jpg) ## Use liteCam for game recording The [liteCam game recording software](https://www.litecam.net/en/) can capture your game at up to 60 fps, and it will record OpenGL and DirectX games that other software cannot. While you simply choose from preset keys to set up your recording, which makes it easier to use, there is no option to capture still shots which some people like to have. Even though it does not have quite as many extra settings and tools as a lot of other video game recording software, it does produce good-quality recordings that many gamers appreciate for their use. ![wondershare video editor](https://images.wondershare.com/images/multimedia/video-editor/litecam.jpg) ## Use Wondershare Filmora for game capturing [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) is a multipurpose video software tool with a built-in webcam recorder which allows you to easily capture with your webcam. Audio recording is also made easy, perfect for game players who want to showcase your favorite games with your followers. It offers built-in converters and video editor supporting converting and editing many different video formats shot either with your camcorder or iPhone or Android. Wondershare Filmora is different from some of the others on the market as it not only allows video capture but also provides a handful of video editing, video uploading choices, and it works with multiple devices. This program has a high speed processor and lots of varied settings, and a simple and user-friendly interface, along with exceptional video editing tools to make your recording fun and easy. You can download a 30-day free trial here to check out: [![Download Filmora9 Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora9 Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) Are you addicted to Diablo 3: Ultimate Evil Edition? Show off your mad skills saving the world of Sanctuary with an amazing recorded video from your game. The best tools allow you to easily upload your gameplay videos wherever you'd like to share. ![author avatar](https://lh5.googleusercontent.com/-AIMmjowaFs4/AAAAAAAAAAI/AAAAAAAAABc/Y5UmwDaI7HU/s250-c-k/photo.jpg) Liza Brown Liza Brown is a writer and a lover of all things video. Follow @Liza Brown ##### Liza Brown Mar 27, 2024• Proven solutions Whether Middle Earth: Shadow of Mordor, Titanfall or Destiny is your favorite video game or you prefer more nostalgic style game play like Mario Kart 8 or NBA 2K15, chances are you want to record something fantastic that happens (or that you do!) within the game. YouTube is filled with videos of gamers killing the newest games or reviewing new editions on brand new platforms. How do they make those awesome videos and capture all of their great plays? Simple—when you know which programs to use to take advantage of some of the latest software tools that can record your gaming screen effortlessly as you play! [Wondershare Filmstock Gaming Video Editing Skils](https://images.wondershare.com/filmora/article-images/learn-gaming-video-editing-skills-banner.png)](https://filmstock.wondershare.com/creative-theme-game?source%5Fchannel=seo%5Farticle&spm=rs.filmora%5Fweb) ## Record Video Games with Fraps [Fraps](http://www.fraps.com/) is the old standby that is easy to use, even for recording newbies, and remains the most popular choice for recording video gameplay. Aside from its simple user interface, it can display game benchmarks and easily make adjustments for framerates and sizing. Fraps was designed specifically to run while your games are playing and record in high quality, and it does a great job at that dedicated task. While some users complain that the size of Fraps files are huge, you can use a different application to compress the files for uploading and sharing. ![wondershare video editor](https://images.wondershare.com/images/multimedia/video-editor/fraps.jpg) ## Use liteCam for game recording The [liteCam game recording software](https://www.litecam.net/en/) can capture your game at up to 60 fps, and it will record OpenGL and DirectX games that other software cannot. While you simply choose from preset keys to set up your recording, which makes it easier to use, there is no option to capture still shots which some people like to have. Even though it does not have quite as many extra settings and tools as a lot of other video game recording software, it does produce good-quality recordings that many gamers appreciate for their use. ![wondershare video editor](https://images.wondershare.com/images/multimedia/video-editor/litecam.jpg) ## Use Wondershare Filmora for game capturing [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) is a multipurpose video software tool with a built-in webcam recorder which allows you to easily capture with your webcam. Audio recording is also made easy, perfect for game players who want to showcase your favorite games with your followers. It offers built-in converters and video editor supporting converting and editing many different video formats shot either with your camcorder or iPhone or Android. Wondershare Filmora is different from some of the others on the market as it not only allows video capture but also provides a handful of video editing, video uploading choices, and it works with multiple devices. This program has a high speed processor and lots of varied settings, and a simple and user-friendly interface, along with exceptional video editing tools to make your recording fun and easy. You can download a 30-day free trial here to check out: [![Download Filmora9 Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora9 Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) Are you addicted to Diablo 3: Ultimate Evil Edition? Show off your mad skills saving the world of Sanctuary with an amazing recorded video from your game. The best tools allow you to easily upload your gameplay videos wherever you'd like to share. ![author avatar](https://lh5.googleusercontent.com/-AIMmjowaFs4/AAAAAAAAAAI/AAAAAAAAABc/Y5UmwDaI7HU/s250-c-k/photo.jpg) Liza Brown Liza Brown is a writer and a lover of all things video. Follow @Liza Brown ##### Liza Brown Mar 27, 2024• Proven solutions Whether Middle Earth: Shadow of Mordor, Titanfall or Destiny is your favorite video game or you prefer more nostalgic style game play like Mario Kart 8 or NBA 2K15, chances are you want to record something fantastic that happens (or that you do!) within the game. YouTube is filled with videos of gamers killing the newest games or reviewing new editions on brand new platforms. How do they make those awesome videos and capture all of their great plays? Simple—when you know which programs to use to take advantage of some of the latest software tools that can record your gaming screen effortlessly as you play! [Wondershare Filmstock Gaming Video Editing Skils](https://images.wondershare.com/filmora/article-images/learn-gaming-video-editing-skills-banner.png)](https://filmstock.wondershare.com/creative-theme-game?source%5Fchannel=seo%5Farticle&spm=rs.filmora%5Fweb) ## Record Video Games with Fraps [Fraps](http://www.fraps.com/) is the old standby that is easy to use, even for recording newbies, and remains the most popular choice for recording video gameplay. Aside from its simple user interface, it can display game benchmarks and easily make adjustments for framerates and sizing. Fraps was designed specifically to run while your games are playing and record in high quality, and it does a great job at that dedicated task. While some users complain that the size of Fraps files are huge, you can use a different application to compress the files for uploading and sharing. ![wondershare video editor](https://images.wondershare.com/images/multimedia/video-editor/fraps.jpg) ## Use liteCam for game recording The [liteCam game recording software](https://www.litecam.net/en/) can capture your game at up to 60 fps, and it will record OpenGL and DirectX games that other software cannot. While you simply choose from preset keys to set up your recording, which makes it easier to use, there is no option to capture still shots which some people like to have. Even though it does not have quite as many extra settings and tools as a lot of other video game recording software, it does produce good-quality recordings that many gamers appreciate for their use. ![wondershare video editor](https://images.wondershare.com/images/multimedia/video-editor/litecam.jpg) ## Use Wondershare Filmora for game capturing [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) is a multipurpose video software tool with a built-in webcam recorder which allows you to easily capture with your webcam. Audio recording is also made easy, perfect for game players who want to showcase your favorite games with your followers. It offers built-in converters and video editor supporting converting and editing many different video formats shot either with your camcorder or iPhone or Android. Wondershare Filmora is different from some of the others on the market as it not only allows video capture but also provides a handful of video editing, video uploading choices, and it works with multiple devices. This program has a high speed processor and lots of varied settings, and a simple and user-friendly interface, along with exceptional video editing tools to make your recording fun and easy. You can download a 30-day free trial here to check out: [![Download Filmora9 Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora9 Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) Are you addicted to Diablo 3: Ultimate Evil Edition? Show off your mad skills saving the world of Sanctuary with an amazing recorded video from your game. The best tools allow you to easily upload your gameplay videos wherever you'd like to share. ![author avatar](https://lh5.googleusercontent.com/-AIMmjowaFs4/AAAAAAAAAAI/AAAAAAAAABc/Y5UmwDaI7HU/s250-c-k/photo.jpg) Liza Brown Liza Brown is a writer and a lover of all things video. Follow @Liza Brown ##### Liza Brown Mar 27, 2024• Proven solutions Whether Middle Earth: Shadow of Mordor, Titanfall or Destiny is your favorite video game or you prefer more nostalgic style game play like Mario Kart 8 or NBA 2K15, chances are you want to record something fantastic that happens (or that you do!) within the game. YouTube is filled with videos of gamers killing the newest games or reviewing new editions on brand new platforms. How do they make those awesome videos and capture all of their great plays? Simple—when you know which programs to use to take advantage of some of the latest software tools that can record your gaming screen effortlessly as you play! [Wondershare Filmstock Gaming Video Editing Skils](https://images.wondershare.com/filmora/article-images/learn-gaming-video-editing-skills-banner.png)](https://filmstock.wondershare.com/creative-theme-game?source%5Fchannel=seo%5Farticle&spm=rs.filmora%5Fweb) ## Record Video Games with Fraps [Fraps](http://www.fraps.com/) is the old standby that is easy to use, even for recording newbies, and remains the most popular choice for recording video gameplay. Aside from its simple user interface, it can display game benchmarks and easily make adjustments for framerates and sizing. Fraps was designed specifically to run while your games are playing and record in high quality, and it does a great job at that dedicated task. While some users complain that the size of Fraps files are huge, you can use a different application to compress the files for uploading and sharing. ![wondershare video editor](https://images.wondershare.com/images/multimedia/video-editor/fraps.jpg) ## Use liteCam for game recording The [liteCam game recording software](https://www.litecam.net/en/) can capture your game at up to 60 fps, and it will record OpenGL and DirectX games that other software cannot. While you simply choose from preset keys to set up your recording, which makes it easier to use, there is no option to capture still shots which some people like to have. Even though it does not have quite as many extra settings and tools as a lot of other video game recording software, it does produce good-quality recordings that many gamers appreciate for their use. ![wondershare video editor](https://images.wondershare.com/images/multimedia/video-editor/litecam.jpg) ## Use Wondershare Filmora for game capturing [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/) is a multipurpose video software tool with a built-in webcam recorder which allows you to easily capture with your webcam. Audio recording is also made easy, perfect for game players who want to showcase your favorite games with your followers. It offers built-in converters and video editor supporting converting and editing many different video formats shot either with your camcorder or iPhone or Android. Wondershare Filmora is different from some of the others on the market as it not only allows video capture but also provides a handful of video editing, video uploading choices, and it works with multiple devices. This program has a high speed processor and lots of varied settings, and a simple and user-friendly interface, along with exceptional video editing tools to make your recording fun and easy. You can download a 30-day free trial here to check out: [![Download Filmora9 Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Filmora9 Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) Are you addicted to Diablo 3: Ultimate Evil Edition? Show off your mad skills saving the world of Sanctuary with an amazing recorded video from your game. The best tools allow you to easily upload your gameplay videos wherever you'd like to share. ![author avatar](https://lh5.googleusercontent.com/-AIMmjowaFs4/AAAAAAAAAAI/AAAAAAAAABc/Y5UmwDaI7HU/s250-c-k/photo.jpg) Liza Brown Liza Brown is a writer and a lover of all things video. Follow @Liza Brown <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> ## Videopad Video Editor Review and Buying Recommendation There are a variety of video editors available for home video editors, but VideoPad editor offers the basic tools needed by home movie makers. In addition to being easy to learn and use, it has many additional features that don't interfere with your work but are there to assist if you need them. ![videopad-interface](https://images.wondershare.com/filmora/article-images/videopad-interface.jpg) There are multiple versions of this multiplatform video editor at different price points, in addition to a free version. How can you go wrong? This is one of the reasons why VideoPad is one of the best free video editing software programs. VideoPad Video Editor is compatible with both Mac and Windows computers and supports a number of video import and export options. This nch video editor comes with a free basic plan where you don't have to pay anything, so you can try to see how it works. In this article, we will do a quick review of this video editing software so that you have a better understanding of its features. ## **Features of VideoPad** The features list of videopad video editor is as follows: * You can share videos with your family and friends * Facebook and YouTube videos can be uploaded directly * Multiple resolutions for exporting movies * Burn DVDs and Blu-rays * You can save the file to your PSP, iPod, iPhone, or 3GP mobile phone * Visual effects and video transitions * Effects models for visual effects * Editing 3D videos * 2D to 3D stereoscopic conversion * 360 video overlays and texts * Optimization of videos * Reducing camera shake * Sequences can be enhanced with photos and digital images * Tools for audio production * Mix music and import it * A library of sound effects * Any camera can be used to create videos ### **Ease of use and interface** With VideoPad's easy-to-use interface and well-organized conventions, movie makers of any skill level can become familiar with its basics in no time at all. You will become fluent in no time at all in opening and closing windows, stringing clips together, and adding narration, transitions, and text to create a powerful visual presentation. Adding video, audio, and still, photo assets to the files pane will put them on the timeline and allow you to assemble your story. Videos and still images are organized into bins by the app, ensuring they don't get confused on the timeline, which speeds up the workflow, especially for newcomers. The app uses menus and can be dragged and dropped, so a single objective can be accomplished in different ways. You can control all functions from within the application frame, or dockable panels can be used to get a closer look at what needs to be done. A permanent reorganization of the workspace would be appreciated. ### **Videopad Video Editing Features** VideoPad is the perfect balance between too much and not enough. Although there are not many options, it offers a reasonable selection of transitions for moving between clips and images, as well as a selection of filters to give them a unique look. In addition to editing 360-degree video, video stabilization is another helpful feature. Each filter can be previewed with a click before applying it, and You can combine several to create a custom effect or template for reuse. You can also adjust their length via menus. A video can be enhanced with transitions, visual effects, overlays, and text using VideoPad. Also included are some basic audio tools and a library of sound effects and atmospheric background music. There are a number of features that allow you to optimize videos, including color correction, adding digital images, adding subtitles, and adjusting the speed of playback. With its video stabilization feature, you can reduce camera shake, and the high-end version supports special effect plugins, but only for Windows. ### **Videopad Audio Editing Features** VideoPad offers a limited set of audio tools, but it does allow you to mix multiple audio tracks, music, and narration to create a movie soundtrack. A video clip's audio can be faded, mixed, and adjusted for volume, but if you want to go further, you'll need an external mixer or editor. From VideoPad's main menu, you can download NCH's own WavePad. While the text-to-speech features always sounded false, you can record narration directly within the program. There is a great idea in having voice recognition for subtitles, which is only available on the Windows version. However, the implementation falls short of expectations. Although the video was clearly spoken in a quiet environment, it automatically failed to translate into subtitles. ### **Videopad Content Sharing features** Video creators who publish to YouTube or other social media platforms can use the software because it allows them to share videos directly to platforms such as Dropbox, Flickr, Google Drive, and Vimeo. To avoid unnecessary data sharing, you can save videos to your desktop and upload them yourself. ### **Is VideoPad worth buying?** Although the VideoPad video editor free version is somewhat limited, it functions as a free trial to see if you like it enough to upgrade. Apps that are easy to use and have a simple interface can help convert a free user to a paying customer, and VideoPad has a strong claim to your money thanks to its simplicity and light hardware requirements. ## **Our Recommendation** As a beginner, you may be looking to use Videopad free, but when it comes to features, it just falls short compared to modern video editors. So, we recommend you use our Filmora X video editor. Filmora video editor is free to download, so you can try out all the features without paying a penny. However free version will have a watermark when you export the video. You will have to purchase a subscription to get rid of the watermark. If you compare the features and user-friendliness of both these video editors, then Filmora definitely stands out by all means. In addition to its feature richness, it also has a user-friendly interface that beginners can easily adapt to. So, don't waste your time and give it a try right now. #### Wondershare Filmora Get started easily with Filmora's powerful engine, intuitive interface, and thousands of effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![](https://neveragain.allstatics.com/2019/assets/image/box/filmora-9.png) There are multiple versions of this multiplatform video editor at different price points, in addition to a free version. How can you go wrong? This is one of the reasons why VideoPad is one of the best free video editing software programs. VideoPad Video Editor is compatible with both Mac and Windows computers and supports a number of video import and export options. This nch video editor comes with a free basic plan where you don't have to pay anything, so you can try to see how it works. In this article, we will do a quick review of this video editing software so that you have a better understanding of its features. ## **Features of VideoPad** The features list of videopad video editor is as follows: * You can share videos with your family and friends * Facebook and YouTube videos can be uploaded directly * Multiple resolutions for exporting movies * Burn DVDs and Blu-rays * You can save the file to your PSP, iPod, iPhone, or 3GP mobile phone * Visual effects and video transitions * Effects models for visual effects * Editing 3D videos * 2D to 3D stereoscopic conversion * 360 video overlays and texts * Optimization of videos * Reducing camera shake * Sequences can be enhanced with photos and digital images * Tools for audio production * Mix music and import it * A library of sound effects * Any camera can be used to create videos ### **Ease of use and interface** With VideoPad's easy-to-use interface and well-organized conventions, movie makers of any skill level can become familiar with its basics in no time at all. You will become fluent in no time at all in opening and closing windows, stringing clips together, and adding narration, transitions, and text to create a powerful visual presentation. Adding video, audio, and still, photo assets to the files pane will put them on the timeline and allow you to assemble your story. Videos and still images are organized into bins by the app, ensuring they don't get confused on the timeline, which speeds up the workflow, especially for newcomers. The app uses menus and can be dragged and dropped, so a single objective can be accomplished in different ways. You can control all functions from within the application frame, or dockable panels can be used to get a closer look at what needs to be done. A permanent reorganization of the workspace would be appreciated. ### **Videopad Video Editing Features** VideoPad is the perfect balance between too much and not enough. Although there are not many options, it offers a reasonable selection of transitions for moving between clips and images, as well as a selection of filters to give them a unique look. In addition to editing 360-degree video, video stabilization is another helpful feature. Each filter can be previewed with a click before applying it, and You can combine several to create a custom effect or template for reuse. You can also adjust their length via menus. A video can be enhanced with transitions, visual effects, overlays, and text using VideoPad. Also included are some basic audio tools and a library of sound effects and atmospheric background music. There are a number of features that allow you to optimize videos, including color correction, adding digital images, adding subtitles, and adjusting the speed of playback. With its video stabilization feature, you can reduce camera shake, and the high-end version supports special effect plugins, but only for Windows. ### **Videopad Audio Editing Features** VideoPad offers a limited set of audio tools, but it does allow you to mix multiple audio tracks, music, and narration to create a movie soundtrack. A video clip's audio can be faded, mixed, and adjusted for volume, but if you want to go further, you'll need an external mixer or editor. From VideoPad's main menu, you can download NCH's own WavePad. While the text-to-speech features always sounded false, you can record narration directly within the program. There is a great idea in having voice recognition for subtitles, which is only available on the Windows version. However, the implementation falls short of expectations. Although the video was clearly spoken in a quiet environment, it automatically failed to translate into subtitles. ### **Videopad Content Sharing features** Video creators who publish to YouTube or other social media platforms can use the software because it allows them to share videos directly to platforms such as Dropbox, Flickr, Google Drive, and Vimeo. To avoid unnecessary data sharing, you can save videos to your desktop and upload them yourself. ### **Is VideoPad worth buying?** Although the VideoPad video editor free version is somewhat limited, it functions as a free trial to see if you like it enough to upgrade. Apps that are easy to use and have a simple interface can help convert a free user to a paying customer, and VideoPad has a strong claim to your money thanks to its simplicity and light hardware requirements. ## **Our Recommendation** As a beginner, you may be looking to use Videopad free, but when it comes to features, it just falls short compared to modern video editors. So, we recommend you use our Filmora X video editor. Filmora video editor is free to download, so you can try out all the features without paying a penny. However free version will have a watermark when you export the video. You will have to purchase a subscription to get rid of the watermark. If you compare the features and user-friendliness of both these video editors, then Filmora definitely stands out by all means. In addition to its feature richness, it also has a user-friendly interface that beginners can easily adapt to. So, don't waste your time and give it a try right now. #### Wondershare Filmora Get started easily with Filmora's powerful engine, intuitive interface, and thousands of effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![](https://neveragain.allstatics.com/2019/assets/image/box/filmora-9.png) There are multiple versions of this multiplatform video editor at different price points, in addition to a free version. How can you go wrong? This is one of the reasons why VideoPad is one of the best free video editing software programs. VideoPad Video Editor is compatible with both Mac and Windows computers and supports a number of video import and export options. This nch video editor comes with a free basic plan where you don't have to pay anything, so you can try to see how it works. In this article, we will do a quick review of this video editing software so that you have a better understanding of its features. ## **Features of VideoPad** The features list of videopad video editor is as follows: * You can share videos with your family and friends * Facebook and YouTube videos can be uploaded directly * Multiple resolutions for exporting movies * Burn DVDs and Blu-rays * You can save the file to your PSP, iPod, iPhone, or 3GP mobile phone * Visual effects and video transitions * Effects models for visual effects * Editing 3D videos * 2D to 3D stereoscopic conversion * 360 video overlays and texts * Optimization of videos * Reducing camera shake * Sequences can be enhanced with photos and digital images * Tools for audio production * Mix music and import it * A library of sound effects * Any camera can be used to create videos ### **Ease of use and interface** With VideoPad's easy-to-use interface and well-organized conventions, movie makers of any skill level can become familiar with its basics in no time at all. You will become fluent in no time at all in opening and closing windows, stringing clips together, and adding narration, transitions, and text to create a powerful visual presentation. Adding video, audio, and still, photo assets to the files pane will put them on the timeline and allow you to assemble your story. Videos and still images are organized into bins by the app, ensuring they don't get confused on the timeline, which speeds up the workflow, especially for newcomers. The app uses menus and can be dragged and dropped, so a single objective can be accomplished in different ways. You can control all functions from within the application frame, or dockable panels can be used to get a closer look at what needs to be done. A permanent reorganization of the workspace would be appreciated. ### **Videopad Video Editing Features** VideoPad is the perfect balance between too much and not enough. Although there are not many options, it offers a reasonable selection of transitions for moving between clips and images, as well as a selection of filters to give them a unique look. In addition to editing 360-degree video, video stabilization is another helpful feature. Each filter can be previewed with a click before applying it, and You can combine several to create a custom effect or template for reuse. You can also adjust their length via menus. A video can be enhanced with transitions, visual effects, overlays, and text using VideoPad. Also included are some basic audio tools and a library of sound effects and atmospheric background music. There are a number of features that allow you to optimize videos, including color correction, adding digital images, adding subtitles, and adjusting the speed of playback. With its video stabilization feature, you can reduce camera shake, and the high-end version supports special effect plugins, but only for Windows. ### **Videopad Audio Editing Features** VideoPad offers a limited set of audio tools, but it does allow you to mix multiple audio tracks, music, and narration to create a movie soundtrack. A video clip's audio can be faded, mixed, and adjusted for volume, but if you want to go further, you'll need an external mixer or editor. From VideoPad's main menu, you can download NCH's own WavePad. While the text-to-speech features always sounded false, you can record narration directly within the program. There is a great idea in having voice recognition for subtitles, which is only available on the Windows version. However, the implementation falls short of expectations. Although the video was clearly spoken in a quiet environment, it automatically failed to translate into subtitles. ### **Videopad Content Sharing features** Video creators who publish to YouTube or other social media platforms can use the software because it allows them to share videos directly to platforms such as Dropbox, Flickr, Google Drive, and Vimeo. To avoid unnecessary data sharing, you can save videos to your desktop and upload them yourself. ### **Is VideoPad worth buying?** Although the VideoPad video editor free version is somewhat limited, it functions as a free trial to see if you like it enough to upgrade. Apps that are easy to use and have a simple interface can help convert a free user to a paying customer, and VideoPad has a strong claim to your money thanks to its simplicity and light hardware requirements. ## **Our Recommendation** As a beginner, you may be looking to use Videopad free, but when it comes to features, it just falls short compared to modern video editors. So, we recommend you use our Filmora X video editor. Filmora video editor is free to download, so you can try out all the features without paying a penny. However free version will have a watermark when you export the video. You will have to purchase a subscription to get rid of the watermark. If you compare the features and user-friendliness of both these video editors, then Filmora definitely stands out by all means. In addition to its feature richness, it also has a user-friendly interface that beginners can easily adapt to. So, don't waste your time and give it a try right now. #### Wondershare Filmora Get started easily with Filmora's powerful engine, intuitive interface, and thousands of effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![](https://neveragain.allstatics.com/2019/assets/image/box/filmora-9.png) There are multiple versions of this multiplatform video editor at different price points, in addition to a free version. How can you go wrong? This is one of the reasons why VideoPad is one of the best free video editing software programs. VideoPad Video Editor is compatible with both Mac and Windows computers and supports a number of video import and export options. This nch video editor comes with a free basic plan where you don't have to pay anything, so you can try to see how it works. In this article, we will do a quick review of this video editing software so that you have a better understanding of its features. ## **Features of VideoPad** The features list of videopad video editor is as follows: * You can share videos with your family and friends * Facebook and YouTube videos can be uploaded directly * Multiple resolutions for exporting movies * Burn DVDs and Blu-rays * You can save the file to your PSP, iPod, iPhone, or 3GP mobile phone * Visual effects and video transitions * Effects models for visual effects * Editing 3D videos * 2D to 3D stereoscopic conversion * 360 video overlays and texts * Optimization of videos * Reducing camera shake * Sequences can be enhanced with photos and digital images * Tools for audio production * Mix music and import it * A library of sound effects * Any camera can be used to create videos ### **Ease of use and interface** With VideoPad's easy-to-use interface and well-organized conventions, movie makers of any skill level can become familiar with its basics in no time at all. You will become fluent in no time at all in opening and closing windows, stringing clips together, and adding narration, transitions, and text to create a powerful visual presentation. Adding video, audio, and still, photo assets to the files pane will put them on the timeline and allow you to assemble your story. Videos and still images are organized into bins by the app, ensuring they don't get confused on the timeline, which speeds up the workflow, especially for newcomers. The app uses menus and can be dragged and dropped, so a single objective can be accomplished in different ways. You can control all functions from within the application frame, or dockable panels can be used to get a closer look at what needs to be done. A permanent reorganization of the workspace would be appreciated. ### **Videopad Video Editing Features** VideoPad is the perfect balance between too much and not enough. Although there are not many options, it offers a reasonable selection of transitions for moving between clips and images, as well as a selection of filters to give them a unique look. In addition to editing 360-degree video, video stabilization is another helpful feature. Each filter can be previewed with a click before applying it, and You can combine several to create a custom effect or template for reuse. You can also adjust their length via menus. A video can be enhanced with transitions, visual effects, overlays, and text using VideoPad. Also included are some basic audio tools and a library of sound effects and atmospheric background music. There are a number of features that allow you to optimize videos, including color correction, adding digital images, adding subtitles, and adjusting the speed of playback. With its video stabilization feature, you can reduce camera shake, and the high-end version supports special effect plugins, but only for Windows. ### **Videopad Audio Editing Features** VideoPad offers a limited set of audio tools, but it does allow you to mix multiple audio tracks, music, and narration to create a movie soundtrack. A video clip's audio can be faded, mixed, and adjusted for volume, but if you want to go further, you'll need an external mixer or editor. From VideoPad's main menu, you can download NCH's own WavePad. While the text-to-speech features always sounded false, you can record narration directly within the program. There is a great idea in having voice recognition for subtitles, which is only available on the Windows version. However, the implementation falls short of expectations. Although the video was clearly spoken in a quiet environment, it automatically failed to translate into subtitles. ### **Videopad Content Sharing features** Video creators who publish to YouTube or other social media platforms can use the software because it allows them to share videos directly to platforms such as Dropbox, Flickr, Google Drive, and Vimeo. To avoid unnecessary data sharing, you can save videos to your desktop and upload them yourself. ### **Is VideoPad worth buying?** Although the VideoPad video editor free version is somewhat limited, it functions as a free trial to see if you like it enough to upgrade. Apps that are easy to use and have a simple interface can help convert a free user to a paying customer, and VideoPad has a strong claim to your money thanks to its simplicity and light hardware requirements. ## **Our Recommendation** As a beginner, you may be looking to use Videopad free, but when it comes to features, it just falls short compared to modern video editors. So, we recommend you use our Filmora X video editor. Filmora video editor is free to download, so you can try out all the features without paying a penny. However free version will have a watermark when you export the video. You will have to purchase a subscription to get rid of the watermark. If you compare the features and user-friendliness of both these video editors, then Filmora definitely stands out by all means. In addition to its feature richness, it also has a user-friendly interface that beginners can easily adapt to. So, don't waste your time and give it a try right now. #### Wondershare Filmora Get started easily with Filmora's powerful engine, intuitive interface, and thousands of effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![](https://neveragain.allstatics.com/2019/assets/image/box/filmora-9.png) <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://ai-driven-video-production.techidaily.com/updated-2024-approved-the-ultimate-guide-to-video-making-on-mac-top-tools-and-tips/"><u>Updated 2024 Approved The Ultimate Guide to Video Making on Mac Top Tools and Tips</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/2024-approved-best-free-online-photo-background-blur-tools/"><u>2024 Approved Best Free Online Photo Background Blur Tools</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/new-crop-and-resize-8-excellent-online-image-ratio-editors-for-2024/"><u>New Crop and Resize 8 Excellent Online Image Ratio Editors for 2024</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/2024-approved-free-4k-video-converter-roundup-the-best/"><u>2024 Approved Free 4K Video Converter Roundup The Best</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/crop-and-resize-8-excellent-online-image-ratio-editors-for-2024/"><u>Crop and Resize 8 Excellent Online Image Ratio Editors for 2024</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/updated-stop-motion-on-demand-cloud-based-software-for-animators/"><u>Updated Stop Motion on Demand Cloud-Based Software for Animators</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/updated-2024-approved-the-art-of-attention-grabbing-thumbnails-youtube-size-guide-and-more/"><u>Updated 2024 Approved The Art of Attention-Grabbing Thumbnails YouTube Size Guide and More</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/gopro-video-editing-simplified-a-free-online-resource/"><u>GoPro Video Editing Simplified A Free Online Resource</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/updated-2024-approved-edit-like-a-pro-5-insider-tips-for-final-cut-pro-users/"><u>Updated 2024 Approved Edit Like a Pro 5 Insider Tips for Final Cut Pro Users</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/updated-2024-approved-unlock-the-power-of-microsoft-video-editor-windows-video-editing-tips-and-tricks/"><u>Updated 2024 Approved Unlock the Power of Microsoft Video Editor Windows Video Editing Tips and Tricks</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/updated-2024-approved-customize-your-video-layout-tips-and-tricks-for-changing-shape/"><u>Updated 2024 Approved Customize Your Video Layout Tips and Tricks for Changing Shape</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/2024-approved-ditch-adobe-top-10-premiere-elements-competitors-for-video-editing/"><u>2024 Approved Ditch Adobe? Top 10 Premiere Elements Competitors for Video Editing</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/2024-approved-produce-high-quality-videos-on-your-mac-expert-techniques-and-strategies/"><u>2024 Approved Produce High-Quality Videos on Your Mac Expert Techniques and Strategies</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/new-2024-approved-movie-magic-made-easy-upgrade-your-home-videos-to-hollywood-quality/"><u>New 2024 Approved Movie Magic Made Easy Upgrade Your Home Videos to Hollywood Quality</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/updated-in-2024-subtitle-it-for-free-10-best-online-tools/"><u>Updated In 2024, Subtitle It for Free 10 Best Online Tools</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/in-2024-slow-motion-magic-unlocking-the-power-of-windows-live-movie-maker/"><u>In 2024, Slow Motion Magic Unlocking the Power of Windows Live Movie Maker</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/in-2024-design-your-own-face-online-best-free-tools-and-websites/"><u>In 2024, Design Your Own Face Online Best Free Tools and Websites</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/updated-in-2024-from-zero-to-hero-fixing-fcpx-plugin-problems-in-minutes/"><u>Updated In 2024, From Zero to Hero Fixing FCPX Plugin Problems in Minutes</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/2024-approved-best-animation-software-for-all-skill-levels-top-picks/"><u>2024 Approved Best Animation Software for All Skill Levels Top Picks</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/2024-approved-make-a-blockbuster-trailer-best-software-for-mac-and-windows/"><u>2024 Approved Make a Blockbuster Trailer Best Software for Mac and Windows</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/1714080633235-2024-approved-avs-video-editor-review-does-it-live-up-to-expectations/"><u>2024 Approved AVS Video Editor Review Does It Live Up to Expectations?</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/the-fcpx-handbook-expert-approved-tutorials-and-websites-for-2024/"><u>The FCPX Handbook Expert-Approved Tutorials and Websites for 2024</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/in-2024-ways-to-make-your-facebook-video-cover-size-is-perfect/"><u>In 2024, Ways To Make Your Facebook Video Cover Size Is Perfect</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/new-2024-approved-lyric-video-creation-made-easy-top-free-and-paid-platforms/"><u>New 2024 Approved Lyric Video Creation Made Easy Top Free and Paid Platforms</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/new-2024-approved-the-5-best-animation-makers-for-creating-engaging-whiteboard-videos/"><u>New 2024 Approved The 5 Best Animation Makers for Creating Engaging Whiteboard Videos</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/updated-in-2024-free-avi-video-concatenators-top-10-tools-for-smooth-joining/"><u>Updated In 2024, Free AVI Video Concatenators Top 10 Tools for Smooth Joining</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/in-2024-waveform-wizardry-the-10-best-online-generators-you-need-now/"><u>In 2024, Waveform Wizardry The 10 Best Online Generators You Need Now</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/updated-get-lumafusion-for-mac-os-explore-alternative-video-editors-for-2024/"><u>Updated Get Lumafusion for Mac OS Explore Alternative Video Editors for 2024</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/pc-video-editing-made-easy-vn-editor-review-for-2024/"><u>PC Video Editing Made Easy VN Editor Review for 2024</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/in-2024-video-editing-essentials-freezing-frames-like-a-pro/"><u>In 2024, Video Editing Essentials Freezing Frames Like a Pro</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/new-in-2024-minitool-movie-maker-review-features-pricing-and-better-options/"><u>New In 2024, Minitool Movie Maker Review Features, Pricing, and Better Options</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/new-avs-video-editor-2023-features-pricing-and-performance-review-for-2024/"><u>New AVS Video Editor 2023 Features, Pricing, and Performance Review for 2024</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/merge-videos-with-ease-10-alternative-tools-to-easy-video-joiner/"><u>Merge Videos with Ease 10 Alternative Tools to Easy Video Joiner</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/new-the-ultimate-list-28-best-video-to-gif-converters-this-year-for-2024/"><u>New The Ultimate List 28 Best Video to GIF Converters This Year for 2024</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/new-in-2024-get-noticed-top-10-online-tools-for-gaming-intro-creation/"><u>New In 2024, Get Noticed Top 10 Online Tools for Gaming Intro Creation</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/2024-approved-bring-your-vision-to-life-top-10-music-video-production-studios/"><u>2024 Approved Bring Your Vision to Life Top 10 Music Video Production Studios</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/updated-in-2024-unleash-your-creativity-top-10-free-video-editors-for-mp4-files/"><u>Updated In 2024, Unleash Your Creativity Top 10 Free Video Editors for MP4 Files</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/updated-master-final-cut-pro-x-40-essential-keyboard-shortcuts-for-2024/"><u>Updated Master Final Cut Pro X 40 Essential Keyboard Shortcuts for 2024</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/updated-2024-approved-top-chromebook-video-editing-software-free-options/"><u>Updated 2024 Approved Top Chromebook Video Editing Software Free Options</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/2024-approved-in-this-article-we-will-review-gopro-quik-for-desktop-and-recommend-alternatives-to-gopro-quik-pc/"><u>2024 Approved In This Article, We Will Review Gopro Quik for Desktop and Recommend Alternatives to Gopro Quik Pc</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/in-2024-converting-video-frames-to-stunning-images-a-guide-to-10-top-converters/"><u>In 2024, Converting Video Frames to Stunning Images A Guide to 10 Top Converters</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/new-2024-approved-top-photo-to-video-converters-for-mesmerizing-slideshows/"><u>New 2024 Approved Top Photo to Video Converters for Mesmerizing Slideshows</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/updated-2024-approved-stop-motion-made-easy-best-apps-for-mobile-animation/"><u>Updated 2024 Approved Stop Motion Made Easy Best Apps for Mobile Animation</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/updated-2024-approved-videopad-video-editor-review-and-buying-recommendation/"><u>Updated 2024 Approved Videopad Video Editor Review and Buying Recommendation</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/new-how-to-download-youtube-audio-a-step-by-step-guide-for-2024/"><u>New How to Download YouTube Audio A Step-by-Step Guide for 2024</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/new-top-rated-online-trailer-editing-services-for-2024/"><u>New Top-Rated Online Trailer Editing Services for 2024</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/new-best-text-motion-tracking-software-for-2024/"><u>New Best Text Motion Tracking Software for 2024</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/in-2024-download-filmora-at-no-cost-safe-legal-and-virus-free/"><u>In 2024, Download Filmora at No Cost Safe, Legal, and Virus-Free</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/gaming-intro-design-tools-best-options-for-windows-and-mac/"><u>Gaming Intro Design Tools Best Options for Windows and Mac</u></a></li> <li><a href="https://ai-driven-video-production.techidaily.com/new-smoother-skin-in-minutes-a-plugin-free-fcpx-editing-technique/"><u>New Smoother Skin in Minutes A Plugin-Free FCPX Editing Technique</u></a></li> <li><a href="https://activate-lock.techidaily.com/new-guide-how-to-check-icloud-activation-lock-status-from-your-iphone-13-by-drfone-ios/"><u>New Guide How To Check iCloud Activation Lock Status From Your iPhone 13</u></a></li> <li><a href="https://screen-mirror.techidaily.com/how-to-do-samsung-galaxy-f34-5g-screen-sharing-drfone-by-drfone-android/"><u>How To Do Samsung Galaxy F34 5G Screen Sharing | Dr.fone</u></a></li> <li><a href="https://ai-video-apps.techidaily.com/new-in-2024-top-tricks-for-seamless-soundcloud-to-mp3-conversion/"><u>New In 2024, Top Tricks for Seamless Soundcloud to MP3 Conversion</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-access-your-apple-iphone-se-when-you-forget-the-passcode-drfone-by-drfone-ios/"><u>How to Access Your Apple iPhone SE When You Forget the Passcode? | Dr.fone</u></a></li> <li><a href="https://iphone-transfer.techidaily.com/in-2024-4-quick-ways-to-transfer-contacts-from-apple-iphone-11-pro-max-to-iphone-withwithout-itunes-drfone-by-drfone-transfer-from-ios/"><u>In 2024, 4 Quick Ways to Transfer Contacts from Apple iPhone 11 Pro Max to iPhone With/Without iTunes | Dr.fone</u></a></li> <li><a href="https://phone-solutions.techidaily.com/best-android-data-recovery-undelete-lost-messages-from-honor-magic5-ultimate-by-fonelab-android-recover-messages/"><u>Best Android Data Recovery - Undelete Lost Messages from Honor Magic5 Ultimate</u></a></li> <li><a href="https://sim-unlock.techidaily.com/in-2024-what-does-enter-puk-code-mean-and-why-did-the-sim-get-puk-blocked-on-htc-u23-device-by-drfone-android/"><u>In 2024, What Does Enter PUK Code Mean And Why Did The Sim Get PUK Blocked On HTC U23 Device</u></a></li> <li><a href="https://screen-mirror.techidaily.com/in-2024-how-can-motorola-edge-40-promirror-share-to-pc-drfone-by-drfone-android/"><u>In 2024, How Can Motorola Edge 40 ProMirror Share to PC? | Dr.fone</u></a></li> <li><a href="https://activate-lock.techidaily.com/in-2024-how-to-remove-the-activation-lock-on-your-ipad-and-iphone-se-2020-without-apple-account-by-drfone-ios/"><u>In 2024, How to Remove the Activation Lock On your iPad and iPhone SE (2020) without Apple Account</u></a></li> <li><a href="https://phone-solutions.techidaily.com/5-ways-to-restart-vivo-y78plus-without-power-button-drfone-by-drfone-reset-android-reset-android/"><u>5 Ways to Restart Vivo Y78+ Without Power Button | Dr.fone</u></a></li> <li><a href="https://screen-mirror.techidaily.com/in-2024-how-can-motorola-edge-40mirror-share-to-pc-drfone-by-drfone-android/"><u>In 2024, How Can Motorola Edge 40Mirror Share to PC? | Dr.fone</u></a></li> <li><a href="https://fix-guide.techidaily.com/how-to-revive-your-bricked-infinix-hot-40i-in-minutes-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>How To Revive Your Bricked Infinix Hot 40i in Minutes | Dr.fone</u></a></li> <li><a href="https://techidaily.com/remove-honor-unlock-screen-by-drfone-android-unlock-android-unlock/"><u>Remove Honor unlock screen</u></a></li> <li><a href="https://ios-pokemon-go.techidaily.com/reasons-why-pokemon-gps-does-not-work-on-apple-iphone-6-plus-drfone-by-drfone-virtual-ios/"><u>Reasons why Pokémon GPS does not Work On Apple iPhone 6 Plus? | Dr.fone</u></a></li> <li><a href="https://phone-solutions.techidaily.com/4-easy-ways-for-your-realme-12-5g-hard-reset-drfone-by-drfone-reset-android-reset-android/"><u>4 Easy Ways for Your Realme 12 5G Hard Reset | Dr.fone</u></a></li> <li><a href="https://techidaily.com/how-to-recover-lost-data-from-apple-iphone-7-drfone-by-drfone-ios-data-recovery-ios-data-recovery/"><u>How To Recover Lost Data from Apple iPhone 7? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-unlock-iphone-6s-plus-without-passcode-4-easy-methods-drfone-by-drfone-ios/"><u>How To Unlock iPhone 6s Plus Without Passcode? 4 Easy Methods | Dr.fone</u></a></li> <li><a href="https://review-topics.techidaily.com/how-to-upgrade-iphone-15-plus-to-the-latest-ios-version-drfone-by-drfone-ios-system-repair-ios-system-repair/"><u>How to Upgrade iPhone 15 Plus to the Latest iOS Version? | Dr.fone</u></a></li> <li><a href="https://fix-guide.techidaily.com/in-2024-does-find-my-friends-work-on-honor-magic-5-lite-drfone-by-drfone-virtual-android/"><u>In 2024, Does find my friends work on Honor Magic 5 Lite | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-unlock-stolen-apple-iphone-11-pro-max-in-different-conditionsin-drfone-by-drfone-ios/"><u>How To Unlock Stolen Apple iPhone 11 Pro Max In Different Conditionsin | Dr.fone</u></a></li> <li><a href="https://bypass-frp.techidaily.com/in-2024-how-to-bypass-frp-from-infinix-zero-5g-2023-turbo-by-drfone-android/"><u>In 2024, How to Bypass FRP from Infinix Zero 5G 2023 Turbo?</u></a></li> <li><a href="https://unlock-android.techidaily.com/in-2024-mastering-lock-screen-settings-how-to-enable-and-disable-on-vivo-y100t-by-drfone-android/"><u>In 2024, Mastering Lock Screen Settings How to Enable and Disable on Vivo Y100t</u></a></li> <li><a href="https://android-pokemon-go.techidaily.com/in-2024-latest-way-to-get-shiny-meltan-box-in-pokemon-go-mystery-box-on-oppo-reno-10-5g-drfone-by-drfone-virtual-android/"><u>In 2024, Latest way to get Shiny Meltan Box in Pokémon Go Mystery Box On Oppo Reno 10 5G | Dr.fone</u></a></li> <li><a href="https://location-social.techidaily.com/in-2024-how-to-pause-life360-location-sharing-for-realme-narzo-n55-drfone-by-drfone-virtual-android/"><u>In 2024, How To Pause Life360 Location Sharing For Realme Narzo N55 | Dr.fone</u></a></li> <li><a href="https://android-location-track.techidaily.com/in-2024-how-to-spy-on-text-messages-from-computer-and-realme-11-proplus-drfone-by-drfone-virtual-android/"><u>In 2024, How to Spy on Text Messages from Computer & Realme 11 Pro+ | Dr.fone</u></a></li> <li><a href="https://blog-min.techidaily.com/how-to-exit-recovery-mode-on-iphone-xs-max-drfone-by-drfone-ios-system-repair-ios-system-repair/"><u>How To Exit Recovery Mode on iPhone XS Max? | Dr.fone</u></a></li> <li><a href="https://phone-solutions.techidaily.com/does-samsung-galaxy-a25-5g-support-mov-videos-by-aiseesoft-video-converter-play-mov-on-android/"><u>Does Samsung Galaxy A25 5G support MOV videos ?</u></a></li> <li><a href="https://ai-editing-video.techidaily.com/2024-approved-finding-best-gif-websites-is-easy-as-pie/"><u>2024 Approved Finding Best GIF Websites Is Easy as Pie</u></a></li> <li><a href="https://ios-unlock.techidaily.com/locked-out-of-apple-iphone-se-5-ways-to-get-into-a-locked-apple-iphone-se-by-drfone-ios/"><u>Locked Out of Apple iPhone SE? 5 Ways to get into a Locked Apple iPhone SE</u></a></li> </ul></div>
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { ReactiveFormsModule } from '@angular/forms'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { AppComponent } from './app.component'; import { JwtInterceptor, ErrorInterceptor } from './helpers'; import { HomeComponent } from './home'; import { PostComponent } from './post'; import { LoginComponent } from './login'; import { appRoutingModule } from './app.routing'; import { fakeBackendProvider } from './helpers'; @NgModule({ imports: [ BrowserModule, ReactiveFormsModule, HttpClientModule, NgbModule, appRoutingModule, ], declarations: [ AppComponent, HomeComponent, PostComponent, LoginComponent, ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, fakeBackendProvider ], bootstrap: [AppComponent] }) export class AppModule { }
# frozen_string_literal: true require "rails_helper" RSpec.describe ApplicationJob do describe "saving and restoring the current user" do let(:user) { create(:user, name: "Background User") } let(:buffer) { StringIO.new } let(:logs) { buffer.string } let(:job_class) do Class.new(::ApplicationJob) do def perform logger.info <<~INFO Performed #{self.class.name} for #{Current.user.name} INFO end end end before do ActiveJob::Base.logger = Logger.new(buffer) stub_const("MyApplicationJob", job_class) end it "uses the enqueing user when performing the job later" do Current.set(user: user) do MyApplicationJob.perform_later end expect { Thread.new { perform_enqueued_jobs }.join }.not_to change(Current, :user).from(nil) expect(logs).to include <<~LOGS INFO -- : Performed MyApplicationJob for Background User LOGS end it "uses the current user when performing the job now" do expect { Current.set(user: user) do MyApplicationJob.perform_now end }.not_to change(Current, :user).from(nil) expect(logs).to include <<~LOGS INFO -- : Performed MyApplicationJob for Background User LOGS end end end
from patchwork.common.utils.utils import exclude_none_dict from patchwork.step import Step from patchwork.steps.CallLLM.CallLLM import CallLLM from patchwork.steps.ExtractModelResponse.ExtractModelResponse import ( ExtractModelResponse, ) from patchwork.steps.LLM.typed import LLMInputs from patchwork.steps.PreparePrompt.PreparePrompt import PreparePrompt class LLM(Step): def __init__(self, inputs): """Initializes the class and checks for required input keys. Args: inputs dict: A dictionary containing the input data to be validated. Raises: ValueError: If any required keys are missing from the provided input data. """ super().__init__(inputs) missing_keys = LLMInputs.__required_keys__.difference(set(inputs.keys())) if len(missing_keys) > 0: raise ValueError(f'Missing required data: "{missing_keys}"') self.inputs = inputs def run(self) -> dict: """Executes a series of tasks to process prompts and extract responses from a language model. This method orchestrates the flow from preparing prompts, calling the language model (LLM), and extracting responses, ultimately returning a structured dictionary with relevant outputs. Args: self: The instance of the class, which contains the inputs necessary for processing. Returns: dict: A dictionary containing the processed information, including prompts, responses from the LLM, extracted responses, and token counts. """ prepare_prompt_outputs = PreparePrompt(self.inputs).run() call_llm_outputs = CallLLM( dict( prompts=prepare_prompt_outputs.get("prompts"), **self.inputs, ) ).run() extract_model_response_outputs = ExtractModelResponse( dict( openai_responses=call_llm_outputs.get("openai_responses"), **self.inputs, ) ).run() return exclude_none_dict( dict( prompts=prepare_prompt_outputs.get("prompts"), openai_responses=call_llm_outputs.get("openai_responses"), extracted_responses=extract_model_response_outputs.get("extracted_responses"), request_tokens=call_llm_outputs.get("request_tokens"), response_tokens=call_llm_outputs.get("response_tokens"), ) )
# Trollus Discord Bot 🎵 A Discord bot for playing YouTube sounds in voice channels with customizable volume and per-server sound management. ## Features 🚀 - **Add Sound**: `/trollus addus` - Add a sound from a YouTube URL. - **Play Sound**: `/trollus playus` - Play a sound with optional voice channel selection. - **List Sounds**: `/trollus listus` - List all available sounds with pagination. - **Remove Sound**: `/trollus removus` - Remove a sound. - **Stop Sound**: `/trollus stopus` - Stop the current sound and disconnect. - **Set Volume**: `/trollus volumeus` - Set global volume (0.1x to 5.0x). - **Manage Users**: `/trollus userus` - Add or remove authorized users. ## Installation 🛠️ ### Prerequisites - Node.js v20+ - npm - ffmpeg ### Setup 1. **Clone the repository:** ```bash git clone https://github.com/yourusername/trollus-bot.git cd trollus-bot ``` 2. **Install dependencies:** ```bash npm install ``` 3. **Create a `.env` file:** ```env DISCORD_TOKEN=your_discord_token CLIENT_ID=your_application_id ``` 4. **Create required directories:** ```bash mkdir -p assets/sounds mkdir -p data ``` 5. **Add a valid `cookies.txt` file in the root directory (for YouTube authentication).** 6. **Configure allowed users in `src/config.ts`:** ```typescript allowedUsers: [ 'your_discord_user_id', // Add other admin user IDs ] as string[], ``` ### Build & Deploy 1. **Build the project:** ```bash npm run build ``` 2. **Deploy slash commands:** ```bash npm run deploy ``` 3. **Start the bot:** ```bash npm start ``` ## Configuration ⚙️ ### System Limits - **Maximum sound size:** 100MB - **Maximum sounds per server:** 100 - **Maximum total storage:** 20GB ### Volume Control - **Default volume:** 1.0 - **Maximum volume:** 5.0 (500%) - **Minimum volume:** 0.1 (10%) ## Development 💻 ### Available Scripts - **Run with hot reload:** `npm run dev` - **Deploy slash commands:** `npm run deploy` - **Build TypeScript:** `npm run build` - **Start production bot:** `npm start` ## Project Structure 📁 ``` trollus-bot/ ├── src/ │ ├── commands/ │ │ └── trollus/ │ │ ├── add.ts │ │ ├── play.ts │ │ ├── list.ts │ │ └── ... │ ├── services/ │ │ └── YoutubeService.ts │ ├── database/ │ │ └── JsonDatabase.ts │ ├── utils/ │ │ └── validators.ts │ ├── types/ │ │ └── index.ts │ └── config.ts ├── assets/ │ └── sounds/ │ └── [guild_id]/ ├── data/ │ └── database.json └── dist/ ``` ### Database Structure ```typescript interface DatabaseSchema { servers: { [guildId: string]: { sounds: Sound[]; allowedUsers: string[]; settings: { defaultVolume: number; }; }; }; } ``` ## Dependencies 📦 - `discord.js`: ^14.11.0 - `@discordjs/voice`: ^0.18.0 - `@discordjs/opus`: ^0.9.0 - `youtube-dl-exec`: ^3.0.12 - `dotenv`: ^16.0.3 - `uuid`: ^9.0.0 ## Troubleshooting 🔍 1. **Command not found** - Run `npm run deploy` to update slash commands. - Wait a few minutes for Discord to register commands. 2. **Sound download fails** - Check `cookies.txt` is valid. - Verify YouTube URL format. - Check storage limits. 3. **Voice errors** - Ensure ffmpeg is installed. - Check bot has voice permissions. - Verify voice channel access. ## License 📄 MIT License ## Author 👤 xdLulux ## Support 💬 For issues and feature requests, please open an issue on GitHub. (no support L)
// SSNFinder.h : Declaration of the CSSNFinder #pragma once #include "resource.h" // main symbols #include <AFCategories.h> #include <IdentifiableObject.h> #include <string> #include <list> using namespace std; struct StringSegmentType { int iStartIndex; int iEndIndex; }; // CSSNFinder class ATL_NO_VTABLE CSSNFinder : public CComObjectRootEx<CComMultiThreadModel>, public CComCoClass<CSSNFinder, &CLSID_SSNFinder>, public IDispatchImpl<ISSNFinder, &IID_ISSNFinder, &LIBID_UCLID_REDACTIONCUSTOMCOMPONENTSLib>, public IDispatchImpl<IAttributeModifyingRule, &IID_IAttributeModifyingRule, &LIBID_UCLID_AFCORELib>, public IDispatchImpl<ICategorizedComponent, &IID_ICategorizedComponent, &LIBID_UCLID_COMUTILSLib>, public IDispatchImpl<ICopyableObject, &IID_ICopyableObject, &LIBID_UCLID_COMUTILSLib>, public IDispatchImpl<ILicensedComponent, &IID_ILicensedComponent, &LIBID_UCLID_COMLMLib>, public IDispatchImpl<IMustBeConfiguredObject, &IID_IMustBeConfiguredObject, &LIBID_UCLID_COMUTILSLib>, public IPersistStream, public ISupportErrorInfo, public ISpecifyPropertyPagesImpl<CSSNFinder>, public IDispatchImpl<IIdentifiableObject, &IID_IIdentifiableObject, &LIBID_UCLID_COMUTILSLib>, private CIdentifiableObject { public: CSSNFinder(); ~CSSNFinder(); DECLARE_REGISTRY_RESOURCEID(IDR_SSNFINDER) DECLARE_PROTECT_FINAL_CONSTRUCT() BEGIN_COM_MAP(CSSNFinder) COM_INTERFACE_ENTRY(ISSNFinder) COM_INTERFACE_ENTRY2(IDispatch, ISSNFinder) COM_INTERFACE_ENTRY(IAttributeModifyingRule) COM_INTERFACE_ENTRY(ICategorizedComponent) COM_INTERFACE_ENTRY(ICopyableObject) COM_INTERFACE_ENTRY(ILicensedComponent) COM_INTERFACE_ENTRY(IMustBeConfiguredObject) COM_INTERFACE_ENTRY(IPersistStream) COM_INTERFACE_ENTRY(ISupportErrorInfo) COM_INTERFACE_ENTRY_IMPL(ISpecifyPropertyPages) COM_INTERFACE_ENTRY(IIdentifiableObject) END_COM_MAP() BEGIN_PROP_MAP(CSSNFinder) PROP_PAGE(CLSID_SSNFinderPP) END_PROP_MAP() BEGIN_CATEGORY_MAP(CSSNFinder) IMPLEMENTED_CATEGORY(CATID_AFAPI_VALUE_MODIFIERS) END_CATEGORY_MAP() public: // ISSNFinder STDMETHOD(SetOptions)(/*[in]*/ BSTR bstrSubattributeName, /*[in]*/ VARIANT_BOOL vbSpatialSubattribute, /*[in]*/ VARIANT_BOOL vbClearIfNoneFound); STDMETHOD(GetOptions)(/*[out]*/ BSTR* pbstrSubattributeName, /*[out]*/ VARIANT_BOOL* pvbSpatialSubattribute, /*[out]*/ VARIANT_BOOL* pvbClearIfNoneFound); // IAttributeModifyingRule STDMETHOD(raw_ModifyValue)(/*[in]*/ IAttribute* pAttribute, /*[in]*/ IAFDocument* pOriginInput, /*[in]*/ IProgressStatus* pProgressStatus); // ICategorizedComponent STDMETHOD(raw_GetComponentDescription)(/*[out, retval]*/ BSTR* pstrComponentDescription); // ICopyableObject STDMETHOD(raw_Clone)(/*[out, retval]*/ IUnknown** pObject); STDMETHOD(raw_CopyFrom)(/*[in]*/ IUnknown* pObject); // ILicensedComponent STDMETHOD(raw_IsLicensed)(/*[out, retval]*/ VARIANT_BOOL* pbValue); // IMustBeConfiguredObject STDMETHOD(raw_IsConfigured)(/*[out]*/ VARIANT_BOOL* pbValue); // IPersistStream STDMETHOD(GetClassID)(/*[out]*/ CLSID *pClassID); STDMETHOD(IsDirty)(); STDMETHOD(Load)(/*[unique][in]*/ IStream *pStm); STDMETHOD(Save)(/*[unique][in]*/ IStream *pStm, /*[in]*/ BOOL fClearDirty); STDMETHOD(GetSizeMax)(/*[out]*/ ULARGE_INTEGER *pcbSize); // ISupportsErrorInfo STDMETHOD(InterfaceSupportsErrorInfo)(/*[in]*/ REFIID riid); // IIdentifiableObject STDMETHOD(get_InstanceGUID)(GUID *pVal); private: // Private variables // dirty flag bool m_bDirty; // name of subattributes string m_strSubattributeName; // whether the attribute and subattributes should be stored as spatial (true) or hybrid (false) bool m_bSpatialSubattribute; // if no matches are found, whether the attribute should be cleared (true) or unmodified (false) bool m_bClearIfNoneFound; // Private methods //--------------------------------------------------------------------------------------------- // PURPOSE: To return a valid SSOCR engine. // PROMISE: Instantiates and licenses m_ipOCREngine if it was NULL. Returns m_ipOCREngine. IOCREnginePtr getOCREngine(); //--------------------------------------------------------------------------------------------- // PROMISE: Throws an exception if this component is not licensed. Runs successfully otherwise. void validateLicense(); //------------------------------------------------------------------------------------------------- // PURPOSE: Searches strText in the range of [iStartIndex, iEndIndex) for likely social security // numbers. For each SSN found, a string segment, containing the index of the first and // last digit of the social security number, is added to listSegments. // REQUIRE: 0 <= iStartIndex < iEndIndex <= strText.length() static void findSSNs(const string& strText, int iStartIndex, int iEndIndex, list<StringSegmentType>& listSegments); //-------------------------------------------------------------------------------------------------- // PURPOSE: Increments riNumDigits, riNumUnrec, riNumSpaces counters based on the value of cChar. // Returns false if cChar is a disqualifying character, true otherwise. If // bSpaceDisqualifies is true, spaces will be considered disqualifying characters. // PROMISE: (1) If cChar is a digit, riNumDigits will be incremented. // (2) If cChar is the unrecognized symbol, riNumUnrec will be incremented. // (3) If cChar is a space, riNumSpaces will be incremented. Underscores are treated like // spaces. // (4) If cChar is not one of the above characters, it is a disqualifying characer. // // Returns false if cChar is a disqualifying character, true otherwise. If // bSpaceDisqualifies is true, the space is a disqualifying character. static bool incrementCounters(char cChar, int& riNumDigits, int& riNumUnrec, int& riNumSpaces, bool bSpaceDisqualifies=false); //------------------------------------------------------------------------------------------------- // PROMISE: If the sum of the digit and unrecognized character counters are within the minimum // (iMinDigits) and maximum (iMaxDigits), sets riMatchingIndex to iIndex. Returns true if // a terminal matching index has been found (ie. riMatchingIndex != -1 and the sum of // digits and unrecognized characters equals iMaxDigits). static bool findMatchingIndex(int iMinDigits, int iMaxDigits, int iIndex, int& riNumDigits, int& riNumUnrec, int& riMatchingIndex); };
<template> <div class="photoinfo-container"> <h3>{{photoinfo.title}}</h3> <p class="subtitles"> <span>发表时间: {{photoinfo.add_time | dateFormat}}</span> <span>点击: {{photoinfo.click}}次</span> </p> <hr> <!-- 缩略图区域 --> <div class="thumbs"> <img class="preview-img" v-for="(item, index) in list" :key="item.src" :src="item.src" height="100" @click="$preview.open(index, list)"> </div> <!-- 图片的内容 --> <div class="content" v-html="photoinfo.content"></div> <!-- 放置一个现成的评论子组件 --> <cmt-box :id="id"></cmt-box> </div> </template> <script> // 1.导入评论子组件 import comment from '../subcomponents/comment.vue' export default { data(){ return{ id: this.$route.params.id, //从路由中获取到的图片id photoinfo: {}, //图片详情 list: [] //缩略图的数组 } }, created(){ this.getPhotoInfo(); this.getThumbs(); }, methods:{ getPhotoInfo(){ // 获取图片的详情 this.$http.get('api/getimageInfo/' + this.id).then(result => { if(result.body.status === 0){ this.photoinfo = result.body.message[0]; } }) }, getThumbs(){ // 获取缩略图 this.$http.get('api/getthumimages/' + this.id).then(result => { if(result.body.status === 0){ // 循环每个图片数据,补全图片的宽和高 result.body.message.foreach(item => { item.w = 600; item.h = 400; }); // 把完整的数据保存到list中 this.list = result.body.message; } }) } }, components: { 'cmt-box': comment } } </script> <style lang="scss" scoped> .photoinfo-container{ padding: 3px; h3{ color: #26A2FF; font-size: 15px; text-align: center; margin: 15px 0; } .subtitle{ display: flex; justify-content: space-between; font-size: 13px; } .content{ font-size: 13px; line-height: 30px; } .thumbs{ img{ margin: 10px; box-shadow: 0 0 8px #999; } } } </style>
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2017, AdaCore -- -- -- -- 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. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- 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 -- -- HOLDER 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 body NXT.Analog_Sensor_Utils is ------------------------- -- Get_Average_Reading -- ------------------------- procedure Get_Average_Reading (Sensor : in out NXT_Analog_Sensor'Class; Interval : Time_Span; Result : out Integer; Successful : out Boolean) is Deadline : constant Time := Clock + Interval; Reading : Integer; Total : Integer := 0; Count : Integer := 0; begin while Clock <= Deadline loop Get_Raw_Reading (Sensor, Reading, Successful); if not Successful then Result := 0; return; end if; -- Reading is in range 0 .. ADC_Conversion_Max_Value, ie 0 .. 1023, -- so we are not likely to overflow for a reasonable interval, but -- it is possible... Total := Total + Reading; Count := Count + 1; end loop; Result := Total / Count; end Get_Average_Reading; end NXT.Analog_Sensor_Utils;
/** * @module Card */ export default class Card { /** * @description * <div class="exapmle" data-module="card" data-example='[{"simple":"250-420"},{"collapse":"330-620"},{"function":"280-750"},{"img":"1030-570"},{"outline":"230-350"},{"width":"520-800"},{"simpleComponent":"470-300"}]'></div> * @property {string} outline - Defining the elements of the border CSS style the default value is default, such as "none","default", "primary", "success", "warning", "danger", "info". * @property {string} imageSrc - Defining image path. * @property {string} title - Define the element of title. * @property {function} functions - Defines some function button of card. * @property {functions} headerfunctions - Defines some function of card header. * @property {boolean} collapse - Defines whether context of the element can be show,the default is true. * @property {boolean} collapseIcon - Defines whether collapse icon of the element can be show,the default is false. * @property {string} width - Defines width of card in card group , the default is 12. * @property {string} id - React.PropTypes.string. * @property {string} name - React.PropTypes.string. * @property {string} value - Defines whether context of the element can be show,the default is true. * @property {object} style - Defines whether collapse icon of the element can be show,the default is false. * @property {string} styleClass - React.PropTypes.oneOf(["default", "primary", "success", "warning", "danger", "info"]). * @property {string} className -React.PropTypes.string. * @property {boolean} enabled - React.PropTypes.bool. * @property {boolean} visiabled - React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.string]). * @property {functions} onClick - React.PropTypes.func. */ example() { } };
#include <stdio.h> #include <stdlib.h> #define rep(y,x) for(int i=y;i<x;i++) int c_size=0; typedef struct Node ll; struct Node{ int data; struct Node *next; }; ll*head=NULL; //Creating initial LinkedList void createNode(){ ll *temp,*ptr; temp = (ll *)malloc(sizeof(ll)); if(temp==NULL){ printf("\nOUT OF MEMORY SPACE"); exit(0); } printf("\nENTER NODE DATA: "); scanf("%d",&temp->data); temp->next=NULL; if(head==NULL){ head=temp; } else{ ptr=head; while(ptr->next!=NULL){ ptr=ptr->next; } ptr->next=temp; } } //Displaying the LinkedList void display(){ ll *ptr; int node_no=1; if(head==NULL){ printf("\nLINKED LIST IS EMPTY\n"); return; } else{ ptr = head; printf("\n"); rep(0,30) printf("-"); printf("\nDISPLAYING THE LINKED LIST\n"); rep(0,30) printf("-"); printf("\n[ "); while(ptr!=NULL){ printf("(Data:%d||Node:%d)-->",ptr->data,node_no++); ptr = ptr->next; } printf("NULL ]\n"); } } /* Insertion functions starts */ //Insertion at the beginning of the linked list void insertAtBegin(){ ll *temp; temp = (ll *)malloc(sizeof(ll)); if(temp==NULL){ printf("\nOUT OF MEMORY SPACE"); exit(0); } printf("\nENTER NODE DATA: "); scanf("%d",&temp->data); temp->next=NULL; if(head==NULL){ head=temp; } else{ temp->next=head; head=temp; } } //Insertion at the end of the linked list void insertAtEnd(){ ll *temp,*ptr; temp = (ll *)malloc(sizeof(ll)); ptr=head; if(temp==NULL){ printf("\nOUT OF MEMORY SPACE"); exit(0); } printf("\nENTER NODE DATA: "); scanf("%d",&temp->data); temp->next=NULL; if(head==NULL){ head=temp; } else{ while(ptr->next!=NULL){ ptr=ptr->next; } ptr->next=temp; } } //Insertion at a given position in the linked list void insertAtPosition(){ ll *temp,*ptr; temp = (ll *)malloc(sizeof(ll)); ptr=head; if(temp==NULL){ printf("\nOUT OF MEMORY SPACE"); exit(0); } if(head==NULL){ printf("\nLINKED LIST IS EMPTY\n"); return; } int pos; printf("\nENTER POSITION FOR NODE INSERTION: "); scanf("%d",&pos); printf("\nENTER NODE DATA: "); scanf("%d",&temp->data); temp->next=NULL; if(pos==1){ temp->next=head; head=temp; } else{ int i=1; while(i!=pos-1){ if(ptr==NULL){ printf("\nPOSITION NOT FOUND!!\n"); return; } ptr=ptr->next; i++; } temp->next=ptr->next; ptr->next=temp; } } //Insertion after a specified node in the linked list void insertAfterNode(){ ll *temp,*ptr; temp = (ll *)malloc(sizeof(ll)); ptr=head; if(temp==NULL){ printf("\nOUT OF MEMORY SPACE"); exit(0); } if(head==NULL){ printf("\nLINKED LIST IS EMPTY\n"); return; } else{ int nd; printf("\nENTER NODE VALUE FOR NODE INSERTION: "); scanf("%d",&nd); printf("\nENTER NODE DATA: "); scanf("%d",&temp->data); temp->next=NULL; while(ptr->data!=nd){ if(ptr->next==NULL){ printf("\nNODE NOT FOUND!!\n"); return; } ptr=ptr->next; } temp->next=ptr->next; ptr->next=temp; } } /* Insertion functions ends */ /* Deletion functions starts */ //Deletion of node at the beginning of the linked list void deleteAtFirst(){ ll *ptr; if(head==NULL){ printf("\nLINKED LIST IS EMPTY\n"); return; } else{ ptr=head; head=ptr->next; free(ptr); printf("DELETION COMPLETE"); } } //Deletion of node at the end of the linked list void deleteAtLast(){ ll *prev,*ptr; if(head==NULL){ printf("\nLINKED LIST IS EMPTY\n"); return; } else if(head->next==NULL){ ptr=head; head=NULL; printf("DELETION COMPLETE"); free(ptr); } else{ ptr=head; while(ptr->next!=NULL){ prev=ptr; ptr=ptr->next; } prev->next=NULL; free(ptr); printf("DELETION COMPLETE"); } } //Deletion of node at a given position in the linked list void deleteAtPosition(){ ll *prev,*ptr; if(head==NULL){ printf(" \nLINKED LIST IS EMPTY"); return; } else{ int pos; printf("\nENTER POSITION FOR NODE TO DELETE : "); scanf("%d",&pos); if(pos==1){ ptr=head; head=head->next; free(ptr); printf("DELETION COMPLTETE"); } else{ ptr=head; int i=1; while(i<pos){ if(ptr->next==NULL){ printf("\nPOSITION NOT FOUND!!\n"); return; } prev=ptr; ptr=ptr->next; i++; } prev->next=ptr->next; free(ptr); printf("DELETION COMPLTETE"); } } } //Deletion of a specified node in the linked list void deleteSpecifiedNode(){ ll *prev,*ptr; if(head==NULL){ printf("\nLINKED LIST IS EMPTY\n"); return; } else{ ptr=head; int nd; printf("\nENTER NODE VALUE FOR NODE DELETION: "); scanf("%d",&nd); if(ptr->data==nd){ ptr=head; head=head->next; free(ptr); printf("DELETION COMPLTETE"); } else{ while(ptr->data!=nd){ if(ptr->next==NULL){ printf("\nNODE NOT FOUND!!\n"); return; } prev=ptr; ptr=ptr->next; } prev->next=ptr->next; free(ptr); printf("DELETION COMPLTETE"); } } } /* Deletion functions ends */ //Search function searches given node in the linked list void searchNode(){ ll *ptr; int node_no=1; if(head==NULL){ printf("\nLINKED LIST IS EMPTY\n"); return; } else{ ptr = head; int key; printf("\n"); rep(0,30) printf("-"); printf("\nENTER A NODE VALUE FOR SEARCHING : "); scanf("%d",&key); while(ptr->data!=key){ if(ptr->next==NULL){ printf("\nNODE NOT FOUND!!\n"); rep(0,30) printf("-"); printf("\n"); return; } else ++node_no; ptr = ptr->next; } if(node_no==1) printf("\nNODE %d FOUND @ %dst POSITION\n",ptr->data,node_no); else if(node_no==2) printf("\nNODE %d FOUND @ %dnd POSITION\n",ptr->data,node_no); else if(node_no==3) printf("\nNODE %d FOUND @ %drd POSITION\n",ptr->data,node_no); else printf("\nNODE %d FOUND @ %dth POSITION\n",ptr->data,node_no); rep(0,30) printf("-"); printf("\n"); } } //Reverse the entire linked list void reverseList(){ ll *ptr,*prev,*next; prev=next=NULL; ptr=head; if(head==NULL){ printf("\nLINKED LIST IS EMPTY\n"); return; } else{ while(ptr!=NULL){ next=ptr->next; ptr->next=prev; prev=ptr; ptr=next; } head=prev; printf("\nLINKED LIST IS REVERSED\n"); } } int main() { int choice; rep(0,10) printf("*"); printf("WELCOME TO LINKED LIST"); rep(0,10) printf("*"); printf("\n"); while(1){ rep(0,30) printf("="); printf("\n<-<-<-MAIN MENU->->->\n(1)CREATE\n(2)INSERT\n(3)DELETE\n(4)DISPLAY\n(5)SEARCH A NODE\n(6)REVERSE THE LIST\n(7)EXIT\n"); rep(0,30) printf("-"); printf("\nENTER YOUR CHOICE: "); scanf("%d",&choice); printf("\n"); rep(0,30) printf("-"); printf("\n"); switch(choice){ case 1: { int num; printf("\nENTER NUMBER OF NODES IN THE STARTING LINKED LIST: "); scanf("%d",&num); while(num!=0){ createNode(); num--; } break; } case 2: { int ch1; rep(0,30) printf(">"); printf("\n<-<-<-INSERTION MENU->->->\n(1)INSERT AT THE BEGINNING\n(2)INSERT AT THE END\n(3)INSERT NODE AT POSITION\n(4)INSERT AFTER A SPECIFIED NODE\n"); rep(0,30) printf(">"); printf("\nENTER YOUR CHOICE: "); scanf("%d",&ch1); switch(ch1){ case 1: insertAtBegin(); break; case 2: insertAtEnd(); break; case 3: insertAtPosition(); break; case 4: insertAfterNode(); break; default: exit(0); } break; } case 3: { int ch2; printf("\n"); rep(0,30) printf("<"); printf("\n<-<-<-DELETION MENU->->->\n(1)DELETE THE FIRST NODE\n(2)DELETE THE LAST NODE\n(3)DELETE NODE AT POSITION\n(4)DELETE A NODE OF SPECIFIED VALUE\n"); rep(0,30) printf("<"); printf("\nENTER YOUR CHOICE: "); scanf("%d",&ch2); switch(ch2){ case 1: deleteAtFirst(); break; case 2: deleteAtLast(); break; case 3: deleteAtPosition(); break; case 4: deleteSpecifiedNode(); break; default: exit(0); } break; } case 4: display(); break; case 5: searchNode(); break; case 6: reverseList(); break; case 7: exit(0); break; default: printf("WRONG OPTION SELCTED!!TRY AGAIN\n"); } printf("\n"); rep(0,30) printf("="); printf("\n\n\n"); } getch(); return 0; }
const request = require('supertest') const express = require('express') // mock authenticateToken in router const auth = require("../lib/authenticate") jest.spyOn(auth, 'authenticateToken').mockImplementation( (req, res, next) => { const { published } = req.query; if (published && published === 'true') { // pass authentication if retrieving published posts only return next() } // set authenticated user req.authenticatedUser = { userid: '678288616906366dc56a79e6', username: 'jan' }; return next() } ) const testPublishedPostId = "978288616906366dc56a79f6" const testUnpublishedPostId = "67e288616906366dc56a7999" const Post = require("../models/post"); const dbOps = require('../db/dbOps') jest.spyOn(dbOps, 'findPostById').mockImplementation(async (testPublishedPostId) => { console.log("mock findPostById function") const post_published = new Post({ title: "post 1", content: "test content", date_created: Date.now(), is_published: true, _id: testPublishedPostId }) return Promise.resolve(post_published) }) const postsRouter = require('../routes/posts'); const app = express() app.use(express.urlencoded({ extended: false })); app.use("/posts", postsRouter); describe('get post detail', () => { let server let agent beforeEach((done) => { server = app.listen(4000, () => { agent = request.agent(server) done() }) }) afterEach((done) => { jest.clearAllMocks() server.close(done) }) it("gets a published post detail by its id and returns code 200", async () => { const res = await agent .get(`/posts/${testPublishedPostId}?published=true`) expect(res.headers['content-type']).toMatch(/json/); expect(res.statusCode).toEqual(200); expect(res.body.title).toBe('post 1'); expect(res.body.content).toBe('test content'); }); it("it returns code 401 if requesting a published post but the post is actually unpublished", async () => { jest.spyOn(dbOps, 'findPostById').mockImplementation(async (testUnpublishedPostId) => { console.log("mock findPostById function") const post_published = new Post({ title: "post 2", content: "unpublished test content", date_created: Date.now(), _id: testUnpublishedPostId }) return Promise.resolve(post_published) }) const res = await agent .get(`/posts/${testUnpublishedPostId}?published=true`) expect(res.statusCode).toEqual(401); }); it("it returns code 404 if post not found", async () => { jest.spyOn(dbOps, 'findPostById').mockImplementation(async (someid) => { console.log("mock findPostById function - no post found") return Promise.resolve(null) }) const res = await agent .get('/posts/978288616906366dc56a7910?published=true') expect(res.statusCode).toEqual(404); }); it("gets an unpublished post detail by its id and returns code 200", async () => { jest.spyOn(dbOps, 'findPostById').mockImplementation(async (testUnpublishedPostId) => { console.log("mock findPostById function") const post_published = new Post({ title: "post 2", content: "unpublished test content", date_created: Date.now(), _id: testUnpublishedPostId }) return Promise.resolve(post_published) }) const res = await agent .get(`/posts/${testUnpublishedPostId}`) expect(res.headers['content-type']).toMatch(/json/); expect(res.statusCode).toEqual(200); expect(res.body.title).toBe('post 2'); expect(res.body.content).toBe('unpublished test content'); }); });
import os import logging # Add logging import import streamlit as st from main import process_query from agent_manager import AgentManager from dotenv import load_dotenv from langchain.chat_models import ChatOpenAI import numpy as np import sounddevice as sd import soundfile as sf import time import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import seaborn as sns import pandas as pd from io import BytesIO from together import Together # Configure logger logging.basicConfig(level=logging.ERROR) # Set to ERROR to avoid debug logs logger = logging.getLogger(__name__) # Load environment variables load_dotenv() # Initialize session state if 'messages' not in st.session_state: st.session_state.messages = [] if 'recording' not in st.session_state: st.session_state.recording = False if 'audio_data' not in st.session_state: st.session_state.audio_data = None if 'audio_chunks' not in st.session_state: st.session_state.audio_chunks = [] if 'temp_audio_path' not in st.session_state: st.session_state.temp_audio_path = None if 'together_api_key' not in st.session_state: st.session_state.together_api_key = os.getenv('TOGETHER_API_KEY') if 'model_name' not in st.session_state: st.session_state.model_name = "meta-llama/Llama-3.3-70B-Instruct-Turbo" # Initialize AgentManager and other components agent_manager = AgentManager() chat_model = ChatOpenAI(model_name="gpt-4", temperature=0.5) # Page configuration st.set_page_config(page_title="AI Agent Chat", page_icon="🤖", layout="wide") # Title (optional, can be removed for a clean chat UI) st.title("AI Agent Orchestrator") # Create a temp directory if it doesn't exist if 'temp_dir' not in st.session_state: temp_dir = "temp_uploads" os.makedirs(temp_dir, exist_ok=True) st.session_state.temp_dir = temp_dir # Define supported file types SUPPORTED_FORMATS = ['pdf', 'docx', 'xlsx', 'csv', 'png', 'jpg', 'jpeg', 'mp4', 'avi', 'mov', 'mkv', 'wmv', 'flv', 'mp3', 'wav', 'm4a', 'flac', 'aac'] # Input box fixed at the bottom prompt = st.chat_input("Type your message here (e.g., 'Convert this PDF to DOCX' or 'Convert this video to MP4')...") uploaded_file = st.file_uploader("Upload your file", type=SUPPORTED_FORMATS) # Add format hint if uploaded_file: file_type = os.path.splitext(uploaded_file.name)[1][1:].lower() # Define all video formats VIDEO_FORMATS = ['mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv'] supported_conversions = { 'pdf': ['docx'], 'docx': ['pdf'], 'xlsx': ['csv'], 'csv': ['xlsx'], 'png': ['txt'], # OCR 'jpg': ['txt'], # OCR 'jpeg': ['txt'] # OCR } # Add video format conversions dynamically for video_format in VIDEO_FORMATS: supported_conversions[video_format] = [fmt for fmt in VIDEO_FORMATS if fmt != video_format] if file_type in supported_conversions: formats = supported_conversions[file_type] if file_type in VIDEO_FORMATS: st.info(f"💡 You can convert this video to any of these formats: {', '.join(formats).upper()}") else: st.info(f"💡 You can convert this {file_type.upper()} file to: {', '.join(formats).upper()}") st.success(f"File '{uploaded_file.name}' uploaded successfully!") st.session_state.uploaded_file = uploaded_file # Add this hint after file upload for data files if uploaded_file and uploaded_file.name.endswith(('.csv', '.xlsx', '.xls')): st.info("💡 You can ask me to create visualizations from this data. Try asking something like: \n\n" + "- 'Create a visualization showing the distribution of values'\n" + "- 'Show me a graph comparing the different categories'\n" + "- 'Generate a plot analyzing the trends in this data'") col1, col2 = st.columns(2) with col1: if not st.session_state.recording: if st.button("🎤 Start Recording"): st.session_state.recording = True st.session_state.audio_chunks = [] st.rerun() with col2: if st.session_state.recording: if st.button("⏹️ Stop Recording"): st.session_state.recording = False if st.session_state.audio_chunks: audio_data = np.concatenate(st.session_state.audio_chunks) temp_path = os.path.join(st.session_state.temp_dir, "temp_recording.wav") sf.write(temp_path, audio_data, 16000) st.session_state.temp_audio_path = temp_path st.session_state.audio_data = audio_data st.rerun() if st.session_state.recording: st.warning("🎙️ Recording in progress... Press 'Stop Recording' when finished.") try: with sd.InputStream(channels=1, samplerate=16000, dtype=np.float32) as stream: while st.session_state.recording: audio_chunk, _ = stream.read(1024) st.session_state.audio_chunks.append(audio_chunk) time.sleep(0.01) except Exception as e: st.error(f"Recording error: {str(e)}") st.session_state.recording = False if st.session_state.temp_audio_path and os.path.exists(st.session_state.temp_audio_path): st.audio(st.session_state.temp_audio_path) st.info("💡 Type 'transcribe this audio' or similar to process the recording") # Display chat messages above the input box with st.container(): st.subheader("Chat Messages") for message in reversed(st.session_state.messages): # Reverse the order of messages with st.chat_message(message["role"]): st.write(message["content"]) # Add MIME type mapping MIME_TO_EXTENSION = { 'application/pdf': '.pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': '.xlsx', 'text/csv': '.csv', 'text/plain': '.txt', 'video/mp4': '.mp4', 'video/x-msvideo': '.avi', 'video/x-matroska': '.mkv', 'video/quicktime': '.mov', 'video/x-ms-wmv': '.wmv', 'video/x-flv': '.flv' } def display_response(response): try: if isinstance(response, dict): response_type = response.get('type') # Enhanced visualization handling if response_type == 'visualization': if 'image_data' in response: try: # Display the visualization st.image(response['image_data']) # Show interpretation if available if 'interpretation' in response: st.markdown("### Interpretation") st.markdown(response['interpretation']) # Add download button st.download_button( label="📥 Download Visualization", data=response['image_data'], file_name="visualization.png", mime="image/png" ) return "Visualization generated successfully" except Exception as viz_error: st.error(f"Error displaying visualization: {str(viz_error)}") return "Failed to display visualization" # Handle visualization responses first if response_type == 'visualization': if 'image_data' in response: try: # Display the visualization st.image(response['image_data']) # Add download button st.download_button( label="📥 Download Visualization", data=response['image_data'], file_name="visualization.png", mime="image/png" ) return "Visualization generated successfully" except Exception as viz_error: st.error(f"Error displaying visualization: {str(viz_error)}") return "Failed to display visualization" # Handle image generation responses if response_type == 'image': if 'url' in response: st.image(response['url'], caption="Generated by DALL-E", use_container_width=True) # Display the URL below the image st.markdown(f"**Image URL**: {response['url']}") return response.get('content', "Image generated successfully") # Handle visualization responses if response_type == 'visualization': if 'image_data' in response: # Display the image st.image(response['image_data'], use_column_width=True) # Add download button st.download_button( label="📥 Download Visualization", data=response['image_data'], file_name=response.get('filename', 'visualization.png'), mime=response.get('mime_type', 'image/png') ) return "Visualization generated successfully" # Handle file conversion responses if response_type == 'file' and 'data' in response and 'mime_type' in response: if not isinstance(response['data'], bytes): st.error("Invalid file data format") return "File conversion failed: Invalid data format" extension = MIME_TO_EXTENSION.get(response['mime_type'], '.txt') filename = f"converted_file{extension}" # Create a unique key for each download button download_key = f"download_{filename}_{st.session_state.messages.__len__()}" # Create download button st.download_button( label=f"📥 Download {extension.upper()} File", data=response['data'], file_name=filename, mime=response['mime_type'], key=download_key # Ensure unique key ) # Show success message st.success(f"✅ File successfully converted to {extension.upper()}") # Avoid returning early to allow further processing # return f"File converted to {extension.upper()}. Click the download button above to save your file." # Handle image generation responses if response_type == 'image': if 'url' in response: image_url = response['url'] if image_url.startswith(('http://', 'https://')): # For DALL-E images (direct URLs) st.image(image_url, caption="Generated by DALL-E", use_container_width=True) elif image_url.startswith('file://'): # For FLUX images (local files) file_path = response.get('file_path') if file_path and os.path.exists(file_path): with open(file_path, 'rb') as f: st.image(f.read(), caption="Generated by FLUX.1-Schnell", use_container_width=True) st.markdown(f"**Image URL**: {image_url}") return response.get('content', "Image generated successfully") # Handle transcription responses if response_type == 'text' and "Transcription" in response.get('content', ''): st.markdown(f"**Transcription:** {response['content']}") return response['content'] # Handle visualization responses if response_type == 'visualization' and 'plot_data' in response: # Display the base64 image st.image(response['plot_data'], use_column_width=True) # Show interpretation if available if response.get('explanation'): st.markdown("### Analysis") st.markdown(response['explanation']) return response.get('content', "Visualization generated successfully") # Handle non-audio query responses if response.get('agent_info'): st.info(response['agent_info']) # Handle text responses elif response_type == 'text' or 'content' in response: content = response.get('content', '') if content: st.markdown(content) return content # Default handling if 'content' in response: st.markdown(response['content']) return response['content'] elif isinstance(response, str): st.markdown(response) return response return "Unsupported response format" except Exception as e: error_msg = f"Error displaying response: {str(e)}" st.error(error_msg) logger.error(error_msg) return error_msg # Handle input processing if prompt: st.session_state.messages.append({"role": "user", "content": prompt}) with st.chat_message("user"): st.write(prompt) with st.chat_message("assistant"): with st.spinner("Processing..."): try: # Check if there's recorded audio and the prompt is about transcription if (st.session_state.temp_audio_path and os.path.exists(st.session_state.temp_audio_path) and any(word in prompt.lower() for word in ['transcribe', 'transcription', 'convert to text'])): response = process_query( file_path=st.session_state.temp_audio_path, query="Please transcribe this audio file" ) elif st.session_state.get("uploaded_file"): file_path = os.path.join(st.session_state.temp_dir, st.session_state.uploaded_file.name) with open(file_path, "wb") as f: f.write(st.session_state.uploaded_file.getbuffer()) response = process_query(file_path=file_path, query=prompt) else: response = process_query(file_path=None, query=prompt) # After processing, clean up the temporary audio file if st.session_state.temp_audio_path and os.path.exists(st.session_state.temp_audio_path): try: os.remove(st.session_state.temp_audio_path) st.session_state.temp_audio_path = None except Exception as e: logger.error(f"Error cleaning up temp audio file: {str(e)}") # Display and format the response chat_message = display_response(response) # Add assistant's response to chat history if chat_message: st.session_state.messages.append({ "role": "assistant", "content": chat_message }) except Exception as e: error_msg = f"Error processing request: {str(e)}" st.error(error_msg) logger.error(f"Processing error: {str(e)}") st.session_state.messages.append({ "role": "assistant", "content": error_msg }) # Sidebar with agent information with st.sidebar: st.header("Available Agents") agents = agent_manager.get_agents() for agent in agents: st.subheader(agent['name']) st.write(f"Description: {agent['description']}") st.write(f"Tools: {', '.join(agent['tools'])}") st.divider() # Add this function after your imports def chat_with_llm(df: pd.DataFrame, user_message: str): try: # Add column info to the prompt column_info = f"\nAvailable columns: {', '.join(df.columns.tolist())}" system_prompt = f"""You're a Python data scientist and data visualization expert. Given a pandas DataFrame 'df', generate Python code to create visualizations using matplotlib, seaborn, or pandas plotting functions. The data fields should be clearly visible. Focus on creating clear and informative visualizations that answer the user's query. {column_info} Important: Your response MUST include Python code wrapped in ```python``` code blocks. Example format: Brief interpretation of what the visualization will show. ```python # Your Python code here ```""" messages = [ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_message}, ] with st.spinner('Creating visualization...'): # Debug: Print API key (masked) api_key = st.session_state.together_api_key if api_key: logger.info(f"API Key found: {api_key[:4]}...{api_key[-4:]}") else: st.error("No Together API key found!") return {"success": False, "type": "text", "content": "API key missing"} client = Together(api_key=st.session_state.together_api_key) # Debug: Print DataFrame info logger.info(f"DataFrame columns: {df.columns.tolist()}") logger.info(f"DataFrame shape: {df.shape}") response = client.chat.completions.create( model=st.session_state.model_name, messages=messages, ) response_message = response.choices[0].message # Debug: Print raw response logger.info(f"Raw response: {response_message.content}") # Extract code with better error handling if '```python' in response_message.content: python_code = response_message.content.split('```python')[1].split('```')[0] logger.info(f"Extracted code: {python_code}") else: st.error("No Python code found in response") return {"success": False, "type": "text", "content": "No visualization code generated"} interpretation = response_message.content.split('```')[0].strip() if python_code: try: # Clear any existing plots plt.close('all') plt.figure(figsize=(10, 6)) # Execute the visualization code local_vars = {'df': df, 'plt': plt, 'sns': sns, 'pd': pd} exec(python_code, globals(), local_vars) # Save the plot to bytes buf = BytesIO() plt.savefig(buf, format='png', bbox_inches='tight', dpi=300) buf.seek(0) image_data = buf.getvalue() plt.close() return { "success": True, "type": "visualization", "image_data": image_data, "interpretation": interpretation } except Exception as viz_error: st.error(f"Visualization execution error: {str(viz_error)}") st.error(f"Problematic code:\n{python_code}") return { "success": False, "type": "text", "content": f"Error executing visualization: {str(viz_error)}" } return { "success": False, "type": "text", "content": "No valid visualization code generated" } except Exception as e: logger.error(f"General error in chat_with_llm: {str(e)}") return { "success": False, "type": "text", "content": f"Error generating visualization: {str(e)}" } # Update the visualization handling section if uploaded_file is not None and uploaded_file.name.endswith(('.csv', '.xlsx', '.xls')): try: # Read the data file if uploaded_file.name.endswith('.csv'): df = pd.read_csv(uploaded_file) else: df = pd.read_excel(uploaded_file) # Display data preview and column names st.write("Dataset Preview:") st.dataframe(df.head()) st.write("Available columns:", ', '.join(df.columns.tolist())) # Add visualization prompt if prompt and any(word in prompt.lower() for word in ['visualize', 'plot', 'graph', 'chart', 'show', 'create', 'distribution', 'trend']): with st.spinner("Generating visualization..."): result = chat_with_llm(df, prompt) if result.get('success'): # Display the visualization st.image(result['image_data']) if result.get('interpretation'): st.markdown("### Interpretation") st.markdown(result['interpretation']) st.download_button( label="📥 Download Visualization", data=result['image_data'], file_name="visualization.png", mime="image/png" ) st.session_state.messages.append({ "role": "assistant", "content": "Visualization generated successfully" }) else: st.error(result.get('content', 'Failed to generate visualization')) except Exception as e: st.error(f"Error processing data file: {str(e)}") logger.error(f"Error processing data file: {str(e)}")
from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from django import forms from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy from .models import CustomUser class CustomUserCreationForm(UserCreationForm): manager_dropdown = forms.ModelChoiceField( queryset=CustomUser.objects.filter(groups__name='Manager'), empty_label="Select a manager", required=True, widget=forms.Select(attrs={'class': 'form-control'}) # Add class for styling ) class Meta(UserCreationForm.Meta): model = CustomUser fields = ( "employer", "manager_dropdown", "username", "password1", "password2", "first_name", "last_name", "dob", "email", "sin", "address", "address_two", "city", "state_province", "country", "postal", ) widgets = { 'dob': forms.DateInput(attrs={'type': 'date'}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["first_name"].required = True self.fields["last_name"].required = True self.fields["address"].required = True self.fields["address_two"].required = False self.fields["city"].required = True self.fields["state_province"].required = True self.fields["country"].required = True self.fields["postal"].required = True self.fields["email"].required = True self.fields["sin"].required = True self.fields['dob'].required = True self.fields['postal'].required = True # Populate choices for manager_dropdown managers = CustomUser.objects.filter(groups__name='Manager') manager_choices = [(manager.id, manager.username) for manager in managers] self.fields['manager_dropdown'].choices = [('', 'Select a manager')] + manager_choices self.helper = FormHelper() self.helper.form_method = "post" self.helper.add_input(Submit("submit", "Register")) self.helper.form_action = reverse_lazy("index") # Optionally set an empty label for the dropdown self.fields["employer"].empty_label = "Select an employer" self.fields["employer"].required = True # Apply margin-top or margin-bottom to all fields for field_name in self.fields: self.fields[field_name].widget.attrs["class"] = "mt-1" # Apply margin-top self.fields[field_name].widget.attrs["class"] = "mb-2" # Apply margin-bottom def clean_email(self): email = self.cleaned_data['email'] return email.lower() # Convert email to lowercase def clean(self): cleaned_data = super().clean() phone_number = cleaned_data.get("phone_number") email = cleaned_data.get("email") if phone_number and CustomUser.objects.filter(phone_number=phone_number).exists(): self.add_error("phone_number", "This phone number is already in use.") if email and CustomUser.objects.filter(email=email).exists(): self.add_error("email", "This email is already in use") return cleaned_data def clean_manager_dropdown(self): manager = self.cleaned_data.get('manager_dropdown') if manager is None: raise forms.ValidationError('Invalid manager selection.') # Here, we extract the ID from the selected manager manager_id = manager.id print(f'Manager ID from clean_manager_dropdown: {manager_id}') valid_manager_ids = [manager.id for manager in CustomUser.objects.filter(groups__name='Manager')] if manager_id not in valid_manager_ids: raise forms.ValidationError('Invalid manager selection.') # Return the manager's ID return manager_id class TwoFactorAuthenticationForm(forms.Form): verification_code = forms.CharField( max_length=12, required=True, widget=forms.TextInput(attrs={'class': 'form-control'}), ) def __init__(self, *args, **kwargs): super(TwoFactorAuthenticationForm, self).__init__(*args, **kwargs) self.fields['verification_code'].widget.attrs.update({'style': 'margin: 10px 0;'})
export interface ISampleReq { id: string; } export interface ISampleRes { data: { name: string }; } export interface ISampleLoginReq { userId: string; password: string; } export interface ISampleLoginRes { createDate: string; modifiedDate: string; id: string; password: string; result: string; // createDate: "2023-08-13T07:43:40.302Z"; // modifiedDate: "2023-08-13T07:43:40.302Z"; // id: "string"; // password: "string"; // result: "string"; } // member export interface IgetMemberInfoRes { createDate: string; modifiedDate: string; id: number; memberId: string; memberPw: string; memberIdImageUrl: string; nickname: string; name: string; gender: string; introduce: string; birth: string; phone: string; address: string; email: string; authCode: string; snsCode: string; status: string; memo: string; } export interface IgetMemberInfoReq { memberId: string; } export interface ISampleApi { getSampleApi(param: ISampleReq): Promise<ISampleRes>; getSampleLoginApi(param: ISampleLoginReq): Promise<ISampleLoginRes>; getMemberInfo(param: IgetMemberInfoReq): Promise<IgetMemberInfoRes>; }
using System.Collections.Generic; using System.Linq.Expressions; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Editor.Engine.Interfaces; using System.IO; using Game_Tools_Week4_Editor; using System.Windows.Forms; namespace Game_Tools_Week4_Editor { internal class Level : ISerializable { // Accessors public Camera GetCamera() { return m_camera; } //Members private List<Models> m_models = new(); private Camera m_camera = new(new Vector3(0, 2, 2), 16 / 9); public Level() { } public void LoadContent(ContentManager _content) { Models teapot = new(_content, "Teapot" , "Metal", "MyShader", Vector3.Zero, 1.0f); teapot.SetShader(_content.Load<Effect>("MyShader")); AddModel(teapot); teapot = new(_content, "Teapot", "Metal", "MyShader", new Vector3(1, 0, 0), 1.0f); AddModel(teapot); } public void AddModel(Models _model) { m_models.Add(_model); } public List<Models> GetSelectedModels() { List<Models> models = new List<Models>(); foreach (var model in m_models) { if(model.Selected) models.Add(model); } return models; } public void Render() { foreach(Models m in m_models) { m.Render(m_camera.View, m_camera.Projection); } } private void HandleTranslate() { InputController ic = InputController.Instance; Vector3 translate = Vector3.Zero; if (ic.isKeyDown(Keys.Left)) translate.X += -10; if (ic.isKeyDown(Keys.Right)) translate.X += 10; if (ic.isKeyDown(Keys.Menu)) // menu == alt key { if (ic.isKeyDown(Keys.Up)) translate.Z += 1; if (ic.isKeyDown(Keys.Down)) translate.Z += -1; } else { if (ic.isKeyDown(Keys.Up)) translate.Y += 10; if (ic.isKeyDown(Keys.Down)) translate.Y += -10; } if (ic.IsButtonDown(MouseButtons.Middle)) { Vector2 dir = ic.MousePosition - ic.LastPosition; translate.X = dir.X; translate.Y = -dir.Y; } if (ic.GetWheel() != 0) { translate.Z = ic.GetWheel() * 2; } if (translate != Vector3.Zero) { bool modelTranslated = false; foreach(Models model in m_models) { if(model.Selected) { modelTranslated = true; model.Translate(translate / 1000, m_camera); } } if (!modelTranslated) { m_camera.Translate(translate * 0.001f); } } } private void HandleRotate(float _delta) { InputController ic = InputController.Instance; if (ic.IsButtonDown(MouseButtons.Right) && (!ic.isKeyDown(Keys.Menu))) { Vector2 dir = ic.MousePosition - ic.LastPosition; if (dir != Vector2.Zero) { Vector3 movement = new Vector3(dir.Y, dir.X, 0) * _delta; bool modelRotated = false; foreach(Models model in m_models) { if (model.Selected) { modelRotated = true; model.Rotation += movement; } } if(!modelRotated) { m_camera.Rotate(movement); } } } } private void HandleScale(float _delta) { InputController ic = InputController.Instance; if( (ic.IsButtonDown(MouseButtons.Right)) && (ic.isKeyDown(Keys.Menu))) { float l = ic.MousePosition.X - ic.LastPosition.X; if(l != 0) { l *= _delta; foreach(Models model in m_models) { if(model.Selected) { model.Scale += l; } } } } } private void HandlePick() { InputController ic = InputController.Instance; if(ic.IsButtonDown(MouseButtons.Left)) { Ray r = ic.GetPickRay(m_camera); foreach(Models model in m_models) { model.Selected = false; foreach(ModelMesh mesh in model.Mesh.Meshes) { BoundingSphere s = mesh.BoundingSphere; s = s.Transform(model.GetTransform()); float? f = r.Intersects(s); if(f.HasValue) { model.Selected = true; } } } } } public void Update(float _delta) { HandleTranslate(); HandleRotate(_delta); HandleScale(_delta); HandlePick(); } public void Serialize(BinaryWriter _stream) { _stream.Write(m_models.Count); foreach( var model in m_models) { model.Serialize(_stream); } m_camera.Serialize(_stream); } public void Deserialize(BinaryReader _stream, ContentManager _content) { int modelCount = _stream.ReadInt32(); for (int count = 0; count < modelCount; count++) { Models m = new(); m.Deserialize(_stream, _content); m_models.Add(m); } m_camera.Deserialize(_stream, _content); } public override string ToString() { string s = string.Empty; foreach(Models m in m_models) { if(m.Selected) { s += "\nModel: Pos: " + m.Position.ToString() + " Rot: " + m.Rotation.ToString(); } } return m_camera.ToString() + s; } } }
Nome: detector event api Contexto: Uma API que recebe por sistema eventos de detectores de amônia e os armazena em banco de dados com data e hora desses eventos. Os detectores disparam sistema registrador quando etes detectam concentraçao acima de 20ppm, armazenando qual detector (id), concentração máxima detectada, data e horário dessa ocorrência. A partir desses registros, usuários com perfil de acesso nesse mesmo sistema poderão consultar esses eventos por filtros aplicados por data, período e id dos detectores. Contratos: Cadastro de evento: - id (DT_004); - nome detector (estufa resfriamento de presunto); - registro máximo (45 ppm); - data da ocorrência (DD/MM/AAAA HH:MM:SS); POST /api/detection-events { "id": "DT_004", "name": "estufa resfriamento de presunto", "reg_max": 45.9 } PUT /api/detection-events/{id} Reconhecimento de alarme: - usuário; - data de reconhecimento (DD:MM:SS); - id (DT_004); { "status": "REARMED|WARNING|MUTED", "user": "Raphael" } DELETE /api/detection-events/{id} - GET /api/detection-events/{id} Um evento: - id (DT_004); - nome detector (estufa resfriamento de presunto); - registro máximo (45 ppm); - data da ocorrência (DD/MM/AAAA HH:MM:SS); - Status reconhecimento; - usuário; - data de reconhecimento (DD:MM:SS); GET /api/detection-events?id=DT_004&name=XPTO&created_on_start=2023-07-21 00:00:00&created_on_start_end=2023-07-21 23:59:59 Lista de eventos: - id (DT_004); - nome detector (estufa resfriamento de presunto); - registro máximo (45 ppm); - data da ocorrência (DD/MM/AAAA HH:MM:SS); - Status reconhecimento; - usuário; - data de reconhecimento (DD:MM:SS HH:MM:SS); v1: { "id": "DT_004", "name": "estufa resfriamento de presunto", "reg_max": 45, "created_on": "2023-07-21 17:10:33" "status": "WARNING|REARMED|MUTED", "user": "Raphael", "recognized_on": "2023-07-21 17:10:33" } v2: { "id": "DT_004", "name": "estufa resfriamento de presunto", "reg_max": 45, "created_on": "2023-07-21 17:10:33", "history": [ { "status": "WARNING", "user": "Raphael", "created_on": "2023-07-21 17:10:33" }, { "status": "MUTED", "user": "Raphael", "created_on": "2023-07-21 17:11:15" }, { "status": "REARMED", "user": "Raphael", "created_on": "2023-07-21 17:25:56" } ] } Filros: - id; - nome detector; - período; Status de reconhecimento: - alarmando; - rearmado; - silenciado; Design Frontend do App: - Uma página de Sign in conforme layout no link do material mui; - Uma página de cadastro de novo usuário. Estes usuários devem estar perfil de usuário, sendo gerente, supervisor e operador; - Uma página com uma planta geral, mostrando um fluxograma de processo; - Cada equipamento será um componente com possibilidade de abrir um Modal para inserção de algumas informações, as quais serão: PV (medição atual), SP (Set Point), botões de Cancel e Confirme; - No Modal deve possuir como title o nome do detector ou a TAG; - Uma página contendo um history registrando os valores de cada detector distribuído no tempo cor cores para cada detector; Tecnologias: - GIT - OK - Java - Spring Boot Framework - MongoDB (NOSQL) - JSON - Docker - React
import type { NextPage } from "next"; import { useTodos, useTodosDispatch } from "src/state/todo"; const Home: NextPage = () => { const todos = useTodos(); const { toggleIsDone } = useTodosDispatch(); return ( <div> <h3>Todo一覧</h3> {todos.map((todo) => ( <div key={todo.id}> <label style={{ fontSize: "2rem" }}> <input type="checkbox" style={{ width: "1.5rem", height: "1.5rem" }} checked={todo.isDone} onChange={() => toggleIsDone(todo.id)} /> {todo.text} </label> </div> ))} </div> ); }; export default Home;
import { makeStyles } from "@mui/styles"; import { Paper, Typography, CircularProgress, Box, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Grow, Pagination, } from "@mui/material"; import { useState, useEffect } from "react"; import useCurrentLeague from "../../../hooks/useCurrentLeague"; import MyAxios from "../../../api/MyAxios"; import { useTheme } from "@mui/material/styles"; const useStyles = makeStyles((theme) => ({ title: { display: "flex", justifyContent: "center", alignItems: "center", height: "3rem", backgroundColor: theme.palette.primary.main, color: "white", borderRadius: "4px 4px 0 0", border: "2px solid", borderColor: theme.palette.primary.light, }, loadingBox: { width: "100%", display: "flex", justifyContent: "center", alignItems: "center", minHeight: "20vh", }, row: { cursor: "pointer", "&:hover": { backgroundColor: theme.palette.primary.dark, "& h6": { color: "white", }, outline: "2px solid white", }, boxShadow: theme.shadows[3], borderRadius: "4px", backgroundColor: "white", minHeight: "1rem", padding: "0.5rem", margin: "5rem", "& td:first-child": { borderTopLeftRadius: "4px", borderBottomLeftRadius: "4px", }, "& td:last-child": { borderTopRightRadius: "4px", borderBottomRightRadius: "4px", }, }, tableHeadRow: { // backgroundColor: theme.palette.blueBackground.dark, // color: "white", "& td:first-child": { borderTopLeftRadius: "10px", borderBottomLeftRadius: "4px", }, "& td:last-child": { borderTopRightRadius: "4px", borderBottomRightRadius: "4px", }, }, })); const Ranking = () => { const theme = useTheme(); const classes = useStyles(); const [isLoading, setIsLoading] = useState(true); const [notify, setNotify] = useState(""); const { currentLeague } = useCurrentLeague(); const [data, setData] = useState([]); const [refinedData, setRefinedData] = useState([]); // [ const [currentPage, setCurrentPage] = useState(1); const [totalPage, setTotalPage] = useState(1); useEffect(async () => { if (!currentLeague) return; try { setIsLoading(true); setNotify(""); const response = await MyAxios.get( `/cauthughibanmuagiai/${currentLeague.id}` ); if (response?.data?.data) { setData(response.data.data); } setIsLoading(false); } catch (error) { console.log(error); setIsLoading(false); setNotify("Không tìm thấy dữ liệu"); } }, [currentLeague]); useEffect(async () => { if (!data) return; try { // setData(data.sort((a, b) => b.soBanThang - a.soBanThang)); const promises = data?.map(async (item) => { const res = await MyAxios.get(`/cauthu?id=${item?.idCauThu}`); return { ...item, loaiCauThu: res?.data?.data?.loaiCauThu, hinhAnh: res?.data?.data?.hinhAnh, }; }); setRefinedData(await Promise.all(promises)); } catch (err) { console.log(err); } }, [data]); return ( <> <Paper elevation={3} sx={{ minWidth: "40vw" }}> <Typography variant="h3" className={classes.title}> Danh sách cầu thủ ghi bàn </Typography> {isLoading && ( <Box className={classes.loadingBox}> <CircularProgress /> </Box> )} {!isLoading && notify && ( <Box className={classes.loadingBox}> <Typography variant="subtitle1">{notify}</Typography> </Box> )} {!isLoading && !notify && ( <TableContainer sx={{ display: "flex", flexDirection: "column", backgroundColor: "blueBackground.main", borderRadius: "0 0 4px 4px", }} > <Table sx={{ borderCollapse: "separate", borderSpacing: "0 0.5em", padding: "1rem", paddingTop: "0", }} > <TableHead> <TableRow className={classes.tableHeadRow}> <TableCell align="center"> <Typography variant="h6" sx={{ backgroundColor: "primary.main", color: "white", padding: "0.5rem", borderRadius: "4px", // margin: "0.5rem", }} > Cầu thủ </Typography> </TableCell> <TableCell align="center"> <Typography sx={{ ml: "1rem" }} variant="h6"> Đội bóng </Typography> </TableCell> <TableCell align="center"> <Typography variant="h6">Loại cầu thủ</Typography> </TableCell> <TableCell align="center"> <Typography variant="h6">Số bàn thắng</Typography> </TableCell> </TableRow> </TableHead> <TableBody sx={{ backgroundColor: "blueBackground.light", }} > {refinedData.map((item, index) => ( <Grow in={!isLoading} {...(!isLoading ? { timeout: index * 1000 } : {})} key={index} > <TableRow key={index} className={classes.row}> <TableCell align="center" sx={{ padding: "8px" }}> <Box sx={{ display: "flex", justifyContent: "flex-start", alignItems: "center", }} > <img style={{ width: "35px", marginLeft: "1rem", marginRight: "1rem", }} src={item?.hinhAnh} ></img> <Typography variant="h6"> {" "} {item?.tenCauThu} </Typography> </Box> </TableCell> <TableCell align="center" sx={{ padding: "8px" }}> <Typography variant="h6"> {item?.tenDoi}</Typography> </TableCell> <TableCell align="center" sx={{ padding: "8px" }}> <Typography variant="h6"> {" "} {item?.loaiCauThu} </Typography> </TableCell> <TableCell align="center" sx={{ padding: "8px" }}> <Typography variant="h6"> {" "} {item.soLuongBanThang} </Typography> </TableCell> </TableRow> </Grow> ))} </TableBody> </Table> </TableContainer> )} <Box sx={{ display: "flex", justifyContent: "center", backgroundColor: "blueBackground.main", paddingBottom: "0.5rem", }} > {refinedData.length > 0 ? ( <Pagination count={totalPage} page={currentPage} variant="contained" shape="rounded" // onChange={handlePageChange} key={currentPage} ></Pagination> ) : ( <Typography variant="h6" sx={{ padding: "1rem" }}> Không có dữ liệu </Typography> )} </Box> </Paper> </> ); }; export default Ranking;
import React from 'react'; import UserBar from './UserBar'; import FileBrowser from './FileBrowser'; import AddPanel from '../Panel/addPanel/AddPanel'; import '../../stylesheets/FileSystem.css'; class FileSystem extends React.Component { constructor(props) { super(props); this.state = { username: this.props.userData[1], userid: this.props.userData[0], current_location: '/' }; this.file_browser = React.createRef(); this.user_bar = React.createRef(); this.add_panel = React.createRef(); } render() { return ( <section id="filesystem"> <UserBar username={this.state.username} current_location={this.state.current_location} main_change_directory={this.main_change_directory} ref={this.user_bar} open_add_panel={this.open_add_panel} /> <FileBrowser username={this.state.username} userid={this.state.userid} url={this.props.url} current_location={this.current_location} main_change_directory={this.main_change_directory} ref={this.file_browser} /> <AddPanel get_current_directory={this.get_current_directory} main_change_directory={this.main_change_directory} url={this.props.url} ref={this.add_panel} userid={this.state.userid} /> </section> ); } main_change_directory = (filepath, from_browser = false) => { this.setState({ current_location: filepath }, () => { if (!from_browser) this.file_browser.current.change_directory(filepath); this.user_bar.current.render(); }); }; get_current_directory = () => this.state.current_location; open_add_panel = () => this.add_panel.current.open_panel(); } export default FileSystem;
import streamlit as st import ibis import json import pyodbc import duckdb import pandas as pd from pathlib import Path from typing import Optional, Dict, Any import os def detect_delimiter(file_path: str) -> str: """Detect the delimiter in a CSV file""" try: # Read first few lines of the file with open(file_path, 'r') as file: sample = file.readline() + file.readline() # Count potential delimiters delimiters = { ',': sample.count(','), ';': sample.count(';'), '\t': sample.count('\t'), '|': sample.count('|') } # Return the delimiter with highest count return max(delimiters.items(), key=lambda x: x[1])[0] except Exception as e: st.error(f"Error detecting delimiter: {str(e)}") return ',' def preview_csv(file_path: str, delimiter: str, quotechar: str, has_header: bool) -> pd.DataFrame: """Preview first 5 rows of CSV file""" try: df = pd.read_csv( file_path, delimiter=delimiter, quotechar=quotechar, header=0 if has_header else None, nrows=5 ) return df except Exception as e: st.error(f"Error previewing CSV: {str(e)}") return None def get_column_types(df: pd.DataFrame) -> Dict[str, str]: """Get column types from DataFrame""" type_mapping = { 'int64': 'INTEGER', 'float64': 'DOUBLE', 'object': 'VARCHAR', 'bool': 'BOOLEAN', 'datetime64[ns]': 'TIMESTAMP' } return {col: type_mapping.get(str(df[col].dtype), 'VARCHAR') for col in df.columns} def load_backend_configs() -> Dict[str, Dict[str, Any]]: """Load backend configurations from backends.json""" with open("backends.json", "r") as f: return json.load(f) def load_saved_connections() -> Dict[str, Dict[str, Any]]: """Load saved connections from a JSON file""" config_path = Path("connections.json") if config_path.exists(): with open(config_path, "r") as f: return json.load(f) return {} def save_connection(name: str, db_type: str, params: Dict[str, Any]) -> None: """Save connection details to a JSON file""" connections = load_saved_connections() connections[name] = { "type": db_type, "params": params } with open("connections.json", "w") as f: json.dump(connections, f, indent=4) def delete_connection(name: str) -> None: """Delete a saved connection""" connections = load_saved_connections() if name in connections: del connections[name] with open("connections.json", "w") as f: json.dump(connections, f, indent=4) def rename_connection(old_name: str, new_name: str) -> None: """Rename a saved connection""" if old_name == new_name: return connections = load_saved_connections() if old_name in connections: connections[new_name] = connections.pop(old_name) with open("connections.json", "w") as f: json.dump(connections, f, indent=4) def get_connection_params(db_type: str) -> Dict[str, Any]: """Return connection parameters based on database type from backends.json""" backends = load_backend_configs() return backends.get(db_type, {}) def create_connection(db_type: str, params: Dict[str, Any]) -> Optional[ibis.BaseBackend]: """Create database connection using Ibis""" try: connection_method = getattr(ibis, db_type.lower()) # For databases that only need a path parameter, pass the path string directly if len(params) == 1 and "path" in params: return connection_method.connect(params["path"]) return connection_method.connect(**params) except Exception as e: st.error(f"Connection error: {str(e)}") return None def main(): st.title("Connection Manager") st.logo("https://infoblueprint.co.za/wp-content/uploads/2021/06/infoblueprint-logo-600px.png") # Initialize session state variables if they don't exist if 'selected_db' not in st.session_state: st.session_state.selected_db = None if 'connection_name' not in st.session_state: st.session_state.connection_name = "" if 'connection_params' not in st.session_state: st.session_state.connection_params = {} # Add tabs for managing connections tab1, tab2 = st.tabs(["Create Connection", "Manage Connections"]) with tab1: backends = load_backend_configs() db_options = sorted(list(backends.keys()) + ["CSV"]) st.session_state.selected_db = st.selectbox( "Select a database system:", db_options, index=None, placeholder="Choose a database..." ) if st.session_state.selected_db: st.session_state.connection_name = st.text_input( "Connection name", value=f"{st.session_state.selected_db}_connection", key="connection_name_create" ) if st.session_state.selected_db == "CSV": file_path = st.text_input("CSV File Path", help="Provide the full path to your CSV file") if file_path and os.path.exists(file_path): # CSV Import Options st.subheader("CSV Import Options") # Detect delimiter detected_delimiter = detect_delimiter(file_path) delimiter_options = { 'Comma (,)': ',', 'Semicolon (;)': ';', 'Tab (\\t)': '\t', 'Pipe (|)': '|', 'Custom': 'custom' } delimiter_choice = st.selectbox( "Delimiter", options=list(delimiter_options.keys()), index=list(delimiter_options.values()).index(detected_delimiter) if detected_delimiter in delimiter_options.values() else 0 ) if delimiter_choice == 'Custom': delimiter = st.text_input("Enter custom delimiter", value=detected_delimiter) else: delimiter = delimiter_options[delimiter_choice] # Quote character quote_options = { 'Double Quote (")': '"', "Single Quote (')": "'", 'None': '' } quote_choice = st.selectbox("Quote Character", options=list(quote_options.keys())) quotechar = quote_options[quote_choice] # Header option has_header = st.checkbox("File has header", value=True) # Preview data st.subheader("Preview Data") df_preview = preview_csv(file_path, delimiter, quotechar, has_header) if df_preview is not None: st.dataframe(df_preview) # Improved Column Type UI st.subheader("Column Types") # Auto-detect toggle auto_detect = st.checkbox("Auto-detect column types", value=True) if auto_detect: column_types = get_column_types(df_preview) # Display auto-detected types in a table format type_df = pd.DataFrame({ 'Column Name': column_types.keys(), 'Detected Type': column_types.values() }) st.table(type_df) else: # Manual column type selection with improved UI sql_types = ['INTEGER', 'DOUBLE', 'VARCHAR', 'BOOLEAN', 'TIMESTAMP', 'DATE'] column_types = {} # Create a container for the column type selection with st.container(): # Use tabs to organize column types by category st.markdown("#### Configure Column Types") # Create a DataFrame for the column type selection type_data = [] for col in df_preview.columns: # Get sample values for the column sample_values = df_preview[col].head(3).tolist() sample_str = ", ".join(str(x) for x in sample_values) # Auto-detect initial type initial_type = get_column_types(df_preview)[col] type_data.append({ "Column": col, "Sample Values": sample_str, "Type": initial_type }) # Create selection UI for i, row in enumerate(type_data): col1, col2, col3 = st.columns([2, 3, 2]) with col1: st.text(row["Column"]) with col2: st.text(f"Sample: {row['Sample Values'][:50]}...") with col3: column_types[row["Column"]] = st.selectbox( "Type", options=sql_types, index=sql_types.index(row["Type"]) if row["Type"] in sql_types else 0, key=f"type_{i}", label_visibility="collapsed" ) # Add quick type selection buttons st.markdown("#### Quick Type Selection") col1, col2, col3, col4 = st.columns(4) with col1: if st.button("All VARCHAR"): for col in df_preview.columns: column_types[col] = "VARCHAR" st.rerun() with col2: if st.button("All INTEGER"): for col in df_preview.columns: column_types[col] = "INTEGER" st.rerun() with col3: if st.button("All DOUBLE"): for col in df_preview.columns: column_types[col] = "DOUBLE" st.rerun() with col4: if st.button("Reset to Auto-detected"): column_types = get_column_types(df_preview) st.rerun() # Import to DuckDB with specified options if st.button("Import CSV", type="primary"): try: conn = duckdb.connect("flatfiles.db") # Create table name from file name table_name = Path(file_path).stem.lower().replace(" ", "_") # Show selected configuration st.write("Configuration Summary:") config_df = pd.DataFrame({ 'Setting': ['Table Name', 'Delimiter', 'Quote Character', 'Has Header'], 'Value': [table_name, delimiter, quotechar, has_header] }) st.dataframe(config_df) # Show column types st.write("Column Types:") types_df = pd.DataFrame({ 'Column': column_types.keys(), 'Type': column_types.values() }) st.dataframe(types_df) # Construct CREATE TABLE statement with column types columns_def = ", ".join([f'"{col}" {dtype}' for col, dtype in column_types.items()]) create_table_sql = f""" CREATE TABLE IF NOT EXISTS {table_name} ( {columns_def} ) """ conn.execute(create_table_sql) # Import data copy_sql = f""" COPY {table_name} FROM '{file_path}' (DELIMITER '{delimiter}', HEADER {str(has_header).lower()}, QUOTE '{quotechar if quotechar else ""}') """ conn.execute(copy_sql) conn.close() # Store DuckDB parameters st.session_state.connection_params = {"path": "flatfiles.db"} st.success(f"CSV file imported as table: {table_name}") except Exception as e: st.error(f"Error importing CSV: {str(e)}") elif file_path: st.error("File not found. Please check the path and try again.") # Special handling for MSSQL to include driver selection elif st.session_state.selected_db.lower() == "mssql": params = get_connection_params(st.session_state.selected_db) st.session_state.connection_params = {} for param, default_value in params.items(): if param != 'driver': st.session_state.connection_params[param] = ( st.text_input( param, str(default_value), type="password" if param == "password" else "default", key=f"create_{param}" ) ) drivers = [driver for driver in pyodbc.drivers()] driver = st.selectbox( "Select SQL Server Driver", drivers, key="driver_select_create" ) st.session_state.connection_params['driver'] = driver else: # Handle other database types normally params = get_connection_params(st.session_state.selected_db) st.session_state.connection_params = {} for param, default_value in params.items(): st.session_state.connection_params[param] = ( st.text_input( param, str(default_value), type="password" if param == "password" else "default", key=f"create_{param}" ) ) col1, col2 = st.columns(2) # Test connection button with col1: if st.button("Test Connection", key="test_conn_create"): if st.session_state.selected_db == "CSV": conn = create_connection("duckdb", {"path": "flatfiles.db"}) else: conn = create_connection(st.session_state.selected_db, st.session_state.connection_params) if conn: st.success("Connection successful!") # Save connection button with col2: if st.button("Save Connection", key="save_conn_create"): if st.session_state.selected_db == "CSV": save_connection( st.session_state.connection_name, "duckdb", {"path": "flatfiles.db"} ) else: save_connection( st.session_state.connection_name, st.session_state.selected_db, st.session_state.connection_params ) st.success(f"Connection '{st.session_state.connection_name}' saved successfully!") with tab2: st.subheader("Manage Saved Connections") saved_connections = load_saved_connections() if saved_connections: selected_connection = st.selectbox( "Select a connection to manage", list(saved_connections.keys()), index=None, placeholder="Choose a connection...", key="connection_select_manage" ) if selected_connection: conn_details = saved_connections[selected_connection] col1, col2 = st.columns(2) with col1: if st.button("Edit Connection", key="edit_conn_btn"): st.session_state['editing_connection'] = selected_connection st.session_state['editing_details'] = conn_details st.rerun() with col2: if st.button("Delete Connection", key="delete_conn_btn"): delete_connection(selected_connection) st.success(f"Connection '{selected_connection}' deleted successfully!") st.rerun() if st.session_state.get('editing_connection') == selected_connection: st.subheader("Edit Connection") new_connection_name = st.text_input( "Connection Name", selected_connection, key="edit_connection_name" ) new_params = {} for param, value in conn_details['params'].items(): new_params[param] = st.text_input( param, value, type="password" if param == "password" else "default", key=f"edit_{param}" ) col1, col2, col3 = st.columns(3) with col1: if st.button("Test Connection", key="test_conn_edit"): conn = create_connection(conn_details['type'], new_params) if conn: st.success("Connection successful!") with col2: if st.button("Save Changes", key="save_changes_btn"): if new_connection_name != selected_connection: delete_connection(selected_connection) save_connection(new_connection_name, conn_details['type'], new_params) st.success("Changes saved successfully!") st.session_state.pop('editing_connection', None) st.session_state.pop('editing_details', None) st.rerun() with col3: if st.button("Cancel", key="cancel_edit_btn"): st.session_state.pop('editing_connection', None) st.session_state.pop('editing_details', None) st.rerun() else: st.info("No saved connections found.") if __name__ == "__main__": main()
"use client"; import { motion } from "framer-motion"; import Image from "next/image"; import HeroSection from "./component/HeroSection"; import Navbar from "./component/Navbar"; import Aboutsection from "./component/Aboutsection"; import ProjectSection from "./component/ProjectSection"; import EmailSection from "./component/EmailSection"; import Footer from "./component/Footer"; export default function Home() { return ( <main className="flex min-h-screen flex-col bg-fixed bg-cover bg-center bg-no-repeat" style={{ backgroundImage: "url('/gif.gif')" }} > <div className="container mx-auto px-12 py-4"> {/* Navbar Animation */} <motion.div initial={{ y: -100, opacity: 0 }} animate={{ y: 0, opacity: 1 }} transition={{ type: "spring", stiffness: 70, damping: 20 }} > <Navbar /> </motion.div> {/* Hero Section Animation */} <motion.div initial={{ opacity: 0, scale: 0.8 }} animate={{ opacity: 1, scale: 1 }} transition={{ duration: 0.8, ease: "easeOut" }} > <HeroSection /> </motion.div> {/* About Section Animation */} <motion.div initial={{ x: -200, opacity: 0 }} whileInView={{ x: 0, opacity: 1 }} viewport={{ once: true }} transition={{ type: "spring", stiffness: 50, damping: 20 }} > <Aboutsection /> </motion.div> {/* Project Section Animation */} <motion.div initial={{ y: 100, opacity: 0 }} whileInView={{ y: 0, opacity: 1 }} viewport={{ once: true }} transition={{ type: "tween", duration: 0.8 }} > <ProjectSection /> </motion.div> {/* Email Section Animation */} <motion.div initial={{ rotate: -10, opacity: 0 }} whileInView={{ rotate: 0, opacity: 1 }} viewport={{ once: true }} transition={{ type: "spring", stiffness: 60, damping: 15 }} > <EmailSection /> </motion.div> </div> {/* Footer Animation */} <motion.div initial={{ y: 100, opacity: 0 }} animate={{ y: 0, opacity: 1 }} transition={{ type: "spring", stiffness: 50, damping: 20 }} > <Footer /> </motion.div> </main> ); }
import { auth, database } from "../firebase"; interface IUser { clientId?: string; activity?: string; address?: string; addressCompany?: string; birthdate?: string; companyActivity?: string; companyAddress?: string; companyName?: string; companyPhone?: string; companySiren?: string; companySocialDenomination?: string; contactEmail?: string; email?: string; picture?: string; firstName?: string; id: string; isComplete?: boolean; lastName?: string; userType?: string; } const addUserToAuthentication = async (user) => { return (await auth.auth.createUserWithEmailAndPassword(user.email, "123456789")).user?.uid; }; const addUserToCollection = async (user, userId) => { return await database.user.doc(userId).set({ id: userId, ...user }); }; const users: Omit<IUser, "id">[] = [ { email: "john.peter@azinove.com", lastName: "Peter", firstName: "John", picture: "https://avatarfiles.alphacoders.com/226/thumb-226055.png", isComplete: true, birthdate: "2000-01-28", companyActivity: "Développement web", companyAddress: "{'label':'22 Rue d'Eschau, Ostwald, France','value':{'description':'22 Rue d'Eschau, Ostwald, France','matched_substrings':[{'length':2,'offset':0},{'length':12,'offset':3}],'place_id':'ChIJ58NGQHbLlkcR6x-QcdEw7KM','reference':'ChIJ58NGQHbLlkcR6x-QcdEw7KM','structured_formatting':{'main_text':'22 Rue d'Eschau','main_text_matched_substrings':[{'length':2,'offset':0},{'length':12,'offset':3}],'secondary_text':'Ostwald, France'},'terms':[{'offset':0,'value':'22'},{'offset':3,'value':'Rue d'Eschau'},{'offset':17,'value':'Ostwald'},{'offset':26,'value':'France'}],'types':['street_address','geocode']}}", companyName: "Azinove", companyPhone: "01 78 34 12 89", companySiren: "127-938-502", companySocialDenomination: "Agence web", contactEmail: "john.peter@azinove.com", userType: "professional" }, { email: "elio.alexis@azinove.com", lastName: "Elio", firstName: "Elio", picture: "https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/3573926f-d599-49ee-b873-67080338e9a8/ddc4x6j-3d08bbe8-8f79-4121-a7c4-b43b9dc1f326.jpg/v1/fill/w_1280,h_1278,q_75,strp/profile_picture_maker_by_zoom2636_ddc4x6j-fullview.jpg?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7ImhlaWdodCI6Ijw9MTI3OCIsInBhdGgiOiJcL2ZcLzM1NzM5MjZmLWQ1OTktNDllZS1iODczLTY3MDgwMzM4ZTlhOFwvZGRjNHg2ai0zZDA4YmJlOC04Zjc5LTQxMjEtYTdjNC1iNDNiOWRjMWYzMjYuanBnIiwid2lkdGgiOiI8PTEyODAifV1dLCJhdWQiOlsidXJuOnNlcnZpY2U6aW1hZ2Uub3BlcmF0aW9ucyJdfQ.MnDAlQ-vFE_VZWWvg-_kYSvPBiJf_XrTVztIsBoAAd4", isComplete: true, birthdate: "2002-01-28", companyActivity: "Développement web", companyAddress: "{'label':'22 Rue d'Eschau, Ostwald, France','value':{'description':'22 Rue d'Eschau, Ostwald, France','matched_substrings':[{'length':2,'offset':0},{'length':12,'offset':3}],'place_id':'ChIJ58NGQHbLlkcR6x-QcdEw7KM','reference':'ChIJ58NGQHbLlkcR6x-QcdEw7KM','structured_formatting':{'main_text':'22 Rue d'Eschau','main_text_matched_substrings':[{'length':2,'offset':0},{'length':12,'offset':3}],'secondary_text':'Ostwald, France'},'terms':[{'offset':0,'value':'22'},{'offset':3,'value':'Rue d'Eschau'},{'offset':17,'value':'Ostwald'},{'offset':26,'value':'France'}],'types':['street_address','geocode']}}", companyName: "Azinove", companyPhone: "01 78 34 12 89", companySiren: "127-931-532", companySocialDenomination: "Agence web", contactEmail: "elio.alexis@azinove.com", userType: "professional" } ]; export const upUsers = async (): Promise<void> => { const usersId = await Promise.all( users.map(async (user) => { // It is currently not working with two promises ?! return await addUserToAuthentication(user); // await addUserToCollection(user); }) ); await Promise.all( users.map(async (user, i) => { await addUserToCollection(user, usersId[i]); }) ); };
package com.example.spring_jwt_tutorial.model; import jakarta.persistence.*; import lombok.*; import java.io.Serializable; import java.util.List; @Entity @Setter @Getter @AllArgsConstructor @NoArgsConstructor public class Role implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String code; @ManyToMany @JoinTable(name = "role_permission", joinColumns = { @JoinColumn(name = "role_id", referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "permission_id", referencedColumnName = "id") } ) private List<Permission> permissions; @ManyToMany(mappedBy = "roles") private List<User> users; }
import React, { useContext, useRef, useState } from 'react' import axios from 'axios'; import { UserContext } from '../context/userContext'; import Cookies from 'universal-cookie'; import { useNavigate } from 'react-router-dom'; import Swal from 'sweetalert2'; const App = () => { const cookies = new Cookies(null, { path: '/' }); const navigate = useNavigate(); const [active, setActive] = useState(false); const [endPoint, header] = useContext(UserContext); const emailRef = useRef(); const passwordRef = useRef(); const regNameRef = useRef(); const regSnameRef = useRef(); const regNumRef = useRef(); const regEmailRef = useRef(); const regPassRef = useRef(); const loginSubmit = (e) => { e.preventDefault(); axios.post(`${endPoint}/auth`, { email: emailRef.current.value, password: passwordRef.current.value }, header) .then(res => { if (res.status === 201 || res.status === 200) { cookies.set("x-auth-token", res.data); localStorage.setItem("user", 'true'); Swal.fire({ title: "Login is successfull", icon: "success", preConfirm: () => { navigate('/') } }) } console.log(res.data) }) .catch(err => console.log(err)) } const registerSubmit = (e) => { e.preventDefault(); axios.post(`${endPoint}/register`, { name: regNameRef.current.value, surname: regSnameRef.current.value, email: regEmailRef.current.value, phone: regNumRef.current.value, password: regPassRef.current.value }, header) .then(res => { if (res.status === 201 || res.status === 200) { cookies.set("x-auth-token", res.data); localStorage.setItem("user", 'true'); Swal.fire({ title: "Register is successfull", icon: "success", preConfirm: () => { navigate('/') } }) } console.log(res.data) }) .catch(err => { console.log(err); if (err.status === 400 || err.status === 401) { let alertText = ""; if (err.response.data.match("password")) { alertText = err.response.data } else if (err.response.data.match("empty")) { alertText = err.response.data } else if (err.response.data.match("email")) { alertText = err.response.data } else if (err.response.data.match("already")) { alertText = err.response.data } Swal.fire({ title: alertText, icon: "error" }) } }) } return ( <div className='account-info'>z <div className={active ? "active container" : "container"}> <div className="form-container sign-up"> <form onSubmit={registerSubmit}> <h1>Create Account</h1> <div className="social-icons"> <a href="#" className="icon"><i className="fa-brands fa-google-plus-g" /></a> <a href="#" className="icon"><i className="fa-brands fa-facebook-f" /></a> <a href="#" className="icon"><i className="fa-brands fa-github" /></a> <a href="#" className="icon"><i className="fa-brands fa-linkedin-in" /></a> </div> <span>or use your email for registeration</span> <input ref={regNameRef} type="text" placeholder="Name" /> <input ref={regSnameRef} type="text" placeholder="Surname" /> <input ref={regNumRef} type="phone" placeholder="Phone" /> <input ref={regEmailRef} type="email" placeholder="Email" /> <input ref={regPassRef} type="password" placeholder="Password" /> <button>Sign Up</button> </form> </div> <div className="form-container sign-in"> <form onSubmit={loginSubmit}> <h1>Sign In</h1> <div className="social-icons"> <a href="#" className="icon"><i className="fa-brands fa-google-plus-g" /></a> <a href="#" className="icon"><i className="fa-brands fa-facebook-f" /></a> <a href="#" className="icon"><i className="fa-brands fa-github" /></a> <a href="#" className="icon"><i className="fa-brands fa-linkedin-in" /></a> </div> <span>or use your email password</span> <input type="email" ref={emailRef} placeholder="Email" /> <input type="password" ref={passwordRef} placeholder="Password" /> <a href="#">Forget Your Password?</a> <button>Sign In</button> </form> </div> <div className="toggle-container"> <div className="toggle"> <div className="toggle-panel toggle-left"> <h1>Welcome Back!</h1> <p>Enter your personal details to use all of site features</p> <button className="hidden" onClick={() => setActive(false)}>Sign In</button> </div> <div className="toggle-panel toggle-right"> <h1>Hello, Friend!</h1> <p>Register with your personal details to use all of site features</p> <button className="hidden" onClick={() => setActive(true)}>Sign Up</button> </div> </div> </div> </div> </div> ) } export default App
import React, { useState } from 'react'; import { format, differenceInBusinessDays } from 'date-fns'; import { HolidayType } from '../types/holiday'; import type { DateRange } from 'react-day-picker'; interface HolidayFormProps { selectedDate: Date | undefined; selectedRange: DateRange | undefined; onSubmit: (type: HolidayType, description: string) => void; onCancel: () => void; } export function HolidayForm({ selectedDate, selectedRange, onSubmit, onCancel }: HolidayFormProps) { const [type, setType] = useState<HolidayType>('annual-leave'); const [description, setDescription] = useState(''); if (!selectedDate && !selectedRange?.from && !selectedRange?.to) return null; const businessDays = selectedRange?.from && selectedRange?.to ? differenceInBusinessDays(selectedRange.to, selectedRange.from) + 1 : 1; return ( <div className="p-4 bg-white rounded-lg shadow-md"> <h3 className="text-lg font-semibold mb-4"> {selectedDate ? ( `Add Holiday - ${format(selectedDate, 'dd MMMM yyyy')}` ) : ( selectedRange?.from && selectedRange?.to ? ( `Add Holiday - ${format(selectedRange.from, 'dd MMM yyyy')} to ${format(selectedRange.to, 'dd MMM yyyy')} (${businessDays} working days)` ) : '' )} </h3> <div className="space-y-4"> <div> <label className="block text-sm font-medium text-gray-700">Type</label> <select value={type} onChange={(e) => setType(e.target.value as HolidayType)} className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500" > <option value="annual-leave">Annual Leave</option> <option value="public-holiday">Public Holiday</option> <option value="workplace-closure">Workplace Closure</option> </select> </div> <div> <label className="block text-sm font-medium text-gray-700">Description</label> <input type="text" value={description} onChange={(e) => setDescription(e.target.value)} className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500" placeholder="Optional description" /> </div> <div className="flex justify-end gap-2"> <button onClick={onCancel} className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50" > Cancel </button> <button onClick={() => onSubmit(type, description)} className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700" > Save </button> </div> </div> </div> ); }
import { Lead } from '../../entities/lead.entity'; import { Repository, UpdateResult } from 'typeorm'; import { InjectRepository } from '@nestjs/typeorm'; import { FindAllLeadCommand, ILead } from '../find-all-lead.command'; import { CommandHandler, ICommandHandler } from '@nestjs/cqrs'; import { Injectable, BadRequestException } from '@nestjs/common'; import { Interaction } from 'interaction/entities/interaction.entity'; @Injectable() @CommandHandler(FindAllLeadCommand) export class FindAllLeadHandler implements ICommandHandler<FindAllLeadCommand> { constructor( @InjectRepository(Lead) private readonly leadRepository: Repository<Lead>, ) {} async execute(command: FindAllLeadCommand): Promise<ILead[]> { try { const aggregatedLeadsData = await this.leadRepository .createQueryBuilder('lead') .leftJoin( Interaction, 'interaction', 'interaction.lead_id = lead.lead_id', ) .select([ 'lead.lead_id', 'lead.lead_name', 'lead.lead_status', 'lead.email', 'lead.source', 'lead.added_date', 'lead.updated_date', 'COUNT(interaction.lead_id) AS interaction_count', ]) .groupBy('lead.lead_id') .getRawMany(); const structuredLeadsData = aggregatedLeadsData.map((data) => { return { lead_id: data.lead_lead_id, lead_name: data.lead_lead_name, email: data.lead_email, lead_status: data.lead_lead_status, source: data.lead_source, added_date: data.lead_added_date, updated_date: data.lead_updated_date, interaction_count: data.interaction_count, }; }); return structuredLeadsData; } catch (error) { throw new BadRequestException(error.message); } } }
import 'package:flutter/material.dart'; import 'package:nb_utils/nb_utils.dart'; import '../../../../components/cached_image_widget.dart'; import '../../../../components/price_widget.dart'; import '../../../../components/view_all_label_component.dart'; import '../../../../main.dart'; import '../../../../models/booking_detail_response.dart'; class AddonComponent extends StatefulWidget { final List<ServiceAddon> serviceAddon; AddonComponent({ required this.serviceAddon, }); @override _AddonComponentState createState() => _AddonComponentState(); } class _AddonComponentState extends State<AddonComponent> { double imageHeight = 60; @override void initState() { super.initState(); } @override void setState(fn) { if (mounted) super.setState(fn); } @override Widget build(BuildContext context) { if (widget.serviceAddon.isEmpty) return Offstage(); return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ ViewAllLabel( label: languages.addOns, list: [], onTap: () {}, ), AnimatedListView( listAnimationType: ListAnimationType.FadeIn, fadeInConfiguration: FadeInConfiguration(duration: 2.seconds), shrinkWrap: true, itemCount: widget.serviceAddon.length, padding: EdgeInsets.zero, physics: NeverScrollableScrollPhysics(), itemBuilder: (_, i) { ServiceAddon data = widget.serviceAddon[i]; return Stack( children: [ Container( width: context.width(), padding: EdgeInsets.all(16), margin: EdgeInsets.only(bottom: 16), decoration: boxDecorationWithRoundedCorners( borderRadius: radius(), backgroundColor: context.cardColor, border: appStore.isDarkMode ? Border.all(color: context.dividerColor) : null, ), child: Row( children: [ CachedImageWidget( url: data.serviceAddonImage, height: imageHeight, fit: BoxFit.cover, radius: defaultRadius, ), 16.width, Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Marquee( directionMarguee: DirectionMarguee.oneDirection, child: Text(data.name.validate(), style: boldTextStyle()), ), 2.height, PriceWidget( price: data.price.validate(), hourlyTextColor: Colors.white, size: 12, ), ], ), ], ).expand(), ], ), ), Positioned( height: imageHeight + 32, right: 32, child: Center( child: Icon( Icons.check_circle_outline_outlined, size: 24, color: Colors.green, ), ), ).visible(data.status.getBoolInt()) ], ); }, ) ], ); } }
package Marketplace.Types.MsgToOrderFn; import Marketplace.Constant.Constants; import Marketplace.Constant.Enums; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.Getter; import lombok.Setter; import org.apache.flink.statefun.sdk.java.TypeName; import org.apache.flink.statefun.sdk.java.types.SimpleType; import org.apache.flink.statefun.sdk.java.types.Type; @Getter @Setter public class PaymentNotification { private static final ObjectMapper mapper = new ObjectMapper(); public static final Type<PaymentNotification> TYPE = SimpleType.simpleImmutableTypeFrom( TypeName.typeNameOf(Constants.TYPES_NAMESPACE, "PaymentNotification"), mapper::writeValueAsBytes, bytes -> mapper.readValue(bytes, PaymentNotification.class)); @JsonProperty("orderId") private int orderId; @JsonProperty("orderStatus") private Enums.OrderStatus orderStatus; @JsonCreator public PaymentNotification(@JsonProperty("orderId") int orderId, @JsonProperty("orderStatus") Enums.OrderStatus orderStatus) { this.orderId = orderId; this.orderStatus = orderStatus; } }
import React, {useState, useEffect} from 'react'; import {View, Text, StyleSheet, Image, TouchableOpacity} from 'react-native'; import {RouteProp, useRoute} from '@react-navigation/native'; import axios from 'axios'; import {API_URL} from '@env'; import {RecommendItemParamList} from '../../components/Recommend/RecommendItem'; import DetailInfo from '../../components/Detail/DetailInfo'; import DetailReview from '../../components/Detail/DetailReview'; import AsyncStorage from '@react-native-async-storage/async-storage'; import {useSelector} from 'react-redux'; import CommonModal from '../../components/common/Modal'; type DetailScreenRouteProp = RouteProp<RecommendItemParamList, 'Detail'>; export type PillData = { id: number; name: string; expirationDate: string; appearance: string; doseAmount: string; storageMethod: string; doseGuide: string; functionality: string; imageUrl: string; isInWishlist: boolean; isInKit: boolean; }; const DetailScreen: React.FC = () => { const [selectedTab, setSelectedTab] = useState<'info' | 'review'>('info'); const [pillData, setPillData] = useState<PillData | null>(null); const route = useRoute<DetailScreenRouteProp>(); const {id} = route.params; const [token, setToken] = useState<string | null>(null); const [myWishList, setMyWishList] = useState<boolean>(false); const [myKit, setMyKit] = useState<boolean>(false); const [pillImageUrl, setPillImageUrl] = useState<string>() const userSeq = useSelector((state: {userSeq: number | null}) => state.userSeq); const [isModalVisible, setModalVisible] = useState(false); // 모달 상태 추가 const [modalMessage, setModalMessage] = useState(''); // 모달 메시지 상태 추가 const [modalImage, setModalImage] = useState<any>(null); // 모달 이미지 상태 추가 useEffect(() => { const fetchToken = async () => { const storedToken = await AsyncStorage.getItem('jwt_token'); setToken(storedToken); }; fetchToken(); }, []); // 보충제 데이터 들고오기 (상세 데이터) useEffect(() => { const fetchPillData = async () => { if (!token) return; try { const response = await axios.get(`${API_URL}/api/v1/supplement/${id}`, { headers: { access: `${token}`, }, }); const data = response.data; setPillData({ id: data.supplementSeq, name: data.pillName, expirationDate: data.expirationDate, appearance: data.appearance, doseAmount: data.doseAmount, storageMethod: data.storageMethod, doseGuide: data.doseGuide, functionality: data.functionality, imageUrl: data.imageUrl, isInWishlist: data.inWishlist, isInKit: data.inMykit, }); setMyWishList(data.inWishlist); setMyKit(data.inMykit); } catch (error) { console.log(error); } }; fetchPillData(); }, [id, token]); if (!pillData) { return ( <View style={styles.loading}> <Text>Loading...</Text> </View> ); } const handleWishListBtn = async () => { try { if (myWishList) { // 위시리스트에서 제거 await axios.delete(`${API_URL}/api/v1/wishlist`, { headers: { access: `${token}`, }, params: { userSeq, supplementSeq: id, }, }); setMyWishList(false); setModalMessage('위시리스트에서 제거되었습니다!'); setModalImage(require('../../assets/wishlistremove.png')); } else { // 위시리스트에 추가 await axios.post( `${API_URL}/api/v1/wishlist`, {userSeq, supplementSeq: id}, { headers: { access: `${token}`, }, }, ); setMyWishList(true); setModalMessage('위시리스트에 추가되었습니다!'); setModalImage(require('../../assets/wishlistadd.png')); } setModalVisible(true); // 1초 후에 모달을 숨김 setTimeout(() => { setModalVisible(false); }, 2000); } catch (error) { console.log(error); } }; const handleKitBtn = async () => { try { if (myKit) { // 복용 중 목록에서 제거 const response = await axios.delete(`${API_URL}/api/v1/cabinet`, { headers: { access: `${token}`, }, params: { supplementSeq: id, }, }); // 응답 상태를 로그로 확인 console.log('제거', response.status); if (response.status === 200 || response.status === 204) { setMyKit(false); setModalMessage('마이키트에서 제거되었습니다!'); setModalImage(require('../../assets/wishlistremove.png')); } } else { // 복용 중 목록에 추가 const response = await axios.post( `${API_URL}/api/v1/cabinet`, {supplementSeq: id}, { headers: { access: `${token}`, }, }, ); // 응답 상태를 로그로 확인 console.log('추가', response.status); if (response.status === 200) { setMyKit(true); setModalMessage('마이키트에 추가되었습니다!'); setModalImage(require('../../assets/wishlistadd.png')); } } setModalVisible(true); // 2초 후에 모달을 숨김 setTimeout(() => { setModalVisible(false); }, 2000); } catch (error) { console.log(error); } }; return ( <View style={styles.container}> <View style={styles.infoBox}> {/* <Image source={ pillData.imageUrl && pillData.imageUrl.trim() !== '' ? { uri: pillData.imageUrl } : require('../../assets/noImage.png') } style={styles.image} /> */} <Image source={{uri: pillData.imageUrl}} style={styles.image} /> <View style={styles.infoContainer}> <Text style={styles.pillName}> {pillData.name} </Text> <View style={styles.rowContainer}> <TouchableOpacity onPress={handleWishListBtn}> <Image source={ myWishList ? require('../../assets/heart1.png') // 위시리스트에 있을 때 : require('../../assets/heart2.png') // 위시리스트에 없을 때 } style={styles.wishListBtn} resizeMode="contain" /> </TouchableOpacity> <TouchableOpacity onPress={handleKitBtn}> <Text style={styles.dosageText}> {myKit ? '복용 중' : '복용 안 함'} </Text> </TouchableOpacity> </View> </View> </View> <View style={styles.canSelectMenu}> <TouchableOpacity style={ selectedTab === 'info' ? styles.selectedTextBox : styles.notSelectedTextBox } onPress={() => setSelectedTab('info')}> <Text style={ selectedTab === 'info' ? styles.selectedText : styles.notSelectedText }> 상세 정보 </Text> <View style={selectedTab === 'info' ? styles.selectedCheck : null}></View> </TouchableOpacity> <TouchableOpacity style={ selectedTab === 'review' ? styles.selectedTextBox : styles.notSelectedTextBox } onPress={() => setSelectedTab('review')}> <Text style={ selectedTab === 'review' ? styles.selectedText : styles.notSelectedText }> 리뷰 </Text> <View style={ selectedTab === 'review' ? styles.selectedCheck : null }></View> </TouchableOpacity> </View> <View style={styles.selectedContent}> {selectedTab === 'info' ? ( <DetailInfo pillData={pillData} /> ) : ( <DetailReview id={pillData.id} /> )} </View> {/* 공통 모달 컴포넌트 사용 */} <CommonModal visible={isModalVisible} message={modalMessage} onClose={() => setModalVisible(false)} imageSource={modalImage} /> </View> ); }; const styles = StyleSheet.create({ loading: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff', }, container: { flex: 1, backgroundColor: '#fff', paddingLeft: 20, paddingRight: 20, }, infoBox: { height: '20%', flexDirection: 'row', }, image: { width: '40%', marginTop: 10, resizeMode: 'contain', }, pillName: { fontSize: 15, color: 'black', marginTop: 40, marginRight: 10, maxWidth: '80%', }, infoContainer: { display: 'flex', flexDirection: 'column', gap: 20, }, rowContainer: { flexDirection: 'row', alignItems: 'center', marginTop: 10, }, dosageText: { marginLeft: 10, }, canSelectMenu: { flexDirection: 'row', marginTop: 20, justifyContent: 'center', }, selectedTextBox: { width: '50%', height: 50, borderWidth: 1, borderColor: '#939185', justifyContent: 'center', alignItems: 'center', }, notSelectedTextBox: { width: '50%', height: 50, borderWidth: 1, borderColor: '#939185', justifyContent: 'center', alignItems: 'center', }, selectedText: { fontSize: 20, color: 'black', }, notSelectedText: { fontSize: 20, color: '#939185', }, selectedCheck: { width: 40, height: 10, marginTop: 11, backgroundColor: '#D3EBCD', borderTopLeftRadius: 7, borderTopRightRadius: 7, }, selectedContent: { height: '65%', borderWidth: 1, borderColor: '#939185', borderBlockStartColor: '#F7F7F7', }, wishListBtn: { width: 30, }, }); export default DetailScreen;
import {RegistrationStore} from './registration.js'; import {DatasetStore, extractIri, extractIris} from './dataset.js'; import {dereference, fetch, HttpError, NoDatasetFoundAtUrl} from './fetch.js'; import DatasetExt from 'rdf-ext/lib/Dataset'; import Pino from 'pino'; import {Valid, Validator} from './validator.js'; import {crawlCounter} from './instrumentation.js'; import {rate, RatingStore} from './rate.js'; export class Crawler { constructor( private registrationStore: RegistrationStore, private datasetStore: DatasetStore, private ratingStore: RatingStore, private validator: Validator, private logger: Pino.Logger ) {} /** * Crawl all registered URLs that were last read before `dateLastRead`. */ public async crawl(dateLastRead: Date) { const registrations = await this.registrationStore.findRegistrationsReadBefore(dateLastRead); for (const registration of registrations) { this.logger.info(`Crawling registration URL ${registration.url}...`); let datasets: DatasetExt[] = []; let statusCode = 200; let isValid = false; try { const data = await dereference(registration.url); const validationResult = await this.validator.validate(data); isValid = validationResult.state === 'valid'; if (isValid) { this.logger.info(`${registration.url} passes validation`); datasets = await fetch(registration.url); await this.datasetStore.store(datasets); datasets.map(async dataset => { const dcatValidationResult = await this.validator.validate(dataset); const rating = rate(dcatValidationResult as Valid); await this.ratingStore.store(extractIri(dataset), rating); }); } else { this.logger.info(`${registration.url} does not pass validation`); } } catch (e) { if (e instanceof HttpError) { statusCode = e.statusCode; this.logger.info( `${registration.url} returned HTTP error ${statusCode}` ); } if (e instanceof NoDatasetFoundAtUrl) { // Request was successful, but no datasets exist any longer at the URL. this.logger.info(`${registration.url} has no datasets`); } } crawlCounter.add(1, { status: statusCode, valid: isValid, }); const updatedRegistration = registration.read( [...extractIris(datasets).keys()], statusCode, isValid ); await this.registrationStore.store(updatedRegistration); } } }
test.sy0{ -- Basic tests without core -- Type definitions public all x ~~ foo[x] ~> tree[x]. public option[x] ::= .none | .some(x). public boolean ::= .true | .false. -- Tree type public tree[x] ::= .empty | .node(foo[x],x,tree[x]). -- Person type public person ::= .noone | someone{ name:string. spouse : ref option[person]. }. nn:(person)=>option[string]. nn(.noone) => .none. nn(someone{name=N}) => .some(N). spouse:(person) => option[person]. spouse(P) => P.spouse!. -- A small contract public contract all x ~~ lS[x] ::= { large : x. small : x. } public implementation lS[integer] => {. large=10. small=-10. .} largest:all x ~~ lS[x] |: ()=>x. largest() => large. contract all x ~~ ar[x] ::= { plus:(x,x)=>x. } double:all x ~~ ar[x] |: (x)=>x. double(X) => plus(X,X). quad:all x ~~ ar[x] |: (x)=>x. quad(X) => double(double(X)). dbl:all x ~~ ((x)=>x)=>(x)=>x. dbl(F) => (X)=>F(F(X)). qd:all x ~~ ar[x] |: (x)=>x. qd(X) => dbl(double)(X). implementation ar[integer] => { plus(x,y) => _int_plus(x,y). } dblInt:(integer)=>integer. dblInt(X) => plus(X,X). }
A web app built with [React](https://reactjs.org/) and [Express](https://expressjs.com/). # What does empocketer do? _Empocketer_ allows anyone with a [Pocket](https://getpocket.com) account to log in to the app, and create lists of sites with RSS or Atom feeds. Every two hours it checks all those feeds for new content, and pushes new articles to the Pocket accounts of the relevant users. # How does it work? Essentially, Empocketer uses a [React](https://reactjs.org/) front end with an [Express](https://expressjs.com/) based API and [nedb-core](https://github.com/nedbhq/nedb-core) database as the back end, using the [Pocket API](https://getpocket.com/developer/) to interact with Pocket. Empocketer uses [Passport](http://www.passportjs.org) and the `passport-pocket` package to handle logins, using Pocket's API based on OAuth. Routing uses [Express](https://expressjs.com/), and the [Handlebars](http://handlebarsjs.com/) template engine. The database is embedded in the app using [nedb-core](https://github.com/nedbhq/nedb-core) and feeds are checked using the ever-reliable [feedparser](https://www.npmjs.com/package/feedparser) package. # Requirements You will need to [register your app with Pocket](https://getpocket.com/developer/) and get a Pocket Consumer Key. You also need an smtp email host. I recommend [Mailgun](https://www.mailgun.com/) - it's free unless you're sending more than 10,000 emails per month, which seems rather reasonable! # Installing your own version 1. save the code to the directory you will be serving it from 2. copy settings-example.json to a new file called settings.json, and fill it in with your own real values. 3. `npm install` 4. `npm start` 5. point your web browser to `localhost:3000` If you want to run it on a server (i.e. not to just test on your own machine) you'll need to set up something like `forever` or `systemd` to keep it running. It will default to run on port 3000 so you'll need to [configure a proxy](https://www.sitepoint.com/configuring-nginx-ssl-node-js/) # Todos * Admin interface, including ability to block users, blacklist certain terms from being used in list names, and possibly ban certain feeds. * Account deletion * more complete installation instructions including hosting config See Issues for any other stuff that's being worked on. # License GPL 3+
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Edit Kegiatan - Manajemen Tugas</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> <style> body { background: url("{{ url_for('static', filename='images/bg2.jpg') }}") no-repeat center center fixed; background-size: cover; color: white; padding: 20px 0; } .container { background: rgba(46, 46, 46, 0.85); padding: 40px; border-radius: 10px; box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3); margin-top: 50px; max-width: 600px; } h1 { color: #29df3f; text-align: center; margin-bottom: 40px; font-weight: bold; } .form-label { color: #29df3f; font-weight: 500; margin-bottom: 8px; } .form-control { background-color: rgba(51, 51, 51, 0.9); color: white; border: 1px solid rgba(41, 223, 63, 0.2); padding: 12px; border-radius: 8px; transition: all 0.3s ease; } .form-control:focus { background-color: rgba(68, 68, 68, 0.9); border-color: #29df3f; box-shadow: 0 0 0 0.25rem rgba(41, 223, 63, 0.25); color: white; } .form-control::placeholder { color: rgba(255, 255, 255, 0.5); } .btn-primary { background-color: #29df3f; color: white; border: none; padding: 12px; font-weight: 500; transition: all 0.3s ease; width: 100%; margin-top: 20px; } .btn-primary:hover { background-color: #27ae60; transform: translateY(-2px); } .alert { margin-bottom: 20px; } .required-field::after { content: " *"; color: #e74c3c; } .form-text { color: rgba(255, 255, 255, 0.7); font-size: 0.875rem; margin-top: 4px; } input[type="date"] { color-scheme: dark; } </style> </head> <body> <div class="container"> <!-- Display Flash Messages --> {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} <div class="alert alert-{{ category }} alert-dismissible fade show" role="alert"> {{ message }} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endfor %} {% endif %} {% endwith %} <h1>Edit Kegiatan</h1> <form method="POST" action="{{ url_for('edit_activity', activity_id=activity.id) }}"> <div class="mb-3"> <label for="kegiatan" class="form-label required-field">Kegiatan</label> <input type="text" class="form-control" id="kegiatan" name="kegiatan" placeholder="Masukkan nama kegiatan" required value="{{ activity.kegiatan }}"> <div class="form-text">Masukkan nama kegiatan yang ingin diedit</div> </div> <div class="mb-3"> <label for="jenis_kegiatan" class="form-label required-field">Jenis Kegiatan</label> <input type="text" class="form-control" id="jenis_kegiatan" name="jenis_kegiatan" placeholder="Masukkan jenis kegiatan" required value="{{ activity.jenis_kegiatan }}"> <div class="form-text">Masukkan jenis kegiatan (misalnya: Kuliah, Praktikum, dll.)</div> </div> <div class="mb-3"> <label for="deadline" class="form-label required-field">Deadline</label> <input type="date" class="form-control" id="deadline" name="deadline" required value="{{ activity.deadline }}"> <div class="form-text">Tentukan batas waktu kegiatan</div> </div> <button type="submit" class="btn btn-primary">Simpan Perubahan</button> </form> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> <script> // Set minimum date as today const today = new Date().toISOString().split('T')[0]; document.getElementById('deadline').setAttribute('min', today); </script> </body> </html>
import React from 'react'; import {BrowserRouter, NavLink, Route} from 'react-router-dom' import UsersPage from './components/UsersPage'; import TodosPage from './components/TodosPage'; import UserItemPage from './components/UserItemPage'; import TodoItemPage from './components/TodoItemPage'; const App = () => { return ( <BrowserRouter> <div> <NavLink to='/users'>Пользователи</NavLink> <NavLink to='/todos'>Список дел</NavLink> <Route path="/users" exact component={UsersPage} /> <Route path="/todos" exact component={TodosPage} /> <Route path="/users/:id" component={UserItemPage} /> <Route path="/todos/:id" component={TodoItemPage} /> </div> </BrowserRouter> ); }; export default App
// // SearchBookInteractor.swift // Book-RIBs // // Created by 이서준 on 2023/04/07. // import RIBs import RxSwift import RxCocoa protocol SearchBookRouting: ViewableRouting { // TODO: Declare methods the interactor can invoke to manage sub-tree via the router. func routeToBookDetail(of isbn13: String) func detachToBookDetail(_ animated: Bool) } protocol SearchBookPresentable: Presentable { var listener: SearchBookPresentableListener? { get set } // TODO: Declare methods the interactor can invoke the presenter to present data. var booksStream: BehaviorRelay<[BookItem]> { get } var isLoading: BehaviorRelay<Bool> { get } } protocol SearchBookListener: AnyObject { // TODO: Declare methods the interactor can invoke to communicate with other RIBs. } final class SearchBookInteractor: PresentableInteractor<SearchBookPresentable>, SearchBookInteractable, SearchBookPresentableListener { private let repository: BookRepository private let serviceProvider: ServiceProviderType weak var router: SearchBookRouting? weak var listener: SearchBookListener? private var page: Int = 1 init( presenter: SearchBookPresentable, repository: BookRepository, serviceProvider: ServiceProviderType ) { self.repository = repository self.serviceProvider = serviceProvider super.init(presenter: presenter) presenter.listener = self } override func didBecomeActive() { super.didBecomeActive() // TODO: Implement business logic here. } override func willResignActive() { super.willResignActive() // TODO: Pause any business logic. } func search(for word: String) { self.page = 1 _ = fetchBookItemsResult(of: word) .do(onNext: { [weak self] _ in self?.presenter.isLoading.accept(false) }) .bind(to: presenter.booksStream) } func paging(of word: String) { self.page += 1 print("page \(page)") _ = fetchBookItemsResult(of: word, page: self.page) .withUnretained(self) .do(onNext: { $0.0.presenter.isLoading.accept(false) }) .map { var current = $0.0.presenter.booksStream.value current.append(contentsOf: $0.1) return current } .bind(to: presenter.booksStream) } func selectedBook(of item: BookItem) { guard let isbn13 = item.isbn13 else { return } router?.routeToBookDetail(of: isbn13) } func detachBookDetailRIB(_ animated: Bool) { router?.detachToBookDetail(animated) } private func fetchBookItemsResult(of word: String, page: Int = 1) -> Observable<[BookItem]> { let fetchResult = repository.fetchSearchResults(of: word, page: page) return Observable<[BookItem]>.create { [weak self] observer in self?.presenter.isLoading.accept(true) fetchResult.sink { result in switch result { case.success(let bookModel): observer.onNext(bookModel.books ?? []) observer.onCompleted() case .failure(let error): print(error.localizedDescription) observer.onError(error) } } return Disposables.create() } } }
library(grid) library(nara) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Load the spritemap for pacman and the ghosts #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ spritemap <- png::readPNG("image/game-sprites.png") if (FALSE) { dim(spritemap) grid.raster(spritemap) } #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #' Extract a sprite from the spritemap #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ extract <- function(row, col) { sprite <- spritemap[1 + (row-1)*16 + 0:15, 457 + (col-1)*16 + 0:15,] alpha <- sprite[,,1] == 1 | sprite[,,2] == 1 | sprite[,,3] == 1 alpha[] <- as.numeric(alpha) new <- c(sprite, alpha) d <- dim(sprite) d[3] <- 4 dim(new) <- d nara::array_to_nr(new) } #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Extract pacman sprites #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ pacman <- list( right = list(extract(1, 1), extract(1, 2), extract(1, 3), extract(1, 2)), left = list(extract(2, 1), extract(2, 2), extract(1, 3), extract(2, 2)), up = list(extract(3, 1), extract(3, 2), extract(1, 3), extract(3, 2)), down = list(extract(4, 1), extract(4, 2), extract(1, 3), extract(4, 2)), rest = list(extract(1, 3), extract(1, 3), extract(1, 3), extract(1, 3)) ) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Extract ghost sprites #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ghost1 <- list( right = list(extract(5, 1), extract(5, 2)), left = list(extract(5, 3), extract(5, 4)), up = list(extract(5, 5), extract(5, 6)), down = list(extract(5, 7), extract(5, 8)) ) ghost2 <- list( right = list(extract(6, 1), extract(6, 2)), left = list(extract(6, 3), extract(6, 4)), up = list(extract(6, 5), extract(6, 6)), down = list(extract(6, 7), extract(6, 8)) ) ghost3 <- list( right = list(extract(7, 1), extract(7, 2)), left = list(extract(7, 3), extract(7, 4)), up = list(extract(7, 5), extract(7, 6)), down = list(extract(7, 7), extract(7, 8)) ) ghost4 <- list( right = list(extract(8, 1), extract(8, 2)), left = list(extract(8, 3), extract(8, 4)), up = list(extract(8, 5), extract(8, 6)), down = list(extract(8, 7), extract(8, 8)) ) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Combine all ghosts #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ghost <- list( ghost1, ghost2, ghost3, ghost4 ) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Test plot of a single sprite #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if (FALSE) { grid.raster(ghost4$right[[1]], interpolate = FALSE) grid.newpage(); dev.hold(); grid.raster(pacman$rest[[2]], interpolate = FALSE); dev.flush() }
import 'package:ucpc_inventory_management_app/exports.dart'; class Product { final String? id; final String name; final String description; final List imageUrls; final String? supplierId; final double price; final int quantity; final bool isPopular; final bool isHidden; final String barcode; final String createdBy; final String? updatedBy; final Timestamp createdAt; final Timestamp? updatedAt; Product({ this.id, this.description = "", this.imageUrls = const [], this.price = 0, this.quantity = 0, this.updatedBy, this.updatedAt, this.supplierId, this.isPopular = false, this.isHidden = false, this.barcode = "", required this.name, required this.createdBy, required this.createdAt, }); Map<String, dynamic> toJson() { return { 'name': name, 'description': description, 'imageUrls': imageUrls, 'supplierId': supplierId, 'price': price, 'quantity': quantity, 'createdAt': createdAt, 'updatedAt': updatedAt, 'createdBy': createdBy, 'updatedBy': updatedBy, 'isPopular': isPopular, 'isHidden': isHidden, 'barcode': barcode, }; } factory Product.fromJson(Map<String, dynamic> json, String id) { return Product( id: id, name: json['name'], description: json['description'], imageUrls: json['imageUrls'], supplierId: json['supplierId'], price: json['price'].toDouble(), quantity: json['quantity'], createdAt: json['createdAt'], updatedAt: json['updatedAt'], createdBy: json['createdBy'], updatedBy: json['updatedBy'], isPopular: json['isPopular'], isHidden: json['isHidden'], barcode: json['barcode'], ); } Product copyWith({ String? id, String? name, String? description, List<String>? imageUrls, String? supplierId, double? price, int? quantity, bool? isPopular, bool? isHidden, String? barcode, String? createdBy, String? updatedBy, Timestamp? createdAt, Timestamp? updatedAt, }) { return Product( id: id ?? this.id, name: name ?? this.name, description: description ?? this.description, imageUrls: imageUrls ?? this.imageUrls, supplierId: supplierId ?? this.supplierId, price: price ?? this.price, quantity: quantity ?? this.quantity, isPopular: isPopular ?? this.isPopular, isHidden: isHidden ?? this.isHidden, barcode: barcode ?? this.barcode, createdBy: createdBy ?? this.createdBy, updatedBy: updatedBy ?? this.updatedBy, createdAt: createdAt ?? this.createdAt, updatedAt: updatedAt ?? this.updatedAt, ); } }
import React, { useState, useEffect } from 'react' import TripCard from './TripCard' export default function TripList () { const [trips, setTrips] = useState([]) function removeTrip (id) { setTrips(trips.filter(trip => trip.id !== id)) } useEffect(() => { fetch('http://localhost:3000/api/v1/trips').then(res => { if (res.ok) { res.json().then(data => setTrips(data)) } else { res.json().then(data => console.log(data)) } }) }, []) return ( <> <h1>Trip List</h1> {trips && trips.map(trip => ( <TripCard trip={trip} removeTrip={removeTrip} key={trip.id} /> ))} </> ) }
from torch.utils.data import Dataset from pathlib import Path import os import cv2 import open3d as o3d import numpy as np import torch import MinkowskiEngine as ME from omegaconf import DictConfig import hydra import json from ncut.SensorData_python3_port import SensorData def color_images_from_sensor_data(sens: SensorData, image_size=None, frame_skip=1): """ Returns a generator object for color images contained in the sensor data as torch tensors. """ for f in range(0, len(sens.frames), frame_skip): color = sens.frames[f].decompress_color(sens.color_compression_type) if image_size is not None: color = cv2.resize( color, (image_size[1], image_size[0]), interpolation=cv2.INTER_NEAREST ) yield color def depth_images_from_sensor_data(sens: SensorData, image_size=None, frame_skip=1): """ Returns a generator object for depth images contained in the sensor data as torch tensors. """ for f in range(0, len(sens.frames), frame_skip): depth_data = sens.frames[f].decompress_depth(sens.depth_compression_type) depth = np.fromstring(depth_data, dtype=np.uint16).reshape( sens.depth_height, sens.depth_width ) if image_size is not None: depth = cv2.resize( depth, (image_size[1], image_size[0]), interpolation=cv2.INTER_NEAREST ) yield depth def poses_from_sensor_data(sens: SensorData, frame_skip=1): """ Returns a generator object for camera poses in the sensor data. """ for f in range(0, len(sens.frames), frame_skip): yield sens.frames[f].camera_to_world def color_intrinsics_from_sensor_data(sens: SensorData): return sens.intrinsic_color class FeatureExtractionScannet(Dataset): """ Used for 2D or 3D feature extraction of scannet scenes. """ def __init__( self, dataset_dir, sensordata_glob_pattern, mesh_glob_pattern, voxel_size, scale_colors_to_depth_resolution, frame_skip=1, content=[ "mesh_voxel_coords", "mesh_original_coords", "mesh_colors", "color_images", "depth_images", "camera_poses", "color_intrinsics", ], ): """ ONLY TO BE USED WITH BATCH SIZE 1 OVERRIDE DATALOADER collate_fn WITH lambda x: x dataset_dir: base dir of scannet dataset sensordata_filename_pattern: glob pattern for sens file mesh_filename_pattern: glob pattern for mesh ply file voxel_size: voxel size in meters scale_colors_to_depth_resolution: if true, color images are downscaled to depth image resolution and intrinsics are adapted accordingly frame_skip: every kth frame for color images, depth images, and poses content: dict entries of a sample scene_name (always contained): scene name as string of format sceneXXXX_XX mesh_voxel_coords: np array of shape (n_points, 3) of coords normalized w.r.t. voxel size mesh_original_coords: np array of shape (n_points, 3) of coords in meters mesh_colors: np array of shape (n_points, 3) of RGB colors of points color_images: generator object that loads images np arrays of shape (height, width, channels(3)) depth_images: generator object that loads depth images as torch tensors of shape (depth_height, depth_width) color_intrinsics: intrinsic parameters of color camera - np array of shape (4, 4) """ self.scans = [ str(os.path.dirname(i)) for i in Path(dataset_dir).rglob(sensordata_glob_pattern) ] self.sensordata_glob_pattern = sensordata_glob_pattern self.mesh_glob_pattern = mesh_glob_pattern self.voxel_size = voxel_size self.scale_colors_to_depth_resolution = scale_colors_to_depth_resolution self.frame_skip = frame_skip self.content = content def __len__(self): return len(self.scans) def __getitem__(self, idx): scene_name = os.path.basename(self.scans[idx]) sample = {"scene_name": scene_name} # mesh stuff mesh_content = ["mesh_voxel_coords", "mesh_original_coords", "mesh_colors"] if any(file in self.content for file in mesh_content): mesh_path = str( next(iter(Path(self.scans[idx]).glob(self.mesh_glob_pattern))) ) assert os.path.isfile(mesh_path), f"mesh file does not exist: {mesh_path}" mesh = o3d.io.read_triangle_mesh(mesh_path) if "mesh_voxel_coords" in self.content: sample["mesh_voxel_coords"] = ( np.array(mesh.vertices).astype(np.single) / self.voxel_size ) if "mesh_original_coords" in self.content: sample["mesh_original_coords"] = np.array(mesh.vertices).astype(np.single) if "mesh_colors" in self.content: sample["mesh_colors"] = np.array(mesh.vertex_colors).astype(np.single) # image stuff image_content = [ "color_images", "depth_imgages", "camera_poses", "color_instrinsics", ] if any(item in self.content for item in image_content): sens_path = str( next(iter(Path(self.scans[idx]).glob(self.sensordata_glob_pattern))) ) assert os.path.isfile(sens_path), f"sens file does not exist: {sens_path}" sensordata = SensorData(sens_path) if self.scale_colors_to_depth_resolution: depth_h, depth_w = next( iter(depth_images_from_sensor_data(sensordata)) ).shape img_h, img_w, _ = next( iter(color_images_from_sensor_data(sensordata)) ).shape scale_x = depth_w / img_w scale_y = depth_h / img_h if "color_images" in self.content: if self.scale_colors_to_depth_resolution: sample["color_images"] = color_images_from_sensor_data( sensordata, image_size=(depth_h, depth_w), frame_skip=self.frame_skip, ) else: sample["color_images"] = color_images_from_sensor_data( sensordata, frame_skip=self.frame_skip ) if "depth_images" in self.content: sample["depth_images"] = depth_images_from_sensor_data( sensordata, frame_skip=self.frame_skip ) if "camera_poses" in self.content: sample["camera_poses"] = poses_from_sensor_data( sensordata, frame_skip=self.frame_skip ) if "color_intrinsics" in self.content: intr = color_intrinsics_from_sensor_data(sensordata) if self.scale_colors_to_depth_resolution: intr[0, 0], intr[1, 1] = intr[0, 0] * scale_x, intr[1, 1] * scale_y intr[0, 2], intr[1, 2] = intr[0, 2] * scale_x, intr[1, 2] * scale_y sample["color_intrinsics"] = intr return sample @staticmethod def to_sparse_tens(coords, features, device): """ Turns either mesh_voxel_coords + features or mesh_original_coords + features into a minkowski engine sparse tensor voxel representation. Note that this is a lossy conversion because several points might map to the same voxel. """ coords = torch.IntTensor(coords).to(device) features = torch.Tensor(features).to(device) coords, features = ME.utils.sparse_collate(coords=[coords], feats=[features]) return ME.SparseTensor(coordinates=coords, features=features) @staticmethod def dataloader_from_hydra(datacfg: DictConfig, only_first=False): """ datacfg must be hydra config of the following form: If only_first is True, the dataloader's first batch will be returned. dataset: <config to instantiate this class> dataloader: <config to instantiate dataloader with batch size 1 (else will be overwritten!)> """ ds = hydra.utils.instantiate(datacfg.dataset) loader = hydra.utils.instantiate( datacfg.dataloader, dataset=ds, collate_fn=lambda x: x ) assert loader.batch_size == 1, "batch size must be 1!" if only_first: return [next(iter(loader))] return loader class NormalizedCutDataset(Dataset): """ Used for creation of initial pseudo masks from previously saved point-wise features. """ def __init__( self, scannet_base_dir, mode, segments_base_dir, base_dir_3d, coords_filename_3d, features_filename_3d, base_dir_2d, coords_filename_2d, features_filename_2d, ): self.scannet_base_dir = scannet_base_dir self.segments_base_dir = segments_base_dir self.base_dir_3d = base_dir_3d self.coords_filename_3d = coords_filename_3d self.features_filename_3d = features_filename_3d self.base_dir_2d = base_dir_2d self.coords_filename_2d = coords_filename_2d self.features_filename_2d = features_filename_2d # read scenes from split file assert mode in ["train", "val", "test"], "mode must be train, val, or test" split_file = os.path.join(scannet_base_dir, "splits", f"scannetv2_{mode}.txt") with open(split_file, "r") as sf: self.scenes = [i.strip() for i in sf.readlines()] def __len__(self): return len(self.scenes) def __getitem__(self, idx): # load coords and feats from np files coords = np.load( os.path.join(self.base_dir_3d, self.scenes[idx], self.coords_filename_3d) ) feats_3d = np.load( os.path.join(self.base_dir_3d, self.scenes[idx], self.features_filename_3d) ) feats_2d = np.load( os.path.join(self.base_dir_2d, self.scenes[idx], self.features_filename_2d) ) # load segments from json and convert to np segments_filename = str( next(iter(Path(self.segments_base_dir).glob(f"{self.scenes[idx]}*.json"))) ) with open(segments_filename, "r") as sf: segments_file_dict = json.loads(sf.read()) segment_ids = np.asarray(segments_file_dict["segIndices"], dtype=int) segment_connectivity = np.asarray( segments_file_dict["segConnectivity"], dtype=int ) return { "coords": coords, # (n_points, 3), float "feats_3d": feats_3d, # (n_points, dim_feats_3d), float "feats_2d": feats_2d, # (n_points, dim_feats_2d), float "segment_ids": segment_ids, # (n_points,), int "segment_connectivity": segment_connectivity, # (-1, 2), int (neighborhood edges of segments) "scene_name": self.scenes[idx], # str wrapped in list to make it batchable } @staticmethod def dataloader_from_hydra(datacfg: DictConfig, only_first=False): """ datacfg must be hydra config of the following form: If only_first is True, the dataloader's first batch will be returned. dataset: <config to instantiate this class> dataloader: <config to instantiate dataloader with batch size 1 (else will be overwritten!)> """ ds = hydra.utils.instantiate(datacfg.dataset) loader = hydra.utils.instantiate(datacfg.dataloader, dataset=ds) if only_first: return [next(iter(loader))] return loader
package com.commercetools.sync.taxcategories; import com.commercetools.api.client.ProjectApiRoot; import com.commercetools.api.models.tax_category.TaxCategory; import com.commercetools.api.models.tax_category.TaxCategoryDraft; import com.commercetools.api.models.tax_category.TaxCategoryUpdateAction; import com.commercetools.sync.commons.BaseSyncOptionsBuilder; import javax.annotation.Nonnull; public final class TaxCategorySyncOptionsBuilder extends BaseSyncOptionsBuilder< TaxCategorySyncOptionsBuilder, TaxCategorySyncOptions, TaxCategory, TaxCategoryDraft, TaxCategoryUpdateAction> { public static final int BATCH_SIZE_DEFAULT = 50; private TaxCategorySyncOptionsBuilder(@Nonnull final ProjectApiRoot ctpClient) { this.ctpClient = ctpClient; } /** * Creates a new instance of {@link TaxCategorySyncOptionsBuilder} given a {@link * io.sphere.sdk.client.SphereClient} responsible for interaction with the target CTP project, * with the default batch size ({@code BATCH_SIZE_DEFAULT} = 50). * * @param ctpClient instance of the {@link io.sphere.sdk.client.SphereClient} responsible for * interaction with the target CTP project. * @return new instance of {@link TaxCategorySyncOptionsBuilder} */ public static TaxCategorySyncOptionsBuilder of(@Nonnull final ProjectApiRoot ctpClient) { return new TaxCategorySyncOptionsBuilder(ctpClient).batchSize(BATCH_SIZE_DEFAULT); } /** * Creates new instance of {@link com.commercetools.sync.taxcategories.TaxCategorySyncOptions} * enriched with all attributes provided to {@code this} builder. * * @return new instance of {@link com.commercetools.sync.taxcategories.TaxCategorySyncOptions} */ @Override public TaxCategorySyncOptions build() { return new TaxCategorySyncOptions( ctpClient, errorCallback, warningCallback, batchSize, beforeUpdateCallback, beforeCreateCallback, cacheSize); } /** * Returns an instance of this class to be used in the superclass's generic methods. Please see * the JavaDoc in the overridden method for further details. * * @return an instance of this class. */ @Override protected TaxCategorySyncOptionsBuilder getThis() { return this; } }
import "./topbar.css"; import { Search, Person, Chat, Notifications } from "@material-ui/icons"; import {Link, useHistory} from "react-router-dom"; import {useContext, useRef} from "react"; import { AuthContext } from "../../context/AuthContext"; import axios from "axios"; export default function Topbar() { const { user } = useContext(AuthContext); const PF = process.env.REACT_APP_PUBLIC_FOLDER; const pattern = useRef(); const history = useHistory() const handleSearch = async () => { try { const res = await axios.post(`/api/users/find`, {pattern: pattern.current.value}); if (!res.data) { alert("No users found for pattern: " + pattern.current.value) } else { history.push("/profile/" + res.data); } } catch (err) { console.log(err); alert("Failed to search pattern: " + pattern.current.value + err) } } const signOut = () => { localStorage.setItem("user", null) history.push("/login") } axios.defaults.headers['Authorization'] = localStorage.getItem("app_token"); return ( <div className="topbarContainer"> <div className="topbarLeft"> <Link to="/" style={{ textDecoration: "none" }}> <span className="logo">NasiLjubimci</span> </Link> </div> <div className="topbarCenter"> <div className="searchbar"> <Search className="searchIcon" onClick={handleSearch}/> <input placeholder="Search for friend, post or video" className="searchInput" ref={pattern} /> </div> </div> <div className="topbarRight"> <div className="topbarLinks"> <Link to={`/profile/${user.username}`}> <span className="topbarLink">Timeline</span> </Link> <Link to={`/events`}> <span className="topbarLink">Events</span> </Link> </div> <div className="topbarIcons"> <Link to={`/profileRequests/${user.username}`}> <div className="topbarIconItem"> <Person /> <span className="topbarIconBadge">1</span> </div> </Link> <div className="topbarIconItem"> <Link to={`/messages`}> <div className="topbarIconItem"> <Chat /> <span className="topbarIconBadge">2</span> </div> </Link> </div> <div className="topbarIconItem"> <Notifications /> <span className="topbarIconBadge">1</span> </div> </div> <Link to={`/profile/${user.username}`}> <img src={ user.profilePicture ? "data:image/png;base64, " + user.profilePicture : "./icons/noAvatar.png" } alt="" className="topbarImg" /> </Link> <button className="logoutButton" onClick={signOut}> Sign Out </button> </div> </div> ); }
class MenuItemPricesController < ApplicationController # GET /menu_item_prices # GET /menu_item_prices.xml def index @menu_item_prices = MenuItemPrice.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @menu_item_prices } end end # GET /menu_item_prices/1 # GET /menu_item_prices/1.xml def show @menu_item_price = MenuItemPrice.find(params[:id]) respond_to do |format| format.html # _unused_show.html.haml format.xml { render :xml => @menu_item_price } end end # GET /menu_item_prices/new # GET /menu_item_prices/new.xml def new @menu_item_price = MenuItemPrice.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @menu_item_price } end end # GET /menu_item_prices/1/edit def edit @menu_item_price = MenuItemPrice.find(params[:id]) end # POST /menu_item_prices # POST /menu_item_prices.xml def create @menu_item_price = MenuItemPrice.new(params[:menu_item_price]) respond_to do |format| if @menu_item_price.save format.html { redirect_to(@menu_item_price, :notice => 'Menu item price was successfully created.') } format.xml { render :xml => @menu_item_price, :status => :created, :location => @menu_item_price } else format.html { render :action => "new" } format.xml { render :xml => @menu_item_price.errors, :status => :unprocessable_entity } end end end # PUT /menu_item_prices/1 # PUT /menu_item_prices/1.xml def update @menu_item_price = MenuItemPrice.find(params[:id]) respond_to do |format| if @menu_item_price.update_attributes(params[:menu_item_price]) format.html { redirect_to(@menu_item_price, :notice => 'Menu item price was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @menu_item_price.errors, :status => :unprocessable_entity } end end end # DELETE /menu_item_prices/1 # DELETE /menu_item_prices/1.xml def destroy @menu_item_price = MenuItemPrice.find(params[:id]) @menu_item_price.destroy respond_to do |format| format.html { redirect_to(menu_item_prices_url) } format.xml { head :ok } end end end
/* eslint-disable no-unused-vars */ /* eslint-disable no-undef */ import React, { useState, useEffect } from 'react'; import { Form, InputGroup } from 'react-bootstrap'; import { useDispatch, useSelector } from "react-redux"; import { useNavigate } from 'react-router-dom'; import { RegisterUser, reset } from "../features/authSlice"; import axios from 'axios'; // const DaftarForm = () => { // const navigate = useNavigate(); // const [name, setName] = useState(''); // const [email, setEmail] = useState(''); // const [password, setPassword] = useState(''); // const [confPassword, setConfPassword] = useState(''); // const dispatch = useDispatch(); // const { user, isError, isSuccess, message } = useSelector((state) => state.auth); const DaftarForm = () => { const navigate = useNavigate(); const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [confPassword, setConfPassword] = useState(''); const dispatch = useDispatch(); const { user, isError, isSuccess, message } = useSelector((state) => state.auth); useEffect(() => { if (user || isSuccess) { navigate("/lapak"); } dispatch(reset()); }, [user, isSuccess, dispatch, navigate]); // const handleRegister = async (e) => { // e.preventDefault(); // try { // await dispatch(RegisterUser({ name, email, password, confPassword })); // // Check if registration was successful // if (!isError && isSuccess) { // // Navigate to the desired page // navigate("/lapak"); // } // } catch (error) { // // Handle any errors during registration // if (error.response) { // console.log(error.response.data.msg); // } // } // }; const handleRegister = async (e) => { e.preventDefault(); try { await dispatch(RegisterUser({ name, email, password, confPassword })); if (!isError && isSuccess) { navigate("/lapak"); } } catch (error) { if (error.response) { console.log(error.response.data.msg); } } }; return ( <div className='daftar-form'> <Form onSubmit={handleRegister}> <InputGroup className="mb-2" > {isError && <p className="has-text-centered">{message}</p>} <Form.Control type="text" placeholder="Nama lengkap" aria-label="nama" aria-describedby="basic-addon1" value={name} onChange={(e) => setName(e.target.value)} required /> </InputGroup> <InputGroup className="mb-2"> <Form.Control type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} required aria-label="email" aria-describedby="basic-addon1" /> </InputGroup> <InputGroup className="mb-2"> <Form.Control type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} required aria-label="password" aria-describedby="basic-addon1" /> </InputGroup> <InputGroup className="mb-2"> <Form.Control type="password" placeholder="Confirm Password" value={confPassword} onChange={(e) => setConfPassword(e.target.value)} required aria-label="password" aria-describedby="basic-addon1" /> </InputGroup> <div className="d-grid gap-2"> <button className="btn btn-primer" type="submit">Daftar</button> </div> </Form> </div> ); } export default DaftarForm;
--- description: "Langkah Mudah untuk Membuat Roti sobek lembut oven tangkring Anti Gagal" title: "Langkah Mudah untuk Membuat Roti sobek lembut oven tangkring Anti Gagal" slug: 1061-langkah-mudah-untuk-membuat-roti-sobek-lembut-oven-tangkring-anti-gagal date: 2020-04-18T18:27:38.393Z image: https://img-global.cpcdn.com/recipes/db841f8c41a60cd2/751x532cq70/roti-sobek-lembut-oven-tangkring-foto-resep-utama.jpg thumbnail: https://img-global.cpcdn.com/recipes/db841f8c41a60cd2/751x532cq70/roti-sobek-lembut-oven-tangkring-foto-resep-utama.jpg cover: https://img-global.cpcdn.com/recipes/db841f8c41a60cd2/751x532cq70/roti-sobek-lembut-oven-tangkring-foto-resep-utama.jpg author: Tony Tyler ratingvalue: 4.8 reviewcount: 8 recipeingredient: - "500 gr Tepung terigu pro tinggi me cakra" - "100 gr gula pasir" - "2 butir telor" - "11 gr ragi me 1 sachet haan" - "100 gr margarin me blue band" - "220 ml air es bisa d ganti susu cair" - "Sejumput garam" - "25 gr Susu bubuk" - " Isian selai coklat nanas keju pisang" - " Olesan susu kental manis dan margarin" recipeinstructions: - "Campurkan tepung terigu, ragi, susu, gula masukkan telor satu persatu uleni, masukkan air sedikit demi sedikit, perhatikan jangan sampai keenceran, daya serap tepung bisa berbeda uleni sampai kalis elastis" - "Ngulenya bisa manual tangan dengan gerakan kayak nyuci baju jaman dulu, atau pakai hand mixer spiral.. ngulennya sampai kalis elastis.. kuncinya disini adonan harus kalis elastis," - "Setelah kalis, bulatkan adonan tutup serbet bersih dan diamkan hingga mengembang 2 kali lipat, me: 40 menit, makin panas suhu ruang adonan makin cepat mengembang" - "Setelah adonan mengembang, kempeskan adonan, uleni sbntar saja potong dan timbanh adonan 30 gr bulat bulankan (rounding) istirahatkan adonan sekitan 10 - 20 menit, tutup serbet bersih" - "Ambil adonan yg telah di bulat bulatkan, pipihkan tambahkan isian sesuai selera, lakukan hingga habis letakkan pada loyang yg telah di alas kertas roti atau di oles margarin" - "Diamkan adonan 1 jam tutup dengan serbet," - "Campurkan 2 sdm skm dengan 2 sdm air hingga mencair, untuk dijadikan bahan olesan pertama" - "Setelah 1 jam adonan mengembang, oles tipis campurn skm dan air menggunakan kuas, pelan pelan saja secara merata" - "Panaskan oven dengan suhu 180 derajat, panggang roti di rak bawah 7 menut, lalu pindahkan ke rak atas, sambil memutar loyang agak matang merata selama 8menit, atau sampai coklat keemasan, kenali oven masing2" - "Keluarkan roti dari oven, selagi hangat oles roti dengan margarin hingga nampak berkilau." categories: - Resep tags: - roti - sobek - lembut katakunci: roti sobek lembut nutrition: 280 calories recipecuisine: Indonesian preptime: "PT32M" cooktime: "PT55M" recipeyield: "2" recipecategory: Lunch --- ![Roti sobek lembut oven tangkring](https://img-global.cpcdn.com/recipes/db841f8c41a60cd2/751x532cq70/roti-sobek-lembut-oven-tangkring-foto-resep-utama.jpg) Anda sedang mencari inspirasi resep roti sobek lembut oven tangkring yang unik? Cara menyiapkannya memang tidak terlalu sulit namun tidak gampang juga. Jika keliru mengolah maka hasilnya akan hambar dan justru cenderung tidak enak. Padahal roti sobek lembut oven tangkring yang enak seharusnya punya aroma dan cita rasa yang mampu memancing selera kita. Banyak hal yang sedikit banyak mempengaruhi kualitas rasa dari roti sobek lembut oven tangkring, mulai dari jenis bahan, kemudian pemilihan bahan segar, sampai cara membuat dan menghidangkannya. Tak perlu pusing jika ingin menyiapkan roti sobek lembut oven tangkring enak di mana pun anda berada, karena asal sudah tahu triknya maka hidangan ini dapat jadi suguhan spesial. Roti sobek ini super lembut ya walaupun pakai oven tangkring. Bismillah Assalamualaikum warahmatullahi wabarakatuh Haii semuanyaa Julie balik lagi buat ngasih resep yg baru buat kalian.simak baik&#34; yaaa.😊 Resep Roti. ROTI SOBEK HOMEMADE LEMBUT - OVEN TANGKRING - TANPA MIXER Hallo pemirsa semuanya, kiranya kita semuanya dalam lindungan TYME dan rejeki kita juga lancar. Nah, kali ini kita coba, yuk, buat roti sobek lembut oven tangkring sendiri di rumah. Tetap berbahan sederhana, hidangan ini dapat memberi manfaat dalam membantu menjaga kesehatan tubuhmu sekeluarga. Anda bisa membuat Roti sobek lembut oven tangkring menggunakan 10 bahan dan 10 tahap pembuatan. Berikut ini cara dalam menyiapkan hidangannya. <!--inarticleads1--> ##### Bahan-bahan dan bumbu yang digunakan untuk pembuatan Roti sobek lembut oven tangkring: 1. Sediakan 500 gr Tepung terigu pro tinggi (me: cakra) 1. Siapkan 100 gr gula pasir 1. Ambil 2 butir telor 1. Ambil 11 gr ragi (me : 1 sachet haan) 1. Sediakan 100 gr margarin (me: blue band) 1. Gunakan 220 ml air es (bisa d ganti susu cair) 1. Gunakan Sejumput garam 1. Sediakan 25 gr Susu bubuk 1. Gunakan Isian : selai coklat, nanas, keju, pisang 1. Siapkan Olesan ; susu kental manis dan margarin Bisa jadi pengganjal lapar atau bekal untuk ke kantor. Gak perlu oven, kamu bisa menggunakan teflon untuk memanggangnya. СтраницыКомпанииЕда и напиткиHOBI MASAKВидеоResep ROTI SOBEK (Oven Tangkring) Super Lembut. Sini yg doyan makan roti sobek tapi ga punya oven (kayak saya 😁), jgn galau bund, yuk cobain pake panci presto. Keyword resep roti sobek, roti sobek manis. <!--inarticleads2--> ##### Cara menyiapkan Roti sobek lembut oven tangkring: 1. Campurkan tepung terigu, ragi, susu, gula masukkan telor satu persatu uleni, masukkan air sedikit demi sedikit, perhatikan jangan sampai keenceran, daya serap tepung bisa berbeda uleni sampai kalis elastis 1. Ngulenya bisa manual tangan dengan gerakan kayak nyuci baju jaman dulu, atau pakai hand mixer spiral.. ngulennya sampai kalis elastis.. kuncinya disini adonan harus kalis elastis, 1. Setelah kalis, bulatkan adonan tutup serbet bersih dan diamkan hingga mengembang 2 kali lipat, me: 40 menit, makin panas suhu ruang adonan makin cepat mengembang 1. Setelah adonan mengembang, kempeskan adonan, uleni sbntar saja potong dan timbanh adonan 30 gr bulat bulankan (rounding) istirahatkan adonan sekitan 10 - 20 menit, tutup serbet bersih 1. Ambil adonan yg telah di bulat bulatkan, pipihkan tambahkan isian sesuai selera, lakukan hingga habis letakkan pada loyang yg telah di alas kertas roti atau di oles margarin 1. Diamkan adonan 1 jam tutup dengan serbet, 1. Campurkan 2 sdm skm dengan 2 sdm air hingga mencair, untuk dijadikan bahan olesan pertama 1. Setelah 1 jam adonan mengembang, oles tipis campurn skm dan air menggunakan kuas, pelan pelan saja secara merata 1. Panaskan oven dengan suhu 180 derajat, panggang roti di rak bawah 7 menut, lalu pindahkan ke rak atas, sambil memutar loyang agak matang merata selama 8menit, atau sampai coklat keemasan, kenali oven masing2 1. Keluarkan roti dari oven, selagi hangat oles roti dengan margarin hingga nampak berkilau. Seperti namanya roti sobek ini saat dimakan perlu disobek dahulu, nama yang unik dan memiliki tekstur yang lembut dan enak. Roti jenis ini banyak dilirik oleh masyarakat dari anak - anak sampai orang tua. Roti sobek memang menjadi roti dengan kualitas rasa juara dan bertekstur lembut. Untuk membuat roti sobek lembut dibutuhkan ragi, tepung terigu protein tinggi, susu, gula, garam, margarin, dan pewarna makanan. KOMPAS.com - Roti sobek punya tekstur lembut yang bisa dipadukan dengan beragam isian maupun olesan. Terima kasih telah membaca resep yang kami tampilkan di sini. Besar harapan kami, olahan Roti sobek lembut oven tangkring yang mudah di atas dapat membantu Anda menyiapkan makanan yang menarik untuk keluarga/teman ataupun menjadi ide bagi Anda yang berkeinginan untuk berjualan makanan. Selamat mencoba!
import { Injectable } from '@angular/core'; import { BehaviorSubject, tap } from 'rxjs'; import { HttpClient, HttpHeaders } from "@angular/common/http"; import { SessionStorageService } from "../session-storage/session-storage.service"; import { User } from '../../../models/user'; import { LoginResult, RegisterResult } from "../../../models/authApiResults"; import { environment } from "../../../../environments/environment"; @Injectable({ providedIn: 'root' }) export class AuthService { private loginUrl = '/login'; private redirectUrl = '/courses'; private isAuthorized$$ = new BehaviorSubject(!!this.sessionStorageService.getToken()); public isAuthorized$ = this.isAuthorized$$.asObservable(); constructor(private http: HttpClient, private sessionStorageService: SessionStorageService) { } login(user: User) { return this.http.post<LoginResult>(`${environment.apiURL}/login`, user) .pipe( tap(res => { if (res.successful) { const token = res.result.replace('Bearer ', ''); this.sessionStorageService.setToken(token); this.isAuthorized$$.next(true); } else { console.log('Auth is failed'); } })); } logout() { const authorization = this.sessionStorageService.getToken(); const headers = new HttpHeaders() .set('authorization', `Bearer ${authorization}`); return this.http.delete(`${environment.apiURL}/logout`, { headers }) .pipe( tap(() => { this.sessionStorageService.deleteToken(); this.isAuthorized$$.next(false); }) ); } register(user: User) { return this.http.post<RegisterResult>(`${environment.apiURL}/register`, user); } get isAuthorised() { return this.isAuthorized$$.getValue(); } getLoginUrl() { return this.loginUrl; } getRedirectUrl() { return this.redirectUrl; } }
from datetime import datetime, timedelta from sqlalchemy.orm import Session from sqlalchemy import func, and_ from fastapi import HTTPException from contacts.database.models import Contact, User from contacts.schemas import ContactBase, ContactUpdate, ContactCreate async def get_contact( id: int, user: User, db: Session ): try: contact = db.query(Contact).filter(and_(Contact.id == id, Contact.user_id == user.id)).first() except Exception as e: raise HTTPException(status_code=404, detail=f'Contact not found.') return contact async def get_all_contacts( user: User, db: Session ) -> list[ContactBase]: contacts = db.query(Contact).filter(Contact.user_id == user.id).all() return contacts async def add_contact( body: ContactCreate, user: User, db: Session ): contact = Contact( user_id=user.id, name=body.name, surname=body.surname, email=body.email, phone_number=body.phone_number, date_of_birth=body.date_of_birth, additional_data=body.additional_data ) db.add(contact) db.commit() db.refresh(contact) return contact async def delete_contact( contact_id: int, user: User, db: Session ): contact = await get_contact(contact_id, user, db) db.delete(contact) db.commit() return contact async def update_contact( contact_id: int, new_contact: ContactUpdate, user: User, db: Session ): contact = await get_contact(contact_id, user, db) contact.user_id = contact.user_id contact.name = new_contact.name if True else contact.name contact.surname = new_contact.surname if True else contact.surname contact.email = new_contact.email if True else contact.email contact.phone_number = new_contact.phone_number if True else contact.phone_number contact.date_of_birth = new_contact.date_of_birth if True else contact.date_of_birth contact.additional_data = new_contact.additional_data if True else contact.additional_data db.commit() db.refresh(contact) return contact async def search_contact( user: User, db: Session, name: str = None, surname: str = None, email: str = None, ): result = db.query(Contact).filter(Contact.user_id == user.id).all() if name: result = result.filter(Contact.name == name).all() if surname: result = result.filter(Contact.surname == surname).all() if email: result = result.filter(Contact.email == email).all() if result: return result else: raise HTTPException(status_code=404, detail="Contact not found") async def get_upcoming_birthdays_from_db( user: User, db: Session ): today = datetime.today().date() next_week = today + timedelta(days=7) contacts = db.query(Contact).filter( and_( Contact.user_id == user.id, (func.to_char(Contact.date_of_birth, 'MM-DD') >= func.to_char(today, 'MM-DD')) & (func.to_char(Contact.date_of_birth, 'MM-DD') <= func.to_char(next_week, 'MM-DD')) )).all() if contacts: return contacts else: raise HTTPException(status_code=404, detail="Contacts not found")
import json import psycopg2 from django.conf import settings from ofirio_common.states_constants import states_from_short from ofirio_common.enums import PropClass2 from common.utils import get_is_test_condition, get_pg_connection from common.base_urlgen_command import BaseUrlgenCommand from common.klaviyo.feed import build_feed_item class Command(BaseUrlgenCommand): ''' Creates json files ('feeds') for klaviyo. Each state has sales and rent feeds ''' buf_size = 1024 * 16 chunk_size = 1000 klaviyo_dir = settings.BASE_DIR / 'data' / 'klaviyo' def _handle(self, *args, **options): self.conn = get_pg_connection() for state_id in states_from_short: sections = ('buy', 'rent', ) if settings.INVEST_ENABLED: sections += ('invest',) for section in sections: feed = self.make_feed(state_id, section) if not feed: continue path = self.klaviyo_dir / f'klaviyo-{state_id}-{section}.json' with open(path, 'w') as f: json.dump(feed, f, separators=(',', ':')) print('done', path) self.conn.close() def get_properties(self, state_id, section): ''' get all properties from prop_cache for specified state and prop class ''' if section == 'invest': prop_class = 'sales' invest_condition = "and params ->> 'has_invest_view' = 'true'" elif section == 'buy': invest_condition = '' prop_class = 'sales' else: invest_condition = '' prop_class = 'rent' query = f''' select c.prop_id, c.address ->> 'line' address_line, c.address ->> 'city' address_city, c.address ->> 'state_code' address_state_code, c.address ->> 'zip' address_zip, c.list_date, c.status, c.data -> 'price' price, c.data -> 'beds' beds, c.data -> 'cleaned_prop_type' prop_type, c.data -> 'cap_rate' cap_rate, c.data -> 'predicted_rent' predicted_rent, c.data -> 'estimated_mortgage' estimated_mortgage, c.badges badges, c.params params, p.photos -> 0 image from prop_cache c join prop_photos p on c.real_prop_id = p.prop_id where prop_class = %(prop_class)s and state_id = %(state_id)s and status in ('for_sale', 'for_rent') {get_is_test_condition(table_alias='c')} {invest_condition} order by prop_id ''' with self.conn.cursor( name='cursor_for_feed', cursor_factory=psycopg2.extras.RealDictCursor) as cursor: cursor.itersize = self.chunk_size cursor.execute(query, {'state_id': state_id, 'prop_class': prop_class}) while chunk := cursor.fetchmany(self.chunk_size): yield chunk self.conn.commit() def make_feed(self, state_id, section): ''' generates list of feed items (dicts) ''' print('=======', state_id, section, '========') feed = [] i = 0 for chunk in self.get_properties(state_id, section): print(f'chunk #{i}') urls = self.convert_to_urls(chunk) items = [build_feed_item(prop, url, section) for prop, url in zip(chunk, urls)] feed.extend(items) i += 1 if len(feed): print(f'{state_id}: converted {len(feed)} properties') return feed
PostgreSQL: Documentation: 15: 42.1. Installing Procedural Languages Home About Download Documentation Community Developers Support Donate Your account 9th February 2023: PostgreSQL 15.2, 14.7, 13.10, 12.14, and 11.19 Released! Documentation → PostgreSQL 15 Supported Versions: Current (15) / 14 / 13 / 12 / 11 Development Versions: devel Unsupported versions: 10 / 9.6 / 9.5 / 9.4 / 9.3 / 9.2 / 9.1 / 9.0 / 8.4 / 8.3 / 8.2 / 7.3 / 7.2 42.1. Installing Procedural Languages Prev  Up Chapter 42. Procedural Languages Home  Next 42.1. Installing Procedural Languages A procedural language must be “installed” into each database where it is to be used. But procedural languages installed in the database template1 are automatically available in all subsequently created databases, since their entries in template1 will be copied by CREATE DATABASE. So the database administrator can decide which languages are available in which databases and can make some languages available by default if desired. For the languages supplied with the standard distribution, it is only necessary to execute CREATE EXTENSION language_name to install the language into the current database. The manual procedure described below is only recommended for installing languages that have not been packaged as extensions. Manual Procedural Language Installation A procedural language is installed in a database in five steps, which must be carried out by a database superuser. In most cases the required SQL commands should be packaged as the installation script of an “extension”, so that CREATE EXTENSION can be used to execute them. The shared object for the language handler must be compiled and installed into an appropriate library directory. This works in the same way as building and installing modules with regular user-defined C functions does; see Section 38.10.5. Often, the language handler will depend on an external library that provides the actual programming language engine; if so, that must be installed as well. The handler must be declared with the command CREATE FUNCTION handler_function_name() RETURNS language_handler AS 'path-to-shared-object' LANGUAGE C; The special return type of language_handler tells the database system that this function does not return one of the defined SQL data types and is not directly usable in SQL statements. Optionally, the language handler can provide an “inline” handler function that executes anonymous code blocks (DO commands) written in this language. If an inline handler function is provided by the language, declare it with a command like CREATE FUNCTION inline_function_name(internal) RETURNS void AS 'path-to-shared-object' LANGUAGE C; Optionally, the language handler can provide a “validator” function that checks a function definition for correctness without actually executing it. The validator function is called by CREATE FUNCTION if it exists. If a validator function is provided by the language, declare it with a command like CREATE FUNCTION validator_function_name(oid) RETURNS void AS 'path-to-shared-object' LANGUAGE C STRICT; Finally, the PL must be declared with the command CREATE [TRUSTED] LANGUAGE language_name HANDLER handler_function_name [INLINE inline_function_name] [VALIDATOR validator_function_name] ; The optional key word TRUSTED specifies that the language does not grant access to data that the user would not otherwise have. Trusted languages are designed for ordinary database users (those without superuser privilege) and allows them to safely create functions and procedures. Since PL functions are executed inside the database server, the TRUSTED flag should only be given for languages that do not allow access to database server internals or the file system. The languages PL/pgSQL, PL/Tcl, and PL/Perl are considered trusted; the languages PL/TclU, PL/PerlU, and PL/PythonU are designed to provide unlimited functionality and should not be marked trusted. Example 42.1 shows how the manual installation procedure would work with the language PL/Perl. Example 42.1. Manual Installation of PL/Perl The following command tells the database server where to find the shared object for the PL/Perl language's call handler function: CREATE FUNCTION plperl_call_handler() RETURNS language_handler AS '$libdir/plperl' LANGUAGE C; PL/Perl has an inline handler function and a validator function, so we declare those too: CREATE FUNCTION plperl_inline_handler(internal) RETURNS void AS '$libdir/plperl' LANGUAGE C STRICT; CREATE FUNCTION plperl_validator(oid) RETURNS void AS '$libdir/plperl' LANGUAGE C STRICT; The command: CREATE TRUSTED LANGUAGE plperl HANDLER plperl_call_handler INLINE plperl_inline_handler VALIDATOR plperl_validator; then defines that the previously declared functions should be invoked for functions and procedures where the language attribute is plperl. In a default PostgreSQL installation, the handler for the PL/pgSQL language is built and installed into the “library” directory; furthermore, the PL/pgSQL language itself is installed in all databases. If Tcl support is configured in, the handlers for PL/Tcl and PL/TclU are built and installed in the library directory, but the language itself is not installed in any database by default. Likewise, the PL/Perl and PL/PerlU handlers are built and installed if Perl support is configured, and the PL/PythonU handler is installed if Python support is configured, but these languages are not installed by default. Prev  Up  Next Chapter 42. Procedural Languages  Home  Chapter 43. PL/pgSQL — SQL Procedural Language Submit correction If you see anything in the documentation that is not correct, does not match your experience with the particular feature or requires further clarification, please use this form to report a documentation issue. Privacy Policy | Code of Conduct | About PostgreSQL | Contact Copyright © 1996-2023 The PostgreSQL Global Development Group
import React, { useState, useEffect, useRef } from 'react'; import styled from 'styled-components'; import axios from 'axios'; import Contacts from '../components/Contacts'; import Welcome from "../components/Welcome" import { useNavigate } from 'react-router-dom'; import { allUsersRoute, host } from '../utils/APIRoutes'; import ChatContainer from "../components/ChatContainer"; import {io} from "socket.io-client"; function Chat() { const socket = useRef(); const navigate = useNavigate(); const [contacts, setContacts] = useState([]); const [currentUser, setCurrentUser] = useState(undefined); const [currentChat, setCurrentChat] = useState(undefined); const [isLoaded, setIsLoaded] = useState(false); useEffect(() => { const fetchData = async () => { if (!localStorage.getItem('chat-app-user')) { navigate('/login'); } else { setCurrentUser(await JSON.parse(localStorage.getItem('chat-app-user'))); setIsLoaded(true); } }; fetchData(); }, []); const handleCurrentChat = (chat) =>{ setCurrentChat(chat); // console.log(currentChat) } useEffect(()=>{ if(currentUser){ socket.current = io(host); socket.current.emit("add-user",currentUser._id); } },[currentUser]); useEffect(() => { const fetchData = async () => { if (currentUser) { if (currentUser.isAvatarImageSet) { const data = await axios.get(`${allUsersRoute}/${currentUser._id}`); setContacts(data.data); } else { navigate('/setAvatar'); } } }; fetchData(); }, [currentUser]); return ( <Container> <div className="container"> <Contacts contacts={contacts} currentUser={currentUser} changeChat= {handleCurrentChat}/> {isLoaded && currentChat===undefined ? <Welcome currentUser={currentUser}/> : <ChatContainer currentChat={currentChat} currentUser={currentUser} socket={socket}/> } </div> </Container> ); } const Container = styled.div` height: 100vh; width: 100vw; display: flex; justify-content: center; gap: 1rem; align-items: center; background-color: #131324; .container { height: 85vh; width: 85vw; background-color: #00000076; display: grid; grid-template-columns: 25% 75%; @media screen and (min-width: 720px) and (max-width: 1080px) { grid-template-columns: 35% 65%; } } `; export default Chat;
use super::{BufStream, SizeHint}; use bytes::Buf; use futures::Poll; /// Limits the stream to a maximum amount of data. #[derive(Debug)] pub struct Limit<T> { stream: T, remaining: u64, } /// Errors returned from `Limit`. #[derive(Debug)] pub struct LimitError<T> { /// When `None`, limit was reached inner: Option<T>, } impl<T> Limit<T> { pub(crate) fn new(stream: T, amount: u64) -> Limit<T> { Limit { stream, remaining: amount, } } } impl<T> BufStream for Limit<T> where T: BufStream, { type Item = T::Item; type Error = LimitError<T::Error>; fn poll_buf(&mut self) -> Poll<Option<Self::Item>, Self::Error> { use futures::Async::Ready; if self.stream.size_hint().lower() > self.remaining { return Err(LimitError { inner: None }); } let res = self.stream.poll_buf() .map_err(|err| { LimitError { inner: Some(err) } }); match res { Ok(Ready(Some(ref buf))) => { if buf.remaining() as u64 > self.remaining { self.remaining = 0; return Err(LimitError { inner: None }); } self.remaining -= buf.remaining() as u64; } _ => {} } res } fn size_hint(&self) -> SizeHint { let mut hint = self.stream.size_hint(); let upper = hint.upper() .map(|upper| upper.min(self.remaining)) .unwrap_or(self.remaining); hint.set_upper(upper); hint } fn consume_hint(&mut self, amount: usize) { // TODO: Should this be capped by `self.remaining`? self.stream.consume_hint(amount) } } // ===== impl LimitError ===== impl<T> LimitError<T> { /// Returns `true` if the error was caused by polling the stream. pub fn is_stream_err(&self) -> bool { self.inner.is_some() } /// Returns `true` if the stream reached its limit. pub fn is_limit_err(&self) -> bool { self.inner.is_none() } }
<div style=" background-image: url('/assets/img/slika39.jpg');background-size: cover; background-position: center center;background-repeat: no-repeat;"> <div class="register-form" > <div class="text-center mb-3 mt-5"> <img src="/assets/img/logo.png" width="150px" alt="Company Logo"> </div> <div class="text-center mb-4"> <h6 style="font-family: 'Open Sans', sans-serif;">Kreirajte svoj račun</h6> </div> <form (ngSubmit)="onSubmit()" #registerForm="ngForm"> <div class="form-input"> <span><i class="bi bi-person" style="color: #e91e63;"></i></span> <input type="text" id="firstName" name="firstName" [(ngModel)]="firstName" placeholder="Ime" required> </div> <div class="form-input"> <span><i class="bi bi-person" style="color: #e91e63;"></i></span> <input type="text" id="lastName" name="lastName" [(ngModel)]="lastName" placeholder="Prezime" required> </div> <div class="form-input"> <span><i class="bi bi-envelope" style="color: #e91e63;"></i></span> <input type="email" id="email" name="email" [(ngModel)]="email" placeholder="Email adresa" required> </div> <div class="form-input"> <span><i class="bi bi-gender-ambiguous" style="color: #e91e63;"></i></span> <select id="gender" name="gender" [(ngModel)]="gender" required> <option value="" disabled selected>Odaberite spol</option> <option value="male">Muško</option> <option value="female">Žensko</option> <option value="other">Ostalo</option> </select> </div> <div class="form-input"> <span><i class="bi bi-telephone" style="color: #e91e63;"></i></span> <input type="text" id="phoneNumber" name="phoneNumber" [(ngModel)]="phoneNumber" placeholder="Kontakt telefon" required> </div> <div class="form-input"> <span><i class="bi bi-geo-alt" style="color: #e91e63;"></i></span> <input type="text" id="country" name="country" [(ngModel)]="country" placeholder="Država" required> </div> <div class="form-input"> <span><i class="bi bi-geo-alt" style="color: #e91e63;"></i></span> <input type="text" id="city" name="city" [(ngModel)]="city" placeholder="Grad" required> </div> <div class="form-input"> <span><i class="bi bi-geo-alt" style="color: #e91e63;"></i></span> <input type="text" id="address" name="address" [(ngModel)]="address" placeholder="Adresa" required> </div> <div class="form-input"> <span><i class="bi bi-postcard" style="color: #e91e63;"></i></span> <input type="text" id="postalCode" name="postalCode" [(ngModel)]="postalCode" placeholder="Poštanski broj" required> </div> <div class="form-input"> <span><i class="bi bi-lock" style="color: #e91e63;"></i></span> <input type="password" id="password" name="password" [(ngModel)]="password" placeholder="Lozinka" required> <i class="bi bi-eye field-icon toggle-password icon" style="color: #e91e63;" (click)="togglePasswordVisibility()"></i> </div> <div class="form-input"> <span><i class="bi bi-lock" style="color: #e91e63;"></i></span> <input type="password" id="confirmPassword" name="confirmPassword" [(ngModel)]="confirmPassword" placeholder="Potvrdite lozinku" required> <i class="bi bi-eye field-icon toggle-password icon" style="color: #e91e63;" (click)="togglePasswordVisibility()"></i> </div> <div class="mb-3"> <button type="submit" class="btn btn-primary btn-block custom-register-btn" [disabled]="!registerForm.form.valid" style="display: flex;justify-content: center;">Registracija</button> </div> <div *ngIf="error" class="alert alert-danger" role="alert"> {{ error }} </div> <div class="text-center mb-5" style="color: #777;"> Već imate račun? <a [routerLink]="['/login']" class="login-link">Prijava</a> </div> </form> </div> </div>
#include <stdlib.h> #include <ctype.h> #include <stdio.h> #include "allocation.h" void* log_calloc(FILE* MemoryLogFile, size_t nMemb, size_t size) { void* ptr = calloc(nMemb, size); if (MemoryLogFile) { ON_HTML(fprintf(MemoryLogFile, "<p>" "Called calloc <br>" "Number of members: <em style=\"color:Red\">%ld</em><br>" "Size of members: <em style=\"color:Red\">%ld</em><br>" "Returned: <em style=\"color:Red\">%p</em> <br>" "----------------------<br>" "</p>", nMemb, size, ptr)); ON_LOG( fprintf(MemoryLogFile, "Called calloc \n" "Number of members: %ld\n" "Size of members: %ld\n" "Returned: %p \n" "----------------------\n", nMemb, size, ptr)); } return ptr; } void* log_realloc(FILE* MemoryLogFile, void* ptr, size_t SizeInBytes) { ptr = realloc(ptr, SizeInBytes); if (MemoryLogFile) { ON_HTML(fprintf(MemoryLogFile, "<p>" "Called realloc <br>" "Size in bytes: <em style=\"color:Red\">%ld</em><br>" "Returned: <em style=\"color:Red\">%p</em> <br>" "----------------------<br>" "</p>", SizeInBytes, ptr)); ON_LOG(fprintf(MemoryLogFile, "Called realloc \n" "Size in bytes: %ld \n" "Returned: %p \n" "----------------------\n", SizeInBytes, ptr)); } return ptr; } void* log_free(FILE* MemoryLogFile, void* ptr) { free(ptr); if (MemoryLogFile) { ON_HTML(fprintf(MemoryLogFile, "<p>" "Called free <br>" "Pointer: <em style=\"color:Red\">%p</em><br>" "----------------------<br>" "</p>", ptr)); ON_LOG(fprintf(MemoryLogFile, "Called free \n" "Pointer: %p \n" "----------------------\n", ptr)); } return ptr; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>JS비동기 : 3. 프라미스 연습1</title> <script> function 화면뿌려(이거) { document.querySelector("#show").innerHTML += 이거 + "<br>"; } function 킬링타임() { let d = new Date(); document.querySelector("#time").innerHTML = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds(); } /************************************************** [ 프라미스 체이닝 ] - 프라미스로 생성코드를 담고 then메서드로 사용코드를 실행시 연속해서 생성코드가 이어질 경우 다음 then메서드를 체이닝하여 연속 사용할 수 있다! 이때 프라미스로 생성코드를 리턴해야 기다린 후 다음 then메서드를 호출하여 원하는 기다림효과를 볼 수 있다! ((사용예)) 프라미스변수 .then(()=>return 프라미스) .then(()=>return 프라미스) .then(()=>마지막실행코드) _________________________________________________ [ 프라미스 병렬호출 ] - 프라미스는 병렬로 then메서드 호출이 가능하다! ((사용예)) 프라미스변수 .then(()=>실행코드1) 프라미스변수 .then(()=>실행코드2) -> 병렬호출은 프라미스 체이닝으로 해도 동일함! ->>> then 메서드에 return코드로 프라미스를 쓰지 않으면 모두 순서대로 프라미스 호출 후 바로 실행됨! ((사용예)) 프라미스변수 .then(()=>실행코드1) .then(()=>실행코드2) **************************************************/ // 프라미스 객체 생성시 함수내부 코드는 바로 실행됨! const myPromise = new Promise((scFn) => { // scFn - 성공함수 setTimeout(() => { 화면뿌려("나는 전도연이다!"); // 성공함수를 호출해야만 then메서드가 연결된다! scFn("약속이행"); // then메서드 전달 }, 2000); // 프라미스 후에 실행할 코드는 then() 메서드에 연결한다! myPromise .then((res) => { //res - 성공함수 리턴값 console.log("첫번째 then리턴값", res); // 시간이 걸리는 다른 코드는 프라미스 이후에 then메서드 호출시 실행된다! // 따라서 천제 기다리는 시간을 셋팅할 필요없다! // 단지 호출된 시점부터 얼마후 실행할지만 고려 // 여기서는 1초후 실행하기 // 다음 then메서드를 순서대로 기다렸다가 // 실행시키러면 then메서드안에 프라미스를 // 리턴해주는 형태로 코드를 작성해야함! return new Promise((scFn) => { setTimeout(() => { 화면뿌려( `<img src="https://images.khan.co.kr/article/2023/03/03/news-p.v1.20230303.139d5a1324fd43e9b750689a1c57af4e_P1.jpg" style="height:70vh" alt="길복순">` ); // 다음의 then메서드를 호출함 scFn("두번째 약속이행!"); }); /////new Promise /////// }, 1000); }) // 프라미스 체이닝(then메서드를 이어붙임!) // -> 개별적으로 프라미스에 붙여사용할 것을 // 더 쉽게 이어붙이는 방법의 코딩임! // myPromise.then(() => { .then((res) => { console.log("두번째 then리턴값", res); // 다음 메서드 순차실행을 위해 프라미스 리턴 return new Promise((scFn) => { setTimeout(() => { 화면뿌려(`킬링타임<div id="time" style="font-size:5vh"></div>`); // 다음 then메서드에 전달할 성공함수 호출! scFn("세번째 약속이행!"); }, 1000); }); }) .then((res) => { console.log("세번째 then리턴값", res); // 여기서는 프라미스 리턴 불필요! // 왜? 마지막 코드니까! setInterval(킬링타임, 1000); }); // 일정시간 후 함수실행 -> 비동기함수 호출! // setTimeout(() => setInterval(킬링타임, 1000), 6000); // setTimeout(() => { // 화면뿌려(`킬링타임<div id="time" style="font-size:5vh"></div>`); // }, 5000); // setTimeout(() => { // 화면뿌려( // `<img src="https://images.khan.co.kr/article/2023/03/03/news-p.v1.20230303.139d5a1324fd43e9b750689a1c57af4e_P1.jpg" style="height:70vh" alt="길복순">` // ); // }, 4000); // setTimeout(() => { // 화면뿌려("나는 전도연이다!"); // }, 2000); </script> <style> @import url("https://fonts.googleapis.com/css2?family=Nanum+Brush+Script&display=swap"); body { background-image: linear-gradient(to bottom, #494949, gray); background-repeat: no-repeat; background-attachment: fixed; text-align: center; } #show { font-family: "Nanum Brush Script", cursive; font-size: 5vw; background-image: linear-gradient(to bottom, red, orange, pink, aqua); background-clip: text; -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-repeat: no-repeat; font-weight: bold; } </style> </head> <body> <div id="show"></div> </body> </html>
import React, { useState } from 'react'; import { User, Phone, Mail, Lock, ChevronRight } from 'lucide-react'; import { useNavigate } from 'react-router-dom'; const Signup = () => { const navigate = useNavigate(); const [formData, setFormData] = useState({ name: '', gender: '', mobile: '', email: '', password: '', confirmPassword: '', }); const [loading, setLoading] = useState(false); const [error, setError] = useState(''); const [success, setSuccess] = useState(false); const handleChange = (e) => { const { name, value } = e.target; setFormData(prev => ({ ...prev, [name]: value })); setError(''); }; const handleSubmit = async (e) => { e.preventDefault(); if (formData.password !== formData.confirmPassword) { setError('Passwords do not match'); return; } if (formData.mobile.length !== 10 || !/^[0-9]+$/.test(formData.mobile)) { setError('Invalid mobile number'); return; } if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+]).{8,}$/.test(formData.password)) { setError('Password must contain at least one number, one lowercase letter, one uppercase letter, and one special character'); return; } setLoading(true); try { const response = await fetch('https://mediconnect-but5.onrender.com/api/patient/signup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formData), }); const data = await response.json(); if (response.ok) { setSuccess(true); setFormData({ name: '', gender: '', mobile: '', email: '', password: '', confirmPassword: '', }); // Navigate to login page after successful signup setTimeout(() => { navigate('/patient/login'); }, 2000); } else { setError(data.error || 'Signup failed. Please try again.'); } } catch (err) { setError(err.message); } finally { setLoading(false); } }; return ( <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-50"> {/* Navbar */} <nav className="bg-white shadow-sm"> <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8"> <div className="flex justify-between h-16 items-center"> <div className="flex items-center"> <span className="text-2xl font-bold text-indigo-600">mediConnect</span> </div> <button onClick={() => { navigate('/patient/login') }} className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-indigo-600 bg-white hover:bg-indigo-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors duration-200" > Login <ChevronRight className="ml-2 h-4 w-4" /> </button> </div> </div> </nav> {/* Main Content */} <div className="max-w-md mx-auto py-12 px-4 sm:px-6 lg:px-8"> <div className="bg-white rounded-xl shadow-xl p-8"> <div className="text-center mb-8"> <h2 className="text-2xl font-bold text-gray-900">Join mediConnect</h2> <p className="mt-2 text-gray-600">Create your patient account to get started</p> </div> {error && ( <div className="mb-6 p-4 bg-red-50 border border-red-200 text-red-700 rounded-md flex items-center"> <span>{error}</span> </div> )} {success && ( <div className="mb-6 p-4 bg-green-50 border border-green-200 text-green-700 rounded-md flex items-center"> <span>Account created successfully!</span> </div> )} <form onSubmit={handleSubmit} className="space-y-6"> <div className="space-y-4"> <div className="relative flex items-center"> <User className="absolute left-3 h-5 w-5 text-gray-400" /> <input type="text" name="name" value={formData.name} onChange={handleChange} placeholder="Full Name" className="pl-10 w-full h-12 rounded-lg border border-gray-300 bg-white px-3 shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 transition-colors duration-200" required /> </div> <select name="gender" value={formData.gender} onChange={handleChange} className="w-full h-12 rounded-lg border border-gray-300 bg-white px-3 shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 transition-colors duration-200" required > <option value="">Select Gender</option> <option value="Male">Male</option> <option value="Female">Female</option> <option value="Other">Other</option> </select> <div className="relative flex items-center"> <Phone className="absolute left-3 h-5 w-5 text-gray-400" /> <input type="tel" name="mobile" value={formData.mobile} onChange={handleChange} placeholder="Mobile Number" className="pl-10 w-full h-12 rounded-lg border border-gray-300 bg-white px-3 shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 transition-colors duration-200" required /> </div> <div className="relative flex items-center"> <Mail className="absolute left-3 h-5 w-5 text-gray-400" /> <input type="email" name="email" value={formData.email} onChange={handleChange} placeholder="Email Address" className="pl-10 w-full h-12 rounded-lg border border-gray-300 bg-white px-3 shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 transition-colors duration-200" required /> </div> <div className="relative flex items-center"> <Lock className="absolute left-3 h-5 w-5 text-gray-400" /> <input type="password" name="password" value={formData.password} onChange={handleChange} placeholder="Password" className="pl-10 w-full h-12 rounded-lg border border-gray-300 bg-white px-3 shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 transition-colors duration-200" required /> </div> <div className="relative flex items-center"> <Lock className="absolute left-3 h-5 w-5 text-gray-400" /> <input type="password" name="confirmPassword" value={formData.confirmPassword} onChange={handleChange} placeholder="Confirm Password" className="pl-10 w-full h-12 rounded-lg border border-gray-300 bg-white px-3 shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 transition-colors duration-200" required /> </div> </div> <button type="submit" disabled={loading} className="w-full flex justify-center py-3 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200" > {loading ? 'Creating Account...' : 'Create Account'} </button> </form> </div> </div> </div> ); }; export default Signup;
import React, { useEffect, useState } from 'react'; import { useParams } from 'react-router-dom'; import { PageLayout } from '../components/layout/PageLayout'; import { Card } from '../components/ui/Card'; import { Badge } from '../components/ui/Badge'; import { AuthorBadge } from '../components/blog/AuthorBadge'; import { useBlogPost } from '../hooks/useBlogPost'; import { formatDate } from '../utils/date'; export function BlogPost() { const { slug } = useParams(); const { post, isLoading, error } = useBlogPost(slug!); if (isLoading) { return ( <PageLayout> <div className="animate-pulse space-y-4"> <div className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-1/2" /> <div className="h-64 bg-gray-200 dark:bg-gray-700 rounded" /> </div> </PageLayout> ); } if (error || !post) { return ( <PageLayout> <Card className="p-6 bg-red-50 dark:bg-red-900/20"> <p className="text-red-600 dark:text-red-400"> {error || 'Post not found'} </p> </Card> </PageLayout> ); } return ( <PageLayout> <article className="max-w-4xl mx-auto"> {post.cover_image && ( <img src={post.cover_image} alt={post.title} className="w-full h-96 object-cover rounded-lg mb-8" /> )} <h1 className="text-4xl font-bold mb-4">{post.title}</h1> <div className="flex items-center justify-between mb-8"> <AuthorBadge name={post.author_name} verified={post.author_verified} /> <div className="text-sm text-gray-500"> {formatDate(post.created_at)} </div> </div> <div className="prose dark:prose-invert max-w-none mb-8"> {post.content.split('\n').map((paragraph, index) => ( <p key={index}>{paragraph}</p> ))} </div> <div className="flex flex-wrap gap-2"> {post.tags.map(tag => ( <Badge key={tag} variant="outline"> {tag} </Badge> ))} </div> </article> </PageLayout> ); }
import CloudUploadIcon from '@mui/icons-material/CloudUpload'; import { TextField } from '@mui/material'; import Button from '@mui/material/Button'; import { styled } from '@mui/material/styles'; import MDBox from 'components/MDBox'; import MDButton from 'components/MDButton'; import useVirusTotal from 'hooks/virustotal/useVirusTotal'; import * as React from 'react'; import { useLocation } from 'react-router-dom'; import Swal from 'sweetalert2'; const VisuallyHiddenInput = styled('input')({ clip: 'rect(0 0 0 0)', clipPath: 'inset(50%)', height: 1, overflow: 'hidden', position: 'absolute', bottom: 0, left: 0, whiteSpace: 'nowrap', width: 1, }); export default function ScanFile({ onScan = () => { } }) { // get id=hash from the url using the useLocation hook const loc = useLocation(); const id = new URLSearchParams(loc.search).get('id'); const [hash, setHash] = React.useState(''); const { renderNotifications, handleFileScan, handleHashScan, } = useVirusTotal(); const handleUrlScan = () => { handleHashScan(hash).then((data) => { onScan(data); }); }; const handleFileUpload = (e) => { const file = e.target.files[0]; if (!file) return; if (file.size > 32 * 1024 * 1024) { Swal.fire({ icon: 'error', title: 'File size too large', text: 'Please upload a file less than 32MB in size', }) } handleFileScan(file).then((data) => { onScan(data); }); }; React.useEffect(() => { if (id) { setHash(id); handleHashScan(id).then((data) => { onScan(data); }); } }, [id]); return ( <div className=''> <MDBox> <MDBox className="flex gap-4 flex-col md:flex-row"> <TextField id="outlined-basic" label="Enter File Hash" variant="outlined" style={{ height: '100%', }} value={hash} onChange={e => setHash(e.target.value)} className='flex-1' /> <MDButton color='secondary' variant='outlined' onClick={handleUrlScan}> Scan Hash </MDButton> <MDBox className="w-full md:w-fit"> <Button className="text-white w-full" component="label" role={undefined} variant="contained" tabIndex={-1} startIcon={<CloudUploadIcon />} > Upload file <VisuallyHiddenInput type="file" onChange={handleFileUpload} /> </Button> </MDBox> </MDBox> <p className='italic ml-4 text-sm'> By submitting data above, you agree to our Terms of Service and Privacy Notice, and consent to sharing your submission with the security community. </p> </MDBox> {renderNotifications} </div> ); }
package com.example.demo; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authorize -> authorize .requestMatchers("/login", "/logout", "/webjars/**", "/css" + "/**").permitAll() .anyRequest().authenticated() ) .oauth2Login(oauth2 -> oauth2 .loginPage("/login") .defaultSuccessUrl("/home", true) .failureUrl("/error?error=Login failed") ).logout(logout -> logout .logoutUrl("/logout") .invalidateHttpSession(true) .clearAuthentication(true) ); return http.build(); } }
package com.example.dicodingevent.data.network.dto import com.example.dicodingevent.domain.model.Event import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class EventDto( @Json(name = "id") val id: Int, @Json(name = "name") val name: String, @Json(name = "summary") val summary: String, @Json(name = "description") val description: String, @Json(name = "imageLogo") val imageLogo: String, @Json(name = "mediaCover") val mediaCover: String, @Json(name = "category") val category: String, @Json(name = "ownerName") val ownerName: String, @Json(name = "cityName") val cityName: String, @Json(name = "quota") val quota: Int, @Json(name = "registrants") val registrants: Int, @Json(name = "beginTime") val beginTime: String, @Json(name = "endTime") val endTime: String, @Json(name = "link") val link: String ) fun EventDto.toEvent(): Event { return Event( id = id, name = name, summary = summary, description = description, imageLogo = imageLogo, mediaCover = mediaCover, category = category, ownerName = ownerName, cityName = cityName, quota = quota, registrants = registrants, beginTime = beginTime, endTime = endTime, link = link ) }
import * as React from 'react'; import { Button, Box, Field, Flex, Popover, Typography, useComposedRefs, } from '@strapi/design-system'; import { CaretDown } from '@strapi/icons'; import { useField, type InputProps, type FieldValue } from '@strapi/strapi/admin'; import { HexColorPicker } from 'react-colorful'; import { useIntl } from 'react-intl'; import { styled } from 'styled-components'; import { getTrad } from '../utils/getTrad'; const ColorPreview = styled.div` border-radius: 50%; width: 20px; height: 20px; margin-right: 10px; background-color: ${(props) => props.color}; border: 1px solid rgba(0, 0, 0, 0.1); `; const ColorPicker = styled(HexColorPicker)` && { width: 100%; aspect-ratio: 1.5; } .react-colorful__pointer { width: ${({ theme }) => theme.spaces[3]}; height: ${({ theme }) => theme.spaces[3]}; } .react-colorful__saturation { border-radius: ${({ theme }) => theme.spaces[1]}; border-bottom: none; } .react-colorful__hue { border-radius: 10px; height: ${({ theme }) => theme.spaces[3]}; margin-top: ${({ theme }) => theme.spaces[2]}; } `; const ColorPickerToggle = styled(Button)` & > span { display: flex; justify-content: space-between; align-items: center; width: 100%; } svg { width: ${({ theme }) => theme.spaces[2]}; height: ${({ theme }) => theme.spaces[2]}; } svg > path { fill: ${({ theme }) => theme.colors.neutral500}; justify-self: flex-end; } `; const ColorPickerPopover = styled(Popover.Content)` padding: ${({ theme }) => theme.spaces[2]}; min-height: 270px; `; type ColorPickerInputProps = InputProps & FieldValue & { labelAction?: React.ReactNode; }; export const ColorPickerInput = React.forwardRef<HTMLButtonElement, ColorPickerInputProps>( ( { hint, disabled = false, labelAction, label, name, required = false, onChange, value, error }, forwardedRef ) => { const [showColorPicker, setShowColorPicker] = React.useState(false); const colorPickerButtonRef = React.useRef<HTMLButtonElement>(null!); const { formatMessage } = useIntl(); const color = value || '#000000'; const composedRefs = useComposedRefs(forwardedRef, colorPickerButtonRef); return ( <Field.Root name={name} id={name} error={error} hint={hint} required={required}> <Flex direction="column" alignItems="stretch" gap={1}> <Field.Label action={labelAction}>{label}</Field.Label> <Popover.Root onOpenChange={setShowColorPicker}> <Popover.Trigger> <ColorPickerToggle ref={composedRefs} aria-label={formatMessage({ id: getTrad('color-picker.toggle.aria-label'), defaultMessage: 'Color picker toggle', })} aria-controls="color-picker-value" aria-haspopup="dialog" aria-expanded={showColorPicker} aria-disabled={disabled} disabled={disabled} variant="tertiary" size="L" > <Flex> <ColorPreview color={color} /> <Typography style={{ textTransform: 'uppercase' }} textColor={value ? undefined : 'neutral600'} variant="omega" > {color} </Typography> </Flex> <CaretDown aria-hidden /> </ColorPickerToggle> </Popover.Trigger> <ColorPickerPopover sideOffset={4}> <ColorPicker color={color} onChange={(hexValue) => onChange(name, hexValue)} /> <Flex paddingTop={3} paddingLeft={4} justifyContent="flex-end"> <Box paddingRight={2}> <Typography variant="omega" tag="label" textColor="neutral600"> {formatMessage({ id: getTrad('color-picker.input.format'), defaultMessage: 'HEX', })} </Typography> </Box> <Field.Root> <Field.Input aria-label={formatMessage({ id: getTrad('color-picker.input.aria-label'), defaultMessage: 'Color picker input', })} style={{ textTransform: 'uppercase' }} value={value} placeholder="#000000" onChange={onChange} /> </Field.Root> </Flex> </ColorPickerPopover> </Popover.Root> <Field.Hint /> <Field.Error /> </Flex> </Field.Root> ); } );
local spritesheet = require('spritesheet') local pickable = require('src.pickable') local timer = require('src.system.timer') local inventory = require('src.pickables.inventory') -- Initialize player variables player = { x = 0, y = 0, -- Vertical velocity (initially zero) yVelocity = 0, -- Flag to check if the player is on the ground imagePath = 'sprites/icedragon-anims-lg.png', scaleX = 1, scaleY = 1, width = 1, height = 1, onGround = false, facing = LEFT, collider = nil, quads = nil, image = nil, currentSprite = 1, hp = 2, inventory = inventory(), dead = false, canAccelJump = true, jumpTimerExpired = false } -- Set player jump strength (adjust as needed) PLAYER_SPEED = 6000 JUMP_STRENGTH = 1900 MAX_SPEED = 500 FORCE_JUMP_ACCELLERATION = 12000 FORCE_JUMP_MAX_SPEED = 500 FORCE_JUMP_START_SPEED = 300 WIN_CONDITION = 3 local debugCircle = {} local debugCollisionText = "" local function isFalling(collider) local _, vy = collider:getLinearVelocity() return vy > 0 end local function playerBelowPlatform(playercollider, platformcollider) local _, py = playercollider:getPosition() local _, ty = platformcollider:getPosition() local th = TILE_SIZE return py > ty - th end local function isInPit() end local function feetTouchGround(playercollider, groundcollider) -- is the player passing through a one-way platform or above it return not playerBelowPlatform(playercollider, groundcollider) end local function preSolve(playerc, collidedc, contact) local nx, ny = contact:getNormal() debugCollisionText = ny if not playerc.collision_class == Colliders.PLAYER then return end if collidedc.collision_class == Colliders.GROUND then if ny ~= 0 and feetTouchGround(playerc, collidedc) and not isFalling(playerc) then player.onGround = true player.canAccelJump = true end elseif collidedc.collision_class == Colliders.PLATFORMS then if playerBelowPlatform(playerc, collidedc) then contact:setEnabled(false) else if not isFalling(player.collider) then player.onGround = true player.canAccelJump = true end end end -- don't get pushed around by coins if collidedc.collision_class == Colliders.CONSUMABLE then contact:setEnabled(false) end end function player.Draw() local px, py = player.collider:getPosition() local scaleX if player.facing == RIGHT then scaleX = player.scaleX else -- players origin is their left side, so when the image -- flips we need to push them right player.x = player.x + player.width scaleX = -player.scaleX end if DEBUG then love.graphics.setColor(DebugPlayerColor(player.onGround)) end player.currentAnim8:draw( player.image, player.x - player.width / 2, player.y - player.height / 2, 0, scaleX, player.scaleY) if DEBUG then local vx, vy = player.collider:getLinearVelocity() love.graphics.setColor(Colors.DebugText()) love.graphics.print(px .. "\n" .. py .. "\n", px - 40, py - 40) love.graphics.setColor(Colors.RED()) love.graphics.print("yVel:" .. vy .. "\n" .. "xVel:" .. vx .. "\n", px - 40, py + 40) if not player.onGround then love.graphics.setColor(Colors.GREEN()) else love.graphics.setColor(Colors.RED()) end local onGroundText = "inAir:" .. (player.onGround and 'false' or 'true') local jumpKeyPressed = "jumpKey:" .. (love.keyboard.isDown('space') and 'true' or 'false') local jumpExpired = "jumpExpired:" .. (player.jumpTimerExpired and 'true' or 'false') local debugCollisionText = "collision normal:" .. debugCollisionText love.graphics.print(jumpKeyPressed .. " " .. onGroundText .. " " .. jumpExpired .. "\n" .. debugCollisionText, px + 32, py) love.graphics.setColor(Colors.RED()) if debugCircle[1] ~= nil then love.graphics.circle('fill', debugCircle[1], debugCircle[2], 3) end end end function Face(direction) player.facing = direction if direction == LEFT then player.currentSprite = 1 else player.currentSprite = 2 end end local function resetAnim() player.currentAnim8 = player.animations.idle end local function chooseConstantAnimation(velocity) if player.currentAnim8 ~= player.animations.walk and player.currentAnim8 ~= player.animations.idle then return end if velocity == 0 then player.currentAnim8 = player.animations.idle else player.currentAnim8 = player.animations.walk end end local function hurt() local ec = player.collider:getEnterCollisionData('Enemy') local hurt = false hurt = ec.collider:getObject():attak(player) if hurt == false then return end if player.currentAnim8 == player.animations.hurt then return end print('oof') player.currentAnim8 = player.animations.hurt player.hp = player.hp - 1 if player.hp <= 0 then player.dead = true player.currentAnim8 = player.animations.ded end end local function checkInAir() if player.collider:exit(Colliders.GROUND) or player.collider:exit(Colliders.PLATFORMS) then return true end end function player.UpdatePlayer(dt) local px = player.collider:getLinearVelocity() if checkInAir() then player.onGround = false end -- anim chooseConstantAnimation(px) player.currentAnim8:update(dt) if player.dead or player.win then return end -- damage if player.collider:enter(Colliders.ENEMY) then hurt() end -- Check keyboard input if (love.keyboard.isDown('d') or love.keyboard.isDown('right')) and px < MAX_SPEED then player.collider:applyForce(PLAYER_SPEED, 0) Face(RIGHT) elseif (love.keyboard.isDown('a') or love.keyboard.isDown('left')) and px > -MAX_SPEED then player.collider:applyForce(-PLAYER_SPEED, 0) Face(LEFT) end -- Update player position based on collider player.x, player.y = player.collider:getX(), player.collider:getY() if player.collider:enter(Colliders.CONSUMABLE) then local collided = player.collider:getEnterCollisionData(Colliders.CONSUMABLE) local pickup = collided.collider player.inventory:add(pickable.Pickup(pickup)) end -- if player.jumpTimerExpired then player.jumpTimerExpired = false end end local function expireJumpTimer() player.jumpTimerExpired = true end function player.Jump() local vx, vy = player.collider:getLinearVelocity() if love.keyboard.isDown('space') and vy >= -FORCE_JUMP_MAX_SPEED and player.canAccelJump and not player.jumpStarted and player.onGround then -- start jump player.jumpStarted = true -- if traversing a wall or flying into a ceiling bc of this dumb algo, expire after a half sec or somethin timer.add('JumpTimer', .5, expireJumpTimer, false) player.collider:setLinearVelocity(vx, -FORCE_JUMP_START_SPEED) else -- at top jump speed or jump key released or timer expired if player.jumpStarted then if not love.keyboard.isDown('space') or vy <= -FORCE_JUMP_MAX_SPEED or player.jumpTimerExpired then print('arc') player.jumpStarted = false player.canAccelJump = false end end if player.jumpStarted and player.canAccelJump and vy >= -FORCE_JUMP_MAX_SPEED then -- keep accellerating jump until max print('accel') player.collider:applyForce(0, -FORCE_JUMP_ACCELLERATION) end if player.jumpTimerExpired then player.jumpTimerExpired = false end end end function player.LinearJump() if player.onGround then player.onGround = false local vx, vy = player.collider:getLinearVelocity() player.collider:setLinearVelocity(vx, 0) player.collider:applyLinearImpulse(0, -JUMP_STRENGTH) end end function player.InitPlayer(scaleX, scaleY, goal, startX, startY) local playerWidth = 32 -- actual number of pixels wide for each sprite in the sprite sheet local playerHeight = 32 -- actual number of pixels high for each sprite in the sprite sheet player.scaleX = scaleX player.scaleY = scaleY player.width = playerWidth * scaleX player.height = playerWidth * scaleY player.collider = World:newBSGRectangleCollider( player.x, player.y, player.width / 1.34, player.height, 6 ) player.collider:setCollisionClass(Colliders.PLAYER) player.collider:setFixedRotation(true) player.collider:setPreSolve(preSolve) player.collider:setObject(player) player.image = love.graphics.newImage(player.imagePath) player.grid = spritesheet.NewAnim8Grid(player.image, playerWidth, playerHeight) player.animations = {} player.animations.walk = Anim8.newAnimation(player.grid('1-6', 1), 0.1) player.animations.idle = Anim8.newAnimation(player.grid('1-4', 2), 0.2) player.animations.jump = Anim8.newAnimation(player.grid('1-2', 3), 0.2, function() resetAnim() end) player.animations.hurt = Anim8.newAnimation(player.grid('1-2', 4), 0.2, function() resetAnim() end) player.animations.ded = Anim8.newAnimation(player.grid('1-2', 5), 0.2, 'pauseAtEnd') player.currentAnim8 = player.animations.walk player.goal = goal Face(RIGHT) player.x = startX player.y = startY player.collider:setX(player.x) player.collider:setY(player.y) player.initialized = true print('start at ', player.x, player.y) end return player
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class BSTIterator { static List<Integer> list; static int cur; public BSTIterator(TreeNode root) { cur = 0; list = new ArrayList(); search(root); } private static void search(TreeNode node) { if (node == null) { return; } search(node.left); list.add(node.val); search(node.right); } public boolean hasNext() { return cur < list.size(); } public int next() { return list.get(cur++); } public boolean hasPrev() { return cur > 1; } public int prev() { cur -= 2; return list.get(cur++); } } /** * Your BSTIterator object will be instantiated and called as such: * BSTIterator obj = new BSTIterator(root); * boolean param_1 = obj.hasNext(); * int param_2 = obj.next(); * boolean param_3 = obj.hasPrev(); * int param_4 = obj.prev(); */
// // StorageManager.swift // Drunkard 1.0 // // Created by USER on 01.08.22. // import Foundation import FirebaseStorage final class storageManager { static let shared = storageManager() private let storage = Storage.storage().reference() /* /images/(safeEmail)_profile_pircute.png /images/(safeEmail)_background_picture.png */ public typealias UploadPictureCompletion = (Result<String,Error>) -> Void public func uploadBackgroundPicture(with Data: Data, filename: String, completion: @escaping UploadPictureCompletion){ storage.child("images/\(filename)").putData(Data, metadata: nil) { metadata, error in guard error == nil else { //failed print("failed to upload picture") completion(.failure(StorageErrors.failedToUpload)) return } self.storage.child("images/\(filename)").downloadURL { url, error in guard let url = url else { print("failed to download url") completion(.failure(StorageErrors.failedToDownloadURL)) return } let urlString = url.absoluteString print("url string downloaded: \(urlString)") completion(.success(urlString)) } } } public func uploadPicture(with Data: Data, filename: String, completion: @escaping UploadPictureCompletion){ storage.child("images/\(filename)").putData(Data, metadata: nil) { metadata, error in guard error == nil else { //failed print("failed to upload picture") completion(.failure(StorageErrors.failedToUpload)) return } self.storage.child("images/\(filename)").downloadURL { url, error in guard let url = url else { print("failed to download url") completion(.failure(StorageErrors.failedToDownloadURL)) return } let urlString = url.absoluteString print("url string downloaded: \(urlString)") completion(.success(urlString)) } } } public enum StorageErrors: Error { case failedToUpload case failedToDownloadURL } public func downloadURL(for path: String, completion: @escaping (Result<URL, Error>) -> Void ) { let reference = storage.child(path) reference.downloadURL { url, error in guard let url = url, error == nil else { completion(.failure(StorageErrors.failedToDownloadURL)) return } completion(.success(url)) } } }
// // Maxheapify.c // // // // #include <stdio.h> #include <stdlib.h> typedef struct newstruct { int size; int array[100]; }heap; void printHEAP(heap * A) { for(int i =0; i<A->size; i++){ printf("%d ",A->array[i]); } printf("\n\n"); } int parent(int i){ return (i-1)/2; } int left_child(int i){ return 2*i+1; } int right_child(int i){ return 2*i+2; } void swap(int *x, int *y){ int temp = *x; *x = *y; *y = temp; } void maxheapify(heap *A, int index){ printf("in maxheapify\n"); int left = left_child(index); int right = right_child(index); int largest=index; if (left<=A->size && A->array[left]>A->array[index]) { largest=left; } if( right<=A->size && A->array[right]>A->array[largest]){ largest=right; } if(largest!=index){ int buffer; buffer=A->array[index]; A->array[index]=A->array[largest]; A->array[largest]=buffer; maxheapify(A,largest); printf("finished maxheapify \n"); } } void buildmaxheap(heap *A){ printf("In buildmax-heap\n"); int i; for (i= ((A->size)/2)-1;i>=0;i--) { maxheapify(A,i); } printf("finished buildmax-heap\n"); } void insertkey(heap *A, int new){ printf("in Insertkey\n"); A->array[A->size]=new; A->size=A->size+1; printf("the size is %d\n",A->size); buildmaxheap(A); maxheapify(A,A->size/2); printf("finished insertkey \n"); } void extractmax(heap *A){ printf("in extractmax \n"); printf("Extracting the MAX value Which is %d\n",A->array[0]); A->array[0]=A->array[A->size-1]; A->array[A->size-1]=0; A->size=A->size-1; buildmaxheap(A); maxheapify(A,0); printf("The new MAX value is %d\n",A->array[0]); printf("finsihed extractmax\n"); } void changekey(heap *A, int key, int new){ printf("in changekey\n"); printf("Chaning the value of %d to %d\n",A->array[key],new); A->array[key]=new; buildmaxheap(A); maxheapify(A,key); printf("finished changekey\n"); } void deletekey( heap *A, int key){ printf("in Deletekey\n"); printf("Delteing the following key which is %d\n",A->array[key]); int last=A->array[A->size-1]; A->array[A->size-1]=0; A->size=A->size-1; changekey(A,key, last); buildmaxheap(A); maxheapify(A,key); printf("finished deletekey\n"); } heap* filescan(FILE *f){ printf("in filescan\n"); if (!f) { printf("File not found\n"); exit(0); }else{ heap * A=malloc(sizeof(heap)); int size; fscanf(f, "%d", &size); A->size=size; for(int j =0; j<100;j++) { A->array[j]=0; } for(int i=0; i<size;i++){ fscanf(f,"%d", &A->array[i]); } printf("in filescan\n"); buildmaxheap(A); char letter; int firstp; int secondp; while(!feof(f)){ fscanf(f,"%c", &letter); if (A->size == 0) { break; } switch (letter) { case 'I': fscanf(f,"%d", &firstp); printf("The value of the key that is being inserted is %d\n",firstp); insertkey(A,firstp); printHEAP(A); break; case 'E': extractmax(A); printHEAP(A); break; case 'C': fscanf(f,"%d %d", &firstp, &secondp); printf("The key that is being changed is %d and is being changed with %d\n",firstp,secondp); changekey(A,firstp-1, secondp); printHEAP(A); break; case 'D': fscanf(f,"%d", &firstp); printf("The key that is being deleted is %d\n",firstp); deletekey(A,firstp-1); printHEAP(A); break; default: break; } } return A; } } int main(void){ FILE *f; f=fopen("file.txt", "r"); heap * A=filescan(f); fclose(f); printf("\n"); printf("FINAL ANS:\n"); printHEAP(A); printf("\n"); return 0; }
import { DatePipe } from '@angular/common'; import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable, catchError, throwError } from 'rxjs'; import { User } from '../models/user'; @Injectable({ providedIn: 'root' }) export class UserService { private baseUrl = 'http://localhost:8083/'; private url = 'api/users'; constructor( private http: HttpClient, ) { } index(): Observable<User[]>{ return this.http.get<User[]>(this.url) .pipe( catchError((err:any) => { console.log(err); return throwError(() => new Error('userService.index(): error')); }) ); } create(user: User): Observable<User>{ return this.http.post<User>(this.url, user) .pipe( catchError((err:any) => { console.log(err); return throwError(() =>new Error('userService.create(): error')); }) ); } show(userId: number): Observable<User>{ return this.http.get<User>( this.url+'/'+userId).pipe( catchError((err: any) => { console.log(err); return throwError(() =>new Error('userService.show(): error')); })); } update(user: User): Observable<User>{ return this.http.put<User>(this.url+'/'+user.id, user).pipe( catchError((err:any) => { console.log(err); console.log('userService.update(): error'); return throwError( () => new Error('userService.update(): error'+err)) }) ); } destroy(userId: number): Observable<void> { return this.http.delete<void>(this.url+'/'+userId).pipe( catchError((err:any) => { console.log(err); console.log('userService.destroy(): error'); return throwError( () => new Error('userService.destroy(): error'+err)); }) ) } }
import React, { useState, useEffect } from 'react'; import { useNavigate, useLocation } from 'react-router-dom'; import io from 'socket.io-client'; import BootStrap from './BootStrap'; const socket = io.connect("http://localhost:8000"); export default function ChattingRooms() { const [rooms, setRooms] = useState({}); const [newRoomName, setNewRoomName] = useState(''); const navigate = useNavigate(); const location = useLocation(); const initialCrewName = location.state?.crewName; // Home에서 받은 crewName useEffect(() => { socket.emit("requestRooms"); // 서버에서 채팅방 목록 요청 socket.on("roomsList", (receivedRooms) => { setRooms(receivedRooms); }); return () => { socket.off("roomsList"); }; }, []); const createRoom = () => { socket.emit("createRoom", newRoomName); // 새 채팅방 생성 요청 setNewRoomName(''); }; const joinRoom = (roomId) => { navigate(`/room/${roomId}`, { state: { crewName: initialCrewName } }); // 특정 채팅방에 입장 }; return (<> <BootStrap /> <div className='helloRooms'> <h1 className='show-Title'>Talk Together</h1> <div className='show-chatting-rooms'> <input type="text" className="form-control" value={newRoomName} onChange={(e) => setNewRoomName(e.target.value)}/> <button onClick={createRoom} className="btn btn-outline-success">Create Room</button> </div> <ul className="rooms-list"> {Object.entries(rooms) .map(([id, room]) => ( <li key={id}> {room.name} <button onClick={() => joinRoom(id)} className="btn btn-outline-primary">Join Room</button> </li> ))} </ul> </div> </>); }
"use client" import Link from "next/link" import { usePathname } from "next/navigation" const Links = [ { name: "Home", path: '/', }, { name: "About Me", path: "/about", }, { name: "Services", path: "/services", }, { name: "Work", path: "/work", }, { name: "Contact", path: "/contact", }, ]; const Nav = () => { const pathname = usePathname(); console.log(pathname); return ( <nav className="flex gap-12"> {Links.map((LinkItem, index) => { const isActive = pathname === LinkItem.path; return ( <Link href={LinkItem.path} key={index} className={`${isActive ? "text-white border-b-2 border-purple" : ""} capitalize= "text-[18px] hover:text-white transition-all`} > {LinkItem.name} </Link> ); })} </nav> ); }; export default Nav;
--- id: integrations-llamaindex title: LlamaIndex sidebar_label: LlamaIndex --- ## Quick Summary LlamaIndex is a data framework for LLMs that facilitates the ingestion of data from various sources such as APIs, databases, and PDFs, and indexes it for later retrieval in RAG-based LLM applications. ## Evaluating LlamaIndex RAG applications built using LlamaIndex can be easily evaluated within `deepeval`. Lets use this RAG application built using Llamaindex as an example: ```python from llama_index import VectorStoreIndex, SimpleDirectoryReader # Consult the LlamaIndex docs if you're unsure what this does documents = SimpleDirectoryReader("YOUR_DATA_DIRECTORY").load_data() index = VectorStoreIndex.from_documents(documents) rag_application = index.as_query_engine() ``` You can then query your RAG application and evaluate each response using `deepeval`'s metrics: ```python from deepeval.metrics import AnswerRelevancyMetric from deepeval.test_case import LLMTestCase ... # An example input to your RAG application user_input = "What is LlamaIndex?" # LlamaIndex returns a response object that contains # both the output string and retrieved nodes response_object = rag_application.query(user_input) # Process the response object to get the output string # and retrieved nodes if response_object is not None: actual_output = response_object.response retrieval_context = [node.get_content() for node in response_object.source_nodes] # Create a test case and metric as usual test_case = LLMTestCase( input=user_input, actual_output=actual_output, retrieval_context=retrieval_context ) answer_relevancy_metric = AnswerRelevancyMetric() # Evaluate answer_relevancy_metric.measure(test_case) print(answer_relevancy_metric.score) print(answer_relevancy_metric.reason) ``` :::info You can also extract all necessary outputs and retrieval contexts for each given input to your LlamaIndex application to [create an `EvaluationDataset` to evaluate test cases in bulk.](evaluation-datasets) ::: ## Unit Testing LlamaIndex Unit testing LlamaIndex is as simple as defining an `EvaluationDataset` and generating `actual_output`s and `retrieval_context`s at evaluation time. Building upon the previous example: ```python test_llamaindex.py import pytest from deepeval import assert_test from deepeval.metrics import AnswerRelevancyMetric from deepeval.test_case import LLMTestCase from deepeval.dataset import EvaluationDataset, Golden example_golden = Golden(input="What is LlamaIndex?") dataset = EvaluationDataset(goldens=[example_golden]) @pytest.mark.parametrize( "golden", dataset.goldens, ) def test_rag(golden: Golden): # LlamaIndex returns a response object that contains # both the output string and retrieved nodes response_object = rag_application.query(golden.input) # Process the response object to get the output string # and retrieved nodes if response_object is not None: actual_output = response_object.response retrieval_context = [node.get_content() for node in response_object.source_nodes] test_case = LLMTestCase( input=golden.input, actual_output=actual_output, retrieval_context=retrieval_context ) answer_relevancy_metric = AnswerRelevancyMetric(threshold=0.5) assert_test(test_case, [answer_relevancy_metric]) ``` Here, `rag_application` is simply the query engine from Llamaindex, which you'll have to import from the appropriate module. :::note In this example, we initialized an `EvaluationDataset` with a `Golden` instead of an `LLMTestCase`. This is because we're generating `actual_output`s and `retrieval_context`s at evaluation time, meaning we cannot initialize with test cases since an `LLMTestCase` requires an `actual_output` to create. Remember, a `Golden` do not require an `actual_output`, so whilst test cases are always ready for evaluation, a golden isn't. ::: ## Using DeepEval for LlamaIndex In LlamaIndex, there are entities known as evaluators that evaluates the responses of LlamaIndex applications. Continuing from the previous example, here's an alternative way to make use of the `AnswerRelevancyMetric` through `deepeval`'s LlamaIndex evaluators: ```python from deepeval.integrations.llama_index import DeepEvalAnswerRelevancyEvaluator ... # An example input to your RAG application user_input = "What is LlamaIndex?" # LlamaIndex returns a response object that contains # both the output string and retrieved nodes response_object = rag_application.query(user_input) evaluator = DeepEvalAnswerRelevancyEvaluator() evaluation_result = evaluator.evaluate_response( query=user_input, response=response_object ) print(evaluation_result) ``` :::info In LlamaIndex's documentation, you might see examples where the `evaluate()` method is called on an evaluator instead of the `evaluate_response()` method. While both is correct, you should **ALWAYS** use the `evaluate_response()` methods when using `deepeval`'s LlamaIndex evaluators. ::: ### Answer Relevancy The `DeepEvalAnswerRelevancyEvaluator` uses `deepeval`'s `AnswerRelevancyMetric` for evaluation. ```python from deepeval.integrations.llama_index import DeepEvalAnswerRelevancyEvaluator evaluator = DeepEvalAnswerRelevancyEvaluator( # Optional. A float representing the minimum passing threshold, defaulted to 0.5. threshold=0.5, # Optional. A string specifying which of OpenAI's GPT models to use, defaulted to 'gpt-4-0125-preview'. model="gpt-4-0125-preview", # Optional. A boolean which when set to `True`, will include a reason for its evaluation score, defaulted to `True`. include_reason=True ) ``` ### Faithfulness The `DeepEvalFaithfulnessEvaluator` uses `deepeval`'s `FaithfulnessMetric` for evaluation. ```python from deepeval.integrations.llama_index import DeepEvalFaithfulnessEvaluator evaluator = DeepEvalFaithfulnessEvaluator( # Optional. A float representing the minimum passing threshold, defaulted to 0.5. threshold=0.5, # Optional. A string specifying which of OpenAI's GPT models to use, defaulted to 'gpt-4-0125-preview'. model="gpt-4-0125-preview", # Optional. A boolean which when set to `True`, will include a reason for its evaluation score, defaulted to `True`. include_reason=True ) ``` ### Contextual Relevancy The `DeepEvalContextualRelevancyEvaluator` uses `deepeval`'s `ContextualRelevancyMetric` for evaluation. ```python from deepeval.integrations.llama_index import DeepEvalContextualRelevancyEvaluator evaluator = DeepEvalContextualRelevancyEvaluator( # Optional. A float representing the minimum passing threshold, defaulted to 0.5. threshold=0.5, # Optional. A string specifying which of OpenAI's GPT models to use, defaulted to 'gpt-4-0125-preview'. model="gpt-4-0125-preview", # Optional. A boolean which when set to `True`, will include a reason for its evaluation score, defaulted to `True`. include_reason=True ) ``` ### Summarization The `DeepEvalSummarizationEvaluator` uses `deepeval`'s `SummarizationMetric` for evaluation. ```python from deepeval.integrations.llama_index import DeepEvalSummarizationEvaluator evaluator = DeepEvalSummarizationEvaluator( # Optional. A float representing the minimum passing threshold, defaulted to 0.5. threshold=0.5, # Optional. A string specifying which of OpenAI's GPT models to use, defaulted to 'gpt-4-0125-preview'. model="gpt-4-0125-preview", # Optional. A boolean which when set to `True`, will include a reason for its evaluation score, defaulted to `True`. include_reason=True ) ``` ### Bias The `DeepEvalBiasEvaluator` uses `deepeval`'s `BiasMetric` for evaluation. ```python from deepeval.integrations.llama_index import DeepEvalBiasEvaluator evaluator = DeepEvalBiasEvaluator( # Optional. A float representing the maximum passing threshold, defaulted to 0.5. threshold=0.5, # Optional. A string specifying which of OpenAI's GPT models to use, defaulted to 'gpt-4-0125-preview'. model="gpt-4-0125-preview", # Optional. A boolean which when set to `True`, will include a reason for its evaluation score, defaulted to `True`. include_reason=True ) ``` ### Toxicity The `DeepEvalToxicityEvaluator` uses `deepeval`'s `ToxicityMetric` for evaluation. ```python from deepeval.integrations.llama_index import DeepEvalToxicityEvaluator evaluator = DeepEvalToxicityEvaluator( # Optional. A float representing the maximum passing threshold, defaulted to 0.5. threshold=0.5, # Optional. A string specifying which of OpenAI's GPT models to use, defaulted to 'gpt-4-0125-preview'. model="gpt-4-0125-preview", # Optional. A boolean which when set to `True`, will include a reason for its evaluation score, defaulted to `True`. include_reason=True ) ``` ## Metrics vs Evaluators While both `deepeval`'s metrics and evaluators yield the same result, `deepeval` is a full evaluation suite built specifically for LLM evaluation. Naturally, `deepeval` forces you to follow evaluation best practices, something not accomplishable through the use of the evaluators abstraction. So while both metrics and evaluators can be used for a one-off, standalone evaluation, metrics: - can be combined to evaluate multiple criteria asynchronously - can be used to evaluate entire `EvaluationDataset`s - can leverage `deepeval`'s native Pytest integration to unit test LlamaIndex applications in CI/CD pipelines - can be used with any framework, meaning you are not vendor locked-in into LlamaIndex - covers a wider range of evaluation criteria/use cases - automatically integrates with [Confident AI](confident-ai-introduction), which offers evaluation analysis, evaluation debugging, dataset management, and real-time evaluations in production :::note The only upside of using `deepeval`'s LlamaIndex evaluators instead of metrics, is an evaluator automatically extracts the `retrieval_context` from a LlamaIndex response. However, as shown in previous examples, manually extracting the `retrieval_context` from a LlamaIndex response is extremely straightforward: ```python ... # LlamaIndex returns a response object that contains # both the output string and retrieved nodes response_object = rag_application.query(user_input) # Process the response object to get the output string # and retrieved nodes if response_object is not None: actual_output = response_object.response retrieval_context = [node.get_content() for node in response_object.source_nodes] ``` :::
{% import 'utils/macros.html.twig' as macros %} {% for project in projects %} <article class="uk-comment"> {{ macros.statusColor(readerList, project.itemId) }} <header class="uk-comment-header uk-margin-remove uk-flex"> <div class="items-checkbox uk-margin-right uk-margin-top uk-hidden"> <form class="uk-form"> <input type="checkbox" value="{{ project.itemId }}"> </form> </div> <div class="uk-margin-right uk-flex-item-none"> {% if not project.modificatorItem.isDeleted and project.modificatorItem.isUser %} {{ macros.userIconLink(project.modificatorItem) }} {% else %} {{ macros.userIcon(project.modificatorItem) }} {% endif %} <div class="uk-comment-meta"> <span class="uk-text-nowrap"> {% if project.modificationDate|date("d.m.Y") == "now"|date("d.m.Y") %} {{ 'today'|trans({})|capitalize }}, {{ project.modificationDate|date("H:i") }} {% else %} {% if '9999-00-00' not in project.modificationDate %} {{ project.modificationDate|craue_date }} {% else %} {{ project.creationDate|craue_date }} {% endif %} {% endif %} </span> </div> </div> <div> <h4 class="uk-comment-title"> <a href="{{ path('app_project_detail', {'roomId': roomId, 'itemId': project.itemId}) }}">{{ project.title|decodeHtmlEntity }}</a> </h4> <div class="uk-comment-meta"> {% if project.contactPersonString is not empty %} <a href="{{ path('app_user_sendmailviacontactform', {'roomId': roomId, 'itemId': project.creatorId, 'originPath': 'app_project_list'}) }}">{{ project.contactPersonString }}</a> {% else %} <a href="{{ path('app_user_sendmailviacontactform', {'roomId': roomId, 'itemId': project.creatorId, 'originPath': 'app_project_list'}) }}">{{ project.getContactModeratorListString }}</a> {% endif %} </div> <div class="uk-comment-meta"> {{ macros.contextLink(roomId, project, projectsMemberStatus[project.itemId]) }} </div> </div> </header> </article> {% else %} {{ 'No more results found'|trans}} {% endfor %}
<template> <section class="md:min-w-[750px] md:max-w-[820px] w-[90vw] min-h-[80vh] bg-[#222222] mx-auto mt-10 rounded-lg"> <div v-if="loggingOut" class="w-[300px] mx-auto"> <div class="absolute w-[300px] h-[30px] rounded-md bg-green-500 -mt-[20px]"> <p class="text-center text-[16px] font-bold my-0 mt-[3px]">Logging Out...</p> </div> </div> <div class="max-w-[500px] mx-auto pt-10"> <div class="w-[100px] mx-auto"> <img :src="profileStore.user.avatarUrl" alt="" class="w-[100px] h-[100px] bg-gray-300 rounded-full"> </div> <p class="text-gray-400 font-semibold mt-5 text-center">Account created: <span class="font-bold text-gray-300"> {{profileStore.user.createdAt}} </span></p> <div class="mt-10 rounded-md md:pl-5 md:text-[20px]"> <p class=" font-semibold text-gray-100 bg-[#333333] py-[10px] px-[10px] rounded-md w-[150px]">Your details:</p> <div> <div class="text-gray-500 font-semibold w-[100%] md:max-w-[auto]"> <p class="bg-[#333333] py-[10px] px-[10px] rounded-md">ID: <span class="font-bold text-gray-200 ml-[10px] text-[13px] md:text-[20px]">{{profileStore.user.id}}</span></p> <p class="bg-[#333333] py-[10px] px-[10px] rounded-md">Name: <span class="font-bold text-gray-200 ml-[10px]">{{profileStore.user.name}}</span></p> <p class="bg-[#333333] py-[10px] px-[10px] rounded-md">Email: <span class="font-bold text-gray-200 ml-[10px]">{{profileStore.user.email}}</span></p> </div> <div class="w-[170px] md:w-[auto] mx-auto md:mx-0"> <button class="mt-5 w-[170px] bg-purple-500 rounded-md text-[#111111]" @click.prevent="logOut">Log out</button> </div> </div> </div> </div> </section> </template> <script> import {useProfileStore} from '../stores/profile'; import {supabase} from '../includes/supabase'; import { ref } from 'vue'; export default{ setup(){ const profileStore = useProfileStore(); let loggingOut = ref(false); async function logOut(){ try{ loggingOut.value = true; const { error } = await supabase.auth.signOut(); if(error) throw error; else{ setTimeout(function(){window.location.href = '/';},1000) } }catch{ alert(error); } }; return{ profileStore, logOut, loggingOut, } } } </script>
<script setup lang="ts"> import {hideOnClickMenu} from "~/composables/shared/HideOnClickMenu"; import {useRouter} from "nuxt/app"; import {useAuthStore} from "~/store/auth/auth"; import {useAuth} from "~/composables/auth/useAuth"; const {logout} = useAuth(); const router = useRouter(); const user = computed(() => useAuthStore().getUser); const isAuth = computed(() => useAuthStore().isAuth); const data = reactive({ isShow: false, }); const showMenu = () => { data.isShow = !data.isShow; }; const goTo = (routName: string) => { showMenu(); router.push({ name: 'profile'}); }; const logOut = () => { logout(); return router.push('/'); } onMounted(() => { hideOnClickMenu().hideUserMenu('user', 'user-container', 'show-menu', showMenu); }); </script> <template> <div class="auth"> <client-only> <div class="guest-group d-flex-md align-items-center" v-if="!isAuth"> <div class="sign-in hover" @click="router.push('/auth/sign-in')">SIGN IN</div> <div class="sign-up hover" @click="router.push('/auth/sign-up')">SIGN UP</div> </div> </client-only> <div class="user-group d-flex align-items-center" v-if="isAuth"> <div class="notify d-flex align-items-center"> <div class="hover d-flex align-items-center justify-content-center"> <svg-template class="cursor" name="notification"/> </div> <div class="hover d-flex align-items-center justify-content-center"> <svg-template class="cursor" name="message"/> </div> </div> <client-only> <div :class="{ 'rotate-vector': data.isShow }" class="user d-flex-md align-items-center hover" @click="showMenu()" > <div class="name">{{ user.firstname + (user.lastname ? '. ' + user.lastname[0] : '') }}</div> <div class="avatar"> <img class="img-avatar" src="/img/ava.jpeg" alt="Avatar"> </div> </div> </client-only> <div :class="{ 'show-menu': data.isShow }" class="user-container"> <div class="user-menu"> <div class="item d-flex align-items-center hover" @click="goTo('profile')"> <svg-template name="home"/> <div>Home</div> </div> <hr> <div class="item d-flex align-items-center hover"> <svg-template name="settings"/> <div>Settings</div> </div> <hr> <div class="item d-flex align-items-center hover"> <svg-template name="sign-out"/> <div @click="logOut">Sign out</div> </div> </div> </div> </div> </div> </template>
use derive_builder::Builder; use gitlab::api::Endpoint; use reqwest::Method; use std::borrow::Cow; #[derive(Debug, Builder)] pub struct DeleteKey { pub key_id: u64, } impl DeleteKey { /// Create a builder for the endpoint. pub fn builder() -> DeleteKeyBuilder { DeleteKeyBuilder::default() } } impl Endpoint for DeleteKey { fn method(&self) -> Method { Method::DELETE } fn endpoint(&self) -> Cow<'static, str> { format!("user/keys/{}", self.key_id).into() } }
using FluentAssertions; using NUnit.Framework; namespace DataStructures.Tree.BinarySearchTree { [TestFixture] public class CustomBinarySearchTreeTests { [Test] public void BinarySearchTree_InsertNodes_RootAndChildrenCorrect() { // arrange var bst = new CustomBinarySearchTree<int>(); // act // 2 // / \ // 1 4 // / / \ // 0 3 6 // / // 5 bst.Insert(2); bst.Insert(4); bst.Insert(6); bst.Insert(1); bst.Insert(3); bst.Insert(5); bst.Insert(0); var root = bst.GetRoot(); // assert // root root!.Value.Should().Be(2); // depth 1 var nodeOne = root.Left!; var nodeFour = root.Right!; nodeOne.Value.Should().Be(1); nodeFour.Value.Should().Be(4); // depth 2 var nodeZero = nodeOne.Left!; nodeZero.Value.Should().Be(0); nodeOne.Right.Should().BeNull(); var nodeThree = nodeFour.Left!; var nodeSix = nodeFour.Right!; nodeThree.Value.Should().Be(3); nodeSix.Value.Should().Be(6); // depth 3 nodeZero.Left.Should().BeNull(); nodeZero.Right.Should().BeNull(); nodeThree.Left.Should().BeNull(); nodeThree.Right.Should().BeNull(); var nodeFive = nodeSix.Left!; nodeFive.Value.Should().Be(5); nodeSix.Right.Should().BeNull(); } [Test] public void BinarySearchTree_InsertNodes_InOrderEnumeration() { // arrange // 2 // / \ // 1 4 // / / \ // 0 3 6 // / // 5 var bst = new CustomBinarySearchTree<int>(); bst.Insert(2); bst.Insert(4); bst.Insert(6); bst.Insert(1); bst.Insert(3); bst.Insert(5); bst.Insert(0); // act var enumerator = bst.GetEnumerator(); // assert in-order 0,1,2,3,4,5,6 enumerator.MoveNext(); enumerator.Current.Should().Be(0); enumerator.MoveNext(); enumerator.Current.Should().Be(1); enumerator.MoveNext(); enumerator.Current.Should().Be(2); enumerator.MoveNext(); enumerator.Current.Should().Be(3); enumerator.MoveNext(); enumerator.Current.Should().Be(4); enumerator.MoveNext(); enumerator.Current.Should().Be(5); enumerator.MoveNext(); enumerator.Current.Should().Be(6); var moveBehindLast = enumerator.MoveNext(); moveBehindLast.Should().BeFalse(); enumerator.Dispose(); } [Test] public void BinarySearchTree_InsertNodes_PreOrderEnumeration() { // arrange // 2 // / \ // 1 4 // / / \ // 0 3 6 // / // 5 var bst = new CustomBinarySearchTree<int>(); bst.Insert(2); bst.Insert(4); bst.Insert(6); bst.Insert(1); bst.Insert(3); bst.Insert(5); bst.Insert(0); // act var enumerator = bst.GetPreOrderEnumerator(); // assert pre-order 2,1,0,4,3,6,5 enumerator.MoveNext(); enumerator.Current.Should().Be(2); enumerator.MoveNext(); enumerator.Current.Should().Be(1); enumerator.MoveNext(); enumerator.Current.Should().Be(0); enumerator.MoveNext(); enumerator.Current.Should().Be(4); enumerator.MoveNext(); enumerator.Current.Should().Be(3); enumerator.MoveNext(); enumerator.Current.Should().Be(6); enumerator.MoveNext(); enumerator.Current.Should().Be(5); var moveBehindLast = enumerator.MoveNext(); moveBehindLast.Should().BeFalse(); enumerator.Dispose(); } [Test] public void BinarySearchTree_InsertNodes_PostOrderEnumeration() { // arrange // 2 // / \ // 1 4 // / / \ // 0 3 6 // / // 5 var bst = new CustomBinarySearchTree<int>(); bst.Insert(2); bst.Insert(4); bst.Insert(6); bst.Insert(1); bst.Insert(3); bst.Insert(5); bst.Insert(0); // act var enumerator = bst.GetPostOrderEnumerator(); // assert post-order 0,1,3,5,6,4,2 enumerator.MoveNext(); enumerator.Current.Should().Be(0); enumerator.MoveNext(); enumerator.Current.Should().Be(1); enumerator.MoveNext(); enumerator.Current.Should().Be(3); enumerator.MoveNext(); enumerator.Current.Should().Be(5); enumerator.MoveNext(); enumerator.Current.Should().Be(6); enumerator.MoveNext(); enumerator.Current.Should().Be(4); enumerator.MoveNext(); enumerator.Current.Should().Be(2); var moveBehindLast = enumerator.MoveNext(); moveBehindLast.Should().BeFalse(); enumerator.Dispose(); } [Test] public void BinarySearchTree_InsertNodes_LevelOrderEnumeration() { // arrange // 2 // / \ // 1 4 // / / \ // 0 3 6 // / // 5 var bst = new CustomBinarySearchTree<int>(); bst.Insert(2); bst.Insert(4); bst.Insert(6); bst.Insert(1); bst.Insert(3); bst.Insert(5); bst.Insert(0); // act var enumerator = bst.GetLevelOrderEnumerator(); // assert post-order 2,1,4,0,3,6,5 enumerator.MoveNext(); enumerator.Current.Should().Be(2); enumerator.MoveNext(); enumerator.Current.Should().Be(1); enumerator.MoveNext(); enumerator.Current.Should().Be(4); enumerator.MoveNext(); enumerator.Current.Should().Be(0); enumerator.MoveNext(); enumerator.Current.Should().Be(3); enumerator.MoveNext(); enumerator.Current.Should().Be(6); enumerator.MoveNext(); enumerator.Current.Should().Be(5); var moveBehindLast = enumerator.MoveNext(); moveBehindLast.Should().BeFalse(); enumerator.Dispose(); } [Test] public void BinarySearchTree_InsertNodes_Search() { // arrange // 2 // / \ // 1 4 // / / \ // 0 3 6 // / // 5 var bst = new CustomBinarySearchTree<int>(); bst.Insert(2); bst.Insert(4); bst.Insert(6); bst.Insert(1); bst.Insert(3); bst.Insert(5); bst.Insert(0); // act var twoNode = bst.Search(2); var fourNode = bst.Search(4); var sixNode = bst.Search(6); var oneNode = bst.Search(1); var threeNode = bst.Search(3); var fiveNode = bst.Search(5); var zeroNode = bst.Search(0); var nonExistentNode = bst.Search(99); // assert twoNode.Result!.Value.Should().Be(2); fourNode.Result!.Value.Should().Be(4); sixNode.Result!.Value.Should().Be(6); oneNode.Result!.Value.Should().Be(1); threeNode.Result!.Value.Should().Be(3); fiveNode.Result!.Value.Should().Be(5); zeroNode.Result!.Value.Should().Be(0); nonExistentNode.Result.Should().BeNull(); } [Test] public void BinarySearchTree_InsertNodes_RemoveLeafNodesUpToRoot() { // arrange // 2 // / \ // 1 4 // / / \ // 0 3 6 // / // 5 var bst = new CustomBinarySearchTree<int>(); bst.Insert(2); bst.Insert(4); bst.Insert(6); bst.Insert(1); bst.Insert(3); bst.Insert(5); bst.Insert(0); // act // 1 // / // 0 bst.Remove(5); bst.Remove(3); bst.Remove(6); bst.Remove(4); bst.Remove(2); var root = bst.GetRoot()!; // assert root.Value.Should().Be(1); root.Left!.Value.Should().Be(0); } [Test] public void BinarySearchTree_InsertNodes_RemoveNodesWithOneSubtree() { // arrange // 2 // / \ // 1 3 // / \ // 0 4 var bst = new CustomBinarySearchTree<int>(); bst.Insert(2); bst.Insert(3); bst.Insert(4); bst.Insert(1); bst.Insert(0); // act // 2 // / \ // 0 4 bst.Remove(3); bst.Remove(1); var root = bst.GetRoot()!; // assert root.Value.Should().Be(2); root.Left!.Value.Should().Be(0); root.Left!.Left.Should().BeNull(); root.Left!.Right.Should().BeNull(); root.Right!.Value.Should().Be(4); root.Right!.Left.Should().BeNull(); root.Right!.Right.Should().BeNull(); } [Test] public void BinarySearchTree_InsertNodes_RemoveNonExistentNode() { // arrange // 2 // / \ // 1 3 var bst = new CustomBinarySearchTree<int>(); bst.Insert(2); bst.Insert(3); bst.Insert(1); // act var removeResult = bst.Remove(0); var root = bst.GetRoot()!; // assert removeResult.Should().BeFalse(); root.Value.Should().Be(2); root.Left!.Value.Should().Be(1); root.Left!.Left.Should().BeNull(); root.Left!.Right.Should().BeNull(); root.Right!.Value.Should().Be(3); root.Right!.Left.Should().BeNull(); root.Right!.Right.Should().BeNull(); } [Test] public void BinarySearchTree_InsertNodes_RemoveRootWithTwoSubtrees() { // arrange // 4 // / \ // 1 5 // / \ \ // 0 3 6 // / // 2 var bst = new CustomBinarySearchTree<int>(); bst.Insert(4); bst.Insert(5); bst.Insert(6); bst.Insert(1); bst.Insert(3); bst.Insert(2); bst.Insert(0); // act // 3 // / \ // 1 5 // / \ \ // 0 2 6 bst.Remove(4); var root = bst.GetRoot()!; // assert // root root.Value.Should().Be(3); // depth 1 var nodeOne = root.Left!; var nodeFive = root.Right!; nodeOne.Value.Should().Be(1); nodeFive.Value.Should().Be(5); // depth 2 var nodeZero = nodeOne.Left!; var nodeTwo = nodeOne.Right!; nodeZero.Value.Should().Be(0); nodeTwo.Value.Should().Be(2); var nodeSix = nodeFive.Right!; nodeSix.Value.Should().Be(6); // depth 3 nodeZero.Left.Should().BeNull(); nodeZero.Right.Should().BeNull(); nodeTwo.Left.Should().BeNull(); nodeTwo.Right.Should().BeNull(); nodeSix.Left.Should().BeNull(); nodeSix.Right.Should().BeNull(); } } }
[CmdletBinding(DefaultParameterSetName = 'Value')] Param( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [object]$VM, [Parameter()] [string]$ComputerName, [Parameter(Mandatory = $true, ParameterSetName = 'Value')] [string]$Name, [Parameter(Mandatory = $true, ParameterSetName = 'Value')] [string]$Value, [Parameter(Mandatory = $true, ParameterSetName = 'Hashtable')] [hashtable]$SystemSettings, [Parameter(DontShow)] [string]$Hostname = [System.Environment]::MachineName.ToLowerInvariant() ) Begin { Function Get-VMFromParameters { [CmdletBinding()] Param( [Parameter(Mandatory = $true)][ValidateScript({ $_ -is [Microsoft.HyperV.PowerShell.VirtualMachine] -or $_ -is [guid] -or $_ -is [string] })] [object]$VM, [string]$ComputerName, [switch]$Force ) # if VM is a virtual machine object and Force not set... If ($VM -is [Microsoft.HyperV.PowerShell.VirtualMachine] -and -not $Force) { # ...return VM as-is Return $VM } # if computername not provided... If ([string]::IsNullOrEmpty($ComputerName)) { # ...and VM is a virtual machine... If ($VM -is [Microsoft.HyperV.PowerShell.VirtualMachine]) { # get computer name from VM $ComputerName = $VM.ComputerName } Else { # get computer name from hostname $ComputerName = $Hostname } } # define required parameters for Get-VM $GetVM = @{ ComputerName = $ComputerName ErrorAction = [System.Management.Automation.ActionPreference]::Stop } # if VM is a virtual machine object... If ($VM -is [Microsoft.HyperV.PowerShell.VirtualMachine]) { # ...set ID from Id property on VM object $GetVM['Id'] = $VM.Id } # if VM is a GUID... ElseIf ($VM -is [guid] -or [guid]::TryParse($VM, [ref][guid]::Empty)) { # ...set ID from value of VM cast as a GUID $GetVM['Id'] = [guid]$VM } # if VM is a string... Else { # ...set Name from value of VM $GetVM['Name'] = $VM } # get VM with arguments Try { $VM = Get-VM @GetVM } Catch { Throw $_ } # return objects If ($VM -is [Microsoft.HyperV.PowerShell.VirtualMachine]) { Return $VM } ElseIf ($VM -is [array]) { Write-Host ("$Hostname,$ComputerName,$Name - ERROR: retrieved multiple VM objects with provided parameters") Throw $_ } Else { Write-Host ("$Hostname,$ComputerName,$Name - ERROR: retrieved unexpected object type with provided parameters") Throw $_ } } Function Get-CimInstanceForVM { [CmdletBinding()] Param( # define VM parameters [Parameter(Mandatory = $true)] [object]$VM, [string]$ComputerName = $VM.ComputerName.ToLower() ) # get VM from parameters Try { $VM = Get-VMFromParameters -ComputerName $ComputerName -VM $VM } Catch { Write-Host ("$Hostname,$ComputerName,$Name - ERROR: could not retrieve VM") Throw $_ } # define CIM instance for VM system settings $GetCimInstance = @{ ComputerName = $ComputerName Namespace = 'Root\Virtualization\V2' ClassName = 'Msvm_VirtualSystemSettingData' Filter = "ConfigurationId = '$($VM.Id)'" ErrorAction = [System.Management.Automation.ActionPreference]::Stop } # retrieve original VM system settings and host management service via CIM Try { Get-CimInstance @GetCimInstance } Catch { Throw $_ } } Function Get-CimInstanceForVMMS { [CmdletBinding()] Param( [Parameter(Mandatory = $true)] [string]$ComputerName ) # define CIM instance for host management service $GetCimInstance = @{ ComputerName = $ComputerName Namespace = 'Root\Virtualization\V2' ClassName = 'Msvm_VirtualSystemManagementService' ErrorAction = [System.Management.Automation.ActionPreference]::Stop } # retrieve CIM instance for host management service Try { Get-CimInstance @GetCimInstance } Catch { Throw $_ } } Function Set-VMSystemSettings { [CmdletBinding()] Param( # define VM parameters [Parameter(Mandatory = $true)] [object]$VM, [string]$ComputerName = $VM.ComputerName.ToLower(), # define system settings parameters [hashtable]$SystemSettings ) # get VM from parameters Try { # cast return as type to force terminating error $VM = Get-VMFromParameters -ComputerName $ComputerName -VM $VM } Catch { Write-Host ("$Hostname,$ComputerName,$Name - ERROR: could not retrieve VM") Throw $_ } # define CIM instance for VM system settings $GetCimInstanceForVM = @{ VM = $VM ErrorAction = [System.Management.Automation.ActionPreference]::Stop } # retrieve original VM system settings and host management service via CIM Try { Write-Host ("$Hostname,$ComputerName,$Name - ...retrieving CIM instance for VM...") $CimInstanceForVM = Get-CimInstanceForVM @GetCimInstanceForVM } Catch { Write-Host ("$Hostname,$ComputerName,$Name - ERROR: could not retrieve CIM instance for VM") Throw $_ } # define counter for changes $SystemSettingsCounter = [int32]0 # modify VM system settings ForEach ($SystemSetting in $SystemSettings.Keys) { If ($CimInstanceForVM.$SystemSetting -eq $SystemSettings[$SystemSetting]) { Write-Host ("$Hostname,$ComputerName,$Name - ...found '$SystemSetting' set to '$($SystemSettings[$SystemSetting])'") } Else { Write-Host ("$Hostname,$ComputerName,$Name - ...updating '$SystemSetting' from '$($CimInstanceForVM.$SystemSetting)' to '$($SystemSettings[$SystemSetting])'") $CimInstanceForVM.$SystemSetting = $SystemSettings[$SystemSetting] $SystemSettingsCounter++ } } # check counter for changes If ($SystemSettingsCounter -eq 0) { Write-Host ("$Hostname,$ComputerName,$Name - ...existing firmware settings match requested settings") Return } # serialize and encode VM system settings Try { $CimSerializer = [Microsoft.Management.Infrastructure.Serialization.CimSerializer]::Create() $CimSerialized = $CimSerializer.Serialize($CimInstanceForVM, [Microsoft.Management.Infrastructure.Serialization.InstanceSerializationOptions]::None) $CimEncodedData = [System.Text.Encoding]::Unicode.GetString($CimSerialized) } Catch { Write-Host ("$Hostname,$ComputerName,$Name - ERROR: could not serialize the CIM objects for VM firmware") Throw $_ } # define CIM instance for VM management service $GetCimInstanceForVMMS = @{ ComputerName = $ComputerName ErrorAction = [System.Management.Automation.ActionPreference]::Stop } # retrieve CIM instance for host management service Write-Host ("$Hostname,$ComputerName,$Name - ...retrieving CIM instance for VM management service") Try { $CimInstanceForVMMS = Get-CimInstanceForVMMS @GetCimInstanceForVMMS } Catch { Write-Host ("$Hostname,$ComputerName,$Name - ERROR: could not retrieve CIM instance for VM management service") Throw $_ } # define CIM method for host management service $InvokeCimMethod = @{ CimInstance = $CimInstanceForVMMS MethodName = 'ModifySystemSettings' Arguments = @{ SystemSettings = $CimEncodedData } ErrorAction = [System.Management.Automation.ActionPreference]::Stop } # invoke CIM method on host management service to update VM system settings with modified values Write-Host ("$Hostname,$ComputerName,$Name - updating firmware settings via CIM...") Try { $CimMethod = Invoke-CimMethod @InvokeCimMethod } Catch { Write-Host ("$Hostname,$ComputerName,$Name - ERROR: could not call method to update firmware settings via CIM") Throw $_ } # check CIM return value If ($CimMethod.ReturnValue -eq 0) { Write-Host ("$Hostname,$ComputerName,$Name - ...firmware settings updated...") } Else { Write-Host ("$Hostname,$ComputerName,$Name - ERROR: firmware settings not updated, CIM returned: '$($CimMethod.ReturnValue)'") } } } Process { # create hashtable from parameters If ($PSCmdlet.ParameterSetName -eq 'Value') { $SystemSettings = @{ $Name = $Value } } # call primary function Try { Set-VMSystemSettings -VM $VM -SystemSettings $SystemSettings } Catch { Throw $_ } }
import PropTypes from 'prop-types'; import css from 'components/statistics/Statistics.module.css'; export const Statistics = ({ good, neutral, bad, total, positivePercentage, }) => { return ( <ul> <li> <p className={css.stat}>Good: {good}</p> </li> <li> <p className={css.stat}>Neutral: {neutral}</p> </li> <li> <p className={css.stat}>Bad: {bad}</p> </li> <li> <p className={css.stat}>Total: {total}</p> </li> <li> <p className={css.stat}>Positive feedback: {positivePercentage}%</p> </li> </ul> ); }; Statistics.propTypes = { good: PropTypes.number.isRequired, neutral: PropTypes.number.isRequired, bad: PropTypes.number.isRequired, total: PropTypes.number.isRequired, positivePercentage: PropTypes.number.isRequired, };
/* StarPU --- Runtime system for heterogeneous multicore architectures. * * Copyright (C) 2010-2012 Université de Bordeaux * * StarPU is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at * your option) any later version. * * StarPU 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 Lesser General Public License in COPYING.LGPL for more details. */ #ifndef __STARPU_TASK_LIST_H__ #define __STARPU_TASK_LIST_H__ #include <starpu_task.h> #include <starpu_util.h> #ifdef __cplusplus extern "C" { #endif struct starpu_task_list { struct starpu_task *head; struct starpu_task *tail; }; static STARPU_INLINE void starpu_task_list_init(struct starpu_task_list *list) { list->head = NULL; list->tail = NULL; } static STARPU_INLINE void starpu_task_list_push_front(struct starpu_task_list *list, struct starpu_task *task) { if (list->tail == NULL) { list->tail = task; } else { list->head->prev = task; } task->prev = NULL; task->next = list->head; list->head = task; } static STARPU_INLINE void starpu_task_list_push_back(struct starpu_task_list *list, struct starpu_task *task) { if (list->head == NULL) { list->head = task; } else { list->tail->next = task; } task->next = NULL; task->prev = list->tail; list->tail = task; } static STARPU_INLINE struct starpu_task *starpu_task_list_front(struct starpu_task_list *list) { return list->head; } static STARPU_INLINE struct starpu_task *starpu_task_list_back(struct starpu_task_list *list) { return list->tail; } static STARPU_INLINE int starpu_task_list_empty(struct starpu_task_list *list) { return (list->head == NULL); } static STARPU_INLINE void starpu_task_list_erase(struct starpu_task_list *list, struct starpu_task *task) { struct starpu_task *p = task->prev; if (p) { p->next = task->next; } else { list->head = task->next; } if (task->next) { task->next->prev = p; } else { list->tail = p; } task->prev = NULL; task->next = NULL; } static STARPU_INLINE struct starpu_task *starpu_task_list_pop_front(struct starpu_task_list *list) { struct starpu_task *task = list->head; if (task) starpu_task_list_erase(list, task); return task; } static STARPU_INLINE struct starpu_task *starpu_task_list_pop_back(struct starpu_task_list *list) { struct starpu_task *task = list->tail; if (task) starpu_task_list_erase(list, task); return task; } static STARPU_INLINE struct starpu_task *starpu_task_list_begin(struct starpu_task_list *list) { return list->head; } static STARPU_INLINE struct starpu_task *starpu_task_list_end(struct starpu_task_list *list STARPU_ATTRIBUTE_UNUSED) { return NULL; } static STARPU_INLINE struct starpu_task *starpu_task_list_next(struct starpu_task *task) { return task->next; } #ifdef __cplusplus } #endif #endif /* __STARPU_TASK_LIST_H__ */
// Tests that replaying the oplog entries during the startup recovery also writes to the change // collection. // @tags: [ // requires_fcv_62, // ] import {configureFailPoint} from "jstests/libs/fail_point_util.js"; import {verifyChangeCollectionEntries} from "jstests/serverless/libs/change_collection_util.js"; const replSetTest = new ReplSetTest({nodes: 1, name: "ChangeStreamMultitenantReplicaSetTest", serverless: true}); replSetTest.startSet({ setParameter: { featureFlagServerlessChangeStreams: true, multitenancySupport: true, featureFlagRequireTenantID: true, featureFlagSecurityToken: true } }); replSetTest.initiate(); let primary = replSetTest.getPrimary(); const tenantId = ObjectId(); const token = _createTenantToken({tenant: tenantId}); primary._setSecurityToken(token); // Enable the change stream to create the change collection. assert.commandWorked(primary.getDB("admin").runCommand({setChangeStreamState: 1, enabled: true})); // Insert a document to the collection and then capture the corresponding oplog timestamp. This // timestamp will be the start timestamp beyond (inclusive) which we will validate the oplog and the // change collection entries. const startTimestamp = assert .commandWorked(primary.getDB("test").runCommand( {insert: "seedCollection", documents: [{_id: "beginTs"}]})) .operationTime; // Pause the checkpointing, as such non-journaled collection including the change collection will // not be persisted. const pauseCheckpointThreadFailPoint = configureFailPoint(primary, "pauseCheckpointThread"); pauseCheckpointThreadFailPoint.wait(); // Insert a document to the collection. assert.commandWorked(primary.getDB("test").runCommand( {insert: "stockPrice", documents: [{_id: "mdb", price: 250}]})); // Verify that the inserted document can be queried from the 'stockPrice', the 'oplog.rs', and // the 'system.change_collection'. assert.eq(assert .commandWorked(primary.getDB("test").runCommand( {find: "stockPrice", filter: {_id: "mdb", price: 250}})) .cursor.firstBatch.length, 1); // Clear the token before accessing the local database primary._setSecurityToken(undefined); assert.eq(assert .commandWorked(primary.getDB("local").runCommand( {find: "oplog.rs", filter: {ns: "test.stockPrice", o: {_id: "mdb", price: 250}}})) .cursor.firstBatch.length, 1); primary._setSecurityToken(token); assert.eq(assert .commandWorked(primary.getDB("config").runCommand({ find: "system.change_collection", filter: {ns: "test.stockPrice", o: {_id: "mdb", price: 250}} })) .cursor.firstBatch.length, 1); // Perform ungraceful shutdown of the primary node and do not clean the db path directory. replSetTest.stop(0, 9, {allowedExitCode: MongoRunner.EXIT_SIGKILL}, {forRestart: true}); // Run a new mongoD instance with db path pointing to the replica set primary db directory. const standalone = MongoRunner.runMongod({ setParameter: { featureFlagServerlessChangeStreams: true, multitenancySupport: true, featureFlagRequireTenantID: true }, dbpath: primary.dbpath, noReplSet: true, noCleanData: true }); assert.neq(null, standalone, "Fail to restart the node as standalone"); // Set the token on the new connection standalone._setSecurityToken(token); // Verify that the inserted document does not exist both in the 'stockPrice' and // the 'system.change_collection' but exists in the 'oplog.rs'. assert.eq(assert .commandWorked(standalone.getDB("test").runCommand( {find: "stockPrice", filter: {_id: "mdb", price: 250}})) .cursor.firstBatch.length, 0); // Clear the token before accessing the local database standalone._setSecurityToken(undefined); assert.eq(assert .commandWorked(standalone.getDB("local").runCommand( {find: "oplog.rs", filter: {ns: "test.stockPrice", o: {_id: "mdb", price: 250}}})) .cursor.firstBatch.length, 1); standalone._setSecurityToken(token); assert.eq(assert .commandWorked(standalone.getDB("config").runCommand({ find: "system.change_collection", filter: {ns: "test.stockPrice", o: {_id: "mdb", price: 250}} })) .cursor.firstBatch.length, 0); // Stop the mongoD instance and do not clean the db directory. MongoRunner.stopMongod(standalone, null, {noCleanData: true, skipValidation: true, wait: true}); // Start the replica set primary with the same db path. replSetTest.start(primary, { noCleanData: true, serverless: true, setParameter: { featureFlagServerlessChangeStreams: true, multitenancySupport: true, featureFlagRequireTenantID: true } }); primary = replSetTest.getPrimary(); primary._setSecurityToken(token); // Verify that the 'stockPrice' and the 'system.change_collection' now have the inserted // document. This document was inserted by applying oplog entries during the startup recovery. assert.eq(assert .commandWorked(primary.getDB("test").runCommand( {find: "stockPrice", filter: {_id: "mdb", price: 250}})) .cursor.firstBatch.length, 1); assert.eq(assert .commandWorked(primary.getDB("config").runCommand({ find: "system.change_collection", filter: {ns: "test.stockPrice", o: {_id: "mdb", price: 250}} })) .cursor.firstBatch.length, 1); // Get the oplog timestamp up to this point. All oplog entries upto this timestamp must exist in the // change collection. primary._setSecurityToken(undefined); const endTimestamp = primary.getDB("local").oplog.rs.find().toArray().at(-1).ts; assert(endTimestamp !== undefined); // Verify that the oplog and the change collection entries between the ('startTimestamp', // 'endTimestamp'] window are exactly same and in the same order. verifyChangeCollectionEntries(primary, startTimestamp, endTimestamp, tenantId, token); replSetTest.stopSet();
/** \file MouseEvents.h */ #pragma once #include "Event.h" namespace Engine { /** \class MouseButtonEvent mouse events */ class MouseButtonEvent : public Event { protected: int m_Button; MouseButtonEvent(int button) : m_Button(button){} public: virtual int getCategoryFlags() const override { return EventCategoryMouse | EventCategoryMouseButton | EventCategoryInput; } inline int getMouseButton() { return m_Button; } }; /** \class MouseButtonPressedEvent mouse button press */ class MouseButtonPressedEvent : public MouseButtonEvent { public: MouseButtonPressedEvent(int button): MouseButtonEvent(button){} static EventType getStaticType() { return EventType::MouseButtonPressed; } virtual EventType getEventType() const override { return EventType::MouseButtonPressed; } }; /** \class MouseButtonReleasedEvent mouse button released */ class MouseButtonReleasedEvent : public MouseButtonEvent { public: MouseButtonReleasedEvent(int button) : MouseButtonEvent(button) {} static EventType getStaticType() { return EventType::MouseButtonReleased; } virtual EventType getEventType() const override { return EventType::MouseButtonReleased; } }; /** \class MouseMovedEvent mouse button moved */ class MouseMovedEvent : public Event { private: int m_xOffset; int m_yOffset; public: MouseMovedEvent(int xOffset, int yOffset) : m_xOffset(xOffset), m_yOffset(yOffset){} static EventType getStaticType() { return EventType::MouseMoved; } EventType getEventType() const override { return EventType::MouseMoved; } int getCategoryFlags() const override { return EventCategoryMouse; } inline int getXOffset() { return m_xOffset; } inline int getYOffset() { return m_yOffset; } }; /** \class MouseScrolledEvent mouse scrolled */ class MouseScrolledEvent : public Event { private: int m_xOffset; int m_yOffset; public: MouseScrolledEvent(int xOffset, int yOffset) : m_xOffset(xOffset), m_yOffset(yOffset) {} static EventType getStaticType() { return EventType::MouseScrolled; } EventType getEventType() const override { return EventType::MouseScrolled; } int getCategoryFlags() const override { return EventCategoryMouse | EventCategoryInput; } inline int getXOffset() { return m_xOffset; } inline int getYOffset() { return m_yOffset; } }; }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package vista.swing.vista; import controlador.datos.Facade; import hibernate.dto.Alojamiento; import hibernate.dto.VistaActividadesAlojamiento; import hibernate.dto.VistaActividadesAlojamientoId; import javax.swing.JOptionPane; import org.hibernate.Session; /** * Ventana para comprobar los datos del Alojamiento introducido y confirmar. * @author Mario Codes Sánchez * @since 21/02/2017 */ public class MostrarAlojamiento extends javax.swing.JFrame { private Alojamiento alojamiento; /** * Creates new form VentanaAltaAlojamiento * @param alojamiento Alojamiento del cual se obtienen los datos. */ public MostrarAlojamiento(Alojamiento alojamiento) { initComponents(); this.setResizable(false); this.setLocationRelativeTo(null); this.setVisible(true); this.alojamiento = alojamiento; setDatos(this.alojamiento); } private void setDatos(Alojamiento alojamiento) { String nombre = alojamiento.getNombre(); String telefono = alojamiento.getTelefonoContacto(); String dirSoc = alojamiento.getDireccionSocial(); String razSoc = alojamiento.getRazonSocial(); int valoracion = alojamiento.getValoracion(); String apertura = alojamiento.getFechaApertura(); int habitaciones = alojamiento.getNumHabitaciones(); String provincia = alojamiento.getProvincia(); String descripcion = alojamiento.getDescripcion(); if(nombre != null) this.jTextFieldInputNombreAloj.setText(nombre); if(telefono != null) this.jTextFieldInputTelefono.setText(telefono); if(dirSoc != null) this.jTextFieldInputDirSocial.setText(dirSoc); if(razSoc != null) this.jTextFieldInputRazonSocial.setText(razSoc); this.jSpinnerValoracion.setValue(valoracion); if(apertura != null) this.jTextFieldInputFechaApertura.setText(apertura); this.jSpinnerHabitaciones.setValue(habitaciones); if(provincia != null) this.jComboBoxProvincia.setSelectedItem(nombre); if(descripcion != null) this.jTextPaneInputDescripcionAloj.setText(descripcion); } private VistaActividadesAlojamientoId getDatos() { String nombre = this.jTextFieldInputNombreAloj.getText(); String telefono = this.jTextFieldInputTelefono.getText(); String dirSoc = this.jTextFieldInputDirSocial.getText(); String razSoc = this.jTextFieldInputRazonSocial.getText(); int valoracion = (int) this.jSpinnerValoracion.getValue(); String apertura = this.jTextFieldInputFechaApertura.getText(); int habitaciones = (int) this.jSpinnerHabitaciones.getValue(); String provincia = this.jComboBoxProvincia.getSelectedItem().toString(); String descripcion = this.jTextPaneInputDescripcionAloj.getText(); return new VistaActividadesAlojamientoId(0, 6, nombre, descripcion, dirSoc, razSoc, telefono, valoracion, apertura, habitaciones, provincia, "", "", "", "", "", "", "", 0, "", ""); } private boolean alta(VistaActividadesAlojamientoId id) { Session s = Facade.abrirSessionHibernate(); VistaActividadesAlojamiento vaa = new VistaActividadesAlojamiento(id); s.save(vaa); return Facade.cerrarSessionHibernate(s); } private boolean checkObligatorios() { return !(this.jTextFieldInputNombreAloj.getText().isEmpty() && this.jTextFieldInputDirSocial.getText().isEmpty()); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanelDatosAlojamiento = new javax.swing.JPanel(); jLabelTelefono = new javax.swing.JLabel(); jTextFieldInputTelefono = new javax.swing.JTextField(); jLabelNombre = new javax.swing.JLabel(); jTextFieldInputNombreAloj = new javax.swing.JTextField(); jTextFieldInputDirSocial = new javax.swing.JTextField(); jLabelDirSocial = new javax.swing.JLabel(); jTextFieldInputRazonSocial = new javax.swing.JTextField(); jLabelRazonSocial = new javax.swing.JLabel(); jSpinnerValoracion = new javax.swing.JSpinner(); jLabelValoracion = new javax.swing.JLabel(); jLabelFechaApertura = new javax.swing.JLabel(); jTextFieldInputFechaApertura = new javax.swing.JTextField(); jLabelHabitaciones = new javax.swing.JLabel(); jSpinnerHabitaciones = new javax.swing.JSpinner(); jLabelProvincia = new javax.swing.JLabel(); jComboBoxProvincia = new javax.swing.JComboBox(); jScrollPane2 = new javax.swing.JScrollPane(); jTextPaneInputDescripcionAloj = new javax.swing.JTextPane(); jLabelDescripcion = new javax.swing.JLabel(); jLabelMainTitulo = new javax.swing.JLabel(); jButtonAceptar = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanelDatosAlojamiento.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Datos Alojamiento", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("sansserif", 2, 12))); // NOI18N jLabelTelefono.setText("Telefono"); jTextFieldInputTelefono.setEnabled(false); jLabelNombre.setText("Nombre"); jTextFieldInputNombreAloj.setEnabled(false); jTextFieldInputDirSocial.setEnabled(false); jLabelDirSocial.setText("Dir. Social"); jTextFieldInputRazonSocial.setEnabled(false); jLabelRazonSocial.setText("Razon Social"); jSpinnerValoracion.setModel(new javax.swing.SpinnerNumberModel(1, 1, 5, 1)); jSpinnerValoracion.setEnabled(false); jLabelValoracion.setText("Valoracion"); jLabelFechaApertura.setText("Fecha Apertura"); jTextFieldInputFechaApertura.setEnabled(false); jLabelHabitaciones.setText("Habitaciones"); jSpinnerHabitaciones.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(1))); jSpinnerHabitaciones.setEnabled(false); jLabelProvincia.setText("Provincia"); jComboBoxProvincia.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Huesca", "Zaragoza", "Teruel" })); jComboBoxProvincia.setEnabled(false); jTextPaneInputDescripcionAloj.setEnabled(false); jScrollPane2.setViewportView(jTextPaneInputDescripcionAloj); jLabelDescripcion.setText("Descripcion"); javax.swing.GroupLayout jPanelDatosAlojamientoLayout = new javax.swing.GroupLayout(jPanelDatosAlojamiento); jPanelDatosAlojamiento.setLayout(jPanelDatosAlojamientoLayout); jPanelDatosAlojamientoLayout.setHorizontalGroup( jPanelDatosAlojamientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelDatosAlojamientoLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelDatosAlojamientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelDatosAlojamientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanelDatosAlojamientoLayout.createSequentialGroup() .addGroup(jPanelDatosAlojamientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelValoracion) .addComponent(jLabelHabitaciones)) .addGap(12, 12, 12) .addGroup(jPanelDatosAlojamientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelDatosAlojamientoLayout.createSequentialGroup() .addComponent(jSpinnerHabitaciones, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabelProvincia) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 57, Short.MAX_VALUE) .addComponent(jComboBoxProvincia, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanelDatosAlojamientoLayout.createSequentialGroup() .addComponent(jSpinnerValoracion, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabelFechaApertura)))) .addComponent(jLabelDescripcion) .addGroup(jPanelDatosAlojamientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextFieldInputFechaApertura, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanelDatosAlojamientoLayout.createSequentialGroup() .addGroup(jPanelDatosAlojamientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelRazonSocial) .addComponent(jLabelDirSocial) .addComponent(jLabelTelefono) .addComponent(jLabelNombre)) .addGap(12, 12, 12) .addGroup(jPanelDatosAlojamientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jTextFieldInputDirSocial, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE) .addComponent(jTextFieldInputTelefono, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextFieldInputNombreAloj, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextFieldInputRazonSocial))))) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 352, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanelDatosAlojamientoLayout.setVerticalGroup( jPanelDatosAlojamientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelDatosAlojamientoLayout.createSequentialGroup() .addGroup(jPanelDatosAlojamientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelNombre) .addComponent(jTextFieldInputNombreAloj, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelDatosAlojamientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldInputTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelTelefono)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelDatosAlojamientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldInputDirSocial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelDirSocial)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelDatosAlojamientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldInputRazonSocial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelRazonSocial)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelDatosAlojamientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jSpinnerValoracion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelValoracion) .addComponent(jLabelFechaApertura) .addComponent(jTextFieldInputFechaApertura, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanelDatosAlojamientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelHabitaciones) .addComponent(jSpinnerHabitaciones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelProvincia) .addComponent(jComboBoxProvincia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE) .addComponent(jLabelDescripcion) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jLabelMainTitulo.setFont(new java.awt.Font("sansserif", 1, 18)); // NOI18N jLabelMainTitulo.setText("Comprobacion de Datos"); jButtonAceptar.setText("Confirmar"); jButtonAceptar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAceptarActionPerformed(evt); } }); jButton2.setText("Cancelar"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanelDatosAlojamiento, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jButtonAceptar) .addGap(27, 27, 27) .addComponent(jButton2) .addGap(110, 110, 110)))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabelMainTitulo) .addGap(96, 96, 96)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabelMainTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanelDatosAlojamiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonAceptar) .addComponent(jButton2)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed this.dispose(); }//GEN-LAST:event_jButton2ActionPerformed private void jButtonAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAceptarActionPerformed AltaBajaVista.setAlojamiento(this.alojamiento); this.dispose(); }//GEN-LAST:event_jButtonAceptarActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton2; private javax.swing.JButton jButtonAceptar; private javax.swing.JComboBox jComboBoxProvincia; private javax.swing.JLabel jLabelDescripcion; private javax.swing.JLabel jLabelDirSocial; private javax.swing.JLabel jLabelFechaApertura; private javax.swing.JLabel jLabelHabitaciones; private javax.swing.JLabel jLabelMainTitulo; private javax.swing.JLabel jLabelNombre; private javax.swing.JLabel jLabelProvincia; private javax.swing.JLabel jLabelRazonSocial; private javax.swing.JLabel jLabelTelefono; private javax.swing.JLabel jLabelValoracion; private javax.swing.JPanel jPanelDatosAlojamiento; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JSpinner jSpinnerHabitaciones; private javax.swing.JSpinner jSpinnerValoracion; private javax.swing.JTextField jTextFieldInputDirSocial; private javax.swing.JTextField jTextFieldInputFechaApertura; private javax.swing.JTextField jTextFieldInputNombreAloj; private javax.swing.JTextField jTextFieldInputRazonSocial; private javax.swing.JTextField jTextFieldInputTelefono; private javax.swing.JTextPane jTextPaneInputDescripcionAloj; // End of variables declaration//GEN-END:variables }
import React, { useState } from 'react'; import axios from 'axios'; const AddEmployeeForm = ({onAddEmployee}) => { const [formData, setFormData] = useState({ firstName: '', lastName: '', dob: '', position: '', salary: '', }); const [loading, setLoading] = useState(false); const handleChange = (e) => { const { name, value } = e.target; setFormData((prevData) => ({ ...prevData, [name]: value, })); }; const handleSubmit = async (e) => { e.preventDefault(); // Basic form validation if (!formData.firstName || !formData.lastName || !formData.dob || !formData.position || !formData.salary) { alert('Please fill in all required fields.'); return; } setLoading(true); try { const formDataObject = new FormData(); formDataObject.append('firstName', formData.firstName); formDataObject.append('lastName', formData.lastName); formDataObject.append('dob', formData.dob); formDataObject.append('position', formData.position); formDataObject.append('salary', formData.salary); const response = await axios.post( 'http://localhost:8082/employee-service/employeesManage/createEmployee', formDataObject ); onAddEmployee(response.data); // Display the response in an alert alert(`Employee added successfully: ${JSON.stringify(response.data)}`); // Clear the form after successful submission setFormData({ firstName: '', lastName: '', dob: '', position: '', salary: '', }); } catch (error) { console.error('Error adding employee:', error); // Display the error message in an alert alert(`Error adding employee: ${error.message}`); } finally { setLoading(false); } }; return ( <div> <h2>เพิ่มข้อมูลพนักงาน</h2> <form onSubmit={handleSubmit}> <label> ชื่อจริง: <input type="text" name="firstName" value={formData.firstName} onChange={handleChange} /> </label> <br /> <label> นามสกุล: <input type="text" name="lastName" value={formData.lastName} onChange={handleChange} /> </label> <br /> <label> วันเกิด: <input type="date" name="dob" value={formData.dob} onChange={handleChange} /> </label> <br /> <label> ตำแหน่ง: <input type="text" name="position" value={formData.position} onChange={handleChange} /> </label> <br /> <label> เงินเดือน: <input type="number" name="salary" value={formData.salary} onChange={handleChange} /> </label> <br /> <button type="submit" disabled={loading}> {loading ? 'Adding Employee...' : 'Add Employee'} </button> </form> </div> ); }; export default AddEmployeeForm;
import type { Event } from '@prisma/client' import { events, event, createEvent, updateEvent, deleteEvent } from './events' import type { StandardScenario } from './events.scenarios' // Generated boilerplate tests do not account for all circumstances // and can fail without adjustments, e.g. Float. // Please refer to the RedwoodJS Testing Docs: // https://redwoodjs.com/docs/testing#testing-services // https://redwoodjs.com/docs/testing#jest-expect-type-considerations describe('events', () => { scenario('returns all events', async (scenario: StandardScenario) => { const result = await events() expect(result.length).toEqual(Object.keys(scenario.event).length) }) scenario('returns a single event', async (scenario: StandardScenario) => { const result = await event({ id: scenario.event.one.id }) expect(result).toEqual(scenario.event.one) }) scenario('creates a event', async () => { const result = await createEvent({ input: { date: '2023-12-02T23:21:22.460Z', time: 'String', title: 'String', description: 'String', tags: 'String', updatedAt: '2023-12-02T23:21:22.460Z', }, }) expect(result.date).toEqual(new Date('2023-12-02T23:21:22.460Z')) expect(result.time).toEqual('String') expect(result.title).toEqual('String') expect(result.description).toEqual('String') expect(result.tags).toEqual('String') expect(result.updatedAt).toEqual(new Date('2023-12-02T23:21:22.460Z')) }) scenario('updates a event', async (scenario: StandardScenario) => { const original = (await event({ id: scenario.event.one.id })) as Event const result = await updateEvent({ id: original.id, input: { date: '2023-12-03T23:21:22.461Z' }, }) expect(result.date).toEqual(new Date('2023-12-03T23:21:22.461Z')) }) scenario('deletes a event', async (scenario: StandardScenario) => { const original = (await deleteEvent({ id: scenario.event.one.id })) as Event const result = await event({ id: original.id }) expect(result).toEqual(null) }) })
If you want to import files from the OpenJDK into `libcore/`, you are reading the right documentation. # Concept ```text ---------A----------C------------ expected_upstream \ \ -----------B----------D---------- master ``` The general idea is to get a change from OpenJDK into libcore in AOSP by `git merge` from an OpenJDK branch. However, each file in `ojluni/` can come from a different OpenJDK version. `expected_upstream` is a staging branch storing the OpenJDK version of each file. Thus, we can use `git merge` when we update an `ojluni/` file from a new upstream version, and the command should automatically merge the file if no merge conflict. # Workflow ## Prerequisite * python3 * pip3 * A remote `aosp` is setup in your local git repository ## 1. Setup ```shell cd $ANDROID_BUILD_TOP/libcore source ./tools/expected_upstream/install_tools.sh ``` ## 2. Upgrade a java class to a higher OpenJDK version For example, upgrade `java.lang.String` to 11.0.13-ga version: ```shell ojluni_modify_expectation modify java.lang.String jdk11u/jdk-11.0.13-ga ojluni_merge_to_master # -b <bug id> if it fixes any bug ``` or if `java.lang.String` is missing in the EXPECTED_UPSTREAM file: ```shell ojluni_modify_expectation add jdk11u/jdk-11.0.13-ga java.lang.String ojluni_merge_to_master # -b <bug id> if it fixes any bug ``` `ojluni_merge_to_master` will `git-merge` from the upstream branch. If you see any merge conflicts, please resolve the merge conflicts as usual, and then run `git commit` to finalize the commit. ### Iteration You can build and test the change. If you need to import more files, ```shell ojluni_modify_expectation ... # -a imports more files into the last merge commit instead of a new commit ojluni_merge_to_master -a ``` ### Bash Autocompletion For auto-completion, `ojluni_modify_expectation` supports bash autocompletion. ```shell $ ojluni_modify_expectation modify java.lang.Str # <tab> java.lang.StrictMath java.lang.StringBuilder java.lang.StringUTF16 java.lang.String java.lang.StringCoding java.lang.StringBuffer java.lang.StringIndexOutOfBoundsException ``` ## 2a. Add a java test from the upstream The process is similar to the above commands, but needs to run `ojluni_modify_expectation` with an `add` subcommand. For example, add a test for `String.isEmpty()` method: ```shell ojluni_modify_expectation add jdk8u/jdk8u121-b13 java.lang.String.IsEmpty # -a imports more files into the last merge commit instead of a new commit ojluni_merge_to_master -a ``` Note: `java.lang.String.IsEmpty` is a test class in the upstream repository. # 3. Upload your changes for code reviews After you build and test, you are satisfied with your change, you can upload the change with the following commands ```shell # Upload the original upstream files to the expected_upstream branch $ git push aosp HEAD^2:refs/for/expected_upstream # Upload the merge commit to the master branch $ repo upload --cbr . ``` # Directory Layout in the `aosp/expected_upstream` branch. 1. `ojluni/` * It has the same layout as the ojluni/ files in `aosp/master` 2. `EXPECTED_UPSTREAM` file * The table has 3 columns, i.e. 1. Destination path in `ojluni/` 2. Expected upstream version / an upstream git tag 3. Upstream source path * The file format is like .csv file using a `,` separator 3. `tools/expected_upstream/` * Contains the tools # Understanding your change ## Changes that should be made via the `aosp/expected_upstream` branch 1. Add or upgrade a file from the upstream OpenJDK * You are reading the right document! This documentation tells you how to import the file from the upstream. Later, you can merge the file and `expected_upstream` into `aosp/master` branch. 2. Remove an `ojluni/` file that originally came from the OpenJDK * Please remove the file on both `aosp/master` and `aosp/expected_upstream` branches. Don't forget to remove the entry in the `EXPECTED_UPSTREAM` too. 3. Revert the merge commit on `aosp/master` from `expected_upstream` * If you don't plan to re-land your change on `aosp/master`, you should probably revert the change `aosp/expected_upstream` as well. * If you plan to re-land your change, your re-landing commit won't be a merge commit, because `git` doesn't allow you to merge the same commit twice into the same branch. You have 2 options 1. Revert your change on `expected_upsteam` too and start over again when you reland your change 2. Just accept that the re-landing commit won't be a merge commit. ## Changes that shouldn't happen in the `aosp/expected_upstream` branch In general, if you want to change an `ojluni/` file by a text editor / IDE manually, you should make the change on `aosp/master`. 1. Changes to non-OpenJDK files * Those files are usually under the `luni/` folder, you can make the change directly on `aosp/master` 2. Adding / updating a patch to an existing `ojluni/` file * You can make the change directly on `aosp/master`. Please follow this [patch style guideline](https://goto.google.com/libcore-openjdk8-verify). 3. Cherry-picking a commit from upstream * You should first try to update an `ojluni/` file to a particular upstream version. If you can't but still want to cherry-pick a upstream fix, you should do so on the `aosp/master` branch. 4. Changes to non-OpenJDK files in `ojluni/` * Files, e.g. Android.bp, don't come from the upstream. You can make the change directly on `aosp/master`. # [Only relevant if using `ojluni_refresh_files`] Submit your change in [AOSP gerrit](http://r.android.com/) ```text ----11.0.13-ga---------------- openjdk/jdk11u \ A \ ------------B-----C------------ expected_upstream \ --------------------D---E------ master ``` Here are the order of events / votes required to submit your CL on gerrit as of Nov 2021. 1. `Presubmit-Verified +2` on all 5 CLs * Due to [b/204973624](http://b/204973624), you may `Bypass-Presubmit +1` on commit `A` and `B` if the presubmit fails. 2. `Code-review +2` on all 5 CLs from an Android Core Library team member 3. If needed, `API-review +1` on commit `E` from an Android API council member 4. Click the submit button / `Autosubmit +1` on commit `B`, `C` and `E` * Never submit commit `A` individually without submitting `B` together. * Otherwise, gerrit will create another merge commit from `A` without submitting `B`. * Due a Gerrit bug, you can't submit the commit `C` before submitting `B` first manually, even though `B` is the direct parent of `C`. So just submit `B` yourself manually. * If you can't submit the CL due a permission issue, ask an Android Core Library member to submit. ## [Only relevant if using `ojluni_refresh_files`] Life of a typical change Commit graph of a typical change ```text ----11.0.13-ga---------------- openjdk/jdk11u \ A \ ------------B-----C------------ expected_upstream \ --------------------D---E------ master ``` Typically, you will need 5 CLs * Commit `A` imports the file and moves the file in the `ojluni/` folder * Commit `B` merges the file into the expected_upstream with other `ojluni` files * Commit `A` and `B` are created by the `ojluni_refresh_files` script * Commit `C` edits the entry in the `EXPECTED_UPSTREAM` file * Commit `D` is a merge commit created by `git merge` * Commit `E` adds Android patches * Includes other changes to non-OpenJDK files, e.g. `Android.bp`, `api/current.txt`. ### Why can't have a single commit to replace the commits `A`, `B` and `C`? * Preserve the upstream history. We can later `git blame` with the upstream history. # [Only relevant if using `ojluni_refresh_files`] Known bugs * `repo upload` may not succeed because gerrit returns error. 1. Just try to run `repo upload` again! * The initial upload takes a long time because it tries to sync with the remote AOSP gerrit server. The second upload is much faster because the `git` objects have been uploaded. 2. `repo upload` returns TimeOutException, but the CL has been uploaded. Just find your CL in http://r.android.com/. See http://b/202848945 3. Try to upload the merge commits 1 by 1 ```shell git rev-parse HEAD # a sha is printed and you will need it later git reset HEAD~1 # reset to a earlier commit repo upload --cbr . # try to upload it again git reset <the sha printed above> ``` * After `ojluni_modify_expectation add` and `ojluni_refresh_files`, a `git commit -a` would include more files than just EXPECTED_UPSTREAM, because `git`, e.g. `git status`, isn't aware of changes in the working tree / in the file system. This can lead to an error when checking out the branch that is based on master. 1. Do a `git checkout --hard <initial commit before the add>` 2. Rerun the `ojluni_modify_expectation add` and `ojluni_refresh_files` 3. `git stash && git stash pop` 4. Commit the updated EXPECTED_UPSTREAM and proceed # Report bugs * Report bugs if the git repository is corrupted! * Sometimes, you can recover the repository by running `git reset aosp/expected_upstream`
import { useMemo, useState, useEffect } from "react"; import Card from "components/Card"; import { useTranslation } from "react-i18next"; import { useHistory, useParams } from "react-router-dom"; import { Input } from "alisa-ui"; import Form from "components/Form/Index"; import * as yup from "yup"; import { useFormik } from "formik"; import Header from "components/Header"; import Button from "components/Button"; import Breadcrumb from "components/Breadcrumb"; import CancelIcon from "@mui/icons-material/Cancel"; import SaveIcon from "@mui/icons-material/Save"; import { useTheme } from "@mui/material/styles"; import { getCancelingReason, postCancelingReason, updateCancelingReason, } from "services"; import CustomSkeleton from "components/Skeleton"; import { StyledTab, StyledTabs } from "components/StyledTabs"; import SwipeableViews from "react-swipeable-views"; import TabPanel from "components/Tab/TabPanel"; import TextArea from "components/Textarea"; export default function CancelReasonsCreate() { const { t } = useTranslation(); const history = useHistory(); const params = useParams(); const theme = useTheme(); const a11yProps = (index) => { return { id: `full-width-tab-${index}`, "aria-controls": `full-width-tabpanel-${index}`, }; }; const handleChangeTab = (event, newValue) => { setValue(newValue); }; const handleChangeIndex = (index) => setValue(index); const tabLabel = (text, isActive = false) => ( <span className="px-1">{text}</span> ); const [value, setValue] = useState(0); const [isLoading, setIsLoading] = useState(true); const [saveLoading, setSaveLoading] = useState(false); const initialValues = useMemo( () => ({ text: "", text_for_client: { uz: "", en: "", ru: "", }, }), [], ); const onSubmit = (values) => { const data = { ...values, }; setSaveLoading(true); const selectedAction = params.id ? updateCancelingReason(params.id, data) : postCancelingReason(data); selectedAction .then((res) => { history.goBack(); }) .finally(() => { setSaveLoading(false); }); }; const formik = useFormik({ initialValues, onSubmit, }); const { values, handleChange, setValues, handleSubmit } = formik; const routes = [ { title: t(`cancel-reasons`), link: true, route: `/home/settings/content/cancel-reasons`, }, { title: params.id ? t("edit") : t("create"), }, ]; const headerButtons = ( <> <Button icon={CancelIcon} size="large" shape="outlined" color="red" borderColor="bordercolor" onClick={() => history.goBack()} > {t("cancel")} </Button> <Button icon={SaveIcon} size="large" type="submit" loading={saveLoading}> {t("save")} </Button> </> ); useEffect(() => { if (params.id) { getCancelingReason(params.id) .then((res) => { setValues({ text: res?.text, text_for_client: { uz: res?.text_for_client?.uz, ru: res?.text_for_client?.ru, en: res?.text_for_client?.en, }, }); }) .finally(() => { setIsLoading(false); }); } else { setIsLoading(false); } }, [params.id, setValues]); return !isLoading ? ( <form onSubmit={handleSubmit}> <div style={{ minHeight: "100vh" }} className="flex flex-col justify-between" > <div> <Header title={params.id ? t("edit") : t("add")} startAdornment={<Breadcrumb routes={routes} />} /> <div className="m-4"> <div className="grid grid-cols-2 gap-5"> <Card title={t("general.information")}> <div className="flex flex-col items-baseline"> <div className="input-label">{t("name")}</div> <div className="w-full"> <Form.Item formik={formik} name="text"> <Input size="large" value={values.text} onChange={handleChange} name="text" placeholder={t("input")} /> </Form.Item> </div> </div> <div> <StyledTabs value={value} onChange={handleChangeTab} centered={false} aria-label="full width tabs example" TabIndicatorProps={{ children: <span className="w-2" /> }} className="border-b mb-4" > <StyledTab label={ <span className="flex justify-around items-center"> {tabLabel(t("uz"))} </span> } {...a11yProps(0)} /> <StyledTab label={ <span className="flex justify-around items-center"> {tabLabel(t("ru"))} </span> } {...a11yProps(1)} /> <StyledTab label={ <span className="flex justify-around items-center"> {tabLabel(t("en"))} </span> } {...a11yProps(2)} /> </StyledTabs> <SwipeableViews axis={theme.direction === "rtl" ? "x-reverse" : "x"} index={value} onChangeIndex={handleChangeIndex} > <TabPanel value={value} index={0} dir={theme.direction}> <div className="input-label">{t("text_for_client")}</div> <div className="w-full"> <Form.Item formik={formik} name="text_for_client.uz"> <TextArea id="text_for_client.uz" {...formik.getFieldProps("text_for_client.uz")} /> </Form.Item> </div> </TabPanel> <TabPanel value={value} index={1} dir={theme.direction}> <div className="input-label">{t("text_for_client")}</div> <div className="w-full"> <Form.Item formik={formik} name="text_for_client.ru"> <TextArea id="text_for_client.ru" {...formik.getFieldProps("text_for_client.ru")} /> </Form.Item> </div> </TabPanel> <TabPanel value={value} index={2} dir={theme.direction}> <div className="input-label">{t("text_for_client")}</div> <div className="w-full"> <Form.Item formik={formik} name="text_for_client.en"> <TextArea id="text_for_client.en" {...formik.getFieldProps("text_for_client.en")} /> </Form.Item> </div> </TabPanel> </SwipeableViews> </div> </Card> </div> </div> </div> <div className="flex justify-end items-center w-full bg-white p-4 gap-5"> {headerButtons} </div> </div> </form> ) : ( <CustomSkeleton /> ); }
<?php /** * Nooku Framework - http://nooku.org/framework * * @copyright Copyright (C) 2007 - 2014 Johan Janssens and Timble CVBA. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link https://github.com/nooku/nooku-framework for the canonical source repository */ /** * APC 3.1.4 compatibility */ if(extension_loaded('apc') && !function_exists('apc_exists')) { /** * Check if an APC key exists * * @param mixed $keys A string, or an array of strings, that contain keys. * @return boolean Returns TRUE if the key exists, otherwise FALSE */ function apc_exists($keys) { $result = null; apc_fetch($keys,$result); return $result; } } /** * PHP5.4 compatibility * * @link http://nikic.github.io/2012/01/28/htmlspecialchars-improvements-in-PHP-5-4.html */ if (!defined('ENT_SUBSTITUTE')) { define('ENT_SUBSTITUTE', ENT_IGNORE); //PHP 5.3 behavior } /** * mbstring compatibility * * @link http://php.net/manual/en/book.mbstring.php */ if (!function_exists('mb_strlen')) { function mb_strlen($str) { return strlen(utf8_decode($str)); } } if (!function_exists('mb_substr')) { /* * Joomla checks if mb_substr exists to determine the availability of mbstring extension * Loading JString before providing the replacement function makes sure everything works */ if (class_exists('JLoader') && is_callable(array('JLoader', 'import'))) { JLoader::import('joomla.string.string'); JLoader::load('JString'); } function mb_substr($str, $offset, $length = NULL) { // generates E_NOTICE // for PHP4 objects, but not PHP5 objects $str = (string)$str; $offset = (int)$offset; if (!is_null($length)) $length = (int)$length; // handle trivial cases if ($length === 0) return ''; if ($offset < 0 && $length < 0 && $length < $offset) return ''; // normalise negative offsets (we could use a tail // anchored pattern, but they are horribly slow!) if ($offset < 0) { // see notes $strlen = strlen(utf8_decode($str)); $offset = $strlen + $offset; if ($offset < 0) $offset = 0; } $Op = ''; $Lp = ''; // establish a pattern for offset, a // non-captured group equal in length to offset if ($offset > 0) { $Ox = (int)($offset/65535); $Oy = $offset%65535; if ($Ox) { $Op = '(?:.{65535}){'.$Ox.'}'; } $Op = '^(?:'.$Op.'.{'.$Oy.'})'; } else { // offset == 0; just anchor the pattern $Op = '^'; } // establish a pattern for length if (is_null($length)) { // the rest of the string $Lp = '(.*)$'; } else { if (!isset($strlen)) { // see notes $strlen = strlen(utf8_decode($str)); } // another trivial case if ($offset > $strlen) return ''; if ($length > 0) { // reduce any length that would // go passed the end of the string $length = min($strlen-$offset, $length); $Lx = (int)( $length / 65535 ); $Ly = $length % 65535; // negative length requires a captured group // of length characters if ($Lx) $Lp = '(?:.{65535}){'.$Lx.'}'; $Lp = '('.$Lp.'.{'.$Ly.'})'; } else if ($length < 0) { if ( $length < ($offset - $strlen) ) { return ''; } $Lx = (int)((-$length)/65535); $Ly = (-$length)%65535; // negative length requires ... capture everything // except a group of -length characters // anchored at the tail-end of the string if ($Lx) $Lp = '(?:.{65535}){'.$Lx.'}'; $Lp = '(.*)(?:'.$Lp.'.{'.$Ly.'})$'; } } if (!preg_match( '#'.$Op.$Lp.'#us',$str, $match )) { return ''; } return $match[1]; } }
<?php namespace App\Exports; use Illuminate\View\View; use Illuminate\Database\Eloquent\Collection; use Maatwebsite\Excel\Concerns\FromView; use Maatwebsite\Excel\Concerns\ShouldAutoSize; use Maatwebsite\Excel\Concerns\WithProperties; class BugExport extends BaseExport implements FromView, WithProperties, ShouldAutoSize { /** * @var Illuminate\Database\Eloquent\Collection */ private $data; public function __construct(Collection $data) { $this->data = $data; } public function view(): View { $bugs = $this->data; return view('export.bugs', compact('bugs')); } /** * Set file properties * * @return array */ public function properties(): array { return [ 'creator' => env('APP_NAME'), 'lastModifiedBy' => env('APP_NAME'), 'title' => 'Liste des bugs', 'description' => 'Liste des bugs ControlPower', 'subject' => 'Liste des bugs', 'keywords' => 'bugs,export,spreadsheet,excel', 'category' => 'Bugs', 'manager' => 'Noual Ali - noualdev@gmail.com', 'company' => 'Banque Nationale d\'Algérie (BNA)', ]; } }
import React, { useState} from 'react'; import { Container, Typography, TextField, Button, Box, } from '@mui/material'; import axios from 'axios'; import { useNavigate, useParams } from 'react-router-dom'; //Formulario de contacto const Response = ({ onSubmit }) => { const {idMessage} = useParams("idMessage"); const [message, setMessage] = useState(''); const navigate = useNavigate(); const handleSubmit = (e) => { e.preventDefault(); axios.put("http://localhost:5000/api/contacts/"+idMessage, { status: "on", response: message, }).then(res => { navigate("/messages"); }) setMessage(''); }; return ( <Box> <Container maxWidth="md"> <Typography variant="h5" gutterBottom> Formulario de contacto </Typography> <Box component="form" onSubmit={handleSubmit}> <TextField label="Mensaje" fullWidth multiline required value={message} onChange={(e) => setMessage(e.target.value)} rows="15" sx={{height: "400px", mt: "10px"}} /> <Button type="submit" variant="contained" color="primary" sx={{ mt: 2 }}> Enviar </Button> </Box> </Container> </Box> ); } export default Response;
# JSON Viewer ## Description This web application allows you to upload a JSON file, view and edit its contents, apply filters to highlight specific attributes, and export the edited JSON file. ## Features - **Upload JSON**: Upload a JSON file from your local machine. - **View JSON**: Display the JSON data in a structured and editable format. - **Edit JSON**: Edit the values of the JSON data directly in the browser. - **Filter JSON**: Apply filters to highlight specific attributes and values. - **Export JSON**: Export the edited JSON data to a file. ## How to Run Locally ### Prerequisites - Node.js installed on your machine. You can download it from [nodejs.org](https://nodejs.org/). ### Steps 1. Clone the repository: ```sh git clone <repository-url> cd <repository-directory> 2. Install the dependencies: ```sh npm install 3. Start the local server: ```sh npm start 4. Open your web browser and go to http://127.0.0.1:8080/. ### File Structure 1. index.html: The main HTML file. 2. styles.css: The CSS file for styling the application. 3. script.js: The JavaScript file containing the application logic. ### Usage 1. Click the "Upload JSON" button to upload a JSON file. 2. View and edit the JSON data in the displayed text area. 3. Use the filter options to highlight specific attributes and values. 4. Click the "Export JSON" button to download the edited JSON file.
"""Component providing support for Reolink select entities.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass import logging from typing import Any from reolink_aio.api import ( Chime, ChimeToneEnum, DayNightEnum, HDREnum, Host, SpotlightModeEnum, StatusLedEnum, TrackMethodEnum, ) from reolink_aio.exceptions import InvalidParameterError, ReolinkError from homeassistant.components.select import SelectEntity, SelectEntityDescription from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers.entity_platform import AddEntitiesCallback from .entity import ( ReolinkChannelCoordinatorEntity, ReolinkChannelEntityDescription, ReolinkChimeCoordinatorEntity, ReolinkChimeEntityDescription, ) from .util import ReolinkConfigEntry, ReolinkData _LOGGER = logging.getLogger(__name__) @dataclass(frozen=True, kw_only=True) class ReolinkSelectEntityDescription( SelectEntityDescription, ReolinkChannelEntityDescription, ): """A class that describes select entities.""" get_options: list[str] | Callable[[Host, int], list[str]] method: Callable[[Host, int, str], Any] value: Callable[[Host, int], str] | None = None @dataclass(frozen=True, kw_only=True) class ReolinkChimeSelectEntityDescription( SelectEntityDescription, ReolinkChimeEntityDescription, ): """A class that describes select entities for a chime.""" get_options: list[str] method: Callable[[Chime, str], Any] value: Callable[[Chime], str] def _get_quick_reply_id(api: Host, ch: int, mess: str) -> int: """Get the quick reply file id from the message string.""" return [k for k, v in api.quick_reply_dict(ch).items() if v == mess][0] SELECT_ENTITIES = ( ReolinkSelectEntityDescription( key="floodlight_mode", cmd_key="GetWhiteLed", translation_key="floodlight_mode", entity_category=EntityCategory.CONFIG, get_options=lambda api, ch: api.whiteled_mode_list(ch), supported=lambda api, ch: api.supported(ch, "floodLight"), value=lambda api, ch: SpotlightModeEnum(api.whiteled_mode(ch)).name, method=lambda api, ch, name: api.set_whiteled(ch, mode=name), ), ReolinkSelectEntityDescription( key="day_night_mode", cmd_key="GetIsp", translation_key="day_night_mode", entity_category=EntityCategory.CONFIG, get_options=[mode.name for mode in DayNightEnum], supported=lambda api, ch: api.supported(ch, "dayNight"), value=lambda api, ch: DayNightEnum(api.daynight_state(ch)).name, method=lambda api, ch, name: api.set_daynight(ch, DayNightEnum[name].value), ), ReolinkSelectEntityDescription( key="ptz_preset", translation_key="ptz_preset", get_options=lambda api, ch: list(api.ptz_presets(ch)), supported=lambda api, ch: api.supported(ch, "ptz_presets"), method=lambda api, ch, name: api.set_ptz_command(ch, preset=name), ), ReolinkSelectEntityDescription( key="play_quick_reply_message", translation_key="play_quick_reply_message", get_options=lambda api, ch: list(api.quick_reply_dict(ch).values())[1:], supported=lambda api, ch: api.supported(ch, "play_quick_reply"), method=lambda api, ch, mess: ( api.play_quick_reply(ch, file_id=_get_quick_reply_id(api, ch, mess)) ), ), ReolinkSelectEntityDescription( key="auto_quick_reply_message", cmd_key="GetAutoReply", translation_key="auto_quick_reply_message", entity_category=EntityCategory.CONFIG, get_options=lambda api, ch: list(api.quick_reply_dict(ch).values()), supported=lambda api, ch: api.supported(ch, "quick_reply"), value=lambda api, ch: api.quick_reply_dict(ch)[api.quick_reply_file(ch)], method=lambda api, ch, mess: ( api.set_quick_reply(ch, file_id=_get_quick_reply_id(api, ch, mess)) ), ), ReolinkSelectEntityDescription( key="auto_track_method", cmd_key="GetAiCfg", translation_key="auto_track_method", entity_category=EntityCategory.CONFIG, get_options=[method.name for method in TrackMethodEnum], supported=lambda api, ch: api.supported(ch, "auto_track_method"), value=lambda api, ch: TrackMethodEnum(api.auto_track_method(ch)).name, method=lambda api, ch, name: api.set_auto_tracking(ch, method=name), ), ReolinkSelectEntityDescription( key="status_led", cmd_key="GetPowerLed", translation_key="doorbell_led", entity_category=EntityCategory.CONFIG, get_options=lambda api, ch: api.doorbell_led_list(ch), supported=lambda api, ch: api.supported(ch, "doorbell_led"), value=lambda api, ch: StatusLedEnum(api.doorbell_led(ch)).name, method=lambda api, ch, name: ( api.set_status_led(ch, StatusLedEnum[name].value, doorbell=True) ), ), ReolinkSelectEntityDescription( key="hdr", cmd_key="GetIsp", translation_key="hdr", entity_category=EntityCategory.CONFIG, entity_registry_enabled_default=False, get_options=[method.name for method in HDREnum], supported=lambda api, ch: api.supported(ch, "HDR"), value=lambda api, ch: HDREnum(api.HDR_state(ch)).name, method=lambda api, ch, name: api.set_HDR(ch, HDREnum[name].value), ), ) CHIME_SELECT_ENTITIES = ( ReolinkChimeSelectEntityDescription( key="motion_tone", cmd_key="GetDingDongCfg", translation_key="motion_tone", entity_category=EntityCategory.CONFIG, supported=lambda chime: "md" in chime.chime_event_types, get_options=[method.name for method in ChimeToneEnum], value=lambda chime: ChimeToneEnum(chime.tone("md")).name, method=lambda chime, name: chime.set_tone("md", ChimeToneEnum[name].value), ), ReolinkChimeSelectEntityDescription( key="people_tone", cmd_key="GetDingDongCfg", translation_key="people_tone", entity_category=EntityCategory.CONFIG, get_options=[method.name for method in ChimeToneEnum], supported=lambda chime: "people" in chime.chime_event_types, value=lambda chime: ChimeToneEnum(chime.tone("people")).name, method=lambda chime, name: chime.set_tone("people", ChimeToneEnum[name].value), ), ReolinkChimeSelectEntityDescription( key="visitor_tone", cmd_key="GetDingDongCfg", translation_key="visitor_tone", entity_category=EntityCategory.CONFIG, get_options=[method.name for method in ChimeToneEnum], supported=lambda chime: "visitor" in chime.chime_event_types, value=lambda chime: ChimeToneEnum(chime.tone("visitor")).name, method=lambda chime, name: chime.set_tone("visitor", ChimeToneEnum[name].value), ), ReolinkChimeSelectEntityDescription( key="package_tone", cmd_key="GetDingDongCfg", translation_key="package_tone", entity_category=EntityCategory.CONFIG, get_options=[method.name for method in ChimeToneEnum], supported=lambda chime: "package" in chime.chime_event_types, value=lambda chime: ChimeToneEnum(chime.tone("package")).name, method=lambda chime, name: chime.set_tone("package", ChimeToneEnum[name].value), ), ) async def async_setup_entry( hass: HomeAssistant, config_entry: ReolinkConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up a Reolink select entities.""" reolink_data: ReolinkData = config_entry.runtime_data entities: list[ReolinkSelectEntity | ReolinkChimeSelectEntity] = [ ReolinkSelectEntity(reolink_data, channel, entity_description) for entity_description in SELECT_ENTITIES for channel in reolink_data.host.api.channels if entity_description.supported(reolink_data.host.api, channel) ] entities.extend( ReolinkChimeSelectEntity(reolink_data, chime, entity_description) for entity_description in CHIME_SELECT_ENTITIES for chime in reolink_data.host.api.chime_list if entity_description.supported(chime) ) async_add_entities(entities) class ReolinkSelectEntity(ReolinkChannelCoordinatorEntity, SelectEntity): """Base select entity class for Reolink IP cameras.""" entity_description: ReolinkSelectEntityDescription def __init__( self, reolink_data: ReolinkData, channel: int, entity_description: ReolinkSelectEntityDescription, ) -> None: """Initialize Reolink select entity.""" self.entity_description = entity_description super().__init__(reolink_data, channel) self._log_error = True if callable(entity_description.get_options): self._attr_options = entity_description.get_options(self._host.api, channel) else: self._attr_options = entity_description.get_options @property def current_option(self) -> str | None: """Return the current option.""" if self.entity_description.value is None: return None try: option = self.entity_description.value(self._host.api, self._channel) except ValueError: if self._log_error: _LOGGER.exception("Reolink '%s' has an unknown value", self.name) self._log_error = False return None self._log_error = True return option async def async_select_option(self, option: str) -> None: """Change the selected option.""" try: await self.entity_description.method(self._host.api, self._channel, option) except InvalidParameterError as err: raise ServiceValidationError(err) from err except ReolinkError as err: raise HomeAssistantError(err) from err self.async_write_ha_state() class ReolinkChimeSelectEntity(ReolinkChimeCoordinatorEntity, SelectEntity): """Base select entity class for Reolink IP cameras.""" entity_description: ReolinkChimeSelectEntityDescription def __init__( self, reolink_data: ReolinkData, chime: Chime, entity_description: ReolinkChimeSelectEntityDescription, ) -> None: """Initialize Reolink select entity for a chime.""" self.entity_description = entity_description super().__init__(reolink_data, chime) self._log_error = True self._attr_options = entity_description.get_options @property def current_option(self) -> str | None: """Return the current option.""" try: option = self.entity_description.value(self._chime) except ValueError: if self._log_error: _LOGGER.exception("Reolink '%s' has an unknown value", self.name) self._log_error = False return None self._log_error = True return option async def async_select_option(self, option: str) -> None: """Change the selected option.""" try: await self.entity_description.method(self._chime, option) except InvalidParameterError as err: raise ServiceValidationError(err) from err except ReolinkError as err: raise HomeAssistantError(err) from err self.async_write_ha_state()
import React, { useState } from 'react'; import {Box} from '../../contents/Box' import {FormField, FormItem, FormBtn, FormTitle, FormInput} from '../FormContacts/FormContacts.styled' export default function FormContacts({onSubmit}) { const [name, setName] = useState(''); const [number, setNumber] = useState(''); const inputNameChange = e => { const value = e.currentTarget.value; if (value.length <= 30 && /^[a-zA-Zа-яА-Я]*$/.test(value)) { setName( value ); } } const inputNumberChange = e => { const value = e.currentTarget.value; if (value.length <= 7 && /^\d*$/.test(value)) { setNumber(value ); } } const contactsSubmit = e => { e.preventDefault(); // console.log(name) // console.log(number) // console.log(onSubmit) onSubmit(name, number); setName(''); setNumber(''); } return ( <Box border="2px solid #003B46" borderRadius="5px" width="350px" display="flex" flexDirection="column" alignItems="center" bg="#C4DFE6" p="40px 0px" height="170px" > <FormTitle>Phonebook</FormTitle> <FormField onSubmit={contactsSubmit}> <FormItem> Name <FormInput type="text" name="name" placeholder="Name" pattern="[a-zA-Zа-яА-Я]{5,20}" title="Содержит только буквы, минимум 5" maxLength="30" required value={name} onChange={inputNameChange} /> </FormItem> <FormItem> Phone number <FormInput type="tel" placeholder="Phone number" name="number" pattern="\d{7,7}" title="Номер телефона состоит из 7 цифр" maxLength="7" required value={number} onChange={inputNumberChange} /> </FormItem> <FormBtn type="submit">Add contacts</FormBtn> </FormField> </Box> ); }
/* (1) Synchronous:- Store in Main stack (2) Asynchronous: stored in Side stack, always return a promise (3) Async-Await:- async function always return a promise (4) Syntax:- async function myFunc(){....} (5) Await:- A keyword used to pause the execution of an async function until the Promise is settled (either resolved or rejected). (6) Benefits of Using Async-Await:- :- Async-Await ka use hum krte hai Asynchronous ko Synchronous ki tarah Behave krwane ke liye. :- With Async-Await aap synchronous code bhi aise likh skte ho jaise ki aap noraml Synchronous code likhe rahe ho. :- Await ka matalb hai agli line tab ka na execute kro jabtak agle ka answer na aa jaye. :- Await ko work krwane ke liye Await ke parent function me Async lagana padega. */ //! Example.1 async function getData() { // get request:- async (async hai toh aage await laga denge toh synchronous ke tarah behave krega) const response = await fetch("https://jsonplaceholder.typicode.com/posts/1"); // parse json:- async const data = await response.json(); //converting in JSON format console.log(data); } // getData(); //! Example.2 async function fetchWithErrorHandling() { try { const response = await fetch("invalid-url"); const data = await response.json(); console.log(data); } catch (error) { console.error("Error:", error); } } // fetchWithErrorHandling(); /* Notes: In async-await if condition is true code will execute & if condition is false then error occur to overcome this problem we always use try catch method. */ //! Example.3 const promiseOne = new Promise((reslove, reject) => { setTimeout(() => { if (true) { reslove({ userName: "Ankit", password: "12345" }); } else { reject("Error: Something went wrong"); } }, 1000); }); async function consumePromiseOne() { try { let result = await promiseOne; console.log(result); } catch (error) { console.log(error); } } // consumePromiseOne(); //! Example.5 function api() { return new Promise((resolve, reject) => { setTimeout(() => { console.log("Weather data"); resolve(200); }, 1000); }); } async function getWetherData() { let result = await api(); console.log(result); } // getWetherData();
import 'package:equatable/equatable.dart'; import '../../domain/entities/season.dart'; class SeasonModel extends Equatable { SeasonModel({ required this.airDate, required this.episodeCount, required this.id, required this.name, required this.overview, required this.posterPath, required this.seasonNumber, }); final DateTime? airDate; final int episodeCount; final int id; final String? name; final String? overview; final String? posterPath; final int? seasonNumber; factory SeasonModel.fromJson(Map<String, dynamic> json) => SeasonModel( airDate: json['air_date'] == null ? null : DateTime.parse(json["air_date"]), episodeCount: json["episode_count"], id: json["id"], name: json["name"], overview: json["overview"], posterPath: json["poster_path"], seasonNumber: json["season_number"], ); Season toEntity() { return Season( airDate: this.airDate, episodeCount: this.episodeCount, id: this.id, name: this.name, overview: this.overview, posterPath: this.posterPath, seasonNumber: this.seasonNumber, ); } @override List<Object?> get props => [ airDate, episodeCount, id, name, overview, posterPath, seasonNumber, ]; }
import React from 'react'; import { Row, Col, Button, Input } from "antd"; type Callback = (error?: Error) => void; type AddHandler = (name: string, callback: Callback) => void; const NOOP_ADD_HANDLER = (name: string, callback: Callback) => callback(); type TaskFormProps = { nameValue?: string; onAdd?: AddHandler; }; export default function TaskForm({ onAdd = NOOP_ADD_HANDLER, nameValue = ''}: TaskFormProps) { const [name, setName] = React.useState(nameValue); const [addTaskEnabled, setAddTaskEnabled] = React.useState(!!nameValue); const [loading, setLoading] = React.useState(false); // TODO: how to use useRef? const inputRef = React.useRef<any>(undefined); const handleClick = () => { setLoading(true); onAdd(name, (err) => { setLoading(false); inputRef.current.focus(); setName(''); }); }; const handleKeyEnter = () => { if (!name) { return; } setLoading(true); onAdd(name, (err) => { setLoading(false); setName(''); inputRef.current.focus(); }); }; const handleKeyPress = (event: React.KeyboardEvent) => { if (event.key !== 'Enter') { return; } handleKeyEnter(); }; const handleNameChange = (event: React.ChangeEvent<HTMLInputElement>) => { setName(event.target.value); }; React.useEffect(() => { setAddTaskEnabled(name.length !== 0); }, [name]); return ( <Row gutter={10}> <Col flex={1}> <Input placeholder='Enter task name' value={name} onChange={handleNameChange} onKeyPress={handleKeyPress} disabled={loading} ref={inputRef} /> </Col> <Col> <Button data-testid='add-task' type='primary' onClick={handleClick} disabled={!addTaskEnabled} loading={loading} > Add task </Button> </Col> </Row> ); }