text
stringlengths
184
4.48M
#include <stdlib.h> #include "binary_trees.h" /** * binary_tree_insert_right - function to insert node to it's parent right. * @parent: parent of the new node. * @value: value of the new node. * Return: the new node. */ binary_tree_t *binary_tree_insert_right(binary_tree_t *parent, int value) { binary_tree_t *new = malloc(sizeof(binary_tree_t)); if (new == NULL || parent == NULL) return (NULL); new->n = value; new->left = NULL; new->right = NULL; new->parent = parent; if (parent->right != NULL) { new->right = parent->right; new->right->parent = new; parent->right = new; } else { parent->right = new; } return (new); }
/** * <p>Copyright: Copyright (c) 2019</p> * * <h3>License</h3> * * Copyright (c) 2019 by Jonatan Gomez-Perdomo. <br> * All rights reserved. <br> * * <p>Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * <ul> * <li> Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * <li> 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. * <li> Neither the name of the copyright owners, their employers, nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * </ul> * <p>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 OWNERS 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. * * * * @author <A HREF="http://disi.unal.edu.co/profesores/jgomezpe"> Jonatan Gomez-Perdomo </A> * (E-mail: <A HREF="mailto:jgomezpe@unal.edu.co">jgomezpe@unal.edu.co</A> ) * @version 1.0 */ package speco.array.sort; import kompari.Order; import speco.array.Sort; /** * <p>Bubble sort algorithm</p> * @param <T> Type of elements in the array */ public class Bubble<T> extends Sort<T> { /** * Creates a sorting algorithm with the given order * @param order Order used for sorting the objects */ public Bubble(Order<T> order) { super(order); } /** * Crates a sorting algorithm with the given order * @param order Order used for sorting the objects * @param start Initial position in the array to be sorted * @param end Final position in the array to be sorted */ public Bubble(Order<T> order, int start, int end){ super(order, start, end ); } /** * Sorts a portion of the array of objects according to the given order (it does not creates a new array) * @param a Array of objects to be sorted * @param start Initial position in the array to be sorted * @param end Final position in the array to be sorted */ @Override public void apply(Object a, int start, int end, Order<T> order) { for(int i = start; i < end - 1; i++){ @SuppressWarnings("unchecked") T x = (T)java.lang.reflect.Array.get(a, i); for(int j = i + 1; j < end; j++) { @SuppressWarnings("unchecked") T y = (T)java.lang.reflect.Array.get(a, j); if(order.compare(y, x)<0) { java.lang.reflect.Array.set(a, i, y); java.lang.reflect.Array.set(a, j, x); x = y; } } } } }
import React from "react"; import { FaShare } from "react-icons/fa"; import { FaGithub } from "react-icons/fa"; import { Zoom } from "react-awesome-reveal"; const ProjectCard = ({project}) => { return ( <div className="lg:mt-5 flex flex-col"> <Zoom> <div className="centered flex-row lg:w-5/6 w-full m-auto "> <a href={project.url} target="_blank" className="h-[220px] w-1/2 xl:w-1/3 min-w-[300px] bg-white rounded-xl hidden lg:block "> <img className="object-fit w-full h-full rounded-xl " src={project.img} alt="" /> </a> <div className=" lg:w-1/2 w-full "> <div className="mt-10"> <div className="lg:w-full lg:h-[200px] h-[210px] bg-gradient-to-t from-secondary to-gray-300 rounded-xl flex flex-col lg:mx-10 text-white "> <span className="flex justify-end lg:text-[25px] text-[23px] "> {project.title} </span> <p className="text-justify lg:text-[19px] text-[16px] mt-[15px] mx-4 text-primary text-size-14"> {project.desc} </p> </div> </div> <span className="text-[15px] text-white lg:mr-[-35px] flex justify-end mt-[10px] "> {project.tech} </span> <a href={project.url} target="_blank" className="flex justify-end mt-[10px] lg:mr-[-35px]"> <FaGithub className=" text-white mr-5 w-7 h-7" /> <FaShare className=" text-white text-right w-7 h-7" /> </a> </div> </div> </Zoom> </div> ); }; export default ProjectCard;
import { defineStore } from "pinia"; export const useMainStore = defineStore("main", { state: () => ({ userProfile: { name: "Jacob Anderson", age: 23, interests: ["Music", "Programming", "Chess", "Playing Piano"], about: "My name is Jacob Anderson, I am from Georgia and absolutely love music!", education: [ { degree: "Major: Computer Engineering, Minor: Computer Science", institution: "Brigham Young University, Provo, UT", description: "Current GPA: 3.77, August 2020 to Present", }, { degree: "College classes while in HS", institution: "Georgia State University", description: "GPA 3.52, Aug 2017 to May 2018", }, ], work: [ { role: "Undergrad Research", company: "Brigham Young University", description: "Assisted in developing a non-invasive glucose device with Dr. Chiang and Dr. Davis, focusing on system integration and data analysis. Sep 2022 to Present", }, { role: "Private Instructor and Instructor Success Trainer (IST)", company: "Juni Learning", description: "Taught youth (7-18) programming, math, and science 1-on-1. May 2021 to Present", }, { role: "Full-Time Service Volunteer in Ecuador", company: "The Church of Jesus Christ of Latter-day Saints", description: "Held leadership/manager positions over 12 volunteers. July 2018 to Apr 2020", }, { role: "Programmer and Assistant", company: "AudioT", description: "Worked for the start-up AudioT in programming Raspberry Pi’s using Python and Bash. May 2020 to August 2020", }, { role: "Web Designer", company: "Freelance", description: "Wrote and prepared websites using HTML, CSS, JavaScript and Vue. July 2020 to June 2021", }, ], skills: [ "Fluent in Spanish – Reading and Writing proficiency Moderate to High", "Programming – C, C++, Java, TypeScript, Python, System Verilog, HTML, CSS, JavaScript (moderate fluency), Scratch, RISC-V Assembly, React, and Vue", ], achievements: [ "Rank of Eagle Scout in the BSA organization", "Phi Eta Sigma Honor Society Member", ], otherActivities: [ "Study Abroad at Georgia Tech Lorraine in Metz France Winter semesters of 2015 and 2016", "First Lego League Robotics Team 2011 to 2014", "Shakespeare Tavern of Atlanta, Volunteer", ], experience: [ { role: "Research Assistant", location: "BYU", description: "Assisting in research for developing a non-invasive glucose monitoring device.", }, { role: "Employee", location: "Chick-Fil-A", description: "I worked at Chick-Fil-A for a few years", }, { role: "Employee", location: "Crumbl", description: "I worked at Crumbl over the summer", }, { role: "Web Developer", location: "Freelance", description: "I worked for my dad writing websites over the summer", }, { role: "Web Developer", location: "Startup", description: "I worked for my dad's student's startup over the summer", }, ], projects: [ { name: "Website for Dad", description: "I wrote a basic website for my Dad (With HTML and CSS only)", }, { name: "Student Startup Website", description: "I wrote and am writing a website for his student's startup he's helping with", }, { name: "Eagle Project", description: "I did an eagle project creating an orienteering course", }, ], }, }), // Define actions for fetching or mutating the state actions: { // Used for APIs }, // Define getters to compute derived state or access specific parts of the state getters: { // Example getter for getting all event names // eventNames: state => state.events.body.map(event => event.name), }, });
import React, { useEffect, useState } from "react"; import axios from "axios"; import TableContainer from "@material-ui/core/TableContainer"; import Table from "@material-ui/core/Table"; import TableHead from "@material-ui/core/TableHead"; import TableRow from "@material-ui/core/TableRow"; import TableCell from "@material-ui/core/TableCell"; import TableBody from "@material-ui/core/TableBody"; import Paper from "@material-ui/core/Paper"; import { makeStyles } from "@material-ui/core/styles"; import { FaStar } from "react-icons/fa"; import IconButton from "@material-ui/core/IconButton"; import ArrowUpwardIcon from "@material-ui/icons/ArrowUpward"; import ArrowDownwardIcon from "@material-ui/icons/ArrowDownward"; import "./Feedbacks.css"; const StarRating = ({ rating }) => { const stars = Array(5).fill(0); return ( <div> {stars.map((_, index) => ( <FaStar key={index} size={24} color={index < rating ? "#FFBA5A" : "#a9a9a9"} /> ))} </div> ); }; const useStyles = makeStyles((theme) => ({ container: { margin: 10, }, filterInput: { marginBottom: 10, marginRight: 10, }, addButton: { backgroundColor: theme.palette.primary.main, color: theme.palette.common.white, "&:hover": { backgroundColor: theme.palette.primary.dark, }, marginRight: 10, }, tableContainer: { marginTop: 20, }, table: { width: "100%", }, tableHeader: { backgroundColor: theme.palette.grey[200], }, tableCell: { border: `1px solid ${theme.palette.grey[400]}`, textAlign: "left", padding: 12, }, actionsCell: { display: "flex", gap: 8, }, editButton: { backgroundColor: theme.palette.warning.main, color: theme.palette.common.white, "&:hover": { backgroundColor: theme.palette.warning.dark, }, }, deleteButton: { backgroundColor: theme.palette.error.main, color: theme.palette.common.white, "&:hover": { backgroundColor: theme.palette.error.dark, }, }, sortIcon: { fontSize: 18, }, })); const FeedbacksTable = () => { const classes = useStyles(); const [feedback, setFeedback] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [sortOrder, setSortOrder] = useState("desc"); useEffect(() => { const fetchData = async () => { try { const feedbackData = await axios.get( `http://localhost:8080/feedback/getAllFeedbacks` ); setFeedback(feedbackData.data); } catch (error) { console.error("Error fetching data: ", error); setError(error.message); } finally { setLoading(false); } }; fetchData(); }, []); const sortByRating = (a, b) => { if (sortOrder === "asc") { return a.rating - b.rating; } else { return b.rating - a.rating; } }; const sortedFeedback = [...feedback].sort(sortByRating); const toggleSortOrder = () => { setSortOrder(sortOrder === "asc" ? "desc" : "asc"); }; return ( <div className={classes.container}> <h2>Feedback List</h2> <TableContainer component={Paper} className={classes.tableContainer}> <Table className={classes.table}> <TableHead> <TableRow className={classes.tableHeader}> <TableCell>ID</TableCell> <TableCell>First Name</TableCell> <TableCell>Last Name</TableCell> <TableCell>Feedback text</TableCell> <TableCell> Rating{" "} <IconButton onClick={toggleSortOrder}> {sortOrder === "asc" ? ( <ArrowUpwardIcon className={classes.sortIcon} /> ) : ( <ArrowDownwardIcon className={classes.sortIcon} /> )} </IconButton> </TableCell> <TableCell>Feedback date</TableCell> </TableRow> </TableHead> <TableBody> {sortedFeedback.map((feedbackItem, index) => ( <TableRow key={feedbackItem.id} className={index % 2 === 0 ? classes.evenRow : classes.oddRow} > <TableCell className={classes.tableCell}> {feedbackItem.id} </TableCell> <TableCell className={classes.tableCell}> {feedbackItem.firstName} </TableCell> <TableCell className={classes.tableCell}> {feedbackItem.lastName} </TableCell> <TableCell className={classes.tableCell}> {feedbackItem.feedbackText} </TableCell> <TableCell className={classes.tableCell}> <StarRating rating={feedbackItem.rating} /> </TableCell> <TableCell className={classes.tableCell}> {feedbackItem.feedbackDate ? new Date(feedbackItem.feedbackDate).toLocaleDateString( "en-GB" ) : "N/A"}{" "} </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> </div> ); }; export default FeedbacksTable;
import {compare} from "bcrypt"; import jwt from "jsonwebtoken"; import UserModel from "../../Model/User/User.js"; const AuthUser={ login:async(req,res)=>{ try { if(req.session.token){ return res.status(200).json({ status: true, message: 'Login Already Login.'}); } else{ const { email,password} = req.body; const user = await UserModel.findOne({ where: { email: email } }); if (!user) { return res.status(404).json({ status: false, message: 'User Not Registered.' }); } const comparepassword=await compare(password,user.password); if (!comparepassword) { return res.status(401).json({ status: false, message: 'Password Not Matched.' }); } const data = { id: user.id, email: user.email, password: user.password, }; const token = jwt.sign(data, process.env.JWT_SECRET, { expiresIn: "1d", }); req.session.token=token;//setting session with token return res.status(200).json({ status: true, message: 'Login successful.', user,token }); } } catch (e) { return res.status(500).json({ status: false, error: `An error occurred while login user.${e.message}` }); } }, logout:async(req,res)=>{ try { if(req.session.token){ await req.session.destroy(); return res.status(200).json({ status: true, message: 'Logout successful.' }); } else{ return res.status(200).json({ status: true, message: 'You Are Not Logged IN.' }); } } catch (e) { return res.status(500).json({ status: false, error: `An error occurred while logging out.${e.message}` }); } } } export default AuthUser;
import * as React from 'react'; import {render, fireEvent} from '@testing-library/react-native'; import {useDispatch} from 'react-redux'; import {CategoryToggle} from '../src/components'; import {setCategory, removeCategory} from '../src/state/categorySlice'; import {IToggleProps} from '../src/components/category-toggle'; // Mock useDispatch jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux'), useDispatch: jest.fn(), })); describe('CategoryToggle', () => { const mockDispatch = jest.fn(); beforeEach(() => { // Clear mock and set a mock implementation before each test mockDispatch.mockClear(); (useDispatch as unknown as jest.Mock).mockReturnValue(mockDispatch); }); it('dispatches setCategory action on press when not active', () => { const props: IToggleProps = { active: false, categoryName: 'Greyhound', categoryId: 'test-category-id', }; const {getByText} = render(<CategoryToggle {...props} />); fireEvent.press(getByText(props.categoryName)); expect(mockDispatch).toHaveBeenCalledWith(setCategory(props.categoryId)); }); it('dispatches removeCategory action on press when active', () => { const props: IToggleProps = { active: true, categoryName: 'Greyhound', categoryId: 'test-category-id', }; const {getByText} = render(<CategoryToggle {...props} />); fireEvent.press(getByText(props.categoryName)); expect(mockDispatch).toHaveBeenCalledWith(removeCategory(props.categoryId)); }); });
// // Created by fufeng on 2023/12/6. // #include <iostream> //假设类A有一个成员变量是一个int数组,在C++98/03标准中,如果要在构造函数中对其进行初始化,需要这样写: //C++98/03类成员变量是数组时的初始化语法 class A { public: A() { arr[0] = 2; arr[1] = 0; arr[2] = 1; arr[3] = 9; } public: int arr[4]; }; // 对于字符数组,可能就要在构造函数中使用strcpy、memcpy这一类函数了; // 再者如果数组元素足够多,初始值又没什么规律,这种赋值代码会有很多行。 // 但是,如果arr是一个局部变量,在定义arr时其实是可以使用如下的语法初始化的: // int arr[4] = {2, 0, 1, 9}; // // 既然C++98/03标准中,局部变量数组支持这种语法,为什么在类成员变量语法中就不支持呢? // 这是旧语法不合理的一个地方,因此在C++11语法中类成员变量也可以使用这种语法进行初始化了: //C++11类成员变量是数组时的初始化语法 class A11 { public: A11() : arr{2, 0, 1, 9} { } public: int arr[4]; }; // 但在C++89/03标准中要使用这种语法,必须是针对类的static const成员,且必须是整型(包括bool、char、int、long等)。 //C++89/03在类定义处初始化成员变量 class A_const { public: //T的类型必须整型,且必须是static const成员 //static const T t = 某个整型值; static const int t = 0; }; //在C++11标准中,就没有这种限制了,你可以使用花括号(即{})对任意类型的变量进行初始化,且不用是static类型。 //C++11在类定义处初始化成员变量 class A11_const { public: bool ma{true}; int mb{2019}; std::string mc{"helloworld"}; }; int main(int argc, char *argv[]) { return 0; }
import { Injectable } from '@angular/core'; import { Actions, createEffect, ofType } from '@ngrx/effects'; import { CreateRestaurant, EditRestaurant, LoadCategories, LoadCompanyRestaurants, LoadRestaurants, RemoveRestaurant, SearchRestaurants, SuccessCreateRestaurant, SuccessEditRestaurant, SuccessLoadCategories, SuccessLoadRestaurants, SuccessRemoveRestaurant } from './restaurants.actions'; import { catchError, first, map, switchMap, take } from 'rxjs/operators'; import { RestaurantsService } from './restaurants.service'; import { combineLatest, from, Observable, of } from 'rxjs'; import { select, Store } from '@ngrx/store'; import { State } from '../index'; import { ErrorAction, SuccessForm } from '../commons/commons.actions'; import { ErrorType, Restaurant, Table } from '@bon-appetit/interfaces'; import { companyQuery } from '../company/company.selectors'; import { LoadTables, SuccessLoadTables } from '../tables/tables.actions'; @Injectable() export class RestaurantsEffects { companyId$: Observable<number> = this.store.pipe( select(companyQuery.getCompanyId), first<number>(Boolean) ); constructor(private actions$: Actions, private restaurantsService: RestaurantsService, private store: Store<State>) {} loadRestaurants$ = createEffect(() => this.actions$.pipe( ofType(LoadRestaurants), switchMap(() => { return this.restaurantsService.getRestaurants().pipe( map((restaurants: Restaurant[]) => { return SuccessLoadRestaurants({ restaurants }); }), catchError(e => { return of( ErrorAction({ error: { type: ErrorType.ERROR_LOAD_RESTAURANTS, message: 'Wystąpił bląd podczas pobierania restauracji.' } }) ); }) ); }) ) ); createRestaurant$ = createEffect(() => this.actions$.pipe( ofType(CreateRestaurant), switchMap(({ createRestaurant }) => { return this.restaurantsService.create(createRestaurant).pipe( switchMap((restaurant: Restaurant) => { return from([ SuccessCreateRestaurant({ restaurant }), SuccessForm() ]); }), catchError(e => { return of( ErrorAction({ error: { type: ErrorType.ERROR_CREATE_RESTAURANT, message: 'Wystąpił bląd podczas tworzenia restauracji.' } }) ); }) ); }) ) ); editRestaurant$ = createEffect(() => this.actions$.pipe( ofType(EditRestaurant), switchMap(({ editRestaurant }) => { return this.restaurantsService.edit(editRestaurant).pipe( map(changes => { return SuccessEditRestaurant({ changes }); }), catchError(e => { return of( ErrorAction({ error: { type: ErrorType.ERROR_EDIT_RESTAURANT, message: 'Wystąpił bląd podczas edycji restauracji.' } }) ); }) ); }) ) ); removeRestaurant$ = createEffect(() => this.actions$.pipe( ofType(RemoveRestaurant), switchMap(({ restaurantId }) => { return this.restaurantsService.remove(restaurantId).pipe( map(() => { return SuccessRemoveRestaurant({ restaurantId }); }), catchError(e => { return of( ErrorAction({ error: { type: ErrorType.ERROR_REMOVE_RESTAURANT, message: 'Wystąpił bląd podczas usuwania restauracji.' } }) ); }) ); }) ) ); loadCategories = createEffect(() => this.actions$.pipe( ofType(LoadCategories), switchMap(() => { return this.restaurantsService.loadCategories().pipe( map((categories: []) => { return SuccessLoadCategories({ categories }); }), catchError(e => { return of( ErrorAction({ error: { type: ErrorType.ERROR_REMOVE_RESTAURANT, message: 'Wystąpił bląd podczas usuwania restauracji.' } }) ); }) ); }) ) ); loadRestaurantsCompany$ = createEffect(() => this.actions$.pipe( ofType(LoadCompanyRestaurants), switchMap(() => { return combineLatest([this.companyId$]).pipe( switchMap(([ companyId]) => { return this.restaurantsService.searchRestaurantCompany(companyId).pipe( map((restaurants: Restaurant[]) => { return SuccessLoadRestaurants({ restaurants }); }), catchError(() => { return of( ErrorAction({ error: { type: ErrorType.ERROR_LOAD_RESTAURANTS, message: 'Wystąpił bląd podczas pobierania restauracji.' } }) ); }) ); }) ) }) ) ); searchRestaurants$ = createEffect(() => this.actions$.pipe( ofType(SearchRestaurants), switchMap(({ searchQuery }) => { return this.restaurantsService.searchRestaurant(searchQuery).pipe( map(restaurants => { return SuccessLoadRestaurants({ restaurants }); }) ) }) ) ) }
<!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>Fundamentos JavaScript</title> </head> <body> <h1>FUNDAMENTOS JAVASCRIPT</h1> <h2>OBJETOS LITERALES</h2> <script> /* ********** Curso JavaScript: 18. OBJETOS LITERALES - #jonmircha ********** */ // antes let nombre = "Kenai"; edad =3; const perro = { nombre: nombre, edad:edad, ladrar: function() { console.log ("guau guau!!") } } console.log(perro); perro.ladrar(); // ahora const dog = { nombre, edad, raza:"Callejero", ladrar () { console.log("guauu guauu guauu!!!") } } console.log(dog); dog.ladrar(); </script> </body> </html>
package com.example; import com.example.forum.repository.ForumJpaRepository; import com.example.forum.repository.ForumRepository; import com.example.forum.service.ForumService; import com.example.forum.service.ForumServiceImpl; import com.example.login.repository.LoginJpaRepository; import com.example.login.repository.LoginRepository; import com.example.login.service.LoginService; import com.example.login.service.LoginServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.persistence.EntityManager; @Configuration public class SpringConfig { private final EntityManager em; @Autowired public SpringConfig(EntityManager em) { this.em = em; } /** 로그인 */ @Bean public LoginService loginService() { return new LoginServiceImpl(loginRepository()); } @Bean public LoginRepository loginRepository() { return new LoginJpaRepository(em); } /** 게시판 */ @Bean public ForumService forumService() { return new ForumServiceImpl(forumRepository()); } @Bean public ForumRepository forumRepository() { return new ForumJpaRepository(em); } }
<?php namespace Memo\Game; use JsonSerializable; /** * Represents a question of a game. */ interface Question extends JsonSerializable { /** * Submits an answer to the question. * * @param mixed $answer The answer. * @return boolean True if the answer is correct, false otherwise. */ public function submitAnswer(mixed $answer): bool; /** * Returns the maximum number of answers that can be submitted. * * @return integer|null The number of attempts. Null if it is unlimited. */ public function maxAnswerAttempts(): ?int; }
import { useContext, useEffect, useState } from 'react' import { UserContextProvider, UserContext } from './UserContext' const Example = () => { return ( <> <UserContextProvider> <Header /> <Content /> </UserContextProvider> </> ) } const Header = () => { const { user, isAuth, login, logout } = useContext(UserContext) return ( <> <h1>Header</h1> <h2>{isAuth ? user.name : 'Log in first'}</h2> <button onClick={login}>Login</button> <button onClick={logout}>Logout</button> </> ) } const Content = () => { const { user, isAuth } = useContext(UserContext) return <>{isAuth ? user.age : null}</> } export default Example
// // Copyright 2023 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import React, {useCallback} from 'react'; import {FlatList, StyleSheet, View} from 'react-native'; import type {NativeStackScreenProps} from '@react-navigation/native-stack'; import {Loading} from '../components/Loading'; import {Movie} from '../models/Movie'; import {MovieList} from '../components/MovieList'; import {MoviesNavigatorParamList} from '../navigation/MoviesNavigator'; import {routes} from '../navigation/routes'; import {useMovies} from '../providers/MovieProvider'; type MoviesScreenProps = NativeStackScreenProps< MoviesNavigatorParamList, typeof routes.MOVIES >; /** * Displays the movies by genre/category. */ export function MoviesScreen({navigation: {navigate}}: MoviesScreenProps) { const {movieSections, setSelectedMovie} = useMovies(); const showMovieInfo = useCallback( (movie: Movie) => { setSelectedMovie(movie); navigate(routes.MOVIE); }, [navigate, setSelectedMovie], ); return ( <View style={styles.container}> {/* A loading screen is shown for a few seconds to hide when the on-screen movie posters load from their remote sources. */} <Loading duration={3500} /> {/* Renders each horizontal section of movies. */} <FlatList data={movieSections} initialNumToRender={6} keyExtractor={section => section.category} renderItem={({item: section}) => ( <MovieList category={section.category} movies={section.movies} onItemPress={showMovieInfo} /> )} showsVerticalScrollIndicator={false} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, }, });
import React from 'react'; import ReactDOM from 'react-dom/client'; import Routes from './pages'; import { Provider } from 'react-redux'; import { persistor, store } from './core/store.ts'; import { ChakraProvider } from '@chakra-ui/react'; import { BrowserRouter } from 'react-router-dom'; import { PersistGate } from 'redux-persist/integration/react'; async function enableMocking() { if (import.meta.env.MODE !== 'mocked') { return; } const { worker } = await import('./mocks/browser'); // `worker.start()` returns a Promise that resolves // once the Service Worker is up and ready to intercept requests. return worker.start(); } enableMocking().then(() => { ReactDOM.createRoot(document.getElementById('root')!).render( <React.StrictMode> <Provider store={store}> <PersistGate loading={null} persistor={persistor}> <BrowserRouter> <ChakraProvider> <Routes /> </ChakraProvider> </BrowserRouter> </PersistGate> </Provider> </React.StrictMode> ); });
.. _CONCEPTS_CLASS_IMPLEMENTATION: The Implementation Basics of Classes Repititorium Class Creation --------------------------- Components of Classes ^^^^^^^^^^^^^^^^^^^^^ The classes are implemented as basic data structures containing data and references to functions to proceed the data. This basic concept is honed by various additional concepts for the actual implementation. In case of *Python* the most implementation details are part of the language definition. These are for example the magic functions and data members enclosed in double_underscores *__<member-data-or-function>__*. The most prominent disclosed implementation details for the class definition and creation are here the functions - or more approriate the methods - *__new__* and *__init*, and the data *__class__* and *__bases__*. The class fabric is which has created the class is either referenced by a special member *__metaclass__*, or could be evaluated dynamic by the call of the *type* function. The data members reflect the blueprint of the inheritance structure of the class design. While in static compiled languages the blueprint has to be defined before compileation and is by default not foreseen to be altered, *Python* provides by concept the dynamic creation of classes at runtime. In *Python* the classes are actually runtime instances, which serve as a dynamic instance fabric. The actual creation is performed by the so called *metaclass*, either the default *type*, or a custom class. Thus *Python* discloses the complete mechanism of class and data creation with standard callbacks for user defined procedures. Classes and Objects ^^^^^^^^^^^^^^^^^^^ The overall blueprint of the class definition, and the class and instance creation could be described in a model of three dimensions. #. Class-Hierarcy #. Type-Hierarchy #. Instance-Containment The Class-Hierarcy is defined by the abstraction model of the application. It describes the data and process flow. The type hierarcy provides the means to implement the Class-Hierarchy into real-world programs. In most programming languages these are hidden by the compiler and though not part of the programming paradigm, *Python* discloses this as a standard part of the programming language. .. _FIGURE_CLASSCONSTRUCTIONLAYERS: .. figure:: _static/class-and-objects.png :figwidth: 700 :align: center :target: _static/class-and-objects.png Figure: Class and Instance Elements |classandobjects_zoom| .. |classandobjects_zoom| image:: _static/zoom.png :alt: zoom :target: _static/class-and-objects.png :width: 16 The Instance-Containment represents the runtime data structure to be used to process the actual data and provides the workflow to the user. The cental role in this contex is defined by the methods described in the following sections. * *__init__* - for the standard development * *__new__* - for the advanced development Types of Classes and Objects ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The basic paradigma of *Python* is focused on the dynamic definition and creation of its entities. This comprises the blueprint and the implementation, while the most other programming languages focus on for the dynamic runtime environment on the implementation only. The *Python* runtime environment provides for the dynamic class creation as well as the dynamic instance creation. Thus the classes theirselves are runtime instances. The basic categories of runtime entities are type instances and object instances. Where the types are the fabrics for instances of type *object*. The instances of type *object* provide the basic hooks of the instance items into the the runtime framework of the *Python* implementation. The actual implementation of *Python* has varied by different object types due to different implementation concepts and frameworks. This was finalized in the so called *new object* type, which also supports a specific runtime method resolution order - *MRO*. This is in particular established as the so called *C3 linearization* [C3LIN]_. Resulting in the standard items: * *type* - as the common fabric for classes and and their instances * *object* - as the top level class, providing the integration of application instances into the runtime framework Refer to the *Python* documentation for further details [PYLANG]_. Call Flow of Class Creation --------------------------- The essential criteria for the parameter design of the dynamic named tuple extension is the call flow of instance and though the custom class construction. The basic class construction in Python comprises 3 layers of classes and objects. The metaclass is only involved in the class construction, while the instanciation of the classes are worked out by their defined inheritance hierarchy. The inheritance hierarchy serves also for the runtime resolution of method calls e.g. by the "*C3 linearization*" [C3LIN]_ - which is applied for the new *object* types. This section provides yet another short overview as a reminder with some conrete example flows as required for the design of the classes :ref:`RETURN_NamedTupleXABC` and :ref:`RETURN_NamedTupleXABCMeta`. For a detailed overview refer to [customclass]_. For a detailed article see "Understanding Python metaclasses" [IONELPYMETA]_. Single Inheritance ^^^^^^^^^^^^^^^^^^ The basic process flow is pretty straight forward in case of single inheritance. .. _FIGURE_CLASSCONSTRUCTIONLAYERSSINGLE: .. figure:: _static/class-construction-layers.png :figwidth: 500 :align: center :target: _static/class-construction-layers.png Figure: Class Construction Layers |classconstructionlayers_zoom| .. |classconstructionlayers_zoom| image:: _static/zoom.png :alt: zoom :target: _static/class-construction-layers.png :width: 16 **Source** The following example code demonstrates the draft class structure with all *__new__* and *__init__* methods present. :: from __future__ import print_function import abc print("0------------------------------") print() class NamedTupleXABCMeta(abc.ABCMeta): def __new__(cls, *args, **kargs): print("NamedTupleXABCMeta :new :" + str(cls) + " " + str(args) + " " + str(kargs)) return super(NamedTupleXABCMeta, cls).__new__(cls, *args, **kargs) def __init__(self, *args, **kargs): print("NamedTupleXABCMeta :init :" + str(self) + " " + str(args) + " " + str(kargs)) return super(NamedTupleXABCMeta, self).__init__(*args, **kargs) class NamedTupleXABC(object): __metaclass__ = NamedTupleXABCMeta def __new__(cls, *args, **kargs): print("NamedTupleXABC :new :" + str(cls) + " " + str(args) + " " + str(kargs)) return super(NamedTupleXABC, cls).__new__(cls, *args, **kargs) def __init__(self, *args, **kargs): print("NamedTupleXABC :init :" + str(self) + " " + str(args) + " " + str(kargs)) return super(NamedTupleXABC, self).__init__(*args, **kargs) class AppTupleClass(NamedTupleXABC): _fields = ('a',) def __new__(cls, *args, **kargs): print("AppTupleClass :new :" + str(cls) + " " + str(args) + " " + str(kargs)) return super(AppTupleClass, cls).__new__(cls, *args, **kargs) def __init__(self, *args, **kargs): print("AppTupleClass :init :" + str(self) + " " + str(args) + " " + str(kargs)) return super(AppTupleClass, self).__init__(*args, **kargs) print() print("1------------------------------") print() a = AppTupleClass() print() print("OK") **Result** Results in the output: .. parsed-literal:: 0------------------------------ NamedTupleXABCMeta :new :<class '__main__.NamedTupleXABCMeta'> ('NamedTupleXABC', ... # class creation parameters NamedTupleXABCMeta :init :<class '__main__.NamedTupleXABC'> ('NamedTupleXABC', ... NamedTupleXABCMeta :new :<class '__main__.NamedTupleXABCMeta'> ('AppTupleClass', ... NamedTupleXABCMeta :init :<class '__main__.AppTupleClass'> ('AppTupleClass', ... 1------------------------------ AppTupleClass :new :<class '__main__.AppTupleClass'> () {} # instance creation parameters NamedTupleXABC :new :<class '__main__.AppTupleClass'> () {} AppTupleClass :init :<__main__.AppTupleClass object at 0x7f99d6daf6d0> () {} NamedTupleXABC :init :<__main__.AppTupleClass object at 0x7f99d6daf6d0> () {} OK **Discussion** With the call flow: 0. Create global class definitions as objects by themselfs. These are each created and initialized completeley, because of the order each is completely defined by itself and the eventually required previous already created classes. 1. NamedTupleXABC: 1. Create - __new__ 2. Initialize - __init__ 2. AppTupleClass: 1. Create - __new__ 2. Initialize - __init__ 1. Create instances/objects. Each instance is created completely by walking through the upward hierarchy in the inheritance hierarchy. Resulting in combined creation following combined initialization. 1. Create - new 1. AppTupleClass 2. NamedTupleXABC 2. Initialize - __init__ 1. AppTupleClass 2. NamedTupleXABC As depicted, a metaclass itself is not created here by the applications metaclass but provided by the systems *type*. The application defined metaclasses serve as the class factory and create and initialize all assigned classes by calling *__new__* and *__init__*. Here *AppTupleClass* and *NamedTupleXABC*. The instance creation is performed along the inheritance hierarchy starting at the derived class. The applications abstract metaclasses are not involved in the instance creation calls. The call hierarchy is first processed for the creation, second for the initialization. For the application by *namedtuplex* refer to :ref:`Creation of the Named Tuple <CREATIONOFTHENAMEDTUPLE>`. Multiple Inheritance - Mixin ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The process flow changes when an instance of a named tuple class is taken into account. The additional named tuple class in the actual implementation is hereby created by the factory defined by :ref:`param_tuplefactory`. The created *namedtuple* class is the first in the list of base classes *__bases__*, thus called by default by the *super* method. The abstract class is the second in the list and is not requied to be called after instanciation anyhow. .. _FIGURE_CLASSCONSTRUCTIONLAYERSMIXIN: .. figure:: _static/class-construction-layers-namedtuple.png :figwidth: 650 :align: center :target: _static/class-construction-layers-namedtuple.png Figure: Class Construction Layers with Mixin |classconstructionlayersnamedtuple_zoom| .. |classconstructionlayersnamedtuple_zoom| image:: _static/zoom.png :alt: zoom :target: _static/class-construction-layers-namedtuple.png :width: 16 **Source** The following example code demonstrates the draft class structure with all *__new__* and *__init__* methods present. :: from __future__ import print_function import abc import namedtupledefs print("0------------------------------") print() _MyTuple = namedtupledefs.namedtuple('MyTuple', 'x y z', fielddefaults=(22,33)) class MyTuple(_MyTuple): def __new__(cls, *args, **kargs): print("MyTuple :new :" + str(cls) + " " + str(args) + " " + str(kargs)) return super(MyTuple, cls).__new__(cls, *args, **kargs) def __init__(self, *args, **kargs): print("MyTuple :init :" + str(self) + " " + str(args) + " " + str(kargs)) return super(MyTuple, self).__init__(*args, **kargs) class NamedTupleXABCMeta(abc.ABCMeta): def __new__(cls, *args, **kargs): print("NamedTupleXABCMeta :new :" + str(cls) + " " + str(args) + " " + str(kargs)) return super(NamedTupleXABCMeta, cls).__new__(cls, *args, **kargs) def __init__(self, *args, **kargs): print("NamedTupleXABCMeta :init :" + str(self) + " " + str(args) + " " + str(kargs)) return super(NamedTupleXABCMeta, self).__init__(*args, **kargs) class NamedTupleXABC(object): __metaclass__ = NamedTupleXABCMeta def __new__(cls, *args, **kargs): print("NamedTupleXABC :new :" + str(cls) + " " + str(args) + " " + str(kargs)) return super(NamedTupleXABC, cls).__new__(cls, *args, **kargs) def __init__(self, cls, *args, **kargs): print("NamedTupleXABC :init :" + str(self) + " " + str(args) + " " + str(kargs)) # the abc.ABC passes __init__ to type() return super(NamedTupleXABC, self).__init__() class AppTupleClass(MyTuple, NamedTupleXABC): # # The mixin is actually created by the metaclass, here defined static for demonstration # _fields = ('a',) def __new__(cls, *args, **kargs): print("AppTupleClass :new :" + str(cls) + " " + str(args) + " " + str(kargs)) return super(AppTupleClass, cls).__new__(cls, *args, **kargs) def __init__(self, *args, **kargs): print("AppTupleClass :init :" + str(self) + " " + str(args) + " " + str(kargs)) return super(AppTupleClass, self).__init__(*args, **kargs) print() print("1------------------------------") print() a = AppTupleClass(11, 22) # uses default for 'z' print() print(a) print("OK") **Result** Results in the output: .. parsed-literal:: warning: Debugger speedups using cython not found. Run '"/home/acue/venv/2.7.14/bin/python2.7" "/local/hd1/home1/env/ide/eclipse/eclipse-cpp-neon-3-linux-gtk-x86_64-20171019-devops_18/dropins/PyDev 7.0.3/plugins/org.python.pydev.core_7.0.3.201811082356/pysrc/setup_cython.py" build_ext --inplace' to build. pydev debugger: starting (pid: 2857) 0------------------------------ NamedTupleXABCMeta :new :<class '__main__.NamedTupleXABCMeta'> ('NamedTupleXABC', (<type 'object'>,), {'__module__': '__main__', '__metaclass__': <class '__main__.NamedTupleXABCMeta'>, '__new__': <function __new__ at 0x7f5e2c1bee60>, '__init__': <function __init__ at 0x7f5e2c1beed8>}) {} NamedTupleXABCMeta :init :<class '__main__.NamedTupleXABC'> ('NamedTupleXABC', (<type 'object'>,), {'__module__': '__main__', '__metaclass__': <class '__main__.NamedTupleXABCMeta'>, '__new__': <function __new__ at 0x7f5e2c1bee60>, '__init__': <function __init__ at 0x7f5e2c1beed8>}) {} NamedTupleXABCMeta :new :<class '__main__.NamedTupleXABCMeta'> ('AppTupleClass', (<class '__main__.MyTuple'>, <class '__main__.NamedTupleXABC'>), {'__module__': '__main__', '_fields': ('a',), '__new__': <function __new__ at 0x7f5e2a742230>, '__init__': <function __init__ at 0x7f5e2a7422a8>}) {} NamedTupleXABCMeta :init :<class '__main__.AppTupleClass'> ('AppTupleClass', (<class '__main__.MyTuple'>, <class '__main__.NamedTupleXABC'>), {'__module__': '__main__', '_fields': ('a',), '__new__': <function __new__ at 0x7f5e2a742230>, '__init__': <function __init__ at 0x7f5e2a7422a8>}) {} 1------------------------------ AppTupleClass :new :<class '__main__.AppTupleClass'> (11, 22) {} MyTuple :new :<class '__main__.AppTupleClass'> (11, 22) {} AppTupleClass :init :MyTuple(x=11, y=22, z=33) (11, 22) {} MyTuple :init :MyTuple(x=11, y=22, z=33) (11, 22) {} NamedTupleXABC :init :MyTuple(x=11, y=22, z=33) (22,) {} MyTuple(x=11, y=22, z=33) OK **Discussion** With the call flow: 0. Create global class definitions as objects by themselfs. These are each created and initialized completeley, because of the order each is completely defined by itself and the eventually required previous already created classes. 1. NamedTupleXABC: 1. Create - __new__ 2. Initialize - __init__ 2. AppTupleClass: 1. Create - __new__ 2. Initialize - __init__ 1. Create instances/objects. Each instance is created completely by walking through the upward hierarchy in the inheritance hierarchy. Resulting in combined creation following combined initialization. 1. Create - new 1. AppTupleClass 2. NamedTupleXABC 2. Initialize - __init__ 1. AppTupleClass 2. NamedTupleXABC As depicted, a metaclass itself is not created here by the applications metaclass but provided by the systems *type*. The application defined metaclasses serve as the class factory and create and initialize all assigned classes by calling *__new__* and *__init__*. Here *AppTupleClass* and *NamedTupleXABC*. The instance creation is performed along the inheritance hierarchy starting at the derived class. The applications abstract metaclasses are not involved in the instance creation calls. The call hierarchy is first processed for the creation, second for the initialization. For the application by *namedtuplex* refer to :ref:`Creation of the Named Tuple <CREATIONOFTHENAMEDTUPLE>`. The Structure of *namedtuplex* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ **Source** The following example code displays the structure as actually defined by *namedtuplex*. The implemented demonstration method stubs are at the same positions as the originals. The only adaptation is the callwrapper for the tuple class *MyTuple* of the demonstrator. Thus the callflow traces are the same. :: from __future__ import print_function import abc import namedtupledefs print("0------------------------------") print() _MyTuple = namedtupledefs.namedtuple('MyTuple', 'x y z', fielddefaults=(22,33)) class MyTuple(_MyTuple): def __new__(cls, *args, **kargs): print("MyTuple :new :" + str(cls) + " " + str(args) + " " + str(kargs)) return super(MyTuple, cls).__new__(cls, *args, **kargs) def __init__(self, *args, **kargs): print("MyTuple :init :" + str(self) + " " + str(args) + " " + str(kargs)) return super(MyTuple, self).__init__(*args, **kargs) class NamedTupleXABCMeta(abc.ABCMeta): def __new__(cls, *args, **kargs): print("NamedTupleXABCMeta :new :" + str(cls) + " " + str(args) + " " + str(kargs)) return super(NamedTupleXABCMeta, cls).__new__(cls, *args, **kargs) def __init__(self, *args, **kargs): print("NamedTupleXABCMeta :init :" + str(self) + " " + str(args) + " " + str(kargs)) return super(NamedTupleXABCMeta, self).__init__(*args, **kargs) class NamedTupleXABC(object): __metaclass__ = NamedTupleXABCMeta _fields = abc.abstractproperty() class AppTupleClass(MyTuple, NamedTupleXABC): # **The mixin is actually created by the metaclass, here defined static for demonstration** _fields = ('a',) def __new__(cls, *args, **kargs): print("AppTupleClass :new :" + str(cls) + " " + str(args) + " " + str(kargs)) return super(AppTupleClass, cls).__new__(cls, *args, **kargs) def __init__(self, *args, **kargs): print("AppTupleClass :init :" + str(self) + " " + str(args) + " " + str(kargs)) return super(AppTupleClass, self).__init__(*args, **kargs) print() print("1------------------------------") print() a = AppTupleClass(11, 22) # uses default for 'z' print() print(a) print("OK") **Result** Results in the output: .. parsed-literal:: 0------------------------------ NamedTupleXABCMeta :new :<class '__main__.NamedTupleXABCMeta'> ('NamedTupleXABC', (<type 'object'>,), {'__module__': '__main__', '__metaclass__': <class '__main__.NamedTupleXABCMeta'>}) {} NamedTupleXABCMeta :init :<class '__main__.NamedTupleXABC'> ('NamedTupleXABC', (<type 'object'>,), {'__module__': '__main__', '__metaclass__': <class '__main__.NamedTupleXABCMeta'>}) {} NamedTupleXABCMeta :new :<class '__main__.NamedTupleXABCMeta'> ('AppTupleClass', (<class '__main__.MyTuple'>, <class '__main__.NamedTupleXABC'>), {'__module__': '__main__', '_fields': ('a',), '__new__': <function __new__ at 0x7f2f5617c050>, '__init__': <function __init__ at 0x7f2f5617c140>}) {} NamedTupleXABCMeta :init :<class '__main__.AppTupleClass'> ('AppTupleClass', (<class '__main__.MyTuple'>, <class '__main__.NamedTupleXABC'>), {'__module__': '__main__', '_fields': ('a',), '__new__': <function __new__ at 0x7f2f5617c050>, '__init__': <function __init__ at 0x7f2f5617c140>}) {} 1------------------------------ AppTupleClass :new :<class '__main__.AppTupleClass'> (11, 22) {} MyTuple :new :<class '__main__.AppTupleClass'> (11, 22) {} AppTupleClass :init :MyTuple(x=11, y=22, z=33) (11, 22) {} MyTuple :init :MyTuple(x=11, y=22, z=33) (11, 22) {} MyTuple(x=11, y=22, z=33) OK **Discussion** The call flow is the same as before, while the new call of the application class *AppTupleClass* is eventually present in rare cases only. The call flow once again: 0. Create global class definitions as objects by themselfs. These are each created and initialized completeley, because of the order each is completely defined by itself and the eventually required previous already created classes. 1. NamedTupleXABC: 1. Create - __new__ 2. Initialize - __init__ 2. AppTupleClass: 1. Create - __new__ 2. Initialize - __init__ 1. Create instances/objects. Each instance is created completely by walking through the upward hierarchy in the inheritance hierarchy. Resulting in combined creation following combined initialization. 1. Create - new 1. AppTupleClass 2. NamedTupleXABC 2. Initialize - __init__ 1. AppTupleClass 2. NamedTupleXABC For the application by *namedtuplex* refer to :ref:`Creation of the Named Tuple <CREATIONOFTHENAMEDTUPLE>`.
package _04 import ( "testing" ) func Test_maxDepth(t *testing.T) { tests := []struct { name string root *TreeNode want int }{ { name: "Example 1", root: &TreeNode{ Val: 22, Left: nil, Right: nil, }, want: 1, }, { name: "Example 2", root: &TreeNode{ Val: 1, Left: &TreeNode{ Val: 3, Left: &TreeNode{ Val: 5, Left: nil, Right: nil, }, Right: nil, }, Right: &TreeNode{ Val: 3, Left: nil, Right: nil, }, }, want: 3, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := maxDepth(tt.root); got != tt.want { t.Errorf("maxDepth() = %v, want %v", got, tt.want) } }) } }
package open.api.coc.clans.domain.common.converter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import lombok.RequiredArgsConstructor; import open.api.coc.clans.database.entity.player.PlayerHeroEntity; import open.api.coc.clans.domain.common.HeroEquipmentResponse; import open.api.coc.clans.domain.common.HeroResponse; import open.api.coc.external.coc.clan.domain.common.Hero; import open.api.coc.external.coc.clan.domain.common.HeroEquipment; import open.api.coc.external.coc.config.HeroConfig; import org.springframework.core.convert.converter.Converter; import org.springframework.lang.NonNull; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; @Component @RequiredArgsConstructor public class HeroResponseConverter implements Converter<Hero, HeroResponse> { private final HeroEquipmentResponseConverter heroEquipmentResponseConverter; @Override public HeroResponse convert(Hero source) { HeroConfig hero = getHeroConfig(source.getName()); return HeroResponse.builder() .code(hero.getCode()) .name(source.getName()) .koreanName(hero.getKoreanName()) .village(source.getVillage()) .level(source.getLevel()) .maxLevel(source.getMaxLevel()) .equipments(makeEquipments(source.getEquipment())) .build(); } private List<HeroEquipmentResponse> makeEquipments(List<HeroEquipment> equipments) { if (CollectionUtils.isEmpty(equipments)) { return Collections.emptyList(); } return equipments.stream() .map(heroEquipmentResponseConverter::convert) .collect(Collectors.toList()); } private HeroConfig getHeroConfig(String name) { try { return HeroConfig.findByName(name); } catch (Exception ignored) { return HeroConfig.UNKNOWN; } } public @NonNull HeroResponse convert(PlayerHeroEntity source) { HeroConfig hero = getHeroConfig(source.getId().getName()); return HeroResponse.builder() .code(hero.getCode()) .name(source.getId().getName()) .koreanName(hero.getKoreanName()) .village("home") .level(source.getLevelInfo().getLevel()) .maxLevel(source.getLevelInfo().getMaxLevel()) .equipments(new ArrayList<>()) .build(); } }
// Closest to the Right (https://codeforces.com/edu/course/2/lesson/6/1/practice/contest/283911/problem/C) #include <iostream> #include <vector> using namespace std; // Time: O(logN) // Space: O(1) int upper_bound_2(vector<int>& A, int K) { int N = A.size(); int l = 0, h = N-1; while (h-l > 1) { int m = (h-l)/2 + l; if (A[m] >= K) h = m; else l = m+1; // A[m] < K } if (A[l] >= K) return l+1; else if (A[h] >= K) return h+1; else return N+1; } int upper_bound(vector<int>& A, int K) { int N = A.size(); int l = 0, h = N-1; while (l <= h) { int m = (h-l)/2 + l; if (A[m] >= K) h = m-1; else l = m+1; // A[m] < K } return l+1; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int N, Q; cin >> N >> Q; vector<int> A(N); for (int i = 0; i < N; i++) cin >> A[i]; vector<int> res; int q; for (int i = 0; i < Q; i++) { cin >> q; res.push_back(upper_bound(A, q)); } for (int r : res) cout << r << endl; return 0; }
import { useState, useEffect } from "react"; import Image from "next/image"; import Link from "next/link"; import { usePathname } from "next/navigation"; import Logo from "@/images/suitmedia-logo-fix.png"; export default function Header() { const [show, setShow] = useState(true); const [lastScrollY, setLastScrollY] = useState(0); const controlHeader = () => { if (typeof window !== "undefined") { if (window.scrollY > lastScrollY) { setShow(false); } else { setShow(true); } setLastScrollY(window.scrollY); } }; useEffect(() => { if (typeof window !== "undefined") { window.addEventListener("scroll", controlHeader); return () => { window.removeEventListener("scroll", controlHeader); }; } }, [lastScrollY]); const pathname = usePathname(); return ( <header className={`fixed top-0 left-0 w-full shadow transition-transform bg-[#eb6125] duration-200 z-50 ${ show ? "translate-y-0" : "-translate-y-full" }`} > <div className="flex p-2 items-center"> <div className="container mx-auto text-white"> <Image src={Logo} alt="Logo" width={180} height={180} className="lg:ml-12 md:ml-2" ></Image> </div> <div> <ul className="flex flex-row lg:space-x-2 lg:mr-12 font-base md:mr-4 lg:text-base mt-1 md:text-sm"> <li className={`text-white hover:text-orange-300 cursor-pointer px-2 pb-2 ${pathname === "/" ? "fix-underline" : "link-underline"}`}> <Link href="/">Home</Link> </li> <li className={`text-white hover:text-orange-300 cursor-pointer px-2 pb-2 ${pathname === "/work" ? "fix-underline" : "link-underline"}`}> <Link href="/work">Work</Link> </li> <li className={`text-white hover:text-orange-300 cursor-pointer px-2 pb-2 ${pathname === "/about" ? "fix-underline" : "link-underline"}`}> <Link href="/about">About</Link> </li> <li className={`text-white hover:text-orange-300 cursor-pointer px-2 pb-2 ${pathname === "/services" ? "fix-underline" : "link-underline"}`}> <Link href="/services">Services</Link> </li> <li className={`text-white hover:text-orange-300 cursor-pointer px-2 pb-2 ${pathname === "/ideas" ? "fix-underline" : "link-underline"}`}> <Link href="/ideas">Ideas</Link> </li> <li className={`text-white hover:text-orange-300 cursor-pointer px-2 pb-2 ${pathname === "/careers" ? "fix-underline" : "link-underline"}`}> <Link href="/careers">Careers</Link> </li> </ul> </div> </div> <style jsx>{` .link-underline, .fix-underline { border-bottom-width: 0; background-image: linear-gradient(transparent, transparent), linear-gradient(#fff, #fff); background-size: 0 4px; background-position: 0 100%; background-repeat: no-repeat; transition: background-size 0.3s ease-in-out; } .link-underline:hover { background-size: 100% 4px; background-position: 0 100%; } .fix-underline { background-size: 100% 4px; background-position: 0 100%; } `}</style> </header> ); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>animation封装</title> <style> .moveBox { width: 100px; height: 100px; background-color: aliceblue; text-align: center; line-height: 100px; position: absolute; } </style> </head> <body> <div class='moveBox'>box</div> <script> window.addEventListener('load', function() { var moveBox = document.querySelector('.moveBox'); slowAnimation(moveBox, 400); }); // 匀速动画 function animation(moveEle, targetDistance) { clearInterval(moveEle.timer); moveEle.timer = setInterval(function () { var offLeft = moveEle.offsetLeft; if (offLeft >= targetDistance) { clearInterval(moveEle.timer); } moveEle.style.left = offLeft + 2 + 'px'; }, 30); } // 缓动动画 function slowAnimation(moveEle, targetDistance) { clearInterval(moveEle.timer); moveEle.timer = setInterval(function () { var offLeft = moveEle.offsetLeft; var step = (targetDistance - offLeft) / 10; step = step > 0 ? Math.ceil(step) : Math.floor(step); if (offLeft >= targetDistance) { clearInterval(moveEle.timer); } moveEle.style.left = offLeft + step + 'px'; }, 15); } </script> </body> </html>
package simple; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; public class SimpleClient { /** * @param args */ public static void main(String[] args) { // verifica correttezza dei parametri if (args.length != 1 && args.length != 2) { System.out.println("Usage: java -jar SimpleClient.jar server [\"message to send\"]"); return; } try { // preparazione dell'indirizzo del server InetAddress address = InetAddress.getByName(args[0]); // creazione socket Socket client = new Socket(address, 12345); System.out.println("Client ready.\n"); BufferedReader in; in = new BufferedReader(new InputStreamReader(client.getInputStream())); // creazione buffer di scrittura PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true); if (args.length == 2) { System.out.println("Buffer ready, sending message \"" + args[1] + "\"...\n"); // scrittura del messaggio (passato come parametro) nel buffer in uscita out.println(args[1]); System.out.println("Message sent.\n"); } else { String msg = null; BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); while (msg == null || !msg.startsWith(":q!")) { System.out.println("Buffer ready, write the message you want to send (\":q!\" to quit): "); msg = console.readLine(); // scrittura del messaggio nel buffer in uscita out.println(msg); System.out.println("Message sent.\n"); String answer = in.readLine(); System.out.println("answer is: '" + answer + "'"); } } // chiusura socket client.close(); } catch (Exception e) { e.printStackTrace(); } } }
<!DOCTYPE html> <html lang="es" xmlns:th="http://www.thymeleaf.org"> <head th:replace="fragments/componentes/plantilla :: head"></head> <body class="horizontal-layout horizontal-menu 2-columns " data-open="hover" data-menu="horizontal-menu" data-col="2-columns"> <nav th:replace="fragments/componentes/plantilla :: header"></nav> <div th:replace="fragments/componentes/plantilla :: menu"></div> <div class="app-content content"> <div class="content-overlay"></div> <div class="content-wrapper"> <div class="content-header row"> <div class="content-header-left col-md-6 col-12 mb-2"> <h3 class="content-header-title" th:text="#{text.usuario.form.h3.gestionUsuarios}"></h3> <div class="row breadcrumbs-top"> <div class="breadcrumb-wrapper col-12"> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a th:href="@{/dashboard}"> <span th:text="#{text.tittle.home}"></span> </a> </li> <li class="breadcrumb-item active" th:text="#{text.usuario.form.li.Usuarios}"></li> </ol> </div> </div> </div> </div> <div class="content-body"> <section id="pagination"> <div class="row"> <div class="col-12"> <div class="card"> <div th:if="${success != null}" class="alert alert-info" role="alert"> <strong>¡Ok!</strong> <span th:text="${success}"></span> </div> <div class="card-header"> <h4 class="card-title float-left" th:text="#{text.usuario.list.h4.listaUsuarios}"></h4> <div class="media width-250 float-right"> <div class="media-body media-right text-right"> <a th:href="@{/usuario/formulario}" class="btn btn-primary"> <i class="la la-plus"></i> <span th:text="#{text.usuario.list.span.crearUsuario}"></span> </a> <a th:href="@{${url}(excel='true',format='xlsx')}" class="m-2" onclick="deshabilitar(this)"> <i class="la la-download"></i>xlsx </a> <div id="cargarXls" style="display: none;" class="spinner-border text-danger" role="status"> <span class="sr-only">Loading...</span> </div> </div> </div> </div> <div class="card-body"> <div class="card-text"> <form th:action="@{/usuario/listado}" th:object="${buscador}"> <div class="row mb-2"> <div class="col-12 col-md-6 col-lg-4 mb-2"> <label class="font-weight-bold" for="rol" th:text="#{text.usuario.list.filtro.rol}"></label> <select id="rol" class="form-control" th:field="*{rol}"> <option selected value="" th:text="#{text.usuario.list.filtro.select-rol}"></option> <option th:each="role : ${roles}" th:value="${role.texto}" th:text="${role.texto=='TRANSPORTADORA'?'TRANSPORTADOR':role.texto}"></option> </select> </div> <div class="col-12 col-md-6 col-lg-4 mb-2"> <label class="font-weight-bold" for="fecha-inicio" th:text="#{text.usuario.list.filtro.fecha-inicio}"></label> <input id="fecha-inicio" type="date" class="form-control square" th:max="${#dates.format(#dates.createNow(),'yyyy-MM-dd')}" th:field="*{fechaInicio}"/> </div> <div class="col-12 col-md-6 col-lg-4 mb-2"> <label class="font-weight-bold" for="fecha-finalizacion" th:text="#{text.usuario.list.filtro.fecha-finalizacion}"></label> <input id="fecha-finalizacion" type="date" class="form-control square" th:max="${#dates.format(#dates.createNow(),'yyyy-MM-dd')}" th:field="*{fechaFinalizacion}"/> </div> <div class="col-12 col-md-6 col-lg-4 mb-2"> <label class="font-weight-bold" for="pais" th:text="#{text.usuario.list.filtro.pais}"></label> <select id="pais" class="form-control" th:field="*{idPais}"> <option selected value="" th:text="#{text.usuario.list.filtro.select-pais}"></option> <option th:each="pais : ${paises}" th:value="${pais.id}" th:text="${pais.nombre}"></option> </select> </div> <div class="col-12 col-md-6 col-lg-4 mb-2"> <label class="font-weight-bold" for="otro" th:text="#{text.usuario.list.filtro.otro}"></label> <input id="otro" type="text" class="form-control square" th:placeholder="#{text.usuario.list.filtro.buscar}" th:field="*{otro}"/> </div> <div class="col-12 col-md-6 col-lg-4 mt-2 mb-2 mb-lg-0 text-right" > <button type="submit" name="search" id="search-btn" class="btn btn-success" > <i class="la la-search"></i> </button> <a type="button" class="btn btn-danger text-white" th:href="@{/usuario/listado}" th:text="#{text.usuario.list.filtro.limpiarFiltros}"></a> </div> </div> </form> </div> <div class="table-responsive"> <table class="table alt-pagination"> <thead class="thead-dark"> <tr> <th th:replace="fragments/componentes/paginador :: columna-no-q(campo='telefono',columna='__#{text.usuario.list.th.telefono}__')"></th> <th th:replace="fragments/componentes/paginador :: columna-no-q(campo='nombre',columna='__#{text.usuario.list.th.nombre}__')"></th> <th th:replace="fragments/componentes/paginador :: columna-no-q(campo='mail',columna='__#{text.usuario.list.th.email}__')"></th> <th th:replace="fragments/componentes/paginador :: columna-no-q(campo='pais.nombre',columna='__#{text.usuario.list.th.pais}__')"></th> <th th:replace="fragments/componentes/paginador :: columna-no-q(campo='cuit',columna='__#{text.usuario.list.th.cuilCuit}__')"></th> <th th:replace="fragments/componentes/paginador :: columna-no-q(campo='rol',columna='__#{text.usuario.list.th.rol}__')"></th> <th th:replace="fragments/componentes/paginador :: columna-no-q(campo='modificacion',columna='__#{text.usuario.list.th.modificacion}__')"></th> <th>Acciones</th> </tr> </thead> <tbody> <tr th:each="entidad : ${page}"> <td class="align-left"> <div class="name" th:text="${entidad.telefono}"></div> </td> <td class="align-left"> <div class="name" th:text="${entidad.nombre}"></div> </td> <td class="align-left"> <div class="name" th:text="${entidad.mail}"></div> </td> <td class="align-left"> <div class="name" th:text="${entidad.nombrePais}"></div> </td> <td class="align-left"> <div class="name" th:text="${entidad.cuit}"></div> </td> <td class="align-middle"> <div class="last-login"> <span class="badge badge-info" th:text="${entidad.rol}"></span> </div> </td> <td class="align-middle"> <div class="last-login" th:text="${entidad.modificacion} ? ${#dates.format(entidad.modificacion, 'dd/MM/yyyy HH:mm')}"></div> </td> <td class="align-middle"> <div class="option" style="display: flex; justify-content: space-between;"> <a th:if="${session.usuario.rol.toString() != 'INVITADO'}" th:href="@{/usuario/formulario(accion=actualizar,id=__${entidad.id}__)}" th:title="#{text.tittle.editar}"> <i class="la la-pencil success"></i> </a> <a th:if="${session.usuario.rol.toString() != 'INVITADO'}" th:href="@{/usuario/formulario(accion=eliminar,id=__${entidad.id}__)}" th:title="#{text.tittle.eliminar}"> <i class="la la-trash danger"></i> </a> </div> </td> </tr> </tbody> </table> <div th:replace="fragments/componentes/paginador :: paginador-no-q"></div> </div> </div> </div> </div> </div> </section> </div> </div> </div> <div class="sidenav-overlay"></div> <div class="drag-target"></div> <th:block th:replace="fragments/componentes/plantilla :: footer"></th:block> <script th:inline="javascript"> $("#pais").select2(); $("#rol").select2(); </script> <!--DESHABILITAR LINK DE DOCUMENTO xls cuando se hace click--> <script> deshabilitar = (element) => { element.style.pointerEvents = 'none'; element.style.color = '#bbb'; $("#cargarXls").show(); setTimeout(() => { element.style.pointerEvents = null; element.style.color = 'blue'; $("#cargarXls").hide(); }, 2000); }; </script> </body> </html>
#include "main.h" #include <stdlib.h> #include <string.h> /** * _strdup - point to a newly allocated memory which points at a copy of string * @str: input string *Return: pointer to the memory */ char *_strdup(char *str) { int i; char *ptr; int size; if (str == NULL) return (NULL); size = strlen(str); ptr = malloc(sizeof(char) * size + 1); if (ptr == NULL) return (NULL); for (i = 0; i < size; i++) { ptr[i] = str[i]; } return (ptr); }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jbouyer <jbouyer@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2022/11/21 14:14:19 by jbouyer #+# #+# */ /* Updated: 2022/11/22 14:56:01 by jbouyer ### ########.fr */ /* */ /* ************************************************************************** */ #include <iostream> #include "Whatever.hpp" // int main( void ) // { // int a = 2; // int b = 3; // ::swap( a, b ); // a = 2; // std::cout << "a = " << a << ", b = " << b << std::endl; // std::cout << "min( a, b ) = " << ::min( a, b ) << std::endl; // std::cout << "max( a, b ) = " << ::max( a, b ) << std::endl; // std::string c = "chaine1"; // std::string d = "chaine2"; // std::cout << "c = " << c << ", d = " << d << std::endl; // ::swap(c, d); // std::cout << "c = " << c << ", d = " << d << std::endl; // std::cout << "min( c, d ) = " << ::min( c, d ) << std::endl; // std::cout << "max( c, d ) = " << ::max( c, d ) << std::endl; // return 0; // } class Awesome { public: Awesome(void):_n(0){} Awesome(int n):_n(n){} Awesome & operator=(Awesome &a){_n=a._n;return *this;} bool operator==(Awesome const &rhs) const {return(this->_n==rhs._n);} bool operator!=(Awesome const &rhs) const{return(this->_n!=rhs._n);} bool operator<(Awesome const &rhs) const{return(this->_n<rhs._n);} bool operator>(Awesome const &rhs) const{return(this->_n>rhs._n);} bool operator>=(Awesome const &rhs) const{return(this->_n>=rhs._n);} bool operator<=(Awesome const &rhs) const{return(this->_n<=rhs._n);} int get_n() const {return _n;} private: int _n; }; std::ostream & operator<<(std::ostream & o, const Awesome &a){o<<a.get_n();return o;} int main() { Awesome a(2), b(4); swap(a,b); std::cout<<a<<" "<<b<<std::endl; std::cout<<max(a,b)<<std::endl; std::cout<<min(a,b)<<std::endl; return(0); }
<!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/stilos.css"> <title>Estruc Selectiva Sim Dob</title> </head> <body> <header> <h1>ESTRUCTURA SELECTIVA SIMPLE DOBLE</h1> <h2 class="centrado">Problema N° 22</h2> </header> <main> <form action=""> <table> <tr> <th class="col_izq">Variables</th> <th class="col_der">Valores</th> </tr> <!-- Entrada de Datos por teclado --> <tr> <td class="col_izq"><label for="txtmc">Monto de la compra: </label></td> <td class="col_der"><input type="text" name="txtmc" id="txtmc" value=""></td> </tr> <tr> <td class="col_izq"><label for="txttc">Tipo Cliente: </label></td> <td class="col_der"> <select name="txttc" id="txttc"> <option value="G">Cliente General </option> <option value="A">Cliente Afiliado </option> </select> </td> </tr> <tr> <td class="col_izq"><label for="txtfp">Forma de Pago</label></td> <td class="col_der"> <select name="txtfp" id="txtfp"> <option value="C">Al Contado </option> <option value="P">A Plazos </option> </select> </td> </tr> <!-- Salida de Datos por Pantalla --> <tr> <td class="col_izq"><label for="txtr">Tasa Descuento/Recargo: </label></td> <td class="col_der"><input type="text" name="txtr" id="txtr" value="" readonly></td> </tr> <tr> <td class="col_izq"><label for="txm">Monto de descuento/recargo: </label></td> <td class="col_der"><input type="text" name="txtm" id="txtm" value="" readonly></td> </tr> <tr> <td class="col_izq"><label for="txtp">Total a pagar: </label></td> <td class="col_der"><input type="text" name="txttp" id="txttp" value="" readonly></td> </tr> <tr> <td class="col_izq"></td> <td class="col_der"><button type="button" onclick="calcular()">Calcular</button></td> </tr> </table> </form> </main> <footer> <p>Todos los derechos reservados &copy;2022 Ing. Walter Vásquez Piña</p> </footer> <script> function calcular() { //Constantes const DESC_G = 0.15; const DESC_A = 0.2; const REC_G = 0.11; const REC_A = 0.05; //Variables let mc = 0; //Monto de la compra let tc = ""; //Tipo de cliente let fp = ""; //Forma de pago let r = ""; //Tasa Descuento/Recargo let m = 0; //Monto de descuento/recargo let tp = 0; //Total a pagar var doc_tc, doc_fp; //Elementos HMTL "Select" mc = parseFloat(document.getElementById('txtmc').value); //console.log(m); doc_tc = document.getElementById('txttc'); tc = doc_tc.value; //console.log(doc_tc.value); doc_fp = document.getElementById('txtfp'); fp = doc_fp.value; //console.log(doc_fp.value); // Proceso if (tc == "G") { if (fp == "C" || fp == "c") { r = "DESCUENTO 15%"; m = mc * DESC_G; tp = mc - m; } else { r = "RECARGO 10%"; m = mc * REC_G; tp = mc - m; } } else { if (fp == "C") { r = "DESCUENTO 20%"; m = mc * DESC_A; tp = mc - m; } else { r = "RECARGO 5%"; m = mc * REC_A; tp = mc - m; } } // Salida document.getElementById('txtr').value = r; document.getElementById('txtm').value = m; document.getElementById('txttp').value = tp; document.getElementById('txtmc').focus(); } </script> </body> </html>
const Joi = require('joi'); const respond = require('../../utils/respond'); const { User } = require('../../models'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const loginValidation = Joi.object({ email: Joi.string().email().required().label('email'), password: Joi.string().min(8).required().label('password'), }); const login = async (req, res) => { const { error, value: { email, password: password_requested }, } = loginValidation.validate(req.body); if (error) { return res.status(400).json(respond(400, error.message, '')); } try { const user = await User.findOne({ where: { email } }); const { id, name, password } = user; const match = await bcrypt.compare(password_requested, password); if (!match) return res.status(400).json(respond(400, 'Email or password wrong', '')); const token_payload = { id, name, email, }; const secretKey = process.env.SECRET_KEY || 'rahasia'; const token = jwt.sign(token_payload, secretKey, { expiresIn: '1d' }); // res.header('Access-Control-Allow-Credentials', true); // res.cookie('token', 'Bearer ' + token, { maxAge: 3600000 }); return res.status(200).json(respond(200, 'Login successfuly', { email, token })); } catch (error) { return res.status(500).json(respond(500, error, '')); } }; module.exports = login;
package com.labdessoft.ToDoList.entity; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Enumerated; import jakarta.persistence.EnumType; import jakarta.persistence.Transient; import java.time.LocalDate; import org.springframework.format.annotation.DateTimeFormat; import lombok.Getter; import lombok.Setter; import lombok.NoArgsConstructor; import lombok.AllArgsConstructor; // import io.swagger.v3.oas.annotations.media.Schema; import java.time.temporal.ChronoUnit; @Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class Task { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; // @Schema(name = "Detalhes da tarefa") private String description; private Boolean completed; @DateTimeFormat(pattern = "yyyy-MM-dd") private LocalDate startDate; @DateTimeFormat(pattern = "yyyy-MM-dd") private LocalDate dueDate; @Enumerated(EnumType.STRING) private TaskType type; @Enumerated(EnumType.STRING) private TaskPriority priority; // @Schema(name = "Dia para o prazo") @Transient public Long getDaysRemaining() { if (dueDate != null) { return LocalDate.now().until(dueDate, ChronoUnit.DAYS); } return null; } // @Schema(name = "Tipo: alto, medio ,baixo") public enum TaskPriority { HIGH, MEDIUM, LOW } // @Schema(name = "Tipo: prazo, data ,livre") public enum TaskType { WITH_DEADLINE, FIXED_DATE, FREE } public Task(String description) { this.description = description; this.completed = false; } @Override public String toString() { return "Task[id=" + id + ", description=" + description + ", completed=" + completed + ", startDate=" + startDate + ", dueDate=" + dueDate + ", type=" + type + "]"; } }
<?php declare(strict_types=1); namespace App\Tests\Feature; use App\Domain\Document\BaseDocument; use App\Domain\Document\Company\Company; use App\Domain\Document\Location\Location; use App\Domain\Document\Security\Administrator; use App\Domain\Document\Transaction\Transaction; use App\Tests\Extension\MissingTranslationsExtension; use App\Tests\Feature\Traits\JsonResponseTrait; use App\Tests\Feature\Traits\MessageBusTrait; use Doctrine\ODM\MongoDB\DocumentManager; use Doctrine\ODM\MongoDB\DocumentNotFoundException; use Happyr\ServiceMocking\Test\RestoreServiceContainer; use MongoDB\Driver\Session; use Symfony\Bundle\FrameworkBundle\KernelBrowser; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Contracts\Translation\TranslatorInterface; /** * Base feature test class. Provides useful methods for checking JSON responses and loads fixtures when needed. * * Note that fixtures will only be reloaded if $loadFixtures is set to true AND markTouchesDb() has been called. * This is to speed up the tests but may introduce some unexpected side effects if one forgets to call markTouchesDb(). * * Additionally, $authenticate property can be used to control whether the test client should be authenticated or not. * By default, the client is authenticated with default test user, but testing some public endpoints may require to set it to false. */ abstract class BaseTestCase extends WebTestCase { use JsonResponseTrait; use RestoreServiceContainer; use MessageBusTrait; protected static KernelBrowser $client; protected static bool $loadFixtures = true; protected static bool $authenticate = true; /** * @var array|object[] */ protected static array $fixtures = []; protected static Session $session; private static bool $touchesDb = false; protected static DocumentManager $dm; protected function setUp(): void { parent::setUp(); if (!self::$booted) { self::$client = self::createClient(); } $this->replaceBus(); Fixtures::$loader = self::getContainer()->get('fidry_alice_data_fixtures.loader.doctrine_mongodb'); self::$dm = self::getContainer()->get('doctrine_mongodb.odm.document_manager'); if (!static::$loadFixtures) { return; } $this->loadFixtures(); self::$touchesDb = false; $this->getDocumentManager()->clear(); if (static::$authenticate) { $this->authenticate(); } } protected function markTouchesDb(): void { self::$touchesDb = true; } protected function tearDown(): void { $this->getDocumentManager()->clear(); $translator = self::getContainer()->get(TranslatorInterface::class); MissingTranslationsExtension::addMessages(static::class.'::'.$this->getName(), $translator->getCollectedMessages()); parent::tearDown(); } /** * @return object[] */ protected function loadFixtures(): array { return self::$fixtures = Fixtures::loadFixtures(self::$touchesDb); } protected function getTestCompany(): Company { return self::$fixtures['test_company_1']; // @phpstan-ignore-line } protected function getTestLocation(): Location { return self::$fixtures['location_test_1']; // @phpstan-ignore-line } protected function getTestTransaction(): Transaction { return self::$fixtures['transaction_confirmed_test_company']; // @phpstan-ignore-line } protected function getTestUser(): Administrator { return self::$fixtures['user_test']; // @phpstan-ignore-line } protected function getDocumentManager(): DocumentManager { return self::$dm; } protected function authenticate(?Administrator $user = null): KernelBrowser { return self::$client->loginUser($user ?? $this->getTestUser()); } /** * @template T of BaseDocument * * @param T $document * * @return T */ protected function refresh(BaseDocument $document): BaseDocument { /** @var T|null $newDocument */ $newDocument = $this->getDocumentManager()->find($document::class, $document->getId()); if (null === $newDocument) { throw DocumentNotFoundException::documentNotFound($document::class, $document->getId()); } $this->getDocumentManager()->refresh($newDocument); return $newDocument; } }
# mypy: no-disallow-untyped-decorators # pylint: disable=E0611,E0401 from unittest import mock from g4f import ChatCompletion from httpx import AsyncClient from tortoise.contrib import test from src.enums import ModelNameEnum, RoleEnum from src.main import app from src.models import Interaction, Message class InteractionTestCase(test.IsolatedTestCase): async def test_create_interaction(self): async with AsyncClient(app=app, base_url="http://test") as ac: response = await ac.post( "/interactions", json={"model_name": "gpt3_5", "prompt": "My name is Shahriar"}, ) assert response.status_code == 200 data = response.json() assert data["settings"]["model_name"] == "gpt3_5" assert data["settings"]["prompt"] == "My name is Shahriar" assert "id" in data interaction_id = data["id"] created_obj = await Interaction.get(id=interaction_id) assert created_obj.ai_model_name.value == "gpt3_5" assert created_obj.prompt == "My name is Shahriar" @mock.patch.object(ChatCompletion, "create_async") async def test_create_message(self, ai_response): ai_response.return_value = "Hello Shahriar. What can I do for you?" interaction = await Interaction.create( ai_model_name=ModelNameEnum.GPT4, prompt="My name is Shahriar" ) async with AsyncClient(app=app, base_url="http://test") as ac: response = await ac.post( f"/interactions/{interaction.id}/messages", json={"content": "Hi"} ) assert response.status_code == 200 data = response.json() assert data["message"]["content"] == "Hi" assert data["message"]["role"] == "human" assert data["response"]["content"] == "Hello Shahriar. What can I do for you?" assert data["response"]["role"] == "ai" assert "id" in data["message"] assert "id" in data["response"] message_id = data["message"]["id"] response_id = data["response"]["id"] message_obj = await Message.get(id=message_id) assert message_obj.content == "Hi" assert message_obj.role == RoleEnum.HUMAN response_obj = await Message.get(id=response_id) assert response_obj.content == "Hello Shahriar. What can I do for you?" assert response_obj.role == RoleEnum.AI async def test_get_messages(self): interaction = await Interaction.create( ai_model_name=ModelNameEnum.GPT4, prompt="My name is Shahriar" ) message1 = await Message.create( interaction=interaction, role=RoleEnum.HUMAN, content="Hi", ) message2 = await Message.create( interaction=interaction, role=RoleEnum.AI, content="Hello there. How can I help you?", ) async with AsyncClient(app=app, base_url="http://test") as ac: response = await ac.get(f"/interactions/{interaction.id}/messages") assert response.status_code == 200 data = response.json() assert data[0]["id"] == str(message1.id) assert data[0]["content"] == "Hi" assert data[0]["role"] == "human" assert data[1]["id"] == str(message2.id) assert data[1]["content"] == "Hello there. How can I help you?" assert data[1]["role"] == "ai" async def test_get_interactions(self): interaction1 = await Interaction.create( ai_model_name=ModelNameEnum.GPT4, prompt="Hello World" ) interaction2 = await Interaction.create( ai_model_name=ModelNameEnum.GPT3_5, prompt="Act like a therapist" ) message1 = await Message.create( interaction=interaction1, role=RoleEnum.HUMAN, content="Hi", ) message2 = await Message.create( interaction=interaction1, role=RoleEnum.AI, content="Hello there. How can I help you?", ) async with AsyncClient(app=app, base_url="http://test") as ac: response = await ac.get("/interactions") assert response.status_code == 200 data = response.json() assert len(data) == 2 format_dt = lambda dt: dt.isoformat().replace("+00:00", "Z") self.maxDiff = None self.assertListEqual( data, [ { "id": str(interaction2.id), "created_at": format_dt(interaction2.created_at), "updated_at": format_dt(interaction2.updated_at), "role": RoleEnum.SYSTEM.value, "settings": { "model_name": interaction2.ai_model_name.value, "prompt": interaction2.prompt, }, "messages": [], }, { "id": str(interaction1.id), "created_at": format_dt(interaction1.created_at), "updated_at": format_dt(interaction1.updated_at), "role": RoleEnum.SYSTEM.value, "settings": { "model_name": interaction1.ai_model_name.value, "prompt": interaction1.prompt, }, "messages": [ { "id": str(message1.id), "role": message1.role.value, "content": message1.content, "created_at": format_dt(message1.created_at), }, { "id": str(message2.id), "role": message2.role.value, "content": message2.content, "created_at": format_dt(message2.created_at), }, ], }, ], )
import { FC, useContext, useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import { PlayerEvent, ServerEvent } from "../../../common/enums"; import { GlobalContext } from "../App"; import { createNewGame } from "../services/socket-helpers"; import { IndividualForm } from "./IndividualForm"; import { TeamForm } from "./TeamForm"; type GameMode = "individual" | "team"; export const Form: FC = () => { const [gameMode, setGameMode] = useState<GameMode>("individual"); const [numberOfEntities, setNumberOfEntities] = useState(2); const { globalState, setGlobalState } = useContext(GlobalContext); const navigate = useNavigate(); useEffect(() => { const { playerEvent, serverEvent, gameId, teams } = globalState; // console.info(globalState); if (playerEvent === PlayerEvent.CREATE_GAME && gameId === undefined) { console.info("Submitting generic form"); createNewGame({ globalState, setGlobalState }); } if ( playerEvent === PlayerEvent.CREATE_GAME && serverEvent === ServerEvent.GAME_CREATED && gameId !== undefined ) { console.info(globalState); console.table( globalState.teams .flatMap((team) => team.players) .flatMap((player) => player.cards.map((card) => ({ id: player.id, ...card })) ) ); console.log("%cNavigating", "font-size: 2em"); navigate(`/games/${gameId}`); } }, [globalState]); return ( <section> <fieldset> <legend>Game Mode</legend> <label> <input type="radio" name="gameMode" value="individual" checked={gameMode === "individual"} onChange={(e) => setGameMode(e.target.value as GameMode)} /> Individual </label> <label> <input type="radio" name="gameMode" value="team" checked={gameMode === "team"} onChange={(e) => setGameMode(e.target.value as GameMode)} /> Team </label> <br /> <label> Number of {gameMode === "individual" ? "Players" : "Teams"}: <input type="number" min="2" max="24" // since there are only 48 * 2 = 96 cards in a sequence deck value={numberOfEntities} onChange={(e) => setNumberOfEntities(() => e.target.valueAsNumber)} /> </label> </fieldset> {gameMode === "individual" ? ( <IndividualForm numberOfPlayers={numberOfEntities} /> ) : ( <TeamForm numberOfTeams={numberOfEntities} /> )} </section> ); }; export default Form;
import Head from 'next/head'; import type { NextPage, GetServerSideProps } from 'next'; import client from 'src/backend/client'; import { CountriesQuery } from 'src/backend/queries/country'; import { ICountry } from 'src/backend/types'; import Card from 'src/components/card'; import Link from 'next/link'; interface Props { countries: ICountry[]; } const Home: NextPage<Props> = ({ countries }) => { return ( <> <Head> <title>Create Next App</title> <meta name="description" content="Generated by create next app" /> <link rel="icon" href="/favicon.ico" /> </Head> <main className="flex flex-1 flex-col justify-center items-center min-h-screen pt-16 bg-slate-100 dark:bg-slate-800"> <h1 className="text-6xl"> Welcome to{' '} <a href="https://nextjs.org" className="text-primary hover:underline focus:underline" > Next.js! </a>{' '} Template </h1> <h1 className="text-3xl font-bold mt-10"> Here are some country cards with puppy images! </h1> <Link className="dark:bg-white dark:text-red-600 dark:active:text-red-500 bg-primary text-black hover:text-slate-800 block w-full rounded px-4 py-2 mt-5 text-sm font-medium shadow dark:hover:text-red-700 focus:outline-none focus:ring sm:w-auto" href="/" > Go Back Home </Link> <div className="grid items-center justify-center flex-wrap max-w-3xl grid-cols-2"> {countries.map((country: ICountry) => ( <Card key={country.code} header={country.name} paragraph={country.code} /> ))} </div> </main> </> ); }; export default Home; export const getServerSideProps: GetServerSideProps = async () => { const { data } = await client.query({ query: CountriesQuery, }); return { props: { countries: data.countries.slice(0, 4), }, }; };
<template> <!--背景图--> <v-app class="bg"> <v-content> <!--响应流式布局--> <v-container class="fill-height" fluid > <v-row align="center" justify="center" class="login-form" elevation="12" > <!--md="4" 代表中等设备的比例,例如电脑,ipad,sd=代表小型设备,比如:手机--> <v-col cols="12" md="4" > <!--阴影效果 elevation-12--> <v-card class="elevation-12"> <!--登录卡片的顶部,用来放置一标题和icon--> <v-toolbar color="primary" dark flat > <v-toolbar-title>Login form</v-toolbar-title> <v-spacer /> <v-tooltip bottom> <template v-slot:activator="{ on }"> <v-btn :href="source" icon large target="_blank" v-on="on" > <v-icon>mdi-code-tags</v-icon> </v-btn> </template> <span>Source</span> </v-tooltip> </v-toolbar> <!--文本内容密码用户输入框,以及验证码或者一些其他的东西--> <v-card-text> <!--表单--> <v-form> <v-text-field id="name" label="Name" name="name" type="text" /> <v-text-field id="password" label="Password" name="password" type="password" /> </v-form> </v-card-text> <!--行为,用来放置一些动作,例如按钮的提交操作,重置操作--> <v-card-actions> <!--分割线--> <v-spacer /> <v-btn color="primary mr-6" @click="$router.push('/')" >Login</v-btn> <v-btn color="cyan mr-6" dark >Reset</v-btn> </v-card-actions> </v-card> </v-col> </v-row> </v-container> </v-content> <!--遮罩层,渐变,用于美化页面--> <div class="mask"></div> </v-app> </template> <script> export default { props: { source: String } } </script> <style lang="scss" scoped> .bg { background-image: url('../assets/img/beauty.jpg'); background-size: 100% 100%; // opacity: 0.8; .login-form { z-index: 100; } } .mask { //铺满页面 position: absolute; top: 0; bottom: 0; left: 0; right: 0; //从左向右进行渐变 background-image: linear-gradient(to right, #bf30ac 0%, #0f9d58 100%); //透明度 opacity: 0.7; } </style>
package com.o3dr.services.android.lib.drone.mission.item; import android.os.Parcel; import android.os.Parcelable; import com.o3dr.services.android.lib.coordinate.LatLongAlt; import com.o3dr.services.android.lib.drone.mission.MissionItemType; public abstract class MissionItem implements Parcelable, Cloneable { private final MissionItemType type; public interface Command { } public interface ComplexItem<T extends MissionItem> { void copy(T t); } public interface SpatialItem { LatLongAlt getCoordinate(); void setCoordinate(LatLongAlt latLongAlt); } public abstract MissionItem clone(); public int describeContents() { return 0; } protected MissionItem(MissionItemType missionItemType) { this.type = missionItemType; } public MissionItemType getType() { return this.type; } public void writeToParcel(Parcel parcel, int i) { parcel.writeInt(this.type.ordinal()); } protected MissionItem(Parcel parcel) { this.type = MissionItemType.values()[parcel.readInt()]; } public boolean equals(Object obj) { if (this == obj) { return true; } if ((obj instanceof MissionItem) && this.type == ((MissionItem) obj).type) { return true; } return false; } public int hashCode() { MissionItemType missionItemType = this.type; if (missionItemType != null) { return missionItemType.hashCode(); } return 0; } public String toString() { return "MissionItem{type=" + this.type + '}'; } }
import { IsNotEmpty, IsNumber, IsString } from 'class-validator'; import { ApiProperty } from '@nestjs/swagger'; export class CreateLocationDto { @IsString() @IsNotEmpty() @ApiProperty() name: string; @IsString() @IsNotEmpty() @ApiProperty() address: string; @IsNumber() @IsNotEmpty() @ApiProperty() latitude: number; @IsNumber() @IsNotEmpty() @ApiProperty() longitude: number; }
import { z } from "zod"; const columnSchema = z.discriminatedUnion("kind", [ z.object({ kind: z.literal("varchar"), size: z.number() }), z.object({ kind: z.literal("uuid") }), z.object({ kind: z.literal("ulid") }), z.object({ kind: z.literal("decimal"), precision: z.number(), decimal: z.number() }), z.object({ kind: z.literal("bigint") }), z.object({ kind: z.literal("boolean") }), z.object({ kind: z.literal("datetime") }), z.object({ kind: z.literal("enum"), values: z.array(z.string()) }), ]); const tableSchema = z.object({ name: z.string(), fields: z.array(z.object({ name: z.string(), pk: z.boolean().default(false).optional(), kind: columnSchema })) }) type TableSchema = z.infer<typeof tableSchema> const relationSchema = z.object({ src_table: z.string(), src_field: z.string(), dest_table: z.string(), dest_field: z.string(), kind: z.union([z.literal("one2one"), z.literal("one2many"), z.literal("many2one")]) }) type RelationSchema = z.infer<typeof relationSchema> const userTable: TableSchema = { name: "user", fields: [ { name: "id", pk: true, kind: { kind: "ulid" } }, { name: "email", kind: { kind: "varchar", size: 300 } } ] } const sprintTable: TableSchema = { name: "sprint", fields: [ { name: "id", pk: true, kind: { kind: "ulid" } }, { name: "name", kind: { kind: "varchar", size: 50 } } ] } const sprintUploadTable: TableSchema = { name: "sprint_upload", fields: [ { name: "id", pk: true, kind: { kind: "ulid" } }, { name: "sprint_name", kind: { kind: "varchar", size: 50 } }, { name: "sprint_id", kind: { kind: "ulid" } }, ] } const relations: RelationSchema[] = [ { src_table: "sprint_upload", src_field: "sprint_id", dest_table: "sprint", dest_field: "id", kind: "many2one" } ] const DbSchema = { tables: [userTable, sprintTable, sprintUploadTable], relations: relations, } console.log(Bun.inspect(DbSchema))
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="icon" type="image/png" sizes="32x32" href="./assets/favicon-32x32.png"> <!-- Google fonts --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Barlow+Condensed:wght@400;700&family=Bellefair&family=Barlow:wght@400;700&display=swap" rel="stylesheet"> <!-- Our custom CSS --> <link rel="stylesheet" href="index.css"> <title>Frontend Mentor | Space tourism website</title> <script defer src="./index.js"></script> </head> <body class="destination"> <a class="skip-to-content" href="#main">Skip to content</a> <header class="primary-header flex"> <div> <img src="./starter-code/assets/shared/logo.svg" alt="space tourism logo" class="logo"> </div> <!-- hamburger menu --> <button class="mobile-nav-toggle" aria-controls="primary-navigation"><span class="sr-only" aria-expanded="false">Menu</span></button> <nav> <ul id="primary-navigation" data-visible="false" class="primary-navigation underline-indicators flex"> <li class="active"><a class="ff-sans-cond uppercase text-white letter-spacing-2" href="index.html"><span>00</span>Home</a> <li><a class="ff-sans-cond uppercase text-white letter-spacing-2" href="destination.html"><span>01</span>Destination</a> <li><a class="ff-sans-cond uppercase text-white letter-spacing-2" href="crew.html"><span>02</span>Crew</a> <li><a class="ff-sans-cond uppercase text-white letter-spacing-2" href="technology.html"><span>03</span>Technology</a> </ul> </nav> </header> <main id="main" class="grid-container grid-container--destination"> <h1 class="numbered-title"><span aria-hidden="true">01</span>Pick your destination</h1> <img src="starter-code/assets/destination/image-europa.png" alt="the moon"> <div class="tab-list underline-indicators flex"> <button aria-selected="true" class="uppercase ff-sans-cond text-accent bg-dark">Moon</button> <button aria-selected="false" class="uppercase ff-sans-cond text-accent bg-dark">Mars</button> <button aria-selected="false" class="uppercase ff-sans-cond text-accent bg-dark">Europa</button> <button aria-selected="false" class="uppercase ff-sans-cond text-accent bg-dark">Titan</button> </div> <article class="destination-info"> <h2 class="fs-800 ff-serif uppercase">Europa</h2> <p>The smallest of the four Galilean moons orbiting Jupiter, Europa is a winter lover’s dream. With an icy surface, it’s perfect for a bit of your snug wintery cabin.</p> <div class="destination-meta flex"> <div> <h3 class="text-accent fs-200 uppercase">Avg. distance</h3> <p class="fs-500 ff-serif uppercase">628 mil. km</p> </div> <div> <h3 class="text-accent fs-200 uppercase">Est. travel time</h3> <p class="fs-500 ff-serif uppercase">3 years</p> </div> </div> </article> </main> </body> </html>
<template> <footer> <div class="countInfo"> <div class="statistic"> <div class="value" style="color:orange"><i class="clock icon"></i>{{ existTime }}d</div> <div class="label"><p class="describe">网站存活</p></div> </div> <div class="statistic"> <div class="value" style="color:royalblue"><i class="calendar check outline icon"></i>{{ totalViews }}</div> <div class="label"><P class="describe">总阅读量</P></div> </div> <div class="statistic"> <div class="value" style="color:salmon"><i class="file alternate icon"></i>{{ totalBlogs }}</div> <div class="label"><p class="describe">总博客数</p></div> </div> <div class="statistic"> <div class="value" style="color:green"><i class="tags icon"></i>{{ totalTags }}</div> <div class="label"><p class="describe">总标签数</p></div> </div> </div> <div class="create"> <span>Copyright © ️2022️&nbsp;|&nbsp;Violet&nbsp;|&nbsp;</span> <span><a href="#">陕ICP备2021015553号-1</a></span> </div> </footer> </template> <script> import {getCountInfo} from "../axios"; import { AreaChartOutlined, FieldTimeOutlined, FileMarkdownOutlined, TagsOutlined, } from "@ant-design/icons-vue"; export default { name: "Footer", components: { AreaChartOutlined, FieldTimeOutlined, FileMarkdownOutlined, TagsOutlined, }, data() { return { totalViews: "", existTime: "", totalBlogs: "", totalTags: "", }; }, created() { getCountInfo().then((res) => { this.totalViews = res.data.data.totalViews; this.existTime = res.data.data.existTime; this.totalBlogs = res.data.data.totalBlogs; this.totalTags = res.data.data.totalTags; }); }, }; </script> <style scoped> footer { width: 100%; display: flex; flex-direction: row; text-align: center; justify-content: space-between; align-items: center; backdrop-filter: saturate(50%) blur(8px); background: rgba(255, 255, 255, .7); box-shadow: 0 0 2px 0 rgba(0, 0, 0, 0.18); } .countInfo { display: flex; flex-direction: row; margin-top: 10px; } .create { font-size: 18px; margin-right: 40px; } .value { font-size: 25px; } .label { font-size: 15px; } .statistic { margin: 0 25px; } .describe { margin-bottom: 10px; } @media screen and (max-width: 1000px) { footer { flex-direction: column; } .describe { display: none; } } @media (prefers-color-scheme: dark) { footer { color: #fff !important; background: rgba(36, 36, 36, .7); box-shadow: 0 1px 10px rgba(0, 0, 0, 0.05); } } </style>
package au.com.agl.kotlincats.presentation import androidx.arch.core.executor.testing.InstantTaskExecutorRule import au.com.agl.kotlincats.data.model.exceptions.GenericException import au.com.agl.kotlincats.data.model.exceptions.NetworkException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestCoroutineDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Before import org.junit.Test import org.mockito.Mockito.`when` import org.mockito.Mockito.mock import org.mockito.Mockito.verify import au.com.agl.kotlincats.domain.usecase.CatUseCases import au.com.agl.kotlincats.presentation.adapter.DataItem import au.com.agl.kotlincats.presentation.adapter.HeaderDataItem import au.com.agl.kotlincats.presentation.adapter.PetDataItem import org.junit.Rule import java.lang.Exception @ExperimentalCoroutinesApi class CatViewModelTest { private lateinit var viewModel: CatViewModel private lateinit var useCase: CatUseCases private val testDispatcher = TestCoroutineDispatcher() @get:Rule val instantExecutorRule = InstantTaskExecutorRule() @Before fun setUp() { Dispatchers.setMain(testDispatcher) useCase = mock(CatUseCases::class.java) viewModel = CatViewModel(useCase) } @After fun tearDown() { Dispatchers.resetMain() testDispatcher.cleanupTestCoroutines() } @Test fun `loadCatOwners success`() { val expectedDataItems = listOf<DataItem>( HeaderDataItem("Male"), PetDataItem("Garfield"), PetDataItem("Fido"), HeaderDataItem("Female"), PetDataItem("Garfield") ) `when`(useCase.getAllOwners()).thenReturn(expectedDataItems) // Act viewModel.loadCatOwners() // Assert verify(useCase).getAllOwners() assert(viewModel.owners.value == State.success(expectedDataItems)) } @Throws(NetworkException::class) fun `loadCatOwners network error`() { `when`(useCase.getAllOwners()).thenThrow(NetworkException()) viewModel.loadCatOwners() verify(useCase).getAllOwners() } @Throws(GenericException::class) fun `loadCatOwners generic error`() { val errorMessage = "Generic error" `when`(useCase.getAllOwners()).thenThrow(Exception(errorMessage)) viewModel.loadCatOwners() verify(useCase).getAllOwners() } }
import React, { useEffect, useState } from 'react' import { useRouter } from 'next/router' import Tab from '@src/components/Tab' import ArkalogicaLogo from '@src/assets/images/LogoArkalogica.svg' import CPLogo from '@src/assets/images/LogoCP.svg' import DatavidiaLogo from '@src/assets/images/LogoDatavidia.svg' import UXVdiaLogo from '@src/assets/images/LogoUXVidia.svg' // import ArkavidiaLogo from '@src/assets/images/logo/logo-arkavidia.png' import EmptyImage from '@src/assets/images/empty.png' import Image from 'next/image' import Link from 'next/link' import { getTeamData } from '@src/services/team' import { TeamData } from '@src/types/team' const routes = [ { name: 'Informasi', path: '/dashboard/information' }, { name: 'Data Peserta', path: '/dashboard/participant-data' }, { name: 'Submission', path: '/dashboard/submission' } ] const getLogo = (type: string) => { switch (type) { case 'competitive-programming': return CPLogo case 'datavidia': return DatavidiaLogo case 'arkalogica': return ArkalogicaLogo case 'uxvidia': return UXVdiaLogo default: return EmptyImage } } function SideNav({ compe }: { compe: string }) { const router = useRouter() return ( <div className="flex flex-col w-full h-fit shadow-[0_2px_8px_1px_rgba(0,0,0,0.1)] bg-white rounded-lg py-[36px] px-[24px] gap-8"> <div className="flex justify-center items-center"> <Image width={'120px'} height={'120px'} src={getLogo(compe)} /> </div> <div className="flex lg:flex-col flex-row lg:gap-8 sm:gap-5 justify-center items-center"> {routes.map((item, idx) => { if (idx === 2 && compe !== 'uxvidia' && compe !== 'datavidia') return null else return ( <Link href={item.path} key={idx}> {item.path === router.pathname ? ( <Tab>{item.name}</Tab> ) : ( <a className="px-2 py-2 lg:text-[20px] sm:text-[12px] font-varela text-center"> {item.name} </a> )} </Link> ) })} </div> </div> ) } function Dashboard({ children }: React.PropsWithChildren<{}>) { const [teamData, setTeamData] = useState<TeamData | null>() const fetchTeamData = async () => { const response = await getTeamData() setTeamData(response.data) } useEffect(() => { fetchTeamData() }, []) return ( <div className="p-5 lg:p-14"> <div className="lg:flex"> <div className="lg:w-2/12 py-[33px]"> <SideNav compe={teamData?.team_category ?? ('' as string)}></SideNav> </div> <div className="flex lg:flex-col lg:w-10/12 lg:px-[55px] py-[35px] lg:py-[69px] lg:gap-[30px]"> {children} </div> </div> </div> ) } export default Dashboard
# coding=utf-8 import numpy as np def softmax(softmax_x): """Compute the softmax function for each row of the input x. It is crucial that this function is optimized for speed because it will be used frequently in later code. You might find numpy functions np.exp, np.sum, np.reshape, np.max, and numpy broadcasting useful for this task. Numpy broadcasting documentation: http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html You should also make sure that your code works for a single N-dimensional vector (treat the vector as a single row) and for M x N matrices. This may be useful for testing later. Also, make sure that the dimensions of the output match the input. You must implement the optimization in problem 1(a) of the written assignment! Arguments: x -- A N dimensional vector or M x N dimensional numpy matrix. Return: x -- You are allowed to modify x in-place """ """ Softmax Regresyonu hatirlayalim: Softmax Regresyon lojistik regresyonun genellestirilmis halidir. Lojistik Regresyon Modeli sinif etiketi y’nin olasi iki degeri için calisabilmektedir, Softmax Regresyon Modeli ise sinif etiketlerinin daha fazla deger alabilecegi siniflandırma sorunlariyla ilgilenmektedir. """ """ x girdisinin her satiri icin softmax fonksiyonunu hesaplayacagiz.""" orig_shape = softmax_x.shape # c = constant : in practice, we make use of this property and choose c = -max_ix_i when # computing softmax probablities for numerical stability # softmax(x) = softmax(x+c) # softmax(x) = exp(x) / sum(exp(x)) c = -1 * np.max(softmax_x, axis=-1, keepdims=True) exps = np.exp(softmax_x + c) sum_exps = np.sum(exps, axis=-1, keepdims=True) softmax_x = exps / sum_exps assert softmax_x.shape == orig_shape return softmax_x def test_softmax_basic(): """ Some simple tests to get you started. Warning: these are not exhaustive. """ print "Running basic tests..." test1 = softmax(np.array([1, 2])) print test1 ans1 = np.array([0.26894142, 0.73105858]) assert np.allclose(test1, ans1, rtol=1e-05, atol=1e-06) test2 = softmax(np.array([[1001, 1002], [3, 4]])) print test2 ans2 = np.array([ [0.26894142, 0.73105858], [0.26894142, 0.73105858]]) assert np.allclose(test2, ans2, rtol=1e-05, atol=1e-06) test3 = softmax(np.array([[-1001, -1002]])) print test3 ans3 = np.array([0.73105858, 0.26894142]) assert np.allclose(test3, ans3, rtol=1e-05, atol=1e-06) print "You should be able to verify these results by hand!\n" def test_softmax(): """ Use this space to test your softmax implementation by running: python q1_softmax.py This function will not be called by the autograder, nor will your tests be graded. """ print "Running your tests..." ### YOUR CODE HERE raise NotImplementedError ### END YOUR CODE if __name__ == "__main__": test_softmax_basic() # test_softmax()
I22r-Translate-Microsoft Microsoft backend for the Internationalizationizer translation framework. Translates content from one supported language to another, using the Microsoft Translator webservice with the I22r::Translate framework. See the I22r::Translate for more information. To use the Microsoft Translator API, you must set up an account at the "Windows Azure Marketplace", choose a translator API data plan, and "register an application" to get a "client ID" and a "client secret" that you must provide to this module. See the instructions below or the I22r::Translate::Microsoft documentation on how to get these credentials. INSTALLATION To install this module, run the following commands: perl Makefile.PL make make test make install TESTING WITH MICROSOFT DATA SERVICES CREDENTIALS If you have registered for data services from Microsoft and want to use your credentials with the unit tests in this distribution, edit the bottom of the file t/Constants.pm before you run "make test". See the documentation for the I22r::Translate::Microsoft package for some (possibly outdated) information about how to obtain those credentials. If you do not specify your credentials (a "client id" and a "secret"), then the unit tests that interact with Microsoft's data services will be skipped. CONFIGURATION This Microsoft backend is used in conjunction with the I22r::Translate framework. You configure the framework with a call to I22r::Translate->config , passing a key-value pair with the key "I22r::Translate::Microsoft". A minimal configuration would look like: I22r::Translate->config( 'I22r::Translate::Microsoft' => { ENABLED => 1, CLIENT_ID => '... see below ...', SECRET => '... see below ...' } ); The CLIENT_ID and SECRET parameters are required. See the I22r::Translate::Microsoft and I22r::Translate documentation about other possible parameters. GETTING CREDENTIALS FOR MICROSOFT TRANSLATOR API You will need to obtain and provide a "client id" and "client secret" to the I22r::Translate framework to use the Microsoft backend. As of October 2012, here are the instructions for getting these credentials: 1. If you don't have a Windows Live ID , sign up for one at L<https://signup.live.com/signup.aspx?lic=1> 2. Visit https://datamarket.azure.com/dataset/bing/microsofttranslator . Register for a "Windows Azure Marketplace" account. 3. Choose a Microsoft Translator data plan. One of the available plans is a free option for 2,000,000 characters/month. 4. Now you have to "register an application". Visit https://datamarket.azure.com/developer/applications and hit the big green REGISTER button. 5. Choose any "Client ID" and "Name" for your application. The "URI" is also a required field, but the translator API doesn't use it, so you can put whatever you like in that field, too. Make a note of the "Client ID" value that you entered and the "Client secret" value that Microsoft provided. You will have to provide these values to the I22r::Translate::Microsoft backend configuration with the "CLIENT_ID" and "SECRET" keys. Example: If your application registration screen (at https::/datamarket.azure.com/developer/applications) looks like: * Client ID angus * Name The Beefinator * Client secret ykiDjfQ9lztW/oFUC4t2ciPWH2nJS88FqXcQbs/Z9Y=7 * Redirect URI https://ilikebeef.com/ Description The multilingual Beefinator site Then you would configure the Microsoft backend with I22r::Translate->config( 'I22r::Translate::Microsoft' => { ENABLED => 1, CLIENT_ID => "angus", SECRET => "ykiDjfQ9lztW/oFUC4t2ciPWH2nJS88FqXcQbs/Z9Y=7" } ); (these are not real credentials). SUPPORT AND DOCUMENTATION After installing, you can find documentation for this module with the perldoc command. perldoc I22r::Translate::Microsoft You can also look for information at: RT, CPAN's request tracker (report bugs here) http://rt.cpan.org/NoAuth/Bugs.html?Dist=I22r-Translate-Microsoft AnnoCPAN, Annotated CPAN documentation http://annocpan.org/dist/I22r-Translate-Microsoft CPAN Ratings http://cpanratings.perl.org/d/I22r-Translate-Microsoft Search CPAN http://search.cpan.org/dist/I22r-Translate-Microsoft/ LICENSE AND COPYRIGHT Copyright (C) 2012 Marty O'Brien This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License. See http://dev.perl.org/licenses/ for more information.
package org.kenux.security.domain.entity; import lombok.*; import javax.persistence.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; @Entity @Data @ToString(exclude = {"userRoles"}) @EqualsAndHashCode(of = "id") @NoArgsConstructor @AllArgsConstructor @Builder public class Account implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column private String username; @Column private String email; @Column private int age; @Column private String password; @ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL}) @JoinTable(name = "accout_roles", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "role_id") }) private Set<Role> userRoles = new HashSet<>(); }
package middlewares import ( "bytes" "io" "log" "strings" "time" "github.com/gin-gonic/gin" "github.com/google/uuid" ) func Logger() gin.HandlerFunc { return func(c *gin.Context) { logID := uuid.New().String() c.Set("logID", logID) startTime := time.Now() // 检查 Content-Type 头,判断请求是否包含文件 contentType := c.GetHeader("Content-Type") if contentType != "" && (strings.Contains(contentType, "multipart/form-data")) { log.Printf("[LogID:%s] Request: %s %s", logID, c.Request.Method, c.Request.RequestURI) } else { body, _ := c.GetRawData() c.Request.Body = io.NopCloser(bytes.NewBuffer(body)) log.Printf("[LogID:%s] Request: %s %s %s", logID, c.Request.Method, c.Request.RequestURI, string(body)) } c.Next() elapsedTime := time.Since(startTime) log.Printf("[LogID:%s] %s %s %d %v %s", logID, c.Request.Method, c.Request.RequestURI, c.Writer.Status(), elapsedTime, c.Request.UserAgent(), ) } }
# Arm Move Group Interface - [Arm Move Group Interface](#arm-move-group-interface) - [Description](#description) - [Features](#features) - [Generate motion plan to joint space goal `arm/JointSpaceGoal`](#generate-motion-plan-to-joint-space-goal-armjointspacegoal) - [Generate motion plan to pose goal `arm/PoseGoal`](#generate-motion-plan-to-pose-goal-armposegoal) - [Generate motion plan via array of end-effector pose waypoints (i.e. trajectory) `arm/PoseGoalArray`](#generate-motion-plan-via-array-of-end-effector-pose-waypoints-ie-trajectory-armposegoalarray) - [Execute motion plan `arm/Execute`](#execute-motion-plan-armexecute) - [Stop arm `arm/Stop`](#stop-arm-armstop) - [Clear current motion plan `arm/Clear`](#clear-current-motion-plan-armclear) - [Notes](#notes) - [Motion Planners](#motion-planners) ## Description This package hosts the node that utilizes the Move Group C++ Interface to generate motion plans from a custom service interface. The custom service interface is outlined in the **arm_msgs** package. Example service calls can be found in the **arm_tests** package. ## Features ### Generate motion plan to joint space goal `arm/JointSpaceGoal` The following command generates a motion plan at **10% of max speed** to joint angles: - J1: $10\degree$ - J2: $45\degree$ - J3: $0\degree$ - J4: $0\degree$ - J5: $60\degree$ - J6: $90\degree$ ```bash ros2 service call /arm/JointSpaceGoal arm_msgs/srv/JointSpaceGoal '{speed: 10, joint_pos_deg: [10, 45, 0, 0, 60, 90]}' ``` ### Generate motion plan to pose goal `arm/PoseGoal` The following command generates a motion plan at **30% of max speed** to coordinates: - x: $0.2$m - y: $-0.5$m - z: $0.8$m with quaternion orientation: - x: $0.0$ - y: $0.0$ - z: $-\sqrt{2}/2$ - w: $\sqrt{2}/2$ ```bash ros2 service call /arm/PoseGoal arm_msgs/srv/PoseGoal '{speed: 30, pose: {position: {x: 0.2, y: -0.5, z: 0.8}, orientation: {x: 0.0, y: 0.0, z: -0.7071, w: 0.7071}}}' ``` <br> <br> ### Generate motion plan via array of end-effector pose waypoints (i.e. trajectory) `arm/PoseGoalArray` <br> The ros2 service is of type `PoseTargetArray` which has parameters: - `type`: - `'linear'` for linear movements - `'arc'` for curved/circular movements - `step_size`: Interpolation between points (default $0.01$m) - `jump_threshold`: Limits jump between generated points (default $0.0$m (ignored)) - `waypoints`: Array of type `geometry_msgs/Pose` messages -- desired waypoints the end effector to reach sequentially <br> <br> The following command generates a linear motion plan with the following waypoints assuming **orientation fixed at identity**, 1cm max step size, and jump threshold ignored: - Waypoint 1: - x: $0.2$m - y: $0.0$m - z: $0.0$m - Waypoint 2: - x: $0.2$m - y: $0.4$m - z: $0.3$m ```bash ros2 service call /arm/PoseGoalArray arm_msgs/srv/PoseTargetArray '{type: 'linear', step_size: 0.01, jump_threshold: 0.0, waypoints: {pose: {position: {x: 0.2, y: 0.0, z: 0.0}, orientation: {x: 0.0, y: 0.0, z: 0.0, w: 1.0}}, pose: {position: {x: 0.2, y: 0.4, z: 0.3}, orientation: {x: 0.0, y: 0.0, z: 0.0, w: 1.0}}}}' ``` <br> <br> The following command generates a curved motion plan creating a quarter-circle arc in the $xz$ plane with radius $0.1$m assuming **start position at origin**, **orientation fixed at identity**, 1cm max step size, and jump threshold ignored: - Center of motion - x: $0.01$m - y: $0.0$ - z: $0.0$ - Endpoint - x: $0.01$m - y: $0.0$ - z: $0.01$m <br> ```bash ros2 service call /arm/PoseGoalArray arm_msgs/srv/PoseTargetArray '{type: 'linear', step_size: 0.01, jump_threshold: 0.0, waypoints: {pose: {position: {x: 0.01, y: 0.0, z: 0.0}, orientation: {x: 0.0, y: 0.0, z: 0.0, w: 1.0}}, pose: {position: {x: 0.01, y: 0.0, z: 0.01}, orientation: {x: 0.0, y: 0.0, z: 0.0, w: 1.0}}}}' ``` <br> ### Execute motion plan `arm/Execute` To execute a generated motion plan: ```bash ros2 service call /arm/Execute std_srvs/srv/Trigger ``` <br> ### Stop arm `arm/Stop` To stop current execution of the arm: ```bash ros2 service call /arm/Stop std_srvs/srv/Trigger ``` <br> ### Clear current motion plan `arm/Clear` To clear the current motion plan: ```bash ros2 topic pub --once /arm/Clear std_msgs/msg/Bool '{data: True}' ``` <br> ## Notes ### Motion Planners The arm move group interface node utilizes the STOMP planner for linear movements in space, and uses the PILZ ('CIRC') industrial motion planner for circular/arc movements. > :warning: STOMP planner only accepts **joint space** goals.
let map = L.map("map", { center: [37.7749, -122.4194], zoom: 5 }); // Adding a tile layer (the background map image) to our map: // We use the addTo() method to add objects to our map. L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); // Store Url const url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.geojson'; d3.json(url).then(function (data) { L.geoJSON(data, { style: function (feature) { let mag = feature.properties.mag; let depth = feature.geometry.coordinates[2]; return { weight: 1, color: 'black', radius: mag * 4, fillOpacity: .65, fillColor: depth < 10 ? 'green' : depth < 30 ? 'lime' : depth < 50 ? 'yellow' : depth < 70 ? 'orange' : depth < 90 ? 'darkkorange' : 'red' }; }, pointToLayer: (data, latlng) => L.circleMarker(latlng) }).bindPopup(function (layer) { let { mag, place, time } = layer.feature.properties; let depth = layer.feature.geometry.coordinates[2]; let date = new Date(time).toLocaleString(); return `<h5>${place}<br>${date}<br>Magnitude: ${mag}<br>Depth: ${depth}</h5>`; }).addTo(map); }); let legend = L.control({position:'bottomright'}); legend.onAdd = function() { let div = L.DomUtil.create('div','legend'); div.innerHTML = ` <div style="background:green">-10 - 10</div> <div style="background:lime">10 - 30</div> <div style="background:yellow">30 - 50</div> <div style="background:orange">50 - 70</div> <div style="background:darkorange">70 - 90</div> <div style="background:red">90+</div> `; return div } legend.addTo(map)
const express = require("express"); const { v4: uuidv4 } = require("uuid"); const app = express(); app.use(express.json()); const customers = []; //middleware function verifyIfExistAccountCPF(request, response, next) { const {cpf} = request.headers; const customer = customers.find(custumer => custumer.cpf === cpf); if(!customer) { return response.status(400).json({ error: "custumer not found "}) } request.customer = customer; return next(); } app.post("/account", (request, response) => { const { cpf, name } = request.body; const customerAlreadyExists = customers.some((custumer) => custumer.cpf === cpf) if(customerAlreadyExists) { return response.status(400).json({error: "Custumer already exists!"}); } customers.push({ cpf, name, id: uuidv4(), statement: [], }); return response.status(201).send(); }); // app.use(verifyIfExistAccountCPF); app.get("/statement", verifyIfExistAccountCPF, (request, response) => { const { customer} = request; return response.json(customer.statement) }); app.post("/deposit", verifyIfExistAccountCPF, (request, response) => { const { description, amount } = request.body; console.log(request) const { customer } = request; const statementOperation = { description, amount, created_at: new Date(), type: 'credit' } customer.statement.push(statementOperation); return response.status(201).send(); }) app.listen(3333);
import { jsx as _jsx } from "react/jsx-runtime"; import * as React from "react"; import { Slot } from "@radix-ui/react-slot"; import { Controller, FormProvider, useFormContext, } from "react-hook-form"; import { cn } from "@/lib/utils"; import { Label } from "@/components/ui/label"; const Form = FormProvider; const FormFieldContext = React.createContext({}); const FormField = ({ ...props }) => { return (_jsx(FormFieldContext.Provider, { value: { name: props.name }, children: _jsx(Controller, { ...props }) })); }; const useFormField = () => { const fieldContext = React.useContext(FormFieldContext); const itemContext = React.useContext(FormItemContext); const { getFieldState, formState } = useFormContext(); const fieldState = getFieldState(fieldContext.name, formState); if (!fieldContext) { throw new Error("useFormField should be used within <FormField>"); } const { id } = itemContext; return { id, name: fieldContext.name, formItemId: `${id}-form-item`, formDescriptionId: `${id}-form-item-description`, formMessageId: `${id}-form-item-message`, ...fieldState, }; }; const FormItemContext = React.createContext({}); const FormItem = React.forwardRef(({ className, ...props }, ref) => { const id = React.useId(); return (_jsx(FormItemContext.Provider, { value: { id }, children: _jsx("div", { ref: ref, className: cn("space-y-2", className), ...props }) })); }); FormItem.displayName = "FormItem"; const FormLabel = React.forwardRef(({ className, ...props }, ref) => { const { error, formItemId } = useFormField(); return (_jsx(Label, { ref: ref, className: cn(error && "text-destructive", className), htmlFor: formItemId, ...props })); }); FormLabel.displayName = "FormLabel"; const FormControl = React.forwardRef(({ ...props }, ref) => { const { error, formItemId, formDescriptionId, formMessageId } = useFormField(); return (_jsx(Slot, { ref: ref, id: formItemId, "aria-describedby": !error ? `${formDescriptionId}` : `${formDescriptionId} ${formMessageId}`, "aria-invalid": !!error, ...props })); }); FormControl.displayName = "FormControl"; const FormDescription = React.forwardRef(({ className, ...props }, ref) => { const { formDescriptionId } = useFormField(); return (_jsx("p", { ref: ref, id: formDescriptionId, className: cn("text-sm text-muted-foreground", className), ...props })); }); FormDescription.displayName = "FormDescription"; const FormMessage = React.forwardRef(({ className, children, ...props }, ref) => { const { error, formMessageId } = useFormField(); const body = error ? String(error?.message) : children; if (!body) { return null; } return (_jsx("p", { ref: ref, id: formMessageId, className: cn("text-sm font-medium text-destructive", className), ...props, children: body })); }); FormMessage.displayName = "FormMessage"; export { useFormField, Form, FormItem, FormLabel, FormControl, FormDescription, FormMessage, FormField, };
import { useRef } from "react"; import { useDispatch } from "react-redux"; import styled from "styled-components"; import { filterRecipesByName } from "../redux/actions"; const SearchSection = styled.section` padding-top: 2rem; > * { margin: 0.3rem; } `; export default function SearchBar() { const dispatcher = useDispatch(); const inputRef = useRef(); const searchHandler = () => { const recipeName = inputRef.current.value; if (recipeName.length) dispatcher(filterRecipesByName(recipeName)); else console.log( "Input is empty, distpatch something to make it equal to base state" ); }; return ( <SearchSection className="name-search"> <label htmlFor="food-name">Search For Food</label> <input type="text" placeholder="Search..." id="food-name" ref={inputRef} /> <button onClick={searchHandler}>Search</button> </SearchSection> ); }
import React, { useState, useMemo } from 'react'; import { ScrollView } from 'react-native'; import AnimalHistoriesComponent from '../animal-histories/animal-histories.component'; import HistoryFilterComponent from '../history-filter/history-filter.component'; import InputSearch from '../input-search/input-search.component'; import { Container } from './style'; import { useSelector } from 'react-redux'; import { NotAnimalsText } from '../home-component/styles'; import { startOfWeek, endOfWeek, isSameDay, isSameMonth, parseISO, } from 'date-fns'; import { ptBR } from 'date-fns/locale'; interface HealthRecord { id: string; animalId: string; accuracy: number; name: string; time: string; healthHistory: any[]; healthStatus: string; imageDetails?: any; color: string; } const HistoriesAnalysis = () => { const [hasSkeleton, setHasSkeleton] = useState(true); const [searchText, setSearchText] = useState(''); const [filterType, setFilterType] = useState< 'Hoje' | 'Semanal' | 'Mensal' | 'Todos' >('Hoje'); const allAnimals = useSelector((state: any) => state.animals.animals); const extractHealthRecords = (animals: HealthRecord[]) => animals.flatMap((animal) => animal.healthHistory.map((record: any) => ({ ...record, animalId: animal.id, name: animal.name, imageDetails: animal.imageDetails, color: animal.color, })) ); const filterRecordsByText = (records: HealthRecord[], text: string) => records.filter((record) => record.name.toLowerCase().includes(text.toLowerCase()) ); const filterRecordsByDate = (records: HealthRecord[], filterType: string) => { const today = new Date(); switch (filterType) { case 'Hoje': return records.filter((record) => isSameDay(parseISO(record.time), today) ); case 'Semanal': return records.filter((record) => { const recordDate = parseISO(record.time); return ( recordDate >= startOfWeek(today, { locale: ptBR }) && recordDate <= endOfWeek(today, { locale: ptBR }) ); }); case 'Mensal': return records.filter((record) => isSameMonth(parseISO(record.time), today) ); case 'Todos': default: return records; } }; const filteredHealthRecords = useMemo(() => { if (allAnimals.length === 0) return []; let extractedRecords = extractHealthRecords(allAnimals); extractedRecords = filterRecordsByText(extractedRecords, searchText); extractedRecords = filterRecordsByDate(extractedRecords, filterType); return extractedRecords; }, [allAnimals, searchText, filterType]); React.useEffect(() => { if (filteredHealthRecords.length !== 0) { setHasSkeleton(false); } }, [allAnimals]); return ( <ScrollView scrollEnabled> <Container> <InputSearch setSearchText={setSearchText} /> <HistoryFilterComponent onSelectFilter={setFilterType} /> {filteredHealthRecords.length === 0 ? ( <NotAnimalsText style={{ marginTop: 100 }}> Nenhum análise encontrada </NotAnimalsText> ) : ( filteredHealthRecords .reverse() .map((item) => ( <AnimalHistoriesComponent key={item.id} animalId={item.animalId} accuracy={item.accuracy} animalName={item.name} dateAnalysis={item.time} predictClass={item.healthStatus} animalImage={item.imageDetails?.url} color={item.color} hasSkeleton={hasSkeleton} /> )) )} </Container> </ScrollView> ); }; export default HistoriesAnalysis;
import React from "react"; import { CurrentUserContext } from "../context/CurrentUserContext"; export default function Card(props) { const currentUser = React.useContext(CurrentUserContext); const isOwn = props.ownerId === currentUser._id; const cardDeleteButtonClassName = `card__delete-button ${ isOwn ? "card__delete-button_visible" : "card__delete-button_hidden" }`; const isLiked = props.likes.some((i) => i._id === currentUser._id); const cardLikeButtonClassName = `card__like-button ${ isLiked ? "card__like-button_active" : "card__like-button" }`; function handleClick() { props.handleClick(props); } function handleLikeClick() { props.onCardLike(props); } function handleDeleteClick() { props.onCardDelete(props); } return ( <li className="card"> <img className="card__image" onClick={handleClick} src={props.url} alt={props.alt} /> <div className="card__section"> <h2 className="card__title">{props.title}</h2> <button type="button" onClick={handleDeleteClick} aria-label="Кнопка: удалить карточку" className={cardDeleteButtonClassName} ></button> <div className="card__like-section"> <button type="button" onClick={handleLikeClick} aria-label="Кнопка: мне нравится" className={cardLikeButtonClassName} ></button> <p className="card__like-counter">{props.likes?.length}</p> </div> </div> </li> ); }
import React , { useState } from 'react' import {close , logo , menu} from '../assets' import {navLinks} from '../constants' const Navbar = () => { const [toggle , setToggle] = useState(false) return ( <div className='w-full flex py-6 justify-between items-center navbar'> <img src={logo} alt='logo' className='w-[124px] h-[32px]' /> <ul className='list-none sm:flex hidden justify-end items-center flex-1 gap-10'> {navLinks.map( (nav) => { return ( <li key={nav.id} className='font-poppins font-normla cursor-pointer text-[16px] text-white' > <a href={`#${nav.id}`}> {nav.title} </a> </li> ) })} </ul> <div className='sm:hidden flex justify-end items-center flex-1'> <img src={toggle ? close : menu} alt='menu' className='w-[28px] h-[28px] object-contain' onClick={() => setToggle( prev => !prev)} /> <div className={`${toggle ? 'flex' : 'hidden'} sm:hidden p-6 bg-black-gradient absolute top-20 right-0 mx-4 my-2 min-w-[140px] rounded-xl sidebar`}> <ul className='list-none flex flex-col justify-end items-center flex-1 gap-3'> {navLinks.map( (nav , index) => { return ( <li key={nav.id} className='font-poppins font-normla cursor-pointer text-[16px] text-white' > <a href={`#${nav.id}`}> {nav.title} </a> </li> ) })} </ul> </div> </div> </div> ) } export default Navbar
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Bienes Raices</title> <link rel="stylesheet" href="css/normalize.css"> <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700,900&display=swap" rel="stylesheet"> <link rel="stylesheet" href="css/styles.css"> </head> <body> <header class="site-header"> <div class="contenedor contenido-header"> <div class="barra"> <a href="index.html"> <img src="img/logo.svg" alt="Logotipo de Bienes Raices"> </a> <div class="mobile-menu"> <a href="#navegacion"> <img src="img/barras.svg" alt=""> </a> </div> <nav id="navegacion" class="navegacion"> <a href="nosotros.html">Nosotros</a> <a href="anuncios.html">Anuncios</a> <a href="blogs.html">Blogs</a> <a href="contacto.html">Contacto</a> </nav> </div> </div> </header> <h1 class="fw-300 center-text">Contacto</h1> <img src="img/destacada3.jpg" alt="Imagen Anuncio"> <main class="contenedor seccion contenido-centrado"> <h2 class="fw-300 center-text">Llena el formulario de Contacto</h2> <form action=""> <fieldset> <legend>Información Personal</legend> <label for="nombre">Nombre:</label> <input type="text" id="nombre" placeholder="Tu nombre"> <label for="email">E-mail</label> <input type="email" id="email" placeholder="Correo"> <label for="telefono">Teléfono</label> <input type="tel" id="telefono" placeholder="Tu Telefono" required> <label for="mensaje">Mensaje:</label> <textarea name="mensaje" id="mensaje"></textarea> </fieldset> <fieldset> <legend>Información sobre Propiedad</legend> <label for="opciones">Vende o Compra</label> <select name="opciones" id="opciones"> <option value="" disabled selected> -- Selecione --</option> <option value="compra">Compra</option> <option value="vende">Vende</option> </select> <label for="cantidad">Cantidad</label> <input type="number" name="cantidad" id="cantidad"> </fieldset> <fieldset> <p>Como desea ser contactado</p> <div class="forma-contacto"> <label for="opcion-telefono">Teléfono</label> <input type="radio" name="opcion-radio" value='opcion-telefono' id="opcion-telefono"> <label for="opcion-email">E-mail</label> <input type="radio" value="opcion-email" name="opcion-radio" id="opcion-email"> </div> <p>si eligio Telefono, elija la fecha y hora</p> <label for="fecha">Fecha</label> <input type="date" name="fecha" id="fecha"> <label for="hora">Hora</label> <input type="time" name="hora" id="hora"> </fieldset> <input type="submit" value="Enviar" class="boton boton-verde"> </form> </main> <footer class="site-footer seccio"> <div class="contenedor contenedor-footer"> <nav class="navegacion"> <a href="nosotros.html">Nosotros</a> <a href="anuncios.html">Anuncios</a> <a href="blogs.html">Blogs</a> <a target="_blank" href="contacto.html">Contacto</a> </nav> <p>Todos los Derechos Reservados 2019 &#169;</p> </div> </footer> </body> </html>
package com.pseudoankit.contactscmp.contacts.presentation.ui.component import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import com.pseudoankit.contactscmp.contacts.domain.Contact @Composable fun RecentlyAddedContacts( contacts: List<Contact>, onClick: (Contact) -> Unit, modifier: Modifier = Modifier ) { Column( modifier = modifier ) { if (contacts.isNotEmpty()) { Text( text = "Recently Added", modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp), fontWeight = FontWeight.Bold ) Spacer(Modifier.height(16.dp)) } LazyRow( modifier = Modifier.fillMaxWidth(), contentPadding = PaddingValues(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(16.dp) ) { items(contacts) { contact -> Column( modifier = modifier.clickable(onClick = { onClick(contact) }), horizontalAlignment = Alignment.CenterHorizontally ) { ContactPhoto( contact = contact, modifier = Modifier.size(50.dp) ) Spacer(Modifier.height(8.dp)) Text( text = contact.firstName, ) } } } } }
import React, { useState } from 'react'; import { Link } from 'react-router-dom'; import '../../assets/styles/Home.css'; import shape from '../../assets/img/shape.png'; import person from '../../assets/img/person.svg'; import person2 from '../../assets/img/person2.svg'; import person4 from '../../assets/img/person4.svg'; const HomeForm = () => { const [dark, setDark] = useState(false); const [section, setSection] = useState('inicio'); const toggleAnimation = () => { setDark((prevDark) => !prevDark); setAnimating(true); }; const handleHamburgerClick = () => { const bigWrapper = document.querySelector('.big-wrapper'); bigWrapper.classList.toggle('active'); }; const handleSectionChange = (newSection) => { setSection(newSection); }; return ( <main> <div className={`big-wrapper ${dark ? 'dark' : 'light'}`}> <img src={shape} alt="" className="shape" /> <header> <div className="home-container"> <div className="logo"> <i className="uil uil-pagelines"></i> <h3>GreenRoof</h3> </div> <div className="links"> <ul> <li onClick={handleHamburgerClick}> <button onClick={() => handleSectionChange('inicio')}> Inicio </button> </li> <li onClick={handleHamburgerClick}> <button onClick={() => handleSectionChange('caracteristicas')}> Características </button> </li> <li onClick={handleHamburgerClick}> <button onClick={() => handleSectionChange('ventajas')} > Ventajas </button> </li> <li> <button><Link to="/auth" className="home-btn"> Iniciar sesión </Link></button> </li> </ul> </div> <div className="overlay"></div> <div className="hamburger-menu" onClick={handleHamburgerClick}> <div className="bar"></div> </div> </div> </header> {/* Sección de Inicio */} {section === 'inicio' && ( <div className="showcase-area"> <div className="home-container"> <div className="left"> <div className="big-title"> <h1 className="titulos-home">Bienvenido a GreenRoof:</h1> <h1 className="titulos-home">casas inteligentes para tu mejor amigo</h1> </div> <p className="text"> En GreenRoof reinventamos las casas para perros. Nuestras casas tienen techo verde con sistema de monitoreo integrado para garantizar el bienestar de tu mascota. </p> <p className="text"> Con nuestra aplicación web, podrás verificar en tiempo real la temperatura, humedad y más desde tu computadora o teléfono. El riego automático se encarga de mantener el pasto fresco. Duerme tranquilo sabiendo que tu perro está cómodo en su hogar inteligente. </p> </div> <div className="right"> <img src={person} alt="Person Image" className="person" /> </div> </div> </div> )} {/* Sección de Características */} {section === 'caracteristicas' && ( <div className="showcase-area"> <div className="home-container"> <div className="left"> <div className="big-title2"> <h1 className="titulos-home">Caracteristicas</h1> </div> </div> <div className="right"> <img src={person2} alt="Person Image" className="person" /> </div> </div> </div> )} {/* Sección de Beneficios (Aún por agregar) */} {section === 'ventajas' && ( <div className="showcase-area"> <div className="home-container"> <div className="left"> <div className="big-title2"> <h1 className="titulos-home">Ventajas</h1> </div> </div> <div className="right"> <img src={person4} alt="Person Image" className="person" /> </div> </div> </div> )} <div className="bottom-area"> <div className="home-container"> <button className="toggle-btn" onClick={toggleAnimation}> <i className="far fa-moon"></i> <i className="far fa-sun"></i> </button> </div> </div> </div> </main> ); }; export default HomeForm;
import { Types } from 'mongoose'; import moment from 'moment'; // Types import { Validation } from '@/types'; import { ITodo, ITodoValidator, TodoPriority } from '@/types/todo'; class TodoValidator implements ITodoValidator { public Id(input: string): Validation { if (!input) { return { error: true, text: 'ID cannot be empty!', }; } else if (!Types.ObjectId.isValid(input)) { return { error: true, text: 'Invalid ID!', }; } return { error: false, text: '', }; } public UserId(input: string): Validation { if (!input) { return { error: true, text: 'User ID cannot be empty!', }; } else if (!Types.ObjectId.isValid(input)) { return { error: true, text: 'Invalid user ID!', }; } return { error: false, text: '', }; } public ListId(input: string | null): Validation { if (input) { if (!Types.ObjectId.isValid(input)) { return { error: true, text: 'Invalid list ID!', }; } } return { error: false, text: '', }; } public Name(input: string): Validation { if (!input) { return { error: true, text: 'Name cannot be empty!', }; } return { error: false, text: '', }; } public Notes(input: string | null): Validation { if (input) { return { error: false, text: '', }; } return { error: false, text: '', }; } public URL(input: string | null): Validation { const pattern: RegExp = new RegExp( '^(https?:\\/\\/)?' + // Protocol '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // Domain '((\\d{1,3}\\.){3}\\d{1,3}))' + // OR IPv4 '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // Port and Path '(\\?[;&a-z\\d%_.~+=-]*)?' + // Query String '(\\#[-a-z\\d_]*)?$', 'i', ); if (input) { if (!pattern.test(input)) { return { error: true, text: 'Invalid URL!', }; } } return { error: false, text: '', }; } public Due(input: string | null): Validation { if (input) { if (!moment(input).isValid()) { return { error: true, text: 'Invalid due!', }; } else { return { error: false, text: '', }; } } return { error: true, text: 'Due cannot be empty!', }; } public Priority(input: string): Validation { switch (input) { case TodoPriority.NONE: break; case TodoPriority.LOW: break; case TodoPriority.MEDIUM: break; case TodoPriority.HIGH: break; default: return { error: true, text: 'Invalid priority attribute!', }; } return { error: false, text: '', }; } } export default new TodoValidator();
import Box from '@mui/material/Box'; import {connect, DispatchProp} from "react-redux"; import {RootState} from "../../store"; import {Container, Switch, TextField, Typography} from '@mui/material'; import Header from "../../Header"; import Grid from "@mui/material/Grid"; import {Field, Form} from "react-final-form"; import Button from "@mui/material/Button"; import {Footer} from "../../Footer"; import {criarContatos, UsuarioDadosPessoaisForm, validation} from "./actions.ts"; import {useNavigate} from "react-router-dom"; import {NovoUsuarioContext} from "../context.tsx"; import {FieldArray} from "react-final-form-arrays"; import arrayMutators from 'final-form-arrays' import {useContext} from "react"; import Link from "@mui/material/Link"; function NovaContaContatos({dispatch}: DispatchProp) { const navigate = useNavigate(); const onSubmit = async (values: Partial<UsuarioDadosPessoaisForm>) => { criarContatos(dispatch, values, navigate); } const {novosContatos} = useContext(NovoUsuarioContext); return ( <Grid> <Header hideMenu={true}/> <Box> <Container component="div" maxWidth="xs"> <Box sx={{ marginTop: 2, display: 'flex', flexDirection: 'column', alignItems: 'center', }} > <Typography component="h1" variant="h5"> Contatos </Typography> <Form onSubmit={onSubmit} validate={validation} initialValues={{ contatos: novosContatos }} mutators={{ ...arrayMutators, }} render={({ handleSubmit, }) => ( <form onSubmit={handleSubmit}> <Grid container spacing={2}> <Grid item xs={12}> <Grid container spacing={2}> <Grid item xs={10}> URL </Grid> <Grid item xs={2}> Visível </Grid> </Grid> <FieldArray name="contatos"> {({fields}) => fields.map((name, index) => ( <div key={name}> <Grid container spacing={2}> <Grid item xs={10} style={{marginTop: "15px"}}> <Field component="input" name={`${name}.descricao`} > {({input}) => <TextField {...input} label={novosContatos[index].descricaoContato} type="text"/>} </Field> </Grid> <Grid item xs={2} style={{marginTop: "20px"}}> <Field component="input" name={`${name}.visivel`} > {({input}) => <Switch {...input} defaultChecked /> } </Field> </Grid> </Grid> </div> )) } </FieldArray> </Grid> </Grid> <Button type="submit" fullWidth variant="contained" sx={{mt: 3, mb: 2}} > Salvar </Button> <Link href="/nova-conta-localidade">Preencher depois</Link> </form> )} /> </Box> <Footer sx={{mt: 5}}/> </Container> </Box> </Grid> ); } const mapStateToProps = (state: RootState) => ({ user: state.userReducer.user }) export default connect(mapStateToProps)(NovaContaContatos)
<!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>Grid Layout</title> <style> body { background-color: lightgray; } .parent { display: grid; min-height: 100vh; grid-template-rows: repeat(8, 1fr); grid-template-columns: repeat(5, 1fr); grid-gap: 1rem; } .child { display: grid; height: 100%; grid-template-rows: repeat(8, 1fr); grid-template-columns: repeat(5, 1fr); grid-gap: 2rem; background-color: cadetblue; display: flex; justify-content: center; align-items: center; } .small { grid-row: span 1; grid-column: span 1; } .medium { grid-row: span 2; grid-column: span 2; } .large { grid-row: span 3; grid-column: span 3; } .tall { grid-row: span 3; grid-column: span 2; } .wide { grid-row: span 2; grid-column: span 3; } </style> </head> <body> <main> <div class="parent"> <div class="child medium">1st child</div> <div class="child large">2nd child</div> <div class="child medium">3rd child</div> <div class="child small">4th child</div> <div class="child tall">5th child</div> <div class="child wide">6th child</div> <div class="child wide">7th child</div> <div class="child medium">8th child</div> </div> </main> </body> </html>
// https://quii.gitbook.io/learn-go-with-tests/go-fundamentals/structs-methods-and-interfaces package structs import "math" type Shape interface { // can be used by different types (parametric polymorphism: https://en.wikipedia.org/wiki/Parametric_polymorphism) Area() float64 } type Rectangle struct { Width float64 Height float64 } func Perimeter(rectangle Rectangle) float64 { // This is a function return 2 * (rectangle.Width + rectangle.Height) } func (r Rectangle) Area() float64 { // This is a method. The only difference between function and method is the syntax of the method receiver 'func (receiverName ReceiverType) MethodName(args)': It is a convention in Go to have the receiver variable be the first letter of the type. return r.Width * r.Height } type Circle struct { Radius float64 } func (c Circle) Area() float64 { // go does not have 'method overloading' return math.Pi * c.Radius * c.Radius } type Triangle struct { Base float64 Height float64 } func (t Triangle) Area() float64 { return t.Base * t.Height * 0.5 }
import { Icon } from '@iconify/react'; import Slider from 'react-slick'; import Div from '../Div'; import Team from '../Team'; export default function TeamSlider() { /** Team Member Data **/ const teamData = [ { memberImage: '/images/koushik.jpg', memberName: 'Koushik Avula', memberDesignation: 'Director', memberSocial: { }, }, { memberImage: '/images/sujith.jpg', memberName: 'Sujith Chereddy', memberDesignation: 'Director', memberSocial: { }, }, { memberImage: '/images/mounisha.jpg', memberName: 'Mounisha', memberDesignation: 'HR', memberSocial: { }, }, { memberImage: '/images/bhavya.jpg', memberName: 'Bhavya Konda', memberDesignation: 'Strategist', memberSocial: { }, }, { memberImage: '/images/husain.jpg', memberName: 'Husain Naqvi', memberDesignation: 'Graphic Designer', memberSocial: { }, }, { memberImage: '/images/gajanand.jpg', memberName: 'Ghajanand', memberDesignation: 'Graphic Designer', memberSocial: { }, }, { memberImage: '/images/pranati.jpg', memberName: 'Pranati Bhadrachalam', memberDesignation: 'CSM', memberSocial: { }, }, { memberImage: '/images/vishal.jpg', memberName: 'Vishal Bharadwaj', memberDesignation: 'Sr Developer', memberSocial: { }, }, { memberImage: '/images/praveen.jpg', memberName: 'Praveen K', memberDesignation: 'App Tester', memberSocial: { }, }, { memberImage: '/images/dilip.jpg', memberName: 'Dileep K', memberDesignation: 'Lead Analyst', memberSocial: { }, }, { memberImage: '/images/nidhi.jpg', memberName: 'Nidhi Reddy', memberDesignation: 'Sr Analyst', memberSocial: { }, }, { memberImage: '/images/swetha.jpg', memberName: 'Swetha Guntupalli ', memberDesignation: 'Full Stack Developer', memberSocial: { }, }, { memberImage: '/images/harika1.jpg', memberName: 'Harika Nidadavolu', memberDesignation: 'Business Operations Manager', memberSocial: { }, }, { memberImage: '/images/sanjay.jpg', memberName: 'Sanjay Korukonda', memberDesignation: 'Business Operations Manager', memberSocial: { }, }, { memberImage: '/images/saha.jpg', memberName: 'Satya Harika', memberDesignation: 'Private Equity Associate', memberSocial: { }, }, { memberImage: '/images/saha.jpg', memberName: 'Satya Harika', memberDesignation: 'Private Equity Associate', memberSocial: { }, }, ]; /** Slider Settings **/ const SlickArrowLeft = ({ currentSlide, slideCount, ...props }) => ( <div {...props} className={ 'slick-prev slick-arrow' + (currentSlide === 0 ? ' slick-disabled' : '') } aria-hidden="true" aria-disabled={currentSlide === 0 ? true : false} > <Icon icon="bi:arrow-left" /> </div> ); const SlickArrowRight = ({ currentSlide, slideCount, ...props }) => ( <div {...props} className={ 'slick-next slick-arrow' + (currentSlide === slideCount - 1 ? ' slick-disabled' : '') } aria-hidden="true" aria-disabled={currentSlide === slideCount - 1 ? true : false} > <Icon icon="bi:arrow-right" /> </div> ); const settings = { dots: false, infinite: true, speed: 500, slidesToShow: 4, slidesToScroll: 1, prevArrow: <SlickArrowLeft />, nextArrow: <SlickArrowRight />, responsive: [ { breakpoint: 1200, settings: { slidesToShow: 3, }, }, { breakpoint: 991, settings: { slidesToShow: 2, dots: true, arrows: false, }, }, { breakpoint: 500, settings: { slidesToShow: 1, dots: true, arrows: false, }, }, ], }; return ( <Slider {...settings} className="cs-gap-24 cs-arrow_style2"> {teamData.map((item, index) => ( <Div key={index}> <Team memberImage={item.memberImage} memberName={item.memberName} memberDesignation={item.memberDesignation} memberSocial={item.memberSocial} /> </Div> ))} </Slider> ); }
package application import ( "app/internal/handler" "app/internal/repository" "net/http" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" ) // NewDefault returns a new Default func NewDefault(addr string) (d *Default) { // default config defaultRouter := chi.NewRouter() defaultAddr := ":8080" if addr != "" { defaultAddr = addr } d = &Default{ rt: defaultRouter, addr: defaultAddr, } return } // Default is a struct that contains the default application type Default struct { // rt is the router of the server rt *chi.Mux // addr is the address of the server addr string } // TearDown tears down the default application func (d *Default) TearDown() (err error) { return } // SetUp sets up the default application func (d *Default) SetUp() (err error) { // dependencies // - repository: map rp := repository.NewProductMap(nil, 0) // - handler hd := handler.NewProduct(rp) // router // - middlewares d.rt.Use(middleware.Logger) d.rt.Use(middleware.Recoverer) // - routes / endpoints d.rt.Post("/product", hd.Create()) return } // Run runs the default application func (d *Default) Run() (err error) { err = http.ListenAndServe(d.addr, d.rt) return }
#ifndef BLOOPER_PLUGIN_COMPONENT_HPP #define BLOOPER_PLUGIN_COMPONENT_HPP #include <blooper/internal/abstract/abstract.hpp> BLOOPER_NAMESPACE_BEGIN class PluginComponent : public CoreComponentBase { public: BLOOPER_STATE_ID(PluginComponent); struct Options { } options; [[nodiscard]] explicit PluginComponent( AbstractCoreContext& context, State state, JucePluginRef plugin, Options options = {}); [[maybe_unused, nodiscard]] inline const JucePlugin& getPlugin() const noexcept; [[maybe_unused, nodiscard]] inline JucePluginConstRef getPluginRef() const noexcept; void resized() override; private: [[maybe_unused, nodiscard]] inline JucePlugin& getPlugin() noexcept; [[maybe_unused, nodiscard]] inline JucePluginRef getPluginRef() noexcept; JucePluginRef plugin; class Button : public juce::TextButton { public: explicit Button(PluginComponent* parent); void clicked(const juce::ModifierKeys& modifiers) override; private: PluginComponent* parent; } button; }; [[maybe_unused]] const JucePlugin& PluginComponent::getPlugin() const noexcept { return *plugin; } [[maybe_unused]] JucePlugin& PluginComponent::getPlugin() noexcept { return *plugin; } [[maybe_unused]] JucePluginConstRef PluginComponent::getPluginRef() const noexcept { return plugin; } [[maybe_unused]] JucePluginRef PluginComponent::getPluginRef() noexcept { return plugin; } BLOOPER_NAMESPACE_END #endif // BLOOPER_PLUGIN_COMPONENT_HPP
const express = require("express"); const path = require("path"); const dbPath = path.join(__dirname, "cricketTeam.db"); const { open } = require("sqlite"); const sqlite3 = require("sqlite3"); const app = express(); app.use(express.json()); db = null; const initializeDBAndServer = async () => { try { db = await open({ filename: dbPath, driver: sqlite3.Database, }); app.listen(3002, () => { console.log("Server Running"); }); } catch (e) { console.log(`DB:Error:${e.message}`); process.exit(1); } }; initializeDBAndServer(); const convertDbObjectToResponseObject = (dbObject) => { return { playerId: dbObject.player_id, playerName: dbObject.player_name, jerseyNumber: dbObject.jersey_number, role: dbObject.role, }; }; //GET Players API app.get("/players/", async (request, response) => { const getPlayersQuery = ` SELECT * FROM cricket_team ORDER BY player_id;`; const playersArray = await db.all(getPlayersQuery); response.send( playersArray.map((eachPlayer) => convertDbObjectToResponseObject(eachPlayer) ) ); }); //POST player API app.post("/players/", async (request, response) => { const playerDetails = request.body; const { playerName, jerseyNumber, role } = playerDetails; const addPlayerQuery = `INSERT INTO cricket_team(player_name,jersey_number,role) VALUES ('${playerName}','${jerseyNumber}','${role}');`; await db.run(addPlayerQuery); response.send("Player Added to Team"); }); //GET player API app.get("/players/:playerId/", async (request, response) => { const { playerId } = request.params; const getPlayerQuery = `SELECT * FROM cricket_team WHERE player_id=${playerId};`; const player = await db.get(getPlayerQuery); response.send(convertDbObjectToResponseObject(player)); }); //UPDATE player API app.put("/players/:playerId/", async (request, response) => { const { playerId } = request.params; const bookDetails = request.body; const { playerName, jerseyNumber, role } = bookDetails; const addPlayerQuery = `UPDATE cricket_team SET player_name='${playerName}',jersey_number='${jerseyNumber}',role='${role}' WHERE player_id=${playerId};`; await db.run(addPlayerQuery); response.send("Player Details Updated"); }); //DELETE Player API app.delete("/players/:playerId/", async (request, response) => { const { playerId } = request.params; const deleteBookQuery = `DELETE FROM cricket_team WHERE player_id=${playerId};`; await db.run(deleteBookQuery); response.send("Player Removed"); }); module.exports = app;
/** * \ingroup autobrew * * \file autobrew.c * \author Richard Hall (hallboyone@icloud.com) * \brief Local UI source * \version 1.0 * \date 2023-05-19 */ #include "machine_logic/autobrew.h" #include "pico/time.h" #include <stdlib.h> #include "utils/macros.h" /** * \brief A single leg of an autobrew routine. * Each leg has a mapping function that generates a pump power setting from a linear changing flowrate * defined by setpoint_start and setpoint_end. The leg will run until a timeout is reached or one * of any optional ending triggers return true. When first called, setup functions can be called to get * external components ready. */ typedef struct _autobrew_leg { autobrew_mapping mapping; /**< Which of the configured mappings to use. -1 is straight mapping. */ uint16_t setpoint_start; /**< Setpoint at start of leg. */ uint16_t setpoint_end; /**< Setpoint at end of leg. */ uint16_t timeout_ms; /**< Maximum duration of the leg in milliseconds. */ int32_t trigger_data[AUTOBREW_TRIGGER_MAX_NUM]; /**< Trigger values for the end of a leg (0 -> no trigger). */ autobrew_trigger triggers[AUTOBREW_TRIGGER_MAX_NUM]; /**< Trigger values for the end of a leg (0 -> no trigger). */ autobrew_setup_fun setup_funs[AUTOBREW_SETUP_FUN_MAX_NUM]; /**< All the setup functions to run at start of leg. */ } autobrew_leg; static autobrew_leg _routine[AUTOBREW_LEG_MAX_NUM]; /**< Array for storing all the configured legs of the routine. */ static uint8_t _num_legs = 0; /**< The number of legs that have been configured. */ static uint8_t _current_leg = 0; /**< The leg the routine is currently on. */ static absolute_time_t _leg_end_time; /**< The timeout for the current leg. nil_time if leg has ended. */ static uint8_t _current_power; /**< The latest power computed in the routine. */ static bool _pump_changed; /**< Flag indicating if the pump has changed between ticks. */ /** * \brief Initialize all leg struct values to 0 or NULL. * \param leg_idx Index of leg that will be cleared */ static void _autobrew_clear_leg_struct(uint8_t leg_idx){ _routine[leg_idx].setpoint_start = 0; _routine[leg_idx].setpoint_end = 0; _routine[leg_idx].timeout_ms = 0; for (uint8_t i = 0; i < AUTOBREW_TRIGGER_MAX_NUM; i++){ _routine[leg_idx].trigger_data[i] = 0; _routine[leg_idx].triggers[i] = NULL; } for (uint8_t i = 0; i < AUTOBREW_SETUP_FUN_MAX_NUM; i++){ _routine[leg_idx].setup_funs[i] = NULL; } _routine[leg_idx].mapping = NULL; } /** * \brief Computes the current setpoint of the leg */ static uint16_t _autobrew_get_current_setpoint(){ const int64_t t_remaining_ms = absolute_time_diff_us(get_absolute_time(), _leg_end_time)/1000; if (t_remaining_ms < 0){ return _routine[_current_leg].setpoint_end; } else { const int16_t c = _routine[_current_leg].setpoint_end - _routine[_current_leg].setpoint_start; return _routine[_current_leg].setpoint_start + c - (c * t_remaining_ms)/(_routine[_current_leg].timeout_ms); } } /** * \brief Takes a leg and updates the state based on the current time. * \return True if leg has ended. Else false. */ static bool _autobrew_leg_tick(){ // If at end of routine, just set state to known value and exit if(_current_leg == _num_legs){ _current_power = 0; return false; } autobrew_leg * cl = &_routine[_current_leg]; // First time leg has ticked? if(is_nil_time(_leg_end_time)){ // Save timeout for leg _leg_end_time = make_timeout_time_ms(cl->timeout_ms); // Run all startup functions for leg for(uint8_t i = 0; i < AUTOBREW_SETUP_FUN_MAX_NUM; i++){ if(cl->setup_funs[i] == NULL) break; cl->setup_funs[i](); } } // Check if leg has finished bool leg_finished = absolute_time_diff_us(get_absolute_time(), _leg_end_time) <= 0; for(uint8_t i = 0; i < AUTOBREW_TRIGGER_MAX_NUM; i++){ if(leg_finished){ _leg_end_time = nil_time; _current_leg += 1; _current_power = 0; return true; } if(cl->triggers[i] == NULL) break; leg_finished = cl->triggers[i](cl->trigger_data[i]) ; } // Get new pump setting. const uint16_t setpoint = _autobrew_get_current_setpoint(); _current_power = (cl->mapping == NULL ? setpoint : cl->mapping(setpoint)); assert(_current_power <= AUTOBREW_PUMP_POWER_MAX); return false; } void autobrew_init(){ _num_legs = 0; autobrew_reset(); } uint8_t autobrew_add_leg(autobrew_mapping mapping, uint16_t setpoint_start, uint16_t setpoint_end, uint16_t timeout_ms){ assert(_num_legs < AUTOBREW_LEG_MAX_NUM); _autobrew_clear_leg_struct(_num_legs); _routine[_num_legs].mapping = mapping; _routine[_num_legs].setpoint_start = setpoint_start; _routine[_num_legs].setpoint_end = setpoint_end; _routine[_num_legs].timeout_ms = timeout_ms; _num_legs += 1; return (_num_legs-1); } void autobrew_leg_add_trigger(uint8_t leg_id, autobrew_trigger trigger, int32_t trigger_data){ assert(leg_id < AUTOBREW_LEG_MAX_NUM); for(uint8_t i = 0; i < AUTOBREW_TRIGGER_MAX_NUM; i++){ if(_routine[leg_id].triggers[i] == NULL){ _routine[leg_id].triggers[i] = trigger; _routine[leg_id].trigger_data[i] = trigger_data; return; } } assert(false); // If we reach this line, we have no more trigger slots } void autobrew_leg_add_setup_fun(uint8_t leg_id, autobrew_setup_fun setup_fun){ assert(leg_id < AUTOBREW_LEG_MAX_NUM); for(uint8_t i = 0; i < AUTOBREW_SETUP_FUN_MAX_NUM; i++){ if(_routine[leg_id].setup_funs[i] == NULL){ _routine[leg_id].setup_funs[i] = setup_fun; return; } } assert(false); // If we reach this line, we have no more setup function slots } bool autobrew_routine_tick(){ uint8_t previous_power = _current_power; // tick until reaching a leg with work left to do or end of routine while(_autobrew_leg_tick()) tight_loop_contents(); _pump_changed = (_current_power!=previous_power); return autobrew_finished(); } uint8_t autobrew_pump_power(){ return _current_power; } bool autobrew_pump_changed(){ return _pump_changed; } int8_t autobrew_current_leg(){ return (autobrew_finished() ? -1 : _current_leg); } bool autobrew_finished(){ return _current_leg == _num_legs; } void autobrew_reset(){ _current_leg = 0; _leg_end_time = nil_time; _current_power = 0; _pump_changed = false; }
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { IDiseaseRepository } from 'src/domain/repositories/diseaseRepository.interface'; import { Repository } from 'typeorm'; import { DiseaseEntity } from '../entities/disease.entity'; import { DiseaseModel } from 'src/domain/model/disease.model'; @Injectable() export class DiseaseRepository implements IDiseaseRepository { constructor( @InjectRepository(DiseaseEntity) private DiseaseRepository: Repository<DiseaseEntity>, ) {} async findAllDisease(): Promise<any[]> { const result = await this.DiseaseRepository.find({ where: { isActive: true, }, }); return result.map((item) => this.toModel(item)); } private toModel(data: DiseaseEntity): DiseaseModel { const model: DiseaseModel = new DiseaseModel(data); return model; } }
package com.vedruna.appletterboxdproyectofinal.ui.activities; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.vedruna.appletterboxdproyectofinal.R; import com.vedruna.appletterboxdproyectofinal.dto.MovieListDTO; import com.vedruna.appletterboxdproyectofinal.network.ApiService; import com.vedruna.appletterboxdproyectofinal.network.RetrofitClient; import com.vedruna.appletterboxdproyectofinal.ui.adapters.ManageMovieListsAdapter; import com.vedruna.appletterboxdproyectofinal.utils.TokenManager; import java.io.IOException; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class ManageMovieListsActivity extends AppCompatActivity implements ManageMovieListsAdapter.OnManageListListener { private static final String TAG = "ManageMovieListsActivity"; private RecyclerView recyclerView; private ManageMovieListsAdapter adapter; private Long filmId; // ID de la película actual private String username; // Nombre de usuario del usuario actualmente logueado @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_manage_movie_lists); filmId = getIntent().getLongExtra("filmId", -1); username = TokenManager.getInstance(this).getUsername(); // Obtiene el nombre de usuario logueado recyclerView = findViewById(R.id.listsRecyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); adapter = new ManageMovieListsAdapter(new ArrayList<>(), this); recyclerView.setAdapter(adapter); fetchMovieLists(); Button createNewListButton = findViewById(R.id.createNewListButton); createNewListButton.setOnClickListener(v -> showCreateListDialog()); } private void fetchMovieLists() { ApiService apiService = RetrofitClient.getApiService(this); Call<List<MovieListDTO>> call = apiService.getMovieListsByUsername(username); call.enqueue(new Callback<List<MovieListDTO>>() { @Override public void onResponse(Call<List<MovieListDTO>> call, Response<List<MovieListDTO>> response) { if (response.isSuccessful() && response.body() != null) { adapter.updateItems(response.body()); } else { Toast.makeText(ManageMovieListsActivity.this, "Failed to fetch lists", Toast.LENGTH_SHORT).show(); Log.e(TAG, "Failed to fetch lists: " + response.message()); if (response.errorBody() != null) { try { Log.e(TAG, "Error body: " + response.errorBody().string()); } catch (IOException e) { e.printStackTrace(); } } } } @Override public void onFailure(Call<List<MovieListDTO>> call, Throwable t) { Toast.makeText(ManageMovieListsActivity.this, "Failed to fetch lists", Toast.LENGTH_SHORT).show(); Log.e(TAG, "Failed to fetch lists: " + t.getMessage(), t); } }); } private void showCreateListDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Create New List"); View view = getLayoutInflater().inflate(R.layout.dialog_edit_list, null); builder.setView(view); EditText listNameEditText = view.findViewById(R.id.editListName); EditText listDescriptionEditText = view.findViewById(R.id.editListDescription); builder.setPositiveButton("Create", (dialog, which) -> { String name = listNameEditText.getText().toString().trim(); String description = listDescriptionEditText.getText().toString().trim(); createMovieList(new MovieListDTO(null, name, username, null, description, false, new ArrayList<>())); // Usa el nombre de usuario }); builder.setNegativeButton("Cancel", null); builder.show(); } private void createMovieList(MovieListDTO movieListDTO) { ApiService apiService = RetrofitClient.getApiService(this); Call<MovieListDTO> call = apiService.createMovieList(movieListDTO); call.enqueue(new Callback<MovieListDTO>() { @Override public void onResponse(Call<MovieListDTO> call, Response<MovieListDTO> response) { if (response.isSuccessful() && response.body() != null) { fetchMovieLists(); // Refresh the list Toast.makeText(ManageMovieListsActivity.this, "List created", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ManageMovieListsActivity.this, "Failed to create list", Toast.LENGTH_SHORT).show(); Log.e(TAG, "Failed to create list: " + response.message()); if (response.errorBody() != null) { try { Log.e(TAG, "Error body: " + response.errorBody().string()); } catch (IOException e) { e.printStackTrace(); } } } } @Override public void onFailure(Call<MovieListDTO> call, Throwable t) { Toast.makeText(ManageMovieListsActivity.this, "Failed to create list", Toast.LENGTH_SHORT).show(); Log.e(TAG, "Failed to create list: " + t.getMessage(), t); } }); } @Override public void onAddMovieToList(MovieListDTO movieList) { Log.d(TAG, "Adding film to list: " + movieList.getListId()); ApiService apiService = RetrofitClient.getApiService(this); Call<MovieListDTO> call = apiService.addFilmToList(movieList.getListId(), filmId); call.enqueue(new Callback<MovieListDTO>() { @Override public void onResponse(Call<MovieListDTO> call, Response<MovieListDTO> response) { if (response.isSuccessful() && response.body() != null) { fetchMovieLists(); // Refresh the list Toast.makeText(ManageMovieListsActivity.this, "Film added to list", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ManageMovieListsActivity.this, "Failed to add film to list", Toast.LENGTH_SHORT).show(); Log.e(TAG, "Failed to add film to list: " + response.message()); if (response.errorBody() != null) { try { Log.e(TAG, "Error body: " + response.errorBody().string()); } catch (IOException e) { e.printStackTrace(); } } } } @Override public void onFailure(Call<MovieListDTO> call, Throwable t) { Toast.makeText(ManageMovieListsActivity.this, "Failed to add film to list", Toast.LENGTH_SHORT).show(); Log.e(TAG, "Failed to add film to list: " + t.getMessage(), t); } }); } @Override public void onDeleteList(MovieListDTO movieList) { Log.d(TAG, "Deleting list: " + movieList.getListId()); ApiService apiService = RetrofitClient.getApiService(this); Call<Void> call = apiService.deleteMovieList(movieList.getListId()); call.enqueue(new Callback<Void>() { @Override public void onResponse(Call<Void> call, Response<Void> response) { if (response.isSuccessful()) { fetchMovieLists(); // Refresh the list Toast.makeText(ManageMovieListsActivity.this, "List deleted", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ManageMovieListsActivity.this, "Failed to delete list", Toast.LENGTH_SHORT).show(); Log.e(TAG, "Failed to delete list: " + response.message()); if (response.errorBody() != null) { try { Log.e(TAG, "Error body: " + response.errorBody().string()); } catch (IOException e) { e.printStackTrace(); } } } } @Override public void onFailure(Call<Void> call, Throwable t) { Toast.makeText(ManageMovieListsActivity.this, "Failed to delete list", Toast.LENGTH_SHORT).show(); Log.e(TAG, "Failed to delete list: " + t.getMessage(), t); } }); } @Override public void onRemoveMovieFromList(MovieListDTO movieList) { Log.d("ManageMovieListsActivity", "Removing film from list: " + movieList.getListId() + " Film ID: " + filmId); if (movieList.getListId() == null) { Log.e("ManageMovieListsActivity", "List ID is null. Cannot remove film."); Toast.makeText(this, "List ID is null. Cannot remove film.", Toast.LENGTH_SHORT).show(); return; } ApiService apiService = RetrofitClient.getApiService(this); Call<MovieListDTO> call = apiService.removeFilmFromList(movieList.getListId(), filmId); call.enqueue(new Callback<MovieListDTO>() { @Override public void onResponse(Call<MovieListDTO> call, Response<MovieListDTO> response) { if (response.isSuccessful() && response.body() != null) { fetchMovieLists(); // Refresh the list Toast.makeText(ManageMovieListsActivity.this, "Film removed from list", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ManageMovieListsActivity.this, "Failed to remove film from list", Toast.LENGTH_SHORT).show(); Log.e("ManageMovieListsActivity", "Failed to remove film from list: " + response.message()); if (response.errorBody() != null) { try { Log.e("ManageMovieListsActivity", "Error body: " + response.errorBody().string()); } catch (IOException e) { e.printStackTrace(); } } } } @Override public void onFailure(Call<MovieListDTO> call, Throwable t) { Toast.makeText(ManageMovieListsActivity.this, "Failed to remove film from list", Toast.LENGTH_SHORT).show(); Log.e("ManageMovieListsActivity", "Failed to remove film from list: " + t.getMessage(), t); } }); } }
// import React, { useEffect, useState } from "react"; // import { FiCheckSquare, FiX } from "react-icons/fi"; // import { AnimatePresence, motion } from "framer-motion"; // const SlideInNotifications = () => { // const [notifications, setNotifications] = useState([]); // const removeNotif = (id) => { // setNotifications((pv) => pv.filter((n) => n.id !== id)); // }; // return ( // <div className="bg-white min-h-[200px] flex items-center justify-center"> // <button // onClick={() => { // setNotifications((pv) => [generateRandomNotif(), ...pv]); // }} // className="text-sm text-white bg-indigo-500 hover:bg-indigo-600 active:scale-95 transition-all font-medium px-3 py-2 rounded" // > // Add notification // </button> // <div className="flex flex-col gap-1 w-72 fixed top-2 right-2 z-50 pointer-events-none"> // <AnimatePresence> // {notifications.map((n) => ( // <Notification removeNotif={removeNotif} {...n} key={n.id} /> // ))} // </AnimatePresence> // </div> // </div> // ); // }; // const NOTIFICATION_TTL = 5000; // const Notification = ({ text, id, removeNotif }) => { // useEffect(() => { // const timeoutRef = setTimeout(() => { // removeNotif(id); // }, NOTIFICATION_TTL); // return () => clearTimeout(timeoutRef); // }, []); // return ( // <motion.div // layout // initial={{ y: -15, scale: 0.95 }} // animate={{ y: 0, scale: 1 }} // exit={{ x: "100%", opacity: 0 }} // transition={{ duration: 0.35, ease: "easeOut" }} // className="p-2 flex items-start rounded gap-2 text-xs font-medium shadow-lg text-white bg-indigo-500 pointer-events-auto" // > // <FiCheckSquare className=" mt-0.5" /> // <span>{text}</span> // <button onClick={() => removeNotif(id)} className="ml-auto mt-0.5"> // <FiX /> // </button> // </motion.div> // ); // }; // export default SlideInNotifications; // const generateRandomNotif = () => { // const names = [ // "John Anderson", // "Emily Peterson", // "Frank Daniels", // "Laura Williams", // "Donald Sanders", // "Tom Smith", // "Alexandra Black", // ]; // const randomIndex = Math.floor(Math.random() * names.length); // const data = { // id: Math.random(), // text: `New notification from ${names[randomIndex]}`, // }; // return data; // };
<!DOCTYPE html> <html lang="pl"> <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 rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/1.0.0/modern-normalize.min.css" /> <link rel="stylesheet" href="./css/main.min.css" /> <link href="https://fonts.googleapis.com/css2?family=Raleway:wght@700&family=Roboto:wght@400;500;700;900&display=swap" rel="stylesheet" /> <title>Studio</title> </head> <body> <header class="header"> <div class="container"> <div class="header__items"> <a href="index.html" class="logo" ><span class="logo--blue">Web</span>Studio</a > <nav class="navigation"> <ul class="list navigation__list"> <li> <a href="./index.html" class="navigation__link navigation__link--active">Agencja</a> </li> <li> <a href="./portfolio.html" class="navigation__link">Portfolio</a> </li> <li> <a href="./kontakt.html" class="navigation__link">Kontakt</a> </li> </ul> </nav> <nav class="mobile-nav"> <button type="button" class="mobile-nav__button menu-toggle js-open-menu"> <svg class="mobile-nav__icon" width="24" height="16"> <use href="./images/sprite.svg#icon-menu_24px"></use> </svg> </button> </nav> <div class="mobile-menu js-menu-container"> <button type="button" class="mobile-menu__x-button menu-toggle js-close-menu" aria-expanded="false" aria-controls="mobile-menu"> <svg class="mobile-menu__icon" width="40px" height="40px"> <use href="./images/sprite.svg#icon-close_40px"></use> </svg> </button> <ul class="list mobile-menu__list"> <li class="mobile-menu__item"><a href="./index.html" class="mobile-menu__link">Agencja</a> </li> <li class="mobile-menu__item"><a href="./portfolio.html" class="mobile-menu__link">Portfolio</a> </li> <li class="mobile-menu__item"><a href=# class="mobile-menu__link">Kontakt</a> </li> </ul> <ul class="list contact-list--mobile"> <li class="contact-list__item--mobile"> <a href="tel:+48111111111" class="mobile-menu__link contact-list__link--mobile"> +48 111 111 111</a > </li> <li class="contact-list__item--mobile"> <a href="mailto:info@devstudio.com" class="mobile-menu__link contact-list__link--mobile" > info@devstudio.com</a > </li> </ul> <ul class="list social"> <li class="social__link"><a href=# target=_blank class="mobile-menu__link">Instagram</a></li> <li class="social__link"><a href=# target=_blank class="mobile-menu__link">Twitter</a></li> <li class="social__link"><a href=# target=_blank class="mobile-menu__link">Facebook</a></li> <li class="social__link"><a href=# target=_blank class="mobile-menu__link">LinkedIn</a></li> </ul> </div> <ul class="list contact-list"> <li> <a href="mailto:info@devstudio.com" class="contact-list__link" > <svg class="contact-list__icon" width="16" height="12"> <use href="./images/sprite.svg#icon-envelope"></use> </svg> info@devstudio.com</a > </li> <li> <a href="tel:+48111111111" class="contact-list__link"> <svg class="contact-list__icon" width="20" height="32"> <use href="./images/sprite.svg#icon-smartphone"></use> </svg> +48 111 111 111</a > </li> </ul> </div> </div> </header> <main> <section class="intro section"> <div class="intro__items container"> <h1 class="intro__header"> Efektywne rozwiązania <br /> dla Waszego biznesu </h1> <button type="button" class="button" data-modal-open>Zamów usługę</button> <div class="backdrop is-hidden" data-modal> <div class="modal__content"> <button type="button" class="modal__x-button" data-modal-close> <svg width="11" height="11"><use href="./images/sprite.svg#icon-Vector"></use></svg> </button> <h2 class="modal__header"> Zostaw swoje dane w formularzu poniżej </h2> <form class="modal__form" name="modal-form"> <label class="form__label"> Imię <fieldset class="form__fieldset"> <svg class="form__icon" width="18" height="18"> <use href="./images/sprite.svg#icon-person-black-18dp-1"></use> </svg> <input class="form__input" type="text" name="name" minlength="2" maxlength="50"> </fieldset> </label> <label class="form__label"> Telefon <fieldset class="form__fieldset"> <svg class="form__icon" width="18" height="18"> <use href="./images/sprite.svg#icon-phone-black-18dp-1"></use> </svg> <input class="form__input" type="tel" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{3}" title="Format numeru 123-456-789"> </fieldset> </label> <label class="form__label"> E-mail <fieldset class="form__fieldset"> <svg class="form__icon" width="18" height="18"> <use href="./images/sprite.svg#icon-email-black-18dp-1"></use> </svg> <input class="form__input" type="email" name="mail"> </fieldset> </label> <label class="form__label form__comment-field"> Komentarz <textarea class="form__textarea" name="comment" rows="5" maxlength="500" placeholder="Wprowadź tekst"></textarea> </label> <fieldset class="form__checkbox-fieldset"> <label> <svg class="form__checkbox-icon" width="16" height="15"> <use href="./images/sprite.svg#icon-icon-check"></use> </svg> <input class="form__checkbox" type="checkbox" name="agreements"> Oświadczam iż akceptuję <a href="#" class="form__link">Regulamin</a> i <a href="#" class="form__link">Politykę prywatności</a>. </label> </fieldset> <button type="submit" class="button form__button">Wyślij</button> </form> </div> </div> </div> </section> <section class="lorem-section section"> <div class="container"> <ul class="list lorem-section__list"> <li class="lorem-section__item"> <div class="lorem-section__icon"> <svg width="70" height="70"> <use href="./images/sprite.svg#icon-antenna"></use> </svg> </div> <h3 class="lorem-section__title">Lorem, ipsum.</h3> <p class="lorem-section__text"> Lorem ipsum dolor sot amet consectetur adipisicing elit. Atque, ipsa sit! In natus desrunt ab modi corporis! Velit, cum. </p> </li> <li class="lorem-section__item"> <div class="lorem-section__icon"> <svg width="70" height="70"> <use href="./images/sprite.svg#icon-diagram"></use> </svg> </div> <h3 class="lorem-section__title">Lorem, ipsum.</h3> <p class="lorem-section__text"> Lorem ipsum dolor sot amet consectetur adipisicing elit. Atque, ipsa sit! In natus desrunt ab modi corporis! Velit, cum. </p> </li> <li class="lorem-section__item"> <div class="lorem-section__icon"> <svg width="70" height="70"> <use href="./images/sprite.svg#icon-clock"></use> </svg> </div> <h3 class="lorem-section__title">Lorem, ipsum.</h3> <p class="lorem-section__text"> Lorem ipsum dolor sot amet consectetur adipisicing elit. Atque, ipsa sit! In natus desrunt ab modi corporis! Velit, cum. </p> </li> <li class="lorem-section__item"> <div class="lorem-section__icon"> <svg width="70" height="70"> <use href="./images/sprite.svg#icon-astronaut"></use> </svg> </div> <h3 class="lorem-section__title">Lorem, ipsum.</h3> <p class="lorem-section__text"> Lorem ipsum dolor sot amet consectetur adipisicing elit. Atque, ipsa sit! In natus desrunt ab modi corporis! Velit, cum. </p> </li> </ul> </div> </section> <section class="skills-section section"> <div class="container"> <h2 class="skills-section__header">Czym się zajmujemy</h2> <ul class="list skills-section__list"> <li class="skills-section__item"> <img class="skills-section__img" alt="Pisanie kodu" src="./images/ourskills1@1x.webp" srcset="./images/ourskills1@2x.webp 2x" sizes="370, 294" /> <div class="skills-section__description"> <p> Aplikacje komputerowe </p> </div> </li> <li class="skills-section__item"> <img class="skills-section__img" src="./images/ourskills2@1x.webp" srcset="./images/ourskills2@2x.webp 2x" sizes="370, 294" /> <div class="skills-section__description"> <p> Aplikacje mobline </p> </div> </li> <li class="skills-section__item"> <img class="skills-section__img" src="./images/ourskills3@1x.webp" srcset="./images/ourskills3@2x.webp 2x" sizes="370, 294" /> <div class="skills-section__description"> <p> Aplikacje graficzne </p> </div> </li> </ul> </div> </section> <section class="team section"> <div class="container"> <h2 class="team__header">Nasz zespół</h2> <ul class="list team__list"> <li class="team-card"> <figure class="team-card__picture"> <img class="team-card__img" alt="That's our Product Designer" src="./images/person1mob@1x.webp" srcset="./images/person1mob@1x.webp 450w, ./images/person1mob@2x.webp 900w, ./images/person1tab@1x.webp 354w, ./images/person1tab@2x.webp 708w, ./images/person1desk@1x.webp 270w, ./images/person1desk@2x.webp 540w" sizes="(min-width: 1200px) 270px, (min-width: 768px) 354px, (min-width: 480px) 450px, 290px" /> <figcaption class="team-card__description"> <h3 class="team-card__name">John Doe</h3> <p class="team-card__text">Product Designer</p> <ul class="list team-card__socialmedia-list"> <li> <a class="socialmedia__link" href="#"> <svg class="socialmedia__icon" width="20" height="20"> <use href="./images/sprite.svg#icon-instagram"></use> </svg> </a> </li> <li> <a class="socialmedia__link" href="#"> <svg class="socialmedia__icon" width="20" height="20"> <use href="./images/sprite.svg#icon-twitter"></use> </svg> </a> </li> <li> <a class="socialmedia__link" href="#"> <svg class="socialmedia__icon" width="20" height="20"> <use href="./images/sprite.svg#icon-facebook"></use> </svg> </a> </li> <li> <a class="socialmedia__link" href="#"> <svg class="socialmedia__icon" width="20" height="20"> <use href="./images/sprite.svg#icon-linkedin"></use> </svg> </a> </li> </ul> </figcaption> </figure> </li> <li class="team-card"> <figure class="team-card__picture"> <img class="team-card__img" alt="That's our Frontend Developer" src="./images/person4mob@1x.webp" srcset="./images/person4mob@1x.webp 450w, ./images/person4mob@2x.webp 900w, ./images/person4tab@1x.webp 354w, ./images/person4tab@2x.webp 708w, ./images/person4desk@1x.webp 270w, ./images/person4desk@2x.webp 540w" sizes="(min-width: 1200px) 270px, (min-width: 768px) 354px, (min-width: 480px) 450px, 290px" /> <figcaption class="team-card__description"> <h3 class="team-card__name">John Doe</h3> <p class="team-card__text">Frontend Developer</p> <ul class="list team-card__socialmedia-list"> <li> <a class="socialmedia__link" href="#"> <svg class="socialmedia__icon" width="20" height="20"> <use href="./images/sprite.svg#icon-twitter"></use> </svg> </a> </li> <li> <a class="socialmedia__link" href="#"> <svg class="socialmedia__icon" width="20" height="20"> <use href="./images/sprite.svg#icon-facebook"></use> </svg> </a> </li> <li> <a class="socialmedia__link" href="#"> <svg class="socialmedia__icon" width="20" height="20"> <use href="./images/sprite.svg#icon-linkedin"></use> </svg> </a> </li> <li> <a class="socialmedia__link" href="#"> <svg class="socialmedia__icon" width="20" height="20"> <use href="./images/sprite.svg#icon-instagram"></use> </svg> </a> </li> </figcaption> </figure> </li> <li class="team-card"> <figure class="team-card__picture"> <img class="team-card__img" alt="That's our Marketing specialist" src="./images/person2mob@1x.webp" srcset="./images/person2mob@1x.webp 450w, ./images/person2mob@2x.webp 900w, ./images/person2tab@1x.webp 354w, ./images/person2tab@2x.webp 708w, ./images/person2desk@1x.webp 270w, ./images/person2desk@2x.webp 540w" sizes="(min-width: 1200px) 270px, (min-width: 768px) 354px, (min-width: 480px) 450px, 290px" /> <figcaption class="team-card__description"> <h3 class="team-card__name">John Doe</h3> <p class="team-card__text">Marketing</p> <ul class="list team-card__socialmedia-list"> <li> <a class="socialmedia__link" href="#"> <svg class="socialmedia__icon" width="20" height="20"> <use href="./images/sprite.svg#icon-instagram"></use> </svg> </a> </li> <li> <a class="socialmedia__link" href="#"> <svg class="socialmedia__icon" width="20" height="20"> <use href="./images/sprite.svg#icon-twitter"></use> </svg> </a> </li> <li> <a class="socialmedia__link" href="#"> <svg class="socialmedia__icon" width="20" height="20"> <use href="./images/sprite.svg#icon-facebook"></use> </svg> </a> </li> <li> <a class="socialmedia__link" href="#"> <svg class="socialmedia__icon" width="20" height="20"> <use href="./images/sprite.svg#icon-linkedin"></use> </svg> </a> </li> </ul> </figcaption> </figure> </li> <li class="team-card"> <figure class="team-card__picture"> <img class="team-card__img" alt="That's our Product Designer" src="./images/person3mob@1x.webp" srcset="./images/person3mob@1x.webp 450w, ./images/person3mob@2x.webp 900w, ./images/person3tab@1x.webp 354w, ./images/person3tab@2x.webp 708w, ./images/person3desk@1x.webp 270w, ./images/person3desk@2x.webp 540w" sizes="(min-width: 1200px) 270px, (min-width: 768px) 354px, (min-width: 480px) 450px, 290px" /> <figcaption class="team-card__description"> <h3 class="team-card__name">John Doe</h3> <p class="team-card__text">UI Designer</p> <ul class="list team-card__socialmedia-list"> <li> <a class="socialmedia__link" href="#"> <svg class="socialmedia__icon" width="20" height="20"> <use href="./images/sprite.svg#icon-instagram"></use> </svg> </a> </li> <li> <a class="socialmedia__link" href="#"> <svg class="socialmedia__icon" width="20" height="20"> <use href="./images/sprite.svg#icon-twitter"></use> </svg> </a> </li> <li> <a class="socialmedia__link" href="#"> <svg class="socialmedia__icon" width="20" height="20"> <use href="./images/sprite.svg#icon-facebook"></use> </svg> </a> </li> <li> <a class="socialmedia__link" href="#"> <svg class="socialmedia__icon" width="20" height="20"> <use href="./images/sprite.svg#icon-linkedin"></use> </svg> </a> </li> </ul> </figcaption> </figure> </li> </ul> </div> </section> <section class="ourclients section"> <div class="container"> <h2 class="ourclients__header">Nasi klienci</h2> <ul class="list ourclients__list"> <li> <a class="ourclients__link" href="#"> <svg class="ourclients__logo" width="106" height="60"> <use href="./images/sprite.svg#icon-logo1"></use> </svg> </a> </li> <li> <a class="ourclients__link" href="#"> <svg class="ourclients__logo" width="106" height="60"> <use href="./images/sprite.svg#icon-logo2"></use> </svg> </a> </li> <li> <a class="ourclients__link" href="#"> <svg class="ourclients__logo" width="106" height="60"> <use href="./images/sprite.svg#icon-logo3"></use> </svg> </a> </li> <li> <a class="ourclients__link" href="#"> <svg class="ourclients__logo" width="106" height="60"> <use href="./images/sprite.svg#icon-logo4"></use> </svg> </a> </li> <li> <a class="ourclients__link" href="#"> <svg class="ourclients__logo" width="106" height="60"> <use href="./images/sprite.svg#icon-logo5"></use> </svg> </a> </li> <li> <a class="ourclients__link" href="#"> <svg class="ourclients__logo" width="106" height="60"> <use href="./images/sprite.svg#icon-logo6"></use> </svg> </a> </li> </ul> </div> </section> </main> <footer class="section footer"> <div class="container list footer__items"> <div class="footer__address"> <a href="index.html" class="logo logo--footer" ><span class="logo--blue">Web</span>Studio</a > <ul class="list contact-list__footer"> <li> <address class="contact-list__address"> m. Warszawa, Aleje Jerozolimskie 21 </address> </li> <li> <a href="mailto:info@example.com" class="contact-list__link--footer" >info@example.com</a > </li> <li> <a href="tel:+48111111111" class="contact-list__link--footer" >+48 111 111 111</a > </li> </ul> </div> <div> <h2 class="footer__socialmedia-header">Dołącz do nas</h2> <ul class="list footer__socialmedia"> <li> <a class="socialmedia__link socialmedia__link--footer" href="#"> <svg class="socialmedia__icon" width="20" height="20"> <use href="./images/sprite.svg#icon-instagram"></use> </svg> </a> </li> <li> <a class="socialmedia__link socialmedia__link--footer" href="#"> <svg class="socialmedia__icon" width="20" height="20"> <use href="./images/sprite.svg#icon-twitter"></use> </svg> </a> </li> <li> <a class="socialmedia__link socialmedia__link--footer" href="#"> <svg class="socialmedia__icon" width="20" height="20"> <use href="./images/sprite.svg#icon-facebook"></use> </svg> </a> </li> <li> <a class="socialmedia__link socialmedia__link--footer" href="#"> <svg class="socialmedia__icon" width="20" height="20"> <use href="./images/sprite.svg#icon-linkedin"></use> </svg> </a> </li> </ul> </div> <div> <form class="newsletter"> <label> <h2 class="newsletter__label">Zapisz się do newslettera</h2> <input class="newsletter__input" type="email" name="newsletter-mail" placeholder="E-mail" required> </label> <button class="button newsletter__button" type="submit">Zapisz się <svg class="newsletter__send-icon" width="24" height="24"> <use href="./images/sprite.svg#icon-newsletter__send-icon"></use> </svg> </button> </form> </div> </div> </footer> <script src="./js/modal.js"></script> <script defer src="https://cdnjs.cloudflare.com/ajax/libs/body-scroll-lock/3.1.5/bodyScrollLock.min.js" integrity="sha512-HowizSDbQl7UPEAsPnvJHlQsnBmU2YMrv7KkTBulTLEGz9chfBoWYyZJL+MUO6p/yBuuMO/8jI7O29YRZ2uBlA==" crossorigin="anonymous" ></script> <script defer src="./js/mobile-menu.js"></script> </body> </html>
# Assignment - Surge Software Engineering Intern ## info - Link : [surgeintern.vercel.app](https://surgeintern.vercel.app) - Application Type: Web Application - Time spent building: 4 days ## stack ![Next JS](https://img.shields.io/badge/Next-black?style=for-the-badge&logo=next.js&logoColor=white) ![TypeScript](https://img.shields.io/badge/typescript-%23007ACC.svg?style=for-the-badge&logo=typescript&logoColor=white) ![Prisma](https://img.shields.io/badge/Prisma-3982CE?style=for-the-badge&logo=Prisma&logoColor=white) ![TailwindCSS](https://img.shields.io/badge/tailwindcss-%2338B2AC.svg?style=for-the-badge&logo=tailwind-css&logoColor=white) ![Playwright](https://img.shields.io/badge/Playwright-45ba4b?style=for-the-badge&logo=Playwright&logoColor=white) ![Postman](https://img.shields.io/badge/Postman-FF6C37?style=for-the-badge&logo=Postman&logoColor=white) ![Vercel](https://img.shields.io/badge/Vercel-000000?style=for-the-badge&logo=vercel&logoColor=white) ![Postgres](https://img.shields.io/badge/PostgreSQL-316192?style=for-the-badge&logo=postgresql&logoColor=white) - Next Auth - Authorization Library - Zod - Type validation Library ## requirements - [x] Authentication - Register and Login screens for authentication. - Integration of Captcha for login/registration forms. - Users can authenticate with their username/email and password. - Use an identity management solution for authentication. - Validation for all sorts of data and input fields. - [x] Protect pages - protected using middleware ["/posts","/profile"] - [x] Post Indexing depends on the time created and the no. of likes received - [x] End to End Test cases and Deploy using Github actions. - [x] Dockerize the entire application. (node, MySQL) ## challenges I faced challenges during the development process. They are, - **Writing Tests** - Even though I had experience developing web applications this is the first time I spend writing tests for an application with a auth provider. And I spend somewhere around 4 hours to figure out a workaround. The test can be run only in the development disabling the recaptcha from the .env. The login page provides the JWT session and without users cannot access the protected pages. - **CI/CD pipelines** - I am used to deploying applications on hosting services such as Vercel and Netlify using automatic deployment which does not require writing manual scripts. But I manage to work with Github Actions gaining a sound understanding. ## features - Infinite Scroll - Cursor-based scroll fetch requests posts on demand. - Relative Time - Relative time for posts based on Internationalization API. - Like/Removing a Like - Response behavior based on promises. - Posting - Users can post pictures using URLs to the images as the assignment does not encourage the usage of File Storages. ## software used - VS Code - Code Editor - Postman - API testing - Terminator - Terminal - Docker - Virtualization Software - Firefox/Chrome - Web browsers ## Commands - <code>yarn dev</code> - Starts development server (web) - <code>yarn test</code> - Run tests - <code>docker compose up --build</code> - Docker commands - <code>yarn studio</code> - Spin up Prisma studio using .env.local and dev.prisma schema - <code>yarn db:push</code> - Push model changes to the database using .env.local and dev.prisma - <code>yarn prisma db seed</code> - Seed the database ## proofs ### Github Actions ![image](https://github.com/0xbyt3z/surge-assignment/assets/40062006/658fc06e-fbc2-45e7-be02-e4359b46d971) ![image](https://github.com/0xbyt3z/surge-assignment/assets/40062006/c7bf54f3-7047-4fac-a9e6-8b890e14a57d) ### Tests ![Screenshot at 2023-08-22 15-22-16](https://github.com/0xbyt3z/surge-assignment/assets/40062006/cd8aa9ed-9570-4505-aa7b-e3c15dadaa6a) ![Screenshot at 2023-08-22 15-27-25](https://github.com/0xbyt3z/surge-assignment/assets/40062006/ea4834bd-cf75-4f52-866c-5da92617d192)
import React, {useState} from 'react'; import './Forecast.css'; import TabNavigator from '../TabNavigator/TabNavigator'; import HourlyCard from './ForecastCard/HourlyCard/HourlyCard'; import WeeklyCard from './ForecastCard/WeeklyCard/WeeklyCard'; import Spinner from '../Spinner/Spinner'; const Forecast = props => { const [value,setValue] = useState(0); const tabNavigatorHandler = (value) => { setValue(value); }; let weeklyData = <Spinner /> let hourlyData = <Spinner /> if (props.hourlyData) { hourlyData = ( props.hourlyData.map(item => ( <HourlyCard key={item.dt} time={item.dt} temp={item.temp} pressure={item.pressure} humidity={item.humidity} clouds={item.clouds} wind={item.wind_speed} weather={item.weather} /> )) ) }; if (props.weeklyData) { weeklyData = ( props.weeklyData.map(item => ( <WeeklyCard key={item.dt} date={item.dt} temp={item.temp} pressure={item.pressure} humidity={item.humidity} clouds={item.clouds} wind={item.wind_speed} weather={item.weather} /> )) ) }; return ( <div className='Forecast'> <h2 className='LocationName'>{props.locationName}</h2> <TabNavigator value={value} changed={(_,value)=>tabNavigatorHandler(value)} /> {value === 0 ? hourlyData : weeklyData} </div> ); } export default Forecast;
import { Injectable } from '@angular/core'; import { Network } from '@capacitor/network'; import { ToastService } from './toast.service'; import { Directory, Filesystem } from '@capacitor/filesystem'; import * as JSZip from 'jszip'; import { DbService } from './db.service'; import { FilesystemService } from './filesystem.service'; @Injectable({ providedIn: 'root' }) export class DownloadService { databaseName = "oficinavirtual.db"; endpoint: string = "https://appgp.mjhudesings.com/slim/test-download"; nombre: string = "salida.zip"; private directorioTmp: string = 'temp'; constructor( private filesystemService: FilesystemService, private toastService: ToastService, private dbService: DbService ) { } public async descargarYDescomprimirPaqueteDatos() { const hayConexion = (await Network.getStatus()).connected; if(hayConexion){ const paqueteDescargado = await this.descargarPaquete(); if(paqueteDescargado){ const paqueteDescomprimido = await this.descomprimirPaquete(); if(paqueteDescomprimido){ const baseDeDatosMovida = await this.moverBaseDeDatos(); if(baseDeDatosMovida){ const conectado = await this.dbService.connectDatabase(); if(conectado){ return true; }else{ this.toastService.mostrarToast('No se ha podido conectar con la base de datos.', 1500, 'bottom', 'baseline'); return false; } }else{ this.toastService.mostrarToast('Ha ocurrido un error al mover la base de datos a la memoria interna.', 1500, 'bottom', 'baseline'); return false; } }else{ this.toastService.mostrarToast('Ha ocurrido un error al descomprimir el paquete.', 1500, 'bottom', 'baseline'); return false; } }else{ this.toastService.mostrarToast('Ha ocurrido un error al descargar el paquete de datos.', 1500, 'bottom', 'baseline'); return false; } }else{ this.toastService.mostrarToast('No tienes conexión a Internet.', 1500, 'bottom', 'baseline'); return false; } } public async descargarPaquete() { this.toastService.mostrarToast('Descargando paquete de datos', 1500, 'bottom', 'baseline'); this.filesystemService.crearDirectorioTmp(); const downloadResult = await this.filesystemService.descargarFichero(this.directorioTmp + "/" + this.nombre, this.endpoint, Directory.External).then(()=>{ return true; }).catch(()=>{ return false; }); return downloadResult; } public async descomprimirPaquete() { const zipData = await this.filesystemService.leerFichero(this.directorioTmp + "/" + this.nombre, Directory.External); const zip = new JSZip(); const zipContent = await zip.loadAsync(zipData.data, { base64: true }); const result = await zipContent.file(this.databaseName); if (result) { return await this.filesystemService.crearFichero(this.databaseName, Directory.External, await result.async('base64'), true).then(()=>{ return true; }).catch(()=>{ return false; }); } else { return false; } } public async moverBaseDeDatos() { const result = await this.filesystemService.copiarBBDDExternaAInterna(this.dbService.nombreDB); if (result) { return await this.dbService.moverBBDDAInterna(); } else { return false; } } }
import { it, expect, describe } from '@jest/globals'; import buildOrder from '../src/buildOrder'; import { Node } from '../src/Node'; describe('buildOrder', () => { it('should return empty array for empty input', () => { const expected: string[] = []; const result = buildOrder([], []); expect(result).toEqual(expected); }); it('should return empty array for empty input', () => { const expected: string[] = []; const result = buildOrder([], ['a']); expect(result).toEqual(expected); }); it(`should return ['a']`, () => { const expected: string[] = ['a']; const result = buildOrder(['a'], []); expect(result).toEqual(expected); }); it(`should return ['a', 'b']`, () => { const expected: string[] = ['a', 'b']; const result = buildOrder(['a', 'b'], [['a', 'b']]); expect(result).toEqual(expected); }); it(`should return ['a', 'b', 'c']`, () => { const expected: string[] = ['a', 'b', 'c']; const result = buildOrder( ['a', 'b', 'c'], [ ['a', 'b'], ['a', 'c'], ] ); expect(result).toEqual(expected); }); it(`should return ['a', 'b', 'c', 'd']`, () => { const expected: string[] = ['a', 'b', 'c', 'd']; const result = buildOrder( ['a', 'b', 'c', 'd'], [ ['a', 'b'], ['a', 'c'], ['c', 'd'], ] ); expect(result).toEqual(expected); }); it(`should throw an error`, () => { const fn = () => buildOrder(['a', 'e'], [['e', 'e']]); expect(fn).toThrow(); }); });
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <title>Kelly Bootstrap Template - Index</title> <meta content="" name="description"> <meta content="" name="keywords"> <!-- Favicons --> <link href="{% static '' %}assets/img/favicon.png" rel="icon"> <link href="{% static '' %}assets/img/apple-touch-icon.png" rel="apple-touch-icon"> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Raleway:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet"> <!-- Vendor CSS Files --> <link href="{% static '' %}assets/vendor/aos/aos.css" rel="stylesheet"> <link href="{% static '' %}assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link href="{% static '' %}assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet"> <link href="{% static '' %}assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet"> <link href="{% static '' %}assets/vendor/glightbox/css/glightbox.min.css" rel="stylesheet"> <link href="{% static '' %}assets/vendor/swiper/swiper-bundle.min.css" rel="stylesheet"> <!-- Template Main CSS File --> <link href="{% static '' %}assets/css/style.css" rel="stylesheet"> </head> <body> <!-- ======= Header ======= --> <header id="header" class="fixed-top"> <div class="container-fluid d-flex justify-content-between align-items-center"> <h1 class="logo me-auto me-lg-0"><a href="index.html">Kelly</a></h1> <!-- Uncomment below if you prefer to use an image logo --> <!-- <a href="index.html" class="logo"><img src="assets/img/logo.png" alt="" class="img-fluid"></a>--> <nav id="navbar" class="navbar order-last order-lg-0"> <ul> <li><a class="active" href="{% url 'home' %}">Home</a></li> <li><a href="{% url 'about' %}">About</a></li> <li><a href="{% url 'shop' %}">Shop</a></li> <li><a href="{% url 'blog' %}">Blog</a></li> <li><a href="{% url 'contact' %}">Contact</a></li> {% if user.is_authenticated %} <li><a href="{% url 'logout' %}">LogOut</a></li> <li><a href="{% url 'profile' %}">Profile</a></li> {% else %} <li><a data-bs-toggle="modal" href="#exampleModalToggle" role="button">SignUp/LogIn</a></li> {% endif %} </ul> <i class="bi bi-list mobile-nav-toggle"></i> </nav><!-- .navbar --> <div class="header-social-links"> <a href="#" class="twitter"><i class="bi bi-twitter"></i></a> <a href="#" class="facebook"><i class="bi bi-facebook"></i></a> <a href="#" class="instagram"><i class="bi bi-instagram"></i></a> <a href="#" class="linkedin"><i class="bi bi-linkedin"></i></i></a> </div> </div> </header><!-- End Header --> <!-- SingUp modal --> <div class="modal fade" id="exampleModalToggle" aria-hidden="true" aria-labelledby="exampleModalToggleLabel" tabindex="-1"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalToggleLabel">Sign In</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form id="login-form" action="{% url 'login' %}" method="post" class=""> {% csrf_token %} <div class="form-floating mb-3"> <input type="text" name="username" class="form-control rounded-3" id="floatingInput" placeholder="UserName"> <label for="floatingInput">Username</label> </div> <div class="form-floating mb-3"> <input type="password" name="password" class="form-control rounded-3" id="floatingPassword" placeholder="Password"> <label for="floatingPassword">Password</label> </div> <button class="w-100 mb-2 btn btn-lg rounded-3 btn-primary" type="submit">LogIn</button> <small class="text-muted">Forgot your password? click here</small> <hr class="my-4"> </form> </div> <div class="modal-footer"> <button class="btn btn-primary" data-bs-target="#exampleModalToggle2" data-bs-toggle="modal">have not an account?? Register here</button> </div> </div> </div> </div> <div class="modal fade" id="exampleModalToggle2" aria-hidden="true" aria-labelledby="exampleModalToggleLabel2" tabindex="-1"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalToggleLabel2">SignUp</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form id="register-form" method="post" action="{% url 'register' %}" class=""> {% csrf_token %} <div class="form-floating mb-3"> <input type="text" name="username" class="form-control rounded-3" id="floatingInput" placeholder="UserName"> <label for="floatingInput">Username</label> </div> <div class="form-floating mb-3"> <input type="email" name="email" class="form-control rounded-3" id="floatingInput" placeholder="name@example.com"> <label for="floatingInput">Email address</label> </div> <div class="form-floating mb-3"> <input type="password" name="password1" class="form-control rounded-3" id="floatingPassword" placeholder="Password"> <label for="floatingPassword">Password</label> </div> <div class="form-floating mb-3"> <input type="password" name="password2" class="form-control rounded-3" id="floatingPassword" placeholder="Password"> <label for="floatingPassword">Password Confirmation</label> </div> <button class="w-100 mb-2 btn btn-lg rounded-3 btn-primary" type="submit">Register</button> <hr class="my-4"> </form> </div> <div class="modal-footer"> <button class="btn btn-primary" data-bs-target="#exampleModalToggle" data-bs-toggle="modal">Back to SignIn</button> </div> </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <script> const register = document.getElementById('register-form'); register.addEventListener("submit",submitHandler); function submitHandler(e) { var serializedData = $(this).serialize(); e.preventDefault(); $.ajax({ type: 'POST' , url : '{% url "register" %}', data: serializedData , dataType: 'json', success: function (data) { if (data.msg === 'Success') { alert('registered Succesfully, you can log in now'); $("#register-form").trigger('reset'); } else { alert('there was an err try again') } } }) } </script> <script> const login = document.getElementById('login-form'); login.addEventListener("submit",submitHandler); function submitHandler(e) { var serializedData = $(this).serialize(); e.preventDefault(); $.ajax({ type: 'POST' , url : '{% url "login" %}', data: serializedData , dataType: 'json', success: function (data) { if (data.msg === 'Success') { alert('Logged in!'); $("#login-form").trigger('reset'); window.location.reload(); } else { alert('there was an err try again') } } }) } </script> {% block content %} {% endblock content %} <!-- ======= Footer ======= --> <footer id="footer"> <div class="container"> <div class="copyright"> &copy; Copyright <strong><span>Kelly</span></strong>. All Rights Reserved </div> <div class="credits"> Designed by <a href="#">Ashkan</a> </div> </div> </footer><!-- End Footer --> <div id="preloader"></div> <a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i class="bi bi-arrow-up-short"></i></a> <!-- Vendor JS Files --> <script src="{% static '' %}assets/vendor/purecounter/purecounter.js"></script> <script src="{% static '' %}assets/vendor/aos/aos.js"></script> <script src="{% static '' %}assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <script src="{% static '' %}assets/vendor/glightbox/js/glightbox.min.js"></script> <script src="{% static '' %}assets/vendor/isotope-layout/isotope.pkgd.min.js"></script> <script src="{% static '' %}assets/vendor/swiper/swiper-bundle.min.js"></script> <script src="{% static '' %}assets/vendor/waypoints/noframework.waypoints.js"></script> <script src="{% static '' %}assets/vendor/php-email-form/validate.js"></script> <!-- Template Main JS File --> <script src="{% static '' %}assets/js/main.js"></script> </body> </html>
"use client"; import Image from "next/image"; import Link from "next/link"; import { FC } from "react"; import type { TProfileBySessionId } from "@/app/api/profile/getBySessionId"; import type { TProfileList } from "@/app/api/profile/list"; import { SearchForm } from "@/app/entities/search/searchForm"; import { ELanguage, ERoutes } from "@/app/shared/enums"; import { useNavigator, useProxyUrl } from "@/app/shared/hooks"; import { createPath } from "@/app/shared/utils"; import { Online } from "@/app/uikit/components/online"; import "./MainPage.scss"; type TProps = { lng: ELanguage; profile?: TProfileBySessionId; profileList?: TProfileList; }; export const MainPage: FC<TProps> = ({ lng, profile, profileList }) => { const navigator = useNavigator({ lng }); const { proxyUrl } = useProxyUrl(); return ( <div className="MainPage"> <SearchForm lng={lng} profile={profile} /> <div className="MainPage-List"> {(profileList?.content ?? []).map((item) => ( <Link href={{ pathname: createPath({ route: ERoutes.Profile, params: { id: item.id }, lng: lng, }), query: { latitude: (navigator?.latitudeGPS ?? "").toString(), longitude: (navigator?.longitudeGPS ?? "").toString(), }, }} key={item.id} > <div className="MainPage-WrapperImage" key={item.id}> <Online classes={{ root: "MainPage-Online" }} isOnline={item.isOnline} /> <Image alt="" className="MainPage-Image" fill={true} priority={true} sizes="100vw" src={`${proxyUrl}${item.image.url}`} quality={100} /> </div> </Link> ))} </div> </div> ); };
/** * Returns the indentation of the given line in indentation units. Odd spaces * are not counted. This method only analyzes the content of <code>line</code> * up to the first non-whitespace character. * * @param line * the string to measure the indent of * @param tabWidth * the width of one tab character in space equivalents * @param indentWidth * the width of one indentation unit in space equivalents * @return the number of indentation units that line is indented by * @exception IllegalArgumentException * if: * <ul> * <li>the given <code>indentWidth</code> is lower or equals to * zero</li> * <li>the given <code>tabWidth</code> is lower than zero</li> * <li>the given <code>line</code> is null</li> * </ul> */ public static int measureIndentUnits(CharSequence line, int tabWidth, int indentWidth) { if (indentWidth <= 0 || tabWidth < 0 || line == null) { throw new IllegalArgumentException(); } int visualLength = measureIndentInSpaces(line, tabWidth); return visualLength / indentWidth; }
import React from "react"; import { useSelector } from "react-redux"; import { useLocation } from "react-router-dom"; import { Routes } from "../RouteConfig"; import { Container, DFlex, HeaderStyle, ItemNav, Nav, } from "./styled.components"; export const Header = () => { const { basketReducer: { totalPrice }, } = useSelector((state) => state); let location = useLocation(); return ( <HeaderStyle> <Container> <DFlex> <div style={{ width: 30 }}> <img src="pngaaa.com-2507896.png" alt="logo" width="100%" /> </div> <p> {location.pathname === "/" ? totalPrice === 0 ? "" : `You have ${totalPrice}$ in you basket` : ""} </p> <Nav> <ItemNav to={Routes.gallery}>Gallery</ItemNav> <ItemNav to={Routes.basket}>Basket</ItemNav> </Nav> </DFlex> </Container> </HeaderStyle> ); };
How can you select all the even number records from a table? All the odd number records? * modulus operator. WHERE order_qty % 2 = 0, WHERE order_qty % 2 != 0 It's the end of 2017, and the owner of a confectionary wants to write an SQL query that finds the COUNT of orders placed in 2017 by customer e-mail address. She wants to ORDER the results by the COUNT of orders placed in 2016, descending, so that she can personally send thank-you e-mails to her top customers by order volume. Can you write a query that will help this owner find the COUNT of all orders placed in 2017, by customer e-mail address, sorted descending? * * This solution assumes the Orders table includes a column for an email address attached to each order entry, and includes a date column. SELECT o.email, COUNT(*) order_count FROM orders o WHERE o.occurred_at BETWEEN '2017-01-01' AND '2018-01-01' GROUP BY o.email ORDER BY order_count DESC; * This solution assumes database has an Orders table ( that includes a date column entry for each order row), however with the email address stored in a separate accounts table, being linked through a.account_id(Primary key), o.account_id(foreign key). In this solution each account has a single email address. SELECT accounts.email, COUNT(orders.*) order_count FROM orders JOIN accounts ON orders.account_id = accounts.id WHERE orders.occurred_at BETWEEN '2017-01-01' AND '2018-01-01' GROUP BY accounts.email ORDER BY order_count DESC; You have IDs on 2 tables, you want the IDs which are in the first table, but not in the second one. Answer with both JOIN and SubQuery. Do a left join where b.ID is null ( here b is the second table) *This solution returns all a.ID's that do not exist in b.ID( showing all NULL values in b_ID column, for visual comparison) SELECT a.ID a_ID, b.ID b_id FROM a LEFT b ON a.ID = b.ID WHERE b.ID IS NULL; *Same result as above, only showing a.ID values in a single column. SELECT a.ID FROM a LEFT b ON a.ID = b.ID WHERE b.ID IS NULL; b. Select ID from a where id not in (select id from b) * Selecting a.ID using where NOT IN a select from b SELECT a.ID aID_only FROM a.ID WHERE a.ID NOT IN (SELECT b.ID FROM B); You have a table with salaries of employees, how will you get the 10th highest salary (keep in mind that multiple employees might have the same salaries) a. Select top 1 salary from (select distinct top 10 salary from emp order by salary desc) x order by salary SELECT top_ten_salary.* FROM ( SELECT DISTINCT salary_total_usd as salary_amount FROM emp ORDER BY salary_total_usd DESC LIMIT 10 ) top_ten_salary ORDER BY top_ten_salary DESC LIMIT 1
/** * {@inheritDoc} * * Extracts the key parameters from the parameter set, translates them into * filter-based parameters, and then passes the modified parameter set to * the event filter. */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Filter> filterArray = new ArrayList<>(); // convenient syntax for EventTextFilter String eventTextString = Encode.forHtmlContent(request.getParameter("eventtext")); if (eventTextString != null && eventTextString.length() > 0) { filterArray.add(new EventTextFilter(eventTextString)); } // convenient syntax for LogMessageSubstringFilter String msgSubstring = WebSecurityUtils.sanitizeString(request.getParameter("msgsub")); if (msgSubstring != null && msgSubstring.length() > 0) { filterArray.add(new LogMessageSubstringFilter(msgSubstring)); } // convenient syntax for LogMessageMatchesAnyFilter String msgMatchAny = WebSecurityUtils.sanitizeString(request.getParameter("msgmatchany")); if (msgMatchAny != null && msgMatchAny.length() > 0) { filterArray.add(new LogMessageMatchesAnyFilter(msgMatchAny)); } // convenient syntax for NodeNameContainingFilter String nodeNameLike = WebSecurityUtils.sanitizeString(request.getParameter("nodenamelike")); if (nodeNameLike != null && nodeNameLike.length() > 0) { filterArray.add(new NodeNameLikeFilter(nodeNameLike)); } // convenient syntax for ExactUEIFilter String exactUEI = WebSecurityUtils.sanitizeString(request.getParameter("exactuei")); if (exactUEI != null && exactUEI.length() > 0) { filterArray.add(new ExactUEIFilter(exactUEI)); } // convenient syntax for LocationFilter String location = WebSecurityUtils.sanitizeString(request.getParameter("location")); if (location != null && !location.equalsIgnoreCase("any")) { filterArray.add(new LocationFilter(WebSecurityUtils.sanitizeString(location))); } // convenient syntax for NodeLocationFilter String nodeLocation = WebSecurityUtils.sanitizeString(request.getParameter("nodelocation")); if (nodeLocation != null && !nodeLocation.equalsIgnoreCase("any")) { filterArray.add(new NodeLocationFilter(WebSecurityUtils.sanitizeString(nodeLocation))); } // convenient syntax for SystemIdFilter String systemId = WebSecurityUtils.sanitizeString(request.getParameter("systemId")); if (systemId != null && !systemId.equalsIgnoreCase("any")) { filterArray.add(new SystemIdFilter(WebSecurityUtils.sanitizeString(systemId))); } // convenient syntax for ServiceFilter String service = WebSecurityUtils.sanitizeString(request.getParameter("service")); if (service != null && !service.equalsIgnoreCase("any")) { filterArray.add(new ServiceFilter(WebSecurityUtils.safeParseInt(service), this.getServletContext())); } // convenient syntax for IPLikeFilter String ipLikePattern = WebSecurityUtils.sanitizeString(request.getParameter("iplike")); if (ipLikePattern != null && !ipLikePattern.equals("")) { filterArray.add(new IPAddrLikeFilter(ipLikePattern)); } // convenient syntax for SeverityFilter String severity = WebSecurityUtils.sanitizeString(request.getParameter("severity")); if (severity != null && !severity.equalsIgnoreCase("any")) { filterArray.add(new SeverityFilter(WebSecurityUtils.safeParseInt(severity))); } String eventId = WebSecurityUtils.sanitizeString(request.getParameter("eventid")); if (eventId != null && !"".equals(eventId)) { int eventIdInt = WebSecurityUtils.safeParseInt(eventId); if (eventIdInt > 0) { filterArray.add(new EventIdFilter(eventIdInt)); } } // convenient syntax for AfterDateFilter as relative to current time String relativeTime = WebSecurityUtils.sanitizeString(request.getParameter("relativetime")); if (relativeTime != null && !relativeTime.equalsIgnoreCase("any")) { int timeInt = WebSecurityUtils.safeParseInt(relativeTime); if (timeInt > 0) { try { filterArray.add(EventUtil.getRelativeTimeFilter(timeInt)); } catch (IllegalArgumentException e) { // ignore the relative time if it is an illegal value this.log("Illegal relativetime value", e); } } } String useBeforeTime = WebSecurityUtils.sanitizeString(request.getParameter("usebeforetime")); if (useBeforeTime != null && useBeforeTime.equals("1")) { try { filterArray.add(this.getBeforeDateFilter(request)); } catch (IllegalArgumentException e) { // ignore the before time if it is an illegal value this.log("Illegal before time value", e); } catch (MissingParameterException e) { throw new ServletException(e); } } String useAfterTime = WebSecurityUtils.sanitizeString(request.getParameter("useaftertime")); if (useAfterTime != null && useAfterTime.equals("1")) { try { filterArray.add(this.getAfterDateFilter(request)); } catch (IllegalArgumentException e) { // ignore the after time if it is an illegal value this.log("Illegal after time value", e); } catch (MissingParameterException e) { throw new ServletException(e); } } String queryString = ""; if (filterArray.size() > 0) { String[] filterStrings = new String[filterArray.size()]; for (int i = 0; i < filterStrings.length; i++) { Filter filter = filterArray.get(i); filterStrings[i] = EventUtil.getFilterString(filter); } Map<String, Object> paramAdditions = new HashMap<String, Object>(); paramAdditions.put("filter", filterStrings); queryString = Util.makeQueryString(request, paramAdditions, IGNORE_LIST); } else { queryString = Util.makeQueryString(request, IGNORE_LIST); } response.sendRedirect(redirectUrl + "?" + queryString); }
import { UserContext } from "../context/user" import { API } from '../config/api' import { useState, useContext } from 'react' import { useNavigate } from 'react-router-dom' import { motion, AnimatePresence } from 'framer-motion' import { useMutation } from 'react-query' const modal = { hidden: { y: "-100vw", opacity: 0 }, visible: { y: "0vw", opacity: 1, transition: { duration: 0.1, type: "spring", damping: 50, stiffness: 500 } }, exit: { y: "100vw", opacity: 0 } } const styles = { inputAuth: 'bg-[#d7ceca] border-2 border-[#613d2b] rounded-md py-1.5 px-2 mb-4' } export function Register({modalRegister, setModalRegister, switchModal}) { const [message, setMessage] = useState(null) const [form, setForm] = useState({ name: '', email: '', password: '', }) const { name, email, password } = form const handleChange = (e) => { setForm({ ...form, [e.target.name]: e.target.value, }) } const handleSubmit = useMutation(async (e) => { try { e.preventDefault(); const config = { headers: {'Content-type': 'application/json'} } const body = JSON.stringify(form); await API.post('/register', body, config); switchModal() } catch (error) { console.log(error) setMessage( <p>{error}</p> ) } }) return ( <AnimatePresence initial={false} exitBeforeEnter={true} onExitComplete={() => null}> { modalRegister && <motion.section className='fixed z-50 top-0 w-screen h-screen flex justify-center items-center bg-black bg-opacity-90 cursor-pointer' initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} onClick={ () => setModalRegister(false) }> <motion.form className='w-1/4 py-8 px-6 flex flex-col bg-white rounded-md cursor-default' initial="hidden" animate="visible" exit="exit" variants={ modal } onClick={ (e) => e.stopPropagation() } onSubmit={ (e) => handleSubmit.mutate(e) }> <h2 className='mb-7 font-bold text-[#613d2b] text-3xl'>Register</h2> {message} <input className={styles.inputAuth} type="email" id="email" name="email" placeholder="Email" value={email} onChange={ handleChange } /> <input className={styles.inputAuth} type="password" id="password" name="password" placeholder="Password" value={password} onChange={ handleChange } /> <input className={styles.inputAuth} type="text" id="name" name="name" placeholder="Full Name" value={name} onChange={ handleChange } /> <button className='w-100 py-2 mt-3 mb-4 bg-[#613d2b] rounded-md font-semibold text-white text-sm' type="submit"> Register </button> <p className='text-sm text-center tracking-wide'>Already have an account ? Click <strong className='cursor-pointer' onClick={ switchModal }> Here</strong> </p> </motion.form> </motion.section> } </AnimatePresence> ) } export function Login({modalLogin, setModalLogin, switchModal}) { const navigate = useNavigate() const [_, dispatch] = useContext(UserContext) const [message, setMessage] = useState(null) const [form, setForm] = useState({ email: '', password: '' }) const { email, password } = form const handleChange = (e) => { setForm({ ...form, [e.target.name]: e.target.value, }) } const handleSubmit = useMutation(async (e) => { try { e.preventDefault() const config = { headers: {'Content-type': 'application/json'} } const body = JSON.stringify(form) const response = await API.post('/login', body, config) if (response?.status === 200) { dispatch({ type: 'LOGIN', payload: response.data.data }) if (response.data.data.status === "admin") { navigate('/income') } else { navigate('/') } } } catch (error) { console.log(error) setMessage( <p>{error}</p> ) } }) return ( <AnimatePresence initial={false} exitBeforeEnter={true} onExitComplete={() => null}> { modalLogin && <motion.section className='fixed z-50 top-0 w-screen h-screen flex justify-center items-center bg-black bg-opacity-90 cursor-pointer' initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} onClick={ () => setModalLogin(false) }> <motion.form className='w-96 py-8 px-6 flex flex-col bg-white rounded-md cursor-default' initial="hidden" animate="visible" exit="exit" variants={ modal } onClick={ (e) => e.stopPropagation() } onSubmit={ (e) => handleSubmit.mutate(e) }> <h2 className='mb-7 font-bold text-[#613d2b] text-3xl'>Login</h2> {message} <input className={styles.inputAuth} type="email" id="email" name="email" placeholder="Email" value={email} onChange={handleChange} required /> <input className={styles.inputAuth} type="password" id="password" name="password" placeholder="Password" value={password} onChange={ handleChange } required /> <button className='w-100 py-2 mt-3 mb-4 bg-[#613d2b] rounded-md font-semibold text-white text-sm' type="submit"> Login </button> <p className='text-sm text-center tracking-wide'>Don't have an account ? Click <strong className='cursor-pointer' onClick={ switchModal }> Here</strong> </p> </motion.form> </motion.section> } </AnimatePresence> ) }
import React, { useState, useEffect } from "react"; import CategoryService from "@/services/category.service"; import { useRouter } from "next/navigation"; export default function CategoryEdit({ categoryId }) { const [category, setCategory] = useState(null); const [name, setName] = useState(""); const router = useRouter(); useEffect(() => { CategoryService.getCategoryById(categoryId) .then((fetchedCategory) => { setCategory(fetchedCategory); setName(fetchedCategory.name || ""); }) .catch((error) => { console.error("Error fetching category details:", error); }); }, [categoryId]); // Define the handleUpdateCategory function const handleUpdateCategory = async (e) => { e.preventDefault(); try { const updatedCategory = { ...category, name, }; const updatedCategoryResult = await CategoryService.updateCategory( updatedCategory ); console.log("Category updated successfully:", updatedCategoryResult); router.push("/dashboard/category"); } catch (error) { console.error("Error updating category:", error); } }; if (!category) { return <div>Loading...</div>; } return ( <section className="bg-white w-screen"> <div className="py-8 px-4 mx-auto max-w-2xl lg:py-16"> <h2 className="mb-4 text-xl font-bold text-gray-900">Edit Category</h2> <form onSubmit={handleUpdateCategory}> <div className="grid gap-4 sm:grid-cols-2 sm:gap-6"> <div className="sm:col-span-2"> <label htmlFor="categoryName" className="relative block overflow-hidden rounded-md border border-gray-200 px-3 pt-3 shadow-sm focus-within:border-blue-600 focus-within:ring-1 focus-within:ring-blue-600" > <input type="text" id="categoryName" placeholder="Category Name" className="peer h-8 w-full border-none bg-transparent p-0 placeholder-transparent focus:border-transparent focus:outline-none focus:ring-0 sm:text-sm text-black" value={name} onChange={(e) => setName(e.target.value)} required /> <span className="absolute left-3 top-3 -translate-y-1/2 text-xs text-gray-700 transition-all peer-placeholder-shown:top-1/2 peer-placeholder-shown:text-sm peer-focus:top-3 peer-focus:text-xs"> Category Name </span> </label> </div> </div> <button className="inline-flex items-center px-5 py-2.5 mt-4 sm:mt-6 text-sm font-medium text-center text-white bg-secondary rounded-lg focus:ring-4 focus:ring-primary-200 hover:bg-primary" type="submit" > Edit </button> </form> </div> </section> ); }
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { HttpClientModule } from '@angular/common/http'; import { NgxsModule } from '@ngxs/store'; import { NgxsReduxDevtoolsPluginModule } from '@ngxs/devtools-plugin'; import { HeaderComponent } from './components/header/header.component'; import { FooterComponent } from './components/footer/footer.component'; import { HomeComponent } from './components/home/home.component'; import { VideoDetailsComponent } from './pages/video-details/video-details.component'; import { SafePipe } from './pipe/safe.pipe'; import { VideoState } from './store/state/video.state'; @NgModule({ declarations: [ AppComponent, HeaderComponent, FooterComponent, HomeComponent, VideoDetailsComponent, SafePipe ], imports: [ BrowserModule, HttpClientModule, AppRoutingModule, NgxsModule.forRoot([VideoState]), NgxsReduxDevtoolsPluginModule.forRoot() ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
package api import ( "context" cartApi "modulith/modules/cart" invoiceApi "modulith/modules/invoice" "modulith/modules/order/database" "modulith/modules/order/routes" "modulith/shared" ) type api struct { db database.Database itemApi cartApi.ItemApi cartApi cartApi.CartApi } func Initialize(dsn string, itemApi cartApi.ItemApi, cartApi cartApi.CartApi, invoiceApi invoiceApi.InvoiceApi) (*api, shared.Routes) { db := database.Initialize(dsn) return &api{ db: db, }, routes.NewRoutes(&db, itemApi, cartApi, invoiceApi) } type OrderApi interface { GetOrderByOrderId(ctx context.Context, orderId string) (*database.Order, error) } func (app *api) GetOrderByOrderId(ctx context.Context, orderId string) (*database.Order, error) { return app.db.GetOrderByOrderId(ctx, orderId) }
function countVowels(str) { if (typeof str !== 'string') { throw new Error('Data type is not a string'); } const formattedStr = str.toLowerCase(); const vowels = ['a', 'e', 'i', 'o', 'u']; let count = 0; for (let i = 0; i < formattedStr.length; i++) { const char = formattedStr[i]; if (vowels.includes(char)) { count++; } } return count; } module.exports = countVowels;
package com.example.cursoradaptertest; import androidx.appcompat.app.AppCompatActivity; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.SimpleCursorAdapter; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends AppCompatActivity { ListView lv_movies; ArrayList<HashMap<String, String>> cursorDatas; CursorAdapter cursorAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv_movies = findViewById(R.id.lv_movies); cursorDatas = new ArrayList<HashMap<String, String>>(); DBHelper helper = new DBHelper(this); SQLiteDatabase db = helper.getWritableDatabase(); Cursor cursor = db.rawQuery("select * from tb_data", null); while(cursor.moveToNext()){ HashMap<String, String> map = new HashMap<>(); map.put("title", cursor.getString(1)); map.put("content", cursor.getString(2)); cursorDatas.add(map); } cursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, new String[]{"title", "content"}, new int[]{android.R.id.text1, android.R.id.text2}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); lv_movies.setAdapter(cursorAdapter); lv_movies.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(MainActivity.this, cursorDatas.get(position).get("title") + "," + cursorDatas.get(position).get("content"), Toast.LENGTH_SHORT).show(); } }); } }
import { i18n } from '../documentTranslation' export default { title: 'Product', name: 'product', type: 'document', // The next property enables full-document translation for this document // via the sanity-intl plugin. You can of course modify this object should you // need to on a document-to-document bassis. i18n, fields: [ { title: 'Title', name: 'title', type: 'string', }, { title: 'Slug', name: 'slug', type: 'slug', options: { source: 'title', }, }, { title: 'Product Category', name: "productCategory", type: 'array', of: [{ type: 'reference', to: [ { type: 'productCategory' } ] }] }, { title: 'Image', name: 'image', type: 'captionImage' }, { title: '3D Model', name: 'model', type: 'file' }, { title: 'Description', name: 'description', type: 'richText' } , { title: 'Specifications', name: 'specifications', type: 'richText' }, { name: 'downloads', title: 'Product Files For Download', type: 'array', of: [{ type: 'file' }] }, ], // preview: { // select: { // title: 'title', // media: 'image' // } // } }
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>GSちゃんねる</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <style> div { padding: 10px; font-size: 16px; } </style> </head> <body> <header> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">GSちゃんねる</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> </ul> </div> </nav> </header> <ul id="echo" class="list-group"> <!-- データ表示部分 --> </ul> <div> <button type="button" id="showNew" class="btn btn-light">show new</button> </div> <form id="insert_form"> <div class="form-group"> <input type="text" class="form-control" id="name" name="name" placeholder="名前(省略可)"> </div> <div class="form-group"> <textarea class="form-control" id="comment" name="comment" rows="3" placeholder="コメント"></textarea> </div> <div class="form-group"> <input type="file" class="form-control-file" id="upfile" name="upfile" accept="image/*" capture="camera"> </div> <div class="form-group"> <button type="button" id="send" class="btn btn-primary">Submit</button> </div> </form> <script> // DBから取得したデータを表示する関数 const createListTagFromData = data => { return data.map(x => `<li class="list-group-item"> <p>${x.id} ${x.name} ${x.indate}</p> <p>${x.comment}</p> <img src="${x.image}" alt="" height="150px"> </li>` ).join(''); }; // DBからデータを取得する関数 const getAllDataFromDb = () => { const url = 'ajax_get.php'; fetch(url) .then(res => res.json()) .then(response => { document.getElementById('echo').innerHTML = createListTagFromData(response); }) .catch(error => console.error('Error:', error)); }; // DBへデータを登録する関数 const insertDataToDb = () => { const url = 'ajax_post.php'; const data = new FormData(document.getElementById('insert_form')); const requestData = { method: 'POST', body: data }; fetch(url, requestData) .then(res => res.json()) .then(response => { document.getElementById('echo').innerHTML = createListTagFromData(response); document.getElementsByTagName('button')[0].setAttribute('disabled', false); }) .catch(error => console.error('Error:', error)); }; getAllDataFromDb(); document.getElementById('showNew').addEventListener('click', function () { getAllDataFromDb(); }); document.getElementById('send').addEventListener('click', function () { document.getElementsByTagName('button')[0].setAttribute('disabled', true); insertDataToDb(); document.getElementById('name').value = ''; document.getElementById('comment').value = ''; document.getElementById('upfile').value = ''; }); </script> </body> </html>
import { Person, PhoneOutlined } from "@mui/icons-material"; import { Card, Typography } from "@mui/material"; import React from "react"; const ContactField = ({ title, name, phone }) => { return ( <Card variant="outlined" sx={{ padding: "8px" }}> <Typography variant="caption">{title}</Typography> <div style={{ display: "flex" }}> <Person color="primary" /> {name ? ( <Typography variant="body1" sx={{ marginLeft: "4px" }}> {name} </Typography> ) : ( <Typography variant="body1" sx={{ marginLeft: "4px" }}> No Contact Name Entered </Typography> )} </div> <div style={{ display: "flex" }}> <PhoneOutlined style={{ color: "blue" }} /> {phone ? ( <Typography variant="body1" sx={{ marginLeft: "4px" }}> {phone} </Typography> ) : ( <Typography variant="body1" sx={{ marginLeft: "4px" }}> No Phone Number Entered </Typography> )} </div> <div style={{ marginTop: "24px" }} /> </Card> ); }; export default ContactField;
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib prefix="tag" tagdir="/WEB-INF/tags" %> <!DOCTYPE html> <html> <head> <title>Song trainer Home Page</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link type="text/css" href="/css/stylesheet.css" rel="stylesheet"> <link rel="icon" href="/favicon.ico" /> <script src="/js/main.js" /></script> </head> <body> <tag:header user="${user}"></tag:header> <div class="wrapper"> <h2>Home</h2> <div class="playlists-title"> <h3>My playlists</h3> <a href="${pageContext.request.contextPath}/playlist/addPlaylist"><i class="fa fa-solid fa-plus"></i> Add</a> </div> <table> <thead> <tr> <th>Name</th> <th>Instrument</th> <th style="text-align: right;">Actions</th> </tr> </thead> <tbody> <c:forEach var="tempPlaylist" items="${playlists}"> <!-- construct an "update" link with playlist id --> <c:url var="updatePlaylistLink" value="/playlist/showUpdateForm"> <c:param name="playlistId" value="${tempPlaylist.id}" /> </c:url> <!-- construct a "delete" link with playlist id --> <c:url var="deletePlaylistLink" value="/playlist/deletePlaylist"> <c:param name="playlistId" value="${tempPlaylist.id}" /> </c:url> <tr> <td><a href="${pageContext.request.contextPath}/playlist?id=${tempPlaylist.id}">${tempPlaylist.name}</a></td> <td>${tempPlaylist.instrumentStr}</td> <td class="icons"> <a href="${updatePlaylistLink}"><button class="pencil"><i class="fa fa-solid fa-pencil"></i></button></a> <a href="${deletePlaylistLink}" onclick="if (!(confirm('Are you sure you want to delete this playlist?'))) return false"> <button class="trash"><i class="fa fa-solid fa-trash"></i></button> </a> </td> </tr> </c:forEach> </tbody> </table> <div class="users"> <div> <h3>My Followed users</h3> <c:forEach var="follow" items="${followed}"> <a href="/profile?id=${follow.key.id}&inst=ALL" class="user"><i class="fa fa-solid fa-user"></i> ${follow.key.userName}</a><br><br> <c:forEach var="playlist" items="${follow.value}"> <td><i class="fa fa-solid fa-arrow-right play"></i><a href="${pageContext.request.contextPath}/playlist?id=${playlist.id}">${playlist.name}</a></td><br><br> </c:forEach> <br> </c:forEach> </div> <div> <h3>Search users</h3> <form:form action="${pageContext.request.contextPath}/search" method="post"> <input type="text" name="keyword" placeholder="username"/> <input type ="submit" value="Search"> </form:form><br> <c:forEach var="tempUser" items="${users}"> <a href="${pageContext.request.contextPath}/profile?id=${tempUser.id}&inst=ALL" class="user"><i class="fa fa-solid fa-user"></i> ${tempUser.userName}</a><br><br> </c:forEach><br> </div> </div> </div> </body> </html> <style> .playlists-title { display: flex; justify-content: space-between; align-items: baseline; } .playlists-title a { padding: 12px 20px; background-color: #13b992; color: #1a1d28; border-radius: 12px; text-decoration: none; transition: linear 0.3s; } .playlists-title a:hover { box-shadow: 0px 0px 5px 5px rgba(19, 185, 146, 0.24); } form input { background-color: transparent; color: white; border-radius: 7px; border: 1px solid white; padding: 7px; } .users { display: flex; justify-content: space-between; } .users div { width: 50%; } .user { background-color: #13b992; color: #1F2230; border-radius: 14px; padding: 7px; text-decoration: none; margin-bottom: 3px; } .play { color: #13b992 !important; margin-left: 20px !important; padding-right: 10px; } .user i { padding-right: 5px; } </style>
""" Los objetos son instancias de las clases diagrama uml (juntos) codigo (solos) """ import datetime from datetime import datetime from enum import Enum import os os.system('clear' or 'cls') # funcion para presentar datos en columnas def datosMasEspacios(anchoColumna=15,alineacion='izquierda',dato=''): espacios = ' '*(anchoColumna-len(str(dato))) if alineacion == 'izquierda': return str(dato)+espacios elif alineacion == 'derecha': return espacios+str(dato) else: return espacios[:int(len(espacios)/2)]+str(dato)+espacios[int(len(espacios)/2):] class TipoContrato(Enum): FIJO = "Salario Fijo" COMI = "Por Comision" class Antiguedad(Enum): CAT1 = "Menos de 2 años" CAT2 = "De 2 a 5 años" CAT3 = "Mas de 5 años" class Empleado: # instancias ordenadas en listas emplPorComision = [] emplSalarioFijo = [] def __init__(self, dni, nombre, apellido, añoIngreso, relContractual) -> None: self.dni = dni self.nombre = nombre self.apellido = apellido self.añoIngreso = añoIngreso self.relContractual = relContractual if relContractual == 'porComision': self.__class__.emplPorComision.append(self) else: self.__class__.emplSalarioFijo.append(self) def calcularSalario(self): pass def mostrarSalario(): # titulo print('\n----------------------------------') print('Listado de empleados por comision:') print('----------------------------------\n') # ancho de columan para la presentacion en terminal anchoColumna = 15 alineacion = 'izquierda' titulos = ['Nombre','Apellido','Salario'] print(datosMasEspacios(anchoColumna,alineacion,titulos[0]), datosMasEspacios(anchoColumna,alineacion,titulos[1]), datosMasEspacios(anchoColumna,'derecha',titulos[2]), end=' ') print('\n') # iteracion por las instancias PorComision for empl in Empleado.emplPorComision: salarioPorComision = empl.calcularSalario(empl.salarioMinimo,empl.clientesCaptados,empl.montoPorCliente) print(datosMasEspacios(anchoColumna,alineacion,empl.nombre), datosMasEspacios(anchoColumna,alineacion,empl.apellido), datosMasEspacios(anchoColumna,'derecha',salarioPorComision)) # titulo print('\n--------------------------------------') print('Listado de empleados con salario fijo:') print('--------------------------------------\n') # ordenar las instancias por salario Empleado.emplSalarioFijo = sorted(Empleado.emplSalarioFijo, key=lambda empl:empl.calcularSalario(empl.sueldoBasico,empl.añoIngreso), reverse=True) # iteracion por las instancias SalarioFijo titulos = ['Nombre','Apellido','Salario'] print(datosMasEspacios(anchoColumna,alineacion,titulos[0]), datosMasEspacios(anchoColumna,alineacion,titulos[1]), datosMasEspacios(anchoColumna,'derecha',titulos[2]), end=' ') print('\n') for empl in Empleado.emplSalarioFijo: # Calcular el salario de cada instancia salarioFijoValor = empl.calcularSalario(empl.sueldoBasico,empl.añoIngreso) # llenar con espacios casa str para un ancho de columna comun print(datosMasEspacios(anchoColumna,alineacion,empl.nombre), datosMasEspacios(anchoColumna,alineacion,empl.apellido), datosMasEspacios(anchoColumna,'derecha',salarioFijoValor)) print() class PorComision(Empleado): def __init__(self, dni, nombre, apellido, añoIngreso, relContractual, salarioMinimo, clientesCaptados, montoPorCliente ) -> None: self.salarioMinimo = salarioMinimo self.clientesCaptados = clientesCaptados self.montoPorCliente = montoPorCliente super().__init__(dni, nombre, apellido, añoIngreso, relContractual) def calcularSalario(self, salarioMinimo, clientesCaptados, montoPorCliente): comision = clientesCaptados * montoPorCliente # si la comision es menor al salario minimo, recibe el salario minimo, sino la comision. if comision > salarioMinimo: salario = comision return float(salario) else: salario = salarioMinimo return float(salario) def empleadoConMasClientes(): # ordenar las instancias 'PorComision' por clientesCaptados, orden descendente. Empleado.emplPorComision = sorted(Empleado.emplPorComision, key=lambda employee:employee.clientesCaptados, reverse=True) # tomar el primero de la lista (el mayor valor) empl = Empleado.emplPorComision[0] texto = f'El empleado con mas clientes captados es : {empl.nombre} {empl.apellido}. cantidad: {empl.clientesCaptados} clientes.' print('\n'+'-'*len(texto)) print(texto) print('-'*len(texto)) def rankingMasClientes(): # ordenar las instancias 'PorComision' por clientesCaptados, orden descendente. Empleado.emplPorComision = sorted(Empleado.emplPorComision, key=lambda employee:employee.clientesCaptados, reverse=True) # tomar el primero de la lista (el mayor valor) empl = Empleado.emplPorComision[0:3] texto = 'El ranking de los empleados con mas clientes captados es : ' print('\n'+'-'*len(texto)) print(texto) print('-'*len(texto)) print() anchoColumna = 15 alineacion = 'izquierda' titulos = ['Lugar','Nombre','Apellido','Cts. Captados'] [print(datosMasEspacios(anchoColumna,alineacion,titulos[ind]),end=' ') for ind in range(0,len(titulos))] print('\n') for e in empl: print(datosMasEspacios(anchoColumna,alineacion,f'{empl.index(e)+1}° : '), datosMasEspacios(anchoColumna,alineacion,e.nombre), datosMasEspacios(anchoColumna,alineacion,e.apellido), datosMasEspacios(anchoColumna,alineacion,e.clientesCaptados)) class SalarioFijo(Empleado): porcAdicional = {'CAT1':1,'CAT2':1.05,'CAT3':1.1} def __init__(self, dni, nombre, apellido, añoIngreso, relContractual, sueldoBasico) -> None: self.sueldoBasico = sueldoBasico super().__init__(dni, nombre, apellido, añoIngreso, relContractual) def calcularSalario(self, sueldoBasico, añoIngreso): year = datetime.now().year antiguedad = year - añoIngreso if antiguedad < 2: salario = sueldoBasico * SalarioFijo.porcAdicional['CAT1'] elif antiguedad < 5: salario = sueldoBasico * SalarioFijo.porcAdicional['CAT2'] else: salario = sueldoBasico * SalarioFijo.porcAdicional['CAT3'] return float(salario) empl01 = PorComision('12345678','Ariel', 'Sanchez',1985, 'porComision',1000000, 50, 15000) empl02 = PorComision('11223344','Alejandro', 'Gomez',1995, 'porComision',1000000, 100, 15000) empl03 = PorComision('11122233','Brian', 'Figueroa',2005, 'porComision',1000000, 200, 15000) empl04 = PorComision('11112222','Carlos', 'Colombo',2015, 'porComision',1000000, 300, 15000) empl05 = PorComision('33334444','Cecilia', 'Garcia',2022, 'porComision',1000000, 500, 15000) empl06 = SalarioFijo('55556666','Alicia', 'Mendoza',2009, 'salarioFijo',2000000) empl07 = SalarioFijo('77778888','Maria' , 'Lorenzo',2010, 'salarioFijo',2000000) empl08 = SalarioFijo('99990000','Laura', 'Salguero',2023, 'salarioFijo',3000000) empl09 = SalarioFijo('22222222','Macarena', 'Silverado',2021, 'salarioFijo',3000000) empl10 = SalarioFijo('33333333','German', 'Larrea',2018, 'salarioFijo',4000000) PorComision.empleadoConMasClientes() PorComision.rankingMasClientes() print() Empleado.mostrarSalario()
# DataOps - Laboratório 6 Processmento e Análise de Dados em AWS GLue As instruções do laboratório estão em português. Para alterar o idioma, procure a opção na barra inferior do console AWS. ## Objetivos * Utilizar AWS Glue Crawler para encontrar dados no S3 * Armazenar dados encontrados pelo Crawler no AWS Glue Data Catalog * Executar um processo de ETL no AWS Glue para extrair do Data Catalog, fazer transformações, e incluir no Redshift ## Arquitetura da solução <img src="images/Imagem1.png" width='100%'/> ## Configurar um VPC Endpoint para conectar com S3 Para o Crawler do AWS Glue poder ler os dados do S3 é preciso criar um VPC Endpoint, que estabelece uma conexão privada entre a VPC e os serviços da AWS, em passar pela inter-net. Assim, o Glue consegue acessar os dados do S3 de forma privada e segura. 1. Procure na barra superior pelo serviço `VPC` e clique no serviço para abrir 2. No menu ao lado esquerdo procure e clique em <img src="images/Imagem2.png" height='25'/> 3. Depois clique em <img src="images/Imagem3.png" height='25'/> 4. No campo `Etiqueta de nome` coloque `s3-glue-endpoint` 5. Na barra de pesquisa da seção `Serviços` escreva `s3` e aperte `Enter` 6. No resultado selecione a opção que tem seguintes características: Nome do serviço: `com.amazonaws.us-east-1.s3` Tipo: `Gateway` <img src="images/Imagem7.png" width='100%'/> 7. Na seção `VPC` selecione a única opção disponível (`padrão`) <img src="images/Imagem98.png" width='100%'/> 8. Em `Tabelas de rotas` selecione o checkbox da única linha disponível <img src="images/Imagem9.png" width='100%'/> 9. Clique em <img src="images/Imagem10.png" height='25'/> 10. Confirme o endpoint criado <img src="images/Imagem12.png" width='100%'/> ## Criar Crawler no AWS Glue 1. Procure na barra superior pelo serviço `Glue` e clique no serviço para abrir 2. No menu lateral esquerdo, procure e clique em <img src="images/Imagem13.png" height='25'/> 3. Clique em <img src="images/Imagem14.png" height='25'/> e comece a configuração do novo Crawler 3.1. `Name`: `crawler-vacinas` 3.2. Clique em <img src="images/Imagem15.png" height='25'/> 3.3. Na tela seguinte, clique em <img src="images/Imagem99.png" height='25'/>. No popup, configure a nova conexão: 3.4. No popup, selecione o bucket e pasta `dataops-impacta-dados-nomesobrenome/input` (bucket criado no [Laboratório 1](https://github.com/fesousa/dataops-lab1)), clicando em <img src="images/Imagem100.png" height='25'/>. Ao escolher o bucket e a pasta, clique em <img src="images/Imagem102.png" height='25'/> <img src="images/Imagem101.png" width='100%'/> 3.5. Ao voltar para a tela anterior, clique em <img src="images/Imagem103.png" height='25'/> 3.6. Clique em <img src="images/Imagem15.png" height='25'/> 3.7. Em `IAM Role` selecione `Lab Role` 3.8. Clique em <img src="images/Imagem15.png" height='25'/> 3.9. Na tela `Set output and scheduling`, clique em <img src="images/Imagem31.png" height='25'/>. Uma nova aba será aberta. 3.10 Na nova aba coloque no campo `Name` o nome `vacinas_database` e clique em <img src="images/Imagem32.png" height='25'/> 3.11. Volte para a aba onde está criando o crawler e clique em <img src="images/Imagem104.png" height='25'/> para atualizar as opções de `Target database` 3.12. Em `Target database` selecione o database que acabou de criar (`vacinas_database`) 3.13. No campo `Table name prefix` escreva `vacinas_` 3.14. Clique em <img src="images/Imagem34.png" height='25'/> 3.15. Revise as configurações e clique em <img src="images/Imagem35.png" height='25'/> 3.16. Verifique o Crawler criado na nova tela <img src="images/Imagem36.png" width='100%'/> 3.17. Ainda nessa tela, execute o crawler clicando em <img src="images/Imagem38.png" height='25'/>. A execuceção começará e poderá ser acompanhada no final da página, na seção `Crawler runs` <img src="images/Imagem105.png" width='100%'/> 3.18. Aguarde até que o Status fique `Completed` <img src="images/Imagem105.png" width='100%'/> 3.19 Verifique a nova tabela criada clicando em `Tables` (`Data Catalog --> Database --> Tables`) <img src="images/Imagem41.png" width='100%'/> ## Consultar dados do Data Catalog com Amazon Athena 1. O Amazon Athena precisa de um bucket para armazenar os resultados de consulta. Procure pelo serviço S3 e crie um novo bucket chamado `dataops-impacta-athena-nomesobrenome`. Troque `nomesobrenome` pelo seu nome e sobrenome 2. Volte ao AWS Glue e selecione `Tables` no menu lateral esquerdo 3. Na tela das tabelas, abra a tabela `vacinas_input` <img src="images/Imagem43.png" width='100%'/> 4. Clique em <img src="images/Imagem44.png" height='25'/> e depois em <img src="images/Imagem45.png" height='25'/> <img src="images/Imagem43.png" width='100%'/> 5. No popup, clique em <img src="images/Imagem46.png" height='25'/> para ser redirecionado para o Amazon Athena 6. Já no Amazon Athena, clique em `Settings` nas abas superiores 7. Na seção `Query result and encryption settings` clique em <img src="images/Imagem49.png" height='25'/> 8. Clique em <img src="images/Imagem50.png" height='25'/> para selecionar o bucket S3 dos resultado 9. Selecione o bucket `dataops-impacta-athena-nomesobrenome` (bucket que acabou de criar) e clique em <img src="images/Imagem51.png" height='25'/> <img src="images/Imagem108.png" width='100%'/> 10. Clique em <img src="images/Imagem52.png" height='25'/> 11. De volta do Athena clique em `Editor` 12. Na seção `Data` ao lado esquerdo, verifique se em `Database` o baco de dados `vacinas_database` está selecionado <img src="images/Imagem54.png" width='100%'/> 13. Ao lado direito, no editor de consultas, verifique se já existe a seguinte consulta, para re-tornar os 10 primeiros registros: ```sql SELECT * FROM "vacinas-database"."vacinas_input" limit 10; ``` Se não houver, coloque essa consulta no editor e clique em <img src="images/Imagem55.png" height='25'/>. Você deverá ver um resultado parecido com o seguinte: <img src="images/Imagem56.png" width='100%'/> 14. Execute uma nova consulta para retornar a quantidade de registros e veja o resultado ```sql SELECT count(1) FROM "vacinas-database"."vacinas_input"; ``` ## Inserir mais dados do Data Catalog 1. Na AWS, procure e abra o serviço `Lambda` 2. Selecione a função lambda `dataops-coleta-vacinas-ci-cd` criada no [Laboratório 4](https://github.com/fesousa/dataops-lab4) 3. Teste a função com o seguinte json OBS: O Link abaixo é dinâmico. Pegue outro link de arquivo de vacinação aqui: https://opendatasus.saude.gov.br/dataset/covid-19-vacinacao/resource/5093679f-12c3-4d6b-b7bd-07694de54173 ```json { "url":"https://s3.sa-east-1.amazonaws.com/ckan.saude.gov.br/SIPNI/COVID/uf/uf%3DAP/part-00000-0e081da1-2126-45b3-8bfd-78667a8589af.c000.csv", "uf":"ap" } ``` A execução vai coletar dados de vacinação do Amapá e salvar no S3. Se precisar, veja no [Laboratório 4](https://github.com/fesousa/dataops-lab4) como testar a função lambda 4. Volte para o Amazon Athena e execute a consulta para contar a quantidade de registros novamente e verifique o resultado. Os dados do Amapá foram inseridos. 5. Ainda no Athena, execute uma consulta para contar quantos registros existem de cada Estado (campo `estabelecimento_uf`) ## Executar ETL com Glue Job (Trabalho) 1. Na AWS, procure e abra o serviço `Glue` 2. No menu da lateral esquerda, selecione `ETL Jobs` 3. Selecione a opção `Spark script editor` e clique em <img src="images/Imagem58.png" height='25'/> 4. Na nova tela, coloque o script `pyspark abaixo` ```python ${etl_vacinas.py} ``` 4.1. No código verifique se está de acordo com o que está no seu ambiente: * Linha 41: database = "vacinas_database", table_name = "vacinas_input". Deve estar de acordo com o que está em seu data catalog 5. Na parte superior onde está escrito `Unitled Job`, edite o nome do job para `etl_vacinas` <img src="images/Imagem109.png" width='100%'/> 6. Clique na aba `Job details` e configure: 6.1. `IAM Role`: selecione `LabRole`] 6.2. Na seção `Connections` (deve expandir `Advanced properties`) clique no link `AWS Glue` para abrir uma nova aba e adicionar a conexão do Redshift <img src="images/Imagem110.png" width='100%'/> 6.3. Na nova aba, na seção `Connections` clique em `Create connection` <img src="images/Imagem111.png" width='100%'/> 6.4. Em `Name` coloque `redshift-connection` (preste atenção neste nome. É o que está configurado no script do Job [linha 65]. Se for diferente, a execução vai falhar) 6.5. Em `Connection type` escolha `Amazon Redshift` 6.6. Em `Connection access` configure o cluster redshift criado no labortório 5. Você só precisa escolher `Database instances` e `Password`, os outros campos ficam iguais. Se não lembra a senha, altere no redshift. 6.7. Clique em `Create connection` 6.8. Volte a aba onde está configurando o job e selecione a conexão criada. Se não aparecer, clique no botão de atualizar ao lado do campo de opções <img src="images/Imagem112.png" width='100%'/> 7. Clique em <img src="images/Imagem71.png" height='25'/> na parte superior 8. Clique em <img src="images/Imagem113.png" height='25'/> na parte superior 9. Acompanhe a execução do script clicando na aba `Runs`: 9.1. Espere até que a execução fique com o status `Succeeded`. A execução demora cerca de 4 minutos. Clique em <img src="images/Imagem75.png" height='25'/> de tempos em tempos para ver a atualização <img src="images/Imagem76.png" width='100%'/> 9.2. Lembre-se de iniciar o cluster redshift antes de excutar o processo 10. Abra o redshift e verifique a tabela `vacinas_dw` criada pelo editor de consultas 11. Utilize o editor de consultas para consultar os registros da tabela utilizando SQL 9.1. Quantidade de registros na tabela ```sql select count(1) from vacinas_dw; ``` &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;9.2. Quantidade de vacinas por UF ```sql select sum(quantidade), uf from vacinas_dw group by uf; ``` &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;9.3. Registros de vacinação com mais de 1000 vacinas ```sql select * from vacinas_dw where quantidade > 1000 ``` 12. Lembre-se de pausar o cluster Redshift quando terminar o laboratório. <div class="footer"> &copy; 2023 Fernando Sousa <br/> {{update}} </div>
<!DOCTYPE html> <html lang="{{@site.lang}}"> <head> {{!-- Document Settings --}} <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> {{!-- Base Meta --}} <title>{{meta_title}}</title> <meta name="HandheldFriendly" content="True" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> {{!-- Styles'n'Scripts --}} <link rel="stylesheet" type="text/css" href="{{asset "main/css/main.css"}}" /> {{!-- This tag outputs SEO meta+structured data and other important settings --}} {{ghost_head}} </head> <body class="is-preload {{body_class}}"> <div id="wrapper"> <main id="main"> <div class="inner"> {{!-- Header --}} <header id="header"> {{#if @site.logo}} <a href="{{@site.url}}" class="logo image"> <img src="{{@site.logo}}" alt="{{@site.title}}" /> </a> {{else}} <a href="{{@site.url}}" class="logo">{{@site.title}}</a> {{/if}} <ul class="icons"> <li> <a href="https://github.com/mikemimik" class="icon fa-github" title="GitHub"> <span class="label">GitHub</span> </a> </li> {{#if @site.twitter}} <li> <a href="{{twitter_url @site.twitter}}" class="icon fa-twitter" title="Twitter"> <span class="label">Twitter</span> </a> </li> {{/if}} {{#if @site.facebook}} <li> <a href="{{facebook_url @site.facebook}}" class="icon fa-facebook" title="Facebook"> <span class="label">Facebook</span> </a> </li> {{/if}} <li> <a href="https://linkedin.com/in/mperrotte/" class="icon fa-linkedin" title="LinkedIn"> <span class="label">LinkedIn</span> </a> </li> <li> <a href="https://feedly.com/i/subscription/feed/{{@site.url}}/rss/" class="icon fa-rss" target="_blank" rel="noopener"> <span class="label" title="RSS">RSS</span> </a> </li> </ul> </header> {{!-- All the main content gets inserted here, index.hbs, post.hbs, etc --}} {{{body}}} </div> </main> {{!-- The left sidebar - partials/sidebar.hbs --}} {{> sidebar}} </div> {{!-- Theme Scripts --}} <script src="{{asset "main/js/jquery.min.js"}}"></script> <script src="{{asset "main/js/browser.min.js"}}"></script> <script src="{{asset "main/js/breakpoints.min.js"}}"></script> <script src="{{asset "main/js/util.js"}}"></script> <script src="{{asset "main/js/main.js"}}"></script> {{!-- Ghost outputs important scripts & data with the {ghost_foot} tag it should always be the very last thing before the closing body tag --}} {{ghost_foot}} </body> </html>
package com.virgingames.cucumber.pages; import com.virgingames.cucumber.utility.Utility; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class HomePage extends Utility { private static final Logger log = LogManager.getLogger(HomePage.class.getName()); public HomePage() { PageFactory.initElements(driver, this); } @CacheLookup @FindBy(xpath = "//label[contains(text(),'Accept')]") WebElement Accept; @CacheLookup @FindBy(xpath = "//span[contains(text(),'Poker')]") WebElement poker; @CacheLookup @FindBy(xpath = "//body/div[@id='app']/div[@id='styledApp']/div[1]/a[1]/div[1]/canvas[1]") WebElement JoinNow; public void clickOnAccept() { log.info("Clicking on Accept Cookie : " + Accept.toString()); clickOnElement(Accept); } public void clickOnPoker() { log.info("Clicking on login link : " + poker.toString()); clickOnElement(poker); } public void clickOncanvas() { log.info("Clicking on login link : " + JoinNow.toString()); clickOnElement(JoinNow); } }
import streamlit as st import requests from PIL import Image from io import BytesIO import time def discover_dog(): retries = 5 for attempt in range(retries): try: response = requests.get('http://dogs_microservice:5000/dogs') response.raise_for_status() dogs = response.json() dog_names = [dog['breed'] for dog in dogs] selected_dog_name = st.selectbox("Select a dog", dog_names) selected_dog = next((dog for dog in dogs if dog['breed'] == selected_dog_name), None) if selected_dog: image_data = bytes.fromhex(selected_dog['obrazek']) image = Image.open(BytesIO(image_data)) st.image(image, width=300) st.header("Dog Information") st.markdown("---") st.write("**Breed:**", selected_dog['breed']) st.write("**Curiosity:**", selected_dog['curiosity']) else: st.error("Dog not found. Please select a valid dog.") break # If successful, break out of retry loop except requests.RequestException as e: if attempt < retries - 1: st.warning(f"Error fetching data: {e}. Retrying...") time.sleep(2) # Wait for 2 seconds before retrying else: st.error(f"Max retries exceeded: {e}") if __name__ == "__main__": st.title("Discover a Dog") discover_dog()
Feature: Reading Group Creation In order to create new reading groups to make my own readings As a regular user I should be able to create reading groups @kalibro_configuration_restart Scenario: Should not create reading groups without login Given I am at the All Reading Groups page Then I should not see "New Reading Group" @kalibro_configuration_restart Scenario: Reading Group creation Given I am a regular user And I am signed in And I am at the New Reading Group page And I fill the Name field with "My reading group" And I fill the Description field with "New reading group" When I press the Save button Then I should see "My reading group" And I should see "New reading group" And I should see "New Reading" And I should see "Destroy" @kalibro_configuration_restart Scenario: Reading Group creation with already taken name Given I am a regular user And I am signed in And I have a reading group named "Group" And I am at the New Reading Group page And I fill the Name field with "Group" And I fill the Description field with "Same Group" When I press the Save button Then I should see "Name has already been taken" @kalibro_configuration_restart Scenario: Reading Group creation with blank name Given I am a regular user And I am signed in And I am at the New Reading Group page And I fill the Name field with " " And I fill the Description field with "Anything" When I press the Save button Then I should see "Name can't be blank" @kalibro_configuration_restart Scenario: Reading Group name with whitespaces Given I am a regular user And I am signed in And I have a reading group named "Reading Group" And I am at the New Reading Group page And I fill the Name field with " Reading Group " When I press the Save button Then I should see "Name has already been taken"
import {HttpException, HttpStatus, Injectable} from '@nestjs/common' import { User } from './users.model' import { InjectModel } from '@nestjs/sequelize' import { CreateUserDto } from './create-user.dto' import { RolesService } from '../roles/roles.service'; import {AssignRoleDto} from "./assign-role.dto"; import {BanUserDto} from "./ban-user.dto"; @Injectable() export class UsersService { constructor(@InjectModel(User) private userRepository: typeof User, private rolesService: RolesService) {} async createUser(dto: CreateUserDto) { const user = await this.userRepository.create(dto) const role = await this.rolesService.getRoleByValue('USER') await user.$set('roles', [role.id]) user.roles = [role] return user } async getAllUser() { return await this.userRepository.findAll({include: {all: true}}) } async getUserByEmail(email: string) { return await this.userRepository.findOne({where: {email}, include: {all: true}}) } async assignRole(dto: AssignRoleDto) { const user = await this.userRepository.findByPk(dto.userId) const role = await this.rolesService.getRoleByValue(dto.value) if(!user && !role) { throw new HttpException('User and role is not found', HttpStatus.NOT_FOUND) } else if(!user) { throw new HttpException('User is not found', HttpStatus.NOT_FOUND) } else if(!role) { throw new HttpException('Role is not found', HttpStatus.NOT_FOUND) } await user.$add('roles', role.id) return dto } async banUser(dto: BanUserDto) { const user = await this.userRepository.findByPk(dto.userId) if(!user) { throw new HttpException('User is not found', HttpStatus.NOT_FOUND) } user.banned = true user.banReason = dto.reason await user.save() return user } }
import './App.css' import { useEffect, useState } from 'react'; import SingleCard from './components/SingleCard'; import { Card } from './lib/classes'; const cardImages: Card[] = [ new Card("/img/drakeposting-1.jpg", false, 1, 'drakeposting', 1), new Card("/img/drakeposting-2.jpg", false, 2, 'drakeposting', 2), new Card("/img/girl-yelling-cat-1.jpg", false, 3, 'girl-yelling-cat', 1), new Card("/img/girl-yelling-cat-2.jpg", false, 4, 'girl-yelling-cat', 2), new Card("/img/kombucha-girl-1.jpg", false, 5, 'kombucha-girl',1), new Card("/img/kombucha-girl-2.jpg", false, 6, 'kombucha-girl', 2), new Card("/img/cat-monkey-1.jpg", false, 7, 'cat-monkey', 1), new Card("/img/cat-monkey-2.jpg", false, 8, 'cat-monkey', 2), new Card("/img/this-is-fine-1.jpg", false, 9, 'this-is-fine', 1), new Card("/img/this-is-fine-2.jpg", false, 10, 'this-is-fine', 2), new Card("/img/for-the-better-1.jpg", false, 11, 'for-the-better', 1), new Card("/img/for-the-better-2.jpg", false, 12, 'for-the-better', 2) ] function App() { const [cards, setCards] = useState<Card[]>([]); const [turns, setTurns] = useState(0); const [disabled, setDisabled] = useState(false); const [choiceOne, setChoiceOne] = useState<Card | null>(null); const [choiceTwo, setChoiceTwo] = useState<Card | null>(null); const shuffleCards = () => { const shuffledCards = [...cardImages] .sort(() => Math.random() - 0.5) .map((card) => ({ ...card, id: Math.random() })); setCards(shuffledCards); setTurns(0); setChoiceOne(null); setChoiceTwo(null); } const resetTurn = () => { setChoiceOne(null); setChoiceTwo(null); setDisabled(false); setTurns(prevTurns => prevTurns + 1); console.log('turns: ' + turns); } const handleChoice = (card: Card) => { choiceOne ? setChoiceTwo(card) : setChoiceOne(card); } //start game automatically useEffect(() => { shuffleCards(); }, []); useEffect(() => { if(choiceOne && choiceTwo){ setDisabled(true); if(choiceOne.meme === choiceTwo.meme){ setCards((prevCards: Card[]) => { return prevCards.map(card => { if(card.meme === choiceOne.meme){ return {...card, matched: true}; }else{ return card; } }); }) console.log('correct!'); }else{ console.log('wrong!!'); } setTimeout(resetTurn, 1000); } }, [choiceOne, choiceTwo]); console.log(cards); return ( <div className="App"> <h1>reMEMEber</h1> <button onClick={ shuffleCards }>New Game</button> <div className="card-grid"> {cards.map((card: Card) => ( <SingleCard key={card.id} card={ card } handleChoice={handleChoice} flipped={card === choiceOne || card === choiceTwo || card.matched} disabled={disabled} /> ))} </div> <p>Turns: { turns }</p> </div> ); } export default App
package com.jason.tics.exercise.domain.exam; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.hibernate.validator.constraints.Length; import javax.persistence.*; import java.util.List; /** * 试卷,题目集合 * @author Jason */ @Setter @Getter @ToString @Entity @Table public class Paper { @Id private Long id; @OneToMany(targetEntity = PaperQuestion.class, cascade = CascadeType.ALL, mappedBy = "paper") private List<PaperQuestion> questions; @Length(max = 30) private String paperName; private Long timeLimit; public Double getTotalScore(){ double s = 0; for (PaperQuestion question : questions) { s += question.getScore(); } return s; } }
package easy /*Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2] Example 3: Input: nums = [3,3], target = 6 Output: [0,1] Constraints: 2 <= nums.length <= 104 -109 <= nums[i] <= 109 -109 <= target <= 109 Only one valid answer exists. Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?*/ fun main(args: Array<String>) { val data = intArrayOf(2, 7, 11, 15) val target = 9 val result = twoSum(data, target) println("result: " + result.first() + ", " + result.last()) } fun twoSum(nums: IntArray, target: Int): IntArray { val numToIndexMap = mutableMapOf<Int, Int>() for (i in nums.indices) { val complement = target - nums[i] if (numToIndexMap.containsKey(complement)) { return intArrayOf(numToIndexMap[complement]!!, i) } numToIndexMap[nums[i]] = i } return intArrayOf() }
# -------------------------- # # Stopwords: Latin and Greek # # Make TXT from JSON # # -------------------------- # source("~/Documents/github/r-dev/helpers.R") # Initial conversion to JSON # -------------------------- # Test RJSON package # R to/from JSON with flattened output: not what I need # install.packages("rjson") library(rjson) # memo: needed R structure to reproduce my levels/headings with rjson test_from_r <- list( "TYPOGRAPHICAL SYMBOLS" = c("!", "$"), "PRONOUNS" = list( "ego" = c("ego", "egon"), "meus" = c("mea", "meae") ) ) test_from_r <- unlist(test_from_r, use.names = TRUE) test_r_to_json <- toJSON(test_from_r) write_lines(test_r_to_json, "./test/test_json_txt/test_r_to_json.json") test_r_from_json <- read_file("./versions/stopwords_latin_v2_1.json") test_r_from_json <- fromJSON(test_r_from_json) write_lines(test_r_from_json, "./test/test_json_txt/test_r_from_json.txt") # TXT/Markdown to JSON # too complicated: can't close brackets easily # if used at all, JSON has to be the structured source format # test_input <- read_file("./test/test_json_txt/test_input.txt") # test_output <- c("{", test_input, "}") # test_output <- str_replace_all(test_output, "#\\s(.*)\n(?=\n##)", "\"\\1\": {\n") # test_output <- str_replace_all(test_output, "#+\\s(.*)\n", "\"\\1\": [\n") # test_output <- str_replace_all(test_output, "\\{\n\n", "\\{\n") # test_output <- str_replace_all(test_output, "\n\n", "\n],\n") # test_output <- str_replace_all(test_output, "\n([^\\]\"].*)", "\n\"\\1\",") # test_output <- str_replace_all(test_output, ",\n([\\]\\}])", "\n\\1") # test_output <- str_replace_all(test_output, ",\\n\\n\\}", "\n}") # breaking here # write_lines(test_output, "./test/test_json_txt/test_output.md") # or try Markdown to R list, then toJSON? # for now use a CLI Python Markdown to JSON converter # https://github.com/njvack/markdown-to-json # result: stopwords_latin_v2_1.json and stopwords_greek_v2_2.json # Test JSON to TXT/Markdown with my headings # ------------------------------------------ test_input_json <- read_file("./test/test_json_txt/test_input.json") test_input_json %>% str_replace_all("^\\{\n", "") %>% str_replace_all("\\}\n\\}\n", "") %>% str_replace_all("\\s*\"([A-Z]+.*)\": [\\[\\{\\],]+\n", "# \\1\n") %>% str_replace_all("\\s*\"(.*)\": \\[\n", "## \\1\n") %>% # str_replace_all("[\":\\{\\}\\[\\],]", "\n") %>% str_replace_all("\\:(?!\")", "\n") %>% str_replace_all("\\[(?!\")", "\n") %>% str_replace_all("\\](?!\")", "\n") %>% str_replace_all("\\{(?!\")", "\n") %>% str_replace_all("\\}(?!\")", "\n") %>% str_replace_all("\\\\(?!\")", "\n") %>% str_replace_all(",", "\n") %>% str_replace_all('\\"(?!\")', "\n") %>% str_replace_all("\\\\", "\n") %>% str_replace_all("\n\\s+", "\n") %>% str_replace_all("##", "\n##") %>% str_replace_all("\n#(.)", "\n\n#\\1") %>% str_replace_all("\n\n\n", "\n\n") %>% write_file("./test/test_json_txt/test_output.md") # Add metadata today <- format(Sys.time(), "%Y-%m-%d") version_latin <- "2.1" current_latin_count <- count_items_in_txt_list("stopwords_latin.txt") test_output <- read_file("./test/test_json_txt/test_output.md") # meta <- read_file("stopwords_latin_metadata.txt") current_metadata <- paste0( "# Ancient Latin stopwords", "\n", "# version ", version_latin, "\n", "# ", today, "\n", "# Aurélien Berra", "\n", "# ", "\n", "# Ancient Latin stopwords for textual analysis", "\n", "# language: Latin (la, lat)", "\n", "# type: dataset", "\n", "# items count: ", current_latin_count, "\n", "# https://github.com/aurelberra/stopwords", "\n", "# rights: CC-BY-NC-SA", "\n", "\n" ) test_stopwords <- paste0(current_metadata, test_output) write_file(test_stopwords, "./test/test_json_txt/test_stopwords.txt")
import React, { useState } from 'react'; import { useHistory } from 'react-router-dom'; import { auth } from '../firebase'; const Register = () => { const [username, setUsername] = useState(''); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const history = useHistory(); const handleRegister = () => { if (password !== confirmPassword) { alert('Passwords do not match.'); return; } auth.createUserWithEmailAndPassword(email, password) .then((userCredential) => { // You can also save additional user data like username to Firebase here history.push('/dashboard'); }) .catch((error) => { alert('Registration failed. Please try again.'); }); }; return ( <div className="container"> <div className="row justify-content-center"> <div className="col-md-6"> <h2 className="mt-5 mb-3">Register</h2> <input type="text" className="form-control mb-2" placeholder="Username" value={username} onChange={(e) => setUsername(e.target.value)} /> <input type="email" className="form-control mb-2" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} /> <input type="password" className="form-control mb-2" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} /> <input type="password" className="form-control mb-2" placeholder="Confirm Password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} /> <button className="btn btn-primary" onClick={handleRegister}> Register </button> </div> </div> </div> ); }; export default Register;