text stringlengths 184 4.48M |
|---|
import React, { useState } from "react";
import {
Box,
Button,
Heading,
SimpleGrid,
Spinner,
Text,
useToast,
} from "@chakra-ui/react";
import { InfoIcon } from "@chakra-ui/icons";
import { Grid, Badge, Flex, Select } from "@chakra-ui/react";
import { Link } from "react-router-dom";
import {
Modal,
ModalOverlay,
ModalContent,
ModalHeader,
ModalFooter,
ModalBody,
ModalCloseButton,
useDisclosure,
} from "@chakra-ui/react";
import axios from "axios";
const EachAppointment = ({ item, refrace }) => {
const { isOpen, onOpen, onClose } = useDisclosure();
const [select, setSelect] = useState("");
const [loading, setLoading] = useState(false);
const toast = useToast();
const sendNotifaction = (data) => {
axios
.post(`https://drab-blue-mite-belt.cyclic.app/otp/send-mail`, data)
.then((res) => {});
};
const handleUpdate = () => {
setLoading(true);
let Admin = {
email: "sharmaashish7251@gmail.com",
subject: `Appointment ${select}`,
massage: `
Dear Admin,
A new appointment has been ${select}:
- Patient Name: ${item.name}
- Doctor: ${item.doctor}
- Date: ${item.date}
- Time: ${item.time}
Please review and confirm this appointment in our system. If you have any questions or need to make adjustments, please take the necessary actions accordingly.
Thank you for your attention to this appointment.
Best regards,
Doctorsqeries
info@doctorsqueries.com
`,
};
let user = {
email: item.email,
subject: `Appointment ${select}`,
massage: `
Dear ${item.name},
We are pleased to confirm your appointment has been ${select} with ${item.doctor} on at ${item.date}. Below are the appointment details: https://doctorsquery.vercel.app/user-dashboard
- Date: ${item.date}
- Time: ${item.time}
- Doctor: ${item.doctor}
Thank you for choosing Doctorsqeries! We look forward to serving you.
Best regards,
Doctorsqeries
info@doctorsqueries.com
`,
};
axios
.patch(`https://drab-blue-mite-belt.cyclic.app/appointment/${item._id}`, {
...item,
status: select,
})
.then((res) => {
toast({
title: res.data.msg,
description: "",
status: "success",
duration: 5000,
isClosable: true,
});
setLoading(false);
onClose();
refrace();
sendNotifaction(Admin);
sendNotifaction(user);
});
};
return (
<div>
<Box
bg="white"
p={6}
rounded="md"
boxShadow="md"
width="100%"
marginTop={"12px"}
marginBottom={"20px"}
// maxW="400px"
>
<Heading size="lg" mb={4} color="red.400">
Patient Information
</Heading>
<Grid templateColumns="2fr 2fr" gap={5}>
<Text fontWeight="bold" color="gray.600">
Name:
</Text>
<Text>{item.name}</Text>
<Text fontWeight="bold" color="gray.600">
Age:
</Text>
<Text>{item.age}</Text>
<Text fontWeight="bold" color="gray.600">
Gender:
</Text>
<Text>{item.gender}</Text>
<Text fontWeight="bold" color="gray.600">
Address:
</Text>
<Text>{item.address}</Text>
<Text fontWeight="bold" color="gray.600">
Email:
</Text>
<Text>{item.email}</Text>
<Text fontWeight="bold" color="gray.600">
Mobile:
</Text>
<Text>{item.mobile}</Text>
</Grid>
<Text color="gray.600" mt={4}>
Reason for Visit: <Text as="span">{item.reason}</Text>
</Text>
<Text color="gray.600">
Doctor: <Text as="span">{item.doctor}</Text>
</Text>
<Text color="gray.600">
Specialty: <Text as="span">{item.specilaty}</Text>
</Text>
<Flex alignItems="center">
<Text fontWeight="bold" color="gray.600">
Status:
</Text>
<Badge
fontSize={"16px"}
colorScheme={
item.status === "approved"
? "green"
: item.status === "visited"
? "blue"
: item.status === "cancel"
? "red"
: "yellow"
}
ml={2}
>
{item.status}
</Badge>
</Flex>
<Box display={"flex"} justifyContent={"space-between"}>
<Text color="gray.600">
Date: <Text as="span">{item.date}</Text>
</Text>
<Button colorScheme="red" onClick={onOpen}>
Update Appointment
</Button>
<Modal blockScrollOnMount={false} isOpen={isOpen} onClose={onClose}>
<ModalOverlay />
<ModalContent>
<ModalHeader color={"red.500"}>Update Appointment</ModalHeader>
<ModalCloseButton />
<ModalBody>
<Text fontWeight="bold" mb="1rem">
id : {item._id}
</Text>
<Text fontWeight="bold" mb="1rem">
{item.name}
</Text>
<Badge
fontSize={"16px"}
colorScheme={
item.status === "approved"
? "green"
: item.status === "visited"
? "blue"
: item.status === "cancel"
? "red"
: "yellow"
}
ml={2}
>
Status : {item.status}
</Badge>
<br />
<Select
value={select}
onChange={(e) => setSelect(e.target.value)}
marginTop={"10px"}
placeholder="Select option"
>
<option value="approved">Approved</option>
<option value="visited">Visited</option>
<option value="cancel">Cancel</option>
</Select>
<Text marginTop={"12px"}>
Make This Appointment{" "}
<Badge
fontSize={"16px"}
colorScheme={
select === "approved"
? "green"
: select === "visited"
? "blue"
: select === "cancel"
? "red"
: "yellow"
}
ml={2}
>
{select}
</Badge>
</Text>
</ModalBody>
<ModalFooter>
<Button colorScheme="blue" mr={3} onClick={onClose}>
Close
</Button>
<Button
onClick={handleUpdate}
colorScheme="red"
variant="outline"
>
Update {loading ? <Spinner /> : ""}
</Button>
</ModalFooter>
</ModalContent>
</Modal>
</Box>
<Text color="gray.600">
Time: <Text as="span">{item.time}</Text>
</Text>
</Box>
</div>
);
};
export default EachAppointment; |
<?php
/**
* Pimcore
*
* This source file is available under two different licenses:
* - GNU General Public License version 3 (GPLv3)
* - Pimcore Commercial License (PCL)
* Full copyright and license information is available in
* LICENSE.md which is distributed with this source code.
*
* @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)
* @license http://www.pimcore.org/license GPLv3 and PCL
*/
namespace Pimcore\Model\Document\Editable;
use Pimcore\Model;
/**
* @method \Pimcore\Model\Document\Editable\Dao getDao()
*/
class Numeric extends Model\Document\Editable
{
/**
* Contains the current number, or an empty string if not set
*
* @internal
*
* @var string
*/
protected $number = '';
/**
* {@inheritdoc}
*/
public function getType()
{
return 'numeric';
}
/**
* {@inheritdoc}
*/
public function getData()
{
return $this->number;
}
/**
* @see EditableInterface::getData
*
* @return string
*/
public function getNumber()
{
return $this->getData();
}
/**
* {@inheritdoc}
*/
public function frontend()
{
return $this->number;
}
/**
* {@inheritdoc}
*/
public function setDataFromResource($data)
{
$this->number = $data;
return $this;
}
/**
* {@inheritdoc}
*/
public function setDataFromEditmode($data)
{
$this->number = $data;
return $this;
}
/**
* {@inheritdoc}
*/
public function isEmpty()
{
if (is_numeric($this->number)) {
return false;
}
return empty($this->number);
}
} |
"use strict";
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.createBlogFeedFiles = void 0;
const tslib_1 = require("tslib");
const path_1 = tslib_1.__importDefault(require("path"));
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
const feed_1 = require("feed");
const srcset = tslib_1.__importStar(require("srcset"));
const utils_1 = require("@docusaurus/utils");
const utils_common_1 = require("@docusaurus/utils-common");
const cheerio_1 = require("cheerio");
async function generateBlogFeed({ blogPosts, options, siteConfig, outDir, locale, }) {
if (!blogPosts.length) {
return null;
}
const { feedOptions, routeBasePath } = options;
const { url: siteUrl, baseUrl, title, favicon } = siteConfig;
const blogBaseUrl = (0, utils_1.normalizeUrl)([siteUrl, baseUrl, routeBasePath]);
const blogPostsForFeed = feedOptions.limit === false || feedOptions.limit === null
? blogPosts
: blogPosts.slice(0, feedOptions.limit);
const updated = blogPostsForFeed[0]?.metadata.date;
const feed = new feed_1.Feed({
id: blogBaseUrl,
title: feedOptions.title ?? `${title} Blog`,
updated,
language: feedOptions.language ?? locale,
link: blogBaseUrl,
description: feedOptions.description ?? `${siteConfig.title} Blog`,
favicon: favicon ? (0, utils_1.normalizeUrl)([siteUrl, baseUrl, favicon]) : undefined,
copyright: feedOptions.copyright,
});
const createFeedItems = options.feedOptions.createFeedItems ?? defaultCreateFeedItems;
const feedItems = await createFeedItems({
blogPosts: blogPostsForFeed,
siteConfig,
outDir,
defaultCreateFeedItems,
});
feedItems.forEach(feed.addItem);
return feed;
}
async function defaultCreateFeedItems({ blogPosts, siteConfig, outDir, }) {
const { url: siteUrl } = siteConfig;
function toFeedAuthor(author) {
return { name: author.name, link: author.url, email: author.email };
}
return Promise.all(blogPosts.map(async (post) => {
const { metadata: { title: metadataTitle, permalink, date, description, authors, tags, }, } = post;
const content = await (0, utils_1.readOutputHTMLFile)(permalink.replace(siteConfig.baseUrl, ''), outDir, siteConfig.trailingSlash);
const $ = (0, cheerio_1.load)(content);
const blogPostAbsoluteUrl = (0, utils_1.normalizeUrl)([siteUrl, permalink]);
const toAbsoluteUrl = (src) => String(new URL(src, blogPostAbsoluteUrl));
// Make links and image urls absolute
// See https://github.com/facebook/docusaurus/issues/9136
$(`div#${utils_common_1.blogPostContainerID} a, div#${utils_common_1.blogPostContainerID} img`).each((_, elm) => {
if (elm.tagName === 'a') {
const { href } = elm.attribs;
if (href) {
elm.attribs.href = toAbsoluteUrl(href);
}
}
else if (elm.tagName === 'img') {
const { src, srcset: srcsetAttr } = elm.attribs;
if (src) {
elm.attribs.src = toAbsoluteUrl(src);
}
if (srcsetAttr) {
elm.attribs.srcset = srcset.stringify(srcset.parse(srcsetAttr).map((props) => ({
...props,
url: toAbsoluteUrl(props.url),
})));
}
}
});
const feedItem = {
title: metadataTitle,
id: blogPostAbsoluteUrl,
link: blogPostAbsoluteUrl,
date,
description,
// Atom feed demands the "term", while other feeds use "name"
category: tags.map((tag) => ({ name: tag.label, term: tag.label })),
content: $(`#${utils_common_1.blogPostContainerID}`).html(),
};
// json1() method takes the first item of authors array
// it causes an error when authors array is empty
const feedItemAuthors = authors.map(toFeedAuthor);
if (feedItemAuthors.length > 0) {
feedItem.author = feedItemAuthors;
}
return feedItem;
}));
}
async function createBlogFeedFile({ feed, feedType, generatePath, }) {
const [feedContent, feedPath] = (() => {
switch (feedType) {
case 'rss':
return [feed.rss2(), 'rss.xml'];
case 'json':
return [feed.json1(), 'feed.json'];
case 'atom':
return [feed.atom1(), 'atom.xml'];
default:
throw new Error(`Feed type ${feedType} not supported.`);
}
})();
try {
await fs_extra_1.default.outputFile(path_1.default.join(generatePath, feedPath), feedContent);
}
catch (err) {
logger_1.default.error(`Generating ${feedType} feed failed.`);
throw err;
}
}
function shouldBeInFeed(blogPost) {
const excluded = blogPost.metadata.frontMatter.draft ||
blogPost.metadata.frontMatter.unlisted;
return !excluded;
}
async function createBlogFeedFiles({ blogPosts: allBlogPosts, options, siteConfig, outDir, locale, }) {
const blogPosts = allBlogPosts.filter(shouldBeInFeed);
const feed = await generateBlogFeed({
blogPosts,
options,
siteConfig,
outDir,
locale,
});
const feedTypes = options.feedOptions.type;
if (!feed || !feedTypes) {
return;
}
await Promise.all(feedTypes.map((feedType) => createBlogFeedFile({
feed,
feedType,
generatePath: path_1.default.join(outDir, options.routeBasePath),
})));
}
exports.createBlogFeedFiles = createBlogFeedFiles; |
# Git
## Установка git
Ubuntu
```bash
sudo apt update # на всякий случай смотрим новые версии
sudo apt install git-all
```
Windows - GitHub Desktop (CLI + GUI)
## Настройка git
```bash
git config --global user.name "<имя фамилия>"
git config --global user.email "<ваш емейл>"
```
## Аккаунт на github
```bash
# Создание ssh-ключей
ssh-keygen -t ed25519 -C "your_email@example.com"
# Дальше будет несколько вопросов. На все вопросы нужно нажимать Enter.
# Запуск агента ssh, который следит за ключами - для windows не надо
eval "$(ssh-agent -s)"
# Добавления нового ssh-ключа в агент - для windows не надо
ssh-add ~/.ssh/id_ed25519
```
Затем нужно открыть настройки аккаунта на github и перейти в раздел SSH и GPG keys - [ссылка](https://github.com/settings/keys). Нажать на кнопку New SSH key. Скопировать содержимое файла *~/.ssh/id_ed25519.pub* (Linux) или *%userprofile%\ssh\id_ed25519.pub* в Windows. |
<?php
namespace Modules\Marketing\Http\Livewire\Banner;
use App\Constants\BackgroundPosition;
use App\Services\ImageService;
use Livewire\Component;
use Livewire\WithFileUploads;
use Modules\Marketing\Entities\Banner;
class Edit extends Component
{
use WithFileUploads;
public $banner, $oldThumbnail, $thumbnail, $type = 'image', $name, $alt, $reference_url, $position, $is_active = true,
$background_position, $with_caption, $caption_title, $caption_text, $with_button, $button_text, $button_link;
public $backgroundPositions = [], $pluckBackgroundPositions = null;
protected function rules()
{
return [
'thumbnail' => 'nullable|mimes:png,jpg,jpeg|max:512',
'name' => 'required|max:191|unique:banners,id,' . $this->banner->id . ',id',
'alt' => 'nullable|max:191',
'reference_url' => 'nullable|url',
'is_active' => 'nullable|boolean',
'position' => 'numeric|max:20',
'background_position' => 'nullable|max:191|in:' . $this->pluckBackgroundPositions,
'caption_title' => 'nullable|max:191',
'caption_text' => 'nullable|max:500',
'button_text' => 'nullable|max:191',
'button_link' => 'nullable|max:191',
];
}
public function mount($banner)
{
$this->banner = $banner;
$this->oldThumbnail = $banner->desktop_media_path;
$this->name = $banner->name;
$this->alt = $banner->alt;
$this->reference_url = $banner->references_url;
$this->is_active = $banner->is_active;
$this->position = $banner->position;
$this->with_caption = $banner->with_caption;
$this->background_position = $banner->desktop_background_position;
$this->caption_title = $banner->caption_title;
$this->caption_text = $banner->caption_text;
$this->with_button = $banner->with_button;
$this->button_text = $banner->button_text;
$this->button_link = $banner->button_link;
$backgroundPositions = BackgroundPosition::all();
$this->backgroundPositions = $backgroundPositions;
$pluckBackgroundPositions = array_map(function ($position) {
return $position['value'];
}, $backgroundPositions);
$this->pluckBackgroundPositions = implode(',', $pluckBackgroundPositions);
}
public function updatedName($value)
{
$this->alt = $value;
}
public function update()
{
$this->validate();
$service = new ImageService();
$data = [
'banner_type' => $this->type,
'name' => $this->name,
'alt' => $this->alt,
'references_url' => $this->reference_url,
'position' => $this->position,
'is_active' => $this->is_active ? 1 : 0,
'desktop_background_position' => $this->background_position ?: null,
'with_caption' => $this->with_caption ? 1 : 0,
'caption_title' => $this->caption_title,
'caption_text' => $this->caption_text,
'with_button' => $this->with_button ? 1 : 0,
'button_text' => $this->button_text,
'button_link' => $this->button_link,
];
if ($this->thumbnail) {
$path = explode('/', $this->oldThumbnail);
$shortPath = implode('/', array_slice($path, -2, 2));
$service->removeImage('images', $shortPath);
$data['desktop_media_path'] = url($service->storeImage($this->thumbnail, 1920, 100));
}
$this->banner->update($data);
return session()->flash('success', 'Banner berhasil diperbarui.');
}
public function render()
{
return view('marketing::livewire.banner.edit');
}
} |
package ru.yandex.practicum.filmorate.mapper;
import org.mapstruct.*;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import ru.yandex.practicum.filmorate.model.data.FilmEntity;
import ru.yandex.practicum.filmorate.model.presentation.rest_command.DirectorRestCommand;
import ru.yandex.practicum.filmorate.model.presentation.rest_view.DirectorRestView;
import ru.yandex.practicum.filmorate.model.service.Director;
import ru.yandex.practicum.filmorate.model.service.Film;
import ru.yandex.practicum.filmorate.model.service.Genre;
import ru.yandex.practicum.filmorate.model.service.RatingMpa;
import ru.yandex.practicum.filmorate.model.presentation.rest_command.FilmRestCommand;
import ru.yandex.practicum.filmorate.model.presentation.rest_command.GenreRestCommand;
import ru.yandex.practicum.filmorate.model.presentation.rest_command.RatingMpaRestCommand;
import ru.yandex.practicum.filmorate.model.presentation.rest_view.FilmRestView;
import ru.yandex.practicum.filmorate.model.presentation.rest_view.GenreRestView;
import ru.yandex.practicum.filmorate.model.presentation.rest_view.RatingMpaRestView;
@Mapper(componentModel = "spring")
public interface FilmMapper {
@Mapping(target = "mpa", source = "rating")
@Mapping(target = "genres", source = "genres",qualifiedByName = "mapGenreSetRestView")
@Mapping(target = "likes", source = "likes", qualifiedByName = "mapLikes")
@Mapping(target = "directors", source = "directors", qualifiedByName = "mapDirectorSetRestView")
FilmRestView toRestView(Film film);
@Mapping(target = "rating", source = "mpa")
@Mapping(target = "genres", source = "genres", qualifiedByName = "mapGenreSet")
@Mapping(target = "likes", source = "likes", qualifiedByName = "mapLikes")
@Mapping(target = "directors", source = "directors", qualifiedByName = "mapDirectorSet")
Film fromRestCommand(FilmRestCommand filmRestCommand);
@Mapping(target = "likes", expression = "java(new java.util.HashSet<>())")
@Mapping(target = "genres", expression = "java(new java.util.HashSet<>())")
@Mapping(target = "directors", expression = "java(new java.util.HashSet<>())")
Film fromDbEntity(FilmEntity filmEntity);
default RatingMpa intToRatingMpa(Integer id) {
return RatingMpa.getRatingById(id);
}
default RatingMpaRestView mapMpaRestView(RatingMpa rating) {
return new RatingMpaRestView(rating.getId(), rating.getName());
}
default RatingMpa mapRating(RatingMpaRestCommand rating) {
if (rating != null) {
return RatingMpa.getRatingById(rating.getId());
}
return RatingMpa.G;
}
@Named("mapGenreSetRestView")
default Set<GenreRestView> mapGenreSetRestView(Set<Genre> genreSet) {
Set<GenreRestView> filmGenres = new TreeSet<>(Comparator.comparingInt(GenreRestView::getId));
if (genreSet != null) {
filmGenres.addAll(genreSet.stream()
.map(genre -> new GenreRestView(genre.getId(), genre.getByRus()))
.collect(Collectors.toSet()));
return filmGenres;
}
return new HashSet<>();
}
@Named("mapDirectorSetRestView")
default Set<DirectorRestView> mapDirectorSetRestView(Set<Director> directorSet) {
Set<DirectorRestView> filmDirectors = new TreeSet<>(Comparator.comparingInt(DirectorRestView::getId));
if (directorSet != null) {
filmDirectors.addAll(directorSet.stream()
.map(director -> new DirectorRestView(director.getId(), director.getName()))
.collect(Collectors.toSet()));
return filmDirectors;
}
return new HashSet<>();
}
@Named("mapLikes")
default Set<Long> mapLikesSet(Set<Long> likesSet) {
if (likesSet != null) {
return new TreeSet<>(likesSet);
}
return new HashSet<>();
}
@Named("mapGenreSet")
default Set<Genre> mapGenreSet(Set<GenreRestCommand> genreRestCommandSet) {
if (genreRestCommandSet != null) {
return genreRestCommandSet.stream()
.map(genreRestCommand -> Genre.getGenreById(genreRestCommand.getId()))
.collect(Collectors.toSet());
}
return new HashSet<>();
}
@Named("mapDirectorSet")
default Set<Director> mapDirectorSet(Set<DirectorRestCommand> directorRestCommandSet) {
if (directorRestCommandSet != null) {
return directorRestCommandSet.stream()
.map(directorRestCommand ->
Director.builder().id(directorRestCommand.getId()).name("name").build())
.collect(Collectors.toSet());
}
return new HashSet<>();
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Data KasSiswa</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
</head>
<body style="background: lightgray">
<div class="container mt-5">
<div class="row">
<div class="col-md-12">
<div class="card border-0 shadow rounded">
<div class="card-body">
<a href="{{ route('pembayaran.create') }}" class="btn btn-md btn-success mb-3">Tambah Pembayaran</a>
<a href="{{ route('siswa.index') }}" class="btn btn-md btn-secondary mb-3">Siswa</a>
<table class="table table-bordered">
<tr>
<th scope="col">ID</th>
<th scope="col">Siswa</th>
<th scope="col">Kelas</th>
<th scope="col">Total Bayar</th>
<th scope="col">Terakhir Pembayaran</th>
<th scope="col">Aksi</th>
</tr>
</thead>
<tbody>
@forelse ($pembayaran as $index =>$pembayaran)
<tr>
<td>{{ $index + 1 }}</td>
<td>{{ $pembayaran->siswa->nama }}</td>
<td>{{ $pembayaran->siswa->kelas }}</td>
<td>{{ $pembayaran->total_bayar }}</td>
<td>{{ $pembayaran->tgl_bayar_last}}</td>
<td class="text-center">
<a href="{{ route('pembayaran.history', $pembayaran->siswa_id) }}" class="btn btn-sm btn-primary">History</a>
@csrf
@method('DELETE')
</form>
</td>
</tr>
@empty
<div class="alert alert-danger">
Data Post belum Tersedia.
</div>
@endforelse
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script>
//message with toastr
@if(session()->has('success'))
toastr.success('{{ session('success') }}', 'BERHASIL!');
@elseif(session()->has('error'))
toastr.error('{{ session('error') }}', 'GAGAL!');
@endif
</script>
</body>
</html> |
import dotenv from "dotenv";
import Product from "../models/product";
import { productSchema } from "../schemas/product";
import Category from "../models/category";
import { paginate } from "mongoose-paginate-v2";
dotenv.config();
export const getAll = async (req, res) => {
// const { _litmit = 10, _sort = "createAt", _order = "asc" } = req.query;
// const options = {
// customLabel: {
// docs: "data",
// litmit: _litmit,
// _sort: {
// [_sort]: _order === "desc" ? -1 : 1,
// },
// },
// };
try {
// const products = await Product.paginate({});
const products = await Product.find();
if (products.length === 0) {
return res.status(404).json({
message: "Không có sản phẩm nào",
});
}
return res.json({
message: "Lấy danh sách sản phẩm thành công",
products,
});
} catch (error) {
return res.status(400).json({
message: error.message,
});
}
// try {
// const products = await Product.find();
// return res.json({
// message: "Hiện thị danh sách sản phẩm thành công",
// products
// });
// } catch (error) {
// return res.status(400).json({
// message: error.message,
// });
// }
};
export const get = async (req, res) => {
try {
const product = await Product.findById(req.params.id).populate("categoryId");
if (!product) {
return res.json({
message: "Không tìm thấy sản phẩm",
});
}
return res.json({
message: "Lấy sản phẩm thành công",
product,
});
} catch (error) {
return res.status(400).json({
message: error.message
});
}
};
export const create = async (req, res) => {
try {
// validate
const { error } = productSchema.validate(req.body);
if (error) {
return res.status(400).json({
message: error.details[0].message,
});
}
const product = await Product.create(req.body);
await Category.findByIdAndUpdate(product.categoryId, {
$addToSet: { products: product._id },
});
if (!product) {
return res.json({
message: "Thêm sản phẩm không thành công",
});
}
return res.json({
message: "Thêm sản phẩm thành công",
product,
});
} catch (error) {
return res.status(400).json({
message: error.message,
});
}
};
export const update = async (req, res) => {
try {
const product = await Product.findOneAndUpdate({ _id: req.params.id }, req.body, {
new: true,
});
if (!product) {
return res.json({
message: "Cập nhật sản phẩm không thành công",
});
}
return res.json({
message: "Cập nhật sản phẩm thành công",
product,
});
} catch (error) {
return res.status(400).json({
message: error.message,
});
}
};
export const remove = async (req, res) => {
try {
const product = await Product.findByIdAndDelete(req.params.id);
return res.json({
message: "Xóa sản phẩm thành công",
product,
});
} catch (error) {
return res.status(400).json({
message: error.message,
});
}
}; |
import React, { Fragment, useState } from "react";
import { Transition, Dialog } from "@headlessui/react";
import AdminTable from '../../components/table/AdminTable'
export default function Employee() {
const [isOpen, setIsOpen] = useState(false);
function closeModal() {
setIsOpen(false);
}
function openModal() {
setIsOpen(true);
}
const reset = (e) => {
e.preventDefault();
setIsOpen(false);
};
return (
<div className='h-full w-full bg-gray-200'>
<div className='px-12 pt-8'>
<h1 className='font-bold text-2xl'>Administration</h1>
</div>
<div className=' bg-white mx-4 my-4 shadow-sm w-9/10 h-5/6 border rounded-xl border-gray-100'>
<div className='flex border-b p-3 border-gray-100 justify-between'>
<h1 className='font-semibold'>Organization</h1>
<button
onClick={openModal}
className='rounded bg-red-700 text-white text-xs px-4 py-2 font-semibold'>
Edit Employee
</button>
<Transition appear show={isOpen} as={Fragment}>
<Dialog
as='div'
className='fixed inset-0 z-10 overflow-y-auto'
onClose={closeModal}>
<div className='min-h-screen px-4 text-center'>
<Transition.Child
as={Fragment}
enter='ease-out duration-300'
enterFrom='opacity-0 scale-95'
enterTo='opacity-100 scale-100'
leave='ease-in duration-200'
leaveFrom='opacity-100 scale-100'
leaveTo='opacity-0 scale-95'>
<div className='inline-block w-full max-w-md p-6 my-8 overflow-hidden text-left align-middle transition-all transform bg-white shadow-xl rounded'>
<Dialog.Title
as='h3'
className='text-lg font-md leading-6 text-gray-900'>
Edit Employee
</Dialog.Title>
<div className='flex max-w-md max-auto'>
<div className='py-2'>
<div className='h-14 my-4'>
<label className='block text-gray-600 text-sm font-normal'>
Name
</label>
<input
type='text'
name='name'
// value={project.projectName}
onChange={(e) => handleChange(e)}
className='h-10 w-96 border mt-2 px-2 py-2'></input>
</div>
<div className='h-14 my-4'>
<label className='block text-gray-600 text-sm font-normal'>
Phone Number
</label>
<input
type='text'
name='phoneNumber'
// value={project.description}
onChange={(e) => handleChange(e)}
className='h-10 w-96 border mt-2 px-2 py-2'></input>
</div>
<div className='h-14 my-4'>
<label className='block text-gray-600 text-sm font-normal'>
Email
</label>
<input
type='text'
name='email'
// value={project.employees}
onChange={(e) => handleChange(e)}
className='h-10 w-96 border mt-2 px-2 py-2'></input>
</div>
<div className='h-14 my-4'>
<label className='block text-gray-600 text-sm font-normal'>
Role
</label>
<input
type='select'
name='role'
// value={project.employees}
onChange={(e) => handleChange(e)}
className='h-10 w-96 border mt-2 px-2 py-2'></input>
</div>
<div className='h-14 my-4 space-x-4 pt-4'>
<button
// onClick={saveProject}
className='rounded text-white font-semibold bg-green-600 hover:bg-green-800 py-2 px-6'>
SUBMIT
</button>
<button
onClick={reset}
className='rounded text-white font-semibold bg-red-600 hover:bg-red-800 py-2 px-6'>
Close
</button>
</div>
</div>
</div>
</div>
</Transition.Child>
</div>
</Dialog>
</Transition>
</div>
<div>
<AdminTable />
</div>
</div>
</div>
);
} |
import torch
from torch import Tensor
from abc import ABC, abstractmethod
from typing import Tuple
class BaseSystem(ABC):
@abstractmethod
def apply_control(self, control_output: Tensor, distrubance: Tensor) -> None:
"""
Update the position and velocity of the object
Args:
control_output (float): control output applied to the object
distrubance (float): distrubance applied to the object
Returns:
None
"""
pass
@abstractmethod
def get_position(self) -> Tensor:
"""
Get the position of the object
Args:
None
Returns:
float: position of the object
"""
pass
class Trolley(BaseSystem):
def __init__(self, mass: Tensor, friction: Tensor, dt: Tensor) -> None:
"""
Initialize the trolley
Args:
mass (float): mass of the trolley
friction (float): friction coefficient of the trolley
dt (float): time step between the current and previous position
Returns:
None
"""
self.mass: Tensor = torch.tensor(mass)
self.friction: Tensor = torch.tensor(friction)
self.spring_constant: Tensor = torch.tensor(50.)
self.dt: Tensor = torch.tensor(dt)
self.position: Tensor = torch.tensor(0.)
self.delta_position: Tensor = torch.tensor(0.)
self.velocity: Tensor = torch.tensor(0.)
self.F: Tensor = torch.tensor(50.)
def apply_control(self, control_output: Tensor, distrubance: Tensor = torch.tensor(0.)) -> None:
"""
Update the position and velocity of the trolley based on the control output
Args:
TODO: select best unit for the demonstration
Returns:
None
Equation of model:
F = ma
a = F/m
a = F/m - friction*v/m
v = v + a*dt
x = x + v*dt
"""
F = control_output
acceleration = F / self.mass - self.friction * self.velocity / self.mass - self.spring_constant * self.delta_position / self.mass
self.velocity += acceleration * self.dt
position = self.position + self.velocity * self.dt
self.delta_position = position - self.position
self.position = position
def get_position(self) -> Tensor:
"""
Get the position of the trolley
Args:
None
Returns:
float: position of the trolley
"""
return self.position
def get_U(self) -> Tuple[Tensor, Tensor, Tensor]:
return self.position, self.position/self.dt, self.position/(self.dt**2)
def reset(self) -> None:
"""
Reset the position and velocity of the trolley
Args:
None
Returns:
None
"""
self.position = torch.tensor(0, dtype=torch.float32)
self.velocity = torch.tensor(0, dtype=torch.float32)
self.delta_position = torch.tensor(0, dtype=torch.float32)
class ContinuousTankHeating(BaseSystem):
def __init__(self, dt: Tensor) -> None:
self.dt: Tensor = dt
self.Tf: Tensor = torch.tensor(300.)
self.T: Tensor = torch.tensor(300.)
self.epsilon: Tensor = torch.tensor(1.)
self.tau: Tensor = torch.tensor(4.)
self.Q: Tensor = torch.tensor(2.)
# TODO: fix the equation of the model
def update(self, control_output: Tensor, distrubance: Tensor = torch.tensor(0.)) -> None:
"""
Update the position and velocity of the trolley
Equation of model:
dTdt = 1/(1+epsilon) * [1/tau * (Tf - T) + Q * (Tq - T)]
Vars:
Tq: target temperature
Tf: temperature of the incoming fluid
T: current temperature
tau: residence time
epsilon: ratio of the heat capacity of the tank to the heat capacity of the fluid
"""
Tq = control_output
dTdt = 1/(1 + self.epsilon) * (1/self.tau * (self.Tf - self.T) + self.Q * (Tq - self.T))
self.T += dTdt * self.dt
def get_position(self) -> Tensor:
return self.T |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Use different fonts</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Jacquard+12&display=swap" rel="stylesheet">
<link rel="stylesheet" href="fonts/static/stylesheet.css">
<style>
p {
font-size: 2rem;
}
.jacquard-12-regular {
font-family: "Jacquard 12", system-ui;
font-weight: 400;
font-style: normal;
}
</style>
</head>
<body>
<main>
<h1>Use different fonts</h1>
<section>
<h2>Use system fonts</h2>
<div class="system_fonts" style="font-family: 'Bahnschrift', Comic Sans MS, sans-serif;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Libero cum obcaecati explicabo! Praesentium
quasi enim porro ad consequuntur numquam reiciendis ipsam blanditiis sed neque autem tempore tenetur
dolor, reprehenderit libero.</p>
</div>
</section>
<section>
<h2>Use remote fonts</h2>
<div class="remote_fonts" style="font: 1.2em/2 'Jacquard 12', sans-serif;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Libero cum obcaecati explicabo! Praesentium
quasi enim porro ad consequuntur numquam reiciendis ipsam blanditiis sed neque autem tempore tenetur
dolor, reprehenderit libero.</p>
</div>
</section>
<section>
<h2>Use local fonts</h2>
<div class="local_fonts" style="font: 0.9em/0.9 'DM Sans';">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Libero cum obcaecati explicabo! Praesentium
quasi enim porro ad consequuntur numquam reiciendis ipsam blanditiis sed neque autem tempore tenetur
dolor, reprehenderit libero.</p>
</div>
</section>
<section>
<h2>Use fonts with unexpected language</h2>
<div class="local_fonts" style="font: 0.9em/0.9 'DM Sans';">
<p>Lorem <span style="color: red">(ХОПАНЬКИ нежданчик!!)</span> ipsum dolor sit amet, consectetur
adipisicing elit. Libero cum obcaecati explicabo! Praesentium quasi enim porro ad consequuntur
numquam reiciendis ipsam blanditiis sed neque autem tempore tenetur dolor, reprehenderit libero.</p>
</div>
</section>
</main>
</body>
</html> |
# 🚀 C++ Programlama Dili Dersi 🚀
<p align="center">
<img src="https://github.com/YusufsKaygusuz/Deneyap_Software_Techn/assets/86704802/cd98b111-b66c-4ddb-b0c4-f62ce0ab8b46" alt="ReLU" width="150"/>
<img src="https://github.com/YusufsKaygusuz/Deneyap_Software_Techn/assets/86704802/7bfa61ee-d340-41b9-8855-dec4c561744f" alt="ReLU" width="200"/>
<img src="https://github.com/YusufsKaygusuz/Deneyap_Software_Techn/assets/86704802/a4e54abd-9ff4-4d8f-b784-bd0653e9b8f3" alt="ReLU" width="150"/>
<img src="https://github.com/YusufsKaygusuz/Deneyap_Software_Techn/assets/86704802/a90a23b8-0c21-40ee-9617-b17d2858b100" alt="ReLU" width="150"/>
<img src="https://github.com/YusufsKaygusuz/Deneyap_Software_Techn/assets/86704802/705deb43-4977-46c8-8d32-b0c34b4b7b66" alt="ReLU" width="150"/>
</p>
## 📚 İçindekiler
| Hafta | Haftalık İçerik |
|-------|--------------------------------------------|
| 📆 Week 3 | [**Değişken ve Veri Tiplerini Tanıyalım**](#week-3-değişken-ve-veri-tiplerini-tanıyalım) |
| 📆 Week 4 | [**Karar Verme Yapılarına Giriş If-Else if-else**](#week-4-karar-verme-yapılarına-giriş-if-else-if-else) |
| 📆 Week 5 | [**Döngülere Giriş For Döngüsü & Switch-case**](#week-5-döngülere-giriş-for-döngüsü--switch-case) |
| 📆 Week 6 | [**Diziler Konusuyla İlgili Örnek Kodlar**](#week-6-diziler-konusuna-ait-örnek-kodlar) |
| 📆 Week 7 | [**Fonksiyonlara Giriş ve Örnekler**](#week-7-fonksiyonlara-giriş-ve-örnekler) |
| 📆 Week 8 | [**Fonksiyon Pratiği ve Sınıflara (Class) Giriş**](#week-8-fonksiyon-pratiği-ve-sınıflara-class-giriş) |
| 📆 Week 9 | [**Sınıflarda (Class) Yapıcı ve Yıkıcı Metodlar**](#week-9-sınıflarda-class-yapıcı-ve-yıkıcı-metodlar) |
## Week 3: Değişken ve Veri Tiplerini Tanıyalım
Bu hafta, C++ programlama dilindeki temel yapı taşlarından olan değişkenleri ve veri tiplerini tanıyacağız. Değişkenler, program içinde bilgi saklama ve işleme yeteneği kazandırır. Ayrıca, temel veri tipleri (int, float, char, vs.) üzerinde çalışarak programlama temellerini oluşturacağız.
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
// int: Tam sayı
int tamSayi = 42;
// float: Ondalıklı sayı (tek hassasiyet)
float ondalikliSayi = 3.14f;
// double: Ondalıklı sayı (çift hassasiyet)
double ciftHassasiyetliSayi = 2.71828;
// string: Metin dizisi
string metin = "Merhaba, dünya!";
// bool: Mantıksal değer (true/false)
bool dogruMu = true;
// char: Tek karakter
char karakter = 'A';
// Değişken değerlerini ekrana yazdırma
cout << "Tam Sayı: " << tamSayi << endl;
cout << "Ondalıklı Sayı: " << ondalikliSayi << endl;
cout << "Çift Hassasiyetli Sayı: " << ciftHassasiyetliSayi << endl;
cout << "Metin: " << metin << endl;
cout << "Mantıksal Değer: " << (dogruMu ? "true" : "false") << endl;
cout << "Karakter: " << karakter << endl;
return 0;
}
```
## Week 4: Karar Verme Yapılarına Giriş If-Else if-else
Koşullu ifadelerle çalışmaya başlayacağımız bu hafta, if-else if-else gibi yapıları kullanarak programlara karar verme yeteneği kazandıracağız. Bu yapılar, programlarımızı çeşitli durumlara göre yönlendirmemizi sağlar.
```cpp
#include <iostream>
using namespace std;
int main() {
// Kullanıcıdan bir sayı girişi istenir
cout << "Bir sayı giriniz: ";
int sayi;
cin >> sayi;
// if-else if-else yapısı kullanılarak karar verme
if (sayi > 0) {
cout << "Girilen sayı pozitif." << endl;
} else if (sayi < 0) {
cout << "Girilen sayı negatif." << endl;
} else {
cout << "Girilen sayı sıfır." << endl;
}
return 0;
}
```
## Week 5: Döngülere Giriş For Döngüsü & Switch-case
Bu hafta, döngülerin temelini oluşturan for döngüsü ile programlarımızı tekrarlı işlemlere yönlendirmeyi öğreneceğiz. Ayrıca, switch-case yapısı ile farklı durumları ele alarak programlarımızı daha esnek hale getireceğiz.
```cpp
#include <iostream>
using namespace std; // std isim alanını kullan
int main() {
// for döngüsü ile sayıları ekrana yazdırma
cout << "For Döngüsü İle Sayıları Yazdırma:" << endl;
for (int i = 1; i <= 5; ++i) {
cout << i << " ";
}
cout << endl;
// Kullanıcının seçtiği sayıya göre switch-case yapısı
cout << "Bir sayı giriniz (1-3 arasında): ";
int kullaniciSecimi;
cin >> kullaniciSecimi;
switch (kullaniciSecimi) {
case 1:
cout << "Birinci durum seçildi." << endl;
break;
case 2:
cout << "İkinci durum seçildi." << endl;
break;
case 3:
cout << "Üçüncü durum seçildi." << endl;
break;
default:
cout << "Geçersiz giriş. 1-3 arasında bir sayı giriniz." << endl;
}
return 0;
}
```
## Week 6: Diziler Konusuna Ait Örnek Kodlar
Diziler, benzer tipteki verileri tek bir değişken altında saklamamıza olanak tanıyan önemli bir konsepttir. Bu hafta, dizilerin tanımlanması, elemanlara erişim ve dizilerle ilgili temel işlemleri içeren örnek kodlarla pratik yapacağız.
<h3>Dizi Tanımlama ve Elemanlara Erişim</h3>
```cpp
#include <iostream>
using namespace std;
int main() {
// Dizi tanımlama
int sayilar[5] = {1, 2, 3, 4, 5};
// Dizi elemanlarına erişim
for (int i = 0; i < 5; ++i) {
cout << "sayilar[" << i << "] = " << sayilar[i] << endl;
}
return 0;
}
```
<h3>Dizi Boyutu ve Ortalama Hesaplama</h3>
```cpp
#include <iostream>
using namespace std;
int main() {
// Dizi tanımlama
double notlar[] = {75.5, 80.0, 90.5, 85.0, 88.5};
// Dizi boyutunu ogrenme
int dizininBoyutu = sizeof(notlar) / sizeof(notlar[0]);
// Dizi elemanlarına erişim ve toplam hesaplama
double toplam = 0.0;
for (int i = 0; i < dizininBoyutu; ++i) {
cout << "notlar[" << i << "] = " << notlar[i] << endl;
toplam += notlar[i];
}
// Ortalama hesaplama ve ekrana yazdırma
double ortalama = toplam / dizininBoyutu;
cout << "Not Ortalaması: " << ortalama << endl;
return 0;
}
```
## Week 7: Fonksiyonlara Giriş ve Örnekler
Fonksiyonlar, kodunuzu modüler hale getirmenizi sağlayan ve belirli görevleri yerine getiren bloklardır. Bu hafta, fonksiyonların tanımlanması, çağrılması ve örneklerle pratiği üzerinde duracağız. Fonksiyonlar, kodun okunabilirliğini artırır ve tekrar kullanılabilirlik sağlar.
<h3>Temel Fonksiyon Tanımlama ve Çağrılma</h3>
```cpp
#include <iostream>
using namespace std;
// Fonksiyon tanımı
void selamla() {
cout << "Merhaba! Bu bir fonksiyon." << endl;
}
int main() {
// Fonksiyon çağrısı
selamla();
return 0;
}
```
<h3>Parametreli Fonksiyon ve Çağrılma</h3>
```cpp
#include <iostream>
using namespace std;
// Parametreli fonksiyon tanımı
void kareAlVeYazdir(int sayi) {
int kare = sayi * sayi;
cout << sayi << " sayısının karesi: " << kare << endl;
}
int main() {
// Parametreli fonksiyon çağrısı
kareAlVeYazdir(5);
kareAlVeYazdir(8);
return 0;
}
```
<h3>Fonksiyonlardan Değer Döndürme</h3>
```cpp
#include <iostream>
using namespace std;
// Fonksiyon tanımı
int topla(int x, int y) {
return x + y;
}
int main() {
// Fonksiyon çağrısı ve değeri kullanma
int sonuc = topla(3, 4);
cout << "Toplam: " << sonuc << endl;
return 0;
}
```
## Week 8: Fonksiyon Pratiği ve Sınıflara (Class) Giriş
Bu hafta, fonksiyonları daha derinlemesine anlamlandırarak pratiğini yapacak ve C++ dilindeki sınıflara (class) giriş yapacağız. Sınıflar, nesne yönelimli programlamanın temelini oluşturur ve veri yapısını daha organize bir şekilde yönetmemizi sağlar.
<h3></h3>
```cpp
#include <iostream>
using namespace std;
// MatematikIslemleri adlı sınıfın tanımlanması
class MatematikIslemleri {
public:
// Sınıf içindeki fonksiyonlar (üye fonksiyonlar)
int topla(int x, int y) {
return x + y;
}
int carp(int x, int y) {
return x * y;
}
double bol(double x, double y) {
// y değeri 0'dan farklı mı kontrolü. Eğer sıfır değilse bölme işlemi gerçekleşmeli.
if (y != 0.0) {
return x / y;
}
// y değeri 0'a eşitse (Bir sayının sıfıra bölünmesi sonucunda) tanımsızlık ortaya çıkar ve hata oluşur.
else {
cerr << "Hata: Sıfıra bölme!" << endl;
return 0.0;
}
}
};
int main() {
// MatematikIslemleri sınıfından bir nesne oluşturulması
MatematikIslemleri hesapMakinesi;
// Sınıfın fonksiyonlarını kullanma
int toplamSonucu = hesapMakinesi.topla(5, 3);
cout << "Toplam: " << toplamSonucu << endl;
int carpimSonucu = hesapMakinesi.carp(4, 6);
cout << "Çarpım: " << carpimSonucu << endl;
double bolumSonucu = hesapMakinesi.bol(9.0, 3.0);
std::cout << "Bölüm: " << bolumSonucu << endl;
return 0;
}
```
## Week 9: Sınıflarda (Class) Yapıcı ve Yıkıcı Metodlar
C++ dilinde constructor (kurucu fonksiyon) bir nesnenin oluşturulduğu anı temsil eden özel bir fonksiyondur. Bir sınıf tanımlandığında, bu sınıfa ait bir constructor tanımlanabilir ve bir nesne oluşturulduğunda otomatik olarak çağrılır. Constructor, sınıfın üye değişkenlerini başlatmak ve diğer başlangıç işlemlerini gerçekleştirmek için kullanılır.
Deconstructor (yıkıcı fonksiyon) ise bir nesne yok edildiğinde çağrılan bir özel fonksiyondur. Sınıfın ömrü sona erdiğinde, deconstructor bellek yönetimi ve diğer temizlik işlemlerini gerçekleştirmek için kullanılır. Deconstructor, sınıfın bellek ve kaynak yönetimini düzgün bir şekilde tamamlamasına yardımcı olur.
Örnek kullanım:
```cpp
#include <iostream>
class MyClass {
public:
// Constructor
MyClass() {
std::cout << "Constructor çağrıldı!" << std::endl;
}
// Deconstructor
~MyClass() {
std::cout << "Deconstructor çağrıldı!" << std::endl;
}
};
int main() {
// Nesne oluşturulduğunda constructor çağrılır
MyClass myObject;
// Program sona erdiğinde deconstructor çağrılır
return 0;
}
``` |
import Map from '../../../../../src/ol/Map.js';
import View from '../../../../../src/ol/View.js';
import ZoomToExtent from '../../../../../src/ol/control/ZoomToExtent.js';
import {
clearUserProjection,
useGeographic,
} from '../../../../../src/ol/proj.js';
describe('ol.control.ZoomToExtent', function () {
describe('constructor', function () {
it('can be constructed without arguments', function () {
const instance = new ZoomToExtent();
expect(instance).to.be.an(ZoomToExtent);
});
});
describe('#handleZoomToExtent', function () {
let map;
beforeEach(function () {
const target = document.createElement('div');
target.style.width = '256px';
target.style.height = '256px';
document.body.appendChild(target);
map = new Map({
target: target,
view: new View({
center: [0, 0],
zoom: 0,
}),
});
});
afterEach(function () {
document.body.removeChild(map.getTargetElement());
map.setTarget(null);
clearUserProjection();
});
it('it handles view coordinates', function () {
const control = new ZoomToExtent({extent: [10, 48, 12, 50]});
map.addControl(control);
control.handleZoomToExtent();
map.renderSync();
const extent = map.getView().calculateExtent();
expect(extent[0]).to.roughlyEqual(10, 1e-10);
expect(extent[1]).to.roughlyEqual(48, 1e-10);
expect(extent[2]).to.roughlyEqual(12, 1e-10);
expect(extent[3]).to.roughlyEqual(50, 1e-10);
});
it('it handles user coordinates', function () {
useGeographic();
const control = new ZoomToExtent({extent: [10, 48, 12, 50]});
map.addControl(control);
control.handleZoomToExtent();
map.renderSync();
const extent = map.getView().calculateExtent();
expect(extent[0]).to.roughlyEqual(9.4754646122, 1e-10);
expect(extent[1]).to.roughlyEqual(48, 1e-10);
expect(extent[2]).to.roughlyEqual(12.5245353878, 1e-10);
expect(extent[3]).to.roughlyEqual(50, 1e-10);
});
it('it handles projection extent', function () {
useGeographic();
const control = new ZoomToExtent();
map.addControl(control);
control.handleZoomToExtent();
map.renderSync();
const extent = map.getView().calculateExtent();
expect(extent[0]).to.roughlyEqual(-180, 1e-10);
expect(extent[1]).to.roughlyEqual(-85.0511287798, 1e-10);
expect(extent[2]).to.roughlyEqual(180, 1e-10);
expect(extent[3]).to.roughlyEqual(85.0511287798, 1e-10);
});
});
}); |
package com.example.skiply.service;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.example.skiply.entity.Receipt;
import com.example.skiply.entity.Student;
import com.example.skiply.exceptions.SkiplyException;
import com.example.skiply.repository.ReceiptRepository;
import com.example.skiply.repository.StudentRepository;
@Service
public class FeeService {
@Autowired
private ReceiptRepository receiptRepository;
@Autowired
private StudentRepository studentRepository;
public ResponseEntity<?> collect(Receipt receipt) throws SkiplyException {
try {
Optional<Student> optionalStudent = studentRepository.findById(receipt.getStudentId());
if(optionalStudent.isPresent()) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd MMMM yyyy, hh:mm");
LocalDateTime localDate = LocalDateTime.now();
String currentDateTime = dtf.format(localDate);
receipt.setDateTime(currentDateTime);
receipt = receiptRepository.save(receipt);
}
Student student = updateStudent(optionalStudent.get(), receipt);
return new ResponseEntity<Student>(student, HttpStatus.OK);
}catch(Exception e) {
throw new SkiplyException(e.getMessage());
}
}
/**
* To add receipt for student who paid fee
*
* @param student
* @param receipt
* @return
*/
private Student updateStudent(Student student, Receipt receipt) {
student.setReceipt(receipt);
student = studentRepository.save(student);
return student;
}
} |
'use client';
import { ReactNode } from 'react';
export interface SocialLinkProps {
href: string;
children: ReactNode;
className?: string;
colorType?: string;
}
export default function SocialLink({
href,
children,
className = '',
colorType = 'black',
}: SocialLinkProps) {
return (
<a
rel="noopener noreferrer"
href={href}
className={`px-[5px] min-w-12 xl:min-w-20 min-h-12 xl:min-h-20 inline-flex items-center justify-center rounded-lg backdrop-blur-md common-transition
${
colorType === 'black'
? 'black-style bg-black-light-10'
: 'white-style bg-white-light-10'
}
${className}`}
>
{children}
</a>
);
} |
class Solution {
public String removeDuplicateLetters(String s) {
//algo
//1.count--
//2.exist
//3.check big or not -if true remove and mark false;
//4.push and make false
Stack<Character>st=new Stack<>();
boolean []exists=new boolean[26];
int[]freq=new int[26];
//filling frequencies
for(int i=0;i<s.length();i++)
{
char ch=s.charAt(i);
freq[ch-'a']++;
}
for(int i=0;i<s.length();i++)
{
char ch=s.charAt(i);
//step 1
freq[ch-'a']--;
//step 2
if(exists[ch-'a']==true)
{
continue;
}
//step 3
while(st.size()>0 && st.peek()>ch && freq[st.peek()-'a']>0)
{
char remove=st.pop();
exists[remove-'a']=false;
}
//step 4:
//push and mark true;
st.push(ch);
exists[ch-'a']=true;
}
//put all stack elements to string
StringBuilder sb=new StringBuilder();
while(st.size()>0)
{
sb.append(st.pop());
}
sb.reverse();
return sb.toString();
}
} |
/*
* Introducing useCallback and useEffect hooks
*/
import { useCallback, useEffect, useRef, useState } from 'react';
function App() {
const [length, setLength] = useState(8);
const [numberAllowed, setNumberAllowed] = useState(false);
const [characterAllowed, setCharacterAllowed] = useState(false);
const [password, setPassword] = useState("");
const passwordRef = useRef(null);
/*
* Function for generate random password
*
*
* Here we are giving dependencies to optimize the function and avoid unnecessary re-renders.
*
* useCallback is about memoizing a function, while useEffect is about running side effects after
* rendering and when dependencies change.
*
* Here dependencies used to optimize method and avoid unnecessary re-renders.
*/
const passwordGenerator = useCallback(() => {
let pass = "";
let str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
if (numberAllowed) str += "0123456789";
if (characterAllowed) str += "!@#$%^&*_-+={}[]~`";
for (let i = 1; i <= length; i++) {
let char = Math.floor(Math.random() * str.length + 1);
pass += str.charAt(char);
}
setPassword(pass);
}, [length, numberAllowed, characterAllowed, setPassword]);
const copyPasswordToClipboard = useCallback(() => {
passwordRef.current?.select();
passwordRef.current?.setSelectionRange(0, 999);
window.navigator.clipboard.writeText(password);
}, [password]);
useEffect(() => {
passwordGenerator();
}, [length, numberAllowed, characterAllowed, passwordGenerator]);
return (
<div className="w-full h-screen bg-black">
<div className='flex flex-col gap-3 justify-center items-center py-10 text-orange-500'>
<h1 className="text-4xl text-center text-white">Password Generator</h1>
<div className="flex flex-col w-2/6 min-w-80 bg-gray-500 gap-4 py-6 my-4 px-6 items-center rounded-lg">
<div id="generate-copy-password" className="w-full max-w-sm">
<div className="flex items-center">
<button
onClick={passwordGenerator}
className="flex-shrink-0 z-10 inline-flex items-center py-2.5 px-2 text-sm font-medium text-center text-white bg-blue-700 dark:bg-blue-600 border dark:hover:bg-blue-700 rounded-s-lg border-blue-700 dark:border-blue-600 hover:border-blue-700 dark:hover:border-blue-700 focus:ring-1 focus:outline-none focus:ring-blue-300 dark:focus:ring-blue-800 hover:bg-blue-200">
Generate
</button>
<div className="relative w-full">
<input id="password-generator"
type="text"
className="bg-gray-50 text-sm block w-full p-2.5 text-orange-500 outline-none"
value={password}
readOnly
ref={passwordRef}
/>
</div>
<button onClick={copyPasswordToClipboard} className="flex-shrink-0 z-10 inline-flex items-center py-3 px-4 text-sm font-medium text-center text-gray-500 dark:text-gray-400 hover:text-gray-900 bg-gray-100 border border-gray-300 rounded-e-lg hover:bg-gray-200 focus:ring-1 focus:outline-none focus:ring-gray-100 dark:bg-gray-700 dark:hover:bg-gray-600 dark:focus:ring-gray-700 dark:hover:text-white dark:border-gray-600" type="button">
<span id="default-icon">
<svg className="w-4 h-4" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 18 20">
<path d="M16 1h-3.278A1.992 1.992 0 0 0 11 0H7a1.993 1.993 0 0 0-1.722 1H2a2 2 0 0 0-2 2v15a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2Zm-3 14H5a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2Zm0-4H5a1 1 0 0 1 0-2h8a1 1 0 1 1 0 2Zm0-5H5a1 1 0 0 1 0-2h2V2h4v2h2a1 1 0 1 1 0 2Z" />
</svg>
</span>
</button>
</div>
</div>
<div className='flex text-sm gap-x-2'>
<div className='flex items-center gap-x-1'>
<input
type="range"
min={6}
max={50}
value={length}
className='cursor-pointer'
onChange={(e) => { setLength(e.target.value) }}
/>
<label>Length: {length}</label>
</div>
<div className="flex items-center gap-x-1">
<input
type="checkbox"
defaultChecked={numberAllowed}
id="numberInput"
onChange={() => {
setNumberAllowed((prev) => !prev);
}}
/>
<label htmlFor="numberInput">Numbers</label>
</div>
<div className="flex items-center gap-x-1">
<input
type="checkbox"
defaultChecked={characterAllowed}
id="characterInput"
onChange={() => {
setCharacterAllowed((prev) => !prev)
}}
/>
<label htmlFor="characterInput">Characters</label>
</div>
</div>
</div>
</div>
</div >
)
}
export default App |
<script lang="ts">
import { Button } from 'flowbite-svelte';
import { goto } from '$app/navigation';
import { TrashBinOutline } from 'flowbite-svelte-icons';
import { enhance } from '$app/forms';
import type { Employee } from '$lib/types';
import EmployeeForm from '$components/EmployeeForm.svelte';
import type { ActionFailure } from '@sveltejs/kit';
import type { ActionsSuccess } from './$types';
import Message from '$components/Message.svelte';
export let data: Employee | undefined;
export let form: ActionFailure<{ error: string }>['data'] | ActionsSuccess<Record<string, any>>;
$: message = form?.error || form?.success;
</script>
<EmployeeForm
id="form-update"
action="?/update"
enhanceCallback={() => {
return async ({ update }) => {
await update({ reset: false });
};
}}
{data}
/>
<form
id="form-delete"
method="POST"
action="?/delete"
use:enhance={() => {
return async ({ result, update }) => {
await update();
if (result.type === 'success') {
goto('/', { replaceState: true })
}
};
}}
>
<input type="hidden" name="id" value={data?._id} />
</form>
<Message {message} />
<div class="flex justify-between">
<Button type="submit" form="form-update">Save</Button>
<Button outline={true} type="submit" form="form-delete" color="red">
<TrashBinOutline size="xs" class="mr-1" />
Delete
</Button>
</div> |
<div>
{{-- Creamos nuevo archivo css buttons.css para crearle la apariencia de botón a nuesto icono de font awesome. Y recuerda importarlo despues en app.css --}}
<a class="btn btn-green" wire:click="$set('open',true)">
<i class="fas fa-edit"></i>
</a>
{{-- Ahora creamos un modal para cuando le demos click se nos abra, para eso utilizaremos el componente de jetstream dialog-modal y dentro necesita 3 slots title content y footer --}}
<x-jet-dialog-modal wire:model="open">
<x-slot name="title">
Editar el post
</x-slot>
<x-slot name="content">
<div wire:loading wire:target="image"
class="mb-4 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
<strong class="font-bold">Imagen cargando!</strong>
<span class="block sm:inline">Espere un momento hasta que la imagen se procese.</span>
</div>
@if ($image)
{{-- Vamos a mostrar la imagen antes de guardarla aquí --}}
<img class="mb-4" src="{{ $image->temporaryUrl() }}">
@else
<img class="mb-4" src="{{ Storage::url($post->image) }}">
@endif
<div class="mb-4">
<x-jet-label value="Título del post" />
<x-jet-input type="text" wire:model="post.title" class="w-full" />
</div>
<div class="mb-4">
<x-jet-label value="Contenido del post" />
<textarea wire:model="post.content" rows="6" class="w-full form-control"></textarea>
</div>
<div class="mb-4">
{{-- Creamos un imput file para guardar las imagenes
Y jugamos con los cambios de id para borrar el contenido del imput file --}}
<input type="file" wire:model="image" id={{ $identificador }} />
<x-jet-input-error for="image"></x-jet-input-error>
</div>
</x-slot>
<x-slot name="footer">
<x-jet-secondary-button class="mr-4" wire:click="$set('open',false)">
Cancelar
</x-jet-secondary-button>
<x-jet-danger-button wire:click="save" wire:loading.attr="disabled" wire:target="save, image"
class="disabled:opacity-25">
Actualizar post
</x-jet-danger-button>
</x-slot>
</x-jet-dialog-modal>
</div> |
require 'test_helper'
class ActivityLogsControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get "/activity_logs?user_id=#{peter_user.id}", headers: jwt_header, as: :json
assert_response :success
get "/activity_logs?schema_name=SCHEMA", headers: jwt_header, as: :json
assert_response :success
get "/activity_logs?schema_name=SCHEMA&table_name=TABLE", headers: jwt_header, as: :json
assert_response :success
get "/activity_logs?schema_name=SCHEMA&table_name=TABLE&column_name=COLUMN", headers: jwt_header, as: :json
assert_response :success
get "/activity_logs", headers: jwt_header, as: :json
assert_response :internal_server_error, log_on_failure('At least one parameter')
end
test "should create activity_log" do
ActivityLogsController::ALLOWED_LEVELS.each do |level|
assert_difference('ActivityLog.count') do
post activity_logs_url, headers: jwt_header, params: { activity_log: { level: level, user_id: peter_user.id, schema_name: 'Schema1', table_name: 'Table1', column_name: 'Column1', action: 'Something happened' } }, as: :json
end
assert_response 201
end
post activity_logs_url, headers: jwt_header, params: { activity_log: { level: 'hugo', user_id: peter_user.id, schema_name: 'Schema1', table_name: 'Table1', column_name: 'Column1', action: 'Something happened' } }, as: :json
assert_response :internal_server_error
end
end |
package org.restassured.javafaker;
import org.restassured.requestbodylearning.Products_Pojo;
import com.github.javafaker.Faker;
/**
*
* @author Ritesh Mansukhani
* In this Program we Generate Products_Pojo Instance utilizing Java Faker to Set
* Variable values of Products_Pojo
*
*/
public class DummyProductDataGenerator {
public static Products_Pojo generateData() {
Faker dummy = new Faker();
Products_Pojo data = new Products_Pojo();
data.setTitle(dummy.book().title());
data.setPrice(dummy.number().randomDigit());
data.setBrand(dummy.book().author());
data.setCategory(dummy.book().genre());
data.setStock(dummy.number().randomDigit());
return data;
}
} |
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/01/DMux8Way.hdl
/**
* 8-way demultiplexor:
* {a, b, c, d, e, f, g, h} = {in, 0, 0, 0, 0, 0, 0, 0} if sel == 000
* {0, in, 0, 0, 0, 0, 0, 0} if sel == 001
* etc.
* {0, 0, 0, 0, 0, 0, 0, in} if sel == 111
*/
CHIP DMux8Way {
IN in, sel[3];
OUT a, b, c, d, e, f, g, h;
PARTS:
// Put your code here:
Not(in=sel[0], out=nsel0);
Not(in=sel[2], out=nsel2);
Not(in=sel[1], out=nsel1);
DMux4Way(in=in, sel=sel[0..1], a=e1, b=e2, c=e3, d=e4);
DMux4Way(in=in, sel=sel[0..1], a=e5, b=e6, c=e7, d=e8);
And(a=e1, b=nsel2, out=a);
And(a=e2, b=nsel2, out=b);
And(a=e3, b=nsel2, out=c);
And(a=e4, b=nsel2, out=d);
And(a=e5, b=sel[2], out=e);
And(a=e6, b=sel[2], out=f);
And(a=e7, b=sel[2], out=g);
And(a=e8, b=sel[2], out=h);
} |
class EmailDataModel {
final String firstName;
final String lastName;
final String email;
EmailDataModel({
required this.firstName,
required this.lastName,
required this.email,
});
factory EmailDataModel.fromJson(Map<String, dynamic> json) {
return EmailDataModel(
firstName: json['first_name'] as String,
lastName: json['last_name'] as String,
email: json['email'] as String,
);
}
Map<String, dynamic> toJson() {
return {
'first_name': firstName,
'last_name': lastName,
'email': email,
};
}
} |
package tree;
import visitor.NodeVisitor;
/**
* A node of the operator "*" on integer.
*
* @author lxcc0wave
* @version 2017.3.15
*/
public class Multiply extends BinaryOperator{
/**
* Constructs a "*" oeprator with the specified operands.
*
* @param left left operand(not {@code null})
* @param right right operand(not {@code null})
*/
public Multiply(Node left, Node right) {
super(left, right);
}
@Override
public int eval() {
return this.getLeft().eval() * this.getRight().eval();
}
@Override
public void dump(int n) {
System.out.println(makeIndent(n) + "Multiply");
this.getLeft().dump(n + 1);
this.getRight().dump(n + 1);
}
public boolean equals(Multiply exp){
if(exp == null)
return false;
return this.getLeft().equals(exp.getLeft())
&& this.getRight().equals(exp.getRight());
}
@Override
public boolean equals(Object obj){
if(! (obj instanceof Multiply))
return false;
return equals((Multiply)obj);
}
@Override
public String toString(){
return "Multiply";
}
@Override
public void accept(NodeVisitor v) {
v.visit(this);
}
} |
package domains;
import javax.persistence.*;
import java.sql.Date;
@Entity
@Table(name = "T_RATE_AVALIACAO_DIARIA")
@SequenceGenerator(name = "avaliacaoDiaria", sequenceName = "SQ_TB_AVALIACAO_DIARIA", allocationSize = 1)
public class AvaliacaoDiaria {
public AvaliacaoDiaria() {
}
public AvaliacaoDiaria(Aluno aluno, Materia materia, String dsAvaliacao, Integer nrEstrela, Date dtAvaliacao) {
this.aluno = aluno;
this.materia = materia;
this.dsAvaliacao = dsAvaliacao;
this.nrEstrela = nrEstrela;
this.dtAvaliacao = dtAvaliacao;
}
public AvaliacaoDiaria(Integer cdAvaliacaoDiaria, Aluno aluno, Materia materia, String dsAvaliacao, Integer nrEstrela, Date dtAvaliacao) {
this.cdAvaliacaoDiaria = cdAvaliacaoDiaria;
this.aluno = aluno;
this.materia = materia;
this.dsAvaliacao = dsAvaliacao;
this.nrEstrela = nrEstrela;
this.dtAvaliacao = dtAvaliacao;
}
@Id
@Column(name = "cd_avaliacao_diaria", nullable = false, precision = 3)
@GeneratedValue(generator = "avaliacaoDiaria", strategy = GenerationType.SEQUENCE)
private Integer cdAvaliacaoDiaria;
@ManyToOne
@JoinColumn(name = "cd_aluno", nullable = false)
private Aluno aluno;
@ManyToOne
@JoinColumn(name = "cd_materia", nullable = false)
private Materia materia;
@Column(name = "ds_avaliacao", nullable = false, length = 255)
private String dsAvaliacao;
@Column(name = "nr_estrela", nullable = false, precision = 3)
private Integer nrEstrela;
@Column(name = "dt_avaliacao", nullable = false)
private Date dtAvaliacao;
public Integer getCdAvaliacaoDiaria() {
return cdAvaliacaoDiaria;
}
public void setCdAvaliacaoDiaria(Integer cdAvaliacaoDiaria) {
this.cdAvaliacaoDiaria = cdAvaliacaoDiaria;
}
public Aluno getAluno() {
return aluno;
}
public void setAluno(Aluno aluno) {
this.aluno = aluno;
}
public Materia getMateria() {
return materia;
}
public void setMateria(Materia materia) {
this.materia = materia;
}
} |
import { DeviceContribution } from '../api';
import { Device_GL } from './Device';
export interface WebGLRendererPluginOptions {
targets: ('webgl1' | 'webgl2')[];
xrCompatible: boolean;
antialias: boolean;
preserveDrawingBuffer: boolean;
premultipliedAlpha: boolean;
onContextCreationError: (e: Event) => void;
onContextLost: (e: Event) => void;
onContextRestored: (e: Event) => void;
}
export class WebGLDeviceContribution implements DeviceContribution {
constructor(private pluginOptions: Partial<WebGLRendererPluginOptions>) {}
async createSwapChain($canvas: HTMLCanvasElement) {
const {
targets,
xrCompatible,
antialias = false,
preserveDrawingBuffer = false,
premultipliedAlpha = true,
} = this.pluginOptions;
const options: WebGLContextAttributes & { xrCompatible: boolean } = {
// alpha: true,
antialias,
// @see https://stackoverflow.com/questions/27746091/preservedrawingbuffer-false-is-it-worth-the-effort
preserveDrawingBuffer,
// @see https://webglfundamentals.org/webgl/lessons/webgl-qna-how-to-use-the-stencil-buffer.html
stencil: true,
// @see https://webglfundamentals.org/webgl/lessons/webgl-and-alpha.html
premultipliedAlpha,
xrCompatible,
};
this.handleContextEvents($canvas);
let gl: WebGLRenderingContext | WebGL2RenderingContext;
if (targets.includes('webgl2')) {
gl =
$canvas.getContext('webgl2', options) ||
($canvas.getContext(
'experimental-webgl2',
options,
) as WebGL2RenderingContext);
}
if (!gl && targets.includes('webgl1')) {
gl =
$canvas.getContext('webgl', options) ||
($canvas.getContext(
'experimental-webgl',
options,
) as WebGLRenderingContext);
}
return new Device_GL(gl as WebGLRenderingContext | WebGL2RenderingContext, {
shaderDebug: true,
trackResources: true,
});
}
private handleContextEvents($canvas: HTMLCanvasElement) {
const { onContextLost, onContextRestored, onContextCreationError } =
this.pluginOptions;
// bind context event listeners
if (onContextCreationError) {
// @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/webglcontextcreationerror_event
$canvas.addEventListener(
'webglcontextcreationerror',
onContextCreationError,
false,
);
}
if (onContextLost) {
$canvas.addEventListener('webglcontextlost', onContextLost, false);
}
if (onContextRestored) {
$canvas.addEventListener(
'webglcontextrestored',
onContextRestored,
false,
);
}
}
} |
--1
SELECT
UCASE('trybe') AS UCASE;
--2
SELECT
REPLACE(
'Você já ouviu falar do DuckDuckGo?',
'DuckDuckGo',
'Google'
) AS STR_REPLACE;
--3
SELECT
LENGTH('Uma frase qualquer') AS STR_LENGTH;
--4
SELECT
SUBSTRING(
'A linguagem JavaScript está entre as mais usadas',
13,
10
) AS STR_SUBSTRING;
--5
SELECT
LCASE('RUA NORTE 1500, SÃO PAULO, BRASIL') AS LCASE;
--1
SELECT
film_id,
title,
IF(
title = 'ACE GOLDFINGER',
'Já assisti a esse filme',
'Não conheço o filme'
) AS 'conheço o filme?'
FROM
sakila.film;
--2
SELECT
title,
rating,
CASE
WHEN rating = 'G' THEN 'Livre para todos'
WHEN rating = 'PG' THEN 'Não recomendado para menores de 10 anos'
WHEN rating = 'PG-13' THEN 'Não recomendado para menores de 13 anos'
WHEN rating = 'R' THEN 'Não recomendado para menores de 17 anos'
ELSE 'Proibido para menores de idade'
END AS 'público-alvo'
FROM
sakila.film;
--1
SELECT
ROUND(15 + (RAND() * 5));
--2
SELECT
ROUND(15.7515971, 5);
--3
SELECT
FLOOR(39.494);
--4
SELECT
CEIL(85.234);
--1
SELECT
DATEDIFF('2030-01-20', NOW());
--2
SELECT
TIMEDIFF('10:25:45', '11:00:00');
--1
SELECT
AVG(length) AS 'Média de Duração',
MIN(length) AS 'Duração Mínima',
MAX(length) AS 'Duração Máxima',
SUM(length) AS 'Tempo de Exibição Total',
COUNT(*) AS 'Filmes Registrados'
FROM
sakila.film;
--1
SELECT
active,
COUNT(*)
FROM
sakila.customer
GROUP BY
active;
--2
SELECT
store_id,
active,
COUNT(*)
FROM
sakila.customer
GROUP BY
store_id,
active
ORDER BY
store_id;
--3
SELECT
rating,
AVG(rental_rate) AS avg_rental_dur
FROM
sakila.film
GROUP BY
rating
ORDER BY
avg_rental_dur DESC;
--4
SELECT
district,
COUNT(*) AS address_count
FROM
sakila.address
GROUP BY
district
ORDER BY
address_count DESC;
--1
SELECT
rating,
AVG(length) AS avg_rating
FROM
sakila.film
GROUP BY
rating
HAVING
avg_rating BETWEEN 115.0
AND 121.50;
--2
SELECT
rating,
SUM(replacement_cost) total_replacement_cost
FROM
sakila.film
GROUP BY
rating
HAVING
total_replacement_cost > 3950.50
ORDER BY
total_replacement_cost; |
package com.iktex.hb04.models.entity;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Getter
@Setter
@NoArgsConstructor
public class Vehicle extends AbstractBaseClass {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String v_model;
private int v_year;
private String v_plate;
@ManyToMany
@JsonManagedReference
private List<Accident> accident = new ArrayList<>();
@ManyToOne
@JsonManagedReference
private Customer customer;
public Vehicle(String v_model, int v_year, String v_plate) {
this.v_model = v_model;
this.v_year = v_year;
this.v_plate = v_plate;
}
} |
/*******************************************************************************
This file is part of the SimplexSolver.
Copyright (C) 2009 Roman Tsisyk <roman@tsisyk.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
#include "simplexmethod.h"
#include "simplexmethodparams.h"
#include <iostream>
int main(int argc, char *argv[])
{
// Step 0. Input data
SimplexMethod::InitalParamsFactory paramsFactory(5, 4);
paramsFactory.setFuncType(SimplexMethod::OptimizeToMin);
paramsFactory.setRowC(0, 4.0);
paramsFactory.setRowC(1, 1.2);
paramsFactory.setRowC(2, 5.8);
paramsFactory.setRowC(3, 6.0);
paramsFactory.setRowC(4, 7.5);
paramsFactory.setColumnB(0, 1.12);
paramsFactory.setColumnB(1, 0.3);
paramsFactory.setColumnB(2, 0.1);
paramsFactory.setColumnB(3, 0.4);
paramsFactory.setColumnCompareOp(0, SimplexMethod::Equal);
paramsFactory.setColumnCompareOp(1, SimplexMethod::LessEqual);
paramsFactory.setColumnCompareOp(2, SimplexMethod::GreatEqual);
paramsFactory.setColumnCompareOp(3, SimplexMethod::LessEqual);
paramsFactory.setMatrixA(0, 0, 1);
paramsFactory.setMatrixA(0, 1, 1);
paramsFactory.setMatrixA(0, 2, 1);
paramsFactory.setMatrixA(0, 3, 1);
paramsFactory.setMatrixA(0, 4, 1);
paramsFactory.setMatrixA(1, 0, 0.8);
paramsFactory.setMatrixA(1, 1, 0.6);
paramsFactory.setMatrixA(1, 2, 0.1);
paramsFactory.setMatrixA(1, 3, 0.1);
paramsFactory.setMatrixA(1, 4, 0.1);
paramsFactory.setMatrixA(2, 0, 0.1);
paramsFactory.setMatrixA(2, 1, 0.3);
paramsFactory.setMatrixA(2, 2, 0.5);
paramsFactory.setMatrixA(2, 3, 0.3);
paramsFactory.setMatrixA(2, 4, 0.2);
paramsFactory.setMatrixA(3, 0, 0.1);
paramsFactory.setMatrixA(3, 1, 0.1);
paramsFactory.setMatrixA(3, 2, 0.4);
paramsFactory.setMatrixA(3, 3, 0.6);
paramsFactory.setMatrixA(3, 4, 0.7);
SimplexMethod::Solver *solver = new SimplexMethod::Solver(paramsFactory.initalParams());
// Step 1. Make canonical form of problem
solver->makeInitialBasis();
// Step 2. Try to find optimal basis
solver->iterate();
SimplexMethod::Status status;
while(SimplexMethod::SolutionFound == (status = solver->status()))
{
solver->changeBasis();
solver->iterate();
}
// Make integer basis
while(SimplexMethod::OptimalSolutionFound == (status = solver->status()))
{
solver->iterateInt();
}
// Step 3. Write result
switch(status)
{
// you can use SimplexMethod::Params functions to print result
case SimplexMethod::OptimalIntSolutionFound:
case SimplexMethod::OptimalSolutionFound: std::cout << "Optimum is founded: " << solver->F(); break;
case SimplexMethod::SolutionNotExists: std::cout << "Optimum is not found."; break;
case SimplexMethod::Error: std::cout << "Some error was occured while calculating solution: "; break;
default: std::cout << "Invalid state";
}
std::cout << std::endl;
delete solver;
return 0;
} |
import { Component } from "react";
import { Link } from "react-router-dom";
class ErrorBoundary extends Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
//typicallt you would log this to something like TrackJS or NewRelic
console.error("errorBoundary component caught an error", error, info);
}
render() {
if (this.state.hasError) {
return (
<h2>
There was an error with this listing.
<Link to="/">Click here to go back to homepage</Link>
</h2>
);
}
return this.props.children;
}
}
export default ErrorBoundary; |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 24 09:45:15 2023
@author: cycon
"""
import sys
import numpy as np
import EngineErrors as EngineErrors
import EnginePerformanceFunctions as EPF
# Use to define the general states/functions shared by each/most stages
class Stage():
def __init__(self, **kwargs):
'''
A general stage class that serves as a baseline for every stage.
Parameters
----------
**kwargs : TYPE
DESCRIPTION.
Returns
-------
None.
'''
self.R = 287 # J/kg*K
self.gam_a = 1.4
self.gam_g = 4/3
self.cp_a = 1.005 # kJ/kg*K
self.cp_g = 1.148 # kJ/kg*K
# General properties that could be used by all stages
# so all components know the atm conditions
self.Ta = kwargs.get('Ta')
self.Pa = kwargs.get('Pa')
self.Vinf = kwargs.get('Vinf')
self.Minf = kwargs.get('Minf')
self.Toi = kwargs.get('Toi')
self.Poi = kwargs.get('Poi')
self.Ti = kwargs.get('Ti')
self.Pi = kwargs.get('Pi')
self.Mi = kwargs.get('Mi')
self.Vi = kwargs.get('Vi')
self.m_dot = kwargs.get('m_dot') # Stays constant through component
self.mdot_ratio = 1 # used to track mass flow ratio through sections
self.ni = kwargs.get('ni', 1) # Isentropic efficiency
self.BPR = kwargs.get('BPR',1)
self.Toe = kwargs.get('Toe')
self.Poe = kwargs.get('Poe')
self.Te = kwargs.get('Te')
self.Pe = kwargs.get('Pe')
self.Me = kwargs.get('Me')
self.Ve = kwargs.get('Ve')
self.StageName = ""
self.Power = None
def forward(self, next_Stage):
next_Stage.Toi = self.Toe
next_Stage.Poi = self.Poe
next_Stage.Ti = self.Te
next_Stage.Pi = self.Pe
next_Stage.Mi = self.Me
next_Stage.Vi = self.Ve
next_Stage.m_dot = self.m_dot
next_Stage.mdot_ratio = self.mdot_ratio
def printOutputs(self):
form ='{:9.3f}'
print('Stage: ', self.StageName)
if self.Toe != None:
print('\t Toe = {} K'.format(form).format(self.Toe))
if self.Poe != None:
print('\t Poe = {} Pa'.format(form).format(self.Poe))
if self.Te != None:
print('\t Te = {} K'.format(form).format(self.Te))
if self.Pe != None:
print('\t Pe = {} Pa'.format(form).format(self.Pe))
if self.m_dot != None:
print('\tmdot = {} kg/s'.format(form).format(self.m_dot))
if self.Me != None:
print('\t Me = {}'.format(form).format(self.Me))
if self.Ve != None:
print('\t Ve = {} m/s'.format(form).format(self.Ve))
if self.Power != None:
print('\t Pow = {} W'.format(form).format(self.Power))
if self.SpecPower != None:
print('\t Specific Pow = {} J/kg'.format(form).format(self.specPower))
self.extraOutputs()
def extraOutputs(self):
# Overwrite this and put any extra outputs here within individual stages
return None
class Intake(Stage):
def __init__(self, **kwargs):
Stage.__init__(self, **kwargs)
self.StageName = "Intake"
# NOTE: Ram efficiency ~= Isentropic Efficiency
def calculate(self):
# Always assume Pi/Pa and Ti/Ta are given (atmos conditions)
self.Pi = self.Pa
self.Ti = self.Ta
self.Vi = self.Vinf
self.Mi = self.Minf
# If no vel or mach num inputted, assume stationary
if self.Mi == None:
if self.Vi == None:
self.Mi = 0
else:
self.Mi = self.Vi/np.sqrt(self.gam_a*self.R*self.Ti)
else:
if self.Vi == None:
self.Vi = self.Mi*np.sqrt(self.gam_a*self.R*self.Ti)
# Now we should have mach num no matter what
# and the static props (atm props)
self.Toe = self.Ti * (1 + (self.gam_a-1)*(self.Mi**2)/2)
self.Poe = self.Pi * (1 + self.ni*(self.Mi**2)*(self.gam_a-1)/2)**(self.gam_a/(self.gam_a-1))
class Compressor(Stage):
def __init__(self, **kwargs):
Stage.__init__(self, **kwargs)
self.StageName = "Compressor"
# Adding PR and BPR
self.r = kwargs.get('rc') # Pressure Ratio of stage
self.BPR = kwargs.get('BPR', 1) # Bypass Ratio: total mass flow (air)/mass flow through core
self.np = kwargs.get('np') # Polytropic efficiency
self.mdot_ratio = 1 # Starts as 1 for fan, will be updated by prior comp if
# different from 1 from forward section
def calculate(self):
# Should always have input To and Po, need to calculate power
# and output To and Po. r will always be given, BPR will affect output
# to next stage
if self.r == None:
raise EngineErrors.MissingValue('R-Press. Ratio','Compressor')
elif self.np == None:
self.np = ((self.gam_a-1)/self.gam_a)*np.log(self.r) / \
np.log( (self.r**((self.gam_a-1)/self.gam_a) - 1)/self.ni + 1)
n_frac = (self.gam_a-1)/(self.gam_a*self.np)
self.Toe = self.Toi + self.Toi*(self.r**n_frac - 1)
self.Poe = self.r*self.Poi
if self.m_dot == None:
self.specPower = self.mdot_ratio*self.cp_a*(self.Toe-self.Toi)
else:
self.Power = self.m_dot*self.cp_a*(self.Toe-self.Toi)
# Done
def forward(self, next_Stage_hot, next_Stage_cold=None):
next_Stage_hot.Toi = self.Toe
next_Stage_hot.Poi = self.Poe
next_Stage_hot.Ti = self.Te
next_Stage_hot.Pi = self.Pe
next_Stage_hot.Mi = self.Me
next_Stage_hot.Vi = self.Ve
next_Stage_hot.mdot_ratio = self.mdot_ratio
if next_Stage_cold == None:
next_Stage_hot.m_dot = self.m_dot
else:
if self.BPR == None:
raise EngineErrors.MissingValue('BPR','Compressor')
else:
if self.m_dot != None:
m_dot_h = self.m_dot/(1 + self.BPR)
m_dot_c = self.m_dot - m_dot_h
next_Stage_hot.m_dot = m_dot_h
next_Stage_cold.m_dot = m_dot_c
else:
# No inputted mdot
mdot_ratio_h = 1/(1+self.BPR)
next_Stage_hot.m_dot = None
next_Stage_hot.mdot_ratio = mdot_ratio_h
next_Stage_cold.m_dot = None
# Dont need to send mdot ratio to cold section
next_Stage_cold.Toi = self.Toe
next_Stage_cold.Poi = self.Poe
next_Stage_cold.Ti = self.Te
next_Stage_cold.Pi = self.Pe
next_Stage_cold.Mi = self.Me
next_Stage_cold.Vi = self.Ve
def calculate_nc(self, np, gamma=1.4):
'''
Parameters
----------
np : Float, 0-1
Polytropic efficiency.
gamma : Float, optional
Gamma. The default is 1.4.
Returns
-------
Isentropic Efficiency.
'''
nc = ( self.r**((self.gam_a-1)/self.gam_a) - 1 ) / ( self.r**((self.gam_a-1)/(self.gam_a*np)) - 1 )
return nc
class Combustor(Stage):
def __init__(self, **kwargs):
Stage.__init__(self, **kwargs)
self.StageName = "Combustor"
self.dTo = kwargs.get('dTb')
self.dPo = kwargs.get('dPb_dec', 0) # the pressure loss within the compressor as a decimal (0.05 = 5% loss)
self.f = kwargs.get('f')
self.Q = kwargs.get('Q_fuel')
self.nb = kwargs.get('nb', 1) # Combustor efficiency
def calculate(self):
# Assuming we have the Ti and Pi from compressor/prev stage
# We need to have the exit
if self.Toe == None:
# No Turbine inlet temp given
if self.dTo == None:
# No combustor increase temp given
if self.f == None and self.Q == None:
# No air-fuel ratio given, cant calculate temps
raise EngineErrors.MissingValue('Toe, dTo, or f&Q','Combustor')
else:
# We have f and Q to calculate exit temp
f_ideal = self.f*self.nb # inputted f would be actual
self.Toe = (f_ideal*self.Q + self.cp_a*self.Toi)/(self.cpg(1+f_ideal))
else:
# We dont have exit temp, but do have temp increase
self.Toe = self.Toi + self.dTo
# else: Dont need to use since we have what we need
# We have turbine inlet temp (Te)
self.Poe = self.Poi*(1-self.dPo)
self.dTo = self.Toe - self.Toi # will use later for f calcs
if self.f == None:
if self.Q != None:
# Assuming non-ideal, will calculate f and use in mass fuel flow
self.f = (self.cp_g*self.Toe - self.cp_a*self.Toi) / (self.ni*(self.Q - self.cp_g*self.Toe))
if self.m_dot != None and self.f != None:
self.m_dot += self.f*self.m_dot
elif self.m_dot == None and self.f != None:
self.mdot_ratio = (1+self.f)/(self.BPR + 1)
class Turbine(Stage):
def __init__(self, Comp_to_power, **kwargs):
Stage.__init__(self, **kwargs)
self.StageName = "Turbine"
self.np = kwargs.get('np') # Polytropic efficiency
self.nm = kwargs.get('nm',1)
self.Compressor = Comp_to_power # Could be list
# Will have inlet temp, compressor power
self.r = kwargs.get('rt') # Add for later, not used now
# this will be for generators or when turbine pressure ratio is specified
def calculate(self):
if self.m_dot != None:
if type(self.Compressor) == list:
com_power = 0
for i in range(0,len(self.Compressor)):
com_power += self.Compressor[i].Power
self.Power = com_power/self.nm
else:
self.Power = self.Compressor.Power/self.nm
# Calculate exit temp
self.Toe = self.Toi - self.Power/(self.m_dot*self.cp_g)
else:
# No m_dot is given, need to power balance based on
# BPR ratios instead
if type(self.Compressor) == list:
com_power = 0
for i in range(0,len(self.Compressor)):
com_power += self.Compressor[i].Power_ratio
self.specPower = com_power/self.nm
else:
self.specPower = self.Compressor.Power_ratio/self.nm
# Calculate exit temp
self.Toe = self.Toi - self.specPower/(self.mdot_ratio*self.cp_g)
if self.np == None:
if self.r != None:
# Calculate np
self.np = np.log(1- self.ni*(1 - self.r**((self.gam_g-1)/self.gam_g)))
self.np /= np.log(self.r)*(self.gam_g-1)/self.gam_g
else:
print('Warning: insufficient parameters given to turbine')
print('Continuing assuming polytropic efficiency = 1')
self.np = 1
m_frac = self.np*(self.gam_g-1)/self.gam_g
self.Poe = self.Poi*(1- (self.Toi-self.Toe)/self.Toi )**(1/m_frac)
class Nozzle(Stage):
def __init__(self, air_type='hot', **kwargs):
Stage.__init__(self, **kwargs)
self.StageName = "Nozzle"
if air_type == 'hot':
self.gam = self.gam_g
else:
self.gam = self.gam_a
def calculate(self):
# Check if choked
Tc = self.Toi*(2/(self.gam_g+1))
Pc = self.Poi*(1 - (1/self.ni)*(1-Tc/self.Toi))**(self.gam/(self.gam-1))
P_rat = self.Poi/self.Pa
P_crit = self.Poi/Pc
if P_rat > P_crit:
# Nozzle is choked
if self.Pe == None:
self.Pe = Pc
else:
# We are given exit pressure. For now assuming this
# is because Pe = Pa for a fully expanded CD Nozzle
self.Te = self.Toi*(1-self.ni*(1-(self.Pe/self.Poi)**((self.gam-1)/self.gam)))
else:
# Nozzle is not choked
self.Pe = self.Pa
self.Te = self.Toi*(1-self.ni*(1-(self.Pe/self.Poi)**((self.gam-1)/self.gam)))
self.Me = np.sqrt((2/(self.gam-1))*(self.Toi/self.Te - 1))
self.Ve = self.Me*np.sqrt(self.gam*self.R*self.Te)
# Stag props at exit
self.Toe = self.Toi
self.Poe = self.Pe * (1 + (self.gam -1)*(self.Me**2)/2)**(self.gam/(self.gam -1))
class compressor_rotor():
def __init__(self, r_tip, r_root, omega, Ca, AssumeConstAxialVel=True, **inputs):
self.r = inputs.get('r')
self.w = inputs.get('omega')
self.Ca = inputs.get('Ca')
self.deg_reac = inputs.get('lambda')
self.Ca1 = inputs.get('Ca1')
self.Ca2 = inputs.get('Ca2')
self.C1 = inputs.get('C1')
self.C2 = inputs.get('C1')
self.Cw1 = inputs.get('Cw1')
self.Cw2 = inputs.get('Cw2')
self.V1 = inputs.get('V1')
self.V2 = inputs.get('V1')
self.Vw1 = inputs.get('Vw1')
self.Vw2 = inputs.get('Vw2')
self.alpha_1 =inputs.get('alpha_1')
self.alpha_2 =inputs.get('alpha_2')
self.beta_1 =inputs.get('beta_1')
self.beta_2 =inputs.get('beta_2')
self.deg_reac = inputs.get('lambda')
# Velocity Triangle
# /|\
# /β|α\
# V1 / | \ C1
# / | \
# / |Ca \
# / | \
# <------|------>
# Vw1 Cw1
# -------------->
# U
# /P
# // Rotor
# || ----> U
# ||
# \
class rotor_turbine():
def __init__(self):
print('In development')
def combustor_component():
def __init__(self):
# Possible inputs/Outputs:
# mdot
# mdot_ratio ?
# mdot_fuel
# A_inlet
# A_mean
# A_exit
# phi - Overall equivalence ratio
# phi_local - Local equivalence ratio near flame
# mdot_local - Local mass flow rate near flame
# dPo_full - Full load pressure loss
# dPo - Pressure loss at current conditions
# V_inlet - Average Inlet velocity
# V_exit - Average Exit velocity
# To_i - Initial stagnation temperature
# To_e - Exit stagnation temperature
# Po_i - Inlet stagnation pressure
# Po_e - Exit stagnation pressure
# f_stoich - Stoicheometric fuel/air ratio
# f_ideal - Ideal fuel/air ratio
# f_actual - Actual fuel/air ratio
# f_local - Local fuel/air ratio
# nb - combustor efficiency
# Intermediates
# K1
# K2
# X - 1/phi
# General Values
self.R = 287 # J/kg*K
self.cpa = 1.005 # kJ/kg
self.cpg = 1.148 # kJ/kg
self.gam_a = 1.4
self.gam_g = float(4/3)
self.MW_air = 137.3653 # kg/kmol
self.MW_C = 12.011 # kg/kmol
self.MW_H = 1.0078 # kg/kmol
# Desired Calculations:
# Pressure Loss
# Pressure Loss at part-load
# Inlet Area
# Exit Area
# Mean Area
# Inlet Velocity
# Exit Velocity
# Fuel to air ratio
# Overall equivalence ratio
# Local mass flow rate
# Local equivalence ratio
def rho(self, To, Po, mdot, A, Gamma=None):
Gamma = self.gam_a if Gamma==None else Gamma
P = self.SOMEITERATIVESOLVER(Po, To, mdot, A)
a = To
b = -P/self.R
c = - (Gamma-1)*mdot / (2*Gamma*self.R*A**2)
rho = (-b + np.sqrt(b**2 - 4*a*c)) / (2*a) # Dont need the - for the quad
return rho
def rho(self, To, Po, Mach, Gamma=None):
Gamma = self.gam_a if Gamma==None else Gamma
rho_o = Po / (self.R*To)
rho = rho_o / ((1 + (Gamma-1)*(Mach**2)/2)**(1/(Gamma-1)) )
return rho
def SOMEITERATIVESOLVER(self, Po, To, mdot, A):
print("Working on derivation (its uggy)")
class Turbofan_SingleSpool():
def __init__(self, **kwargs):
'''
A signgle spool turbofan which has one turbine to power the
fan and compressor. It has a cold-air bypass which is after the fan
and goes straight to a nozzle. The core-flow goes to a second compressor
and then to the combustor, followed by a single turbine and lastly the
core nozzle.
Parameters
----------
**kwargs : Dictionary
Contains all needed and optional parameters with the keys listed below.
Required:
'Ta': Atmospheric static temperature
'Pa': Atmospheric static pressure
'rfan': Fan Pressure Ratio
'rc': Compressor Pressure Ratio
'BPR': Bypass Ratio (If not passed, assumed 1 so no bypass occurs)
'T_turb_in': Turbine inlet temp
Optional
'Vinf': None, # Or Minf
'Minf': 0.85, # Or Vinf, if none its assumed stationary
'mdot_a': # Mass flow rate of air into engine (kg/s)
'Q_fuel': Heat energy of fuel, pass if real to calculate f and include fuel flow in power/velecity calcs
'F': Thrust of the engine produced
Efficiencies (Assumed to be 1 if not passed)
'ni': Inlet Isentropic Efficiency
'nj': Nozzle Isentropic Efficiency
'nf': Fan Isentropic Efficiency
'nc': Compressor Isentropic Efficiency
'nt': Turbine Isentropic Efficiency
'nb': Cobustor Efficincy
'nm': Mechanical Efficiency
'npf': Fan Polytropic Efficiency (overrides isentropic)
'npc': Compressor Polytropic Efficiency (overrides isentropic)
'npt': Turbine Polytropic Efficiency (overrides isentropic)
'dP_combustor': Decimal pressure drop in combustor (ex: 0.05 for 5% P loss, 0 for ideal)
Returns
-------
None.
'''
# Stages
# Atm moving
# Inlet
# Fan (is a compressor)
# Bypass Nzzle
# LP Compressor
# HP Compressor
# Combustor
# HP Turbine
# LP Turbine
# Nozzle
self.inputs = kwargs.copy()
gen_kwargs = {
'Ta': kwargs.get('Ta'),
'Pa': kwargs.get('Pa'),
'Vinf': kwargs.get('Vinf'),
'Minf': kwargs.get('Minf'),
'BPR': kwargs.get('BPR',1), # Need this here on case mdot=None
'Q_fuel': kwargs.get('Q_fuel')}# kJ/kg
# Efficiencies
ni = kwargs.get('ni',1) # Inlet
nj = kwargs.get('nj',1) # Nozzle
nf = kwargs.get('nf',1) # Compressor - Isentropic
nc = kwargs.get('nc',1) # Compressor - Isentropic
nt = kwargs.get('nt',1) # Turbine - Isentropic
nb = kwargs.get('nb',1) # Cobustor
nm = kwargs.get('nm',1) # Mechanical
npf = kwargs.get('npf') # Fan - Polytropic
npc = kwargs.get('npc') # Compressor - Polytropic
npt = kwargs.get('npt') # Turbine - Polytropic
# Pressure Ratios/Relations
dP_b = kwargs.get('dP_combustor') # Decimal pressure drop in combustor
rfan = kwargs.get('rfan') # Fan PR
rc = kwargs.get('rc') # Compressor PR
# Turbine Inlet
To_ti = kwargs.get('T_turb_in') # K - Turbine inlet temp
# Air Mass flow
mdot = kwargs.get('mdot_a') # kg/s
self.F = kwargs.get('F')
# Define each stage and pass in parameters
self.inlet = Intake(**gen_kwargs,ni=ni,m_dot=mdot)
self.fan = Compressor(**gen_kwargs, rc=rfan, np=npf, ni=nf)
self.BP_nozzle = Nozzle('cold',**gen_kwargs, ni=nj)
self.HP_comp = Compressor(**gen_kwargs, rc=rc, np=npc, ni=nc)
self.combustor = Combustor(**gen_kwargs, Toe=To_ti, dPb_dec=dP_b, ni=nb)
self.HP_turb = Turbine([self.fan, self.HP_comp], **gen_kwargs, nm=nm, ni=nt, np=npt)
self.nozzle = Nozzle(**gen_kwargs, ni=nj) # Nozzle/Exhaust?
# Set names for easier readout checks
self.fan.StageName = 'Fan'
self.BP_nozzle.StageName = 'Cold Nozzle'
self.nozzle.StageName = 'Hot Nozzle'
# Define all stages in engine to iterate through
# Two dimensional since there is a bypass, ie one stage
# passes params to two different stages
self.AllStages = [[self.inlet, None ],
[self.fan, None],
[self.HP_comp, self.BP_nozzle],
[self.combustor,None],
[self.HP_turb, None],
[self.nozzle, None]]
def calculate(self, printVals=True):
'''
Calculates the properties of the air throughout the engine.
Parameters
----------
printVals : Bool, optional
When true, it will print out each components exit conditions. The default is True.
Returns
-------
None.
'''
for i in range(0,len(self.AllStages)):
# Calculate each row and print outputs
self.AllStages[i][0].calculate()
if printVals: self.AllStages[i][0].printOutputs()
# Check if current stage has a parallel (ie, prev stage passes air to 2 stages)
if self.AllStages[i][1] != None:
self.AllStages[i][1].calculate()
if printVals: self.AllStages[i][1].printOutputs()
# Move forward/propogate
if i != len(self.AllStages)-1: # It is not at the end, so forward
if self.AllStages[i+1][1] != None:
# Means that this stage delivers to two stages: fan -> HPC & BP Noz
self.AllStages[i][0].forward(self.AllStages[i+1][0],self.AllStages[i+1][1])
else:
# Stage delivers to one stage
self.AllStages[i][0].forward(self.AllStages[i+1][0])
def getOutputs(self):
'''
Returns a dictionary containing important values fromwithin the engine
using typical engine notaion. Must be run after calculate in order to contain values.
Returns
-------
outs : Dictionary
Conatins the following items:
'mdot_c' - bypass flow [kg/s]
'mdot_h1' - core flow [kg/s]
'mdot_h2' - core flow + fuel [kg/s]
'mdot' - air flow into the engine [kg/s]
'Ca' - Initial vel of air (rel to engine) [m/s]
'C9' - Exhast vel of core [m/s]
'C19' - Exhuast vel of bypass [m/s]
'Pa' - Static atmospheric pressure [Pa]
'P9' - Exit pressure of core noz [Pa]
'P19' - Exit pressure of bypass noz [Pa]
'To3': - Combustor inlet stagnation temp [K]
'To4': - Combustor outlet stagnation temp [K]
'nb': - combustor efficiency
'dH': - fuel energy [kJ/kg]
'f': - air to fuel ratio
'''
outs = {
'mdot_c': self.BP_nozzle.m_dot, # bypass flow
'mdot_h1': self.HP_comp.m_dot, # core flow
'mdot_h2': self.nozzle.m_dot, # core flow + fuel
'mdot': self.inlet.m_dot, # air flow in
'Ca': self.inlet.Vi, # Initial vel of air
'C9': self.nozzle.Ve, # Exhast vel of core
'C19': self.BP_nozzle.Ve, # Exhuast vel of bypass
'Pa': self.inputs.get('Pa'),
'P9': self.nozzle.Pe, # Exit pressure of core noz
'P19': self.BP_nozzle.Pe,# Exit pressure of bypass noz
'To3': self.combustor.Toi, # combustor inlet temp
'To4': self.combustor.Toe, # combustor outlet temp
'nb': self.combustor.ni, # combustor efficiency
'dH': self.combustor.Q, # fuel energy
'f': self.combustor.f # air to fuel ratio
}
return outs
def printInputs(self):
'''
Prints out all of the kwargs entered on intialization
Returns
-------
None.
'''
print('Inputs')
for key,val in self.inputs.items():
print('\t {} = {}'.format(key,val))
def calculatePerformanceParams(self):
outs = self.getOutputs()
# Calculate thrust or mdot if one is given and not the other
if self.F == None:
if outs['mdot'] != None:
# Calcualte thrust
self.F = EPF.Thrust_1(outs['mdot'], self.inputs['BPR'], outs['C9'], outs['C19'], outs['Ca'])
else:
if outs['mdot'] == None:
# calculate mdot
mdot = EPF.mdot_2(self.F, self.inputs('BPR'), outs['C9'], outs['C19'], outs['Ca']) |
package com.processout.sdk.ui.core.component
import androidx.annotation.DrawableRes
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.Image
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import com.processout.sdk.ui.core.annotation.ProcessOutInternalApi
/** @suppress */
@ProcessOutInternalApi
@Composable
fun POAnimatedImage(
@DrawableRes id: Int,
modifier: Modifier = Modifier,
alignment: Alignment = Alignment.Center,
contentScale: ContentScale = ContentScale.Fit,
visibleState: MutableTransitionState<Boolean> = remember {
MutableTransitionState(initialState = false)
.apply { targetState = true }
}
) {
AnimatedVisibility(
visibleState = visibleState,
enter = fadeIn(animationSpec = tween()),
exit = fadeOut(animationSpec = tween())
) {
Image(
painter = painterResource(id = id),
contentDescription = null,
modifier = modifier,
alignment = alignment,
contentScale = contentScale
)
}
} |
import java.net.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class bank {
static HashMap<String, customerInfo> map = new HashMap<>(); //creating hashmap to store customer objects with their name as the key value
public static void main(String args[]) throws IOException {
ServerSocket server = null;
try {
//creating a new server socket at port 14000
server = new ServerSocket(14000);
server.setReuseAddress(true);
while (true) {
// The code below checks for incoming customer connections and starts a new thread to handle each client
Socket client = server.accept();
System.out.println("New client got connected!!!");
ClientHandler clientSock = new ClientHandler(client);
new Thread(clientSock).start();
}
//The code below will catch any exception thrown while starting the server and closes the server socket if it is not null
} catch (IOException e) {
e.printStackTrace();
} finally {
if (server != null) {
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// This class implements the Runnable interface to handle client requests
private static class ClientHandler implements Runnable {
private final Socket clientSocket;
private customerInfo customer;
//Constructors to set the clientSocket attributes
public ClientHandler() {
this.clientSocket = null;
}
public ClientHandler(Socket socket) {
this.clientSocket = socket;
}
public void run() {
PrintWriter out = null;
BufferedReader in = null;
try {
// The code below will handle the customer requests coming from the customer input stream and parsing that input
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String input;
while (!clientSocket.isClosed() && (input = in.readLine()) != null) {
//The command from the customer side is split to check the first word and decide what to implement
String command = "";
String[] line = input.split(" ");
command = line[0];
switch (command) {
//If the open command is received the ClientHandler class will check if the command is valid and create a customer object if it and if not a Failure message is returned
case "open":
if (line[1].length() <= 15) {
double balance = Double.parseDouble(line[2]);
int portA = Integer.parseInt(line[4]);
int portB = Integer.parseInt(line[5]);
if (portA >= 14000 && portA <= 14499 && portB >= 14000 && portB <= 14499) {
customerInfo customer = new customerInfo(line[1], balance, line[3], portA, portB, clientSocket);
out.println(open(customer));
out.flush();
} else {
out.println("FAILURE");
out.flush();
}
} else {
out.println("FAILURE");
out.flush();
}
break;
// if the new-cohort command is recieved, function new Cohort is called to create a cohort
case "new-cohort":
String cName = line[1];
int n = Integer.parseInt(line[2]);
String value = newCohort(cName, n);
sendMembersInfo(cName, value);
break;
//If the delete-cohort command i received, function deleteCohort is called
case "delete-cohort":
cName = line[1];
// Socket socket = new Socket(map.get(cName).getIPv4() , map.get(cName).getPortB());
// PrintWriter pw = new PrintWriter(socket.getOutputStream() , true);
if (deleteCohort(cName)) {
out.println("SUCCESS : The cohort has been deleted");
out.flush();
} else {
out.println("FAILURE");
out.flush();
}
break;
//If the exit command is received we call the exit method
case "exit":
cName = line[1];
if (exit(cName).equals("SUCCESS")) {
out.println("SUCCESS");
out.flush();
out.println("disconnected");
out.flush();
} else {
out.print("FAILURE");
out.flush();
}
break;
case "print":
print();
break;
case "update":
map.get(line[1]).setBalance(Double.parseDouble(line[2]));
System.out.println("The customer " + map.get(line[1]).getCustomerName() + " has been updated to " + map.get(line[1]).getBalance() + "\n");
Thread.sleep(800);
break;
case "rollback":
map.get(line[1]).setBalance(Double.parseDouble(line[2]));
System.out.println("The customer " + map.get(line[1]).getCustomerName() + " has been rolled back to " + map.get(line[1]).getBalance()+"\n");
Thread.sleep(800);
break;
default:
System.out.println(input);
out.println("FAILURE");
out.flush();
System.out.println("Incorrect Input");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static boolean sendMembersInfo(String customerName, String cohortList) throws IOException {
if (map.isEmpty() || !(map.containsKey(customerName))) {
return false;
}
customerInfo currCust = map.get(customerName);
if (currCust.getCohort() == null) {
return false;
}
List<customerInfo> cohort = currCust.getCohort();
PrintWriter out = null;
for (customerInfo i : cohort) {
out = new PrintWriter(i.getClientSocket().getOutputStream(), true);
out.println(cohort.size());
out.flush();
out.println("You have been added to the cohort");
out.flush();
out.println(cohortList);
out.flush();
}
return true;
}
//This method is to print all the customers in the bank and is used for testing purposes
public static void print() {
for (Map.Entry<String, customerInfo> mapElement : map.entrySet()) {
String key = mapElement.getKey();
customerInfo value = (mapElement.getValue());
value.printCustomer();
}
}
//Function to open a new customer account
public static String open(customerInfo customer) {
if (!map.isEmpty() && map.containsKey(customer.getName())) {
return "FAILURE";
} else {
map.put(customer.getName(), customer);
return "SUCCESS";
}
}
//Function to create a new Cohort, n being the number of people that should be in the cohort
public static String newCohort(String customerName, int n) {
if (n > map.size() || !map.containsKey(customerName) || n < 2) {
return "FAILURE";
}
//Checks if the customer trying to create a cohort is not in another cohort at the bank and if he is Failure message is returned
customerInfo currCust = map.get(customerName);
if (currCust.getCohort() != null) {
return "FAILURE";
}
int count = 1;
ArrayList<customerInfo> generatedCohort = new ArrayList<>();
generatedCohort.add(currCust);
//Adds random customer to the cohort whose cohort value is null
for (Map.Entry<String, customerInfo> mapElement : map.entrySet()) {
if (count == n) {
break;
}
customerInfo value = (mapElement.getValue());
if (value.getCohort() == null && !value.customerName.equals(customerName)) {
count++;
generatedCohort.add(value);
}
}
//formatted output to show the memebers added to the cohort to the customer who invoked the command
if (count == n) {
String ret = "SUCCESS\n";
ret += "Customer";
ret += "\t" + "Balance";
ret += "\t" + "IPv4 Address";
ret += "\t" + "Port(s)" + "\n";
for (int i = 0; i < generatedCohort.size(); i++) {
generatedCohort.get(i).setCohort(generatedCohort);
if (i == generatedCohort.size() - 1) {
ret += generatedCohort.get(i).getCustomerName();
ret += "\t" + generatedCohort.get(i).getBalance();
ret += "\t" + generatedCohort.get(i).getIPv4();
ret += "\t" + generatedCohort.get(i).getPortA();
ret += "\t" + generatedCohort.get(i).getPortB();
} else {
ret += generatedCohort.get(i).getCustomerName();
ret += "\t" + generatedCohort.get(i).getBalance();
ret += "\t" + generatedCohort.get(i).getIPv4();
ret += "\t" + generatedCohort.get(i).getPortA();
ret += "\t" + generatedCohort.get(i).getPortB() + "\n";
}
}
return ret;
}
return "FAILURE";
}
//Function to delete a cohort from the bank and
public static boolean deleteCohort(String customerName) throws IOException {
if (map.isEmpty() || !(map.containsKey(customerName))) {
return false;
}
customerInfo currCust = map.get(customerName);
if (currCust.getCohort() == null) {
return false;
}
List<customerInfo> cohort = currCust.getCohort();
PrintWriter out = null;
for (customerInfo i : cohort) {
if (i.getCustomerName() != customerName) {
out = new PrintWriter(i.getClientSocket().getOutputStream(), true);
out.println("You have been removed from the cohort.\n");
out.flush();
}
i.setCohort(null);
}
return true;
}
//Functions to exit from the bank if and only if the customer is not present in a cohort
public static String exit(String customerName) {
if (map.isEmpty() || !map.containsKey(customerName) || map.get(customerName).getCohort() != null) {
return "FAILURE";
} else {
System.out.println(customerName + " got disconnected!!!");
map.remove(customerName);
return "SUCCESS";
}
}
} |
package com.controller;
import java.io.File;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import com.alibaba.fastjson.JSONObject;
import java.util.*;
import org.springframework.beans.BeanUtils;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.ContextLoader;
import javax.servlet.ServletContext;
import com.service.TokenService;
import com.utils.*;
import java.lang.reflect.InvocationTargetException;
import com.service.DictionaryService;
import org.apache.commons.lang3.StringUtils;
import com.annotation.IgnoreAuth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.entity.*;
import com.entity.view.*;
import com.service.*;
import com.utils.PageUtils;
import com.utils.R;
import com.alibaba.fastjson.*;
/**
* 社区人员出入
* 后端接口
* @author
* @email
*/
@RestController
@Controller
@RequestMapping("/shequchuru")
public class ShequchuruController {
private static final Logger logger = LoggerFactory.getLogger(ShequchuruController.class);
@Autowired
private ShequchuruService shequchuruService;
@Autowired
private TokenService tokenService;
@Autowired
private DictionaryService dictionaryService;
//级联表service
@Autowired
private ZhuhuService zhuhuService;
/**
* 后端列表
*/
@RequestMapping("/page")
public R page(@RequestParam Map<String, Object> params, HttpServletRequest request){
logger.debug("page方法:,,Controller:{},,params:{}",this.getClass().getName(),JSONObject.toJSONString(params));
String role = String.valueOf(request.getSession().getAttribute("role"));
if(StringUtil.isEmpty(role))
return R.error(511,"权限为空");
else if("住户".equals(role))
params.put("zhuhuId",request.getSession().getAttribute("userId"));
if(params.get("orderBy")==null || params.get("orderBy")==""){
params.put("orderBy","id");
}
PageUtils page = shequchuruService.queryPage(params);
//字典表数据转换
List<ShequchuruView> list =(List<ShequchuruView>)page.getList();
for(ShequchuruView c:list){
//修改对应字典表字段
dictionaryService.dictionaryConvert(c, request);
}
return R.ok().put("data", page);
}
/**
* 后端详情
*/
@RequestMapping("/info/{id}")
public R info(@PathVariable("id") Long id, HttpServletRequest request){
logger.debug("info方法:,,Controller:{},,id:{}",this.getClass().getName(),id);
ShequchuruEntity shequchuru = shequchuruService.selectById(id);
if(shequchuru !=null){
//entity转view
ShequchuruView view = new ShequchuruView();
BeanUtils.copyProperties( shequchuru , view );//把实体数据重构到view中
//级联表
ZhuhuEntity zhuhu = zhuhuService.selectById(shequchuru.getZhuhuId());
if(zhuhu != null){
BeanUtils.copyProperties( zhuhu , view ,new String[]{ "id", "createDate"});//把级联的数据添加到view中,并排除id和创建时间字段
view.setZhuhuId(zhuhu.getId());
}
//修改对应字典表字段
dictionaryService.dictionaryConvert(view, request);
return R.ok().put("data", view);
}else {
return R.error(511,"查不到数据");
}
}
/**
* 后端保存
*/
@RequestMapping("/save")
public R save(@RequestBody ShequchuruEntity shequchuru, HttpServletRequest request){
logger.debug("save方法:,,Controller:{},,shequchuru:{}",this.getClass().getName(),shequchuru.toString());
String role = String.valueOf(request.getSession().getAttribute("role"));
if(StringUtil.isEmpty(role))
return R.error(511,"权限为空");
else if("住户".equals(role))
shequchuru.setZhuhuId(Integer.valueOf(String.valueOf(request.getSession().getAttribute("userId"))));
Wrapper<ShequchuruEntity> queryWrapper = new EntityWrapper<ShequchuruEntity>()
.eq("zhuhu_id", shequchuru.getZhuhuId())
.eq("shequchuru_types", shequchuru.getShequchuruTypes())
.eq("lai_address", shequchuru.getLaiAddress())
.eq("qu_address", shequchuru.getQuAddress())
;
logger.info("sql语句:"+queryWrapper.getSqlSegment());
ShequchuruEntity shequchuruEntity = shequchuruService.selectOne(queryWrapper);
if(shequchuruEntity==null){
shequchuru.setInsertTime(new Date());
shequchuru.setCreateTime(new Date());
shequchuruService.insert(shequchuru);
return R.ok();
}else {
return R.error(511,"表中有相同数据");
}
}
/**
* 后端修改
*/
@RequestMapping("/update")
public R update(@RequestBody ShequchuruEntity shequchuru, HttpServletRequest request){
logger.debug("update方法:,,Controller:{},,shequchuru:{}",this.getClass().getName(),shequchuru.toString());
String role = String.valueOf(request.getSession().getAttribute("role"));
if(StringUtil.isEmpty(role))
return R.error(511,"权限为空");
else if("住户".equals(role))
shequchuru.setZhuhuId(Integer.valueOf(String.valueOf(request.getSession().getAttribute("userId"))));
//根据字段查询是否有相同数据
Wrapper<ShequchuruEntity> queryWrapper = new EntityWrapper<ShequchuruEntity>()
.notIn("id",shequchuru.getId())
.andNew()
.eq("zhuhu_id", shequchuru.getZhuhuId())
.eq("shequchuru_types", shequchuru.getShequchuruTypes())
.eq("lai_address", shequchuru.getLaiAddress())
.eq("qu_address", shequchuru.getQuAddress())
;
logger.info("sql语句:"+queryWrapper.getSqlSegment());
ShequchuruEntity shequchuruEntity = shequchuruService.selectOne(queryWrapper);
if(shequchuruEntity==null){
// String role = String.valueOf(request.getSession().getAttribute("role"));
// if("".equals(role)){
// shequchuru.set
// }
shequchuruService.updateById(shequchuru);//根据id更新
return R.ok();
}else {
return R.error(511,"表中有相同数据");
}
}
/**
* 删除
*/
@RequestMapping("/delete")
public R delete(@RequestBody Integer[] ids){
logger.debug("delete:,,Controller:{},,ids:{}",this.getClass().getName(),ids.toString());
shequchuruService.deleteBatchIds(Arrays.asList(ids));
return R.ok();
}
/**
* 批量上传
*/
@RequestMapping("/batchInsert")
public R save( String fileName){
logger.debug("batchInsert方法:,,Controller:{},,fileName:{}",this.getClass().getName(),fileName);
try {
List<ShequchuruEntity> shequchuruList = new ArrayList<>();//上传的东西
Map<String, List<String>> seachFields= new HashMap<>();//要查询的字段
Date date = new Date();
int lastIndexOf = fileName.lastIndexOf(".");
if(lastIndexOf == -1){
return R.error(511,"该文件没有后缀");
}else{
String suffix = fileName.substring(lastIndexOf);
if(!".xls".equals(suffix)){
return R.error(511,"只支持后缀为xls的excel文件");
}else{
URL resource = this.getClass().getClassLoader().getResource("static/upload/" + fileName);//获取文件路径
File file = new File(resource.getFile());
if(!file.exists()){
return R.error(511,"找不到上传文件,请联系管理员");
}else{
List<List<String>> dataList = PoiUtil.poiImport(file.getPath());//读取xls文件
dataList.remove(0);//删除第一行,因为第一行是提示
for(List<String> data:dataList){
//循环
ShequchuruEntity shequchuruEntity = new ShequchuruEntity();
// shequchuruEntity.setZhuhuId(Integer.valueOf(data.get(0))); //住户 要改的
// shequchuruEntity.setShequchuruTypes(Integer.valueOf(data.get(0))); //出入类型 要改的
// shequchuruEntity.setShequchuruTiwen(data.get(0)); //体温 要改的
// shequchuruEntity.setLaiAddress(data.get(0)); //从哪来 要改的
// shequchuruEntity.setQuAddress(data.get(0)); //到哪去 要改的
// shequchuruEntity.setShequchuruContent("");//照片
// shequchuruEntity.setInsertTime(date);//时间
// shequchuruEntity.setCreateTime(date);//时间
shequchuruList.add(shequchuruEntity);
//把要查询是否重复的字段放入map中
}
//查询是否重复
shequchuruService.insertBatch(shequchuruList);
return R.ok();
}
}
}
}catch (Exception e){
return R.error(511,"批量插入数据异常,请联系管理员");
}
}
} |
# 一、入门
📕Java中的日志系统
## 1. JUL
Java Util Logging :Java 原生的日志框架。
JUL 不需要引入第三方依赖包。包含了一些核心组件,如记录器(Logger)、处理器(Handler)、格式化器(Formatter)和过滤器(Filter)等。适用于小型应用或对日志功能要求不高的场景。
JUL 本身并没有像 `Slf4j` 那样专门的、广泛使用的日志门面。主要就是 Java 自身提供的一套日志机制,直接使用其相关的 API 来进行日志操作。
可以使用Lombok快速开启日志
```java
@Log
public class Main {
public static void main(String[] args) {
System.out.println("自动生成的Logger名称:"+log.getName());
log.info("我是日志信息");
}
}
```
只需要添加一个@Log注解即可,添加后,我们可以直接使用一个静态变量log,而它就是自动生成的Logger。
## 2. 日志门面
日志门面:如`Slf4j`,把不同的日志系统的实现进行了具体的抽象化,只提供了统一的日志使用接口,使用时只需要按照其提供的接口方法进行调用即可,由于它只是一个接口,并不是一个具体的可以直接单独使用的日志框架,所以最终日志的格式、记录级别、输出方式等都要通过接口绑定的具体的日志系统来实现,这些具体的日志系统就有`log4j`、`logback`等,也叫做日志实现。
但是不同的框架可能使用了不同的日志框架,如果这个时候出现众多日志框架并存的情况,我们现在希望的是所有的框架一律使用日志门面(Slf4j)进行日志打印,这时该怎么去解决?我们不可能将其他框架依赖的日志框架替换掉,直接更换为Slf4j吧,这样显然不现实。
这时,可以采取类似于偷梁换柱的做法,只保留不同日志框架的接口和类定义等关键信息,而将实现全部定向为Slf4j调用。相当于有着和原有日志框架一样的外壳,对于其他框架来说依然可以使用对应的类进行操作,而具体如何执行,真正的内心已经是Slf4j的了。
所以,SpringBoot为了统一日志框架的使用,做了这些事情:
- 直接将其他依赖以前的日志框架剔除
- 导入对应日志框架的Slf4j中间包
- 导入自己官方指定的日志实现,并作为Slf4j的日志实现层
SpringBoot使用的是Slf4j作为日志门面,Logback(是log4j 框架的作者开发的新一代日志框架,它效率更高、能够适应诸多的运行环境,同时天然支持SLF4J)作为日志实现,对应的依赖为:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
```
此依赖已经被包含了,所以我们如果需要打印日志,可以像这样:
```java
@ResponseBody
@GetMapping("/test")
public User test(){
Logger logger = LoggerFactory.getLogger(TestController.class);
logger.info("用户访问了一次测试数据");
return mapper.findUserById(1);
}
```
因为我们使用了`Lombok`,所以直接一个注解也可以搞定:
```java
@Slf4j
@Controller
public class MainController {
@ResponseBody
@GetMapping("/test")
public User test(){
log.info("用户访问了一次测试数据");
return mapper.findUserById(1);
}
```
## 3. 日志等级
日志级别从低到高分为`TRACE` < `DEBUG` < `INFO` < `WARN` < `ERROR` < `FATAL`,默认只会打印`INFO`以上级别的信息
# 二、Logback
和JUL一样,Logback也能实现定制化,我们可以编写对应的配置文件,SpringBoot推荐将配置文件名称命名为`logback-spring.xml`,表示这是SpringBoot下Logback专用的配置:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 配置 -->
</configuration>
```
最外层由`configuration`包裹,<u>一旦编写,那么就会替换默认的配置</u>,所以如果什么都不写的话,会导致我们的SpringBoot项目没有配置任何日志输出方式,控制台也不会打印日志。
在 Spring Boot 项目中,已经在 `org/springframework/boot/logging/logback/defaults.xml` 这个文件中为我们预先设置好了一些默认的日志输出格式等相关配置。而我们如果想要实现一个在控制台打印日志的配置,只需要去设置相应的“附加器”(appender)。
通过配置特定的 appender,比如指定将日志输出到控制台,我们就可以利用 Spring Boot 已经定义好的日志格式,直接在控制台上看到按照预设格式输出的日志信息。这样就无需我们从头去详细地定义日志的各种具体格式和规则等,极大地简化了日志配置的工作。
导入后,我们利用预设的日志格式创建一个控制台日志打印:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 导入其他配置文件,作为预设 -->
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<!-- Appender作为日志打印器配置,这里命名随意 -->
<!-- ch.qos.logback.core.ConsoleAppender是专用于控制台的Appender -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>${CONSOLE_LOG_CHARSET}</charset>
</encoder>
</appender>
<!-- 指定日志输出级别,以及启用的Appender,这里就使用了我们上面的ConsoleAppender -->
<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</configuration>
```
配置完成后,我们发现控制台已经可以正常打印日志信息了。
接着我们来看看如何开启 文件打印 ,我们只需要配置一个对应的Appender即可:
```xml
<!-- ch.qos.logback.core.rolling.RollingFileAppender用于文件日志记录,它支持滚动 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
<charset>${FILE_LOG_CHARSET}</charset>
</encoder>
<!-- 自定义滚动策略,防止日志文件无限变大,也就是日志文件写到什么时候为止,重新创建一个新的日志文件开始写 -->
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!-- 文件保存位置以及文件命名规则,这里用到了%d{yyyy-MM-dd}表示当前日期,%i表示这一天的第N个日志 -->
<FileNamePattern>log/%d{yyyy-MM-dd}-spring-%i.log</FileNamePattern>
<!-- 到期自动清理日志文件 -->
<cleanHistoryOnStart>true</cleanHistoryOnStart>
<!-- 最大日志保留时间 -->
<maxHistory>7</maxHistory>
<!-- 最大单个日志文件大小 -->
<maxFileSize>10MB</maxFileSize>
</rollingPolicy>
</appender>
<!-- 指定日志输出级别,以及启用的Appender,这里就使用了我们上面的ConsoleAppender -->
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE"/>
</root>
```
配置完成后,我们可以看到日志文件也能自动生成了。
也可以魔改官方提供的日志格式,官方文档:https://logback.qos.ch/manual/layouts.html
# 三、MDC
这里需要提及的是MDC机制,Logback内置的日志字段还是比较少,如果我们需要打印有关业务的更多的内容,包括自定义的一些数据,需要借助logback MDC机制,MDC为“`Mapped Diagnostic Context`”(映射诊断上下文),即将一些运行时的上下文数据通过logback打印出来;此时我们需要借助`org.sl4j.MDC`类。
比如我们现在需要记录是哪个用户访问我们网站的日志,只要是此用户访问我们网站,都会在日志中携带该用户的ID,我们希望每条日志中都携带这样一段信息文本,而官方提供的字段无法实现此功能,这时就需要使用MDC机制:
```java
@ResponseBody
@GetMapping("/test")
public User test(HttpServletRequest request){
MDC.put("reqId", request.getSession().getId());
log.info("用户访问了一次测试数据");
return mapper.findUserById(1);
}
```
通过这种方式,我们就可以向日志中传入自定义参数了,我们日志中添加这样一个占位符`%X{键值}`,名字保持一致:
```xml
%clr([%X{reqId}]){faint}
```
这样当我们向MDC中添加信息后,只要是当前线程(本质是ThreadLocal实现)下输出的日志,都会自动替换占位符。
以下是一条使用了上述机制后的日志记录示例:
> [INFO] 用户访问了一次测试数据 - [reqId: some_session_id]
在这个示例中,“`[reqId: some_session_id]`”就是通过 MDC 机制添加并在日志中体现出来的自定义信息,其中“`some_session_id`”是实际放入 MDC 中的请求会话 ID。
我问了下AI,与直接字符串拼接的区别是什么
> 与直接在 `log.info` 里用字符串拼接相比,主要有以下一些区别:
>
> **灵活性方面**:使用 MDC 机制可以更灵活地管理和添加自定义数据,不需要每次都在代码中进行具体的拼接操作,减少了代码中的硬编码和可能出现的重复拼接逻辑。
>
> **维护性方面**:如果后续需要修改或添加更多的自定义数据,使用 MDC 只需在相应位置进行设置,而字符串拼接则可能需要在多个地方修改代码。
>
> **代码简洁性**:避免了在大量地方进行复杂的字符串拼接操作,使代码看起来更简洁、清晰。
>
> **线程安全性**:MDC 基于 `ThreadLocal` 实现,能确保在多线程环境下每个线程的数据独立性,而字符串拼接可能在多线程场景下出现一些潜在的同步问题。
>
> 比如,如果之后需要记录用户的其他信息,或者在多个不同的方法中都要记录类似的自定义信息,使用 MDC 会更加方便和高效,无需对每个地方的日志输出都进行繁琐的字符串修改。
# 四、MyBatis 日志系统
Mybatis也有日志系统,详细记录了所有的数据库操作等,但是我们在前面的学习中没有开启它,现在我们学习了日志之后,我们就可以尝试开启Mybatis的日志系统,来监控所有的数据库操作,要开启日志系统,我们需要进行配置:
```xml
<setting name="logImpl" value="JDK_LOGGING" />
``` |
import LogoutButton from "../components/LogoutButton";
import React, {useEffect, useState} from "react";
import {Image, Item} from "../model/Item";
import axios from "axios";
import "material-react-toastify/dist/ReactToastify.css";
import {toast} from "react-toastify";
import Button from "@mui/material/Button";
import UploadIcon from '@mui/icons-material/Upload';
import {categories, defaultCategory, defaultStatus, states} from "../model/Constants";
import {
Box,
CssBaseline,
FormControl,
Grid,
InputLabel,
MenuItem,
Select,
TextField,
ThemeProvider,
Typography
} from "@mui/material";
import Container from "@mui/material/Container";
import {Save} from "@mui/icons-material";
import {Link, useNavigate, useParams} from "react-router-dom";
import Footer from "../components/Footer";
import theme from "../styles/theme";
import {v4 as uuidv4} from "uuid";
import {FieldError} from "../model/FieldError";
import AppBarLogout from "../components/AppBarLogout";
export default function ItemPage() {
const [isEditItem, setIsEditItem] = useState(false);
const [name, setName] = useState("");
const [price, setPrice] = useState("");
const [description, setDescription] = useState("");
const [imageUrl, setImageUrl] = useState("");
const [category, setCategory] = useState("");
const [status, setStatus] = useState("AVAILABLE");
const [errorName, setErrorName] = useState("");
const [errorPrice, setErrorPrice] = useState("");
const [errorDescription, setErrorDescription] = useState("");
const [errorImageUrl, setErrorImageUrl] = useState("");
const navigate = useNavigate();
const params = useParams();
useEffect(() => {
(async () => {
const id = params.id;
const idIsSet = id !== undefined && id !== null;
const itemDataPromise: Promise<Item> = idIsSet ?
axios.get("/api/items/" + id).then((response) => response.data) :
Promise.resolve(() => ({} as Item));
itemDataPromise.then((item: Item) => {
setIsEditItem(idIsSet);
setName(item.name ?? "");
setPrice(item.price ? item.price.toFixed(2).replace(".", ",") : "");
setDescription(item.description ?? "");
setImageUrl(item.image?.url ?? "");
setCategory(item.category ?? defaultCategory);
setStatus(item.status ? item.status : defaultStatus);
});
})();
}, [params.id]);
function submitItemData(event: React.FormEvent<HTMLElement>) {
event.preventDefault();
setErrorName("");
setErrorDescription("");
setErrorPrice("");
setErrorImageUrl("");
const correctedPrice = parseFloat(price.toString().replace(",", "."))
const image: Image = {
url: imageUrl,
}
const item: Item = {
name: name,
price: correctedPrice,
description: description,
image: image,
category: category,
status: status
}
const axiosAction = isEditItem ?
axios.put("/api/items/" + params.id, item) :
axios.post("/api/items/", item);
return axiosAction
.then(() => {
setIsEditItem(false);
setName("");
setPrice("");
setDescription("");
setImageUrl("");
setCategory(defaultCategory);
setStatus(defaultStatus);
})
.then(() => toast.success("Item saved."));
}
const handleError = (error: any) => {
if (error.response.status === 400 && error.response.data.errors) {
error.response.data.errors.forEach((fieldError: FieldError) => {
if (fieldError.field === "name") {
setErrorName(fieldError.message);
} else if (fieldError.field === "description") {
setErrorDescription(fieldError.message);
} else if (fieldError.field === "price") {
setErrorPrice(fieldError.message);
} else if (fieldError.field === "image" || fieldError.field === "image.url") {
setErrorImageUrl(fieldError.message);
} else {
toast.error(fieldError.message);
}
});
} else {
toast.error("Error: " + error);
}
}
const submitItemAndGoHome = (event: React.FormEvent<HTMLElement>) => {
submitItemData(event)
.then(() => navigate("/"))
.catch((error) => handleError(error));
}
const submitItemAndAddNewItem = (event: React.FormEvent<HTMLElement>) => {
submitItemData(event)
.then(() => navigate("/itemdetails"))
.catch((error) => handleError(error));
}
const fileInputRef = React.useRef<HTMLInputElement>(null);
const uploadImage = (event: React.ChangeEvent<HTMLInputElement>) => {
event.preventDefault();
if (event.target.files && event.target.files.length > 0) {
const formData = new FormData();
formData.append("file", event.target.files[0]);
axios.post("/api/files", formData)
.then((response) => {
setImageUrl(response.data.imageUrl);
toast.success("Image saved and set as Image URL. Please save item to save changes.");
})
.catch((error) => toast.error(error.message));
}
}
return (
<ThemeProvider theme={theme}>
<CssBaseline/>
<AppBarLogout/>
<Container
component="main"
sx={{
p: 2,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
}}>
<Box>
<Typography
variant="h5"
align="center"
color="#91BFBC"
gutterBottom
>
View, edit and add your items.
</Typography>
<Typography
variant="h6"
align="center"
color="#91BFBC"
paragraph>
Make art lovers happy!
</Typography>
<Box
component="form"
sx={{mt: 3}}>
<Grid container spacing={2}>
<Grid item xs={12}>
<TextField
autoFocus
required
fullWidth
id="name"
label="Title"
name="name"
value={name}
error={errorName !== ""}
helperText={errorName}
onChange={(event) => {
setName(event.target.value)
}}
/>
</Grid>
{/*// IMAGE*/}
<Grid item xs={6}>
<TextField
required
fullWidth
label="Image URL"
id="image"
name="image"
value={imageUrl}
error={errorImageUrl !== ""}
helperText={errorImageUrl}
onChange={(event) => {
setImageUrl(event.target.value)
}}
/>
</Grid>
<Grid item xs={6}>
<Button
fullWidth
variant={"contained"}
component={"label"}
startIcon={<UploadIcon/>}
sx={{color: '#fff'}}
onClick={(event) => {
event.preventDefault();
fileInputRef.current?.click();
}}> UPLOAD IMAGE
</Button>
<input
ref={fileInputRef}
style={{display: "none"}}
type={"file"}
onChange={(e) => uploadImage(e)}
accept={"image/*"}
/>
</Grid>
{imageUrl && (
<Grid item xs={12}>
<img src={imageUrl} alt="preview" style={{width: "100%"}}/>
</Grid>
)}
{/*// IMAGE END*/}
<Grid item xs={12}>
<TextField
required
fullWidth
multiline
id="description"
label="Description"
name="description"
value={description}
error={errorDescription !== ""}
helperText={errorDescription}
onChange={(event) => {
setDescription(event.target.value)
}}
/>
</Grid>
<Grid item xs={12}>
<TextField
fullWidth
id="price"
label="Price in EUR"
name="price"
value={price}
error={errorPrice !== ""}
helperText={errorPrice}
onChange={(event) => {
setPrice(event.target.value)
}}
/>
</Grid>
<Grid item xs={12}>
<FormControl fullWidth>
<InputLabel id="status-category-label">Category</InputLabel>
<Select
required
fullWidth
labelId="category-select-label"
value={category}
label="Category"
onChange={(event) => setCategory(event.target.value)}
>
{categories.map((category) => (
<MenuItem key={uuidv4()} value={category}>{category}</MenuItem>))}
</Select>
</FormControl>
</Grid>
<Grid item xs={12}>
<FormControl fullWidth>
<InputLabel id="status-select-label">Status</InputLabel>
<Select
required
fullWidth
labelId="status-select-label"
value={status}
label="Status"
onChange={(event) => setStatus(event.target.value)}
>
{states.map((status) => (
<MenuItem key={uuidv4()} value={status}>{status}</MenuItem>))}
</Select>
</FormControl>
</Grid>
</Grid>
<Grid container
justifyContent="center"
spacing={1}>
<Grid item xs={6}>
<Button
variant="contained"
fullWidth
sx={{mt: 3, mb: 2, color: '#fff'}}
startIcon={<Save/>}
onClick={(event) => submitItemAndGoHome(event)}
>
Save & back
</Button>
</Grid>
<Grid item xs={6}>
<Button
variant="contained"
fullWidth
sx={{mt: 3, mb: 2, color: '#fff'}}
startIcon={<Save/>}
onClick={(event) => submitItemAndAddNewItem(event)}
>
Save & Next
</Button>
</Grid>
<Link
style={{textDecoration: "none", color: "#91BFBC"}}
to={"/"}
>
{"Back to home page without saving"}
</Link>
<Grid item xs={12}>
<Button
variant="outlined"
fullWidth
sx={{mt: 3, mb: 2, color: '#91BFBC'}}
startIcon={<UploadIcon/>}
href={"/csvImport"}
>
Go to csv-Upload Page
</Button>
</Grid>
</Grid>
</Box>
</Box>
<Grid container={true}
sx={{mb: 2}}
>
<LogoutButton/>
</Grid>
</Container>
<Footer/>
</ThemeProvider>
);
} |
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution {
public:
int leastWeightCapacity(int arr[], int n, int d) {
// code here
int start = 0;
int end = 0;
int mid;
int ans;
for(int i=0; i<n; i++){
start = max(start, arr[i]);
end += arr[i];
}
while(start <= end){
mid = start + (end - start)/2;
int capacity=0;
int days = 1;
for(int i=0; i<n ; i++){
capacity += arr[i];
if(capacity > mid){
days++;
capacity = arr[i];
}
}
if(days <= d){
end = mid - 1;
ans = mid;
}
else {
start = mid + 1;
}
}
return ans;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int N, D;
cin >> N;
int arr[N];
for (int i = 0; i < N; i++)
cin >> arr[i];
cin >> D;
Solution ob;
cout << ob.leastWeightCapacity(arr, N, D) << endl;
}
return 0;
}
// } Driver Code Ends |
package day_8.org.encapsulation;
//Achieve security
//For encapsulation data members should be private
public class Employee {
//private variable to store the data
private String name;
private int age;
private double salary;
//getter method for all -> read the value
public String getName() {
return name;
}
//Setter method for taking the values
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
//business logic
if(age>0) {
this.age = age;
}
else {
System.out.println("Age cannot be negative");
}
}
//Setter and getter for salary
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
if(salary>0) {
this.salary = salary;
}
else {
System.out.println("Salary must be greater than 0");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//Create an object
Employee emp1 = new Employee();
emp1.setName("Antanin Ginsita");
emp1.setAge(22);
emp1.setSalary(15000);
System.out.println(emp1.name+" "+emp1.age+" "+emp1.salary);
}
} |
<!DOCTYPE html>
<html lang='fr'>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="view-transition" content="same-origin"/>
<title>
{% block title %}The District
{% endblock %}
</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 128 128%22><text y=%221.2em%22 font-size=%2296%22>⚫️</text><text y=%221.3em%22 x=%220.2em%22 font-size=%2276%22 fill=%22%23fff%22>sf</text></svg>">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
{# <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> #}
{# {{ encore_entry_link_tags('main') }} #}
{# {{% import (app) %}} #}
{# <link rel="stylesheet" href="{{ asset('/css/bootstrap.min.css') }}"> #}
{# {% block stylesheets %}
<link rel="stylesheet" href="{{ asset('css/style.css')}}">
{% endblock %} #}
{# {% block javascripts %} #}
{# <script src="{{ asset('/js/bootstrap.bundle.min.js') }}" defer></script> #}
{# {{ encore_entry_script_tags('main') }} #}
{# <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"></script> #}
<link
rel="shortcut icon" type="image/svg+xml" href="{{ asset('favicon.svg') }}"> {# {% endblock %} #}
</head>
<body>
{#
{% block header %} #}
{{ include('_partials/_nav.html.twig')}}
{% if app.user and app.user.isVerified == false %}
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
<div class="alert-message">
<strong>Votre compte n'est pas activé</strong>,
<a href="{{ path('resend_verif') }}">renvoyer le lien d'activation</a>
</div>
</div>
{% endif %}
{# {% for messages in app.flashes %}
{% for message in messages %}
<p>{{ message|raw }}</p>
{% endfor %}
{% endfor %} #}
<div class="container body-container">
<div class="row">
<div class="col-sm-9 offset-2">
<main class="main-content">
{# {% use "bootstrap_5_layout.html.twig" %} #}
{{ include('_partials/_flash.html.twig') }}
</main>
</div>
</div>
</div>
{% block body %}{% endblock %}
{# {% set _route = app.request.get('route')}
<li class="nav-item{{ _route == '_partials' ? ' active' : '' }}">
<a class="nav-link" href="{{ path('app_accueil') }}">
<i class="fa fa-home" aria-hidden="true"></i>
{{ 'menu.homepage'|trans }}
</a>
</li>
{% if is_granted('ROLE_ADMIN') %}
<li class="nav-item">
<a class="nav-link" href="{{ path('admin_post_index') }}">
<i class="fa fa-lock" aria-hidden="true"></i>
{{ 'menu.admin'|trans }}
</a>
</li>
{% endif %}
{% endblock %}
<li class="nav-item{{ _route == 'blog_search' ? ' active' : '' }}">
<a class="nav-link" href="{{ path('blog_search') }}">
<i class="fa fa-search"></i>
{{ 'menu.search'|trans }}</a>
</li>
{% if app.user %}
<li class="nav-item dropdown">
<a href="#" class="nav-link dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false" id="user">
<i class="fa fa-user" aria-hidden="true"></i>
<span class="caret"></span>
<span class="sr-only">{{ app.user.fullname }}</span>
</a>
<div class="dropdown-menu user" role="menu" aria-labelledby="user">
<a class="dropdown-item" href="{{ path('user_edit') }}">
<i class="fa fa-edit" aria-hidden="true"></i>
{{ 'menu.user'|trans }}
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="{{ logout_path() }}">
<i class="fa fa-sign-out" aria-hidden="true"></i>
{{ 'menu.logout'|trans }}
</a>
</div>
</li>
{% endif %}
<li class="nav-item dropdown">
{% from 'default/_language_selector.html.twig' import render_language_selector %}
{{ render_language_selector() }}
</li>
</ul>
</div>
</div>
</nav> #}
{# <div id="sidebar" class="col-sm-3">
{% block sidebar %}
{{ render_esi(controller('Symfony\\Bundle\\FrameworkBundle\\Controller\\TemplateController::templateAction', {
'template': 'blog/about.html.twig',
'sharedAge': 600,
'_locale': app.request.locale
})) }}
{% endblock %}
</div>
</div> #}
{# {% endblock %} #}
{% block footer %}
<footer>
<div class="container">
<div class="row">
<div id="footer-copyright" class="col-md-6">
<p>©
{{ 'now'|date('Y') }}
- The District</p>
<p>{{ 'mit_license'|trans }}</p>
</div>
<div id="footer-resources" class="col-md-6">
<p>
<a rel="noopener noreferrer" target="_blank" href="https://twitter.com/symfony" title="Symfony on X (formerly Twitter)">
<i class="fa-brands fa-x-twitter" aria-hidden="true"></i>
</a>
<a target="_blank" href="https://symfony.com/blog/" title="Symfony Blog">
<i class="fa-solid fa-rss" aria-hidden="true"></i>
</a>
</p>
</div>
</div>
</div>
</footer>
{% endblock %}
</body>
</html> |
EVOSIM - README
Evosim - A three-dimensional, real time simulation of natural selection.
This is a proof of concept executed with the intention of realising how capable today's computing power is in simulating of 3D artificial genepools, which are likely to contain many rigidbodies.
The program is intended to be a 'toy'. It is not a scientific tool or a true reflection of evolution in the natural world.
Settings:
All settings are contained in a JSON file in "evosim_Data/settings.json".
All non-integer values must be written in the form "x.x", e.g. 3.0
There is no validation performed on these values.
Config:
population_logging - Whether you want the creature count over time to be logged to a data file
foodbit_logging - Whether you want the foodbit count over time to be logged to a data file
log_time - How often, in seconds, you want the data to be written to the data file
Camera:
sensitivity - Sensitivity of camera movement controls
invert - 1 = invert camera, 0 = don't invert camera
Environment:
tile_scale - Controls the size of the tiles on the plane the creatures live on; purely cosmetic
Ether:
total_energy - How much energy is put into the system
starting_number_foodbits - How many foodbits the simulation starts with
starting_creatures - How many creatures the simulation starts with
creature_spread - The size of the area that the initial creatures are spawned in
Foodbit:
init_energy - How many units of energy a foodbit starts with
destroy_at - How many units of energy at which a foodbit is destroyed
spore_time - How often, in seconds, is a new foodbit spawned (if enough energy)
spore_range - How far from the parent foodbit can a child spawn
wide_spread - The size of the area that the initial foodbits are spawned in
decay_amount - How many units of energy a foodbit decays by every
decay_time - How often, in seconds, does the foodbit decay
decay_rate - The probability of a foodbit decaying at decay_time
Creature:
MAX_ENERGY - The absolute maximum units of energy a creature can have
init_energy - The amount of units of energy given to the initial creatures
hunger_threshold - The energy level at which the creature becomes hungry and looks for food
line_of_sight - How far a creature can see
energy_to_offspring - The percentage of energy each creature gives to its offspring
metabolic_rate - The amount of energy subtracted from a creature every second just for existing
mate_range - The range at which one creature can mate with another
eat_range - The range at which a creature can eat a foodbit
eye_refresh_rate - How often, in seconds, a creature looks around and updates what they can see
age_sexual_maturity - The age of a creature, in seconds, at which they can mate with another creature
branch_limit - How many limbs can a creature have branching from its main body part
recurrence_limit - How many limb segments each branch can have
root:
max_root_scale {x,y,z} - The maximum size of the root body part when the initial creatures are generated
min_root_scale {x,y,z} - The minimum size of the root body part when the initial creatures are generated
limb:
max_limb_scale {x,y,z} - The maximum size of a limb segment when the initial creatures are generated
min_limb_scale {x,y,z} - The minimum size of a limb segment when the initial creatures are generated
Genitalia:
"line_length" - The length of the line when no mate is in line of sight
Genetics:
crossover_rate - The probability of each gene being crossed over with a gene of a partner
mutation_rate - The probability of each gene being mutated
mutation_factor - By how much is a gene mutated
Evosim by Craig Lomax is licensed under a Creative Commons
Attribution-NonCommercial-ShareAlike 4.0 International
License (http://creativecommons.org/licenses/by-nc-sa/4.0/). |
#include <stdio.h>
#include <string.h>
#define NAME_LENGTH 100
enum weapon { no_weapon, big_sword, little_sword, wand, fish };
enum armor { no_armor, knight_armor, mage_robes, overalls };
struct party_member {
char character_name[NAME_LENGTH];
// Gear:
enum weapon weapon;
enum armor armor;
};
void print_party_member(struct party_member member);
void swap_gear(struct party_member *member1, struct party_member *member2);
int main (void) {
struct party_member luigi;
strcpy(luigi.character_name, "Luigi");
luigi.weapon = big_sword;
luigi.armor = knight_armor;
struct party_member mario;
strcpy(mario.character_name, "Mario");
mario.weapon = no_weapon;
mario.armor = overalls;
printf("Gear before swapping:\n\n");
print_party_member(luigi);
print_party_member(mario);
printf("\n");
swap_gear(&luigi, &mario);
printf("Gear after swapping:\n\n");
print_party_member(luigi);
print_party_member(mario);
}
// Swaps the weapon and armor of member1 and member2
void swap_gear(struct party_member *member1, struct party_member *member2) {
enum armor temp_armor = member2->armor;
enum weapon temp_weapon = member2->weapon;
// member1->armor is equivalent to (*member1).armor
// This goes to the struct pointed at by member1 and accesses its 'armor'
// field
member2->armor = member1->armor;
member2->weapon = member1->weapon;
member1->armor = temp_armor;
member1->weapon = temp_weapon;
}
/****************** UNIMPORTANT: just for printing ************************/
char *get_weapon_str(enum weapon weapon) {
if (weapon == big_sword) {
return "Big sword";
} else if (weapon == little_sword) {
return "Little sword";
} else if (weapon == wand) {
return "Wand";
} else if (weapon == fish) {
return "Fish";
} else {
return "No weapon";
}
}
char *get_armor_str(enum armor armor) {
if (armor == knight_armor) {
return "Knight armor";
} else if (armor == mage_robes) {
return "Mage robes";
} else if (armor == overalls) {
return "Overalls";
} else {
return "No armor";
}
}
void print_party_member(struct party_member member) {
printf("%s\n", member.character_name);
printf("weapon: %s\n", get_weapon_str(member.weapon));
printf("armor: %s\n\n", get_armor_str(member.armor));
} |
const HttpError = require("../models/http-error");
const moment = require("moment");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const User = require("../models/user");
const getUsers = async (req, res, next) => {
let users;
try {
users = await User.find({}, "-password");
} catch (err) {
const error = new HttpError(
"Fetching users failed, please try again later.",
500
);
return next(error);
}
res.json({ users: users.map((user) => user.toObject({ getters: true })) });
};
const getSpecificUser = async (req, res, next) => {
const userId = req.params.uid;
let user;
try {
user = await User.findById(userId);
} catch (err) {
const error = new HttpError("Server error, cannot find user", 500);
return next(error);
}
if (!user) {
const error = new HttpError("Cannot find such user", 404);
return next(error);
}
res.status(201).json({ user: user.toObject({ getters: true }) });
};
const getUserQuestions = async (req, res, next) => {
const userId = req.params.uid;
let userWithQns;
try {
userWithQns = await User.findById(userId).populate("questions");
} catch (err) {
const error = new HttpError(
"Fetching questions failed, please try again later.",
500
);
return next(error);
}
if (!userWithQns) {
return next(
new HttpError("Could not find questions for the provided user id.", 404)
);
}
res.status(201).json({
qns: userWithQns.questions.map((qns) => qns.toObject({ getters: true })),
});
};
const login = async (req, res, next) => {
const { username, password } = req.body;
let user;
try {
user = await User.findOne({
username: { $regex: "^" + username + "$", $options: "im" },
});
} catch (err) {
const error = new HttpError("Server error, cannot find user", 500);
return next(error);
}
if (!user) {
const error = new HttpError(
"Invalid credentials, could not log you in.",
401
);
return next(error);
}
let isValidPassword = false;
try {
isValidPassword = await bcrypt.compare(password, user.password);
} catch (err) {
const error = new HttpError(
"Could not log you in, please check your credentials and try again.",
500
);
return next(error);
}
if (!isValidPassword) {
const error = new HttpError(
"Invalid credentials, could not log you in.",
403
);
return next(error);
}
let token;
try {
token = jwt.sign(
{ userId: user.id, username: user.username },
process.env.PRIV_KEY,
{ expiresIn: "2h" }
);
} catch (err) {
const error = new HttpError(
"Logging in failed, please try again later.",
500
);
return next(error);
}
res
.status(201)
.json({ user: user.toObject({ getters: true }), token: token });
};
const signup = async (req, res, next) => {
const { username, password, reenterpwd, avatar } = req.body;
if (password !== reenterpwd) {
const error = new HttpError("Password does not match", 404);
return next(error);
}
let existingUser;
try {
existingUser = await User.findOne({
username: { $regex: "^" + username + "$", $options: "im" },
});
} catch (err) {
const error = new HttpError(
"Signing up failed, please try again later.",
500
);
return next(error);
}
if (existingUser) {
const error = new HttpError(
"User exists already, please login instead.",
422
);
return next(error);
}
if (avatar === "") {
const error = new HttpError("Please select an Avatar", 404);
return next(error);
}
let hashedPassword;
try {
hashedPassword = await bcrypt.hash(password, 12);
} catch (err) {
const error = new HttpError(
"Could not create user, please try again.",
500
);
return next(error);
}
const createdUser = new User({
username: username,
password: hashedPassword,
created_at: moment(),
gravatar: avatar,
votes: 0,
questions: [],
answers: [],
});
try {
await createdUser.save();
} catch (err) {
const error = new HttpError("Signing up failed", 500);
return next(error);
}
let token;
try {
token = jwt.sign(
{ userId: createdUser.id, username: createdUser.username },
process.env.PRIV_KEY,
{ expiresIn: "2h" }
);
} catch (err) {
const error = new HttpError(
"Signing up failed, please try again later.",
500
);
return next(error);
}
res
.status(201)
.json({ user: createdUser.toObject({ getters: true }), token: token });
};
exports.getUsers = getUsers;
exports.getSpecificUser = getSpecificUser;
exports.getUserQuestions = getUserQuestions;
exports.login = login;
exports.signup = signup; |
//
// MainButton.swift
// fitAtStreet
//
// Created by Ruslan Sadritdinov on 25.08.2023.
//
import UIKit
final class MainButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Setup Section
private extension MainButton {
func setup() {
setupStyle()
setupShadow()
}
func setupShadow() {
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: .small, height: .small)
layer.shadowRadius = 8
layer.shadowOpacity = 0.4
clipsToBounds = true
layer.masksToBounds = false
}
func setupStyle() {
setTitleColor(.white, for: .normal)
backgroundColor = .systemBlue
titleLabel?.font = UIFont(name: "Roboto-Regular", size: 18)
layer.cornerRadius = .medium
}
}
// MARK: - Action Section
extension MainButton {
func shake() {
Vibration.error.vibrate()
let shake = CABasicAnimation(keyPath: "position")
shake.duration = 0.1
shake.repeatCount = 2
shake.autoreverses = true
let fromPoint = CGPoint(x: center.x - 8, y: center.y)
let fromValue = NSValue(cgPoint: fromPoint)
let toPoint = CGPoint(x: center.x, y: center.y)
let toValue = NSValue(cgPoint: toPoint)
shake.fromValue = fromValue
shake.toValue = toValue
layer.add(shake, forKey: "position")
}
func tap() {
Vibration.success.vibrate()
UIView.animate(withDuration: 0.15, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0.5, options: .curveEaseIn, animations: {
self.transform = CGAffineTransform(scaleX: 0.92, y: 0.92)
}) { _ in
UIView.animate(withDuration: 0.15, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 4, animations: {
self.transform = CGAffineTransform(scaleX: 1, y: 1)
} , completion: nil)
}
}
} |
import React, { useEffect, useState } from 'react';
import VoteListItemProperty from './VoteListItemProperty';
import VoteListItemName from './VoteListItemName';
import VoteListItemPeriod from './VoteListItemPeriod';
import VoteListItemProgress from './VoteListItemProgress';
import { useNavigate } from 'react-router-dom';
import { VoteListRequest } from '../../pages/VoteList';
import axios from 'axios';
import { serverurl } from '../../components/serverurl';
import { useQuery } from '@tanstack/react-query';
const VoteListItem: React.FC<VoteListRequest> = ({real_estate_name,vote_id,subscription_img_1,vote_title,vote_start_date,vote_end_date}) => {
const [voteCA,setVoteCA] = useState<string>("");
const [currentUser,setCurrentUser] = useState<string>("");
const fetchVoteCA = async () => {
const response = await axios.get(`${serverurl}/vote/vote_contract_address`,{
params: {
vote_id: `${vote_id}`
}
});
return response.data;
};
const {data,error,isLoading,isError} = useQuery({
queryKey: ["fetchVoteCA",vote_id],
queryFn: fetchVoteCA,
enabled: !!vote_id
});
useEffect(()=>{
console.log(data);
if(data){
setVoteCA(data[0].address);
}
},[data]);
useEffect(()=>{
const getWalletAccount = async () => {
const accounts = await window.ethereum.request({method:"eth_accounts"});
if(accounts.length > 0){
setCurrentUser(accounts[0]);
}
};
getWalletAccount();
},[])
const navigation = useNavigate();
const toVoteDetail = () => {
navigation(`/vote-detail/${real_estate_name}/${vote_title}`,{
state: {
real_estate_name: real_estate_name,
vote_ca: voteCA,
img: subscription_img_1,
wallet: currentUser
}
});
};
return (
<div className='w-full h-32 border-b border-slate-200 flex flex-row' onClick={toVoteDetail}>
<div className='w-[80%] h-full'>
<VoteListItemProperty real_estate_name={real_estate_name} />
<VoteListItemName vote_title={vote_title} />
<VoteListItemPeriod vote_start_date={vote_start_date} vote_end_date={vote_end_date} />
</div>
<VoteListItemProgress vote_start_date={vote_start_date} vote_end_date={vote_end_date} />
</div>
)
}
export default VoteListItem; |
---
title: "Palettes de couleurs"
format:
html: default
docx:
toc: true
number-sections: true
filters:
- lightbox
lightbox: auto
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
options(Encoding="UTF-8")
library(Statamarkdown)
stataexe <- "C:/Program Files/Stata17/StataSE-64.exe"
knitr::opts_chunk$set(engine.path=list(stata=stataexe))
```
<br>
Lorsqu’ils sont générés, les graphiques appliquent un thème/style par défaut:
- Ces thèmes sont appelés `scheme`.
- Les options de la commande graphique visent à modifier les paramètres du thème.
- Les paramètres du style/thèmes sont appliqués aux couleurs, tailles/épaisseurs, positions des éléments de texte, définitions des axes….
- Stata dispose de 5 thèmes officiels. Des thèmes externes ont été programmés et peuvent être installés. La série de commandes associées à **`grstyle`** (*Ben Jann*) permet de paramétrer très facilement un thème, a minima en 2-3 lignes avec un nombre très réduit d’arguments.
- Collection **`schemepack`** : récemment (2021), *Asjad Naqvi* a programmé une suite de thèmes à partir du paquet `grstyle`. Cette série offre une alternative très séduisante au thèmes usines vieillissants de Stata.
* Les thèmes utilisent des palettes de couleurs. Il existe 3 types de palettes selon la nature des données.
* ***Palettes qualitatives*** (variables discrètes).
* ***Palettes séquentielles*** (variables ordonnées/quantitatives).
* ***Palettes divergentes*** (variables ordonnées/quantitatives avec deux sens implicites et une valeur pivot
- Des commandes externes permettent d’augmenter le nombre de palettes mises à disposition par Stata, de les modifier ou de les créer.
- Pour la cartographie, la commande `spmap` (*Maurizio Pisatti*) intègre une quarantaine de palettes, principalement séquentielles (commande à visée cartographique).
- La librairie `brewscheme` (William Buchanan) dispose de plusieurs commandes pour générer des palettes de couleurs. Son utilisation est assez complexe.
- La commande **`colorpalette` (Benn Jann) charge plusieurs dizaines de palettes de couleurs, de tout type, permet de les modifier, d’en créer, et de les utiliser facilement dans la création de graphiques. Elle est indispensable dès lors qu’on souhaite utiliser efficacement des couleurs différentes de celles fournies par le logiciel. Cette commande, à mon sens incontournable, sera longuement traitée dans ce chapitre, ainsi que la commande `grstyle` qui reprend sa syntaxe pour générer de manière rapide un thème.
# **Les palettes usines**
Stata dispose de 5 palettes de couleurs usines qui sont associées à des thèmes graphiques. Par exemple la *palette s2* est associée au *thème s2color*.
Les palettes associées aux thèmes Stata sont de type qualitative. L’ordre d’utilisation des couleurs dans un graphique composé de plusieurs objets est pensé de tel sorte que des couleurs même type, par exemple le bleu, ne se succède pas.
{fig-align="left"}
Les numéros sur l’abscisse correspondent à l’ordre par défaut d’utilisation des couleurs.Les couleurs usines ont un nom, auquel correspond un code RGB.
{fig-align="left"}
La palette **mono** d’avère très utile pour modifier les couleurs des titres, labels, grids ou du background. Elle est ambivalente, l’ordre par défaut de la palette est plutôt qualitatif, mais le nom des couleurs correspond à une palette séquentielle appelé « grey scale » (gs# avec # allant de 0 – noir – à 16 – blanc).
{fig-align="left"}
{fig-align="left"}
*Remarque*: il est facile de générer une couleur appartenant à une palette correspondant à une échelle de gris: les trois valeurs du code RGB étant identique (compris entre 0 et 255).
<br>
On est vite limité avec les palettes usines de Stata. Malgré les efforts de plusieurs utilisateurs pour augmenter leur nombre (M.Pissatti, F.Briatte, D.Bischoff…), la commande **`colorpalette`** (Ben Jann) a récemment permis de démultiplier quasiment à l’infini les possibilités en terme de manipulation des couleurs.
# **Colorpalette (Ben Jann)**
***Installation***
```{stata, eval=FALSE}
ssc install palettes [, replace force]
ssc install colrspace [, replace force]
```
***Syntaxe générique***
<div class="grey">
```{stata, eval=FALSE}
colorpalette nom_palette/collection [, nom_sous_palette] [options]
```
*Remarque*: le nom d’une palette peut être une couleur ou une série de couleur
```{stata, eval=FALSE}
* Charge et affiche la palette s1 de Stata
colorpalette s1
* Charge et affiche la palette hue
colorpalette hue
* Charge et affiche la palette viridis
colorpalette viridis
* Charge et affiche la palette summer de la collection matplotlib
colorpalette matplotlib, summer
* Charge et affiche une palette composée des couleur bleu et rouge
colorpalette blue red
```
Pour visualiser les palettes disponibles : **`help colorpalette`**.
**Exemple : la palette plasma**
- Appartient à la ***collection viridis**, palettes Python visant à remplacer les palettes de la *collection matplotlib* (intégrée à `colorpalette`)
- Longueur par défaut : 15 couleurs
- Type : séquentielle
```{stata, eval=FALSE}
colorpalette plasma
```
{fig-align="left"}
<br>
## **Principales options et altération d’une palette**
**Modifier la taille de la palette: `n(#)`**
Important car la réduction de la taille pour certaines palettes ne consiste pas à prendre les # premiers éléments de la palette par défaut (cf palettes *hu*e ou *viridis*), mais forcer une palette non qualitative, donc plutôt séquentielle, à produire une palette réduite avec des types de couleurs contrastées plutôt qualitative.
**Modifier l’intensité ou l’opacité : intensity(#), opacity(#) et ipolate(#)**
- On peut modifier l’intensité (saturation) ou l’opacité d’une palette avec **`intensity(#)` ou **`intensity(numlist)`** et **`opacity(#)`**.
- On peut créer une palette séquentielle à partir d’une couleur de départ avec **`intensity(#1(delta)#2)`**.
- On peut créer une palette divergente avec des couleurs de départ, d’arrivée et de transition avec **`ipolate(#)`**.
**Select – reverse - nograph**
- On peut sélectionner des couleurs d’une palette avec **`select(numlist)`**. L’option autorise la répétition de couleurs, utile lorsque plusieurs objets graphiques partage une même couleur au sein d’un graphique (exemple nuages de point et courbes pour différentes valeurs d’une variable additionnelle : voir exemple avec `grstyle`).
- On peut inverser l'ordre des couleurs de la palette: **`reverse`**.
- Ne pas afficher la palette: **`nograph`** [voir *utilisation de colorpalette pour générer un graphique*]. Après avoir séléctionné les couleurs, à utiliser systématiquement pour charger la palette avant son utilisation dans un graphique. Cela réduit considérablement le temps d’exécution.
***Création d’une palette de 4 couleurs***
```{stata, eval=FALSE}
colorpalette plasma, n(4)
```
{fig-align="left"}
***Répétition d’une liste de couleur avec select(numlist)***
```{stata, eval=FALSE}
colorpalette plasma, select(1 8 15 1 8 15)
```
{width=60%, fig-align="left"}
***Création d'une palette séquentielle avec augmentation de l'intensité***
A partir de la couleur 3 (RGB= 237,121,83), création d’une palette sequentielle d’une longueur de 15, allant de "237,121,83*0" (proche blanc) à "237,121,83*15".
```{stata, eval=FALSE}
colorpalette "237 121 83", intensity(0(.1)1.5)
```
{width=60%, fig-align="left"}
***Création d'une palette séquentielle avec augmentation de l'intensité***
Création d’une palette séquentielle d’une longueur 15 allant de la couleur 1 à la couleur 3 de la palette plasma à 4 couleurs.
```{stata, eval=FALSE}
colorpalette "13 8 135" "237 121 83", ipolate(15)
```
{width=60%, fig-align="left"}
Si on ajoute la couleur 2 de la palette d’origine comme couleur de transition
```{stata, eval=FALSE}
colorpalette "13 8 135" "156 23 158" "237 121 83", ipolate(15)
```
{width=60%, fig-align="left"}
Si on utilise le blanc comme couleur de transition, on obtient une palette divergente.
```{stata, eval=FALSE}
colorpalette "13 8 135" white "237 121 83", ipolate(15)
```
{width=60%, fig-align="left"}
**Créer, enregistrer et charger sa propre palette**
`colorpalette` permet de conserver en mémoire sa propre palette, en la générant dans un .ado (voir la fin du chapitre dédié aux macros) ou dans le programme principal. Par exemple avec la palette issue du premier exemple (palette plasma à 4 couleur).
```{stata, eval=FALSE}
* Création de la palette mypal
capt program drop colorpalette_mypal
program colorpalette_mypal
c_local P 13 8 135, 156 23 158, 237 121 83, 240 249 33
c_local class qualitative
end
* On charge la palette avec la commande colorpalette_mypal
colorpalette_mypal
* On affiche la palette my_pal
colorpalette my_pal
```
### **Utilisation de colorpalette pour générer un graphique**
On remarque, avec return list, que la commande génère une liste de macros qui enregistre les codes RGB des couleurs de la palette.
- la macro `r(p)` permet d’utiliser les couleurs de la palette dans un graphique à un seul bloc d’éléments.
- les macros `r(p#)` permettent d’utiliser les couleurs dans un graphique composé de plusieurs éléments.
La commande `colorpalette` n’est qu’un générateur de couleurs qui renvoie une liste de codes RGB sous forme de macros. Si pour des graphiques simples la technique du « copié/collé » de codes RGB reste possible, l’utilisation des macros va être une nouvelle fois fortement recommandée. On peut déjà néanmoins indiquer qu’avec le générateur de thème **`grstyle` (voir la section suivante), également programmé par *B.Jann*, une sélection de couleurs pourra être directement intégrée à un graphique sans manipulation supplémentaire.
**Macros générées par `colorpalette`**
On va partir de la palette plasma précédente avec 4 couleurs et un % d’opacité de 80%. Avec return list, on affiche sous forme de macros la liste des codes RGB des couleurs
```{stata, eval=FALSE}
colorpalette plasma, n(4) opacity(80) nograph
return list
/*
scalars:
r(n) = 4
macros:
r(ptype) : "color"
r(pname) : "plasma"
r(pnote) : "plasma colormap from matplotlib.org"
r(psource) : "https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/_cm_listed.py"
r(pclass) : "sequential"
r(p) : ""13 8 135%80" "156 23 158%80" "237 121 83%80" "240 249 33%80""
r(p4) : "240 249 33%80"
r(p3) : "237 121 83%80"
r(p2) : "156 23 158%80"
r(p1) : "13 8 135%80"
*/
```
La liste renvoie la macro r(p) qui liste l’ensemble des codes couleurs. Cette macro est utilisée pour les graphiques avec un seul objet qui liste pour l’axe des ordonnées une série de variables.
***Exemple***
```{stata, eval=FALSE}
sysuse uslifeexp
colorpalette plasma, n(4) opacity(80) nograph
tw line le_wmale le_wfemale le_bmale le_bfemale year, lc(`r(p)')
```
La macro `r(p)` a déjà deux doubles quotes, on ne doit pas enfermer cette liste par "".
La liste de macros `r(p#)` renvoie le code couleur de chaque élément de la palette, ici `r(p1)` à `r(p4)`. Ces macros sont utilisées pour les graphiques composés de plusieurs objets. Entrée directement dans la syntaxe d’un graphique, ces macros devront être enfermées dans des doubles quotes.
***Exemple***
On va afficher un graphique avec 4 densités sous forme d’aires générées aléatoirement. De nouveau on utilisera la palette plasma réduite à 4 couleurs et 80% d’opacité.
*Données*
```{stata, eval=FALSE}
clear
set obs 1000
gen y1= rnormal(0,1.5)
gen y2= rnormal(3, 2)
gen y3= rnormal(6, 3)
gen y4= rnormal(9, 4)
forv i=1/4 {
kdensity y`i', n(500) gen(x`i' d`i') nograph
}
```
*Graphique* (sans macros empilées pour faciliter la lisibilité du programme)
```{stata, eval=FALSE}
Colorpalette plasma , n(4) opacity(80) nograph
local ops lc(black) lw(*.5)
#delimit ;
tw line d1 x1, recast(area) `ops' fc("`r(p1)'")
|| line d2 x2, recast(area) `ops' fc("`r(p2)'")
|| line d3 x3, recast(area) `ops' fc("`r(p3)'")
|| line d4 x4, recast(area) `ops' fc("`r(p4)'")
||, legend(order(1 "r(p1)" 2 "r(p2)" 3 "r(p3)" 4 "r(p4)") pos(11) row(1) region(color(%0)))
;
```
{width=60%, fig-align="left"}
Sans modifier la syntaxe du graphique, on peut alors simplement changer de palette, en modifiant son nom et/ou en modifiant une ou plusieurs options comme l’opacité.
***Exemple***: *palette winter* de la collection *matplotlib*, avec 50% d’opacité et en inversant l’ordre des couleurs.
```{stata, eval=FALSE}
colorpalette winter , matplotlib n(4) opacity(80) nograph
local ops lc(black) lw(*.5)
#delimit ;
tw line d1 x1, recast(area) `ops' fc("`r(p1)'")
|| line d2 x2, recast(area) `ops' fc("`r(p2)'")
|| line d3 x3, recast(area) `ops' fc("`r(p3)'")
|| line d4 x4, recast(area) `ops' fc("`r(p4)'")
||, legend(order(1 "`r(p1)'" 2 "`r(p2)'" 3 "`r(p3)'" 4 "`r(p4)'")
pos(11) row(1) region(color(%0)))
;
```
*Remarque : en utilisant les macros dans la légende, on a affiché les codes couleurs*
{width=60%, fig-align="left"}
# **Exemples de palettes**
Sur le même principe que les deux graphiques précédents mais avec 6 éléments, on a mis à disposition une petite commande, **`testpal`**, qui permet de tester le rendu d’un graphique. La commande reporte 6 objets graphiques sous la forme de densités représentées par des aires et par des groupes. Les deux graphiques de la première colonne sont sur un fond blanc, ceux de la deuxième colonne sont sur un fond paramétrable (palette gs) par défaut très sombre.
***Installation***
```{stata, eval=FALSE}
net install testpal, from("https://raw.githubusercontent.com/mthevenin/stata_fr/master/ado/testpal/") replace
```
***Syntaxe***
<div class="grey">
```{stata, eval=FALSE}
testpal nom_palette , [rev] [op(#)] [bf(#)]
```
- `rev`: inverse l'ordre des couleurs de la palette.
- `op(#)`: modifie le pourcentage d'opacité des couleurs. Par défaut 100% (op(100)). # est compris entre 0+ et 100.
- `bf(#)`: permet de modifier la clarté des graphiques de la seconde colonne (blanc pour la première). # est une valeur comprise entre 1 (noir) et 14 (presque blanc).
***Exemple avec la palette qualitative burd (François Briatte)***
```{stata, eval=FALSE}
testpal burd, rev op(100) bf(5)
```
{width=60%, fig-align="left"}
Pour les quelques palettes populaires qui vont être rapidement présentées, les options de la commande `testpal` n’ont pas été modifiées. Le nom de la palette est donné par le titre du graphique.
<br>
## **Palettes qualitatives**
**Tableau**
**https://www.tableau.com/about/blog/2016/7/colors-upgrade-tableau-10-56782**
{width=60%, fig-align="left"}
**HUE**
- Il s’agit de la palette par défaut de ggplot2 (R)
- De plus en plus remplacée par la palette Viridis (voir plus loin)
{width=60%, fig-align="left"}
## **Palettes séquentielles**
- Utilisées massivement en cartographie et plus généralement pour représenter des fréquences (graphique type barre) ou des valeurs ordonnées
- Couleurs allant du plus clair au plus foncé (ou inversement).
– Modification de l’intensité d’une couleur.
– Une ou plusieurs gammes de couleurs : par exemples du jaune au rouge, du jaune au bleu…
En réduisant la taille de certaines palettes séquentielles ou divergentes, on peut obtenir une palette plutôt qualitative. C’est le cas de la collection, très en vogue, *Viridis*.
**Collection viridis**
- La palette **Viridis** et les ses palettes associées (plasma, magma, cividis...) est la palette "star" du moment.
- Développée pour Python pour donner une palette alternative à *Matplotlib*, elle est devenue la palette par défaut de la librairie graphique
- Avantages:
- Même rendu, ou très proche, des couleurs sur toutes les parties d’un écran (uniformité).
- Différences de couleurs maintenue à l’impression n&b.
- Gère la plupart des formes de daltonisme.
- Limites : pour les courbes, un fond blanc ou très clair ou un fond noir ou très foncé, les couleurs aux extrémités passent difficilement. Prévoir un fond gris moyen ou ne pas sélectionner les couleurs aux extrémités de la palette.
- Les autres palettes : plasma est également très utilisée, en particulier pour le remplissage de surface (aire).
- Plus d’infos : **https://rtask.thinkr.fr/fr/ggplot2-welcome-viridis/**
{width=60%, fig-align="left"}
{width=60%, fig-align="left"}
**Collection colorbrewer**
Très populaire en cartographie: **https://colorbrewer2.org/#type=sequential&scheme=BuGn&n=3**
{width=60%, fig-align="left"}
On présentera enfin une seule palette de type divergente, issue de cette collection, la palette *spectral*.
{width=60%, fig-align="left"}
<br> |
<!DOCTYPE html>
<html>
<head>
<title>R7b</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
<%= javascript_include_tag "application", "data-turbo-track": "reload", defer: true %>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<style>
.turbo-progress-bar {
height: 5px;
background-color: gray;
}
</style>
</head>
<body>
<ssscript src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></ssscript>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
<%= render current_user ? 'layouts/navbar_signed_in' : 'layouts/navbar' %>
<div aria-live="polite" aria-atomic="true" class="position-relative">
<!-- Position it: -->
<!-- - `.toast-container` for spacing between toasts -->
<!-- - `top-0` & `end-0` to position the toasts in the upper right corner -->
<!-- - `.p-3` to prevent the toasts from sticking to the edge of the container -->
<div id="toast-container" class="toast-container position-fixed top-0 end-0 p-3 pt-4 mt-5">
<!-- Then put toasts within -->
<div class="toast" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="30000" data-controller="hello">
<div class="toast-header">
<img src="..." class="rounded me-2" alt="...">
<strong class="me-auto">Bootstrap</strong>
<small class="text-muted">just now</small>
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
<div class="toast-body">
See? Just like this.
</div>
</div>
<div class="toast" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="30000">
<div class="toast-header">
<img src="..." class="rounded me-2" alt="...">
<strong class="me-auto">Bootstrap</strong>
<small class="text-muted">2 seconds ago</small>
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
<div class="toast-body">
Heads up, toasts will stack automatically
</div>
</div>
</div>
</div>
<div class="container">
<% if notice %><p class="alert alert-success"><%= notice %></p><% end %>
<% if alert %><p class="alert alert-danger"><%= alert %></p><% end %>
<%= yield %>
</div>
<% render 'layouts/footer' %>
</body>
</html> |
// Copyright 2023 The glassdb 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 middleware
import (
"testing"
"time"
"github.com/jonboulle/clockwork"
"github.com/stretchr/testify/assert"
)
func TestRateLimiter(t *testing.T) {
clock := clockwork.NewFakeClock()
rt := rateLimiter{
tokensPerSec: 1,
clock: clock,
buckets: make(map[string]bucketState),
}
begin := clock.Now()
assert.True(t, rt.TryAcquireToken("k"))
clock.Advance(100 * time.Millisecond)
assert.True(t, rt.TryAcquireToken("k"))
clock.Advance(100 * time.Millisecond)
assert.True(t, rt.TryAcquireToken("k"))
clock.Advance(700 * time.Millisecond)
assert.True(t, rt.TryAcquireToken("k"))
clock.Advance(150 * time.Millisecond)
// Here 1050ms passed.
// We were able to sneak in 3 extra requests, so we should be rejected for
// around 4 seconds.
for clock.Now().Sub(begin) < 4*time.Second {
assert.False(t, rt.TryAcquireToken("k"), "elapsed: %v", clock.Now().Sub(begin))
clock.Advance(250 * time.Millisecond)
}
// We can sneak in more requests.
for i := 0; i < 5; i++ {
assert.True(t, rt.TryAcquireToken("k"), "i: %d", i)
}
clock.Advance(time.Second)
begin = clock.Now()
// And now we should be blocked again for 5 seconds.
for clock.Now().Sub(begin) < 4*time.Second {
assert.False(t, rt.TryAcquireToken("k"), "elapsed: %v", clock.Now().Sub(begin))
clock.Advance(250 * time.Millisecond)
}
assert.True(t, rt.TryAcquireToken("k"))
} |
import * as React from 'react';
import './TournamentsPage.scss';
import { inject, observer } from 'mobx-react';
import { StoreNames } from '../../stores/Store';
import { UserStore } from '../../stores/UserStore';
import { Tournament } from 'models/Tournament';
import TournamentsTable from './TournamentsTable/TournamentsTable';
import AddTournamentForm from './TournamentForm/AddTournamentForm';
import Header from 'sharedComponents/header/Header';
import RoundedButton from 'sharedComponents/roundedButton/RoundedButton';
import { TournamentService } from 'service/TournamentService';
interface State {
tournaments: Tournament[];
displayForm: boolean;
}
interface Props {}
@inject(StoreNames.UserStore)
@observer
export default class TournamentsPage extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
tournaments: [],
displayForm: false,
};
}
private tournamentService: TournamentService = new TournamentService();
get userStore() {
return this.props[StoreNames.UserStore] as UserStore;
}
componentDidMount = async () => {
const tournaments: Tournament[] = await this.tournamentService.getTournaments();
this.setState({ tournaments });
};
toggleForm = (): void => {
this.setState({ displayForm: !this.state.displayForm });
};
public render() {
const { displayForm, tournaments } = this.state;
return (
<div className={classNames.containerStyle}>
<Header />
<div className={classNames.pageStyle}>
<h1>Tournaments {displayForm && `/ Add`}</h1>
{displayForm ? (
<AddTournamentForm toggleShowForm={this.toggleForm} />
) : (
<>
<RoundedButton
className={classNames.addButton}
handleClick={this.toggleForm}
>
Add Tournament
</RoundedButton>
<TournamentsTable tournaments={tournaments} />
</>
)}
</div>
</div>
);
}
}
const classNames = {
containerStyle: 'tournaments-page-container',
pageStyle: 'tournaments-page',
addButton: 'add-tournament-button',
}; |
module ourtime
import time
// const (
// numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
// letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
// 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
// months = {
// 'january': 1
// 'february': 2
// 'march': 3
// 'april': 4
// 'may': 5
// 'june': 6
// 'july': 7
// 'august': 8
// 'september': 9
// 'october': 10
// 'november': 11
// 'december': 12
// }
// )
fn parse(timestr string) !i64 {
trimmed := timestr.trim_space()
if trimmed == '' {
n := now()
time_unix := n.unix_time()
return time_unix
}
mut relative_bool := false
if trimmed.starts_with('+') || trimmed.starts_with('-') {
relative_bool = true
}
if relative_bool == true {
time_unix := get_unix_from_relative(trimmed) or {
return error('Failed to get unix from relative time: ${err}')
}
return time_unix
} else {
time_unix := get_unix_from_absolute(trimmed) or {
return error('Failed to get unix from absolute time: ${err}')
}
return time_unix
}
return error('bug')
}
pub fn get_unix_from_relative(timestr string) !i64 {
// removes all spaces from the string
mut full_exp := timestr.replace(' ', '')
// If input is empty or contains just a 0
if full_exp == '' || full_exp.trim(' ') == '0' {
time_unix := time.now().unix_time()
return time_unix
}
// duplicates the + and - signs
full_exp = full_exp.replace('+', '£+')
full_exp = full_exp.replace('-', '£-')
// create an array of periods
mut exps := full_exp.split_any('£')
exps = exps.filter(it.len > 0)
mut total := 0
for mut exp in exps {
mut mult := 0
if exp.ends_with('s') {
mult = 1
} else if exp.ends_with('m') {
mult = 60
} else if exp.ends_with('h') {
mult = 60 * 60
} else if exp.ends_with('d') {
mult = 60 * 60 * 24
} else if exp.ends_with('w') {
mult = 60 * 60 * 24 * 7
} else if exp.ends_with('M') {
mult = 60 * 60 * 24 * 30
} else if exp.ends_with('Q') {
mult = 60 * 60 * 24 * 30 * 3
} else if exp.ends_with('Y') {
mult = 60 * 60 * 24 * 365
} else {
return error('could not parse time suffix for: ${exp}')
}
if exp.starts_with('-') {
mult *= -1
}
// remove +/- and period
exp = exp[1..(exp.len - 1)]
// multiplies the value by the multiplier
exp_int := exp.int() * mult
total += exp_int
}
time_unix := total + time.now().unix_time()
return time_unix
}
pub fn get_unix_from_absolute(timestr_ string) !i64 {
timestr := timestr_.trim_space()
split_time_hour := timestr.split(' ')
if split_time_hour.len > 2 {
return error('format of date/time not correct: ${timestr_}')
}
mut datepart := ''
mut timepart := ''
if split_time_hour.len == 2 {
// there is a date and time part
datepart = split_time_hour[0]
timepart = split_time_hour[1]
} else if split_time_hour.len == 2 {
datepart = split_time_hour[0]
} else {
return error("format of date/time not correct: '${timestr_}'")
}
datepart = datepart.replace('/', '-')
if timepart.contains('-') || timepart.contains('/') {
return error("format of date/time not correct, no - or / in time: '${timestr_}'")
}
split := datepart.split(':')
if split.len != 3 {
return error("unrecognized dat format, time must either be YYYY/MM/DD or DD/MM/YYYY, or : in stead of /. Input was:'${timestr_}'")
}
if split[2].len == 4 {
datepart = split.reverse().join('-')
} else if !(split[0].len == 4) {
return error("unrecognized time format, time must either be YYYY/MM/DD or DD/MM/YYYY, or : in stead of /. Input was:'${timestr_}'")
}
timparts := timepart.split(':')
if timparts.len == 2 {
timepart = '${timepart}:00'
} else if timparts.len == 1 {
timepart = '${timepart}:00:00'
} else if timparts.len == 0 {
timepart = '00:00:00'
} else {
return error("format of date/time not correct, in time part: '${timestr_}'")
}
full_string := '${datepart} ${timepart}'
time_struct := time.parse(full_string) or {
return error("could not parse date/time string '${timestr_}': ${err}")
}
return time_struct.unix_time()
} |
import {
Body,
Controller,
Get,
HttpStatus,
Post,
Response,
UseGuards,
} from '@nestjs/common';
import { AuthService } from 'src/auth/auth.service';
import { AuthDto } from './auth-dto/auth.dto';
import { JwtService } from '@nestjs/jwt';
import { JwtAuthGuard } from './auth.guard';
@Controller('auth')
export class AuthController {
constructor(
private readonly authService: AuthService,
private jwtService: JwtService,
) {}
@Post('login')
async login(@Body() authDto: AuthDto, @Response() res) {
try {
if (!authDto.email) {
return await res.status(HttpStatus.BAD_REQUEST).json({
message: 'Enter your email !',
});
} else if (!authDto.password) {
return await res.status(HttpStatus.BAD_REQUEST).json({
message: 'Enter your Password !',
});
} else {
const user = await this.authService.login(authDto);
if (user != null) {
const payload = { user: user };
const jwt = await this.jwtService.signAsync(payload);
return res.status(HttpStatus.OK).json({
token: jwt,
user,
});
} else {
return res.status(HttpStatus.NOT_FOUND).json({
message: 'User not found ',
});
}
}
} catch (error) {
console.log(error);
}
}
@UseGuards(JwtAuthGuard)
@Get('profile/:id')
async getProfile(id: number) {
try {
const user = await this.authService.getUserData(id);
return user;
} catch (error) {
console.log(error);
}
}
} |
import { Route } from "@/interfaces/router";
import { getMetadataTitle } from "@/utils/core";
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import Link from "next/link";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: getMetadataTitle(),
description: "A Pokémon TCG fansite",
};
const routes: Route[] = [
{
label: "Home",
uri: "/",
},
{
label: "About",
uri: "/about",
},
{
label: "Writings",
uri: "/writings",
},
];
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={inter.className}>
<nav>
{routes.map((route, routeIndex) => (
<Link key={routeIndex} href={route.uri}>
{route.label}
</Link>
))}
</nav>
{children}
</body>
</html>
);
} |
# Conversational Search
by @howethomas (https://github.com/howethomas)
This Streamlit app searches an ElasticSearch server for simple text based search
of anything that would appear in a vCon: names of agents, customers, phone numbers,
stores - anything contained within the parties, dialogs, attachments and analysis.
The upper left has a sidebar for advanced options, currently to restrict viewed results
to those containing summaries, and the number of results to return.
## Features
- Search the vCon index by passing any search terms
- Retrieve matching vCons sorted by relevance
- Display key metadata like date, duration, dealer name, etc.
- Show highlighted matches in the conversation
- Listen to audio recordings of the conversations
- Download the full vCon JSON
- Configure advanced options like number of results and summary filter
## Usage
The script is meant to be run in Streamlit. Simply enter your search terms in the input box.
Advanced configuration options are available in the left sidebar:
- Only show results with a summary
- Number of results to display
## Implementation
The script uses the official Elasticsearch Python client to query the index.
It connects to a hosted Elasticsearch instance defined in the Streamlit secrets.
The index contains vCon documents - the open conversation standard.
Results are parsed into Vcon objects to extract key fields and build the UI.
## Deployment
This script is designed to run on Streamlit Cloud.
The Elasticsearch credentials need to be configured in the Streamlit secrets:
- `ELASTIC_SEARCH_CLOUD_ID`
- `ELASTIC_SEARCH_API_KEY`
Other secrets:
- `CONV_DETAIL_URL` - Base URL for the vCon detail pages
## Future Work
Some ideas for enhancing the search:
- Suggest search terms as the user types
- Support more advanced query syntax and operators
- Add filters for metadata fields like date, team, etc
- Page through results
- Build an analytics dashboard for search usage
Let me know if you have any other questions! |
use self::{meta::AssetLoaderMetas, observers::on_import_folder};
use crate::{
config::AssetConfig,
database::{AssetDatabase, LoadState},
loader::AssetLoader,
storage::{AssetSettings, Assets},
Asset, AssetId, AssetPath, Settings,
};
use rouge_ecs::{
macros::Resource,
observer::{Action, Actions, Observers},
process::{Process, StartProcess},
World,
};
use rouge_game::game::GameEnvironment;
use std::path::{Path, PathBuf};
pub mod meta;
pub mod observers;
#[derive(Clone, Resource)]
pub struct MainWorldActions(Actions);
impl MainWorldActions {
pub fn new(actions: Actions) -> Self {
MainWorldActions(actions)
}
}
impl std::ops::Deref for MainWorldActions {
type Target = Actions;
fn deref(&self) -> &Actions {
&self.0
}
}
impl std::ops::DerefMut for MainWorldActions {
fn deref_mut(&mut self) -> &mut Actions {
&mut self.0
}
}
pub struct ImportAssets<A: Asset> {
paths: Vec<PathBuf>,
_marker: std::marker::PhantomData<A>,
}
impl<A: Asset> ImportAssets<A> {
pub fn new(paths: Vec<PathBuf>) -> Self {
Self {
paths,
_marker: std::marker::PhantomData,
}
}
}
impl<A: Asset> Action for ImportAssets<A> {
type Output = Vec<PathBuf>;
fn execute(&mut self, _: &mut rouge_ecs::World) -> Self::Output {
std::mem::take(&mut self.paths)
}
}
pub struct ImportFolder {
path: PathBuf,
}
impl ImportFolder {
pub fn new(path: PathBuf) -> Self {
Self { path }
}
}
impl Action for ImportFolder {
type Output = PathBuf;
fn execute(&mut self, _: &mut rouge_ecs::World) -> Self::Output {
std::mem::take(&mut self.path)
}
}
pub struct LoadAsset<A: Asset> {
path: AssetPath,
_marker: std::marker::PhantomData<A>,
}
impl<A: Asset> LoadAsset<A> {
pub fn new(path: impl Into<AssetPath>) -> Self {
Self {
path: path.into(),
_marker: std::marker::PhantomData,
}
}
pub fn process(path: impl Into<AssetPath>) -> StartProcess {
StartProcess::new(LoadProcess::<A>::new(path.into()))
}
}
impl<A: Asset> Action for LoadAsset<A> {
type Output = AssetId;
fn skip(&self, world: &rouge_ecs::World) -> bool {
match &self.path {
AssetPath::Id(id) => {
let state = world.resource::<AssetDatabase>().load_state(*id);
state == LoadState::Loaded || state == LoadState::Loading
}
AssetPath::Path(path) => {
let db = world.resource::<AssetDatabase>();
match db.id_from_path(Path::new(path)) {
Some(id) => {
let state = db.load_state(id);
state == LoadState::Loaded || state == LoadState::Loading
}
None => false,
}
}
}
}
fn execute(&mut self, world: &mut rouge_ecs::World) -> Self::Output {
match &self.path {
AssetPath::Id(id) => *id,
AssetPath::Path(path) => {
let db = world.resource_mut::<AssetDatabase>();
match db.id_from_path(Path::new(path)) {
Some(id) => id,
None => {
let config = world.resource::<AssetConfig>();
let full_path = config.asset_path().join(path);
let info_path = config.asset_info_path(&full_path);
let info = config
.load_asset_info::<A>(&info_path)
.expect("Failed to load asset info.");
db.set_path_id(info.id(), &path);
info.id()
}
}
}
}
}
}
pub struct UnloadAsset<A: Asset> {
path: AssetPath,
_marker: std::marker::PhantomData<A>,
}
impl<A: Asset> UnloadAsset<A> {
pub fn new(path: AssetPath) -> Self {
Self {
path,
_marker: std::marker::PhantomData,
}
}
}
impl<A: Asset> Action for UnloadAsset<A> {
type Output = AssetId;
fn skip(&self, world: &rouge_ecs::World) -> bool {
match &self.path {
AssetPath::Id(id) => {
let state = world.resource::<AssetDatabase>().load_state(*id);
state == LoadState::Unloaded || state == LoadState::Unloading
}
AssetPath::Path(path) => {
let db = world.resource::<AssetDatabase>();
match db.id_from_path(Path::new(path)) {
Some(id) => {
let state = db.load_state(id);
state == LoadState::Unloaded || state == LoadState::Unloading
}
None => true,
}
}
}
}
fn execute(&mut self, world: &mut rouge_ecs::World) -> Self::Output {
match &self.path {
AssetPath::Id(id) => *id,
AssetPath::Path(path) => {
let db = world.resource_mut::<AssetDatabase>();
match db.id_from_path(Path::new(path)) {
Some(id) => id,
None => panic!("Failed to find asset id from path."),
}
}
}
}
}
pub struct ProcessAsset<A: Asset> {
id: AssetId,
_marker: std::marker::PhantomData<A>,
}
impl<A: Asset> ProcessAsset<A> {
pub fn new(id: AssetId) -> Self {
Self {
id,
_marker: std::marker::PhantomData,
}
}
}
impl<A: Asset> Action for ProcessAsset<A> {
type Output = AssetId;
fn skip(&self, world: &rouge_ecs::World) -> bool {
let db = world.resource::<AssetDatabase>();
let state = db.load_state(self.id);
state != LoadState::Loaded
}
fn execute(&mut self, _: &mut rouge_ecs::World) -> Self::Output {
self.id
}
}
pub struct AssetLoaded<A: Asset> {
id: AssetId,
asset: Option<A>,
}
impl<A: Asset> AssetLoaded<A> {
pub fn new(id: AssetId, asset: A) -> Self {
Self {
id,
asset: Some(asset),
}
}
}
impl<A: Asset> Action for AssetLoaded<A> {
type Output = AssetId;
fn skip(&self, world: &World) -> bool {
world.resource::<Assets<A>>().contains(&self.id)
}
fn execute(&mut self, world: &mut rouge_ecs::World) -> Self::Output {
world
.resource_mut::<Assets<A>>()
.insert(self.id, self.asset.take().unwrap());
self.id
}
}
pub struct SettingsLoaded<S: Settings> {
id: AssetId,
settings: Option<S>,
}
impl<S: Settings> SettingsLoaded<S> {
pub fn new(id: AssetId, settings: S) -> Self {
Self {
id,
settings: Some(settings),
}
}
}
impl<S: Settings> Action for SettingsLoaded<S> {
type Output = AssetId;
fn skip(&self, world: &World) -> bool {
world.resource::<AssetSettings<S>>().contains(&self.id)
}
fn execute(&mut self, world: &mut rouge_ecs::World) -> Self::Output {
world
.resource_mut::<AssetSettings<S>>()
.insert(self.id, self.settings.take().unwrap());
self.id
}
}
pub struct LoadProcess<A: Asset> {
action: Option<LoadAsset<A>>,
_ty: std::marker::PhantomData<A>,
}
impl<A: Asset> LoadProcess<A> {
pub fn new(path: impl Into<AssetPath>) -> Self {
LoadProcess {
action: Some(LoadAsset::new(path)),
_ty: std::marker::PhantomData,
}
}
}
impl<A: Asset> Process for LoadProcess<A> {
fn init(&mut self, main: &mut World, sub: &mut World) {
let main_actions = MainWorldActions::new(main.actions().clone());
let metas = main.resource::<AssetLoaderMetas>();
for (_, meta) in metas.iter() {
meta.add_on_import_observer(sub);
meta.add_on_load_observer(sub);
meta.add_on_unload_observer(sub);
meta.add_on_process_observer(sub);
meta.clone_cacher(main, sub);
}
sub.add_resource(metas.clone());
sub.add_resource(main_actions);
sub.add_resource(main.resource::<AssetDatabase>().clone());
sub.add_resource(main.resource::<GameEnvironment>().clone());
sub.add_resource(main.resource::<AssetConfig>().clone());
sub.actions_mut().add(self.action.take().unwrap())
}
fn execute(&mut self, world: &mut World) {
while !world.resource::<AssetDatabase>().is_imported()
&& world.resource::<GameEnvironment>().is_development()
{}
world.flush();
}
}
pub struct ImportProcess {
paths: Vec<PathBuf>,
}
impl ImportProcess {
pub fn new(paths: Vec<PathBuf>) -> Self {
Self { paths }
}
}
impl Process for ImportProcess {
fn init(&mut self, main: &mut World, sub: &mut World) {
let main_actions = MainWorldActions::new(main.actions().clone());
let metas = main.resource::<AssetLoaderMetas>();
for (_, meta) in metas.iter() {
meta.add_on_import_observer(sub);
meta.add_on_load_observer(sub);
meta.add_on_unload_observer(sub);
meta.add_on_process_observer(sub);
meta.clone_cacher(main, sub);
}
sub.add_resource(main_actions);
sub.add_resource(metas.clone());
sub.add_resource(main.resource::<AssetDatabase>().clone());
sub.add_resource(main.resource::<GameEnvironment>().clone());
sub.add_resource(main.resource::<AssetConfig>().clone());
sub.add_observers(Observers::<ImportFolder>::new().add_system(on_import_folder));
for path in &self.paths {
sub.actions_mut().add(ImportFolder::new(path.clone()));
}
}
fn execute(&mut self, world: &mut World) {
world.flush();
world.resource_mut::<AssetDatabase>().set_imported();
}
} |
import 'package:flutter/material.dart';
class Input extends StatefulWidget {
final bool showLastIcon;
final String placeholder;
final bool valid;
final Function(String text) onChanged;
const Input({Key? key, this.showLastIcon = false, required this.placeholder,this.valid=true, required this.onChanged}) : super(key: key);
@override
_InputState createState() => _InputState();
}
class _InputState extends State<Input> {
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.fromLTRB(15, 0, 25, 20),
child: TextField(
style: TextStyle(
fontSize: 12.0,
height:2,
color: Colors.black
),
onChanged: (text) => widget.onChanged(text),
decoration: InputDecoration(
errorText:widget.valid?null: "This text must not be empty",
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.grey.shade200),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.grey.shade200),
),
isDense: true,
contentPadding: const EdgeInsets.symmetric(horizontal: 0, vertical: 0),
labelText: widget.placeholder,
labelStyle: new TextStyle(
fontSize: 12.0,
),
floatingLabelBehavior: FloatingLabelBehavior.never,
prefixIcon: IconButton(
onPressed: () {
print('search button pressed');
},
icon: widget.placeholder == "First name" ||
widget.placeholder == "Last name"
? const Icon(Icons.person_outline,color: Colors.grey,size: 20,)
: (widget.placeholder == "E-mail"
? const Icon(Icons.email_outlined,color: Colors.grey,size: 20,)
: widget.placeholder == "Last name"
? const Icon(Icons.password_outlined,color: Colors.grey,size: 20,)
: const Icon(Icons.password_outlined,color: Colors.grey,size: 20,)),
),
suffixIcon: widget.showLastIcon
? Container(
width: 50,
child: Row(
children: [
IconButton(
onPressed: () {
print('mic button pressed');
},
icon: Icon(Icons.mic,color: Colors.grey,size: 20,),
),
],
),
)
: null,
)),
);
}
} |
<!DOCTYPE html>
<html ⚡>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
<title>Dual Spaces</title>
<link rel="canonical" href="https://algebrology.github.io/dual-spaces/" />
<meta name="referrer" content="no-referrer-when-downgrade" />
<meta property="og:site_name" content="Algebrology" />
<meta property="og:type" content="article" />
<meta property="og:title" content="Dual Spaces" />
<meta property="og:description" content="Since I haven't posted for a while, I decided to break up my rants about homology with some posts on linear (and multilinear) algebra. In this post, we will (as usual) deal only with finite dimensional vector spaces." />
<meta property="og:url" content="https://algebrology.github.io/dual-spaces/" />
<meta property="article:published_time" content="2019-08-09T03:55:00.000Z" />
<meta property="article:modified_time" content="2020-08-24T18:29:15.000Z" />
<meta property="article:tag" content="linear algebra" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="Dual Spaces" />
<meta name="twitter:description" content="Since I haven't posted for a while, I decided to break up my rants about homology with some posts on linear (and multilinear) algebra. In this post, we will (as usual) deal only with finite dimensional vector spaces." />
<meta name="twitter:url" content="https://algebrology.github.io/dual-spaces/" />
<meta name="twitter:label1" content="Written by" />
<meta name="twitter:data1" content="Eric Shapiro" />
<meta name="twitter:label2" content="Filed under" />
<meta name="twitter:data2" content="linear algebra" />
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "Article",
"publisher": {
"@type": "Organization",
"name": "Algebrology",
"url": "https://algebrology.github.io/",
"logo": {
"@type": "ImageObject",
"url": "https://algebrology.github.io/favicon.ico",
"width": 48,
"height": 48
}
},
"author": {
"@type": "Person",
"name": "Eric Shapiro",
"url": "https://algebrology.github.io/author/eric/",
"sameAs": []
},
"headline": "Dual Spaces",
"url": "https://algebrology.github.io/dual-spaces/",
"datePublished": "2019-08-09T03:55:00.000Z",
"dateModified": "2020-08-24T18:29:15.000Z",
"keywords": "linear algebra",
"description": "Since I haven't posted for a while, I decided to break up my rants about homology with some posts on linear (and multilinear) algebra. In this post, we will (as usual) deal only with finite dimensional vector spaces.",
"mainEntityOfPage": {
"@type": "WebPage",
"@id": "https://algebrology.github.io/"
}
}
</script>
<meta name="generator" content="Ghost 3.30" />
<link rel="alternate" type="application/rss+xml" title="Algebrology" href="https://algebrology.github.io/rss/" />
<style amp-custom>
*,
*::before,
*::after {
box-sizing: border-box;
}
html {
overflow-x: hidden;
overflow-y: scroll;
font-size: 62.5%;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
body {
min-height: 100vh;
margin: 0;
padding: 0;
color: #3a4145;
font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Open Sans,Helvetica Neue,sans-serif;
font-size: 1.7rem;
line-height: 1.55em;
font-weight: 400;
font-style: normal;
background: #fff;
scroll-behavior: smooth;
overflow-x: hidden;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
p,
ul,
ol,
li,
dl,
dd,
hr,
pre,
form,
table,
video,
figure,
figcaption,
blockquote {
margin: 0;
padding: 0;
}
ul[class],
ol[class] {
padding: 0;
list-style: none;
}
img {
display: block;
max-width: 100%;
}
input,
button,
select,
textarea {
font: inherit;
-webkit-appearance: none;
}
fieldset {
margin: 0;
padding: 0;
border: 0;
}
label {
display: block;
font-size: 0.9em;
font-weight: 700;
}
hr {
position: relative;
display: block;
width: 100%;
height: 1px;
border: 0;
border-top: 1px solid currentcolor;
opacity: 0.1;
}
::selection {
text-shadow: none;
background: #cbeafb;
}
mark {
background-color: #fdffb6;
}
small {
font-size: 80%;
}
sub,
sup {
position: relative;
font-size: 75%;
line-height: 0;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
ul li + li {
margin-top: 0.6em;
}
a {
color: #1292EE;
text-decoration-skip-ink: auto;
}
h1,
h2,
h3,
h4,
h5,
h6 {
margin: 0;
font-weight: 700;
color: #121212;
line-height: 1.4em;
}
h1 {
font-size: 3.4rem;
line-height: 1.1em;
}
h2 {
font-size: 2.4rem;
line-height: 1.2em;
}
h3 {
font-size: 1.8rem;
}
h4 {
font-size: 1.7rem;
}
h5 {
font-size: 1.6rem;
}
h6 {
font-size: 1.6rem;
}
amp-img {
height: 100%;
width: 100%;
max-width: 100%;
max-height: 100%;
}
amp-img img {
object-fit: cover;
}
.page-header {
padding: 50px 5vmin 30px;
text-align: center;
font-size: 2rem;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.page-header a {
color: #121212;
font-weight: 700;
text-decoration: none;
font-size: 1.6rem;
letter-spacing: -0.1px;
}
.post {
max-width: 680px;
margin: 0 auto;
}
.post-header {
margin: 0 5vmin 5vmin;
text-align: center;
}
.post-meta {
margin: 1rem 0 0 0;
text-transform: uppercase;
color: #738a94;
font-weight: 500;
font-size: 1.3rem;
}
.post-image {
margin: 0 0 5vmin;
}
.post-image img {
display: block;
width: 100%;
height: auto;
}
.post-content {
padding: 0 5vmin;
}
.post-content > * + * {
margin-top: 1.5em;
}
.post-content [id]:not(:first-child) {
margin: 2em 0 0;
}
.post-content > [id] + * {
margin-top: 1rem;
}
.post-content [id] + .kg-card,
.post-content blockquote + .kg-card {
margin-top: 40px;
}
.post-content > ul,
.post-content > ol,
.post-content > dl {
padding-left: 1.9em;
}
.post-content hr {
margin-top: 40px;
}
.post .post-content hr + * {
margin-top: 40px;
}
.post-content amp-img {
background-color: #f8f8f8;
}
.post-content blockquote {
position: relative;
font-style: italic;
}
.post-content blockquote::before {
content: "";
position: absolute;
left: -1.5em;
top: 0;
bottom: 0;
width: 0.3rem;
background: #000;
}
.post-content :not(.kg-card):not([id]) + .kg-card {
margin-top: 40px;
}
.post-content .kg-card + :not(.kg-card) {
margin-top: 40px;
}
.kg-card figcaption {
padding: 1.5rem 1.5rem 0;
text-align: center;
font-weight: 500;
font-size: 1.3rem;
line-height: 1.4em;
opacity: 0.6;
}
.kg-card figcaption strong {
color: rgba(0,0,0,0.8);
}
.post-content :not(pre) code {
vertical-align: middle;
padding: 0.15em 0.4em 0.15em;
border: #e1eaef 1px solid;
font-weight: 400;
font-size: 0.9em;
line-height: 1em;
color: #dc0050;
background: #f0f6f9;
border-radius: 0.25em;
}
.post-content > pre {
overflow: scroll;
padding: 16px 20px;
color: #fff;
background: #1F2428;
border-radius: 5px;
box-shadow: 0 2px 6px -2px rgba(0,0,0,.1), 0 0 1px rgba(0,0,0,.4);
}
.kg-embed-card {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
.kg-image-card img {
margin: auto;
}
.kg-gallery-card + .kg-gallery-card {
margin-top: 0.75em;
}
.kg-gallery-container {
position: relative;
}
.kg-gallery-row {
display: flex;
flex-direction: row;
justify-content: center;
}
.kg-gallery-image {
width: 100%;
height: 100%;
}
.kg-gallery-row:not(:first-of-type) {
margin: 0.75em 0 0 0;
}
.kg-gallery-image:not(:first-of-type) {
margin: 0 0 0 0.75em;
}
.kg-bookmark-card,
.kg-bookmark-publisher {
position: relative;
}
.kg-bookmark-container,
.kg-bookmark-container:hover {
display: flex;
flex-wrap: wrap;
flex-direction: row-reverse;
color: currentColor;
background: rgba(255,255,255,0.6);
font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Open Sans,Helvetica Neue,sans-serif;
text-decoration: none;
border-radius: 5px;
box-shadow: 0 2px 6px -2px rgba(0, 0, 0, 0.1), 0 0 1px rgba(0, 0, 0, 0.4);
overflow: hidden;
}
.kg-bookmark-content {
flex-basis: 0;
flex-grow: 999;
padding: 20px;
order: 1;
}
.kg-bookmark-title {
font-weight: 600;
font-size: 1.5rem;
line-height: 1.3em;
}
.kg-bookmark-description {
display: -webkit-box;
max-height: 45px;
margin: 0.5em 0 0 0;
font-size: 1.4rem;
line-height: 1.55em;
overflow: hidden;
opacity: 0.8;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.kg-bookmark-metadata {
margin-top: 20px;
}
.kg-bookmark-metadata {
display: flex;
align-items: center;
font-weight: 500;
font-size: 1.3rem;
line-height: 1.3em;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.kg-bookmark-description {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
}
.kg-bookmark-metadata amp-img {
width: 18px;
height: 18px;
max-width: 18px;
max-height: 18px;
margin-right: 10px;
}
.kg-bookmark-thumbnail {
display: flex;
flex-basis: 20rem;
flex-grow: 1;
justify-content: flex-end;
}
.kg-bookmark-thumbnail amp-img {
max-height: 200px;
}
.kg-bookmark-author {
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
.kg-bookmark-publisher::before {
content: "•";
margin: 0 .5em;
}
.kg-width-full.kg-card-hascaption {
display: grid;
grid-template-columns: inherit;
}
.post-content table {
border-collapse: collapse;
width: 100%;
}
.post-content th {
padding: 0.5em 0.8em;
text-align: left;
font-size: .75em;
text-transform: uppercase;
}
.post-content td {
padding: 0.4em 0.7em;
}
.post-content tbody tr:nth-child(2n + 1) {
background-color: rgba(0,0,0,0.1);
padding: 1px;
}
.post-content tbody tr:nth-child(2n + 2) td:last-child {
box-shadow:
inset 1px 0 rgba(0,0,0,0.1),
inset -1px 0 rgba(0,0,0,0.1);
}
.post-content tbody tr:nth-child(2n + 2) td {
box-shadow: inset 1px 0 rgba(0,0,0,0.1);
}
.post-content tbody tr:last-child {
border-bottom: 1px solid rgba(0,0,0,.1);
}
.page-footer {
padding: 60px 5vmin;
margin: 60px auto 0;
text-align: center;
background-color: #f8f8f8;
}
.page-footer h3 {
margin: 0.5rem 0 0 0;
}
.page-footer p {
max-width: 500px;
margin: 1rem auto 1.5rem;
font-size: 1.7rem;
line-height: 1.5em;
color: rgba(0,0,0,0.6)
}
.powered {
display: inline-flex;
align-items: center;
margin: 30px 0 0;
padding: 6px 9px 6px 6px;
border: rgba(0,0,0,0.1) 1px solid;
font-size: 12px;
line-height: 12px;
letter-spacing: -0.2px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;
font-weight: 500;
color: #222;
text-decoration: none;
background: #fff;
border-radius: 6px;
}
.powered svg {
height: 16px;
width: 16px;
margin: 0 6px 0 0;
}
@media (max-width: 600px) {
body {
font-size: 1.6rem;
}
h1 {
font-size: 3rem;
}
h2 {
font-size: 2.2rem;
}
}
@media (max-width: 400px) {
h1 {
font-size: 2.6rem;
line-height: 1.15em;
}
h2 {
font-size: 2rem;
line-height: 1.2em;
}
h3 {
font-size: 1.7rem;
}
}
</style>
<style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
<script async src="https://cdn.ampproject.org/v0.js"></script>
</head>
<body class="amp-template">
<header class="page-header">
<a href="https://algebrology.github.io">
Algebrology
</a>
</header>
<main class="content" role="main">
<article class="post">
<header class="post-header">
<h1 class="post-title">Dual Spaces</h1>
<section class="post-meta">
Eric Shapiro -
<time class="post-date" datetime="2019-08-08">08 Aug 2019</time>
</section>
</header>
<section class="post-content">
<ol>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#the-dual-space">The Dual Space</a></li>
<li><a href="#the-double-dual-space">The Double Dual Space</a></li>
</ol>
<hr></hr>
<h3 id="introductionanameintroduction">Introduction<a name="introduction"></a></h3>
<p>Since I haven't posted for a while, I decided to break up my rants about homology with some posts on linear (and multilinear) algebra. In this post, we will (as usual) deal only with finite dimensional vector spaces. Since we care only about abstract properties of vector spaces and not about any specific vector space, I will talk generally about a vector space $V$ of dimension $n$ over a field $\F$ for the remainder of this post.</p>
<p>As we discovered previously, every finite dimensional vector space has a basis. That is, there exists a linearly independent collection $(e_1,e_2,\ldots,e_n)$ of vectors in $V$ for which any vector $v$ in $V$ can be expressed as a linear combination of these basis vectors. That is, for any $v\in V$ there exist scalars $(v^i)_{i=1}^n$ in $\F$ for which</p>
<p>$$v=\sum_{i=1}^n v^i e_i.$$</p>
<p>Note that in the expression above, I have moved the index on $v^i$ into the upper position, whereas in previous posts I would have written the same scalars as $v_i$. There is a good reason for this, and it is commonly seen in physics and differential geometry. The reason will become apparent shortly, but for now just realize that using superscripts for index placement is really no different than using subscripts, and it <strong>does not</strong> represent exponentiation. For instance, $v^2$ represents the second scalar in a list and <strong>not</strong> $v\cdot v$.</p>
<p>Having a basis for our vector space is nice for two main reasons:</p>
<ol>
<li>Any vector can be expressed in terms of the basis because the basis vectors span our vector space.</li>
<li>There is no redundancy in this expression because the basis vectors are linearly independent.</li>
</ol>
<p>Recall also that a linear map $T$ between vector spaces $U$ and $V$ is a function $T:U\to V$ for which</p>
<ol>
<li>$T(u_1+u_2) = T(u_1) + T(u_2)$ for any $u_1, u_2 \in U$.</li>
<li>$T(au) = aT(u)$ for any $a\in F$ and any $u\in U$.</li>
</ol>
<p>We learned that linear maps are completely determined by the way that they act on basis vectors. In fact, we can specify the images of the basis vectors and <em>extend by linearity</em> to obtain a linear map on the whole vector space.</p>
<p>Now let's turn everything on its head.</p>
<h3 id="thedualspaceanamethedualspace">The Dual Space<a name="the-dual-space"></a></h3>
<p>Let's define the most important concept of this post:</p>
<blockquote>
<p><strong>Definition.</strong> Given a vector space $V$ over a field $\F$, its <strong>dual space</strong>, written $V^*$, is the set of all linear maps from $V$ to $\F$.</p>
</blockquote>
<p>Of course, we are now talking about $\F$ as a vector space over itself, or else the idea of a linear map would make no sense.</p>
<p>This definition may seem intimidating at first, but it's really not that complicated. An element of the dual space is just a linear function which eats a vector and returns a scalar. Elements of the dual space are often called <strong>covectors</strong> or <strong>linear functionals</strong>.</p>
<p>Now, the fact that the dual space literally has the word "space" in its name is hopefully suggestive that it is itself a vector space. I suppose there might technically be multiple ways to turn this set into a vector space, but the canonical way is as follows:</p>
<blockquote>
<ul>
<li>The zero vector ${\bf 0}\in V^*$ is the zero map ${\bf 0}:V\to\F$ which maps every vector to the zero element of $\F$. That is, ${\bf 0}(v)=0$ for every $v\in V$.</li>
<li>Vector addition is just function addition. That is, if $s$ and $t$ are maps in the dual space, then $s+t$ is another map defined by $(s+t)(v) = s(v) + t(v)$.</li>
<li>Scalar multiplication is inherited directly. That is, if $a$ is a scalar in $\F$ and $t$ is a map in the dual space, then $at$ is another map defined by $(at)(v) = a\cdot t(v)$.</li>
<li>Additive inverses are given by scalar multiplication by $-1$. That is, if $t$ is a map in the dual space then $-t=(-1)\cdot t$.</li>
</ul>
<p>It is hopefully evident that all of the above maps are linear, and that with these definitions, the dual space satisfies the axioms of a vector space. I will not check these properties here because it is not difficult or instructive to do so.</p>
</blockquote>
<p>Now, the next natural question to ask is how the dual space $V^*$ is related to the original space $V$. The answer is not immediately obvious. There is no canonical mapping which takes any vector and picks out a specific covector which it is related to. That's not to say we can't form a bijection from $V$ to $V^*$, it just wouldn't have much meaning, and there is not an obvious candidate for a <em>favored</em> bijection.</p>
<p>In fact, creating such a bijection would require first choosing a basis for $V$. Mathematicians do not consider this to be a natural correspondence, since it relies on picking some arbitrary basis, so we say there is no <strong>natural</strong> or <strong>canonical</strong> correspondence between $V$ and $V^*$.</p>
<p>However, if we try to figure out the dimension of the dual space, the picture begins to become a little clearer. Before we proceed, we'll need the following definition:</p>
<blockquote>
<p><strong>Definition.</strong> Given $n\in\N$, the <strong>Kronecker delta</strong> is the function $\delta:\Z_n\times \Z_n\to\R$ defined by</p>
<p>$$\delta^i_j =<br />
\begin{cases}<br />
0 & \text{if } i\ne j, \\<br />
1 & \text{if } i = j.<br />
\end{cases}$$</p>
</blockquote>
<p>The weird upper and lower index notation in place of a more traditional notation for function arguments, such as $\delta(i, j)$, does have a purpose which will soon become apparent.</p>
<p>Alright, we're now well armed to make a very bold claim:</p>
<blockquote>
<p><strong>Theorem.</strong> If $(e_i)_{i=1}^n$ is a basis for a finite dimensional vector space $V$, then $(e^i)_{i=1}^n$ is a basis for $V^*$, where each basis covector $e^i:V\to\F$ is defined on basis vectors by $$e^i(e_j)=\delta^i_j$$ and defined on all of $V$ by extending by linearity.</p>
<p><strong>Aside.</strong> Before we try to prove this, let's take a look at what these basis covectors really are. Since $(e_i)_{i=1}^n$ is a basis for $V$, we can write any vector $v\in V$ as $v=\sum_{j=1}^n v^j e_j$. Applying the $i$th basis covector to $v$ and using its linearity, we get</p>
<p>$$\begin{align}<br />
e^i(v) &= e^i\left(\sum_{j=1}^n v^j e_j\right) \\<br />
&= \sum_{j=1}^n v^j e^i(e_j) \\<br />
&= \sum_{j=1}^n v^j \delta^i_j \\<br />
&= v^i.<br />
\end{align}$$</p>
<p>That is, $e^i$ is the linear map which picks out only the $i$th component of $v$ and discards the rest. It is in some sense a projection map onto the $i$th coordinate.</p>
<p>In order to understand why the complicated-looking sum above broke down into such a simple expression, recall the defining property of the Kronecker delta function. For almost every $j$, the Kronecker delta was identically zero and so those $v^j$ terms do not contribute to the sum. The only term for which it wasn't zero was the $i$th term, and so we were left with only $v^i$. This ability of the Kronecker delta function to simplify ugly sums is almost magical, and we will see it over and over again.</p>
<p><strong>Proof.</strong> In order to show that $(e^i)_{i=1}^n$ is a basis for $V^*$, we need to show that it is linearly independent and that it spans $V^*$.</p>
<p>We argue first that it is linearly independent. Suppose $\sum_{i=1}^n a_i e^i=0$ for some scalars $(a_i)_{i=1}^n$. Then for any vector $v=\sum_{j=1}^n v^j e_j$ in $V$,</p>
<p>\begin{align}<br />
\left(\sum_{i=1}^n a_i e^i\right)(v) &= \left(\sum_{i=1}^n a_i e^i\right)\left(\sum_{j=1}^n v^j e_j\right) \\<br />
&= \sum_{i=1}^n\sum_{i=j}^n a_i v^j e^i(e_j) \\<br />
&= \sum_{i=1}^n\sum_{i=j}^n a_i v^j \delta^i_j \\<br />
&= \sum_{i=1}^n a_i v^i \\<br />
&= 0.<br />
\end{align}</p>
<p>Since the $v^i$ were arbitrary, the only way this can only be true is if the scalars $(a_i)_{i=1}^n$ are identically zero. Thus, $(e^i)_{i=1}^n$ are linearly independent.</p>
<p>We argue next that the covectors $(e^i)_{i=1}^n$ span the dual space. To this end, suppose $s$ is any covector in $V^*$. For any vector $v=\sum_{j=1}^n v^j e_j$, we have from the linearity of $s$ that</p>
<p>\begin{align}<br />
s(v) &= s\left(\sum_{j=1}^n v^j e_j\right) \\<br />
&= \sum_{j=1}^n v^j s(e_j).<br />
\end{align}</p>
<p>Define $s_j = s(e_j)$ for each $1\le j \le n$. Then</p>
<p>\begin{align}<br />
\left(\sum_{j=1}^n s_j e^j\right)(v) &= \left(\sum_{j=1}^n s_j e^j\right)\left(\sum_{i=1}^n v^i e_i\right) \\<br />
&= \sum_{j=1}^n\sum_{i=1}^n s_j v^i e^j(e_i) \\<br />
&= \sum_{j=1}^n\sum_{i=1}^n s_j v^i \delta^j_i \\<br />
&= \sum_{j=1}^n s_j v^j \\<br />
&= \sum_{j=1}^n v^j s(e_j) \\<br />
&= s(v).<br />
\end{align}</p>
<p>We've thus shown that any covector can be written as a linear combination of the covectors $(e^i)_{i=1}^n$, and thus they span the dual space.</p>
<p>It follows that $(e^i)_{i=1}^n$ forms a basis for $V^*$, as desired.</p>
</blockquote>
<p>We call the basis defined in the proof above the <strong>dual basis</strong>, and it is the basis we usually work with when talking about the dual space. Note that the dual basis depends on the basis we chose for the original vector space, so every basis for $V$ has a corresponding dual basis for $\dual{V}$. However, it is of course not the <em>only</em> basis we could choose. It is just particularly convenient for our purposes because of the way things tend to simplify via the Kronecker delta.</p>
<p>Hidden in the result above is the fact that $\dim V^*=\dim V$. That's because we've exhibited a basis for $V^*$ consisting of $n$ covectors, which is the definition of the dimension of a vector space. So the dual space always has the same dimension as the original vector space (as long as its finite dimensional)! Which is pretty cool I guess. 😎</p>
<p>The following result will be useful to us later.</p>
<blockquote>
<p><strong>Lemma.</strong> Suppose $V$ is a finite dimensional vector space over a field $\F$ and let $v\in V$. If $s(v) = 0$ for every covector $s\in\dual{V}$, then $v = 0$.</p>
<p><strong>Proof.</strong> We proceed by contraposition, supposing that $v\ne 0$ and arguing that there exists a covector $s\in\dual{V}$ for which $s(v)\ne 0$.</p>
<p>Choose any basis $(e_i)_{i=1}^n$ for $V$. Then we may write $v=\sum_{i=1}^n v^i e_i$ for some scalars $v^1, v^2, \ldots, v^n\in\F$. Since $v\ne 0$, one of its components (with respect to our chosen basis) must be nonzero. That is, there exists $k\in \{1, 2, \ldots, n\}$ for which $v^k\ne 0$.</p>
<p>We choose $s=e^k$, the $k$th dual basis vector. Notice that, by linearity of $s$,</p>
<p>\begin{align}<br />
s(v) &= e^k(v) \\<br />
&= e^k\left( \sum_{i=1}^n v^i e_i \right) \\<br />
&= \sum_{i=1}^n v^i e^k(e_i) \\<br />
&= \sum_{i=1}^n v^i \delta^k_i \\<br />
&= v^k \\[.5em]<br />
&\ne 0.<br />
\end{align}</p>
<p>Thus, we have demonstrated there exists a covector $s$ for which $s(v)\ne 0$, and the result follows by contraposition.</p>
</blockquote>
<h3 id="thedoubledualspaceanamethedoubledualspace">The Double Dual Space<a name="the-double-dual-space"></a></h3>
<p>The following definition is exactly as you might expect.</p>
<blockquote>
<p><strong>Definition.</strong> Given a vector space $V$ over a field $\F$ and its dual space $\dual{V}$, its <strong>double dual space</strong>, written $\ddual{V}$, is the dual space of $\dual{V}$.</p>
</blockquote>
<p>By now, things may seem hopelessly abstract. If the dual space was the space of all linear functions from $V$ to $\F$, that would make the double dual the space of all linear functions from the space of linear functions from $V$ to $\F$ into $\F$. As if that wasn't complicated enough, there's no end in sight. Am I ever going to stop? Or am I going to next construct the triple dual space, the quadruple dual space, ad infinitum?</p>
<p>It turns out we don't need to keep going, because as we will soon see, $\ddual{V}$ is essentially just $V$. We will need the above lemma to prove it.</p>
<blockquote>
<p><strong>Theorem.</strong> Every finite dimensional vector space $V$ over a field $\F$ is canonically isomorphic to its double dual space $\ddual{V}$.</p>
<p><strong>Proof.</strong> Recall first that <em>canonically isomorphic</em> means we can find a isomorphism which does not depend on a choice of basis. So proving the "canonical" part consists only of not choosing a basis to arrive at the result.</p>
<p>Since the dual space of any finite dimensional vector space shares its dimension, it follows that</p>
<p>$$\dim \ddual{V} = \dim \dual{V} = \dim V.$$</p>
<p>Thus, the rank-nullity theorem tells us that a linear map $T:V\to \ddual{V}$ is an isomorphism if it is injective, which greatly simplifies the proof.</p>
<p>Define a map $T:V\to \ddual{V}$ by</p>
<p>$$\big(T(v)\big)(s) = s(v)$$</p>
<p>for any vector $v\in V$ and any covector $s\in \dual{V}$.</p>
<p>Let's pause to make some sense of this. Since $T$ takes $V$ into its double dual, the image $T(v)$ of any vector $v\in V$ will be a linear map in $\ddual{V}$, which itself takes a covector $s\in\dual{V}$. That's why we're defining $T(v)$ by how it acts on a covector $s$.</p>
<p>We will argue that $T$ is an isomorphism. Let's show first that $T$ is a linear map. To this end, suppose $v, v_1, v_2 \in V$ and $a \in \F$. Then because of the linearity of $s$,</p>
<p>$$\begin{align}<br />
\big(T(v_1 + v_2)\big)(s) &= s(v_1 + v_2) \\<br />
&= s(v_1) + s(v_2) \\<br />
&= \big(T(v_1)\big)(s) + \big(T(v_2)\big)(s),<br />
\end{align}$$</p>
<p>and</p>
<p>$$\begin{align}<br />
\big(T(av)\big)(s) &= s(av) \\<br />
&= as(v) \\<br />
&= a\big(T(v)\big)(s).<br />
\end{align}$$</p>
<p>We'll show next that $T$ is injective (and thus bijective by our earlier dimension argument). We will do so by showing that its kernel is trivial. So suppose $v\in\ker T$. Then by definition,</p>
<p>$$\begin{align}<br />
\big(T(v)\big)(s) &= s(v) \\<br />
&= 0<br />
\end{align}$$</p>
<p>for all covectors $s\in\dual{V}$. It follows then from the above lemma that $v=0$, since the above holds for any choice of covector $s$. Therefore, $\ker T = \{0\}$ and so $T$ is injective (and thus bijective).</p>
<p>We have shown that $T$ is a bijective linear map, and we have done so without explicitly choosing a basis for any of the vector spaces involved, so it follows that $T$ is a canonical isomorphism, as desired.</p>
</blockquote>
<p>So it turns out that $V$ and $\ddual{V}$ can be used almost interchangeably. But using the double dual space gives us a nice kind of duality (pardon the pun), in that we can think of covectors as maps which act on vectors, and we can think of vectors as maps which act on covectors. Physicists often do this without realizing that they are technically working with cocovectors instead of vectors, but that's fine because the isomorphism makes it work.</p>
<p>I'll leave this here for now. Next time I'll talk about multilinear maps and tensor products!</p>
</section>
</article>
</main>
<footer class="page-footer">
<h3>Algebrology</h3>
<p>A gentle introduction to insanity.</p>
<p><a href="https://algebrology.github.io">Read more posts →</a></p>
<a class="powered" href="https://ghost.org" target="_blank" rel="noopener"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 156 156"><g fill="none" fill-rule="evenodd"><rect fill="#15212B" width="156" height="156" rx="27"/><g transform="translate(36 36)" fill="#F6F8FA"><path d="M0 71.007A4.004 4.004 0 014 67h26a4 4 0 014 4.007v8.986A4.004 4.004 0 0130 84H4a4 4 0 01-4-4.007v-8.986zM50 71.007A4.004 4.004 0 0154 67h26a4 4 0 014 4.007v8.986A4.004 4.004 0 0180 84H54a4 4 0 01-4-4.007v-8.986z"/><rect y="34" width="84" height="17" rx="4"/><path d="M0 4.007A4.007 4.007 0 014.007 0h41.986A4.003 4.003 0 0150 4.007v8.986A4.007 4.007 0 0145.993 17H4.007A4.003 4.003 0 010 12.993V4.007z"/><rect x="67" width="17" height="17" rx="4"/></g></g></svg> Published with Ghost</a></span>
</footer>
</body>
</html> |
import json
import multiprocessing as mp
import typing as t
import uuid
from dataclasses import dataclass
from unstructured.ingest.enhanced_dataclass import enhanced_field
from unstructured.ingest.error import DestinationConnectionError, WriteError
from unstructured.ingest.interfaces import (
AccessConfig,
BaseConnectorConfig,
BaseDestinationConnector,
BaseIngestDoc,
ConfigSessionHandleMixin,
IngestDocSessionHandleMixin,
WriteConfig,
)
from unstructured.ingest.logger import logger
from unstructured.ingest.utils.data_prep import chunk_generator
from unstructured.staging.base import flatten_dict
from unstructured.utils import requires_dependencies
if t.TYPE_CHECKING:
from pinecone import Index as PineconeIndex
@dataclass
class PineconeAccessConfig(AccessConfig):
api_key: str = enhanced_field(sensitive=True)
@dataclass
class SimplePineconeConfig(ConfigSessionHandleMixin, BaseConnectorConfig):
index_name: str
environment: str
access_config: PineconeAccessConfig
@dataclass
class PineconeWriteConfig(WriteConfig):
batch_size: int = 50
num_processes: int = 1
@dataclass
class PineconeDestinationConnector(IngestDocSessionHandleMixin, BaseDestinationConnector):
write_config: PineconeWriteConfig
connector_config: SimplePineconeConfig
_index: t.Optional["PineconeIndex"] = None
@property
def pinecone_index(self):
if self._index is None:
self._index = self.create_index()
return self._index
def initialize(self):
pass
@requires_dependencies(["pinecone"], extras="pinecone")
def create_index(self) -> "PineconeIndex":
import pinecone
pinecone.init(
api_key=self.connector_config.access_config.api_key,
environment=self.connector_config.environment,
)
index = pinecone.Index(self.connector_config.index_name)
logger.debug(
f"Connected to index: {pinecone.describe_index(self.connector_config.index_name)}"
)
return index
@DestinationConnectionError.wrap
def check_connection(self):
_ = self.pinecone_index
@DestinationConnectionError.wrap
@requires_dependencies(["pinecone"], extras="pinecone")
def upsert_batch(self, batch):
import pinecone.core.client.exceptions
index = self.pinecone_index
try:
response = index.upsert(batch)
except pinecone.core.client.exceptions.ApiException as api_error:
raise WriteError(f"http error: {api_error}") from api_error
logger.debug(f"results: {response}")
def write_dict(self, *args, dict_list: t.List[t.Dict[str, t.Any]], **kwargs) -> None:
logger.info(
f"Upserting {len(dict_list)} elements to destination "
f"index at {self.connector_config.index_name}",
)
pinecone_batch_size = self.write_config.batch_size
logger.info(f"using {self.write_config.num_processes} processes to upload")
if self.write_config.num_processes == 1:
for chunk in chunk_generator(dict_list, pinecone_batch_size):
self.upsert_batch(chunk) # noqa: E203
else:
with mp.Pool(
processes=self.write_config.num_processes,
) as pool:
pool.map(self.upsert_batch, list(chunk_generator(dict_list, pinecone_batch_size)))
def write(self, docs: t.List[BaseIngestDoc]) -> None:
dict_list: t.List[t.Dict[str, t.Any]] = []
for doc in docs:
local_path = doc._output_filename
with open(local_path) as json_file:
dict_content = json.load(json_file)
# we assign embeddings to "values", and other fields to "metadata"
dict_content = [
# While flatten_dict enables indexing on various fields,
# element_serialized enables easily reloading the element object to memory.
# element_serialized is formed without text/embeddings to avoid data bloating.
{
"id": str(uuid.uuid4()),
"values": element.pop("embeddings", None),
"metadata": {
"text": element.pop("text", None),
"element_serialized": json.dumps(element),
**flatten_dict(
element,
separator="-",
flatten_lists=True,
),
},
}
for element in dict_content
]
logger.info(
f"appending {len(dict_content)} json elements from content in {local_path}",
)
dict_list.extend(dict_content)
self.write_dict(dict_list=dict_list) |
import React from "react";
import { useLocation, useNavigate } from "react-router-dom";
export default function Header() {
const location = useLocation();
const navigate = useNavigate();
console.log(location.pathname);
function pathMathRoute(route) {
if (route === location.pathname) {
console.log("true");
return true;
}
}
return (
<div className="bg-white border-b shadow-sm sticky top-0 z-50">
<header className="flex justify-between items-center px-3 max-w-6xl mx-auto">
<div>
<img
src="https://static.rdc.moveaws.com/images/logos/rdc-logo-default.svg"
alt="Logo"
className="h-5 cursor-pointer"
onClick={() => navigate("/")}
/>
</div>
<div>
<ul className="flex space-x-10">
<li
className={`cursor-pointer py-3 text-sm font-semibold text-gray-400 border-b-[3px] border-b-transparent
${pathMathRoute("/") && "text-black border-b-red-500"}`}
onClick={() => navigate("/")}
>
Home
</li>
<li
className={`cursor-pointer py-3 text-sm font-semibold text-gray-400 border-b-[3px] border-b-transparent
${pathMathRoute("/offers") && "text-black border-b-red-500"}`}
onClick={() => navigate("/offers")}
>
Offers
</li>
<li
className={`cursor-pointer py-3 text-sm font-semibold text-gray-400 border-b-[3px] border-b-transparent
${pathMathRoute("/sign-in") && "text-black border-b-red-500"}`}
onClick={() => navigate("/sign-in")}
>
Sign In
</li>
</ul>
</div>
</header>
</div>
);
} |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_striteri.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tsolanki <tsolanki@student.hive.fi> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/04/29 23:47:27 by tsolanki #+# #+# */
/* Updated: 2024/05/06 21:32:54 by tsolanki ### ########.fr */
/* */
/* ************************************************************************** */
void ft_striteri(char *s, void (*f)(unsigned int, char *))
{
unsigned int i;
i = 0;
while (s[i])
{
f(i, &s[i]);
i++;
}
}
/*
** The ft_striteri function applies a function to each character of a string,
** providing the index and a pointer to the character.
**
** Parameters:
** s - A pointer to the string to be iterated over.
** f - The function to be applied to each character.
** It takes an unsigned integer (the index) and a pointer to a character
** as parameters, and performs some operation on the character.
**
** Return:
** None
*/ |
import { Component, OnInit } from '@angular/core';
import {HttpHeaders, HttpResponse} from '@angular/common/http';
import { ActivatedRoute, Data, ParamMap, Router } from '@angular/router';
import { combineLatest, filter, Observable, switchMap, tap } from 'rxjs';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { IMaintainance } from '../maintainance.model';
import { ITEMS_PER_PAGE, PAGE_HEADER, TOTAL_COUNT_RESPONSE_HEADER } from 'app/config/pagination.constants';
import { ASC, DESC, SORT, ITEM_DELETED_EVENT, DEFAULT_SORT_DATA } from 'app/config/navigation.constants';
import { EntityArrayResponseType, MaintainanceService } from '../service/maintainance.service';
import { MaintainanceDeleteDialogComponent } from '../delete/maintainance-delete-dialog.component';
import { FilterOptions, IFilterOptions, IFilterOption } from 'app/shared/filter/filter.model';
import {CarService} from "../../car/service/car.service";
import {ICar} from "../../car/car.model";
import {map} from "rxjs/operators";
@Component({
selector: 'jhi-maintainance',
templateUrl: './maintainance.component.html',
})
export class MaintainanceComponent implements OnInit {
maintainances?: IMaintainance[];
isLoading = false;
predicate = 'id';
ascending = true;
filters: IFilterOptions = new FilterOptions();
itemsPerPage = ITEMS_PER_PAGE;
totalItems = 0;
page = 1;
carsSharedCollection: ICar[] = [];
selectedCar: ICar | null = null;
constructor(
protected maintainanceService: MaintainanceService,
protected activatedRoute: ActivatedRoute,
public router: Router,
protected modalService: NgbModal,
protected carService: CarService,
) {}
trackId = (_index: number, item: IMaintainance): number => this.maintainanceService.getMaintainanceIdentifier(item);
ngOnInit(): void {
this.loadCars();
this.load();
this.filters.filterChanges.subscribe(filterOptions => this.handleNavigation(1, this.predicate, this.ascending, filterOptions));
}
private loadCars() {
this.carService
.query()
.pipe(map((res: HttpResponse<ICar[]>) => res.body ?? []))
.subscribe((cars: ICar[]) => (this.carsSharedCollection = cars));
}
delete(maintainance: IMaintainance): void {
const modalRef = this.modalService.open(MaintainanceDeleteDialogComponent, { size: 'lg', backdrop: 'static' });
modalRef.componentInstance.maintainance = maintainance;
// unsubscribe not needed because closed completes on modal close
modalRef.closed
.pipe(
filter(reason => reason === ITEM_DELETED_EVENT),
switchMap(() => this.loadFromBackendWithRouteInformations())
)
.subscribe({
next: (res: EntityArrayResponseType) => {
this.onResponseSuccess(res);
},
});
}
load(): void {
this.loadFromBackendWithRouteInformations().subscribe({
next: (res: EntityArrayResponseType) => {
this.onResponseSuccess(res);
},
});
}
navigateToWithComponentValues(): void {
this.handleNavigation(this.page, this.predicate, this.ascending, this.filters.filterOptions);
}
navigateToPage(page = this.page): void {
this.handleNavigation(page, this.predicate, this.ascending, this.filters.filterOptions);
}
protected loadFromBackendWithRouteInformations(): Observable<EntityArrayResponseType> {
return combineLatest([this.activatedRoute.queryParamMap, this.activatedRoute.data]).pipe(
tap(([params, data]) => this.fillComponentAttributeFromRoute(params, data)),
switchMap(() => this.queryBackend(this.page, this.predicate, this.ascending, this.filters.filterOptions))
);
}
protected fillComponentAttributeFromRoute(params: ParamMap, data: Data): void {
const page = params.get(PAGE_HEADER);
this.page = +(page ?? 1);
const sort = (params.get(SORT) ?? data[DEFAULT_SORT_DATA]).split(',');
this.predicate = sort[0];
this.ascending = sort[1] === ASC;
this.filters.initializeFromParams(params);
}
protected onResponseSuccess(response: EntityArrayResponseType): void {
this.fillComponentAttributesFromResponseHeader(response.headers);
const dataFromBody = this.fillComponentAttributesFromResponseBody(response.body);
this.maintainances = dataFromBody;
}
protected fillComponentAttributesFromResponseBody(data: IMaintainance[] | null): IMaintainance[] {
return data ?? [];
}
protected fillComponentAttributesFromResponseHeader(headers: HttpHeaders): void {
this.totalItems = Number(headers.get(TOTAL_COUNT_RESPONSE_HEADER));
}
protected queryBackend(
page?: number,
predicate?: string,
ascending?: boolean,
filterOptions?: IFilterOption[]
): Observable<EntityArrayResponseType> {
this.isLoading = true;
const pageToLoad: number = page ?? 1;
const queryObject: any = {
page: pageToLoad - 1,
size: this.itemsPerPage,
eagerload: true,
sort: this.getSortQueryParam(predicate, ascending),
"carId.equals": this.selectedCar ? this.selectedCar.id : null
};
filterOptions?.forEach(filterOption => {
queryObject[filterOption.name] = filterOption.values;
});
return this.maintainanceService.query(queryObject).pipe(tap(() => (this.isLoading = false)));
}
protected handleNavigation(page = this.page, predicate?: string, ascending?: boolean, filterOptions?: IFilterOption[]): void {
const queryParamsObj: any = {
page,
size: this.itemsPerPage,
sort: this.getSortQueryParam(predicate, ascending),
};
filterOptions?.forEach(filterOption => {
queryParamsObj[filterOption.nameAsQueryParam()] = filterOption.values;
});
this.router.navigate(['./'], {
relativeTo: this.activatedRoute,
queryParams: queryParamsObj,
});
}
protected getSortQueryParam(predicate = this.predicate, ascending = this.ascending): string[] {
const ascendingQueryParam = ascending ? ASC : DESC;
if (predicate === '') {
return [];
} else {
return [predicate + ',' + ascendingQueryParam];
}
}
} |
package com.jpa.kotlinjpa.controller.dto
import com.jpa.kotlinjpa.entity.Student
import jakarta.validation.constraints.NotBlank
data class StudentSignInDto(
@field:NotBlank
val name: String,
@field:NotBlank
val email: String,
@field:NotBlank
val phone: String
) {
fun toEntity(): Student {
return Student(name, email, phone)
}
}
data class StudentResponseDto(
val name: String,
val email: String,
val phone: String,
val enrolls: List<EnrollResponseDto>
) {
constructor(entity: Student) : this(
name = entity.name,
email = entity.email,
phone = entity.phone,
enrolls = entity.enrolls.map { EnrollResponseDto(it) }
)
} |
//
// Created by nonolive66 on 2018/7/25.
//
#include <log.h>
#include <string.h>
#include "librtmp/rtmp.h"
#include "SpecificData.h"
#include "HandlerThread.h"
#include "Object.h"
#include "Lock.h"
#define ERROR_DISCONNECT -100
#ifndef HARDWAREVIDEOCODEC_RTMP_H
#define HARDWAREVIDEOCODEC_RTMP_H
class RtmpClient {
public:
RtmpClient(int cacheSize);
/**
* 连接rtmp服务
*/
int connect(char *url, int timeOutMs);
int _connect(char *url, int timeOutMs);
/**
* 新建流连接
*/
int connectStream(int w, int h);
int _connectStream(int w, int h);
/**
* 删除流连接
*/
void deleteStream();
/**
* 发送sps、pps 帧
*/
int sendVideoSpecificData(const char *sps, int spsLen, const char *pps, int ppsLen);
int _sendVideoSpecificData();
/**
* 发送视频帧
*/
int sendVideo(const char *data, int len, long timestamp);
int _sendVideo(char *data, int len, long timestamp);
/**
* 发送音频关键帧
*/
int sendAudioSpecificData(const char *data, int len);
int _sendAudioSpecificData();
/**
* 发送音频数据
*/
int sendAudio(const char *data, int len, long timestamp);
int _sendAudio(char *data, int len, long timestamp);
/**
* 释放资源
*/
void stop();
void setCacheSize(int size);
void setErrorCallback(void (callback)(int));
~RtmpClient();
HandlerThread *getPipeline();
private:
int cacheSize;
Lock *mutex;
HandlerThread *pipeline = NULL;
SpecificData *sps = NULL, *pps = NULL, *spec = NULL;
long videoCount = 0, audioCount = 0;
long retryTime[3] = {3000, 9000, 27000};
int width;
int height;
int timeOutMs;
char *url;
RTMP *rtmp = NULL;
void (*errorCallback)(int);
void saveVideoSpecificData(const char *sps, int spsLen, const char *pps, int ppsLen);
void saveAudioSpecificData(const char *spec, int len);
int sendVideoSpecificData(SpecificData *sps, SpecificData *pps);
int sendAudioSpecificData(SpecificData *spec);
/*
* Discard all data between two IDRs, including audio.
* If cacheSize too small to cache two IDRs, an error may occur.
*/
bool dropMessage();
RTMPPacket *makeVideoPacket(char *data, int len, long timestamp);
RTMPPacket *makeAudioPacket(char *data, int len, long timestamp);
RTMPPacket *makeVideoSpecificData(SpecificData *sps, SpecificData *pps);
RTMPPacket *makeAudioSpecificData(SpecificData *spec);
void lock();
void unlock();
};
class ClientWrapper : public Object {
public:
RtmpClient *client;
ClientWrapper(RtmpClient *client) {
this->client = client;
}
virtual ~ClientWrapper() {
}
};
class Connection : public ClientWrapper {
public:
Connection(RtmpClient *client) : ClientWrapper(client) {}
char *url;
int timeOut;
virtual ~Connection() {
}
};
class Size : public ClientWrapper {
public:
Size(RtmpClient *client) : ClientWrapper(client) {}
int width, height;
virtual ~Size() {
}
};
class Packet : public ClientWrapper {
public:
Packet(RtmpClient *client) : ClientWrapper(client) {}
char *data;
int size;
long timestamp;
virtual ~Packet() {
// LOGE("RTMP: release Packet");
if (NULL != data) {
free(data);
data = NULL;
}
}
};
#endif //HARDWAREVIDEOCODEC_RTMP_H |
package com.example.quizapp
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import com.example.quizapp.databinding.ActivityQuizBinding
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
class QuizActivity : AppCompatActivity() {
private lateinit var binding:ActivityQuizBinding
private var count:Int=0
private var score:Int=0
lateinit var list:ArrayList<QuestionModel>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding=ActivityQuizBinding.inflate(layoutInflater)
setContentView(binding.root)
list=ArrayList<QuestionModel>()
Firebase.firestore.collection("quiz")
.get().addOnSuccessListener {
docs->
list.clear()
for (i in docs.documents){
var questionmodel=i.toObject(QuestionModel::class.java)
list.add(questionmodel!!)
}
binding.question.setText(list.get(0).question)
binding.option1.setText(list.get(0).option1)
binding.option2.setText(list.get(0).option2)
binding.option3.setText(list.get(0).option3)
binding.option4.setText(list.get(0).option4)
}
binding.option1.setOnClickListener{
nextData(binding.option1.text.toString())
}
binding.option2.setOnClickListener{
nextData(binding.option2.text.toString())
}
binding.option3.setOnClickListener{
nextData(binding.option3.text.toString())
}
binding.option4.setOnClickListener{
nextData(binding.option4.text.toString())
}
}
private fun nextData(i: String) {
if(list.get(count).answer.equals(i))
score++
count+=1
if(count>=list.size){
val intent= Intent(this,ScoreActivity::class.java)
intent.putExtra("Score",score)
startActivity(intent)
finish()
}
else {
binding.question.setText(list.get(count).question)
binding.option1.setText(list.get(count).option1)
binding.option2.setText(list.get(count).option2)
binding.option3.setText(list.get(count).option3)
binding.option4.setText(list.get(count).option4)
}
}
} |
---
title: Syntax
ref: https://developer.mozilla.org/docs/Web/JavaScript/Reference
---
## Basic
### Built-in functions
```js
typeof myVar; // 'string', 'number', 'boolean', 'object', 'undefined'
isNaN(myVar);
```
#### Type conversion
```js
const num = parseInt('10');
const dec = parseFloat('3.1416');
const bool = Boolean(0); // !!0 - true for empty lists and objects!
```
## Flow control
### Condition
```js
if (10 < 20) {
doSomething();
} else if (10 > 20) {
doSomething();
} else {
doSomething();
}
```
### Switch
```js
switch (myExpr) {
case '1':
doSomething();
break;
case '2':
doSomething();
break;
default:
doSomething();
break;
}
``` |
import { useState, useEffect } from 'react';
import { createUserWithEmailAndPassword, updateProfile } from 'firebase/auth';
import { ref, uploadBytesResumable, getDownloadURL } from 'firebase/storage';
import { doc, setDoc } from 'firebase/firestore';
import { projectAuth, projectStorage, projectFirestore } from '../firebase/config';
import { useAuthContext } from './useAuthContext';
export const useSignup = () => {
const [isCancelled, setIsCancelled] = useState(false);
const [error, setError] = useState(null);
const [isPending, setIsPending] = useState(false);
const { dispatch } = useAuthContext();
const signup = async (email, password, displayName, thumbnail) => {
setError(null);
setIsPending(true);
try {
// signup
const res = await createUserWithEmailAndPassword(projectAuth, email, password);
if (!res || !res.user) {
throw new Error('Could not complete signup');
}
// upload user thumbnail
const uploadPath = `thumbnails/${res.user.uid}/${thumbnail.name}`;
const storageRef = ref(projectStorage, uploadPath);
const img = await uploadBytesResumable(storageRef, thumbnail);
const imgUrl = await getDownloadURL(img.ref);
// Check if the user object has the updateProfile method
if (typeof updateProfile === 'function') {
// add display name to user
await updateProfile(res.user, { displayName, photoURL: imgUrl });
} else {
console.error('updateProfile method not available on user object');
}
// create a user document in Firestore
const userDocRef = doc(projectFirestore, 'users', res.user.uid);
console.log('Firestore User Doc Ref:', userDocRef);
console.log('Data to be Set in Firestore:', {
email: res.user.email,
displayName,
photoURL: imgUrl,
online: true,
});
await setDoc(userDocRef, {
email: res.user.email,
displayName,
photoURL: imgUrl,
online: true,
});
console.log('Firestore User Document Created Successfully');
// dispatch login action
dispatch({ type: 'LOGIN', payload: res.user });
if (!isCancelled) {
setIsPending(false);
setError(null);
}
} catch (err) {
console.error('Signup Error Code:', err.code);
console.error('Signup Error Message:', err.message);
if (!isCancelled) {
setError(err.message);
setIsPending(false);
}
}
};
useEffect(() => {
return () => setIsCancelled(true);
}, []);
return { signup, error, isPending };
}; |
import 'reflect-metadata';
import { Resolver, Query, Args, Mutation, Int } from '@nestjs/graphql';
import { UserModel } from '../Models/user';
import { UsersService } from './users.service';
import { UserCreateInput } from './dto/user-create-input.input';
import { LoginInput } from './dto/login-input.input';
import { LoggedUserOutput } from './dto/logged-user.output';
import { UseGuards, UseInterceptors } from '@nestjs/common';
import { JwtAuthGuard } from '../common/auth/jwt-auth.guard';
import { Example, LogAccountCreation } from './users.interceptor';
import { PaginationInput } from './dto/pagination.input';
@Resolver(UserModel)
export class UsersResolver {
constructor(private readonly usersService: UsersService) {}
@UseGuards(JwtAuthGuard)
@Query(() => [UserModel], {
nullable: 'items',
name: 'users',
description: 'Get all users. You need to be logged in to use this query.',
})
async allUsers(
@Args('pagination', {
nullable: true,
type: () => PaginationInput,
description: 'Optional argument used to paginate the query.',
})
pagination: PaginationInput | null,
) {
return this.usersService.findAll(pagination);
}
@UseGuards(JwtAuthGuard)
@UseInterceptors(Example)
@Query(() => UserModel, {
nullable: true,
description: 'Get user by id. You need to be logged in to use this query.',
})
async user(
@Args('id', {
type: () => Int,
description: 'The id of the user.',
})
id: number,
) {
return this.usersService.findOne(id);
}
@UseInterceptors(LogAccountCreation)
@Mutation(() => String, {
nullable: true,
name: 'signUp',
description: 'Sign up. It will return your password.',
})
async signUp(
@Args('user', {
description:
'The new user informations with email, name and blockchain address.',
})
user: UserCreateInput,
) {
return this.usersService.create(user);
}
@Mutation(() => LoggedUserOutput, {
nullable: true,
name: 'signIn',
description: 'Sign in. It will return a JWT token.',
})
async signIn(
@Args('user', { description: 'The user email and password' })
loginUserInput: LoginInput,
) {
return this.usersService.login(loginUserInput);
}
} |
# SvelteKit TypeSafe API Fetch 🔗🌐
Making SvelteKit **fetch** and **validation** of server endpoints easier than ever!
## Feature list
- Type safe `fetch`-like functions to create a better coding experience.
- Usage of the powerful `zod` library to parse the incomming data.
- Plug and play and opt-in structure.
## Installation
Install the package with your favorite NodeJs package manager.
```sh
npm i sveltekit-typesafe-api zod
```
## Get started
Follow these 3 simple steps to harnest the power of `zod` and `TypeScript` in your API endpoints:
1. Simply add the vite plugin :
```ts
// vite.config.ts
import { sveltekit } from "@sveltejs/kit/vite";
import { defineConfig } from "vite";
import { typesafeApi } from "sveltekit-typesafe-api/vite";
export default defineConfig({
plugins: [sveltekit(), typesafeApi()],
});
```
2. Create a `zod` object to validate the endpoint's request body, and pass it to the `validate` function.
```ts
// src/routes/api/+server.ts
import { json } from "@sveltejs/kit";
import { z } from "zod";
import { validate } from "sveltekit-typesafe-api/server";
import type { RequestHandler } from "./$types";
export const POST = (async ({ request }) => {
const { data } = await validate(request, {
email: z.string().email(),
password: z.string().min(8),
});
return json({
success: true,
jwt: db.createJWT({ email: data.email, password: data.password }),
});
}) satisfies RequestHandler;
```
3. All done, you can finally enjoy the new type safe `api` !
```svelte
<script>
import { api } from "sveltekit-typesafe-api";
let res: Promise<Response> | undefined;
const onClick = () => res = api.POST("/api", { body: { email: "laurent@guibi.ca", password: "******" } });
</sricpt>
```
## Contributing
This package is still in beta. Do not hesitate to contact me if you have feedback of any kind! :)
Ideas, bug reports, PRs and the likes are welcome as a [Github issue](https://github.com/Guibi1/sveltekit-typesafe-api/issues) or as a [discussion](https://github.com/Guibi1/sveltekit-typesafe-api/discussions)! |
---
type: reference, howto
stage: Secure
group: Composition Analysis
info: To determine the technical writer assigned to the Stage/Group associated with this page, see https://about.gitlab.com/handbook/product/ux/technical-writing/#assignments
---
# Dependency Scanning Analyzers **(ULTIMATE)**
Dependency Scanning relies on underlying third-party tools that are wrapped into
what we call "Analyzers". An analyzer is a
[dedicated project](https://gitlab.com/gitlab-org/security-products/analyzers)
that wraps a particular tool to:
- Expose its detection logic.
- Handle its execution.
- Convert its output to the common format.
This is achieved by implementing the [common API](https://gitlab.com/gitlab-org/security-products/analyzers/common).
Dependency Scanning supports the following official analyzers:
- [`gemnasium`](https://gitlab.com/gitlab-org/security-products/analyzers/gemnasium)
- [`gemnasium-maven`](https://gitlab.com/gitlab-org/security-products/analyzers/gemnasium-maven)
- [`gemnasium-python`](https://gitlab.com/gitlab-org/security-products/analyzers/gemnasium-python)
The analyzers are published as Docker images, which Dependency Scanning uses
to launch dedicated containers for each analysis.
The Dependency Scanning analyzers' current major version number is 2.
Dependency Scanning is pre-configured with a set of **default images** that are
maintained by GitLab, but users can also integrate their own **custom images**.
## Official default analyzers
Any custom change to the official analyzers can be achieved by using a
[CI/CD variable in your `.gitlab-ci.yml`](index.md#customizing-the-dependency-scanning-settings).
### Using a custom Docker mirror
You can switch to a custom Docker registry that provides the official analyzer
images under a different prefix. For instance, the following instructs Dependency
Scanning to pull `my-docker-registry/gl-images/gemnasium`
instead of `registry.gitlab.com/security-products/gemnasium`.
In `.gitlab-ci.yml` define:
```yaml
include:
template: Security/Dependency-Scanning.gitlab-ci.yml
variables:
SECURE_ANALYZERS_PREFIX: my-docker-registry/gl-images
```
This configuration requires that your custom registry provides images for all
the official analyzers.
### Disable specific analyzers
You can select the official analyzers you don't want to run. Here's how to disable
the `gemnasium` analyzer.
In `.gitlab-ci.yml` define:
```yaml
include:
template: Security/Dependency-Scanning.gitlab-ci.yml
variables:
DS_EXCLUDED_ANALYZERS: "gemnasium"
```
### Disabling default analyzers
Setting `DS_EXCLUDED_ANALYZERS` to a list of the official analyzers disables them.
In `.gitlab-ci.yml` define:
```yaml
include:
template: Security/Dependency-Scanning.gitlab-ci.yml
variables:
DS_EXCLUDED_ANALYZERS: "gemnasium, gemnasium-maven, gemnasium-python"
```
This is used when one totally relies on [custom analyzers](#custom-analyzers).
## Custom analyzers
You can provide your own analyzers by
defining CI jobs in your CI configuration. For consistency, you should suffix your custom Dependency
Scanning jobs with `-dependency_scanning`. Here's how to add a scanning job that's based on the
Docker image `my-docker-registry/analyzers/nuget` and generates a Dependency Scanning report
`gl-dependency-scanning-report.json` when `/analyzer run` is executed. Define the following in
`.gitlab-ci.yml`:
```yaml
nuget-dependency_scanning:
image:
name: "my-docker-registry/analyzers/nuget"
script:
- /analyzer run
artifacts:
reports:
dependency_scanning: gl-dependency-scanning-report.json
```
The [Security Scanner Integration](../../../development/integrations/secure.md) documentation explains how to integrate custom security scanners into GitLab.
## Analyzers data
The following table lists the data available for the Gemnasium analyzer.
| Property \ Tool | Gemnasium |
|---------------------------------------|:------------------:|
| Severity | 𐄂 |
| Title | ✓ |
| File | ✓ |
| Start line | 𐄂 |
| End line | 𐄂 |
| External ID (for example, CVE) | ✓ |
| URLs | ✓ |
| Internal doc/explanation | ✓ |
| Solution | ✓ |
| Confidence | 𐄂 |
| Affected item (for example, class or package) | ✓ |
| Source code extract | 𐄂 |
| Internal ID | ✓ |
| Date | ✓ |
| Credits | ✓ |
- ✓ => we have that data
- ⚠ => we have that data, but it's partially reliable, or we need to extract that data from unstructured content
- 𐄂 => we don't have that data, or it would need to develop specific or inefficient/unreliable logic to obtain it.
The values provided by these tools are heterogeneous, so they are sometimes
normalized into common values (for example, `severity`, `confidence`, etc). |
1. What is DP?
Ans : Technique to solve overlapping subproblems and optimal structures
optimal structures -> Min,Max,Largest
Dp Simply Means -> Recursion + Storage
Types of Dp
1. Memozations (Top Down)
2. Tabulation (Bottom Up)
Steps To Solve Any DP Problmes
1.Recursion ---> 2. Recursion + Memozations ---> 3. Tabulation ---> 4. Space Optimization
----> Steps To Make Recursion To Recursion + Memozations (Top Down)
Steps 1 : Create Dp Array inside the main Function and Pass In Function as Parameter
Qsn -> How To identify Which types of Dimension array use 1D,2D,3D?
Ans -> Just The Changing Parameter of Function in Recursion Code :-> Means Jitna Parameter Change Ho Raha Hai Utne Dimension Ka Array Lagega.
Steps 2 : Store the ans in DP Array
Steps 3 : Check ( Just After The Base Case )if the Dp Array already has answer,if yes then return true.
Steps 4 return the ans
----> Steps To Make Recursion + Memozations To Tabulation (Bottom Up)
Steps 1 : Create Dp Array inside the Function.
Steps 2 : Base Case analysis of Recursion code and Update the Dp Array Accordingly.
Steps 3 : Find the range for the creating variable and Copy Paste (Recursion + Memozations) The Inside The Range then Rename the Function to DP.
Steps 4 : return the ans |
import 'package:flutter/material.dart';
import 'package:today_weather/apps/utils/convert.dart';
import 'package:today_weather/models/model_weather.dart';
import 'package:today_weather/pages/home/widgets/widget_forecast.dart';
// ignore: must_be_immutable
class WidgetHourly extends StatelessWidget {
WidgetHourly(
{super.key, required this.dataForecastday, required this.timeNow});
List<Forecastday> dataForecastday;
String? timeNow;
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
List<Hour> data = MyConverter().filterHours(dataForecastday);
return SizedBox(
height: size.width * 0.45,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: data.length,
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return Container(
width: size.width * 0.185,
padding: const EdgeInsets.symmetric(vertical: 7),
margin: const EdgeInsets.only(right: 4),
decoration: BoxDecoration(
border: Border.all(width: 1, color: Colors.black12),
borderRadius: BorderRadius.circular(5),
),
child: Column(
children: [
Text(
'${data[index].tempC}°',
style: TextStyle(
fontSize: size.width * 0.038,
fontWeight: FontWeight.w400,
),
),
WidgetForecast(size: size, hour: data[index]),
],
),
);
},
),
);
}
} |
using System;
using System.ComponentModel.DataAnnotations;
namespace EducationDepartment.Models.ViewModels
{
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(20, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 8)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm Password")]
[Compare(nameof(Password), ErrorMessage = "비밀번호와 일치하지 않습니다")]
public string ConfirmPassword { get; set; }
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<title>My Portfolio</title>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<!-- Bootstrap CSS v5.2.1 -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT"
crossorigin="anonymous"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
/>
<link rel="stylesheet" href="../style.css" />
<link rel="stylesheet" href="../style.scss" />
</head>
<body>
<div class="container">
<header id="main-header">
<div class="row g-0">
<div class="col-lg-4 col-md-5">
<img
src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSXH98yJm1oyNSP_MX99nhEiw_0yw5OEyuWiA&usqp=CAU"
alt=""
/>
</div>
<div class="col-lg-8 col-md-7">
<div class="d-flex flex-column">
<div class="p-5 bg-dark text-white">
<div
class="
name
d-flex
flex-row
justify-content-between
align-items-center
"
>
<h1 class="display-4">PM Modi</h1>
<div><i class="fa fa-twitter"></i></div>
<div><i class="fa fa-facebook"></i></div>
<div><i class="fa fa-instagram"></i></div>
<div><i class="fa fa-github"></i></div>
</div>
</div>
<div class="p-4 bg-black">
Experienced Full Stack Web Developer
</div>
<div
class="
d-flex
flex-row
text-white
align-items-strech
text-center
"
>
<div
class="port-item p-4 bg-primary"
data-bs-toggle="collapse"
data-bs-target="#home"
>
<i class="fa fa-home d-block"></i>Home
</div>
<div
class="port-item p-4 bg-success"
data-bs-toggle="collapse"
data-bs-target="#resume"
>
<i class="fa fa-graduation-cap d-block"></i>Resume
</div>
<div
class="port-item p-4 bg-warning"
data-bs-toggle="collapse"
data-bs-target="#work"
>
<i class="fa fa-folder-open d-block"></i>work
</div>
<div
class="port-item p-4 bg-danger"
data-bs-toggle="collapse"
data-bs-target="#contact"
>
<i class="fa fa-envelope d-block"></i>contact
</div>
</div>
</div>
</div>
</div>
</header>
<!-- home -->
<div class="collapse show" id="home">
<div class="card card-body bg-primary text-white py-5">
<h2>Welcome to my page</h2>
<p class="lead">
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis,
harum!
</p>
</div>
</div>
<!-- Resume -->
<div class="collapse" id="resume">
<div class="card card-body py-5">
<h>My Skills</h>
<p class="lead">
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis,
harum!
</p>
<hr />
<h4>Html</h4>
<div class="progress mb-3">
<div
class="
progress-bar-striped progress-bar-animated
bg-success bg-success
"
style="width: 100%"
></div>
</div>
<h4>css</h4>
<div class="progress mb-3">
<div
class="progress-bar-striped progress-bar-animated bg-primary"
style="width: 100%"
></div>
</div>
<h4>JavaScript</h4>
<div class="progress mb-3">
<div
class="
progress-bar-striped progress-bar-animated
bg-success bg-info
"
style="width: 90%"
></div>
</div>
<h4>PHP</h4>
<div class="progress mb-3">
<div
class="
progress-bar-striped progress-bar-animated
bg-success bg-warning
"
style="width: 80%"
></div>
</div>
<h4>Python</h4>
<div class="progress mb-3">
<div
class="
progress-bar-striped progress-bar-animated
bg-success bg-danger
"
style="width: 70%"
></div>
</div>
</div>
</div>
<!-- Work -->
<div class="collapse" id="work">
<div class="card card-body bg-warning text-white py-5">
<h2>Welcome to my page</h2>
<p class="lead">
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis,
harum!
</p>
</div>
</div>
<!-- contact -->
<div class="collapse" id="contact">
<div class="card card-body bg-danger text-white py-5">
<h2>Welcome to my page</h2>
<p class="lead">
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis,
harum!
</p>
</div>
</div>
<footer id="main-footer" class="p-5 bg-dark text-white">
<div class="row">
<div class="col-md-6">
<a href="#" class="btn btn-outline-light"
><i class="fa fa-cloud">Download Resume</i></a
>
</div>
</div>
</footer>
</div>
<!-- Bootstrap JavaScript Libraries -->
<script
src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"
integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3"
crossorigin="anonymous"
></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.min.js"
integrity="sha384-7VPbUDkoPSGFnVtYi0QogXtr74QeVeeIs99Qfg5YCF+TidwNdjvaKZX19NZ/e6oz"
crossorigin="anonymous"
></script>
</body>
</html> |
import { Resolver, Mutation, Args, Query } from '@nestjs/graphql';
import { StudentType } from './student.type';
import { StudentService } from './student.service';
import { CreateStudentInput } from './student.input';
@Resolver(of => StudentType)
export class StudentResolver {
constructor(private studentService: StudentService) {}
@Query(returns => StudentType)
student(@Args('id') id: string) {
return this.studentService.get(id);
}
@Query(returns => [StudentType])
students() {
return this.studentService.getAll();
}
@Mutation(returns => StudentType)
createStudent(
@Args('createStudentInput') createStudentInput: CreateStudentInput,
) {
return this.studentService.create(createStudentInput);
}
} |
import React from "react";
import Button from "@material-ui/core/Button";
import TextField from "@material-ui/core/TextField";
import Grid from "@material-ui/core/Grid";
import Typography from "@material-ui/core/Typography";
import CustomSnackbar from '../CustomSnackbar'
import { Formik } from "formik";
import { commonStyles } from "../commonStyles";
import SaveIcon from "@material-ui/icons/Save";
import Autocomplete from '@material-ui/lab/Autocomplete';
import CancelIcon from "@material-ui/icons/Cancel";
import * as Yup from "yup";
import { format, startOfToday } from "date-fns";
import CustomCircularProgress from "../CustomCircularProgress";
const defaultDate = format(startOfToday(), 'yyyy-MM-dd')
const VacatingNoticeSchema = Yup.object().shape({
lease_details: Yup.object().typeError("Rental agreement is required")
.required("Rental agreement is required"),
notification_date: Yup.date().required("Vacating Date Required"),
vacating_date: Yup.date().required("Move Out Date is Required"),
});
const NoticeInputForm = (props) => {
const { activeLeases, submitForm, history } = props;
const classes = commonStyles();
const noticeToEdit = props.noticeToEdit || {}
let noticeValues = {
id: noticeToEdit.id,
notification_date: noticeToEdit.notification_date || defaultDate,
vacating_date: noticeToEdit.vacating_date || defaultDate,
lease_id: noticeToEdit.lease_id || '',
lease_details: activeLeases.find(({ id }) => id === noticeToEdit.lease_id) || null,
};
return (
<Formik
initialValues={noticeValues}
enableReinitialize
validationSchema={VacatingNoticeSchema}
onSubmit={async (values, { resetForm, setStatus }) => {
try {
const vacatingNotice = {
id: values.id,
lease_id: values.lease_details.id,
vacating_date: values.vacating_date,
notification_date: values.notification_date,
unit_id: values.lease_details.unit_id,
property_id: values.lease_details.property_id,
tenant_id: values.lease_details.tenants[0]
};
await submitForm(vacatingNotice, "notices")
resetForm({});
if (values.id) {
history.goBack()
}
setStatus({ sent: true, msg: "Notice saved successfully!" })
} catch (error) {
setStatus({ sent: false, msg: `Error! ${error}.` })
}
}}
>
{({
values,
status,
handleSubmit,
touched,
errors,
handleChange,
setFieldValue,
handleBlur,
isSubmitting,
}) => (
<form
className={classes.form}
method="post"
id="noticeInputForm"
onSubmit={handleSubmit}
>
<Grid
container
spacing={2}
justify="center"
alignItems="stretch"
direction="column"
>
{
status && status.msg && (
<CustomSnackbar
variant={status.sent ? "success" : "error"}
message={status.msg}
/>
)
}
{
isSubmitting && (<CustomCircularProgress open={true} />)
}
<Grid item>
<Typography color="textSecondary" component="p">
Recording every tenant's intention to move out will automatically end the agreement
on the last move-out date.
</Typography>
</Grid>
<Grid item container spacing={2} direction="row">
<Grid item sm>
<Autocomplete
id="lease_details"
value={values.lease_details}
onChange={(event, newValue) => {
setFieldValue("lease_details", newValue);
}}
style={{ width: "100%" }}
options={activeLeases}
autoHighlight
getOptionLabel={(option) => option ? `${option.tenant_name} ${option.unit_ref}` : ''}
renderOption={(option) => (
<React.Fragment>
{option.tenant_name} {option.unit_ref}
</React.Fragment>
)}
renderInput={(params) => (
<TextField
{...params}
label="Tenants"
variant="outlined"
error={errors.lease_details && touched.lease_details}
helperText={touched.lease_details && errors.lease_details}
inputProps={{
...params.inputProps,
}}
/>
)}
/>
</Grid>
<Grid item sm>
<TextField
fullWidth
disabled
InputLabelProps={{ shrink: true }}
variant="outlined"
id="unit"
name="unit"
label="Unit"
value={values.lease_details ? values.lease_details.unit_ref : ''}
/>
</Grid>
</Grid>
<Grid item container spacing={2} direction="row">
<Grid item sm>
<TextField
disabled
fullWidth
InputLabelProps={{ shrink: true }}
variant="outlined"
id="lease_type"
name="type"
label="Agreement Type"
value={values.lease_details ? values.lease_details.lease_type : ""}
/>
</Grid>
<Grid item sm>
<TextField
disabled
fullWidth
InputLabelProps={{ shrink: true }}
variant="outlined"
id="lease_start"
name="lease_start"
label="Start - End"
value={values.lease_details ? `${values.lease_details.start_date} - ${values.vacating_date}` : ''}
/>
</Grid>
</Grid>
<Grid item container spacing={2} direction="row">
<Grid item sm>
<TextField
fullWidth
type="date"
InputLabelProps={{ shrink: true }}
variant="outlined"
id="notification_date"
name="notification_date"
label="Notification Date"
value={values.notification_date}
onChange={handleChange}
onBlur={handleBlur}
error={"notification_date" in errors}
helperText={errors.notification_date}
/>
</Grid>
<Grid item sm>
<TextField
fullWidth
type="date"
InputLabelProps={{ shrink: true }}
variant="outlined"
id="vacating_date"
name="vacating_date"
label="Move Out Date"
value={values.vacating_date}
onChange={handleChange}
onBlur={handleBlur}
error={"vacating_date" in errors}
helperText={errors.vacating_date}
/>
</Grid>
</Grid>
<Grid item container direction="row" className={classes.buttonBox}>
<Grid item>
<Button
color="secondary"
variant="contained"
size="medium"
startIcon={<CancelIcon />}
onClick={() => history.goBack()}
disableElevation
>
Cancel
</Button>
</Grid>
<Grid item>
<Button
type="submit"
color="primary"
variant="contained"
size="medium"
startIcon={<SaveIcon />}
form="noticeInputForm"
disabled={isSubmitting}
>
Move Out
</Button>
</Grid>
</Grid>
</Grid>
</form>
)
}
</Formik >
);
};
export default NoticeInputForm; |
import { OperatorsRegex } from "../operators/regex"
import { TokenExpr, TokenType } from "./token"
/** List of regular expressions to scan a token */
export const TokenRegex: readonly TokenExpr[] = [
// Exponential numbers are in the form `AeB` where A and B
// are decimal numbers. The `e` can be upper or lower case.
// For example, `1.23e+4`, `0.3e5`, `1.23e-4` are all valid
// exponential numbers.
// Numbers in exponential format must be scanned before
// words, so the "e" in the exponent is not mistaken for
// the start of a word.
// Example: `1.23e+4` is a number, but `e+4` is not.
[TokenType.NUMBER_EXP, /[0-9]+(?:\.[0-9]+)?e(?:\+|-)?[0-9]+(?:\.[0-9]+)?/ig],
// Words can contain letters, numbers and underscores,
// start only with a letter or an underscore,
// and can be separated by dots. For example, `a.b_` is
// a valid word, but `a.1` or `.a_` are not.
// Words must be scanned before decimal numbers, so the
// numeric part of a word is not mistaken for a number.
// Example: `a1` is only one word token, not a word `a`
// followed by a number `1`.
// Symbol $ is also allowed in words at any position.
[TokenType.WORD, /[a-z$_](?:[a-z0-9$_]*(?:\.[a-z0-9$_]+)?)*/ig],
// Standard decimal numbers
[TokenType.NUMBER, /[0-9]+(?:\.[0-9]+)?/ig],
// Scan parentheses
[TokenType.PARANTHESIS_OPEN, /\(/ig],
[TokenType.PARANTHESIS_CLOSE, /\)/ig],
// Scan commas
[TokenType.COMMA, /,/ig],
// Scan operators.
// All registered operators must be included in this
// regular expression.
[TokenType.OPERATOR, OperatorsRegex],
] |
<div class="max-w-2xl mt-16 p-4 mx-auto">
<button mat-raised-button color="primary" routerLink="/recipes" class="mb-4">Zurück zur Rezeptliste</button>
<form #form="ngForm" class="flex flex-col gap-4">
<h1>Rezept erstellen</h1>
<mat-form-field>
<mat-label>Name</mat-label>
<input matInput name="name" placeholder="Ex. Pizza" [(ngModel)]="recipe.name" #name="ngModel" required
minlength="4" pattern="[a-zA-Z ]*">
<mat-error>{{getErrors(name)}}</mat-error>
</mat-form-field>
<mat-form-field>
<mat-label>Beschreibung</mat-label>
<textarea matInput name="description" [(ngModel)]="recipe.description"
placeholder="Beschreibung des Rezepts..." rows="7" required minlength="10"
#description="ngModel"></textarea>
<mat-error>{{getErrors(description)}}</mat-error>
</mat-form-field>
<mat-form-field>
<mat-label>YouTube-URL</mat-label>
<input matInput name="link" [(ngModel)]="recipe.link" required minlength="5" #link="ngModel">
<mat-error>{{getErrors(link)}}</mat-error>
</mat-form-field>
<app-ingredients-form [(ingredients)]="recipe.ingredients"></app-ingredients-form>
<button mat-raised-button color="primary" [disabled]="form.invalid || ingredientsFormComponent?.invalid"
(click)="save()">Speichern</button>
</form>
</div> |
# Leetcode question 283: Move Zeros
# Given an integer array nums, move all 0's to the end of it while
# maintaining the relative order of the non-zero elements.
# Do not return anything modify nums in-place
def moveZeroes(nums: list[int]) -> None:
# create two pointers that start at zero
i = 0
j = 0
# loop until j is greater than the length of nums
while j < len(nums):
# check if the value of the j as index of nums is not 0
if nums[j] != 0:
# once nums[j] != 0, check if value of i != current value of j
if i != j:
# swap values of nums[i] for nums[j]
nums[i], nums[j] = nums[j], nums[i]
# increment i to increase pointer value
i += 1
# increment j to increase index pointer value if j = 0 or after swap
j += 1
# Test Cases
print(moveZeroes([0, 1, 0, 3, 12])) # [0, 0, 1, 3, 12]
print(moveZeroes([0, 0, 1])) # [0, 0, 1] |
package de.muenchen.isi.domain.service;
import de.muenchen.isi.domain.exception.AbfrageStatusNotAllowedException;
import de.muenchen.isi.domain.exception.BauvorhabenNotReferencedException;
import de.muenchen.isi.domain.exception.EntityIsReferencedException;
import de.muenchen.isi.domain.exception.EntityNotFoundException;
import de.muenchen.isi.domain.exception.FileHandlingFailedException;
import de.muenchen.isi.domain.exception.FileHandlingWithS3FailedException;
import de.muenchen.isi.domain.exception.OptimisticLockingException;
import de.muenchen.isi.domain.exception.UniqueViolationException;
import de.muenchen.isi.domain.mapper.BauvorhabenDomainMapper;
import de.muenchen.isi.domain.mapper.SearchDomainMapper;
import de.muenchen.isi.domain.model.AbfrageModel;
import de.muenchen.isi.domain.model.BauvorhabenModel;
import de.muenchen.isi.domain.model.infrastruktureinrichtung.InfrastruktureinrichtungModel;
import de.muenchen.isi.domain.model.search.response.AbfrageSearchResultModel;
import de.muenchen.isi.domain.model.search.response.InfrastruktureinrichtungSearchResultModel;
import de.muenchen.isi.domain.service.filehandling.DokumentService;
import de.muenchen.isi.infrastructure.entity.Abfrage;
import de.muenchen.isi.infrastructure.entity.common.GlobalCounter;
import de.muenchen.isi.infrastructure.entity.common.Stadtbezirk;
import de.muenchen.isi.infrastructure.entity.common.Verortung;
import de.muenchen.isi.infrastructure.entity.enums.CounterType;
import de.muenchen.isi.infrastructure.entity.enums.lookup.StatusAbfrage;
import de.muenchen.isi.infrastructure.entity.infrastruktureinrichtung.Infrastruktureinrichtung;
import de.muenchen.isi.infrastructure.repository.AbfrageRepository;
import de.muenchen.isi.infrastructure.repository.AbfragevarianteRepository;
import de.muenchen.isi.infrastructure.repository.BauvorhabenRepository;
import de.muenchen.isi.infrastructure.repository.InfrastruktureinrichtungRepository;
import de.muenchen.isi.infrastructure.repository.common.GlobalCounterRepository;
import de.muenchen.isi.infrastructure.repository.common.KommentarRepository;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.stereotype.Service;
@Slf4j
@Service
@RequiredArgsConstructor
public class BauvorhabenService {
private final BauvorhabenDomainMapper bauvorhabenDomainMapper;
private final SearchDomainMapper searchDomainMapper;
private final BauvorhabenRepository bauvorhabenRepository;
private final AbfrageRepository abfrageRepository;
private final AbfragevarianteRepository abfragevarianteRepository;
private final InfrastruktureinrichtungRepository infrastruktureinrichtungRepository;
private final GlobalCounterRepository globalCounterRepository;
private final AbfrageService abfrageService;
private final DokumentService dokumentService;
private final KommentarRepository kommentarRepository;
/**
* Die Methode gibt ein {@link BauvorhabenModel} identifiziert durch die ID zurück.
*
* @param id zum Identifizieren des {@link BauvorhabenModel}.
* @return {@link BauvorhabenModel}.
*/
public BauvorhabenModel getBauvorhabenById(final UUID id) throws EntityNotFoundException {
final var optEntity = this.bauvorhabenRepository.findById(id);
final var entity = optEntity.orElseThrow(() -> {
final var message = "Bauvorhaben nicht gefunden";
log.error(message);
return new EntityNotFoundException(message);
});
return this.bauvorhabenDomainMapper.entity2Model(entity);
}
/**
* Diese Methode speichert ein {@link BauvorhabenModel}.
*
* @param bauvorhaben zum Speichern
* @param abfrageId ID der Abfrage bei einer Datenübernahme
* @return das gespeicherte {@link BauvorhabenModel}
* @throws UniqueViolationException falls der Name des Bauvorhabens {@link BauvorhabenModel#getNameVorhaben()} bereits vorhanden ist
* @throws OptimisticLockingException falls in der Anwendung bereits eine neuere Version der Entität gespeichert ist
* @throws EntityNotFoundException falls bei der Datenübernahme die ausgewählte Abfrage nicht mehr vorhanden ist
* @throws EntityIsReferencedException falls bei der Datenübernahme die ausgewählte Abfrage bereits ein Bauvorhaben referenziert
*/
public BauvorhabenModel saveBauvorhaben(final BauvorhabenModel bauvorhaben, final UUID abfrageId)
throws UniqueViolationException, OptimisticLockingException, EntityNotFoundException, EntityIsReferencedException {
var bauvorhabenEntity = this.bauvorhabenDomainMapper.model2Entity(bauvorhaben);
final var saved = this.bauvorhabenRepository.findByNameVorhabenIgnoreCase(bauvorhabenEntity.getNameVorhaben());
if ((saved.isPresent() && saved.get().getId().equals(bauvorhabenEntity.getId())) || saved.isEmpty()) {
try {
if (StringUtils.isEmpty(bauvorhaben.getBauvorhabenNummer())) {
bauvorhabenEntity.setBauvorhabenNummer(
this.buildBauvorhabennummer(bauvorhabenEntity.getVerortung())
);
}
bauvorhabenEntity = this.bauvorhabenRepository.saveAndFlush(bauvorhabenEntity);
// falls bei Neuanlage eines Bauvorhabens eine Datenübernahme mit einer Abfrage durchgeführt wurde, dann wird diese mit dem Bauvorhaben verknüpft
if (bauvorhaben.getId() == null && abfrageId != null) {
final var abfrageModel = this.abfrageService.getById(abfrageId);
this.throwEntityIsReferencedExceptionWhenAbfrageIsReferencingBauvorhaben(
abfrageModel,
bauvorhabenEntity.getNameVorhaben()
);
abfrageModel.setBauvorhaben(bauvorhabenEntity.getId());
abfrageService.save(abfrageModel);
}
} catch (final ObjectOptimisticLockingFailureException exception) {
final var message = "Die Daten wurden in der Zwischenzeit geändert. Bitte laden Sie die Seite neu!";
throw new OptimisticLockingException(message, exception);
}
return this.bauvorhabenDomainMapper.entity2Model(bauvorhabenEntity);
} else {
throw new UniqueViolationException(
"Der angegebene Name des Bauvorhabens ist schon vorhanden, bitte wählen Sie daher einen anderen Namen und speichern Sie die Abfrage erneut."
);
}
}
/**
* Diese Methode updated ein {@link BauvorhabenModel}.
*
* @param bauvorhaben zum Updaten
* @return das geupdatete {@link BauvorhabenModel}
* @throws EntityNotFoundException falls das Bauvorhaben identifiziert durch die {@link BauvorhabenModel#getId()} nicht gefunden wird
* @throws UniqueViolationException falls der Name des Bauvorhabens {@link BauvorhabenModel#getNameVorhaben()} bereits vorhanden ist
* @throws OptimisticLockingException falls in der Anwendung bereits eine neuere Version der Entität gespeichert ist
* @throws FileHandlingFailedException falls es beim Dateihandling zu einem Fehler gekommen ist.
* @throws FileHandlingWithS3FailedException falls es beim Dateihandling im S3-Storage zu einem Fehler gekommen ist.
* @throws EntityIsReferencedException falls bei Neuanlage eines Bauvorhabens bei Datenübernahme einer Abfrage diese bereits ein Bauvorhaben referenziert
*/
public BauvorhabenModel updateBauvorhaben(final BauvorhabenModel bauvorhaben)
throws EntityNotFoundException, UniqueViolationException, OptimisticLockingException, FileHandlingFailedException, FileHandlingWithS3FailedException, EntityIsReferencedException {
final var originalBauvorhabenDb = this.getBauvorhabenById(bauvorhaben.getId());
dokumentService.deleteDokumenteFromOriginalDokumentenListWhichAreMissingInParameterAdaptedDokumentenListe(
bauvorhaben.getDokumente(),
originalBauvorhabenDb.getDokumente()
);
return this.saveBauvorhaben(bauvorhaben, null);
}
/**
* Diese Methode löscht ein {@link BauvorhabenModel}.
*
* @param id zum Identifizieren des {@link BauvorhabenModel}.
* @throws EntityNotFoundException falls das Bauvorhaben identifiziert durch die {@link BauvorhabenModel#getId()} nicht gefunden wird.
* @throws EntityIsReferencedException falls das {@link BauvorhabenModel} in einer Abfrage referenziert wird.
*/
public void deleteBauvorhaben(final UUID id) throws EntityNotFoundException, EntityIsReferencedException {
final var bauvorhaben = this.getBauvorhabenById(id);
this.throwEntityIsReferencedExceptionWhenAbfrageIsReferencingBauvorhaben(bauvorhaben);
this.throwEntityIsReferencedExceptionWhenInfrastruktureinrichtungIsReferencingBauvorhaben(bauvorhaben);
this.kommentarRepository.deleteAllByBauvorhabenId(id);
this.bauvorhabenRepository.deleteById(id);
}
/**
* Diese Methode setzt in einem {@link BauvorhabenModel} eine neue relevante Abfragevariante.
* Ist diese Abfragevariante bereits relevant, wird die relevante Abfragevariante des Bauvorhabens auf null gesetzt.
* Ist eine andere Abfragevariante bereits relevant, wird eine Exception geworfen.
* Die Abfrage muss sich im Status {@link StatusAbfrage#IN_BEARBEITUNG_SACHBEARBEITUNG} befinden.
*
* @param abfragevarianteId als ID der neuen relevanten Abfragevariante
* @return das aktualisierte {@link BauvorhabenModel}
* @throws EntityNotFoundException falls die Abfrage oder Abfragevariante nicht gefunden wurde
* @throws UniqueViolationException falls schon eine andere Abfragevariante relevant ist
* @throws OptimisticLockingException falls in der Anwendung bereits eine neuere Version der Entität gespeichert ist
* @throws AbfrageStatusNotAllowedException falls die Abfrage den falschen Status hat
* @throws BauvorhabenNotReferencedException falls die Abfrage zu keinem Bauvorhaben gehört
*/
public BauvorhabenModel changeRelevanteAbfragevariante(final UUID abfragevarianteId)
throws EntityNotFoundException, UniqueViolationException, OptimisticLockingException, AbfrageStatusNotAllowedException, BauvorhabenNotReferencedException, EntityIsReferencedException {
final AbfrageModel abfrage = abfrageService.getByAbfragevarianteId(abfragevarianteId);
abfrageService.throwAbfrageStatusNotAllowedExceptionWhenStatusAbfrageIsInvalid(
abfrage,
StatusAbfrage.IN_BEARBEITUNG_SACHBEARBEITUNG
);
final var bauvorhabenId = abfrage.getBauvorhaben();
if (bauvorhabenId == null) {
String message =
"Die Abfrage ist keinem Bauvorhaben zugeordnet. Somit kann keine Abfragevariante als relevant markiert werden.";
log.error(message);
throw new BauvorhabenNotReferencedException(message);
}
final var bauvorhaben = this.getBauvorhabenById(bauvorhabenId);
final var relevanteAbfragevarianteId = bauvorhaben.getRelevanteAbfragevariante();
if (relevanteAbfragevarianteId != null) {
if (!relevanteAbfragevarianteId.equals(abfragevarianteId)) {
final var relevanteAbfragevariante = abfragevarianteRepository
.findById(relevanteAbfragevarianteId)
.orElseThrow(() -> {
final var message = "Abfragevariante nicht gefunden.";
log.error(message);
return new EntityNotFoundException(message);
});
var errorMessage =
"Die Abfragevariante " +
relevanteAbfragevariante.getName() +
" in Abfrage " +
abfrage.getName() +
" ist bereits als relevant markiert.";
log.error(errorMessage);
throw new UniqueViolationException(errorMessage);
} else {
bauvorhaben.setRelevanteAbfragevariante(null);
}
} else {
bauvorhaben.setRelevanteAbfragevariante(abfragevarianteId);
}
return this.saveBauvorhaben(bauvorhaben, null);
}
/**
* Die Methode gibt alle {@link InfrastruktureinrichtungSearchResultModel} als Liste zurück sortiert nach InfrastrukturTyp und innerhalb
* des InfrastrukturTyps alphabetisch aufsteigend welche einem Bauvorhaben zugeordnet sind.
*
* @param bauvorhabenId zum Identifizieren des {@link BauvorhabenModel}
* @return Liste von {@link InfrastruktureinrichtungSearchResultModel} welche einem Bauvorhaben zugeordent sind
*/
public List<InfrastruktureinrichtungSearchResultModel> getReferencedInfrastruktureinrichtungen(
final UUID bauvorhabenId
) {
return this.infrastruktureinrichtungRepository.findAllByBauvorhabenId(bauvorhabenId)
.map(this.searchDomainMapper::entity2SearchResultModel)
.sorted(
Comparator
.comparing(InfrastruktureinrichtungSearchResultModel::getInfrastruktureinrichtungTyp)
.thenComparing(InfrastruktureinrichtungSearchResultModel::getNameEinrichtung)
)
.collect(Collectors.toList());
}
/**
* Die Methode gibt alle {@link AbfrageSearchResultModel} als Liste zurück sortiert nach Erstellungsdatum aufsteigend
* welche einem Bauvorhaben zugeordnet sind.
*
* @param bauvorhabenId zum Identifizieren des {@link BauvorhabenModel}
* @return Liste von {@link AbfrageSearchResultModel} welche einem Bauvorhaben zugeordent sind
*/
public List<AbfrageSearchResultModel> getReferencedAbfrage(final UUID bauvorhabenId) {
return this.abfrageRepository.findAllByBauvorhabenIdOrderByCreatedDateTimeDesc(bauvorhabenId)
.map(this.searchDomainMapper::entity2SearchResultModel)
.map(AbfrageSearchResultModel.class::cast)
.collect(Collectors.toList());
}
/**
* Wird das im Parameter gegebene {@link BauvorhabenModel} durch ein {@link AbfrageModel} referenziert,
* wird eine {@link EntityIsReferencedException} geworfen.
*
* @param bauvorhaben zum Prüfen.
* @throws EntityIsReferencedException falls das {@link BauvorhabenModel} durch ein {@link AbfrageModel} referenziert wird.
*/
protected void throwEntityIsReferencedExceptionWhenAbfrageIsReferencingBauvorhaben(
final BauvorhabenModel bauvorhaben
) throws EntityIsReferencedException {
final List<String> nameAbfragen =
this.abfrageRepository.findAllByBauvorhabenId(bauvorhaben.getId())
.map(Abfrage::getName)
.collect(Collectors.toList());
if (!nameAbfragen.isEmpty()) {
final var commaSeparatedNames = String.join(", ", nameAbfragen);
final var message =
"Das Bauvorhaben " +
bauvorhaben.getNameVorhaben() +
" wird durch die Abfragen " +
commaSeparatedNames +
" referenziert.";
log.error(message);
throw new EntityIsReferencedException(message);
}
}
/**
* Wird das im Parameter gegebene {@link BauvorhabenModel} durch ein {@link InfrastruktureinrichtungModel} referenziert,
* wird eine {@link EntityIsReferencedException} geworfen.
*
* @param bauvorhaben zum Prüfen.
* @throws EntityIsReferencedException falls das {@link BauvorhabenModel} durch ein {@link InfrastruktureinrichtungModel} referenziert wird.
*/
protected void throwEntityIsReferencedExceptionWhenInfrastruktureinrichtungIsReferencingBauvorhaben(
final BauvorhabenModel bauvorhaben
) throws EntityIsReferencedException {
final List<String> namenInfrastruktureinrichtung =
this.infrastruktureinrichtungRepository.findAllByBauvorhabenId(bauvorhaben.getId())
.map(Infrastruktureinrichtung::getNameEinrichtung)
.collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(namenInfrastruktureinrichtung)) {
final var commaSeparatedNames = String.join(", ", namenInfrastruktureinrichtung);
final var message =
"Das Bauvorhaben " +
bauvorhaben.getNameVorhaben() +
" wird durch die Infrastruktureinrichtungen " +
commaSeparatedNames +
" referenziert.";
log.error(message);
throw new EntityIsReferencedException(message);
}
}
protected void throwEntityIsReferencedExceptionWhenAbfrageIsReferencingBauvorhaben(
final AbfrageModel abfrage,
final String nameBauvorhaben
) throws EntityIsReferencedException {
final var bauvorhaben = abfrage.getBauvorhaben();
if (ObjectUtils.isNotEmpty(bauvorhaben)) {
final var message =
"Die Abfrage " + abfrage.getName() + " referenziert das Bauvorhaben " + nameBauvorhaben + ".";
log.error(message);
throw new EntityIsReferencedException(message);
}
}
/**
* Leitet aus der Verortung die Bauvorhabennummer ab. Aufbau: {kleinste Stadtbezirksnummer}_{fortlaufende Bauvorhabennummer}
*
* @param verortung Verortung des Bauvorhabens
* @return ermittelte Bauvorhabennummer
* @throws OptimisticLockingException im Falle eines konkurrierenden Zugriffs auf die globale fortlaufende Bauvorhabennummer
*/
private String buildBauvorhabennummer(Verortung verortung) throws OptimisticLockingException {
if (verortung != null) {
final Optional<String> minStadtbezirkNummer = CollectionUtils
.emptyIfNull(verortung.getStadtbezirke())
.stream()
.map(Stadtbezirk::getNummer)
.filter(Objects::nonNull)
.min(String::compareTo);
if (!minStadtbezirkNummer.isEmpty()) {
final Optional<GlobalCounter> saved =
this.globalCounterRepository.findByCounterType(CounterType.NUMMER_BAUVORHABEN);
var bauvorhabennummerEntity = saved.isPresent()
? saved.get()
: new GlobalCounter(CounterType.NUMMER_BAUVORHABEN, 0);
bauvorhabennummerEntity.setCounter(bauvorhabennummerEntity.getCounter() + 1);
try {
bauvorhabennummerEntity = this.globalCounterRepository.saveAndFlush(bauvorhabennummerEntity);
return String.format(
"%s_%s",
minStadtbezirkNummer.get(),
StringUtils.leftPad(String.valueOf(bauvorhabennummerEntity.getCounter()), 4, "0")
);
} catch (final ObjectOptimisticLockingFailureException exception) {
final var message = "Die Daten wurden in der Zwischenzeit geändert. Bitte laden Sie die Seite neu!";
throw new OptimisticLockingException(message, exception);
}
}
}
return null;
}
} |
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DS3231.h>
#include <NewPing.h>
#include <math.h> // Bibliothèque pour utiliser la constante pi
// Définition des dimensions de l'écran OLED
#define SCREEN_WIDTH 128 // Largeur de l'écran OLED en pixels
#define SCREEN_HEIGHT 64 // Hauteur de l'écran OLED en pixels
#define OLED_RESET -1 // Numéro de la broche de réinitialisation (ou -1 si elle partage la broche de réinitialisation de l'Arduino)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
DS3231 myRTC; // Objet pour le module d'horloge en temps réel
// Définition des broches pour le capteur à ultrasons
#define TRIGGER_PIN 3 // Broche Arduino connectée à la broche de déclenchement du capteur à ultrasons
#define ECHO_PIN 2 // Broche Arduino connectée à la broche d'écho du capteur à ultrasons
#define MAX_DISTANCE 200 // Distance maximale que nous voulons mesurer (en centimètres). La distance maximale du capteur est évaluée à 400-500cm
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // Configuration de NewPing avec les broches et la distance maximale
// Définition des broches pour les boutons
#define BUTTON1_PIN 4 // Broche Arduino connectée au bouton de réglage de l'heure et de la date
#define BUTTON2_PIN 5 // Broche Arduino connectée au bouton de changement d'affichage
#define BUTTON3_PIN 6 // Broche Arduino connectée au bouton de mesure immédiate du niveau d'eau
// Énumération pour les différents modes de réglage de l'horloge
enum Mode {MODE_NORMAL, MODE_SET_HOUR, MODE_SET_MINUTE, MODE_SET_DAY, MODE_SET_MONTH, MODE_SET_YEAR};
Mode mode = MODE_NORMAL;
// Variables pour le réglage de l'heure
unsigned long lastButtonPressTime = 0;
int setHour = 0, setMinute = 0, setDay = 1, setMonth = 1, setYear = 2013;
// Variables pour la mesure de la distance
unsigned long lastMeasurementTime = 0;
#define MEASUREMENT_INTERVAL 12 * 60 * 60 * 1000 // Intervalle de mesure en millisecondes (12 heures)
// Structure pour stocker les mesures
struct Measurement {
int distance; // Distance mesurée
float volume; // Volume calculé
int hour, minute, day, month, year; // Date et heure de la mesure
};
Measurement measurements[10]; // Tableau pour stocker les 10 dernières mesures
// Énumération pour les différents modes d'affichage
enum DisplayMode {DISPLAY_VOLUME, DISPLAY_HISTORY, DISPLAY_TIME};
DisplayMode displayMode = DISPLAY_VOLUME;
// Constantes pour la cuve
#define RADIUS_INTERIOR 1170 // Rayon intérieur de la cuve en mm
#define HEIGHT_TRUNCATED 880 // Hauteur du segment tronqué intérieur en mm
#define HEIGHT_MAX 1520 // Hauteur maximale d'eau dans la cuve en mm
#define SENSOR_HEIGHT 300 // Hauteur du capteur au-dessus du trop-plein d'eau en mm
// Fonction pour calculer le volume en fonction de la distance mesurée
float calculateVolume(int distance) {
float h = HEIGHT_MAX + SENSOR_HEIGHT - distance * 10; // Conversion de la distance en hauteur d'eau en mm
if (h < 0) h = 0;
if (h <= HEIGHT_TRUNCATED) {
return (M_PI * h * h / 3) * (3 * RADIUS_INTERIOR - h) / 1000; // Formule pour le volume d'un segment sphérique en litres
} else {
float h_truncated = HEIGHT_MAX - h;
return (4.0 / 3.0 * M_PI * RADIUS_INTERIOR * RADIUS_INTERIOR * RADIUS_INTERIOR
- M_PI * h_truncated * h_truncated / 3 * (3 * RADIUS_INTERIOR - h_truncated)) / 1000; // Formule pour le volume d'une sphère tronquée en litres
}
}
void setup() {
Serial.begin (9600); // Commencer la communication série à 9600 bauds
Wire.begin(); // Commencer la communication avec le module d'horloge en temps réel
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // Initialiser l'écran OLED avec l'adresse I2C 0x3C (pour le 128x64)
pinMode(BUTTON1_PIN, INPUT_PULLUP); // Définir la broche du bouton comme entrée avec résistance de rappel interne
pinMode(BUTTON2_PIN, INPUT_PULLUP); // Définir la broche du bouton comme entrée avec résistance de rappel interne
pinMode(BUTTON3_PIN, INPUT_PULLUP); // Définir la broche du bouton comme entrée avec résistance de rappel interne
}
void loop() {
// Mesure de la distance si l'intervalle de mesure est écoulé ou si le bouton de mesure est pressé
if (millis() - lastMeasurementTime >= MEASUREMENT_INTERVAL || (digitalRead(BUTTON3_PIN) == LOW && mode == MODE_NORMAL)) {
lastMeasurementTime = millis();
lastButtonPressTime = millis();
delay(50); // Délai entre les pings
unsigned int uS = sonar.ping(); // Mesure du temps de ping en microsecondes
int distance = uS / US_ROUNDTRIP_CM; // Conversion du temps de ping en distance en cm
float volume = calculateVolume(distance); // Calcul du volume en litres
Serial.println(distance); // Envoi de la distance à la console série
// Affichage de la distance et du volume sur l'écran OLED
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.println("Distance:");
display.println(distance);
display.println("Volume:");
display.println(volume);
display.display();
// Stockage de la mesure dans le tableau
for (int i = 9; i > 0; i--) {
measurements[i] = measurements[i-1];
}
measurements[0].distance = distance;
measurements[0].volume = volume;
bool h12, PM_time, Century;
measurements[0].hour = myRTC.getHour(h12, PM_time);
measurements[0].minute = myRTC.getMinute();
measurements[0].day = myRTC.getDate();
measurements[0].month = myRTC.getMonth(Century);
measurements[0].year = myRTC.getYear();
}
// Gestion du bouton de réglage de l'heure et de la date
if (digitalRead(BUTTON1_PIN) == LOW) {
lastButtonPressTime = millis();
if (mode == MODE_NORMAL) {
if (millis() - lastButtonPressTime > 10000) {
mode = MODE_SET_HOUR;
setHour = 0;
setMinute = 0;
setDay = 30;
setMonth = 10;
setYear = 2013;
}
} else {
if (millis() - lastButtonPressTime > 10000) {
if (mode == MODE_SET_HOUR) {
mode = MODE_SET_MINUTE;
} else if (mode == MODE_SET_MINUTE) {
mode = MODE_SET_DAY;
} else if (mode == MODE_SET_DAY) {
mode = MODE_SET_MONTH;
} else if (mode == MODE_SET_MONTH) {
mode = MODE_SET_YEAR;
} else if (mode == MODE_SET_YEAR) {
mode = MODE_NORMAL;
myRTC.setHour(setHour);
myRTC.setMinute(setMinute);
myRTC.setDate(setDay);
myRTC.setMonth(setMonth);
myRTC.setYear(setYear);
}
} else {
if (mode == MODE_SET_HOUR) {
setHour = (setHour % 24) + 1;
} else if (mode == MODE_SET_MINUTE) {
setMinute = (setMinute % 60) + 1;
} else if (mode == MODE_SET_DAY) {
setDay = (setDay % 31) + 1;
} else if (mode == MODE_SET_MONTH) {
setMonth = (setMonth % 12) + 1;
} else if (mode == MODE_SET_YEAR) {
setYear++;
}
}
}
}
// Gestion du bouton de changement d'affichage
if (digitalRead(BUTTON2_PIN) == LOW) {
lastButtonPressTime = millis();
displayMode = (DisplayMode)((displayMode + 1) % 3);
}
// Affichage des informations en fonction du mode d'affichage
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
if (displayMode == DISPLAY_VOLUME) {
display.println("Volume:");
display.println(measurements[0].volume);
} else if (displayMode == DISPLAY_HISTORY) {
for (int i = 0; i < 10; i++) {
display.print(measurements[i].distance);
display.print(" ");
display.print(measurements[i].day);
display.print("/");
display.print(measurements[i].month);
display.print("/");
display.print(measurements[i].year);
display.print(" ");
display.print(measurements[i].hour);
display.print(":");
display.println(measurements[i].minute);
}
} else if (displayMode == DISPLAY_TIME) {
bool h12, PM_time, Century;
display.print(myRTC.getDate());
display.print("/");
display.print(myRTC.getMonth(Century));
display.print("/");
display.print(myRTC.getYear());
display.print(" ");
display.print(myRTC.getHour(h12, PM_time));
display.print(":");
display.println(myRTC.getMinute());
}
display.display();
// Éteindre l'écran OLED si aucun bouton n'a été pressé pendant une minute
if (millis() - lastButtonPressTime > 60000) {
display.ssd1306_command(SSD1306_DISPLAYOFF);
} else {
display.ssd1306_command(SSD1306_DISPLAYON);
}
} |
import React, {useState, useEffect, createContext, useContext, useCallback} from 'react';
const URL = "https://openlibrary.org/search.json?title=";
const AppContext = createContext();
const AppProvider = ({children}) => {
const [searchTerm, setSearchTerm] = useState("");
const [books, setBooks] = useState([]);
const [loading, setLoading] = useState(false);
const [resultTitle, setResultTitle] = useState("");
const fetchBooks = useCallback(async() => {
setLoading(true);
try{
const response = await fetch(`${URL}${searchTerm}`);
const data = await response.json();
const {docs} = data;
// const docs = data.docs; This is the same as the line above, which is using destructuting assignment.
if (docs) {
const newBooks = docs.slice(0,20).map((bookSingle) => {
const {key, author_name, cover_i, edition_count, first_publish_year, title} = bookSingle;
return {
id: key,
author: author_name,
cover_id: cover_i,
edition_count: edition_count,
first_publish_year: first_publish_year,
title: title
}
});
setBooks(newBooks);
if (newBooks.length>1) {
setResultTitle("Your search results:");
} else {
setResultTitle("No search results found.")
}
} else {
setBooks([]);
setResultTitle("No search results found.");
}
setLoading(false);
} catch(error){
console.log(error);
setLoading(false);
}
}, [searchTerm]);
useEffect(() => {
fetchBooks();
}, [searchTerm, fetchBooks]);
return (
<AppContext.Provider value={{loading, books, setSearchTerm, resultTitle, setResultTitle}}>
{children}
</AppContext.Provider>
)
}
export const useGlobalContext = () => {
return useContext(AppContext);
}
export {AppContext, AppProvider}; |
package com.app4web.asdzendo.paemi.ui.recycler.grid.dummy
import java.util.ArrayList
import java.util.HashMap
/**
* Helper class for providing sample content for user interfaces created by
* Android template wizards.
*
* TODO: Replace all uses of this class before publishing your app.
*/
object DummyContent {
/**
* An array of sample (dummy) items.
*/
val ITEMS: MutableList<DummyItem> = ArrayList()
/**
* A map of sample (dummy) items, by ID.
*/
private val ITEM_MAP: MutableMap<String, DummyItem> = HashMap()
private const val COUNT = 65
init {
// Add some sample items.
for (i in 1..COUNT) addItem(createDummyItem(i))
}
private fun addItem(item: DummyItem) {
ITEMS.add(item)
ITEM_MAP[item.id] = item
}
private fun createDummyItem(position: Int): DummyItem {
return DummyItem(position.toString(), "Карточка $position", makeDetails(position))
}
private fun makeDetails(position: Int): String {
val builder = StringBuilder()
builder.append("Details about Item: ").append(position)
for (i in 0 until position) {
builder.append("\nMore details information here.")
}
return builder.toString()
}
/**
* A dummy item representing a piece of content.
*/
data class DummyItem(val id: String, val content: String, val details: String) {
override fun toString(): String = content
}
} |
import React from 'react';
import { render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { createMemoryHistory } from 'history';
import { App } from './App';
describe('App component', () => {
let history;
beforeEach(() => {
history = createMemoryHistory();
render(
<MemoryRouter history={history}>
<App />
</MemoryRouter>
);
});
test('renders a Header', () => {
expect(screen.getByTestId('app-header')).toBeVisible();
});
test('renders the Home page by default', () => {
expect(screen.queryByTestId('home-page')).toBeVisible();
expect(screen.queryByTestId('todo-page')).not.toBeInTheDocument();
expect(screen.queryByTestId('chat-page')).not.toBeInTheDocument();
});
test('when the Todo header option is clicked, navigates to the Todo page', () => {
// initial conditions
expect(screen.queryByTestId('home-page')).toBeVisible();
expect(screen.queryByTestId('todo-page')).not.toBeInTheDocument();
expect(screen.queryByTestId('chat-page')).not.toBeInTheDocument();
const todoOption = screen.getAllByText('Todo')[0];
todoOption.click();
expect(screen.queryByTestId('home-page')).not.toBeInTheDocument();
expect(screen.queryByTestId('todo-page')).toBeVisible();
expect(screen.queryByTestId('chat-page')).not.toBeInTheDocument();
});
test('when the Chat header option is clicked, navigates to the Chat page', () => {
// initial conditions
expect(screen.queryByTestId('home-page')).toBeVisible();
expect(screen.queryByTestId('todo-page')).not.toBeInTheDocument();
expect(screen.queryByTestId('chat-page')).not.toBeInTheDocument();
const chatOption = screen.getAllByText('Chat')[0];
chatOption.click();
expect(screen.queryByTestId('home-page')).not.toBeInTheDocument();
expect(screen.queryByTestId('todo-page')).not.toBeInTheDocument();
expect(screen.queryByTestId('chat-page')).toBeVisible();
});
test('when the Demo Site header title is clicked, navigates to the Home page', () => {
// initial conditions
const todoOption = screen.getAllByText('Todo')[0];
todoOption.click();
expect(screen.queryByTestId('home-page')).not.toBeInTheDocument();
const homeOption = screen.getByTestId('app-header__app-name');
homeOption.click();
expect(screen.queryByTestId('home-page')).toBeVisible();
expect(screen.queryByTestId('todo-page')).not.toBeInTheDocument();
expect(screen.queryByTestId('chat-page')).not.toBeInTheDocument();
});
}); |
package com.xzp.springboot.rocketmq.config;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.bean.ConsumerBean;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.aliyun.openservices.ons.api.bean.Subscription;
import com.xzp.springboot.rocketmq.listener.DemoMessageListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* RocketMQ配置类
* @author xuzhipeng
* @date 2022/2/8
*/
@Configuration
public class RocketMqConfiguration {
@Resource
private RocketMqProperties rocketMqProperties;
@Resource
private DemoMessageListener demoMessageListener;
/**
* 生产者
* @return producerBean
*/
@Bean(initMethod = "start", destroyMethod = "shutdown")
public ProducerBean producerBean() {
ProducerBean producer = new ProducerBean();
Properties properties = rocketMqProperties.getMqProperties();
producer.setProperties(properties);
return producer;
}
/**
* 消费者
* @return demoConsumer
*/
@Bean(name = "demoConsumer", initMethod = "start", destroyMethod = "shutdown")
public ConsumerBean demoConsumer() {
ConsumerBean consumerBean = new ConsumerBean();
//配置文件
Properties properties = rocketMqProperties.getMqProperties();
properties.setProperty(PropertyKeyConst.GROUP_ID, rocketMqProperties.getGroupId());
//将消费者线程数固定为20个 20为默认值
properties.setProperty(PropertyKeyConst.ConsumeThreadNums, "20");
consumerBean.setProperties(properties);
//订阅关系
Map<Subscription, MessageListener> subscriptionTable = new HashMap<>(1);
Subscription subscription = new Subscription();
subscription.setTopic(rocketMqProperties.getTopic());
subscription.setExpression(rocketMqProperties.getTag());
subscriptionTable.put(subscription, demoMessageListener);
consumerBean.setSubscriptionTable(subscriptionTable);
return consumerBean;
}
} |
import React, { useState, useEffect } from 'react';
import { useSelector } from 'react-redux';
import { RootState } from '../../store/storeConfig';
import { Container, Paper } from '@mui/material';
import { useStyles } from './style';
import { Theme, useMediaQuery } from '@material-ui/core';
import { Alert } from '../../components';
interface Props {
children: React.ReactNode;
}
const DefaultLayout: React.FC<Props> = props => {
const { children } = props;
const classes = useStyles();
const isMdUp = useMediaQuery((theme: Theme) => theme.breakpoints.up('md'));
const { error, loading } = useSelector((state: RootState) => state.users);
const [isOpen, setIsOpen] = useState(false);
useEffect(() => {
if (error && !loading) {
setIsOpen(true);
setTimeout(() => {
setIsOpen(false);
}, 700);
} else if (!error) {
setIsOpen(false);
}
}, [error, loading]);
return (
<>
<div className={classes.root}>
<Container className={classes.root}>
{!isMdUp ? (
<>
<Container maxWidth="sm">
<div className={classes.content}>
<Paper className={classes.paperMobile} elevation={16}>
{children}
</Paper>
</div>
</Container>
</>
) : (
<>
<Container maxWidth="md">
<div className={classes.content}>
<Paper className={classes.paper} elevation={16}>
{children}
</Paper>
</div>
</Container>
</>
)}
</Container>
</div>
{isOpen && <Alert />}
</>
);
};
export default DefaultLayout; |
import {
Body,
Controller,
Param,
Post,
UseGuards,
Get,
Put,
} from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { ProgressService } from './progress.service';
import JwtAuthenticationGuard from 'src/auth/guards/jwt-authentiacation.guard';
import { RolesGuard } from 'src/guards/roles.guard';
import { Roles } from 'src/decorators/roles.decorator';
import { Role } from '@prisma/client';
import { CreateProgressesDto } from './dto/CreateProgressesDto';
import {
UpdateMenteeAcceptedProgressesDto,
UpdateMentorAcceptedProgressesDto,
UpdateProgressesDto,
} from './dto/UpdateProgressDto';
@Controller('mentor/:mentorId/sessions/:sessionId/progress')
@ApiTags('Progress Program Register')
@ApiBearerAuth()
export class ProgressController {
constructor(private readonly progressService: ProgressService) {}
@Post('/')
@UseGuards(JwtAuthenticationGuard, RolesGuard)
@Roles(Role.MENTOR)
@ApiOperation({ summary: 'Mentor create progress for register program' })
createProgresses(
@Param('sessionId') sessionId: string,
@Body() dto: CreateProgressesDto[],
) {
return this.progressService.create(+sessionId, dto);
}
@Put('/:id')
@UseGuards(JwtAuthenticationGuard, RolesGuard)
@Roles(Role.MENTOR)
@ApiOperation({ summary: 'Mentor modify progress for register program' })
modifyProgresses(@Param('id') id: string, @Body() dto: UpdateProgressesDto) {
return this.progressService.update(+id, dto);
}
@Put('/:id/finishAccepted')
@UseGuards(JwtAuthenticationGuard, RolesGuard)
@Roles(Role.MENTOR)
@ApiOperation({
summary: 'Mentor modify mentor accepted progress for register program',
})
modifyMentorAcceptedProgresses(
@Param('id') id: string,
@Body() dto: UpdateMentorAcceptedProgressesDto,
) {
return this.progressService.mentorUpdate(+id, dto);
}
@Put('/:id/finished')
@UseGuards(JwtAuthenticationGuard, RolesGuard)
@Roles(Role.MENTEE)
@ApiOperation({
summary: 'Mentor modify mentee accepted progress for register program',
})
modifyMenteeAcceptedProgresses(
@Param('id') id: string,
@Body() dto: UpdateMenteeAcceptedProgressesDto,
) {
return this.progressService.menteeUpdate(+id, dto);
}
@Get('/')
@UseGuards(JwtAuthenticationGuard, RolesGuard)
@Roles(Role.MENTOR, Role.MENTEE)
@ApiOperation({ summary: 'Get progress for register program' })
getProgress(@Param('sessionId') sessionId: string) {
return this.progressService.get(+sessionId);
}
} |
class Solution {
public:
void reverseString(vector<char>& s) {
int n = s.size();
int l=0,h=n-1;
while(l<h){
swap(s[l],s[h]);
l++;
h--;
}
}
};
// Another Solution
class Solution {
public:
void reverseString(vector<char>& s) {
for(int i=0, j=s.size()-1; i<j ; i++, j--){
swap(s[i],s[j]);
}
}
};
// Another Solution
class Solution {
public:
void reverseString(vector<char>& s) {
reverse(s.begin(),s.end());
}
};
// Another Solution
class Solution {
public:
string reverseString(string s) {
int n = s.size();
for(int i = 0; i < n/2; i++) {
swap(s[i], s[n - 1 - i]);
}
return s;
}
}; |
import os.path
from PIL import Image
from torch.utils.data import Dataset
class CustomDataset(Dataset):
def __init__(self, txt_file, root_folder, transform=None):
self.txt_file = txt_file
self.transform = transform
self.root_folder = root_folder
self.data = self._load_data()
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
img_name, label = self.data[idx]
img_path = os.path.join(self.root_folder, img_name)
image = Image.open(img_path).convert("RGB")
if self.transform:
image = self.transform(image)
return image, label
def _load_data(self):
data = []
with open(self.txt_file, "r") as file:
for line in file:
img_name, label = line.strip().split()
label = int(label)
data.append((img_name, label))
return data |
""""
Copyright © Krypton 2019-2023 - https://github.com/kkrypt0nn (https://krypton.ninja)
Description:
🐍 A simple template to start to code your own and personalized discord bot in Python programming language.
Version: 5.5.0
"""
import json
import http.client
import discord
from discord.ext import commands
from discord.ext.commands import Context
from datetime import date
from helpers import checks
# Here we name the cog and create a new class for the cog.
class NFL(commands.Cog, name="nfl"):
def __init__(self, bot):
self.bot = bot
self.nfl_headers = {
'x-rapidapi-host': "v1.american-football.api-sports.io",
'x-rapidapi-key': self.bot.config['SPORTS_TOKEN']
}
# Here you can just add your own commands, you'll always need to provide "self" as first parameter.
@commands.hybrid_group(
name="nfl",
description="Get NFL information.",
)
async def nfl(self, context: Context) -> None:
if context.invoked_subcommand is None:
embed = discord.Embed(
description="Please specify a subcommand.",
color=0xE02B2B
)
await context.send(embed=embed)
@nfl.command(
name="live",
description="Get live NFL scores.",
)
@checks.not_blacklisted()
async def nfl_live(self, ctx):
nfl_conn = http.client.HTTPSConnection("v1.american-football.api-sports.io")
endpoint="games?live=all"
nfl_conn.request("GET", "/"+endpoint, headers=self.nfl_headers)
res = nfl_conn.getresponse()
data = res.read()
response = json.loads(data.decode("utf-8"))
print(response)
games = response["response"]
if len(games) > 0:
await ctx.send(f'{len(games)} games today.')
for g in games:
print(json.dumps(g, indent=4))
team_json = g['teams']
score_json = g['scores']
status_json = g['game']
periods_json = g['game']
#print(json.dumps(team_json, indent=4))
#print(json.dumps(score_json, indent=4))
home_team = team_json['home']['name']
away_team = team_json['away']['name']
home_score = score_json['home']['total']
away_score = score_json['away']['total']
current_clock = status_json['status']['timer']
current_quarter = periods_json['status']['short']
#print(f'{home_team} ({home_score}) -- {away_team} ({away_score})')
await ctx.send(f'```{home_team} ({home_score}) -- {away_team} ({away_score}) | Clock: {current_clock} Quarter: {current_quarter}```')
else:
await ctx.send('No live games right now!')
@nfl.command(
name="today",
description="Get today's NFL games.",
)
@checks.not_blacklisted()
async def nfl_today(self, ctx):
nfl_conn = http.client.HTTPSConnection("v1.american-football.api-sports.io")
endpoint="games?league=1&season=2022&date=" + str(date.today())
nfl_conn.request("GET", "/"+endpoint, headers=self.nfl_headers)
res = nfl_conn.getresponse()
data = res.read()
response = json.loads(data.decode("utf-8"))
print(response)
games = response["response"]
if len(games) > 0:
await ctx.send(f'{len(games)} games today.')
for g in games:
print(json.dumps(g, indent=4))
team_json = g['teams']
score_json = g['scores']
status_json = g['game']
periods_json = g['game']
#print(json.dumps(team_json, indent=4))
#print(json.dumps(score_json, indent=4))
home_team = team_json['home']['name']
away_team = team_json['away']['name']
home_score = score_json['home']['total']
away_score = score_json['away']['total']
current_clock = status_json['status']['timer']
current_quarter = periods_json['status']['short']
#print(f'{home_team} ({home_score}) -- {away_team} ({away_score})')
await ctx.send(f'```{home_team} ({home_score}) -- {away_team} ({away_score}) | Clock: {current_clock} Quarter: {current_quarter}```')
else:
await ctx.send('No games today!')
# And then we finally add the cog to the bot so that it can load, unload, reload and use it's content.
async def setup(bot):
await bot.add_cog(NFL(bot)) |
# The emails vector has already been defined for you
emails <- c("john.doe@ivyleague.edu", "education@world.gov", "dalai.lama@peace.org",
"invalid.edu", "quant@bigdatacollege.edu", "cookie.monster@sesame.tv")
# Use grepl() to match for .edu addresses more robustly See how metacharacters were used.
grepl(pattern="@.*\\.edu", x=emails)
# Use grep() to match for .edu addresses more robustly, save result to hits
hits <- grep(pattern="@.*\\.edu", x=emails)
# Subset emails using hits
emails[hits] |
<?php
namespace App\Listeners\Transaction\Created;
use Error;
use Exception;
use App\Models\Setting;
use App\Events\Transaction;
use App\Models\Transaction as TransactionModel;
use Illuminate\Support\Facades\Log;
class InvoiceListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param Transaction\Created $event
* @return void
*/
public function handle(Transaction\Created $event)
{
try {
$transaction = $event->getTransaction();
$settings = Setting::whereIn("key", $this->_invoiceHeaderInfo())->pluck("value", "key")->toArray();
$transaction = $transaction->load([
"orders.orderProducts.product",
]);
$pdf = \PDF::loadView('admin.transaction.invoice_pdf', compact("settings", "transaction"));
$fileName = "order_invoice_" . $transaction->id . "_" . time() . ".pdf";
$path = "pdf_temp/" . $fileName;
$fullPath = public_path($path);
$pdf->save($fullPath);
$transaction->addMedia($fullPath)
->usingName($fileName)
->setFileName($fileName)
->toMediaCollection(TransactionModel::MEDIA_COLLECTION_NAME);
} catch (Exception | Error $e) {
Log::channel("transaction-events-errors")->error("Exception in InvoiceListener: ". $e->getMessage());
}
}
/**
* Array of invoice header info.
*/
private function _invoiceHeaderInfo() : array
{
return [
"site_logo",
"address",
"zip_code",
"legal_registration_no",
"email",
"website",
"phone",
"tax_no"
];
}
} |
// Require necessary files
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Intents } = require('discord.js');
const token = process.env['TOKEN'];
// New client instance with specified intents
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
// Read commands
client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
client.commands.set(command.data.name, command);
}
// Notify that the bot is online
client.once('ready', () => {
console.log(`Ready! Logged in as ${client.user.tag}`);
});
// Dynamically execute commands
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
// Login to Discord
client.login("ton token"); |
from celery import shared_task
from django.utils import timezone
from datetime import timedelta
from loan.models import Loan, Repayment
from company.models import SmsSetting, SystemSetting, TemplateSetting
from .loan_math import update_due_amount,get_previous_due_date, update_credit_score, total_penalty,get_interval_period
from .sms_messages import send_sms, send_email
from .mpesa_api import disburse_loan
#task to mark a loan as overdue
@shared_task
def mark_loans_as_overdue():
today = timezone.now().date()
# Find all loans that are due but not yet cleared or marked as overdue
loans = Loan.objects.filter(due_date__date__lt=today).exclude(status__in=['cleared', 'overdue', 'written off', 'rolled over'])
for loan in loans:
previous_due_date = get_previous_due_date(loan).date()
# Check if there are any repayments made by the borrower for the loan
repayments = Repayment.objects.filter(
loan_id=loan,
member=loan.member,
date_paid__lte=today,
date_paid__gt=previous_due_date
)
total_repayments = sum(repayment.amount for repayment in repayments)
#include a case of mutiple missed payments
start_date = loan.approved_date + timedelta(days=1)
interval_period = get_interval_period(loan) #in timedelta(days=50) format
difference = (timezone.now() - start_date).days ##get difference between start date and current_date
expired_intervals = difference // interval_period.days #get expired payment intervals/installments
penalities = total_penalty(loan)
if penalities is None:
penalities = 0
missed_payments = expired_intervals * loan.due_amount + penalities
if total_repayments < missed_payments:
#if total_repayments < loan.due_amount:
# Loan is overdue
loan.status = 'overdue'
loan.save()
#update member credit score
update_credit_score(loan)
try:
system_settings = SystemSetting.objects.get(company=loan.company)
except SystemSetting.DoesNotExist:
system_settings = None
try:
sms_settings = SmsSetting.objects.get(company=loan.company)
except SmsSetting.DoesNotExist:
sms_settings = None
try:
template_setting = TemplateSetting.objects.get(company=loan.company)
except:
template_setting = None
#available tags
first_name = loan.member.first_name
last_name = loan.member.last_name
organization_name = loan.member.company.name
currency = loan.company.currency
due_amount = loan.due_amount
account_no = loan.company.account_no
paybill_no = loan.company.paybill_no
#format raw message template
message_raw = template_setting.loan_overdue
message = message_raw.format(
first_name=first_name,
last_name=last_name,
organization_name=organization_name,
currency=currency,
due_amount=due_amount,
account_no=account_no,
paybill_no=paybill_no,
)
if sms_settings is not None:
if system_settings.is_send_sms and sms_settings.api_token is not None and sms_settings.sender_id is not None:
# send sms
send_sms(
sms_settings.sender_id,
sms_settings.api_token,
loan.member.phone_no,
message
)
@shared_task
def hello_engima():
print('I get printed after every minute')
#update due amount foe overdue loans
@shared_task
def update_due_amount_task():
loans = Loan.objects.filter(status='overdue')
for loan in loans:
update_due_amount(loan)
# -- end --
#task to send loan balances sms weekly
@shared_task
def send_loan_balance():
loans = Loan.objects.filter(status__in=['approved', 'overdue'])
for loan in loans:
balance = loan.loan_balance()
final_date = loan.final_payment_date().date().strftime('%Y-%m-%d')
try:
system_settings = SystemSetting.objects.get(company=loan.company)
except SystemSetting.DoesNotExist:
system_settings = None
try:
sms_settings = SmsSetting.objects.get(company=loan.company)
except SmsSetting.DoesNotExist:
sms_settings = None
try:
template_setting = TemplateSetting.objects.get(company=loan.company)
except:
template_setting = None
#available tags
first_name = loan.member.first_name
last_name = loan.member.last_name
organization_name = loan.member.company.name
currency = loan.company.currency
due_date = loan.due_date.date().strftime('%Y-%m-%d')
due_amount = loan.due_amount
loan_balance = balance
account_no = loan.company.account_no
paybill_no = loan.company.paybill_no
#format raw message template
message_raw = template_setting.loan_balance
message = message_raw.format(
first_name=first_name,
last_name=last_name,
organization_name=organization_name,
currency=currency,
due_date=due_date,
due_amount=due_amount,
loan_balance=loan_balance,
account_no=account_no,
paybill_no=paybill_no,
final_date=final_date
)
if sms_settings is not None:
if system_settings.is_send_sms and sms_settings.api_token is not None and sms_settings.sender_id is not None:
# send sms of loan balance
send_sms(
sms_settings.sender_id,
sms_settings.api_token,
loan.member.phone_no,
message)
# --end
@shared_task
def send_sms_task(sender_id, token, phone_number, message):
# Call the send_sms function
send_sms(sender_id, token, phone_number, message)
@shared_task
def send_email_task(context, template_path, from_name, from_email, subject, recipient_email, replyto_email):
send_email(
context,
template_path,
from_name,
from_email,
subject,
recipient_email,
replyto_email
)
@shared_task
def disburse_loan_task(consumer_key, consumer_secret, shortcode, username, loan):
disburse_loan(
consumer_key,
consumer_secret,
shortcode,
username,
loan
) |
% initialize EEGLAB
if ~exist('ALLCOM','var')
eeglab;
end
% initialize fieldtrip without adding alternative files to path
% assuming FT is on your path already or is added via EEGlab plugin manager
global ft_default
ft_default.toolbox.signal = 'matlab'; % can be 'compat' or 'matlab'
ft_default.toolbox.stats = 'matlab';
ft_default.toolbox.image = 'matlab';
ft_defaults % this sets up the FieldTrip path
%% [OPTIONAL] check the .xdf data to explore the structure
ftPath = fileparts(which('ft_defaults'));
addpath(fullfile(ftPath, 'external','xdf'));
xdfPath = '...yourpath\yourfile.xdf'; % enter full path to your .xdf file
% load .xdf data to check what is in there
streams = load_xdf(xdfPath);
streamnames = cellfun(@(x) x.info.name, streams, 'UniformOutput', 0)' % will display names of streams contained in .xdf
% display names of all channels in the .xdf data
for Si = 1:numel(streamnames)
if isfield( streams{Si}.info.desc, 'channels')
channelnames = cellfun(@(x) x.label, streams{Si}.info.desc.channels.channel, 'UniformOutput', 0)'
end
end
%% [OPTIONAL] enter metadata about the data set, data modalities, and participants
% general metadata shared across all modalities
% will be saved in BIDS-folder/data_description.json
% see "https://bids-specification.readthedocs.io/en/stable/03-modality-agnostic-files.html#:~:text=LICENSE-,dataset_description.json,-The%20file%20dataset_description"
%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
generalInfo = [];
% required for dataset_description.json
generalInfo.dataset_description.Name = 'name of your data set';
generalInfo.dataset_description.BIDSVersion = 'version of BIDS-specification you are following'; % if sharing motion data, use "unofficial extension"
% optional for dataset_description.json
generalInfo.dataset_description.License = 'licence type';
generalInfo.dataset_description.Authors = {"author 1", "author 2", "author 3"};
generalInfo.dataset_description.Acknowledgements = 'acknowledgement text';
generalInfo.dataset_description.Funding = {"funding source 1", "funding source 2"};
generalInfo.dataset_description.ReferencesAndLinks = {"reference", "link to article"};
generalInfo.dataset_description.DatasetDOI = 'DOI of your data set';
% general information shared across modality specific json files
generalInfo.InstitutionName = 'name of your institute';
generalInfo.InstitutionalDepartmentName = 'name of your department';
generalInfo.InstitutionAddress = 'address of your institute';
generalInfo.TaskDescription = 'text describing your task';
% information about the eeg recording system
% will be saved in BIDS-folder/sub-XX/[ses-XX]/eeg/*_eeg.json and *_coordsystem.json
% see "https://bids-specification.readthedocs.io/en/stable/04-modality-specific-files/03-electroencephalography.html#:~:text=MAY%20be%20specified.-,Sidecar%20JSON%20(*_eeg.json),-Generic%20fields%20MUST"
% and "https://bids-specification.readthedocs.io/en/stable/04-modality-specific-files/03-electroencephalography.html#:~:text=after%20the%20recording.-,Coordinate%20System%20JSON,-(*_coordsystem.json"
%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
eegInfo = [];
eegInfo.coordsystem.EEGCoordinateSystem = 'enter the name of your coordinate system'; % only needed when you share eloc
eegInfo.coordsystem.EEGCoordinateUnits = 'enter the unit of your coordinate system'; % only needed when you share eloc
eegInfo.coordsystem.EEGCoordinateSystemDescription = 'enter description of your coordinate system'; % only needed when you share eloc
eegInfo.eeg.SamplingFrequency = 1000; % nominal sampling frequency
% information about the motion recording system
% will be saved in BIDS-folder/sub-XX/[ses-XX]/motion/*_motion.json
% see "https://docs.google.com/document/d/1iaaLKgWjK5pcISD1MVxHKexB3PZWfE2aAC5HF_pCZWo/edit?usp=sharing"
%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
motionInfo = [];
tracking_systems = {'System1', 'System2'}; % enter the names of your tracking systems
% motion specific fields in json
motionInfo.motion = [];
% system 1 information
motionInfo.motion.TrackingSystems(1).TrackingSystemName = tracking_systems{1};
motionInfo.motion.TrackingSystems(1).Manufacturer = 'HTC'; % manufacturer of the motion capture system
motionInfo.motion.TrackingSystems(1).ManufacturersModelName = 'Vive Pro'; % model name of the tracking system
motionInfo.motion.TrackingSystems(1).SamplingFrequency = 90; % If no nominal Fs exists, n/a entry returns 'n/a'. If it exists, n/a entry returns nominal Fs from motion stream.
motionInfo.motion.TrackingSystems(1).DeviceSerialNumber = 'n/a';
motionInfo.motion.TrackingSystems(1).SoftwareVersions = 'n/a';
motionInfo.motion.TrackingSystems(1).SpatialAxes = 'FRU'; % XYZ spatial axes description
motionInfo.motion.TrackingSystems(1).RotationRule = 'left-hand'; % if rotation is present, does it follow the left-hand or right-hand rule?
motionInfo.motion.TrackingSystems(1).RotationOrder = 'ZXY'; % order of euler angles' extrinsic rotation
% system 2 information
motionInfo.motion.TrackingSystems(2).TrackingSystemName = tracking_systems{2};
motionInfo.motion.TrackingSystems(2).Manufacturer = 'Impuls X2';
motionInfo.motion.TrackingSystems(2).ManufacturersModelName = 'PhaseSpace';
motionInfo.motion.TrackingSystems(2).SamplingFrequency = 90;
motionInfo.motion.TrackingSystems(2).DeviceSerialNumber = 'n/a';
motionInfo.motion.TrackingSystems(2).SoftwareVersions = 'n/a';
motionInfo.motion.TrackingSystems(2).SpatialAxes = 'FRU';
motionInfo.motion.TrackingSystems(2).RotationRule = 'left-hand';
motionInfo.motion.TrackingSystems(2).RotationOrder = 'ZXY';
% participant information
%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
% here describe the fields in the participant file
% see "https://bids-specification.readthedocs.io/en/stable/03-modality-agnostic-files.html#participants-file:~:text=UTF%2D8%20encoding.-,Participants%20file,-Template%3A"
% for numerical values :
% subjectData.fields.[insert your field name here].Description = 'describe what the field contains';
% subjectData.fields.[insert your field name here].Unit = 'write the unit of the quantity';
% for values with discrete levels :
% subjectData.fields.[insert your field name here].Description = 'describe what the field contains';
% subjectData.fields.[insert your field name here].Levels.[insert the name of the first level] = 'describe what the level means';
% subjectData.fields.[insert your field name here].Levels.[insert the name of the Nth level] = 'describe what the level means';
%--------------------------------------------------------------------------
subjectInfo.fields.nr.Description = 'numerical ID of the participant';
subjectInfo.fields.age.Description = 'age of the participant';
subjectInfo.fields.age.Unit = 'years';
subjectInfo.fields.sex.Description = 'sex of the participant';
subjectInfo.fields.sex.Levels.M = 'male';
subjectInfo.fields.sex.Levels.F = 'female';
subjectInfo.fields.handedness.Description = 'handedness of the participant';
subjectInfo.fields.handedness.Levels.R = 'right-handed';
subjectInfo.fields.handedness.Levels.L = 'left-handed';
% names of the columns - 'nr' column is just the numerical IDs of subjects
% do not change the name of this column
subjectInfo.cols = {'nr', 'age', 'sex', 'handedness'};
subjectInfo.data = {1, 30, 'F', 'R' ; ...
2, 22, 'M', 'R'; ...
3, 23, 'F', 'R'; ...
4, 34, 'M', 'R'; ...
5, 25, 'F', 'R'; ...
6, 21, 'F', 'R' ; ...
7, 28, 'M', 'R'; ...
8, 28, 'M', 'R'; ...
9, 24, 'F', 'R'; ...
10, 25, 'F', 'L'; ...
11, 30, 'F', 'R'; ...
12, 22, 'M', 'R'; ...
13, 23, 'F', 'R'; ...
14, 34, 'M', 'R'; ...
15, 25, 'F', 'R'; ...
16, 21, 'F', 'R' ; ...
17, 28, 'M', 'R'; ...
18, 28, 'M', 'R'; ...
19, 24, 'F', 'R'; ...
20, 25, 'F', 'L';};
%% iterate over participants, sessions, and runs to import file-by-file
studyFolder = '...\yourstudyfolder'; % full path to your study folder
sessionNames = {'sessionA', 'ssssionB'}; % replace with names of your sessions (if there are no multiple sessions, remove confg.ses and the session loop in the following)
% loop over participants
for subject = 1:20
% loop over sessions
for session = 1:2
config = []; % reset for each loop ´
config.bids_target_folder = '...\BIDS-data'; % required, replace with the folder where you want to store your bids data
config.filename = fullfile('...\yourxdffile.xdf'); % required, replace with your xdf file full path
config.eeg.chanloc = fullfile('...\yourelocfile.elc'); % optional, if you have electrode location file, replace with the full patht to the file.
config.task = 'YourTaskName'; % optional, replace with your task name
config.subject = subject; % required
config.session = sessionNames{session}; % optional
config.overwrite = 'on'; % optional
config.eeg.stream_name = 'YourEEGStreamName'; % required, replace with the unique keyword in your eeg stream in the .xdf file
%------------------------------------------------------------------
config.motion.streams{1}.xdfname = 'YourStreamNameInXDF'; % replace with name of the stream corresponding to the first tracking system
config.motion.streams{1}.bidsname = tracking_systems{1}; % a comprehensible name to represent the tracking system
config.motion.streams{1}.tracked_points = 'headRigid'; % name of the point that is being tracked in the tracking system, the keyword has to be containted in the channel name (see "bemobil_bids_motionconvert")
config.motion.streams{1}.tracked_points_anat= 'head'; % example of how the tracked point can be renamed to body part name for metadata
% names of position and quaternion channels in each stream
config.motion.streams{1}.positions.channel_names = {'headRigid_Rigid_headRigid_X'; 'headRigid_Rigid_headRigid_Y' ; 'headRigid_Rigid_headRigid_Z' };
config.motion.streams{1}.quaternions.channel_names = {'headRigid_Rigid_headRigid_quat_W';'headRigid_Rigid_headRigid_quat_Z';...
'headRigid_Rigid_headRigid_quat_X';'headRigid_Rigid_headRigid_quat_Y'};
config.motion.streams{2}.xdfname = 'YourStreamNameInXDF2';
config.motion.streams{2}.bidsname = tracking_systems{2};
config.motion.streams{2}.tracked_points = {'Rigid1', 'Rigid2', 'Rigid3', 'Rigid4'}; % example when there are multiple points tracked by the system
config.motion.streams{2}.positions.channel_names = {'Rigid1_X', 'Rigid2_X', 'Rigid3_X', 'Rigid4_X';... % each column is one tracked point and rows are different coordinates
'Rigid1_Y', 'Rigid2_Y', 'Rigid3_Y', 'Rigid4_Y';...
'Rigid1_Z', 'Rigid2_Z', 'Rigid3_Z', 'Rigid4_Z'};
config.motion.streams{2}.quaternions.channel_names = {'Rigid1_A', 'Rigid2_A', 'Rigid3_A', 'Rigid4_A';...
'Rigid1_B', 'Rigid2_B', 'Rigid3_B', 'Rigid4_B';...
'Rigid1_C', 'Rigid2_C', 'Rigid3_C', 'Rigid4_C'; ...
'Rigid1_D', 'Rigid2_D', 'Rigid3_D', 'Rigid4_D'};
bemobil_xdf2bids(config, ...
'general_metadata', generalInfo,...
'participant_metadata', subjectInfo,...
'motion_metadata', motionInfo, ...
'eeg_metadata', eegInfo);
end
fclose all
%% configuration for bemobil bids2set
%----------------------------------------------------------------------
config.set_folder = fullfile(studyFolder,'2_raw-EEGLAB');
config.session_names = sessionNames;
config.other_data_types = {'motion'}; % specify which other data type than eeg is there (only 'motion' and 'physio' supported atm)
bemobil_bids2set(config);
end |
package com.heyanle.easybangumi4.base.preferences.mmkv
import com.heyanle.easybangumi4.base.preferences.Preference
import com.heyanle.okkv2.core.okkv
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
/**
* Created by HeYanLe on 2023/7/30 19:15.
* https://github.com/heyanLE
*/
class MMKVPreference<T : Any>(
private val key: String,
private val defaultValue: T,
) : Preference<T> {
private var valueOkkv by okkv(key, def = defaultValue)
private val flow = MutableStateFlow(valueOkkv)
override fun key(): String {
return key
}
override fun get(): T {
return valueOkkv
}
override fun set(value: T) {
valueOkkv = value
flow.update {
value
}
}
override fun defaultValue(): T {
return defaultValue
}
override fun isSet(): Boolean {
return true
}
override fun delete() {
set(defaultValue)
}
override fun flow(): Flow<T> {
return flow
}
override fun stateIn(scope: CoroutineScope): StateFlow<T> {
return flow.stateIn(scope, SharingStarted.Eagerly, get())
}
}
class MMKVObjectPreference<T>(
private val key: String,
private val defaultValue: T,
private val serializer: (T) -> String,
private val deserializer: (String) -> T
) : Preference<T> {
private var valueOkkv by okkv(key, def = serializer(defaultValue))
private val flow = MutableStateFlow(deserializer(valueOkkv))
override fun key(): String {
return key
}
override fun get(): T {
return flow.value
}
override fun set(value: T) {
valueOkkv = serializer(value)
flow.update {
value
}
}
override fun defaultValue(): T {
return defaultValue
}
override fun isSet(): Boolean {
return true
}
override fun delete() {
set(defaultValue)
}
override fun flow(): Flow<T> {
return flow
}
override fun stateIn(scope: CoroutineScope): StateFlow<T> {
return flow.stateIn(scope, SharingStarted.Eagerly, get())
}
} |
from __future__ import print_function
import logging
import grpc
import EmployeeService_pb2
import EmployeeService_pb2_grpc
import const
def run():
with grpc.insecure_channel(const.IP+':'+const.PORT) as channel:
stub = EmployeeService_pb2_grpc.EmployeeServiceStub(channel)
# Query an employee's data
response = stub.GetEmployeeDataFromID(EmployeeService_pb2.EmployeeID(id=101))
print ('Employee\'s data: ' + str(response))
# Add a new employee
response = stub.CreateEmployee(EmployeeService_pb2.EmployeeData(id=301, name='Jose da Silva', title='Programmer'))
print ('Added new employee ' + response.status)
# Change an employee's title
response = stub.UpdateEmployeeTitle(EmployeeService_pb2.EmployeeTitleUpdate(id=301, title='Senior Programmer'))
print ('Updated employee ' + response.status)
# Delete an employee
response = stub.DeleteEmployee(EmployeeService_pb2.EmployeeID(id=201))
print ('Deleted employee ' + response.status)
# List all employees
response = stub.ListAllEmployees(EmployeeService_pb2.EmptyMessage())
print ('All employees: ' + str(response))
# List all seniors employees
response = stub.GetEmployeesSeniors(EmployeeService_pb2.EmptyMessage())
print ('All seniors employees: ' + str(response))
# Update employee name
response = stub.UpdateEmployeeName(EmployeeService_pb2.EmployeeNameUpdate(id=101, name="Gabriel"))
print ('Employee name updated: ' + str(response))
# List all tech lead employees
response = stub.GetEmployeesTechLeaders(EmployeeService_pb2.EmptyMessage())
print ('All tech leaders employees: ' + str(response))
if __name__ == '__main__':
logging.basicConfig()
run() |
# Stopwatch App
This is a simple Stopwatch App created using HTML, CSS, and JavaScript. The app allows users to start, stop, and reset a timer, displaying elapsed time in a human-readable format.
## Features
- Start button: Initiates the stopwatch timer.
- Pause (Stop) button: Halts the timer.
- Reset button: Resets the timer to 00:00:00.
- Real-time display: Updates the timer display as time progresses.
- Millisecond precision: Provides time with millisecond accuracy.
## Getting Started
1. Clone the repository:
```bash
git clone https://github.com/Musyoka2020-eng/Stopwatch-app.git
```
2. Open the `index.html` file in your web browser.
## Usage
- Click the "Start" button to begin the stopwatch.
- Click the "Pause" button to stop the timer at the current elapsed time.
- Click the "Reset" button to reset the timer to 00:00:00.
## Code Structure
- `index.html`: The main HTML file containing the structure of the app.
- `style.css`: The stylesheet defining the app's visual appearance.
- `script.js`: The JavaScript file containing the logic for the stopwatch functionality.
## Contributing
Contributions are welcome! If you have any suggestions, improvements, or bug fixes, feel free to open an issue or submit a pull request.
## License
This project is licensed under the [MIT License](LICENSE).
## Acknowledgments
- This project was inspired by the need for a simple, user-friendly stopwatch. |
# Curso de Vue.js de Cero a Experto
Apuntes y proyectos para el curso de Vue.js
[](https://es.vuejs.org/)
[](https://joseluisgs.github.io/docs/license/)

<p align="center">
<a href="https://joseluisgs.github.io/" target="_blank"><img src="https://fernando-herrera.com/recursos-extra/wallpapers/vue-js.jpeg"
width='600px' borderRadius='1rem' boxShadow = '0 5px 18px rgba(0,0,0,0.3)'></a>
</p>
- [Curso de Vue.js de Cero a Experto](#curso-de-vuejs-de-cero-a-experto)
- [Acerca de](#acerca-de)
- [Contenido](#contenido)
- [Licencia](#licencia)
- [Autor](#autor)
- [Contacto](#contacto)
- [¿Un café?](#un-café)
- [Licencia de uso](#licencia-de-uso)
- [Agradecimientos](#agradecimientos)
## Acerca de
Este repositorio recoge apuntes, proyectos y anotaciones del curso de [Vue.js](https://vuejs.org/) de Cero a Experto.
## Contenido
El contenido del curso se divide en las siguientes secciones:
- [00: Herramientas](00-Herramientas/README.md). Herramientas, extensiones y configuración inicial.
- [01: JavaScript](01-JavaScript/README.md). JavaScript avanzando.
- [02: Vue.js](02-IntroVue//README.md). Vue.js avanzando.
- [03: Vue y SFC](03-SFC/README.md). Creación de proyectos avanzados basados en componentes con SFC.
- [04: Introducción al Test](04-IntroTest/README.md). Nos iniciaremos al test unitario y de integración.
- [05: Pokemon Game Options API](05-Pokemon-Game-OptionsAPI/README.md). Creación de un juego de pokemon siguiendo Options API con sus test.
- [06: Pokemon Game Composition API](06-Pokemon-Game-CompositionAPI/README.md). Nuestro primer acercamiento a la API deComposición. Creación de un juego de pokemon siguiendo Composition API con sus test. Dos forms de hacerlo hasta llegar a script setup, la forma actualmente recomendada.
- [07: Vue Router y Ciclo de Vida](07-VueRouter-CicloVida/README.md). Usaremos Vue Router para navegar por nuestra app en base a rutas, nombres, paso de parámetros, rutas anidadas y guardas de las mismas. Profundizaremos en el ciclo de vida de un componente de Vue.
- [08: Introducción a Pinia y Store](08-IntroPiniaStore/README.md). Usaremos Pinia como store de Vue.js para compartid información entre varios componentes.
- [09: Journal App](09-JournalApp/README.md). Aplicación resumen de lo visto en el curso hasta este punto: router y pinia.
- [10: Quasar App](10-Quasar/README.md). Ejemplo de cómo usar Quasar como framework sobre Vue.js.
## Licencia
Puedes encontrar mi plantilla de licencia en: [LICENSE](#licencia-de-uso).
## Autor
Codificado con :sparkling_heart: por [José Luis González Sánchez](https://twitter.com/joseluisgonsan)
[](https://twitter.com/joseluisgonsan)
[](https://github.com/joseluisgs)
### Contacto
<p>
Cualquier cosa que necesites házmelo saber por si puedo ayudarte 💬.
</p>
<p>
<a href="https://joseluisgs.github.io/" target="_blank">
<img src="https://joseluisgs.github.io/img/favicon.png"
height="30">
</a>
<a href="https://github.com/joseluisgs" target="_blank">
<img src="https://distreau.com/github.svg"
height="30">
</a>
<a href="https://twitter.com/joseluisgonsan" target="_blank">
<img src="https://i.imgur.com/U4Uiaef.png"
height="30">
</a>
<a href="https://www.linkedin.com/in/joseluisgonsan" target="_blank">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/ca/LinkedIn_logo_initials.png/768px-LinkedIn_logo_initials.png"
height="30">
</a>
<a href="https://discordapp.com/users/joseluisgs#3560" target="_blank">
<img src="https://logodownload.org/wp-content/uploads/2017/11/discord-logo-4-1.png"
height="30">
</a>
<a href="https://g.dev/joseluisgs" target="_blank">
<img loading="lazy" src="https://googlediscovery.com/wp-content/uploads/google-developers.png"
height="30">
</a>
</p>
### ¿Un café?
<p><a href="https://www.buymeacoffee.com/joseluisgs"> <img align="left" src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" height="48" alt="joseluisgs" /></a></p><br><br><br>
## Licencia de uso
Este repositorio y todo su contenido está licenciado bajo licencia **Creative Commons**, si desea saber más, vea la [LICENSE](https://joseluisgs.github.io/docs/license/). Por favor si compartes, usas o modificas este proyecto cita a su autor, y usa las mismas condiciones para su uso docente, formativo o educativo y no comercial.
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img alt="Licencia de Creative Commons" style="border-width:0" src="https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">JoseLuisGS</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="https://joseluisgs.github.io/" property="cc:attributionName" rel="cc:attributionURL">José Luis González Sánchez</a> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">Creative Commons Reconocimiento-NoComercial-CompartirIgual 4.0 Internacional License</a>.<br />Creado a partir de la obra en <a xmlns:dct="http://purl.org/dc/terms/" href="https://github.com/joseluisgs" rel="dct:source">https://github.com/joseluisgs</a>.
#### Agradecimientos
Este proyecto está basado en una serie de tutoriales de [Udemy](https://www.udemy.com/course/vuejs-fh). |
<template>
<form @submit.prevent="login">
<VAlert v-if="error" type="error" class="mb-4"> Error: {{ error }} </VAlert>
<div v-if="loading" class="flex items-center justify-center flex-1">
<VLoading class="w-24 h-24 text-primary-600" />
</div>
<div class="space-y-4" v-if="!loading">
<VInput
v-model="email"
name="email"
type="email"
label="Email address"
placeholder="john@example.com"
required
/>
<VInput
v-model="password"
name="password"
type="password"
label="Password"
required
/>
<div class="flex items-center justify-end space-x-4">
<VButton type="button" @click="loadDemoUser()">Load Demo User</VButton>
<VButton
type="submit"
variant="primary"
:disabled="!email || !password"
>
<span>Login</span>
<CursorArrowRaysIcon class="w-5 h-5 ml-2" />
</VButton>
</div>
</div>
</form>
</template>
<script setup>
import { CursorArrowRaysIcon } from '@heroicons/vue/24/outline'
// Import the auth store from pinia
import { useAuth } from '~~/store/auth'
const auth = useAuth()
const email = ref()
const password = ref()
const error = ref(null)
const loading = ref(false)
function loadDemoUser() {
email.value = 'user@example.com'
password.value = 'password'
}
async function login() {
loading.value = true
error.value = null
try {
// Login
await auth.login({
email: email.value,
password: password.value,
})
// Clear the form
email.value = ''
password.value = ''
} catch (e) {
error.value = e.message
} finally {
loading.value = false
}
}
</script> |
<script lang="ts" setup>
const Links = {
home: 'http://www.huohuo90.com',
github: 'https://github.com/ecaps1038/yike-design-dev',
devStandard: 'https://dwawvfgxvzk.feishu.cn/wiki/GraewTYxJidb6dkeV5ycjGG4nHb',
task: 'https://dwawvfgxvzk.feishu.cn/wiki/T8D3w5VqbinQr5kLNoVcrDQKnbg?table=tblT9WqhCE0EWKfP&view=vewXxBNTOK',
design:
'https://www.figma.com/file/EMPOindzRJTKt1Gx6Egojq/Yike-design?type=design&node-id=0%3A278&mode=design&t=buLeC3MzFSkXagtR-1',
}
const navLinks = {
'/develop': '开发',
'/design': '设计',
'/module': '组件',
}
const isDev = import.meta.env.DEV
</script>
<template>
<div class="top-bar">
<router-link class="logo" to="/">
<img src="@/assets/icon/logo.svg" />
<IconYkdesignFill class="name" />
<yk-tag v-if="isDev" type="primary">DEV</yk-tag>
</router-link>
<yk-space class="nav-links" :size="24" align="center">
<a class="nav-item responsive-hidden" :href="Links.design">UI 设计稿</a>
<a class="nav-item responsive-hidden" :href="Links.task">任务文档</a>
<a class="nav-item responsive-hidden" :href="Links.devStandard">
开发规范
</a>
<router-link
v-for="(link, path) in navLinks"
:key="path"
:to="path"
class="nav-item"
>
{{ link }}
</router-link>
<a class="nav-item responsive-hidden" :href="Links.home" target="_blank">
主站
</a>
<a class="nav-item" :href="Links.github" target="_blank">
<icon-github-fill />
</a>
<a class="nav-item"><yk-theme /></a>
</yk-space>
</div>
</template>
<style lang="less" scoped>
.top-bar {
position: fixed;
top: 0;
left: 0;
z-index: 99;
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 24px;
width: 100vw;
height: var(--top-bar-height);
border-bottom: 1px solid @line-color-s;
background-color: @bg-color-l;
transition: all @animats;
box-sizing: border-box;
a {
display: flex;
align-items: center;
color: inherit;
}
.router-link-active {
font-weight: 600;
color: @pcolor;
}
}
.logo {
display: flex;
justify-content: center;
cursor: pointer;
img {
width: 36px;
height: 28px;
}
.name {
margin: 2px 10px 0;
width: auto;
height: 18px;
color: @font-color-l !important;
}
.yk-tag {
vertical-align: text-top;
}
}
.nav-item {
padding: 5px 8px;
border-radius: 4px;
text-decoration: none;
color: @font-color-l;
cursor: pointer;
.nav-item:hover {
font-weight: 500;
}
}
/* stylelint-disable-next-line media-feature-range-notation */
@media (max-width: 810px) {
.responsive-hidden {
display: none !important;
}
.logo {
.name {
display: none;
}
}
.nav-links {
gap: 8px !important;
}
}
</style> |
<?php
// services Custom Post Type
function services_init() {
// set up services labels
$labels = array(
'name' => 'servicess',
'singular_name' => 'services',
'add_new' => 'Add New services',
'add_new_item' => 'Add New services',
'edit_item' => 'Edit services',
'new_item' => 'New services',
'all_items' => 'All servicess',
'view_item' => 'View services',
'search_items' => 'Search servicess',
'not_found' => 'No servicess Found',
'not_found_in_trash' => 'No servicess found in Trash',
'parent_item_colon' => '',
'menu_name' => 'servicess',
);
// register post type
$args = array(
'labels' => $labels,
'public' => true,
'has_archive' => true,
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => array('slug' => 'services'),
'query_var' => true,
'supports' => array(
'title',
'editor',
'excerpt',
'trackbacks',
'custom-fields',
'comments',
'revisions',
'thumbnail',
'author',
'page-attributes'
)
);
register_post_type( 'services', $args );
}
add_action( 'init', 'services_init' ); |
=== ACVO ===
Contributors: themely
Tags: one-column, two-columns, featured-images, custom-menu, custom-logo, right-sidebar, full-width-template, theme-options, translation-ready, threaded-comments, portfolio, photography, blog
Requires at least: 4.7
Tested up to: 5.9
Stable tag: 1.1.3
Requires PHP: 5.6
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
== Description ==
Avante Lite is a clean, modern and elegant one-page theme designed for professionals and small businesses. Its strength lies in displaying all your content on a single page, is easily customizable and allows you to build a stunning website in minutes. Avante doesn�t depend on frameworks or page builders to display content but relies on native WordPress widgets, pages and the Live Customizer. It�s responsive, search engine friendly and light-weight. Avante is perfect for small business, startup, professional, agency, firm as well as personal portfolio websites or blogs.
== Installation ==
1. Upload the zip file to your themes directory.
2. Activate the theme.
3. Install the recommended plugins
4. Create page entitled "Home"
5. Assign it the One-Page Template from the Page Attributes section.
5. Set "Home" page as the static front-page in Settings > Reading.
6. Navigate to Appearance > Customize to configure your theme settings.
== Copyright ==
Avante Lite WordPress Theme, Copyright 2021 Ishmael 'Hans' Desjarlais
Avante Lite is distributed under the terms of the GNU GPL
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Avante bundles the following third-party resources:
###
Bootstrap
http://getbootstrap.com/
(C) 2011-2015 Twitter, Inc
Licensed under the MIT License, http://opensource.org/licenses/MIT
###
###
FontAwesome
http://fontawesome.io
(C) 2015 Dave Candy
Font License
Applies to all desktop and webfont files.
License: SIL OFL 1.1
URL: http://scripts.sil.org/OFL
Code License
Applies to all CSS files
License: MIT License
URL: http://opensource.org/licenses/mit-license.html
###
###
SmoothScroll
https://github.com/cferdinandi/smooth-scroll
(C) 2015 Go Make Things, LLC
Licensed under the MIT license,
https://github.com/cferdinandi/smooth-scroll/blob/master/LICENSE.md
###
###
Bootstrap NavWalker
https://github.com/mebishalnapit/bootstrap-navwalker/
(C) 2018 Bishal Napit
Licensed under the GNU General Public License v3.0,
http://www.gnu.org/licenses/gpl-3.0.txt
###
###
Google Fonts
http://www.google.com/fonts
(C) 2015 Google
Licensed under the SIL Open Font license,
http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=OFL
###
###
Slick Font
https://github.com/kenwheeler/slick
(C) 2017 Ken Wheeler
Licensed under the MIT license,
https://github.com/kenwheeler/slick/blob/master/LICENSE
###
###
TGM Plugin Activation
https://github.com/TGMPA/TGM-Plugin-Activation
(C) 2019 Thomas Griffin
Licensed under the GNU General Public License v2.0,
https://github.com/TGMPA/TGM-Plugin-Activation/blob/develop/LICENSE.md
###
###
hoverIntent v1.9.0
https://github.com/briancherne/jquery-hoverIntent
(C) 2007-2017 Brian Cherne
Licensed under the MIT license,
http://opensource.org/licenses/mit-license.html
###
###
Magnific Popup - v1.1.0 - 2016-02-20
https://github.com/dimsemenov/Magnific-Popup
(C) 2016 Dmitry Semenov
Licensed under the MIT license,
https://github.com/dimsemenov/Magnific-Popup/blob/master/LICENSE
###
###
Royalty-Free Stock Photography
* screenshot.png
License: CC0 1.0 Universal (CC0 1.0)
License URL: https://pxhere.com/en/license
Source: https://pxhere.com/en/photo/26343
* images/bg-hero.jpg
License: CC0 1.0 Universal (CC0 1.0)
License URL: https://pxhere.com/en/license
Source: https://pxhere.com/en/photo/26343
* images/bg-about.jpg
License: CC0 1.0 Universal (CC0 1.0)
License URL: https://pxhere.com/en/license
Source: https://pxhere.com/en/photo/1629588
* images/bg-cta.jpg
License: CC0 1.0 Universal (CC0 1.0)
License URL: https://pxhere.com/en/license
Source: https://pxhere.com/en/photo/893407
* images/bg-contact.jpg
License: CC0 1.0 Universal (CC0 1.0)
License URL: https://pxhere.com/en/license
Source: https://pxhere.com/en/photo/99094
###
###
Fonts - Archivo, Rubik and Montserrat by Google Fonts
###
== Screenshots ==
1. 1. screenshot.png
== Changelog ==
### 1.1.3 - March 10th, 2022
Changes: Tested with WordPress 5.9
### 1.0.6 - July 14th, 2021
Changes:
- Completed changes mentioned in trac ticket https://themes.trac.wordpress.org/ticket/101968#comment:6
### 1.0.4 - July 6th, 2021
Changes:
- Updated stock photography license info in readme.txt
### 1.0.3 - July 5th, 2021
Changes:
- Completed changes mentioned in trac ticket https://themes.trac.wordpress.org/ticket/101829#comment:5
### 1.0.1 - July 2nd, 2021
Changes:
- Completed changes mentioned in trac ticket https://themes.trac.wordpress.org/ticket/101745#comment:3
### 1.0 - June 30th, 2021
Changes:
* INITIAL RELEASE *
== Frequently Asked Questions ==
= How do I setup the One-Page Template? =
1. Create or edit a page, and assign it the One-Page Template from the Page Attributes section.
2. Go to Settings > Reading and set "Front page displays" to "A static page".
3. Select the page you just assigned the One-page Template to as "Front page" and then choose another page as "Posts page" to serve your blog posts.
== Upgrade Notice ==
= 0.1 =
* INITIAL RELEASE * |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.