text
stringlengths
184
4.48M
const Banner = require('../models/bannerModel'); const asyncHandler = require('express-async-handler'); const loadAddBanner = asyncHandler(async (req, res) => { try { res.render('add-Banner', { Message: '' }); } catch (error) { console.error(error); } }); const addBanner = asyncHandler(async (req, res) => { try { const { title, description, expDate } = req.body; const image = req.file.filename; // Assuming a single image is uploaded //console.log(image); const bannerData = await Banner.create({ title: title, image: image, description: description, startDate: new Date(), endDate: expDate, }); res.render('add-Banner', { Message: 'Banner Added' }); } catch (error) { console.error(error); } }); const bannerList = asyncHandler(async (req, res) => { try { // Get current date const currentDate = new Date(); // Find all coupons const bannerData = await Banner.find(); // Check each coupon for expiration and update 'isActive' accordingly for (let banner of bannerData) { if (banner.endDate <= currentDate) { // If expiration date has passed, set 'isActive' to false await Banner.findByIdAndUpdate(banner._id, { isActive: false }); } } const updatedBanner = await Banner.find(); res.render('banner-List', { bannerData: updatedBanner }); } catch (error) { console.error(error); } }); const bannerStatus = asyncHandler(async (req, res) => { try { const BannerId = req.query.bannerId; console.log('bannerid', BannerId); const findBanner = await Banner.findById(BannerId); if (!findBanner) { return res.status(404).json({ error: 'Banner not found' }); } const currentDate = new Date(); if (findBanner.endDate < currentDate) { return res.status(400).json({ error: 'Banner has expired. Status cannot be changed.' }); } const newStatus = !findBanner.isActive; const changeStatus = await Banner.findByIdAndUpdate(BannerId, { isActive: newStatus }, { new: true }); res.status(200).json({ message: 'Banner status updated successfully' }); } catch (error) { console.error(error); res.status(500).json({ error: 'Failed to update the Banner status' }); } }); module.exports = { loadAddBanner, addBanner, bannerList, bannerStatus };
import { useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import axios from "axios"; import { Container,Button, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Grid, Typography ,} from '@mui/material'; import { useAuth } from '../../../context/AuthContext'; import Navbar from '../../../component/NavBar'; const MoviePage = () => { const { logout, user } = useAuth(); const [listMovies, setListMovies] = useState([]); const navigate = useNavigate(); useEffect(() => { fetchMovieList(); }, []); const fetchMovieList = async () => { try { const resultMovies = await axios.get("http://localhost:8110/api/movie/get"); const moviesWithCreator = resultMovies.data.map(movie => { return { ...movie, createdByCurrentUser: user && movie.createdBy === user._id, }; }); setListMovies(moviesWithCreator); } catch (error) { console.error(error); } }; const deleteMovie = async (idMovie) => { try { const resultMovie = await axios.delete( `http://localhost:8110/api/movie/${idMovie}` ); if (resultMovie.status === 200) { const updatedMovies = listMovies.filter( (movie) => movie._id !== idMovie ); setListMovies(updatedMovies); alert("Movie eliminada correctamente"); } else { alert("Error al eliminar la Movie"); } } catch (error) { alert("Error al eliminar la Movie", error ); console.error(error); } }; const addMovie = () => { navigate("/movies/addMovie"); }; const detailMovie = (idMovie) => { navigate(`/movies/detailMovie/${idMovie}`); }; const addReviewMovie = (idMovie, nameMovie) => { navigate(`/movies/${idMovie}/addReview`, { state: { nameMovie } }); }; return ( <div> <div> <Navbar pageTitle="List de Movies" /> <Container fixed style={{ marginTop: '20px', marginBottom: '20px' }}> <Grid container rowSpacing={1} columnSpacing={{ xs: 1, sm: 2, md: 3 }}> <Grid item xs={10}> <Typography variant="h4">Lists Movies </Typography> </Grid> <Grid item xs={2}> <Button variant="contained" color="primary" onClick={addMovie} sx={{backgroundColor: "#00a3c3",position: "relative",overflow: "hidden"}}> Add Movie </Button> </Grid> </Grid> <TableContainer component={Paper} style={{ marginTop: '20px' }}> <Table> <TableHead> <TableRow> <TableCell>Title</TableCell> <TableCell>Rating</TableCell> <TableCell>Action</TableCell> </TableRow> </TableHead> <TableBody> {listMovies.map((movie, index) => ( <TableRow key={index}> <TableCell>{movie.title}</TableCell> <TableCell>{movie.avgReview !== 0 ? movie.avgReview : movie.rating}</TableCell> <TableCell> <Button variant="outlined" onClick={() => detailMovie(movie._id)}> Read Reviews </Button> <Button variant="outlined" onClick={() => addReviewMovie(movie._id, movie.title)}> Write a Review </Button> </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> </Container> </div> </div> ); }; export default MoviePage;
import React, { useEffect, useState, useMemo, useCallback } from "react"; import { Owner as OwnerModel } from "../../models/Owner"; import * as OwnerApi from "../../network/owner_api"; import { darken } from "@mui/material"; import MaterialReactTable, { type MaterialReactTableProps, type MRT_Cell, type MRT_ColumnDef, type MRT_Row, } from 'material-react-table'; import { Box, Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, MenuItem, Stack, TextField, Tooltip, } from '@mui/material'; import { Delete, Edit } from '@mui/icons-material'; import { formatOwnerType } from "../../utils/formatDate"; export type Owner = { ownerId: number; ownerType: string; name: string; bankName: string; }; const RetrieveAllOwnersView = () => { type OwnerInput = { ownerId: number, ownerType: string, name: string, bankName: string, }; const [createModalOpen, setCreateModalOpen] = useState(false); const [tableData, setTableData] = useState<Owner[]>(() => []); const [validationErrors, setValidationErrors] = useState<{ [cellId: string]: string; }>({}); const handleCreateNewRow = (values: Owner) => { tableData.push(values); setTableData([...tableData]); const insertOwner: OwnerInput = { ownerId: 0, ownerType: values.ownerType, name: values.name, bankName: values.bankName, }; // Send the API request to update the Owner OwnerApi.createOwner(insertOwner).then(() => { console.log("Owner added!"); }); }; const handleSaveRowEdits: MaterialReactTableProps<Owner>['onEditingRowSave'] = async ({ exitEditingMode, row, values }) => { if (!Object.keys(validationErrors).length) { tableData[row.index] = values; //send/receive api updates here, then refetch or update local table data for re-render const updatedOwner: OwnerInput = { ownerId: parseInt(values.ownerId), ownerType: values.ownerType, name: values.name, bankName: values.bankName, }; // Send the API request to update the Owner await OwnerApi.updateOwner(updatedOwner.ownerId, updatedOwner); setTableData([...tableData]); exitEditingMode(); //required to exit editing mode and close modal } }; const handleCancelRowEdits = () => { setValidationErrors({}); }; const handleDeleteRow = useCallback( (row: MRT_Row<Owner>) => { if ( !window.confirm(`Are you sure you want to delete ${row.getValue('name')}`) ) { return; } //send api delete request here, then refetch or update local table data for re-render OwnerApi.deleteOwner(row.getValue('ownerId')).then(() => { console.log("Owner Deleted!"); }); tableData.splice(row.index, 1); setTableData([...tableData]); }, [tableData], ); const getCommonEditTextFieldProps = useCallback( ( cell: MRT_Cell<Owner>, ): MRT_ColumnDef<Owner>['muiTableBodyCellEditTextFieldProps'] => { return { error: !!validationErrors[cell.id], helperText: validationErrors[cell.id], onChange: (e) => { const value = e.target.value; if (!value) { setValidationErrors((prev) => ({ ...prev, [cell.id]: 'Required', })); } else { setValidationErrors((prev) => { const next = { ...prev }; delete next[cell.id]; return next; }); } //cell.setEditingCellValue(value); }, }; }, [validationErrors], ); const columns = useMemo<MRT_ColumnDef<Owner>[]>( () => [ { accessorKey: 'ownerId', header: 'ownerId', enableColumnOrdering: false, enableEditing: false, //disable editing on this column enableSorting: false, enableHiding: false, size: 10, editable: "never" }, { accessorKey: 'ownerType', header: 'ownerType', size: 5, muiTableBodyCellEditTextFieldProps: ({ cell }) => ({ ...getCommonEditTextFieldProps(cell), }), //customize normal cell render on normal non-aggregated rows Cell: ({ cell }) => <>{formatOwnerType(cell.getValue<string>())}</>, }, { accessorKey: 'name', header: 'name', size: 20, muiTableBodyCellEditTextFieldProps: ({ cell }) => ({ ...getCommonEditTextFieldProps(cell), }), }, { accessorKey: 'bankName', header: 'bankName', size: 20, muiTableBodyCellEditTextFieldProps: ({ cell }) => ({ ...getCommonEditTextFieldProps(cell), }), }, ], [getCommonEditTextFieldProps], ); useEffect(() => { OwnerApi.fetchOwner().then((owners) => { //tableData=owners; setTableData(owners); console.log(owners); }); }, []); return ( <> <MaterialReactTable displayColumnDefOptions={{ 'mrt-row-actions': { muiTableHeadCellProps: { align: 'center', }, size: 120, }, }} columns={columns} data={tableData} editingMode="modal" //default enableColumnOrdering initialState={{ columnVisibility: { ownerId: false } }} //hide firstName column by default enableEditing onEditingRowSave={handleSaveRowEdits} onEditingRowCancel={handleCancelRowEdits} renderRowActions={({ row, table }) => ( <Box sx={{ display: 'flex', gap: '1rem' }}> <Tooltip arrow placement="left" title="Edit"> <IconButton onClick={() => table.setEditingRow(row)}> <Edit /> </IconButton> </Tooltip> <Tooltip arrow placement="right" title="Delete"> <IconButton color="error" onClick={() => handleDeleteRow(row)}> <Delete /> </IconButton> </Tooltip> </Box> )} renderTopToolbarCustomActions={() => ( <Button color="secondary" onClick={() => setCreateModalOpen(true)} variant="contained" > Create New Owner </Button> )} /> <CreateNewAccountModal columns={columns} open={createModalOpen} onClose={() => setCreateModalOpen(false)} onSubmit={handleCreateNewRow} /> </> ); }; interface CreateModalProps { columns: MRT_ColumnDef<Owner>[]; onClose: () => void; onSubmit: (values: Owner) => void; open: boolean; } //example of creating a mui dialog modal for creating new rows export const CreateNewAccountModal = ({ open, columns, onClose, onSubmit, }: CreateModalProps) => { const [values, setValues] = useState<any>(() => columns.reduce((acc, column) => { acc[column.accessorKey ?? ''] = ''; return acc; }, {} as any), ); const handleSubmit = () => { //put your validation logic here onSubmit(values); onClose(); }; return ( <Dialog open={open}> <DialogTitle textAlign="center">Create New Owner</DialogTitle> <DialogContent> <form onSubmit={(e) => e.preventDefault()}> <Stack sx={{ width: '100%', minWidth: { xs: '300px', sm: '360px', md: '400px' }, gap: '1.5rem', }} > {columns.filter(column=>column.accessorKey !=="ownerId").map((column) => ( <TextField key={column.accessorKey} label={column.header} name={column.accessorKey} onChange={(e) => setValues({ ...values, [e.target.name]: e.target.value }) } /> ))} </Stack> </form> </DialogContent> <DialogActions sx={{ p: '1.25rem' }}> <Button onClick={onClose}>Cancel</Button> <Button color="secondary" onClick={handleSubmit} variant="contained"> Create New Owner </Button> </DialogActions> </Dialog> ); }; export default RetrieveAllOwnersView;
import { Test, TestingModule } from '@nestjs/testing' import { PostController } from './post.controller' import { PostService } from '../services/post.service' describe('PostController', () => { let controller: PostController let service: PostService beforeEach(async () => { const serviceMock = { findAll: jest.fn(), findOne: jest.fn(), getAllComments: jest.fn(), findPostsLikedByUser: jest.fn(), create: jest.fn(), update: jest.fn(), remove: jest.fn(), } const module: TestingModule = await Test.createTestingModule({ controllers: [PostController], providers: [{ provide: PostService, useValue: serviceMock }] }).compile() controller = module.get<PostController>(PostController) service = module.get<PostService>(PostService) }) it('should call findAll with correct parameters', async () => { const findAllSpy = jest.spyOn(service, 'findAll') await controller.findAll(1, 10, 'createdAt', 'asc') expect(findAllSpy).toHaveBeenCalledWith(1, 10, 'createdAt', 'asc') }) it('should call findOne with correct parameters', async () => { const findOneSpy = jest.spyOn(service, 'findOne') await controller.findOne('uuid') expect(findOneSpy).toHaveBeenCalledWith('uuid') }) it('should call getAllComments with correct parameters', async () => { const getAllCommentsSpy = jest.spyOn(service, 'getAllComments') await controller.getAllComments('uuid') expect(getAllCommentsSpy).toHaveBeenCalledWith('uuid') }) it('should call findPostsLikedByUser with correct parameters', async () => { const findPostsLikedByUserSpy = jest.spyOn(service, 'findPostsLikedByUser') await controller.findPostsLikedByUser('uuid') expect(findPostsLikedByUserSpy).toHaveBeenCalledWith('uuid') }) it('should call update with correct parameters', async () => { const updateSpy = jest.spyOn(service, 'update') const dto = { title: 'title', location: 'location', } await controller.update('uuid', dto) expect(updateSpy).toHaveBeenCalledWith('uuid', dto) }) it('should call remove with correct parameters', async () => { const removeSpy = jest.spyOn(service, 'remove') await controller.remove('uuid') expect(removeSpy).toHaveBeenCalledWith('uuid') }) })
import { ClientSideRowModelModule } from '@ag-grid-community/client-side-row-model'; import { ColDef, Grid, GridOptions, IFiltersToolPanel, ModuleRegistry, } from '@ag-grid-community/core'; import '@ag-grid-community/core/dist/styles/ag-grid.css'; import '@ag-grid-community/core/dist/styles/ag-theme-alpine.css'; import { ColumnsToolPanelModule } from '@ag-grid-enterprise/column-tool-panel'; import { FiltersToolPanelModule } from '@ag-grid-enterprise/filter-tool-panel'; import { MenuModule } from '@ag-grid-enterprise/menu'; import { SetFilterModule } from '@ag-grid-enterprise/set-filter'; // Register the required feature modules with the Grid ModuleRegistry.registerModules([ ClientSideRowModelModule, MenuModule, FiltersToolPanelModule, ColumnsToolPanelModule, SetFilterModule, ]); var filterParams = { comparator: (filterLocalDateAtMidnight: Date, cellValue: string) => { var dateAsString = cellValue; if (dateAsString == null) return -1; var dateParts = dateAsString.split('/'); var cellDate = new Date( Number(dateParts[2]), Number(dateParts[1]) - 1, Number(dateParts[0]) ); if (filterLocalDateAtMidnight.getTime() === cellDate.getTime()) { return 0; } if (cellDate < filterLocalDateAtMidnight) { return -1; } if (cellDate > filterLocalDateAtMidnight) { return 1; } }, // browserDatePicker: true, }; const columnDefs: ColDef[] = [ { field: 'athlete', filter: 'agTextColumnFilter' }, { field: 'age', filter: 'agNumberColumnFilter', maxWidth: 100 }, { field: 'country' }, { field: 'year', maxWidth: 100 }, { field: 'date', filter: 'agDateColumnFilter', filterParams: filterParams, }, { field: 'sport' }, { field: 'gold', filter: 'agNumberColumnFilter' }, { field: 'silver', filter: 'agNumberColumnFilter' }, { field: 'bronze', filter: 'agNumberColumnFilter' }, { field: 'total', filter: 'agNumberColumnFilter' }, ]; const gridOptions: GridOptions = { columnDefs: columnDefs, defaultColDef: { flex: 1, minWidth: 150, filter: true, sortable: true, }, sideBar: 'filters', onGridReady: (params) => { ((params.api.getToolPanelInstance( 'filters' ) as any) as IFiltersToolPanel).expandFilters(); }, }; var savedFilterModel: any = null; function clearFilters() { gridOptions.api!.setFilterModel(null); } function saveFilterModel() { savedFilterModel = gridOptions.api!.getFilterModel(); var keys = Object.keys(savedFilterModel); var savedFilters: string = keys.length > 0 ? keys.join(', ') : '(none)'; (document.querySelector('#savedFilters') as any).innerHTML = savedFilters; } function restoreFilterModel() { gridOptions.api!.setFilterModel(savedFilterModel); } function restoreFromHardCoded() { var hardcodedFilter = { country: { type: 'set', values: ['Ireland', 'United States'], }, age: { type: 'lessThan', filter: '30' }, athlete: { type: 'startsWith', filter: 'Mich' }, date: { type: 'lessThan', dateFrom: '2010-01-01' }, }; gridOptions.api!.setFilterModel(hardcodedFilter); } function destroyFilter() { gridOptions.api!.destroyFilter('athlete'); } // setup the grid after the page has finished loading var gridDiv = document.querySelector<HTMLElement>('#myGrid')!; new Grid(gridDiv, gridOptions); fetch('https://www.ag-grid.com/example-assets/olympic-winners.json') .then((response) => response.json()) .then((data) => gridOptions.api!.setRowData(data)); if (typeof window !== 'undefined') { // Attach external event handlers to window so they can be called from index.html (<any>window).clearFilters = clearFilters; (<any>window).saveFilterModel = saveFilterModel; (<any>window).restoreFilterModel = restoreFilterModel; (<any>window).restoreFromHardCoded = restoreFromHardCoded; (<any>window).destroyFilter = destroyFilter; }
use rand::{thread_rng, Rng}; use std::fs::File; use std::io::Read; use std::path::{self, PathBuf}; use clap::Parser; use colored::{Color, Colorize}; #[derive(Parser, Debug)] #[command(author, about)] struct Args { file: PathBuf, } fn to_color(num: u8) -> (Color, Color) { fn to_color_inner(num: u8) -> Color { match num { 0 => Color::Black, 1 => Color::Red, 2 => Color::Green, 3 => Color::Yellow, 4 => Color::Blue, 5 => Color::Magenta, 6 => Color::Cyan, 7 => Color::White, 8 => Color::BrightBlack, 9 => Color::BrightRed, 10 => Color::BrightGreen, 11 => Color::BrightYellow, 12 => Color::BrightBlue, 13 => Color::BrightMagenta, 14 => Color::BrightCyan, 15 => Color::BrightWhite, _ => panic!("Invalid number"), } } let (div, rem) = (num / 16, num % 16); // dbg!("{} {}", div, rem); (to_color_inner(div), to_color_inner(rem)) } fn main() { let args = Args::parse(); let bias: u8 = thread_rng().gen(); let step: u8 = thread_rng().gen(); let noise_color = to_color(step.wrapping_add(bias)); print!("{}", "@".on_color(noise_color.1).color(noise_color.0)); let file = File::open(path::Path::new(&args.file)).expect(&"File not found".red().to_string()); for (i, buf) in file.bytes().enumerate() { match buf { Ok(b) => { let (fg, bg) = to_color( b.wrapping_mul(step.wrapping_add((i % u8::MAX as usize) as u8)) .wrapping_add(bias), ); print!("{}", "#".on_color(bg).color(fg)); } Err(e) => println!("{}", e), } } }
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:marvel_heroes/app/core/exceptions/marvel_exceptions.dart'; import 'package:marvel_heroes/app/modules/marvel_characters/models/character/characters_response_model.dart'; import '../models/comics/comic_model.dart'; part 'marvel_state.freezed.dart'; @freezed abstract class MarvelState with _$MarvelState { const factory MarvelState({required bool isLoading, required bool isLoadingMoreCharacters, @Default(null) CharactersResponseModel? characters, @Default([]) List<ComicModel> comics, MarvelApiExceptions? exception}) = _ComicsState; factory MarvelState.initialState() => const MarvelState(isLoading: false, isLoadingMoreCharacters: false, characters: null, comics: []); factory MarvelState.isLoading(bool isLoading) => MarvelState(isLoading: isLoading, isLoadingMoreCharacters: false, characters: null); factory MarvelState.isLoadingMoreCharacters(bool isLoadingMore) => MarvelState(isLoading: isLoadingMore, isLoadingMoreCharacters: false); factory MarvelState.getAllCharactersResult(CharactersResponseModel? characters) => MarvelState(isLoading: false, isLoadingMoreCharacters: false, characters: characters); factory MarvelState.comicsResult(List<ComicModel> comics) => MarvelState(isLoading: false, isLoadingMoreCharacters: false, comics: comics); factory MarvelState.error(MarvelApiExceptions exception) => MarvelState(isLoading: false, isLoadingMoreCharacters: false, exception: exception); }
// url: https://leetcode.com/problems/reorder-list/ /** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @return {void} Do not return anything, modify head in-place instead. */ // Make an array that contains all of the nodes in order // loop through the array, connecting the left element with the right element, and then connect the right element with the left one // with the length of the array determine the length between the two nodes // handle 3 cases // nodes are the same // set the next node to null // nodes are adjacent // set the next node for the left node to be the right but set the right node's next to be null // nodes are further apart // set the left node next to be the right node, set the right node next to be the node ordered after the left node in the array // return the head var reorderList = function(head) { const nodes = [] let visitedNode = head while(visitedNode){ nodes.push(visitedNode) visitedNode = visitedNode.next } // nodes now has all of the nodes const half = nodes.length / 2 let left let right for(let i = 0; i < half; i++){ left = i right = nodes.length - 1 - i const distanceBetweenNodes = right - left if(distanceBetweenNodes > 0){ nodes[left].next = nodes[right] nodes[right].next = distanceBetweenNodes === 1 ? null : nodes[left + 1] }else{ nodes[left].next = null } } return head };
package com.ms.bf.client.adapter; import ch.qos.logback.classic.spi.ILoggingEvent; import com.fasterxml.jackson.core.JsonProcessingException; import com.ms.bf.client.adapter.kafka.client.KafkaProducerAdapter; import com.ms.bf.client.config.property.KafkaProperty; import com.ms.bf.client.domain.Client; import com.ms.bf.client.config.exception.GenericException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.platform.commons.logging.LoggerFactory; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.support.KafkaHeaders; import org.springframework.messaging.Message; import org.springframework.messaging.MessagingException; import java.util.logging.Logger; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class KafkaProducerAdapterTest { @Mock private KafkaTemplate<String, String> kafkaTemplate; @Mock private KafkaProperty kafkaProperty; @Mock private ObjectMapper objectMapper; @InjectMocks private KafkaProducerAdapter kafkaProducerAdapter; @BeforeEach void setUp() { lenient().when(kafkaProperty.getTopicName()).thenReturn("testTopic"); } @Test void testSendMessage() throws GenericException, JsonProcessingException { Client client = mock(Client.class); when(client.toString()).thenReturn("Client{name='test', accountNumber='123', age=30}"); when(objectMapper.writeValueAsString(client)).thenReturn("{\"name\":\"test\", \"accountNumber\":\"123\", \"age\":30}"); kafkaProducerAdapter.sendMessage(client); verify(kafkaTemplate, times(1)).send(any(Message.class)); } @Test void testSendMessage_JsonProcessingException() throws JsonProcessingException { Client client = mock(Client.class); when(client.toString()).thenReturn("Client{name='test', accountNumber='123', age=30}"); doThrow(JsonProcessingException.class).when(objectMapper).writeValueAsString(client); assertThrows(GenericException.class, () -> { kafkaProducerAdapter.sendMessage(client); }); } @Test void testSendMessage_MessagingException() throws MessagingException, JsonProcessingException { Client client = mock(Client.class); when(client.toString()).thenReturn("Client{name='test', accountNumber='123', age=30}"); when(objectMapper.writeValueAsString(client)).thenReturn("{\"name\":\"test\", \"accountNumber\":\"123\", \"age\":30}"); doThrow(MessagingException.class).when(kafkaTemplate).send(any(Message.class)); assertThrows(GenericException.class, () -> { kafkaProducerAdapter.sendMessage(client); }); } @Test void testSendMessage_LogsSentMessage() throws GenericException, JsonProcessingException { Client client = mock(Client.class); when(client.toString()).thenReturn("Client{name='test', accountNumber='123', age=30}"); when(objectMapper.writeValueAsString(client)).thenReturn("{\"name\":\"test\", \"accountNumber\":\"123\", \"age\":30}"); kafkaProducerAdapter.sendMessage(client); ArgumentCaptor<String> logCaptor = ArgumentCaptor.forClass(String.class); assertTrue(logCaptor.getValue().contains("Sent message value: Client{name='test', accountNumber='123', age=30}")); } }
## a long-long story.... ## Final project - How average senitments changed over time of ALL books # # DS of Unstructured Text Data held by Eduardo Ariño de la Rubia on CEU in 2018 # Tamas Burghard # # # 01 making the list of books # # This script filter a bunch of books from the Gutenberg project (more than 1000!) # AND retrieving the publishing dates from 2 pages. # # scraping is very slow, # # Input: gutenbergR metafiles + scraped info from the web # Output: download_this.feather library(gutenbergr) library(tidyverse) library(stringr) library(urltools) library(rvest) library(feather) rm(list = ls()) authors <- gutenberg_authors %>% filter(deathdate > 1850) # meta: shortlist of interesting books meta <- gutenberg_metadata %>% inner_join(authors) %>% filter(language == "en", has_text == TRUE, !is.na(wikipedia), !str_detect(gutenberg_bookshelf, "hildren"), !str_detect(gutenberg_bookshelf, "Australia"), !str_detect(gutenberg_bookshelf, "United Kingdom"), !str_detect(gutenberg_bookshelf, "Animals"), str_detect(gutenberg_bookshelf, "iction"), str_detect(author, ",") ) %>% mutate(author2 = str_replace(author, "^([0-9A-Za-z]+), ([0-9A-Za-z]+)(\\.|,| |$)([\\.,() 0-9A-Za-z])*", "\\2 \\1") ) # author2: a simpler name, just one name and family name. increases the search rate on web # uncomment this for a basic analysis by author # meta %>% # group_by(wikipedia) %>% # summarise(N = n()) %>% # arrange(desc(N)) ################## helper functions ################################# ## to extract year number from scraped text ## input: messy string from scrape ## output: 4 digit number, starting with 1-2 ## method: extracting from the last 6/12 characters extract_publish <- function(RAW_TEXT_I) { s1 <- str_trunc(RAW_TEXT_I, 6, side = "left", ellipsis = "") min(as.numeric(str_extract_all(s1, "[0-9]{4,4}")), na.rm = TRUE) } extract_publish_openlib <- function(RAW_TEXT_I) { s1 <- str_trunc(RAW_TEXT_I,12, side = "left", ellipsis = "") min(as.numeric(str_extract_all(s1, "[0-9]{4,4}")), na.rm = TRUE) } #############end of helper functions ################################# look_this <- meta # will looking for this list #look_this <- meta %>% sample_n(20) # uncomment this line to try the scraping on a sample ############### Worldcat.org ############################################# ############### getting publish year info, searching for author2 and title # vectorized search url1 <- "https://www.worldcat.org/search?qt=worldcat_org_bks&q=" url2 <- paste0("ti:", url_encode( look_this$title)) url3 <- paste0("+au:", url_encode(look_this$author2)) url4 <- "&qt=advanced&dblist=638" url <- paste0(url1, url2, url3, url4) # composing the search url vector raw_worldcat_download <- tibble(links = url) %>% # do the search scrape mutate( webpages = map(links, read_html)) # this takes a long time, so better break the pipe here #save(raw_worldcat_download, file = "./Final_project/raw_worldcat_download.RData") # feather is not working with this data raw_worldcat_processed <- raw_worldcat_download %>% # get the html text out mutate( nodes = map(webpages, html_nodes, '.itemPublisher')) %>% mutate( text = map(nodes, html_text)) look_this$year_worldcat <- map_dbl(raw_worldcat_processed$text, extract_publish) # call the helper function ################# second method www.openlibrary.org url1 <- "https://openlibrary.org/search?q=" url2 <- paste0("title:", url_encode( look_this$title)) url3 <- paste0("+author:", url_encode(look_this$author2)) url4 <- "&mode=everything" url <- paste0(url1, url2, url3, url4) raw_openlib_download <- tibble(links = url) %>% mutate( webpages = map(links, read_html)) # takes a long time, better break the pipe here #save(raw_openlib_download, file = "./Final_project/raw_openlib_download.RData") raw_openlib_processed <- raw_openlib_download %>% mutate( nodes = map(webpages, html_nodes, '.resultPublisher')) %>% mutate( text = map(nodes, html_text)) look_this$year_openlib <- map_dbl(raw_openlib_processed$text, extract_publish_openlib) # call the helper #write_feather(look_this, "./Final_project/look_this.feather") ## now we have 'look_this' that contains the possible booklist with the metadata #look_this <- read_feather("./Final_project/look_this.feather") # uncomment this to start the script from here # now we merge the two publish dates into one # also compare to the birth / death year of the author yearhelper <- function(birth, death, y1, y2) { birth <- birth + 15 # allow to publish at age 15 death <- death + 5 # until death + 5: exact year when the author wrote those words is important. if (y1 < birth || y1 > death) { # not credible dates y1 <- Inf } if (y2 < birth || y2 > death) { # not credible dates y2 <- Inf } min(y1,y2) # the publish year is the lower of the two scraped } look_this$year <- Inf # ugly for cycle instead of a map with 4 parameters num <- length(look_this$gutenberg_id) for (i in seq(1:num)) { look_this$year[[i]] <- yearhelper(look_this$birthdate[[i]], look_this$deathdate[[i]], look_this$year_openlib[[i]], look_this$year_worldcat[[i]] ) } # now we have the publish date in the year column, we can filter out the books # not matching our year criteria download_this <- look_this %>% filter(year < 1990, year > 1850) write_feather(download_this, "./Final_project/download_this.feather") ### end of this script. continue with 02_download.R
import Vue from 'vue' import VueRouter from 'vue-router' import TripDetails from '../views/TripDetails' Vue.use(VueRouter) const routes = [ // { // path: '/', // name: 'home', // component: HomeView // }, { path: '/about', name: 'about', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue') }, { path:"/TripDetails", name: "TripDetails", component:TripDetails }, { path:"/NewTrip", name:"NewTrip", component:() => import('../views/NewTrip.vue') } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }); export default router
%--- Description ---% % % Filename: generate_hermite_matrix.m % Authors: Ben Adcock, Juan M. Cardenas, Nick Dexter % Part of the paper "A Unified Framework for Learning with Nonlinear Model % Classes from Arbitrary Linear Samples" % % Description: generates a measurement matrix using tensor Hermite % polynomials from an arbitrary multi-index set and collection of sample % points % % Inputs: % I - d x N array of multi-indices % y_grid - m x d array of sample points % % Output: % A - normalized measurement matrix function A = generate_hermite_matrix(I,y_grid) [d,n] = size(I); % get N (number of matrix columns) and d (dimension) m = size(y_grid,1); % get m (number of matrix rows) A = zeros(m,n); % initialize A pmax = max(I(:)); % find maximum polynomial degree for i = 1:m y = y_grid(i,:); % select ith sample point S = hermmat(y',pmax+1); % build A for j = 1:n Sij = zeros(d,1); for l = 1:d Sij(l,1) = S(l,I(l,j)+1); end A(i,j) = prod(Sij); end end % normalize A A = A/sqrt(m); end
import { FormControl, FormLabel, TextField, Button, Typography, } from '@mui/material'; import { CustomContainer } from './styles'; import { Link, useLocation, useNavigate } from 'react-router-dom'; import { useState, ChangeEvent } from 'react'; import toast from 'react-hot-toast'; import { login } from '../../lib/api'; import { useAuth } from '../../hooks/auth/useAuth'; export const Login = () => { const { setAuth } = useAuth(); const navigate = useNavigate(); const location = useLocation(); const from = location.state?.from?.pathname ?? '/'; const [loginUser, setLoginUser] = useState({ email: '', password: '', }); function handleChange( e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>, ) { setLoginUser((prev) => ({ ...prev, [e.target.name]: e.target.value, })); } async function submit() { if (loginUser.password.trim().length < 3 || loginUser.email.length < 2) { return toast.error('Поля заполнены некорректно.'); } const response = await login(loginUser.email, loginUser.password); const accessToken = response?.accessToken; const roles = response?.roles; console.log('Login: accessToken'); console.log(accessToken); console.log('Login: roles'); console.log(roles); console.log('Login: setAuth checking'); console.log(setAuth); if (typeof setAuth === 'function') { console.log('Login: setAuth is function'); setAuth({ roles, accessToken }); navigate(from, { replace: true }); } } return ( <CustomContainer> <Typography variant="h4" mb=".5em" textAlign="center"> Вход </Typography> <FormControl sx={{ marginBottom: '1.5em' }}> <FormLabel>Почта</FormLabel> <TextField type="email" name="email" value={loginUser.email} onChange={handleChange} /> </FormControl> <FormControl sx={{ marginBottom: '1.5em' }}> <FormLabel>Пароль</FormLabel> <TextField type="password" name="password" value={loginUser.password} onChange={handleChange} /> </FormControl> <Typography variant="overline" margin="1em 0"> <Link to="/register">Нет аккаунта?</Link> </Typography> <Button variant="outlined" sx={{ padding: '1em 2em', marginBottom: '2.5em' }} onClick={submit} > Войти </Button> </CustomContainer> ); };
use crate::{helpers::vec_to_led_data, Color, Effect, LedData, LED_SIZE}; use std::{collections::VecDeque, f64::consts::PI}; #[derive(Clone)] pub struct RainbowEffect { iterator: usize, } impl Effect for RainbowEffect { fn new() -> Self { Self { iterator: 0 } } fn update(&mut self) -> anyhow::Result<Option<LedData>> { let mut data: VecDeque<Color> = VecDeque::with_capacity(LED_SIZE); for i in 0..LED_SIZE { let phase_r = i as f64 * 2.0 * PI / LED_SIZE as f64; let phase_g = (i as f64 * 2.0 * PI / LED_SIZE as f64) + (2.0 * PI / 3.0); let phase_b = (i as f64 * 2.0 * PI / LED_SIZE as f64) + (4.0 * PI / 3.0); let r = ((phase_r).sin() * 127.0 + 128.0) as u8; let g = ((phase_g).sin() * 127.0 + 128.0) as u8; let b = ((phase_b).sin() * 127.0 + 128.0) as u8; data.push_back(Color::new(r, g, b)); } data.rotate_right(self.iterator); let data = Vec::from(data); self.iterator += 1; if self.iterator >= data.len() { self.iterator = 0; } Ok(Some(vec_to_led_data(data))) } }
<?php namespace App\Controller; use App\Repository\CommentRepository; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; class GuestbookController extends AbstractController { #[Route('/guestbook', name: 'app_guestbook')] public function guestbook(Request $request, CommentRepository $commentRepository): Response { $limit = 5; // Le nombre de commentaires par page $page = (int) $request->query->get('page', 1); // Récupère la page actuelle ou utilise la première page par défaut $totalComments = count($commentRepository->findAll()); $lastPage = ceil($totalComments / $limit); $offset = ($page - 1) * $limit; $comments = $commentRepository->findBy([], [], $limit, $offset); return $this->render('guestbook/guestbook.html.twig', [ 'comments' => $comments, 'lastPage' => $lastPage, 'currentPage' => $page, ]); } }
<?php declare(strict_types=1); /* * The MIT License (MIT) * * Copyright (c) 2014-2021 Spomky-Labs * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ namespace Akeeba\Passwordless\Webauthn; use Akeeba\Passwordless\Assert\Assertion; use Akeeba\Passwordless\CBOR\Stream; use function Akeeba\Passwordless\Safe\fclose; use function Akeeba\Passwordless\Safe\fopen; use function Akeeba\Passwordless\Safe\fread; use function Akeeba\Passwordless\Safe\fwrite; use function Akeeba\Passwordless\Safe\rewind; use function Akeeba\Passwordless\Safe\sprintf; final class StringStream implements \Akeeba\Passwordless\CBOR\Stream { /** * @var resource */ private $data; /** * @var int */ private $length; /** * @var int */ private $totalRead = 0; public function __construct(string $data) { $this->length = mb_strlen($data, '8bit'); $resource = \Akeeba\Passwordless\Safe\fopen('php://memory', 'rb+'); \Akeeba\Passwordless\Safe\fwrite($resource, $data); \Akeeba\Passwordless\Safe\rewind($resource); $this->data = $resource; } public function read(int $length): string { if (0 === $length) { return ''; } $read = \Akeeba\Passwordless\Safe\fread($this->data, $length); $bytesRead = mb_strlen($read, '8bit'); \Akeeba\Passwordless\Assert\Assertion::length($read, $length, \Akeeba\Passwordless\Safe\sprintf('Out of range. Expected: %d, read: %d.', $length, $bytesRead), null, '8bit'); $this->totalRead += $bytesRead; return $read; } public function close(): void { \Akeeba\Passwordless\Safe\fclose($this->data); } public function isEOF(): bool { return $this->totalRead === $this->length; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300&display=swap" rel="stylesheet"> </head> <body> <header> <h1 id="title">freeCodeCamp Survey Form</h1> <p id="description">Thank you for taking the time to help us improve the platform</p> </header> <main> <form action="https://www.example.com" id="survey-form"> <fieldset> <div> <label for="name" id="name-label">Name <input type="text" name="name" id="name" placeholder="Enter your name" class="width" required></label> </div> <div> <label for="email" id="email-label">Email <input type="email" name="email" id="email" placeholder="Enter your Email" class="width" required></label> </div> <div> <label for="age" id="number-label">Age <span>(optional)</span> <input type="number" name="age" id="number" min="10" max="99" class="width" placeholder="Age"></label> </div> <div class="desc"> <label for="description">Which option best describes your current role? <select name="description" id="dropdown"> <option value="" disabled selected>Select current role</option> <option value="1">Student</option> <option value="2">Full Time Job</option> <option value="3">Full TIme Learner</option> <option value="4">Prefer not to say</option> <option value="5">Other</option> </select> </label> </div> <div class="recommend"> Would you recommend freeCodeCamp to a friend? <label for="recommend" class="incline"> <input type="radio" name="recommend" class="inline" value="definitely"> Definitely </label> <label for="recommend" class="incline"> <input type="radio" name="recommend" class="inline" value="maybe"> Maybe </label> <label for="recommend" class="incline"> <input type="radio" name="recommend" class="inline" value="not sure"> Not Sure </label> </div> <div class="features"> <label for="feat">What is your favorite feature of freeCodeCamp? <select name="feat" id="feat"> <option value="" disabled selected>Select an option</option> <option value="1">Challenges</option> <option value="2">Projects</option> <option value="3">Community</option> <option value="4">Open Source</option> </select> </label> </div> <div class="improvements"> What would you like to see improved? <span>(Check all that apply)</span> <label for="checkbox" class="incline"><input type="checkbox" name="checkbox" value="front-end projects" class="inline"> Front-end Projects </label> <label for="checkbox" class="incline"><input type="checkbox" name="checkbox" value="back-end projects" class="inline"> Back-end Projects </label> <label for="checkbox" class="incline"><input type="checkbox" name="checkbox" value="data visualisation" class="inline"> Data Visualization </label> <label for="checkbox" class="incline"><input type="checkbox" name="checkbox" value="challenges" class="inline"> Challenges </label> <label for="checkbox" class="incline"><input type="checkbox" name="checkbox" value="open source community" class="inline"> Open Source Community </label> <label for="checkbox" class="incline"><input type="checkbox" name="checkbox" value="gitter help rooms" class="inline"> Gitter help rooms </label> <label for="checkbox" class="incline"><input type="checkbox" name="checkbox" value="videos" class="inline"> Videos </label> <label for="checkbox" class="incline"><input type="checkbox" name="checkbox" value="city meetups" class="inline"> City Meetups </label> <label for="checkbox" class="incline"><input type="checkbox" name="checkbox" value="wiki" class="inline"> Wiki </label> <label for="checkbox" class="incline"><input type="checkbox" name="checkbox" value="forum" class="inline"> Forum </label> <label for="checkbox" class="incline"><input type="checkbox" name="checkbox" value="additional courses" class="inline"> Additional Courses </label> </div> <div class="suggest"> <label for="suggestions">Any comments or suggestions? <textarea name="suggestions" id="textarea" cols="80" rows="6" placeholder="Enter your comment here..."></textarea> </label> </div> <div class="submit"> <input type="submit" value="Submit" id="submit" /> </div> </fieldset> </form> </main> </body> </html>
package chapter2.item3.min; public class Elvis { public static Elvis instance; public static Elvis getInstance(){ if(instance == null){ instance = new Elvis(); } return instance; } /** * 장점 * 구현 간결 싱글턴입을 api 들어냄 * 단점 * 싱글턴을 사용하는 클라이언트가 테스트 하기 어려움 * 역질렬화시 새로운 인스턴스 생길 수 있음. public static final Elvis INSTANCE = new Elvis(); private Elvis(){ }*/ /** * 제너릭 싱글턴 팩터링 만들 수 있다. * 단점 스레드 세이프 하지 않음 private static final Elvis INSTANCE = new Elvis(); private Elvis(){} public static Elvis getInstance(){ return INSTANCE; }*/ /* 제너릭한 싱글톤 패턴을 구현 가능 public class GenericSingleton<T> { public static final GenericSingleton<?> INSTANCE = new GenericSingleton<>(); private GenericSingleton() { } public static <T> GenericSingleton<T> getInstance() { return (GenericSingleton<T>) INSTANCE; } public boolean send( T message ) { // blah~ blah~ return true; } }*/ }
# BVI-VFI: A Video Quality Database for Video Frame Interpolation ### Duolikun Danier, Fan Zhang, David Bull ### IEEE Transactions on Image Processing (TIP) [Project](https://danier97.github.io/BVI-VFI-database) | [Database](https://forms.office.com/Pages/ResponsePage.aspx?id=MH_ksn3NTkql2rGM8aQVG1fDz7azbERMp_0LZtGJZ19UQlFMREhWU0E3QzRVMkYyT0VFTUg3T041Qy4u) | [arXiv](https://arxiv.org/abs/2210.00823) ## Updates **[2023.10.21]** We added DMOS scores obtained via the subject screening process recommened by [ITU-T P.910](https://www.itu.int/ITU-T/recommendations/rec.aspx?rec=15005&lang=en). See the Description section below for details. ## Abstract Video frame interpolation (VFI) is a fundamental research topic in video processing, which is currently attracting increased attention across the research community. While the development of more advanced VFI algorithms has been extensively researched, there remains little understanding of how humans perceive the quality of interpolated content and how well existing objective quality assessment methods perform when measuring the perceived quality. In order to narrow this research gap, we have developed a new video quality database named BVI-VFI, which contains 540 distorted sequences generated by applying five commonly used VFI algorithms to 36 diverse source videos with various spatial resolutions and frame rates. We collected more than 10,800 quality ratings for these videos through a large scale subjective study involving 189 human subjects. Based on the collected subjective scores, we further analysed the influence of VFI algorithms and frame rates on the perceptual quality of interpolated videos. Moreover, we benchmarked the performance of 33 classic and state-of-the-art objective image/video quality metrics on the new database, and demonstrated the urgent requirement for more accurate bespoke quality assessment methods for VFI. ## TL; DR - A video database with subjective quality labels was collected. - Analysis on quality labels reveals that - Recent deep learning-based VFI methods have a clear advantage over simple frame repeating and averating, but the performance gap narrows at frame rate increases. - Simple frame repeating and averating can outperform DL methods on dynamic textures (rapid and irregular motion). - Motion magnitude and complexity jointly impacts VFI difficulty. - Higher spatial resolution also makes VFI more challenging. - 33 existing image/video quality assessment methods were benchmarked, and best performance (SRCC=0.7) was achieved by FAST. - There is a need for a better quality evaluator for VFI, and the proposed database can be used for development and benchmarking of them. ## Downloading the database Please fill in this [registration form](https://forms.office.com/Pages/ResponsePage.aspx?id=MH_ksn3NTkql2rGM8aQVG1fDz7azbERMp_0LZtGJZ19UQlFMREhWU0E3QzRVMkYyT0VFTUg3T041Qy4u) to get access to the download link. I'll then share the download link ASAP. **Note:** if you have filled in the form before and been given access to the previous version of the BVI-VFI database, you will also be able to access the new larger database. There is no need to register again. ## Description ### Videos The BVI-VFI database contains 108 reference and 540 distorted sequences, as well as the differential subjective scores for all the distorted videos. The .mp4 files contained are compressed with H.264 (libx264) under lossless mode (crf=0). The naming of the files are as follows: ``` <seq name>_<spatial resolution>_<frame rate>_<VFI method>.mp4 ``` Files ending with "_GT.mp4" are the reference sequences. ### Subjective data We provide raw subjective data and post-processed DMOS scores obtained according to two different standards: ITU [BT-500](https://www.itu.int/rec/R-REC-BT.500) and [P.910](https://www.itu.int/ITU-T/recommendations/rec.aspx?rec=15005&lang=en). These subjective data are provided in .json format. #### P.910 - `all_data_raw.json`: raw scores collected from subjects, including scores given to both reference and distorted videos. - `all_dmos_p910.json`: the DMOS values obtained following the P.910 subject screening method (see the standard and paper for more details). - `all_dmosstd_p910.json`: the standard deviations of the DMOS obtaiend via P.910. #### BT-500 - `all_diff_raw.json`: the differential scores calculated for all the judgements of all users. Each score = (score assigned by the participant to current reference) - (score assigned by the participant to current distorted sequence). - `all_z_scores.json`: the differential scores normalised over the scores given by each user (see paper for more details). - `DMOS_XXXXp.json`: the DMOS scores computed for each distorted sequence. ## Copyright disclaimer The sequences contained in the BVI-VFI dataset are obtained from various sources, including - [BVI-HFR dataset](https://data.bris.ac.uk/data/dataset/k8bfn0qsj9fs1rwnc2x75z6t7) - [LIVE-YT-HFR dataset](https://live.ece.utexas.edu/research/LIVE_YT_HFR/LIVE_YT_HFR/index.html) This database has been compiled by the University of Bristol, Bristol, UK. All intellectual property rights remain with the University of Bristol. The dataset should only be used for academic purpose. This copyright and permission notice shall be duplicated whenever the data is copied. The University of Bristol makes no warranties with respect to the material and expressly disclaims any warranties regarding its fitness for any purpose. Unless the above conditions are agreed to by the recipient, no permission is granted for any use and copying of the data. By using the database and sequences, the user agrees to the conditions of this copyright and disclaimer. ## Citation ``` @misc{danier2022bvi, title={BVI-VFI: A Video Quality Database for Video Frame Interpolation}, author={Duolikun Danier and Fan Zhang and David Bull}, year={2022}, eprint={2210.00823}, archivePrefix={arXiv}, primaryClass={eess.IV} } @misc{danier2022subjective, title={A Subjective Quality Study for Video Frame Interpolation}, author={Duolikun Danier and Fan Zhang and David Bull}, year={2022}, eprint={2202.07727}, archivePrefix={arXiv}, primaryClass={eess.IV} } ```
package com.care.sekki.recipeboard; import java.io.File; import java.io.FileInputStream; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.ui.Model; import org.springframework.util.FileCopyUtils; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import com.care.sekki.common.PageService; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; @Service public class RecipeBoardService { @Autowired private RecipeBoardMapper recipeboardMapper; @Autowired private HttpSession session; public void recipeboardForm(String cp, Model model) { int currentPage = 1; try{ currentPage = Integer.parseInt(cp); }catch(Exception e){ currentPage = 1; } int pageBlock = 3; // 한 페이지에 보일 데이터의 수 int end = pageBlock * currentPage; // 테이블에서 가져올 마지막 행번호 int begin = end - pageBlock + 1; // 테이블에서 가져올 시작 행번호 ArrayList<RecipeBoardDTO> boards = recipeboardMapper.recipeboardForm(begin, end); int totalCount = recipeboardMapper.count(); String url = "recipeboardForm.jsp?currentPage="; String result = PageService.printPage(url, currentPage, totalCount, pageBlock); model.addAttribute("boards", boards); model.addAttribute("result", result); model.addAttribute("currentPage", currentPage); } public String recipeboardWriteProc(MultipartHttpServletRequest multi) { String id = (String)session.getAttribute("id"); if(id == null || id.isEmpty()) { return "로그인"; } RecipeBoardDTO recipeboard = new RecipeBoardDTO(); recipeboard.setId(id); recipeboard.setTitle(multi.getParameter("title")); recipeboard.setContent(multi.getParameter("content")); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); recipeboard.setWriteDate(sdf.format(new Date())); recipeboard.setFileName(""); if(recipeboard.getTitle() == null || recipeboard.getTitle().isEmpty()) { return "제목을 입력하세요."; } MultipartFile file = multi.getFile("upfile"); String fileName = file.getOriginalFilename(); if(file.getSize() != 0) { // 파일의 중복을 해결하기 위해 시간의 데이터를 파일이름으로 구성함. sdf = new SimpleDateFormat("yyyyMMddHHmmss-"); Calendar cal = Calendar.getInstance(); fileName = sdf.format(cal.getTime()) + fileName; recipeboard.setFileName(fileName); // 업로드 파일 저장 경로 // ubuntu@ip-172-31-32-35:~$ sudo mkdir /opt/tomcat/tomcat-10/webapps/upload // ubuntu@ip-172-31-32-35:~$ sudo chown -RH tomcat: /opt/tomcat/tomcat-10/webapps/upload String fileLocation = "/opt/tomcat/tomcat-10/webapps/upload/"; File save = new File(fileLocation + fileName); try { // 서버가 저장한 업로드 파일은 임시저장경로에 있는데 개발자가 원하는 경로로 이동 file.transferTo(save); } catch (Exception e) { e.printStackTrace(); } } recipeboardMapper.recipeboardWriteProc(recipeboard); return "게시글 작성 완료"; } public RecipeBoardDTO recipeboardContent(String n) { int no = 0; try{ no = Integer.parseInt(n); }catch(Exception e){ return null; } RecipeBoardDTO recipeboard = recipeboardMapper.recipeboardContent(no); if(recipeboard == null) return null; recipeboard.setHits(recipeboard.getHits()+1); incHit(recipeboard.getNo()); System.out.println("board.getFileName() : " + recipeboard.getFileName()); System.out.println("board.getFileName() : " + recipeboard.getFileName().isEmpty()); if(recipeboard.getFileName() != null && recipeboard.getFileName().isEmpty() == false) { String fn = recipeboard.getFileName(); String[] fileName = fn.split("-", 2); recipeboard.setFileName(fileName[1]); } return recipeboard; } public void incHit(int no) { recipeboardMapper.incHit(no); } public boolean recipeboardDownload(String n, HttpServletResponse res) { int no = 0; try{ no = Integer.parseInt(n); }catch(Exception e){ return false; } String fileName = recipeboardMapper.recipeboardDownload(no); if(fileName == null) return false; String location = "/opt/tomcat/tomcat-10/webapps/upload/"; File file = new File(location + fileName); try { String[] original = fileName.split("-", 2); res.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(original[1], "UTF-8")); FileInputStream fis = new FileInputStream(file); FileCopyUtils.copy(fis, res.getOutputStream()); fis.close(); } catch (Exception e) { e.printStackTrace(); } return true; } public RecipeBoardDTO recipeboardModify(String n) { int no = 0; try{ no = Integer.parseInt(n); }catch(Exception e){ return null; } RecipeBoardDTO recipeboard = recipeboardMapper.recipeboardContent(no); if(recipeboard == null) return null; if(recipeboard.getFileName() != null && recipeboard.getFileName().isEmpty() == false) { String fn = recipeboard.getFileName(); String[] fileName = fn.split("-", 2); recipeboard.setFileName(fileName[1]); } return recipeboard; } public String recipeboardModifyProc(RecipeBoardDTO recipeboard) { if(recipeboard.getTitle() == null || recipeboard.getTitle().isEmpty()) return "제목을 입력하세요."; recipeboardMapper.recipeboardModifyProc(recipeboard); return "게시글 수정 완료"; } public String recipeboardDeleteProc(String n) { String id = (String)session.getAttribute("id"); if(id == null || id.isEmpty()) { return "로그인"; } int no = 0; try{ no = Integer.parseInt(n); }catch(Exception e){ return "게시글 번호에 문제가 생겼습니다."; } RecipeBoardDTO recipeboard = recipeboardMapper.recipeboardContent(no); if(recipeboard == null) return "게시글 번호에 문제가 생겼습니다."; if(id.equals(recipeboard.getId()) == false) return "작성자만 삭제 할 수 있습니다."; recipeboardMapper.recipeboardDeleteProc(no); String path = "/opt/tomcat/tomcat-10/webapps/upload/" + recipeboard.getFileName(); File file = new File(path); if(file.exists() == true) { file.delete(); } return "게시글 삭제 완료"; } }
/* * Copyright 2023 CloudWeGo Authors * * 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 shmipc // Monitor could emit some metrics with periodically type Monitor interface { // OnEmitSessionMetrics was called by Session with periodically. OnEmitSessionMetrics(PerformanceMetrics, StabilityMetrics, ShareMemoryMetrics, *Session) // flush metrics Flush() error } type stats struct { allocShmErrorCount uint64 fallbackWriteCount uint64 fallbackReadCount uint64 eventConnErrorCount uint64 queueFullErrorCount uint64 recvPollingEventCount uint64 sendPollingEventCount uint64 outFlowBytes uint64 inFlowBytes uint64 hotRestartSuccessCount uint64 hotRestartErrorCount uint64 } //PerformanceMetrics is the metrics about performance type PerformanceMetrics struct { ReceiveSyncEventCount uint64 //the SyncEvent count that session had received SendSyncEventCount uint64 //the SyncEvent count that session had sent OutFlowBytes uint64 //the out flow in bytes that session had sent InFlowBytes uint64 //the in flow in bytes that session had receive SendQueueCount uint64 //the pending count of send queue ReceiveQueueCount uint64 //the pending count of receive queue } //StabilityMetrics is the metrics about stability type StabilityMetrics struct { AllocShmErrorCount uint64 //the error count of allocating share memory FallbackWriteCount uint64 //the count of the fallback data write to unix/tcp connection FallbackReadCount uint64 //the error count of receiving fallback data from unix/tcp connection every period //the error count of unix/tcp connection //which usually happened in that the peer's process exit(crashed or other reason) EventConnErrorCount uint64 //the error count due to the IO-Queue(SendQueue or ReceiveQueue) is full //which usually happened in that the peer was busy QueueFullErrorCount uint64 //current all active stream count ActiveStreamCount uint64 //the successful count of hot restart HotRestartSuccessCount uint64 //the failed count of hot restart HotRestartErrorCount uint64 } //ShareMemoryMetrics is the metrics about share memory's status type ShareMemoryMetrics struct { CapacityOfShareMemoryInBytes uint64 //capacity of all share memory AllInUsedShareMemoryInBytes uint64 //current in-used share memory }
from flask import Flask, request, jsonify from pymongo import MongoClient from datetime import datetime from bson import ObjectId import os import re from gevent.pywsgi import WSGIServer app = Flask(__name__) # Configura la conexión a MongoDB mongo_uri = os.getenv("MONGO_URI") client = MongoClient(mongo_uri) db = client['dbPagos'] # Reemplaza 'tu_base_de_datos' con el nombre de tu base de datos collection = db['Pagos'] # Reemplaza 'tus_datos' con el nombre de tu colección # Ruta para almacenar datos @app.route('/guardar_datos', methods=['POST']) def guardar_datos(): data = request.json # Asegúrate de que los campos necesarios estén presentes en la solicitud required_fields = ['Referencia','Fecha', 'Detalle'] if not all(field in data for field in required_fields): return jsonify({'error': 'Campos requeridos incompletos'}), 400 # Inserta los datos en la base de datos result = collection.insert_one(data) # Retorna la ID del documento recién insertado return jsonify({'message': 'Datos almacenados con éxito', 'id': str(result.inserted_id)}), 201 # Ruta para buscar por Referencia @app.route('/buscar_por_referencia', methods=['POST']) def buscar_por_referencia(): data = request.json referencia = data.get('Referencia') print(referencia) if not referencia: return jsonify({'error': 'Se requiere el parámetro "referencia"'}), 400 # Realiza la búsqueda en la base de datos por el campo "Referencia" result = list(collection.find({'Referencia': referencia})) print(result) # Convierte los ObjectId a cadenas antes de serializar a JSON for item in result: item['_id'] = str(item['_id']) return jsonify({'resultados': result}) def extract_numeric_value(monto_with_symbol): match = re.search(r'\d+(\.\d+)?', monto_with_symbol) return float(match.group()) if match else 0.0 # Ruta para listar registros por rango de fechas y calcular la sumatoria del campo Monto @app.route('/listar_por_fechas', methods=['GET']) def listar_por_fechas(): fecha_inicio = request.args.get('fecha_inicio') fecha_fin = request.args.get('fecha_fin') if not fecha_inicio or not fecha_fin: return jsonify({'error': 'Se requieren los parámetros "fecha_inicio" y "fecha_fin"'}), 400 fecha_inicio = datetime.strptime(fecha_inicio, '%Y-%m-%d') fecha_fin = datetime.strptime(fecha_fin, '%Y-%m-%d') # Realiza la búsqueda en la base de datos por el rango de fechas result = list(collection.find({'Fecha': {'$gte': fecha_inicio, '$lte': fecha_fin}})) # Calcula la sumatoria del campo Monto #total_monto = sum(item['Monto'] for item in result) total_monto = sum(extract_numeric_value(item.get('Detalle', {}).get('Monto', '')) for item in result) total_comision = 0 numpagos = 0 # Convierte los ObjectId a cadenas antes de serializar a JSON for item in result: item['_id'] = str(item['_id']) detalle = item.get('Detalle') if detalle.get('TransID'): total_comision += 10 else: total_comision +=15 numpagos = len(result) return jsonify({'resultados': result, 'monto': total_monto,'comision':total_comision, 'pagos': numpagos}) if __name__ == '__main__': http_server = WSGIServer(("0.0.0.0",8080), app) http_server.serve_forever()
// ======== Module Imports ======== // import {dom, domProduct} from '../dom.js'; import { singleProductUrl } from '../data.js'; import { initTheme,toggleTheme } from '../darkMode.js' import { initStartingData } from '../fillStartingData.js' import { toggleNavListeners } from '../toggleSidebar.js'; import {toggleCartListeners} from '../cart/toggleCart.js'; import { formatPrice, getParameterValue } from '../utils.js'; import { addToCart, initCart } from '../cart/setupCart.js'; // Init App document.addEventListener('DOMContentLoaded', initApp) // Functions async function initApp() { initStartingData(); initTheme(); toggleNavListeners(); toggleCartListeners(); initCart(); const productId = getProductId(); const singleProductData = await fetchProduct(productId); if (singleProductData) { displayProduct(singleProductData); loadAddToCartListener(productId); } } async function fetchProduct(id) { try { const response = await fetch(`${singleProductUrl}/?id=${id}`); if (response.status>=200 && response.status <=299) { const data = await response.json(); hideLoading(); return data; } else { domProduct.center.innerHTML = ` <div class="single-product-error"> <h3 class="error">Sorry, something went wrong.</h3> <a href="index.html" class="btn">Back Home</a> </div> ` } } catch(err) { console.log(err); } hideLoading(); } function displayProduct(productData) { const {id, fields} = productData; const {name, company, price, colors, description} = fields; const image = fields.image[0].thumbnails.large.url; document.title = `${name.toUpperCase()} | Comfy`; domProduct.pageTitle.textContent = `Home / ${name}`; domProduct.productImg.src = image; domProduct.productTitle.textContent = name; domProduct.company.textContent = `by ${company}`; domProduct.price.textContent = formatPrice(price); domProduct.desc.textContent = description; // colors colors.forEach(color => { const span = document.createElement('span'); span.classList.add('product-color'); span.style.backgroundColor = color; domProduct.colors.appendChild(span); }) } function hideLoading() { domProduct.pageLoading.style.display = 'none'; } function getProductId() { const id = getParameterValue('id'); return id; } function loadAddToCartListener(id) { domProduct.cartBtn.addEventListener('click', () => { addToCart(id); }) }
##### 消息队列的作用是啥 1. 服务解耦,生产者和消费者的解耦 2. 削峰填谷 3. 可以持久化,数据也可以保存下来 4. 一定程度起到了限流的作用 ##### kafka名词解释 生产者:消息的产生方 消费者:消息的消费方 broker:kafka服务器,负责接受消息,持久化消息,提供消息给消费者 topic:主题 Partition:分区,一个topic下有m个分区,每个分区是一组有序的消息日志,分区编号从0开始 Replica:副本,备份机制,一个partition可以有多个副本,不同副本分布在不同的broker上,但是副本只可以有一个 领导者副本,其他都是追随者副本 TPS: 消费者吞吐量 Consumer Group:消费者组,多个消费者组成的一个逻辑概念,一条消息,一个组只能有一个消费者消费 Consumer Offset:哪个消费者 消费哪个消息的 哪个分区的 什么位置。 重平衡:Rebalance。消费者组内某个消费者实例挂掉后,其他消费者实例自动重新分配订阅主题分区的过程。Rebalance 是 Kafka 消费者端实现高可用的重要手段。 至此我们能够完整地串联起 Kafka 的三层消息架构: 第一层是主题层,每个主题可以配置 M 个分区,而每个分区又可以配置 N 个副本。 第二层是分区层,每个分区的 N 个副本中只能有一个充当领导者角色,对外提供服务;其他 N-1 个副本是追随者副本,只是提供数据冗余之用。 第三层是消息层,分区中包含若干条消息,每条消息的位移从 0 开始,依次递增。最后,客户端程序只能与分区的领导者副本进行交互。 ##### Kafka架构可以简单说下? kafka主要 由多个broker组成的集群,每个broker下面可以容纳多个topic,每个topic下面会细分多个分区,从0开始,但并不是所有分区都在一个机器上面,每个分区又有多个备份,备份中分主从备份,主从备份也是分布在多个broker上,从而保证了消息数据的不丢失。consumer发送消息到 某个topic下,根据分区算法自动发送到某个分区,消费者则从某个broker上的某个分区开始主动拉取消息发送。 ##### kafka高可用是怎么做的 kafka高可用主要是得益于他的架构设计,分区的多副本设计,一个分区下会有多个副本,其中会有一个leader副本,其他是follower副本,当某个broker挂掉以后,如果broker上的follower 宕机了,那么不影响,因为kafka只会跟leader副本交互,如果leader副本宕机了,那剩下的所有的副本会在zk的帮助下选举出一个新的leader,相当于把故障转移了,而kafka设计的leader和follower之间是数据同步的,相当于冗余备份。通过这种方式kafka达到了数据备份, 故障转移 + 高可用。 另外一方面,kafka的ack参数也确保了数据的不丢失,也是可以帮助到高可用。kafka把所有的副本 leader 和 follower 只要是有效在同步数据,那会放在ISR的集合中,当发送消息的时候 ack=0,表示只要producer发送成功了,那消息就是发送成功了 ack=1,表示只要producer 发送消息成功,并且leader 落盘了,那就是发送成功了,默认配置 Ack = all,表是不仅leader要落盘,还是ISR中其他follower也落盘才算发送成功。 所以通过这种配置来保证数据不丢失,高可用,但是也不是100%有效的,如果只有ISR里只有一个leader 没follower 该丢失还是要丢失。 ##### kafka副本的好处是啥? 正常副本: 1. 数据备份,数据冗余 2. 提供了更高的集群伸缩性,可以扩展机器来提高读写性能,横向扩展 3. 通过把副本数据放在离用户更近的地方,来降低数据延迟 kafka的副本 1. 数据备份,数据冗余,高可用。 所谓副本本质就是一个只能追加写消息的提交日志。根据 Kafka 副本机制的定义,同一个分区下的所有副本保存有相同的消息序列,这些副本分散保存在不同的 Broker 上,从而能够对抗部分 Broker 宕机带来的数据不可用。 ##### Kafka 为什么 follower副本不提供服务 1. 避免数据延迟,写的数据立刻可见 2. 数据延迟带来的 consumer 消费同一个 partition消息可能会有 丢失 的问题。 ##### ISR 如何定义,条件是啥? 1. 有参数确认,默认 follower 落后 leader 10秒就 不算了,10s以内 还在ISR内。 ISR会动态收缩扩容 ##### 什么是UnClean选举? 副本全挂掉了,必须要选举一个新的副本,但是ISR里又没有副本了,只能在非ISR副本里选举,叫做unclean选举。有参数配置控制。 开启 就相当于 提高了可用性,但是牺牲了 数据一致性, 关闭就相当于 牺牲了可用性,但是可以保障数据一致性。等待leader恢复 ##### Kafka如何保障消息不丢失? 1. producer端通过acks =all 来保障消息的不丢失,或者代码里 使用 send(message, callback) 来接收发送失败的 callback 2. consumer段如果是多线程消费消息的话,最好手动提交offerset,否则容易导致重复消费数据,或者消费失败数据。 ##### Kafka消息的可靠性保障是什么 ? 所谓的消息交付可靠性保障,是指 Kafka 对 Producer 和 Consumer 要处理的消息提供什么样的承诺。常见的承诺有以下三种: - 最多一次(at most once):消息可能会丢失,但绝不会被重复发送。 - 至少一次(at least once):消息不会丢失,但有可能被重复发送。 - 精确一次(exactly once):消息不会丢失,也不会被重复发送。 Kafka默认提供交付可靠性保障是至少一次。 为什么默认是至少一次,因为1、至少一次实现起来不复杂,2、consumer 保持幂等比较简单 3、事务producer 机制复杂。 Kafka消息交付可靠性保障以及精确处理一次语义通过两种机制来实现的:冥等性(Idempotence)和事务(Transaction)。 幂等性主要解决的是 同一个partition下的同一个分区可以做到 精确一次不重复。 ###### 幂等性原理: producer启动的时候会有一个pid,partion,以及每次发消息有个 sequence num,每发一个消息 自增。这三者组成了一个唯一键,发送以后producer 会判断是否已发送,已发送那就不再发了,这个是producer的幂等性。 每次producer 重启后 pid会变。 类似地,Broker 端也会为每个`<PID, Topic, Partition>`维护一个序号,并且每次 Commit 一条消息时将其对应序号递增。对于接收的每条消息,如果其序号比 Broker 维护的序号(即最后一次 Commit 的消息的序号)大一,则 Broker 会接受它,否则将其丢弃: - 如果消息序号比 Broker 维护的序号大一以上,说明中间有数据尚未写入,也即乱序,此时 Broker 拒绝该消息,Producer 抛出`InvalidSequenceNumber` - 如果消息序号小于等于 Broker 维护的序号,说明该消息已被保存,即为重复消息,Broker 直接丢弃该消息,Producer 抛出`DuplicateSequenceNumber` 上述设计解决了 0.11.0.0 之前版本中的两个问题: - Broker 保存消息后,发送 ACK 前宕机,Producer 认为消息未发送成功并重试,造成数据重复 - 前一条消息发送失败,后一条消息发送成功,前一条消息重试后成功,造成数据乱序 ###### 事务原理 kafka事务能够保证将消息原子性地写入到多个分区中。这批消息要么全部写入成功,要么全部失败。另外,事务型 Producer 也不惧进程的重启。Producer 重启回来后,Kafka 依然保证它们发送消息的精确一次处理。 ![CleanShot 2023-03-18 at 02.07.35@2x](/Users/jazz/Library/Application Support/CleanShot/media/media_CV7dZF0Gf8/CleanShot 2023-03-18 at [email protected]) kafka解决事务的原理核心: 2PC 引入了 事务协调器的组件帮助完成分布式事务。 1. 每个broker都会有个事务协调器。启动的时候,producer 会跟 事务协调器要一个pid,重启后pid也是相同的。 2. producer开启事务,发送消息以后,消息会打上事务的标,同时也会告诉协调器 我向那个partion里发 3. 协调器收到commit 或者abort消息,在内置 topic _transaction_state 频道里 发送消息询问对应的broker ,消息是否落盘。 4. 对应broker的topic 收到消息后确认是否落盘,落盘成功则 发送成功消息,否则失败 5. 事务协调器收到 成功/失败消息后,反馈 producer 事务成功还是失败 分布式事务流程就这样。 ##### kafka consumer是多线程的还是单线程的? 老版本有多线程的consumer,新版本单线程,也有多线程的解决方案。consumer实例是线程不安全的,共享会报错,但是有api可以多个线程唤醒操作,单线程优点 1. 代码逻辑简单 2. 移植到其他语言方便 3. 把消息消费多线程的选择 留给使用者 多线程方案主要两种 1. 每个线程自己的consumer 2. 业务消费代码使用多线程,然后手动commit。 优缺点比较 ![](https://static001.geekbang.org/resource/image/84/0c/84dc0edb73f203b55808b33ca004670c.jpg?wh=3927*1716) ##### kafka如何保障消息的顺序性 顺序性包括局部有序和全局有序 全局有序:不支持,只能通过 只设置一个partion来实现全局有序,退化成局部有序。 局部有序:业务key 来实现partion key的逻辑就可以了。例如:Topic消息是订单的流水表,包含订单orderId,业务要求同一个orderId的消息需要按照生产顺序进行消费。 重试对于消息顺序性是有影响的,比如 producer 发送了 A ,B 2个消息,A发送失败了,B成功了,然后A重试,但是broker上是先收到了B再收到了A,正确顺序应该是AB。 解决方案: 1. 有个参数,broker响应producer ack之前 允许发送多少消息,设置为1 则是一次就发一个消息,然后ack才另外发一个消息。 max.in.flight.requests.per.connection = 1 2. max.in.flight.requests.per.connection =1会严重影响性能,那只能在consumer段做业务 包容,消费到这种错误的BA消息顺序 然后报警,打标,重试。 ##### 消息堆积怎么解决 1. 确认业务逻辑是否 耗时,比较耗时的 那发的也要注意,或者纯异步 保存到数据库里处理 2. 不耗时,是否是 producer过快 还是 comsumer 过慢,多线程处理 ##### 什么是Kafka的重平衡? consumer 重平衡 就是重新分配consumer的过程。为了尽量达到所有consumer 数据消费量 压力一致。 重平衡触发的三个条件 - 组成员数量发生变化。 - 订阅主题数量发生变化。 - 订阅主题的分区数发生变化。 重平衡主要靠 consumer之间的心跳来进行通知,流程如下 1. 新增consumer 想 broker的 协调者发送消息,需要假如 consumer group 2. broker 通知所有的consumer 需要重平衡 3. 所有新的broker 发送消息告诉 协调者 我需要加入xx consumer group 4. 协调者 选出最早的一个 发送加入 group请求的 consumer 5. 协调者把 所有consumer 消费的信息 以及topic 信息全部发送给 leader consumer 6. leader consumer 把 重新分配的方案 发送给 协调者 7. 协调者 把对应consumer 消费的最新消息 分别发送给每个 consumer 8. 结束 重平衡从broker视角 主要分三种 1. 新的消费者加入 2. 旧的消费者退出,主动发送leave group命令离开 3. 旧的消费者 崩溃退出,有具体心跳参数控制,心跳发现 离开 在重平衡之前,协调者会要求所有consumer 尽快在一个时间之内 提交自己的offset。在整个重平衡过程中,组内所有消费者实例都会暂停消费。 ##### 消息队列横向对比?
<%= stylesheet_link_tag "dashboard", "data-turbo-track": "reload" %> <body> <header class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0 shadow"> <a class="navbar-brand col-md-3 col-lg-2 me-0 px-3" href="#"><span>Hi </span><%= current_user.first_name.capitalize %>!</a> <button class="navbar-toggler position-absolute d-md-none collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <input id='myInput' onkeyup="myFunction()" class="form-control form-control-dark w-100" type="text" placeholder="Search by Stock Name" aria-label="Search"> <div class="navbar-nav"> <div class="nav-item text-nowrap"> <%= button_to "Log out", destroy_user_session_path, :method => :delete, class:'nav-link px-3 btn' %> </div> </div> </header> <div class="container-fluid"> <div class="row"> <nav id="sidebarMenu" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse"> <div class="position-sticky pt-3"> <% if current_user.role == 'trader'%> <ul class="nav flex-column"> <li class="nav-item"> <%= link_to root_path, class:'nav-link' do %> <span data-feather="home"></span> Dashboard <% end %> </li> <li class="nav-item"> <%= link_to portfolio_path, class: "nav-link" do%> <span data-feather="file"></span> Portfolio <%end%> </li> <li class="nav-item"> <%= link_to listings_path, class: "nav-link" do%> <span data-feather="file"></span> Listings <%end%> </li> <li class="nav-item"> <%= link_to transactions_path, class: "nav-link" do%> <span data-feather="file"></span> Transaction History <%end%> </li> <li class="nav-item"> <%= link_to balance_path, class: "nav-link" do%> <span data-feather="dollar-sign"></span> Balance <span data-feather="plus-circle"></span> <span><%= number_to_currency current_user.balance %></span> <%end%> </li> </ul> <%end%> <% if current_user.role == 'admin' %> <h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted"> <span>Admin</span> </h6> <ul class="nav flex-column mb-2"> <li class="nav-item"> <a class="nav-link" href="/#pendingUser"> <span data-feather="users"></span> <span>Pending Users</span> <span class="position-absolute end-5px pending"><%= get_pending_users %></span> </a> </li> <li class="nav-item"> <a class="nav-link" href="/new"> <span data-feather="users"></span> Create a Trader </a> </li> <li class="nav-item"> <%= link_to transactions_path, class: 'nav-link' do%> <span data-feather="file-text"></span> Transactions <%end%> </li> </ul> <% end %> </div> </nav> <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4"> <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom"> <h1><%= @listing.name%></h1> </div> <section class="h-100 gradient-custom"> <div class="container py-5"> <div class="row d-flex justify-content-center my-4"> <div class="col-md-8"> <div class="card mb-4"> <div class="card-header py-3"> <h5 class="mb-0">You are <span class='btn btn-primary'> Buying </span></h5> </div> <div class="card-body"> <!-- Single item --> <div class="row"> <div class="col-lg-3 col-md-12 mb-4 mb-lg-0"> <!-- Image --> <div class="bg-image hover-overlay hover-zoom ripple rounded" data-mdb-ripple-color="light"> <img src="<%= @listing.logo %>" class="w-100" alt="Blue Jeans Jacket" /> <a href="#!"> <div class="mask" style="background-color: rgba(251, 251, 251, 0.2)"></div> </a> </div> <!-- Image --> </div> <div class="col-lg-5 col-md-6 mb-4 mb-lg-0"> <!-- Data --> <p><strong><%= @listing.ticker%></strong></p> <p>Earning Ratio: <span class='bg-success text-white px-2 py-1 rounded fw-bold'><%= @listing.pe_ratio %></span></p> <p>Price: <span id='staticPrice'><%= number_to_currency @listing.price%></span></p> <p>Previous Price: <%= number_to_currency @listing.previous_close%></p> <!-- Data --> </div> <div class="col-lg-4 col-md-6 mb-4 mb-lg-0 d-flex flex-column justify-content-center"> <!-- Quantity --> <div class="d-flex mb-4" style="max-width: 300px"> <button class="btn btn-primary px-3 me-2 qty-btn" onclick="this.parentNode.querySelector('input[type=number]').stepDown()"> <i class="fas fa-minus"></i> </button> <div class="form-outline"> <input id="form1" min="0" name="quantity" value="1" type="number" class="form-control" /> </div> <button class="btn btn-primary px-3 ms-2 qty-btn" onclick="this.parentNode.querySelector('input[type=number]').stepUp()"> <i class="fas fa-plus"></i> </button> </div> <!-- Quantity --> <!-- Price --> <p class="text-start text-md-center"> <strong id='front-price'><%= number_to_currency @listing.price %></strong> </p> <button class='btn btn-primary'>Commit</button> <!-- Price --> </div> </div> <!-- Single item --> <hr class="my-4" /> </div> </div> </div> </div> </section> </main> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/feather.min.js" integrity="sha384-uO3SXW5IuS1ZpFPKugNNWqTZRRglnUJK6UAZ/gxOX80nxEkN9NcGZTftn6RzhGWE" crossorigin="anonymous"></script><script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.min.js" integrity="sha384-zNy6FEbO50N+Cg5wap8IKA4M/ZnLJgzc6w2NqACZaK0u0FXfOWRRJOnQtpZun8ha" crossorigin="anonymous"></script> <%= javascript_include_tag "dashboard" %>
package CashMaster.calculator; import static CashMaster.view.Colors.RESET; import CashMaster.model.Record; import CashMaster.util.FileUtil; import CashMaster.view.Colors; import java.util.List; public class FinancialCalculator { static List<Record> records = FileUtil.getRecords(); /** * Calculates the total income from a list of financial records. * * @param records The list of financial records to calculate income from. * @return The total income as a double value. */ public static double calculateTotalIncome(List<Record> records){ double totalIncome = 0.0; for (Record record : records){ if (record.getAmount()>0){ totalIncome+= record.getAmount(); } } return totalIncome; } /** * Calculates the total expenses from a list of financial records. * * @param records The list of financial records to calculate expenses from. * @return The total expenses as a positive double value. */ public static double calculateTotalExpenses(List<Record> records){ double totalExpenses = 0.0; for (Record record : records){ if (record.getAmount()< 0){ totalExpenses+=record.getAmount(); } } return Math.abs(totalExpenses); } /** * Calculates the balance based on a list of financial records. * * @param records The list of financial records to calculate the balance from. * @return The balance, which is the difference between total income and total expenses. */ public static double calculateBalance(List<Record> records){ double totalIncome = 0.0; double totalExpenses = 0.0; for (Record record : records){ if (record.getAmount()>0){ totalIncome += record.getAmount(); }else { totalExpenses += record.getAmount(); } } return totalIncome + totalExpenses; } /** * Prints a summary of total income, total expenses, and the balance to the console. * Do not delete . Can be used. * @param records The list of financial records to calculate and display income and expenses from. */ public static void printIncome(List<Record>records){ System.out.println(); System.out.print(Colors.WHITE_BRIGHT + "Total Income: " + calculateTotalIncome(records) + " ||||| "); System.out.print("Total Expenses: " + calculateTotalExpenses(records)+" ||||| "); System.out.print("Balance: " + calculateBalance(records) + RESET); System.out.println(); System.out.println(); } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Customer; use App\Http\Requests\AddCustomerRequest; class CustomerController extends Controller { public function addCustomer(AddCustomerRequest $request) { $validated = $request->validated(); $customer = new Customer(); $checkConflict = $customer->checkConflict($validated['name'], $validated['owner_id']); if ($checkConflict) { return response()->json(['error' => 'Customer already exists'], 400); } $customer = Customer::create($validated); return response()->json([ 'message' => 'Customer added successfully', 'customer' => $customer ], 200); } public function getCustomers($userId) { $customers = Customer::where('owner_id', $userId)->get(); return response()->json([ 'total' => count($customers), 'customers' => $customers ], 200); } public function deleteCustomer($customerId) { $customer = Customer::where('id', $customerId)->first(); if ($customer != null) { $customer->delete(); return response()->json([ 'message' => 'Customer deleted successfully' ], 200); } else { return response()->json([ 'error' => 'Customer not found' ], 400); } } }
import ImageIcon from '@mui/icons-material/Image'; import { useRef, useState } from 'react'; function AddBookForm({books, setBooks, setFormState}) { const [image, setImage] = useState(null) const lastId = books && books.length > 0 ? books[books.length - 1].id : 0; const title = useRef(null), author = useRef(null) const handleFileChange = (e) => { if (e.target.files[0].type === "image/png" || e.target.files[0].type === "image/jpeg") { const reader = new FileReader(); reader.addEventListener('load', () => { setImage(reader.result) }) reader.readAsDataURL(e.target.files[0]) } } const handleSubmit = (e) => { if (title.current.value.length === 0 || author.current.value.length === 0) return false setBooks([...books ? books : "", {id: lastId + 1, title: title.current.value, author: author.current.value, image}]) setFormState(false) } return ( <form className='addBookForm' action="#"> <input ref={title} className="textInput" required minLength={1} type="text" name="title" id="title" placeholder='Название книги' /> <input ref={author} className="textInput" required minLength={1} type="text" name="author" id="author" placeholder='Автор книги' /> <div className='uploadImage'> <input className="fileInput" accept="image/png, image/jpeg" onChange={(e) => handleFileChange(e)} type="file" name="image" id="image" /> <label className='uploadImageButton' htmlFor="image"><ImageIcon fontSize='large' color="success"/>{image ? <p>Change Image</p> : <p>Upload Image</p>}</label> {image ? <img className='imageInput' src={image} alt="" /> : <></> } </div> <button onClick={handleSubmit} className='submitButton'>ADD BOOK</button> </form> ); } export default AddBookForm;
package com.practice.springboottesting.integration; import com.practice.springboottesting.domain.Employee; import com.practice.springboottesting.repository.EmployeeRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import java.util.List; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; @DataJpaTest @AutoConfigureTestDatabase(replace=AutoConfigureTestDatabase.Replace.NONE) public class EmployeeRepositoryITests extends AbstractionBaseTest{ @Autowired EmployeeRepository employeeRepository; private Employee emp; @BeforeEach void setUp() { emp= Employee.builder() .firstName("Ashu") .lastName("A") .email("[email protected]").build(); } @Test void givenEmployeeObject_whenSave_thenReturnSavedEmployee() { Employee savedEmployee=employeeRepository.save(emp); assertThat(savedEmployee).isNotNull(); assertThat(savedEmployee.getId()).isGreaterThan(0); } @Test void givenEmployeeList_whenFindAll_thenReturnEmployeeList() { //given data, setup Employee emp1= Employee.builder() .firstName("Arpitha") .lastName("R") .email("[email protected]").build(); employeeRepository.save(emp); employeeRepository.save(emp1); // then perform action List<Employee> result=employeeRepository.findAll(); //then verify assertThat(result).isNotNull(); assertThat(result).size().isEqualTo(2); } @Test void givenEmployeeObject_whenFindById_thenReturnEmployee() { //given data, setup employeeRepository.save(emp); // then perform action Employee result = employeeRepository.findById(emp.getId()).get(); //then verify assertThat(result).isNotNull(); } @Test void givenEmployye_whenFindByEmail_thenReturnEmployee() { employeeRepository.save(emp); Employee result=employeeRepository.findByEmail(emp.getEmail()).get(); assertThat(result).isNotNull(); assertThat(result.getEmail().equals(emp.getEmail())); } @Test void givenEmployeeEmail_whenfindbyemail_thenReturnUpdatedEmployee() { //given data, setup employeeRepository.save(emp); Employee savedEmployee=employeeRepository.findById(emp.getId()).get(); savedEmployee.setFirstName("Arpitha"); savedEmployee.setEmail("[email protected]"); // then perform action Employee updatedEmployee=employeeRepository.save(savedEmployee); //then verify assertThat(savedEmployee).isNotNull(); assertThat(updatedEmployee.getFirstName()).isEqualTo("Arpitha"); assertThat(updatedEmployee.getEmail()).isEqualTo("[email protected]"); } @Test void givenEmployee_whenDelete_thenReturn() { //given data, setup employeeRepository.save(emp); // then perform action employeeRepository.delete(emp); Optional<Employee> deletedEmployee=employeeRepository.findById(emp.getId()); //then verify assertThat(deletedEmployee).isEmpty(); } @Test void givenFirstNameLastName_whenFindBy_thenReturnEmployee() { //given data, setup employeeRepository.save(emp); // then perform action Employee result=employeeRepository.getEmployeeByfirstNameAndLAstName(emp.getFirstName(),emp.getLastName()).get(); //then verify assertThat(result).isNotNull(); } }
--- created: 2020-02-12 last_modified: 2022-03-08 version: 1.1 tactics: Credential Access url: https://attack.mitre.org/techniques/T1555/002 platforms: Linux, macOS tags: [T1555_002, techniques, Credential_Access] --- ## Credentials from Password Stores- Securityd Memory ### Description An adversary may obtain root access (allowing them to read securityd?s memory), then they can scan through memory to find the correct sequence of keys in relatively few tries to decrypt the user?s logon keychain. This provides the adversary with all the plaintext passwords for users, WiFi, mail, browsers, certificates, secure notes, etc.(Citation: OS X Keychain)(Citation: OSX Keydnap malware) In OS X prior to El Capitan, users with root access can read plaintext keychain passwords of logged-in users because Apple?s keychain implementation allows these credentials to be cached so that users are not repeatedly prompted for passwords.(Citation: OS X Keychain)(Citation: External to DA, the OS X Way) Apple?s securityd utility takes the user?s logon password, encrypts it with PBKDF2, and stores this master key in memory. Apple also uses a set of keys and algorithms to encrypt the user?s password, but once the master key is found, an adversary need only iterate over the other values to unlock the final password.(Citation: OS X Keychain) ### Detection Monitor processes and command-line arguments for activity surrounded users searching for credentials or using automated tools to scan memory for passwords. ### Defenses Bypassed ### Data Sources - Command: Command Execution - Process: Process Access ### Detection Rule ```query tag: detection_rule tag: T1555_002 ``` ### Rule Testing ```query tag: atomic_test tag: T1555_002 ```
# 以下部分均为可更改部分 import dataclasses from answer_task1 import * import smooth_utils def compute_velocity(pos, dt): ''' 计算速度 ''' return (pos[1:] - pos[:-1]) / dt @dataclasses class motion_data: motion: BVHMotion # pos: np.ndarray pos20: np.ndarray pos40: np.ndarray vel: np.ndarray rot: np.ndarray avel: np.ndarray joint_translation : np.ndarray def add_motion(filename): motion = BVHMotion(filename) joint_trans, _ = motion.batch_forward_kinematics_root_zero() pos = motion.joint_position[:, 0, :] vel = compute_velocity(pos, 1 / 60) pos20 = pos[20: ] - pos[: -20] pos40 = pos[40: ] - pos[: -40] rotations = motion.joint_rotation[:, 0, :] for i in range(rotations.shape[0]): rotations[i] = R.as_quat(decompose_rotation_with_yaxis(rotations[i])[0]) ang_vel = smooth_utils.quat_to_avel(rotations) inv_R = R.from_quat(rotations[0]).inv() for i in range(rotations.shape[0]): rotations[i] = (inv_R * R.from_quat(rotations[i])).as_quat() return motion_data(motion, pos20, pos40, vel, rotations, ang_vel, joint_trans) class CharacterController(): def __init__(self, controller) -> None: self.motions = [] self.motions.append(add_motion('motion_material/kinematic_motion/long_run.bvh')) self.motions.append(add_motion('motion_material/kinematic_motion/long_walk.bvh')) # self.motions.append(BVHMotion('motion_material/kinematic_motion/long_run.bvh')) # self.motions.append(BVHMotion('motion_material/kinematic_motion/long_walk.bvh')) # self.motion_pos = [] # self.motion_velocity = [] # self.motion_rotation = [] # self.motion_ang_vel = [] self.index = [] for motion in self.motions: for i, name in enumerate(motion.motion.joint_name): if name == "lAnkle" or name == "rAnkle": self.index.append(i) self.controller = controller self.cur_joint_pos = [self.motions[0].joint_translation[self.index[0]], self.motions[1].joint_translation[self.index[1]]] self.cur_root_pos = [0, 0, 0] self.cur_root_rot = [0, 0, 0, 1] self.cur_frame = 0 pass def update_state(self, desired_pos_list, desired_rot_list, desired_vel_list, desired_avel_list, current_gait ): ''' 此接口会被用于获取新的期望状态 Input: 平滑过的手柄输入,包含了现在(第0帧)和未来20,40,60,80,100帧的期望状态,以及一个额外输入的步态 简单起见你可以先忽略步态输入,它是用来控制走路还是跑步的 desired_pos_list: 期望位置, 6x3的矩阵, 每一行对应0,20,40...帧的期望位置(水平), 期望位置可以用来拟合根节点位置也可以是质心位置或其他 desired_rot_list: 期望旋转, 6x4的矩阵, 每一行对应0,20,40...帧的期望旋转(水平), 期望旋转可以用来拟合根节点旋转也可以是其他 desired_vel_list: 期望速度, 6x3的矩阵, 每一行对应0,20,40...帧的期望速度(水平), 期望速度可以用来拟合根节点速度也可以是其他 desired_avel_list: 期望角速度, 6x3的矩阵, 每一行对应0,20,40...帧的期望角速度(水平), 期望角速度可以用来拟合根节点角速度也可以是其他 Output: 同作业一,输出下一帧的关节名字,关节位置,关节旋转 joint_name: List[str], 代表了所有关节的名字 joint_translation: np.ndarray,形状为(M, 3)的numpy数组,包含着所有关节的全局位置 joint_orientation: np.ndarray,形状为(M, 4)的numpy数组,包含着所有关节的全局旋转(四元数) Tips: 输出三者顺序需要对应 controller 本身有一个move_speed属性,是形状(3,)的ndarray, 分别对应着面朝向移动速度,侧向移动速度和向后移动速度.目前根据LAFAN的统计数据设为(1.75,1.5,1.25) 如果和你的角色动作速度对不上,你可以在init或这里对属性进行修改 ''' def compute_cost(motion): cost = 0 for i, idx in enumerate(self.index): cost += np.linalg.norm(motion.joint_translation[idx] - self.cur_joint_pos[i]) cost += np.linalg.norm(motion.pos20) return cost # 一个简单的例子,输出第i帧的状态 joint_name = self.motions[0].joint_name joint_translation, joint_orientation = self.motions[0].batch_forward_kinematics() joint_translation = joint_translation[self.cur_frame] joint_orientation = joint_orientation[self.cur_frame] self.cur_root_pos = joint_translation[0] self.cur_root_rot = joint_orientation[0] self.cur_frame = (self.cur_frame + 1) % self.motions[0].motion_length return joint_name, joint_translation, joint_orientation def sync_controller_and_character(self, controller, character_state): ''' 这一部分用于同步你的角色和手柄的状态 更新后很有可能会出现手柄和角色的位置不一致,这里可以用于修正 让手柄位置服从你的角色? 让角色位置服从手柄? 或者插值折中一下? 需要你进行取舍 Input: 手柄对象,角色状态 手柄对象我们提供了set_pos和set_rot接口,输入分别是3维向量和四元数,会提取水平分量来设置手柄的位置和旋转 角色状态实际上是一个tuple, (joint_name, joint_translation, joint_orientation),为你在update_state中返回的三个值 你可以更新他们,并返回一个新的角色状态 ''' # 一个简单的例子,将手柄的位置与角色对齐 controller.set_pos(self.cur_root_pos) controller.set_rot(self.cur_root_rot) return character_state # 你的其他代码,state matchine, motion matching, learning, etc.
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpClient } from '@angular/common/http'; import { SearchByNameResult, HistoryData } from '../home/home.interface'; import { environment } from 'src/environments/environment'; const routes = { searchByName: (name: string) => 'https://api.github.com/search/users?q=' + name, }; @Injectable({ providedIn: 'root' }) export class HomeService { constructor(private httpClient: HttpClient) {} searchByName(name: string): Observable<SearchByNameResult> { return this.httpClient.get<SearchByNameResult>( routes.searchByName(encodeURI(name)) ); } saveHistory(searchData: HistoryData[]) { localStorage.setItem( environment.localstorageKey, JSON.stringify(searchData) ); } getHistory(): HistoryData[] { return JSON.parse( localStorage.getItem(environment.localstorageKey) || '[]' ); } clearHistory() { localStorage.removeItem(environment.localstorageKey); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Step11_Loop.html</title> </head> <body> <button id="printBtn">출력</button> <button id="printBtn2">출력2</button> <div>div1</div> <div>div2</div> <div>div3</div> <div>div4</div> <div>div5</div> <script src="js/jquery-3.2.1.js"></script> <script> var names=["김구라","해골","원숭이","주뎅이","덩어리"]; //출력 버튼을 눌렀을때 실행할 함수 등록 $("#printBtn").click(function(){ $("div").each(function(index, item){ /* 선택된 문서객체의 갯수 만큼 함수가 호출되고 index 와 item 이 함수의 인자로 전달된다. */ $(item).text(names[index]); }); }); //출력 버튼을 눌렀을때 실행할 함수 등록 $("#printBtn2").click(function(){ $("div").each(function(index){ // this 는 선택된 div 의 참조값을 순서대로 참조할 수 있다. $(this).text(names[index]); }); }); </script> </body> </html>
package com.example.mariaiaandroid.singleton.vm import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.mariaiaandroid.ui.state.FormBlockUiState import com.google.ai.client.generativeai.GenerativeModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch class FormBlockViewModel( private val generativeModel: GenerativeModel ) : ViewModel() { private val _uiState: MutableStateFlow<FormBlockUiState> = MutableStateFlow(FormBlockUiState.Initial) val uiState: StateFlow<FormBlockUiState> = _uiState.asStateFlow() fun sending(inputText: String) { _uiState.value = FormBlockUiState.Loading val prompt = "Send that form for me: $inputText" viewModelScope.launch { try { val response = generativeModel.generateContent(prompt) //TODO try a chat Response other time response.text?.let { outputContent -> _uiState.value = FormBlockUiState.Sucess(outputContent) } } catch (e: Exception) { _uiState.value = FormBlockUiState.Error("Error: ${e.localizedMessage}") } } } }
import 'package:dartz/dartz.dart'; import 'package:http/http.dart' as http; import 'package:kopinale/core/constants/variables.dart'; import 'package:kopinale/data/models/responses/city/city_response_model.dart'; import 'package:kopinale/data/models/responses/provience/provience_response_model.dart'; class RajaongkirRemotedatasource { Future<Either<String, ProvienceResponseModel>> getProvinces() async { final url = Uri.parse('https://api.rajaongkir.com/starter/province'); final response = await http.get( url, headers: { 'key': Variables.rajaOngkirKey, }, ); if (response.statusCode == 200) { return Right(ProvienceResponseModel.fromJson(response.body)); } else { return const Left('Error'); } } Future<Either<String, CityResponseModel>> getCitiesByProvience( String provienceId) async { final url = Uri.parse( 'https://api.rajaongkir.com/starter/city?provience=$provienceId'); final response = await http.get( url, headers: {'key': Variables.baseUrl}, ); if (response.statusCode == 200) { return Right(CityResponseModel.fromJson(response.body)); } else { return const Left('Error'); } } // Future<Either<String, CityResponseModel>> getDistrictByCity( // String cityId) async { // final url = Uri.parse( // 'https://api.rajaongkir.com/starter/subdistrict?city=$cityId'); // final response = await http.get( // url, // headers: {'key': Variables.rajaOngkirKey}, // ); // if (response.statusCode == 200) { // return Right(CityResponseModel.fromJson(response.body)); // } else { // return const Left('Error'); // } // } }
// Write the code that will log true or false for the following: // Is 34 divided by 3 greater than 67 divided by 2? console.log((34 / 3) > (67 / 2)); // Does 5 evaluate to the same as "5"? console.log(5 == "5"); // Does 5 strictly equal "5"? console.log(5 === "5"); // Does !3 strictly equal 3? console.log(!3 === 3); // Does "LEARN".length strictly equal 5 AND "Student".length strictly equal 7? console.log("LEARN".length === 5 && "Student".length === 7); // Does "LEARN".length strictly equal 5 OR "Student".length strictly equal 10? console.log("LEARN".length === 5 || "Student".length === 7); // Does "LEARN" contain the subset "RN"? console.log("LEARN".includes("RN")); // Does "LEARN" contain the subset "rn"? console.log("LEARN".includes("rn")); // Does "LEARN"[0] strictly equal "l"? console.log("LEARN"[0] === "l"); // Modify the code from the previous question to return true. console.log("LEARN"[0] === "L"); // Make sure you try different options and change the variables to ensure properly working code. console.log("LEARN"[1] === "E"); console.log("LEARN"[1] === "e"); // Write a statement that takes a variable of item and logs "in budget" if a price is $100 or less. const item = 101 if (item <= 100) { console.log("in budget"); } else { console.log("cannot afford"); }; // Write a statement that takes a variable of hungry and logs "eat food" if you are hungry and "keep coding" if you are not hungry. const hungry = false; if (hungry) { console.log("eat food") } else { console.log("keep coding") }; // Write a statement that takes a variable of trafficLight and logs "go" if the light is green, "slow down" if the light is yellow and "stop" if the light is red. let trafficLight = "broken" if (trafficLight === "green") { console.log("go"); } else if (trafficLight === "yellow") { console.log("slow down"); } else if (trafficLight === "red") { console.log("stop"); } else { console.log("proceed with caution") }; // Write a statement that takes two variables that are numbers and outputs the larger number. If the numbers are equal, output "the numbers are the same". let num1 = "twenty"; let num2 = 10; if (num1 > num2) { console.log(num1); } else if (num2 > num1) { console.log(num2); } else if (num1 === num2) { console.log("the numbers are the same"); } else { console.log("this is not a numbers"); } // Write a statement that takes a variable of a number and logs whether the number is odd, even, or zero. let number = 0; if (number === 0) { console.log("zero"); } else if (number % 2 === 0) { console.log("even"); } else { console.log("odd") } // 🏔 Stretch Goals // Write a statement that takes a variable of a grade percentage and logs the letter grade for that percentage, if the grade is 100% log "perfect score", if the grade is zero log "no grade available." let gradePercentage = 100 if (gradePercentage === 100) { console.log("perfect score"); } else if (gradePercentage < 100 && gradePercentage >= 90) { console.log("A"); } else if (gradePercentage < 90 && gradePercentage >= 80) { console.log("B"); } else if (gradePercentage < 80 && gradePercentage >= 70) { console.log("C"); } else if (gradePercentage < 70 && gradePercentage >= 60) { console.log("D"); } else if (gradePercentage < 60 && gradePercentage >= 50) { console.log("F"); } else { console.log("you dropped out") } // Write a statement that takes a variable of a boolean, number, or string data type and logs the data type of the variable. HINT: Check out the JavaScript typeof operator. let dataType = false; switch (typeof dataType) { case "string": console.log("string"); break; case "boolean": console.log("boolean"); break; case "number": console.log("number"); break; } if(typeof any === "string" || typeof any === "boolean" ||typeof any === "number"){ console.log(typeof any) } // Create a password checker using a single conditional statement. If a user inputs a password with 12 or more characters AND the password includes !, then log "That is a mighty strong password!" If the user’s password is 8 or more characters OR includes !, then log "That password is strong enough." Log "That is not a valid password." for every other input. let password = 'pa123' if (password.length >= 12 && password.includes('!')) { console.log('That is a mighty strong password!') } else if (password.length >= 8 || password.includes('!')) { console.log('That password is strong enough.') } else { console.log('That is not a valid password.') }
import 'package:flutter/material.dart'; import 'package:zedzat/screens/profile.dart'; import 'package:zedzat/screens/rewards.dart'; import 'cart.dart'; import 'homescreen.dart'; import 'offers.dart'; class BottomBarScreen extends StatefulWidget { const BottomBarScreen({super.key}); @override State<BottomBarScreen> createState() => _BottomBarScreenState(); } class _BottomBarScreenState extends State<BottomBarScreen> { int _selectedIndex = 0; final List<Map<String, dynamic>> _pages = [ {'Page':const HomeScreen(),'title':'Home Screen'}, {'Page':const OfferScreen(),'title':'Offers'}, {'Page':const Rewards(),'title':'Rewards'}, {'Page':const CartScreen(),'title':'Cart'}, {'Page':const Profile(),'title':'Profile'}, ]; void _selectedpage(int index) { setState(() { _selectedIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( // appBar: AppBar( // title:Text( _pages[_selectedIndex]['title'],style: TextStyle(color: Colors.black),), // backgroundColor: Colors.white, // ), body: _pages[_selectedIndex]['Page'], bottomNavigationBar: BottomNavigationBar( backgroundColor: Colors.green, type: BottomNavigationBarType.shifting, showSelectedLabels: false, selectedItemColor: Colors.black, unselectedItemColor: Colors.blueGrey, currentIndex: _selectedIndex, onTap: _selectedpage, items: <BottomNavigationBarItem> [ BottomNavigationBarItem(icon: Icon(Icons.home),label: "Home"), BottomNavigationBarItem(icon: Icon(Icons.local_offer),label: "Categories"), BottomNavigationBarItem(icon: Icon(Icons.card_giftcard),label: "Rewards"), BottomNavigationBarItem(icon: Icon(Icons.shopping_bag),label: "Cart"), BottomNavigationBarItem(icon: Icon(Icons.person_2),label: "Profile"), ] ), ); } }
const { expect } = require('chai'); const { ethers } = require('hardhat'); const { BigNumber } = require('ethers'); const ERC20 = require('../data/ERC20.json'); const { CONFIG, getBigNumber, DISCOUNT, getVoteData, getConfig } = require('../scripts/utils'); const GNOSIS_FLAG = false; describe('StakerMap', function () { before(async function () { this.VabbleDAOFactory = await ethers.getContractFactory('VabbleDAO'); this.VabbleFundFactory = await ethers.getContractFactory('VabbleFund'); this.UniHelperFactory = await ethers.getContractFactory('UniHelper'); this.StakingPoolFactory = await ethers.getContractFactory('StakingPool'); this.VoteFactory = await ethers.getContractFactory('Vote'); this.PropertyFactory = await ethers.getContractFactory('Property'); this.FactoryFilmNFTFactory = await ethers.getContractFactory('FactoryFilmNFT'); this.FactoryTierNFTFactory = await ethers.getContractFactory('FactoryTierNFT'); this.FactorySubNFTFactory = await ethers.getContractFactory('FactorySubNFT'); this.OwnableFactory = await ethers.getContractFactory('Ownablee'); this.SubscriptionFactory = await ethers.getContractFactory('Subscription'); this.GnosisSafeFactory = await ethers.getContractFactory('GnosisSafeL2'); this.signers = await ethers.getSigners(); this.deployer = this.signers[0]; this.auditor = this.signers[0]; this.studio1 = this.signers[2]; this.studio2 = this.signers[3]; this.studio3 = this.signers[4]; this.customer1 = this.signers[5]; this.customer2 = this.signers[6]; this.customer3 = this.signers[7]; this.auditorAgent1 = this.signers[8]; this.reward = this.signers[9]; this.auditorAgent2 = this.signers[10]; this.customer4 = this.signers[11]; this.customer5 = this.signers[12]; this.customer6 = this.signers[13]; this.customer7 = this.signers[14]; this.sig1 = this.signers[15]; this.sig2 = this.signers[16]; this.sig3 = this.signers[17]; this.signer1 = new ethers.Wallet(process.env.PK1, ethers.provider); this.signer2 = new ethers.Wallet(process.env.PK2, ethers.provider); }); beforeEach(async function () { // load ERC20 tokens const network = await ethers.provider.getNetwork(); const chainId = network.chainId; console.log("Chain ID: ", chainId); const config = getConfig(chainId); // load ERC20 tokens this.vabToken = new ethers.Contract(config.vabToken, JSON.stringify(ERC20), ethers.provider); this.USDC = new ethers.Contract(config.usdcAdress, JSON.stringify(ERC20), ethers.provider); this.USDT = new ethers.Contract(config.usdtAdress, JSON.stringify(ERC20), ethers.provider); this.GnosisSafe = await (await this.GnosisSafeFactory.deploy()).deployed(); this.auditor = GNOSIS_FLAG ? this.GnosisSafe : this.deployer; this.Ownablee = await (await this.OwnableFactory.deploy( CONFIG.daoWalletAddress, this.vabToken.address, this.USDC.address, this.auditor.address )).deployed(); this.UniHelper = await (await this.UniHelperFactory.deploy( config.uniswap.factory, config.uniswap.router, config.sushiswap.factory, config.sushiswap.router, this.Ownablee.address )).deployed(); this.StakingPool = await (await this.StakingPoolFactory.deploy(this.Ownablee.address)).deployed(); }); it('stakerMap function test', async function () { console.log("====stakerMap===="); console.log([ this.customer1.address, this.customer2.address, this.customer3.address, this.customer4.address ]); let stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([]); await this.StakingPool.connect(this.customer1).__stakerSet(this.customer1.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([this.customer1.address]); await this.StakingPool.connect(this.customer1).__stakerSet(this.customer2.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([this.customer1.address, this.customer2.address]); await this.StakingPool.connect(this.customer1).__stakerSet(this.customer3.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([this.customer1.address, this.customer2.address, this.customer3.address]); await this.StakingPool.connect(this.customer1).__stakerSet(this.customer4.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([this.customer1.address, this.customer2.address, this.customer3.address, this.customer4.address]); // add duplicated address await this.StakingPool.connect(this.customer1).__stakerSet(this.customer1.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([this.customer1.address, this.customer2.address, this.customer3.address, this.customer4.address]); await this.StakingPool.connect(this.customer1).__stakerSet(this.customer2.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([this.customer1.address, this.customer2.address, this.customer3.address, this.customer4.address]); await this.StakingPool.connect(this.customer1).__stakerSet(this.customer3.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([this.customer1.address, this.customer2.address, this.customer3.address, this.customer4.address]); await this.StakingPool.connect(this.customer1).__stakerSet(this.customer4.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([this.customer1.address, this.customer2.address, this.customer3.address, this.customer4.address]); // remove last address await this.StakingPool.connect(this.customer1).__stakerRemove(this.customer4.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([this.customer1.address, this.customer2.address, this.customer3.address]); // remove middle address await this.StakingPool.connect(this.customer1).__stakerRemove(this.customer2.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([this.customer1.address, this.customer3.address]); // remove first address await this.StakingPool.connect(this.customer1).__stakerRemove(this.customer1.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([this.customer3.address]); // remove non exist address await this.StakingPool.connect(this.customer1).__stakerRemove(this.customer1.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([this.customer3.address]); // remove 1 address await this.StakingPool.connect(this.customer1).__stakerRemove(this.customer3.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([]); // add again await this.StakingPool.connect(this.customer1).__stakerSet(this.customer1.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([this.customer1.address]); await this.StakingPool.connect(this.customer1).__stakerSet(this.customer2.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([this.customer1.address, this.customer2.address]); await this.StakingPool.connect(this.customer1).__stakerSet(this.customer3.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([this.customer1.address, this.customer2.address, this.customer3.address]); await this.StakingPool.connect(this.customer1).__stakerSet(this.customer4.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([this.customer1.address, this.customer2.address, this.customer3.address, this.customer4.address]); // remove 2nd address await this.StakingPool.connect(this.customer1).__stakerRemove(this.customer2.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([this.customer1.address, this.customer4.address, this.customer3.address]); // remove 2nd address await this.StakingPool.connect(this.customer1).__stakerRemove(this.customer4.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([this.customer1.address, this.customer3.address]); // remove 2nd address await this.StakingPool.connect(this.customer1).__stakerRemove(this.customer3.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([this.customer1.address]); // remove 1 address await this.StakingPool.connect(this.customer1).__stakerRemove(this.customer1.address, {from: this.customer1.address}) stakerList = await this.StakingPool.getStakerList(); expect(stakerList).to.be.deep.equal([]); }); });
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Lunch Management</title> <link rel="icon" type="image/x-icon" href="{% static 'images/favicon.png' %}" /> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" /> <link rel="stylesheet" href="{% static 'users/style.css' %}" /> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="#">LunchMenu</a> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="{% url 'food:index' %}" ><button class="btn btn-sm btn-outline-secondary" type="button"> View Item </button></a > </li> <li class="nav-item"> <a class="nav-link" aria-current="page" href="{% url 'food:create_item' %}" ><button class="btn btn-sm btn-outline-secondary" type="button"> Add Item </button></a > </li> <li class="nav-item"> <a class="nav-link" href="{% url 'users:view_cart' %}" ><button class="btn btn-sm btn-outline-secondary" type="button"> View Cart </button></a > </li> <li class="nav-item"> <a class="nav-link" href="{% url 'users:user_orders' %}" ><button class="btn btn-sm btn-outline-secondary" type="button"> Orders </button></a > </li> </ul> <ul class="navbar-nav ms-auto"> {% if user.is_authenticated %} <li class="nav-item"> <a href="{% url 'profile' %}" ><button type="submit" class="btn btn-outline-success"> Profile </button></a > </li> <li class="nav-item ms-2"> <form method="post" action="{% url 'logout' %}" style="display: inline" > {% csrf_token %} <a href="{% url 'logout' %}" ><button type="submit" class="btn btn-outline-warning"> Logout </button></a > </form> </li> {% else %} <li class="nav-item"> <a href="{% url 'login' %}" ><button type="submit" class="btn btn-outline-primary"> Login </button></a > </li> <li class="nav-item ms-2"> <a href="{% url 'register' %}" ><button type="submit" class="btn btn-outline-primary"> Register </button></a > </li> {% endif %} </ul> </div> </div> </nav> <div class="container mt-5"> <h2 class="mb-4">Your Orders</h2> {% if orders %} <div class="table-responsive"> <table class="table table-bordered table-hover"> <thead class="table-dark"> <tr> <th>Order ID</th> <th>Date</th> <th>Total Price</th> <th>Details</th> </tr> </thead> <tbody> {% for order in orders %} <tr> <td>{{ order.id }}</td> <td>{{ order.created_at|date:"F j, Y, g:i a" }}</td> <td>BDT {{ order.total_price }}</td> <td> <a href="{% url 'users:order_summary' order.id %}" class="btn btn-info btn-sm" > <i class="bi bi-eye"></i> View Details </a> </td> </tr> {% endfor %} </tbody> </table> </div> {% else %} <div class="alert alert-info text-center" role="alert"> You have no orders. <a href="{% url 'food:index' %}" class="alert-link">Start shopping</a> now! </div> {% endif %} </div> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> </body> </html>
import { AfterViewInit, Component, EventEmitter, OnInit, Output, } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MapToolbarComponent } from './toolbar/toolbar.component'; import { MapDropdownsComponent } from './dropdowns/dropdowns.component'; import { RouteDataService } from '@atticadt/services'; @Component({ selector: 'app-map', standalone: true, imports: [CommonModule, MapDropdownsComponent, MapToolbarComponent], templateUrl: './map.component.html', styleUrls: ['./map.component.scss'], }) export class MapComponent implements OnInit, AfterViewInit { routeInfo = ''; routeData$ = this.routeDataService.routeData$; @Output() afterMapInit = new EventEmitter<void>(); constructor(private routeDataService: RouteDataService) {} ngOnInit(): void { this.routeData$.subscribe((data) => { this.routeInfo = data?.['info']; }); } ngAfterViewInit(): void { this.afterMapInit.emit(); } }
/* eslint-disable jsx-a11y/alt-text */ import React, { useContext, useEffect } from "react"; import AdminContext from "../../context/AdminContext"; import { useNavigate } from "react-router-dom"; import "./categories.scss"; const Categories = () => { const { state, dispatch, createCategory,getCategory} = useContext(AdminContext); const navigate = useNavigate(); useEffect(() => { dispatch({ type: "categoryName", payload: "" }); getCategory(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return ( <div id="admin-categories-container"> <form onSubmit={createCategory}> <input type="text" onChange={(e) => dispatch({ type: "categoryName", payload: e.target.value }) } placeholder="Kategori İsmi" value={state.categoryName} required /> <button type="submit">Kategori Ekle</button> </form> <div id="category-list"> {state.categories.map((category) => ( <div className="admin-categories" onClick={() => navigate(`/admin/categorydetail/${category.id}`)} key={category.id} > <h1>{category.categoryName}</h1> <h4>Problem Sayısı - {category.problemCount}</h4> <hr/> <p>Durumu: {category.isDeleted===true?"❌":"✅"}</p> </div> ))} </div> </div> ); }; export default Categories;
export function findRepeatedDnaSequences(s: string): string[] { const n = s.length if (n < 10) return [] const ans = new Set<string>() const set = new Set<string>() for (let i = 0; i + 10 <= n; ++i) { const substr = s.slice(i, i + 10) if (set.has(substr)) { ans.add(substr) } else { set.add(substr) } } return Array.from(ans) } export function findRepeatedDnaSequences1(s: string): string[] { const n = s.length const L = 10 if (n < L) return [] const map: Record<string, number> = { A: 0b00, C: 0b01, G: 0b10, T: 0b11, } let x = 0 const ans: string[] = [] for (let i = 0; i < L - 1; ++i) { x = (x << 2) | map[s[i]] } const cnt: Record<number, number> = {} for (let i = L - 1; i < n; ++i) { x = ((x << 2) | map[s[i]]) & ((1 << (2 * L)) - 1) cnt[x] = (cnt[x] ?? 0) + 1 if (cnt[x] === 2) { ans.push(s.slice(i - L + 1, i + 1)) } } return ans }
<template> <div class="article-container"> <el-card> <div slot="header"> <my-bread>{{articleId ? '修改' : '发布'}}文章</my-bread> </div> <el-form label-width="100px"> <el-form-item label="标题:"> <el-input v-model="articleForm.title" style="width:400px"></el-input> </el-form-item> <el-form-item label="内容"> <quillEditor :options="editorOption" v-model="articleForm.content"></quillEditor> </el-form-item> <el-form-item label="封面:"> <el-radio-group v-model="articleForm.cover.type" @change="changeType"> <el-radio :label="1">单图</el-radio> <el-radio :label="3">三图</el-radio> <el-radio :label="0">无图</el-radio> <el-radio :label="-1">自动</el-radio> </el-radio-group> <!-- 放组件 --> <div v-if="articleForm.cover.type===1 "> <my-image v-model="articleForm.cover.images[0]"></my-image> </div> <div v-if="articleForm.cover.type === 3"> <my-image v-model="articleForm.cover.images[0]" style="display:inline-block;"></my-image> <my-image v-model="articleForm.cover.images[1]" style="display:inline-block;"></my-image> <my-image v-model="articleForm.cover.images[2]" style="display:inline-block;"></my-image> </div> </el-form-item> <el-form-item label="频道:"> <my-channel v-model="articleForm.channel_id"></my-channel> </el-form-item> <el-form-item v-if="!articleId"> <el-button type="success" @click="submit(false)">发布文章</el-button> <el-button plain @click="submit(true)">存为草稿</el-button> </el-form-item> <el-form-item v-else> <el-button type="success" @click="update(false)">修改文章</el-button> <el-button plain @click="update(true)">存为草稿</el-button> </el-form-item> </el-form> </el-card> </div> </template> <script> import 'quill/dist/quill.core.css' import 'quill/dist/quill.snow.css' import 'quill/dist/quill.bubble.css' import { quillEditor } from 'vue-quill-editor' export default { props: {}, data () { return { editorOption: { placeholder: '', modules: { toolbar: [ ['bold', 'italic', 'underline', 'strike'], ['blockquote', 'code-block'], [{ header: 1 }, { header: 2 }], [{ list: 'ordered' }, { list: 'bullet' }], [{ indent: '-1' }, { indent: '+1' }], ['image'] ] } }, articleForm: { cover: { type: 1, images: [] }, content: null, channel_id: null, title: null }, confirmUrl: null, articleId: null } }, computed: {}, created () { this.articleId = this.$route.query.id if (this.articleId) { this.getArticle() } }, mounted () {}, // 问题当从修改文章点击进去的时候 在点击侧边栏中的发布文章 页面不更新 // 解决方法 添加侦听器 watch 它可以监听vue实例中所有的数据变化 包括 $route.query.id watch: { // 此处不能用箭头函数 因为有this指向问题 监听函数有另两个参数 newVal , oldVal '$route.query.id': function (newVal, oldVal) { // 此处重置表单数据 重新响应页面 不能直接让表单数据等于null或空'' 因为取里面的对象数据会报错 // 若有不正常用户选择回退 则可以另当处理 if (newVal) { // 判断业务articleId 存在修改 不存在 发表 this.articleId = this.$route.query.id if (this.articleId) { // 获取数据 填充表单 this.getArticle() } return false } this.articleForm = { cover: { type: 1, images: [] }, content: null, channel_id: null, title: null } // 清空页面id this.articleId = null } }, methods: { async update (draft) { await this.$http.put( `articles/${this.articleId}?draft=${draft}`, this.articleForm ) // 提示信息 this.$message.success(draft ? '存入草稿成功' : '修改成功') this.$router.push('/article') }, async getArticle () { const { data: { data } } = await this.$http.get('articles/' + this.articleId) this.articleForm = data }, async submit (draft) { await this.$http.post(`articles?draft=${draft}`, this.articleForm) // 提示信息 this.$message.success(draft ? '存入草稿成功' : '发布成功') this.$router.push('/article') }, changeType () { this.articleForm.cover.images = [] } }, components: { quillEditor } } </script> <style scoped lang="less"></style>
import streamlit as st import pandas as pd import plotly.graph_objects as go # ======= LAYOUT ======= st.set_page_config(layout='wide') #### Sidebar st.sidebar.header("Operadoras de saúde") ## RANKING DAS 15 MELHORES OPERADORAS - POR BENEFICIÁRIO operadoras = [368253, 359017, 5711, 326305, 6246, 339679, 343889, 701, 393321, 352501, 304701, 346659, 348520, 302147, 335690] # operadoras = sorted(operadoras) st.sidebar.markdown(''' --- Created by [Matheus A. Cantarutti](https://www.linkedin.com/in/matheusalmeidacantarutti/). ''') # with open('style.css') as f: # st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True) # ### Dashboard st.markdown('### Indicadores Carteira') col1, col2, col3 = st.columns(3) col4, col5, col6 = st.columns(3) # ======= LAYOUT ======= if st.sidebar.selectbox('Selecione a Operadora', index=0, options=operadoras) == operadoras[0]: df = pd.read_csv("dados Selecionados/dados_hapvida.csv", sep=",") st.write("Operadora Hapvida") elif st.sidebar.selectbox('Selecione a Operadora', index=1, options=operadoras) == operadoras[1]: df = pd.read_csv("dados Selecionados/dados_notredame.csv", sep=",") st.write("Operadora NotreDame") elif st.sidebar.selectbox('Selecione a Operadora', index=2, options=operadoras) == operadoras[2]: df = pd.read_csv("dados Selecionados/dados_bradesco.csv", sep=",") st.write("Operadora Bradesco Saúde") elif st.sidebar.selectbox('Selecione a Operadora', index=3, options=operadoras) == operadoras[3]: df = pd.read_csv("dados Selecionados/dados_amilassistenciamedica.csv", sep=",") st.write("Operadora Amil Assistencia Médica") elif st.sidebar.selectbox('Selecione a Operadora', index=4, options=operadoras) == operadoras[4]: df = pd.read_csv("dados Selecionados/dados_sulamerica.csv", sep=",") st.write("Operadora Sul América") elif st.sidebar.selectbox('Selecione a Operadora', index=5, options=operadoras) == operadoras[5]: df = pd.read_csv("dados Selecionados/dados_unimednacional.csv", sep=",") st.write("Operadora Unimed Nacional") elif st.sidebar.selectbox('Selecione a Operadora', index=6, options=operadoras) == operadoras[6]: df = pd.read_csv("dados Selecionados/dados_unimedbelohorizonte.csv", sep=",") st.write("Operadora Unimed Belo Horizonte") elif st.sidebar.selectbox('Selecione a Operadora', index=7, options=operadoras) == operadoras[7]: df = pd.read_csv("dados Selecionados/dados_unimedsegurossaude.csv", sep=",") st.write("Operadora Unimed Seguros Saúde") elif st.sidebar.selectbox('Selecione a Operadora', index=8, options=operadoras) == operadoras[8]: df = pd.read_csv("dados Selecionados/dados_unimedrio.csv", sep=",") st.write("Operadora Unimed Rio") elif st.sidebar.selectbox('Selecione a Operadora', index=9, options=operadoras) == operadoras[9]: df = pd.read_csv("dados Selecionados/dados_unimedportoalegre.csv", sep=",") st.write("Operadora Unimed Porto Alegre") elif st.sidebar.selectbox('Selecione a Operadora', index=10, options=operadoras) == operadoras[10]: df = pd.read_csv("dados Selecionados/dados_unimedcuritiba.csv", sep=",") st.write("Operadora Unimed Curitiba") elif st.sidebar.selectbox('Selecione a Operadora', index=11, options=operadoras) == operadoras[11]: df = pd.read_csv("dados Selecionados/dados_caixadeassistencia.csv", sep=",") st.write("Operadora Caixa de Assistencia") elif st.sidebar.selectbox('Selecione a Operadora', index=12, options=operadoras) == operadoras[12]: df = pd.read_csv("dados Selecionados/dados_notredameminas.csv", sep=",") st.write("Operadora NotreDame Minas Gerais") elif st.sidebar.selectbox('Selecione a Operadora', index=13, options=operadoras) == operadoras[13]: df = pd.read_csv("dados Selecionados/dados_preventsenior.csv", sep=",") st.write("Operadora Prevent Senior") else: df = pd.read_csv("dados Selecionados/dados_unimedcampinas.csv", sep=",") st.write("Operadora Unimed Campinas") df.drop('Unnamed: 0', axis=1, inplace=True) Idosos = float((df['P60'].values / df['Beneficiários Totais'].values) * 100) RazaoDependencia = float(((df['P15'].values + df['P60'].values) / df['P1559'].values) * 100) IndiceEnvelhecimento = float((df['P60'].values / df['P15'].values) * 100) MediaAnos = float(df['IDADE MÉDIA'].values) BENEFICIARIOS_COLETIVO = float((df['TOTAL EM COLETIVO'].values / df['TOTAL'].values) * 100) TIPO_BENEFICIARIOS = ["COLETIVO EMPRESARIAL", "INDIVIDUAL OU FAMILIAR", "COLETIVO POR ADESÃO"] COUNT_BENEFICIARIOS = [float(df['COLETIVO EMPRESARIAL'].values), float(df['INDIVIDUAL OU FAMILIAR'].values), float(df['COLETIVO ADESÃO'].values)] fig = go.Figure() fig.add_trace(go.Pie( labels=TIPO_BENEFICIARIOS, values=COUNT_BENEFICIARIOS, hole=.0 )) col1, col2, col3 = st.columns((2.5,2.5,2.5)) # Linha 1 with col1: col1.metric(label="Percentual de Idosos", value=f'{Idosos:.1f}'"%") with col2: col2.metric(label="Razão de Dependência", value=f'{RazaoDependencia:.1f}'"%") with col3: col3.metric(label="Índice de Envelhecimento", value=f'{IndiceEnvelhecimento:.1f}'"%") # Linha 2 col4, col5, col6 = st.columns((2.5,2.5,2.5)) with col4: col4.metric(label="Idade Média", value=f'{MediaAnos:.1f}'" Anos") with col5: st.markdown("### Beneficiários em Planos Coletivos") col5.metric(label="Beneficiários em Planos coletivos", value=f'{BENEFICIARIOS_COLETIVO:.1f}'"%") with col6: col6.plotly_chart(fig)
import type { MsgProps } from './common-msg' export type Platform = 'WEB' | 'APP' | 'ALL' export type Error = Partial<MsgProps> export type OK = Partial<MsgProps> export const Fn = <T>(x: T): T => x; export type Getters<Type> = { [Property in keyof Type as `get${Capitalize<string & Property>}`]: () => Type[Property] }; class success<V, E extends Error> { constructor(private value: V) { } isSuccess = (): this is success<V, E> => true; isFailure = (): this is failure<V, E> => false; run = () => this.value; getValue = () => { return this.value; }; getError = () => { return 'Nothing Error'; }; } class failure<V, E extends Error> { constructor(private error: E) { } isSuccess = (): this is success<V, E> => false; isFailure = (): this is failure<V, E> => true; run = () => { throw this.error; }; getValue = () => { throw this.error; }; getError = () => { return this.error; }; } export const combine = ( results: SuccessOrFailure<any, Error>[] ): SuccessOrFailure<any | boolean, Error> => { for (const result of results) { if (result.isFailure()) return result; } return Success(true); }; export const Success = <V, E extends Error>(value: V) => new success<V, E>(value); export const Failure = <V, E extends Error>(error: E) => new failure<V, E>(error); export type SuccessOrFailure<V, E extends Error> = | success<V, E> | failure<V, E>;
import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:my_task_diary/libraries/applications_library.dart'; class DatesLibrary { DatesLibrary._(); // *** DATE *** // Converti une DateTime en une Date en String avec les heures, minutes, secondes à 0. static String getDateStringFromDateTime({required DateTime date}) { return DateFormat.yMd(ApplicationsLibrary.kLocale.languageCode).format(date); } // Converti une DateTime en Epoch avec les heures, minutes, secondes à 0. static int getEpochFromDateTime({required DateTime date}) { DateTime dateDateTime = DateFormat.yMd(ApplicationsLibrary.kLocale.languageCode).parse(getDateStringFromDateTime(date: date)); return dateDateTime.millisecondsSinceEpoch; } // Converti une Date String en Epoch avec les heures, minutes, secondes à 0. static int getEpochFromDateString({required String date}) { return DateFormat.yMd(ApplicationsLibrary.kLocale.languageCode).parse(date).millisecondsSinceEpoch; } // Converti un int Epoch en string "yyyy/MM/dd" static String getDateStringFromEpoch({required int epoch}) { return DateFormat("yyyy/MM/dd").format(DateTime.fromMillisecondsSinceEpoch(epoch)); } // *** HEURE *** // Converti un TimeOfDay en un Time en String "hh:mm". static String getTimeStringFromTimeOfDay({required TimeOfDay time}) { return "${time.hour}:${time.minute}"; } // Converti un Time en String "hh:mm" en Epoch static int getEpochFromTimeString({required String time}) { return DateFormat("HH:mm").parse(time).millisecondsSinceEpoch; } // Converti un int Epoch en string hh:mm static String getTimeStringFromEpoch({required int epoch}) { return DateFormat("HH:mm").format(DateTime.fromMillisecondsSinceEpoch(epoch)); } // *** DATE + HEURE *** // Converti une date et time epoch en string static String getFullDateAndTimeStringFromEpoch({required int dateEpoch, required int timeEpoch}) { return "${getDateStringFromEpoch(epoch: dateEpoch)} ${getTimeStringFromEpoch(epoch: timeEpoch)}"; } }
// // PostingViewController.swift // Survy // // Created by Mac mini on 2023/05/06. // import UIKit import Model import SnapKit import Toast class PostingViewController: BaseViewController, Coordinating { var currentTags: [Tag] = [] var currentTargets: [Target] = [] var coordinator: Coordinator? var numOfSpecimen: Int = 100 private let selectableOptionHeight: CGFloat = 27 private let defaultCellHeight: CGFloat = 120 var postingService: PostingServiceType var questionCellHeights = Set<CellHeight>() var tableViewTotalHeight: CGFloat { return questionCellHeights.map { $0.height }.reduce(0, +) } private var targetDataSource: UICollectionViewDiffableDataSource<Section, Target>! private var tagDataSource: UICollectionViewDiffableDataSource<Section, Tag>! let marginSize = 12 enum Section { case main } public init(postingService: PostingServiceType) { self.postingService = postingService super.init(nibName: nil, bundle: nil) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let wholeHeight = tableViewTotalHeight + 100 + 52 + 20 + 16 + 100 print("wholeHeight: \(wholeHeight)") scrollView.contentSize = CGSize(width: UIScreen.screenWidth, height: wholeHeight) // FIXME: scroll to the bottom if new question has added let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.height) if wholeHeight > UIScreen.screenHeight - 100 { scrollView.setContentOffset(bottomOffset, animated: false) } } private let customNavBar: CustomNavigationBar = { let navBar = CustomNavigationBar(title: "설문 요청") return navBar }() override func viewDidLoad() { super.viewDidLoad() customNavBar.delegate = self if postingService.numberOfQuestions == 0 { postingService.addQuestion() } registerPostingBlockCollectionView() setupTopCollectionViews() configureTopDataSource() setupNavigationBar() setupLayout() setupTargets() view.backgroundColor = UIColor.postingVCBackground let tapGesture = UITapGestureRecognizer(target: self, action: #selector(otherViewTapped)) view.addGestureRecognizer(tapGesture) setupInitialSnapshot() } // MARK: - CollectionView, TableView Setup private func registerPostingBlockCollectionView() { postingBlockCollectionView.register(PostingBlockCollectionViewCell.self, forCellWithReuseIdentifier: PostingBlockCollectionViewCell.reuseIdentifier) postingBlockCollectionView.register(PostingBlockCollectionFooterCell.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: PostingBlockCollectionFooterCell.reuseIdentifier) postingBlockCollectionView.delegate = self postingBlockCollectionView.dataSource = self } private func setupTopCollectionViews() { let layout = createLayout() selectedTagsCollectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) selectedTargetsCollectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) selectedTagsCollectionView.backgroundColor = .magenta selectedTargetsCollectionView.backgroundColor = .cyan } private func configureTopDataSource() { let tagCellRegistration = UICollectionView.CellRegistration<TagLabelCollectionViewCell, Tag> { (cell, indexPath, tag) in cell.text = tag.name } tagDataSource = UICollectionViewDiffableDataSource<Section, Tag>(collectionView: selectedTagsCollectionView) { (collectionView: UICollectionView, indexPath: IndexPath, identifier: Tag) -> UICollectionViewCell? in return collectionView.dequeueConfiguredReusableCell(using: tagCellRegistration, for: indexPath, item: identifier) } let targetCellRegistration = UICollectionView.CellRegistration<TargetLabelCollectionViewCell, Target> { (cell, indexPath, target) in cell.text = target.name } targetDataSource = UICollectionViewDiffableDataSource<Section, Target>(collectionView: selectedTargetsCollectionView) { (collectionView: UICollectionView, indexPath: IndexPath, identifier: Target) -> UICollectionViewCell? in return collectionView.dequeueConfiguredReusableCell(using: targetCellRegistration, for: indexPath, item: identifier) } } override func updateMyUI() { // questionCellHeights.removeAll() if postingService.selectedTags != currentTags { currentTags = postingService.selectedTags var tagSnapshot = NSDiffableDataSourceSnapshot<Section, Tag>() tagSnapshot.appendSections([.main]) tagSnapshot.appendItems(currentTags) tagDataSource.apply(tagSnapshot) } if postingService.selectedTargets != currentTargets { currentTargets = postingService.selectedTargets var targetSnapshot = NSDiffableDataSourceSnapshot<Section, Target>() targetSnapshot.appendSections([.main]) targetSnapshot.appendItems(currentTargets) self.targetDataSource.apply(targetSnapshot, animatingDifferences: true) } } private func setupInitialSnapshot() { var tagSnapshot = NSDiffableDataSourceSnapshot<Section, Tag>() tagSnapshot.appendSections([.main]) tagSnapshot.appendItems(currentTags, toSection: .main) tagDataSource.apply(tagSnapshot) var targetSnapshot = NSDiffableDataSourceSnapshot<Section, Target>() targetSnapshot.appendSections([.main]) targetSnapshot.appendItems(currentTargets) targetDataSource.apply(targetSnapshot) } func createLayout() -> UICollectionViewLayout { let layout = UICollectionViewCompositionalLayout { (sectionIndex: Int, layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection in // let contentSize = layoutEnvironment.container.effectiveContentSize let columns = 5 let spacing = CGFloat(10) let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(1.0)) let item = NSCollectionLayoutItem(layoutSize: itemSize) let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(1.0)) let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitem: item, count: columns) group.interItemSpacing = .fixed(spacing) let section = NSCollectionLayoutSection(group: group) section.interGroupSpacing = spacing return section } return layout } // MARK: - Helper functions private func setupTargets() { requestingButton.addTarget(self, action: #selector(requestSurveyTapped), for: .touchUpInside) targetButton.addTarget(self, action: #selector(targetTapped), for: .touchUpInside) categoryButton.addTarget(self, action: #selector(categoryTapped), for: .touchUpInside) } // MARK: - Button Actions override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } @objc func otherViewTapped() { view.dismissKeyboard() } @objc func targetTapped(_ sender: UIButton) { view.dismissKeyboard() coordinator?.manipulate(.targetSelection, command: .present) } @objc func categoryTapped(_ sender: UIButton) { view.dismissKeyboard() coordinator?.manipulate(.categorySelection, command: .present) } @objc func requestSurveyTapped(_ sender: UIButton) { print("current PostingQuestions: ") print("number of Questions: \(postingService.numberOfQuestions)") postingService.postingQuestions.forEach { print("question: \($0.question), questionType: \($0.briefQuestionType)") $0.selectableOptions.forEach { print("options: \($0.value)") } } coordinator?.manipulate(.confirmation, command: .present) } @objc func dismissTapped() { postingService.resetQuestions() self.navigationController?.popViewController(animated: true) } // MARK: - Layout private func setupLayout() { navigationController?.setNavigationBarHidden(true, animated: false) [ customNavBar, scrollView, expectedTimeGuideLabel, expectedTimeResultLabel, requestingButton ].forEach { self.view.addSubview($0) } [ targetButton, categoryButton, selectedTargetsCollectionView, selectedTagsCollectionView, postingBlockCollectionView ].forEach { self.scrollView.addSubview($0) } customNavBar.snp.makeConstraints { make in make.leading.trailing.equalToSuperview() make.top.equalTo(view.safeAreaLayoutGuide) make.height.equalTo(50) } requestingButton.snp.makeConstraints { make in make.leading.trailing.equalTo(view.layoutMarginsGuide) make.height.equalTo(50) make.bottom.equalTo(view.safeAreaLayoutGuide) } expectedTimeResultLabel.snp.makeConstraints { make in make.trailing.equalTo(view.layoutMarginsGuide) make.bottom.equalTo(requestingButton.snp.top).offset(-5) make.width.equalTo(50) } expectedTimeGuideLabel.snp.makeConstraints { make in make.trailing.equalTo(expectedTimeResultLabel.snp.leading).offset(-10) make.bottom.equalTo(expectedTimeResultLabel.snp.bottom) } scrollView.snp.makeConstraints { make in make.top.equalTo(view.safeAreaLayoutGuide).offset(50) make.leading.equalToSuperview() make.width.equalTo(UIScreen.screenWidth) make.bottom.equalTo(expectedTimeGuideLabel.snp.top).offset(-10) } targetButton.snp.makeConstraints { make in make.top.equalToSuperview().offset(20) make.leading.equalToSuperview().inset(20) make.height.equalTo(26) } targetButton.addSmallerInsets() selectedTargetsCollectionView.snp.makeConstraints { make in make.top.equalTo(targetButton.snp.top) make.bottom.equalTo(targetButton.snp.bottom) make.leading.equalTo(targetButton.snp.trailing).offset(10) make.width.equalTo(300) } selectedTargetsCollectionView.backgroundColor = .clear categoryButton.snp.makeConstraints { make in make.top.equalTo(targetButton.snp.bottom).offset(20) make.leading.equalToSuperview().inset(20) make.height.equalTo(26) } categoryButton.addSmallerInsets() selectedTagsCollectionView.snp.makeConstraints { make in make.top.equalTo(categoryButton.snp.top) make.bottom.equalTo(categoryButton.snp.bottom) make.leading.equalTo(categoryButton.snp.trailing).offset(10) make.width.equalTo(300) } selectedTagsCollectionView.backgroundColor = .clear postingBlockCollectionView.snp.makeConstraints { make in make.leading.equalToSuperview() make.width.equalTo(UIScreen.screenWidth) make.top.equalTo(categoryButton.snp.bottom).offset(16) make.bottom.equalTo(expectedTimeGuideLabel.snp.top).offset(-10) } } private func setupNavigationBar() { // self.title = "설문 요청" // setupLeftNavigationBar() } private func setupLeftNavigationBar() { let backButton = UIBarButtonItem(image: UIImage.leftChevron, style: .plain, target: self, action: #selector(dismissTapped)) self.navigationItem.leftBarButtonItem = backButton } // MARK: - Views private let scrollView: UIScrollView = { let scrollView = UIScrollView() return scrollView }() private var selectedTargetsCollectionView: UICollectionView! private var selectedTagsCollectionView: UICollectionView! private lazy var postingBlockCollectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.minimumInteritemSpacing = 12 let configuration = UICollectionLayoutListConfiguration(appearance: .plain) let anotherLayout = UICollectionViewCompositionalLayout.list(using: configuration) let someConfig = UICollectionViewCompositionalLayoutConfiguration() someConfig.scrollDirection = .vertical let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.isScrollEnabled = false collectionView.backgroundColor = .clear return collectionView }() private let targetButton: UIButton = { let button = UIButton() let attributedString = NSAttributedString(string: "타겟층", attributes: [.foregroundColor: UIColor.systemBlue, .font: UIFont.systemFont(ofSize: 18, weight: .semibold)]) button.setAttributedTitle(attributedString, for: .normal) button.backgroundColor = UIColor(white: 0.9, alpha: 1) button.layer.cornerRadius = 6 button.clipsToBounds = true return button }() private let categoryButton: UIButton = { let button = UIButton() let attributedString = NSAttributedString(string: "관심사", attributes: [.foregroundColor: UIColor.systemBlue, .font: UIFont.systemFont(ofSize: 18, weight: .semibold)]) button.setAttributedTitle(attributedString, for: .normal) button.backgroundColor = UIColor(white: 0.9, alpha: 1) button.layer.cornerRadius = 6 button.clipsToBounds = true return button }() private let expectedTimeGuideLabel: UILabel = { let label = UILabel() label.text = "예상 소요시간" return label }() private let expectedTimeResultLabel: UILabel = { let label = UILabel() label.text = "1분" label.textAlignment = .right return label }() private let requestingButton: UIButton = { let button = UIButton() button.setTitle("설문 요청하기", for: .normal) button.backgroundColor = UIColor.grayProgress button.layer.cornerRadius = 7 button.clipsToBounds = true return button }() required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PostingViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return max(postingService.numberOfQuestions, 1) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PostingBlockCollectionViewCell.reuseIdentifier, for: indexPath) as! PostingBlockCollectionViewCell cell.postingBlockCollectionViewDelegate = self cell.cellIndex = indexPath.row // let cellHeight = CellHeight(index: indexPath.row, height: 150 + 20) let cellHeight = CellHeight(index: indexPath.row, height: defaultCellHeight + 20) if self.questionCellHeights.filter { $0.index == indexPath.row }.isEmpty { self.questionCellHeights.insert(cellHeight) } viewDidAppear(false) if postingService.postingQuestions.count > indexPath.row { cell.postingQuestion = postingService.postingQuestions[indexPath.row] } return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { switch kind { case UICollectionView.elementKindSectionFooter: let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: PostingBlockCollectionFooterCell.reuseIdentifier, for: indexPath) as! PostingBlockCollectionFooterCell footer.footerDelegate = self return footer default: fatalError() } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { return CGSize(width: UIScreen.screenWidth - 100, height: 100) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 20 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 20 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { // var height: CGFloat = 150 var height: CGFloat = defaultCellHeight if let first = questionCellHeights.first(where: { cellHeight in cellHeight.index == indexPath.row }) { height = first.height } print("dequeueing height: \(height)") return CGSize(width: UIScreen.screenWidth - 40, height: height) } } extension PostingViewController: PostingBlockCollectionViewCellDelegate { func updateUI(cellIndex: Int, postingQuestion: PostingQuestion) { // let postingQuestion = PostingQuestion(index: cellIndex, question: postingQuestion.question, questionType: postingQuestion.briefQuestionType) guard let correspondingCellHeight = questionCellHeights.first(where: { $0.index == cellIndex }) else { fatalError() } questionCellHeights.remove(correspondingCellHeight) let numberOfSelectableOptions = postingQuestion.numberOfOptions // let newCellHeight = CellHeight(index: cellIndex, height: CGFloat(150 + numberOfSelectableOptions * 22)) // 각 selectableOption 의 크기 let newCellHeight = CellHeight(index: cellIndex, height: defaultCellHeight + CGFloat(numberOfSelectableOptions) * self.selectableOptionHeight) // 각 selectableOption 의 크기 print("newCellHeight: \(newCellHeight)") print("cellHeights: ") questionCellHeights.forEach { print("idx: \($0.index), height: \($0.height)") } questionCellHeights.insert(newCellHeight) print("umm ??") postingBlockCollectionView.reloadItems(at: [IndexPath(row: cellIndex, section: 0)]) // TODO: Reload 했을 때, 입력한 값들이 그대로 유지된 채로 셀 크기만 업데이트 한 것 처럼 보이기. } func setPostingQuestionToIndex(postingQuestion: PostingQuestion, index: Int) { postingService.setPostingQuestion(postingQuestion: postingQuestion, index: index) } } extension PostingViewController: PostingBlockCollectionFooterDelegate { func addQuestionButtonTapped() { postingService.addQuestion() DispatchQueue.main.async { self.postingBlockCollectionView.reloadData() } } } extension PostingViewController: CustomNavigationBarDelegate { func dismiss() { postingService.resetQuestions() self.navigationController?.popViewController(animated: true) } }
package com.kuropatin.zenbooking.validation; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; /** * The annotated element must not be {@code null} and must be a valid {@code date} type in format {@code yyyy-mm-dd}. Difference between today date and annotated element date must be at least * {@code minAge} years. * <p> * Accepts {@code CharSequence}. */ @Documented @Target(FIELD) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = NullableBooleanValidator.class) public @interface NullableBoolean { /** * @return the error message template */ String message() default "Should be empty or a boolean value true or false"; /** * @return the groups the constraint belongs to */ Class<?>[] groups() default {}; /** * @return the payload associated to the constraint */ Class<? extends Payload>[] payload() default {}; }
import { Component, OnInit } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { RoleDialogComponent } from './../popups/role-dialog/role-dialog.component'; @Component({ selector: 'app-role', templateUrl: './role.component.html', styleUrls: ['./role.component.css'] }) export class RoleComponent implements OnInit { displayedColumns: string[] = ['position', 'name', 'weight', 'symbol']; dataSource: any; animal: string; name: string; constructor(public dialog: MatDialog) { } ngOnInit(): void { const ELEMENT_DATA: PeriodicElement[] = [ { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' }, { position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' }, { position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' }, { position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' }, { position: 5, name: 'Boron', weight: 10.811, symbol: 'B' }, { position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C' }, { position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N' }, { position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O' }, { position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F' }, { position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne' }, ]; this.dataSource = ELEMENT_DATA; } openDialog() { const dialogRef = this.dialog.open(RoleDialogComponent,{ width: '250px', data: {name: this.name, animal: this.animal} }); dialogRef.afterClosed().subscribe(result => { console.log(`Dialog result: ${result}`); }); } } export interface PeriodicElement { name: string; position: number; weight: number; symbol: string; }
export interface Product { id: string; category: Category; name: string; price: string; isFeatured: boolean; domain: Domain; color: Color; images: Image[]; } export interface Image { id: string; url: string; } export interface Billboard { id: string; label: string; imageUrl: string; } export interface Category { id: string; name: string; billboard: Billboard; } export interface Domain { id: string; name: string; price: string; } export interface Color { id: string; name: string; value: string; }
import { BrowserRouter, Routes, Route} from "react-router-dom"; import Home from "./paginas/home"; import Categorias from "./paginas/categorias"; import Detalle from "./paginas/detalle"; import Nav from "./components/nav/nav"; import Footer from "./components/footer/footer"; import NotFound from "./paginas/notfound" function App() { //linea 11 el path significa la ruta de la pagina a la que voy a entrar// return ( <BrowserRouter> <Nav></Nav> <Routes> <Route path="/" element={<Home/>}/> <Route path="/home" element={<Home/>}/> <Route path="/categorias" element={<Categorias/>}/> <Route path="/detalle/:id" element={<Detalle/>}/> <Route path="*" element={<NotFound/>}/> </Routes> <Footer></Footer> </BrowserRouter> ); } export default App;
import React, { useEffect } from 'react'; import styled from 'styled-components'; import { useLanguage } from '../../contexts/LanguageContext'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faXmark } from '@fortawesome/free-solid-svg-icons'; const Container = styled.div` justify-content: space-between; align-items: center; display: flex; width: 100%; min-height: 50px; padding: 10px 20px; @media screen and (max-width: 950px) { width: 90%; } @media screen and (max-width: 650px) { width: 95%; } &:hover { background-color: rgba(0, 0, 0, 0.3); border-radius: 50px; } .left { display: flex; flex-direction: row; align-items: center; justify-content: center; margin-left: 10px; gap: 10px; @media screen and (max-width: 750px) { margin-left: 0px; } .product_title { font-size: 1.3rem; width: 200px; max-width: 200px; overflow: hidden; @media screen and (max-width: 750px) { font-size: 0.9rem; max-width: 130px; } } } .radio[type='checkbox'] { border-radius: 10%; height: 20px; width: 20px; background-color: green; } .radio[type='checkbox']:checked { color: green; border-radius: 50%; } .center { display: flex; flex: 0.5; gap: 10px; justify-content: space-evenly; margin: 0 20px; @media screen and (max-width: 650px) { min-width: 120px; } .group { text-align: center; } .description { opacity: 0.7; font-size: 0.7rem; } .quantative { font-size: 1.2rem; @media screen and (max-width: 750px) { font-size: 1rem; } } span { font-size: 0.9rem; } } .removeProduct { margin-right: 10px; width: 25px; height: 25px; text-align: center; display: flex; align-items: center; justify-content: center; &:hover { border: 1px solid; border-radius: 50%; border-color: ${(props) => (props.darkMode ? 'rgba(255, 0, 0, 0.7)' : 'rgba(255, 0, 0, 0.7)')}; cursor: pointer; color: rgba(255, 0, 0, 0.7); } } `; const ReadyProduct = ({ item, setRemoveProduct, setProductToRemove, setProductIDRemove }) => { const theReadyProduct = item; const totalProductPrice = theReadyProduct.quantity * theReadyProduct.price; const { language, translate, translateProductNames } = useLanguage(); const handleRemoveProduct = (item, id) => { setProductToRemove(item.name[language]); setProductIDRemove(id); setRemoveProduct((prev) => !prev); }; return ( <Container key={theReadyProduct.name}> <div className="left"> <div className="product_title">{theReadyProduct.name[language]}</div> </div> <div className="center"> {theReadyProduct.quantity && theReadyProduct.quantity != 0 && ( <div className="group"> <div className="description">{translate('quantity')}</div> <div className="quantative"> {theReadyProduct.quantity} {theReadyProduct.unit} </div> </div> )} {theReadyProduct.price && theReadyProduct.price != 0 && ( <div className="group"> <div className="description">{translate('price')}</div> <div className="quantative"> {theReadyProduct.price} <span>€</span> </div> </div> )} {totalProductPrice ? ( <div className="group"> <div className="description">{translate('total')}</div> <div className="quantative"> {totalProductPrice} <span>€</span> </div> </div> ) : ( '' )} </div> <div onClick={() => handleRemoveProduct(item, item.uniqueKey)} className="removeProduct light largest remove-product-ready"> <FontAwesomeIcon icon={faXmark} /> </div> </Container> ); }; export default ReadyProduct;
<template> <div class="relative group cursor-pointer"> <div class="flex items-center justify-center"> <button class="relative menu-hover my-2 py-2 font-medium text-secondaryColor lg:group-hover:text-thirdColor lg:text-xl lg:mx-4" > {{ $t(title) }} </button> <span :class="{ ' lg:right-2': $i18n.locale === 'en', ' lg:left-2': $i18n.locale === 'ar', }" class="relative" > <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" class="h-4 w-4 transition-transform duration-300 transform rotate-0 lg:group-hover:text-thirdColor group-hover:rotate-180" > <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" ></path> </svg> </span> </div> <ul class="invisible absolute overflow-y-auto max-h-48 lg:max-h-fit z-50 py-1 px-4 text-gray-800 shadow-xl group-hover:visible lg:group-hover:absolute group-hover:relative lg:absolute lg:group-hover:grid lg:group-hover:grid-cols-3 lg:w-screen lg:bg-white lg:max-w-screen-lg lg:overflow-y-hidden" > <li v-for="category in categories" :key="category.category" class="flex items-center m-2" > <RouterLink :to="{ name: 'course', params: { courseId: category.id, title: category.id }, }" append="false" @click="toggleMenu" class="text-secondaryColor text-sm m-4 w-fit font-semibold lg:hover:text-thirdColor" >{{ $t(category.category) }} </RouterLink> <svg :class="{ 'rotate-180': $i18n.locale === 'ar' }" class="w-2 h-2 text-thirdColor" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 8 14" > <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m1 13 5.7-5.326a.909.909 0 0 0 0-1.348L1 1" /> </svg> </li> </ul> </div> </template> <script> export default { props: ['title', 'categories', 'toggleMenu'], data() { return { isMenuOpen: true, }; }, methods: { closeDropdown() { this.isMenuOpen = false; }, }, }; </script>
import * as sinon from 'sinon'; import { options, testResponse } from '../constants'; import { expect } from 'chai'; import { get } from 'lodash'; import { NonfigRequest } from '../../src/request'; import { nonfig, Nonfig } from '../../index'; import { Configuration } from '../../src/configuration.entity'; describe('Find Configurations by path', () => { let api: Nonfig; let request: sinon.SinonStub; beforeEach(() => { api = nonfig(options); request = sinon.stub(NonfigRequest, 'exec'); }); afterEach(() => { request.restore(); }); it('should return configuration', async () => { const path = '/some/path/'; request.resolves(testResponse); const configuration = await api.findByPath(path); expect(request.calledOnce).to.be.true; expect((configuration as Configuration[]).length).to.equal(1); expect(get(configuration, '0.path')).to.equal(path); }); it('should return empty array for non-existent path ', async () => { const path = 'non-existent'; request.resolves([]); const configurations = await api.findByPath(path); expect(request.calledOnce).to.be.true; expect((configurations as Configuration[]).length).to.equal(0); }); });
<template> <main class="main-content"> <div class="sidebar"> <SidebarComponent /> </div> <div class="game-cards"> <div v-for="game in games" :key="game.id" class="game-card"> <GameCard :game="game" /> </div> </div> </main> </template> <script> import "@/styles/home.css"; import GameCard from "./GameCardComponent"; import SidebarComponent from "./SidebarComponent.vue"; export default { components: { GameCard, SidebarComponent, }, data() { return { games: [], }; }, mounted() { this.$store.dispatch("fetchGames").then(() => { this.games = this.$store.state.games; }); }, }; </script>
import React from 'react'; import { useSpring, animated } from '@react-spring/web'; import './App.css'; const sections = [ { id: 'about', title: 'About Me', image: 'DronePhotos\Hoan Bridge.jpg', content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam venenatis quam at libero tristique, a venenatis eros lacinia. Donec ut nisl quis lacus cursus bibendum. Phasellus tincidunt orci vitae quam pretium, at mollis metus eleifend.' }, { id: 'portfolio', title: 'Portfolio', image: 'DronePhotos\Lakefront.jpg', content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam venenatis quam at libero tristique, a venenatis eros lacinia. Donec ut nisl quis lacus cursus bibendum. Phasellus tincidunt orci vitae quam pretium, at mollis metus eleifend.' }, { id: 'contact', title: 'Contact', image: 'DronePhotos\DJI_0268.jpg', content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam venenatis quam at libero tristique, a venenatis eros lacinia. Donec ut nisl quis lacus cursus bibendum. Phasellus tincidunt orci vitae quam pretium, at mollis metus eleifend.' } ]; function Section({ id, title, image, content }) { const [props, set] = useSpring(() => ({ opacity: 0, transform: 'translateY(50px)', })); React.useEffect(() => { const handleScroll = () => { const section = document.getElementById(id); const rect = section.getBoundingClientRect(); if (rect.top < window.innerHeight && rect.bottom >= 0) { set({ opacity: 1, transform: 'translateY(0px)' }); } else { set({ opacity: 0, transform: 'translateY(50px)' }); } }; window.addEventListener('scroll', handleScroll); return () => window.removeEventListener('scroll', handleScroll); }, [id, set]); return ( <animated.section id={id} className="container" style={props}> <h2>{title}</h2> <img src={image} alt={`${title} Photo`} className="content-photo" /> <p>{content}</p> </animated.section> ); } function App() { return ( <> <header> <div className="container"> <img src="Kraft_Headshot3.jpg" alt="Your Photo" className="profile-photo" /> <h1>Your Name</h1> <p className="subtitle">Your Subtitle or Tagline</p> </div> </header> <nav> <div className="container"> <ul> <li><a href="#about">About</a></li> <li><a href="#portfolio">Portfolio</a></li> <li><a href="#contact">Contact</a></li> </ul> </div> </nav> <main> {sections.map(section => ( <Section key={section.id} {...section} /> ))} </main> <footer> <div className="container"> <p>&copy; 2024 Your Name. All Rights Reserved.</p> </div> </footer> </> ); } export default App;
import { ActivityIndicator, Text, TouchableOpacity, TouchableOpacityProps, } from 'react-native'; import Components from '../Themes/Components'; import React from 'react'; import Colors from '../Themes/Colors'; type Props = { isPending?: boolean | undefined; text: string; } & TouchableOpacityProps; const Button = (props: Props) => { return ( <TouchableOpacity style={Components.primaryButton} {...props}> {!props.isPending && ( <Text style={Components.primaryButtonText}>{props.text}</Text> )} {props.isPending && ( <ActivityIndicator size="small" color={Colors.activityIndicator} /> )} </TouchableOpacity> ); }; export default Button;
<div class="content-container"> {{#if isPersonalPost}} <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" data-bs-whatever="@mdo">Edit Post</button> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel">Edit Post</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body d-flex"> <form class="form post-form"> <div class="mb-3"> <label for="recipient-name" class="col-form-label">Enter Post Title:</label> <input type="text" class="form-control" id="edit-post-title"> </div> <div class="mb-3"> <label for="message-text" class="col-form-label">Enter Post Body</label> <textarea class="form-control" id="edit-post-text"></textarea> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="click" class="btn btn-primary" id="edit-post-button">Edit Post</button> <button class="btn btn-primary" type="click" id="delete-post">Delete Post</button> </div> </div> </div> </div> {{/if}} <div class="card single-post"> <div class="card-header"> {{title}} </div> <div class="card-body"> <blockquote class="blockquote mb-0"> <p>{{post_text}}</p> <footer class="blockquote-footer">Created by {{user.username}} on <cite title="Source Title">{{format_date createdAt}}</cite></footer> </blockquote> </div> </div> <div class="text-center" id="single-post" data-postId="{{id}}"> <br> {{#if logged_in}} <form id="signup" class="form comment-form"> <div class="form-group"> <label for="name-signup"></label> <input type="text" class="form-control" id="comment-input" aria-label="Username" aria-describedby="addon-wrapping"> <div class="form-group"> <button class="btn btn-primary mt-2" type="submit">submit comment</button> </div> </form> {{else}} <h4>sign in to leave a comment</h4> {{/if}} <h2 class="white-text">Comments</h2> {{#each comments as |comment| }} <div class="comments-containter mb-3"> <h3>{{comment.user.username}}</h3> <p>{{comment.comment_text}}</p> <p>created on {{format_date createdAt}}</p> </div> {{/each}} </div> <div class="create-post-button"></div> </div> {{#if logged_in}} <script src="../js/logout.js"></script> <script src="../js/Comment.js"></script> <script src="../js/Post.js"></script> {{/if}}
import { BaseComponent } from "./base/baseComponent.js" import { DeployedTower } from "./towers/deployedTower.js" /** * This component stores all the information about the towers that are out on the map * In future, might be best to remove the sprite creation functions out */ export class TowersComponent extends BaseComponent { constructor(sprite_handler, mapSpriteSize){ super() this.mapSpriteSize = mapSpriteSize this.sprite_handler = sprite_handler this.towerStateHashPrev = "" this.observers = [this] this.setEventListeners() this.isSimulation = false } // Setter for tower config setData(towerConfig, playerConfig, thisPlayer) { this.towerConfig = towerConfig this.playerConfig = playerConfig this.thisPlayer = thisPlayer } setSimulation() { this.isSimulation = true } subscribe(observer) { this.observers.push(observer) } addPlacedTower(type, name, playerID, row, col) { const x = col * this.mapSpriteSize + this.mapSpriteSize / 2; const y = row * this.mapSpriteSize + this.mapSpriteSize / 2; const isThisPlayer = (playerID == this.thisPlayer) const colour = (!this.isSimulation) ? this.playerConfig[playerID].colour : "#FFFFFF" let sprite = new DeployedTower(type, name, x, y, this.towerConfig, playerID, colour, isThisPlayer) if (isThisPlayer) { // TODO check if the playerID exist this.observers.forEach((observer) => {sprite.subscribe(observer)}) } this.addChild(sprite) } update(towerData) { let towerStateObjects = towerData["objects"]; let towerStateHash = towerData["hash"]; if (towerStateHash != this.towerStateHashPrev) { this.towerStateHashPrev = towerStateHash // Identify tower not in container but in server update for (let nameIdx = 0; nameIdx < towerStateObjects.length; nameIdx++) { let found = false; for (let towerSpriteIdx = this.children.length - 1; towerSpriteIdx >= 0; towerSpriteIdx--) { found = (this.children[towerSpriteIdx].name == towerStateObjects[nameIdx].name) if (found) break; } if (!found) { this.addPlacedTower(towerStateObjects[nameIdx].type, towerStateObjects[nameIdx].name, towerStateObjects[nameIdx].playerID, towerStateObjects[nameIdx].position.row, towerStateObjects[nameIdx].position.col) } } // Search for tower in container but not in server update for (let towerSpriteIdx = this.children.length - 1; towerSpriteIdx >= 0; towerSpriteIdx--) { let found = false; for (let towerIdx=0; towerIdx < towerStateObjects.length; towerIdx++) { found = (this.children[towerSpriteIdx].name == towerStateObjects[towerIdx].name) if (found) break; } if (!found) { // Tower has been removed on server, remove it from the client view this.removeChildAt(towerSpriteIdx) } } } // Update state of towers present in server update towerStateObjects.forEach((tower) => { let towerToUpdate = this.getChildByName(tower.name) towerToUpdate.setRotation(tower.angle) towerToUpdate.level = tower.level towerToUpdate.aim = tower.aim if (towerToUpdate.range !== tower.range) { towerToUpdate.updateRange(tower.range) } if (tower.hasShot) { towerToUpdate.shoot() } // Update the tower statsistics, but only store stats for towers a playerID owns if (tower.playerID == this.thisPlayer) { towerToUpdate.update(tower.stats, tower.upgrades) } }) } setEventListeners() { this.on("clickDeployedTower", (tower) => { let pos = this.getChildIndex(tower) if (pos > 0) { // When a tower is clicked on we want it to render above the other towers // This is that the range sprite does not obfiscate them let endIdx = this.children.length - 1 let tmp = this.getChildAt(pos) this.children[pos] = this.children[endIdx] this.children[endIdx] = tmp } }) } startInteraction() { this._setContainerInteraction(this, true) } stopInteraction() { this._setContainerInteraction(this, false) } disableTowers() { this.children.forEach((tower) => { tower.interactiveChildren = false }) } enableTowers() { this.children.forEach((tower) => { tower.interactiveChildren = true }) } enableTowerByName(name) { this.getChildByName(name).interactiveChildren = true } tick() { super.tick() this.children.forEach((tower) => { tower.tick() }) } }
## import data from Gallagher et al 2021, supplementary in Wetland Soils ## from Tasmania, AUS ## export for marsh soil C # contact Tania Maxwell, [email protected] # 22.07.22 library(tidyverse) input_file01 <- "reports/03_data_format/data/core_level/Gallagher_2021_SI/Gallagher_2021_TableS2.csv" input_data01 <- read.csv(input_file01) input_data01 <- input_data01 %>% rename_with(~ gsub("..", "_", .x, fixed = TRUE)) %>% #replacing .. in columns by _ rename_with(~ gsub(".", "_", .x, fixed = TRUE)) #replacing . in columns by _ plot(input_data01$TOC_perc, input_data01$Dry_bulk_density_g_ml) ##### add informational source_name <- "Gallagher et al 2021" author_initials <- "JBG" input_data02 <- input_data01 %>% mutate(Source = source_name, Source_abbr = author_initials, Site_name = paste(Source_abbr, Site_No), Habitat_type = "Salt marsh", Country = "Australia") %>% rename(Plot = Site_No) #### reformat data #### input_data03 <- input_data02 %>% rename(OC_perc = TOC_perc, BD_reported_g_cm3 = Dry_bulk_density_g_ml) %>% #1g/ml = 1 g/cm3 mutate(Year_collected = "2018") %>% mutate(accuracy_flag = "direct from dataset", accuracy_code = "1") %>% mutate(Treatment = "Post-fires, input of black carbon") %>% mutate(Method = "EA") ## edit depth #An open-faced ‘Russian Peat Corer’ was used to take 50 cm cores of uncompressed #sediment for macro char profiles in vegetated salt marsh soils and stock measurements # within seagrass stands. The remaining salt marsh stock samples were exhumed carefully # with a PVC pipe and shovel from the base of the soil, where quaternary sands mark the # depth of the salt marsh accumulation. Samples were immediately put on ice before transport. # The sample cores were mixed well within sealed plastic bags to physically represent the stock # variables average; after which a measured volume (≥ 5 cm3) was taken for dry bulk density # with a cut-off 20 cm3 syringe, in the manner of a piston corer. After drying at 60 °C # the remaining mixed samples were shaken and sieved through a 200 μm mesh to remove both # roots and large shells pieces before further processing for organic matter and # elemental carbon analysis (Chew and Gallagher 2018). # --> it seems that "Soil_depth_cm" is the lower depth, and the sample comes from 0 to Soil_depth_cm input_data04 <- input_data03 %>% mutate(U_depth_cm = 0) %>% rename(L_depth_cm = Soil_depth_cm) %>% mutate(L_depth_cm = case_when(L_depth_cm == ">30" ~ "30", # unsure about the sedbury creek site TRUE ~ L_depth_cm)) %>% mutate(U_depth_m = as.numeric(U_depth_cm)/100 , #cm to m L_depth_m = as.numeric(L_depth_cm)/100, DOI = "https://doi.org/10.1007/s13157-021-01460-3")# cm to m #### export #### export_data01 <- input_data04 %>% dplyr::select(Source, Site_name, Site, Plot, Treatment, Habitat_type, Country, Year_collected, Latitude, Longitude, accuracy_flag, accuracy_code, U_depth_m, L_depth_m, Method, OC_perc, BD_reported_g_cm3, DOI) export_data02 <- export_data01 %>% relocate(Source, Site_name, Site, Plot, Treatment, Habitat_type, Latitude, Longitude, accuracy_flag, accuracy_code, Country, Year_collected, .before = U_depth_m) %>% arrange(Site, Habitat_type) ## export path_out = 'reports/03_data_format/data/exported/' export_file <- paste(path_out, source_name, ".csv", sep = '') export_df <- export_data02 write.csv(export_df, export_file)
// Import your Session model const Session = require('../models/session'); // Route handler to get free sessions const getFreeSessions = async (req, res) => { try { const sessions = await Session.find({ status: 'free' }); const formattedSessions = sessions.map(({ wardenId, dayOfWeek, time, slotDetails, status }) => ({ wardenId, dayOfWeek, time, slotDetails, status, })); res.json(formattedSessions); } catch (error) { console.error(error); res.sendStatus(500); } }; const bookSession = async (req, res) => { try { const { wardenId, dayOfWeek, time, slotDetails } = req.body; const session = new Session({ wardenId, dayOfWeek, time, slotDetails, status: 'booked', }); await session.save(); const updatedSlot = await Session.findOneAndUpdate( { wardenId, dayOfWeek, time, status: 'free' }, { status: 'booked' }, { new: true } ); res.json({ message: 'Session booked successfully', bookedSession: session, updatedSlot }); } catch (error) { console.error('Error booking session:', error); res.status(500).json({ message: 'Internal server error' }); } }; const getPendingSessions = async (req, res) => { try { const wardenId = req.user.wardenId; const pendingSessions = await Session.find({ wardenId, status: 'pending' }); res.json(pendingSessions); } catch (error) { console.error('Error fetching pending sessions:', error); res.status(500).json({ message: 'Internal server error' }); } }; const hardcodedSessions = [ { wardenId: 'B', dayOfWeek: 4, time: '10:00', slotDetails: 'Slot A', status: 'free' }, { wardenId: 'B', dayOfWeek: 5, time: '10:00', slotDetails: 'Slot A', status: 'free' }, ]; const addSessions = async (req, res) => { try { const insertedSessions = await Session.create(hardcodedSessions); res.json({ message: 'Sessions added to the database', insertedSessions }); } catch (error) { console.error(error); res.status(500).json({ message: 'Internal server error' }); } }; module.exports = { getFreeSessions, bookSession, getPendingSessions, addSessions };
package com.finalproject.travelagency.service; import com.finalproject.travelagency.auth.AuthenticationService; import com.finalproject.travelagency.exception.UserNotFoundException; import com.finalproject.travelagency.model.User; import com.finalproject.travelagency.repository.UserRepository; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserService { private final UserRepository userRepository; private final AuthenticationService authenticationService; @Autowired public UserService(UserRepository userRepository, AuthenticationService authenticationService) { this.userRepository = userRepository; this.authenticationService = authenticationService; } public User addUser(User user){ user.setPassword(authenticationService.encodePassword(user.getPassword())); return userRepository.save(user); } public List<User> getAllUsers(){ return userRepository.findAll(); } public User updateUser(User user, Long id){ User newUser = userRepository.findUserById(id) .orElseThrow(() -> new UserNotFoundException("User with id=" + id + "was not found.")); newUser.setId(newUser.getId()); newUser.setCity(user.getCity()); newUser.setAddress(user.getAddress()); newUser.setEmail(newUser.getEmail()); newUser.setFirstname(user.getFirstname()); newUser.setLastname(user.getLastname()); newUser.setDateOfBirth(user.getDateOfBirth()); newUser.setPesel(user.getPesel()); newUser.setPhoneNumber(user.getPhoneNumber()); newUser.setPassword(authenticationService.encodePassword(newUser.getPassword())); return userRepository.save(newUser); } public User findUserById(Long id){ return userRepository.findUserById(id) .orElseThrow(() -> new UserNotFoundException("User with id=" + id + "was not found.")); } public void deleteUser(Long id){ userRepository.deleteById(id); } }
import { inject, Injectable } from '@angular/core'; import { filter, map } from 'rxjs/operators'; import { ActivatedRoute, NavigationEnd, Router } from '@angular/router'; import { JsonLdService, SeoSocialShareData, SeoSocialShareService } from 'ngx-seo'; import { BehaviorSubject, Observable } from 'rxjs'; import { SeoRouteData } from '../models/seo-route-data.model'; const BASE_URL = `https://veilige-kopie-identiteitskaart.be`; @Injectable({ providedIn: 'root', }) export class RouteHelper { readonly #router = inject(Router); readonly #activatedRoute = inject(ActivatedRoute); readonly #seoSocialShareService = inject(SeoSocialShareService); readonly #jsonLdService = inject(JsonLdService); readonly currentUrl$: Observable<string>; readonly #currentUrl = new BehaviorSubject<string>(''); constructor( ) { this.#setupRouting(); this.currentUrl$ = this.#currentUrl.asObservable(); } #setupRouting() { this.#router.events.pipe( filter(event => event instanceof NavigationEnd), map(() => this.#activatedRoute), map(route => { while (route.firstChild) { route = route.firstChild; } return route; }), filter(route => route.outlet === 'primary'), ).subscribe((route: ActivatedRoute) => { const seo: any = route.snapshot.data['seo'] as SeoRouteData; this.#currentUrl.next(this.#router.routerState.snapshot.url); if (seo) { const jsonLd = this.#jsonLdService.getObject('Website', { name: seo.title, url: BASE_URL + this.#router.routerState.snapshot.url, }); this.#jsonLdService.setData(jsonLd); const seoData: SeoSocialShareData = { title: seo.title, description: seo.description, image: BASE_URL + seo.shareImg, url: BASE_URL + this.#router.routerState.snapshot.url, type: 'website', }; this.#seoSocialShareService.setData(seoData); } }); } }
import MeetupDetail from "../../components/meetups/MeetupDetail"; import { MongoClient, ObjectId } from "mongodb"; import Head from "next/head"; function MeetupDetails(props) { return ( <> <Head> <title>{props.meetupData.title}</title> <meta name="description" content={props.meetupData.description} /> </Head> <MeetupDetail image={props.meetupData.image} title={props.meetupData.title} address={props.meetupData.address} description={props.meetupData.description} /> </> ); } export async function getStaticPaths() { const client = await MongoClient.connect( "mongodb+srv://thekatrin:[email protected]/?retryWrites=true&w=majority" ); const db = client.db(); const meetupsCollection = db.collection("meetups"); const meetups = await meetupsCollection.find({}, { _id: 1 }).toArray(); client.close(); return { fallback: false, // all paths paths: meetups.map((meetup) => ({ params: { meetupId: meetup._id.toString() }, })), // [ // { // params: { // meetupId: "m1", // }, // }, // { // params: { // meetupId: "m2", // }, // }, // ], }; } export async function getStaticProps(context) { //fetch data for single meetup const meetupId = context.params.meetupId; const client = await MongoClient.connect( "mongodb+srv://thekatrin:[email protected]/?retryWrites=true&w=majority" ); const db = client.db(); const meetupsCollection = db.collection("meetups"); const selectedMeetup = await meetupsCollection.findOne({ _id: new ObjectId(meetupId), }); client.close(); return { props: { meetupData: { id: selectedMeetup._id.toString(), title: selectedMeetup.title, address: selectedMeetup.address, image: selectedMeetup.image, description: selectedMeetup.description, }, // { // id: meetupId, // image: // "https://upload.wikimedia.org/wikipedia/commons/thumb/1/12/Kastellet_citadel_on_Kastellholmen_Stockholm_2016_02.jpg/1024px-Kastellet_citadel_on_Kastellholmen_Stockholm_2016_02.jpg", // title: "A first Meetup in Stockholm", // address: "Some street, 5", // description: "The meetup description", // }, }, }; } export default MeetupDetails;
#include <iostream> #include <SDL.h> #include <SDL_ttf.h> #include "Ball.h" #include "Paddle.h" #include "PlayerScore.h" #include "Utils.h" #include <chrono> bool running = true; float deltaTime = 0.0f; int player1Score = 0; int player2Score = 0; enum Buttons { Paddle1Up, Paddle1Down, Paddle2Up, Paddle2Down, }; bool buttons[4] = {}; //Using Separating Axis Theorem (SAT) for checks Utils::Contact CheckPaddleCollisions(Ball const& ball, Paddle const& paddle) { float ballLeft = ball.position.x; float ballRight = ball.position.x + Utils::BALL_WIDTH; float ballTop = ball.position.y; float ballBottom = ball.position.y + Utils::BALL_HEIGHT; float paddleLeft = paddle.position.x; float paddleRight = paddle.position.x + Utils::PADDLE_WIDTH; float paddleTop = paddle.position.y; float paddleBottom = paddle.position.y + Utils::PADDLE_HEIGHT; Utils::Contact contact{}; if (ballLeft >= paddleRight) { return contact; } if (ballRight <= paddleLeft) { return contact; } if (ballTop >= paddleBottom) { return contact; } if (ballBottom <= paddleTop) { return contact; } float paddleRangeUpper = paddleBottom - (2.0f * Utils::PADDLE_HEIGHT / 3.0f); float paddleRangeMiddle = paddleBottom - (Utils::PADDLE_HEIGHT / 3.0f); //left side if (ball.velocity.x < 0) { contact.penetrationAmount = paddleRight - ballLeft; } //right side of the screen else if (ball.velocity.x > 0) { contact.penetrationAmount = paddleLeft - ballRight; } if ((ballBottom > paddleTop) && (ballBottom < paddleRangeUpper)) { contact.type = Utils::CollisionType::Top; } else if ((ballBottom > paddleRangeUpper) && (ballBottom < paddleRangeMiddle)) { contact.type = Utils::CollisionType::Middle; } else { contact.type = Utils::CollisionType::Bottom; } return contact; } //Using Separating Axis Theorem (SAT) for checks Utils::Contact CheckWallCollision(Ball const& ball) { float ballLeft = ball.position.x; float ballRight = ball.position.x + Utils::BALL_WIDTH; float ballTop = ball.position.y; float ballBottom = ball.position.y + Utils::BALL_HEIGHT; Utils::Contact contact{}; if (ballLeft < 0.0f) { contact.type = Utils::CollisionType::Left; } else if (ballRight > Utils::WINDOW_WIDTH) { contact.type = Utils::CollisionType::Right; } else if (ballTop < 0.0f) { contact.type = Utils::CollisionType::Top; contact.penetrationAmount = -ballTop; } else if (ballBottom > Utils::WINDOW_HEIGHT) { contact.type = Utils::CollisionType::Bottom; contact.penetrationAmount = Utils::WINDOW_HEIGHT - ballBottom; } return contact; } int main(int argc, char* args[]) { //Initialisation if (SDL_Init(SDL_INIT_VIDEO) != 0) { std::cout << "Error with SDL_Init : " << SDL_GetError() << std::endl; return -1; }; TTF_Init(); SDL_Window* gameWindow = SDL_CreateWindow("Pong", 300, 150, Utils::WINDOW_WIDTH, Utils::WINDOW_HEIGHT, SDL_WINDOW_RESIZABLE); SDL_Renderer* renderer = SDL_CreateRenderer(gameWindow, -1, 0); SDL_Event event; //Score TTF_Font* font = TTF_OpenFont("./Assets/font/Roboto-Black.ttf", 40); PlayerScore player1ScoreText(Vector2(Utils::WINDOW_WIDTH / 4, 20), renderer, font); PlayerScore player2ScoreText(Vector2(3 * Utils::WINDOW_WIDTH / 4, 20), renderer, font); //Create ball Ball ball(Vector2((Utils::WINDOW_WIDTH / 2.0f) - (Utils::BALL_WIDTH / 2.0f), (Utils::WINDOW_HEIGHT / 2.0f) - (Utils::BALL_WIDTH / 2.0f)), Vector2(Utils::BALL_SPEED, 0.0f)); //CreatePaddle Paddle paddle1(Vector2(50.0f, (Utils::WINDOW_HEIGHT / 2.0f) - (Utils::PADDLE_HEIGHT / 2.0f)), Vector2(0.0f, 0.0f)); Paddle paddle2(Vector2(Utils::WINDOW_WIDTH - 50.0f, (Utils::WINDOW_HEIGHT / 2.0f) - Utils::PADDLE_HEIGHT / 2.0f), Vector2(0.0f, 0.0f)); //Game loop while (running) { auto startTime = std::chrono::high_resolution_clock::now(); while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { running = false; } else if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_ESCAPE) { running = false; } else if (event.key.keysym.sym == SDLK_z) { buttons[Buttons::Paddle1Up] = true; } else if (event.key.keysym.sym == SDLK_s) { buttons[Buttons::Paddle1Down] = true; } else if (event.key.keysym.sym == SDLK_UP) { buttons[Buttons::Paddle2Up] = true; } else if (event.key.keysym.sym == SDLK_DOWN) { buttons[Buttons::Paddle2Down] = true; } } else if (event.type == SDL_KEYUP) { if (event.key.keysym.sym == SDLK_z) { buttons[Buttons::Paddle1Up] = false; } else if (event.key.keysym.sym == SDLK_s) { buttons[Buttons::Paddle1Down] = false; } else if (event.key.keysym.sym == SDLK_UP) { buttons[Buttons::Paddle2Up] = false; } else if (event.key.keysym.sym == SDLK_DOWN) { buttons[Buttons::Paddle2Down] = false; } } } if (buttons[Buttons::Paddle1Up]) { paddle1.velocity.y = -Utils::PADDLE_SPEED; } else if (buttons[Buttons::Paddle1Down]) { paddle1.velocity.y = Utils::PADDLE_SPEED; } else { paddle1.velocity.y = 0.0f; } if (buttons[Buttons::Paddle2Up]) { paddle2.velocity.y = -Utils::PADDLE_SPEED; } else if (buttons[Buttons::Paddle2Down]) { paddle2.velocity.y = Utils::PADDLE_SPEED; } else { paddle2.velocity.y = 0.0f; } paddle1.Update(deltaTime); paddle2.Update(deltaTime); ball.Update(deltaTime); Utils::Contact contactPaddle1 = CheckPaddleCollisions(ball, paddle1); Utils::Contact contactPaddl2 = CheckPaddleCollisions(ball, paddle2); Utils::Contact contactWalls = CheckWallCollision(ball); if (contactPaddle1.type != Utils::CollisionType::None) { ball.CollideWithPaddle(contactPaddle1); } else if (contactPaddl2.type != Utils::CollisionType::None) { ball.CollideWithPaddle(contactPaddl2); } else if (contactWalls.type != Utils::CollisionType::None) { ball.CollideWithWalls(contactWalls); if (contactWalls.type == Utils::CollisionType::Left) { ++player2Score; player2ScoreText.SetScore(player2Score); } else if (contactWalls.type == Utils::CollisionType::Right) { ++player1Score; player1ScoreText.SetScore(player1Score); } } SDL_SetRenderDrawColor(renderer, 0x0, 0x0, 0x0, 0xFF); SDL_RenderClear(renderer); //Draw middle bar SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); for (int y = 0; y < Utils::WINDOW_HEIGHT; y++) { if (y % 5) { SDL_RenderDrawPoint(renderer, Utils::WINDOW_WIDTH / 2, y); } } ball.DrawBall(renderer); paddle1.DrawPaddle(renderer); paddle2.DrawPaddle(renderer); player1ScoreText.Draw(); player2ScoreText.Draw(); SDL_RenderPresent(renderer); auto stopTime = std::chrono::high_resolution_clock::now(); deltaTime = std::chrono::duration<float, std::chrono::milliseconds::period>(stopTime - startTime).count(); } //Clean up SDL_DestroyRenderer(renderer); SDL_DestroyWindow(gameWindow); TTF_CloseFont(font); TTF_Quit(); SDL_Quit(); return 0; }
// SPDX-Wicense-Identifiew: GPW-2.0 /* * Impwementation of HKDF ("HMAC-based Extwact-and-Expand Key Dewivation * Function"), aka WFC 5869. See awso the owiginaw papew (Kwawczyk 2010): * "Cwyptogwaphic Extwaction and Key Dewivation: The HKDF Scheme". * * This is used to dewive keys fwom the fscwypt mastew keys. * * Copywight 2019 Googwe WWC */ #incwude <cwypto/hash.h> #incwude <cwypto/sha2.h> #incwude "fscwypt_pwivate.h" /* * HKDF suppowts any unkeyed cwyptogwaphic hash awgowithm, but fscwypt uses * SHA-512 because it is weww-estabwished, secuwe, and weasonabwy efficient. * * HKDF-SHA256 was awso considewed, as its 256-bit secuwity stwength wouwd be * sufficient hewe. A 512-bit secuwity stwength is "nice to have", though. * Awso, on 64-bit CPUs, SHA-512 is usuawwy just as fast as SHA-256. In the * common case of dewiving an AES-256-XTS key (512 bits), that can wesuwt in * HKDF-SHA512 being much fastew than HKDF-SHA256, as the wongew digest size of * SHA-512 causes HKDF-Expand to onwy need to do one itewation wathew than two. */ #define HKDF_HMAC_AWG "hmac(sha512)" #define HKDF_HASHWEN SHA512_DIGEST_SIZE /* * HKDF consists of two steps: * * 1. HKDF-Extwact: extwact a pseudowandom key of wength HKDF_HASHWEN bytes fwom * the input keying matewiaw and optionaw sawt. * 2. HKDF-Expand: expand the pseudowandom key into output keying matewiaw of * any wength, pawametewized by an appwication-specific info stwing. * * HKDF-Extwact can be skipped if the input is awweady a pseudowandom key of * wength HKDF_HASHWEN bytes. Howevew, ciphew modes othew than AES-256-XTS take * showtew keys, and we don't want to fowce usews of those modes to pwovide * unnecessawiwy wong mastew keys. Thus fscwypt stiww does HKDF-Extwact. No * sawt is used, since fscwypt mastew keys shouwd awweady be pseudowandom and * thewe's no way to pewsist a wandom sawt pew mastew key fwom kewnew mode. */ /* HKDF-Extwact (WFC 5869 section 2.2), unsawted */ static int hkdf_extwact(stwuct cwypto_shash *hmac_tfm, const u8 *ikm, unsigned int ikmwen, u8 pwk[HKDF_HASHWEN]) { static const u8 defauwt_sawt[HKDF_HASHWEN]; int eww; eww = cwypto_shash_setkey(hmac_tfm, defauwt_sawt, HKDF_HASHWEN); if (eww) wetuwn eww; wetuwn cwypto_shash_tfm_digest(hmac_tfm, ikm, ikmwen, pwk); } /* * Compute HKDF-Extwact using the given mastew key as the input keying matewiaw, * and pwepawe an HMAC twansfowm object keyed by the wesuwting pseudowandom key. * * Aftewwawds, the keyed HMAC twansfowm object can be used fow HKDF-Expand many * times without having to wecompute HKDF-Extwact each time. */ int fscwypt_init_hkdf(stwuct fscwypt_hkdf *hkdf, const u8 *mastew_key, unsigned int mastew_key_size) { stwuct cwypto_shash *hmac_tfm; u8 pwk[HKDF_HASHWEN]; int eww; hmac_tfm = cwypto_awwoc_shash(HKDF_HMAC_AWG, 0, 0); if (IS_EWW(hmac_tfm)) { fscwypt_eww(NUWW, "Ewwow awwocating " HKDF_HMAC_AWG ": %wd", PTW_EWW(hmac_tfm)); wetuwn PTW_EWW(hmac_tfm); } if (WAWN_ON_ONCE(cwypto_shash_digestsize(hmac_tfm) != sizeof(pwk))) { eww = -EINVAW; goto eww_fwee_tfm; } eww = hkdf_extwact(hmac_tfm, mastew_key, mastew_key_size, pwk); if (eww) goto eww_fwee_tfm; eww = cwypto_shash_setkey(hmac_tfm, pwk, sizeof(pwk)); if (eww) goto eww_fwee_tfm; hkdf->hmac_tfm = hmac_tfm; goto out; eww_fwee_tfm: cwypto_fwee_shash(hmac_tfm); out: memzewo_expwicit(pwk, sizeof(pwk)); wetuwn eww; } /* * HKDF-Expand (WFC 5869 section 2.3). This expands the pseudowandom key, which * was awweady keyed into 'hkdf->hmac_tfm' by fscwypt_init_hkdf(), into 'okmwen' * bytes of output keying matewiaw pawametewized by the appwication-specific * 'info' of wength 'infowen' bytes, pwefixed by "fscwypt\0" and the 'context' * byte. This is thwead-safe and may be cawwed by muwtipwe thweads in pawawwew. * * ('context' isn't pawt of the HKDF specification; it's just a pwefix fscwypt * adds to its appwication-specific info stwings to guawantee that it doesn't * accidentawwy wepeat an info stwing when using HKDF fow diffewent puwposes.) */ int fscwypt_hkdf_expand(const stwuct fscwypt_hkdf *hkdf, u8 context, const u8 *info, unsigned int infowen, u8 *okm, unsigned int okmwen) { SHASH_DESC_ON_STACK(desc, hkdf->hmac_tfm); u8 pwefix[9]; unsigned int i; int eww; const u8 *pwev = NUWW; u8 countew = 1; u8 tmp[HKDF_HASHWEN]; if (WAWN_ON_ONCE(okmwen > 255 * HKDF_HASHWEN)) wetuwn -EINVAW; desc->tfm = hkdf->hmac_tfm; memcpy(pwefix, "fscwypt\0", 8); pwefix[8] = context; fow (i = 0; i < okmwen; i += HKDF_HASHWEN) { eww = cwypto_shash_init(desc); if (eww) goto out; if (pwev) { eww = cwypto_shash_update(desc, pwev, HKDF_HASHWEN); if (eww) goto out; } eww = cwypto_shash_update(desc, pwefix, sizeof(pwefix)); if (eww) goto out; eww = cwypto_shash_update(desc, info, infowen); if (eww) goto out; BUIWD_BUG_ON(sizeof(countew) != 1); if (okmwen - i < HKDF_HASHWEN) { eww = cwypto_shash_finup(desc, &countew, 1, tmp); if (eww) goto out; memcpy(&okm[i], tmp, okmwen - i); memzewo_expwicit(tmp, sizeof(tmp)); } ewse { eww = cwypto_shash_finup(desc, &countew, 1, &okm[i]); if (eww) goto out; } countew++; pwev = &okm[i]; } eww = 0; out: if (unwikewy(eww)) memzewo_expwicit(okm, okmwen); /* so cawwew doesn't need to */ shash_desc_zewo(desc); wetuwn eww; } void fscwypt_destwoy_hkdf(stwuct fscwypt_hkdf *hkdf) { cwypto_fwee_shash(hkdf->hmac_tfm); }
from dataclasses import dataclass, field from typing import Optional from pulumi import Output @dataclass class DBParameter: name: str """The name of the RDS parameter.""" value: str """The value of the RDS parameter.""" apply_method: Optional[str] = "immediate" """One of `immediate` for dynamic params or `pending-reboot` for static.""" @dataclass class Replica: availability_zone: str """A-Z into which this replica should be placed.""" @dataclass class RDSInstance: name: str """Name of the DB instance.""" snapshot_identifier: Optional[str] """Specifies whether or not to create this database from a snapshot.""" engine_version: str = "12.4" """Engine version of the DB to use.""" allocated_storage: int = 20 """Initial allocated storage size in GiB.""" multi_az: bool = True """Enable/Disable Multi-AZ Support.""" instance_type: str = "db.t3.medium" """AWS Instance Type to use: https://aws.amazon.com/rds/instance-types/""" databases: Optional[list[str]] = field(default_factory=list) """Postgres Databases to create in this Instance.""" db_parameters: Optional[list[DBParameter]] = field(default_factory=list) """Extra configuration params for RDS.""" replicas: Optional[list[Replica]] = field(default_factory=list) """Optional configuration for cross A-Z replicas.""" @dataclass class RDSInstances: instances: list[RDSInstance] """List of RDS Instances to create.""" @dataclass class RDSInstanceExport: address: Output[str] """The hostname of the RDS instance.""" arn: Output[str] """Amazon Resource Name (ARN) for the RDS instance.""" endpoint: Output[str] """The connection endpoint in `address:port` format.""" hosted_zone_id: Output[str] """The canonical hosted zone id of the DB instance to be used in a Route53 Alias record.""" id: Output[str] """AWS-assigned ID.""" resource_id: Output[str] """The RDS resource ID of this instance.""" password: Output[str] """Database admin password""" snapshot_identifier: Optional[str] = None """Snapshot ID used to create this instance""" databases: Optional[dict] = None """databases and their roles""" @dataclass class RDSExports: name: str """Exported name of this Instance.""" instance: RDSInstanceExport replicas: list[RDSInstanceExport]
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_itoa.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: bperraud <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/11/17 02:42:51 by bperraud #+# #+# */ /* Updated: 2021/11/17 11:32:15 by bperraud ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static int ft_nbrchar(int n) { int i; i = 1; if (n < 0) { i++; while (n < -9) { n /= 10; i++; } } else { while (n > 9) { n /= 10; i++; } } return (i); } char *ft_itoa(int n) { int size; char *str; int neg; neg = 0; size = ft_nbrchar(n); str = malloc((size + 1) * sizeof(char)); if (!str) return (NULL); str[size] = '\0'; if (n < 0) { neg = 1; str[0] = '-'; } while (size-- > neg) { if (neg) str[size] = -(n % 10) + '0'; else str[size] = (n % 10) + '0'; n /= 10; } return (str); }
<h2><%=l(:label_task_manager)%></h2> &nbsp; <%= form_tag(task_manager_path, :method => :get) do %> <fieldset> <div class="splitcontentleft, col-sm-3"> <label for='project_id'><%= l(:label_projects) %>:</label> <%= select_tag 'project_id', content_tag('option') + options_from_collection_for_select(@projects, :id, :name, params[:project_id].to_i), :onchange => "this.form.submit(); return false;", :class => "form-control" %> </div> <div class="splitcontentright"> <div style="float: right" class="col-sm-6"> <div class="splitcontentleft"> <label for='group_id'><%= l(:label_groups) %>:</label> <%= select_tag 'group_id', content_tag('option') + options_from_collection_for_select(@groups, :id, :name, params[:group_id].to_i), :onchange => "this.form.submit(); return false;", :class => "form-control" %> </div> <div class="splitcontentright"> <label for='user_id'><%= l(:label_users) %>:</label> <%= select_tag 'user_id', content_tag('option') + options_from_collection_for_select(@users, :id, :name, params[:user_id].to_i), :onchange => "this.form.submit(); return false;", :class => "form-control" %> </div> </div> </div> </fieldset> <% end %> &nbsp; <legend></legend> <% if params[:user_id].present? || params[:project_id].present? || params[:group_id].present? %> <div id="date" style="width: 38vh"></div> &nbsp; <% end %> <% if @project %> <div class="panel panel-default"> <h3>&nbsp; Project: <%= @project.name %></h3> &nbsp; <% if has_underbooked_members?(@project) %> <div class="alert alert-warning"> <strong><%= l(:label_underbooked_members) %></strong> </div> <% end %> <% if has_overbooked_members?(@project) %> <div class="alert alert-danger"> <strong><%= l(:label_overbooked_members) %></strong> </div> <% end %> <% if has_unassigned_issues?(@project) %> <div class="alert alert-danger"> <strong><%= l(:label_unassigned_tasks) %>:</strong> <br><br> <table id="tasks" class="table"> <thead> <tr> <th><%= l(:field_id) %></th> <th><%= l(:field_tracker) %></th> <th><%= l(:field_subject) %></th> <th><%= l(:field_estimated_hours) %></th> <th><%= l(:field_start_date) %></th> </tr> </thead> <tbody> <% @unassigned_issues.each do |issue| %> <tr> <td><%= link_to issue.id, issue %></td> <td><%= issue.tracker %></td> <td><%= link_to issue.subject, issue %></td> <td><%= issue.estimated_hours %></td> <td><%= issue.start_date %></td> </tr> <% end %> </tbody> </table> </div> </div> <% end %> <% end %> <% @users.each do |u| %> <% if @project && @issues && [email protected](assigned_to_id: u.id).empty? %> <div class="panel panel-default"> <div class="splitcontentleft, col-sm-3"> &nbsp; <h3><%= u.name %></h3> </div> <div class="splitcontentright, col-sm-9"> &nbsp; <div class="panel panel-default"> <table id="members" class="table table-striped table-hover"> <thead> <tr> <th>Project</th> <th>Project manager</th> <th>Hours per day</th> <th># of tasks</th> <th>Estimated time for tasks</th> <th>Workload</th> </tr> </thead> <tbody> <% u.projects.each do |p| %> <% if members_issue_count(u, p) > 0 %> <tr> <td><%= p.name %></td> <td>Menedżer</td> <td><%= members_hours_per_day(u, p) %></td> <td><%= members_issue_count(u, p) %></td> <td><%= members_estimated_time(u, p) %></td> <td><%= overload(u, p) %></td> </tr> <% end %> <% end %> </tbody> </table> </div> </div> <table id="tasks" class="table table-striped table-hover"> <thead> <tr> <%= sort_header_tag('issues.id', :caption => l(:field_id)) %> <th>Project</th> <%= sort_header_tag('trackers.name', :caption => l(:field_tracker)) %> <%= sort_header_tag('issues.subject', :caption => l(:field_subject)) %> <%= sort_header_tag('issues.start_date', :caption => l(:field_start_date)) %> <th>Estimated due date</th> <%= sort_header_tag('issues.estimated_hours', :caption => l(:field_estimated_hours)) %> <th><%= l(:field_assignee_name) %></th> <th><%= l(:field_assignee_hours_per_day) %></th> <th>Logged time</th> </tr> </thead> <tbody> <% @issues.where(assigned_to_id: u.id).each do |issue| %> <tr> <td><%= link_to issue.id, issue %></td> <td><%= issue.project %></td> <td><%= issue.tracker %></td> <td><%= link_to issue.subject, issue %></td> <td><%= issue.start_date %></td> <td><%= estimated_due_date(issue) %></td> <td><%= issue.estimated_hours %></td> <td><%= issue_assigned_to_name(issue) %></td> <td><%= assignees_hours_per_day(issue) %></td> <td><%= issue_time_entries(issue) %></td> </tr> <% end %> <% end %> </tbody> </table> </div> </fieldset> <% end %> <% content_for :header_tags do %> <%= stylesheet_link_tag 'bootstrap', :plugin => 'redmine_task_manager' %> <%= stylesheet_link_tag 'bootstrap-datetimepicker', :plugin => 'redmine_task_manager' %> <%= javascript_include_tag 'jquery', :plugin => 'redmine_task_manager' %> <%= javascript_include_tag 'moment', :plugin => 'redmine_task_manager' %> <%= javascript_include_tag 'bootstrap', :plugin => 'redmine_task_manager' %> <%= javascript_include_tag 'bootstrap-datetimepicker', :plugin => 'redmine_task_manager' %> <%= javascript_include_tag 'bootstrap-datepaginator', :plugin => 'redmine_task_manager' %> <%= javascript_include_tag 'task_manager', :plugin => 'redmine_task_manager' %> <% end %>
import { useEffect } from 'react' import { deleteDoc, doc } from "firebase/firestore"; import { useNavigate } from 'react-router-dom'; import db from '../../firebase'; import { RiDeleteBin2Fill } from "react-icons/ri" import "./Main.css" import ChartComponent from '../components/ChartComponent'; function Main({docs, getExpenseDocs, user, sortedDocs}) { const navigate = useNavigate(); useEffect(() => { if(user.name === null || user.name === "" || user.photoUrl === null || user.photoUrl === "" || user.email === null || user.email === ""){ navigate("/login") } if(user.email !== null || user.email !== "" || docs.length === 0){ getExpenseDocs() } },[]) useEffect(() => {}, [docs]) const deleteExpense = async (id) => { try{ await deleteDoc(doc(db, "Users", user.email, "expenses", id)) getExpenseDocs() } catch (er) { console.error("Error deleting document: ", er); } } return ( <div className='main'> <div className='main__graph'> <ChartComponent data={sortedDocs}/> </div> <div className='main__expenses'> <h1 className='main__expenseHeading'>Recent expenses</h1> <div className='main__expenseTable'> <div className='main__expenseTableHead'> <div className='main__expenseTableHeadCol'>Date</div> <div className='main__expenseTableHeadCol2'>Title</div> <div className='main__expenseTableHeadCol'>Amount</div> <div className='main__expenseTableHeadColOption'></div> </div> {docs?.map((doc, index) => ( index < 7 && <div key={doc.id} className='main__expenseTableHead main__expenseRow'> <div className='main__expenseTableHeadCol'>{doc.date}</div> <div className='main__expenseTableHeadCol2'>{doc.title}</div> <div className='main__expenseTableHeadCol'>{doc.amount}</div> <div className='main__expenseTableHeadColOption'><RiDeleteBin2Fill className='main__expenseTableOption' onClick={() => deleteExpense(doc.id)}/></div> </div> ))} </div> </div> </div> ) } export default Main
import "./slider.css"; import NavigateNextRoundedIcon from '@mui/icons-material/NavigateNextRounded'; import CalendarMonthRoundedIcon from '@mui/icons-material/CalendarMonthRounded'; import PersonOutlineIcon from '@mui/icons-material/PersonOutline'; import LabelOutlinedIcon from '@mui/icons-material/LabelOutlined'; import { DateRange } from "react-date-range"; import { useState } from "react"; import 'react-date-range/dist/styles.css'; import 'react-date-range/dist/theme/default.css'; import {format} from "date-fns" const Slider = () => { const [openDate, setOpenDate] = useState(false); const [date, setDate] = useState([ { startDate: new Date(), endDate: new Date(), key: 'selection' } ]); return ( <div id="carouselExampleCaptions" className="carousel slide mb-3" data-bs-ride="carousel" > <div className="carousel-indicators"> <button style={{ width: "10px", height: "10px", borderRadius: "100%" }} type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" className="active" aria-current="true" aria-label="Slide 1" ></button> <button style={{ width: "10px", height: "10px", borderRadius: "100%" }} type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2" ></button> <button style={{ width: "10px", height: "10px", borderRadius: "100%" }} type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="2" aria-label="Slide 3" ></button> </div> <div className="carousel-inner"> <div className="carousel-item active"> <img className="img-fluid w-100 h-100 overflow-hidden" src="https://sitecore-cd-imgr.shangri-la.com/MediaFiles/2/0/B/{20B18195-50BE-4993-9CAE-0A141AFD3747}201126_slcb_homepage1.jpg" /> <div className="carousel-caption d-block"> <h4>Shangri-La Colombo</h4> <h6> A personal tropical sanctuary set within the heart of the city{" "} </h6> </div> </div> <div className="carousel-item"> <img className="img-fluid w-100 h-100 overflow-hidden" src="https://sitecore-cd-imgr.shangri-la.com/MediaFiles/B/4/D/{B4DC25D4-2F83-4133-BE8A-B139CBAD061B}200710_slcb_slcares.jpg" /> <div className="carousel-caption d-block"> <h4>Shangri-La Cares</h4> <h6> Your well-being in our care - learn more about our safety standards{" "} </h6> </div> </div> <div className="carousel-item"> <img className="img-fluid w-100 h-100 overflow-hidden" src="https://sitecore-cd-imgr.shangri-la.com/MediaFiles/F/A/5/{FA599018-DA27-4904-8585-D0B858639D94}SEAA We Are Vaccinated_website-home-banner.jpeg" /> <div className="carousel-caption d-block"> <h4>We Are Vaccinated</h4> <h6> Our highly vaccinated workforce provides&nbsp;the safest possible environment for&nbsp;your&nbsp;next holiday.{" "} </h6> </div> </div> </div> <div className="preNexButton"> <button className="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="prev" style={{backgroundColor: "#000", width: "40px" ,borderRadius: "100%", height: "40px", top: "40%", left: "2%"}} > <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button className="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="next" style={{backgroundColor: "#000", width: "40px" ,borderRadius: "100%", height: "40px", top: "40%", right: "2%"}} > <span className="carousel-control-next-icon" aria-hidden="true" ></span> <span className="visually-hidden">Next</span> </button> </div> <div className="headerSearch"> <div className="hSearch"> <div className="headerSearchItem"> <div className="startingDate"> <CalendarMonthRoundedIcon className="headerIcon" /> <span style={{marginLeft: "10px"}} onClick={()=>setOpenDate(!openDate)} className="headerSearchText">{`${format(date[0].startDate, "dd/MM/yyyy")}`}</span> {/* <span style={{marginLeft: "10px"}} onClick={()=>setOpenDate(!openDate)} className="headerSearchText">{`${format(date[0].startDate, "dd/MM/yyyy")} to ${format(date[0].endDate, "dd/MM/yyyy")} `}</span> */} {openDate && <DateRange editableDateInputs={true} onChange={(item) => setDate([item.selection])} ranges={date} className="dates" />} </div> <p style={{display: "flex", width: "100px", height: "50px", paddingLeft: "15px", alignItems:"center", marginTop: "-3px"}}>1 night</p> <div className="endingDate"> <span style={{marginLeft: "10px"}} onClick={()=>setOpenDate(!openDate)} className="headerSearchText">{`${format(date[0].endDate, "dd/MM/yyyy")}`}</span> </div> </div> </div> <div className="headerSearchItems"> <PersonOutlineIcon className="headerIcon" /> <span style={{marginLeft: "10px"}} className="headerSearchText">1 Room, 1 Adult, 0 Children</span> </div> <div className="headerSearchIte"> <LabelOutlinedIcon className="headerIcon" /> <span style={{marginLeft: "10px"}} className="headerSearchText" placeholder="">Special Code</span> </div> <div className="headerSearchItemButton"> <button className="searchButton">Search</button> </div> </div> </div> ); }; export default Slider;
# ToDo Android App Welcome to the ToDo Android App! This simple and intuitive task management application helps you keep track of your tasks and stay organized. This README file provides an overview of the app's main features and how to use them. ## Overview Check the story here: [ToDo Story](https://app.screenspace.io/541651585/35bd3229?camera_align=center&font_size=0&zoom=0&soften_edges=1&bg_alpha=false) ## Features ### 1. Task Management - Add new tasks with titles and descriptions. - Mark tasks as completed. - Edit task details. - Organize tasks by priority. (Future Feature) ### 2. Swipe to Delete - Easily delete tasks by swiping them off the screen. ### 3. Light and Dark Modes - Enjoy the app in your preferred visual style with both light and dark modes available. ### 4. Multilingual Support - The app supports both Arabic and English languages for a wider user base. - Users can switch between languages in the app settings. - Other languages to be added later. (Future Feature) ### 5. Cross-Device Sync (Future Feature) - Seamlessly sync your tasks across multiple devices. ### 6. Reminders and Notifications (Future Feature) - Set reminders for important tasks. - Receive notifications for upcoming tasks. ### 7. Categories and Labels (Future Feature) - Organize tasks into categories or apply labels for better task management. ## Installation To get started with the ToDo Android App, follow these steps: 1. **Clone the Repository:** Clone this repository to your local machine using `git clone`. ```bash git clone https://github.com/yourusername/ToDo-Android-App](https://github.com/Mahmoud-Ibrahim-750/ToDo.git ``` or using the GitHub Desktop application. 2. **Open in Android Studio:** Open the project in Android Studio. 3. **Build and Run:** Build the project and run it on an Android emulator or a physical device. ## Usage Once you have the app installed, follow these steps to start using it: 1. **Launch the App:** Open the ToDo app on your Android device. 2. **Create a Task:** Tap the "+" button to add a new task. Enter the task title and description. 3. **Swipe to Delete:** To delete a task, swipe it to the left or right. 4. **Change Display Mode:** Switch between light and dark modes in the app settings. 5. **Change Language:** Change the app language between Arabic and English in the app settings. 6. **Mark as Completed:** Tap the check button to mark a task as completed. 7. **Edit Task:** To a task to display its details and edit them if needed. ## Feedback and Contributions We welcome your feedback and contributions to improve the ToDo Android App. If you encounter any issues or have suggestions for new features, please submit them to our GitHub repository's "Issues" section. We hope you find this ToDo Android App helpful in managing your tasks efficiently. Thank you for using our app! Happy task managing! 📝📅📌
import assert from 'node:assert' import http from 'http' import express from 'express' import { promisifiedClose, promisifiedListen } from '../src/server-promises.js' describe('server-promises.ts', function () { const serversToCleanUp: http.Server[] = [] afterEach(async function () { for (const server of serversToCleanUp) { await new Promise((resolve) => server.close(resolve)) } serversToCleanUp.splice(0, serversToCleanUp.length) }) describe('promisifiedListen()', function () { it('resolves with a started server', async function () { const server = await promisifiedListen(express(), 3333) serversToCleanUp.push(server) assert.strictEqual(server.listening, true) const address = server.address() assert.ok(typeof address === 'object') assert.strictEqual(address?.port, 3333) }) it('rejects if trying to start on a used port', async function () { serversToCleanUp.push(await promisifiedListen(express(), 3333)) await assert.rejects(promisifiedListen(express(), 3333), { code: 'EADDRINUSE' }) }) it('works for plain http.Server', async function () { // The function was initially implemented for express.Application only, but expanded to be more generic. const server = await promisifiedListen(http.createServer(), 3333) serversToCleanUp.push(server) assert.strictEqual(server.listening, true) const address = server.address() assert.ok(typeof address === 'object') assert.strictEqual(address?.port, 3333) }) }) describe('promisifiedClose()', function () { it('resolves as soon as the server is closed', async function () { const server = http.createServer().listen(3333) serversToCleanUp.push(server) assert.strictEqual(server.listening, true) assert.ok(server.address()) await promisifiedClose(server) assert.strictEqual(server.listening, false) assert.strictEqual(server.address(), null) }) it('rejects if the server was not running', async function () { const server = http.createServer() assert.strictEqual(server.address(), null) await assert.rejects(promisifiedClose(server), /not running/) }) it('rejects if called twice on the same instance', async function () { const server = http.createServer().listen(3333) serversToCleanUp.push(server) await assert.doesNotReject(promisifiedClose(server)) await assert.rejects(promisifiedClose(server), /not running/) }) }) })
import java.util.Scanner; public class TestaHora { static final Scanner sc = new Scanner(System.in); public static void main(String[] args) { Hora inicio; Hora fim; fim = new Hora(); inicio = new Hora(); inicio.h = 9; inicio.m = 23; inicio.s = 5; System.out.print("Começou às "); printHora(inicio); System.out.println("."); System.out.println("Quando termina?"); lerHora(fim); // crie esta função! System.out.print("Início: "); printHora(inicio); System.out.print(" Fim: "); printHora(fim); } public static void printHora(Hora x) { System.out.printf("%2d:%2d:%2d", x.h, x.m, x.s); } public static void lerHora(Hora fim) { do { System.out.print("horas? "); fim.h = sc.nextInt(); } while (fim.h < 0 || fim.h > 23); do { System.out.print("minutos? "); fim.m = sc.nextInt(); } while (fim.m < 0 || fim.m > 59); do { System.out.print("segundos? "); fim.s = sc.nextInt(); } while (fim.s < 0 || fim.s > 59); } } class Hora { int h; int m; int s; } /** EXEMPLO do pretendido: $ java TestaHora Começou às 09:23:05. Quando termina? horas? 11 minutos? 72 minutos? 7 segundos? 2 Início: 09:23:05 Fim: 11:07:02. **/
// // Created by Vitor Hugo on 05/04/2022. // #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <signal.h> #include "occupation/occupation.h" #define WRITE_END 1 #define READ_END 0 #define PIPE_SZ 4096 #ifndef COUGH_COUGH_IO_H #define COUGH_COUGH_IO_H /** * reads from File Descriptor * @param fd file descriptor to read from * @param ptr variable to read to * @param n size in bytes to read * @return -1 if error occured | >0 number of bytes read */ ssize_t readn(int fd, void *ptr, size_t n); /** * * write from File Descriptor * @param fd file descriptor to write from * @param ptr variable to write to * @param n size in bytes to written * @return -1 if error occurred | >0 number of bytes written */ ssize_t writen(int fd, const void *ptr, size_t n); /** * write from parent process to output file all data * @param fd_out file descriptor of file to write to * @param fd_pipe file descriptor of pipe of whom to read */ void from_parent_to_file (int fd_out, int fd_pipe); /** * calculates number of years in Dataset * @param data dataset * @return number of years */ ssize_t n_years_dataset (DATASET data); /** * retrieves the first timestamp from data * @param data data * @return first unix timestamp */ uint32_t first_ts(DATASET data); /** * sends data from the parent process to M child processes * @param fd_read file descriptor to read from * @param M number of M processes * @param first_ts first timestamp in data */ void from_parent_to_M_processes (int fd_read, size_t M, uint32_t first_ts); /** * handler for signal * @param SIG signal received */ void handler (int SIG); #endif //COUGH_COUGH_IO_H
/* * Copyright 2002-2019 the original author or authors. * * 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 * * https://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 org.springframework.core.annotation; import java.lang.annotation.Annotation; import java.lang.annotation.Repeatable; import java.lang.reflect.Method; import java.util.Map; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ConcurrentReferenceHashMap; import org.springframework.util.ObjectUtils; import org.springframework.util.ReflectionUtils; /** * Strategy used to determine annotations that act as containers for other * annotations. The {@link #standardRepeatables()} method provides a default * strategy that respects Java's {@link Repeatable @Repeatable} support and * should be suitable for most situations. * * <p>The {@link #of} method can be used to register relationships for * annotations that do not wish to use {@link Repeatable @Repeatable}. * * <p>To completely disable repeatable support use {@link #none()}. * * @author Phillip Webb * @since 5.2 */ public abstract class RepeatableContainers { @Nullable private final RepeatableContainers parent; private RepeatableContainers(@Nullable RepeatableContainers parent) { this.parent = parent; } /** * Add an additional explicit relationship between a contained and * repeatable annotation. * @param container the container type * @param repeatable the contained repeatable type * @return a new {@link RepeatableContainers} instance */ public RepeatableContainers and(Class<? extends Annotation> container, Class<? extends Annotation> repeatable) { return new ExplicitRepeatableContainer(this, repeatable, container); } @Nullable Annotation[] findRepeatedAnnotations(Annotation annotation) { if (this.parent == null) { return null; } return this.parent.findRepeatedAnnotations(annotation); } @Override public boolean equals(@Nullable Object other) { if (other == this) { return true; } if (other == null || getClass() != other.getClass()) { return false; } return ObjectUtils.nullSafeEquals(this.parent, ((RepeatableContainers) other).parent); } @Override public int hashCode() { return ObjectUtils.nullSafeHashCode(this.parent); } /** * Create a {@link RepeatableContainers} instance that searches using Java's * {@link Repeatable @Repeatable} annotation. * @return a {@link RepeatableContainers} instance */ public static RepeatableContainers standardRepeatables() { return StandardRepeatableContainers.INSTANCE; } /** * Create a {@link RepeatableContainers} instance that uses a defined * container and repeatable type. * @param repeatable the contained repeatable annotation * @param container the container annotation or {@code null}. If specified, * this annotation must declare a {@code value} attribute returning an array * of repeatable annotations. If not specified, the container will be * deduced by inspecting the {@code @Repeatable} annotation on * {@code repeatable}. * @return a {@link RepeatableContainers} instance */ public static RepeatableContainers of( Class<? extends Annotation> repeatable, @Nullable Class<? extends Annotation> container) { return new ExplicitRepeatableContainer(null, repeatable, container); } /** * Create a {@link RepeatableContainers} instance that does not expand any * repeatable annotations. * @return a {@link RepeatableContainers} instance */ public static RepeatableContainers none() { return NoRepeatableContainers.INSTANCE; } }
package com.example.a4ads_11_04 import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.a4ads_11_04.ui.theme._4ADS_11_04Theme @Composable fun ErrorView( modifier: Modifier = Modifier, message: String = "Um erro inesperado ocorreu", retryAction: () -> Unit ) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = modifier.fillMaxSize() ) { Text( modifier = Modifier .padding(16.dp), textAlign = TextAlign.Center, fontWeight = FontWeight.Bold, fontSize = 20.sp, color = Color.Gray, text = message ) Button(onClick = { retryAction() }) { Text(text = "Tentar novamente") } } } @Preview(showBackground = true) @Composable fun ErrorViewPreview() { _4ADS_11_04Theme { ErrorView {} } }
<%= form_for(@debate, url: form_url, multipart: true) do |f| %> <%= render 'shared/errors', resource: @debate %> <div class="row"> <div class="small-12 column"> <%= f.label :title, t("debates.form.debate_title") %> <%= f.text_field :title, maxlength: Debate.title_max_length, placeholder: t("debates.form.debate_title"), label: false %> </div> <div class="small-12 column"> <%= f.label :description, t("debates.form.debate_text") %> <%= f.rich_editor :description, maxlength: Debate.description_max_length %> </div> <div class="small-12 column"> <%= f.label :tag_list, t("debates.form.tags_label") %> <p class="note"><%= t("debates.form.tags_instructions") %></p> <span class="tags"> <% @featured_tags.each do |tag| %> <a class="js-add-tag-link"><%= tag.name %></a> <% end %> </span> <%= f.text_field :tag_list, value: @debate.tag_list.to_s, label: false, placeholder: t("debates.form.tags_placeholder"), class: 'js-tag-list' %> </div> <div class="small-12 column datetime"> <%= f.datetime_select :starts_at %> </div> <div class="small-12 column datetime"> <%= f.datetime_select :ends_at %> </div> <div class="small-12 column"> <%= f.file_field :picture %> </div> <div class="small-12 column"> <%= f.label :instructions, t("debates.form.instructions") %> <%= f.rich_editor :instructions, maxlength: Debate.description_max_length %> </div> <div class="small-12 column"> <% if @debate.new_record? %> <%= f.label :terms_of_service do %> <%= f.check_box :terms_of_service, label: false %> <span class="checkbox"> <%= t("form.accept_terms", conditions: link_to(t("form.conditions"), "/conditions", target: "blank")).html_safe %> </span> <% end %> <% end %> </div> <div class="small-12 column"> <%= captcha(@debate) %> </div> <div class="actions small-12 column"> <%= hidden_field_tag :participatory_process_id, @participatory_process.slug %> <%= f.submit(class: "button radius", value: t("debates.#{action_name}.form.submit_button")) %> </div> </div> <% end %>
from odoo import models, fields, api from odoo.exceptions import ValidationError class ApproveHubForm(models.Model): _name = 'approvehub.form' _description = 'Approval Form' name = fields.Char(string='Reference', required=True) model_list = fields.Many2one('ir.model', string='Model Name') partner_id=fields.Many2one('res.partner',string='user') email=fields.Char(related='partner_id.email',string='email') user_ids = fields.One2many('approvehub.form.user.line', 'approvehub_form_id', string='Approvers') approval_status = fields.Selection([ ('draft', 'Draft'), ('approved', 'Approved'), ('rejected', 'Rejected'), ], string='Approval Status', default='draft') @api.constrains('user_ids') def _check_unique_users(self): for record in self: selected_users = record.user_ids.mapped('user_id') if len(selected_users) != len(set(selected_users)): raise ValidationError("Each user can only be selected once.") class ApproveHubFormUserLine(models.Model): _name = 'approvehub.form.user.line' _description = 'Approval Form User Line' user_id = fields.Many2one('res.users', string='User') status = fields.Selection([ ('mandatory', 'Mandatory'), ('not_mandatory', 'Not Mandatory'), ], string='Status', default='mandatory') approvehub_form_id = fields.Many2one('approvehub.form', string='Approval Form')
import React, { Component } from 'react'; import * as firebase from 'firebase'; class LoginForm extends Component { constructor() { super(); this.state = { method: 'login', header: 'Login', email: '', password: '', user: '' } } handleLogin = () => { if (this.state.method !== 'login') { this.setState({ method: 'login', header: 'Login' }); return; } firebase.auth().signInWithEmailAndPassword(this.state.email, this.state.password).catch(function (error) { alert(error.code + ' - ' + error.message); }) } handleLogout = () => { firebase.auth().signOut().then(() => { this.setState({ method: 'login', header: 'Login', email: '', password: ''}); }).catch(function (error) { alert(error.code + ' - ' + error.message); }) } handleRegister = () => { if (this.state.method !== 'register') { this.setState({ method: 'register', header: 'Register' }); return; } firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).catch(function (error) { alert(error.code + ' - ' + error.message); }) } handleInputChange = (e) => { const target = e.target; const id = target.id; const value = target.value; this.setState({ [id]: value }) } componentDidMount = () => { firebase.auth().onAuthStateChanged(user => { console.log(this.state) if (user) { this.setState({ user: user.email, header: 'Welcome ' + user.email }); } else { this.setState({ user: '' }); } console.log(this.state) }); } render() { let form = null; if (!this.state.user) { form = <form className="pure-form pure-form-stacked"> <label htmlFor="email">Email</label> <input type="email" id="email" value={this.state.email} onChange={this.handleInputChange} /> <label htmlFor="password">Password</label> <input type="password" id="password" value={this.state.password} onChange={this.handleInputChange} /> <button type="button" className="pure-button pure-button-primary" onClick={this.handleLogin}>Login</button> <button type="button" className="pure-button pure-button-primary" onClick={this.handleRegister}>Register</button> </form> } else { form = <div> <button type="button" className="pure-button" onClick={this.handleLogout}>Logout</button> </div> } return ( <div className="container"> <h1>{this.state.header}</h1> {form} </div> ) } } export default LoginForm;
### TL;DR quantipy gives your calculations: - intuitive dimensional analysis - effortless unit conversion - automatic commensurability enforcement see [here](https://github.com/itsmiir/qpy/blob/main/units.md) for a list of units and constants the package adds --- ### what is quantipy? #### quantipy is a dimensional analysis module for engineering and physics calculations that allows you to manipulate physical quantities in an intutive way. it also enforces proper unit usage and prevents many unit errors. ### why quantipy? there are several other python packages that provide support for quantities with units. here is a (non-exhaustive) list: - [astropy.units](https://docs.astropy.org/en/latest/units) - [DimPy](http://www.inference.org.uk/db410/) - [DUQ](https://github.com/AAriam/duq) - [Magnitude](https://juanreyero.com/open/magnitude/) - [numericalunits](https://github.com/sbyrnes321/numericalunits) - [Pint](https://pint.readthedocs.io/en/stable/index.html) - [Quantities](https://python-quantities.readthedocs.io/en/latest/index.html) - [Scalar](http://russp.us/scalar-guide.htm) these packages serve a variety of purposes, and all have their strengths and weaknesses. depending on your application, one of these might be better for you--but quantipy has certain features that sets it apart from each of these. In short, **quantipy is ideal as a calculator for quick napkin calculations involving physical quantities.** ### how does it work? here's a simple example-- let's say i want to find the the velocity of an object involved in an inelastic collision: ```py from qntpy import * m1 = 10*kg m2 = 5*kg v1 = 5.4*m/s v2 = 3.2*m/s pCombined = m1*v1 + m2*v2 m3 = m1 + m2 v3 = pCombined/m3 print(v3) # 4.666666666666667 ms⁻¹ ``` ### ok, but how is that useful? sure, that example didn't really need quantipy. but that's not all it can do: for example, take this calculation for the force of an electromagnet using the equation $F = (NI)^2\mu_0 \frac{A}{2l^2}$: ```py from qntpy import * from qntpy.constants import mu_0, g_earth m_1 = 0.9*lbm # quantipy will automatically convert every unit you enter into standard units current = 3*A length = 2*cm turns = 5000 area = 100*mm**2 force = (turns*current)**2 * mu_0 * area / (2*(length**2)) print(force.round(4)) # 35.3429 N print((m_1*g_earth).round(4)) # 4.0007 N if (force > m_1*g_earth): print("magnet can lift load!") else: print("magnet is underpowered :(") # magnet can lift load! ``` a little more useful, huh? ### but wait, there's more! quantipy includes other features too, such as commonly-used physics constants, the ability to represent a value in whatever base or derived units you want, and even currency conversion support, updated daily (with an API key): ```py from qntpy import * from qntpy.currency import * price = 399*USD data = 23*GiB weight = 430*lbf dataPerWeightCurrency = data/price/weight print(dataPerWeightCurrency.termsOf(MB/(EUR*kN), 4)) # 34.3292 MB/EUR•kN ``` ```py from qntpy import * import qntpy.constants as qc mass = 3.043*MeVc2 num_electrons = mass / qc.m_e # call qc.constants() to see all available constants print(round(num_electrons, 0)) # 6.0 ``` ### currency units in addition to normal physics and engineering units, several currencies are defined by quantipy via the [APILayer Exchange Rates Data API](https://apilayer.com/marketplace/exchangerates_data-api). you can access them by importing `qntpy.currency` and adding your APILayer API key to the `api_key.txt` file that is generated by the module--this file lives under `site-packages/qntpy/` in your python environment folder. you can reference currencies in code with their [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency codes and use them as you would other units. ```py import qntpy.currency as cncy print(cncy.BTC.termsOf(cncy.EUR)) # '26369.10595485628 EUR' ``` ### unit enforcement quantipy automatically enforces proper usage of units in your calculations. trying to add incompatible units will throw an error: ```py from qntpy import * m1=10*kg m2=12*m/s print(m1+m2) ArithmeticError: Incompatible units: kg and m/s ``` this feature will solve a surprising amount of calculation errors. ### defining custom units you can even define your own custom constants with your own symbols and conversion factors and use them in your code! ```py from qntpy import * # the first argument is the commensurability of the new unit, the second is its unit symbol, the third is its value # define a new unit "Fizz" equal to 12 m/kg, with the symbol "Fz" Fizz = Unit.derived(m/kg, "Fz", 12) value = 12000*m/kg print(value.termsOf(Fizz)) # 1000.0 Fz newValue = 1000*Fizz print(newValue == value) # True ``` built-in functions are also provided to automatically create prefixed units: ```py kFizz = kilo(Fizz) print(value.termsOf(kFizz)) # 1.0 kFz ``` these functions define a new derived unit whose symbol is the same as the original unit with the SI prefix added. the included prefix functions are as follows: function|value|prefix ---|---|--- `pico`|$10^{-12}{}$|`p` `nano`|$10^{-9}{}$|`n` `micro`|$10^{-6}{}$|`μ` `milli`|$10^{-3}{}$|`m` `kilo`|$10^{3}{}$|`k` `mega`|$10^{6}{}$|`M` `giga`|$10^{9}{}$|`G` `tera`|$10^{12}{}$|`T` `peta`|$10^{15}{}$|`P` ### non-absolute units ```py # define a new unit "Buzz" equal to 2 J, but "0 Buzzes" is equal to 11 J. Buzz = Unit.derived(J, "Bz", 2, 11) ``` this may seem like a weird and arbitrary feature, but it's how quantipy is able to work with units like degrees Celsius, which aren't based on absolute scales. ```py print(0*Buzz) # 11 J ``` be careful how you use non-absolute units; for example, the expression "`12*degC / kg`" is actually equal to "`285.15 K / kg`". it's preferred to use absolute units (kelvins and rankines) for conversion factors. non-absolute units are mostly added for completeness, and so you can convert between them: ```py print((43*degF).termsOf(K), (16*degF).termsOf(degC)) # 279.2611111111111 K -8.888888888888857 ⁰C ``` ### more information for a full list of units and constants added by quantipy, see [here](https://github.com/itsmiir/qpy/blob/main/units.md).
import { useState } from 'react' import { useNavigate } from 'react-router-dom' import ZodGenericValidation from 'app/externalLibraries/zod/ZodSchemaGeneric.ts' import useErrors from 'app/hook/useErrors.ts' export default function useHome() { const [room, setRoom] = useState('') const { getMessageZodErro, getErrorByField, errors } = useErrors() const isFormValid = room && errors.length === 0 const navigate = useNavigate() function handleRoomNameChange(event: React.ChangeEvent<HTMLInputElement>) { setRoom(event.target.value) const validation = ZodGenericValidation.string('room') getMessageZodErro({ field: 'room', validation, value: event.target.value, }) } function handlerSubmit() { navigate(`/${room}`) } return { room, isFormValid, handleRoomNameChange, getErrorByField, handlerSubmit, } }
### Question 2 ![image](Question2_hw1.png) - a. row 2111 col 17 - b. - gender : categorical, nominal - age : numerical, continuous - height : numerical, continuous - weight : numerical, continuous - family_overweight : categorical, nominal - high_caloric_food : categorical, nominal - eat_vegetables : categorical, nominal - main_meals_daily : categorical, nominal - food_between_meals : categorical, nominal - smoke : categorical, nominal - water_intake_daily : categorical, nominal - monitor_calories : categorical, nominal - physical_activity_frequency : numerical, continuous - tech_device_usage : numerical, continuous - alcohol_frequency : categorical, nominal - transportation : categorical, nominal - status : categorical - c. ![Alt text](bmi_code.png) ![Alt text](df_with_bmi.png) - d. ```R boxplot(bmi ~ status, data=data, main="BMI vs Status") ``` ![Alt text](BMI_Status.png) - e. ![Alt text](Question2_e.png) ```R get_physical_transport <- function(transportation) { return(transportation == "Walking" | transportation == "Bike") } data$physical_transport <- get_physical_transport(data$transportation) true_count = sum(data$physical_transport) # create a data frame pie_data <- data.frame(Count = c(true_count, false_count)) row.names(pie_data) <- c("TRUE", "FALSE") pie(pie_data$Count, labels = row.names(pie_data), main = "physical transport") ``` - f. ```R boxplot(bmi ~ status, data=data, main="BMI vs Status") ``` ![Alt text](bmi_physical_transport_boxplot.png)
package dbadapter import ( "context" "encoding/json" "fmt" "runtime" "sort" "sync" "testing" "time" "github.com/jackc/pgx/v5" "github.com/stretchr/testify/require" "weavelab.xyz/river/internal/dbsqlc" "weavelab.xyz/river/internal/rivercommon" "weavelab.xyz/river/internal/riverinternaltest" "weavelab.xyz/river/internal/util/dbutil" "weavelab.xyz/river/internal/util/ptrutil" "weavelab.xyz/river/internal/util/sliceutil" "weavelab.xyz/river/riverdriver" "weavelab.xyz/river/rivertype" ) func Test_StandardAdapter_JobCancel(t *testing.T) { t.Parallel() ctx := context.Background() type testBundle struct { baselineTime time.Time // baseline time frozen at now when setup is called ex dbutil.Executor } setup := func(t *testing.T, ex dbutil.Executor) (*StandardAdapter, *testBundle) { t.Helper() bundle := &testBundle{ baselineTime: time.Now().UTC(), ex: ex, } adapter := NewStandardAdapter(riverinternaltest.BaseServiceArchetype(t), testAdapterConfig(bundle.ex)) adapter.TimeNowUTC = func() time.Time { return bundle.baselineTime } return adapter, bundle } setupTx := func(t *testing.T) (*StandardAdapter, *testBundle) { t.Helper() return setup(t, riverinternaltest.TestTx(ctx, t)) } for _, startingState := range []dbsqlc.JobState{ dbsqlc.JobStateAvailable, dbsqlc.JobStateRetryable, dbsqlc.JobStateScheduled, } { startingState := startingState t.Run(fmt.Sprintf("CancelsJobIn%sState", startingState), func(t *testing.T) { t.Parallel() adapter, bundle := setupTx(t) timeNowString := bundle.baselineTime.Format(time.RFC3339Nano) params := makeFakeJobInsertParams(0, nil) params.State = startingState insertResult, err := adapter.JobInsert(ctx, params) require.NoError(t, err) require.Equal(t, startingState, insertResult.Job.State) jobAfter, err := adapter.JobCancel(ctx, insertResult.Job.ID) require.NoError(t, err) require.NotNil(t, jobAfter) require.Equal(t, dbsqlc.JobStateCancelled, jobAfter.State) require.WithinDuration(t, time.Now(), *jobAfter.FinalizedAt, 2*time.Second) require.JSONEq(t, fmt.Sprintf(`{"cancel_attempted_at":%q}`, timeNowString), string(jobAfter.Metadata)) }) } t.Run("RunningJobIsNotImmediatelyCancelled", func(t *testing.T) { t.Parallel() adapter, bundle := setupTx(t) timeNowString := bundle.baselineTime.Format(time.RFC3339Nano) params := makeFakeJobInsertParams(0, nil) params.State = dbsqlc.JobStateRunning insertResult, err := adapter.JobInsert(ctx, params) require.NoError(t, err) require.Equal(t, dbsqlc.JobStateRunning, insertResult.Job.State) jobAfter, err := adapter.JobCancel(ctx, insertResult.Job.ID) require.NoError(t, err) require.NotNil(t, jobAfter) require.Equal(t, dbsqlc.JobStateRunning, jobAfter.State) require.Nil(t, jobAfter.FinalizedAt) require.JSONEq(t, fmt.Sprintf(`{"cancel_attempted_at":%q}`, timeNowString), string(jobAfter.Metadata)) }) for _, startingState := range []dbsqlc.JobState{ dbsqlc.JobStateCancelled, dbsqlc.JobStateCompleted, dbsqlc.JobStateDiscarded, } { startingState := startingState t.Run(fmt.Sprintf("DoesNotAlterFinalizedJobIn%sState", startingState), func(t *testing.T) { t.Parallel() adapter, bundle := setupTx(t) params := makeFakeJobInsertParams(0, nil) initialRes, err := adapter.JobInsert(ctx, params) require.NoError(t, err) res, err := adapter.queries.JobUpdate(ctx, bundle.ex, dbsqlc.JobUpdateParams{ ID: initialRes.Job.ID, FinalizedAtDoUpdate: true, FinalizedAt: ptrutil.Ptr(time.Now()), StateDoUpdate: true, State: startingState, }) require.NoError(t, err) jobAfter, err := adapter.JobCancel(ctx, res.ID) require.NoError(t, err) require.Equal(t, startingState, jobAfter.State) require.WithinDuration(t, *res.FinalizedAt, *jobAfter.FinalizedAt, time.Microsecond) require.JSONEq(t, `{}`, string(jobAfter.Metadata)) }) } t.Run("ReturnsErrNoRowsIfJobDoesNotExist", func(t *testing.T) { t.Parallel() adapter, _ := setupTx(t) jobAfter, err := adapter.JobCancel(ctx, 1234567890) require.ErrorIs(t, err, riverdriver.ErrNoRows) require.Nil(t, jobAfter) }) } func Test_StandardAdapter_JobGetAvailable(t *testing.T) { t.Parallel() ctx := context.Background() type testBundle struct { baselineTime time.Time // baseline time frozen at now when setup is called tx pgx.Tx } setup := func(t *testing.T) (*StandardAdapter, *testBundle) { t.Helper() bundle := &testBundle{ baselineTime: time.Now(), tx: riverinternaltest.TestTx(ctx, t), } adapter := NewStandardAdapter(riverinternaltest.BaseServiceArchetype(t), testAdapterConfig(bundle.tx)) adapter.TimeNowUTC = func() time.Time { return bundle.baselineTime } return adapter, bundle } t.Run("Success", func(t *testing.T) { t.Parallel() adapter, bundle := setup(t) _, err := adapter.JobInsertTx(ctx, bundle.tx, makeFakeJobInsertParams(0, nil)) require.NoError(t, err) jobRows, err := adapter.JobGetAvailableTx(ctx, bundle.tx, rivercommon.QueueDefault, 100) require.NoError(t, err) require.Len(t, jobRows, 1) jobRow := jobRows[0] require.Equal(t, []string{adapter.workerName}, jobRow.AttemptedBy) }) t.Run("ConstrainedToLimit", func(t *testing.T) { t.Parallel() adapter, bundle := setup(t) _, err := adapter.JobInsertTx(ctx, bundle.tx, makeFakeJobInsertParams(0, nil)) require.NoError(t, err) _, err = adapter.JobInsertTx(ctx, bundle.tx, makeFakeJobInsertParams(1, nil)) require.NoError(t, err) // Two rows inserted but only one found because of the added limit. jobRows, err := adapter.JobGetAvailableTx(ctx, bundle.tx, rivercommon.QueueDefault, 1) require.NoError(t, err) require.Len(t, jobRows, 1) }) t.Run("ConstrainedToQueue", func(t *testing.T) { t.Parallel() adapter, bundle := setup(t) _, err := adapter.JobInsertTx(ctx, bundle.tx, makeFakeJobInsertParams(0, &makeFakeJobInsertParamsOpts{ Queue: ptrutil.Ptr("other-queue"), })) require.NoError(t, err) // Job is in a non-default queue so it's not found. jobRows, err := adapter.JobGetAvailableTx(ctx, bundle.tx, rivercommon.QueueDefault, 1) require.NoError(t, err) require.Empty(t, jobRows) }) t.Run("ConstrainedToScheduledAtBeforeNow", func(t *testing.T) { t.Parallel() adapter, bundle := setup(t) _, err := adapter.JobInsertTx(ctx, bundle.tx, makeFakeJobInsertParams(0, &makeFakeJobInsertParamsOpts{ ScheduledAt: ptrutil.Ptr(time.Now().Add(1 * time.Minute)), })) require.NoError(t, err) // Job is scheduled a while from now so it's not found. jobRows, err := adapter.JobGetAvailableTx(ctx, bundle.tx, rivercommon.QueueDefault, 1) require.NoError(t, err) require.Empty(t, jobRows) }) } func Test_StandardAdapter_JobInsert(t *testing.T) { t.Parallel() ctx := context.Background() type testBundle struct { baselineTime time.Time // baseline time frozen at now when setup is called ex dbutil.Executor } setup := func(t *testing.T, ex dbutil.Executor) (*StandardAdapter, *testBundle) { t.Helper() bundle := &testBundle{ baselineTime: time.Now(), ex: ex, } adapter := NewStandardAdapter(riverinternaltest.BaseServiceArchetype(t), testAdapterConfig(bundle.ex)) adapter.TimeNowUTC = func() time.Time { return bundle.baselineTime } return adapter, bundle } setupTx := func(t *testing.T) (*StandardAdapter, *testBundle) { t.Helper() return setup(t, riverinternaltest.TestTx(ctx, t)) } t.Run("Success", func(t *testing.T) { t.Parallel() adapter, _ := setupTx(t) insertParams := makeFakeJobInsertParams(0, nil) res, err := adapter.JobInsert(ctx, insertParams) require.NoError(t, err) // Sanity check, following assertion depends on this: require.True(t, insertParams.ScheduledAt.IsZero()) require.Greater(t, res.Job.ID, int64(0), "expected job ID to be set, got %d", res.Job.ID) require.JSONEq(t, string(insertParams.EncodedArgs), string(res.Job.Args)) require.Equal(t, int16(0), res.Job.Attempt) require.Nil(t, res.Job.AttemptedAt) require.Empty(t, res.Job.AttemptedBy) require.WithinDuration(t, time.Now(), res.Job.CreatedAt, 2*time.Second) require.Empty(t, res.Job.Errors) require.Nil(t, res.Job.FinalizedAt) require.Equal(t, insertParams.Kind, res.Job.Kind) require.Equal(t, int16(insertParams.MaxAttempts), res.Job.MaxAttempts) require.Equal(t, insertParams.Metadata, res.Job.Metadata) require.Equal(t, int16(insertParams.Priority), res.Job.Priority) require.Equal(t, insertParams.Queue, res.Job.Queue) require.Equal(t, dbsqlc.JobStateAvailable, res.Job.State) require.WithinDuration(t, time.Now(), res.Job.ScheduledAt, 2*time.Second) require.Empty(t, res.Job.Tags) }) t.Run("InsertAndFetch", func(t *testing.T) { t.Parallel() adapter, _ := setupTx(t) const maxJobsToFetch = 8 res, err := adapter.JobInsert(ctx, makeFakeJobInsertParams(0, nil)) require.NoError(t, err) require.NotEqual(t, 0, res.Job.ID, "expected job ID to be set, got %d", res.Job.ID) require.WithinDuration(t, time.Now(), res.Job.ScheduledAt, 1*time.Second) jobs, err := adapter.JobGetAvailable(ctx, rivercommon.QueueDefault, maxJobsToFetch) require.NoError(t, err) require.Len(t, jobs, 1, "inserted 1 job but fetched %d jobs:\n%+v", len(jobs), jobs) require.Equal(t, dbsqlc.JobStateRunning, jobs[0].State, "expected selected job to be in running state, got %q", jobs[0].State) for i := 1; i < 10; i++ { _, err := adapter.JobInsert(ctx, makeFakeJobInsertParams(i, nil)) require.NoError(t, err) } jobs, err = adapter.JobGetAvailable(ctx, rivercommon.QueueDefault, maxJobsToFetch) require.NoError(t, err) require.Len(t, jobs, maxJobsToFetch, "inserted 9 more jobs and expected to fetch max of %d jobs but fetched %d jobs:\n%+v", maxJobsToFetch, len(jobs), jobs) for _, j := range jobs { require.Equal(t, dbsqlc.JobStateRunning, j.State, "expected selected job to be in running state, got %q", j.State) } jobs, err = adapter.JobGetAvailable(ctx, rivercommon.QueueDefault, maxJobsToFetch) require.NoError(t, err) require.Len(t, jobs, 1, "expected to fetch 1 remaining job but fetched %d jobs:\n%+v", len(jobs), jobs) }) t.Run("UniqueJobByArgs", func(t *testing.T) { t.Parallel() adapter, _ := setupTx(t) insertParams := makeFakeJobInsertParams(0, nil) insertParams.Unique = true insertParams.UniqueByArgs = true res0, err := adapter.JobInsert(ctx, insertParams) require.NoError(t, err) require.False(t, res0.UniqueSkippedAsDuplicate) // Insert a second job with the same args, but expect that the same job // ID to come back because we're still within its unique parameters. res1, err := adapter.JobInsert(ctx, insertParams) require.NoError(t, err) require.Equal(t, res0.Job.ID, res1.Job.ID) require.True(t, res1.UniqueSkippedAsDuplicate) insertParams.EncodedArgs = []byte(`{"key":"different"}`) // Same operation again, except that because we've modified the unique // dimension, another job is allowed to be queued, so the new ID is // not the same. res2, err := adapter.JobInsert(ctx, insertParams) require.NoError(t, err) require.NotEqual(t, res0.Job.ID, res2.Job.ID) require.False(t, res2.UniqueSkippedAsDuplicate) }) t.Run("UniqueJobByPeriod", func(t *testing.T) { t.Parallel() adapter, bundle := setupTx(t) insertParams := makeFakeJobInsertParams(0, nil) insertParams.Unique = true insertParams.UniqueByPeriod = 15 * time.Minute res0, err := adapter.JobInsert(ctx, insertParams) require.NoError(t, err) require.False(t, res0.UniqueSkippedAsDuplicate) // Insert a second job with the same args, but expect that the same job // ID to come back because we're still within its unique parameters. res1, err := adapter.JobInsert(ctx, insertParams) require.NoError(t, err) require.Equal(t, res0.Job.ID, res1.Job.ID) require.True(t, res1.UniqueSkippedAsDuplicate) adapter.TimeNowUTC = func() time.Time { return bundle.baselineTime.Add(insertParams.UniqueByPeriod).Add(1 * time.Second) } // Same operation again, except that because we've advanced time passed // the period within unique bounds, another job is allowed to be queued, // so the new ID is not the same. res2, err := adapter.JobInsert(ctx, insertParams) require.NoError(t, err) require.NotEqual(t, res0.Job.ID, res2.Job.ID) require.False(t, res2.UniqueSkippedAsDuplicate) }) t.Run("UniqueJobByQueue", func(t *testing.T) { t.Parallel() adapter, _ := setupTx(t) insertParams := makeFakeJobInsertParams(0, nil) insertParams.Unique = true insertParams.UniqueByQueue = true res0, err := adapter.JobInsert(ctx, insertParams) require.NoError(t, err) require.False(t, res0.UniqueSkippedAsDuplicate) // Insert a second job with the same args, but expect that the same job // ID to come back because we're still within its unique parameters. res1, err := adapter.JobInsert(ctx, insertParams) require.NoError(t, err) require.Equal(t, res0.Job.ID, res1.Job.ID) require.True(t, res1.UniqueSkippedAsDuplicate) insertParams.Queue = "alternate_queue" // Same operation again, except that because we've modified the unique // dimension, another job is allowed to be queued, so the new ID is // not the same. res2, err := adapter.JobInsert(ctx, insertParams) require.NoError(t, err) require.NotEqual(t, res0.Job.ID, res2.Job.ID) require.False(t, res2.UniqueSkippedAsDuplicate) }) t.Run("UniqueJobByState", func(t *testing.T) { t.Parallel() adapter, bundle := setupTx(t) insertParams := makeFakeJobInsertParams(0, nil) insertParams.Unique = true insertParams.UniqueByState = []dbsqlc.JobState{dbsqlc.JobStateAvailable, dbsqlc.JobStateRunning} res0, err := adapter.JobInsert(ctx, insertParams) require.NoError(t, err) require.False(t, res0.UniqueSkippedAsDuplicate) // Insert a second job with the same args, but expect that the same job // ID to come back because we're still within its unique parameters. res1, err := adapter.JobInsert(ctx, insertParams) require.NoError(t, err) require.Equal(t, res0.Job.ID, res1.Job.ID) require.True(t, res1.UniqueSkippedAsDuplicate) // A new job is allowed if we're inserting the job with a state that's // not included in the unique state set. { insertParams := *insertParams // dup insertParams.State = dbsqlc.JobStateCompleted res2, err := adapter.JobInsert(ctx, &insertParams) require.NoError(t, err) require.NotEqual(t, res0.Job.ID, res2.Job.ID) require.False(t, res2.UniqueSkippedAsDuplicate) } // A new job is also allowed if the state of the originally inserted job // changes to one that's not included in the unique state set. { _, err := adapter.queries.JobUpdate(ctx, bundle.ex, dbsqlc.JobUpdateParams{ ID: res0.Job.ID, StateDoUpdate: true, State: dbsqlc.JobStateCompleted, }) require.NoError(t, err) res2, err := adapter.JobInsert(ctx, insertParams) require.NoError(t, err) require.NotEqual(t, res0.Job.ID, res2.Job.ID) require.False(t, res2.UniqueSkippedAsDuplicate) } }) // Unlike other unique options, state gets a default set when it's not // supplied. This test case checks that the default is working as expected. t.Run("UniqueJobByDefaultState", func(t *testing.T) { t.Parallel() adapter, bundle := setupTx(t) insertParams := makeFakeJobInsertParams(0, nil) insertParams.Unique = true insertParams.UniqueByQueue = true res0, err := adapter.JobInsert(ctx, insertParams) require.NoError(t, err) require.False(t, res0.UniqueSkippedAsDuplicate) // Insert a second job with the same args, but expect that the same job // ID to come back because we're still within its unique parameters. res1, err := adapter.JobInsert(ctx, insertParams) require.NoError(t, err) require.Equal(t, res0.Job.ID, res1.Job.ID) require.True(t, res1.UniqueSkippedAsDuplicate) // Test all the other default unique states (see `defaultUniqueStates`) // to make sure that in each case an inserted job still counts as a // duplicate. The only state we don't test is `available` because that's // already been done above. for _, defaultState := range []dbsqlc.JobState{ dbsqlc.JobStateCompleted, dbsqlc.JobStateRunning, dbsqlc.JobStateRetryable, dbsqlc.JobStateScheduled, } { _, err = adapter.queries.JobUpdate(ctx, bundle.ex, dbsqlc.JobUpdateParams{ ID: res0.Job.ID, StateDoUpdate: true, State: defaultState, }) require.NoError(t, err) // Still counts as a duplicate. res1, err := adapter.JobInsert(ctx, insertParams) require.NoError(t, err) require.Equal(t, res0.Job.ID, res1.Job.ID) require.True(t, res1.UniqueSkippedAsDuplicate) } _, err = adapter.queries.JobUpdate(ctx, bundle.ex, dbsqlc.JobUpdateParams{ ID: res0.Job.ID, StateDoUpdate: true, State: dbsqlc.JobStateDiscarded, }) require.NoError(t, err) // Uniqueness includes a default set of states, so by moving the // original job to "discarded", we're now allowed to insert a new job // again, despite not having explicitly set the `ByState` option. res2, err := adapter.JobInsert(ctx, insertParams) require.NoError(t, err) require.NotEqual(t, res0.Job.ID, res2.Job.ID) require.False(t, res2.UniqueSkippedAsDuplicate) }) t.Run("UniqueJobAllOptions", func(t *testing.T) { t.Parallel() adapter, bundle := setupTx(t) insertParams := makeFakeJobInsertParams(0, nil) insertParams.Unique = true insertParams.UniqueByArgs = true insertParams.UniqueByPeriod = 15 * time.Minute insertParams.UniqueByQueue = true insertParams.UniqueByState = []dbsqlc.JobState{dbsqlc.JobStateAvailable, dbsqlc.JobStateRunning} // Gut check to make sure all the unique properties were correctly set. require.True(t, insertParams.Unique) require.True(t, insertParams.UniqueByArgs) require.NotZero(t, insertParams.UniqueByPeriod) require.True(t, insertParams.UniqueByQueue) require.Equal(t, []dbsqlc.JobState{dbsqlc.JobStateAvailable, dbsqlc.JobStateRunning}, insertParams.UniqueByState) res0, err := adapter.JobInsert(ctx, insertParams) require.NoError(t, err) require.False(t, res0.UniqueSkippedAsDuplicate) // Insert a second job with the same args, but expect that the same job // ID to come back because we're still within its unique parameters. res1, err := adapter.JobInsert(ctx, insertParams) require.NoError(t, err) require.Equal(t, res0.Job.ID, res1.Job.ID) require.True(t, res1.UniqueSkippedAsDuplicate) // With args modified { insertParams := *insertParams // dup insertParams.EncodedArgs = []byte(`{"key":"different"}`) // New job because a unique dimension has changed. res2, err := adapter.JobInsert(ctx, &insertParams) require.NoError(t, err) require.NotEqual(t, res0.Job.ID, res2.Job.ID) require.False(t, res2.UniqueSkippedAsDuplicate) } // With period modified { insertParams := *insertParams // dup adapter.TimeNowUTC = func() time.Time { return bundle.baselineTime.Add(insertParams.UniqueByPeriod).Add(1 * time.Second) } // New job because a unique dimension has changed. res2, err := adapter.JobInsert(ctx, &insertParams) require.NoError(t, err) require.NotEqual(t, res0.Job.ID, res2.Job.ID) require.False(t, res2.UniqueSkippedAsDuplicate) // Make sure to change timeNow back adapter.TimeNowUTC = func() time.Time { return bundle.baselineTime } } // With queue modified { insertParams := *insertParams // dup insertParams.Queue = "alternate_queue" // New job because a unique dimension has changed. res2, err := adapter.JobInsert(ctx, &insertParams) require.NoError(t, err) require.NotEqual(t, res0.Job.ID, res2.Job.ID) require.False(t, res2.UniqueSkippedAsDuplicate) } // With state modified { insertParams := *insertParams // dup insertParams.State = dbsqlc.JobStateCompleted // New job because a unique dimension has changed. res2, err := adapter.JobInsert(ctx, &insertParams) require.NoError(t, err) require.NotEqual(t, res0.Job.ID, res2.Job.ID) require.False(t, res2.UniqueSkippedAsDuplicate) } }) t.Run("UniqueJobContention", func(t *testing.T) { t.Parallel() adapter, bundle := setup(t, riverinternaltest.TestDB(ctx, t)) insertParams := makeFakeJobInsertParams(0, nil) insertParams.Unique = true insertParams.UniqueByPeriod = 15 * time.Minute var ( numContendingJobs = runtime.NumCPU() // max allowed test manager connections insertedJobs = make([]*dbsqlc.RiverJob, numContendingJobs) insertedJobsMu sync.Mutex wg sync.WaitGroup ) for i := 0; i < numContendingJobs; i++ { jobNum := i wg.Add(1) go func() { _, err := dbutil.WithTxV(ctx, bundle.ex, func(ctx context.Context, tx pgx.Tx) (struct{}, error) { res, err := adapter.JobInsertTx(ctx, tx, insertParams) require.NoError(t, err) insertedJobsMu.Lock() insertedJobs[jobNum] = res.Job insertedJobsMu.Unlock() return struct{}{}, nil }) require.NoError(t, err) wg.Done() }() } wg.Wait() firstJobID := insertedJobs[0].ID for i := 1; i < numContendingJobs; i++ { require.Equal(t, firstJobID, insertedJobs[i].ID) } }) } func Test_Adapter_JobInsertMany(t *testing.T) { t.Parallel() // This test needs to use a time from before the transaction begins, otherwise // the newly-scheduled jobs won't yet show as available because their // scheduled_at (which gets a default value from time.Now() in code) will be // after the start of the transaction. now := time.Now().UTC().Add(-1 * time.Minute) ctx := context.Background() tx := riverinternaltest.TestTx(ctx, t) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() adapter := NewStandardAdapter(riverinternaltest.BaseServiceArchetype(t), testAdapterConfig(tx)) adapter.TimeNowUTC = func() time.Time { return now } insertParams := make([]*JobInsertParams, 10) for i := 0; i < len(insertParams); i++ { insertParams[i] = makeFakeJobInsertParams(i, nil) } count, err := adapter.JobInsertMany(ctx, insertParams) require.NoError(t, err) require.Len(t, insertParams, int(count)) jobsAfter, err := adapter.JobGetAvailable(ctx, rivercommon.QueueDefault, int32(len(insertParams))) require.NoError(t, err) require.Len(t, jobsAfter, len(insertParams)) } func Test_StandardAdapter_FetchIsPrioritized(t *testing.T) { t.Parallel() ctx := context.Background() tx := riverinternaltest.TestTx(ctx, t) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() adapter := NewStandardAdapter(riverinternaltest.BaseServiceArchetype(t), testAdapterConfig(tx)) for i := 3; i > 0; i-- { // Insert jobs with decreasing priority numbers (3, 2, 1) which means increasing priority. insertParams := makeFakeJobInsertParams(i, nil) insertParams.Priority = i _, err := adapter.JobInsert(ctx, insertParams) require.NoError(t, err) } // We should fetch the 2 highest priority jobs first in order (priority 1, then 2): jobs, err := adapter.JobGetAvailable(ctx, rivercommon.QueueDefault, 2) require.NoError(t, err) require.Len(t, jobs, 2, "expected to fetch exactly 2 jobs") // Because the jobs are ordered within the fetch query's CTE but *not* within // the final query, the final result list may not actually be sorted. This is // fine, because we've already ensured that we've fetched the jobs we wanted // to fetch via that ORDER BY. For testing we'll need to sort the list after // fetch to easily assert that the expected jobs are in it. sort.Slice(jobs, func(i, j int) bool { return jobs[i].Priority < jobs[j].Priority }) require.Equal(t, int16(1), jobs[0].Priority, "expected first job to have priority 1") require.Equal(t, int16(2), jobs[1].Priority, "expected second job to have priority 2") // Should fetch the one remaining job on the next attempt: jobs, err = adapter.JobGetAvailable(ctx, rivercommon.QueueDefault, 1) require.NoError(t, err) require.Len(t, jobs, 1, "expected to fetch exactly 1 job") require.Equal(t, int16(3), jobs[0].Priority, "expected final job to have priority 2") } func Test_StandardAdapter_JobList_and_JobListTx(t *testing.T) { t.Parallel() ctx := context.Background() type testBundle struct { baselineTime time.Time // baseline time frozen at now when setup is called ex dbutil.Executor tx pgx.Tx jobs []*dbsqlc.RiverJob } setup := func(t *testing.T, tx pgx.Tx) (*StandardAdapter, *testBundle) { t.Helper() bundle := &testBundle{ baselineTime: time.Now(), ex: tx, tx: tx, } adapter := NewStandardAdapter(riverinternaltest.BaseServiceArchetype(t), testAdapterConfig(bundle.ex)) adapter.TimeNowUTC = func() time.Time { return bundle.baselineTime } params := makeFakeJobInsertParams(1, &makeFakeJobInsertParamsOpts{Queue: ptrutil.Ptr("priority")}) job1, err := adapter.JobInsert(ctx, params) require.NoError(t, err) params = makeFakeJobInsertParams(2, nil) job2, err := adapter.JobInsert(ctx, params) require.NoError(t, err) params = makeFakeJobInsertParams(3, &makeFakeJobInsertParamsOpts{Metadata: []byte(`{"some_key": "some_value"}`)}) job3, err := adapter.JobInsert(ctx, params) require.NoError(t, err) params = makeFakeJobInsertParams(4, &makeFakeJobInsertParamsOpts{State: ptrutil.Ptr(dbsqlc.JobStateRunning)}) job4, err := adapter.JobInsert(ctx, params) require.NoError(t, err) bundle.jobs = []*dbsqlc.RiverJob{job1.Job, job2.Job, job3.Job, job4.Job} return adapter, bundle } setupTx := func(t *testing.T) (*StandardAdapter, *testBundle) { t.Helper() return setup(t, riverinternaltest.TestTx(ctx, t)) } type testListFunc func(jobs []*dbsqlc.RiverJob, err error) execTest := func(ctx context.Context, t *testing.T, adapter *StandardAdapter, params JobListParams, tx pgx.Tx, testFunc testListFunc) { t.Helper() t.Logf("testing JobList") jobs, err := adapter.JobList(ctx, params) testFunc(jobs, err) t.Logf("testing JobListTx") // use a sub-transaction in case it's rolled back or errors: subTx, err := tx.Begin(ctx) require.NoError(t, err) defer subTx.Rollback(ctx) jobs, err = adapter.JobListTx(ctx, subTx, params) testFunc(jobs, err) } t.Run("Minimal", func(t *testing.T) { t.Parallel() adapter, bundle := setupTx(t) params := JobListParams{ LimitCount: 2, OrderBy: []JobListOrderBy{{Expr: "id", Order: SortOrderDesc}}, State: rivertype.JobStateAvailable, } execTest(ctx, t, adapter, params, bundle.tx, func(jobs []*dbsqlc.RiverJob, err error) { require.NoError(t, err) // job 1 is excluded due to pagination limit of 2, while job 4 is excluded // due to its state: job2 := bundle.jobs[1] job3 := bundle.jobs[2] returnedIDs := sliceutil.Map(jobs, func(j *dbsqlc.RiverJob) int64 { return j.ID }) require.Equal(t, []int64{job3.ID, job2.ID}, returnedIDs) }) }) t.Run("ComplexConditionsWithNamedArgs", func(t *testing.T) { t.Parallel() adapter, bundle := setupTx(t) params := JobListParams{ Conditions: "jsonb_extract_path(args, VARIADIC @paths1::text[]) = @value1::jsonb", LimitCount: 2, NamedArgs: map[string]any{"paths1": []string{"job_num"}, "value1": 2}, OrderBy: []JobListOrderBy{{Expr: "id", Order: SortOrderDesc}}, State: rivertype.JobStateAvailable, } execTest(ctx, t, adapter, params, bundle.tx, func(jobs []*dbsqlc.RiverJob, err error) { require.NoError(t, err) job2 := bundle.jobs[1] returnedIDs := sliceutil.Map(jobs, func(j *dbsqlc.RiverJob) int64 { return j.ID }) require.Equal(t, []int64{job2.ID}, returnedIDs) }) }) t.Run("ConditionsWithQueues", func(t *testing.T) { t.Parallel() adapter, bundle := setupTx(t) params := JobListParams{ Conditions: "finalized_at IS NULL", LimitCount: 2, OrderBy: []JobListOrderBy{{Expr: "id", Order: SortOrderDesc}}, Queues: []string{"priority"}, State: rivertype.JobStateAvailable, } execTest(ctx, t, adapter, params, bundle.tx, func(jobs []*dbsqlc.RiverJob, err error) { require.NoError(t, err) job1 := bundle.jobs[0] returnedIDs := sliceutil.Map(jobs, func(j *dbsqlc.RiverJob) int64 { return j.ID }) require.Equal(t, []int64{job1.ID}, returnedIDs) }) }) t.Run("WithMetadataAndNoStateFilter", func(t *testing.T) { t.Parallel() adapter, bundle := setupTx(t) params := JobListParams{ Conditions: "metadata @> @metadata_filter::jsonb", LimitCount: 2, NamedArgs: map[string]any{"metadata_filter": `{"some_key": "some_value"}`}, OrderBy: []JobListOrderBy{{Expr: "id", Order: SortOrderDesc}}, } execTest(ctx, t, adapter, params, bundle.tx, func(jobs []*dbsqlc.RiverJob, err error) { require.NoError(t, err) job3 := bundle.jobs[2] returnedIDs := sliceutil.Map(jobs, func(j *dbsqlc.RiverJob) int64 { return j.ID }) require.Equal(t, []int64{job3.ID}, returnedIDs) }) }) } func Test_StandardAdapter_JobSetStateCompleted(t *testing.T) { t.Parallel() ctx := context.Background() type testBundle struct { baselineTime time.Time // baseline time frozen at now when setup is called ex dbutil.Executor } setup := func(t *testing.T, ex dbutil.Executor) (*StandardAdapter, *testBundle) { t.Helper() bundle := &testBundle{ baselineTime: time.Now(), ex: ex, } adapter := NewStandardAdapter(riverinternaltest.BaseServiceArchetype(t), testAdapterConfig(bundle.ex)) adapter.TimeNowUTC = func() time.Time { return bundle.baselineTime } return adapter, bundle } setupTx := func(t *testing.T) (*StandardAdapter, *testBundle) { t.Helper() return setup(t, riverinternaltest.TestTx(ctx, t)) } t.Run("CompletesARunningJob", func(t *testing.T) { t.Parallel() adapter, bundle := setupTx(t) params := makeFakeJobInsertParams(0, nil) params.State = dbsqlc.JobStateRunning res, err := adapter.JobInsert(ctx, params) require.NoError(t, err) require.Equal(t, dbsqlc.JobStateRunning, res.Job.State) jAfter, err := adapter.JobSetStateIfRunning(ctx, JobSetStateCompleted(res.Job.ID, bundle.baselineTime)) require.NoError(t, err) require.Equal(t, dbsqlc.JobStateCompleted, jAfter.State) require.WithinDuration(t, bundle.baselineTime, *jAfter.FinalizedAt, time.Microsecond) j, err := adapter.queries.JobGetByID(ctx, bundle.ex, res.Job.ID) require.NoError(t, err) require.Equal(t, dbsqlc.JobStateCompleted, j.State) }) t.Run("DoesNotCompleteARetryableJob", func(t *testing.T) { t.Parallel() adapter, bundle := setupTx(t) params := makeFakeJobInsertParams(0, nil) params.State = dbsqlc.JobStateRetryable res, err := adapter.JobInsert(ctx, params) require.NoError(t, err) require.Equal(t, dbsqlc.JobStateRetryable, res.Job.State) jAfter, err := adapter.JobSetStateIfRunning(ctx, JobSetStateCompleted(res.Job.ID, bundle.baselineTime)) require.NoError(t, err) require.Equal(t, dbsqlc.JobStateRetryable, jAfter.State) require.Nil(t, jAfter.FinalizedAt) j, err := adapter.queries.JobGetByID(ctx, bundle.ex, res.Job.ID) require.NoError(t, err) require.Equal(t, dbsqlc.JobStateRetryable, j.State) }) } func Test_StandardAdapter_JobSetStateErrored(t *testing.T) { t.Parallel() ctx := context.Background() type testBundle struct { baselineTime time.Time // baseline time frozen at now when setup is called errPayload []byte ex dbutil.Executor } setup := func(t *testing.T, executor dbutil.Executor) (*StandardAdapter, *testBundle) { t.Helper() tNow := time.Now() errPayload, err := json.Marshal(dbsqlc.AttemptError{ Attempt: 1, At: tNow.UTC(), Error: "fake error", Trace: "foo.go:123\nbar.go:456", }) require.NoError(t, err) bundle := &testBundle{ baselineTime: tNow, errPayload: errPayload, ex: executor, } adapter := NewStandardAdapter(riverinternaltest.BaseServiceArchetype(t), testAdapterConfig(bundle.ex)) adapter.TimeNowUTC = func() time.Time { return bundle.baselineTime } return adapter, bundle } setupTx := func(t *testing.T) (*StandardAdapter, *testBundle) { t.Helper() return setup(t, riverinternaltest.TestTx(ctx, t)) } t.Run("SetsARunningJobToRetryable", func(t *testing.T) { t.Parallel() adapter, bundle := setupTx(t) params := makeFakeJobInsertParams(0, nil) params.State = dbsqlc.JobStateRunning res, err := adapter.JobInsert(ctx, params) require.NoError(t, err) require.Equal(t, dbsqlc.JobStateRunning, res.Job.State) jAfter, err := adapter.JobSetStateIfRunning(ctx, JobSetStateErrorRetryable(res.Job.ID, bundle.baselineTime, bundle.errPayload)) require.NoError(t, err) require.Equal(t, dbsqlc.JobStateRetryable, jAfter.State) require.WithinDuration(t, bundle.baselineTime, jAfter.ScheduledAt, time.Microsecond) j, err := adapter.queries.JobGetByID(ctx, bundle.ex, res.Job.ID) require.NoError(t, err) require.Equal(t, dbsqlc.JobStateRetryable, j.State) // validate error payload: require.Len(t, jAfter.Errors, 1) require.Equal(t, bundle.baselineTime.UTC(), jAfter.Errors[0].At) require.Equal(t, uint16(1), jAfter.Errors[0].Attempt) require.Equal(t, "fake error", jAfter.Errors[0].Error) require.Equal(t, "foo.go:123\nbar.go:456", jAfter.Errors[0].Trace) }) t.Run("DoesNotTouchAlreadyRetryableJob", func(t *testing.T) { t.Parallel() adapter, bundle := setupTx(t) params := makeFakeJobInsertParams(0, nil) params.State = dbsqlc.JobStateRetryable params.ScheduledAt = bundle.baselineTime.Add(10 * time.Second) res, err := adapter.JobInsert(ctx, params) require.NoError(t, err) require.Equal(t, dbsqlc.JobStateRetryable, res.Job.State) jAfter, err := adapter.JobSetStateIfRunning(ctx, JobSetStateErrorRetryable(res.Job.ID, bundle.baselineTime, bundle.errPayload)) require.NoError(t, err) require.Equal(t, dbsqlc.JobStateRetryable, jAfter.State) require.WithinDuration(t, params.ScheduledAt, jAfter.ScheduledAt, time.Microsecond) j, err := adapter.queries.JobGetByID(ctx, bundle.ex, res.Job.ID) require.NoError(t, err) require.Equal(t, dbsqlc.JobStateRetryable, j.State) require.WithinDuration(t, params.ScheduledAt, jAfter.ScheduledAt, time.Microsecond) }) t.Run("SetsAJobWithCancelAttemptedAtToCancelled", func(t *testing.T) { // If a job has cancel_attempted_at in its metadata, it means that the user // tried to cancel the job with the Cancel API but that the job // finished/errored before the producer received the cancel notification. // // In this case, we want to move the job to cancelled instead of retryable // so that the job is not retried. t.Parallel() adapter, bundle := setupTx(t) params := makeFakeJobInsertParams(0, &makeFakeJobInsertParamsOpts{ ScheduledAt: ptrutil.Ptr(bundle.baselineTime.Add(-10 * time.Second)), }) params.State = dbsqlc.JobStateRunning params.Metadata = []byte(fmt.Sprintf(`{"cancel_attempted_at":"%s"}`, time.Now().UTC().Format(time.RFC3339))) res, err := adapter.JobInsert(ctx, params) require.NoError(t, err) jAfter, err := adapter.JobSetStateIfRunning(ctx, JobSetStateErrorRetryable(res.Job.ID, bundle.baselineTime, bundle.errPayload)) require.NoError(t, err) require.Equal(t, dbsqlc.JobStateCancelled, jAfter.State) require.NotNil(t, jAfter.FinalizedAt) // Loose assertion against FinalizedAt just to make sure it was set (it uses // the database's now() instead of a passed-in time): require.WithinDuration(t, time.Now().UTC(), *jAfter.FinalizedAt, 2*time.Second) // ScheduledAt should not be touched: require.WithinDuration(t, params.ScheduledAt, jAfter.ScheduledAt, time.Microsecond) // Errors should still be appended to: require.Len(t, jAfter.Errors, 1) require.Contains(t, jAfter.Errors[0].Error, "fake error") j, err := adapter.queries.JobGetByID(ctx, bundle.ex, res.Job.ID) require.NoError(t, err) require.Equal(t, dbsqlc.JobStateCancelled, j.State) require.WithinDuration(t, params.ScheduledAt, jAfter.ScheduledAt, time.Microsecond) }) } func Test_StandardAdapter_LeadershipAttemptElect_CannotElectTwiceInARow(t *testing.T) { t.Parallel() ctx := context.Background() tx := riverinternaltest.TestTx(ctx, t) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() adapter := NewStandardAdapter(riverinternaltest.BaseServiceArchetype(t), testAdapterConfig(tx)) won, err := adapter.LeadershipAttemptElect(ctx, false, rivercommon.QueueDefault, "fakeWorker0", 30*time.Second) require.NoError(t, err) require.True(t, won) won, err = adapter.LeadershipAttemptElect(ctx, false, rivercommon.QueueDefault, "fakeWorker0", 30*time.Second) require.NoError(t, err) require.False(t, won) } func Benchmark_StandardAdapter_Insert(b *testing.B) { ctx := context.Background() tx := riverinternaltest.TestTx(ctx, b) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() adapter := NewStandardAdapter(riverinternaltest.BaseServiceArchetype(b), testAdapterConfig(tx)) b.ResetTimer() for i := 0; i < b.N; i++ { if _, err := adapter.JobInsert(ctx, makeFakeJobInsertParams(i, nil)); err != nil { b.Fatal(err) } } } func Benchmark_StandardAdapter_Insert_Parallelized(b *testing.B) { ctx := context.Background() dbPool := riverinternaltest.TestDB(ctx, b) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() adapter := NewStandardAdapter(riverinternaltest.BaseServiceArchetype(b), testAdapterConfig(dbPool)) b.ResetTimer() b.RunParallel(func(pb *testing.PB) { i := 0 for pb.Next() { if _, err := adapter.JobInsert(ctx, makeFakeJobInsertParams(i, nil)); err != nil { b.Fatal(err) } i++ } }) } func Benchmark_StandardAdapter_Fetch_100(b *testing.B) { ctx := context.Background() dbPool := riverinternaltest.TestDB(ctx, b) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() adapter := NewStandardAdapter(riverinternaltest.BaseServiceArchetype(b), testAdapterConfig(dbPool)) for i := 0; i < b.N*100; i++ { insertParams := makeFakeJobInsertParams(i, nil) if _, err := adapter.JobInsert(ctx, insertParams); err != nil { b.Fatal(err) } } b.ResetTimer() for i := 0; i < b.N; i++ { if _, err := adapter.JobGetAvailable(ctx, rivercommon.QueueDefault, 100); err != nil { b.Fatal(err) } } } func Benchmark_StandardAdapter_Fetch_100_Parallelized(b *testing.B) { ctx := context.Background() dbPool := riverinternaltest.TestDB(ctx, b) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() adapter := NewStandardAdapter(riverinternaltest.BaseServiceArchetype(b), testAdapterConfig(dbPool)) for i := 0; i < b.N*100*runtime.NumCPU(); i++ { insertParams := makeFakeJobInsertParams(i, nil) if _, err := adapter.JobInsert(ctx, insertParams); err != nil { b.Fatal(err) } } b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { if _, err := adapter.JobGetAvailable(ctx, rivercommon.QueueDefault, 100); err != nil { b.Fatal(err) } } }) } func testAdapterConfig(ex dbutil.Executor) *StandardAdapterConfig { return &StandardAdapterConfig{ AdvisoryLockPrefix: 0, Executor: ex, WorkerName: "fakeWorker0", } } type makeFakeJobInsertParamsOpts struct { Metadata []byte Queue *string ScheduledAt *time.Time State *dbsqlc.JobState } func makeFakeJobInsertParams(i int, opts *makeFakeJobInsertParamsOpts) *JobInsertParams { if opts == nil { opts = &makeFakeJobInsertParamsOpts{} } metadata := []byte("{}") if len(opts.Metadata) > 0 { metadata = opts.Metadata } return &JobInsertParams{ EncodedArgs: []byte(fmt.Sprintf(`{"job_num":%d}`, i)), Kind: "fake_job", MaxAttempts: rivercommon.MaxAttemptsDefault, Metadata: metadata, Priority: rivercommon.PriorityDefault, Queue: ptrutil.ValOrDefault(opts.Queue, rivercommon.QueueDefault), ScheduledAt: ptrutil.ValOrDefault(opts.ScheduledAt, time.Time{}), State: ptrutil.ValOrDefault(opts.State, dbsqlc.JobStateAvailable), } }
package com.example.springstudents_KorsakovYT.service.Impl; import com.example.springstudents_KorsakovYT.model.Student; import com.example.springstudents_KorsakovYT.repository.InMemoryStudentDAO; import com.example.springstudents_KorsakovYT.service.StudentService; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import java.util.List; @Service @AllArgsConstructor public class InMemoryStudentServiceImpl implements StudentService { private final InMemoryStudentDAO repository; @Override public List<Student> findAllStudent(){ return repository.findAllStudent(); } @Override public Student saveStudent(Student student) { return repository.saveStudent(student); } @Override public Student findByEmail(String email) { return repository.findByEmail(email); } @Override public Student updateStudent(Student student) { return repository.updateStudent(student); } @Override public void deleteStudent(String email) { repository.deleteStudent(email); } }
library(parallel) library(doSNOW) numCores<-floor(detectCores() * 0.75) cl <- makeCluster(numCores) registerDoSNOW(cl) # progress bar ------------------------------------------------------------ library(progress) iterations <- 100 # used for the foreach loop pb <- progress_bar$new( format = "letter = :letter [:bar] :elapsed | eta: :eta", total = iterations, # 100 width = 60) progress_letter <- rep(LETTERS[1:10], 10) # token reported in progress bar # allowing progress bar to be used in foreach ----------------------------- progress <- function(n){ pb$tick(tokens = list(letter = progress_letter[n])) } opts <- list(progress = progress) # foreach loop ------------------------------------------------------------ library(foreach) foreach(i = 1:iterations, .combine = rbind, .options.snow = opts) %dopar% { summary(rnorm(1e6))[3] } stopCluster(cl)
from decimal import Decimal from django.conf import settings from django.contrib.gis.db import models from django.utils.translation import gettext_lazy as _ from .mixins import TimestampedModelMixin, UserStampedModelMixin VAT_PERCENT = Decimal(0.24) class RefundStatus(models.TextChoices): OPEN = "OPEN", _("Open") REQUEST_FOR_APPROVAL = "REQUEST_FOR_APPROVAL", _("Request for approval") ACCEPTED = "ACCEPTED", _("Accepted") REJECTED = "REJECTED", _("Rejected") class Refund(TimestampedModelMixin, UserStampedModelMixin): name = models.CharField(_("Name"), max_length=200, blank=True) order = models.ForeignKey( "Order", verbose_name=_("Order"), on_delete=models.PROTECT, related_name="refunds", ) permits = models.ManyToManyField( "ParkingPermit", verbose_name=_("Permits"), related_name="refunds", blank=True, ) amount = models.DecimalField( _("Amount"), default=0.00, max_digits=6, decimal_places=2 ) iban = models.CharField(max_length=30, blank=True) status = models.CharField( _("Status"), max_length=32, choices=RefundStatus.choices, default=RefundStatus.OPEN, ) description = models.TextField(_("Description"), blank=True) accepted_at = models.DateTimeField(_("Accepted at"), null=True, blank=True) accepted_by = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_("Accepted by"), on_delete=models.PROTECT, null=True, blank=True, ) class Meta: verbose_name = _("Refund") verbose_name_plural = _("Refunds") def __str__(self): return f"{self.name} ({self.iban})" @property def vat(self): return Decimal(self.amount) * VAT_PERCENT
import type {NextFunction, Request, Response} from 'express'; import express from 'express'; import FreetCollection from '../freet/collection'; import * as userValidator from '../user/middleware'; import * as freetValidator from '../freet/middleware'; import * as util from './util'; import FeedCollection from './collection'; import followerCollection from '../follower/collection'; import UserCollection from '../user/collection'; const router = express.Router(); /** * Get the feeds * * @name GET /api/feeds * * * @return {string} - A success message * @throws {403} - If the user is not logged in * @return {FreetResponse[]} - A list of all the freets sorted in descending * order by date modified */ router.get( '/', [ userValidator.isUserLoggedIn ], async (req: Request, res: Response, next: NextFunction) => { const userId = (req.session.userId as string) ?? ''; // Will not be an empty string since its validated in isUserLoggedIn const user = await UserCollection.findOneByUserId(userId); const following = await followerCollection.findAllFollowing(userId); // console.log(following); // following.forEach(async follow => { for(const follow of following){ // console.log('a'); // console.log(follow); const acctFreets = await FreetCollection.findAllByUserId(follow.userId); // console.log(acctFreets) // acctFreets.forEach(async freet => { for(const freet of acctFreets){ // console.log('nn'); await FeedCollection.addOne(userId, freet._id); } } //should add all of followings freets to my own thing let allFeedsConverted; const allFeeds = await FeedCollection.findAllByUserId(userId); if(allFeeds.length >=1){ const unresolvedFeeds = await allFeeds.map(util.constructFeedResponse); allFeedsConverted = await Promise.all(unresolvedFeeds); } res.status(200).json({ message: 'Your feed was created succesfully.', feed: (allFeedsConverted ? allFeedsConverted : allFeeds) }); await FeedCollection.deleteManyOfUserId(userId); } ); export {router as feedRouter};
import { Component, Input, OnInit } from '@angular/core'; import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms'; import { MatDialog } from '@angular/material/dialog'; import { MatSelectChange } from '@angular/material/select'; import { MatSnackBar } from '@angular/material/snack-bar'; import { ActivatedRoute } from '@angular/router'; import { PlaceOrderService } from 'src/app/core/services/place-order.service'; import { PortofolioService } from 'src/app/core/services/portofolio.service'; import { TradeSuggestionsService } from 'src/app/core/services/trade_suggestions/trade-suggestions.service'; import { ConfirmTradeDialogData } from '../../models/trade-suggestions/confirm-trade-dialog-data'; import { TradeSuggestion } from '../../models/trade-suggestions/trade-suggestion'; import { ConfirmTradeDialogComponent } from '../marketbrowser/confirm-trade-dialog/confirm-trade-dialog.component'; @Component({ selector: 'app-trade-suggestions-selector', templateUrl: './trade-suggestions-selector.component.html', styleUrls: ['./trade-suggestions-selector.component.scss'], }) export class TradeSuggestionsSelectorComponent implements OnInit { _interval: string = '1d'; _algorithm: string = 'TS_SSA'; ticker: string; displayedColumns = ['CompanyData', 'PositionType', 'InitialPrice', 'FinalPrice', 'ProfitPercentage', 'Start', 'Final', 'Action'] ALGS_LIST: string[] = ['TS_SSA', 'T_FTO', 'T_SDCA', 'T_FFO', 'T_LBFP']; INTERVAL_LIST: string[] = ['1h', '6h', '1d', '3d', '5d']; tradeSuggestions: TradeSuggestion[] = []; form: UntypedFormGroup; constructor( private fb: UntypedFormBuilder, private tradeSuggestionsService: TradeSuggestionsService, private portofolioService: PortofolioService, private route: ActivatedRoute, public dialog: MatDialog, public snackbar: MatSnackBar ) { this.ticker = this.route.snapshot.paramMap.get('ticker') || ''; this.form = this.fb.group({ interval: [this._interval, [Validators.required]], algorithm: [this._algorithm, [Validators.required]], }); } ngOnInit(): void { this.loadSuggestions() } loadSuggestions(): void { this.tradeSuggestionsService .gatherTradeSuggestions(this.ticker, this._algorithm, this._interval) .subscribe((res) => (this.tradeSuggestions = res)); } openConfirmationDialog(suggestion: TradeSuggestion): void { const dialogRef = this.dialog.open(ConfirmTradeDialogComponent, { width: '350px', data: { investedAmount: suggestion.openRequest.investedAmount, suggestion: suggestion }, }); dialogRef.afterClosed().subscribe(result => { console.log('The dialog was closed'); var resultData = <ConfirmTradeDialogData> result resultData.suggestion.openRequest.stopLossAmount = result.suggestion.openRequest.investedAmount * 3 / 4 if (resultData != undefined) { this.portofolioService .PlaceTransactionOrder(resultData.suggestion.openRequest) .subscribe((res) => { this.snackbar.open('Transaction scheduled successfully', 'OK', {duration: 3000}) for (var entry of this.tradeSuggestions) { if (entry.openRequest.token == res.token) { entry.disabled = true break; } } } , (err) => { this.snackbar.open(`Transaction didn\'t get scheduled. Error: ${err.error.detail}.`, 'OK', {duration: 1000}) }); } }); } algorithmChanged(event: MatSelectChange) { this._algorithm = event.value this.loadSuggestions() } intervalChanged(event: MatSelectChange) { this._interval = event.value this.loadSuggestions() } profitValuePercentage(suggestion: TradeSuggestion) { var difference = Math.abs(suggestion.currentPrice - suggestion.expectedPrice) return difference / suggestion.currentPrice } }
<?php /** * Upgrader API: Bulk_Plugin_Upgrader_Skin class * * @since 4.6.0 */ /** * Bulk Theme Upgrader Skin for WordPress Theme Upgrades. * * @since 3.0.0 * @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader-skins.php. * @see Bulk_Upgrader_Skin */ class Bulk_Theme_Upgrader_Skin extends Bulk_Upgrader_Skin { /** * Theme info. * * The Theme_Upgrader::bulk_upgrade() method will fill this in * with info retrieved from the Theme_Upgrader::theme_info() method, * which in turn calls the wp_get_theme() function. * * @var WP_Theme|false The theme's info object, or false. */ public $theme_info = false; public function add_strings() { parent::add_strings(); /* translators: 1: Theme name, 2: Number of the theme, 3: Total number of themes being updated. */ $this->upgrader->strings['skin_before_update_header'] = __('Updating Theme %1$s (%2$d/%3$d)'); } /** * @param string $title */ public function before($title = '') { parent::before($this->theme_info->display('Name')); } /** * @param string $title */ public function after($title = '') { parent::after($this->theme_info->display('Name')); $this->decrement_update_count('theme'); } public function bulk_footer() { parent::bulk_footer(); $update_actions = [ 'themes_page' => sprintf( '<a href="%s" target="_parent">%s</a>', self_admin_url('themes.php'), __('Go to Themes page') ), 'updates_page' => sprintf( '<a href="%s" target="_parent">%s</a>', self_admin_url('update-core.php'), __('Go to WordPress Updates page') ), ]; if (! current_user_can('switch_themes') && ! current_user_can('edit_theme_options')) { unset($update_actions['themes_page']); } /** * Filters the list of action links available following bulk theme updates. * * @since 3.0.0 * * @param string[] $update_actions Array of theme action links. * @param WP_Theme $theme_info Theme object for the last-updated theme. */ $update_actions = apply_filters('update_bulk_theme_complete_actions', $update_actions, $this->theme_info); if (! empty($update_actions)) { $this->feedback(implode(' | ', (array) $update_actions)); } } }
// // CustomCell.swift // UnsplashPhotoApp // // Created by Amir on 30.04.2022. // import UIKit final class CustomCollectionCell: UICollectionViewCell { static let identifier = "CustomCollectionViewCell" private let padding = 2.0 private var imageURL: URL? { didSet { imageView.image = nil updateImage() } } private lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() override init(frame: CGRect) { super.init(frame: frame) setupView() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK: - Public methods extension CustomCollectionCell { func configure(with photo: Photo) { guard let url = photo.urls else { return } imageURL = URL(string: url.thumb) } } //MARK: - Private Methods extension CustomCollectionCell { private func setupView() { contentView.addSubview(imageView) contentView.backgroundColor = .black configureConstraints() } private func configureConstraints() { NSLayoutConstraint.activate([ imageView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: padding), imageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: padding), imageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -padding), imageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -padding) ]) } private func updateImage() { guard let imageURL = imageURL else { return } getImage(from: imageURL) { result in switch result { case .success(let image): if imageURL == self.imageURL { self.imageView.image = image } case .failure(let error): print(error) } } } private func getImage(from url: URL, completion: @escaping(Result<UIImage, Error>) -> Void){ NetworkManager.shared.fetchImage(from: url) { result in switch result { case .success(let imageData): guard let image = UIImage(data: imageData) else { return } completion(.success(image)) case .failure(let error): completion(.failure(error)) } } } }
package org.siri_hate.main_service.model.dto.mapper; import org.mapstruct.Mapper; import org.mapstruct.MappingTarget; import org.mapstruct.factory.Mappers; import org.siri_hate.main_service.model.dto.request.event.EventFullRequest; import org.siri_hate.main_service.model.dto.response.event.EventFullResponse; import org.siri_hate.main_service.model.dto.response.event.EventSummaryResponse; import org.siri_hate.main_service.model.entity.Event; import java.util.List; /** * This interface represents a mapper for Event. * It uses MapStruct, a code generator that simplifies the implementation of mappings between Java bean types. */ @Mapper(componentModel = "spring") public interface EventMapper { /** * An instance of the EventMapper. */ EventMapper INSTANCE = Mappers.getMapper(EventMapper.class); /** * Maps from EventFullRequest to Event. * * @param event the EventFullRequest object * @return the mapped Event object */ Event toEvent(EventFullRequest event); /** * Maps from Event to EventFullResponse. * * @param event the Event object * @return the mapped EventFullResponse object */ EventFullResponse toEventFullResponse(Event event); /** * Maps from Event to EventSummaryResponse. * * @param event the Event object * @return the mapped EventSummaryResponse object */ EventSummaryResponse toEventSummaryResponse(Event event); /** * Maps from a list of Event to a list of EventSummaryResponse. * * @param events the list of Event objects * @return the mapped list of EventSummaryResponse objects */ List<EventSummaryResponse> toEventSummaryResponseList(List<Event> events); /** * Updates an existing Event object from an EventFullRequest object. * * @param eventFullRequest the EventFullRequest object * @param event the Event object to be updated * @return the updated Event object */ Event eventUpdate(EventFullRequest eventFullRequest, @MappingTarget Event event); }
//{ Driver Code Starts //Initial Template for C++ #include <bits/stdc++.h> using namespace std; class Node{ public: int val; Node *next; Node(int num){ val=num; next=NULL; } }; // } Driver Code Ends //User function Template for C++ /* class Node{ public: int val; Node *next; Node(int num){ val=num; next=NULL; } }; */ bool isPrime(int n){ if(n <= 1) return false; if(n == 2 || n == 3) return true; for(int i = 2 ; i * i <= n ; i++){ if(n % i == 0) return false; } return true; } class Solution{ public: Node *primeList(Node *head){ Node * curr = head; while(curr != NULL){ int orgVal = curr->val; int smallVal = orgVal; int largeVal = orgVal; if(orgVal == 1){ curr->val = 2; continue; } while(!isPrime(smallVal)){ smallVal--; } while(!isPrime(largeVal)){ largeVal++; } if(orgVal - smallVal <= largeVal - orgVal){ curr->val = smallVal; }else{ curr->val = largeVal; } curr = curr->next; } return head; } }; //{ Driver Code Starts. int main(){ int t; cin>>t; while(t--){ int n; cin>>n; Node *head,*tail; int num; cin>>num; head=tail=new Node(num); for(int i=0;i<n-1;i++){ int num; cin>>num; tail->next=new Node(num); tail=tail->next; } Solution ob; Node *temp=ob.primeList(head); while(temp!=NULL){ cout<<temp->val<<" "; temp=temp->next; } cout<<endl; } return 0; } // } Driver Code Ends
import { Icon } from "@chakra-ui/icons"; import { Box, Button, Container, Divider, Flex, Heading, Stack, Text, } from "@chakra-ui/react"; import { withUrqlClient } from "next-urql"; import Link from "next/link"; import { useState } from "react"; import { FaUser } from "react-icons/fa"; import { Loaders, Navbar, Sidebar, Updoot } from "../components"; import EditDeleteButton from "../components/EditDeleteButton"; import { usePostsQuery } from "../generated/graphql"; import { createUrqlClient } from "../utils/createUrqlClient"; import { itemProps, postsDataTypes } from "../utils/dataTypes"; import { getUser } from "../utils/getLocalStorage"; import { isServer } from "../utils/isServer"; const Index = () => { const [variables, setVariables] = useState({ limit: 5, cursor: null as null | string, }); const [{ data, fetching }] = usePostsQuery({ variables, }); if (!fetching && !data) { return ( <Flex> <Box m="auto" my={8}> Something went wrong!!! </Box> </Flex> ); } const loadMore = (data: postsDataTypes) => { setVariables({ limit: variables.limit, cursor: data.posts.posts[data.posts.posts.length - 1].createdAt, }); }; let userId = getUser().userId; const authorId = Number(userId); return ( <> <Navbar /> <Container maxW="950px" style={{ fontFamily: '"Rajdhani", sans-serif' }} mt={10} > {!data && fetching ? ( <> <Loaders /> </> ) : ( <Stack spacing={8}> <Box fontSize="xl" textTransform="lowercase" mb={0}> <Button> <Link href="/create-post">CreatePost</Link> </Button> </Box> {data!.posts.posts.map((item) => !item ? null : ( <Box pt={0} p={3} shadow="md" borderWidth="1px" key={item.id}> <Flex direction="row" justify="space-between" alignItems="center" mb={1} > <Heading fontSize="xl" textTransform="capitalize" style={{ fontFamily: '"Rajdhani", sans-serif' }} > {item.title} </Heading> <Flex> <Icon as={FaUser} boxSize={4} color="tomato"></Icon> <Text pl="1" color="tomato"> {item.author.username} </Text> </Flex> </Flex> <Divider /> <Flex direction="row" alignItems="flex-start" mt={3}> <Updoot item={item as itemProps} /> <Box> <Text mt={1}>{item.descriptionSnippet}...</Text> <Button mt={2} colorScheme="gray" fontSize="xs" size="xs" variant="solid" > <Link href={`/single-page/${item.id}`}>Read More</Link> </Button> </Box> </Flex> {authorId === item?.author?.id ? ( <EditDeleteButton id={item?.id} authorId={item?.author?.id} check={false} /> ) : null} </Box> ) )} </Stack> )} {data && data.posts.hasMore ? ( <Flex> <Button isLoading={fetching} m="auto" my={8} onClick={() => loadMore(data as postsDataTypes)} > Load More </Button> </Flex> ) : null} </Container> </> ); }; export default withUrqlClient( createUrqlClient, isServer() ? { ssr: true } : { ssr: false } )(Index);
package org.apache.bigtop.manager.server.controller; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.annotation.Resource; import jakarta.validation.Valid; import lombok.extern.slf4j.Slf4j; import org.apache.bigtop.manager.server.model.dto.ConfigurationDTO; import org.apache.bigtop.manager.server.model.mapper.ConfigurationMapper; import org.apache.bigtop.manager.server.model.req.ConfigurationReq; import org.apache.bigtop.manager.server.model.vo.CommandVO; import org.apache.bigtop.manager.server.model.vo.ConfigurationVO; import org.apache.bigtop.manager.server.service.ConfigurationService; import org.apache.bigtop.manager.server.utils.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.List; @Slf4j @Tag(name = "Cluster Configuration Controller") @Validated @RestController @RequestMapping("/clusters/{clusterId}/configurations") public class ConfigurationController { @Resource private ConfigurationService configurationService; @Operation(summary = "list", description = "list all version configurations") @GetMapping public ResponseEntity<List<ConfigurationVO>> list(@PathVariable Long clusterId) { List<ConfigurationVO> configurationVOList = configurationService.list(clusterId); return ResponseEntity.success(configurationVOList); } @Operation(summary = "list", description = "list all latest configurations") @GetMapping("/latest") public ResponseEntity<List<ConfigurationVO>> latest(@PathVariable Long clusterId) { List<ConfigurationVO> configurationVOList = configurationService.latest(clusterId); return ResponseEntity.success(configurationVOList); } @Operation(summary = "update", description = "update|create|roll-back configurations") @PutMapping public ResponseEntity<CommandVO> update(@PathVariable Long clusterId, @RequestBody List<@Valid ConfigurationReq> configurationReqs) { List<ConfigurationDTO> configurationDTOList = ConfigurationMapper.INSTANCE.fromReq2DTO(configurationReqs); log.info("configurationDTOList: {}", configurationDTOList); CommandVO configurationVOList = configurationService.update(clusterId, configurationDTOList); return ResponseEntity.success(configurationVOList); } }
import { Helmet } from "react-helmet"; import Header from "../components/Header"; import Input from "../utils/Input"; import Checkbox from "../utils/Checkbox"; import { useState } from "react"; import { useForm } from "react-hook-form"; import { registerAPI } from "../api/auth"; import { useTheme } from "../context/ThemeContext"; import { useNavigate } from "react-router-dom"; import { toast } from "react-toastify"; import { useSignIn } from "react-auth-kit"; import { usePermify } from "@permify/react-role"; export default function RegisterPage() { const { getValues, register, handleSubmit, formState: { errors } } = useForm() const navigate = useNavigate(); const signIn = useSignIn(); const { setUser } = usePermify(); async function onSubmit(data) { // call register api function const response = await registerAPI({ first_name: data['first-name'], last_name: data['last-name'], email: data['email'], password: data['password'], project: data['project-name'] }) console.log(response); if (response.status === 'success') { setUser({ id: response.response.user.email, roles: response.response.user.roles.map(role => role.name), permissions: response.response.user.roles.map(role => role.name) }); signIn({ token: response.response.token, expiresIn: 131400, tokenType: "Bearer", authState: response.response.user }); navigate('/onboarding'); } else { toast.error(response.message); } } function isConfirmEmailSame() { const email = getValues('email') const confirmEmail = getValues('confirm-email') return email === confirmEmail } function isConfirmPasswordSame() { const password = getValues('password') const confirmPassword = getValues('confirm-password') return password === confirmPassword } return ( <main className={`bg-white dark:bg-black`}> <Helmet> <title>DSS | Registration</title> </Helmet> <Header /> <div className="h-screen bg-opacity-0 bg-transparent"> <section className={`bg-neutral-100 dark:bg-[#202427] my-[55px] md:rounded-[12px] max-w-4xl mx-auto px-[16px] md:px-[105px] py-[60px]`}> <h1 className={`text-[#202427] dark:text-white text-[24px] leading-[29px] font-medium mb-[43px]`}>Sign up your Project Group</h1> <form onSubmit={handleSubmit(onSubmit)}> <div className="grid grid-cols-2 gap-x-[32px] gap-y-[19px] mb-[31px]"> <Input name={'project-name'} title={"Name of Project Group"} register={register} getValues={getValues} validations={{ required: true }} error={errors['project-name']} rootClasses={'col-span-2'} /> <Input name={'first-name'} title={"Admin first name"} register={register} getValues={getValues} validations={{ required: true }} error={errors['first-name']} rootClasses={'col-span-2 md:col-span-1'} /> <Input name={'last-name'} title={"Admin last name"} register={register} getValues={getValues} validations={{ required: true }} error={errors['last-name']} rootClasses={'col-span-2 md:col-span-1'} /> <Input name={'email'} title={"Email"} type={'email'} register={register} getValues={getValues} validations={{ required: true, pattern: /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/ }} error={errors['email']} rootClasses={'col-span-2 md:col-span-1'} /> <Input name={'confirm-email'} title={"Confirm email"} type={'email'} register={register} getValues={getValues} validations={{ required: true, pattern: /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/, validate: isConfirmEmailSame }} error={errors['confirm-email']} rootClasses={'col-span-2 md:col-span-1'} /> <Input name={'password'} title={"Password"} type={'password'} register={register} getValues={getValues} validations={{ required: true }} error={errors['password']} rootClasses={'col-span-2 md:col-span-1'} /> <Input name={'confirm-password'} title={"Confirm Password"} type={'password'} register={register} getValues={getValues} validations={{ required: true, validate: isConfirmPasswordSame }} error={errors['confirm-password']} rootClasses={'col-span-2 md:col-span-1'} /> </div> <Checkbox rootClasses={'col-span-2 mb-[75px]'} name={'terms-agree'} register={register} getValues={getValues} validations={{ required: true }} error={errors['terms-agree']} > Yes, I agree to the <span className="underline">Terms of Service</span> and <span className="underline">Privacy policy</span> </Checkbox> <button type="submit" className="ml-auto flex bg-[#0071FF] rounded-full px-[32px] py-[15px] text-white text-[16px] leading-[18px] font-medium"> Sign Up </button> </form> </section> </div> </main> ) }
#pragma once class EUserBrokerOrderDraft; class EUserBrokerOrder : public Entity // todo: rename to EBotUserBrokerOrder { public: static const EType eType = EType::userBrokerOrder; public: enum class Type { buy = meguco_user_broker_order_buy, sell = meguco_user_broker_order_sell, }; enum class State { submitting = meguco_user_broker_order_submitting, open = meguco_user_broker_order_open, //canceling = meguco_user_broker_order_canceling, canceled = meguco_user_broker_order_canceled, //updating = meguco_user_broker_order_updating, closed = meguco_user_broker_order_closed, //removing = meguco_user_broker_order_removing, error = meguco_user_broker_order_error, draft, canceling, updating, removing, }; public: EUserBrokerOrder(const meguco_user_broker_order_entity& data) : Entity(eType, data.entity.id) { type = (Type)data.type; date = QDateTime::fromMSecsSinceEpoch(data.entity.time); price = data.price; amount = data.amount; total = data.total; fee = qAbs(total - price * amount); state = (State)data.state; //rawId = data.raw_id; //timeout = data.timeout; } EUserBrokerOrder(quint64 id, const EUserBrokerOrderDraft& order); /* void toEntity(meguco_user_market_order_entity& entity) const { entity.entity.id = id; entity.entity.time = date.toMSecsSinceEpoch(); entity.entity.size = sizeof(entity); entity.type = (uint8_t)type; entity.state = (uint8_t)state; entity.price = price; entity.amount = amount; entity.total = total; entity.raw_id = rawId; entity.timeout = timeout; } */ Type getType() const {return type;} const QDateTime& getDate() const {return date;} double getPrice() const {return price;} void setPrice(double price, double total) { this->price = price; this->total = total; fee = qAbs(total - price * amount); } double getAmount() const {return amount;} void setAmount(double amount, double total) { this->amount = amount; this->total = total; fee = qAbs(total - price * amount); } double getFee() const {return fee;} double getTotal() const {return total;} State getState() const {return state;} void setState(State state) {this->state = state;} protected: EUserBrokerOrder(EType type, quint64 id) : Entity(type, id) {} protected: Type type; QDateTime date; double price; double amount; double fee; double total; State state; //quint64 rawId; //quint64 timeout; };
import { Button, buttonVariants } from "@/components/ui/button" import { Label } from "@/components/ui/label" import { cn } from "@/lib/utils" import { ImagePlus, X } from 'lucide-react' import Image from 'next/image' import { useEffect, useState } from 'react' export interface SelectedPhoto { file: File, url: string } const PhotosSelector = ( { defaultValue, onChange } : { defaultValue : SelectedPhoto[], onChange: Function }) => { const [ selectedPhotos, setSelectedPhotos ] = useState<SelectedPhoto[]>([]); function handleSelectPhotos(e) { const newPhotos : SelectedPhoto[] = []; const length = e.target.files.length; // TODO: refactor can be used by handleDrop too for(let i = 0; i < length; i++) { const file = e.target.files[i] const fileSizeKB = file.size / 1024 if (fileSizeKB <= 1024) { newPhotos.push({ file: e.target.files[i], url: URL.createObjectURL(e.target.files[i]) }); } else { alert('File size exceeds 1MB limit') } } setSelectedPhotos((oldPhotos) => [...oldPhotos, ...newPhotos]); } function handleDrop(e) { e.preventDefault(); const newPhotos : SelectedPhoto[] = []; if (e.dataTransfer.items) { // Use DataTransferItemList interface to access the file(s) [...e.dataTransfer.items].forEach((item, i) => { // If dropped items aren't files, reject them if (item.kind === "file") { const file = item.getAsFile(); newPhotos.push({ file: file, url: URL.createObjectURL(file) }); } }); } else { // Use DataTransfer interface to access the file(s) [...e.dataTransfer.files].forEach((file, i) => { newPhotos.push({ file: file, url: URL.createObjectURL(file) }); }); } setSelectedPhotos((oldPhotos) => [...oldPhotos, ...newPhotos]); } function deletePhoto(index) { setSelectedPhotos(s => s.filter((_, i) => i !== index)); } // add defaultValue to selectedPhotos useEffect(() => { if(!defaultValue) return; setSelectedPhotos((oldPhotos : SelectedPhotos[]) => { return [...oldPhotos, ...defaultValue]; }); },[defaultValue]); useEffect(() => { console.log(selectedPhotos); onChange(selectedPhotos); }, [selectedPhotos]) return ( <> <div className="flex justify-between items-end"> <h2 className="text-xl font-semibold">Photos</h2> <span className="text-sm">{selectedPhotos.length}/10</span> </div> <div onDragOver={(e) => {e.preventDefault();}} onDrop={(e) => {handleDrop(e)}} className="grid content-center bg-white w-full p-8 text-center rounded border border-black border-dashed md:aspect-[4/3]"> <ImagePlus className="w-16 h-16 mb-2 mx-auto" /> <div> <div className="hidden md:block w-fit mx-auto"> {/* TODO: implement drag and drop. */} <p className="text-lg font-semibold">Drag and Drop Pictures</p> <div className="flex items-center"> <span className="border border-black h-0 flex-grow">&nbsp;</span> <p className="p-2">or</p> <span className="border border-black h-0 flex-grow">&nbsp;</span> </div> </div> <Label className={cn(buttonVariants({ variant: '', size: '', className: '' }))} htmlFor="uploadPhotos">Browse Photos</Label> <input id="uploadPhotos" type="file" accept="image/*" multiple onChange={handleSelectPhotos} className="hidden"></input> </div> </div> <div className="grid grid-cols-5 grid-rows-2 gap-4 my-4"> {/* Thumbnails */} {selectedPhotos && selectedPhotos.map((photo, index) => ( <Label key={index} htmlFor={`post-picture-${index}`} className="rounded relative overflow-hidden aspect-square items-center"> <Image className="align-middle w-full" src={photo.url} width={80} height={80} alt="board game picture"></Image> {/* TODO: existing pictures must be selected on load */} <Button id={`post-picture-${index}`} value={photo.url} onClick={() => deletePhoto(index)} name="post_pictures" type="button" variant="outline" className="absolute top-1 right-1 rounded-full p-0 h-6 w-6 text-danger hover:text-danger"> <X className="w-3 aspect-square"/> </Button> </Label> ))} </div> </> ) } export default PhotosSelector
import { base_url_store } from "@/shared/lib/requestUrl"; import { createAsyncThunk } from "@reduxjs/toolkit"; import axios from "axios"; const purchaseURL = `${base_url_store}/purchase`; export const getStorePurchase = createAsyncThunk("purchase/get", async () => { try { const response = await axios.get(purchaseURL); console.log("Get Store Purchase data: ", response.data); return response.data; } catch (error) { console.log("Failed to get store purchase data"); } }); export const createStorePurchase = createAsyncThunk( "purchase/create", async ({ data }) => { try { const response = await axios.post(purchaseURL, data); console.log("Create Store Purchase data: ", response.data); return response.data; } catch (error) { console.log("Failed to get create purchase data"); } } ); export const updateStorePurchase = createAsyncThunk( "purchase/update", async ({ data }, id) => { try { const updateURL = `${purchaseURL}/${id}`; const response = await axios.patch(updateURL, data); console.log("Update Store Purchase data: ", response.data); return response.data; } catch (error) { console.log("Failed to update store purchase data"); } } ); export const deleteStorePurchase = createAsyncThunk( "purchase/delete", async ({ data }, id) => { try { const deleteURL = `${purchaseURL}/${id}`; const response = await axios.get(deleteURL); console.log("Delete Store Purchase data: ", response.data); return response.data; } catch (error) { console.log("Failed to delete store purchase data"); } } );
<template> <BaseContainer :module="$t('menu.modules.customers')" :title="$t('customers.title')" > <div class="card"> <BaseTableHeader :refresh-action-field="{ page: 1, field: { next: true } }" :title="$t('customers.customer.listTitle')" add-action-router-name="customer.form" refresh-action-name="customer/getCustomersList" entity="Customer" /> <div class="card-body"> <div class="row"> <div class="col-md-4 mt-2 mb-2"> <BaseFieldGroup :with-append="false" :with-refresh="true" refresh-action-name="customer_type/getCustomerTypesList" > <BaseSelect v-model.number="customerFilter.customer_type_id" :options="customerTypes" :placeholder="`${$t('common.attributes.customerType')} ?`" key-label="label" key-value="id" /> </BaseFieldGroup> </div> <div class="col-md-4 mt-2 mb-2"> <BaseFieldGroup :with-append="false" :with-refresh="true" refresh-action-name="country/getCountriesList" > <BaseSelect v-model.number="customerFilter.country_id" :options="countries" :placeholder="`${$t('common.attributes.country')} ?`" key-label="name" key-value="id" /> </BaseFieldGroup> </div> <div class="col-md-4 mt-2 mb-2"> <BaseFieldGroup :with-append="false" :with-refresh="true" refresh-action-name="localization/getLocalizationsList" > <BaseSelect v-model.number="customerFilter.localization_id" :options="cities" :placeholder="`${$t('common.attributes.city')} ?`" key-label="label" key-value="id" /> </BaseFieldGroup> </div> </div> <BaseDatatable v-if="!$store.state.globalLoading" :tfoot="false" :total="customers.length" > <template #headers> <th>#</th> <th>{{ $t('common.attributes.city') }}</th> <th>{{ $t('common.attributes.name') }}</th> <th>{{ $t('common.attributes.phone') }}</th> <th> {{ $t('common.attributes.total_amount_buying') }} </th> <th>{{ $t('common.actions') }}</th> </template> <tr v-for="customer in customers" :key="customer.id"> <td>{{ customer.id }}</td> <td>{{ customer.localization?.city ?? '-' }}</td> <td>{{ `${customer?.first_name} ${customer?.name}` }}</td> <td>{{ customer.phone }}</td> <td> {{ (customer.total_sub_price ?? 0).toFixed() + ' ' + currency }} </td> <td> <BaseActionBtnGroup entity="Customer" :icon-version="true" @show=" $router.push({ name: 'customer.details', params: { id: customer.id }, }) " @update=" $router.push({ name: 'customer.form', params: { id: customer.id }, }) " @delete="deleteCustomer(customer)" /> </td> </tr> </BaseDatatable> <br /> </div> </div> <router-view /> </BaseContainer> </template> <script> import BaseDatatable from '/@/components/common/BaseDatatable.vue'; import store from '/@/store'; import { mapGetters } from 'vuex'; import BaseContainer from '/@/components/common/BaseContainer.vue'; import BaseTableHeader from '/@/components/common/BaseTableHeader.vue'; import BaseSelect from '/@/components/common/BaseSelect.vue'; import BaseFieldGroup from '/@/components/common/BaseFieldGroup.vue'; import BaseActionBtnGroup from '/@/components/common/BaseActionBtnGroup.vue'; export default { name: 'CustomersList', components: { BaseActionBtnGroup, BaseTableHeader, BaseContainer, BaseDatatable, BaseSelect, BaseFieldGroup, }, beforeRouteEnter(routeTo, routeFrom, next) { Promise.all([ store.dispatch('customer/getCustomersList', { page: 1, field: {}, }), store.dispatch('localization/getLocalizationsList', { page: 1, field: {}, }), store.dispatch('country/getCountriesList', { page: 1, field: {}, }), ]) .then(() => { next(); }) .catch((error) => { console.log(error); next(); }); }, data() { return { customerFilter: { customer_type_id: null, localization_id: null, country_id: null, }, }; }, computed: { ...mapGetters('workspace', ['currency']), ...mapGetters('customer', ['getCustomerByFilter', 'customer']), ...mapGetters('customer_type', ['customerTypes']), ...mapGetters('country', ['countries']), ...mapGetters('localization', ['cities']), customers() { return this.getCustomerByFilter(this.customerFilter); }, }, watch: { customers() { if (!this.$store.state.globalLoading) { this.$store.dispatch('setGlobalLoading', true); setTimeout(() => this.$store.dispatch('setGlobalLoading', false), 2000); } }, }, methods: { deleteCustomer(customer) { if (confirm(this.$t('messages.confirmDelete', { label: customer.name }))) this.$store.dispatch('customer/deleteCustomer', customer.id); }, }, }; </script> <style scoped></style>