text
stringlengths
184
4.48M
import 'dart:convert'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:storage_management_system/screens/home_screen/home_screen_cubit.dart'; class ItemsCubit extends Cubit<List<ModalBottomSheetState>> { ItemsCubit() : super([]); void addItem(ModalBottomSheetState item) { List<ModalBottomSheetState> updatedList = List.from(state); updatedList.add(item); emit(updatedList); } bool updateItem(int index, ModalBottomSheetState updatedItem) { final items = List<ModalBottomSheetState>.from(state); if (updatedItem.counter2 == 0) { items.removeAt(index); } else { items[index] = updatedItem; } emit(items); return updatedItem.counter1 <= updatedItem.counter2; } void addItemsFromJson(String jsonString) { final items = jsonDecode(jsonString) as Map<String, dynamic>; for (var entry in items.entries) { String name = entry.key; int amount = entry.value; final existingItemIndex = state.indexWhere((item) => item.itemName == name); if (existingItemIndex == -1) { // If the item doesn't exist, add a new item with a blue card addItem(ModalBottomSheetState( itemName: name, counter2: amount, counter1: 0, )); } else { // If the item exists, update the counter2 of the existing item final existingItem = state[existingItemIndex]; updateItem(existingItemIndex, existingItem.copyWith(counter2: existingItem.counter2 + amount)); } } } }
\section{Big Data Analysis} Big data analytics is where advanced analytic techniques operate on big data sets. Hence, big data analytics is really about two things — \textit{big data} and \textit{analytics}. \subsection{Big Data} As the name suggests, big data is a large amount of data. There are other important attributes of big data. These are: data variety and data velocity. Thus we can define big data using 3 V's: \textit{volume}, \textit{variety}, and \textit{velocity} as showing in figure \ref*{bigData}. \begin{figure}[h] \centering \includegraphics[width=0.5\textwidth]{images/big_data.png} \caption{Big Data: 3 V's \autocite{3vbigdata}} \label{bigData} \end{figure} Beyond these three V's, Big Data is also about how complicated the computing problem is. Given the number of variables and number of data points for analysing the maritime shipping data. It is a very complicated problem. Thus, in addition to the three V's identified by IBM, it would also be necessary to take complexity into account as shown in figure \ref*{bigDataComplex} \autocite{pence2014big}. \begin{figure}[h] \centering \includegraphics[width=0.5\textwidth]{images/big_data_complex.png} \caption{Big Data: Beyond 3 V's - volume, velocity, variety, and complexity} \label{bigDataComplex} \end{figure} \subsection{What is Big Data Analytics?} Big data analytics is the process of examining large and varied data sets to uncover hidden patterns, unknown correlations, market trends, customer preferences and other useful information that can help organizations make more-informed business decisions. Thus, Data analytics revolves around deriving valuable knowledge and meaningful insights from extensive sets of data. This process involves crafting hypotheses, often rooted in gathered experiences and uncovering correlations between variables, sometimes even through serendipitous discoveries. Data analytics can be classified into four distinct types \autocite{rajaraman2016big}: \subsubsection{1. Descriptive Analytics} Descriptive analytics focuses on explaining past events and presenting them in a comprehensible manner. The collected data is structured into visual aids like bar charts, graphs, pie charts, maps, and scatter diagrams, facilitating easy interpretation that offers insights into the data's implications. This mode of data representation is often termed a dashboard, reminiscent of a car's dashboard that provides details such as speed, engine status, fuel levels, and distance traveled. A classic instance of descriptive analytics involves displaying population census data, which categorizes a nation's population by gender, age brackets, education, income, population density, and similar criteria \autocite{rajaraman2016big}. \subsubsection{2. Predictive Analytics} Predictive analytics extends beyond existing data to forecast forthcoming events. It anticipates what is likely to occur in the immediate future. Techniques like time series analysis utilizing statistical methods, neural networks, and machine learning algorithms are employed for this extrapolation. A significant application of predictive analytics is seen in marketing, where it understands customer preferences and needs. For instance, when purchasing shoes online, an advertisement for socks may appear. Another prevalent application is in orchestrating election campaigns. This involves gathering diverse data, such as the demographics of voters in different areas and their perceived needs like infrastructure and local concerns \autocite{rajaraman2016big}. \subsubsection{3. Prescriptive Analytics} This process detects opportunities for enhancing existing solutions by analyzing collected data. Essentially, it guides us on the actions to undertake in order to accomplish a particular objective. An illustrative instance is observed in the aviation industry where airlines determine seat pricing through analysis of historical travel patterns, popular travel origins and destinations, significant events, holidays, and more. This approach is employed to optimize profit generation \autocite{rajaraman2016big}. \subsubsection{4. Exploratory or Discovery Analytics} This process uncovers unforeseen connections among variables within extensive datasets. The collection and analysis of data from diverse sources opens up new avenues for gaining insights and making serendipitous discoveries. One of its major applications involves the identification of patterns in customers' behavior by companies through sources like feedback, tweets, blogs, Facebook data, emails, and sales trends. By deciphering customer behavior, companies can potentially predict actions like renewing a magazine subscription, switching mobile phone service providers, or canceling a hotel reservation. Armed with this information, companies can devise appealing offers aimed at altering the anticipated course of action by the customer \autocite{rajaraman2016big}.
use lv8_parser::{Block as BlockAST, Either, Expression as ExpressionAST, Statement}; use super::{ block::Block, scope::{self, Scope, ValueType}, PrimitiveTypes, }; #[derive(Clone, Debug)] pub struct Function { name: String, body: Block, expected_parameters: Vec<String>, } impl Function { pub fn new(name: String, body: Block, expected_parameters: Vec<String>) -> Self { Self { name, body, expected_parameters, } } pub fn call(mut self, parameters: Vec<ValueType>) -> ValueType { let scope = &mut self.body.scope; let mut parameters = parameters.into_iter(); for expected_parameter in &self.expected_parameters { let parameter = parameters .next() .unwrap_or(ValueType::Variable(PrimitiveTypes::Undefined)); scope.set_variable(expected_parameter.clone(), parameter); } self.body.call() } } impl ToString for Function { fn to_string(&self) -> String { format!("<<function {}>>", self.name) } } pub fn handle_function_call( scope: &mut Scope, function_name: &str, arguments: &[Either<ExpressionAST, Statement>], ) -> ValueType { let function = scope.get_variable(function_name).cloned(); let args = arguments .iter() .map(|x| match x { Either::Left(expression) => scope::expression_to_value(scope, expression), Either::Right(statement) => super::statement::run_statement(scope, statement), }) .collect::<Vec<scope::ValueType>>(); if function.is_none() { panic!("Function not found: {}", function_name); } match function.unwrap() { ValueType::Function(function) => function.call(args), ValueType::InternalFunction(function) => function(args), _ => { panic!("{} is not a function", function_name); } } } pub fn handle_function_definition( scope: &mut Scope, name: &str, parameters: &[String], body: &BlockAST, ) -> ValueType { let new_function_scope = scope.clone(); let body = Block::new(body.clone(), new_function_scope); let function = Function::new(name.to_string(), body, parameters.to_vec()); scope.set_variable(name.to_string(), scope::ValueType::Function(function)); scope::ValueType::Variable(PrimitiveTypes::Undefined) }
import React, {useContext, useEffect, useState} from "react"; import { Link, NavLink, useNavigate, Navigate, useHistory } from "react-router-dom"; import "./Navbar.css"; import * as PATHS from "../../utils/paths"; import * as CONSTS from "../../utils/consts"; import * as CONFIG from '../../config/config' import {UserContext} from '../../context/UserContext.js' import { CheckoutContext } from "../../context/CheckoutContext"; import NavLinkIcon from "../NavLinkIcon"; import MenuIcon from '@mui/icons-material/Menu'; import { AccountBox, ShoppingCart, Login, Logout, AppRegistration, Home, LocalShipping, AddBox, Category } from '@mui/icons-material'; import { AppBar, Box, Toolbar, IconButton, Typography, Menu, Container, Button, MenuItem, CardMedia } from '@mui/material' const linkStyle = {color: 'white', textDecoration: 'none'} const Navbar = (props) => { const {user, setUser} = useContext(UserContext) const [isInSignUpProcess, setIsInSignUpProcess] = useState(false) const [anchorElNav, setAnchorElNav] = useState(null); const [navchange, setNavChange] = useState(0) useEffect(() => { if(!user) { setIsInSignUpProcess(false) return; } if(user.signupStage <= CONFIG.MAX_SIGNUP_STAGE) { setIsInSignUpProcess(true) } else { setIsInSignUpProcess(false) } }, [user]) function handleSignUpStageClick() { setNavChange(navchange+1) } const handleOpenNavMenu = (event) => { setAnchorElNav(event.currentTarget); }; const handleCloseNavMenu = () => { setAnchorElNav(null); }; return ( <> <AppBar position="fixed" style={{backgroundColor: '#fff', filter: 'drop-shadow(0 1px 10px #696969)'}}> <Container maxWidth="xl"> <Toolbar disableGutters> <Link to={!isInSignUpProcess ? PATHS.HOMEPAGE : PATHS.SIGNUPSTAGES} style={linkStyle}> <Typography variant="h6" noWrap component="div" sx={{ mr: 5, display: { xs: 'none', md: 'flex' }, color: 'gray' }} > <CardMedia component="img" style={{objectFit: 'contain', opacity: '1'}} height="40" image={'/logo-big.png'} alt="snackbox logo" /> </Typography> </Link> <Box sx={{ flexGrow: 1, display: { xs: 'flex', md: 'none' }, color: 'black' }}> <IconButton size="large" aria-label="account of current user" aria-controls="menu-appbar" aria-haspopup="true" onClick={handleOpenNavMenu} color="inherit" > <MenuIcon /> </IconButton> <Menu id="menu-appbar" anchorEl={anchorElNav} anchorOrigin={{ vertical: 'bottom', horizontal: 'left', }} keepMounted transformOrigin={{ vertical: 'top', horizontal: 'left', }} open={Boolean(anchorElNav)} onClose={handleCloseNavMenu} sx={{ display: { xs: 'block', md: 'none' }, }} > { // if user is found and hasnt filled signup stage !isInSignUpProcess ? ( <Box> {user ? ( <> <MenuItem onClick={handleCloseNavMenu}> <NavLinkIcon variant="text" text={'Subscriptions'} path={PATHS.SUBSCRIPTIONS} Icon={AddBox} /> </MenuItem> <MenuItem onClick={handleCloseNavMenu}> <NavLinkIcon variant="text" text={'Products'} path={PATHS.PRODUCTS} Icon={Category} /> </MenuItem> <MenuItem onClick={handleCloseNavMenu}> <NavLinkIcon variant="text" text={'Your Orders'} path={PATHS.ORDERS} Icon={LocalShipping} /> </MenuItem> <MenuItem onClick={handleCloseNavMenu}> <NavLinkIcon variant="text" text={'Profile'} path={PATHS.PROFILE} Icon={AccountBox} /> </MenuItem> <MenuItem onClick={handleCloseNavMenu}> <NavLinkIcon variant="text" text={'Checkout'} path={PATHS.CHECKOUT} color={'info'} Icon={ShoppingCart} /> </MenuItem> <MenuItem onClick={handleCloseNavMenu}> <Button variant="outlined" onClick={() => props.handleLogout()} color="error" startIcon={<Logout/>} > Log Out </Button> </MenuItem> </> ) : ( <Box> <MenuItem> <NavLinkIcon variant="outlined" text={'Sign Up'} path={PATHS.SIGNUPPAGE} color={'primary'} Icon={AppRegistration} /> </MenuItem> <MenuItem> <NavLinkIcon variant="outlined" text={'Login'} path={PATHS.LOGINPAGE} color={'secondary'} Icon={Login}/> </MenuItem> </Box> ) } </Box> ) : (<Box></Box>)} </Menu> </Box> <Typography variant="h6" noWrap component="div" sx={{ flexGrow: 1, display: { xs: 'flex', md: 'none' } }} > <Link to={!isInSignUpProcess ? PATHS.HOMEPAGE : PATHS.SIGNUPSTAGES} style={{color: 'gray', textDecoration: 'none'}}> Snack Box </Link> </Typography> <Box sx={{ flexGrow: 0, display: { xs: 'flex', md: 'none' } }}> {user ? ( <Button variant="outlined" onClick={() => props.handleLogout()} color="error" size={'small'} startIcon={<Logout/>} > </Button> ) : ( <NavLinkIcon variant="outlined" text={'Login'} path={PATHS.LOGINPAGE} color={'secondary'} Icon={Login}/> )} </Box> {/** <Button variant="outlined" onClick={() => props.handleLogout()} color="error" startIcon={<Logout/>} > Log Out </Button> */} { // if no user is found and not in form !isInSignUpProcess && user ? ( <> <Box sx={{ flexGrow: 1, display: { xs: 'none', md: 'flex' } }}> <NavLinkIcon variant="text" text={'Subscriptions'} path={PATHS.SUBSCRIPTIONS} Icon={AddBox} /> <NavLinkIcon variant="text" text={'Products'} path={PATHS.PRODUCTS} Icon={Category} /> </Box> </> ) : (<Box sx={{ flexGrow: 1, display: { xs: 'none', md: 'flex' } }}></Box>)} { // if user is found and hasnt filled signup stage isInSignUpProcess ? ( <> <Box sx={{ flexGrow: 1, display: { xs: 'none', md: 'flex' } }}> </Box> </> ) : (<></>) } <Box sx={{ flexGrow: 0, display: { xs: 'none', md: 'flex' } }} > {user ? ( <> { !isInSignUpProcess ? ( <> <NavLinkIcon variant="text" text={'Your Orders'} path={PATHS.ORDERS} Icon={LocalShipping} /> <NavLinkIcon variant="text" text={'Profile'} path={PATHS.PROFILE} Icon={AccountBox} /> <NavLinkIcon variant="text" text={'Checkout'} path={PATHS.CHECKOUT} color={'info'} Icon={ShoppingCart}/> </> ) : (<></>) } <Button variant="outlined" onClick={() => props.handleLogout()} color="error" startIcon={<Logout/>} > Log Out </Button> </> ) : ( <> <NavLinkIcon variant="outlined" text={'Sign Up'} path={PATHS.SIGNUPPAGE} color={'primary'} Icon={AppRegistration} /> <NavLinkIcon variant="outlined" text={'Login'} path={PATHS.LOGINPAGE} color={'secondary'} Icon={Login}/> </> ) } </Box> </Toolbar> </Container> </AppBar> </> ); }; export default Navbar; /* <nav> <Link to={PATHS.HOMEPAGE} className="nav__projectName"> {CONSTS.CAPITALIZED_APP} - created with IronLauncher </Link> <div className="nav__authLinks"> {props.user ? ( <> <Link to={PATHS.PROTECTEDPAGE} className="authLink"> Protected Page </Link> <button className="nav-logoutbtn" onClick={props.handleLogout}> Logout </button> </> ) : ( <> <Link to={PATHS.SIGNUPPAGE} className="authLink"> Signup </Link> <Link to={PATHS.LOGINPAGE} className="authLink"> Log In </Link> </> )} </div> </nav> */
/* * Aethyra * Copyright 2008 Lloyd Bryant <[email protected]> * * This file is part of Aethyra. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef PARTY_H #define PARTY_H #include <string> #include <guichan/actionlistener.hpp> class PartyHandler; class Being; class ChatWindow; class Party { public: Party(ChatWindow *chat); void respond(const std::string &command, const std::string &args); void create(const std::string &party); void leave(const std::string &args); void createResponse(bool ok); void inviteResponse(const std::string &nick, int status) const; void invitedAsk(const std::string &nick, int gender, const std::string &partyName); void leftResponse(const std::string &nick) const; void receiveChat(Being *being, const std::string &msg) const; void help(const std::string &msg) const; private: ChatWindow *mChat; std::string mPartyName; bool mInParty; bool mCreating; /**< Used to give an appropriate response to failure */ PartyHandler *handler; class InviteListener : public gcn::ActionListener { public: InviteListener(bool *inParty) : mInParty(inParty) {} void action(const gcn::ActionEvent &event); private: bool *mInParty; }; InviteListener mInviteListener; }; #endif
import {Module} from "@nestjs/common"; // import {AppController} from "./app.controllers"; // import {AppService} from "./app.service"; import { UsersModule } from './users/users.module'; import {SequelizeModule} from "@nestjs/sequelize"; import * as process from "process"; import {ConfigModule} from "@nestjs/config"; import {User} from "./users/users.model"; import { RolesModule } from './roles/roles.module'; import {Role} from "./roles/roles.model"; import { ProfileModule } from './profile/profile.module'; import {Profile} from "./profile/profile.model"; import { AuthModule } from './auth/auth.module'; import { TextBlockModule } from './text_block/text_block.module'; import { FilesService } from './files/files.service'; import { FilesModule } from './files/files.module'; import {ServeStaticModule} from "@nestjs/serve-static"; import {join} from "path"; import * as path from "path"; import { APP_GUARD } from '@nestjs/core'; import {RolesGuard} from "./auth/guard/roles.guard"; import { TokenModule } from './token/token.module'; import {Token} from "./token/token.model"; import {TextBlock} from "./text_block/text_block.model"; import {Files} from "./files/files.model"; import {MailModule} from "./auth/mail.service/mail.module"; import {JwtService} from "@nestjs/jwt"; import {JwtAuthGuard} from "./auth/guard/jwt-auth.strategy"; import {AdminOrMyselfGuard} from "./auth/guard/admin_or_myself.guard"; // import { JwtAuthGuard } from './guard/jwt.strategy'; // Создадим и экспортируем модуль AppModule, пометим его декоратором @Module. // @Module принимает в себя providers, controllers, imports, exports. @Module({ // Контроллеры, для создания эндпоинтов // AppController controllers: [], // Провайдеры - переиспользуемые компоненты приложения, сервисы с логикой, имплементации паттернов. //AppService. providers: [ { provide: APP_GUARD, useClass: RolesGuard, }, // { // provide: APP_GUARD, // useClass: JwtAuthGuard, // }, // { // provide: APP_GUARD, // useClass: AdminOrMyselfGuard, // }, JwtService, //JwtAuthGuard ], // Модули необходимые для работы приложения. imports: [ // Установим cross-env, для запуска скриптов разработки и продакшена c параметрами. // npm i cross-env // Добавим изменения в скрипты: // "start": "nest start" -> "start": "cross-env NODE_ENV=production nest start" // "start:dev": "nest start --watch" -> "start:dev": "cross-env NODE_ENV=development nest start --watch" // Вынесем настройки БД в файл config, установив пакет конфигурации nestjs командой: npm i @nestjs/config. ConfigModule.forRoot({ // Укажем путь до файла кофигурации: envFilePath: `.${process.env.NODE_ENV}.env` }), // Импортируем и сконфигурируем модуль для работы со статикой. ServeStaticModule.forRoot({ rootPath: path.resolve(__dirname, 'client'), }), // Добавим в список импортов Sequelize - современную ORM для работы с TypeScript и Node.js. SequelizeModule.forRoot({ dialect: 'postgres', host: process.env.POSTGRES_HOST, port: Number(process.env.POSTGRESS_PORT), username: process.env.POSTGRES_USER, password: process.env.POSTGRESS_PASSWORD, database: process.env.POSTGRES_DB, models: [User, Role, Profile, Token, TextBlock, Files], // Зарегистрируем модели для таблички пользователей, ролей и их связей. autoLoadModels: true }), // При создании модуля с пользователями автоматически добавился модуль UsersModule и другие. UsersModule, RolesModule, ProfileModule, AuthModule, TextBlockModule, FilesModule, MailModule, TokenModule, ] }) export class AppModule{}
import {initGame, setRounds, STATUS} from '@/redux/game'; import {MapService} from '@/services/google'; import {GamePage} from 'src/pages/game.page'; import { GoogleStreetViewFailedResponse, GoogleStreetViewResponse, } from '../payloads/google'; import { act, createMockState, createMockStore, fireEvent, render, screen, waitFor, within, } from '../utils'; const mockPush = jest.fn().mockResolvedValue(true); jest.spyOn(require('next/router'), 'useRouter').mockReturnValue({ push: mockPush, }); const getPanoramSpy = jest.spyOn( google.maps.StreetViewService.prototype, 'getPanorama' ); beforeEach(() => { jest.clearAllMocks(); jest.useFakeTimers(); }); afterEach(() => { jest.runOnlyPendingTimers(); jest.useRealTimers(); }); describe('Integration, game play', () => { const state = createMockState(); const store = createMockStore(state); store.dispatch(setRounds(2)); store.dispatch(initGame()); it('searches panorama and does not find one first', async () => { getPanoramSpy.mockRejectedValue(GoogleStreetViewFailedResponse); expect(store.getState().game.status).toBe(STATUS.PENDING_PLAYER); render(<GamePage />, store); expect( screen.getByRole('button', {name: /getting a random street view/i}) ).toBeDisabled(); await waitFor(() => expect(getPanoramSpy).toHaveBeenCalledTimes(50)); const alertDialog = screen.getByRole('alert'); expect( within(alertDialog).getByText(/no results found/i) ).toBeInTheDocument(); expect( within(alertDialog).getByText(/error getting street view data/i) ).toBeInTheDocument(); // Try again and find a panorama getPanoramSpy.mockResolvedValue(GoogleStreetViewResponse); fireEvent.click(screen.getByRole('button', {name: /search again/i})); expect(screen.queryByRole('alert')).not.toBeInTheDocument(); // Router returns a promise await waitFor(() => { expect( screen.getByRole('button', {name: /Start round/i}) ).not.toBeDisabled(); }); expect(screen.getAllByRole('heading')).toMatchSnapshot( 'intermission screen' ); expect(getPanoramSpy).toHaveBeenCalledTimes(51); }); it('round 1 works with user interaction', async () => { const mockClickEvent: Record<string, () => void> = {}; jest .spyOn(MapService.map, 'addListener') .mockImplementation((event, handler) => { const clickEvent = {latLng: {lat: () => 1, lng: () => 1}}; const func = () => handler(clickEvent); mockClickEvent[event] = func; return {remove: () => null}; }); expect(store.getState().game.status).toBe(STATUS.PENDING_PLAYER); render(<GamePage />, store); const startBtn = await screen.findByRole('button', {name: /start round/i}); fireEvent.click(startBtn); expect(screen.getByTestId('google-map-play-mode')).toBeInTheDocument(); expect(screen.getByTestId('google-sv-play-mode')).toBeInTheDocument(); const miniMap = screen.getByRole('region'); expect(miniMap).toHaveStyle({height: '150px', width: '200px'}); const openMiniMapIcon = screen.getByRole('button', { name: /mini-map open button/i, }); fireEvent.click(openMiniMapIcon); expect(miniMap).toHaveStyle({height: '700px', width: '700px'}); const closeMiniMapIcon = screen.getByRole('button', { name: /mini-map close button/i, }); fireEvent.click(closeMiniMapIcon); expect(miniMap).toHaveStyle({height: '150px', width: '200px'}); fireEvent.click(openMiniMapIcon); const submitBtn = screen.getByRole('button', { name: /location submit button/i, }); expect(submitBtn).toHaveTextContent(/place the marker/i); // Fake putting a marker on the map act(() => mockClickEvent.click()); await waitFor(() => { expect(submitBtn).toHaveTextContent(/i'm here/i); }); fireEvent.click(submitBtn); }); it('displays round 1 summary', () => { expect(store.getState().game.status).toBe(STATUS.ROUND_ENDED); const {unmount} = render(<GamePage />, store); expect(screen.getByRole('heading')).toHaveTextContent(/Round 1 is over!/i); expect(screen.getByRole('table')).toMatchSnapshot('summary screen'); expect(screen.getByRole('tablist')).toHaveTextContent( /(Result|Map|Street View|Info)/i ); expect(screen.getByRole('tab', {selected: true})).toHaveTextContent( /Result/i ); fireEvent.click(screen.getByRole('tab', {name: /Map/i})); expect(screen.getByTestId('google-map-review-mode')).toBeInTheDocument(); fireEvent.click(screen.getByRole('tab', {name: /Street View/i})); expect(screen.getByTestId('google-sv-review-mode')).toBeInTheDocument(); fireEvent.click(screen.getByRole('tab', {name: /Info/i})); const infoItems = screen.getAllByRole('listitem'); expect(infoItems).toMatchSnapshot('info table'); expect(infoItems).toHaveLength(2); fireEvent.click(screen.getByRole('tab', {name: /Result/i})); const continueBtn = screen.getByRole('button', { name: /Continue with round 2/i, }); fireEvent.click(continueBtn); // Here, unmount needs to be called explicitly because of race conditions when unmounting // https://github.com/testing-library/react-testing-library/issues/999 unmount(); }); it('dispatches score in round 2 after time runs out', async () => { expect(store.getState().game.status).toBe(STATUS.PENDING_PLAYER); render(<GamePage />, store); const startBtn = await screen.findByRole('button', {name: /start round/i}); fireEvent.click(startBtn); act(() => { jest.runAllTimers(); }); await waitFor( () => { screen.getByRole('table'); }, // Fake awaiting the game timer (30s) {timeout: 1000 * 31} ); expect(screen.getByRole('table')).toMatchSnapshot('summary'); const resultButton = screen.getByRole('button', {name: /See results!/i}); expect(resultButton).toBeInTheDocument(); fireEvent.click(resultButton); }); it('displays final game summary', () => { expect(store.getState().game.status).toBe(STATUS.FINISHED); render(<GamePage />, store); expect(screen.getByRole('table')).toMatchSnapshot('summary'); const headings = screen.getAllByRole('heading'); expect(headings[0]).toHaveTextContent(/Game over!/i); expect(headings[1]).toHaveTextContent(/Player 1 wins/i); const restartButton = screen.getByRole('button', {name: /Play again/i}); expect(restartButton).toBeInTheDocument(); fireEvent.click(restartButton); expect(mockPush).toHaveBeenCalledWith('/'); }); });
import { useState, useEffect } from 'react'; import Button from './Button'; import { useAppContext } from "./context/AppContext"; const ProductDetail = () => { const { selectedProduct, error, setLoading, loading, setError } = useAppContext(); const [quantity, setQuantity] = useState(1); console.log(quantity) useEffect(() => { const fetchData = async () => { setLoading(true); try { await new Promise((resolve) => setTimeout(resolve, 1000)); } catch (error) { setError(error); } finally { setLoading(false); } }; fetchData(); }, [selectedProduct]); const handleQuantityChange = (event) => { setQuantity(event.target.value); }; if (loading) { return ( <div className="flex justify-center items-center h-screen"> <div className="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-gray-900"></div> </div> ); } if (error) { return <div>Error: {error.message}</div>; } if (!selectedProduct) { return <div>No se ha seleccionado ningún producto</div>; } return ( <> <div className="h-screen flex flex-col md:flex-row justify-center items-center gap-10"> <div className="w-72"> <img className="m-auto" src={selectedProduct.imagen} alt={selectedProduct.nombre} /> </div> <div className='flex flex-col mx-7 md:mx-0 h-40 justify-between'> <div> <h2 className="text-2xl mb-2">{selectedProduct.nombre}</h2> <p>{selectedProduct.descripcion}</p> <p>Precio: ${selectedProduct.precio}</p> {selectedProduct.oferta && <p>¡Oferta!</p>} </div> <div className='mt-4'> <Button quantity={quantity} producto={selectedProduct} /> <div className='mt-4'> <label htmlFor="quantity">Cantidad:</label> <input className="ml-2 text-center rounded border-2 w-10" type="number" id="quantity" name="quantity" min="1" max="50" value={quantity} onChange={handleQuantityChange} /> </div> </div> </div> </div> </> ); }; export default ProductDetail;
/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "i2c.h" #include "spi.h" #include "tim.h" #include "usart.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "LED\BSP_LED.h" #include "MPU6050\BSP_MPU6050.h" #include "NRF24L01\BSP_NRF24L01.h" //#include "NRF24L01\24l01.h" /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_TIM2_Init(); MX_I2C1_Init(); MX_USART1_UART_Init(); MX_SPI1_Init(); /* USER CODE BEGIN 2 */ MPU_Init(); NRF24L01_Init(); float gx,gy,gz; short ax,ay,az; float roll,pitch; float d_roll,d_pitch,t_roll,t_pitch; KalmanFilterSys_t pSys; MPU_Get_Gyroscope(&gx,&gy,&gz); // while(1){ // MPU_Get_Accelerometer(&ax,&ay,&az); // Accel_To_Angle(&roll,&pitch,ax,ay,az); // printf("%u,%u\r\n",ax,ay); // } pSys=Get_Kalman_Filter(roll,pitch); d_roll=roll; d_pitch=pitch; //-------------------------------------------- uint8_t tmp_buf[33]=""; while(NRF24L01_Check()) { printf("not found RF chip"); HAL_Delay(1000); } printf("NRF24L01 exist\n"); NRF24L01_TX_Mode(); printf("transmit mode\n"); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ MPU_Get_Accelerometer(&ax,&ay,&az); Accel_To_Angle(&roll,&pitch,ax,ay,az); t_roll=roll; t_pitch=pitch; pitch-=d_pitch; roll-=d_roll; printf("roll=%.4f,pitch=%.4f,d_roll=%.4f,d_pitch=%.4f\r\n",t_roll,t_pitch,roll,pitch); if (-1<pitch&&pitch<1) pitch=0; if (-1<roll&&roll<1) roll=0; if (pitch<0){ tmp_buf[0]=0x10; } if (roll<0){ tmp_buf[0]=0x20; } tmp_buf[1]=(int)pitch*4; tmp_buf[2]=(int)roll*4; d_pitch=t_pitch; d_roll=t_roll; HAL_Delay(50); if(NRF24L01_TxPacket(tmp_buf)==TX_OK) { //printf("NRF24L01 sent:%d,%d,%d\r\n",tmp_buf[0],tmp_buf[1],tmp_buf[2]); } else { //printf("NRF24L01 failed\n"); } tmp_buf[0]=0; tmp_buf[1]=0; tmp_buf[2]=0; } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB buses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } } /* USER CODE BEGIN 4 */ /* USER CODE END 4 */ /** * @brief Period elapsed callback in non blocking mode * @note This function is called when TIM1 interrupt took place, inside * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment * a global variable "uwTick" used as application time base. * @param htim : TIM handle * @retval None */ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { /* USER CODE BEGIN Callback 0 */ /* USER CODE END Callback 0 */ if (htim->Instance == TIM1) { HAL_IncTick(); } /* USER CODE BEGIN Callback 1 */ if (htim->Instance == TIM2) { LED_switch(); } /* USER CODE END Callback 1 */ } /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ __disable_irq(); while (1) { } /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
//contact page import React from 'react' import { useForm } from 'react-hook-form' import { motion } from 'framer-motion' import logo from "../images/logo.png" export default function Contact() { const { register, trigger, formState:{errors} }=useForm() const handleSubmit=async (e)=>{ const isValid=await trigger() if(!isValid){ e.preventDefault(); } } return ( <div> <div className='h-1 w-full bg-gray-900'></div> <section id="contact" className="contact py-48"> {/* HEADINGS */} <motion.div initial="hidden" whileInView="visible" viewport={{ once: true, amount: 0.5 }} transition={{ duration: 0.5 }} variants={{ hidden: { opacity: 0, x: 50 }, visible: { opacity: 1, x: 0 }, }} className="flex justify-center w-full" > <div> <p className=" mb-9 font-playfair font-semibold text-4xl border-b text-center"> {/* Add text-center to center the text */} <span className="text-black ">CONTACT ME</span> TO GET STARTED </p> </div> </motion.div> {/* FORM & IMAGE */} <div className="md:flex md:justify-between gap-16 mt-5 "> <motion.div initial="hidden" whileInView="visible" viewport={{ once: true, amount: 0.5 }} transition={{ delay: 0.2, duration: 0.5 }} variants={{ hidden: { opacity: 0, y: 50 }, visible: { opacity: 1, y: 0 }, }} className="basis-1/2 mt-10 md:mt-0" > <form target="_blank" handleSubmit={handleSubmit} action="https://formsubmit.co/53b5bb8c50b12671cbc6837a041e4a4b" method="POST" > <input className="w-full bg-black text-white font-semibold placeholder-white p-3" type="text" placeholder="NAME" {...register("name", { required: true, maxLength: 100, })} /> {errors.name && ( <p className="text-red mt-1"> {errors.name.type === "required" && "This field is required."} {errors.name.type === "maxLength" && "Max length is 100 char."} </p> )} <input className="w-full bg-white font-semibold placeholder-black p-3 mt-5" type="text" placeholder="EMAIL" {...register("email", { required: true, pattern: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i, })} /> {errors.email && ( <p className="text-red mt-1"> {errors.email.type === "required" && "This field is required."} {errors.email.type === "pattern" && "Invalid email address."} </p> )} <textarea className="w-full bg-black font-semibold placeholder-white p-3 mt-5" name="message" placeholder="MESSAGE" rows="4" cols="50" {...register("message", { required: true, maxLength: 2000, })} /> {errors.message && ( <p className="text-red mt-1"> {errors.message.type === "required" && "This field is required."} {errors.message.type === "maxLength" && "Max length is 2000 char."} </p> )} <button className="p-5 bg-yellow font-semibold text-deep-blue mt-5 hover:bg-red hover:text-white transition duration-500" type="submit" > SEND ME A MESSAGE </button> </form> </motion.div> </div> </section> </div> ); };
import React from 'react'; import * as AccordionRadixUi from '@radix-ui/react-accordion'; import classNames from 'classnames'; import { Icon } from '../../atoms/icon'; import './accordion.scss'; export interface AccordionItems { /** Accordion Header Title */ headerTitle: string | React.ReactNode; /** Accordion Content */ content: string | React.ReactNode; /** ClassName to Header title */ headerTitleClassName?: string; /** Chevron Icon Name */ chevronName?: string; /** ClassName to Content */ contentClassName?: string; /** ClassName to Accordion Item */ accordionItemClassName?: string; } export interface AccordionProps { /** Accordion Items */ accordionItems: AccordionItems[]; /** Accordion Type (Single = close previous)(Multiple = open multiples) */ type: 'single' | 'multiple'; /** ClassName to Root Accordion */ rootAccordionClassName?: string; } export type AccordionTagsProps = React.PropsWithChildren<{ headerTag: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'; }>; export const Accordion = ({ accordionItems, headerTag: Component = 'h3', type = 'single', rootAccordionClassName, headerTitleClassName = 'bg-white hover:bg-primary-100', contentClassName = 'text-text-m', chevronName = 'agora-solid-chevron-down', accordionItemClassName = 'border-b border-neutral-300' }: AccordionProps & AccordionTagsProps & AccordionItems) => { const rootAccordionCss = classNames('agora-accordion flex flex-wrap', rootAccordionClassName); const renderAccordionItem = (items: AccordionItems[]) => { return items?.map((item, index) => { const headerAccordionCss = classNames( 'accordion-trigger flex p-32 w-full justify-between', item.headerTitleClassName ?? headerTitleClassName ); const contentAccordionCss = classNames('px-32 pb-32', item.contentClassName ?? contentClassName); const itemAccordionCss = classNames('w-full', item.accordionItemClassName ?? accordionItemClassName); return ( <AccordionRadixUi.Item value={`item-${index}`} key={`item-${index}`} className={itemAccordionCss}> <AccordionRadixUi.Trigger className={headerAccordionCss}> <Component className="flex">{item.headerTitle}</Component> <Icon icon={item.chevronName ?? chevronName} className="accordion-chevron ml-16" aria-hidden /> </AccordionRadixUi.Trigger> <AccordionRadixUi.Content className={contentAccordionCss}>{item.content}</AccordionRadixUi.Content> </AccordionRadixUi.Item> ); }); }; return ( <AccordionRadixUi.Root className={rootAccordionCss} type={type} {...(type === 'single' && { collapsible: true })}> {renderAccordionItem(accordionItems)} </AccordionRadixUi.Root> ); };
<?php /** * The header for our theme * * This is the template that displays all of the <head> section and everything up until <div id="content"> * * @link https://developer.wordpress.org/themes/basics/template-files/#template-partials * * @package News */ ?> <!doctype html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="profile" href="https://gmpg.org/xfn/11"> <link rel="stylesheet" type="text/css" href="<?php bloginfo('template_directory');?>/css/header.css"> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <?php //wp_body_open(); ?> <header id="masthead" class="site-header container-class"> <div class="site-branding"> <img src="<?php echo get_template_directory_uri() .'/images/header-logo.png'; ?>" alt="site-logo"> </div><!-- .site-branding --> <nav id="site-navigation" class="main-navigation"> <button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false"><?php esc_html_e( 'Primary Menu', 'news' ); ?></button> <?php wp_nav_menu( array( 'theme_location' => 'menu-2', // Display the Secondary menu 'menu_id' => 'secondary-menu', ) ); ?> </nav><!-- #site-navigation --> </header><!-- #masthead --> <script type="text/javascript"> var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>"; </script>
import React from "react"; import withLoader from "./WithLoader"; import useHover from "./useHover"; function DogImages(props) { const [hoverRef, hovering] = useHover(); return ( <div ref={hoverRef} {...props}> {hovering && <div id="hover">Hovering!</div>} <div id="list"> {props.data.message.map((dog, i) => ( <img src={dog} key={i} alt="Dog" /> ))} </div> </div> ); } export default withLoader( DogImages, "https://dog.ceo/api/breeds/image/random/6");
import { MongoMemoryServer } from 'mongodb-memory-server'; import mongoose from 'mongoose'; import jwt from 'jsonwebtoken'; declare global { // eslint-disable-next-line no-var var signin: () => string[]; } // eslint-disable-next-line @typescript-eslint/no-explicit-any let mongo: any; beforeAll(async () => { process.env.JWT_KEY = 'asdf'; mongo = await MongoMemoryServer.create({ binary: { version: '4.4.8' } }); //mongodb 5 without avx requires under 5 version const mongoUri = await mongo.getUri(); await mongoose.connect(mongoUri, { useNewUrlParser: true, useUnifiedTopology: true, }); }); beforeEach(async () => { const collections = await mongoose.connection.db.collections(); for (const collection of collections) { await collection.deleteMany({}); } }); afterAll(async () => { await mongoose.disconnect(); await mongoose.connection.close(); }); global.signin = () => { // Build a JWT payload. { id, email } const payload = { id: new mongoose.Types.ObjectId().toHexString(), email: '[email protected]', }; // Create the JWT! const token = jwt.sign(payload, process.env.JWT_KEY); // Build session Object. { jwt: MY_JWT } const session = { jwt: token }; // Turn that session into JSON const sessionJSON = JSON.stringify(session); // Take JSON and encode it as base64 const base64 = Buffer.from(sessionJSON).toString('base64'); // return as string thats the cookie with the encoded data return [`express:sess=${base64}`]; };
package org.freitas.vendas.domain.dto; import jakarta.validation.constraints.NotBlank; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.freitas.vendas.domain.enums.Role; import org.freitas.vendas.security.PasswordComplexity; /** * @author Edson da Silva Freitas * {@code @created} 11/09/2023 * {@code @project} spring-vendas */ @Data @Builder @AllArgsConstructor @NoArgsConstructor public class RegisterRequest { @NotBlank(message = "{field.login.obrigatorio}") private String login; @PasswordComplexity(minLength = 3, requireLowerCase = true, requireUpperCase = true, requireSpecialChar = true, requireNumber = true, message = "{field.senha.complexidade}") private String password; private Role role = Role.ROLE_USER; }
import { Component, OnInit } from '@angular/core'; import { ValorDominio } from '../../../core/models/dominios/valor-dominio.model'; import { ConsultarContratoResponse } from '../../../core/responses/contratos/consultar-contrato.response'; import { DominioResponse } from '../../../core/responses/dominios/dominio.response'; import { ContratoService } from '../../../services/contrato.service'; import { DominioService } from '../../../services/dominio.service'; @Component({ selector: 'app-espelho-dados-contrato', templateUrl: './espelho-dados-contrato.component.html', styleUrls: ['./espelho-dados-contrato.component.scss'] }) export class EspelhoDadosContratoComponent implements OnInit { constructor( private contratoService: ContratoService, private dominioService: DominioService) { } contrato: ConsultarContratoResponse; tipoRestricao: string = "-"; tipoAditivo: string = "-"; ngOnInit(): void { this.contratoService.contrato$.subscribe(contrato => { if (contrato != undefined) { this.contrato = contrato; this.carregarTipoRestricao(contrato.contrato.tipoRestricao); if (contrato.contrato.tipoAditivo !== null) { this.carregarTipoAditivo(contrato.contrato.tipoAditivo); } else { this.tipoAditivo = "-"; } } else this.contrato = new ConsultarContratoResponse(); }); } private carregarTipoRestricao(tipoRestricaoId: number) { this.dominioService.obterPorTipo('TIPO_RESTRICAO') .subscribe((response: DominioResponse) => { if (response.isSuccessful) { response.valorDominio.forEach((dominio: ValorDominio) => { if (dominio.id == tipoRestricaoId) this.tipoRestricao = dominio.valor; }) } }) } private carregarTipoAditivo(tipoAditivoId: number) { this.dominioService.obterPorTipo('TIPO_ADITIVO') .subscribe((response: DominioResponse) => { if (response.isSuccessful) { response.valorDominio.forEach((dominio: ValorDominio) => { if (dominio.id == tipoAditivoId) this.tipoAditivo = dominio.valor; }) } }) } }
/** * MIDDLEWARE * What is middleware? * How to make a middleware? * Apply middle ware on routes. * Types of middleware. */ const express = require('express'); const app = express(); const reqFilter = (req, res, next) => { if(!req.query.age){ res.send('Please provide your age!'); } else if(req.query.age < 18){ res.send("You can't access this data!"); } else{ next(); } } app.use(reqFilter); app.get('', (req, res) => { res.send('Welcome home page'); }); app.get('/about', (req, res) => { res.send('This is about page'); }); app.listen('5000');
// Setup.jsx import React, { useState } from 'react'; import { signOut } from 'firebase/auth'; import { auth } from '../config/firebaseConfig'; import { useNavigate } from 'react-router-dom'; import SetupPersonalInfo from '../components/Setup/SetupPersonalInfo'; import SetupClasses from '../components/Setup/SetupClasses'; import SetupFriends from '../components/Setup/SetupFriends'; function Setup({ setJustCreated }) { const [currentStep, setCurrentStep] = useState(1); const navigate = useNavigate(); const signOutUser = () => { signOut(auth).then(() => { navigate("/signin"); }).catch((error) => { console.error("An error happened during sign-out:", error); }); } return ( <div className="setup"> <div> <button onClick={signOutUser}>Sign Out</button> </div> {currentStep === 1 && ( <SetupPersonalInfo setJustCreated={setJustCreated} onNext={() => setCurrentStep(2)} /> )} {currentStep === 2 && ( <SetupClasses onBack={() => setCurrentStep(1)} onNext={() => setCurrentStep(3)} /> )} {currentStep === 3 && ( <SetupFriends onBack={() => setCurrentStep(2)} onNext={() => navigate('/home')} /> )} </div> ); } export default Setup;
// Copyright 2023 Ready.io /* eslint-disable import/no-unused-modules */ import type PQueue from 'p-queue' import { ConversationType } from 'types/chat' import { strictAssert } from 'utils/assert' import { isTestEnvironment } from 'utils/environment' import type { LoggerType } from 'utils/logger' import { z } from 'zod' import { OutgoingIdentityKeyError, SendMessageProtoError } from '../textsecure/Errors' import MessageSender from '../textsecure/MessageSender' import type { UUIDStringType } from '../types/UUID' import * as durations from '../utils/durations' import { exponentialBackoffMaxAttempts } from '../utils/exponentialBackoff' import { commonShouldJobContinue } from './helpers/commonShouldJobContinue' import { InMemoryQueues } from './helpers/InMemoryQueues' import { sendDeleteForEveryone, sendDeleteForOnlyMe } from './helpers/sendDelete' import { sendGroupUpdate } from './helpers/sendGroupUpdate' import { sendNormalMessage } from './helpers/sendNormalMessage' import { sendReaction } from './helpers/sendReaction' import { sendReceipts } from './helpers/sendReceipts' import { sendTokenRequestResponse } from './helpers/sendTokenRequestResponse' import type { Job } from './Job' import { JobQueue } from './JobQueue' import { jobQueueDatabaseStore } from './JobQueueDatabaseStore' import type { ParsedJob } from './types' // Note: generally, we only want to add to this list. If you do need to change one of // these values, you'll likely need to write a database migration. export const conversationQueueJobEnum = z.enum([ 'NormalMessage', 'Reaction', 'Receipts', 'DeleteForEveryone', 'DeleteForOnlyMe', // 'DeleteStoryForEveryone', // 'DirectExpirationTimerUpdate', 'GroupUpdate', // 'ProfileKey', 'ResendRequest', // 'SavedProto', // 'SenderKeyDistribution', // 'Story', 'TokenRequestResponse', ]) const normalMessageSendJobDataSchema = z.object({ type: z.literal(conversationQueueJobEnum.enum.NormalMessage), conversationId: z.string(), messageId: z.string(), // Note: recipients are baked into the message itself revision: z.number().optional(), // See sendEditedMessage editedMessageTimestamp: z.number().optional(), }) export type NormalMessageSendJobData = z.infer<typeof normalMessageSendJobDataSchema> const deleteForEveryoneJobDataSchema = z.object({ type: z.literal(conversationQueueJobEnum.enum.DeleteForEveryone), // sender: z.string(), conversationId: z.string(), messageId: z.string(), recipients: z.array(z.string()), attachments: z.optional(z.array(z.string())), }) export type DeleteForEveryoneJobData = z.infer<typeof deleteForEveryoneJobDataSchema> const deleteForOnlyMeJobDataSchema = z.object({ type: z.literal(conversationQueueJobEnum.enum.DeleteForOnlyMe), conversationId: z.string(), messageId: z.string(), attachments: z.optional(z.array(z.string())), }) export type DeleteForOnlyMeJobData = z.infer<typeof deleteForOnlyMeJobDataSchema> const reactionJobDataSchema = z.object({ type: z.literal(conversationQueueJobEnum.enum.Reaction), conversationId: z.string(), messageId: z.string(), // Note: recipients are baked into the message itself // revision: z.number().optional(), }) export type ReactionJobData = z.infer<typeof reactionJobDataSchema> const groupUpdateJobDataSchema = z.object({ type: z.literal(conversationQueueJobEnum.enum.GroupUpdate), sender: z.string(), conversationId: z.string(), groupChangeBase64: z.string().optional(), recipients: z.array(z.string()), revision: z.number(), }) export type GroupUpdateJobData = z.infer<typeof groupUpdateJobDataSchema> const resendRequestJobDataSchema = z.object({ type: z.literal(conversationQueueJobEnum.enum.ResendRequest), conversationId: z.string(), contentHint: z.number().optional(), groupId: z.string().optional(), plaintext: z.string(), receivedAtCounter: z.number(), receivedAtDate: z.number(), senderUuid: z.string(), senderDevice: z.number(), timestamp: z.number(), }) export type ResendRequestJobData = z.infer<typeof resendRequestJobDataSchema> export enum ReceiptType { Delivery = 'deliveryReceipt', Read = 'readReceipt', Viewed = 'viewedReceipt', } const receiptsJobDataSchema = z.object({ type: z.literal(conversationQueueJobEnum.enum.Receipts), conversationId: z.string(), receiptType: z.nativeEnum(ReceiptType), timestamp: z.number(), }) export type ReceiptsJobData = z.infer<typeof receiptsJobDataSchema> const tokenRequestResponseJobDataSchema = z.object({ type: z.literal(conversationQueueJobEnum.enum.TokenRequestResponse), conversationId: z.string(), messageId: z.string(), response: z.union([z.literal('accept'), z.literal('reject')]), timestamp: z.number(), }) export type TokenRequestResponseJobData = z.infer<typeof tokenRequestResponseJobDataSchema> const conversationQueueJobDataSchema = z.union([ deleteForEveryoneJobDataSchema, deleteForOnlyMeJobDataSchema, // deleteStoryForEveryoneJobDataSchema, // expirationTimerUpdateJobDataSchema, groupUpdateJobDataSchema, normalMessageSendJobDataSchema, // nullMessageJobDataSchema, // profileKeyJobDataSchema, reactionJobDataSchema, resendRequestJobDataSchema, // savedProtoJobDataSchema, // senderKeyDistributionJobDataSchema, // storyJobDataSchema, receiptsJobDataSchema, tokenRequestResponseJobDataSchema, ]) type ConversationQueueJobData = z.infer<typeof conversationQueueJobDataSchema> export type ConversationQueueJobBundle = { isFinalAttempt: boolean log: LoggerType messaging: MessageSender shouldContinue: boolean timeRemaining: number timestamp: number } const MAX_RETRY_TIME = durations.DAY const MAX_ATTEMPTS = isTestEnvironment() ? 1 : exponentialBackoffMaxAttempts(MAX_RETRY_TIME) class ConversationJobQueue extends JobQueue<ConversationQueueJobData> { private readonly inMemoryQueues = new InMemoryQueues() // private readonly verificationWaitMap = new Map< // string, // { // resolve: (value: unknown) => unknown; // reject: (error: Error) => unknown; // promise: Promise<unknown>; // } // >(); getQueues(): ReadonlySet<PQueue> { return this.inMemoryQueues.allQueues } public async add( data: Readonly<ConversationQueueJobData>, insert?: (job: ParsedJob<ConversationQueueJobData>) => Promise<void> ): Promise<Job<ConversationQueueJobData>> { // const { conversationId, type } = data; // strictAssert( // window.Signal.challengeHandler, // 'conversationJobQueue.add: Missing challengeHandler!' // ); // window.Signal.challengeHandler.maybeSolve({ // conversationId, // reason: `conversationJobQueue.add(${conversationId}, ${type})`, // }); return super.add(data, insert) } protected parseData(data: unknown): ConversationQueueJobData { return conversationQueueJobDataSchema.parse(data) } protected getInMemoryQueue({ data }: Readonly<{ data: ConversationQueueJobData }>): PQueue { return this.inMemoryQueues.get(data.conversationId) } // private startVerificationWaiter(conversationId: string): Promise<unknown> {} // public resolveVerificationWaiter(conversationId: string): void {} protected async run( { data, timestamp }: Readonly<{ data: ConversationQueueJobData; timestamp: number }>, { attempt, log }: Readonly<{ attempt: number; log: LoggerType }> ): Promise<void> { const { type, conversationId } = data const isFinalAttempt = attempt >= MAX_ATTEMPTS await window.Ready.conversationController.load('ConversationJobQueue.run') const conversation = window.Ready.conversationController.get(conversationId) if (!conversation) { throw new Error(`Failed to find conversation ${conversationId}`) } const sender = conversation.attributes.accountId let timeRemaining: number let shouldContinue: boolean let count = 0 while (true) { count += 1 log.info('calculating timeRemaining and shouldContinue...') timeRemaining = timestamp + MAX_RETRY_TIME - Date.now() shouldContinue = await commonShouldJobContinue({ attempt, log, timeRemaining, skipWait: count > 1, }) if (true) { // !shouldContinue) { break } // if (window.Signal.challengeHandler?.isRegistered(conversationId)) { // if (this.isShuttingDown) { // throw new Error("Shutting down, can't wait for captcha challenge."); // } // log.info( // 'captcha challenge is pending for this conversation; waiting at most 5m...' // ); // // eslint-disable-next-line no-await-in-loop // await Promise.race([ // this.startVerificationWaiter(conversation.id), // // don't resolve on shutdown, otherwise we end up in an infinite loop // sleeper.sleep( // 5 * MINUTE, // `conversationJobQueue: waiting for captcha: ${conversation.idForLogging()}`, // { resolveOnShutdown: false } // ), // ]); // continue; // } // const verificationData = // window.reduxStore.getState().conversations // .verificationDataByConversation[conversationId]; // if (!verificationData) { // break; // } // if ( // verificationData.type === // ConversationVerificationState.PendingVerification // ) { // if (type === conversationQueueJobEnum.enum.ProfileKey) { // log.warn( // "Cancelling profile share, we don't want to wait for pending verification." // ); // return; // } // if (this.isShuttingDown) { // throw new Error("Shutting down, can't wait for verification."); // } // log.info( // 'verification is pending for this conversation; waiting at most 5m...' // ); // // eslint-disable-next-line no-await-in-loop // await Promise.race([ // this.startVerificationWaiter(conversation.id), // // don't resolve on shutdown, otherwise we end up in an infinite loop // sleeper.sleep( // 5 * MINUTE, // `conversationJobQueue: verification pending: ${conversation.idForLogging()}`, // { resolveOnShutdown: false } // ), // ]); // continue; // } // if ( // verificationData.type === // ConversationVerificationState.VerificationCancelled // ) { // if (verificationData.canceledAt >= timestamp) { // log.info( // 'cancelling job; user cancelled out of verification dialog.' // ); // shouldContinue = false; // } else { // log.info( // 'clearing cancellation tombstone; continuing ahead with job' // ); // window.reduxActions.conversations.clearCancelledConversationVerification( // conversation.id // ); // } // break; // } // throw missingCaseError(verificationData); } const { messageSender } = window.Ready if (!messageSender) { throw new Error('messaging interface is not available!') } const jobBundle: ConversationQueueJobBundle = { messaging: messageSender, isFinalAttempt, shouldContinue, timeRemaining, timestamp, log, } // Note: A six-letter variable makes below code autoformatting easier to read. const jobSet = conversationQueueJobEnum.enum try { switch (type) { case jobSet.NormalMessage: await sendNormalMessage(conversation, jobBundle, data) break case jobSet.Reaction: await sendReaction(conversation, jobBundle, data) break case jobSet.Receipts: await sendReceipts(conversation, jobBundle, data) break case jobSet.DeleteForEveryone: await sendDeleteForEveryone(conversation, jobBundle, data) break case jobSet.DeleteForOnlyMe: await sendDeleteForOnlyMe(conversation, jobBundle, data) break // case jobSet.DeleteStoryForEveryone: // await sendDeleteStoryForEveryone(conversation, jobBundle, data) // break // case jobSet.DirectExpirationTimerUpdate: // await sendDirectExpirationTimerUpdate(conversation, jobBundle, data) // break case jobSet.GroupUpdate: await sendGroupUpdate(conversation, jobBundle, data) break // case jobSet.NullMessage: // await sendNullMessage(conversation, jobBundle, data); // break; // case jobSet.ProfileKey: // await sendProfileKey(conversation, jobBundle, data) // break // case jobSet.ResendRequest: // await sendResendRequest(conversation, jobBundle, data) // break // case jobSet.SavedProto: // await sendSavedProto(conversation, jobBundle, data) // break // case jobSet.SenderKeyDistribution: // await sendSenderKeyDistribution(conversation, jobBundle, data) // break // case jobSet.Story: // await sendStory(conversation, jobBundle, data); // break; case jobSet.TokenRequestResponse: await sendTokenRequestResponse(conversation, jobBundle, data) break default: { // Note: This should never happen, because the zod call in parseData wouldn't // accept data that doesn't look like our type specification. log.error(`conversationJobQueue: Got job with type ${type}; Cancelling job.`) } } } catch (error: unknown) { const untrustedUuids: Array<UUIDStringType> = [] const processError = async (toProcess: unknown) => { if (toProcess instanceof OutgoingIdentityKeyError) { const failedConversation = await window.Ready.conversationController.getOrCreate( 'conversationJobQueue.run.processError', sender, toProcess.identifier as UUIDStringType, ConversationType.PRIVATE, undefined ) strictAssert(failedConversation, 'Conversation should be created') const uuid = failedConversation.attributes.identifier as UUIDStringType if (!uuid) { log.error( `failedConversation: Conversation ${failedConversation.id}|${failedConversation.attributes.identifier} missing UUID!` ) return } untrustedUuids.push(uuid) } } await processError(error) if (error instanceof SendMessageProtoError) { Promise.all((error.errors || []).map(processError)) } if (untrustedUuids.length) { // if (type === jobSet.ProfileKey) { // log.warn( // `Cancelling profile share, since there were ${untrustedUuids.length} untrusted send targets.` // ) // return // } if (type === jobSet.Receipts) { log.warn(`Cancelling receipt send, since there were ${untrustedUuids.length} untrusted send targets.`) return } log.error( `Send failed because ${untrustedUuids.length} conversation(s) were untrusted. Adding to verification list.` ) // window.reduxActions.conversations.conversationStoppedByMissingVerification( // { // conversationId: conversation.id, // untrustedUuids, // } // ); } throw error } finally { log.info(`FINISHED`) } } } export const conversationJobQueue = new ConversationJobQueue({ store: jobQueueDatabaseStore, queueType: 'conversation', maxAttempts: MAX_ATTEMPTS, })
import React from 'react'; const Service = () => { const [view, setView] = React.useState('password'); const [userInfo, setUserInfo] = React.useState({}); const getData = (e) => { setUserInfo({ ...userInfo, [e.target.name]: e.target.value }) } const passValidation = () => { const splitVal = userInfo?.password.split(''); for (let i = 0; i < splitVal.length; i++) { if (splitVal[i] === '0') { splitVal[i] = 'zero'; } else if (splitVal[i] === '1') { splitVal[i] = 'one'; } else if (splitVal[i] === '2') { splitVal[i] = 'two'; } } const pass = splitVal.toString(); const changeVal = pass.replaceAll(',', '') const newUserInfo = { ...userInfo, password: changeVal }; return newUserInfo; }; const submitBtn = () => { const validateUser = passValidation(); console.log(validateUser); } /** * pass box input 123 : onetowthree 1 2 3: one tow three asd123: asdonetowthree */ return ( <div> <h1>Service</h1> <button onClick={() => setView(view === 'text' ? 'password' : 'text')}>View Pass</button> <br /> <input type="text" name="name" onChange={(e) => getData(e)} /> <input type="text" name="email" onChange={(e) => getData(e)} /> <input type={view} name="password" onChange={(e) => getData(e)} /> <button onClick={() => submitBtn()}>Submit</button> </div> ); }; export default Service;
<?php interface Observer { public function update($event_info = null); } interface Subject { public function attach($o); public function detach($o); public function notify(); } class User implements Subject { private $observers = []; public function attach($o) { $this->observers[] = $o; } public function detach($o) { $index = array_search($o, $this->observers); if ($index !== false) { unset($this->observers[$index]); } } public function notify() { foreach ($this->observers as $o) { $o->update('何か変更あった'); } } public function changeEmail($email) { $this->notify(); } } class UserObserver implements Observer { public function update($event_info = null) { echo "ユーザーでなんか変更あった" . $event_info . PHP_EOL; } } $u = new User(); $uo = new UserObserver(); $u->attach($uo); $u->changeEmail('[email protected]');
package com.kolip.numberle; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import androidx.annotation.Nullable; import com.kolip.numberle.clasic.BoxStatus; import java.util.HashMap; import java.util.function.Consumer; public class CustomNumPad extends LinearLayout { HashMap<String, View> keyMap = new HashMap<>(); HashMap<String, BoxStatus> keyStatus = new HashMap<>(); public CustomNumPad(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context); } public CustomNumPad(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } public CustomNumPad(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context); } private void init(Context context) { LayoutInflater.from(context).inflate(R.layout.custom_num_pad, this, true); } private void attachListener(Consumer<View> keyListener) { keyMap.put("0", findViewById(R.id.num_0)); keyMap.put("1", findViewById(R.id.num_1)); keyMap.put("2", findViewById(R.id.num_2)); keyMap.put("3", findViewById(R.id.num_3)); keyMap.put("4", findViewById(R.id.num_4)); keyMap.put("5", findViewById(R.id.num_5)); keyMap.put("6", findViewById(R.id.num_6)); keyMap.put("7", findViewById(R.id.num_7)); keyMap.put("8", findViewById(R.id.num_8)); keyMap.put("9", findViewById(R.id.num_9)); keyMap.put("delete", findViewById(R.id.key_delete)); keyMap.put("enter", findViewById(R.id.key_Enter)); keyStatus.put("0", BoxStatus.EMPTY_TEXT); keyStatus.put("1", BoxStatus.EMPTY_TEXT); keyStatus.put("2", BoxStatus.EMPTY_TEXT); keyStatus.put("3", BoxStatus.EMPTY_TEXT); keyStatus.put("4", BoxStatus.EMPTY_TEXT); keyStatus.put("5", BoxStatus.EMPTY_TEXT); keyStatus.put("6", BoxStatus.EMPTY_TEXT); keyStatus.put("7", BoxStatus.EMPTY_TEXT); keyStatus.put("8", BoxStatus.EMPTY_TEXT); keyStatus.put("9", BoxStatus.EMPTY_TEXT); keyMap.values().forEach(key -> key.setOnClickListener(keyListener::accept)); } public void setKeyListener(Consumer<View> listener) { attachListener(listener); } public void setDisable(String key, boolean disable) { if (key.equals("")) return; keyMap.get(key).setClickable(!disable); keyMap.get(key).setAlpha(disable ? 0.5f : 1.0f); } public void setStyle(String key, BoxStatus status) { if (status == BoxStatus.CORRECT_POSITION) { keyMap.get(key).setBackgroundColor(getResources().getColor(R.color.green)); ((Button) keyMap.get(key)).setTextColor(getResources().getColor(R.color.white)); keyStatus.put(key, status); } else if (status == BoxStatus.WRONG_POSITION && keyStatus.get(key) != BoxStatus.CORRECT_POSITION) { keyMap.get(key).setBackgroundColor(getResources().getColor(R.color.yellow)); ((Button) keyMap.get(key)).setTextColor(getResources().getColor(R.color.white)); keyStatus.put(key, status); } else if (status == BoxStatus.WRONG_CHAR && keyStatus.get(key) != BoxStatus.CORRECT_POSITION && keyStatus.get(key) != BoxStatus.WRONG_POSITION) { keyMap.get(key).setBackgroundColor(getResources().getColor(R.color.gray_600)); ((Button) keyMap.get(key)).setTextColor(getResources().getColor(R.color.white)); keyStatus.put(key, status); } } public void clear() { for (View value : keyMap.values()) { if (value.getId() == R.id.key_Enter || value.getId() == R.id.key_delete) continue; ((Button) value).setTextColor(getResources().getColor(R.color.black)); value.setBackgroundColor(getResources().getColor(R.color.light_grey)); } keyStatus.keySet().forEach(key -> keyStatus.put(key, BoxStatus.EMPTY_TEXT)); setClickable(true); setAlpha(1.0f); } public void setDisableAll(boolean disable) { keyMap.values().forEach(v -> { v.setClickable(!disable); v.setAlpha(1.0f); }); } }
Binary search tree object methods #include "binary-search-tree.h" #include <iostream> #include <queue> #include <algorithm> BinarySearchTree::Node::Node(DataType newval) { val = newval; left = nullptr; right = nullptr; } int BinarySearchTree::getNodeDepth(Node* n) const { if(n == nullptr){ return -9999; } else if(n->right == nullptr && n->left == nullptr){ return 0; } else{ return (1 + std::max(getNodeDepth(n->left), getNodeDepth(n->right))); } } BinarySearchTree::BinarySearchTree() { root_ = nullptr; size_ = 0; } BinarySearchTree::~BinarySearchTree() { std::queue <Node*> Q; if(root_ == nullptr){ std::cout << "Tree is empty" << std::endl; return; } Q.push(root_); while(!Q.empty()){ Node *del = Q.front(); if(del->left != nullptr){ Q.push(del->left); } if(del->right != nullptr){ Q.push(del->right); } Q.pop(); delete del; } } j unsigned int BinarySearchTree::size() const { return size_; } BinarySearchTree::DataType BinarySearchTree::max() const { Node *max = root_; while(max->right != nullptr){ max = max->right; } return max->val; } BinarySearchTree::DataType BinarySearchTree::min() const { Node *min = root_; while(min->left != nullptr){ min = min->left; } return min->val; } unsigned int BinarySearchTree::depth() const { unsigned int depth = getNodeDepth(root_); return depth; } void BinarySearchTree::print() const { if(root_ == nullptr){ std::cout << "Tree is empty." << std::endl; return; } else{ std::queue <Node*> Q; Q.push(root_); while(!Q.empty()){ Node *node = Q.front(); Q.pop(); std::cout << node->val << ", "; if(node->left != nullptr){ Q.push(node->left); } if(node->right != nullptr){ Q.push(node->right); } } std::cout << std::endl; } } bool BinarySearchTree::exists(DataType val) const { Node *current = root_; while(current != nullptr){ if(current->val == val){ return true; } else if(val < current->val){ current = current->left; } else{ current = current->right; } } return false; } BinarySearchTree::Node* BinarySearchTree::getRootNode() { return root_; } BinarySearchTree::Node** BinarySearchTree::getRootNodeAddress() { return &root_; } bool BinarySearchTree::insert(DataType val) { Node *insert = new Node(val); if(exists(val)){ return false; } if(root_ == nullptr){ root_ = insert; size_ = 1; return true; } Node *current = root_; Node *parent = nullptr; while(current != nullptr) { parent = current; if (val < current->val) { current = current->left; } else { current = current->right; } } if(val < parent->val){ parent->left = insert; } else{ parent->right = insert; } size_++; return true; } bool BinarySearchTree::remove(DataType val) { if(!exists(val)){ return false; } Node *removed = root_; Node *parent = nullptr; while(removed != nullptr && removed->val != val){ parent = removed; if(val < removed->val){ removed = removed->left; } else{ removed = removed->right; } } //Case 1: Node has no children if(removed->right == nullptr && removed->left == nullptr){ if(removed == root_){ delete root_; root_ = nullptr; } else if(parent->left == removed){ delete removed; parent->left = nullptr; } else{ delete removed; parent->right = nullptr; } } //Case 2: Node has a left child, no right child else if(removed->left != nullptr && removed->right == nullptr){ if(removed == root_){ root_ = removed->left; } else if(parent->left == removed){ parent->left = removed->left; } else{ parent->right = removed->left; } delete removed; } //Case 3: Node has a right child, no left child else if(removed->right != nullptr && removed->left == nullptr){ if(removed == root_){ root_ = removed->right; } else if(parent->left == removed){ parent->left = removed->right; } else{ parent->right = removed->right; } delete removed; } //Case 4: Node has two children else if(removed->left != nullptr && removed->right != nullptr) { Node *predecessor = removed->left; Node *predecessor_parent = removed; while (predecessor->right != nullptr) { predecessor_parent = predecessor; predecessor = predecessor->right; } removed->val = predecessor->val; //predecessor has no left child if(predecessor->left == nullptr){ if(predecessor == removed->left){ removed->left = nullptr; } else{ predecessor_parent->right = nullptr; } } //predecessor has a left child else{ if(predecessor == removed->left){ predecessor_parent->left = predecessor->left; } else{ predecessor_parent->right = predecessor->left; } } delete predecessor; predecessor = nullptr; predecessor_parent = nullptr; } removed = nullptr; parent = nullptr; size_--; return true; }
// // QuakeError.swift // Earthquakes // // Created by hybrayhem. // import Foundation enum QuakeError: Error { case missingData case networkError case unexpectedError(error: Error) } extension QuakeError: LocalizedError { var errorDescription: String? { switch self { case .missingData: return NSLocalizedString( "Found and will discard a quake missing a valid code, magnitude, place, or time.", comment: "" ) case .networkError: return NSLocalizedString( "Error fetching quake data over the network.", comment: "" ) case .unexpectedError(let error): return NSLocalizedString( "Received unexpected error. \(error.localizedDescription)", comment: "" ) } } }
/* ScummVM Tools * * ScummVM Tools is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /* List & description of all the supported tools */ #ifndef GUI_TOOLS_H #define GUI_TOOLS_H #include <wx/string.h> #include <map> #include <vector> #include "configuration.h" #include "../tools.h" /** * A tool supported by the Wizard, holds all information about what format it supports * what input it requires etc. * This is just the frontend, for the backend, the 'Tool' class is used, which this class * holds an instance off. * * @todo Move some logic to the 'Tool' class * @todo Add some way to represent extra arguments to the tool */ class ToolGUI { // Block copy-construction ToolGUI(const ToolGUI &); public: /** * Creates a new tool, can be stack allocated and copied without problems * The type of tool is deduced from the name, if it contains 'extract', it's an extraction tool * and if it contains 'compress' it's a compression tool. If the tool does not contain either, * you must set the type manually. * * @param name The name of the tool, should match the executable name (without the extension) */ ToolGUI(Tool *tool, ToolType type = TOOLTYPE_UNKNOWN); ~ToolGUI(); /** * Adds a supported game to this tool * * @param game_name The name of the game this tool supports */ void addGame(const wxString &game_name); /** * Returns the list of valid inputs of this tool, along with the * paths already set (if applicable) */ ToolInputs getInputList() const; /** * Returns the name of the tool */ wxString getName() const; /** * Returns the helptext of the tool */ wxString getHelp() const; /** * Returns the short version of the helptext, much more suitable for the GUI */ wxString getShortHelp() const; /** * Returns the type of the tool */ ToolType getType() const; // Helper functions to get info about the tool /** * Returns true if the audio format(s) is supported by this tool * * @param format The audio format(s) to test for */ bool supportsAudioFormat(AudioFormat format) const; /** * Returns true if the tool supports a load bar for displaying progress */ bool supportsProgressBar() const; /** * Returns true if the tool outputs to an entire directory, not a single file */ bool outputToDirectory() const; /** * Returns true if the tool can be run again on other files with the same * extension in the same directory. */ bool supportsMultipleRuns() const; /** * Runs the actual tool, will throw errors if it fails */ void run(const Configuration &conf) const; /** The actual tool instance, which runs the compression/extraction */ Tool *_backend; }; // Collection of all tools class ToolsGUI : public Tools { public: ToolsGUI(); ~ToolsGUI(); /** * Must be called before the tools can be used * Setup cannot be done in the constructor since it depends on wx setup code * that must be run before it. */ void init(); /** * Returns a tool by name * asserts if the tool is not found * * @param name Name of the tool to fetch * @return A reference to the tool, tools cannot be modified. */ const ToolGUI &operator[](const wxString &name) const; /** * Returns a tool by name * * @param name Name of the tool to fetch * @return A pointer to the tool, NULL if there is no tool by that name. */ const ToolGUI *get(const wxString &name) const; /** * Returns a list of all tools * * @param tt Filter by this type of tool * @return Returns all tools of this type, list is sorted and contains no duplicates */ wxArrayString getToolList(ToolType tt = TOOLTYPE_ALL) const; /** * Inspects the file and returns a list of tools that might be able to handle it * * @param filename The path to the file to inspect * @param tt Only check tools of this type * @return Returns all tools might be able to handle the file or the directory containing that file */ wxArrayString getToolList(const Common::Filename &filename, ToolType tt = TOOLTYPE_ALL) const; protected: std::map<wxString, ToolGUI *> _toolmap; }; extern ToolsGUI g_tools; #endif
import datetime import email import email.utils import json import os import re import boto3 import requests from bs4 import BeautifulSoup import llm S3_BUCKET_NAME = os.environ.get("S3_BUCKET_NAME") GCP_SECRET_NAME = os.environ.get("GCP_SECRET_NAME") TELEGRAM_SECRET_NAME = os.environ.get("TELEGRAM_SECRET_NAME") REGION_NAME = "eu-west-1" SUMMARY_TABLE_NAME = os.environ.get("SUMMARY_TABLE_NAME") TELEGRAM_API_ENDPOINT = "https://api.telegram.org/bot%s/sendMessage" def load_telegram_credentials(): session = boto3.session.Session() client = session.client(service_name="secretsmanager", region_name=REGION_NAME) get_secret_value_response = client.get_secret_value(SecretId=TELEGRAM_SECRET_NAME) telegram_credentials = get_secret_value_response["SecretString"] return json.loads(telegram_credentials) def load_gcp_credentials(): session = boto3.session.Session() client = session.client(service_name="secretsmanager", region_name=REGION_NAME) get_secret_value_response = client.get_secret_value(SecretId=GCP_SECRET_NAME) gcp_cred = get_secret_value_response["SecretString"] with open("/tmp/credentials.json", "w") as f: f.write(gcp_cred) os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/tmp/credentials.json" def clean_html(raw_html: str) -> str: soup = BeautifulSoup(raw_html, "html.parser") text = soup.get_text(" ") return re.sub("\s+", " ", text).strip() def lambda_handler(event, context): load_gcp_credentials() print("Loaded GCP Credentials successfully") s3 = boto3.resource("s3") message_id = event["Records"][0]["ses"]["mail"]["messageId"] email_object = s3.Object( bucket_name=S3_BUCKET_NAME, key=message_id, ) resp = email_object.get() data = resp["Body"].read() print(f"Loaded email message ID {message_id}") msg = email.message_from_bytes(data) if msg["Subject"] != "Weekend travel advice": print(f'Skipping email with subject {msg["Subject"]}') return { "statusCode": 200, } texts = [ part.get_payload() for part in msg.walk() if part.get_content_type() == "text/html" ] content = clean_html("\n".join(texts)) summary = llm.produce_summary(content) print(f"Got summary from LLM: {summary}") email_date = email.utils.parsedate_to_datetime(msg.get("Date")) week_number = email_date.strftime("%Y-%W") print(f"Email is dated {email_date}, converting to {week_number}") ttl = email_date + datetime.timedelta(days=15) item = { "week-id": {"S": week_number}, "summary": {"S": summary}, "ttl": {"N": str(int(ttl.timestamp()))}, "email-id": {"S": message_id}, } dynamodb = boto3.client("dynamodb") resp = dynamodb.put_item(TableName=SUMMARY_TABLE_NAME, Item=item) print(f"Got response from DynamoDB: {resp}") telegram_creds = load_telegram_credentials() r = requests.post( TELEGRAM_API_ENDPOINT % telegram_creds["bot_token"], data={ "chat_id": telegram_creds["channel_id"], "text": summary[:4096], "parse_mode": "Markdown", }, ) print(f"Got response from Telegram {r.json()}") return { "statusCode": 200, }
/* ''' Suppose you're a school headmaster and somebody has drafted a course list for a new program. Each course has an ID associated with it, and they may have prerequisites. There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1. Return true if you can finish all courses. Otherwise, return false. EXAMPLE(S) Input: numCourses = 1, prerequisites = [[1,0]] Output: true Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. Input: numCourses = 2, prerequisites = [[1,0],[0,1]] Output: false Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. DFS Time: O(v+e) Space: O(v+e) Convert prerequisites -> adjList traverseing all numCourses, 0 -> numCourses into a recursive function check if all courses meet prerequisites, return true return false Use visited map to mark courses visited helper check visited for course, return false check adjList at course length is empty, return true loop the course in adjList recursive call add course to visited adjList at course to empty array return false FUNCTION SIGNATURE function courseSchedule(numCourses, prerequisites) ''' */ // Input: numCourses = 1, prerequisites = [[1,0]] /** * { * 0:[] * 1:[0] * } */ function courseSchedule(numCourses, prerequisites){ const adjList = {} for(let i = 0; i <= numCourses; i++){ adjList[i] = [] } for(let [pre, course] of prerequisites){ adjList[pre].push(course) } const visited = {} function helper(course){ if(visited[course]) return false if(!adjList[course].length) return true visited[course] = 1 for(const crs of adjList[course]){ if(!helper(crs)) return false } visited[course] = 0 adjList[course] = [] return true } for(let crs = 0; crs < numCourses; crs++){ if(!helper(crs)) return false } return true } //1, [0, 1], [0, 2] console.log(courseSchedule(1, [[1,0]])) //true console.log(courseSchedule(2, [[1,0],[0,1]])) //false console.log(courseSchedule(3, [[1,0],[2,0]])) // true console.log(courseSchedule(3, [[1,0],[2,1]])) // true console.log(courseSchedule(3, [[0,1],[0,2]])) // true console.log(courseSchedule(1, [[0,1],[0,2]])) // true /** * { * 0:[] * 1:[] * } */ 1, 2, 0 2, 1, 0 function courseSchedule(numCourses, prerequisites) { const graph = new Map(); const indegree = Array(numCourses).fill(0); const queue = []; const coursesTaken = []; for (const [v, e] of prerequisites) { if (graph.has(v)) { graph.get(v).push(e); } else { graph.set(v, [e]); } indegree[e]++; } // Push our starting/no-dependency nodes into a queue for (let i = 0; i < numCourses; i++) { if (indegree[i] === 0) queue.push(i); } // Process our course dependencies while (queue.length) { // Dequeue course const course = queue.shift(); // Push to order coursesTaken.push(course); // Track indegree edges const dependentCourses = graph.get(course); if (dependentCourses) { for (const dependentCourse of dependentCourses) { indegree[dependentCourse]--; if (indegree[dependentCourse] === 0) queue.push(dependentCourse); } } } // Return results at end return numCourses === coursesTaken.length; };
import React, { useEffect, useState } from "react"; import 'bootstrap/dist/css/bootstrap.min.css'; import { Modal } from "react-bootstrap"; import "../style/global.css"; import { useForm } from "react-hook-form"; import { z } from "zod"; import { useNavigate } from "react-router-dom"; import { zodResolver } from "@hookform/resolvers/zod"; interface UserData { nome: string; idade: string; sexo: string; cidade: string; frequenciaCardiaca: number; pressaoArterial: string; temperatura: number; saturacaoOxigenio: number; frequenciaCardiacaalerta: boolean; frequenciaCardiacaemergencia: boolean; temperaturaalerta: boolean; temperaturaemergencia: boolean; saturacaoOxigenioalerta: boolean; saturacaoOxigenioemergencia: boolean; dataLeitura: Date; userHistory: UserData[]; }; export default function listaPacientes(){ const CadastroSchema = z.object({ nome: z.string() .nonempty("O nome é obrigatório!"), sexo: z.string() .nonempty("O sexo é obrigatório!"), idade: z.string() .nonempty("O idade é obrigatório!"), cidade: z.string() .nonempty("O cidade é obrigatório!"), }); type CadastroData = z.infer<typeof CadastroSchema> const { register, handleSubmit, formState: {errors}, setValue} = useForm<CadastroData>({ resolver: zodResolver(CadastroSchema) }); const [modalCadastro, setModalCadastro] = useState(false); let [user, setUser] = useState<UserData[] | null>() const onSubmit = (d:CadastroData) => { try{ localStorage.setItem(d.nome, JSON.stringify(d)); const chaves = localStorage.getItem("keys") || "xxx"; if (chaves !== 'xxx'){ let keys = chaves; // alert("chaves="+keys); keys = keys + ',' + d.nome; // keys.push(d.nome); localStorage.setItem("keys", keys); }else{ localStorage.setItem("keys", d.nome); } // const arrayChaves = localStorage.getItem('keys')?.split(","); // alert("array de chaves= " + arrayChaves); alert("cadastro realizado"); setValue("nome",""); setValue("sexo",""); setValue("idade",""); setValue("cidade",""); }catch(errors) { alert(errors); } } function Cadastrar(){ return ( <Modal show={modalCadastro} centered onHide={() => setModalCadastro(false)}> <Modal.Header closeButton> <Modal.Title>Cadastrar novo paciente</Modal.Title> </Modal.Header> <Modal.Body> <div className="text-white flex text-center justify-center flex-col"> <form action="" onSubmit={handleSubmit(onSubmit)} className="px-10 rounded-2xl flex flex-col gap-4 text-black"> <div className="flex flex-col text-left gap-1 mt-2"> <label htmlFor="nome">Nome</label> <input {...register("nome")} className="border-solid border-1 border-black rounded-sm h-8 text-black p-1" type="text"/> { errors.nome && <span className="text-red-600">{errors.nome.message}</span> } </div> <div className="flex flex-col text-left gap-1"> <label htmlFor="sexo">Sexo</label> <select {...register("sexo")} className="border-solid border-1 border-black rounded-sm h-8 text-black p-1"> <option value="M">Masculino</option> <option value="F">Feminino</option> <option value="O">Outros</option> </select> {/* <input className="rounded-sm h-8 text-black p-1" type="text"/> */} { errors.sexo && <span className="text-red-600">{errors.sexo.message}</span> } </div> <div className="flex flex-col text-left gap-1"> <label htmlFor="idade">Idade</label> <input {...register("idade")} className="border-solid border-1 border-black rounded-sm h-8 text-black p-1" type="text"/> { errors.idade && <span className="text-red-600">{errors.idade.message}</span> } </div> <div className="flex flex-col text-left gap-1"> <label htmlFor="cidade">Cidade</label> <input {...register("cidade")} className="border-solid border-1 border-black rounded-sm h-8 text-black p-1" type="text"/> { errors.cidade && <span className="text-red-600">{errors.cidade.message}</span> } </div> <button className="bg-green-600 mt-2 rounded font-semibold text-white p-1 hover:bg-green-500 mb-5">Cadastrar</button> </form> </div> </Modal.Body> </Modal> ); } function consultaPessoas() { const keys = localStorage.getItem('keys'); const arrayKeys = keys?.split(',') || []; let newUser : UserData[] = []; // let userHistory : UserData[] = []; arrayKeys.forEach(element => { //alert(user) let item = localStorage.getItem(element); //alert(item) if (item){ const userData = JSON.parse(item) as UserData; userData.frequenciaCardiaca= Math.floor(Math.random() * 100 + 60), userData.pressaoArterial= `${Math.floor(Math.random() * 50 + 90)}/${Math.floor(Math.random() * 20 + 60)}`, userData.temperatura= Math.round(Math.random() * 2.5 + 36), userData.saturacaoOxigenio = Math.floor(Math.random() * 20 + 80), userData.dataLeitura= new Date(); // Verifique se há um histórico de medições para este paciente const historyKey = `${userData.nome}_history`; let history: UserData[] = JSON.parse(localStorage.getItem(historyKey) || '[]'); // Adicione a nova medição ao histórico history.push(userData); // Limite o histórico a 5 medições if (history.length > 5) { history = history.slice(-5); } // Salve o histórico de medições localStorage.setItem(historyKey, JSON.stringify(history)); //exibe cor de alerta caso... if (userData.idade <= "17") { // pessoas a baixo de 17 anos // considerando pacientes em repouso frequencia max é de 100 acima disso esta elevado userData.frequenciaCardiacaalerta = userData.frequenciaCardiaca >= 100; }else if (userData.idade <= "64"){ //pessoas a baixo de 64 anos // considerado pacientes em repouso drequencia max é de 110 acima disso esta elevado userData.frequenciaCardiacaalerta = userData.frequenciaCardiaca >= 110; }else{ //pessoas acima de 64 ano // considerado pacientes em repouso drequencia max é de 90 acima disso esta elevado userData.frequenciaCardiacaalerta = userData.frequenciaCardiaca >= 90; } //exibe cor de perigo caso... if (userData.idade <= "17") { // pessoas a baixo de 17 anos userData.frequenciaCardiacaemergencia = userData.frequenciaCardiaca >= 120; }else if (userData.idade <= "64"){ //pessoas a baixo de 64 anos userData.frequenciaCardiacaemergencia = userData.frequenciaCardiaca >= 130; }else{ //pessoas acima de 64 ano userData.frequenciaCardiacaemergencia = userData.frequenciaCardiaca >= 110; } if (userData.temperatura < 37){ userData.temperaturaalerta = false; userData.temperaturaemergencia = false; }else if (userData.temperatura < 38){ userData.temperaturaalerta = true; userData.temperaturaemergencia = false; }else{ userData.temperaturaalerta = true; userData.temperaturaemergencia = true; } if (userData.saturacaoOxigenio < 85){ userData.saturacaoOxigenioalerta = true; userData.saturacaoOxigenioemergencia = true; }else if (userData.saturacaoOxigenio < 95){ userData.saturacaoOxigenioalerta = true; userData.saturacaoOxigenioemergencia = false; }else{ userData.saturacaoOxigenioalerta = false; userData.saturacaoOxigenioemergencia = false; } // userHistory.push(history) userData.userHistory = history; newUser.push(userData) // console.log(JSON.stringify(userData,null,2)); } }); // setUserHis(userHistory); setUser(newUser); } useEffect(() => { if (localStorage.getItem('keys') != null){ const intervalId = setInterval(() => { consultaPessoas() }, 10000); // 10 segundos return () => clearInterval(intervalId); } }, []); return ( <div> <Cadastrar /> <header className="container-fluid bg-dark"> <nav className="navbar navbar-dark"> <div className="container d-flex align-items-center"> <a className="navbar-brand" href="#"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" className="bi bi-person-vcard-fill" viewBox="0 0 16 16"> <path d="M0 4a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V4Zm9 1.5a.5.5 0 0 0 .5.5h4a.5.5 0 0 0 0-1h-4a.5.5 0 0 0-.5.5ZM9 8a.5.5 0 0 0 .5.5h4a.5.5 0 0 0 0-1h-4A.5.5 0 0 0 9 8Zm1 2.5a.5.5 0 0 0 .5.5h3a.5.5 0 0 0 0-1h-3a.5.5 0 0 0-.5.5Zm-1 2C9 10.567 7.21 9 5 9c-2.086 0-3.8 1.398-3.984 3.181A1 1 0 0 0 2 13h6.96c.026-.163.04-.33.04-.5ZM7 6a2 2 0 1 0-4 0 2 2 0 0 0 4 0Z"/> </svg> </a> <ul className="nav ml-auto"> <li onClick={() => setModalCadastro(true)} className="nav-item nav-item-border"> <a className="nav-link active" aria-current="page" href="#">adicionar</a> </li> <li className="nav-item nav-item-border"> <a className="nav-link" href="#">alterar</a> </li> <li className="nav-item nav-item-border"> <a className="nav-link" href="#">deletar</a> </li> </ul> </div> </nav> </header> <br /> <div className="container"> <table className="table"> <thead className="table-dark"> <tr> <th>Nome</th> <th>Idade</th> <th>Sexo</th> <th>Cidade</th> <th>Pressão Arterial</th> </tr> </thead> <tbody> {user && user.map( itens => ( <tr> <td>{itens.nome}</td> <td>{itens.idade}</td> <td>{itens.sexo}</td> <td>{itens.cidade}</td> <td>{itens.pressaoArterial}</td> </tr> ))} </tbody> </table> </div> </div> ); }
from django.shortcuts import render from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .models import User from .serializer import UserSerializer ################################### # GET USERS ################################### @api_view(['GET']) def get_users(request): try: users = User.objects.all() serializer = UserSerializer(users, many=True) return Response({ 'statusCode': 200, 'message': 'Get all users query was successful', 'admins': serializer.data }, status=status.HTTP_200_OK) except Exception as e: return Response({ 'statusCode': 500, 'message': 'Get all users query internal server error', 'error': str(e) }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) ################################### # CREATE USER ################################### @api_view(['POST']) def create_user(request): try: # Get request body data but complex data data = request.data # Create data structure according to python serializer = UserSerializer(data = data) if serializer.is_valid(): serializer.save() return Response({ 'statusCode': 201, 'message': 'Create user query was successful', 'data': serializer.data }, status=status.HTTP_201_CREATED) else: return Response({ 'statusCode': 400, 'message': 'Create user query was failed', 'error': serializer.errors }, status=status.HTTP_400_BAD_REQUEST) except: return Response({ 'statusCode': 500, 'message': 'Create user query internal server error', 'error': serializer.errors }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) ################################### # GET USER ################################### @api_view(["GET"]) def get_user(request, pk): try: if request.method == 'GET': admin = User.objects.get(pk=pk) serializer = UserSerializer(admin) return Response({ 'statusCode': 200, 'message': 'Get user query was successful', 'data': serializer.data }, status=status.HTTP_200_OK) except User.DoesNotExist: return Response({ 'statusCode': 404, 'message': 'Get user query was failed. No user was found', }, status=status.HTTP_404_NOT_FOUND) except: return Response({ 'statusCode': 500, 'message': 'Get user query internal server error', 'error': serializer.errors }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) ################################### # UPDATE USER ################################### @api_view(['PUT']) def update_user(request, pk): try: data = request.data if request.method == 'PUT': user = User.objects.get(pk=pk) serializer = UserSerializer(user, data) if serializer.is_valid(): serializer.save() return Response({ 'statusCode': 200, 'message': 'Update user query was successful', 'data': serializer.data }); else: return Response({ 'statusCode': 400, 'message': 'Update user query was failed', 'error': serializer.errors }) except User.DoesNotExist: return Response({ 'statusCode': 404, 'message': 'Update user query was failed. No user was found', }, status=status.HTTP_404_NOT_FOUND) except Exception as e: return Response({ 'statusCode': 500, 'message': 'Update user query internal server error', 'error': str(e) }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) ################################### # DELETE USER ################################### @api_view(['DELETE']) def delete_user(request, pk): try: if request.method == 'DELETE': user = User.objects.get(pk=pk) user.delete() return Response({ 'statusCode': 200, 'message': 'Delete user query was successful', 'deleted': True }); except User.DoesNotExist: return Response({ 'statusCode': 404, 'message': 'Delete user query was failed. No user was found', }, status=status.HTTP_404_NOT_FOUND) except Exception as e: return Response({ 'statusCode': 500, 'message': 'Delete user query internal server error', 'error': str(e) }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
const express = require("express"); const app = express(); const bodyParser = require("body-parser"); const connection = require("./database/database") const Pergunta = require("./database/Pergunta"); const Resposta = require("./database/Resposta") //database connection .authenticate() .then(() => { console.log("Conectado com o banco de dados") }) .catch((msgErro) => { console.log(msgErro) }) app.set('view engine', 'ejs'); //usando EJS como view app.use(express.static('public')); //bodyParser app.use(bodyParser.urlencoded({extended: false})) app.use(bodyParser.json()) //routes app.get ("/", (req, res) => { Pergunta.findAll({raw: true, order: [ // SELECT * FROM Perguntas ['id', 'DESC'] //ASC ]}).then(perguntas => { res.render("index", { perguntas: perguntas }) }) }); app.get ("/perguntar", (req, res) => { res.render("perguntar") }); app.post ("/salvarperguntar", (req, res) => { let titulo = req.body.titulo ; let descricao = req.body.descricao ; Pergunta.create({ titulo: titulo, descricao: descricao }).then(() => { res.redirect("/") ; }) }) app.get("/pergunta/:id", (req, res) => { let id = req.params.id ; Pergunta.findOne({ where: {id: id} }).then(pergunta => { if (pergunta != undefined) { Resposta.findAll({ where: {perguntaId: pergunta.id}, order:[ ['id', 'DESC'] ] }).then(respostas => { res.render("pergunta", { pergunta: pergunta, respostas: respostas }); }); }else { res.redirect("/") ; } }); }) app.post("/responder", (req, res) => { let corpo = req.body.corpo ; let perguntaId= req.body.pergunta Resposta.create({ corpo: corpo, perguntaId: perguntaId }).then(()=> { res.redirect("/pergunta/" + perguntaId) }) }) app.listen(8080, () =>{ console.log("App Rodando na porta 8080") });
// // Created by isaca on 7/8/2021. // #ifndef PATTERNS_TRANSPORT_HPP #define PATTERNS_TRANSPORT_HPP #include <string> class Transport { protected: int transportID; double maxSpeed; std::string origin, destination; Transport(int _transportID, double _maxSpeed, std::string _origin, std::string _destination): transportID(_transportID), maxSpeed(_maxSpeed), origin(_origin), destination(_destination) {} public: virtual void move() = 0; // Getters double getMaxSpeed() { return maxSpeed; } std::string getOrigin() { return origin; } std::string getDestination() { return destination; } // Setters void setMaxSpeed(double _maxSpeed) { maxSpeed = _maxSpeed; } void setOrigin(std::string _origin) { origin = _origin; } void setDestination(std::string _destination) { destination = _destination; } }; #endif //PATTERNS_TRANSPORT_HPP
import React,{useState,useEffect} from 'react' // import {Link} from 'react-router-dom'; import {Form,Button,Row,Col,Table} from 'react-bootstrap' import {useDispatch,useSelector} from 'react-redux'; import Message from '../components/Message'; import Loader from '../components/Loader'; import {getUserDetails,updateUserProfile} from '../actions/userActions' import { listMyOrders } from '../actions/orderActions'; import { LinkContainer } from 'react-router-bootstrap'; const ProfileScreen = ({location,history}) => { const [name,setName]=useState(''); const [email,setEmail]=useState(''); const [password,setPassword]=useState(''); const [confirmPassword,setConfirmPassword]=useState(''); const [message,setMessage]=useState(null); const dispatch=useDispatch(); const userDetails=useSelector(state=>state.userDetails) const {loading,error,user}=userDetails; const userLogin=useSelector(state=>state.userLogin) const {userInfo}=userLogin; const userUpdateProfile=useSelector(state=>state.userUpdateProfile) const {success}=userUpdateProfile; const orderListMy=useSelector(state=>state.orderListMy) const {orders,loading:loadingOrders,error:errorOrders}=orderListMy; useEffect(()=>{ if(!userInfo){ history.push('/login'); }else{ if(!user?.name){ dispatch(getUserDetails('profile')) dispatch(listMyOrders()); }else{ setName(user?.name); setEmail(user?.email); } } },[dispatch, history,user,userInfo]) const submitHandler=(e)=>{ e.preventDefault(); // console.log('submit'); if(password !== confirmPassword ){ setMessage('Passwords do not match') }else if(name==='' || email===''){ setMessage('All inputs are required') } else{ // update profile dispatch(updateUserProfile({id:user._id,name,email,password})) } setTimeout(() => { setMessage(null); }, 3000); } return ( <Row> <Col md={3}> <h2>User profile</h2> {message&&<Message variant="danger">{message}</Message>} {error&&<Message variant="danger">{error}</Message>} {success&&<Message variant="success">Profile Updated</Message>} {loading&&<Loader/>} <Form onSubmit={submitHandler}> <Form.Group controlId="name"> <Form.Label>Name</Form.Label> <Form.Control type="text" placeholder="Enter Name" value={name} onChange={(e)=>setName(e.target.value)}> </Form.Control> </Form.Group> <Form.Group controlId="email"> <Form.Label>Email Address</Form.Label> <Form.Control type="email" placeholder="Enter email" value={email} onChange={(e)=>setEmail(e.target.value)}> </Form.Control> </Form.Group> <Form.Group controlId="password"> <Form.Label>Password </Form.Label> <Form.Control type="password" placeholder="Enter password" value={password} onChange={(e)=>setPassword(e.target.value)}> </Form.Control> </Form.Group> <Form.Group controlId="confirmPassword"> <Form.Label>Confirm Password </Form.Label> <Form.Control type="password" placeholder="Confirm password" value={confirmPassword} onChange={(e)=>setConfirmPassword(e.target.value)}> </Form.Control> </Form.Group> <Button type="submit" variant="primary"> Update </Button> </Form> </Col> <Col md={9}> <h2>My orders</h2> {loadingOrders?(<Loader/>):errorOrders?(<Message variant="danger">{errorOrders}</Message>):( <Table striped bordered hover responsive className="table-sm"> <thead> <tr> <th>ID</th> <th>DATE</th> <th>TOTAL</th> <th>PAID</th> <th>DELIVERED</th> <th></th> </tr> </thead> <tbody> {orders.map(order=>( <tr key={order._id}> <td>{order._id}</td> <td>{order.createdAt.substring(0,10)}</td> <td>{order.totalPrice}</td> <td>{order.isPaid?order.paidAt.substring(0,10):( <i className="fas fa-times" style={{color:'red'}}></i> )}</td> <td>{order.isDelivered?order.isDelivered.substring(0,10):( <i className="fas fa-times" style={{color:'red'}}></i> )}</td> <td> <LinkContainer to={`/order/${order._id}`}> <Button className="btn-sm" variant="light"> Details </Button> </LinkContainer> </td> </tr> ))} </tbody> </Table> )} </Col> </Row> ) } export default ProfileScreen;
import { EventEmitter, Injectable } from '@angular/core'; import { isLiveUrl } from '@editor-ui/app/common/utils/is-live-url'; import { ApplicationStateService, FolderActionsService } from '@editor-ui/app/state'; import { Node, Page, Raw } from '@gentics/cms-models'; import { defer, iif, of } from 'rxjs'; import { Observable } from 'rxjs/Observable'; import { catchError, mergeMap, take, tap } from 'rxjs/operators'; import { ErrorHandler } from '../error-handler/error-handler.service'; import { I18nNotification } from '../i18n-notification/i18n-notification.service'; import { I18nService } from '../i18n/i18n.service'; import { NavigationService } from '../navigation/navigation.service'; import { QuickJumpService } from '../quick-jump/quick-jump.service'; @Injectable() export class ListSearchService { /** Notifying subscribers that search has been executed */ searchEvent$ = new EventEmitter<{ term: string, nodeId?: number }>(null); constructor( private errorHandler: ErrorHandler, private folderActions: FolderActionsService, private navigationService: NavigationService, private quickJumpService: QuickJumpService, private state: ApplicationStateService, private i18n: I18nService, private notification: I18nNotification, ) { } /** Search for a string in the folder & node currently active in the item list. */ search(term: string, nodeId?: number): void { const patternShortCutSyntaxId = new RegExp( /^(jump\:)\d+$/ ); const activeNode = this.state.now.entities.node[nodeId || this.state.now.folder.activeNode]; const hosts = Object.values(this.state.now.entities.node).map((node: Node) => node.host); if (term && activeNode && isLiveUrl(term, hosts)) { this.searchLiveUrl(term).pipe( take(1), ).subscribe(); } else if (patternShortCutSyntaxId.test(term)) { // extract number from shortcut syntax const entityId = parseInt((/\d+/.exec(term))[0], 10); this.searchPageId(entityId, nodeId || this.state.now.folder.activeNode); } else { this.folderActions.setFilterTerm(''); this.folderActions.setSearchTerm(term); } this.searchEvent$.emit({ term, ...(nodeId && { nodeId }) }); } searchLiveUrl(liveUrl: string, hosts: string[] = []): Observable<Page<Raw> | undefined> { const fallbackLiveUrl = liveUrl.startsWith('www.') ? liveUrl.substring(4) : `www.${liveUrl}`; return this.folderActions.searchLiveUrl(liveUrl).pipe( take(1), mergeMap((page: Page<Raw> | undefined) => iif(() => page === undefined && isLiveUrl(fallbackLiveUrl, hosts), defer(() => this.folderActions.searchLiveUrl(fallbackLiveUrl)), of(page).pipe(take(1))), ), tap((page: Page<Raw> | undefined) => { this.folderActions.setFilterTerm(''); if (page) { this.navigationService.instruction({ list: { nodeId: page.inheritedFromId, folderId: page.folderId, }, detail: { nodeId: page.inheritedFromId, itemType: 'page', itemId: page.id, editMode: 'preview', }, }).navigate(); return; } this.notification.show({ message: 'message.page_liveurl_not_found', translationParams: { url: liveUrl.replace(/^https?:\/\//, '') }, }); }), catchError(error => { this.errorHandler.catch(error); return of(null).take(1); }), ); } searchPageId(id: number, nodeId: number): Promise<void> { return this.quickJumpService.searchPageById(id, nodeId) .then(result => { if (!result) { this.errorHandler.catch( new Error(this.i18n.translate('editor.no_page_with_id', { id })), { notification: true }, ); return; } // If the page entity is not already in the state, fetch it to get the folder id const loadedPage = this.state.now.entities.page[result.id]; const pageReq: Promise<Page> = loadedPage ? Promise.resolve(loadedPage) : this.folderActions.getPage(result.id, { nodeId: result.nodeId }); return pageReq.then(page => ({ page, nodeId: result.nodeId, })); }) .then(page => { if (!page) { return; } this.folderActions.setFilterTerm(''); if (!page) { return this.folderActions.setSearchTerm(id.toString()); } this.navigationService.instruction({ list: { nodeId: page.nodeId, folderId: page.page.folderId, }, detail: { nodeId: page.nodeId, itemType: 'page', itemId: page.page.id, editMode: 'preview', }, }).navigate(); }); } }
"""이 모듈은 한국 표준시(KST)에 대한 날짜와 시간을 처리하는 함수와 클래스를 제공합니다. - `KSTAwareDatetime` 클래스는 한국 표준시(KST) 시간대 정보를 요구하는 datetime을 나타냅니다. - `validate` 함수는 주어진 datetime이 한국 표준시(KST) 시간대 정보를 가지고 있는지 확인합니다. - `now`, `yesterday`, `datetime` 함수는 각각 현재, 어제, 주어진 시간의 한국 표준시(KST)을 반환합니다. """ from datetime import datetime as _datetime from datetime import timedelta, timezone from functools import wraps from typing import Annotated, Callable from zoneinfo import ZoneInfo from annotated_types import Interval, Timezone KST_TZ = ZoneInfo("Asia/Seoul") KST_TZ_CONSTRAINT = 9 * 60 * 60 KSTAwareDatetime = Annotated[_datetime, Timezone("Asia/Seoul")] Year = Annotated[int, Interval(ge=1, le=9999)] Month = Annotated[int, Interval(ge=1, le=12)] Day = Annotated[int, Interval(ge=1, le=31)] Hour = Annotated[int, Interval(ge=0, le=23)] Minute = Annotated[int, Interval(ge=0, le=59)] Second = Annotated[int, Interval(ge=0, le=59)] Microsecond = Annotated[int, Interval(ge=0, le=999999)] def is_aware(dt: _datetime) -> bool: return dt.tzinfo is not None and dt.tzinfo.utcoffset(dt) is not None def is_naive(dt: _datetime) -> bool: return dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None def is_kst_timezone(tzinfo) -> bool: if tzinfo in [KST_TZ, timezone(timedelta(seconds=32400))]: return True elif tzinfo is not None and tzinfo.utcoffset(None) == timedelta(hours=9): return True return False def is_kst_datetime(dt: _datetime) -> bool: return is_kst_timezone(dt.tzinfo) def ensure_kst_aware_datetime(func: Callable) -> Callable: @wraps(func) def wrapper(*args, **kwargs) -> KSTAwareDatetime: result = func(*args, **kwargs) if not isinstance(result, _datetime) or not is_kst_timezone(result.tzinfo): raise TypeError("Return value is not a KSTAwareDatetime") return result return wrapper @ensure_kst_aware_datetime def to_kst(dt: _datetime) -> KSTAwareDatetime: if is_aware(dt): return dt.astimezone(KST_TZ) else: return dt.replace(tzinfo=timezone.utc).astimezone(KST_TZ) def validate(date: _datetime): """주어진 날짜가 한국 표준시(KST) 시간대 정보를 가지고 있는지 확인합니다.""" if date.tzinfo is None: raise ValueError("datetime should have timezone info.") if date.tzinfo.utcoffset(date) != timedelta(seconds=KST_TZ_CONSTRAINT): raise ValueError("datetime should have KST timezone info.") def now() -> KSTAwareDatetime: """현재 한국 표준시(KST) 시간을 반환합니다.""" return _datetime.now(KST_TZ) def today() -> KSTAwareDatetime: """어제의 한국 표준시(KST) 시간을 반환합니다.""" today_kst = _datetime.now(KST_TZ) return datetime(today_kst.year, today_kst.month, today_kst.day) def yesterday() -> KSTAwareDatetime: """어제의 한국 표준시(KST) 시간을 반환합니다.""" today_kst = _datetime.now(KST_TZ) yesterday_kst = today_kst - timedelta(days=1) return datetime(yesterday_kst.year, yesterday_kst.month, yesterday_kst.day) def datetime( year: Year, month: Month, day: Day, hour: Hour = 0, minute: Minute = 0, second: Second = 0, microsecond: Microsecond = 0, ) -> KSTAwareDatetime: """주어진 시간의 한국 표준시(KST)를 반환합니다.""" return _datetime(year, month, day, hour, minute, second, microsecond, tzinfo=KST_TZ) def today_with_time(hour=0, minute=0) -> KSTAwareDatetime: _today = today() return datetime(_today.year, _today.month, _today.day, hour, minute) def is_same_date(date1: KSTAwareDatetime, date2: KSTAwareDatetime) -> bool: return date1.date() == date2.date()
component output = false hint = "I provide an operator that tests to see if a value matches against the given Java Regular Expression." { /** * I initialize the operator with the given target values (Java RegEx pattern text). */ public void function init( required array targetValues ) { variables.patterns = arguments.targetValues.map( ( targetValue ) => { return( createObject( "java", "java.util.regex.Pattern" ).compile( toString( targetValue ) ) ); } ); } // --- // PUBLIC METHODS. // --- /** * I test the given value to see if it matches against the target Regular Expressions. * The test implicitly casts all values to a string. */ public boolean function testValue( required any value ) { if ( ! isSimpleValue( value ) ) { return( false ); } for ( var pattern in patterns ) { if ( pattern.matcher( toString( value ) ).find() ) { return( true ); } } return( false ); } }
<template> <nav> <router-link to="/">Home</router-link> | <router-link :to="{ name: 'about' }">About</router-link> | <router-link :to="{ name: 'jobs' }">Jobs</router-link> <!-- One of the benefits of using ':to="{ name: 'about' }"' is that even though the link ('/about' or '/about-us' or etc.) changes, the name does not. --> </nav> <button class="history-btn" @click="redirect">Redirect to Jobs</button> <button class="history-btn" @click="back">Go Back</button> <button class="history-btn" @click="forward">Go Forward</button> <router-view/> </template> <script> export default { methods: { redirect() { // Go to jobs page (change route name to redirect to another page) this.$router.push({ name: 'jobs' }); }, back() { this.$router.go(-1); }, forward() { this.$router.go(1); }, }, } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; } nav { padding: 30px; } nav a { font-weight: bold; color: #2c3e50; text-decoration: none; padding: 10px; border-radius: 4px; } nav a.router-link-exact-active { color: #fff; background: #42b983; } .history-btn { margin: 0 10px; padding: 10px; border: none; border-radius: 4px; } .history-btn:hover { cursor: pointer; color: #fff; background: #42b983; } </style>
import { cn } from "@/lib/cn"; import { Box } from "@components/atoms/Box"; import { Collapsible, CollapsibleContent, CollapsibleTrigger, } from "@components/atoms/Collapsible"; import { HStack } from "@components/atoms/HStack"; import { ChevronDown } from "@components/atoms/Icon"; import { Stack } from "@components/atoms/Stack"; import { Text } from "@components/atoms/Text"; import { CreateNewFolder } from "@components/molecules/create-new-folder"; import { Logo } from "@components/molecules/logo"; import { NewChat } from "@components/molecules/new-chat"; import { SearchBar } from "@components/molecules/search-bar"; import { SidebarChatItem } from "@components/molecules/sidebar-chat-item"; import { UserCard } from "@components/molecules/user-card"; import { useState } from "react"; export const Sidebar = () => { const [isOpen, setIsOpen] = useState(true); return ( <aside className="w-80 h-full flex flex-col justify-between py-6 bg-[#141718]"> <Box> <Box className="px-4"> <Logo /> <Stack className="gap-4"> <CreateNewFolder /> <SearchBar /> </Stack> </Box> <hr className="my-4 border-[#232627]" /> <Box className="px-4"> <Collapsible open={isOpen} onOpenChange={setIsOpen} className="w-full" > <CollapsibleTrigger className="w-full"> <HStack className="pl-3 items-center"> <ChevronDown className={cn("transition-all", isOpen && " rotate-180")} /> <Text size={"sm"} className="font-medium text-[#6C7275BF]/75"> Список чатов </Text> </HStack> </CollapsibleTrigger> <CollapsibleContent> <SidebarChatItem pageLink="/123" text="Тут какой-то текст" count={48} /> <SidebarChatItem pageLink="/3123" text="Тут какой-то текст" count={48} /> </CollapsibleContent> </Collapsible> <NewChat /> </Box> </Box> <Box className="px-4"> <UserCard /> </Box> </aside> ); };
//输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数在数组的前半部分,所有偶数在数组的后半部分。 // // // // 示例: // // //输入:nums = [1,2,3,4] //输出:[1,3,2,4] //注:[3,1,2,4] 也是正确的答案之一。 // // // // 提示: // // // 0 <= nums.length <= 50000 // 0 <= nums[i] <= 10000 // // Related Topics 数组 双指针 排序 👍 222 👎 0 package org.harden.sort.leetcode.editor.cn; /** * @author junsenfu * @date 2022-04-27 21:23:40 */ class DiaoZhengShuZuShunXuShiQiShuWeiYuOuShuQianMianLcof{ public static void main(String[] args) { Solution solution = new DiaoZhengShuZuShunXuShiQiShuWeiYuOuShuQianMianLcof().new Solution(); } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int[] exchange(int[] nums) { //前后两个指针 奇前 偶后 int i=0; int j=nums.length-1; while (i<j){ //奇 if((nums[i]&1)==1){ i++; continue; } //偶 if((nums[j]&1)!=1){ j--; continue; } //swap int temp=nums[i]; nums[i]=nums[j]; nums[j]=temp; } return nums; } } //leetcode submit region end(Prohibit modification and deletion) }
import math def f(x): return x * math.exp(x) + x**2 - 1 def f_prime(x): return math.exp(x) + x * math.exp(x) + 2 * x def newton_method(f, f_prime, x0, epsilon, max_iterations): iteration = 0 while True: x1 = x0 - f(x0) / f_prime(x0) if abs(x1 - x0) < epsilon or iteration >= max_iterations: return x1 x0 = x1 iteration += 1 def simple_iteration_method(f, x0, epsilon, max_iterations): iteration = 0 while True: x1 = math.exp(-x0) * (1 - x0**2) if abs(x1 - x0) < epsilon or iteration >= max_iterations: return x1 x0 = x1 iteration += 1 result_simple_iteration = simple_iteration_method(f, 0.5, 0.01, 10000000) print(result_simple_iteration) result_newton = newton_method(f, f_prime, 0.5, 0.01, 10000000) print(result_newton)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Vue Component Example</title> </head> <body> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id="app"> <child-component v-bind:propdata="message"></child-component> <sibling-component v-bind:propdata2="anotherMessage"></sibling-component> </div> <script> Vue.component('child-component', { props: ['propdata'], template: '<p>{{ propdata }}</p>' }); Vue.component('sibling-component', { props: ['propdata2'], template: '<p>{{ propdata2 }}</p>' }); new Vue({ el: '#app', data: { message: 'Hello Vue! passed from parent component', anotherMessage: 'Message 2! passed from parent component' } }); </script> </body> </html>
COLLECTION FRAMEWORK ------------------- Collections - An object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. - A collections framework is a unified architecture for representing and manipulating collections [Collection Framework] - Interfaces - Collection, Set, List, Queue, Deque, Map - Implementations - ArrayList, LinkedList, HashSet, TreeSet, LinkedHashSet, ArrayDeque, HashMap, TreeMap, LinkedHashMap - Algorithms - Sorting, Shuffling, Searching, Data Manipulation, Composition, Min/Max [Benefits] - Reduces Programming Effort - Increases Program Speed and Quality - Allows interoperability among unrelated APIs - Reduces effort to learn and to use new APIs - Reduces effort to design new APIs - Fosters software reuse Arrays - Fixed size - Sequential memory allocation Vector - Dynamic Array - Synchronized. Thread Safe Hashtable - Key Value store (Objects) - Synchronized. Thread Safe Properties - Key Value store (String) List - indexed and ordered - Vector - ArrayList - LinkedList Set - maintains unique values and sorted - TreeSet - HashSet - LinkedHashSet Map - key value store - TreeMap - HashMap - LinkedHashMap Queue - FIFO - PriorityQueue - Deque Collections Framework Hierachy - Iterable - Collection - List - dynamic sizing, ordered, index based, supports - Vector - synchronized - ArrayList - faster frequent reads, random access - LinkedList - frequent insertions and updations - Set - does not allows duplicates, sorted, no index - HashSet - faster search, works based on hashing techinque, not ordered/sorted, allows null values - TreeSet - sorting, not allows null values - Comparable - compareTo(object ob) - Comparator - compare(Object ob1, Objec ob2) - LinkedHashSet - ordered, maintains insertion order, follows Hashing technique - Queue - FIFO -Deque - doubly queue, operation on both sides - PriorityQueue - BlockingQueue - Map - maintains data as key, value pair, not allows duplicate keys - Hashtable - not allows null keys, values, synchronized - HashMap - allows null keys and values , faster search with key(any type primitive or object) - TreeMap - not allows null keys and allows null values - LinkedHashMap - allows null keys and values - Map.Entry - key - value - Iterator - - ListIterator - goes forward and backward - forEach - Arrays.asList(empArr) -- convert array to a list - empList.toArray() -- convert list to array - empSet.toArray() -- convert set to array - convert array to set 1st convert array to list and then convert to set Set set = new HashSet(Arrays.asList(empArr)); --The Collection framework represents a unified architecture for storing and manipulating a group of objects. It has Interfaces and its implementations, i.e., classes and Algorithms(search,sort,aggregate etc) Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion. -- Advantages: Code reusuability Enables to perform operations on group of objects improves program speed and performance -- Earlier , these 2 container classes were there Dictionary (key/value) Vector (Dynamic array) Java Collection framework provides many interfaces ( List, Queue, Deque, Set) and classes (ArrayList, LinkedList, Vector, PriorityQueue, HashSet, LinkedHashSet, TreeSet). --Hierarchy of Collection Framework [ capitals are Interfaces, Togglecase is class ] ITERABLE <-- COLLECTION <-- LIST,QUEUE,SET LIST <-- ArrayList, LinkedList, Vector, Stack QUEUE <-- PriorityQueue QUEUE <-- DEQUE <-- ArrayDeque SET <-- HashSet,LinkedHashSet SET <-- SORTEDSET <-- TreeSet MAP <-- SORTEDMAP <-- TreeMap MAP <-- HasMap <-- LinkedHashMap --Collection Interface The Collection interface is the interface which is implemented by all the classes in the collection framework. It is the root interface in the collection hierarchy. This interface is basically used to pass around the collections and manipulate them where the maximum generality is desired. It declares the methods that every collection will have. Methods of Collection interface boolean add(E e) boolean addAll(Collection<? extends E> c) public boolean remove(Object element) public boolean removeAll(Collection<?> c) default boolean removeIf(Predicate<? super E> filter) public boolean retainAll(Collection<?> c) public int size() public void clear() public boolean contains(Object element) public boolean containsAll(Collection<?> c) public Iterator iterator() public Object[] toArray() public <T> T[] toArray(T[] a) public boolean isEmpty() default Stream<E> parallelStream() default Stream<E> stream() default Spliterator<E> spliterator() public boolean equals(Object element) public int hashCode() --Iterator interface Iterator interface provides the facility of iterating the elements in a forward direction only. Methods of Iterator interface : 1 public boolean hasNext() It returns true if the iterator has more elements otherwise it returns false. 2 public Object next() It returns the element and moves the cursor pointer to the next element. 3 public void remove() It removes the last elements returned by the iterator. It is less used. -- Iterable Interface The Iterable interface is the root interface for all the collection classes. The Collection interface extends the Iterable interface and therefore all the subclasses of Collection interface also implement the Iterable interface. It contains only one abstract method. i.e., Iterator<T> iterator() It returns the iterator over the elements of type T. -- Collections class Collection class is used exclusively with static methods that operate on or return collections. It inherits Object class. Java Collection class supports the polymorphic algorithms that operate on collections. Java Collection class throws a NullPointerException if the collections or class objects provided to them are null. -------------------------------------------- ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size limit. We can add or remove elements anytime. The important points about Java ArrayList class are: Java ArrayList class can contain duplicate elements. Java ArrayList class maintains insertion order. Java ArrayList class is non synchronized. Java ArrayList allows random access because array works at the index basis. In ArrayList, manipulation is little bit slower than the LinkedList in Java because a lot of shifting needs to occur if any element is removed from the array list. --Hierarchy of ArrayList class ITERABLE <-- COLLECTION <-- LIST<-- AbstractList <-- ArrayList -- Constructors of ArrayList Constructor Description ArrayList() It is used to build an empty array list. ArrayList(Collection<? extends E> c) It is used to build an array list that is initialized with the elements of the collection c. ArrayList(int capacity) It is used to build an array list that has the specified initial capacity. --Use of forEach: There are two forEach() method in Java 8, one defined inside Iterable, and the other inside java.util.stream.Stream class. If the purpose of forEach() is just iteration then you can directly call it like list.forEach() or set.forEach() but if you want to perform some operations like filter or map then it better first get the stream and then perform that operation and finally call forEach() method. ----------- --Java LinkedList class uses a doubly linked list to store the elements. Java LinkedList class can contain duplicate elements. Java LinkedList class maintains insertion order. Java LinkedList class is non synchronized. In Java LinkedList class, manipulation is fast because no shifting needs to occur. Java LinkedList class can be used as a list, stack or queue. --Doubly Linked List In the case of a doubly linked list, we can add or remove elements from both sides. ---------- Difference between Array and ArrayList /* Array ArrayList Array is static in size. ArrayList is dynamic in size. An array is a fixed-length data structure. ArrayList is a variable-length data structure. It can be resized itself when needed. Must provide size while initializing Not mandatory Fast operation because of the fixed sizze The Resize operation slows down the ArrayList in performnace An array can store both objects and primitives type. We cannot store primitive type in ArrayList. It automatically converts primitive type to object. Array can be multi-dimensional. ArrayList is always single-dimensional. --Similarities Array and ArrayList both are used for storing elements. Array and ArrayList both can store null values. They can have duplicate values. They do not preserve the order of elements. */ /* -- Difference between ArrayList and LinkedList ArrayList LinkedList 1) ArrayList internally uses a dynamic array to store the elements. LinkedList internally uses a doubly linked list to store the elements. 2) Manipulation with ArrayList is slow because it internally uses an array. Manipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory. If any element is removed from the array, all the bits are shifted in memory. 3) An ArrayList class can act as a list only because it implements List only. LinkedList class can act as a list and queue both because it implements List and Deque interfaces. 4) ArrayList is better for storing and accessing(searching) data. LinkedList is better for manipulating(add/remove) data. -- Difference between ArrayList and Vector Both are same in everything except, Vector is synchronized(thread safe), but ArrayList not ArrayList has fastermrandom access, for frequent reads -- When to use ArrayList and LinkedList in Java ArrayList is better to access data(search operation) time complexity to access elements O(1) LinkedList is better to manipulate(add and remove operations) data. time complexity to access elements O(n/2) -- COMPARE ARRAYLISTS There are following ways to compare two ArrayList in Java: Java equals() method Java removeAll() method Java retainAll() method Java ArrayList.contains() method Java contentEquals() method Java Stream interface : System.out.print("Common elements: " +firstList.stream().filter(secondList::contains).collect(Collectors.toList())); -- REVERSE ArrayList Collections.reverse(lIST); -- convert ArrayList to Array AND Array to ArrayList System.out.println("Converting ArrayList to Array" ); String[] item = fruitList.toArray(new String[fruitList.size()]); System.out.println("Converting Array to ArrayList" ); List<String>l2 = new ArrayList<>(); l2 = Arrays.asList(item); --------------------------------------------------------- -- Set -Does not allow duplicates, sorted, no imdex - HahsSet - faster search, works based on hashing techni - TreeSet - - Comparable - compareTo(Object obj) - Comparator - compare(Object obj1, Object obj2 - LinkedHashSet - ordered, maintains insertion order, follows Hashing technique -- HashSet: HashSet class is used to create a collection that uses a hash table for storage. no duplicates, no order, allows null ITERABLE <-- COLLECTION <-- SET <-- AbstractSet <-- HashSet HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their hashcode. HashSet stores the elements by using a mechanism called hashing. HashSet contains unique elements only. HashSet allows null value. HashSet class is non synchronized. HashSet is the best approach for search operations. The initial default capacity of HashSet is 16, and the load factor is 0.75. -- Difference between List and Set List Set 1. The List is an ordered sequence. 1. The Set is an unordered sequence. 2. List allows duplicate elements 2. Set doesn’t allow duplicate elements. 3. Elements by their position can be accessed, index based. 3. Position access to elements is not allowed, not index based. 4. Multiple null elements can be stored. 4. Null element can store only once. 5. List implementations are ArrayList, LinkedList, Vector, Stack 5. Set implementations are HashSet, LinkedHashSet. -- LinkedHashSet: LinkedHashSet class is a Hashtable and Linked list implementation of the set interface. ITERABLE <-- COLLECTION <-- SET <-- AbstractSet <-- HashSet <-- LinkedHashSet -- TreeSet: TreeSet class implements the Set interface that uses a tree for storage. no duplicates, no null, by default ascending order ITERABLE <-- COLLECTION <-- SET <-- SORTEDSET <-- NAVIGABLESET <-- TreeSet Java TreeSet class contains unique elements only like HashSet. Java TreeSet class access and retrieval times are quiet fast. Java TreeSet class doesn't allow null element. Java TreeSet class is non synchronized. Java TreeSet class maintains ascending order. -- Hashing The hashcode and equals methods must be same all the time It is allowed if equals is false and hashcode is true but not equals is true and hashcode is false Whenever equals is true, hashcode must be true
import { expect } from 'chai'; import { utils, Wallet } from 'ethers'; import { ethers } from 'hardhat'; import { evm, wallet } from '@test-utils'; import { then, when } from '@test-utils/bdd'; import { getNodeUrl } from '@utils/network'; import { IERC20, TradeFactory } from '@typechained'; import forkBlockNumber from '@integration/fork-block-numbers'; import * as setup from '../setup'; const MAX_SLIPPAGE = 10_000; // 1% const AMOUNT_IN = utils.parseEther('10000'); describe('Sushiswap', function () { let strategy: Wallet; let tradeFactory: TradeFactory; let CRV: IERC20; let DAI: IERC20; let snapshotId: string; when('on mainnet', () => { const FORK_BLOCK_NUMBER = forkBlockNumber['mainnet-swappers']; const CHAIN_ID = 1; const CRV_ADDRESS = '0xD533a949740bb3306d119CC777fa900bA034cd52'; const DAI_ADDRESS = '0x6b175474e89094c44da98b954eedeac495271d0f'; const CRV_WHALE_ADDRESS = '0xd2d43555134dc575bf7279f4ba18809645db0f1d'; before(async () => { strategy = await wallet.generateRandom(); await evm.reset({ jsonRpcUrl: getNodeUrl('mainnet'), blockNumber: FORK_BLOCK_NUMBER, }); ({ fromToken: CRV, toToken: DAI, tradeFactory, } = await setup.sync({ chainId: CHAIN_ID, fixture: ['Common', 'Mainnet', 'Sushiswap'], swapper: 'SyncSushiswap', fromTokenAddress: CRV_ADDRESS, toTokenAddress: DAI_ADDRESS, fromTokenWhaleAddress: CRV_WHALE_ADDRESS, amountIn: AMOUNT_IN, strategy, })); snapshotId = await evm.snapshot.take(); }); beforeEach(async () => { await evm.snapshot.revert(snapshotId); }); describe('swap', () => { const data = ethers.utils.defaultAbiCoder.encode([], []); beforeEach(async () => { await tradeFactory .connect(strategy) ['execute(address,address,uint256,uint256,bytes)'](CRV_ADDRESS, DAI_ADDRESS, AMOUNT_IN, MAX_SLIPPAGE, data); }); then('CRV gets taken from strategy', async () => { expect(await CRV.balanceOf(strategy.address)).to.equal(0); }); then('DAI gets airdropped to strategy', async () => { expect(await DAI.balanceOf(strategy.address)).to.be.gt(0); }); }); }); when('on polygon', () => { const FORK_BLOCK_NUMBER = forkBlockNumber['polygon-swappers']; const CHAIN_ID = 137; const CRV_ADDRESS = '0x172370d5cd63279efa6d502dab29171933a610af'; const DAI_ADDRESS = '0x8f3cf7ad23cd3cadbd9735aff958023239c6a063'; const CRV_WHALE_ADDRESS = '0x3a8a6831a1e866c64bc07c3df0f7b79ac9ef2fa2'; before(async () => { strategy = await wallet.generateRandom(); await evm.reset({ jsonRpcUrl: getNodeUrl('polygon'), blockNumber: FORK_BLOCK_NUMBER, }); ({ fromToken: CRV, toToken: DAI, tradeFactory, } = await setup.sync({ chainId: CHAIN_ID, fixture: ['Common', 'Polygon', 'SyncSushiswap'], swapper: 'SyncSushiswap', fromTokenAddress: CRV_ADDRESS, toTokenAddress: DAI_ADDRESS, fromTokenWhaleAddress: CRV_WHALE_ADDRESS, amountIn: AMOUNT_IN, strategy, })); snapshotId = await evm.snapshot.take(); }); beforeEach(async () => { await evm.snapshot.revert(snapshotId); }); describe('swap', () => { const data = ethers.utils.defaultAbiCoder.encode([], []); beforeEach(async () => { await tradeFactory .connect(strategy) ['execute(address,address,uint256,uint256,bytes)'](CRV_ADDRESS, DAI_ADDRESS, AMOUNT_IN, MAX_SLIPPAGE, data); }); then('CRV gets taken from strategy', async () => { expect(await CRV.balanceOf(strategy.address)).to.equal(0); }); then('DAI gets airdropped to strategy', async () => { expect(await DAI.balanceOf(strategy.address)).to.be.gt(0); }); }); }); });
import { StyleSheet, Text, TextInput, View } from "react-native"; import { LinearGradient } from "expo-linear-gradient"; import React, { useState } from "react"; import COLORS from "./COLOR"; import { TouchableOpacity } from "react-native-gesture-handler"; import { Dropdown } from "react-native-element-dropdown"; import DateTimePicker from "@react-native-community/datetimepicker"; import Foundation from "react-native-vector-icons/Foundation"; import axios from "axios"; export default function ApplyForLeave({ navigation }) { const data = [ { leaveType: "Sick Leave", value: "1" }, { leaveType: "Casual Leave", value: "2" }, { leaveType: "Paternity Leave", value: "3" }, { leaveType: "Religious Leave", value: "4" }, { leaveType: "Maternity Leave", value: "5" }, { leaveType: "Unpaid Leave", value: "6" }, ]; const [value, setValue] = useState(null); const [isFocus, setIsFocus] = useState(false); const [dateStart, setDateStart] = useState(new Date(1528578000000)); const [dateEnd, setDateEnd] = useState(new Date(1528578000000)); const [mode, setMode] = useState("date"); const [modeEnd, setModeEnd] = useState("date"); const [show, setShow] = useState(false); const [showEnd, setShowEnd] = useState(false); const [reqLeaveDays, setReqLeaveDays] = useState(); const [reason, setReason] = useState(); const renderLabel = () => { if (value || isFocus) { return ( <Text style={[styles.label, isFocus && { color: COLORS.buttonColor }]}> Leave Types </Text> ); } return null; }; //start date of leave const onChangeDateStart = (event, selectedDate) => { const currentDate = selectedDate; setShow(false); setDateStart(currentDate); }; //end date of leave const onChangeDateEnd = (event, selectedDate) => { const currentDate = selectedDate; setShowEnd(false); setDateEnd(currentDate); }; //start date mode of leave const showMode = (currentMode) => { setShow(true); setMode(currentMode); }; //end date mode of leave const showModeEnd = (currentMode) => { setShowEnd(true); setModeEnd(currentMode); }; //start leave date picker const showDatepicker = () => { // console.log(" Msg"); showMode("date"); }; //end leave date picker const showDatepickerEnd = () => { // console.log(" Msg"); showModeEnd("date"); }; const postData = { leaveType: value, from: dateStart, to: dateEnd, // reqLeaveDays, // status: status, // attachment: attachment, reason: reason, }; const leaveSubmitHandler = async () => { try { const res = await axios.post( "http://192.168.5.18:5001/leaverequest/addrequest", postData ); // console.log(" responce of data", res); res && navigation.navigate("LeaveDetails"); } catch (error) { console.log(" Errors while requesting leave", error); } }; return ( <LinearGradient style={styles.container} colors={[COLORS.linearStart, COLORS.linearEnd]} > <Text style={styles.headerText}>Leave Requests</Text> <View style={styles.border}> <View style={styles.bgText}> <Text>Leave Type</Text> </View> <View style={styles.bg}> {renderLabel()} <Dropdown style={[ styles.dropdown, isFocus && { borderColor: COLORS.buttonColor }, ]} placeholderStyle={styles.placeholderStyle} selectedTextStyle={styles.selectedTextStyle} inputSearchStyle={styles.inputSearchStyle} iconStyle={styles.iconStyle} data={data} search maxHeight={300} labelField="leaveType" valueField="leaveType" placeholder={!isFocus ? "Select leave" : "..."} searchPlaceholder="Search..." value={value} onFocus={() => setIsFocus(true)} onBlur={() => setIsFocus(false)} onChange={(item) => { setValue(item.leaveType); setIsFocus(!isFocus); console.log(" focus in dropdown", isFocus); }} /> </View> </View> <View style={styles.border}> <View style={styles.bgText}> <Text>From Date</Text> </View> <View style={{ flexDirection: "row", marginLeft: 30, }} > <Text style={styles.modalText}> {" "} {dateStart.toLocaleDateString()} {" "} </Text> <Foundation name="calendar" size={25} color={COLORS.textColor} onPress={showDatepicker} /> </View> {showEnd && ( <DateTimePicker testID="EndDateTimePicker" value={dateStart} mode={modeEnd} // is24Hour={true} onChange={onChangeDateEnd} /> )} </View> <View style={styles.border}> <View style={styles.bgText}> <Text>To Date</Text> </View> <View style={{ flexDirection: "row", marginLeft: 30, }} > <Text style={styles.modalText}> {" "} {dateEnd.toLocaleDateString()} {" "} </Text> <Foundation name="calendar" size={25} color={COLORS.textColor} onPress={showDatepickerEnd} /> </View> {show && ( <DateTimePicker testID="dateTimePicker" value={dateEnd} mode={mode} // is24Hour={true} onChange={onChangeDateStart} /> )} </View> <View style={styles.border}> <View style={styles.bgText}> <Text>Total Days</Text> </View> <TextInput value={reqLeaveDays} keyboardType={"number-pad"} style={{ // borderWidth: 1, paddingHorizontal: 50, color: COLORS.textColor, }} onChangeText={(text) => setReqLeaveDays(text)} ></TextInput> </View> <View style={styles.border}> <View style={styles.bgText}> <Text>Reason</Text> </View> <TextInput value={reason} style={{ paddingHorizontal: 50, color: COLORS.textColor, }} onChangeText={(text) => setReason(text)} ></TextInput> </View> <View style={styles.border}> <View style={styles.bgText}> <Text>Attachment</Text> </View> <Text style={{ color: COLORS.textColor }}>choose a file...</Text> {/* <TextInput value={reason} style={{ paddingHorizontal: 50, color: COLORS.textColor, }} onChangeText={(text) => setReason(text)} ></TextInput> */} </View> <TouchableOpacity style={[styles.button, styles.buttonStyle]}> <Text style={[styles.textStyle, { marginTop: 1 }]} onPress={leaveSubmitHandler} > Save{" "} </Text> </TouchableOpacity> </LinearGradient> ); } const styles = StyleSheet.create({ container: { flex: 1, }, headerText: { color: COLORS.textColor, fontSize: 20, fontWeight: "bold", textAlign: "center", marginTop: 20, marginBottom: 30, marginTop: 60, }, border: { borderWidth: 1, borderColor: COLORS.textColor, alignItems: "center", marginLeft: 40, marginRight: 40, marginTop: 20, flexDirection: "row", borderRadius: 5, }, bgText: { backgroundColor: COLORS.textColor, marginRight: 20, width: "40%", alignItems: "center", padding: 5, }, bg: { marginRight: 20, width: "50%", alignItems: "center", padding: 5, }, buttonStyle: { backgroundColor: COLORS.buttonColor, }, textStyle: { color: COLORS.textColor, fontWeight: "bold", textAlign: "center", margin: 10, fontSize: 20, }, button: { borderRadius: 20, padding: 5, elevation: 2, marginLeft: 60, marginRight: 60, marginTop: 20, }, dropdown: { height: 20, width: 150, paddingHorizontal: 10, }, label: { position: "absolute", color: COLORS.buttonColor, left: 22, top: 8, zIndex: 999, paddingHorizontal: 8, fontSize: 14, }, placeholderStyle: { fontSize: 16, color: COLORS.textColor, }, selectedTextStyle: { fontSize: 16, color: COLORS.textColor, }, inputSearchStyle: { height: 40, fontSize: 16, }, modalText: { fontSize: 20, color: COLORS.textColor, }, });
import { memo, useState, useEffect } from "react"; import PropTypes from 'prop-types'; import DatePicker from 'react-datepicker'; import { formatDate } from "../../utils/helpers"; import { Form, Button, Modal } from "react-bootstrap"; import styles from "./taskModal.module.css"; function TaskModal(props) { const [title, setTitle] = useState(""); const [description, setDescription] = useState(""); const [date, setDate] = useState(new Date()); const [isTitleValid, setIsTitleValid] = useState(false); useEffect(() => { const { data } = props; if (data) { setTitle(data.title); setDescription(data.description); setDate(data.date ? new Date(data.date) : new Date()); setIsTitleValid(true); } }, [props]); const saveTask = () => { const newTask = { title: title.trim(), description: description.trim(), date: formatDate(date) }; if (props.data) { newTask._id = props.data._id; } props.onSave(newTask); }; const onTitleChange = (event) => { const { value } = event.target; const trimmedTitle = value.trim(); setIsTitleValid(!!trimmedTitle); setTitle(value); }; return ( <Modal size="md" show={true} onHide={props.onCancel} > <Modal.Header closeButton> <Modal.Title> Add new task </Modal.Title> </Modal.Header> <Modal.Body > <Form.Control className={`${!isTitleValid ? styles.invalid : ''} mb-3`} placeholder="Title" value={title} onChange={onTitleChange} /> <Form.Control className='mb-3' as="textarea" placeholder="Description" rows={5} value={description} onChange={(event) => setDescription(event.target.value)} /> <h6>Deadline:</h6> <DatePicker showIcon selected={date} onChange={setDate} /> </Modal.Body> <Modal.Footer > <div className="d-flex justify-content-evenly gap-3"> <Button className={styles.saveButton} onClick={saveTask} disabled={!isTitleValid} > Save </Button> <Button className={styles.cancelButton} onClick={props.onCancel} > Cancel </Button> </div> </Modal.Footer> </Modal> ); } TaskModal.propTypes = { onCancel: PropTypes.func.isRequired, onSave: PropTypes.func.isRequired, data: PropTypes.object, }; export default memo(TaskModal);
/* * Copyright 1995-2010 by IRSN * * This software is an application framework, with a set of integrated * reusable components, whose purpose is to simplify the task of developing * softwares of numerical mathematics and scientific computing. * * This software is governed by the CeCILL-C license under French law and * abiding by the rules of distribution of free software. You can use, modify * and/or redistribute the software under the terms of the CeCILL-C license * as circulated by CEA, CNRS and INRIA at the following URL * "http://www.cecill.info". * * As a counterpart to the access to the source code and rights to copy, * modify and redistribute granted by the license, users are provided only * with a limited warranty and the software's author, the holder of the * economic rights, and the successive licensors have only limited liability. * * In this respect, the user's attention is drawn to the risks associated * with loading, using, modifying and/or developing or reproducing the * software by the user in light of its specific status of free software, * that may mean that it is complicated to manipulate, and that also * therefore means that it is reserved for developers and experienced * professionals having in-depth computer knowledge. Users are therefore * encouraged to load and test the software's suitability as regards their * requirements in conditions enabling the security of their systems and/or * data to be ensured and, more generally, to use and operate it in the same * conditions as regards security. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL-C license and that you accept its terms. */ #ifndef PEL_EXTRACTION_EXP_HH #define PEL_EXTRACTION_EXP_HH #include <PEL_TransferExp.hh> #include <string> class PEL_ModuleExplorer ; /* Expressions extracting data from an attached data structure that has to be primarily specified by calling `::initialize'( `mod' ). mod must not be modified until having called `::reset' method. Before calling `::initialize', none of the expressions implemented here can be used. --- name : has_data argument : String type : Bool The returned value is true if there exists, in the attached data structure, an entry whose keyword match the argument. Example: if( `has_data'( "/TOTO/my_entry" ) ) MODULE titi ... END MODULE titi --- name : extracted_data arguments : String, optional second argument type : everything The returned value is the result of the evaluation of the data whose keyword matches the first argument (in the attached data structure), if such an entry exists (in the attached data structure). If not, the second argument can be used to define a default value. Example 1: toto = `extracted_data'( "/TOTO/my_entry" ) Example 2: toto = `extracted_data'( "/TOTO/my_entry", 3. ) (toto is "/TOTO/my_entry" in `mod' if any, 3. elsewhere) titi = `extracted_data'( "/TOTO/my_entry", < "a" "b" > ) (titi is "/TOTO/my_entry" in `mod' if any, < "a" "b" > elsewhere) Example 3: For implementation reasons, the second argument becomes mandatory in "if" constructions, even when it is not used. if( has_data( "/TOTO/my_entry" ) ) MODULE titi toto = `extracted_data'( "/TOTO/my_entry", 0. ) END MODULE titi --- name : has_module argument : String type : Bool The returned value is true if there exists, in the attached data structure, a module whose keyword match the argument. Example: if( `has_module'( "/TOTO" ) ) MODULE titi toto = `extracted_data'( "/TOTO/my_entry", 3. ) ... END MODULE titi --- name : extracted_module argument : String, String, optional third argument type : String The returned value is the name of a temporary file containing the MODULE called according to the first argument in the attached data structure. The extracted module is renamed as the second argument of the function. Example1: MODULE titi #include( `extracted_module'( "/TOTO", "TITI" ) ) END MODULE titi The module of name "TOTO" is extracted from the database, and included as module "TITI". Example2: For implementation reasons, a special syntax (with a dummy third argument) is required in "if" constructions. if( has_module( "/TOTO/module" ) ) MODULE titi #include( `extracted_module'( "/TOTO/module", "module", "" ) ) END MODULE titi PUBLISHED */ class PEL_EXPORT PEL_ExtractionExp : public PEL_TransferExp { public: //------------------------------------------------------- //-- Instance delivery and initialization static void initialize( PEL_Module const* mod ) ; static void reset( void ) ; static bool is_initialized( void ) ; static PEL_Module const* data_base( void ) ; //-- Context virtual void declare( PEL_List* lst ) const ; virtual bool context_has_required_variables( PEL_Context const* ct ) const ; //-- Type virtual PEL_Data::Type data_type( void ) const ; //-- Value virtual bool value_can_be_evaluated( PEL_Context const* ct ) const ; virtual stringVector const& undefined_variables( PEL_Context const* ct ) const ; //-- Input - Output virtual void print( std::ostream& os, size_t indent_width ) const ; protected: //----------------------------------------------------- private: //------------------------------------------------------- PEL_ExtractionExp( void ) ; ~PEL_ExtractionExp( void ) ; PEL_ExtractionExp( PEL_ExtractionExp const& other ) ; PEL_ExtractionExp& operator=( PEL_ExtractionExp const& other ) ; enum ExtractionExp{ has_data, ext_data, has_mod, ext_mod } ; PEL_ExtractionExp( PEL_Object* a_owner, ExtractionExp op, std::string const& a_name, PEL_Sequence const* argument_list ) ; //-- Plug in PEL_ExtractionExp( std::string const& a_name, ExtractionExp op ) ; virtual PEL_ExtractionExp* create_replica( PEL_Object* a_owner, PEL_Sequence const* argument_list ) const ; //-- Characteristics virtual std::string const& usage( void ) const ; virtual bool valid_arguments( PEL_Sequence const* some_arguments ) const ; //-- Transfer implementation virtual PEL_Data const* data( PEL_Context const* ct ) const ; //-- Private methods static std::string const& temporary_file( void ) ; static std::string const& data_name( std::string const& exp_name, PEL_Data const* d ) ; void extract_module( std::string const& file_name, std::string const& d_name, std::string const& m_name ) const ; //-- Class attributes static PEL_Module const* DB_MOD ; static PEL_ExtractionExp* PROTO_HAS_DATA ; static PEL_ExtractionExp* PROTO_DATA ; static PEL_ExtractionExp* PROTO_HAS_MOD ; static PEL_ExtractionExp* PROTO_EXTRACTED_MODULE ; //-- Attributes ExtractionExp const OP ; std::string TEMP_FILE_NAME ; PEL_Data const* SRC ; } ; #endif
package com.example.medi_mitra_v1.Login_Signup; import static android.content.ContentValues.TAG; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.example.medi_mitra_v1.Admin.AdminMainActivity; import com.example.medi_mitra_v1.Client.ClientMainActivity; import com.example.medi_mitra_v1.R; import com.example.medi_mitra_v1.Utility.NetworkChangeListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; public class LoginActivity extends AppCompatActivity { TextView signupTv,forgotPass; EditText emailLogin,passwordLogin; Button LoginBtn; FirebaseAuth firebaseAuth; ProgressBar pbLogin; DatabaseReference databaseReference; DocumentReference documentReference; FirebaseFirestore firebaseFirestore; NetworkChangeListener networkChangeListener = new NetworkChangeListener(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); signupTv = findViewById(R.id.noAccountTv); emailLogin = findViewById(R.id.emailEt); forgotPass = findViewById(R.id.forgotTv); pbLogin = findViewById(R.id.ProgressBarLogin); passwordLogin = findViewById(R.id.passwordEt); firebaseAuth = FirebaseAuth.getInstance(); firebaseFirestore = FirebaseFirestore.getInstance(); LoginBtn = findViewById(R.id.loginBtn); forgotPass.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { pbLogin.setVisibility(View.VISIBLE); startActivity(new Intent(getApplicationContext(), ForgotPasswordActivity.class)); pbLogin.setVisibility(View.INVISIBLE); } }); signupTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { pbLogin.setVisibility(View.VISIBLE); startActivity(new Intent(getApplicationContext(), SignupActivity.class)); pbLogin.setVisibility(View.INVISIBLE); } }); LoginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(checkValid()) { pbLogin.setVisibility(View.VISIBLE); LoginBtn.setEnabled(false); firebaseAuth.signInWithEmailAndPassword(emailLogin.getText().toString(),passwordLogin.getText().toString()) .addOnSuccessListener(new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult authResult) { Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT).show(); checkUserAccessLevel(authResult.getUser().getUid()); LoginBtn.setEnabled(true); pbLogin.setVisibility(View.INVISIBLE); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(getApplicationContext(), ""+e.getMessage(), Toast.LENGTH_SHORT).show(); LoginBtn.setEnabled(true); pbLogin.setVisibility(View.INVISIBLE); } }) ; } } }); } private boolean checkValid() { boolean check=true; if(emailLogin.getText().toString().isEmpty()){ emailLogin.setError("Email cannot be empty"); check= false; } if(passwordLogin.getText().toString().isEmpty()) { passwordLogin.setError("Password cannot be empty"); check= false; } return check; } private void checkUserAccessLevel(String uid) { DocumentReference df = firebaseFirestore.collection("Users").document(uid); //extract data df.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { Log.d(TAG, "onSuccess: "+documentSnapshot.getData()); if(documentSnapshot.getString("isUser").equals("1")){ finish(); startActivity(new Intent(getApplicationContext(), ClientMainActivity.class)); } else if(documentSnapshot.getString("isUser").equals("0")){ finish(); startActivity(new Intent(getApplicationContext(), AdminMainActivity.class)); } else { Toast.makeText(getApplicationContext(), "Unkonwn User Type", Toast.LENGTH_SHORT).show(); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(getApplicationContext(), ""+e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } @Override protected void onStart() { IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(networkChangeListener,intentFilter); super.onStart(); } @Override protected void onStop() { unregisterReceiver(networkChangeListener); super.onStop(); } }
// Book Allocation , Split Array , Painters problem are all same approaches. #include <bits/stdc++.h> int students_allocated(vector<int> &books, int n, int limit) { int pages = 0; int student = 1; for (int i = 0; i < n; i++) { if (pages + books[i] <= limit) { pages = pages + books[i]; } else { pages = books[i]; student++; } } return (student); } int findPages(vector<int> &books, int n, int m) { int low = *max_element(books.begin(), books.end()); int high = accumulate(books.begin(), books.end(), 0); while (low <= high) { int mid = (low + high) / 2; int student = students_allocated(books, mid, n); if (student > m) low = mid + 1; else high = mid - 1; } return low; } int main() { vector<int> books = {25, 46, 28, 49, 24}; int n = 5; int m = 4; // students int ans = findPages(books, n, m); cout << "The minimum of maximum pages allocated to a student can be: " << ans << "\n"; return 0; }
import edu.princeton.cs.algs4.In; import edu.princeton.cs.algs4.StdDraw; import edu.princeton.cs.algs4.StdOut; import java.util.Arrays; import java.util.Comparator; public class FastCollinearPoints { private LineSegment[] segments; private Point[] points; public FastCollinearPoints(Point[] points) { // finds all line segments containing 4 or more points if (points == null) throw new IllegalArgumentException(); this.points = new Point[points.length]; //check for nulls for (int i = 0; i < points.length; i++) { if (points[i] == null) throw new IllegalArgumentException(); this.points[i] = points[i]; } Arrays.sort(points); //check for duplicates for (int i = 1; i < points.length; i++) { if (points[i].compareTo(points[i - 1]) == 0) throw new IllegalArgumentException(); } segments = new LineSegment[1]; Point[] slopeArr = new Point[points.length]; for (int i = 0; i < points.length; i++) { slopeArr[i] = points[i]; } int n = 0; for(int i = 0; i < points.length; i++) { Arrays.sort(slopeArr, slopeOrderBreak(points[i])); for (int j = 0; j < slopeArr.length-1; j++) { int count = 0; boolean flag = false; if(points[i].compareTo(slopeArr[j]) > 0) flag = true; while (points[i].slopeTo(slopeArr[j]) == points[i].slopeTo(slopeArr[j + 1])) { j++; count++; if(j == slopeArr.length - 1) break; } if (count >= 2 && !flag) { LineSegment ls = new LineSegment(points[i], slopeArr[j]); segments[n] = ls; n++; if (n == segments.length) { LineSegment[] copy = new LineSegment[n * 2]; for (int c = 0; c < n; c++) { copy[c] = segments[c]; } segments = copy; } } } } LineSegment[] copy = new LineSegment[n]; for (int i = 0; i < n; i++) { copy[i] = segments[i]; } segments = copy; } public int numberOfSegments() { return segments.length; } // the number of line segments public LineSegment[] segments() { return segments; } // the line segments private Comparator<Point> slopeOrderBreak(Point cur) { return new BySlope(cur); } private class BySlope implements Comparator<Point> { private Point cur; public BySlope(Point cur) { this.cur = cur; } public int compare(Point p1, Point p2) { int cmp = Double.compare(cur.slopeTo(p1), cur.slopeTo(p2)); if(cmp != 0) return cmp; else return p1.compareTo(p2); } } public static void main(String[] args) { // read the n points from a file In in = new In(args[0]); int n = in.readInt(); Point[] points = new Point[n]; for (int i = 0; i < n; i++) { int x = in.readInt(); int y = in.readInt(); points[i] = new Point(x, y); } // draw the points StdDraw.enableDoubleBuffering(); StdDraw.setXscale(0, 32768); StdDraw.setYscale(0, 32768); for (Point p : points) { p.draw(); } StdDraw.show(); // print and draw the line segments FastCollinearPoints collinear = new FastCollinearPoints(points); for (LineSegment segment : collinear.segments()) { StdOut.println(segment); segment.draw(); } StdDraw.show(); } }
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} module AtCoderBeginnerContest148.BSpec (spec) where import Data.ByteString (ByteString) import Test.Hspec (Spec, it, shouldBe) import Text.Heredoc (str) import AtCoderBeginnerContest148.B (main) import Test (runWith) spec :: Spec spec = do it "Example 1" $ do let input, output :: ByteString input = [str|2 |ip cc |] output = [str|icpc |] main `runWith` input $ (`shouldBe` output) it "Example 2" $ do let input, output :: ByteString input = [str|8 |hmhmnknk uuuuuuuu |] output = [str|humuhumunukunuku |] main `runWith` input $ (`shouldBe` output) it "Example 3" $ do let input, output :: ByteString input = [str|5 |aaaaa aaaaa |] output = [str|aaaaaaaaaa |] main `runWith` input $ (`shouldBe` output)
<a href="#create-task" class="btn btn-pink float-right mb-3" data-toggle="modal"><i class="fal fa-tasks"></i> Add Tasks</a> @foreach ($tasks as $task) <div class="widget-list-item mb-1"> <div class="widget-list-media"> @if($task->status == 'Completed') <img src="{!! asset('assets/img/complete.png') !!}" alt="" class="rounded lazy"> @else @if($task->priority == 'High') <img src="{!! asset('assets/img/urgent.png') !!}" alt="" class="rounded lazy"> @elseif($task->priority == 'Normal') <img src="{!! asset('assets/img/medium.png') !!}" alt="" class="rounded lazy"> @else <img src="{!! asset('assets/img/deafult.png') !!}" alt="" class="rounded lazy"> @endif @endif </div> <div class="widget-list-content"> <h4 class="widget-list-title mb-1 mt-1"> {!! $task->task !!} </h4> <p class="widget-list-desc font-bold">Priority :<span class="font-weight-bold">{!! $task->priority !!}</span> | Status : <span class="font-weight-bold">{!! $task->status !!}</span> | Assigned To :<span class="text-primary">@if(Hr::check_employee($task->assigned_to) == 1) {!! Hr::employee($task->assigned_to)->names !!} @endif </span> | Due Date : <b>{!! date('d F Y', strtotime($task->date)) !!}</b> </p> <a href="{!! route('crm.deals.task.delete',$task->id) !!}" class="float-right ml-2 badge badge-danger delete"><i class="fas fa-trash"></i> Delete</a> {{-- <a href="#" class="float-right ml-2 badge badge-warning"><i class="fas fa-eye"></i> View</a> --}} <a href="#update-task-{!! $task->id !!}" class="float-right ml-2 badge badge-primary" data-toggle="modal"><i class="fas fa-pen-square"></i> Edit</a> </div> </div> <div class="modal fade" id="update-task-{!! $task->id !!}" tabindex="-1" role="dialog"> <div class="modal-dialog modal-lg"> {!! Form::model($task, ['route' => ['crm.deals.task.update', $task->id], 'method'=>'post', 'autocomplete'=>'off']) !!} <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Add Task</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> @csrf <div class="row"> <div class="col-sm-6"> <div class="form-group form-group-default required"> {!! Form::label('names', 'Task', array('class'=>'control-label')) !!} {!! Form::text('task', null, array('class' => 'form-control', 'placeholder' => 'Enter task')) !!} <input type="hidden" name="dealID" value="{!! $deal->dealID !!}" required> </div> </div> <div class="col-sm-6"> <div class="form-group form-group-default required"> {!! Form::label('Category', 'Category', array('class'=>'control-label')) !!} {{ Form::select('category',[''=>'Choose Category','Call'=>'Call','Email'=>'Email','Follow_up' => 'Follow_up','Meeting' => 'Meeting','Milestone' => 'Milestone','Tweet' => 'Tweet','Other' => 'Other'], null, ['class' => 'form-control']) }} </div> </div> </div> <div class="row"> <div class="col-sm-6"> <div class="form-group form-group-default required"> {!! Form::label('names', 'Date (Due)', array('class'=>'control-label')) !!} {!! Form::text('date', null, array('class' => 'form-control datepicker', 'placeholder' => '')) !!} </div> </div> <div class="col-sm-6"> <div class="form-group form-group-default"> {!! Form::label('Time', 'Time', array('class'=>'control-label')) !!} {!! Form::time('time', null, array('class' => 'form-control', 'placeholder' => '')) !!} </div> </div> </div> <div class="row"> <div class="col-sm-6"> <div class="form-group form-group-default required"> {!! Form::label('names', 'Assigned To', array('class'=>'control-label')) !!} {!! Form::select('assigned_to', $employees, null, array('class' => 'form-control', 'placeholder' => '')) !!} </div> </div> <div class="col-sm-6"> <div class="form-group form-group-default"> {!! Form::label('Time', 'Priority', array('class'=>'control-label')) !!} {{ Form::select('priority',[''=>'Choose Priority','High'=>'High','Normal'=>'Normal','Low' => 'Low'], null, ['class' => 'form-control']) }} </div> </div> </div> <div class="row"> <div class="col-sm-6"> <div class="form-group form-group-default required"> {!! Form::label('status', 'Status', array('class'=>'control-label')) !!} {{ Form::select('status',[''=>'Choose status','Yet to Start'=>'Yet to Start','In Progress'=>'In Progress','Completed' => 'Completed'], null, ['class' => 'form-control']) }} </div> </div> </div> <div class="form-group"> {!! Form::label('Description', 'Description', array('class'=>'control-label')) !!} {{ Form::textarea('description', null, ['class' => 'form-control ckeditor']) }} </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-pink submit"><i class="fas fa-save"></i> Add Task</button> <img src="{!! asset('assets/img/btn-loader.gif') !!}" class="submit-load none" alt="" width="15%"> </div> </div> {!! Form::close() !!} </div> </div> @endforeach {{-- create task --}} <div class="modal fade" id="create-task" tabindex="-1" role="dialog"> <div class="modal-dialog modal-lg"> <form action="{!! route('crm.deals.task.store',$deal->dealID) !!}" method="post" autocomplete="off"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Add Task</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> @csrf <div class="row"> <div class="col-sm-6"> <div class="form-group form-group-default required"> {!! Form::label('names', 'Task', array('class'=>'control-label')) !!} {!! Form::text('task', null, array('class' => 'form-control', 'placeholder' => 'Enter task')) !!} <input type="hidden" name="dealID" value="{!! $deal->dealID !!}" required> </div> </div> <div class="col-sm-6"> <div class="form-group form-group-default required"> {!! Form::label('Category', 'Category', array('class'=>'control-label')) !!} {{ Form::select('category',[''=>'Choose Category','Call'=>'Call','Email'=>'Email','Follow_up' => 'Follow_up','Meeting' => 'Meeting','Milestone' => 'Milestone','Tweet' => 'Tweet','Other' => 'Other'], null, ['class' => 'form-control']) }} </div> </div> </div> <div class="row"> <div class="col-sm-6"> <div class="form-group form-group-default required"> {!! Form::label('names', 'Date (Due)', array('class'=>'control-label')) !!} {!! Form::text('date', null, array('class' => 'form-control datepicker', 'placeholder' => 'Choose date')) !!} </div> </div> <div class="col-sm-6"> <div class="form-group form-group-default"> {!! Form::label('Time', 'Time', array('class'=>'control-label')) !!} {!! Form::time('time', null, array('class' => 'form-control', 'placeholder' => '')) !!} </div> </div> </div> <div class="row"> <div class="col-sm-6"> <div class="form-group form-group-default required"> {!! Form::label('names', 'Assigned To', array('class'=>'control-label')) !!} {!! Form::select('assigned_to', $employees, null, array('class' => 'form-control', 'placeholder' => '')) !!} </div> </div> <div class="col-sm-6"> <div class="form-group form-group-default"> {!! Form::label('Time', 'Priority', array('class'=>'control-label')) !!} {{ Form::select('priority',[''=>'Choose Priority','High'=>'High','Normal'=>'Normal','Low' => 'Low'], null, ['class' => 'form-control']) }} </div> </div> </div> <div class="row"> <div class="col-sm-6"> <div class="form-group form-group-default required"> {!! Form::label('status', 'Status', array('class'=>'control-label')) !!} {{ Form::select('status',[''=>'Choose status','Yet to Start'=>'Yet to Start','In Progress'=>'In Progress','Completed' => 'Completed'], null, ['class' => 'form-control']) }} </div> </div> </div> <div class="form-group"> {!! Form::label('Description', 'Description', array('class'=>'control-label')) !!} {{ Form::textarea('description', null, ['class' => 'form-control ckeditor']) }} </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-pink submit"><i class="fas fa-save"></i> Add Task</button> <img src="{!! asset('assets/img/btn-loader.gif') !!}" class="submit-load none" alt="" width="15%"> </div> </div> </form> </div> </div>
import 'package:flutter/material.dart'; import '../models/chatUsersModel.dart'; import '../widgets/conversationList.dart'; class ChatHomeScreen extends StatelessWidget { ChatHomeScreen({Key? key}); List<ChatUsers> chatUsers = const [ ChatUsers( name: "Benn kaiser", messageText: "kuna game kesho saa saba sharp", imageURL: "https://xsgames.co/randomusers/assets/avatars/male/1.jpg", time: "Now"), ChatUsers( name: "Lauren Chebet", messageText: "wow! that a nice way to think about it", imageURL: "https://xsgames.co/randomusers/assets/avatars/female/2.jpg", time: "Yesterday"), ChatUsers( name: "Henry Omosh", messageText: "Hey where are you?", imageURL: "https://xsgames.co/randomusers/assets/avatars/male/3.jpg", time: "31 Mar"), ChatUsers( name: "Sally", messageText: "Busy! Call me in 20 mins", imageURL: "https://xsgames.co/randomusers/assets/avatars/female/43.jpg", time: "28 Mar"), ChatUsers( name: "Debra Shiks", messageText: "Thankyou, It's awesome", imageURL: "https://xsgames.co/randomusers/assets/avatars/male/5.jpg", time: "23 Mar"), ChatUsers( name: "Jacob Pena", messageText: "will update you in evening", imageURL: "https://xsgames.co/randomusers/assets/avatars/male/6.jpg", time: "17 Mar"), ChatUsers( name: "Mr. Randwet", messageText: "we mzee, nitumie notes bna", imageURL: "https://xsgames.co/randomusers/assets/avatars/male/7.jpg", time: "24 Feb"), ChatUsers( name: "John Wick", messageText: "How are you?", imageURL: "https://xsgames.co/randomusers/assets/avatars/male/8.jpg", time: "18 Feb"), ]; Future<void> _refreshPage() async { // Implement your refresh logic here // This function will be called when the user pulls down to refresh // You can fetch new data, reload content, etc. } @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: Column( children: <Widget>[ Padding( padding: const EdgeInsets.only(left: 16, right: 16, top: 10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ const Text( "WeCare", style: TextStyle(fontSize: 32, fontWeight: FontWeight.bold), ), Container( padding: const EdgeInsets.only( left: 8, right: 8, top: 2, bottom: 2), height: 30, decoration: BoxDecoration( borderRadius: BorderRadius.circular(30), color: Colors.blue[50], ), child: const Row( children: <Widget>[ Icon( Icons.add, color: Color.fromARGB(255, 30, 44, 233), size: 20, ), SizedBox( width: 2, ), Text( "new chat", style: TextStyle( fontSize: 14, fontWeight: FontWeight.bold), ), ], ), ) ], ), ), Padding( padding: const EdgeInsets.all(16.0), child: TextField( decoration: InputDecoration( hintText: "Search...", hintStyle: TextStyle(color: Colors.grey.shade600), prefixIcon: Icon( Icons.search, color: Colors.grey.shade600, size: 20, ), filled: true, fillColor: Colors.grey.shade100, contentPadding: const EdgeInsets.all(8), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(20), borderSide: BorderSide(color: Colors.grey.shade100), ), ), ), ), Expanded( child: RefreshIndicator( onRefresh: _refreshPage, child: ListView.builder( itemCount: chatUsers.length, itemBuilder: (context, index) { return ConversationList( name: chatUsers[index].name, messageText: chatUsers[index].messageText, imageUrl: chatUsers[index].imageURL, time: chatUsers[index].time, isMessageRead: (index == 0 || index == 3) ? true : false, ); }, ), ), ), ], ), ), ); } }
const showdown = require('showdown') const fs = require('fs') const path = require('path') const ncp = require('ncp').ncp ncp.limit = 16 // copy images into /docs ncp(path.join('assets', 'images'), path.join('docs', 'assets', 'images'), err => err ? console.log(err) : null) // copy css into /docs ncp(path.join('assets', 'template', 'css'), path.join('docs', 'css'), err => err ? console.log(err) : null) const converter = new showdown.Converter() const template = fs.readFileSync(path.join('assets', 'template', 'index.html'), 'utf8') const insertIntoTemplate = (content, template) => { const attachmentPoint = 'id="content">' const [before, after] = template.split(attachmentPoint) return [before, attachmentPoint, content, after].join('') } const index = fs.readFileSync(path.join('markdown', './index.md'), 'utf8') const html = insertIntoTemplate(converter.makeHtml(index), template) fs.writeFileSync(path.join('docs', 'index.html'), html) const views = fs.readdirSync(path.join('markdown')).filter(x => x !== 'index.md') views.forEach(view => { const mdPath = path.join('markdown', view) const md = fs.readFileSync(mdPath, 'utf8') const html = insertIntoTemplate(converter.makeHtml(md), template) const outputPath = path.join('docs', view.split('.')[0] + '.html') fs.writeFileSync(outputPath, html) })
import { BrowserRouter as Router, Route, Link, Routes } from 'react-router-dom'; import GoodDesignPage from './GoodDesignPage'; import BadDesignPage from './BadDesignPage'; import mePic from './rawan_picture.jpg'; import './App.css'; function App() { return ( <Router> <div className="App"> <header className="App-header"> <div className="content-container"> {/* Create a container for the content */} <img src={mePic} className="App-logo" alt="logo" /> <div className="App-paragraph"> <p> Howdy my name is Rawan Alzubaidi. I am a senior computer science student. I have a passion in web-development and UX/UI design. Outside of my studies, I have an interest in videography and blogging. I believe that Data visualization is a powerful tool for telling a story with data. Well-designed visualizations, present a narrative that guides the users through the data, helping them understand the significance of the information being presented. This class will allow me to learn more about data visualization best practices and understand how I can analyze data better. <a className="App-link" href="https://rawanaluzbaidi.netlify.app/" target="_blank" rel="noopener noreferrer" > If you would like to check my portfolio </a> </p> </div> </div> <div className="button-container"> <button className="good-design-button"> <Link to="/good-design" activeClassName="active-link"> <i className="fas fa-thumbs-up"></i> Good </Link> </button> <button className="bad-design-button"> <Link to="/bad-design" activeClassName="active-link"> <i className="fas fa-thumbs-down"></i> Bad </Link> </button> </div> <Routes> <Route path="/good-design" element={<GoodDesignPage />} /> <Route path="/bad-design" element={<BadDesignPage />} /> </Routes> </header> </div> </Router> ); } export default App;
import { ChangeEvent, FocusEventHandler, FormEvent, useReducer } from 'react'; import { CR_OFF, CR_ON } from './global-settings'; interface InputState { value: string, isTouched: boolean, dateValue: Date, } const initialInputState = { value: '', isTouched: false, dateValue: new Date(), }; type InputAction = { type: 'INPUT'; payload: string; } | { type: 'BLUR'; } | { type: 'RESET'; } | { type: 'INPUT_DATE'; payload: Date; } /** * Check empty input value * @param {string} value: input value * @returns {boolean} */ export function isNotEmpty(value: string) { return value.trim() !== ''; } /** * Check empty input value * @param {string} value: input value * @returns {boolean} */ export function isEmail(value: string) { return value.includes('@'); } /** * Check empty input value * @param {string} value: input value * @returns {boolean} */ export function isNumber(value: string) { const inputNumber = Number(value); return isNaN(inputNumber); } /** * Reducer * @param {InputState} state of the input form. * @param {InputAction} action of the user. * @returns {state} next state */ function inputStateReducer(state: InputState, action: InputAction) { switch (action.type) { case 'INPUT': { return { ...state, value: action.payload, isTouched: state.isTouched, dateValue: state.dateValue, }; } case 'INPUT_DATE': { return { ...state, value: state.value, isTouched: state.isTouched, dateValue: action.payload, }; } case 'BLUR': { return { value: state.value, isTouched: true, dateValue: state.dateValue, }; } case 'RESET': { return { value: '', isTouched: false, dateValue: new Date(), }; } default: return state; } } /** * NewClientForm * @param {()} validateValue: Higher order function * @returns {JSX.Element} */ function useInput(validateValue: any) { const [inputState, dispatch] = useReducer(inputStateReducer, initialInputState); const valueIsValid = validateValue(inputState.value); const hasError = !valueIsValid && inputState.isTouched; /** * Handler input change * @param {ChangeEvent} event input from user */ function valueChangeHandler(event: ChangeEvent<HTMLInputElement>) { dispatch({ type: 'INPUT', payload: event.target.value }); } /** * Handler input change * @param {string} initialValue input from user */ function valueInitHandler(initialValue: string) { dispatch({ type: 'INPUT', payload: initialValue }); } /** * Handler input change * @param {FormEvent} event select from user */ function valueSelectHandler(event: FormEvent<HTMLSelectElement>) { dispatch({ type: 'INPUT', payload: event.currentTarget.value }); } /** * Handler input change * @param {FormEvent} event select from user */ function valueCheckHandler(event: FormEvent<HTMLInputElement>) { const target = event.currentTarget; let checkboxValue = ''; if (target.type === 'checkbox') { checkboxValue = target.checked ? CR_ON : CR_OFF; } dispatch({ type: 'INPUT', payload: checkboxValue }); } /** * Handler input change * @param {Date} dateValue input from user */ function valueDateHandler(dateValue: Date) { dispatch({ type: 'INPUT_DATE', payload: dateValue }); } /** * Handler input got blur */ function inputBlurHandler() { dispatch({ type: 'BLUR' }); } /** * Handler input got focus * @param {FormEvent} event select from user */ function inputFocusHandler(event: FormEvent<FocusEventHandler>) { dispatch({ type: 'BLUR' }); } /** * Handler reset the input control */ function reset() { dispatch({ type: 'RESET' }); } return { dateValue: inputState.dateValue, hasError, isValid: valueIsValid, value: inputState.value, inputBlurHandler, inputFocusHandler, reset, valueChangeHandler, valueDateHandler, valueInitHandler, valueSelectHandler, valueCheckHandler, }; } export default useInput;
package org.skoman.ebankingbackend.entities; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.SuperBuilder; import org.skoman.ebankingbackend.enums.AccountCurrency; import org.skoman.ebankingbackend.enums.AccountStatus; import javax.persistence.*; import java.util.Date; import java.util.List; @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "TYPE", length = 4) @Data @NoArgsConstructor @AllArgsConstructor @SuperBuilder public abstract class BankAccount { @Id private String id; private double balance; private Date createdAt; @Enumerated(value = EnumType.STRING) private AccountStatus status; @Enumerated(value = EnumType.STRING) private AccountCurrency currency; @ManyToOne private Customer customer; @OneToMany(mappedBy = "bankAccount", fetch = FetchType.EAGER) private List<AccountOperation> accountOperations; }
import { OmitType, PartialType } from "@nestjs/mapped-types"; import { IsNotEmpty, IsString, MaxLength, MinLength } from "class-validator"; import { IsShortDate } from "src/lib/decorators"; export class CreateExperienceDto { @IsString() @IsNotEmpty() @MinLength(5) @MaxLength(30) title: string; @IsNotEmpty() @IsShortDate("startDate", { message: "Start date is of an invalid date format" }) startDate: string; @IsNotEmpty() @IsShortDate("endDate", { message: "End date is of an invalid date format" }) endDate: string; @IsString() @IsNotEmpty() @MinLength(10) @MaxLength(300) description: string; @IsString() @IsNotEmpty() userId: string; } export class UpdateExperienceDto extends PartialType(OmitType(CreateExperienceDto, ["userId"] as const)) {};
110, zon 6 dec '87 CURSUS MACHINETAAL MS-DOS DEEL 4 De vorige aflevering besloten we met de instructies voor optellen en aftrekken. We vervolgen met vermenigvuldigen en delen. VERMENIGVULDIGEN EN DELEN Voor vermenigvuldigen en delen met rest zijn er de instructies MUL, IMUL, DIV EN IDIV. Die met een I houden rekening met het teken (dus FF = -1 en niet 255 decimaal, FE = -2 enzovoort). Die zonder I nemen alles positief. Om grotere getallen te kunnen weergeven, worden de registers DX en AX gecombineerd. DX moet dan voor AX worden gezet, waarmee we een getal van 8 hexadecimale cijfers krijgen. Bij de toepassingen waar het gebruik van machinetaal nuttig is, komen deze ingewikkelde instructies gelukkig vrijwel niet voor. Wat wel vaak voorkomt, is vermenigvuldiging met twee en deling door twee. Daarvoor bestaan weer heel eenvoudige instructies. D1E8 SHR AX,1 SHR schuift de bits in AX een plaatsje naar rechts. Om in detail te zien wat dan gebeurt, moeten we het hexadecimale getal cijfer voor cijfer als bitreeks schrijven. Het hexadecimale getal A (10 decimaal) vertalen we bijvoorbeeld tot de bitreeks 1010 (8+2), het getal 5 tot 0101 (4+1). We schuiven bij SHR de reeks van in principe 16 bits een plaatsje naar rechts. 1010 wordt 0101 (een nul verdwijnt over de rechterrand); het getal A wordt 5. Zo komt SHR neer op delen door twee, zoals in het tientallig stelsel door tien gedeeld wordt, wanneer we een getal een plaatsje over de komma naar rechts schuiven. Schuiven we een hexadecimaal getal meerdere plaatsen naar rechts, dan delen we door 4, 8, 16 enzovoorts. Dat gaat echter niet via SHR AX,5 of iets dergelijks. Zouden we dat met debug proberen in te voeren, dan zien we: -a 105 0A2D:0105 shr ax,5 ^ Error 0A2D:0105 mov cl,5 0A2D:0107 shr ax,cl 0A2D:0109 ^C We moeten dus het gewenste aantal malen verschuiven in CL zetten. Een andere mogelijkheid is een aantal malen SHR AX,1 onder elkaar. Natuurlijk bestaat er ook SHL om met twee te vermenigvuldigen. Deze opdrachten nemen weer alle getallen positief. Voor getallen met teken zijn er SAR en SAL. Andere opdrachten zijn ROR en ROL, waarbij de R staat voor roteren. Hierbij schuift het bit dat aan de ene kant het register verlaat, aan de andere kant weer binnen. Deze rekenopdrachten zijn allemaal gericht op gehele getallen. Grote getallen en getallen met een komma kunnen we er niet mee bewerken. Een dergelijk getal wordt op een speciale manier opgeslagen in een reeks bytes en moet bewerkt worden via een subroutine opgebouwd met de gewone instructies. In het BASIC systeem zitten een groot aantal van dergelijke subroutines, maar het zal een hele kunst zijn ze te identificeren. SUBROUTINES Subroutines worden in machinetaal aangeroepen met de CALL opdracht. Net als van sprongopdrachten bestaat hiervan een gewone en een verre versie: E8AD0B CALL 0BEB 9A09009409 CALL 0994:0009 Het adres waarnaar straks teruggesprongen moet worden, komt op de stack te staan, bij de verre aanroep met codesegment. Voor de terugkeer vanuit de subroutine zijn er natuurlijk ook twee verschillende instructies: C3 RET (voor terugkeer in de buurt) CB RETF (voor terugkeer met een ander codesegment) RET haalt twee bytes van de stack, RETF vier. Omdat het subroutine-mechanisme dezelfde stack gebruikt als wijzelf, moeten binnen de subroutine de PUSHes precies in evenwicht zijn met de POPs. Anders zou het programma bij de terugkeer volledig de weg kwijtraken. DOS FUNCTIES Een bijzondere vorm van de verre aanroep is de interrupt-instructie. Aanroepen van Interrupt 21 geven toegang tot voorgeprogrammeerde functies van MS-DOS. Het volgende stukje programma opent een file: 0A43:0110 BA5C00 MOV DX,005C 0A43:0113 B40F MOV AH,0F 0A43:0115 CD21 INT 21 Gegevens over de file (onder andere de drive en de naam) staan in een bepaalde vorm in het zogenaamde file control blok, dat hier begint op adres 005C, dat we meegeven in het register DX. De functie 'file openen' heeft nummer 0F, welke waarde voor de aanroep in AH geladen moet worden. INT 21 leidt dan tot het feitelijke openen, waarbij de diskettedrive even zal snorren. Wanneer bij het starten van een programma filenamen worden opgegeven, krijgt de eerste (meestal de invoerfile) het begin van een file control blok op adres 5C in de voorloper. Het file control blok voor de tweede (gewoonlijk de uitvoerfile) komt op adres 6C. Wanneer echter het eerste blok geopend wordt, raakt dit tweede blok overschreven. We moeten het dus vooraf overbrengen naar een veilig deel van het geheugen. Informatie over de codes voor in AH, over de andere dingen die bij de aanroep moeten worden meegegeven, en over de dingen die de functies teruggeven, is in principe te vinden in een appendix van het DOS handboek van de computer. Ook aan de opbouw van het file control blok is een appendix gewijd. Helaas echter schijnen de fabrikanten deze informatie steeds minder belangrijk te vinden. 'Wie programmeert er nou met machinetaal?' De uitleg in de handboeken van een paar jaar geleden was veel uitgebreider dan die nu is. Er zijn handboeken waarin men het hele onderwerp heeft laten vallen. Als uw handboek daarbij is, probeer dan iemand te vinden, die zijn PC al een paar jaar geleden gekocht heeft. DIVERSE FUNCTIES Mocht er belangstelling voor zijn, dan kunnen we misschien in een extra les nog ingaan op de diverse functies. Bij het doorlopen van een programma met debug vragen interrupts om een speciale behandeling. Om onduidelijke redenen kunnen we er namelijk niet goed met het t-commando in afdalen. Wanneer u dat probeert, zult u zien dat het programma het spoor bijster raakt. Geef daarom bij het bereiken van een INT instructie niet t, maar g gevolgd door het adres na de INT opdracht. Dat is het adres dat u ziet staan plus twee, waarbij u rekening moet houden met de eigenaardigheden van het hexadecimale stelsel. Behalve de INT 21 functies van DOS bestaan er ook interrupts met andere nummers dan 21. Daarmee beginnen we de volgende aflevering. Behalve als beeldkrant verschijnt deze cursus in afleveringen ook in het tijdschrift Mens en Wetenschap (Postbus 108, 1270 AC HUIZEN, 02152 - 58388). Deze cursus wordt geschreven door Pim van Tend, Veldheimwg 8, 6871 CD RENKUM, 08373-15358. KLEURIGE TENTOONSTELLING Van 28 november 1987 tot en met 29 mei 1988 zal in het Technisch Tentoonstellings Centrum TTC in Delft een boeiende tentoonstelling te zien zijn over het kleursysteem dat door de NOS is ontwikkeld om verf te mengen voor het schilderen van televisie decors. De uit kleurrijke panelen en educatieve opstellingen bestaande tentoonstelling is getiteld 'HET NOS KLEURENPALET' en is vervaardigd door de NOS medewerker Herman Meijer, die het kleursysteem heeft ontwikkeld. De essentie van het NOS kleurentelevisie kleursysteem is dat door het mengen van slechts vijf basisverven meer dan 1700 kleurtinten kunnen worden verkregen. De gebruikte basisverven zijn volledig gifvrij en voldoen aan de strengste kleurkundige eisen. Een belangrijke voorwaarde bij het maken van televisie decors is dat de gebruikte kleuren op een zwart-wit toestel zichtbaar zijn in grijstonen, die duidelijk van elkaar verschillen. Als men niet aan die voorwaarde voldoet, kunnen bepaalde gekleurde details verloren gaan. Men noemt dit verschijnsel het Biesiot effect. Door het gebruik van het kleursysteem van Herman Meijer kan men dit nadelige effect voorkomen. OPBOUW TENTOONSTELLING Aan het begin van de tentoonstelling bevinden zich enkele educatieve opstellingen waarmee elementaire begrippen duidelijk worden gemaakt. De bezoeker kan zelf allerlei kleurfenomenen bekijken, zoals het mengen van gekleurd glas en de werking van het prisma. Tevens wordt ruime aandacht besteed aan de problemen die het mengen van verf op basis van de drie primaire kleuren magenta-rood, citroen-geel en cyaan-blauw met zich mee brengt. Het zal dan duidelijk worden welke kleuren verf men moet kiezen en hoe de kleurencirkel voor het mengen moet worden gebruikt. Alle stappen die tijdens de ontwikkeling van het NOS kleursysteem zijn gemaakt, kan de bezoeker meemaken. Met een echte televisie camera kan men zelf het Biesiot effect op een zwart-wit toestel waarnemen. De tweede helft van de expositie is gewijd aan studies die iedereen die in kleuren is geinteresseerd buitengewoon zal boeien. Met de kleuren uit het NOS systeem worden namelijk de belangrijkste mogelijkheden voor het maken van kleurontwerpen gedemonstreerd. Hierbij komen ook het maken van kleurklanken, kleurreeksen en kleurcomposities aan bod. Bovendien wordt aan de hand van voorbeelden duidelijk gemaakt hoe men te werk kan gaan om kleuren te mengen. Het Technisch Tentoonstellings Centrum TTC is dagelijks geopend van 10 tot 17 uur en op zondag van 13 tot 17 uur. Het is gesloten op erkende feestdagen. De toegang is gratis.
import { options } from "../../config"; import { PointInterface } from "./point"; export class Point implements PointInterface { public _x: number; public _y: number; public color?: string; constructor(x: number, y: number, color?: string) { this._x = x; this._y = y; this.color = color; } set x(value: number) { if (value < 0) return; if (value > options.field.width * options.field.cell) return; this._x = Math.round(value / options.field.cell) * options.field.cell; } set y(value: number) { if (value < 0) return; if (value > options.field.height * options.field.cell) return; this._y = Math.round(value / options.field.cell) * options.field.cell; } get x() { return this._x; } get y() { return this._y; } }
#include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include "msg.h" // Include the message header file with definitions #define MSG_MODE (0600) // Message queue mode int main() { int msqid, n; // Message queue ID and message size MsgType msg; // Message structure // Access the existing message queue using the defined key if ((msqid = msgget(MSG_KEY, MSG_MODE)) < 0) { perror("msgget"); // Error handling for message queue access exit(1); } // Compose a request message and send it to the message queue msg.type = MSG_REQUEST; // Set the message type for the request sprintf(msg.data, "This is a request from %d.", getpid()); // Create the request message if (msgsnd(msqid, (char *)&msg, sizeof(msg), 0) < 0) { perror("msgsnd"); // Error handling for message send exit(1); } printf("Sent a request....."); // Receive a reply message from the message queue if ((n = msgrcv(msqid, (char *)&msg, sizeof(msg), MSG_REPLY, 0)) < 0) { perror("msgrcv"); // Error handling for message receive exit(1); } printf("Received reply: %s\n", msg.data); return 0; }
import gsap from "gsap"; import { useEffect, useRef } from "react"; import { useScrollContext } from "./Scroll"; import { Link } from "@tanstack/react-router"; import { useStickyContext } from "./StickyCursor/StickyContext"; export function NavBar() { const { lenis } = useScrollContext(); const timeline = useRef(gsap.timeline()); const scroll = useScrollContext(); const navRef = useRef(); const { addStickyElement } = useStickyContext(); const createStickyElementRef = (el) => { el && addStickyElement(el); }; const animateNav = (navRef, scrollRef) => { const tl = gsap.timeline({ scrollTrigger: { trigger: scrollRef, start: "0px", end: "8600px", onUpdate: (self) => { const scrollDirection = self.direction; if (scrollDirection === 1) { gsap.to(navRef.current, { y: -200, autoAlpha: 0, duration: 5, ease: "expo.out", }); } else { gsap.to(navRef.current, { y: 0, autoAlpha: 1, duration: 3, ease: "expo.out", }); } }, }, }); return tl; }; useEffect(() => { const context = gsap.context(() => { const tl = timeline.current; tl.add(animateNav(navRef, scroll.ref), 0); }); return () => context.revert(); }, []); const routes = [ { name: "Home", path: "/" }, { name: "Story", path: "/story" }, { name: "Characters", path: "/characters" }, ]; return ( <header ref={navRef} className="navbar__wrapper"> <nav className="navbar" ref={navRef} style={{ fontFamily: "Jujutsu Kaisen" }} > {routes.map((route) => { return ( <Link onClick={() => lenis.scrollTo("top", { duration: 0 })} to={route.path} key={route.name} style={{ position: "relative" }} > {route.name} <div className="navbar__pseudoElement" ref={createStickyElementRef} ></div> </Link> ); })} </nav> </header> ); }
package com.example.mblfoods; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.SearchView; import android.widget.Toast; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.constraintlayout.widget.ConstraintLayout; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class SecondActivity extends AppCompatActivity implements PostRequestAsyncTask.OnPostRequestListener { String url = "https://script.google.com/macros/s/AKfycbybg9O5WOHEK3jrTd4XGCkoj2yLfeQaFOgWnRrPnZQj1AnW0US3gxoCELtAkyby8wdT/exec"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second_activity); // Retrieve the idToken parameter from the Intent String idToken = getIntent().getStringExtra("idToken"); loadalloutlets(); Button addOutletButton = findViewById(R.id.addOutletButton); addOutletButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Display a dialog to get the outlet name from the user showOutletNameDialog(); } }); // Initialize search functionality SearchView searchView = findViewById(R.id.searchView); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { // Not needed return false; } @Override public boolean onQueryTextChange(String newText) { searchForOutlet(newText); return true; } }); } private void searchForOutlet(String query) { ConstraintLayout layout = findViewById(R.id.second_activity_layout); for (int i = 0; i < layout.getChildCount(); i++) { View child = layout.getChildAt(i); if (child instanceof Button) { Button button = (Button) child; String buttonText = button.getText().toString(); if (buttonText.toLowerCase().contains(query.toLowerCase())) { button.setVisibility(View.VISIBLE); } else { button.setVisibility(View.GONE); } } } } private void loadalloutlets() { Map<String, String> postData = new HashMap<>(); JSONObject obj = new JSONObject(); try { obj.put("outletaction", "getoutlets"); } catch (JSONException e) { throw new RuntimeException(e); } postData.put("data", obj.toString()); // Send the POST request new PostRequestAsyncTask(this, postData).execute(url); } private void showOutletNameDialog() { // Create a dialog to prompt the user to enter the name for the outlet // For simplicity, here's a basic example using an EditText within an AlertDialog final EditText outletNameEditText = new EditText(this); // Create the AlertDialog new AlertDialog.Builder(this) .setTitle("Enter Outlet Name") .setView(outletNameEditText) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // User clicked OK button, retrieve the outlet name String outletName = outletNameEditText.getText().toString(); // Trigger POST request with the outlet name try { sendOutletName(outletName); } catch (JSONException e) { throw new RuntimeException(e); } } }) .setNegativeButton("Cancel", null) .show(); } private void sendOutletName(String outletName) throws JSONException { // Here, you would trigger the POST request with the outlet name Map<String, String> postData = new HashMap<>(); JSONObject obj = new JSONObject(); obj.put("outletname", outletName); postData.put("data", String.valueOf(obj)); AsyncTask<String, Void, String> res = new PostRequestAsyncTask(this, postData).execute(url); Log.d("OutletName", "Outlet Name: " + outletName); loadalloutlets(); } @Override public void onPostRequestCompleted(String result) { try { JSONObject jsonObject = new JSONObject(result); if (jsonObject.has("outlets")) { JSONArray outletsArray = jsonObject.getJSONArray("outlets"); CreateOutletButtons(outletsArray); } else { Toast.makeText(this, "No outlets found in the response", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); Toast.makeText(this, "Error processing response"+result, Toast.LENGTH_SHORT).show(); } } private void CreateOutletButtons(JSONArray outletsArray) { ConstraintLayout layout = findViewById(R.id.second_activity_layout); // Initialize the constraint to be connected to the searchView or addOutletButton if there are any int baselineId = R.id.searchView; for (int i = 0; i < outletsArray.length(); i++) { try { final String outletName = outletsArray.getString(i); Log.d("OutletButton", "Creating button for outlet: " + outletName); // Debug information Button button = new Button(this); button.setText(outletName); button.setGravity(Gravity.START | Gravity.CENTER_VERTICAL); // Align text to left button.setPadding(16, 0, 16, 0); // Add padding to text button.setTextColor(Color.BLACK); // Optional: Set text color // Set button ID dynamically to differentiate between buttons button.setId(View.generateViewId()); // Create LayoutParams for the button ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams( ConstraintLayout.LayoutParams.MATCH_PARENT, // Set width to match parent ConstraintLayout.LayoutParams.WRAP_CONTENT ); // Set constraints for the button layoutParams.topToBottom = baselineId; layoutParams.startToStart = ConstraintLayout.LayoutParams.PARENT_ID; layoutParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID; layoutParams.setMargins(16, 16, 16, 0); // Adjust margins as needed // Apply LayoutParams to the button button.setLayoutParams(layoutParams); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openOutletView(outletName); } }); // Add button to the layout layout.addView(button); // Update the baselineId for the next button baselineId = button.getId(); } catch (JSONException e) { e.printStackTrace(); } } } private void openOutletView(String outletName) { Intent intent = new Intent(this, OutletViewActivity.class); intent.putExtra("outletName", outletName); startActivity(intent); } }
package com.lagou.liuyu.service.impl; import com.lagou.liuyu.dao.LagouTokenDao; import com.lagou.liuyu.dto.ResultDTO; import com.lagou.liuyu.enums.BaseEnum; import com.lagou.liuyu.pojo.LagouToken; import com.lagou.liuyu.service.ICodeService; import com.lagou.liuyu.service.IUserService; import com.lagou.liuyu.utils.ResultUtils; import org.apache.commons.codec.digest.DigestUtils; import org.apache.tomcat.util.security.MD5Encoder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Example; import org.springframework.stereotype.Service; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.UUID; /** * @author LiuYu * @date 2022/5/15 22:04 */ @Service public class UserServiceImpl implements IUserService { @Autowired private ICodeService codeService; @Autowired private LagouTokenDao lagouTokenDao; /** * 注册接⼝,true成功,false失败 * * @param email * @param passWord * @param code */ @Override public ResultDTO register(String email, String passWord, String code, HttpServletResponse response) { // 验证验证码是否正确 final ResultDTO resultDTO = codeService.validateCode(email, code); // 验证码服务异常 if(!Objects.equals(BaseEnum.SUCCESS.code(), resultDTO.getCode())){ return ResultUtils.ERROR(BaseEnum.REGISTER_ERROR); } // 验证码错误 if(Objects.equals(resultDTO.getData(), 1)){ return ResultUtils.ERROR(BaseEnum.VALIDATE_CODE_ERROR); } // 验证码超时,超过10分钟 if(Objects.equals(resultDTO.getData(), 2)){ return ResultUtils.ERROR(BaseEnum.VALIDATE_CODE_TIMEOUT); } final LagouToken lagouToken = new LagouToken(); lagouToken.setEmail(email); final List<LagouToken> all = lagouTokenDao.findAll(Example.of(lagouToken)); if(all.size() > 0){ return ResultUtils.ERROR(BaseEnum.REGISTER_USER_NOT_NULL); } // 验证码正确,开始注册账户,生成token令牌 final String token = DigestUtils.md5Hex(email+passWord); LagouToken lagouToken1 = new LagouToken(); lagouToken1.setToken(token); lagouToken1.setEmail(email); lagouTokenDao.save(lagouToken1); Cookie cookie = new Cookie("token", token); response.addCookie(cookie); return ResultUtils.SUCCESS(); } /** * 是否已注册,根据邮箱判断,true代表已经注册过, * false代表尚未注册 * * @param email * @return */ @Override public boolean isRegistered(String email) { LagouToken lagouToken = new LagouToken(); lagouToken.setEmail(email); final Optional<LagouToken> one = lagouTokenDao.findOne(Example.of(lagouToken)); return one.isPresent(); } /** * 登录接⼝,验证⽤户名密码合法性,根据⽤户名和 * 密码⽣成token,token存⼊数据库,并写⼊cookie * 中,登录成功返回邮箱地址,重定向到欢迎⻚ * * @param email * @param passWord * @return */ @Override public String login(String email, String passWord, HttpServletResponse response) { final String token = DigestUtils.md5Hex(email+passWord); LagouToken lagouToken = new LagouToken(); lagouToken.setToken(token); lagouToken.setEmail(email); final Optional<LagouToken> one = lagouTokenDao.findOne(Example.of(lagouToken)); if(one.isPresent()){ Cookie cookie = new Cookie("token", token); cookie.setPath("/"); cookie.setMaxAge(36000); response.addCookie(cookie); return email; } return null; } /** * 根据token查询⽤户登录邮箱接⼝ * * @param token * @return */ @Override public String userInfo(String token) { LagouToken lagouToken = new LagouToken(); lagouToken.setToken(token); final Optional<LagouToken> one = lagouTokenDao.findOne(Example.of(lagouToken)); return one.orElse(new LagouToken()).getEmail(); } }
<template> <form @submit.prevent="onSubmit"> <div class="inputrow"> <label for="nickname">Pseudo :</label> <input type="text" name="nickname" placeholder="Pseudo" v-model="nickname" /> </div> <div class="inputrow"> <label for="firstname">Prénom :</label> <input type="text" name="firstname" placeholder="Prénom" v-model="firstname" /> </div> <div class="inputrow"> <label for="lastname">Nom :</label> <input type="text" name="lastname" placeholder="Nom" v-model="lastname" /> </div> <div class="inputrow"> <label for="email"><span>*</span>Email :</label> <input type="email" name="email" placeholder="Email" v-model="email" /> </div> <div class="group"> <div class="inputrow"> <label for="password1"><span>*</span>Mot de passe :</label> <input :type="pwdIsVisible ? 'text' : 'password'" name="password1" placeholder="Choix du mdp" minlength="8" @input="checkPwd1" v-model="password1" :class="this.isPwd1Ok ? '--valid' : ''" /> <span :class="this.isPwd1Ok ? '--valid' : '--invalid pwdInfo'"> {{ this.isPwd1Ok ? "Ok !" : "Minimum 8 caractères dont au moins une majuscule et un nombre" }} </span> <FontAwesomeIcon :icon="visibleIcon" class="icon" @click="toggleVisible" /> </div> </div> <div class="group"> <div class="inputrow"> <label for="password2"><span>*</span>Confirmation :</label> <input :type="pwdIsVisible ? 'text' : 'password'" name="password2" placeholder="Confirmation du mdp" minlength="8" v-model="password2" @input="checkPwd2" :class="this.isPwd1Ok && this.isPwd2Ok ? '--valid' : ''" /> <FontAwesomeIcon :icon="visibleIcon" class="icon" @click="toggleVisible" /> </div> </div> <input type="text" name="app" v-show="false" v-model="this.app" /> <Button text="Valider" className="--blue" width="80%" /> </form> </template> <script> import Button from "./Button.vue"; import controllers from "@/services/controllers"; import { BASE_URL } from "@/services/settings"; import axios from "axios"; import { faEye, faEyeSlash } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome"; export default { name: "SignupForm", components: { Button, FontAwesomeIcon, }, props: { user: { type: Object, default: { isLoggued: false }, }, }, data() { return { nickname: "", firstname: "", lastname: "", email: "", password1: "", password2: "", app: "auth", isPwd1Ok: false, isPwd2Ok: false, pwdIsVisible: false, }; }, computed: { visibleIcon() { return this.pwdIsVisible ? faEyeSlash : faEye; }, }, mounted() { const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); this.app = urlParams.get("app"); }, methods: { async onSubmit() { const formData = { nickname: this.nickname, firstname: this.firstname, lastname: this.lastname, email: this.email, password1: this.password1, password2: this.password2, app: this.app, }; const isForm = controllers.verifySignupForm(formData); if (!isForm.valid) return isForm.messages.forEach((message) => alert(message)); try { const response = await axios.post(`${BASE_URL}/signup`, formData); if (response.data.code) return controllers.alertCode(response.data.code); if (response.data.message) { alert(response.data.message); this.$emit("toggle-signup"); } } catch (error) { error.response ? alert(error.response.data.message) : alert(error.toString()); } }, checkPwd1() { // console.log('checkPwd1'); const matchRegex = controllers.testRegexPwd(this.password1); this.isPwd1Ok = matchRegex; this.checkPwd2(); }, checkPwd2() { console.log("checkPwd2"); return (this.isPwd2Ok = this.password1 === this.password2); }, toggleVisible() { this.pwdIsVisible = !this.pwdIsVisible; }, }, emits: ["toggle-signup"], }; </script>
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { of } from 'rxjs'; import { HttpHeaders, HttpResponse } from '@angular/common/http'; import { BioBaseApplicationTestModule } from '../../../test.module'; import { TraceFileComponent } from 'app/entities/trace-file/trace-file.component'; import { TraceFileService } from 'app/entities/trace-file/trace-file.service'; import { TraceFile } from 'app/shared/model/trace-file.model'; describe('Component Tests', () => { describe('TraceFile Management Component', () => { let comp: TraceFileComponent; let fixture: ComponentFixture<TraceFileComponent>; let service: TraceFileService; beforeEach(() => { TestBed.configureTestingModule({ imports: [BioBaseApplicationTestModule], declarations: [TraceFileComponent], }) .overrideTemplate(TraceFileComponent, '') .compileComponents(); fixture = TestBed.createComponent(TraceFileComponent); comp = fixture.componentInstance; service = fixture.debugElement.injector.get(TraceFileService); }); it('Should call load all on init', () => { // GIVEN const headers = new HttpHeaders().append('link', 'link;link'); spyOn(service, 'query').and.returnValue( of( new HttpResponse({ body: [new TraceFile(123)], headers, }) ) ); // WHEN comp.ngOnInit(); // THEN expect(service.query).toHaveBeenCalled(); expect(comp.traceFiles && comp.traceFiles[0]).toEqual(jasmine.objectContaining({ id: 123 })); }); }); });
import React, { useEffect, useRef } from 'react' import * as THREE from 'three' import { Main } from './styles' import { Card } from '../../components/Card' import pokeguiaImg from '../../assets/images/pokeguia.png' import kumpelImg from '../../assets/images/kumpelMockup.png' import countriesImg from '../../assets/images/countries.png' import easybankImg from '../../assets/images/easybank.png' import manageImg from '../../assets/images/managelanding.png' import socialMediaImg from '../../assets/images/socialmedia.png' import exchange from '../../assets/images/exchange.png' import smoke from '../../assets/images/smoke.png' export const Work = () => { const mount = useRef(null) useEffect(() => { let delta // Field of view const fov = 75 // Aspect ratio let width = document.documentElement.clientWidth let height = document.documentElement.clientHeight width = width < 320 ? 320 : width height = height < 400 ? 400 : height const aspect = width / height const near = 1 const far = 10000 const particlesNumber = 70 const clock = new THREE.Clock() // Renderer const renderer = new THREE.WebGLRenderer({ alpha: true }) renderer.setSize(width, height) renderer.setClearColor(0x000000, 0) // Create scene const scene = new THREE.Scene() // Camera setup const camera = new THREE.PerspectiveCamera(fov, aspect, near, far) camera.position.z = 1000 scene.add(camera) const light = new THREE.DirectionalLight(0xffffff, 0.6) light.position.set(-1, 0, 1) scene.add(light) // Load texture const smokeTexture = new THREE.TextureLoader().load(smoke) const smokeMaterial = new THREE.MeshLambertMaterial({ color: 0x00dddd, opacity: 0.5, map: smokeTexture, transparent: true }) const smokeGeo = new THREE.PlaneGeometry(300, 300) const smokeParticles = [] // Add particles for (let p = 0; p < particlesNumber; p++) { const particle = new THREE.Mesh(smokeGeo, smokeMaterial) particle.position.set(Math.random() * 500 - 250, Math.random() * 500 - 250, Math.random() * 1000 - 100) particle.rotation.z = Math.random() * 360 scene.add(particle) smokeParticles.push(particle) } mount.current.appendChild(renderer.domElement) const handleResize = () => { let width = document.documentElement.clientWidth let height = document.documentElement.clientHeight width = width < 320 ? 320 : width height = height < 400 ? 400 : height camera.aspect = width / height camera.updateProjectionMatrix() renderer.setSize(width, height) } const evolveSmoke = () => { let sp = smokeParticles.length while (sp--) { smokeParticles[sp].rotation.z += (delta * 0.2) } } window.addEventListener('resize', handleResize) const animate = () => { delta = clock.getDelta() // eslint-disable-next-line no-undef requestAnimationFrame(animate) evolveSmoke() renderer.render(scene, camera) } animate() }, []) return ( <Main ref={mount}> <h2>MY WORK</h2> <ul> <li><Card title='kumpel' description='Kumpel is a web application to search and rent rooms. This project consists of generating a platform where the user can open a request or offer hosting.' image={kumpelImg} link='https://www.youtube.com/watch?v=-iHEr1Ds1SE&list=PLk4Q1VrB4bbc24Na7vyakwVzEUK4rzLYp&index=2' /></li> <li><Card title='pokeguia' description='Pokedex is a site for consulting information on interactive Pokémon with hundreds of Pokémon to filter and explore. This is a project of the Platzi Master program' image={pokeguiaImg} link='https://www.youtube.com/watch?v=8sy8N-TmzPM&list=PLk4Q1VrB4bbc24Na7vyakwVzEUK4rzLYp&index=2&t=3s' /></li> <li><Card title='countries' description='This is the REST Countries API with color theme switcher coding challenge by Frontend Mentor Created using ReactJS. To see more visit my GitHub repository' image={countriesImg} link='https://loving-dubinsky-9b7d47.netlify.app/' /></li> <li><Card title='easybank' description='This the the Easybank landing page coding challenge by Fontend Mentor. Created using ReactJS. To see more visit my GitHub repository' image={easybankImg} link='https://esteban-ladino.github.io/easybank-landing-page/' /></li> <li><Card title='Manage page' description='This is the Manage landing page coding challenge by Frontend Mentor. Created using ReactJS. To see more visit my GitHub repository' image={manageImg} link='https://relaxed-borg-a653d7.netlify.app/' /></li> <li><Card title='social media' description='This is the Social Media Dashboard coding challenge by Frontend Mentor. Created using ReactJS. To see more visit my GitHub repository' image={socialMediaImg} link='https://esteban-ladino.github.io/social-media-dashboard/' /></li> <li><Card title='exchange page' description='This is a platform that will serve you to visualize all cryptocurrencies in real time, it was created at the Vue.js basic course from Platzi. Created using VueJS' image={exchange} link='https://esteban-exchange-project.netlify.app/' /></li> </ul> </Main> ) }
import { useEffect, useState, Fragment, useCallback } from "react"; import v1 from '../../../../../utils/axios-instance-v1' import { useTranslation } from 'react-i18next'; import { TableContainer, Table, TableHead, TableRow, TableCell, TableBody, Paper, Switch, Button, Backdrop, CircularProgress, Snackbar, Alert } from "@mui/material"; import EditModal from "./EditModal/EditModal"; import styled from "styled-components"; import Card from '@mui/material/Card'; import { format } from "date-fns/esm"; import { convertTime12to24 } from "../../../../../shared/utility"; const Loader = styled(Card)` display: flex; align-items: center; justify-content: center; text-align: center; min-height: 60vh; flex-grow: 1; ` export default function BookingSettings(props) { const { t } = useTranslation(); const [bookingTimes, setBookingTimes] = useState([]); const [open, setOpen] = useState(false); const [ show , setShow ] = useState(true); const [success, setSuccess] = useState(false) const [ editModalOpened, setEditModalOpened ] = useState(false); const [ selectedBookingTimeId , setSelectedBookingTimeId ] = useState(null); useEffect(() => { v1.get('/vendors/settings/booking_times') .then(res => { setBookingTimes(res.data) setShow(false) }) }, []); function allowBookingChanged(id) { setOpen(true) let times = [...bookingTimes]; let idx = times.findIndex(t => t.id === id) let time = { ...times[idx] } const openTime = new Date(`2021-02-03 ${convertTime12to24(time.start_time)}`) const closeTime = new Date(`2021-02-03 ${convertTime12to24(time.end_time)}`) v1.put('/vendors/settings/booking_times/' + id, { start_time: format(openTime, 'hh:mm a'), end_time: format(closeTime, 'hh:mm a'), multiple_booking: time.multiple_booking, max_booking: time.max_booking, per_day_max_booking: time.per_day_max_booking, per_slot_max_booking: time.per_slot_max_booking, status: time.status === 'enabled' ? 'disabled' : 'enabled', slot_duration: time.slot_duration }).then(res => { time.status = time.status === 'enabled' ? 'disabled' : 'enabled' times[idx] = time; setBookingTimes(times) setOpen(false) setSuccess(true) }) } function handleClose() { setSuccess(false) } const editModalOpenHandler =(id) => { setEditModalOpened(true) setSelectedBookingTimeId(id) } const editModalCloseHandler =(id) => { setEditModalOpened(false) setSelectedBookingTimeId(null) } const editModalConfirmHandler =(data) => { setEditModalOpened(false) setSelectedBookingTimeId(null) setOpen(true) v1.put(`/vendors/settings/booking_times/${data.id}`, {...data}) .then(res => { let times = [...bookingTimes]; let idx = times.findIndex(t => t.id === data.id) let time = { ...times[idx], ...data } times[idx] = time; setBookingTimes(times) setOpen(false) setSuccess(true) }) } return ( <Fragment> { show ? ( <Loader> <CircularProgress color="secondary" /> </Loader> ) : ( <TableContainer component={Paper}> <Table sx={{ minWidth: 650 }} aria-label="simple table"> <TableHead> <TableRow> <TableCell>{ t('SN') }</TableCell> <TableCell align="right">{t('Day')}</TableCell> <TableCell align="right">{t('Open Time')}</TableCell> <TableCell align="right">{t('Close Time')}</TableCell> <TableCell align="right">{t('Allow Booking')}</TableCell> <TableCell align="right">{t('Action')}</TableCell> </TableRow> </TableHead> <TableBody> {bookingTimes.map((row) => ( <TableRow key={row.id} sx={{ '&:last-child td, &:last-child th': { border: 0 } }} > <TableCell component="th" scope="row"> {row.id} </TableCell> <TableCell align="right">{t(row.day)}</TableCell> <TableCell align="right">{row.start_time}</TableCell> <TableCell align="right">{row.end_time}</TableCell> <TableCell align="right"><Switch checked={ row.status === 'enabled' } onChange={(e) => allowBookingChanged(row.id)} inputProps={{ 'aria-label': 'controlled' }} /></TableCell> <TableCell align="right"><Button onClick={(e) => editModalOpenHandler(row.id) }>{ t('Edit') }</Button></TableCell> </TableRow> ))} </TableBody> </Table> { editModalOpened && ( <EditModal show={editModalOpened} id={selectedBookingTimeId} bookingTimes={bookingTimes} onClose={editModalCloseHandler} onConfirm={editModalConfirmHandler} heading='edit booking times' confirmText='edit' /> ) } </TableContainer> ) } <Backdrop sx={{ color: '#fff', zIndex: (theme) => theme.zIndex.drawer + 1 }} open={open} > <CircularProgress color="inherit" /> </Backdrop> <Snackbar anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }} open={success} onClose={handleClose} key={'bottom-right'} > <Alert onClose={handleClose} severity="success" fullWidth>{t('Saved Successfuly')}</Alert> </Snackbar> </Fragment> ) }
import argparse import os import pickle import random import ssl import numpy as np import skimage import tensorflow as tf import tensorflow_probability as tfp from tensorflow.python.keras.applications import vgg16, mobilenet_v2, resnet50, vgg19, inception_v3 from tensorflow.python.keras.applications.mobilenet_v2 import decode_predictions from tensorflow.python.keras.layers import Dense, Input from tensorflow.python.keras.layers import concatenate from tensorflow.python.keras.models import Model from tensorflow.python.keras.optimizers import Adam from tensorflow.python.keras.utils import to_categorical from tensorflow.python.keras import backend as K from stl10_data_loader import STL10Loader from tools import get_logger epsilon = 1e-10 lambda_reg = 1e-2 NUM_PREDICITION_SAMPLES = 1000 def kullback_leibler_divergence(y_true, y_pred): y_true = K.clip(y_true, K.epsilon(), 1) y_pred = K.clip(y_pred, K.epsilon(), 1) return K.sum(y_true * K.log(y_true / y_pred), axis=-1) def dirichlet_aleatoric_cross_entropy(y_true, y_pred): """ Loss function that applies a categorical cross entropy to the predictions obtained from the original model combined with a beta parameter that models the aleatoric noise associated with each data point. We model a Dirichlet pdf based on the combination of both the prediction and the beta parameter to sample from it and obtain the resulting output probabilities Parameters ---------- y_true: `np.array` the labels in one hot encoding format y_pred: `np.array` output of the model formed by the concatenation of the original prediction in the first num_classes positions, and a beta scalar in the last one Returns ------- an array with the associated cross-entropy for each element of the batch """ # original probability distribution of the prediction among the classes mu_probs = y_pred[:, :num_classes] # beta parameter for each prediction beta = y_pred[:, num_classes:] beta = tf.broadcast_to(beta, (lambda shape: (shape[0], shape[1]))(tf.shape(mu_probs))) # alpha parameter based on the prediction scaled by the beta factor alpha = mu_probs * beta # defition of the Dir pdf dirichlet = tfp.distributions.Dirichlet(alpha) # sampling from the Dir to obtain different y_hats for the prediction z = dirichlet.sample(sample_shape=NUM_PREDICITION_SAMPLES) # MC e_probs = tf.reduce_mean(z, axis=0) # log of the resulting probabilities for the cross entropy formulation log_probs = tf.log(e_probs + epsilon) # cross entropy cross_entropy = -(tf.reduce_sum(y_true[:, :num_classes] * log_probs, axis=-1)) # we return the cross entropy plus a regularization term to prevent the beta # to grow forever aleatoric_loss = cross_entropy + lambda_reg * tf.reduce_sum(beta, axis=-1) return y_true[:, num_classes:] * aleatoric_loss + (1 - y_true[:, num_classes:]) * kullback_leibler_divergence(y_true[:, :num_classes], e_probs) # metric that outputs the max/min value for the sigma logits def max_beta(y_true, y_pred): beta = y_pred[:, num_classes:] return tf.reduce_max(beta) def min_beta(y_true, y_pred): beta = y_pred[:, num_classes:] return tf.reduce_min(beta) def create_uncertainty_model(learning_rate=1e-3, num_hidden_units=20, type = 'mobilenet_v2'): mu_input = Input(shape=(num_classes,)) if type == 'mobilenet_v2': base_model = mobilenet_v2.MobileNetV2(include_top=False, weights='imagenet', input_tensor=None, input_shape=(224, 224, 3), pooling='avg', classes=num_classes) elif type == 'vgg16': base_model = vgg16.VGG16(include_top=False, weights='imagenet', input_tensor=None, input_shape=(224, 224, 3), pooling='avg', classes=num_classes) elif type == 'resnet50': base_model = resnet50.ResNet50(include_top=False, weights='imagenet', input_tensor=None, input_shape=(224, 224, 3), pooling='avg', classes=num_classes) elif type == 'vgg19': base_model = vgg19.VGG19(include_top=False, weights='imagenet', input_tensor=None, input_shape=(224, 224, 3), pooling='avg', classes=num_classes) elif type == 'inception_v3': base_model = inception_v3.InceptionV3(include_top=False, weights='imagenet', input_tensor=None, input_shape=(224, 224, 3), pooling='avg', classes=num_classes) else: base_model = mobilenet_v2.MobileNetV2(include_top=False, weights='imagenet', input_tensor=None, input_shape=(224, 224, 3), pooling='avg', classes=num_classes) base_model.trainable = False beta = base_model.output beta = Dense(num_hidden_units, activation='relu')(beta) beta = Dense(num_hidden_units, activation='relu')(beta) beta = Dense(num_hidden_units, activation='relu')(beta) # beta = Dense(num_hidden_units,activation='relu')(beta) beta = Dense(1, activation='sigmoid')(beta) output = concatenate([mu_input, beta]) model = Model(inputs=[mu_input, base_model.input], outputs=output) model.compile(loss=dirichlet_aleatoric_cross_entropy, optimizer=Adam(lr=learning_rate), metrics=[max_beta, min_beta] ) return model if __name__ == "__main__": parser = argparse.ArgumentParser(description="load the job offers from different sources to a common ES index") parser.add_argument('--epochs', type=int, default=1, help='epochs to train uncertainty model') parser.add_argument('--learning_rate', type=float, default=1e-4, help='learning rate') parser.add_argument('--num_units', type=int, default=40, help='num units') parser.add_argument('--batch_size', type=int, default=64, help='batch size') parser.add_argument('--output_model_file', type=str, default='stl10_uncertainty_model', help='file to dump the generated model') parser.add_argument('--output_history_file', type=str, default='stl10_uncertainty_history', help='file to dump the generated data') parser.add_argument('--input_dir', type=str, default='./', help='dir to load the trained model') parser.add_argument('--label_mapping_file', type=str, default='imagenet_stl10_mapping.pkl', help='label mapping file') parser.add_argument('--inverse_label_mapping_file', type=str, default='stl10_imagenet_mapping.pkl', help='label mapping file') parser.add_argument('--lambda_reg', type=float, default=1e-2, help='Lambda parameter for regularization of beta values') parser.add_argument('--model_type', type=str, default='mobilenet_v2', help='type of base model to learn the betas mobilenet_v2|vgg16|vgg19|resnet50|inception_v3') args = parser.parse_args() input_dir = args.input_dir batch_size = args.batch_size learning_rate = args.learning_rate num_units = args.num_units epochs = args.epochs train_file = 'train_prob_preds.pkl' output_model_file = os.path.sep.join([input_dir, args.output_model_file]) output_history_file = os.path.sep.join([input_dir, args.output_history_file]) lambda_reg = args.lambda_reg logger = get_logger() ssl._create_default_https_context = ssl._create_unverified_context new_shape = (224, 224, 3) num_classes = 10 logger.info('Load mapping file') with open(args.label_mapping_file, 'rb') as file: imagenet_stl10_mapping = pickle.load(file) with open(args.inverse_label_mapping_file, 'rb') as file: stl10_imagenet_mapping = pickle.load(file) logger.info('Load target dataset') with open(os.path.sep.join([input_dir, train_file]), 'rb') as file: mu_predictions = pickle.load(file) logger.error("Loading STL-10") stl10_data_loader = STL10Loader(num_classes) (stl10_x_train, stl10_y_train, stl10_y_train_cat), (_, _, _) = stl10_data_loader.load_raw_dataset() stl10_unlabeled_train, _ = stl10_data_loader.load_raw_ood_dataset(num_training=1000, num_test=1000) logger.error("Resize training images") stl10_x_train_resized = np.array( [skimage.transform.resize(image, new_shape, anti_aliasing=True) for image in stl10_x_train]) stl10_unlabeled_train_resized = np.array( [skimage.transform.resize(image, new_shape, anti_aliasing=True) for image in stl10_unlabeled_train]) stl10_train_X_ood = np.concatenate((stl10_x_train_resized, stl10_unlabeled_train_resized)) ood_label = 1/num_classes ood_labels = [ood_label]*num_classes + [0] stl10_train_y_ood = np.concatenate( (np.insert(stl10_y_train_cat, num_classes, 1, axis=-1), np.array([ood_labels] * stl10_unlabeled_train_resized.shape[0]))) logger.error("Load model") model = mobilenet_v2.MobileNetV2(weights='imagenet') logger.error("Predict training") train_preds = model.predict(stl10_train_X_ood) train_prob_preds = train_preds[:, stl10_imagenet_mapping[0]].sum(axis=1) / len(stl10_imagenet_mapping[0]) for i in range(1, 10): train_prob_preds = np.hstack( (train_prob_preds, train_preds[:, stl10_imagenet_mapping[i]].sum(axis=1) / len(stl10_imagenet_mapping[0]))) train_prob_preds = train_prob_preds.reshape((num_classes, train_preds.shape[0])).T fake_y_pred_train_ood = train_prob_preds / train_prob_preds.sum(axis=1, keepdims=1) train_indexes = np.random.permutation(stl10_train_X_ood.shape[0]) stl10_train_X_ood = stl10_train_X_ood[train_indexes] stl10_train_y_ood = stl10_train_y_ood[train_indexes] fake_y_pred_train_ood = fake_y_pred_train_ood[train_indexes] logger.info("Create uncertainty model") unc_model = create_uncertainty_model(learning_rate=learning_rate, num_hidden_units=num_units, type=args.model_type) logger.info("train uncertainty") training_history = unc_model.fit([fake_y_pred_train_ood, stl10_train_X_ood], stl10_train_y_ood, batch_size=batch_size, epochs=epochs, shuffle=True, verbose=1, validation_split=0.1) logger.info("Save the training history") with open(output_history_file, 'wb') as file: pickle.dump(training_history.history, file) logger.info("Save the model") tf.keras.models.save_model( unc_model, output_model_file, overwrite=True, include_optimizer=True, save_format=None ) logger.info("Done")
<?php include '../../db/db_connection.php'; if ($_SERVER['REQUEST_METHOD'] === 'PUT') { parse_str(file_get_contents("php://input"), $_PUT); // Handle PUT request for updating a user $userId = $_PUT['user_id']; $newUsername = $_PUT['username']; $password = $_PUT['password']; $userType = $_PUT['user_type']; // Check if the new username is already in use by other users $checkStmt = $conn->prepare("SELECT user_id FROM users WHERE username = ? AND user_id != ?"); $checkStmt->bind_param("si", $newUsername, $userId); $checkStmt->execute(); $checkResult = $checkStmt->get_result(); if ($checkResult->num_rows > 0) { $response = array('status' => 'error', 'message' => 'Username already in use'); } else { // Check if there are any changes $existingStmt = $conn->prepare("SELECT username, password, user_type FROM users WHERE user_id = ?"); $existingStmt->bind_param("i", $userId); $existingStmt->execute(); $existingResult = $existingStmt->get_result(); if ($existingResult->num_rows > 0) { $existingUserData = $existingResult->fetch_assoc(); if ( $newUsername === $existingUserData['username'] && $password === $existingUserData['password'] && $userType === $existingUserData['user_type'] ) { $response = array('status' => 'success', 'message' => 'No changes made'); } else { // Update the user $updateStmt = $conn->prepare("UPDATE users SET username = ?, password = ?, user_type = ? WHERE user_id = ?"); $updateStmt->bind_param("sssi", $newUsername, $password, $userType, $userId); $updateStmt->execute(); if ($updateStmt->affected_rows > 0) { $response = array('status' => 'success', 'message' => 'User updated successfully'); } else { $response = array('status' => 'error', 'message' => 'Failed to update user'); } } } else { $response = array('status' => 'error', 'message' => 'User not found'); } } echo json_encode($response); } else { $response = array('status' => 'error', 'message' => 'Invalid request method'); echo json_encode($response); } ?>
import 'dart:convert'; import 'dart:ui'; import 'package:http/http.dart' as http; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:weather_app/halamanRegister.dart'; import 'halamanUtama.dart'; import 'package:crypt/crypt.dart'; class HalamanLogin extends StatefulWidget { const HalamanLogin({super.key}); @override State<HalamanLogin> createState() => _HalamanLoginState(); } class _HalamanLoginState extends State<HalamanLogin> { bool isLoginFailed = false; TextEditingController _usernameController = TextEditingController(); TextEditingController _passwordController = TextEditingController(); List _listData = []; bool siangHari = false; Future _getuser() async { try { final response = await http.get(Uri.parse( "https://weatherdatabaseaccount.000webhostapp.com/read.php")); if (response.statusCode == 200) { final data = jsonDecode(response.body); setState(() { _listData = data; }); } } catch (e) { print(e); } } @override void initState() { _getuser(); DateTime waktuSekarang = DateTime.now(); int jamSekarang = waktuSekarang.hour; super.initState(); if (jamSekarang > 6 && jamSekarang < 18) { siangHari = true; } } Widget build(BuildContext context) { return Scaffold( body: Container( height: MediaQuery.of(context).size.height, decoration: BoxDecoration( image: DecorationImage( image: siangHari ? AssetImage("assets/afternoonSky.jpg") : AssetImage("assets/nightSky.jpg"), fit: BoxFit.cover, ), ), child: Column( mainAxisAlignment: MainAxisAlignment.end, children: [ SingleChildScrollView( child: Container( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter, colors: [ Colors.black, // Atas hitam dengan opasitas 100% Colors.black.withOpacity(0), // Bawah hitam dengan opasitas 50% ], ), ), child: Padding( padding: EdgeInsets.all(MediaQuery.of(context).size.width * 0.1), child: Form( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "Login untuk melanjutkan", style: TextStyle( fontSize: 18, color: Colors.white, shadows: [ Shadow( blurRadius: 10, color: Colors.black, offset: Offset(2, 2), ), ], ), ), SizedBox( height: MediaQuery.of(context).size.width * 0.025, ), ClipRRect( borderRadius: BorderRadius.circular(20), child: BackdropFilter( filter: ImageFilter.blur( sigmaY: 10, sigmaX: 10, ), child: TextFormField( controller: _usernameController, decoration: InputDecoration( filled: true, focusColor: Colors.black, fillColor: Colors.white.withOpacity(0.5), hintText: 'Username', focusedBorder: OutlineInputBorder( borderSide: const BorderSide( color: Colors.white, width: 3), borderRadius: BorderRadius.circular(20)), labelStyle: TextStyle( color: Colors.black12, fontSize: 18), border: OutlineInputBorder( borderRadius: BorderRadius.circular(20.0), borderSide: BorderSide( // Mengatur sifat border color: Colors.blue, // Warna border width: 2.0, // Ketebalan border ), ), ), ), ), ), SizedBox( height: MediaQuery.of(context).size.width * 0.025), ClipRRect( borderRadius: BorderRadius.circular(20), child: BackdropFilter( filter: ImageFilter.blur( sigmaY: 10, sigmaX: 10, ), child: TextFormField( controller: _passwordController, obscureText: true, decoration: InputDecoration( filled: true, focusColor: Colors.black, fillColor: Colors.white.withOpacity(0.5), hintText: 'Password', focusedBorder: OutlineInputBorder( borderSide: const BorderSide( color: Colors.white, width: 3), borderRadius: BorderRadius.circular(20)), labelStyle: TextStyle( color: Colors.black12, fontSize: 18), border: OutlineInputBorder( // Menambah// kan border borderRadius: BorderRadius.circular(20.0), // Mengatur sudut border borderSide: BorderSide( // Mengatur sifat border color: Colors.blue, // Warna border width: 2.0, // Ketebalan border ), ), ), ), ), ), if(isLoginFailed) ( SizedBox( height: MediaQuery.of(context).size.width * 0.075, child: Row( children: [ Text( "Username / password salah.", style: TextStyle( color: Colors.red, fontWeight: FontWeight.bold ), ), ], ), ) ), if(isLoginFailed==false) ( SizedBox( height: MediaQuery.of(context).size.width * 0.075) ), Row( children: [ InkWell( onTap: () { login(); }, child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), color: Colors.teal), child: Padding( padding: const EdgeInsets.all(15.0), child: Row( children: [ Icon( Icons.login_rounded, size: 30, color: Colors.white, ), Text( "LOGIN", style: TextStyle( color: Colors.white, fontSize: 22, fontWeight: FontWeight.bold), ), ], ), ), ), ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: EdgeInsets.only(left: 11.5), child: Text( "Belum punya akun?", style: TextStyle( fontSize: 18, color: Colors.white, shadows: [ Shadow( blurRadius: 10, color: Colors.black, offset: Offset(2, 2), ), ], ), ), ), TextButton( onPressed: () { Navigator.pushReplacement( context, MaterialPageRoute( builder: (BuildContext context) => HalamanRegister())); }, child: Text( 'Register', style: TextStyle( fontSize: 18, color: Colors.teal, fontWeight: FontWeight.bold, ), ), ), ], ), ], ), //SizedBox(height: MediaQuery.of(context).size.width * 0.1), ], ), ), ), ), ), ], ), ), ); } void login() async { String username = _usernameController.text; String password = _passwordController.text; bool isUserFound = false; bool isValid(String cryptFormatHash, String enteredPassword) => Crypt(cryptFormatHash).match(enteredPassword); for (int x = 0; x < _listData.length; x++) { if (_listData[x]["username"] == username) { isUserFound = true; bool cekPassword = isValid(_listData[x]["password"], password); if (cekPassword) { final SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setStringList('items', <String>[_listData[x]["idTempat"], _listData[x]["longitude"], _listData[x]["latitute"], _listData[x]["tempatDefault"], _listData[x]["id"]]); Navigator.pushReplacement( context, MaterialPageRoute( builder: (BuildContext context) => HalamanUtama( idWilayah: _listData[x]["idTempat"], longitude: _listData[x]["longitude"], latitude: _listData[x]["latitute"], kabupaten: _listData[x]["tempatDefault"], id: _listData[x]["id"], ), ), ); break; // Keluar dari loop setelah login berhasil } } } if (!isUserFound) { setState(() { isLoginFailed = true; }); } else { setState(() { isLoginFailed = true; }); } } }
import { useState } from 'react'; import { Dimensions, ImageBackground, StyleSheet, Switch, Text, View, } from 'react-native'; import { useNavigation } from '@react-navigation/native'; import { Information } from 'components/Information'; import { Input } from 'components/Input'; import { DefaultButton } from 'components/buttons/DefaultButton'; import { colors, fonts } from 'settings/themes'; export function SignIn() { const navigation = useNavigation(); const [forgotPassword, setForgotPassword] = useState(false); const [isEnabled, setIsEnabled] = useState(false); const toggleSwitch = () => setIsEnabled(previousState => !previousState); return ( <ImageBackground style={styles.container} source={require('../assets/authBackground.png')} > {forgotPassword ? ( <Information label='Utilize o e-mail usado no cadastro e verifique se o link foi recebido no e-mail' type='information' /> ) : ( <Text style={styles.greenText}> Bem vindo! Faça login para prosseguir </Text> )} <Input label='E-mail' type='default' placeholder='Digite seu e-mail' /> {!forgotPassword && ( <> <Input label='Senha' type='password' placeholder='Digite sua senha' /> <View style={styles.wrapper}> <View style={styles.rememberView}> <Switch style={styles.switch} trackColor={{ false: colors.gray_300, true: colors.quaternaryRGBA }} thumbColor={isEnabled ? colors.quaternary : colors.gray_500} onValueChange={toggleSwitch} value={isEnabled} /> <Text style={styles.grayText}>Lembrar Conta</Text> </View> <Text onPress={() => setForgotPassword(true)} style={styles.grayText} > Esqueceu sua Senha? </Text> </View> </> )} <View style={{ flexDirection: 'row' }}> <DefaultButton label={forgotPassword ? 'Enviar' : 'Entrar'} type='primary' onPress={() => navigation.navigate('Home')} /> </View> {!forgotPassword && ( <> <View style={styles.wrapper}> <View style={styles.line} /> <Text style={styles.grayText}>ou entre com</Text> <View style={styles.line} /> </View> <View style={styles.wrapper}> <DefaultButton label='Google' type='select' iconName='google' onPress={() => navigation.navigate('Home')} /> <DefaultButton label='Facebook' type='select' iconName='facebook' onPress={() => navigation.navigate('Home')} /> </View> <Text style={styles.grayText}>Ainda não possui cadastro?</Text> <Text style={styles.greenText} onPress={() => navigation.navigate('SignUp')} > Cadastre-se </Text> </> )} </ImageBackground> ); }; const styles = StyleSheet.create({ container: { flex: 1, width: Dimensions.get('window').width, alignItems: 'center', justifyContent: 'flex-start', paddingTop: Dimensions.get('window').height/4, paddingHorizontal: 32 }, greenText: { marginBottom: 32, textAlign: 'center', color: colors.terciary, fontFamily: fonts.semiBold, fontSize: 22, fontWeight: '600', }, wrapper: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', width: '100%', gap: 16, marginBottom: 32, }, rememberView: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', }, switch: { marginVertical: -12, marginLeft: -4, marginRight: 4, }, grayText: { color: colors.gray_500, textAlign: 'center', fontFamily: fonts.medium, fontSize: 16, }, line: { flex: .44, height: 1, backgroundColor: colors.gray_200, }, });
// Bryan Zublin // 828354677 // BinarySearchTree.h: Header file for BinaryBinarySearchTree.cpp // The only way to insert data in a tree is with the insert function, thus // satisfying the BST rule giving it a well behaved ordering to the type T. #ifndef BINARY_SEARCH_TREE_H #define BINARY_SEARCH_TREE_H #include <iostream> // for std::cout #include <utility> namespace BST_NS { template<class T> class BinarySearchTree; //forward declaration template<class T> class TreeNode { public: TreeNode( ) : data(NULL), leftLink(NULL), rightLink(NULL) {} TreeNode(T theData, TreeNode<T>* left, TreeNode<T>* right) : data(theData), leftLink(left), rightLink(right) {} friend class BinarySearchTree<T>; private: T data; TreeNode<T>* leftLink; TreeNode<T>* rightLink; }; // supply the pre and post conditions for each method template<class T> class BinarySearchTree { private: TreeNode<T> *root; int tree_size; // mine std::pair<TreeNode<T>*, TreeNode<T>*> bSearch(T item) const; void deleteTree(TreeNode<T> *node); BinarySearchTree<T> copyTree(BinarySearchTree<T> tree); void recursivePreOrderShow(TreeNode<T>* subTreeRoot) const; void recursiveInOrderShow(TreeNode<T>* subTreeRoot) const; void recursivePostOrderShow(TreeNode<T>* subTreeRoot) const; int getTreeHeight(TreeNode<T>*); public: // default ctor BinarySearchTree() : root(NULL), tree_size(0) {} // copy ctor BinarySearchTree(const BinarySearchTree& other); // virtual dtor virtual ~BinarySearchTree(); // insert an item to the tree void insert(T item); // remove an item from the tree void remove(T item); // check if an item exists in the tree bool inTree(T item) const; // overloading assignment operator BinarySearchTree& operator=(const BinarySearchTree other); // empty the tree void makeEmpty(); // pre-order traversal (prints to stdout) void preOrderShow() const; // in-order traversal (prints to stdout) void inOrderShow() const; // post-order traversal (prints to stdout) void postOrderShow() const; // return size of tree int size() const; // return height of tree int height(); }; } // BST_NS #endif
import neuromancer as nm def nnQuadratic2(c, Q, d, b, A, E, F, func, alpha=100): # solution map from model parameters: sol_map(p) -> x sol_map = nm.system.Node(func, ["p"], ["x"], name="smap") # trainable components components = [sol_map] # parameters p = nm.constraint.variable("p") # variables x = nm.constraint.variable("x") # obj & constr obj, constrs = probQuadratic2(x, p, c, Q, d, b, A, E, F, alpha) # merit loss function loss = nm.loss.PenaltyLoss(obj, constrs) # optimization solver problem = nm.problem.Problem(components, loss) return problem def probQuadratic2(x, p, c, Q, d, b, A, E, F, alpha=100): # objective function f = sum(c[i] * x[:, i] for i in range(2)) \ + 0.5 * sum(Q[i, j] * x[:, i] * x[:, j] for i in range(2) for j in range(2)) \ + sum(d[i] * x[:, i+2] for i in range(2)) obj = f.minimize(weight=1.0, name="obj") objectives = [obj] # constraints constraints = [] for i in range(7): lhs = sum(A[i, j] * x[:, j] for j in range(2)) + sum(E[i, j] * x[:, j+2] for j in range(2)) rhs = b[i] + F[i, 0] * p[:, 0] + F[i, 1] * p[:, 1] con = alpha * (lhs <= rhs) con.name = "c{}".format(i) constraints.append(con) # nonnegative for i in range(4): con = alpha * (x[:, i] >= 0) con.name = "xl{}".format(i) constraints.append(con) return objectives, constraints if __name__ == "__main__": import numpy as np import torch from torch import nn from utlis import test # random seed np.random.seed(42) torch.manual_seed(42) # init num_data = 5000 # number of data num_vars = 10 # number of decision variables num_ints = 5 # number of integer decision variables test_size = 1000 # number of test size val_size = 1000 # number of validation size # get datasets from data import getDatasetQradratic2 c, Q, d, b, A, E, F, datasets = getDatasetQradratic2(num_data=num_data, test_size=test_size, val_size=val_size) data_train, data_test, data_dev = datasets # torch dataloaders from torch.utils.data import DataLoader loader_train = DataLoader(data_train, batch_size=32, num_workers=0, collate_fn=data_train.collate_fn, shuffle=True) loader_test = DataLoader(data_test, batch_size=32, num_workers=0, collate_fn=data_test.collate_fn, shuffle=True) loader_dev = DataLoader(data_dev, batch_size=32, num_workers=0, collate_fn=data_dev.collate_fn, shuffle=True) # define neural architecture for the solution map func = nm.modules.blocks.MLP(insize=2, outsize=4, bias=True, linear_map=nm.slim.maps["linear"], nonlin=nn.ReLU, hsizes=[10]*4) # get solver problem = nnQuadratic2(c, Q, d, b, A, E, F, func, alpha=100) # training lr = 0.01 # step size for gradient descent epochs = 200 # number of training epochs warmup = 50 # number of epochs to wait before enacting early stopping policy patience = 50 # number of epochs with no improvement in eval metric to allow before early stopping # set adamW as optimizer optimizer = torch.optim.AdamW(problem.parameters(), lr=lr) # define trainer trainer = nm.trainer.Trainer( problem, loader_train, loader_dev, loader_test, optimizer, epochs=epochs, patience=patience, warmup=warmup) # train solution map best_model = trainer.train() print() # params p = np.random.uniform(0.5, 1, 2) print("Parameters p:", list(p)) print() # get solution from Ipopt print("Ipopt:") from problem.solver import exactQuadratic2 c, Q, d, b, A, E, F = c.cpu().numpy(), Q.cpu().numpy(), d.cpu().numpy(), b.cpu().numpy(), A.cpu().numpy(), E.cpu().numpy(), F.cpu().numpy() model = exactQuadratic2(c, Q, d, b, A, E, F) model.setParamValue(*p) test.solverTest(model, solver="ipopt") # get solution from neuroMANCER print("neuroMANCER:") datapoint = {"p": torch.tensor([list(p)], dtype=torch.float32), "name":"test"} test.nmTest(problem, datapoint, model)
// // LocationSearchView.swift // Uber // // Created by Park Junsuk on 2022/10/06. // import SwiftUI struct LocationSearchView: View { @State var startLocation = "" @Binding var mapViewState: MapViewState @EnvironmentObject var viewModel: LocationSearchViewModel var body: some View { VStack(alignment: .leading) { HStack { VStack { Rectangle() .foregroundColor(.gray) .frame(width: 6, height: 6) Rectangle() .frame(width: 1, height: 24) Rectangle() .frame(width: 6, height: 6) } .padding(.trailing) VStack { TextField("Current Location", text: $startLocation) .padding(.bottom) TextField("Destination Location", text: $viewModel.queryFragment) } } .padding(.horizontal) .padding(.top, 72) Divider() .padding(.vertical) ScrollView { VStack { ForEach(viewModel.result, id: \.self) { i in LocationResultCell(title: i.title, subtitle: i.subtitle) .onTapGesture { withAnimation(.spring()) { viewModel.selectLocation(i) mapViewState = .locationSelected } } } } } .padding(.leading) } .background(.white) } } struct LocationSearchView_Previews: PreviewProvider { static var previews: some View { LocationSearchView(mapViewState: .constant(.noInput)) } }
@extends('layouts.dashboard') @section('admin') <div class="card"> <div class="card-body"> <div class="row align-items-center"> <div class="col-lg-3 col-xl-2"> <a href="{{ route('dashboard.users.create') }}" class="btn btn-primary mb-3 mb-lg-0" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Tambah"><i class="bi bi-plus-square-fill mx-1"></i> Tambah User </a> </div> <div class="col-lg-9 col-xl-10"> <form class="float-lg-end"> <div class="row row-cols-lg-auto g-2"> <div class="col-12"> <a href="javascript:;" class="btn btn-light mb-3 mb-lg-0"><i class="bi bi-download"></i>Export</a> </div> <div class="col-12"> <a href="javascript:;" class="btn btn-light mb-3 mb-lg-0"><i class="bi bi-upload"></i>Import</a> </div> </div> </form> </div> </div> </div> </div> <div class="card"> <div class="card-body"> <div class="d-flex align-items-center"> <h5 class="mb-0">Details All Users</h5> </div> <div class="table-responsive mt-3"> <table id="example" class="table align-middle" style="width: 100%"> <thead class="table-secondary"> <tr> <th>No</th> <th>Nama</th> <th>Email</th> <th>Roles</th> <th width="280px">Aksi</th> </tr> </thead> <tbody> @foreach ($data as $key => $user) <tr> <td> {{ ++$i }} </td> <td> <div class="d-flex align-items-center gap-3 cursor-pointer"> <img src="{{ asset('dashboard/assets/images/avatars/avatar-1.png') }}" class="rounded-circle" width="44" height="44" alt=""> <div class=""> <p class="mb-0">{{ $user['name'] }}</p> </div> </div> </td> <td>{{ $user->email }}</td> <td> @if (!empty($user->getRoleNames())) @foreach ($user->getRoleNames() as $v) <label class="badge {{ $v == 'Admin' ? 'bg-warning' : ($v == 'User' ? 'bg-primary' : 'bg-success') }}">{{ $v }}</label> @endforeach @endif </td> <td> <div class="table-actions d-flex align-items-center gap-3 fs-6"> <a href="{{ route('dashboard.users.show', $user->id) }}" class="text-primary mx-1" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Lihat"> <i class="bi bi-eye-fill"></i> </a> <a href="{{ route('dashboard.users.edit', $user->id) }}" class="text-warning mx-1" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Edit"> <i class="bi bi-pencil-fill"></i> </a> <a href="{{ route('dashboard.users.destroy', $user->id) }}" class="text-danger mx-5" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Hapus" onclick="event.preventDefault(); if (confirm('Anda yakin ingin menghapus?')) { document.getElementById('delete-form-{{ $user->id }}').submit(); }"> <i class="bi bi-trash-fill"></i> </a> <form id="delete-form-{{ $user->id }}" action="{{ route('dashboard.users.destroy', $user->id) }}" method="POST" style="display: none;"> @csrf @method('DELETE') </form> </div> </td> </tr> @endforeach </tbody> </table> </div> </div> </div> {{-- {!! $data->render() !!} --}} @push('style') <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css"> <style> #tbluser_filter { display: none; } </style> @endpush @push('script') <script src="https://code.jquery.com/jquery-3.7.0.js"></script> <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script> <script> $(document).ready(function() { var table = new DataTable('#example', { "language": { "search": "Search:", "searchPlaceholder": "Search your word..." }, columnDefs: [{ orderable: false, targets: 4 }] }); $('#searchInput').on('keyup', function() { table.search(this.value).draw(); }); }); </script> @endpush @endsection
// // NoteChallengeUITests.swift // NoteChallengeUITests // // Created by Dai Tran on 8/10/23. // import XCTest final class NoteChallengeUITests: XCTestCase { override func setUpWithError() throws { continueAfterFailure = false } func testLoginSuccess() { let username = "Jack" let app = XCUIApplication() app.launch() let timeout = 2.0 let userNameTextField = app.textFields["Username"] XCTAssertTrue(userNameTextField.waitForExistence(timeout: timeout)) userNameTextField.tap() userNameTextField.typeText(username) let loginButton = app.buttons["Login"] XCTAssertTrue(loginButton.waitForExistence(timeout: timeout)) loginButton.tap() let navigationTitle = app.navigationBars.matching(identifier: username).firstMatch XCTAssertTrue(navigationTitle.waitForExistence(timeout: timeout)) } func testLoginFailed() { let app = XCUIApplication() app.launch() let timeout = 2.0 let userNameTextField = app.textFields["Username"] XCTAssertTrue(userNameTextField.waitForExistence(timeout: timeout)) let loginButton = app.buttons["Login"] XCTAssertTrue(loginButton.waitForExistence(timeout: timeout)) loginButton.tap() let navigationTitle = app.navigationBars.matching(identifier: "Log In").firstMatch XCTAssertTrue(navigationTitle.waitForExistence(timeout: timeout)) } func testAddNoteSuccess() { let username = "Jack" let addedNote = "Random" let app = XCUIApplication() app.launch() // Input username let timeout = 2.0 let userNameTextField = app.textFields["Username"] XCTAssertTrue(userNameTextField.waitForExistence(timeout: timeout)) userNameTextField.tap() userNameTextField.typeText(username) // Login let loginButton = app.buttons["Login"] XCTAssertTrue(loginButton.waitForExistence(timeout: timeout)) loginButton.tap() var navigationTitle = app.navigationBars.matching(identifier: username).firstMatch XCTAssertTrue(navigationTitle.waitForExistence(timeout: timeout)) let list = app.collectionViews.element let noteCountBeforeAdding = list.exists ? list.cells.count : 0 // Add note let addNoteButton = app.navigationBars.buttons["Add"].firstMatch XCTAssertTrue(addNoteButton.waitForExistence(timeout: timeout)) addNoteButton.tap() navigationTitle = app.navigationBars.matching(identifier: "Add Notes").firstMatch XCTAssertTrue(navigationTitle.waitForExistence(timeout: timeout)) let noteTextField = app.textFields["Note"] noteTextField.tap() noteTextField.typeText(addedNote) let doneButton = app.navigationBars.buttons["Done"].firstMatch XCTAssertTrue(doneButton.waitForExistence(timeout: timeout)) doneButton.tap() // Assert added note XCTAssertTrue(list.waitForExistence(timeout: timeout)) XCTAssertEqual(Int(list.cells.count), noteCountBeforeAdding + 1) let lastCell = list.cells.element(boundBy: list.cells.count - 1) XCTAssertTrue(lastCell.staticTexts[addedNote].exists) } }
import { Field, InputType, registerEnumType } from "@nestjs/graphql" import { Max } from "class-validator" import { Iso3166CountriesCodesEnum, Iso3166CountryCode } from "../interfaces/iso-3166.interface" import { GeonamesEntity } from "./geonames.objects" registerEnumType(Iso3166CountriesCodesEnum, { name: "countryCodes" }) @InputType() export class SearchManyQuery { @Field({ nullable: true }) languageCode?: string @Field(() => Iso3166CountriesCodesEnum, { nullable: true }) countryCode?: Iso3166CountryCode @Field({ defaultValue: 0 }) offset!: number @Max(1000) @Field({ defaultValue: 100 }) limit!: number @Field({ nullable: true, defaultValue: "population" }) sorting?: "population" | string } @InputType() export class SearchSingleQuery { @Field() id!: number @Field({ nullable: true }) languageCode?: string } export type SearchStyle = "SHORT" | "MEDIUM" | "LONG" | "FULL" // More at https://www.geonames.org/export/codes.html export enum GeonamesFeatureCodesEnum { COUNTRY = "PCLI", CITY = "PPL*" } export type FeatureCode = `${GeonamesFeatureCodesEnum}` export interface GeonamesBaseRequestParams { username: string lang?: string } export interface GeonamesManyRequestParams extends GeonamesBaseRequestParams { type?: "json" startRow?: number maxRows?: number orderby?: string style?: SearchStyle fcode?: string country?: Iso3166CountryCode } export interface GeonamesSingleRequestParams extends GeonamesBaseRequestParams { geonameId?: number } export interface GeonamesManyResponse { totalResultsCount: number geonames: [GeonamesEntity] } export interface GeonamesXMLResponse { geoname: { name: string[] toponymName: string[] geonameId: string[] fcode: FeatureCode[] countryCode: Iso3166CountryCode[] } }
import React, { useEffect, useState } from 'react'; import { IonButton, IonButtons, IonCard, IonCardContent, IonCol, IonIcon, IonItem, IonLabel, IonRow, } from '@ionic/react'; import { add, heart, heartOutline } from 'ionicons/icons'; import { useDispatch, useSelector } from 'react-redux'; import { addCartAction, delCartAction } from '../reducers/CartAction'; import { ItemObj, RootState, WishList } from '../model/DomainModels'; import { ErrorProps, ShopItemProps } from '../model/ComponentProps'; import { FirestoreIonImg } from '../services/FirebaseStorage'; import { useFirestore } from 'react-redux-firebase'; import { useHistory } from 'react-router-dom'; import { loadWishList } from '../reducers/WishListAction'; import CurrencyAmount from '../components/CurrencyAmount'; import ErrorDisplay from '../components/ErrorDisplay'; import { filter, remove } from 'lodash'; import { useTranslation } from 'react-i18next'; const ShopItem: React.FC<ShopItemProps> = ({ item, market_id, category_id }) => { const dispatch = useDispatch(); const history = useHistory(); const db = useFirestore(); const { t } = useTranslation(); const auth = useSelector<RootState>((state) => state.firebase.auth) as any; const shop = useSelector<RootState>((state) => state.shop); const WishLists = useSelector<RootState>((state) => state.wishList.data) as any; const cartStore = useSelector<RootState>((state) => state.cart.cartItemList) as ItemObj[]; const [favorites, setFavorites] = useState(heartOutline); const [errorProps, setErrorProps] = useState<ErrorProps>({} as ErrorProps); const totalItemInCard = filter(cartStore, (i: ItemObj) => i.id === item.id).length; const addFavorites = () => { const json_auth = JSON.parse(JSON.stringify(auth)); const obj: WishList = { item_id: item.id, market_id: market_id, category_id: category_id, item: item, }; writeData(obj, json_auth.uid); }; const writeData = async (data: WishList, user_id: string) => { const json_shop = JSON.parse(JSON.stringify(shop)); setFavorites(heart); const items = await db .collection('WishLists') .doc(user_id) .collection('Markets') .doc(market_id) .collection('Items') .get(); if (items.empty) { await db.collection('WishLists').doc(user_id).collection('Markets').doc(market_id).set(json_shop.shop); await db.collection('WishLists').doc(user_id).collection('Markets').doc(market_id).collection('Items').add(data); } else { const itemList: any = []; items.forEach((doc) => { const doc1 = doc.data(); itemList.push(doc1); }); await db .collection('WishLists') .doc(user_id) .collection('Markets') .doc(market_id) .collection('Items') .doc(data.item_id) .set(data); } getWishList(); }; const getWishList = () => { db.collection('WishLists') .doc(auth.uid) .collection('Markets') .doc(market_id) .collection('Items') .get() .then((snapshot) => { if (snapshot.empty) { dispatch(loadWishList([])); } else { const tmp: any = []; snapshot.forEach((doc) => { tmp.push({ ...doc.data(), id: doc.id }); }); dispatch(loadWishList(tmp)); } }) .catch(() => { dispatch(loadWishList([])); }); }; const addCart = (item: ItemObj) => { dispatch(addCartAction(item, market_id)); }; const delCart = (item: ItemObj) => { dispatch(delCartAction(item, market_id)); }; const checkFavorite = (writing: boolean) => { const json_auth = auth; if (json_auth && json_auth.uid) { const docRef = db .collection('WishLists') .doc(json_auth.uid) .collection('Markets') .doc(market_id) .collection('Items'); const isExists = WishLists.find((wItem: any) => wItem.item_id == item.id) as any; if (isExists) { if (writing) { remove(WishLists, { item_id: 'item' }); docRef .doc(isExists.id) .delete() .then(() => { getWishList(); console.log(isExists.id + ' deleted'); }); setFavorites(heartOutline); } else { setFavorites(heart); } } else { if (writing) { addFavorites(); } } } }; useEffect(() => { if (favorites === heartOutline) { console.log('use Effect Set Favorites'); checkFavorite(false); } }, [WishLists]); if ( !item.unit_price || item.unit_price == '' || item.unit_price == null || !item.unit || item.unit == '' || item.unit == null || item.is_deleted ) { return null; } return ( <IonCard> <IonCardContent style={{ padding: 10 }}> <IonRow> <IonCol size="4"> <FirestoreIonImg src={item.img_url as string} showModal /> </IonCol> <IonCol size="7.8"> <IonLabel> <p>{item.name}</p> <br /> <p className="currency"> <CurrencyAmount amount={item.unit_price} /> {item.unit} </p> </IonLabel> <br /> <IonItem lines="none" style={{ float: 'right', height: '33px' }}> {totalItemInCard === 0 ? ( <IonButton color="tertiary" fill="outline" size="small" onClick={() => addCart(item)}> <IonIcon slot="start" icon={add} /> {t('addToCart')} </IonButton> ) : ( <IonButtons style={{ flexDirection: 'row', justifyContent: 'space-around', width: 100 }}> <IonButton color="tertiary" fill="outline" size="small" onClick={() => { delCart(item); }} > - </IonButton> {totalItemInCard} <IonButton color="tertiary" fill="outline" size="small" onClick={() => { addCart(item); }} > + </IonButton> </IonButtons> )} <IonButton color="secondary" fill="clear" size="small" onClick={() => { checkFavorite(true); }} > <IonIcon icon={favorites} /> </IonButton> </IonItem> <IonItem lines="none" style={{ float: 'right' }} className="shop_item_min_order"> <IonLabel>{t('minimumOrder')}: Nil</IonLabel> </IonItem> </IonCol> </IonRow> </IonCardContent> <ErrorDisplay errorProps={errorProps} closeHandler={() => { setErrorProps({ ...errorProps, showError: false }); }} eventHandler={() => { history.push('/login'); setErrorProps({ ...errorProps, showError: false }); }} /> </IonCard> ); }; export default ShopItem;
<!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>Document</title> </head> <body> <div> <form th:action = "@{/search-result/0}" method="GET"> <label for="search">Search</label> <input type="text" name = "keyword"> <button type="submit">Search</button> </form> </div> <div th:if = "${success}"> <p th:text = "${success}"></p> </div> <div th:if = "${failed}"> <p th:text = "${failed}"></p> </div> <div> <div th:if = "${size == 0}"> <p>No category</p> </div> <table th:if = "${size > 0}"> <thead> <tr> <th>Name</th> <th>Category</th> <th>Price</th> <th>Quantity</th> <th>Image</th> <th>Update</th> <th>Action</th> </tr> </thead> <tbody> <tr th:each = "product : ${products}"> <th th:text = "${product.name}"></th> <th th:text = "${product.category.name}"></th> <th th:text = "${product.costPrice}"></th> <th th:text = "${product.currentQuantity}"></th> <th> <img th:src="*{'data:image/jpeg;base64,' + {product.image}}" alt="" style="height:40px; width : 40px"></th> <th><a th:href="@{/update-product/{id} (id = ${product.id})}" >Update</a></th> <th> <a th:if ="${product.activated == false}" th:href="@{/enabled-product/{id} (id = ${product.id})}">Enable</a> <a th:if = "${product.activated == true}" th:href="@{/deleted-product/{id} (id = ${product.id})}">Delete</a> </th> </tr> </tbody> </table> <nav> <ul> <li th:if = "${currentPage != 0}"><a th:href="@{'/search-result/' + ${currentPage - 1}} + '?keyword='+ ${keyword}">Previous</a></li> <li th:each ="i : ${#numbers.sequence(1,totalPages)}" th:classappend = "${currentPage == i -1 ? 'active' : ''}"><a th:href="@{'/search-result/' + ${i-1} + '?keyword=' + ${keyword}}" th:text = "${i}"></a></li> <li th:if = "${currentPage + 1 != totalPages}"><a th:href="@{'/search-result/' + ${currentPage + 1} + '?keyword=' + ${keyword} }">Next</a></li> </ul> </nav> </div> </body> </html>
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Spatie\Health\Checks\Checks\CacheCheck; use Spatie\Health\Checks\Checks\DatabaseCheck; use Spatie\Health\Checks\Checks\DatabaseConnectionCountCheck; use Spatie\Health\Checks\Checks\DatabaseSizeCheck; use Spatie\Health\Checks\Checks\DatabaseTableSizeCheck; use Spatie\Health\Checks\Checks\DebugModeCheck; use Spatie\Health\Checks\Checks\EnvironmentCheck; use Spatie\Health\Checks\Checks\HorizonCheck; use Spatie\Health\Checks\Checks\OptimizedAppCheck; use Spatie\Health\Checks\Checks\QueueCheck; use Spatie\Health\Checks\Checks\RedisCheck; use Spatie\Health\Checks\Checks\RedisMemoryUsageCheck; use Spatie\Health\Checks\Checks\ScheduleCheck; use Spatie\Health\Checks\Checks\UsedDiskSpaceCheck; use Spatie\Health\Facades\Health; class HealthServiceProvider extends ServiceProvider { public function register(): void { Health::checks([ UsedDiskSpaceCheck::new() ->warnWhenUsedSpaceIsAbovePercentage(70) ->failWhenUsedSpaceIsAbovePercentage(90), CacheCheck::new(), DatabaseCheck::new(), DatabaseConnectionCountCheck::new(), DatabaseSizeCheck::new(), DatabaseTableSizeCheck::new(), DebugModeCheck::new(), EnvironmentCheck::new(), OptimizedAppCheck::new(), HorizonCheck::new(), ScheduleCheck::new() ->heartbeatMaxAgeInMinutes(2), QueueCheck::new() //->onQueue([...]) ->failWhenHealthJobTakesLongerThanMinutes(5), RedisCheck::new(), RedisMemoryUsageCheck::new(), ]); } }
# Copyright 2021 Google LLC. This software is provided as-is, without warranty # or representation for any use or purpose. Your use of it is subject to your # agreement with Google. import google from includes.allfunds.loggers import log_info, log_warning from includes.allfunds.utils import get_gcs_dag_config_files, get_local_dag_config_files, parse_dag_configuration, prepare_batch_payload # from includes.allfunds.utils import get_local_dag_config_files, parse_dag_configuration, prepare_batch_payload, \ # removesuffix from airflow import DAG from airflow.models import Variable from airflow.operators.empty import EmptyOperator from airflow.providers.google.cloud.sensors.gcs import GCSObjectsWithPrefixExistenceSensor # from astronomer.providers.google.cloud.sensors.gcs import GCSObjectsWithPrefixExistenceSensorAsync from airflow.providers.google.cloud.transfers.gcs_to_gcs import GCSToGCSOperator from airflow.providers.google.cloud.transfers.gcs_to_bigquery import GCSToBigQueryOperator from airflow.providers.google.cloud.operators.dataproc import DataprocCreateBatchOperator from airflow.decorators import task from datetime import datetime from airflow.operators.python import get_current_context import json import os credentials, project_id = google.auth.load_credentials_from_file( "/opt/airflow/dags/afb-lakehouse-poc-f00756f9a1a7.json") os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = "/opt/airflow/dags/afb-lakehouse-poc-f00756f9a1a7.json" ################################ Main Workflow steps below ################################## def create_data_ingestion_dag(dag_id, schedule, default_args, source_config, processing_config, destination_config ): """Return new created DAG from given config Input : - dag_id string - schedule String - default_args dict - source_config dict Output : DAG """ source_objects_prefix = source_config.source_objects_prefix landing_bucket = source_config.landing_bucket processing_bucket = processing_config.staging_bucket target_project_id = destination_config.target_project_id dataset_id = destination_config.dataset_name source_format = source_config.source_format table_name = destination_config.table_name # store_bucket = destination_config.store_bucket # staging_bucket = "whejna-allfunds-datalake" # override the start date with the right format if "start_date" in default_args: default_args["start_date"] = datetime.strptime(default_args.get("start_date"), '%d/%m/%y') dag = DAG(dag_id, schedule_interval=schedule, default_args=default_args, max_active_runs=5, catchup=False) with dag: start = EmptyOperator( task_id='start', dag=dag, ) prefix = f"""{source_objects_prefix}/{source_objects_prefix}""" + "{{ ds_nodash }}" wait_for_data = GCSObjectsWithPrefixExistenceSensor( task_id=f"gcs_wait_for_data_files", # google_cloud_conn_id=Variable.get("allfunds_landing_bucket_conn_id"), bucket=landing_bucket, prefix=prefix, mode="reschedule", # TODO: fix and put to the configuration file poke_interval=300 ) @task(task_id="local_prepare_dataproc_input", multiple_outputs=True) def prepare_dataproc_input(): pyspark_batch_args = { "input_bucket": f"{processing_bucket}/{source_objects_prefix}*", "template_name": "GCSTOBIGQUERY", "source_format": source_format, "output_mode": "overwrite", "dataset_id": "raw_data", "table_name": f"{table_name}_dataproc", "dataproc_staging_bucket": "whejna-allfunds-datalake", "dataproc_subnetwork_project_id": "whejna-allfunds-datalake", "dataproc_subnetwork_region_id": "europe-west1", "dataproc_subnetwork_name": "default", "dataproc_service_account": "[email protected]" } return prepare_batch_payload(**pyspark_batch_args) prepare_dataproc_input_op = prepare_dataproc_input() batch_ingestion_task = DataprocCreateBatchOperator( task_id="dataproc_transform", batch_id=f"ingestion-from-composer-{table_name.replace('_', '-')}-{int(datetime.timestamp(datetime.now()))}", project_id="whejna-allfunds-datalake", region="europe-west3", gcp_conn_id="allfunds_cloud_default", batch=prepare_dataproc_input_op ) load_to_bq_op = GCSToBigQueryOperator( task_id='bigquery_load', bucket=processing_bucket, destination_project_dataset_table=f"{target_project_id}:{dataset_id}.{table_name}", source_format=source_format, source_objects=batch_ingestion_task.output, compression="NONE", create_disposition="CREATE_IF_NEEDED", write_disposition="WRITE_TRUNCATE", field_delimiter=",", skip_leading_rows=1, location="europe-west1", autodetect=True ) end = EmptyOperator( task_id='end', dag=dag, ) # define the dag dependencies # start >> wait_for_data >> move_to_processing >> load_to_bq_op >> move_to_store >> end start >> wait_for_data >> prepare_dataproc_input_op >> batch_ingestion_task >> load_to_bq_op >> end # move_to_processing >> prepare_dataproc_input_op >> batch_ingestion_task >> move_to_store log_info(msg=f'DAG {dag_id} is added') return dag ################################ Main Function ################################## def main(config_path): """Parse the configuration and submit dynamic dags to airflow global namespace based on config files from GCS bucket. args: config_path - path of the config (bucket / local path) where the configuration file are """ try: dag_config_files = get_gcs_dag_config_files(config_path) except: dag_config_files = get_local_dag_config_files(config_path) log_info(msg=f"added config: {dag_config_files}") ingestion_dags = parse_dag_configuration(dag_config_files) for dag in ingestion_dags: globals()[dag.dag_id] = create_data_ingestion_dag(dag.dag_id, dag.schedule, dag.default_args, dag.source_config, dag.processing_config, dag.destination_config ) # set up the relative path (to avoid using Airflow vars) # config_path = "gs://afb-input-config-dev" config_path = "/opt/airflow/plugins/config" main(config_path)
Puppi: A Pluggable Deploy Automation and SysAdmin helper Puppet module # Written by Lab42 # # http://www.example42.com Licence: GPLv3 Puppi is a Puppet module that lets sysadmins manage and automate the deployment of applications and provides quick and standard commands to obtain informations about the system and what's is going on it. Its structure provides FULL flexibility on the actions required for virtually any kind of application deployment and information gathering. The module provides: - The puppi command and its whole working environment - A set of scripts that can be used in chain to automate any kind of deployment - Puppet defines that make it easy to prepare a puppi set of commands for a project deployment USAGE OF THE PUPPI COMMAND puppi <command> <project_name> [ -options ] The puppi command has these possibile actions: - puppi init <project_name> : First time initialization of the defined project - puppi deploy <project_name> : Deploys the defined project - puppi rollback <project_name> : Rollback to a previous deploy state - puppi check [project_name] : Runs project specific and host wide checks - puppi log [project_name] : Tails system wide or project specific logs - puppi info [topic] : Show system information (for all or only the specified topic) - puppi todo [topic] : Show things to do (or done) manually on the system For most of these actions puppi runs the commands in /etc/puppi/projects/$project_name/$action, logs their status and then runs the commands in /etc/puppi/projects/$project_name/report to provide reporting, in whatever, pluggable, way. You can also provide some options: -f : Force puppi commands execution also on CRITICAL errors -i : Interactively ask confirmation for every command -t : Test mode. Just show the commands that should be executed without doing anything -d <yes|full>: Debug mode. Show debugging info during execution -o "parameter=value parameter2=value2" : Set manual options to override defaults. The options must be in parameter=value syntax, separated by spaces and inside double quotes. Some usage examples: puppi check : Run host-wide checks. puppi check myapp : Run project "myapp" specific tests AND host-wide checks puppi log : Show system logs puppi todo : Show what has to be done manually on the system to complete the setup puppi info : Show general system infos (outputs all the topics available) puppi info network : Show network related info (outputs only the "network" topic) puppi init myapp : Make the first deploy of "myapp". Can be optional. puppi deploy myapp : Deploys myapp with the standard logic/parameters defined in Puppet puppi deploy myapp -f : Deploys myapp and doesn't stop in case of Critical errors puppi deploy myapp -i : Deploys myapp in interactive mode. Confirmation is asked for each step puppi deploy myapp -t : Test mode. Just show the commands that would be executed puppi deploy myapp -d full : Deploys myapp with full debugging output puppi deploy myapp -i -o "version=1.1 source_url=http://dev.example42.com/code/my_app/" : Deploys myapp in interactive mode and sets some custom options that override the standard Puppet params. Note that these parameters change according to the script you use (and the scripts must honour this override in order to make this option work). puppi rollback myapp : Rollbacks myapp to a previous archived state. User is asked to choose which deploy to override The set of commands needed for a specific kind of deploy is entirely managed with specific Puppet "basic defines". FILE PATHS (all of them are provided, and can be configured, in the puppi module): /usr/sbin/puppi - Where the puppi command is placed. Currently is a bash script. /etc/puppi/puppi.conf - Puppi main config file. Here various puppi wide paths are defined /etc/puppi/checks/ - $checksdir - Here can be placed all the host wide checks. If you use the Example42 monitor module and have "puppi" as $monitor_tool, this directory is automatically filled with Nagios plugins based checks. /etc/puppi/projects/ - $projectsdir - In this directory you can have one or more projects subdirs, with the commands to be run for deploy, rollback and check actions. They are completely built (and purged) by the Puppet module. /etc/puppi/scripts/ - $scriptsdir - The general-use scripts directory, these are used by the above commands and may require one or more arguments. /etc/puppi/logs/ - $logssdir - The general-use directory where are placed files containing the log paths to be used by puppi log /etc/puppi/info/ - $infodir - The directory where are placed files containing the commands used by puppi info /var/lib/puppi/archive/ - $archivedir - Where all data to rollback is placed. /var/lib/puppi/archive/ - $archivedir - Where all data to rollback is placed. /var/log/puppi/ - $logdir - Where logs and reports of the different commands are placed. /tmp/puppi/ - $workdir - Temporary, scratchable, directory where Puppi places temporary files. /tmp/puppi/$project/config - A runtime configuration file, where are dinamically placed variables usable by all the scripts invoked by puppi. This is necessary to mantain "state" information that changes on every puppi run (such as the deploy datetime, used for backups). USAGE OF THE PUPPI MODULE The puppi module provides few basic defines to manage puppi's setup elements and some example templates that use these defines to build deployment workflows. The basic defines are: puppi::project - Creates the main project structure. One or more different deployment projects can exist on a node. puppi::initialize - Creates a single command to be placed in the init sequence. It's not required for every project. puppi::deploy - Creates a single command to be placed in the deploy sequence. More than one is generally needed for each project. puppi::rollback - Creates a single command to be placed in the rollback sequence. More than one is generally needed for each project. puppi::check - Creates a single check (based on Nagios plugins) for a project or for the whole host (host wide checks are auto generated by Example42 monitor module) puppi::report - Creates a reporting command to be placed in the report sequence. puppi::log - Creates a log filename entry for a project or the whole hosts. puppi::info - Creates an info entry with the commands used to provide info on a topic The above init, deploy, rollback, check and report defines have generally a standard structure and similar arguments. Every one is reversable (enable => false) but you can wipe out the whole /etc/puppi directory to have it rebuilt from scratch. Here is an example for a deploy command: puppi::deploy { "Retrieve files": # The $name of the define is used in the file name command => "get_curl.sh", # The name of the general-use script to use argument => "file:///storage/file", # The argument(s) passed to the above script priority => "10", # Lower priority scripts are executed first user => "root", # As what user we run the script project => "my-web.app", # The name of the project to use } This define creates a file named /etc/puppi/projects/${project}/deploy/${priority}-${name} Its content is, simply: su - ${user} -c "export project=${project} && /etc/puppi/scripts/${command} ${arguments}" You can glue together, with the desired order according to the priority argument, different basic defines to create a complex project template and use this in you modules. For example, for a simple deployment of a WAR you can use, on the desired node, a define like: puppi::project::war { "myapp": # The name of the project source_url => "http://repository.example42.com/projects/myapp/latest/myapp.war", user => "myappuser", deploy_root => "/store/tomcat/myapp/webapps", report_email => "[email protected]", enable => "true", } Check the manifests/project/ dir for different examples of deploy templates. See there how you can influence the deploy sequence according to the usage of custom arguments. HOW TO CUSTOMIZE It should be clear that with puppi you have full flexibility in the definition of a deployment procedure, since the puppi command is basically a wrapper that executes arbitrary scripts with a given sequence, in pure KISS logic. The advantanges though, are various: - You have a common syntax to manage deploys and rollbacks on an host - In your Puppet manifests you can set in simple, coherent and still flexible and customizable defines all the elements you need for your application deployments. Think about it: with just a Puppet define you build the whole deploy logic - Reporting for each deploy/rollback is built-in and extensible - Automatic checks can be built in the deploy procedure - You have a common, growing, set of general-use scripts for typical actions - You have quick and useful command to see what's happening on the system (puppi check, log, info) - Future planned support for mcollective and a web front-end will make everything funnier There are different parts where you can customize the behaviour of puppi: - The set of general-use scripts in /etc/puppi/scripts/ ( this dir is filled with the content of puppi/files/scripts/ ) can/should be enhanced. These can be arbitrary scripts in whatever language. If you want to follow puppi's logic, though, consider that they should import the common and runtime configuration files and have an exit code logic similar to the one of Nagios plugins: 0 is OK, 1 is WARNING, 2 is CRITICAL. Note that by default a script that exits with WARNING doesn't block the deploy procedure, on the other hand, if a script exits with CRITICAL (exit 2) by default it blocks the procedure. Take a second, also, to explore the runtime config file created by the puppi command that contains variables that can be set and used by the scripts invoked by puppi. - The custom project defines that describe deploy templates. These are placed in puppi/manifests/project/ and can request all the arguments you want to feed your scripts with. Generally is a good idea to design a standard enough template that can be used for all the cases where the deployment procedure involves similar steps. Consider also that you can handle exceptions with variables (see the $loadbalancer_ip usage in puppi/manifests/project/maven.pp) DEPENDENCIES The Example42 puppi module aims to be independent and easily droppalo in your set of modules. In order to do something useful by default it need some packages that you probably already manage: - nagios plugins for the puppi check, - curl for some general scripts used in puppi deploy. Extra elements for check, info and log are automatic included with the relevant application if you use the Example42 modules. PROJECT STATUS Puppi is a work in progress. It has been originally designed to automate deployments in a specific environment and more project templates have to be written to manage different scenarios. It has evolved with some commands useful to quickly understand what's happening on the system and how it's configured. It has greatly broadened its applications and possibilities with the introduction of the mc-puppi mcollective command and the relevant plugin. All the puppi commands you can issue to obtain information, check status and manage applications deployments are now usable via Mcollective.
@host = localhost @port = 3000 @path = @url = {{host}}:{{port}}{{path}} # ------------------------------------------------------ # Post-Comments: One to Many Relationship # ------------------------------------------------------ # posts: [ # {id: "1", title: "a title", views: 100}, # ... # ] # # comments: [ # {id: "1", text: "...", postId: "1"}, # ... # ] # ### 1. Get all Posts GET http://{{url}}/posts ### 2. Get all Posts with their Comments (embeded) GET http://{{url}}/posts?_embed=comments ### 3. Get a Post GET http://{{url}}/posts/1 ### 4. Get a Post with its Comments (embeded) GET http://{{url}}/posts/1?_embed=comments ### 5. Get all Comments http://{{url}}/comments ### 6. Get Comments with the target Post (embeded) GET http://{{url}}/comments?_embed=post ### 7. Create a post with an exists Id POST http://{{url}}/posts Content-Type: application/json {"id":1, "title":"my new post", "views": 0} ### 8. Create a post without an Id POST http://{{url}}/posts Content-Type: application/json {"title":"my new post", "views": 0} ### 9. Pactch the newly added post PATCH http://{{url}}/posts/3 Content-Type: application/json {"views": 1} ### 10. Put the newly added post PUT http://{{url}}/posts/3 Content-Type: application/json {"title": "My New Post"} ### 11. Create a comment with invalid foreign key POST http://{{url}}/comments Content-Type: application/json {"id":3, "text":"comment on post 3", "postId":30} ### 12. Create a comment with a valid foreign key POST http://{{url}}/comments Content-Type: application/json {"text":"comment on post 3", "postId":3} ### 13. Update (PATCH) the comment to an invalid foreign key PATCH http://{{url}}/comments/3 Content-Type: application/json {"postId":"50"} ### 14. Update (PUT) the comment to an invalid foreign key PUT http://{{url}}/comments/3 Content-Type: application/json {"text":"Good Post!","postId":50} ### 15. Delete a post will remove the one to many relationship # _dependent make the related comments deleted # without it, the related comments' foreignkeys will be set to null DELETE http://{{url}}/posts/3?_dependent=comments ### 16. Confirm all comments on post 3 are all gone GET http://{{url}}/comments?postId=3 # ---------------------------------------------------------- # Contacts_Groups: Many to Many Relationship # ---------------------------------------------------------- # contacts: [ # {id: "1", name: "Tracy", mobile: "(555)1234-1256"}, # ... # ] # # groups: [ # {id: "1", name: "Collegue"}, # {id: "2", name: "Friend"}, # ... # ] # # contacts_groups: [ # {id: "1", contactId: "1", groupId: "1"}, # {id: "2", contactId: "1", groupId: "2"}, # ... # ] ### 1. Get all Contacts GET http://{{url}}/contacts ### 2. Get all Contacts with their Groups (embeded) GET http://{{url}}/contacts?_embed=groups ### 3. Get a Contact GET http://{{url}}/contacts/1 ### 4. Get a Contact with the Groups he belongs to (embeded) GET http://{{url}}/contacts/1?_embed=groups ### 5. Get all Groups GET http://{{url}}/groups ### 6. Get all Groups with their Contacts GET http://{{url}}/groups?_embed=contacts ### 7. Get a Group GET http://{{url}}/groups/1 ### 8. Get a Group with the Contacts in it (embeded) GET http://{{url}}/groups/1?_embed=contacts ### 9. Create a Contact # @name addContact POST http://{{url}}/contacts Content-Type: application/json {"name":"Smith", "mobile":"(666)1234-8976"} ### 10. Put the contact into groups of 1,3 @id = {{addContact.response.body.$.data.id}} PATCH http://{{url}}/contacts/{{id}} Content-Type: application/json {"groups": [1,3]} ### Confirm GET http://{{url}}/contacts/{{id}}?_embed=groups ### GET http://{{url}}/groups/1?_embed=contacts ### GET http://{{url}}/groups/3?_embed=contacts ### DELETE http://{{url}}/contacts/{{id}} ### DELETE ### POST http://{{url}}/contacts Content-Type: application/json { "name": "Jane Doe", "mobile": "11111111", "groups": [1,2,3] }
import json import pprint import queue import re import threading import time from sansio_lsp_client import ShowMessageRequest, WorkDoneProgressCreate, RegisterCapabilityRequest, \ ConfigurationRequest, WorkspaceFolders, WorkspaceFolder, ClientState, Shutdown, Client class IOThreadedServer: """ Gathers all messages received from server - to handle random-order-messages that are not a response to a request. """ def __init__(self, pipe_in, pipe_out, lsp_client: Client): self.lsp_client = lsp_client self.msgs = [] self._pout = pipe_out self._pin = pipe_in self._read_q = queue.Queue() self._send_q = queue.Queue() self.reader_thread = threading.Thread( target=self._read_loop, name="lsp-reader", daemon=True ) self.writer_thread = threading.Thread( target=self._send_loop, name="lsp-writer", daemon=True ) self.reader_thread.start() self.writer_thread.start() self.exception = None # threaded def _read_loop(self): try: while True: data = self._pout.read(1) if data == b"": break self._read_q.put(data) except Exception as ex: self.exception = ex self._send_q.put_nowait(None) # stop send loop # threaded def _send_loop(self): try: while True: chunk = self._send_q.get() if chunk is None: break self._pin.write(chunk) self._pin.flush() except Exception as ex: self.exception = ex def _queue_data_to_send(self): send_buf = self.lsp_client.send() if send_buf: self._send_q.put(send_buf) def _read_data_received(self): while not self._read_q.empty(): data = self._read_q.get() events = self.lsp_client.recv(data) for ev in events: self.msgs.append(ev) self._try_default_reply(ev) def _try_default_reply(self, msg): if isinstance( msg, ( ShowMessageRequest, WorkDoneProgressCreate, RegisterCapabilityRequest, ConfigurationRequest, ), ): msg.reply() elif isinstance(msg, WorkspaceFolders): msg.reply([WorkspaceFolder(uri=self.lsp_client.root_uri, name="Root")]) else: print(f"Can't autoreply: {type(msg)}") def wait_for_message_of_type(self, type_, timeout=5): end_time = time.monotonic() + timeout while time.monotonic() < end_time: self._queue_data_to_send() self._read_data_received() # raise thread's exception if have any if self.exception: raise self.exception for msg in self.msgs: if isinstance(msg, type_): self.msgs.remove(msg) return msg time.sleep(0.2) raise Exception( f"Didn't receive {type_} in time; have: " + pprint.pformat(self.msgs) ) def exit_cleanly(self): # Not necessarily error, gopls sends logging messages for example # if self.msgs: # print( # "* unprocessed messages: " + pprint.pformat(self.msgs) # ) assert self.lsp_client.state == ClientState.NORMAL self.lsp_client.shutdown() self.wait_for_message_of_type(Shutdown) self.lsp_client.exit() self._queue_data_to_send() self._read_data_received()
CREATE TABLE ClassRoom( Building varchar(50), RoomNumber INTEGER, Capacity INTEGER, PRIMARY KEY (Building, RoomNumber) ); CREATE TABLE TimeSlot( TimeSlotID varchar(50), Day varchar(50) check ( day in ('Monday', 'Tuesday', 'Wednesday', 'Thrusday', 'Friday', 'Saturday', 'Sunday' ) ), # StartTime time, # EndTime time, StartHour INTEGER(2) check ( StartHour >= 0 and StartHour < 24 ), StartMin INTEGER(2) check ( StartMin >= 0 and StartMin < 60 ), EndHour INTEGER(2) check ( EndHour >= 0 and EndHour < 24 ), EndMin INTEGER(2) check ( EndMin >= 0 and EndMin < 60 ), PRIMARY KEY (TimeSlotID, Day, StartHour, StartMin) ); CREATE TABLE Department( DepartmentName varchar(50), Building varchar(50), Budget INTEGER check ( Budget > 0 ), PRIMARY KEY (DepartmentName) ); CREATE TABLE Course( CourseId varchar(50), Title varchar(50), DepartmentName varchar(50), Credits INTEGER(2) check ( Credits > 0 ), PRIMARY KEY ( CourseId ), FOREIGN KEY (DepartmentName) references Department(DepartmentName) on delete set null ); CREATE TABLE Section( CourseId varchar(50), SectionId varchar(50), TimeSlotID varchar(50), Semester varchar(50) check ( Semester in ('Fall', 'Spring', 'Winter', 'Summer') ), Year INTEGER(4) check ( Year > 2020 ), Building varchar(50), RoomNumber INTEGER, PRIMARY KEY (CourseId, SectionId, Semester, Year), FOREIGN KEY (CourseId) references Course(CourseId) on delete CASCADE, FOREIGN KEY (Building, RoomNumber) references ClassRoom(Building, RoomNumber) on delete set null ); CREATE TABLE Student( ID varchar(50) not null , Name varchar(50) not null, DepartmentName varchar(50), TotalCredit INTEGER(2) check ( TotalCredit > 0 ), PRIMARY KEY (ID), FOREIGN KEY (DepartmentName) references Department(DepartmentName) on delete set null ); CREATE TABLE Instructor( ID varchar(50) not null , Name varchar(50) not null , DepartmentName varchar(50), Salary FLOAT(10) check ( Salary > 0.0 ), PRIMARY KEY (ID), FOREIGN KEY (DepartmentName) references Department(DepartmentName) on delete set null ); CREATE TABLE Takes( ID varchar(50) not null, CourseId varchar(50), SectionId varchar(50), Semester varchar(50), Year INTEGER(4), Grade varchar(1) check ( Grade in ('A', 'B', 'C', 'D', 'F') ), PRIMARY KEY (ID, CourseId, SectionId, Semester,Year), FOREIGN KEY (CourseId, SectionId, Semester, Year) references Section(CourseId, SectionId, Semester, Year) on delete cascade , FOREIGN KEY (ID) references Student(ID) ); CREATE TABLE Teaches( ID varchar(50) not null, CourseId varchar(50), SectionId varchar(50), Semester varchar(50), Year INTEGER(4), PRIMARY KEY (ID, CourseId, SectionId, Semester, Year), FOREIGN KEY (CourseId, SectionId, Semester, Year) references Section(CourseId, SectionId, Semester, Year) on delete cascade , FOREIGN KEY (ID) references Instructor(ID) on delete cascade ); CREATE TABLE Advisor( StudentID varchar(50) not null , InstructorID varchar(50) , PRIMARY KEY (StudentID), FOREIGN KEY (StudentID) references Student(ID) on delete cascade , FOREIGN KEY (InstructorID) references Instructor(ID) on delete set null ); CREATE TABLE Prereq( CourseId varchar(50), PrereqId varchar(50), PRIMARY KEY (CourseId, PrereqId), FOREIGN KEY (CourseId) references Course(CourseId) on delete cascade , FOREIGN KEY (PrereqId) references Course(CourseId) ); # Insertion in ClassRoom Table INSERT INTO ClassRoom(Building, RoomNumber, Capacity) VALUES (1,071, 20); INSERT INTO ClassRoom(Building, RoomNumber, Capacity) VALUES (2,060, 20); INSERT INTO ClassRoom(Building, RoomNumber, Capacity) VALUES (1,074, 20); INSERT INTO ClassRoom(Building, RoomNumber, Capacity) VALUES (2,076, 20); # Insertion in TimeSlot Table INSERT INTO TimeSlot(TimeSlotID, Day, StartHour, StartMin, EndHour, EndMin) VALUES (11,'Monday',13,00,14,00); INSERT INTO TimeSlot(TimeSlotID, Day, StartHour, StartMin, EndHour, EndMin) VALUES (11,'Tuesday',09,00,10,00); INSERT INTO TimeSlot(TimeSlotID, Day, StartHour, StartMin, EndHour, EndMin) VALUES (11,'Thrusday',15,30,17,00); INSERT INTO TimeSlot(TimeSlotID, Day, StartHour, StartMin, EndHour, EndMin) VALUES (11,'Saturday',09,30,16,30); # Insertion in Department INSERT INTO Department(DepartmentName, Building, Budget) VALUES ('Computer Science', 1, 2000); INSERT INTO Department(DepartmentName, Building, Budget) VALUES ('Electronics', 2, 3000); INSERT INTO Department(DepartmentName, Building, Budget) VALUES ('Information Technology', 3, 4000); INSERT INTO Department(DepartmentName, Building, Budget) VALUES ('Mechanical', 4, 6000); # Insertion in Course INSERT INTO Course(CourseId, Title, DepartmentName, Credits) VALUES (91, 'DBMS', 'Computer Science', 6); INSERT INTO Course(CourseId, Title, DepartmentName, Credits) VALUES (92, 'DE', 'Electronics', 4); INSERT INTO Course(CourseId, Title, DepartmentName, Credits) VALUES (93, 'MF&ORM', 'Information Technology', 5); INSERT INTO Course(CourseId, Title, DepartmentName, Credits) VALUES (94, 'BMCE', 'Mechanical', 8); # Insertion in Section INSERT INTO Section(courseid, sectionid, timeslotid, semester, year, building, roomnumber) VALUES (91,81,11,'Fall',2021,1,071); INSERT INTO Section(courseid, sectionid, timeslotid, semester, year, building, roomnumber) VALUES (92,82,11,'Summer',2021,2,060); INSERT INTO Section(courseid, sectionid, timeslotid, semester, year, building, roomnumber) VALUES (93,83,11,'Winter',2021,1,074); INSERT INTO Section(courseid, sectionid, timeslotid, semester, year, building, roomnumber) VALUES (94,84,11,'Spring',2021,2,076); # Insertion in Student INSERT INTO Student(id, name, departmentname, totalcredit) VALUES (51,'Chirag Sardana','Computer Science',4); INSERT INTO Student(id, name, departmentname, totalcredit) VALUES (52,'Ayush Singh','Electronics',5); INSERT INTO Student(id, name, departmentname, totalcredit) VALUES (53,'Deepak','Mechanical',7); INSERT INTO Student(id, name, departmentname, totalcredit) VALUES (54,'Deepak Jindal','Information Technology',2); # Insertion in Instructor INSERT INTO Instructor(id, name, departmentname, salary) VALUES (41,'Sumit Kumar','Computer Science',100100); INSERT INTO Instructor(id, name, departmentname, salary) VALUES (42,'Kanika Gupta','Mechanical',420199); INSERT INTO Instructor(id, name, departmentname, salary) VALUES (43,'Richa Chhabra','Information Technology',300099); INSERT INTO Instructor(id, name, departmentname, salary) VALUES (44,'Mehak Khurana','Computer Science',200111); # Insertion in Takes INSERT INTO Takes(id, courseid, sectionid, semester, year, grade) VALUES (51,91,81,'Fall',2021,'A'); INSERT INTO Takes(id, courseid, sectionid, semester, year, grade) VALUES (52,92,82,'Summer',2021,'B'); INSERT INTO Takes(id, courseid, sectionid, semester, year, grade) VALUES (53,93,83,'Winter',2021,'B'); INSERT INTO Takes(id, courseid, sectionid, semester, year, grade) VALUES (54,91,81,'Fall',2021,'A'); # Insertion in Teaches INSERT INTO Teaches(id, courseid, sectionid, semester, year) VALUES (41,91,81,'Fall',2021); INSERT INTO Teaches(id, courseid, sectionid, semester, year) VALUES (42,92,82,'Summer',2021); INSERT INTO Teaches(id, courseid, sectionid, semester, year) VALUES (43,93,83,'Winter',2021); INSERT INTO Teaches(id, courseid, sectionid, semester, year) VALUES (44,94,84,'Spring',2021); # Insertion in Advisor INSERT INTO Advisor(studentid, instructorid) VALUES (51,41); INSERT INTO Advisor(studentid, instructorid) VALUES (52,42); INSERT INTO Advisor(studentid, instructorid) VALUES (53,43); INSERT INTO Advisor(studentid, instructorid) VALUES (54,44); # Insertion in Prereq INSERT INTO Prereq(CourseId, PrereqId) VALUES (91,92); INSERT INTO Prereq(CourseId, PrereqId) VALUES (92,94); INSERT INTO Prereq(CourseId, PrereqId) VALUES (94,93); INSERT INTO Prereq(CourseId, PrereqId) VALUES (91,94); # Select * From ClassRoom Select * From ClassRoom # Select * From Time Slot Select * From TimeSlot # Select * From Department Select * From Department # Select * From Course Select * From Course # Select * From Section Select * From Section # Select * From Student Select * From Student # Select * From Instructor Select * From Instructor # Select * From Takes Select * From Takes # Select * From Teaches Select * From Teaches # Select * From Advisor Select * From Advisor # Select * From Prereq Select * From Prereq # DESC ClassRoom DESC ClassRoom; # DESC TimeSlot DESC TimeSlot; # DESC Department DESC Department; # DESC Course DESC Course; # DESC Section DESC Section; # DESC Student DESC Student; # DESC Instructor DESC Instructor; # DESC Takes DESC Takes; # DESC Teaches DESC Teaches; # DESC Advisor DESC Advisor; # DESC Prereq DESC Prereq; # Alter Table due to given Question's Condition ALTER TABLE Section MODIFY Year INTEGER(4) check ( Year > 2000 ); # Find the name and department of each instructor Select Instructor.Name , Instructor.DepartmentName FROM Instructor; # Find the department names in the University SELECT Department.DepartmentName FROM Department; # Display the ID, name, department name and salary of instructors after giving a # 10% raise to each instructor SELECT Instructor.ID, Instructor.Name, Instructor.DepartmentName, (Instructor.Salary + Instructor.Salary * 0.1 ) AS Salary From Instructor; # Retrieve the names of all instructors, along with their department names and # department building name. SELECT Instructor.Name, Instructor.DepartmentName, Department.Building FROM Instructor, Department WHERE Instructor.DepartmentName = Department.DepartmentName; # Retrieve the name and corresponding course id of instructors who have taught some course SELECT Instructor.Name, Teaches.CourseId FROM Instructor, Teaches WHERE Instructor.ID = Teaches.ID; # Find instructor names and course identifiers for instructors in the Computer Science # department SELECT Instructor.Name, Teaches.CourseId FROM Instructor, Teaches WHERE Instructor.ID = Teaches.ID AND Instructor.DepartmentName = 'Computer Science'; # Find the names of all instructors whose salary is greater than at least one instructor # in the Computer Science department. SELECT Instructor.Name FROM Instructor WHERE (Instructor.Salary > ANY (SELECT Instructor.Salary FROM Instructor WHERE Instructor.DepartmentName = 'Computer Science')); # ANY is used to select all records of a SELECT STATEMENT. It compares a value # to every value in a list or results from a query and if one condition is Satisfy # it returns true. # Find the names of all departments whose building name includes the substring ‘Watson’. INSERT INTO Department(DepartmentName, Building, Budget) VALUES ('Applied Science', 'Great Watson',2500); INSERT INTO Department(DepartmentName, Building, Budget) VALUES ('Management', 'IBM Watson',2900); SELECT Department.DepartmentName FROM Department WHERE Department.Building LIKE '%Watson%'; # List all instructors in Computer Science department alphabetically SELECT Instructor.Name FROM Instructor WHERE Instructor.DepartmentName = 'Computer Science' ORDER BY Instructor.Name ASC ; # ALTER TABLE Section MODIFY Year INTEGER(4) check ( Year >= 2000 ); # 'section_chk_2 # ALTER TABLE Section CHECK CONSTRAINT section_chk_2; ALTER TABLE Section DROP CHECK section_chk_2; ALTER TABLE Section MODIFY Year INTEGER(4) check ( Year >= 2000 ); # Find the set of all courses taught in the Fall 2009 semester INSERT INTO Section(courseid, sectionid, timeslotid, semester, year, building, roomnumber) VALUES (94,84,11,'Fall',2009,2,076); INSERT INTO Teaches(ID, CourseId, SectionId, Semester, Year) VALUES (43,94,84,'Fall',2009); SELECT Teaches.CourseId, Course.Title FROM Teaches, Course WHERE Teaches.CourseId = Course.CourseId AND Teaches.Year = 2009 AND Teaches.Semester = 'Fall'; # Find the set of all courses taught either in Fall 2009 or in Spring 2010, or both INSERT INTO Section(courseid, sectionid, timeslotid, semester, year, building, roomnumber) VALUES (92,82,11,'Spring',2010,2,076); INSERT INTO Teaches(ID, CourseId, SectionId, Semester, Year) VALUES (42,92,82,'Spring',2010); SELECT Teaches.CourseId, Course.Title, Teaches.Semester, Teaches.Year FROM Teaches, Course WHERE Teaches.CourseId = Course.CourseId AND ( (Teaches.Year = 2009 AND Teaches.Semester = 'Fall') OR (Teaches.Year = 2010 AND Teaches.Semester = 'Spring')); # Find the set of all courses taught in the Fall 2009 as well as in Spring 2010 INSERT INTO Section(courseid, sectionid, timeslotid, semester, year, building, roomnumber) VALUES (92,82,11,'Fall',2010,2,076); INSERT INTO Teaches(ID, CourseId, SectionId, Semester, Year) VALUES (42,92,82,'Fall',2010); # If Separate View Created for both Select Queries then it is possible ? # View1.CourseId = View2.CourseId (SELECT Teaches.CourseId, Course.Title FROM Teaches, Course WHERE Teaches.CourseId = Course.CourseId AND (Teaches.Year = 2010 AND Teaches.Semester = 'Spring') AND Teaches.CourseId IN (SELECT Teaches.CourseId FROM Teaches WHERE (Teaches.Year = 2009 AND Teaches.Semester = 'Fall') ); CREATE VIEW view1 AS SELECT Teaches.CourseId, Course.Title FROM Teaches, Course WHERE Teaches.CourseId = Course.CourseId AND (Teaches.Year = 2010 AND Teaches.Semester = 'Spring'); CREATE VIEW view2 AS SELECT Teaches.CourseId, Course.Title FROM Teaches, Course WHERE Teaches.CourseId = Course.CourseId AND (Teaches.Year = 2009 AND Teaches.Semester = 'Fall'); SELECT * FROM view1; SELECT * FROM view2; SELECT view1.CourseId , view2.CourseId FROM view1, view2 WHERE view1.CourseId = view2.CourseId; SELECT view1.CourseId FROM view1 INNER JOIN view2 ON view1.CourseId = view2.CourseId; SELECT DISTINCT Teaches.CourseId, Course.Title FROM Teaches, Course INNER JOIN Teaches T on Course.CourseId = T.CourseId # Find all courses taught in the Fall 2009 semester but not in the Spring 2010 semester # SELECT view2.CourseId FROM view2 WHERE view2.CourseId NOT IN view1.CourseId; # 3rd March 2021 # Subquery SELECT * FROM Teaches; SELECT * FROM Course; # Subquery with SELECT statement SELECT * FROM Teaches WHERE CourseId IN (SELECT CourseId FROM Course WHERE Course.CourseId = 91); DESC Teaches; # Subquery with INSERT statement CREATE TABLE Temp(c1 varchar(50), CourseId varchar(50), SectionId varchar(50), Semester varchar(50), Year int); INSERT INTO Temp (SELECT * FROM Teaches WHERE CourseId IN (SELECT CourseId FROM Course WHERE Course.CourseId = 91)); SELECT * FROM Temp; show create table Section;
/* * Copyright (c) 2023. caoccao.com Sam Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.caoccao.javet.interfaces; import com.caoccao.javet.exceptions.JavetException; /** * The interface Javet uni-function. * * @param <T> the type parameter * @param <R> the type parameter * @param <E> the type parameter * @since 2.2.0 */ @FunctionalInterface public interface IJavetUniFunction<T, R, E extends Throwable> { /** * Apply. * * @param value the value * @return the result * @throws JavetException the javet exception * @throws E the custom exception * @since 2.2.0 */ R apply(T value) throws JavetException, E; }
package com.trainings.dto; import org.apache.commons.lang.builder.ToStringBuilder; import org.hibernate.validator.constraints.NotEmpty; import java.util.List; public class PersonDTO { private Long id; @NotEmpty private String firstName; @NotEmpty private String lastName; private String address; private List<String> phones; public PersonDTO() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public List<String> getPhones() { return phones; } public void setPhones(List<String> phones) { this.phones = phones; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
### [两两交换链表中的节点](https://leetcode.cn/problems/swap-nodes-in-pairs/) #### 描述 给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。 #### 示例 ![](https://assets.leetcode.com/uploads/2020/10/03/swap_ex1.jpg) ```text 输入:head = [1,2,3,4] 输出:[2,1,4,3] ``` ```text 输入:head = [] 输出:[] ``` #### 解法 分隔链表 -> 分别翻转前后两个链表 -> 合并链表
""" URL configuration for emission_sentri project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from django.urls import include # Configuring Swagger UI for documenting API from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi schema_view = get_schema_view(openapi.Info(title="EmissionSentri API", default_version="v1", description="Below is the structure for accessing EmssionSentri Emissions Model's Data", terms_of_service="https;//emssionsentri.com/terms", contact=openapi.Contact(email="[email protected]"), license=openapi.License(name="Refer EmissionSentri License"))) urlpatterns = [ path('admin/', admin.site.urls), path("emissionsentri_api/", include("emissionsapp.urls")), path('swagger<str:format>', schema_view.without_ui(cache_timeout=0), name='schema-json'), path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ]
const express = require('express'); const { Op } = require('sequelize'); const {Post, Image, User, Comment} = require('../models'); const router = express.Router(); router.get('/', async (req, res, next) => { // GET /posts try { const where = {}; if (parseInt(req.query.lastId,10)) { // 초기 로딩이 아닐 때 where.id = { [Op.lt]: parseInt(req.query.lastId, 10)} // id가 lastId보다 작은 것 불러옴 } const posts = await Post.findAll({ where, limit: 10, // 10개씩 가져오기 order: [['createdAt', 'DESC'], [Comment, 'createdAt', 'DESC'] ], include: [{ model: User, // 게시글 작성자 attributes: ['id', 'nickname'] }, { model: Image }, { model: Comment, include: [{ model: User, // 댓글 작성자 attributes: ['id', 'nickname'] }] }, { model: User, as: 'Likers', attributes: ['id'] }, { model: Post, as: 'Retweet', include: [{ model: User, attributes: ['id', 'nickname'] }, { model: User, as: 'Likers', attributes: ['id'] }, { model: Image }] }] }); res.status(200).json(posts); } catch (error) { console.log(error); next(error); } }); router.get('/related', async (req, res, next) => { // GET /related try { const followings = await User.findAll({ attributes: ['id'], include: [{ model: User, as: 'Followers', where: { id: req.user.id } }] }); const where = { UserId: { [Op.in]: followings.map((v) => v.id) } }; if (parseInt(req.query.lastId,10)) { // 초기 로딩이 아닐 때 where.id = { [Op.lt]: parseInt(req.query.lastId, 10)} // id가 lastId보다 작은 것 불러옴 } const posts = await Post.findAll({ where, limit: 10, // 10개씩 가져오기 order: [ ['createdAt', 'DESC'], [Comment, 'createdAt', 'DESC'] ], include: [{ model: User, // 게시글 작성자 attributes: ['id', 'nickname'] }, { model: Image }, { model: Comment, include: [{ model: User, // 댓글 작성자 attributes: ['id', 'nickname'] }] }, { model: User, // 좋아요 누른 사람 as: 'Likers', attributes: ['id'] }, { model: Post, as: 'Retweet', include: [{ model: User, attributes: ['id', 'nickname'] }, { model: Image }] }] }); res.status(200).json(posts); } catch (error) { console.log(error); next(error); } }); router.get('/unrelated', async (req, res, next) => { // GET /unrelated try { const followings = await User.findAll({ attributes: ['id'], include: [{ model: User, as: 'Followers', where: { id: req.user.id } }] }); const where = { UserId: { [Op.notIn]: followings.map((v) => v.id).concat(req.user.id) } }; if (parseInt(req.query.lastId,10)) { // 초기 로딩이 아닐 때 where.id = { [Op.lt]: parseInt(req.query.lastId, 10)} // id가 lastId보다 작은 것 불러옴 } const posts = await Post.findAll({ where, limit: 10, // 10개씩 가져오기 order: [['createdAt', 'DESC'], [Comment, 'createdAt', 'DESC'] ], include: [{ model: User, // 게시글 작성자 attributes: ['id', 'nickname'] }, { model: Image }, { model: Comment, include: [{ model: User, // 댓글 작성자 attributes: ['id', 'nickname'] }] }, { model: User, // 좋아요 누른 사람 as: 'Likers', attributes: ['id'] }, { model: Post, as: 'Retweet', include: [{ model: User, attributes: ['id', 'nickname'] }, { model: Image }] }] }); res.status(200).json(posts); } catch (error) { console.log(error); next(error); } }); module.exports = router;
import { ApiProperty } from '@nestjs/swagger' import { IsNumber, IsOptional, IsString } from 'class-validator' export class UpdateCoachWorkoutDto { @ApiProperty() @IsString() @IsOptional() readonly name: string @ApiProperty() @IsNumber() @IsOptional() readonly sets: number @ApiProperty() @IsNumber() @IsOptional() readonly reps: number @ApiProperty() @IsNumber() @IsOptional() readonly weight: number @ApiProperty() @IsOptional() readonly date: Date }
import { useState, useEffect } from "react" import { useDispatch, useSelector } from "react-redux" import { getPlayers, getPlayer, updatePlayer } from "../features/players/playerSlice" import { editStats, reset } from "../features/fixtures/fixtureSlice" import { addPointsToPicks } from "../features/lives/livesSlice" import { toast } from "react-toastify" function EditStats({singleFixture, handleShow, handleClose}) { const { players, onePlayer } = useSelector((state) => state.players) const { isError, isSuccess, message } = useSelector((state) => state.fixtures) const dispatch = useDispatch() const [showSwap, setShowSwap] = useState(false) const [data, setData ] = useState({ identifier: '', homeAway: '', player: '', value: '' }) const { identifier, homeAway, player, value } = data useEffect(() => { if(isError) { toast.error(message) } dispatch(getPlayer(player)) dispatch(getPlayers()) return () => { dispatch(reset()) } }, [dispatch, isError, message, player]) const onSubmit = (e) => { e.preventDefault() const stats = { identifier, homeAway, player, value } const playerStat = {} playerStat[identifier] = +value dispatch(updatePlayer({id: player, playerStat, matchday:singleFixture.matchday})) dispatch(editStats({id: singleFixture._id, stats})) /* setData((prevState) => ({ ...prevState, identifier: '', homeAway: '', player: '', value: '' })) */ setShowSwap(true) handleShow() } const closeAddPoints = () => { dispatch(addPointsToPicks({mid: singleFixture.matchday, pid: player})) setShowSwap(false) handleClose() } const onChange = (e) => { setData((prevState) => ({ ...prevState, [e.target.name]: e.target.value })) } return ( <> <section className='form'> <form onSubmit={onSubmit}> <div className="form-group"> <select name="identifier" id="identifier" onChange={onChange}> <option value="">Select Stat</option> {singleFixture?.stats?.map(x => x.identifier)?.map((stat, idx) => ( <option key={idx} value={stat}>{stat}</option> ))} </select> </div> <div className="form-group"> <select name="homeAway" id="homeAway" onChange={onChange}> <option value="">Select Home or Away</option> <option value='home'>Home</option> <option value='away'>Away</option> </select> </div> <div className="form-group"> <select name="player" id="player" onChange={onChange}> <option value="">Select Player</option> {homeAway === 'home' && players .filter(x => x.playerTeam.toString() === singleFixture?.teamHome) .map(player => ( <option key={player._id} value={player._id}> {player.appName} </option>))} {homeAway === 'away' && players .filter(x => x.playerTeam.toString() === singleFixture?.teamAway) .map(player => ( <option key={player._id} value={player._id}> {player.appName} </option>))} </select> </div> <div className="form-group"> <select name="value" id="value" onChange={onChange}> <option value="">Select Value</option> {[-1,1].map((val, idx) => ( <option key={idx} value={+val}>{val}</option> ))} </select> </div> <div className="form-group"> <button className="btn btn-block">Submit</button> </div> </form> </section> {showSwap && <div className="playerpop"> <div className="infobuttons"> <button onClick={() => closeAddPoints()} className='btn-info btn-info-block btn-warn'> Add Player Points </button> </div> </div>} </> ) } export default EditStats
import SwiftUI // base: https://github.com/quangfnv-1159/AppStoreAnimation struct TodayDetailView: View { @Binding var showDetail: Bool @State var animateView = false @State var animateContent = false let caption: String let title: String let backgroundImageName: String let appImageNames: [String] let namespace: Namespace.ID var body: some View { ScrollView(.vertical, showsIndicators: false) { VStack(spacing: 0) { VStack(spacing: 0) { VStack(alignment: .leading) { Text(caption) .foregroundColor(.gray) .font(.headline) Text(title) .foregroundColor(.white) .font(.title) .fontWeight(.bold) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) } .frame(height: 300) .frame(maxWidth: .infinity) .padding(.horizontal, 16) .padding(.top, 59) .background(Image(backgroundImageName).resizable()) HStack(spacing: 40) { ForEach(Array(appImageNames.enumerated()), id: \.offset) { (_, name) in Image(name) .resizable() .frame(width: 66, height: 66) .cornerRadius(16) .shadow(radius: 1) } } .frame(height: 100) .frame(maxWidth: .infinity) .background(Color(.secondarySystemGroupedBackground)) } .matchedGeometryEffect(id: "night", in: namespace, isSource: true) Text(dummyText) .multilineTextAlignment(.leading) .lineSpacing(10) .padding(16) .background(Color(.systemBackground)) .opacity(animateContent ? 1 : 0) .scaleEffect(animateView ? 1 : 0, anchor: .top) } } .overlay(alignment: .topTrailing, content: { Button { withAnimation(.interactiveSpring(response: 0.6, dampingFraction: 0.7, blendDuration: 0.7)) { animateView = false animateContent = false } Task { try? await Task.sleep(nanoseconds: UInt64(0.1 * 1_000_000_000)) withAnimation(.interactiveSpring(response: 0.6, dampingFraction: 0.7, blendDuration: 0.7)) { showDetail = false } } } label: { Image(systemName: "xmark.circle.fill") .font(.title) .foregroundColor(.white) } .padding(.horizontal, 16) .padding(.top, 59) }) .onAppear { withAnimation(.interactiveSpring(response: 0.6, dampingFraction: 0.7, blendDuration: 0.7)) { animateView = true } withAnimation(.interactiveSpring(response: 0.6, dampingFraction: 0.7, blendDuration: 0.7).delay(0.1)) { animateContent = true } } .transition(.identity) } } let dummyText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Dui id ornare arcu odio ut sem nulla pharetra diam. Risus viverra adipiscing at in. Augue lacus viverra vitae congue eu consequat ac felis donec. Volutpat sed cras ornare arcu dui. Vitae nunc sed velit dignissim sodales ut eu sem integer. Faucibus in ornare quam viverra orci. Dictumst vestibulum rhoncus est pellentesque elit ullamcorper dignissim. Nulla facilisi nullam vehi Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Dui id ornare arcu odio ut sem nulla pharetra diam. Risus viverra adipiscing at in. Augue lacus viverra vitae congue eu consequat ac felis donec. Volutpat sed cras ornare arcu dui. Vitae nunc sed velit dignissim sodales ut eu sem integer. Faucibus in ornare quam viverra orci. Dictumst vestibulum rhoncus est pellentesque elit ullamcorper dignissim. Nulla facilisi nullam vehi Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Dui id ornare arcu odio ut sem nulla pharetra diam. Risus viverra adipiscing at in. Augue lacus viverra vitae congue eu consequat ac felis donec. Volutpat sed cras ornare arcu dui. Vitae nunc sed velit dignissim sodales ut eu sem integer. Faucibus in ornare quam viverra orci. Dictumst vestibulum rhoncus est pellentesque elit ullamcorper dignissim. Nulla facilisi nullam vehi"
import { NavLink } from 'react-router-dom'; import { DeleteBtn } from 'components/DeleteBtn/DeleteBtn'; import { NavLinkSkew } from 'components/NavLinkSkew/NavLinkSkew'; import { useMediaQuery } from 'hooks/useMedia'; import { DataWrapper, DescrWrapper, ImageWrapper, RecipeBlockWrapper, SubTitle, Time, TimeWrapper, TitleWrapper, } from './RecipeBlock.styled'; export const RecipeBlock = ({ location, id, text, title, img, time }) => { const isRowBased = useMediaQuery('(min-width: 768px)'); return ( <RecipeBlockWrapper location={location}> {!isRowBased && location === 'favorite' ? ( <NavLink to={`/recipe/${id}`}> <ImageWrapper location={location}> <img src={img} alt={title} /> </ImageWrapper> </NavLink> ) : ( <ImageWrapper location={location}> <img src={img} alt={title} /> </ImageWrapper> )} <DataWrapper location={location}> <TitleWrapper> <SubTitle> <h3>{title}</h3> </SubTitle> {isRowBased && location === 'favorite' && ( <DeleteBtn location={location} id={id} /> )} {location === 'recipes' && <DeleteBtn location={location} id={id} />} </TitleWrapper> <DescrWrapper>{text}</DescrWrapper> <TimeWrapper> <Time>{time}</Time> {!isRowBased && location === 'recipes' && ( <NavLinkSkew navigate={`/recipe/${id}`} location={location} text="See recipe" styled="olive" /> )} {!isRowBased && location === 'favorite' && ( <DeleteBtn location={location} id={id} /> )} {isRowBased && ( <NavLinkSkew navigate={`/recipe/${id}`} location={location} text="See recipe" styled={location === 'favorite' ? 'black' : 'olive'} /> )} </TimeWrapper> </DataWrapper> </RecipeBlockWrapper> ); };
#### CV for PCA ROBUST COX #### library(coxrobust) library(tidyverse) library(survival) liv <- read_csv("C:/Users/kange/Desktop/Thesis/data/liver_clinic.csv") #keep barcode for merging only, not in model liv <- liv %>% select(-c(1)) cn <- read_csv("C:/Users/kange/Desktop/Uoft/Uoft Courses/practicum/week13/cn_pc_nolast.csv") dm <- read_csv("C:/Users/kange/Desktop/Uoft/Uoft Courses/practicum/week13/dm_genomic_pcs.csv") ge <- read_csv("C:/Users/kange/Desktop/Uoft/Uoft Courses/practicum/week13/ge_pc_nolast.csv") allpcs <- cn %>% inner_join(dm, by="barcode") %>% inner_join(ge, by="barcode") liv_final <- liv %>% inner_join(allpcs, by="barcode") liv_final <- liv_final %>% mutate(stage_recode = ifelse(stage == "Stage I" | stage == "Stage II", "Early Stage", "Not Early Stage")) repcrossval <- function(repeats, folds, weight){ cv_conc <- rep(0, repeats) for (k in 1:repeats){ splits <- split(liv_final, sample(1:folds, nrow(liv_final), replace = T)) c <- rep(0, folds) for (i in 1:folds){ d_minusi <- bind_rows(splits[-c(i)]) # dataset without ith fold fit <- coxr(Surv(OS.time, OS) ~age+pc1_cn+pc5_cn+pc1_dm+pc5_dm+pc4_ge+stage_recode, data = d_minusi, f.weight = weight) # fit the "training model" # predict new data's HR/risk using training model somedf <- splits[[i]] %>% mutate(stage_recodeNotEarly=ifelse(stage_recode=="Not Early Stage", 1, 0)) somedf <- somedf %>% select(c(age, pc1_cn, pc5_cn, pc1_dm, pc5_dm, pc4_ge, stage_recodeNotEarly)) preds <- data.frame(preds = exp(as.matrix(somedf) %*% fit$coefficients)) # bind preds to testing data test <- splits[[i]] test_preds <- cbind(test, preds) # useful info surv_time <- test$OS.time censor_status <- test$OS risk <- test_preds$preds # call concordance pairs <- data.frame(t(combn(c(1:nrow(test)), 2))) colnames(pairs) <- c("obs1", "obs2") obs1 <- pairs$obs1 obs2 <- pairs$obs2 time1 <- surv_time[obs1] time2 <- surv_time[obs2] status1 <- censor_status[obs1] status2 <- censor_status[obs2] risk1 <- risk[obs1] risk2 <- risk[obs2] good_df <- data.frame(cbind(obs1, obs2, time1, time2, status1, status2, risk1, risk2)) # good_df contains pairs that can be compared good_df <- good_df %>% filter(!(status1==0 & status2==0)) %>% # not both censored filter(!(time1<=time2 & status1==0 & status2==1)) %>% # time1<time2, time1 censored, time2 not filter(!(time1>=time2 & status2==0 & status1==1)) %>% # time2<time1, time2 censored, time1not rowid_to_column() # tied predictors - just see if any duplications in dataframe, all.vars are the variables in the model # duplicated(liv_final[, all.vars(fit$call[[2]])[-c(1:2)]]) # tied observed event times (a_y) #tied_obs_ind <- good_df %>% filter(time1==time2) %>% select(rowid) #ay <- nrow(tied_obs) # tied predictor and event time # conc vs discordant conc_disc <- good_df %>% filter(!(time1==time2)) %>% mutate(conc = case_when( (time1 < time2 & risk1 > risk2) ~ 1, (time2 < time1 & risk2 > risk1) ~ 1, TRUE ~ 0 )) concordance <- mean(conc_disc$conc) c[i] <- concordance } cross_val_score <- mean(c) cv_conc[k] <- cross_val_score } mean(cv_conc) } # deafult is quadratic
--- title: Java基础 category: - Java order: 10 tag: - Java基础 --- ## 基础 ### java的移位运算符 一共有三种 |位移符号|作用| |----|----| | 左移(<<) | 左移运算符,向左移若干位,高位丢弃,低位补零。x << 1,相当于 x 乘以 2(不溢出的情况下)。 | | 带符号右移(>>) |带符号右移,向右移若干位,高位补符号位,低位丢弃。正数高位补 0,负数高位补 1。x >> 1,相当于 x 除以 2。| | 无符号右移(>>>) |无符号右移,忽略符号位,空位都以 0 补齐。 | > Java 只支持 int 和 long 的位移,浮点型数据不支持位移,其他的例如 short、byte、char 等类型进行位移前,也是先将它的类型转成 int 型再进行位移。 位移示例: ```java (6 << 1 = 12) 0110 << 1 = 1100 = 12 (-6 << 1 = -12) 11111111111111111111111111111010 << 1 = 11111111111111111111111111110100 (6 >> 1 = 3) 0110 >> 1 = 0011 = 3 (-6 >> 1 = -3) 11111111111111111111111111111010 >> 1 = 11111111111111111111111111111101(-3) (6 >>> 1 = 3) 0110 >>> 1 = 0011 = 3 (-6 >>> 1 = 2147483645) 11111111111111111111111111111010 >>> 1 = 01111111111111111111111111111101(2147483645) ``` 位移总结: > << >> 是有符号位移,所以最高位是啥还是啥,位移完正数还是正数,负数还是负数,>>> 是无符号位移,最高位补0,如果是正数就是正常的位移,如果是负数,位移完变成了正数,注意没有 <<<。 ### 包装类型的缓冲机制 Byte、Short、Integer、Long 这 4 种包装类默认创建了数值 [-128,127] 的相应类型的缓存数据 Character 创建了数值在 [0,127] 范围的缓存数据 Boolean 直接返回 True or False > 注意,Float、Double 并没有缓存机制。 > 注意 缓存机制可能导致 == 判断两个值不相等,所以包装类型比较还是用 equals 吧 ### 自动装箱和拆箱 其实代码编译后自动调用了 valueOf() 方法进行装箱,调用 xxValue() 方法进行拆箱。 ### 浮点数精度丢失问题 计算机存储数据都是二进制的,而计算机位数是有限的,如果十进制转二进制发生循环就无法精准表达,例如 0.2 在转成二进制存储的时候,就会发生循环,无法使用二进制精准表达,就会出现精度丢失的问题。 > 建议使用 BigDecimal 或者使用 long 来表达精度数据,new BigDecimal("0.2"), 或者 200,表达 0.2。 > 如果仅仅比较两个值是否相等,建议使用 compareTo 因为 compareTo 仅仅比较两个数值是否相等,例如 1.0 = 1, 如果用 equals 还会比较精度 1.0 != 1; ### BigInteger 用来表示大于 Long.MAX_VALUE 的值。 ### Java成员变量和局部变量 | 比较 | 成员变量 | 局部变量 | |----|----|----| | 位置| 类 | 方法 | | 归属| 对象 | 方法 | | 存储| 实例| 栈空间 | | 生存时间| 实例创建-实例回收 | 方法调用-方法调用结束 | | 默认值| 自动赋默认值,对象=null, 基础类型=0 | 不会自动赋值 | ### 面向对象的三大特征 封装,继承,多态。 ### 接口和抽象类 根本的区别,接口是自顶而下的思想,抽象类是自底而上的设计。 ### Object 它是所有类的父类。 ```java // native 获得当前类的引用对象 getClass // native hash 码 hashCode // 比较是否相等 equals // native 创建并返回当前对象的 copy clone // 返回实例的哈希码的16进制字符串 toString // native 唤醒一个在此对象监视器上等待的线程,如果有多个线程在等待只会唤醒任意一个。 notify // native 唤醒所有在此对象监视器上等待的线程。 notifyAll // 暂停线程的执行。 wait(long timeout) // 同上 wait(long timeout, int nanos) // 同上,无超时时间,一直等待。 wait() // 被垃圾回收时触发。 finalize ``` ### String, StringBuffer, StringBuilder 的区别 String 是不可变的,内部使用 char[] 存储,jdk9 后优化成了 byte[] 存储,这个数组使用了 private final 进行修饰,也没有提供内部方法可以对它进行修改。 例如语法糖的 a + b,其实就是创建了一个新的 StringBuilder 对象,拼接后生成了新的 String对象。 StringBuffer 是安全的,它和 StringBuilder 都集成自 AbstactStringBuilder,它是基于模版方法模式,只不过StringBuilder 的所有方法都使用 Synchronied 进行了装饰,所以它是线程安全的。 StringBuilder 和 StringBuffer 差不多,只不过方法没有加锁,如果是方法内String拼接,使用 StringBuilder 即可。 ### 字符串常量池 字符串常量池在堆中,是JVM为了提高String对象效率提供的一片区域,主要是为了避免字符串的重复创建,字符串常量池放入堆中也是为了提供垃圾回收效率。 ### String#intern 一个 native 方法,作用是将指定的字符串对象的引用保存在字符串常量池中。 1,如果字符串常量池中保存了对应的字符串对象的引用,直接返回该引用。 2,如果字符串常量池中没有保存对应的字符串对象的引用,那就在字符串常量池中创建一个指向该字符串对象的引用并返回。 3,例如: String s1 = "java", String s2 = new String("java"), String s3 = s1.intern(), String s4 = s2.intern(); 最终 s3, s4 得到的都是 s1 的对象引用。 ### Java 异常类结构 1, 所有异常的父接口 Throwable 2, 再下一层是 Exception 和 Error 2.1, Error 包含 OOM 虚拟机Error, 栈溢出Error 等 2.2, 异常包含受检异常 和 非受检异常。 2.2.1, 受检异常主要有IO异常等,非受检异常主要是非法参数,空指针等,非受检异常都是 RuntimeException 以及其子类。 ### 范型 ```java // 范型类 public class Test<T>{ private T a; public Test(T _a){ this.a = _a; } private T getA(){ return this.a; } } // 使用 Test<String> test = new Test<>("abc); ``` ```java // 范型接口 public interface Test<T>{ T doSomeThing(); } public class TestA<T> implements Test<T>{ @Override public T doSomeThing() { return null; } } public class TestB implements Test<String> { @Override public String doSomeThing() { return "abc"; } } ``` ```java // 范型方法 public <E> void doOtherThing(E e){ } ``` ### 反射 反射就是通过某个类的Class对象,获得Class的Method 和 Field 然后通过 Method/Field 的 invoke,调用具体的对象的方法和更新对象的数据。 ```java public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, NoSuchFieldException { // 获取 orderItem 的 class Class<OrderItem> orderItemClass = OrderItem.class; // 创建对象 OrderItem orderItem = new OrderItem(); // 获取所有的公有方法 Method[] methods = orderItemClass.getMethods(); for(Method method : methods){ // 设置状态 if(method.getName().equals("setStatus")){ method.invoke(orderItemDetailDTO, 8); } } // 获取私有字段 Field orderStatus = orderItemDetailDTOClass.getDeclaredField("status"); // 设置可访问 orderItemStatus.setAccessible(true); // 获取字段值 Integer statusVal = (Integer) orderItemStatus.get(orderItemDetailDTO); System.out.println(statusVal); } ``` ### SPI SPI和API的区别 API是服务方提供接口,服务方提供实现。 SPI是调用方提供接口,服务方提供实现。 #### 怎么使用SPI 首先调用方定义接口和方法 服务方提供实现逻辑,在服务方的 META-INF/service 下提供提供一个文件,文件名是接口的全限定名,里边内容是接口的实现类。 调用方引入服务方jar包,通过 ServiceLoader 类就可以加载到实现类 这是JDK的默认约定,因为在 java.util.ServiceLoader 中写死了文件位置 META-INF/services > Springboot starter 也是利用 SPI机制 一个框架想提供一个 starter 就定义一些配置对象,然后把配置对象全限定名放入 META-INF/resource/spring.factories 中, Springboot启动的时候会加载所有依赖包中的 spring.factories 文件中的类,具体逻辑在 SpringFactoriesLoader类中。 注意:springboot3 默认的文件不再是 spring.factories 改成了 org.springframework.boot.autoconfigure.AutoConfiguration.imports ### 序列化 1,不想序列化的字段使用 transient 字段修饰 2,主要的序列化协议有 Hessian kryo protobuf protoStuff 等, 我的开源框架 opentp 的序列化默认就是 kryo 3,json,xml 也是序列化的一种,可读性比较好,但是效率较低,生成的序列化流较大,一般不选择。 4,为什么不推荐 jdk 默认序列化,因为不支持跨语言,性能也不咋好,还存在安全问题(输入的反序列化数据可以通过构造恶意输入,让反序列化产生奇奇怪怪的对象)。 ### 代理 #### 静态代理 1,实现被代理对象的接口 2,实现被代理对象接口,定义的方法 3,引入被代理对象 4,在代理对象的方法內,可以添加增强的逻辑,然后调用被代理对象的方法。 > 太多简单不再举例。 #### 动态代理 1,JDK 动态代理 被代理对象有接口,使用JDK Proxy ```java // 接口 public interface DemoInter { void test(); } // 实现类 public class DemoClass implements DemoInter{ @Override public void test() { System.out.println("test"); } } // 测试 public class Demo { public static void main(String[] args) { // 被代理对象 DemoInter demo = new DemoClass(); // 代理对象 DemoInter demo1 = (DemoInter) Proxy.newProxyInstance(demo.getClass().getClassLoader(), demo.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println(1); Object res = method.invoke(demo, args); System.out.println(2); return res; } }); // 执行测试 demo1.test(); } } ``` 2,CGLIB 被代理对象没有接口,则使用 CGLIB 生成代理对象 ```java 引入依赖 <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.3.0</version> </dependency> // demo 类 public class DemoClass { public void test() { System.out.println("test"); } } // 注意这一段代码在 jdk9 之后会报错。 public class Demo { public static void main(String[] args) { Enhancer enhancer = new Enhancer(); enhancer.setClassLoader(DemoClass.class.getClassLoader()); enhancer.setSuperclass(DemoClass.class); enhancer.setCallback(new MethodInterceptor() { @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { System.out.println(1); Object ob = methodProxy.invokeSuper(o, args); System.out.println(2); return ob; } }); DemoClass o = (DemoClass) enhancer.create(); o.test(); System.out.println(1); } } ``` #### 对比 1,JDK proxy 必须实现接口,CGLIB 不必,因为 CGLIB 是通过生成一个被代理类的子类来进行代理的,因此不能代理声明为 final 类型的类和方法。 2,JDK proxy 效率比较高 3,动态代理在运行时,才生成代理类字节码,并加载到 JVM 中的。 ### Unsafe 提供一些不安全的操作,例如系统内存直接访问等,主要是调用一些 Native 方法。 #### 内存操作 申请内存,设置值,内存copy,释放内存。 ```java //分配新的本地空间 public native long allocateMemory(long bytes); //重新调整内存空间的大小 public native long reallocateMemory(long address, long bytes); //将内存设置为指定值 public native void setMemory(Object o, long offset, long bytes, byte value); //内存拷贝 public native void copyMemory(Object srcBase, long srcOffset,Object destBase, long destOffset,long bytes); //释放内存 public native void freeMemory(long address); ``` #### 内存屏障 禁止load store 指令重排 ```java //内存屏障,禁止load操作重排序。屏障前的load操作不能被重排序到屏障后,屏障后的load操作不能被重排序到屏障前 public native void loadFence(); //内存屏障,禁止store操作重排序。屏障前的store操作不能被重排序到屏障后,屏障后的store操作不能被重排序到屏障前 public native void storeFence(); //内存屏障,禁止load、store操作重排序 public native void fullFence(); ``` #### 对象操作 ```java public class Demo { private int test; public static void main(String[] args) throws Exception{ Unsafe unsafe = getUnsafe(); assert unsafe != null; long offset = unsafe.objectFieldOffset(Demo.class.getDeclaredField("test")); Demo demo = new Demo(); System.out.println(demo.test); unsafe.putInt(demo, offset, 42); System.out.println(demo.test); System.out.println(unsafe.getInt(demo, offset)); } private static Unsafe getUnsafe() { try { Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); return (Unsafe) field.get(null); } catch (Exception e) { e.printStackTrace(); return null; } } } ``` #### 数组操作 ```java // 这两个方法配合起来使用,即可定位数组中每个元素在内存中的位置。 //返回数组中第一个元素的偏移地址 public native int arrayBaseOffset(Class<?> arrayClass); //返回数组中一个元素占用的大小 public native int arrayIndexScale(Class<?> arrayClass); ``` #### CAS ```java public final native boolean compareAndSwapObject(Object o, long offset, Object expected, Object update); public final native boolean compareAndSwapInt(Object o, long offset, int expected,int update); public final native boolean compareAndSwapLong(Object o, long offset, long expected, long update); // cas操作,使用 cpu的原子指令 cmpxchg 指令实现 ``` #### 线程调度 ```java //取消阻塞线程 public native void unpark(Object thread); //time 时间内,阻塞线程 public native void park(boolean isAbsolute, long time); //获得对象锁(可重入锁) @Deprecated public native void monitorEnter(Object o); //释放对象锁 @Deprecated public native void monitorExit(Object o); //尝试获取对象锁 @Deprecated public native boolean tryMonitorEnter(Object o); // Jdk中的锁 AQS 很多用到线程操作 和 CAS // AQS 通过 LockSupport.park() 和 LockSupport.unpark() 实现线程的阻塞和唤醒的,底层就是调用 Unsafe 的 park、unpark。 public class Demo{ public static void main(String[] args) { Thread curThread = Thread.currentThread(); new Thread(()->{ try { TimeUnit.SECONDS.sleep(10); System.out.println("10秒后唤起主线程"); unsafe.unpark(curThread); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); System.out.println("挂起当前线程"); unsafe.park(false, 0L); System.out.println("主线程被唤醒"); } } ``` #### Class操作 ```java //获取静态属性的偏移量 public native long staticFieldOffset(Field f); //获取静态属性的对象指针 public native Object staticFieldBase(Field f); //判断类是否需要初始化(用于获取类的静态属性前进行检测) public native boolean shouldBeInitialized(Class<?> c); @Data public class Demo { public static String aa= "Demo"; int bb; } private void staticTest() throws Exception { Demo demo = new Demo(); // 也可以用下面的语句触发类初始化 // 1. // unsafe.ensureClassInitialized(User.class); // 2. // System.out.println(User.name); System.out.println(unsafe.shouldBeInitialized(Demo.class)); Field aField = User.class.getDeclaredField("aa"); long fieldOffset = unsafe.staticFieldOffset(aField); Object fieldBase = unsafe.staticFieldBase(aField); Object object = unsafe.getObject(fieldBase, fieldOffset); System.out.println(object); } // 输出 false aa ```
import { useContext } from 'react'; import { Token } from '@mindspace-io/core'; import { InjectorContext } from '../injector.context'; /** * Return either the injector instance or the token lookup FROM the * injector. * * A configured injector instance is required along with and a lookup token. * What is returned is a tuple containing the singleton instance and the injector. * * @code * const injector: DependencyInjector = makeInjector([ * { provide: API_KEY, useValue: '873771d7760b846d51d5ac5804ab' }, * { provide: API_ENDPOINT, useValue: 'https://uifaces.co/api?limit=25' }, * { provide: ContactsService, useClass: ContactsService, deps: [API_ENDPOINT, API_KEY] } * ]); * * // Hide how DI is used under the hood * // NOTE: The requires a DependencyInjectionProvider to be used for DI lookups * * export function useContactsHook(): ContactsService { * return useDependencyInjector<ContactsService>(ContactsService) * } * * @returns T is either the DependencyInjector or the injector token lookup. */ export const useDependencyInjector = <T extends unknown>(token?: Token): T => { const injector = useContext(InjectorContext); return (!token ? injector : injector.get(token)) as T; };
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:smartshipapp/authentication/authentication_bloc.dart'; import 'package:smartshipapp/data/model/CreateUser.dart'; import 'package:smartshipapp/data/repositories/abstract/user_repository.dart'; import 'sign_up.dart'; class SignUpBloc extends Bloc<SignUpEvent, SignUpState> { final UserRepository userRepository; final AuthenticationBloc authenticationBloc; SignUpBloc({ @required this.userRepository, @required this.authenticationBloc, }) : assert(userRepository != null), assert(authenticationBloc != null), super(SignUpInitialState()); @override Stream<SignUpState> mapEventToState( SignUpEvent event, ) async* { // normal sign up if (event is SignUpPressed) { yield SignUpProcessingState(); try { final CreateUser res = await userRepository.signUp( firstName: event.firstName, lastName: event.lastName, phoneNumber: event.phoneNumber, email: event.email, password: event.password, country: event.country); // authenticationBloc.add(LoggedIn(token)); if (res.entity != null) { yield SignUpFinishedState(); } else { yield SignUpErrorState(res.message); } } catch (error) { print("error $error"); yield SignUpErrorState(error); } } } }
import EngineGameService from '../services/gameServices/gameServices/engineGameService' import { Cell } from './cell/Cell' import { EngineMoveCells } from '../services/gameServices/types' import { Colors } from '../constants/Colors' import { Player } from './player/Player' import moveFigureService from '../services/moveServices/moveFigureService' import Board from './board/Board' /** * Model representing the game engine with various properties and methods. */ class EngineModel extends EngineGameService { private _connected = false private _pawnAdvantage: number | string = 0 private _engineMove: EngineMoveCells | null = null private currentColorMove: Colors = Colors.WHITE public difficaltyBot: 'begginer' | 'amateur' | 'proffesional' = 'proffesional' private opponentPlayer: Player | null = null public setBoard: React.Dispatch<React.SetStateAction<Board>> public board: Board public gameStarted = false constructor( setBoard: React.Dispatch<React.SetStateAction<Board>>, board: Board ) { super() this.setBoard = setBoard this.board = board } public setDifficaltyBot( difficaltyBot: 'begginer' | 'amateur' | 'proffesional' ) { this.difficaltyBot = difficaltyBot } public getOpponentPlayer() { return this.opponentPlayer } /** * Prepare and start the game engine, establishing a socket connection. */ async prepareAndStartEngine() { try { await this.startEngine(this.difficaltyBot) this.gameStarted = true } catch (error) { console.error('Error:', error) throw error } } /** * Prepare and send a move to the game engine, updating relevant properties. * @param {Cell} selectedCell - The selected cell for the move. * @param {Cell} targetCell - The target cell for the move. * @returns {void} A promise that resolves when the move is sent or null in case of an error. */ async prepareAndSendMoveEngine( selectedCell: Cell | null, targetCell: Cell ): Promise<void> { try { if (selectedCell && selectedCell.figure?.canMove(targetCell)) { const responseEngine = await this.processMoveAndReceiveResponse( selectedCell, targetCell, this.currentColorMove ) if (responseEngine) { this._pawnAdvantage = responseEngine.pawnAdvantage this._engineMove = responseEngine.engineMoveCells setTimeout(() => { moveFigureService.handleMoveFigure( responseEngine.engineMoveCells.targetCell, responseEngine.engineMoveCells.selectedCell, undefined, this.setBoard ) }, 500) } } } catch (error) { console.error('Unforeseen error') throw error } } /** * Prepare and stop the game engine, disconnecting the socket. * @returns {Promise<void>} A promise that resolves when the engine is stopped. */ async prepareAndStopEngine(): Promise<void> { try { if (this.engineSocket && this._connected) { const isStopped = await this.stopEngine(this.engineSocket) if (!isStopped) { console.error('Engine is not stopped') } } } catch (error) { console.error(error) throw error // Передаем ошибку дальше } } /** * Get the current pawn advantage. * @returns {number} The pawn advantage value. */ get pawnAdvantage(): number | string { return this._pawnAdvantage } /** * Get the latest engine moves. * @returns {EngineMoveCells | null} The engine moves or null if not available. */ get engineMove(): EngineMoveCells | null { return this._engineMove } setCurrentColorPlayer() { const swifedtColor = this.currentColorMove === Colors.WHITE ? Colors.BLACK : Colors.WHITE this.currentColorMove = swifedtColor } } export default EngineModel
/** *=06. TypeScript Crash Course - Inheritance and Interfaces * 25. Abstract Classes - Overview * 26. Abstract Classes - Write Some Code */ //--IMPORTS import { Shape } from './Shape'; /** *=Child Class Cirlce */ export class Cirlce extends Shape { //--Fields protected _className: string = "Cirlce"; //--Constructor constructor(theX: number, theY: number, private _radius: number) { //--call superclass/Shape constructor to set _x, _y fields; super(theX, theY); } //--Getters // this.x - actually means - call get x() method from Shape Class, // this.y - actually means - call get y() method from Shape Class; getInfo(): string { return `${this._className}: (x: ${this.x}, y: ${this.y}, radius: ${this._radius});`; } //--Parent Class Abstract Method Implementation // Circle Area = Pi*R^2 calculateArea(): number { //--error: returns string but must return number type //return (Math.PI * Math.pow(this._radius, 2)).toFixed(2); //--correct return Math.PI * Math.pow(this._radius, 2); } }
---@class custom_icons --- Icons will be automatically pulled from tty if necessary --- Icons will otherwise be gotten from gui, falling back to the tty icon if not available --- Note: this only works on the top level. if a table is returned, no such promises are made. local tty = { -- {{{ 1 clock = "", debug = "debug ", lualine = { section_separators = { left = ">", right = "<" }, component_separators = { left = "|", right = "|" }, filename_symbols = { modified = " M ", readonly = "RO ", unnamed = "" }, }, ["neo-tree"] = { -- {{{ 2 default_component_configs = { modified = { symbol = "[+] " }, indent = { indent_marker = "|", last_indent_marker = ">", expander_collapsed = "▶", expander_expanded = "▼", }, icon = { folder_closed = "-", folder_open = "+", folder_empty = "_", folder_empty_open = "_>", default = "*", }, git_status = { symbols = { -- Change type added = "", -- or "✚", but this is redundant info if you use git_status_colors on the name modified = "", -- or "", but this is redundant info if you use git_status_colors on the name deleted = "x", -- this can only be used in the git_status source renamed = "->", -- this can only be used in the git_status source untracked = "?", ignored = "/", unstaged = "_", staged = "+", conflict = "!", }, }, }, }, -- }}} telescope = { prompt_prefix = "> ", selection_caret = "> " }, flash_prompt = "Flash: ", gitsigns = { add = "+", change = "|", delete = "-", topdelete = "-", changedelete = ":", untracked = "?", }, lazyvim = { -- {{{ 2 dap = { Stopped = { "-> ", "DiagnosticWarn", "DapStoppedLine" }, Breakpoint = "X ", BreakpointCondition = "? ", BreakpointRejected = { "! ", "DiagnosticError" }, LogPoint = ".>", }, diagnostics = { Error = "X ", Warn = "! ", Hint = "> ", Info = "I " }, git = { added = "+ ", modified = "M ", removed = "- " }, kinds = { Array = "[] ", Boolean = "", Class = "", Color = "", Constant = "", Constructor = "", Copilot = "", Enum = "", EnumMember = "", Event = "", Field = "", File = "File ", Folder = "Folder ", Function = "Func ", Interface = "", Key = "ABC ", Keyword = "", Method = "Method ", Module = "Mod ", Namespace = "{} ", Null = "NULL ", Number = "# ", Object = "{} ", Operator = "+- ", Package = "", Property = "", Reference = "", Snippet = "", String = "", Struct = "", Text = "", TypeParameter = "<T> ", Unit = "", Value = "ABC ", Variable = "<V> ", }, }, -- }}} noice = { -- {{{ 2 cmdline = { format = { cmdline = { icon = "> " }, search_down = { icon = "/ " }, search_up = { icon = "? " }, filter = { icon = "$" }, lua = { icon = "L " }, help = { icon = "? " }, calculator = { icon = "* " }, IncRename = { icon = "RENAME " }, }, }, format = { level = { icons = { error = "X ", info = "I ", warn = "! " } } }, popupmenu = { kind_icons = { Class = "", Color = "", Constant = "", Constructor = "", Enum = " ", EnumMember = "", Field = "", File = "", Folder = "", Function = "", Interface = "", Keyword = "", Method = "", Module = "", Property = "", Snippet = "", Struct = "", Text = "", Unit = "", Value = "", Variable = "", }, }, }, -- }}} lazy_nvim = { ui = { icons = { cmd = "", config = "", event = "", ft = "", init = "", import = "", keys = "", lazy = "lazy", loaded = "->", not_loaded = "X", plugin = "", runtime = "", source = "", start = "", task = "", list = { "", "", "", "", }, }, }, }, } -- }}} 1 ---@class custom_icons local gui = { -- {{{1 clock = " ", debug = " ", ["neo-tree"] = { -- {{{ 2 default_component_configs = { git_status = { symbols = { added = "✚", conflict = "", deleted = "✖", ignored = "", modified = "", renamed = "󰁕", staged = "", unstaged = "󰄱", untracked = "", }, }, icon = { default = "*", folder_closed = "", folder_empty = "󰜌", folder_empty_open = "󰜌", folder_open = "", }, indent = { expander_collapsed = "", expander_expanded = "", indent_marker = "│", last_indent_marker = "└", }, modified = { symbol = "[+] " }, }, }, -- }}} lualine = { section_separators = { left = "", right = "" }, component_separators = { left = "|", right = "|" }, filename_symbols = { modified = "  ", readonly = "󰌾 ", unnamed = "" }, }, lazyvim = { -- {{{ 2 dap = { Breakpoint = " ", BreakpointCondition = " ", BreakpointRejected = { " ", "DiagnosticError" }, LogPoint = ".>", Stopped = { "󰁕 ", "DiagnosticWarn", "DapStoppedLine" }, }, diagnostics = { Error = " ", Hint = " ", Info = " ", Warn = " " }, git = { added = " ", modified = " ", removed = " " }, kinds = { Array = " ", Boolean = " ", Class = " ", Color = " ", Constant = " ", Constructor = " ", Copilot = " ", Enum = " ", EnumMember = " ", Event = " ", Field = " ", File = " ", Folder = " ", Function = " ", Interface = " ", Key = " ", Keyword = " ", Method = " ", Module = " ", Namespace = " ", Null = " ", Number = " ", Object = " ", Operator = " ", Package = " ", Property = " ", Reference = " ", Snippet = " ", String = " ", Struct = " ", Text = " ", TypeParameter = " ", Unit = " ", Value = " ", Variable = " ", }, }, -- }}} telescope = { prompt_prefix = " ", selection_caret = " " }, gitsigns = { add = "▎", change = "▎", changedelete = "▎", delete = "", topdelete = "", untracked = "▎", }, flash_prompt = "⚡", noice = { -- {{{ 2 cmdline = { format = { IncRename = { icon = " " }, calculator = { icon = "" }, cmdline = { icon = "" }, filter = { icon = "$" }, help = { icon = "" }, lua = { icon = "" }, search_down = { icon = " " }, search_up = { icon = " " }, }, }, format = { level = { icons = { error = " ", info = " ", warn = " " } } }, popupmenu = { kind_icons = { Class = " ", Color = " ", Constant = " ", Constructor = " ", Enum = "了 ", EnumMember = " ", Field = " ", File = " ", Folder = " ", Function = " ", Interface = " ", Keyword = " ", Method = "ƒ ", Module = " ", Property = " ", Snippet = " ", Struct = " ", Text = " ", Unit = " ", Value = " ", Variable = " ", }, }, }, -- }}} lazy_nvim = { ui = { icons = { cmd = " ", config = "", event = "", ft = " ", init = " ", import = " ", keys = " ", lazy = "󰒲 ", loaded = "●", not_loaded = "○", plugin = " ", runtime = " ", source = " ", start = "", task = "✔ ", list = { "●", "➜", "★", "‒", }, }, }, }, } -- }}} ---@class icons :custom_icons ---@field TTY_ICONS custom_icons Use this special key to specify that icons should come from the tty set (only useful in gui environments) local M = setmetatable({}, { __index = function(_, key) if key == "TTY_ICONS" then return tty[key] end local is_tty = require("utils.is_tty") -- If not tty, use gui. If tty or gui not exist, use tty instead return not is_tty() and gui[key] or tty[key] end, }) return M