text
stringlengths 184
4.48M
|
|---|
import React, { RefObject, useEffect } from 'react'
import { SoundRefType } from './types'
const useAudioData = (
playState: [boolean, React.Dispatch<React.SetStateAction<boolean>>],
soundRefs: Array<SoundRefType>,
soundRef: RefObject<HTMLAudioElement>
) => {
const [playing, setPlaying] = playState
const toggle = () => setPlaying(!playing)
const resetOtherSounds = () => {
soundRefs.forEach(({ ref, playState: refPlayState }) => {
if (ref && ref.current) {
if (ref.current !== soundRef.current) {
const [, setRefPlayState] = refPlayState
ref.current.pause()
ref.current.currentTime = 0
setRefPlayState(false)
}
}
})
}
useEffect(() => {
if (soundRef && soundRef.current) {
if (playing) {
resetOtherSounds()
soundRef.current.play()
}
if (!playing) {
soundRef.current.pause()
}
}
}, [playing])
useEffect(() => {
if (soundRef && soundRef.current) {
soundRef.current.addEventListener('ended', () => {
setPlaying(false)
})
}
return () => {
if (soundRef && soundRef.current) {
soundRef.current.removeEventListener('ended', () => setPlaying(false))
}
}
}, [])
return { toggle }
}
export default useAudioData
|
import express from 'express';
import multer from 'multer';
import AWS from 'aws-sdk';
import cassandra from 'cassandra-driver';
const router = express.Router();
const s3Client = new AWS.S3({
accessKeyId: 'ROOTNAME',
secretAccessKey: 'CHANGEME123',
endpoint: 'http://localhost:9000',
s3ForcePathStyle: true,
signatureVersion: 'v4'
});
const cassandraClient = new cassandra.Client({
contactPoints: ['localhost:9042'],
localDataCenter: 'datacenter1',
keyspace: 'videokeyspace'
});
const upload = multer({ storage: multer.memoryStorage() });
router.post('/upload', upload.single('video'), async (req: express.Request, res: express.Response) => {
try {
// Save to MinIO
const videoKey = `${Date.now()}-${req.file!.originalname}`;
await s3Client.putObject({
Bucket: 'videos',
Key: videoKey,
Body: req.file!.buffer,
ContentType: req.file!.mimetype
}).promise();
// Save metadata to Cassandra
const videoId = cassandra.types.Uuid.random();
await cassandraClient.execute('INSERT INTO videos (video_id, title, description, object_storage_key, created_at) VALUES (?, ?, ?, ?, ?)', [
videoId,
req.body.title,
req.body.description,
videoKey,
new Date()
]);
res.status(200).send({ success: true, message: 'Video uploaded successfully!', videoId });
} catch (error: any) {
res.status(500).send({ success: false, message: error.message });
}
});
router.get('/search', async (req: express.Request, res: express.Response) => {
try {
const title = req.query.title as string;
if (!title) {
return res.status(400).send({ success: false, message: 'Title is required for searching.' });
}
const result = await cassandraClient.execute('SELECT * FROM videos WHERE title = ?', [title]);
const videos = result.rows.map(video => {
// Add a temporary URL to fetch the video from MinIO (if needed)
video.url = s3Client.getSignedUrl('getObject', { Bucket: 'videos', Key: video.object_storage_key, Expires: 3600 });
return video;
});
res.send(videos);
} catch (error: any) {
res.status(500).send({ success: false, message: error.message });
}
});
// Add this new route to the backend
router.get('/allVideos', async (req: express.Request, res: express.Response) => {
try {
const result = await cassandraClient.execute('SELECT * FROM videos');
const videos = result.rows.map((video) => {
return {
videoId: video.video_id,
title: video.title,
description: video.description,
url: s3Client.getSignedUrl('getObject', { Bucket: 'videos', Key: video.object_storage_key, Expires: 3600 })
};
});
res.status(200).send(videos);
} catch (error: any) {
res.status(500).send({ success: false, message: error.message });
}
});
export default router;
|
# Crie um portfólio vencedor
## Aprendizagem Baseada em Projetos (PBL) <!--About project-based learning (PBL) / Sobre aprendizagem baseada em projetos (PBL)-->
<p>Aprendizagem Baseada em Projetos (PBL) é sobre imergir em grandes ideais e criar soluções tangíveis. Neste método, você constrói projetos práticos que refletem problemas e desafios do mundo real. Esses projetos não apenas aumentam seu conhecimento, mas também demonstram suas competências.</p>
<details> <!--About portfolio / Sobre portfólio-->
<summary><span>📁 Portfólio</span></summary>
<p>Cada projeto concluído reforça suas <strong>habilidades</strong>, promove <strong>networking</strong> e dá <strong>destaque</strong> ao seu portfólio profissional.</p>
</details>
<details> <!--About skills / Sobre competências-->
<summary><span>📚 Competências</span></summary>
<p>Ao finalizar seus projetos na DIO, você obtém uma <strong>certificação de competências</strong>, um diferencial importante para abrir portas no mercado de trabalho.</p>
</details>
<details> <!--About employability / Sobre empregabilidade-->
<summary><span>💼 Empregabilidade</span></summary>
<p>Através da <strong>Talent Match</strong> você tem acesso às melhores oportunidades de emprego no setor de tecnologia.</p>
</details>
<br>
## Desenvolva suas habilidades <!--About develop your skills / Sobre desenvolva suas habilidades-->
<details> <!--About hard skills / Sobre habilidades difíceis-->
<summary><span>🎓 Hard Skills</span></summary>
<li>Linguagem de programação.</li>
<li>Arquitetura de sistema.</li>
<li>Banco de dados.</li>
<li>Stacks de desenvolvimento.</li>
<li>Ferramentas.</li>
</details>
<details> <!--About soft skills / Sobre habilidades sociais-->
<summary><span>😎 Soft Skills</span></summary>
<li>Trabalho em equipe</li>
<li>Pensamento crítico.</li>
<li>Gerenciamento do tempo.</li>
<li>Comunicação.</li>
<li>Liderança.</li>
</details>
<div align="right"> <!--About back button / Sobre botão voltar-->
<a href="../README.md">
<button><strong>Voltar</strong></button>
</a>
</div>
|
<nav class="navbar navbar-expand-lg bg-body-tertiary rounded" aria-label="Thirteenth navbar example">
<div class="container-fluid">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarsExample11" aria-controls="navbarsExample11" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse d-lg-flex" id="navbarsExample11">
<a class="navbar-brand col-lg-3 me-0" href="#">Centered nav</a>
<ul class="navbar-nav col-lg-6 justify-content-lg-center">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled">Disabled</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown" aria-expanded="false">Dropdown</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
</ul>
</li>
</ul>
<div class="d-lg-flex col-lg-3 justify-content-lg-end">
<button class="btn btn-primary">Button</button>
</div>
</div>
</div>
</nav>
<ul>
<% if user_signed_in? && current_user.admin? %>
<li>
<%= link_to "Dashboard", admin_dashboard_index_path %>
</li>
<% end%>
<% if user_signed_in? && !current_user.admin? %>
<%= link_to "Profil", edit_user_registration_path %>
<% end%>
<% if user_signed_in? %>
<li>
<%= button_to "Sign out", destroy_user_session_path, method: :delete %>
</li>
<% else %>
<li>
<%= link_to "Sign in", new_user_session_path %>
</li>
<li>
<%= link_to "Sign up", new_user_registration_path %>
</li>
<% end %>
</ul>
</nav>
|
---
title: "Identity types"
subtitle: "Martin-Löf Type Theory, identity types"
description: "A minimal Type Theory in Martin-Löf style: Identity types"
---
### Contents {#top}
1. [Identity Types](#id)
1. [Path induction](#pathinduction)
1. [Pauling-Mohring theorem](#paulin-mohring)
1. [Transport](#transport)
1. [Applicative](#appl)
1. [Non dependent](#ap)
1. [Dependent](#apd)
1. [Inversion of identifications](#inversion)
1. [Composition of identifications](#composition)
1. [Reasoning with equality](#reasoning)
--------------------------------------------------------------------------------
```agda
{-# OPTIONS --without-K --safe #-}
module mltt.identity.core where
open import level
open import mltt.pi
open import function.core
```
### Identity Types {#id}
```agda
infix 4 _≡_
data _≡_ {ℓ} {A : Set ℓ} (x : A) : A → Set ℓ where
instance refl : x ≡ x
{-# BUILTIN EQUALITY _≡_ #-}
-- alternative HoTT name
Id : {ℓ : Level} (A : Set ℓ) → A → A → Set ℓ
Id {ℓ} A = _≡_ {ℓ} {A}
-- explicit version of refl
idp : {ℓ : Level} {A : Set ℓ} (x : A) → x ≡ x
idp x = refl {x = x}
-- recover implicit arguments in equalities
lhs : ∀{ℓ} {A : Set ℓ} {x y : A} → x ≡ y → A
lhs {ℓ} {A} {x} {y} p = x
rhs : ∀{ℓ} {A : Set ℓ} {x y : A} → x ≡ y → A
rhs {ℓ} {A} {x} {y} p = y
```
<p style="font-size: smaller; text-align: right">[top ⇑](#top)</p>
---
### Path induction {#pathinduction}
```agda
≡-induction : ∀ {ℓ ℓ'} {A : Set ℓ} (D : (x y : A) → x ≡ y → Set ℓ') →
((x : A) → D x x refl) → ( (x y : A) → (p : x ≡ y) → D x y p )
≡-induction D d x .x refl = d x
𝕁 = ≡-induction
```
#### Paulin-Mohring theorem {#paulin-mohring}
```agda
ℍ : ∀ {ℓ ℓ'} {A : Set ℓ} (x : A) (C : (y : A) → x ≡ y → Set ℓ') →
C x refl → (y : A) → (p : x ≡ y) → C y p
ℍ x C c .x refl = c
𝕁' : ∀ {ℓ ℓ'} {A : Set ℓ} (D : (x y : A) → x ≡ y → Set ℓ') →
((x : A) → D x x refl) → (x y : A) → (p : x ≡ y) → D x y p
𝕁' D d x y p = ℍ x (D x) (d x) y p
𝕁-to-𝕁' : ∀ {ℓ ℓ'} {A : Set ℓ} (D : (x y : A) → x ≡ y → Set ℓ')
(d : (x : A) → D x x refl) (x y : A) (p : x ≡ y) →
𝕁 D d x y p ≡ 𝕁' D d x y p
𝕁-to-𝕁' D d x .x refl = idp (d x) -- signal which reflexivity with an explicit term
ℍ' : ∀ {ℓ ℓ'} {A : Set ℓ} (x : A) (C : (y : A) → x ≡ y → Set ℓ') → C x refl →
(y : A) → (p : x ≡ y) → C y p
ℍ' {ℓ} {ℓ'} {A} x C c y p = 𝕁 𝔻 (λ x C c → c) x y p C c where
𝔻 : ∀ {ℓ ℓ'} {A : Set ℓ} → (x y : A) → (p : x ≡ y) → Set (ℓ ⊔ lsuc ℓ')
𝔻 {ℓ} {ℓ'} {A} x y p = (C : ((y' : A) → (p' : x ≡ y') → Set ℓ')) → (C x refl → C y p)
--TODO: ℍ-to-ℍ'
```
<p style="font-size: smaller; text-align: right">[top ⇑](#top)</p>
---
### Transport {#transport}
```agda
transport𝕁 : ∀{ℓ ℓ'} {A : Set ℓ} (P : A → Set ℓ') {x y : A}
(p : x ≡ y) → P x → P y
transport𝕁 {ℓ} {ℓ'} {A} P {x} {y} p = 𝕁 D d x y p
where
D : ∀{ℓ ℓ'} {A : Set ℓ} {P : A → Set ℓ'} (x y : A) → x ≡ y → Set ℓ'
D {P = P} x y p = P x → P y
d : ∀{ℓ ℓ'} {A : Set ℓ} {P : A → Set ℓ'} (x : A) → D {P = P} x x refl
d x = id
transport : ∀{ℓ ℓ'} {A : Set ℓ} (P : A → Set ℓ') {x y : A}
(p : x ≡ y) → P x → P y
transport P refl = id
transport-agreement : ∀ {ℓ ℓ'} {A : Set ℓ} (P : A → Set ℓ') {x y : A} (p : x ≡ y) →
transport P p ≡ transport𝕁 P p
transport-agreement P refl = idp (id)
```
<p style="font-size: smaller; text-align: right">[top ⇑](#top)</p>
---
### Applicative {#appl}
#### Non dependent {#ap}
```agda
ap : ∀ {ℓ ℓ'} {A : Set ℓ} {B : Set ℓ'} {x y : A} (f : A → B) →
x ≡ y → f x ≡ f y
ap f refl = refl
ap𝕁 : ∀ {ℓ ℓ'} {A : Set ℓ} {B : Set ℓ'} {x y : A} (f : A → B) →
x ≡ y → f x ≡ f y
ap𝕁 {ℓ} {ℓ'} {A} {B} {x} {y} f p = 𝕁 D d x y p where
D : ∀ {ℓ ℓ'} {A : Set ℓ} {B : Set ℓ'} {f : A → B} (x y : A) (p : x ≡ y) → Set ℓ'
D {f = f} x y p = f x ≡ f y
d : ∀ {ℓ ℓ'} {A : Set ℓ} {B : Set ℓ'} {f : A → B} (x : A) → D {f = f} x x refl
d x = refl
ap-agreement : ∀ {ℓ ℓ'} {A : Set ℓ} {B : Set ℓ'} {x y : A} (f : A → B) (p : x ≡ y) → ap f p ≡ ap𝕁 f p
ap-agreement f refl = idp refl
```
#### Dependent {#apd}
```agda
apd' : ∀ {ℓ ℓ'} {A : Set ℓ} (P : A → Set ℓ') (f : (x : A) → P x) {x y : A} →
(p : x ≡ y) → transport P p (f x) ≡ f y
apd' P f {x} refl = idp (f x)
apd : ∀ {ℓ ℓ'} {A : Set ℓ} {P : A → Set ℓ'} (f : (x : A) → P x) {x y : A} →
(p : x ≡ y) → transport P p (f x) ≡ f y
apd f {x} refl = idp (f x)
apd𝕁 : ∀ {ℓ ℓ'} {A : Set ℓ} {P : A → Set ℓ'} (f : (x : A) → P x) {x y : A} →
(p : x ≡ y) → transport P p (f x) ≡ f y
apd𝕁 {ℓ} {ℓ'} {A} {P} f {x} {y} p = 𝕁 D d x y p
where
D : (x y : A) → x ≡ y → Set ℓ'
D x y p = transport P p (f x) ≡ f y
d : (x : A) → D x x refl
d = λ x → refl
apd-agreement : ∀ {ℓ ℓ'} {A : Set ℓ} {P : A → Set ℓ'}
(f : (x : A) → P x) {x y : A} (p : x ≡ y) →
apd f p ≡ apd𝕁 f p
apd-agreement f {x} refl = idp (idp (f x))
```
<p style="font-size: smaller; text-align: right">[top ⇑](#top)</p>
---
### Inversion of identifications {#inversion}
```agda
≡-inv𝕁 : ∀ {ℓ} {A : Set ℓ} {x y : A} → x ≡ y → y ≡ x
≡-inv𝕁 {ℓ} {A} {x} {y} p = 𝕁 (λ x y p → y ≡ x) (λ x → refl) x y p
infixr 30 _⁻¹
_⁻¹ : ∀ {ℓ} {A : Set ℓ} {x y : A} → x ≡ y → y ≡ x
refl ⁻¹ = refl
-- for symmetry
≡-inv = _⁻¹
```
<p style="font-size: smaller; text-align: right">[top ⇑](#top)</p>
---
### Composition of identifications {#composition}
```agda
≡-comp𝕁 : ∀ {ℓ} {A : Set ℓ} {x y z : A} (p : x ≡ y ) → y ≡ z → x ≡ z
≡-comp𝕁 {ℓ} {A} {x} {y} {z} p = 𝕁 D d x y p z where
D : ∀ {ℓ} {A : Set ℓ} (x y : A) (p : x ≡ y) → Set ℓ
D {ℓ} {A} x y p = (z : A) → (q : y ≡ z) → x ≡ z
d : ∀ {ℓ} {A : Set ℓ} (x : A) → D x x refl -- Π[ z ∈ A ] Π[ q ∈ x ≡ z ] (x ≡ z)
d {ℓ} {A} x z q = 𝕁 E (λ x → refl) x z q where
E : ∀ {ℓ} {A : Set ℓ} → Π[ x ∈ A ] Π[ z ∈ A ] Π[ q ∈ x ≡ z ] Set ℓ
E {ℓ} {A} x z q = x ≡ z
infix 25 _◾_
_◾_ : ∀ {ℓ} {A : Set ℓ} {x y z : A} →
x ≡ y → y ≡ z → x ≡ z
refl ◾ q = q
infix 25 _◾′_
_◾′_ : ∀ {ℓ} {A : Set ℓ} {x y z : A} →
x ≡ y → y ≡ z → x ≡ z
p ◾′ refl = p
◾-agreement : ∀ {ℓ} {A : Set ℓ} {x y z : A} (p : x ≡ y) (q : y ≡ z) → p ◾ q ≡ p ◾′ q
◾-agreement refl refl = refl
```
<p style="font-size: smaller; text-align: right">[top ⇑](#top)</p>
---
### Reasoning with equality {#reasoning}
```agda
module ≡-Reasoning {ℓ : Level} {A : Set ℓ} where
infix 3 _∎
infixr 2 _≡⟨_⟩_
infix 1 begin_
begin_ : ∀ {x y : A} → x ≡ y → x ≡ y
begin p = p
_≡⟨_⟩_ : (x : A) {y z : A} →
x ≡ y → y ≡ z → x ≡ z
x ≡⟨ p ⟩ q = p ◾ q
_∎ : (x : A) → x ≡ x
x ∎ = idp x
```
<p style="font-size: smaller; text-align: right">[top ⇑](#top)</p>
---
|
import { useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faPlus } from "@fortawesome/free-solid-svg-icons";
const TodoForm = ({ addTodoItem }) => {
const [newTodo, setNewTodo] = useState({ id: null, task: "", compelted: false });
function handleChange(e) {
setNewTodo({ ...newTodo, task: e.target.value });
}
function addTodo(e) {
if (newTodo.task.trim()) addTodoItem({ ...newTodo, id: Date.now() });
setNewTodo({ ...newTodo, task: "" });
}
function handleEnter(e) {
if (e.key == "Enter") {
addTodo();
}
}
return (
<div className="d-flex m-4 " onKeyDown={handleEnter}>
<input
className="form-control add-task flex-grow-1"
type="text"
name="newTask"
value={newTodo.task}
onChange={handleChange}
placeholder="Add New Task..."
/>
<FontAwesomeIcon icon={faPlus} className="btn btn-dark icon add" onClick={addTodo} />
</div>
);
};
export default TodoForm;
|
import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs/blocks';
import { List } from './List';
import { Box } from './Box';
<Meta title="Components/List" component={List} />
export const items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
];
<Canvas>
<Story name="Default">
{(args) => (
<List {...args}>
{items.map((item) => (
<List.Item key={item.id}>{item.name}</List.Item>
))}
</List>
)}
</Story>
</Canvas>
<ArgsTable story="Default" />
|
/*
* Licencia: Este código y cualquier derivado de el, es propiedad de la
* empresa Metasoft SA de CV y no debe, bajo ninguna circunstancia
* ser copiado, donado, cedido, modificado, prestado, rentado y/o
* mostrado a ninguna persona o institución sin el permiso expli-
* cito y por escrito de la empresa Metasoft SA de CV, que es,
* bajo cualquier criterio, el único dueño de la totalidad de este
* código y cualquier derivado de el.
* ---------------------------------------------------------------
* Paquete: io.kebblar.petstore.api.service
* Proyecto: petstore-back
* Tipo: Clase
* Nombre: TipoDireccionServiceImpl
* Autor: Gustavo Adolfo Arellano (GAA)
* Correo: gustavo.arellano@metasoft.com.mx
* Versión: 0.0.1-SNAPSHOT
*
* Historia:
* Creación: 5 Sep 2021 @ 09:25:39
*/
package io.kebblar.petstore.api.service;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import io.kebblar.petstore.api.model.domain.TipoDireccion;
import io.kebblar.petstore.api.mapper.TipoDireccionMapper;
import io.kebblar.petstore.api.model.exceptions.ServiceException;
import io.kebblar.petstore.api.model.exceptions.MapperException;
/**
* <p>Implementación de la interfaz {@link io.kebblar.petstore.api.service.TipoDireccionService}.
*
* <p>Todos los métodos de esta clase disparan {@link io.kebblar.petstore.api.model.exceptions.ServiceException}
*
* @author luz
* @version 1.0-SNAPSHOT
* @since 1.0-SNAPSHOT
* @see TipoDireccion
* @see TipoDireccionService
*/
@Service("tipoDireccionService")
public class TipoDireccionServiceImpl implements TipoDireccionService {
private static final Logger logger = LoggerFactory.getLogger(TipoDireccionServiceImpl.class);
private final TipoDireccionMapper tipoDireccionMapper;
/**
* Constructor que realiza el setting de todos los Mappers y todos los
* servicios adicionales a ser empleados en esta clase.
*
* @param tipoDireccionMapper mapper utilizado para llamar a metodos de persistencia
*/
public TipoDireccionServiceImpl(TipoDireccionMapper tipoDireccionMapper) {
logger.debug("Invoking TipoDireccionServiceImpl constructor");
this.tipoDireccionMapper = tipoDireccionMapper;
}
/** {@inheritDoc} */
@Override
public TipoDireccion getById(int id) throws ServiceException {
try {
return tipoDireccionMapper.getById(id);
} catch (Exception e) {
throw new MapperException("Error al obtener el tipo de dirección: "+id, e.getMessage());
}
}
/** {@inheritDoc} */
@Override
public List<TipoDireccion> getAll() throws ServiceException {
try {
return tipoDireccionMapper.getAll();
} catch (Exception e) {
throw new MapperException("Error al recuperar la lista de tipo dirección", e.getMessage());
}
}
/** {@inheritDoc} */
@Override
public int insert(TipoDireccion tipoDireccion) throws ServiceException {
try {
return tipoDireccionMapper.insert(tipoDireccion);
} catch (Exception e) {
throw new MapperException("Error al insertar un nuevo tipo de dirección "+tipoDireccion.getNombre(), e.getMessage());
}
}
/** {@inheritDoc} */
@Override
public int update(TipoDireccion tipoDireccion) throws ServiceException {
try {
return tipoDireccionMapper.update(tipoDireccion);
} catch (Exception e) {
throw new MapperException("Error al actualizar el tipo de dirección "+tipoDireccion.getId(), e.getMessage());
}
}
/** {@inheritDoc} */
@Override
public int delete(TipoDireccion tipoDireccion) throws ServiceException {
try {
return tipoDireccionMapper.delete(tipoDireccion.getId());
} catch (Exception e) {
throw new MapperException("Error al borrar el tipo de dirección "+tipoDireccion.getId(), e.getMessage());
}
}
/** {@inheritDoc} */
@Override
public int save(TipoDireccion tipoDireccion) throws ServiceException {
try {
if (getById(tipoDireccion.getId()) == null) {
return tipoDireccionMapper.insert(tipoDireccion);
} else {
return tipoDireccionMapper.update(tipoDireccion);
}
} catch (Exception e) {
throw new MapperException("Error al actualizar el tipo de dirección "+tipoDireccion.getId(), e.getMessage());
}
}
}
|
import { Injectable, NotFoundException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PrismaService } from 'src/prisma/prisma.service';
// import { send } from 'process';
import { Product } from './product.model';
@Injectable()
export class ProductsService{
constructor(
private prisma: PrismaService,
private config: ConfigService,
) {}
//get all products
async getAll(){
const products = await this.prisma.products.findMany();
return [...products];
}
//get single product
async getById(proId){
const product = await this.prisma.products.findUnique(
{
where:{
id : proId,
},
}
);
if(product){
return {...product};
}else{
throw new NotFoundException(' Product was not exist');
}
}
// insert product
async insert(data : any){
const product = await this.prisma.products.create({
data: {
title: data.title,
description: data.description,
price: data.price
}
});
return product;
}
//Update product
async update(proId,data : any){
const product = await this.getById(proId);
if(product){
try{
const updateProduct = await this.prisma.products.update({
where :{
id : proId,
},
data :{
title : data.title,
description : data.description,
price : data.price
}
});
return "product updated successfully";
}catch(error){
return "faild update product";
}
}else{
throw new NotFoundException(' Product was not exist');
}
}
// delete product
async delete(proId){
const product = await this.getById(proId);
if(product){
try{
const deleteProduct = await this.prisma.products.delete({
where : {
id : proId,
},
});
return "product successfully deleted";
}catch(error){
return "faild delete product";
}
}else{
throw new NotFoundException(' Product was not exist');
}
}
}
|
#include <stdio.h>
#define NUM_ALUNOS 15
int main() {
char nomes[NUM_ALUNOS][50];
float notas_prova1[NUM_ALUNOS];
float notas_prova2[NUM_ALUNOS];
float media_aluno[NUM_ALUNOS];
float soma_notas = 0;
// Entrada de dados para cada aluno
for (int i = 0; i < NUM_ALUNOS; i++) {
printf("Digite o nome do aluno %d: ", i + 1);
scanf("%s", nomes[i]);
printf("Digite a nota da prova 1 do aluno %d: ", i + 1);
scanf("%f", ¬as_prova1[i]);
printf("Digite a nota da prova 2 do aluno %d: ", i + 1);
scanf("%f", ¬as_prova2[i]);
// Calcula a média do aluno
media_aluno[i] = (notas_prova1[i] + notas_prova2[i]) / 2;
// Acumula as notas para calcular a média geral da turma
soma_notas += media_aluno[i];
}
// Imprime a listagem de alunos e suas médias
printf("\nListagem de Alunos e Médias:\n");
printf("------------------------------------------\n");
printf("Nome\tNota Prova 1\tNota Prova 2\tMédia\n");
printf("------------------------------------------\n");
for (int i = 0; i < NUM_ALUNOS; i++) {
printf("%s\t%.2f\t\t%.2f\t\t%.2f\n", nomes[i], notas_prova1[i], notas_prova2[i], media_aluno[i]);
}
printf("------------------------------------------\n");
// Calcula e imprime a média geral da turma
float media_geral = soma_notas / NUM_ALUNOS;
printf("\nMédia Geral da Turma: %.2f\n", media_geral);
return 0;
}
|
(function($){
var boundHashChanges = {},
subscribedPagingMessages = {},
currentPageLoads = {},
buildLinks = function(context) {
var links = [],
settings = context.settings,
totalPages,
modifyUrl = function(page) {
var query = {};
query[settings.pageKey] = page;
var mod = {
url: settings.baseUrl,
query: query
};
if(settings.hash && settings.hash.length > 0) {
mod[settings.hash] = settings.hash;
}
return $.telligent.evolution.url.modify(mod);
};
if(settings.totalItems === 0 || settings.pageSize === 0) {
totalPages = 0;
} else {
totalPages = Math.floor(settings.totalItems / settings.pageSize);
if(settings.totalItems % settings.pageSize > 0) {
totalPages = totalPages + 1;
}
}
if(totalPages > 1) {
// first
if(settings.showFirst) {
if(settings.currentPage >= 3 && totalPages > settings.numberOfPagesToDisplay) {
links[links.length] = {
type: 'first',
selected: false,
page: 1,
url: modifyUrl(1)
};
}
}
// previous
if(settings.showPrevious) {
if(settings.currentPage > 0) {
links[links.length] = {
type: 'previous',
selected: false,
page: settings.currentPage,
url: modifyUrl(settings.currentPage)
};
}
}
// individual page links
if(settings.showIndividualPages) {
// determine lower bound
var start;
if(totalPages < settings.numberOfPagesToDisplay || settings.currentPage - Math.floor(settings.numberOfPagesToDisplay / 2) < 0) {
start = 0;
} else if(settings.currentPage + Math.floor(settings.numberOfPagesToDisplay / 2) >= totalPages) {
start = totalPages - settings.numberOfPagesToDisplay;
} else {
start = settings.currentPage - Math.floor(settings.numberOfPagesToDisplay / 2);
}
// determine upper bound
var end;
var lastBuffer = Math.floor(settings.numberOfPagesToDisplay / 2);
if(settings.numberOfPagesToDisplay % 2 === 0) {
lastBuffer = lastBuffer - 1;
}
if(totalPages < settings.numberOfPagesToDisplay || settings.currentPage + lastBuffer >= totalPages) {
end = totalPages - 1;
} else if(settings.currentPage - Math.floor(settings.numberOfPagesToDisplay / 2) < 0) {
end = settings.numberOfPagesToDisplay - 1;
} else {
end = settings.currentPage + lastBuffer;
}
// add links
var i;
for(i = start; i <= end; i++) {
links[links.length] = {
type: 'page',
selected: (settings.currentPage === i),
page: i + 1,
url: modifyUrl(i+1)
};
}
}
// next
if(settings.showNext) {
if(settings.currentPage + 1 < totalPages) {
links[links.length] = {
type: 'next',
selected: false,
page: settings.currentPage + 2,
url: modifyUrl(settings.currentPage + 2)
};
}
}
// last
if(settings.showLast) {
if(settings.currentPage + 3 < totalPages && totalPages > settings.numberOfPagesToDisplay) {
links[links.length] = {
type: 'last',
selected: false,
page: totalPages,
url: modifyUrl(totalPages)
};
}
}
}
return links;
},
renderLinks = function(context) {
var pagerHtml = context.template({ links: context.links });
context.selection.html(pagerHtml);
},
initAjaxPaging = function(context) {
subscribeToPagingMessages(context);
bindToHashChanges(context);
changeHashOnNavigation(context);
loadInitialPage(context);
},
loadInitialPage = function(context) {
// if there was already a page key in this query string's hash, pre-load that page
var initialPage = parseInt($.telligent.evolution.url.hashData()[context.settings.pageKey], 10);
if(!isNaN(initialPage) && initialPage !== context.settings.currentPage) {
// don't allow page loads to stack up infinitely in case a pager was included on a callback
if(currentPageLoads[context.settings.pageKey]) { return; }
currentPageLoads[context.settings.pageKey] = true;
// call the implementation of the paged content requestor
context.settings.onPage(initialPage, function(response){
context.currentPageIndex = initialPage;
renderNewlyPagedContent(context, initialPage, 0, response, false);
});
};
},
changeHashOnNavigation = function(context) {
// intercept paging link clicks and update the hash data
$(context.selection).delegate('a','click',function(e){
e.preventDefault();
var link = $(this),
hashModification = {};
hashModification[context.settings.pageKey] = link.data('page');
$.telligent.evolution.url.hashData(hashModification);
});
},
bindToHashChanges = function(context) {
// only bind to a hash change once for a given key
if(boundHashChanges[context.settings.pageKey]) { return; }
boundHashChanges[context.settings.pageKey] = true;
// listen for relevant hash changes related to page changes
context.currentPageIndex = parseInt($.telligent.evolution.url.hashData()[context.settings.pageKey], 10);
if(isNaN(context.currentPageIndex)) {
context.currentPageIndex = context.settings.currentPage;
}
$(window).bind('hashchange', function(e){
var newPageIndex = parseInt($.telligent.evolution.url.hashData()[context.settings.pageKey], 10);
if(!isNaN(newPageIndex)) {
if(context.currentPageIndex === newPageIndex)
return;
context.newPageIndex = newPageIndex;
var dataToTrigger = {
currentPage: context.currentPageIndex,
newPage: context.newPageIndex,
container: context.settings.pagedContentContainer
};
// publish global message
$.telligent.evolution.messaging.publish(context.settings.pagedContentPagingEvent, dataToTrigger);
// raise local event on this plugin
context.selection.trigger('evolutionPagerPaging', dataToTrigger)
context.currentPageIndex = newPageIndex;
}
});
},
subscribeToPagingMessages = function(context) {
// unsubscribe from previous subscriptions for this widget, if there were any
if(subscribedPagingMessages[context.settings.pagedContentPagingEvent]) {
context.currentPageIndex = parseInt($.telligent.evolution.url.hashData()[context.settings.pageKey], 10);
$.telligent.evolution.messaging.unsubscribe(subscribedPagingMessages[context.settings.pagedContentPagingEvent]);
}
// subscribe to paging messages
subscribedPagingMessages[context.settings.pagedContentPagingEvent] =
$.telligent.evolution.messaging.subscribe(context.settings.pagedContentPagingEvent, function(data) {
// don't allow page loads to stack up infinitely in case a pager was included on a callback
if(currentPageLoads[context.settings.pageKey]) { return; }
currentPageLoads[context.settings.pageKey] = true;
// call the implementation of the paged content requestor
context.settings.onPage(data.newPage, function(response){
context.currentPageIndex = data.newPage;
renderNewlyPagedContent(context, data.newPage, data.currentPage, response, true);
})
});
},
renderNewlyPagedContent = function(context, page, oldPage, content, shouldAnimate) {
var publishPagedMessage = function() {
var dataToTrigger = {
page: page,
container: context.settings.pagedContentContainer
};
// publish global message
$.telligent.evolution.messaging.publish(context.settings.pagedContentPagedEvent, dataToTrigger);
// raise local event on this plugin
context.selection.trigger('evolutionPagerPaged', dataToTrigger)
};
// render content
if(shouldAnimate && (context.settings.transition === 'slide' || context.settings.transition === 'fade')) {
var transition = 'fade';
if(context.settings.transition === 'slide') {
transition = page < oldPage ? 'slideRight' : 'slideLeft';
}
var container = $(context.settings.pagedContentContainer);
var newContent = $('<div></div>')
.attr('id',container.attr('id'))
.html(content)
.hide()
.insertAfter(context.settings.pagedContentContainer);
container.glowTransition(newContent, {
type: transition,
duration: context.settings.transitionDuration,
complete: function() {
$(context.settings.pagedContentContainer).css({width:'',height:'',overflow:'hidden'});
publishPagedMessage();
currentPageLoads[context.settings.pageKey] = false;
}
});
} else {
$(context.settings.pagedContentContainer).html(content);
publishPagedMessage();
currentPageLoads[context.settings.pageKey] = false;
}
// update links
context.settings.currentPage = page - 1;
context.links = buildLinks(context);
renderLinks(context);
};
$.fn.evolutionPager = function(options) {
var settings = $.extend({}, $.fn.evolutionPager.defaults, options || {}),
context = {
selection: this,
settings: settings,
template: $.telligent.evolution.template.compile(settings.template)
};
context.links = buildLinks(context);
renderLinks(context);
if(settings.onPage && settings.pagedContentContainer &&
settings.pagedContentContainer.length > 0)
{
initAjaxPaging(context);
}
return this;
};
$.fn.evolutionPager.defaults = {
// normal options
currentPage: 0,
pageSize: 10,
totalItems: 0,
showPrevious: false,
showNext: false,
showFirst: true,
showLast: true,
showIndividualPages: true,
numberOfPagesToDisplay: 5,
pageKey: 'pi',
hash: '',
baseUrl: window.location.href,
// ajax-specific options
onPage: function(pageIndex, complete) { },
pagedContentContainer: '',
pagedContentPagingEvent: 'ui.page.paging',
pagedContentPagedEvent: 'ui.page.paged',
transition: null, // slide|fade|null
transitionDuration: 250,
// template
template: '' +
' <% foreach(links, function(link, i) { %> ' +
' <% if(link.type === "first") { %> ' +
' <a href="<%: link.url %>" class="first" data-type="first" data-page="<%= link.page %>" data-selected="false"> ' +
' <span>«</span> ' +
' </a> ' +
' <% } else if(link.type === "previous") { %> ' +
' <a href="<%: link.url %>" class="previous" data-type="previous" data-page="<%= link.page %>" data-selected="false"> ' +
' <span><</span> ' +
' </a> ' +
' <% } else if(link.type === "page") { %> ' +
' <a href="<%: link.url %>" class="page<%= link.selected ? " selected" : "" %>" data-type="page" data-page="<%= link.page %>" data-selected="<%= link.selected ? "true" : "false" %>"> ' +
' <span><%= link.page %></span> ' +
' </a> ' +
' <% } else if(link.type === "next") { %> ' +
' <a href="<%: link.url %>" class="next" data-type="next" data-page="<%= link.page %>" data-selected="false"> ' +
' <span>></span> ' +
' </a> ' +
' <% } else if(link.type === "last") { %> ' +
' <a href="<%: link.url %>" class="last" data-type="last" data-page="<%= link.page %>" data-selected="false"> ' +
' <span>»</span> ' +
' </a> ' +
' <% } %> ' +
' <% if(i < (links.length - 1)) { %> ' +
' <span class="separator"></span> ' +
' <% } %> ' +
' <% }); %> '
};
}(jQuery));
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_GREETING
/*
This program has two arguments: the first is a greeting message, and the
second is a name.
The message is an impersonal greeting, such as "Hi" or "Good morning".
name is set to refer to a string holding a friend's name, such as
"Emmanuel" or "Xiao".
First copy the first argument to the array greeting. (Make sure it is
properly null-terminated.)
Write code to personalize the greeting string by appending a space and
then the string pointed to by name.
So, in the first example, greeting should be set to "Hi Emmanuel", and
in the second it should be "Good morning Xiao".
If there is not enough space in greeting, the resulting greeting should be
truncated, but still needs to hold a proper string with a null terminator.
For example, "Good morning" and "Emmanuel" should result in greeting
having the value "Good morning Emmanu".
*/
int main(int argc, char **argv) {
if (argc != 3) {
fprintf(stderr, "Usage: greeting message name\n");
exit(1);
}
char greeting[20];
char *name = argv[2];
if(strlen(argv[1])<20){
strncpy(greeting,argv[1],strlen(argv[1]));
greeting[strlen(argv[1])] = '\0';
}else{
strncpy(greeting,argv[1],19);
greeting[19] = '\0';
}
printf("%s\t%s\n", greeting,name);
return 0;
}
|
library dead_simple_flutter_bottomsheet;
import 'package:flutter/material.dart';
class DeadSimpleBottomSheet extends StatefulWidget {
const DeadSimpleBottomSheet(
{super.key,
/// A callback function called with a value between 0 (collapsed) and 1 (expanded).
/// Called every time the user moves the sheet.
this.onProgress,
/// The expanded height of the sheet
required this.expandedHeight,
/// The collapsed height of the sheet
required this.collapsedHeight,
/// A builder function to build the child. Called every time the user moves the sheet.
required this.child,
/// The maximum alpha of the shadow that appears in the background when the sheet is expanded.
this.maxShadowAlpha = 0.5
});
final Function(double)? onProgress;
final double maxShadowAlpha;
final double expandedHeight;
final double collapsedHeight;
final Widget Function() child;
@override
State<DeadSimpleBottomSheet> createState() => _DeadSimpleBottomSheetState();
}
enum SheetState {
expanded,
moving,
collapsed,
}
class _DeadSimpleBottomSheetState extends State<DeadSimpleBottomSheet>
with SingleTickerProviderStateMixin {
// 0 to 1
double get progress =>
(p - widget.collapsedHeight) /
(widget.expandedHeight - widget.collapsedHeight);
late double p;
late AnimationController _controller;
late Animation<double> _pAnimation;
@override
void initState() {
p = widget.collapsedHeight;
_controller = AnimationController(
duration: const Duration(seconds: 1),
vsync: this,
)..addListener(() {
setState(() {
p = _pAnimation.value;
});
});
_pAnimation =
Tween(begin: widget.collapsedHeight, end: widget.expandedHeight)
.animate(_controller);
super.initState();
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
IgnorePointer(
ignoring: progress == 0,
child: GestureDetector(
onTap: () {
setState(() {
_controller.fling(velocity: -1.0);
});
},
child: Container(
decoration: BoxDecoration(
color: Colors.black
.withAlpha((shadowAlpha * progress * 255).round()),
),
),
),
),
AnimatedBuilder(
animation: _pAnimation,
builder: (context, child) {
return Positioned.directional(
textDirection: TextDirection.ltr,
bottom: 0,
start: 0,
end: 0,
child: SizedBox(
height: _pAnimation.value,
child: OverflowBox(
child: GestureDetector(
onVerticalDragEnd: (details) {
if (progress > 0.5) {
_controller.fling();
widget.onProgress?.call(1);
} else {
_controller.fling(velocity: -1.0);
widget.onProgress?.call(0);
}
},
onVerticalDragUpdate: (details) {
double dy = details.primaryDelta! * -1;
setState(() {
if (_pAnimation.value + dy < widget.collapsedHeight) {
_controller.value = 0;
} else if (_pAnimation.value + dy >
widget.expandedHeight) {
_controller.value = 1;
} else {
_controller.value += dy /
(widget.expandedHeight - widget.collapsedHeight);
}
});
widget.onProgress?.call(progress);
},
child: widget.child(),
),
),
),
);
},
)
],
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}
|
import clsx from "clsx";
import { motion } from "framer-motion";
import { animationFrameEffect, useVisibleScrollEffect } from "src/lib/hooks";
import {
Dispatch,
ReactElement,
RefObject,
SetStateAction,
useRef,
} from "react";
import { useWindowSize } from "react-use";
import { SanityImg } from "sanity-react-extra";
import { Enterprise as EnterpriseInterface } from "lib/@types/use-case-types";
import { imageUrlBuilder } from "utils/sanity";
// import Button from './ui/_Button'
interface EnterpriseProps {
item: EnterpriseInterface;
index: number;
rootRef: RefObject<Element>;
length: number;
setCurrent: Dispatch<SetStateAction<number>>;
current: number;
isScroll: boolean;
}
export default function Enterprise({
item,
index,
rootRef,
length,
setCurrent,
current,
isScroll,
}: EnterpriseProps): ReactElement {
const sectionRef = useRef<HTMLDivElement>(null);
// const [transition, setTransition] = useState(0)
const { height: windowHeight, width: windowWidth } = useWindowSize() ?? {
width: 0,
height: 0,
};
const toggleVisibility = function (visible: boolean) {
if (visible) {
sectionRef.current.style.transform = `translate3d(0px, 0px, 0px) scale3d(1, 1, 1) rotateX(0deg) rotateY(0deg) rotateZ(0deg) skew(0deg, 0deg)`;
sectionRef.current.style.opacity = "1";
} else {
sectionRef.current.style.transform = `translate3d(0px, -120%, 0px) scale3d(1, 1, 1) rotateX(0deg) rotateY(0deg) rotateZ(0deg) skew(0deg, 0deg)`;
sectionRef.current.style.opacity = "0";
}
};
useVisibleScrollEffect(
rootRef,
(offsetBoundingRect, _, y) =>
animationFrameEffect(() => {
const yDelta = y + windowHeight - offsetBoundingRect.top;
const ratio = Math.max(0, Math.min(yDelta / windowHeight, length));
let transitionYValue = 0;
let sectionRatio = 0;
if (index === length - 2) {
sectionRatio = 0;
} else if (ratio >= 0 && ratio < index + 1.5) {
sectionRatio = 0;
transitionYValue = 0;
} else if (ratio > index + 1.5 && ratio < index + 2) {
sectionRatio = ratio - (index + 1);
transitionYValue = 0 + (0.5 - sectionRatio) * 200;
} else {
sectionRatio = 1;
transitionYValue = -120;
}
if (isScroll) {
if (current !== index) {
toggleVisibility(false);
} else {
toggleVisibility(true);
}
} else if (sectionRef.current) {
if (transitionYValue === -120) {
toggleVisibility(false);
} else {
toggleVisibility(true);
if (ratio >= index + 1 || (ratio < 1 && index === 0)) {
setCurrent(index);
} else {
toggleVisibility(false);
}
}
}
}),
[windowHeight, isScroll, current]
);
return (
<motion.div
className={clsx(
"relative flex h-full w-full items-center opacity-0 transition-all duration-500",
item.imagePosition === "center" && "justify-center",
item.imagePosition === "right" && "justify-end",
item.imagePosition === "left" && "justify-start"
)}
ref={sectionRef}
style={{
zIndex: 10 - index,
opacity: 1,
}}
>
<div
className={clsx(
"rounded-lg object-contain",
item.imagePosition !== "center" && "h-[50%] w-[60%] lg:h-[70%]",
item.imagePosition === "center" && "w-full"
)}
>
<SanityImg
className="h-full w-full rounded-xl object-cover md:object-contain"
builder={imageUrlBuilder}
image={item.image}
alt={item.image?.alt || "image"}
height={windowWidth >= 768 ? 1000 : 500}
/>
</div>
<div
className={clsx(
"absolute flex h-full w-full",
item.cardPosition === "bottom-right" &&
"translate-y-[-20%] translate-x-[-5%] items-end justify-end md:translate-y-[-20%] lg:translate-y-[-10%] xl:translate-y-[-1%] xl:translate-x-[-10%] 2xl:translate-y-[-5%]",
item.cardPosition === "bottom-left" &&
"translate-y-[-20%] translate-x-[5%] items-end justify-start md:translate-y-[-20%] lg:translate-y-[-10%] xl:translate-y-[-1%] xl:translate-x-[10%] 2xl:translate-y-[-5%]",
item.cardPosition === "left" && "items-center justify-start",
item.cardPosition === "right" && "items-center justify-end"
)}
>
<div
className={clsx(
"bifrost__transparent_card w-[70vw] rounded-lg p-4 md:max-w-md lg:max-w-xl lg:p-10 xl:max-w-2xl xl:space-y-10"
)}
>
<div className="flex-col space-y-3 md:space-y-10">
<h5 className="text-[22px] font-[275] leading-[22px] lg:text-head-4">
{item.headline}
</h5>
{!!item?.subtitle && (
<h6 className="text-[22px] font-light leading-none md:text-p-2 xl:text-[30px]">
{item.subtitle}
</h6>
)}
<div className="text-[14px] font-[300] leading-[16px] lg:text-body-1">
{item.body}
</div>
<div className="flex">
{/* <Button>
<a href={item.ctaButton.href}>{item.ctaButton.title}</a>
</Button> */}
</div>
</div>
</div>
</div>
</motion.div>
);
}
|
import { ForbiddenException, Injectable } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import * as bcrypt from 'bcrypt'
import { AuthDto } from 'src/auth/dto';
import { Tokens } from 'src/auth/types';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class AuthService {
constructor(private prisma: PrismaService,
private jwtService: JwtService
) { }
// signIn to the application/database
async signupLocal(dto: AuthDto): Promise<Tokens> {
try {
const { email, password } = dto;
const hash = await this.hashPassword(password);
const newUser = await this.prisma.user.create({
data: {
email, hash,
}
})
const tokens = await this.getTokens(newUser.id, newUser.email)
console.log(`current hashRT`, newUser.hashedRT)
await this.updateRefreshTokenHash(newUser.id, tokens.refresh_token);
return tokens;
} catch (error) {
console.log("Error in the signup", error)
}
}
// signIn local service
async signinLocal(dto: AuthDto): Promise<Tokens> {
try {
const { email, password }: any = dto
const user = await this.prisma.user.findUnique({
where: { email }
})
if (!user) {
throw new ForbiddenException('Access Denied')
}
//console.log(password, user.hash)
const matchPassword = await bcrypt.compare(password, user.hash);
if (!matchPassword) {
throw new ForbiddenException("Acess Denied")
}
const tokens = await this.getTokens(user.id, user.email);
await this.updateRefreshTokenHash(user.id, tokens.refresh_token)
return tokens;
}
catch (error) {
console.log('Error in the signIn :', error)
}
}
// signout local service
async logout(userId: number): Promise<boolean> {
const response = await this.prisma.user.updateMany({
where: {
id: userId,
hashedRT: {
not: null,
},
},
data: {
hashedRT: null,
},
}).catch(error => {
console.log(error)
})
return true;
}
async refreshToken(userId: number, refreshToken: string): Promise<any> {
const User = await this.prisma.user.findUnique({
where: {
id: userId
}
})
.catch(error => console.log(error))
if (!User) {
throw new ForbiddenException("Access Denied");
}
const refreshTokenMatch = await bcrypt.compare(refreshToken, User.hashedRT).catch(
error => console.log(`something went wrong` + error)
);
if (!refreshTokenMatch) {
throw new ForbiddenException('Access Denied')
}
const tokens = await this.getTokens(User.id, User.email);
await this.updateRefreshTokenHash(User.id, tokens.refresh_token);
//console.log(tokens)
return tokens;
}
// utility functions for services
async hashPassword(password: string): Promise<string> {
return await bcrypt.hash(password, 10);
}
async getTokens(userId: number, email: string): Promise<Tokens> {
const [access_token, refresh_token] = await Promise.all([
this.jwtService.signAsync({
sub: userId,
email: email,
}, {
secret: process.env.ACCESS_SECRET,
expiresIn: '15m',
}),
this.jwtService.signAsync({
sub: userId,
email: email,
}, {
secret: process.env.REFRESH_SECRET,
expiresIn: '1d',
})
])
return {
access_token, refresh_token,
}
}
async updateRefreshTokenHash(userId: number, refreshToken: string) {
const hashedRT = await this.hashPassword(refreshToken);
await this.prisma.user.update({
where: {
id: userId,
},
data: {
hashedRT,
}
})
return true
}
}
|
import Foundation
protocol LaunchesNetworkServiceProtocol {
func getLaunchesRocket (completion: @escaping (Result<[LaunchesJsonModel]?, Error>) -> Void)
}
class LaunchesNetworkService: LaunchesNetworkServiceProtocol {
func getLaunchesRocket(completion: @escaping (Result<[LaunchesJsonModel]?, Error>) -> Void) {
let urlString = "https://api.spacexdata.com/v4/launches"
guard let url = URL(string: urlString) else { return }
var request = URLRequest(url: url)
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request) { data, _, error in
DispatchQueue.main.async {
guard error == nil, let data = data else { return }
do {
let launchesRocket = try JSONDecoder().decode([LaunchesJsonModel].self, from: data)
completion(.success(launchesRocket))
} catch {
completion(.failure(error))
}
}
}.resume()
}
}
|
#pragma once
template<class T>
class axScopedPush {
using This = axScopedPush<T>;
public:
explicit axScopedPush(T& v)
: _v(&v)
, _oldValue(v)
{}
explicit axScopedPush(T& v, const T& newValue)
: _v(&v)
, _oldValue(v)
{
v = newValue;
}
axScopedPush(This && r) {
_v = r._v;
_oldValue = r._oldValue;
r._v = nullptr;
}
~axScopedPush() {
if (!_v) return;
*_v = _oldValue;
}
T& value() { return *_v; }
T* ptr() { return _v; }
T* operator->() { return _v; }
template<class R> void operator = (const R& r) { *_v = r; }
template<class R> void operator += (const R& r) { *_v += r; }
template<class R> void operator -= (const R& r) { *_v -= r; }
template<class R> void operator *= (const R& r) { *_v *= r; }
template<class R> void operator /= (const R& r) { *_v /= r; }
template<class R> void operator |= (const R& r) { *_v |= r; }
template<class R> void operator &= (const R& r) { *_v &= r; }
template<class R> void operator ^= (const R& r) { *_v /= r; }
private:
T* _v = nullptr;
T _oldValue;
};
template<class T> AX_NODISCARD axScopedPush<T> ax_push(T& v) { return axScopedPush<T>(v); }
template<class T> AX_NODISCARD axScopedPush<T> ax_push(T& v, const T& newValue) { return axScopedPush<T>(v, newValue); }
template<class T>
class axPushable {
using This = axPushable;
public:
template<class... ARGS>
axPushable(const ARGS&... args) : _data(ax_forward(args)...) {}
axScopedPush<T> push() {
return axScopedPush<T>(_data);
}
axScopedPush<T> push(const T& value) {
return axScopedPush<T>(_data, value);
}
const T& get() const & { return _data; }
operator const T& () const & { return _data; }
const T* operator->() const & { return &_data; }
template<class R> auto operator+ (const R& r) const { return _data * r; }
template<class R> auto operator- (const R& r) const { return _data * r; }
template<class R> auto operator* (const R& r) const { return _data * r; }
template<class R> auto operator/ (const R& r) const { return _data * r; }
template<class R> auto operator| (const R& r) const { return _data * r; }
template<class R> auto operator& (const R& r) const { return _data * r; }
template<class R> bool operator> (const R& r) const { return _data > r; }
template<class R> bool operator< (const R& r) const { return _data < r; }
template<class R> bool operator>=(const R& r) const { return _data >= r; }
template<class R> bool operator<=(const R& r) const { return _data <= r; }
template<class R> bool operator==(const R& r) const { return _data == r; }
template<class R> bool operator!=(const R& r) const { return _data != r; }
T& edit() & { return _data; }
private:
T _data;
};
|
package("pnuts.tools")
use("pnuts.tools")
import java.io.PrintStream
import java.io.PrintWriter
import java.io.FileReader
import java.io.FileOutputStream
import java.io.FileInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.net.URL
import java.awt.Frame
import java.awt.Font
import java.awt.Label
import java.awt.Cursor
import java.awt.FlowLayout
import java.awt.FileDialog
import java.awt.Dialog
import java.awt.TextArea
import java.awt.TextField
import java.awt.Color
import org.pnuts.awt.TextAreaOutputStream
import org.pnuts.awt.DialogOutputStream
import pnuts.awt.PnutsLayout
import pnuts.lang.Context
import pnuts.lang.Pnuts
import pnuts.lang.Runtime
import pnuts.compiler.CompilerPnutsImpl
getLineSeparator = function (ta){
ta.setText("\n")
ta.selectAll()
e = ta.getSelectionEnd()
sep = getProperty("line.separator")
if (e == 1){
ta.setText("")
return sep.substring(0, 1)
} else {
ta.setText("")
return sep
}
}
adjustLineSeparator = function (str, sep){
s = StringBuffer()
rest = str
while (rest != null && rest.length() > 0){
idx = rest.indexOf('\n')
if (idx < 0) {
s.append(rest)
break
}
s.append(rest[0..idx-1])
s.append(sep)
rest = rest[idx + 1..]
}
return s.toString()
}
function pnutool (context) {
fontsize = 12
fontstyle = Font::PLAIN
fontname = "sansserif"
directory = null
fr = frame("Pnuts")
ta1 = TextArea("", 10, 10, TextArea::SCROLLBARS_NONE)
ta2 = TextArea("", 10, 10, TextArea::SCROLLBARS_VERTICAL_ONLY)
ta1.setBackground(Color::white)
ta2.setBackground(Color::white)
ta2.setEditable(false)
layout(fr, [PnutsLayout, "halign=fill,valign=fill,expand=x",
ta1, [ta2, "expand=y"]])
lineSeparator = getLineSeparator(ta1)
context.setOutputStream(BufferedOutputStream(TextAreaOutputStream(ta2)))
output = context.getWriter()
context.setErrorStream(PrintWriter(DialogOutputStream(fr), true))
function open (e) {
fd = FileDialog(fr, "Open")
if (directory != null){
fd.setDirectory(directory)
}
fd.show()
str = fd.getFile()
if (str == null){
return
}
directory = fd.getDirectory()
path = directory + getProperty("file.separator") + str
file = File(path)
if (file.exists()){
ta1.setText("")
read(FileReader(path), PrintWriter(TextAreaOutputStream(ta1)))
ta1.setCaretPosition(0)
}
}
function openURL(e){
d = Dialog(fr, "open URL", true)
d.setLayout(FlowLayout())
tf = TextField(30)
d.add(Label("URL: "))
d.add(tf)
d.pack()
center = centerPosition(fr, d)
d.setLocation(center)
bind(d, "windowClosing", function (e) d.dispose())
bind(tf, "actionPerformed", function (e) {
input = tf.getText()
d.dispose()
if (input.length() == 0) return
in = URL(input).openStream()
if (in != null){
ta1.setText("")
read(in, PrintStream(BufferedOutputStream(TextAreaOutputStream(ta1))))
ta1.setCaretPosition(0)
}
in.close()
})
d.show()
tf.requestFocus()
}
function save (e) {
fd = FileDialog(fr, "Save")
if (directory != null){
fd.setDirectory(directory)
}
fd.show()
file = fd.getFile()
directory = fd.getDirectory()
if (file == null) return
path = directory + getProperty("file.separator") + file
out = FileOutputStream(path)
str = ta1.getText()
b = str.getBytes()
out.write(b, 0, b.length)
out.close()
}
function currentLine (ta){
pos = ta.getCaretPosition()
txt = ta.getText()
len = txt.length()
if (len < pos) pos = len
if (pos < 1) return ""
t = txt.substring(0, pos - 1)
sep = lineSeparator
idx2 = txt.indexOf(sep, pos - 1)
idx1 = t.lastIndexOf(sep) + 1
if (idx1 < 0) idx1 = 0
if (idx2 < 0) idx2 = txt.length()
txt.substring(idx1, idx2)
}
function waitCursor(){
wait = Cursor::getPredefinedCursor(Cursor::WAIT_CURSOR)
ta1.setCursor(wait)
ta2.setCursor(wait)
fr.setCursor(wait)
}
function defaultCursor(){
text = Cursor::getPredefinedCursor(Cursor::TEXT_CURSOR)
dft = Cursor::getPredefinedCursor(Cursor::DEFAULT_CURSOR)
ta1.setCursor(text)
ta2.setCursor(text)
fr.setCursor(dft)
}
function evaluate(e){
waitCursor()
txt = ta1.getText()
txt = adjustLineSeparator(txt, lineSeparator)
idx1 = ta1.getSelectionStart()
idx2 = ta1.getSelectionEnd()
len = txt.length()
if (len < idx1) idx1 = len
if (len < idx2) idx2 = len
cmd = txt.substring(idx1,idx2)
if (cmd == null || cmd.length() < 1){
cmd = currentLine(ta1)
}
try {
l = Pnuts::eval(cmd, context.clone())
output.println(format(l))
output.flush()
defaultCursor()
} catch(Throwable e){
error(e, context)
defaultCursor()
}
}
function close(e){
fr.dispose()
}
function selectAll(e){
ta1.selectAll()
}
function clear1(e) ta1.setText("")
function clear2(e) ta2.setText("")
function myload(e){
fd = FileDialog(fr, "Load")
if (directory != null){
fd.setDirectory(directory)
}
fd.show()
str = fd.getFile()
if (str == null){
return
}
directory = fd.getDirectory()
path = directory + getProperty("file.separator") + str
file = File(path)
if (file.exists()){
load(FileInputStream(path))
}
}
function setfont (e) {
waitCursor()
item = e.getSource()
label = item.getLabel()
fontname = label
font = Font(fontname, fontstyle, fontsize)
ta1.setFont(font)
ta2.setFont(font)
defaultCursor()
}
function setstyle (e){
waitCursor()
item = e.getSource()
label = item.getLabel().toUpperCase()
fontstyle = eval("Font::" + label)
font = Font(fontname, fontstyle, fontsize)
ta1.setFont(font)
ta2.setFont(font)
defaultCursor()
}
function setfontsize (e) {
waitCursor()
item = e.getSource()
label = item.getLabel()
fontsize = Integer::parseInt(label)
font = Font(fontname, fontstyle, fontsize)
ta1.setFont(font)
ta2.setFont(font)
defaultCursor()
}
function isApplet(){
return getPackage("").pnuts_applet != null
}
function dispose (e){
fr.dispose()
}
function exitPnutool(e){
exit(0)
}
bundle = "pnuts/tools/pnutool"
function split (e){
mbar = fr.getMenuBar()
if (ta2.isVisible()){
mitem = getMenuItem(mbar, bundle, ["edit", "hide.output"])
mitem.setLabel(formatMessage(bundle, "show.output"))
layout(fr, [PnutsLayout, "halign=fill,valign=fill,expand=xy", ta1])
ta2.setVisible(false)
ta1.requestFocus()
} else {
mitem = getMenuItem(mbar, bundle, ["edit", "show.output"])
mitem.setLabel(formatMessage(bundle, "hide.output"))
layout(fr, [PnutsLayout, "halign=fill,valign=fill,expand=x",
ta1, [ta2, "expand=y"]])
ta2.setVisible(true)
ta1.requestFocus()
}
}
mbar = menubar(fr, bundle,
[["file",
["open", open, 'O'],
["open.url", openURL, 'U'],
["save", save, 'S'],
["load", myload, 'W'],
["eval", evaluate, 'J'],
["close", close, 'Q']],
["edit|",
["font",
["serif", setfont],
["sansserif", setfont],
["dialog", setfont],
["monospaced", setfont]],
["fontstyle",
["Plain", setstyle],
["Bold", setstyle],
["Italic", setstyle]],
["fontsize",
["9", setfontsize],
["10", setfontsize],
["12", setfontsize],
["16", setfontsize],
["18", setfontsize],
["24", setfontsize]],
["-", function (e) null],
["select.all", selectAll, 'A'],
["clear.workspace", clear1, 'K'],
["clear.output", clear2, 'L'],
["hide.output", split, 'E'] ]])
function setHelpMenu(){
try {
mbar.setHelpMenu(menu(
bundle,
["help",
["users.guide",
function (e){
applet = getPackage("").pnuts_applet
if (applet == null) return
ctx = applet.getAppletContext()
ctx.showDocument(URL(applet.getDocumentBase(),
formatMessage(bundle, "guide.url")))
}
]]))
} catch (Error e){
println(e)
}
}
setHelpMenu()
fr.setSize(550, 500)
if (isApplet()){
getMenuItem(mbar, bundle, ["file", "open"]).setEnabled(false)
getMenuItem(mbar, bundle, ["file", "save"]).setEnabled(false)
getMenuItem(mbar, bundle, ["file", "load"]).setEnabled(false)
}
fr.show()
home = getProperty("user.home")
init = File(home, ".pnuts/init.pnut")
if (init.exists()) Pnuts::load(Runtime.fileToURL(init), context)
fr
}
function pnutool() {
pnutool(getContext().clone())
}
|
import {
Controller,
Get,
Post,
Request,
Body,
UseInterceptors,
UploadedFile,
Param,
} from '@nestjs/common';
import {
FileFieldsInterceptor,
FileInterceptor,
FilesInterceptor,
} from '@nestjs/platform-express';
import { ApiBearerAuth, ApiBody, ApiConsumes, ApiTags } from '@nestjs/swagger';
import { customProductPlanDto } from './dto/customProductPlanDto.dto';
import { pharmacyNetworkDto } from './dto/pharmacyNetwork.dto';
import { PharmacyNetworkService } from './pharmacyNetwork.service';
import { diskStorage } from 'multer';
import { updatePharmacyNetworkDto } from './dto/updatePharmacyNetwork.dto';
import { CustomError } from 'src/common/helper/exception';
import { deletePharmacyNetworkDto } from './dto/deletePharmacyNetwork.dto';
@Controller('pharmacy-network')
@ApiTags('PharmacyNetwok')
@ApiBearerAuth()
export class PharmacyNetworkController {
constructor(private pharmacynetworkService: PharmacyNetworkService) {}
@Post('addPharmacyNetwork')
// @UseInterceptors(
// FileInterceptor('contractFile', { dest: './uploads/contractFile/' }),
// )
// @ApiConsumes('multipart/form-data')
@ApiBody({
description: 'Create Pharmacy Netwok',
schema: {
type: 'object',
properties: {
userType: {
type: 'string',
},
name: {
type: 'string',
},
personName: {
type: 'string',
},
address: {
type: 'string',
},
town: {
type: 'string',
},
postalCode: {
type: 'string',
},
country: {
type: 'string',
},
email: {
type: 'string',
},
phoneNumber: {
type: 'string',
},
personOfReference: {
type: 'string',
},
vat: {
type: 'string',
},
galaxy: {
type: 'string',
},
productPlan: {
type: 'string',
},
// contractFile: {
// type: 'string',
// format: 'binary',
// },
paymentMode: {
type: 'string',
},
hqClient: {
type: 'string',
},
agentClient: {
type: 'string',
},
},
},
})
async addPharmacyNetwork(
// @UploadedFile() contractFile: Express.Multer.File,
@Body() pharmacyNetworkDto: pharmacyNetworkDto,
) {
// if (contractFile) {
// pharmacyNetworkDto.contractFile = contractFile.originalname;
// }
console.log("pharmacyNetworkDto:::::::::::::::::::::::",pharmacyNetworkDto);
const addPharamacyNetwork =
await this.pharmacynetworkService.addPharamacyNetwork(pharmacyNetworkDto);
return addPharamacyNetwork;
}
@Get('getProductPlanDetails')
async getProductPlanDetails(@Request() req: Request) {
const getProductPlan = await this.pharmacynetworkService.getProductPlan();
return getProductPlan;
}
@Post('addCustomProductPlan')
async addCustomProductPlan(@Body() params: customProductPlanDto) {
console.log('params is:::::::::::::::', params);
const addCustomProductPlan =
await this.pharmacynetworkService.addCustomProductPlan(params);
return addCustomProductPlan;
}
@Post('getAllPharmacyNetwork')
@ApiBody({
schema: {
type: 'object',
properties: {
page: {
type: 'number',
},
limit: {
type: 'number',
},
search: {
type: 'string',
},
dateRange:{
type:'string'
},
startDate:{
type:'string'
},
endDate:{
type:'string'
}
},
},
})
async getAllPharmacyNetwork(@Body() body: any): Promise<any> {
return this.pharmacynetworkService.getAllPharmacyNetwork(body);
}
@Post('/activeInactivePharmacyNetwork')
@ApiBody({
schema: {
type: 'object',
properties: {
pharmacyNetworkId: {
type: 'string',
},
},
},
})
async activeInactive(@Body() body: any) {
return this.pharmacynetworkService.activeInactivePharmacyNetwork(body);
}
@Post('updatePharmacyNetwork')
async updateSubAdmin(@Body() body: updatePharmacyNetworkDto) {
return this.pharmacynetworkService.updatePharmacyNetwork(body);
}
@Post('getPharmacyNetworkDetails')
@ApiBody({
schema: {
type: 'object',
properties: {
pharmacyNetworkId: {
type: 'string',
},
},
},
})
async getPharmacyNetworkDetails(@Body() body: string) {
const getPharmacyNetwork =
await this.pharmacynetworkService.getPharmacyNetworkDetails(body);
return getPharmacyNetwork
}
@Post('deletePharmacyNetwork')
async deletePharmacyNetwork(@Body() body: deletePharmacyNetworkDto) {
console.log("body is::::::::::::::",body);
const getPharmacyNetwork =
await this.pharmacynetworkService.deletePharmacyNetwork(body);
return getPharmacyNetwork
}
@Post('updateManagementInfo')
@ApiBody({
schema: {
type: 'object',
properties: {
pharmacyNetworkId: {
type: 'string',
},
hqClient: {
type: 'string',
},
agentClient:{
type: 'string',
}
},
},
})
async updateManagementInfo(@Body() body: any) {
const getPharmacyNetwork =
await this.pharmacynetworkService.updateManagementInfo(body);
return getPharmacyNetwork
}
}
|
# 聚合查询
DELETE product
## 数据
PUT product
{
"mappings" : {
"properties" : {
"createtime" : {
"type" : "date"
},
"date" : {
"type" : "date"
},
"desc" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
},
"analyzer":"ik_max_word"
},
"lv" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"name" : {
"type" : "text",
"analyzer":"ik_max_word",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"price" : {
"type" : "long"
},
"tags" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"type" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
}
}
PUT /product/_doc/1
{
"name" : "小米手机",
"desc" : "手机中的战斗机",
"price" : 3999,
"lv":"旗舰机",
"type":"手机",
"createtime":"2020-10-01T08:00:00Z",
"tags": [ "性价比", "发烧", "不卡顿" ]
}
PUT /product/_doc/2
{
"name" : "小米NFC手机",
"desc" : "支持全功能NFC,手机中的滑翔机",
"price" : 4999,
"lv":"旗舰机",
"type":"手机",
"createtime":"2020-05-21T08:00:00Z",
"tags": [ "性价比", "发烧", "公交卡" ]
}
PUT /product/_doc/3
{
"name" : "NFC手机",
"desc" : "手机中的轰炸机",
"price" : 2999,
"lv":"高端机",
"type":"手机",
"createtime":"2020-06-20",
"tags": [ "性价比", "快充", "门禁卡" ]
}
PUT /product/_doc/4
{
"name" : "小米耳机",
"desc" : "耳机中的黄焖鸡",
"price" : 999,
"lv":"百元机",
"type":"耳机",
"createtime":"2020-06-23",
"tags": [ "降噪", "防水", "蓝牙" ]
}
PUT /product/_doc/5
{
"name" : "红米耳机",
"desc" : "耳机中的肯德基",
"price" : 399,
"type":"耳机",
"lv":"百元机",
"createtime":"2020-07-20",
"tags": [ "防火", "低音炮", "听声辨位" ]
}
PUT /product/_doc/6
{
"name" : "小米手机10",
"desc" : "充电贼快掉电更快,超级无敌望远镜,高刷电竞屏",
"price" : "5999",
"lv":"旗舰机",
"type":"手机",
"createtime":"2020-07-27",
"tags": [ "120HZ刷新率", "120W快充", "120倍变焦" ]
}
PUT /product/_doc/7
{
"name" : "挨炮 SE2",
"desc" : "除了CPU,一无是处",
"price" : "3299",
"lv":"旗舰机",
"type":"手机",
"createtime":"2020-07-21",
"tags": [ "割韭菜", "割韭菜", "割新韭菜" ]
}
PUT /product/_doc/8
{
"name" : "XS Max",
"desc" : "听说要出新款12手机了,终于可以换掉手中的4S了",
"price" : 4399,
"lv":"旗舰机",
"type":"手机",
"createtime":"2020-08-19",
"tags": [ "5V1A", "4G全网通", "大" ]
}
PUT /product/_doc/9
{
"name" : "小米电视",
"desc" : "70寸性价比只选,不要一万八,要不要八千八,只要两千九百九十八",
"price" : 2998,
"lv":"高端机",
"type":"耳机",
"createtime":"2020-08-16",
"tags": [ "巨馍", "家庭影院", "游戏" ]
}
PUT /product/_doc/10
{
"name" : "红米电视",
"desc" : "我比上边那个更划算,我也2998,我也70寸,但是我更好看",
"price" : 2999,
"type":"电视",
"lv":"高端机",
"createtime":"2020-08-28",
"tags": [ "大片", "蓝光8K", "超薄" ]
}
PUT /product/_doc/11
{
"name": "红米电视",
"desc": "我比上边那个更划算,我也2998,我也70寸,但是我更好看",
"price": 2998,
"type": "电视",
"lv": "高端机",
"createtime": "2020-08-28",
"tags": [
"大片",
"蓝光8K",
"超薄"
]
}
GET product/_search
{
"size": 20
}
GET product/_search
{
"aggs": {
"my_agg1": {
"avg": {
"field": "{field}"
}
},
"my_agg2": {
"avg": {
"field": "{field}"
}
}
}
}
# 桶聚合
# 统计不同标签的商品数量
## doc_value和field_data(不建议使用field_data)
## 基于磁盘 基于内存
GET product/_search
{
"size": 0,
"aggs": {
"aggs_tag":{
"terms": {
"field": "tags.keyword",
"size": 30,
"order": {
"_count": "asc"
}
}
}
}
}
GET product/_search
{
"size": 0,
"aggs": {
"aggs_tag":{
"terms": {
"field": "tags.keyword"
}
}
}
}
POST product/_mapping
{
"properties":{
"tags":{
"type":"text",
"fielddata":true
}
}
}
GET product/_mapping
GET product/_search
{
"size": 0,
"aggs": {
"aggs_tag":{
"terms": {
"field": "tags"
}
}
}
}
GET product/_search
{
"size": 0,
"aggs": {
"aggs_tag": {
"terms": {
"field": "name.keyword"
}
}
}
}
# 指标聚合
## 最贵、最便宜和平均价格三个指标
GET product/_search
{
"size": 0,
"aggs": {
"max_price": {
"max": {
"field": "price"
}
},
"min_price": {
"min": {
"field": "price"
}
},
"avg_price":{
"avg": {
"field": "price"
}
}
}
}
GET product/_search
{
"size": 0,
"aggs": {
"max_stats": {
"stats": {
"field": "price"
}
}
}
}
## 按照name去重的数量
GET product/_search
{
"size": 0,
"aggs": {
"name_count": {
"cardinality": {
"field": "name"
}
}
}
}
GET product/_search
{
"size": 0,
"aggs": {
"name_count": {
"cardinality": {
"field": "name.keyword"
}
}
}
}
# 管道聚合 二次聚合
## 统计平均加个最低的商品分类
GET product/_search
{
"size": 0,
"aggs": {
"type_bucket": {
"terms": {
"field": "type.keyword"
},
"aggs": {
"price_bucket": {
"avg": {
"field": "price"
}
}
}
},
"my_bucket":{
"min_bucket": {
"buckets_path": "type_bucket>price_bucket"
}
}
}
}
# 嵌套聚合
## 统计不同类型商品中不同级别的数量
GET product/_search
{
"size": 0,
"aggs": {
"type_lv_agg": {
"terms": {
"field": "type.keyword"
},
"aggs": {
"lv_agg": {
"terms": {
"field": "lv.keyword"
}
}
}
}
}
}
## 按照lv分桶,输出每个桶的具体价格信息
GET product/_search
{
"size": 0,
"aggs": {
"lv_price_agg": {
"terms": {
"field": "lv.keyword"
},
"aggs": {
"price_agg": {
"stats": {
"field": "price"
}
}
}
}
}
}
## 统计不同类型商品不同档次的价格信息和标签信息
GET product/_search
{
"size": 0,
"aggs": {
"type_lv_agg": {
"terms": {
"field": "type.keyword"
},
"aggs": {
"lv": {
"terms": {
"field": "lv.keyword"
},
"aggs": {
"price": {
"stats": {
"field": "price"
}
},
"tags_buckets": {
"terms": {
"field": "tags.keyword"
}
}
}
}
}
}
}
}
## 统计每个商品类型中不同档次的商品中平均价格最低的档次
GET product/_search
{
"size": 0,
"aggs": {
"type_bucket": {
"terms": {
"field": "type.keyword"
},
"aggs": {
"lv_bucket": {
"terms": {
"field": "lv.keyword"
},
"aggs": {
"price_avg": {
"avg": {
"field": "price"
}
}
}
},
"my_bucket": {
"min_bucket": {
"buckets_path": "lv_bucket>price_avg"
}
}
}
}
}
}
# 基于查询结果的聚合
GET product/_search
{
"size": 10,
"query": {
"range": {
"price": {
"gte": 5000
}
}
},
"aggs": {
"tags_bucket": {
"terms": {
"field": "tags.keyword",
"size": 10
}
}
}
}
# 基于filter结果的聚合
GET product/_search
{
"size": 10,
"query": {
"constant_score": {
"filter": {
"range": {
"price": {
"gte": 5000
}
}
},
"boost": 1.2
}
},
"aggs": {
"tags_bucket": {
"terms": {
"field": "tags.keyword",
"size": 10
}
}
}
}
GET product/_search
{
"size": 10,
"query": {
"bool": {
"filter": {
"range": {
"price": {
"gte": 5000
}
}
}
}
},
"aggs": {
"tags_bucket": {
"terms": {
"field": "tags.keyword",
"size": 10
}
}
}
}
# 基于聚合的查询
GET product/_search
{
"size": 10,
"aggs": {
"tags_bucket": {
"terms": {
"field": "tags.keyword",
"size": 10
}
}
},
"post_filter": {
"term": {
"tags.keyword": "性价比"
}
}
}
# 取消查询条件
GET product/_search
{
"size": 0,
"query": {
"range": {
"price": {
"gte": 3000
}
}
},
"aggs": {
"all_max_price": {
"global": {},
"aggs": {
"max_price": {
"max": {
"field": "price"
}
}
}
},
"avg_price": {
"avg": {
"field": "price"
}
}
}
}
# 聚合排序
GET product/_search?size=0
{
"aggs": {
"tags_aggs": {
"terms": {
"field": "tags.keyword",
"size": 30,
"order": {
"_key": "asc"
}
}
}
}
}
# 多级聚合
GET product/_search?size=0
{
"aggs": {
"first_sort": {
"terms": {
"field": "type.keyword",
"order": {
"_count": "desc"
}
},
"aggs": {
"second_sort": {
"terms": {
"field": "lv.keyword",
"order": {
"_count": "asc"
}
}
}
}
}
}
}
GET product/_search?size=0
{
"aggs": {
"type_avg_price": {
"terms": {
"field": "type.keyword",
"order": {
"agg_stats>stats_agg.min": "asc"
}
},
"aggs": {
"agg_stats": {
"filter": {
"terms": {
"type.keyword": [
"耳机",
"手机",
"电视"
]
}
},
"aggs": {
"stats_agg": {
"stats": {
"field": "price"
}
}
}
}
}
}
}
}
##
|
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const dotenv = require('dotenv')
dotenv.config()
module.exports = {
data: new SlashCommandBuilder()
.setName('kick')
.setDescription('Kicks the mentioned User')
.addUserOption(option => option.setName('target').setDescription('The user to kick').setRequired(true))
.addStringOption(option => option.setName('reason').setDescription('Reason for kicking the user').setRequired(false)),
async execute(interaction) {
const guild = interaction.guild;
const user = interaction.options.getUser('target');
const channel = await interaction.guild.channels.cache.get(process.env.logChannelId);
const reason = interaction.options.getString('reason');
const kickEmbed = new EmbedBuilder()
.setColor('#FFA411')
.setAuthor({ name: interaction.user.tag, iconURL: interaction.user.displayAvatarURL() })
.setThumbnail(user.displayAvatarURL())
.setTitle('User kicked')
.addFields(
{ name: 'User', value: user.username },
{ name: 'Reason', value: reason },
{ name: 'Kicked by', value: interaction.user.username },
{ name: 'Kicked at', value: new Date().toLocaleString() },
//{ name: 'Kicked in', value: guild.name },
)
.setTimestamp()
.setFooter({ text: '© @jnk 2023' });
const kickLog = new EmbedBuilder()
.setColor('#FFA411')
.setAuthor({ name: interaction.user?.tag, iconURL: interaction.user?.displayAvatarURL() })
.setTitle('User Kicked')
.setDescription(`User **${user.username}** has been kicked by **${interaction.user?.username || 'Unknown User'}**.`)
.addFields(
{ name: 'Reason', value: reason },
{ name: 'Kicked at', value: new Date().toLocaleString() },
)
.setTimestamp()
.setFooter({ text: '© @jnk 2023' });
guild.members.kick(user,reason)
channel.send({ embeds: [kickLog] });
interaction.reply({ embeds: [kickEmbed] });
}
}
|
import {createRouter, createWebHistory} from "vue-router";
import Home from "../components/Home/Home.vue";
import Login from "../components/Login/Login.vue";
import List from "../components/List/List.vue";
import UpdateUser from "../components/Features/user/view/UpdateUser.vue";
import {initialFetchUserById, useAuthStore} from "../components/Features/user/store/authStore.js";
import {AuthGuardService} from "../shared/guard/auth.guard.js";
import { initialFetchUsers, initialRandomUser } from "../components/Features/user/store/usersStore.js";
import CreateUser from "../components/User/CreateUser.vue";
const router = createRouter({
history: createWebHistory(),
routes: [
{path: '/', component: Home, beforeEnter:[AuthGuardService, initialRandomUser]},
{path: '/login', component: Login},
{path: '/users', component: List, beforeEnter:[initialFetchUsers]},
{path: '/update-user/:id', component: UpdateUser, beforeEnter:[AuthGuardService, loadUserById]},
{path: '/create-user', component: CreateUser, beforeEnter:[AuthGuardService]},
]
})
async function loadUserById(to, from, next) {
await initialFetchUserById(to.params.id);
next();
}
router.beforeEach(async () => {
const authStore = useAuthStore()
if(!authStore.loaded){
await authStore.fetchCurrentUser();
}
});
export default router
|
import 'package:flutter/material.dart';
import 'package:vote/constant.dart';
class CustomTextField extends StatefulWidget {
final String hint;
final String label;
final TextEditingController controller;
final TextInputType keyBoardType;
const CustomTextField({
super.key,
required this.hint,
required this.controller,
required this.keyBoardType,
required this.label,
});
@override
State<CustomTextField> createState() => _CustomTextFieldState();
}
class _CustomTextFieldState extends State<CustomTextField> {
@override
Widget build(BuildContext context) {
return Column(
children: [
const SizedBox(height: 10),
TextFormField(
controller: widget.controller,
cursorColor: Colors.black,
keyboardType: widget.keyBoardType,
decoration: InputDecoration(
contentPadding:
const EdgeInsets.symmetric(vertical: 0, horizontal: 20),
labelText: widget.hint,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: const BorderSide(color: mainColor),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: const BorderSide(color: mainColor),
),
disabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: const BorderSide(color: black),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: const BorderSide(color: mainColor),
),
),
),
],
);
}
}
|
package viewpointIOModule.fileIO.xmlImport.handlers;
import com.alchemyapi.api.AlchemyAPI;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import kernel.knowledgeGraph.KnowledgeGraph;
import kernel.knowledgeGraph.nodes.superModel.resources.Agent;
import kernel.knowledgeGraph.nodes.superModel.resources.ArtificialAgent;
import kernel.knowledgeGraph.nodes.superModel.resources.HumanAgent;
import kernel.knowledgeGraph.nodes.superModel.viewpoints.ConnectedViewpoint;
import kernel.knowledgeGraph.nodes.superModel.viewpoints.ViewpointFactory;
import kernel.knowledgeGraph.nodes.superModel.viewpoints.ViewpointPolarity;
import kernel.knowledgeGraph.nodes.webSpecificModel.resources.Document;
import kernel.knowledgeGraph.nodes.webSpecificModel.resources.Topic;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import viewpointIOModule.fileIO.xmlImport.ViewpointsXMLHandler;
/**
*
* @author WillhelmK
*/
public class HALHandler extends ViewpointsXMLHandler {
private final AlchemyAPI alchemyAPI;
private ArrayList<Agent> tmpAuthors;
private ArrayList<Topic> tmpAnnotations;
private URL tmpURL;
private String tmpTitle;
private String tmpForename;
private String tmpSurname;
private String tmpJournal;
private org.w3c.dom.Document alchemyResponse;
private final AlchemyResultParser alchemyParser;
private ArtificialAgent alchemyAgent;
private int i;
public HALHandler(KnowledgeGraph KG) {
super(KG);
alchemyAPI = AlchemyAPI.GetInstanceFromString("093cf54dbd973d85666e8b401838beb3294547af");
alchemyParser = new AlchemyResultParser();
tmpAnnotations = new ArrayList<>();
tmpAuthors = new ArrayList<>();
alchemyAgent = (ArtificialAgent) KG.getNamedObject("Alchemy API");
if(alchemyAgent == null)
alchemyAgent = new ArtificialAgent("Alchemy API");
}
@Override
public void startDocument() throws SAXException {
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
switch(qName) {
case "document":
try {
tmpURL = new URL(attributes.getValue("url"));
} catch (MalformedURLException ex) {
Logger.getLogger(HALHandler.class.getName()).log(Level.SEVERE, null, ex);
}
break;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
switch(qName) {
case "forename":
tmpForename = tmp;
break;
case "surname":
tmpSurname = tmp;
break;
case "author":
tmpAuthors.add(new HumanAgent(tmpForename + " " + tmpSurname));
break;
case "title":
tmpTitle = tmp;
break;
case "journal":
tmpJournal = tmp;
break;
case "keyword":
case "abstract":
if(tmp != null) {
try {
alchemyResponse = alchemyAPI.TextGetRankedConcepts(tmp);
tmpAnnotations.addAll(alchemyParser.getExtractedTopics(alchemyResponse, 0.0f));
} catch (IOException | ParserConfigurationException | XPathExpressionException ex) {
//Logger.getLogger(HALHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
break;
case "document":
Document d = (Document) KG.getNamedObject(tmpTitle);
if(d == null) {
System.out.println("\n-------------------- Document " + i++ + " / 5179 --------------------");
d = new Document(tmpTitle);
d.setUrl(tmpURL);
KG.addResource(d);
Document journal = null;
if(tmpJournal != null) {
journal = (Document) KG.getNamedObject(tmpJournal);
if(journal == null) {
journal = new Document(tmpJournal);
KG.addResource(new Document(tmpJournal));
}
}
for(Agent author : tmpAuthors) {
Agent a = (Agent) KG.getNamedObject(author.getLabel());
if(a == null) {
a = author;
KG.addResource(a);
}
for(Topic annotation : tmpAnnotations) {
Topic t = (Topic) KG.getNamedObject(annotation.getLabel());
if(t == null) {
t = annotation;
KG.addResource(t);
}
ConnectedViewpoint v1 = ViewpointFactory.newInstance(alchemyAgent, a, t, ViewpointPolarity.POSITIVE);
KG.addViewpoint(v1);
System.out.println(v1);
ConnectedViewpoint v2 = ViewpointFactory.newInstance(alchemyAgent, d, t, ViewpointPolarity.POSITIVE);
KG.addViewpoint(v2);
System.out.println(v2);
}
ConnectedViewpoint v3 = ViewpointFactory.newInstance(a, a, d, ViewpointPolarity.POSITIVE);
KG.addViewpoint(v3);
System.out.println(v3);
if(journal != null) {
ConnectedViewpoint v4 = ViewpointFactory.newInstance(a, d, journal, ViewpointPolarity.POSITIVE);
KG.addViewpoint(v4);
System.out.println(v4);
}
}
}
tmpAnnotations.clear();
tmpAuthors.clear();
break;
}
}
@Override
public void endDocument() throws SAXException {
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
String s = "TEST08";
String key = "nfaator!plaeemo!";
Console.WriteLine(Encrypt(s, key));
Console.WriteLine(Decrypt(Encrypt(s, key), key));
}
private static string Encrypt(string s, string key)
{
StringBuilder sbResult = new StringBuilder();
byte[] KeyArray = UTF8Encoding.UTF8.GetBytes(key);
byte[] EncryptArray = UTF8Encoding.UTF8.GetBytes(s);
RijndaelManaged Rdel = new RijndaelManaged();
Rdel.Mode = CipherMode.ECB;
Rdel.Padding = PaddingMode.Zeros;
Rdel.Key = KeyArray;
ICryptoTransform CtransForm = Rdel.CreateEncryptor();
byte[] ResultArray = CtransForm.TransformFinalBlock(EncryptArray, 0, EncryptArray.Length);
foreach (byte b in ResultArray)
{
sbResult.AppendFormat("{0:x2}", b);
}
return sbResult.ToString();
}
private static string Decrypt(string s, string key)
{
byte[] KeyArray = UTF8Encoding.UTF8.GetBytes(key);
byte[] EncryptArray = HexToByte(s);
RijndaelManaged Rdel = new RijndaelManaged();
Rdel.Mode = CipherMode.ECB;
Rdel.Padding = PaddingMode.Zeros;
Rdel.Key = KeyArray;
ICryptoTransform CtransForm = Rdel.CreateDecryptor();
byte[] ResultArray = CtransForm.TransformFinalBlock(EncryptArray, 0, EncryptArray.Length);
return UTF8Encoding.UTF8.GetString(ResultArray);
}
private static byte[] HexToByte(string msg)
{
msg = msg.Replace(" ", "");
byte[] comBuffer = new byte[msg.Length / 2];
for(int i = 0; i < msg.Length; i+=2)
{
try
{
comBuffer[i / 2] = (byte)Convert.ToByte(msg.Substring(i, 2), 16);
}
catch(ArgumentOutOfRangeException ex)
{
Console.WriteLine(ex.ToString());
}
}
return comBuffer;
}
}
}
package test;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
public class FirstApp {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
FirstApp f = new FirstApp();
System.out.println(f.encrypt("TEST08"));
}
private final String KEYNAME = "nfaator!plaeemo!";
private final String ALGORITHM = "AES";
public static final String AES_ECB_NOPADDING = "AES/ECB/NoPadding";
public String encrypt(final String source) throws Exception {
byte[] eArr = null;
SecretKeySpec skeySpec = new SecretKeySpec(KEYNAME.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(AES_ECB_NOPADDING);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
eArr = cipher.doFinal(this.addPadding(source.getBytes()));
return fromHex(eArr);
}
public byte[] encryptToByteArray(final String source) throws Exception {
byte[] eArr = null;
SecretKeySpec skeySpec = new SecretKeySpec(KEYNAME.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(AES_ECB_NOPADDING);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
eArr = cipher.doFinal(this.addPadding(source.getBytes()));
return eArr;
}
public String GetEncryptString(String source) throws Exception {
StringBuilder sbResult = new StringBuilder();
byte[] eArr = null;
SecretKeySpec skeySpec = new SecretKeySpec(KEYNAME.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(AES_ECB_NOPADDING);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
eArr = cipher.doFinal(this.addPadding(source.getBytes()));
for (byte b : eArr) {
sbResult.append(String.format("%02x", b));
}
return sbResult.toString();
}
public String decrypt(final String source) throws Exception {
Cipher cipher = Cipher.getInstance(AES_ECB_NOPADDING);
SecretKeySpec skeySpec = new SecretKeySpec(KEYNAME.getBytes(), ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] eArr = this.removePadding(cipher.doFinal(this.toBytes(source)));
return new String(eArr);
}
private byte[] removePadding(final byte[] pBytes) {
int pCount = pBytes.length;
int index = 0;
boolean loop = true;
while (loop) {
if (index == pCount || pBytes[index] == 0x00) {
loop = false;
index--;
}
index++;
}
byte[] tBytes = new byte[index];
System.arraycopy(pBytes, 0, tBytes, 0, index);
return tBytes;
}
private byte[] toBytes(final String pSource) {
StringBuffer buff = new StringBuffer(pSource);
int bCount = buff.length() / 2;
byte[] bArr = new byte[bCount];
for (int bIndex = 0; bIndex < bCount; bIndex++) {
bArr[bIndex] = (byte) Long.parseLong(buff.substring(2 * bIndex, (2 * bIndex) + 2), 16);
}
return bArr;
}
private byte[] addPadding(final byte[] pBytes) {
int pCount = pBytes.length;
int tCount = pCount + (16 - (pCount % 16));
byte[] tBytes = new byte[tCount];
System.arraycopy(pBytes, 0, tBytes, 0, pCount);
for (int rIndex = pCount; rIndex < tCount; rIndex++) {
tBytes[rIndex] = 0x00;
}
return tBytes;
}
public String fromHex(byte[] pBytes) {
int pCount = pBytes.length;
StringBuffer buff = new StringBuffer(pCount * 2);
for (int pIndex = 0; pIndex < pCount; pIndex++) {
if (((int) pBytes[pIndex] & 0xff) < 0x10) {
buff.append(0);
}
buff.append(Long.toString((int) pBytes[pIndex] & 0xff, 16));
}
return buff.toString();
}
/*
String str = "0101ff01ee"
byte[] data = hexStringToByteArray(str);
*/
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16));
}
return data;
}
}
예를 들어 키는 57616C6B697A3532383332694C6F636B 입니다.
토큰을 얻기 위한 일반 텍스트 명령은 다음과 같습니다. 030000000000000000000000000000000
암호화된 버전은 39E1CBB7EFC7127DE387EDF4A0075D66 입니다
5. 잠금해제
예를 들어 키는 57616C6B697A3532383332694C6F636B 입니다.
예를 들어 잠금 해제 비밀번호는 313130303634 입니다.
예를 들어 토큰은 AB568E21 입니다.
잠금을 해제하는 일반 텍스트 명령은 다음과 같습니다.
200031313030363400000000AB568E21
암호화된버전은 70E8CDAD64B0E3061FA5ACB22EE52AA0 입니다
public static void main(String[] args) throws Exception {
System.out.println("Hello, World!");
byte[] key = { 0x57,0x61,0x6C,0x6B,0x69,0x7A,0x35,0x32,0x38,0x33,0x32,0x69,0x4C,0x6F,0x63,0x6B };
byte[] src = { 0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
System.out.println(" ===> " + bytesToHex(Encrypt(src, key)));
}
public static byte[] Encrypt(byte[] sSrc, byte[] sKey){
try{
SecretKeySpec skeySpec = new SecretKeySpec(sKey, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc);
return encrypted;
}catch(Exception ex){
return null;
}
}
public static byte[] Decrypt(byte[] sSrc, byte[] sKey){
try{
SecretKeySpec skeySpec = new SecretKeySpec(sKey, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] dncrypted = cipher.doFinal(sSrc);
return dncrypted;
}catch(Exception ex){
return null;
}
}
public static String bytesToHex(byte[] bytes) {
char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
|
<template>
<div>
<h1>课程列表</h1>
<el-form :inline="true" :model="courseQuery" class="demo-form-inline">
<el-form-item label="课程标题">
<el-input v-model="courseQuery.courseTitle" placeholder="标题"></el-input>
</el-form-item>
<el-form-item label="总课时">
<el-input v-model="courseQuery.lessonNum" placeholder="课时"></el-input>
</el-form-item>
<el-form-item label="价格区间">
<el-col :span="11">
<el-input v-model="courseQuery.priceBegin" placeholder="价格"></el-input>
</el-col>
<el-col class="line" :span="2">---</el-col>
<el-col :span="11">
<el-input v-model="courseQuery.priceEnd" placeholder="价格"></el-input>
</el-col>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="query">查询</el-button>
</el-form-item>
<el-form-item>
<el-button type="warn" @click="clearData">清空</el-button>
</el-form-item>
</el-form>
<el-table :data="list" style="width: 100%">
<el-table-column label="课程封面" width="500">
<template slot-scope="scope">
<img :src="scope.row.cover"/>
</template>
</el-table-column>
<el-table-column prop="title" label="课程标题" width="100"></el-table-column>
<el-table-column prop="status" label="课程状态" width="100"></el-table-column>
<el-table-column label="总课时数" width="100" prop="lessonNum"></el-table-column>
<el-table-column prop="price" label="课程价格" width="120"></el-table-column>
<el-table-column label="操作" width="400" align="center">
<template slot-scope="scope">
<router-link :to="'/course/info/' + scope.row.id">
<el-button type="primary" size="mini" icon="el-icon-edit">修改课程基本信息</el-button>
</router-link>
<router-link :to="'/course/chapter/' + scope.row.id">
<el-button type="primary" size="mini" icon="el-icon-edit">修改课程大纲</el-button>
</router-link>
<el-button
type="danger"
size="mini"
icon="el-icon-delete"
@click="removeDataById(scope.row.id)"
>
下架
</el-button>
</template>
</el-table-column>
</el-table>
<el-pagination
:current-page="current"
:page-size="size"
:total="total"
style="padding: 30px 0; text-align: center"
layout="total, prev, pager, next, jumper"
@current-change="getCourseListPage"
/>
</div>
</template>
<script>
import courseMethod from '@/api/edu/course.js'
export default {
name: 'list',
data() {
return {
courseQuery: {
courseTitle: '',
lessonNum: '',
priceBegin: '',
priceEnd: '',
status: '',
cover: ''
},
current: 1,
size: 2,
total: 0,
list: []
}
},
created() {
this.getCourseListPage()
},
methods: {
clearData() {
this.courseQuery = {}
this.getCourseListPage()
},
query() {
this.getCourseListPage(this.current, this.courseQuery)
},
getCourseListPage(current = 1, courseQuery = {}) {
this.current = current
this.courseQuery = courseQuery
courseMethod.getPageCourses(this.current, this.size, this.courseQuery).then(response => {
this.total = response.data.total
this.list = response.data.rows
console.log(this.list)
})
},
removeDataById(courseId) {
this.$confirm('此操作将永久删除该课程, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
courseMethod.deleteCourseById(courseId).then(response => {
this.$message.success('删除成功!')
this.getCourseListPage(this.current, this.courseQuery)
})
})
.catch(() => {
this.$message({
type: 'info',
message: '已取消删除'
})
})
}
}
}
</script>
<style scoped>
.el-table .warning-row {
background: oldlace;
}
.el-table .success-row {
background: #f0f9eb;
}
</style>
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package university.prof_courses;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javax.swing.JOptionPane;
import university.AccessLayer.DAO;
import static university.AccessLayer.DAODepartment.checkProfessorIDExistence;
import static university.AccessLayer.DAOEnrollment.checkCourseExistence;
import university.AccessLayer.DAOProf_course;
import static university.AccessLayer.DAOProf_course.checkProfCourseExistence;
import university.models.DTOProf_course;
public class Prof_courseController implements Initializable{
@FXML
private TextField profIdfield;
@FXML
private TextField courseIdField;
@FXML
private Button assignCourseBttn;
@FXML
private Label dataAlert;
@FXML
void handleAssignCourse(ActionEvent event) {
String profIdText = profIdfield.getText();
String courseIdText = courseIdField.getText();
if (profIdText.isEmpty() || courseIdText.isEmpty()) {
// Handle the case where professor ID or course ID is empty
dataAlert.setText("Professor ID and Course ID cannot be empty");
return;
}
try {
int professorID = Integer.parseInt(profIdText);
int courseID = Integer.parseInt(courseIdText);
// Check if IDs are valid
if (professorID <= 0 || courseID <= 0) {
dataAlert.setText("Please enter valid Professor ID and Course ID.");
return;
}
// Check if professor ID exists
if (!checkProfessorIDExistence(professorID)) {
String e = "<html><body style='font-family: Arial; font-size: 12px;'>Invalid Professor ID</body></html>";
JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// Check if course ID exists
if (!checkCourseExistence(courseID)) {
String e = "<html><body style='font-family: Arial; font-size: 12px;'>Invalid Course ID</body></html>";
JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// Check if the professor-course combination already exists
if (checkProfCourseExistence(professorID, courseID)) {
String e = "<html><body style='font-family: Arial; font-size: 12px;'>This Professor-Course combination already exists</body></html>";
JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// Create DTOProf_course instance
DTOProf_course profCourse = new DTOProf_course(professorID, courseID);
// Create a background task for the database operation
Task<Integer> task = new Task<Integer>() {
@Override
protected Integer call() throws Exception {
DAOProf_course daoProf_course = new DAOProf_course();
return daoProf_course.assignProfCourse(profCourse);
}
};
// Set up event handlers for task completion
task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent event) {
int result = task.getValue();
if (result > 0) {
System.out.println("Course assigned to professor successfully!!");
JOptionPane.showMessageDialog(null, "Course assigned to professor successfully!!", "Error", JOptionPane.ERROR_MESSAGE);
// Clear all text fields
clearTextFields();
} else {
System.out.println("Course is not assigned to professor successfully!!");
}
}
});
task.setOnFailed(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent event) {
// Handle task failure (e.g., display an alert)
String e = "<html><body style='font-family: Arial; font-size: 12px;'>An error occurred while assigning the course to the professor. Please try again.</body></html>";
JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
}
});
// Start the background task
new Thread(task).start();
} catch (NumberFormatException e) {
// Handle the case where the input is not a valid integer
dataAlert.setText("Invalid Professor ID or Course ID. Please enter valid integers.");
}
}
// Helper method to clear all text fields
private void clearTextFields() {
profIdfield.clear();
courseIdField.clear();
dataAlert.setText("");
}
@Override
public void initialize(URL location, ResourceBundle resources) {
DAO dao = new DAO();
}
}
|
<?php
$archivo = file('preguntas.csv');
$Errors = [];
function showErrors($Errors)
{
if (count($Errors) > 0) {
foreach ($Errors as $error) {
echo "<p class='error'>$error</p>";
}
}
}
function isValid($data)
{
return (isset($data) && $data != "") ? true : false;
}
$name = $_POST['name'] ?? '';
$respuestas = $_POST['respuestas'] ?? [];
if ($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['enviar'])) {
if (!isValid($name)) {
$Errors[] = "El campo nombre es obligatorio";
}
if (empty($Errors)) {
$respuestas_csv = strtolower($name) . ';' . implode(';', $respuestas) . PHP_EOL;
file_put_contents('respuestas.csv', $respuestas_csv, FILE_APPEND);
header('Location: exito.php');
exit();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Leer csv</title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<h1>Encuesta CSV</h1>
<?php
showErrors($Errors);
?>
<form action="index.php" method="post">
<div>
<label for="pregunta">nombre: </label>
<input type="text" name="name" id="name" value="<?= $name ?? '' ?>">
</div>
<?php foreach ($archivo as $key => $pregunta) : ?>
<div>
<?= "<p>$pregunta</p>" ?>
<label for="">nada</label>
<input type="radio" value="<?= $key; ?>-0" name="respuestas[<?= $key; ?>]" <?= (isset($_POST['respuestas']) && in_array(" $key-0", $_POST['respuestas']))? 'checked' : '' ?>>
<label for="">normal</label>
<input type="radio" value="<?= $key; ?>-1" name="respuestas[<?= $key; ?>]" <?= (isset($_POST['respuestas']) && in_array(" $key-1", $_POST['respuestas']))? 'checked' : '' ?>>
<label for="">mucho</label>
<input type="radio" value="<?= $key; ?>-2" name="respuestas[<?= $key; ?>]" <?= (isset($_POST['respuestas']) && in_array(" $key-2", $_POST['respuestas']))? 'checked' : '' ?>>
</div>
<?php endforeach; ?>
<button type="submit" name="enviar">Enviar</button>
</form>
</body>
</html>
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Internal;
using Serilog;
using Zip.Api.CustomerSummary.Api.Attributes;
using Zip.Api.CustomerSummary.Application.VcnCards.Command.BlockCard;
using Zip.Api.CustomerSummary.Application.VcnCards.Command.BlockDigitalWalletToken;
using Zip.Api.CustomerSummary.Application.VcnCards.Command.CloseCard;
using Zip.Api.CustomerSummary.Application.VcnCards.Command.TerminateDigitalWalletToken;
using Zip.Api.CustomerSummary.Application.VcnCards.Command.UnblockCard;
using Zip.Api.CustomerSummary.Application.VcnCards.Command.UnblockDigitalWalletToken;
using Zip.Api.CustomerSummary.Application.VcnCards.Command.VerifyDigitalWalletToken;
using Zip.Api.CustomerSummary.Application.VcnCards.Query.GetCard;
using Zip.Api.CustomerSummary.Application.VcnCards.Query.GetCards;
using Zip.Api.CustomerSummary.Application.VcnCards.Query.GetCardTransactions;
using Zip.Api.CustomerSummary.Domain.Entities.ApiErrors;
using Zip.Api.CustomerSummary.Domain.Entities.Identity;
using Zip.Api.CustomerSummary.Domain.Entities.VcnCard;
namespace Zip.Api.CustomerSummary.Api.Controllers
{
[Route("api/cards")]
[ApiController]
[ApiVersion("1.0")]
[AuthorizeRole(AppRole.Admin, AppRole.CSPAdmin, AppRole.CSPDefault)]
public class CardsController : ControllerBase
{
private readonly IMediator _mediator;
public CardsController(IMediator mediator)
{
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
}
[HttpGet()]
[ProducesResponseType(typeof(Card), StatusCodes.Status200OK)]
public async Task<IActionResult> GetAsync([FromQuery] GetCardQuery request)
{
try
{
var result = await _mediator.Send(request);
if (result == null)
{
return NoContent();
}
return Ok(result);
}
catch (Exception ex)
{
Log.Error(ex,
"{controller} :: {action} : {message}",
nameof(CardsController),
nameof(GetAsync),
ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError, new InternalServerError(ex.Message));
}
}
[HttpGet("{cardId}/transactions")]
[ProducesResponseType(typeof(List<CardTransaction>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetCardTransactionsAsync([FromQuery] GetCardTransactionsQuery request)
{
try
{
var result = await _mediator.Send(request);
if (result == null || !result.Any())
{
return NoContent();
}
return Ok(result);
}
catch (Exception ex)
{
Log.Error(ex,
"{controller} :: {action} : {message}",
nameof(CardsController),
nameof(GetCardTransactionsAsync),
ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError, new InternalServerError(ex.Message));
}
}
[HttpGet("customer/{customerId}")]
[ProducesResponseType(typeof(RootCards), StatusCodes.Status200OK)]
public async Task<IActionResult> GetCardsAsync([FromQuery] GetCardsQuery request)
{
try
{
var result = await _mediator.Send(request);
if (result == null)
{
return NoContent();
}
return Ok(result);
}
catch (Exception ex)
{
Log.Error(ex,
"{controller} :: {action} : {message}",
nameof(CardsController),
nameof(GetCardsAsync),
ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError, new InternalServerError(ex.Message));
}
}
[HttpPut("{cardId}/block")]
public async Task<IActionResult> BlockCardAsync([FromQuery] BlockCardCommand request)
{
try
{
await _mediator.Send(request);
return Ok();
}
catch (Exception ex)
{
Log.Error(ex,
"{controller} :: {action} : {message}",
nameof(CardsController),
nameof(BlockCardAsync),
ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError, new InternalServerError(ex.Message));
}
}
[HttpPut("{cardId}/unblock")]
public async Task<IActionResult> UnblockCardAsync([FromQuery] UnblockCardCommand request)
{
try
{
await _mediator.Send(request);
return Ok();
}
catch (Exception ex)
{
Log.Error(ex,
"{controller} :: {action} : {message}",
nameof(CardsController),
nameof(UnblockCardAsync),
ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError, new InternalServerError(ex.Message));
}
}
[HttpPut("{cardId}/close")]
[AuthorizeRole(AppRole.Admin, AppRole.CSPAdmin)]
public async Task<IActionResult> CloseCardAsync([FromQuery] CloseCardCommand request)
{
try
{
await _mediator.Send(request);
return Ok();
}
catch (Exception ex)
{
Log.Error(ex,
"{controller} :: {action} : {message}",
nameof(CardsController),
nameof(CloseCardAsync),
ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError, new InternalServerError(ex.Message));
}
}
[HttpPost("digitalwallettokens/{digitalWalletToken}/block")]
public async Task<IActionResult> BlockDigitalWalletTokenAsync([FromQuery] BlockDigitalWalletTokenCommand request)
{
try
{
await _mediator.Send(request);
return Ok();
}
catch (Exception ex)
{
Log.Error(ex,
"{controller} :: {action} : {message}",
nameof(CardsController),
nameof(BlockDigitalWalletTokenAsync),
ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError, new InternalServerError(ex.Message));
}
}
[HttpPost("digitalwallettokens/{digitalWalletToken}/unblock")]
public async Task<IActionResult> UnblockDigitalWalletTokenAsync([FromQuery] UnblockDigitalWalletTokenCommand request)
{
try
{
await _mediator.Send(request);
return Ok();
}
catch (Exception ex)
{
Log.Error(ex,
"{controller} :: {action} : {message}",
nameof(CardsController),
nameof(UnblockDigitalWalletTokenAsync),
ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError, new InternalServerError(ex.Message));
}
}
[HttpPost("digitalwallettokens/{digitalWalletToken}/terminate")]
[AuthorizeRole(AppRole.Admin, AppRole.CSPAdmin)]
public async Task<IActionResult> TerminateDigitalWalletTokenAsync([FromQuery] TerminateDigitalWalletTokenCommand request)
{
try
{
await _mediator.Send(request);
return Ok();
}
catch (Exception ex)
{
Log.Error(ex,
"{controller} :: {action} : {message}",
nameof(CardsController),
nameof(TerminateDigitalWalletTokenAsync),
ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError, new InternalServerError(ex.Message));
}
}
[HttpPost("digitalwallettokens/{digitalWalletToken}/verify")]
public async Task<IActionResult> VerifyDigitalWalletTokenAsync([FromQuery] VerifyDigitalWalletTokenCommand request)
{
try
{
await _mediator.Send(request);
return Ok();
}
catch (Exception ex)
{
Log.Error(ex,
"{controller} :: {action} : {message}",
nameof(CardsController),
nameof(TerminateDigitalWalletTokenAsync),
ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError, new InternalServerError(ex.Message));
}
}
}
}
|
package fastcampus.Java369.part3.Step06_TopologicalSort;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class baekjoon2252 {
static int N, M;
static ArrayList<Integer>[] graph;
static int[] indeg;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
graph = new ArrayList[N + 1];
indeg = new int[N + 1];
for (int i = 1; i <= N; i++) graph[i] = new ArrayList<>();
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine(), " ");
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
graph[x].add(y);
indeg[y]++;
}
bfs2252();
System.out.println(sb);
}
private static void bfs2252() {
Queue<Integer> queue = new LinkedList<>();
for (int i = 1; i <= N; i++) {
if (indeg[i] == 0) queue.add(i);
}
while (!queue.isEmpty()) {
int cur = queue.poll();
sb.append(cur).append(" ");
for (int y : graph[cur]) {
indeg[y]--;
if (indeg[y] == 0) queue.add(y);
}
}
}
}
|
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const mongoose = require('mongoose');
const homeRouter = require('./routes/home');
const authRouter = require('./routes/auth');
const formRouter = require('./routes/form')
const app = express();
mongoose.connect(
`${process.env.DB_PREFIX}${process.env.DB_USERNAME}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}/${process.env.DB_NAME}`,
{ useNewUrlParser: true, useUnifiedTopology: true, retryWrites: false },
(e) => {
if (e) {
throw e;
}
console.log('Connected to database!');
}
);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', homeRouter);
app.use('/auth', authRouter);
app.use('/form', formRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
|
import propTypes from "prop-types";
import "./styles.css";
import { useNavigate } from "react-router-dom";
export default function Logo({
showTitle = false,
url = "https://cdn.iconscout.com/icon/free/png-512/free-swiggy-1613371-1369418.png?f=webp&w=512",
alt = "Logo Swiggy",
title = "Swiggy",
}) {
const navigate = useNavigate();
function handleLogoClick() {
navigate("/");
}
return (
<div className="logo" onClick={handleLogoClick}>
<div>
<img className="image" src={url} alt={alt} />
</div>
{showTitle && (
<div>
<h4>{title}</h4>
</div>
)}
</div>
);
}
Logo.propTypes = {
url: propTypes.string,
alt: propTypes.string,
title: propTypes.string,
showTitle: propTypes.bool,
};
|
import {
FormControl,
OutlinedInput,
FormHelperText,
InputLabel,
InputAdornment,
IconButton,
} from '@mui/material';
import Visibility from '@mui/icons-material/Visibility';
import VisibilityOff from '@mui/icons-material/VisibilityOff';
import RefreshIcon from '@mui/icons-material/Refresh';
import styles from './Input.module.css';
export interface InputProps {
type?: any;
field: { name: string; onChange?: any; value: any; onBlur: any };
disabled?: any;
editor?: any;
label: string;
form?: { touched: any; errors: any };
placeholder: any;
rows?: number;
helperText?: any;
emojiPicker?: any;
textArea?: boolean;
togglePassword?: boolean;
endAdornmentCallback?: any;
validate?: any;
endAdornment?: any;
inputProp?: any;
translation?: string;
onChange?: any;
}
export const Input = ({ textArea = false, disabled = false, ...props }: InputProps) => {
const {
field,
form,
helperText,
type,
togglePassword,
endAdornmentCallback,
emojiPicker,
placeholder,
editor,
rows,
endAdornment,
inputProp,
translation,
onChange,
} = props;
let fieldType = type;
let fieldEndAdorment = null;
if (type === 'password') {
// we should change the type to text if user has clicked on show password
if (togglePassword) {
fieldType = 'text';
}
fieldEndAdorment = (
<InputAdornment position="end">
<IconButton
aria-label="toggle password visibility"
data-testid="passwordToggle"
onClick={endAdornmentCallback}
edge="end"
>
{togglePassword ? (
<Visibility classes={{ root: styles.Visibility }} />
) : (
<VisibilityOff classes={{ root: styles.Visibility }} />
)}
</IconButton>
</InputAdornment>
);
} else if (emojiPicker) {
fieldEndAdorment = emojiPicker;
} else if (type === 'otp') {
fieldType = 'text';
fieldEndAdorment = (
<InputAdornment position="end">
<IconButton
aria-label="resend otp"
data-testid="resendOtp"
onClick={endAdornmentCallback}
edge="end"
>
<p className={styles.Resend}>resend</p>{' '}
<RefreshIcon classes={{ root: styles.ResendButton }} />
</IconButton>
</InputAdornment>
);
}
let showError = false;
if (form && form.errors[field.name] && form.touched[field.name]) {
showError = true;
}
return (
<>
{translation && <div className={styles.Translation}>{translation}</div>}
<div className={styles.Input} data-testid="input">
<FormControl fullWidth error={showError}>
<InputLabel variant="outlined" className={styles.Label} data-testid="inputLabel">
{placeholder}
</InputLabel>
<OutlinedInput
data-testid="outlinedInput"
inputComponent={editor ? editor.inputComponent : undefined}
inputProps={editor ? editor.inputProps : inputProp}
type={fieldType}
classes={{ multiline: styles.Multiline }}
disabled={disabled}
error={showError}
multiline={textArea}
rows={rows}
className={styles.OutlineInput}
label={placeholder}
fullWidth
{...field}
onChange={(e) => {
if (onChange) {
onChange(e.target.value);
}
if (field.onChange) {
field.onChange(e);
}
}}
endAdornment={endAdornment || fieldEndAdorment}
/>
{form && form.errors[field.name] && form.touched[field.name] ? (
<FormHelperText className={styles.DangerText}>{form.errors[field.name]}</FormHelperText>
) : null}
{helperText && (
<div id="helper-text" className={styles.HelperText}>
{helperText}
</div>
)}
</FormControl>
</div>
</>
);
};
|
import { Box, CardContent, CardMedia, Typography } from "@mui/material"
import { Link } from "react-router-dom"
import { demoProfilePicture } from "../utils/constants"
const ChannelCard = ({ channelDetail }) => (
<Box
sx={{
boxShadow:'none',
borderRadius: 20,
display: 'flex',
justifyContent:'center',
alignItems:'center',
width: {xs: '356px', md:'320px'},
height:'326px',
margin:'auto'
}}
>
<Link to={`/channel/${channelDetail?.id?.channelId}`}>
<CardContent sx={{ display: "flex", flexDirection: 'column', justifyContent: 'center', textAlign: 'center', color: 'white' }}>
<CardMedia
image={channelDetail?.snippet?.thumbnails?.high?.url || demoProfilePicture}
alt={channelDetail?.snippet?.title}
sx={{ borderRadius: '50%', height: '180px', width: '180px', mb: 2 }}
/>
<Typography variant="h6">
{channelDetail?.snippet?.title}
</Typography>
{/* Setting subscriber count if any */}
{channelDetail?.statistics?.subscriberCount && (
<Typography variant='subtitle1'>
Subscribers: {parseInt(channelDetail?.statistics?.subscriberCount).toLocaleString()}
</Typography>
)}
</CardContent>
</Link>
</Box>
)
export default ChannelCard
|
//
// TrialChecker.swift
// vpncore - Created on 26.06.19.
//
// Copyright (c) 2019 Proton Technologies AG
//
// This file is part of vpncore.
//
// vpncore 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.
//
// vpncore 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 vpncore. If not, see <https://www.gnu.org/licenses/>.
#if canImport(UIKit)
import UIKit
#elseif canImport(Cocoa)
import Cocoa
#endif
public protocol TrialCheckerFactory {
func makeTrialChecker() -> TrialChecker
}
public class TrialChecker {
public static let trialExpired = Notification.Name("ProfileStorageTrialExpired")
#if os(iOS)
public typealias Factory = PropertiesManagerFactory & VpnGatewayFactory & CoreAlertServiceFactory & VpnKeychainFactory & TrialServiceFactory & StoreKitStateCheckerFactory
#else // No IAP in mac app
public typealias Factory = PropertiesManagerFactory & VpnGatewayFactory & CoreAlertServiceFactory & VpnKeychainFactory & TrialServiceFactory
#endif
private let factory: Factory
private lazy var propertiesManager: PropertiesManagerProtocol = factory.makePropertiesManager()
private lazy var vpnGateway: VpnGatewayProtocol = factory.makeVpnGateway()
private lazy var alertService: CoreAlertService = factory.makeCoreAlertService()
private lazy var trialService: TrialService = factory.makeTrialService()
private lazy var vpnKeychain: VpnKeychainProtocol = factory.makeVpnKeychain()
#if os(iOS)
private lazy var storeKitStateChecker: StoreKitStateChecker = factory.makeStoreKitStateChecker()
#endif
private var trialEndTimer: Timer?
private var credentials: VpnCredentials?
public init(factory: Factory) {
self.factory = factory
NotificationCenter.default.addObserver(self, selector: #selector(vpnCredentialsChanged), name: VpnKeychain.vpnCredentialsChanged, object: nil)
vpnCredentialsChanged()
}
deinit {
endTrialEndTimer()
NotificationCenter.default.removeObserver(self)
}
@objc public func vpnCredentialsChanged() {
do {
endTrialEndTimer()
#if os(iOS)
// User started buying a plan, no need for a trial popup
guard !storeKitStateChecker.isBuyProcessRunning() else {
return
}
#endif
let credentials = try vpnKeychain.fetch()
self.credentials = credentials
if !credentials.isDelinquent {
if credentials.accountPlan == .trial {
let expiration = credentials.expirationTime
if expiration.timeIntervalSince1970 < 0.1 && !propertiesManager.trialWelcomed {
trialService.presentTrialWelcomeViewController(expiration: expiration)
propertiesManager.trialWelcomed = true
} else if expiration > Date() && expiration < Date(timeInterval: 60 * 60 * 24 * 2, since: Date()) && // trial has less than 2 days remaining
!propertiesManager.warnedTrialExpiring {
trialService.presentTrialWelcomeViewController(expiration: expiration)
propertiesManager.warnedTrialExpiring = true
}
startTrialEndTimer(credentials: credentials)
} else if propertiesManager.lastUserAccountPlan == .trial && credentials.accountPlan == .free {
if !propertiesManager.warnedTrialExpired {
trialService.presentTrialExpiredViewController()
propertiesManager.warnedTrialExpired = true
}
if propertiesManager.secureCoreToggle {
disableSecureCore()
}
}
}
propertiesManager.lastUserAccountPlan = credentials.accountPlan
} catch {}
}
private func disableSecureCore() {
vpnGateway.disconnect()
vpnGateway.changeActiveServerType(.standard)
}
/// Disconnect from VPN when trial ends
private func startTrialEndTimer(credentials: VpnCredentials) {
let expiration = credentials.expirationTime
guard expiration.timeIntervalSinceNow > 0 else { return }
endTrialEndTimer()
#if canImport(UIKit)
NotificationCenter.default.addObserver(self, selector: #selector(checkTrialEnded), name: UIApplication.didBecomeActiveNotification, object: nil)
#elseif canImport(Cocoa)
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(checkTrialEnded), name: NSWorkspace.didWakeNotification, object: nil)
#endif
trialEndTimer = Timer(fire: expiration, interval: 0, repeats: false, block: { [checkTrialEnded] timer in
checkTrialEnded()
})
RunLoop.main.add(trialEndTimer!, forMode: .common)
}
private func endTrialEndTimer() {
#if canImport(UIKit)
NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
#elseif canImport(Cocoa)
NSWorkspace.shared.notificationCenter.removeObserver(self, name: NSWorkspace.didWakeNotification, object: nil)
#endif
trialEndTimer?.invalidate()
trialEndTimer = nil
}
@objc private func checkTrialEnded() {
guard let expiration = credentials?.expirationTime,
expiration.timeIntervalSinceNow <= 0 else { return }
vpnGateway.disconnect()
NotificationCenter.default.post(name: TrialChecker.trialExpired, object: nil)
}
}
|
---
title: "\"2024 Approved Essential Insights Into Using Color Grading LUTs with PSCC\""
date: 2024-06-27T10:35:14.206Z
updated: 2024-06-28T10:35:14.206Z
tags:
- screen-recording
- ai video
- ai audio
- ai auto
categories:
- ai
- screen
description: "\"This Article Describes 2024 Approved: Essential Insights Into Using Color Grading LUTs with PSCC\""
excerpt: "\"This Article Describes 2024 Approved: Essential Insights Into Using Color Grading LUTs with PSCC\""
keywords: "Color Grading Basics,LUT Usage Tips,PSCC Techniques,Improve Poster Color,Editing Film Grade,Cinematography Tools,VFX Color Mastery"
thumbnail: https://thmb.techidaily.com/c72f65d6cf6eccfb8dd0cd66944cb2172744b7375f3b2c967f4222ce690bc4fc.jpg
---
## Essential Insights Into Using Color Grading LUTs with PSCC
##### Create High-Quality Video - Wondershare Filmora
An easy and powerful YouTube video editor
Numerous video and audio effects to choose from
Detailed tutorials provided by the official channel
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
With over two billion people posting videos and photos online, it is challenging to make your content stand out. However, some creators seem to always excel with their top-in-class creations. So, how do they do it?
Their success results from the effective use of editing programs and other enhancements to ensure their work is above the rest. For example, Adobe Photoshop CC allows you to effectively apply LUTs to your creations. Below is a complete guide on how to use luts photoshop to get you in the elite leagues.
#### In this article
01 [How to Use LUTs in Photoshop](#part1)
02 [Free LUTs to enhance your image in Photoshop CC.](#part2)
03 [Looking for LUTs for Video? Try Filmora.](#part3)
## How to Use LUTs in Photoshop
A Look Up Table (LUT) refers to a preset value of color calibrations you use in post-production. Some of the reasons for using LUTs include:
* Shorten your color grading time.
* Provide a base to develop your unique style.
* Quickly add color effects to your fast-turnaround videos.
You can use Adobe Photoshop CC to apply LUTs to your creation with ease. Additionally, it comes with preset LUTs to help you achieve a variety of color outcomes. For example, there are plenty of LUTs to give your image an artistic look, as if it was a painting. Additionally, you can use the program on both Windows and Mac devices, including handheld macOS devices.
With the basics out of the way, here is how to use LUTs in Photoshop:
#### 1\. Load your image to the workspace
You can load your photos directly from the program or launch them from your device. The most recent versions of the program store your media on the cloud.
#### 2\. Open the Color Lookup tool
The Color Lookup tool allows you to apply preset and custom LUTs to your image. Below is how to access it.
* Proceed to the Adjustments Panel and click Color Lookup from the dropdown menu. You will find this as the next option after Libraries, on the right side of your workspace. Most editions of Adobe Photoshop CC use a grid icon to represent Color Lookup.
* Alternatively, you may access Color Lookup from the Layers panel. Navigate to the bottom-right corner of your workspace and click the half-shaded icon. Then, select the Color Lookup option from the menu.
#### 3\. Loading your LUT in Photoshop CC
Once the Color Lookup tool is active, select the option Load 3D LUT to activate the dropdown menu. All your LUT presets will appear on the list, each with a different effect. You can also use custom LUTs in Photoshop CC. Here is how you access them.
* Click the Load 3D LUT entry from the dropdown menu. The program will open the File Explorer window that allows you to navigate directories on your device.
* Navigate to the directory that contains your custom luts photoshop, and select the one you need.
* Finally, click on Ok on the File Explorer window to complete the process.
* Make adjustments to your LUT in Photoshop CC.
Preset and custom LUTs may not give you the finish you anticipate. As such, you may need to make adjustments. Some of the adjustments you can make include:
* Color blending.
* Luminosity.
* Opacity.
* Saturation.
* Hues.
On the right side of your workspace is the Layers panel. It includes all the tools you need to edit your LUT. Remember, you need an Adjustment Layer to make changes to your LUTs. Additionally, you can save and export your custom LUTs for use across other video editing programs like Filmora.
## Free LUTs to enhance your image in Photoshop CC
You now have an understanding of how to use LUTs Photoshop to enhance your photos and films. However, the presets LUTs that come pre-installed are often basic and leave a lot to desire. So, what do you do to make your creations better?
Most creators resort to increasing their LUT library from external sources. You can also increase your collection by adding free LUTs from these sources. Furthermore, you will get a sample of what to expect from each LUT collection.
#### 1\. Fix the Photo
Fix the Photo is an online professional photo editing company that has been operating since 2003\. Despite offering a range of premium services, they also offer freebies for you to use in your DIY projects. Additionally, they give you samples of what you can achieve with each free LUT pack to help you in deciding what works best.

You can download this free Classical Monochrome LUT pack to give your photos a soft and gentle finish. The LUT pack is ideal for wedding photos, fashion, and lifestyle photos.
#### 2\. PH Learn
PH Learn is an online learning resource for aspiring photographers and filmmakers. It offers tutorials for the Adobe Creative Cloud Suite, along with free samples you can use to practice.

Here is a free LUT photoshop pack for you to use. It features a variety of creative LUTs ideal for portraits and nature photography.
#### 3\. Free Presets
Free Presets is another valuable LUT photoshop resource you must check out. It offers a variety of LUTs compatible with all your favorite editing programs including Photoshop CC. You can start with this color grading LUT collection to practice.

#### 4\. Envato Elements
The site is full of LUTs you can use across a variety of creative programs. However, you need to pay a subscription to get full access. Regardless, you may find one of their time-limited freebies if you keep checking.

#### 5\. Giggster.com
Giggster.com is an online resource for aspiring filmmakers and photographers. You can find helpful guides and video tutorials on applying different finishes to your work, including color grading and effects.

Here is a free LUT photoshop pack you can use for your color grading projects. As you can see, the pack contains LUTs to transform your images into grayscale, adding a vintage yet crisp finish.
## Looking for LUTs for Video? Try Filmora
Filmora is an easy-to-use video editing program available for both macOS and Windows. It offers you an interactive interface with preset LUTs you can apply to achieve exceptional finishes for each project. Some of the adjustments you can perform with the program include color grading, monitor calibration, and color transfer across different software.
Here is how to use LUTs in Filmora.
#### 1\. Download Filmora
Check the Filmora website to download your compatible version. Then, proceed with the installation to start using the video editing program.
#### 2\. Upload your video
Select the video you want to edit and drop it on the FIlmora timeline. Ensure you click the video so that it is active for editing.
#### 3\. Apply your LUT
Select Tools from the top menu in your workspace. Then, click on Color Correction from the dropdown menu. This opens the LUT importer, where you will click on Load new LUT to choose from a variety of presets and custom LUTs from your device. Once you find the LUT you need, press OK to apply the LUT.
Here are a few things to consider before using LUTs on Filmora.
* You may need to color correct your video before applying any LUTs. For example, your white balance needs to be on point to achieve the best results.
* Videos vary in quality depending on the equipment you use. Therefore, you may not receive the same results from applying the same LUT.
* You will need a subscription to access all of Filmora’s editing tools.
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
For Win 7 or later (64-bit)
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
For macOS 10.12 or later
## Conclusion
**●** Regardless of the editing software you use, LUTs are essential to give your creations the extra boost they need to stand out. The LUT photoshop guide above is sufficient to help you unleash your creativity. Additionally, the free LUT resources give you the freedom to express your artform across different software. So, what are you waiting for? Put what you have read into practice and watch people craving more of your work. /p
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
With over two billion people posting videos and photos online, it is challenging to make your content stand out. However, some creators seem to always excel with their top-in-class creations. So, how do they do it?
Their success results from the effective use of editing programs and other enhancements to ensure their work is above the rest. For example, Adobe Photoshop CC allows you to effectively apply LUTs to your creations. Below is a complete guide on how to use luts photoshop to get you in the elite leagues.
#### In this article
01 [How to Use LUTs in Photoshop](#part1)
02 [Free LUTs to enhance your image in Photoshop CC.](#part2)
03 [Looking for LUTs for Video? Try Filmora.](#part3)
## How to Use LUTs in Photoshop
A Look Up Table (LUT) refers to a preset value of color calibrations you use in post-production. Some of the reasons for using LUTs include:
* Shorten your color grading time.
* Provide a base to develop your unique style.
* Quickly add color effects to your fast-turnaround videos.
You can use Adobe Photoshop CC to apply LUTs to your creation with ease. Additionally, it comes with preset LUTs to help you achieve a variety of color outcomes. For example, there are plenty of LUTs to give your image an artistic look, as if it was a painting. Additionally, you can use the program on both Windows and Mac devices, including handheld macOS devices.
With the basics out of the way, here is how to use LUTs in Photoshop:
#### 1\. Load your image to the workspace
You can load your photos directly from the program or launch them from your device. The most recent versions of the program store your media on the cloud.
#### 2\. Open the Color Lookup tool
The Color Lookup tool allows you to apply preset and custom LUTs to your image. Below is how to access it.
* Proceed to the Adjustments Panel and click Color Lookup from the dropdown menu. You will find this as the next option after Libraries, on the right side of your workspace. Most editions of Adobe Photoshop CC use a grid icon to represent Color Lookup.
* Alternatively, you may access Color Lookup from the Layers panel. Navigate to the bottom-right corner of your workspace and click the half-shaded icon. Then, select the Color Lookup option from the menu.
#### 3\. Loading your LUT in Photoshop CC
Once the Color Lookup tool is active, select the option Load 3D LUT to activate the dropdown menu. All your LUT presets will appear on the list, each with a different effect. You can also use custom LUTs in Photoshop CC. Here is how you access them.
* Click the Load 3D LUT entry from the dropdown menu. The program will open the File Explorer window that allows you to navigate directories on your device.
* Navigate to the directory that contains your custom luts photoshop, and select the one you need.
* Finally, click on Ok on the File Explorer window to complete the process.
* Make adjustments to your LUT in Photoshop CC.
Preset and custom LUTs may not give you the finish you anticipate. As such, you may need to make adjustments. Some of the adjustments you can make include:
* Color blending.
* Luminosity.
* Opacity.
* Saturation.
* Hues.
On the right side of your workspace is the Layers panel. It includes all the tools you need to edit your LUT. Remember, you need an Adjustment Layer to make changes to your LUTs. Additionally, you can save and export your custom LUTs for use across other video editing programs like Filmora.
## Free LUTs to enhance your image in Photoshop CC
You now have an understanding of how to use LUTs Photoshop to enhance your photos and films. However, the presets LUTs that come pre-installed are often basic and leave a lot to desire. So, what do you do to make your creations better?
Most creators resort to increasing their LUT library from external sources. You can also increase your collection by adding free LUTs from these sources. Furthermore, you will get a sample of what to expect from each LUT collection.
#### 1\. Fix the Photo
Fix the Photo is an online professional photo editing company that has been operating since 2003\. Despite offering a range of premium services, they also offer freebies for you to use in your DIY projects. Additionally, they give you samples of what you can achieve with each free LUT pack to help you in deciding what works best.

You can download this free Classical Monochrome LUT pack to give your photos a soft and gentle finish. The LUT pack is ideal for wedding photos, fashion, and lifestyle photos.
#### 2\. PH Learn
PH Learn is an online learning resource for aspiring photographers and filmmakers. It offers tutorials for the Adobe Creative Cloud Suite, along with free samples you can use to practice.

Here is a free LUT photoshop pack for you to use. It features a variety of creative LUTs ideal for portraits and nature photography.
#### 3\. Free Presets
Free Presets is another valuable LUT photoshop resource you must check out. It offers a variety of LUTs compatible with all your favorite editing programs including Photoshop CC. You can start with this color grading LUT collection to practice.

#### 4\. Envato Elements
The site is full of LUTs you can use across a variety of creative programs. However, you need to pay a subscription to get full access. Regardless, you may find one of their time-limited freebies if you keep checking.

#### 5\. Giggster.com
Giggster.com is an online resource for aspiring filmmakers and photographers. You can find helpful guides and video tutorials on applying different finishes to your work, including color grading and effects.

Here is a free LUT photoshop pack you can use for your color grading projects. As you can see, the pack contains LUTs to transform your images into grayscale, adding a vintage yet crisp finish.
## Looking for LUTs for Video? Try Filmora
Filmora is an easy-to-use video editing program available for both macOS and Windows. It offers you an interactive interface with preset LUTs you can apply to achieve exceptional finishes for each project. Some of the adjustments you can perform with the program include color grading, monitor calibration, and color transfer across different software.
Here is how to use LUTs in Filmora.
#### 1\. Download Filmora
Check the Filmora website to download your compatible version. Then, proceed with the installation to start using the video editing program.
#### 2\. Upload your video
Select the video you want to edit and drop it on the FIlmora timeline. Ensure you click the video so that it is active for editing.
#### 3\. Apply your LUT
Select Tools from the top menu in your workspace. Then, click on Color Correction from the dropdown menu. This opens the LUT importer, where you will click on Load new LUT to choose from a variety of presets and custom LUTs from your device. Once you find the LUT you need, press OK to apply the LUT.
Here are a few things to consider before using LUTs on Filmora.
* You may need to color correct your video before applying any LUTs. For example, your white balance needs to be on point to achieve the best results.
* Videos vary in quality depending on the equipment you use. Therefore, you may not receive the same results from applying the same LUT.
* You will need a subscription to access all of Filmora’s editing tools.
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
For Win 7 or later (64-bit)
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
For macOS 10.12 or later
## Conclusion
**●** Regardless of the editing software you use, LUTs are essential to give your creations the extra boost they need to stand out. The LUT photoshop guide above is sufficient to help you unleash your creativity. Additionally, the free LUT resources give you the freedom to express your artform across different software. So, what are you waiting for? Put what you have read into practice and watch people craving more of your work. /p
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
With over two billion people posting videos and photos online, it is challenging to make your content stand out. However, some creators seem to always excel with their top-in-class creations. So, how do they do it?
Their success results from the effective use of editing programs and other enhancements to ensure their work is above the rest. For example, Adobe Photoshop CC allows you to effectively apply LUTs to your creations. Below is a complete guide on how to use luts photoshop to get you in the elite leagues.
#### In this article
01 [How to Use LUTs in Photoshop](#part1)
02 [Free LUTs to enhance your image in Photoshop CC.](#part2)
03 [Looking for LUTs for Video? Try Filmora.](#part3)
## How to Use LUTs in Photoshop
A Look Up Table (LUT) refers to a preset value of color calibrations you use in post-production. Some of the reasons for using LUTs include:
* Shorten your color grading time.
* Provide a base to develop your unique style.
* Quickly add color effects to your fast-turnaround videos.
You can use Adobe Photoshop CC to apply LUTs to your creation with ease. Additionally, it comes with preset LUTs to help you achieve a variety of color outcomes. For example, there are plenty of LUTs to give your image an artistic look, as if it was a painting. Additionally, you can use the program on both Windows and Mac devices, including handheld macOS devices.
With the basics out of the way, here is how to use LUTs in Photoshop:
#### 1\. Load your image to the workspace
You can load your photos directly from the program or launch them from your device. The most recent versions of the program store your media on the cloud.
#### 2\. Open the Color Lookup tool
The Color Lookup tool allows you to apply preset and custom LUTs to your image. Below is how to access it.
* Proceed to the Adjustments Panel and click Color Lookup from the dropdown menu. You will find this as the next option after Libraries, on the right side of your workspace. Most editions of Adobe Photoshop CC use a grid icon to represent Color Lookup.
* Alternatively, you may access Color Lookup from the Layers panel. Navigate to the bottom-right corner of your workspace and click the half-shaded icon. Then, select the Color Lookup option from the menu.
#### 3\. Loading your LUT in Photoshop CC
Once the Color Lookup tool is active, select the option Load 3D LUT to activate the dropdown menu. All your LUT presets will appear on the list, each with a different effect. You can also use custom LUTs in Photoshop CC. Here is how you access them.
* Click the Load 3D LUT entry from the dropdown menu. The program will open the File Explorer window that allows you to navigate directories on your device.
* Navigate to the directory that contains your custom luts photoshop, and select the one you need.
* Finally, click on Ok on the File Explorer window to complete the process.
* Make adjustments to your LUT in Photoshop CC.
Preset and custom LUTs may not give you the finish you anticipate. As such, you may need to make adjustments. Some of the adjustments you can make include:
* Color blending.
* Luminosity.
* Opacity.
* Saturation.
* Hues.
On the right side of your workspace is the Layers panel. It includes all the tools you need to edit your LUT. Remember, you need an Adjustment Layer to make changes to your LUTs. Additionally, you can save and export your custom LUTs for use across other video editing programs like Filmora.
## Free LUTs to enhance your image in Photoshop CC
You now have an understanding of how to use LUTs Photoshop to enhance your photos and films. However, the presets LUTs that come pre-installed are often basic and leave a lot to desire. So, what do you do to make your creations better?
Most creators resort to increasing their LUT library from external sources. You can also increase your collection by adding free LUTs from these sources. Furthermore, you will get a sample of what to expect from each LUT collection.
#### 1\. Fix the Photo
Fix the Photo is an online professional photo editing company that has been operating since 2003\. Despite offering a range of premium services, they also offer freebies for you to use in your DIY projects. Additionally, they give you samples of what you can achieve with each free LUT pack to help you in deciding what works best.

You can download this free Classical Monochrome LUT pack to give your photos a soft and gentle finish. The LUT pack is ideal for wedding photos, fashion, and lifestyle photos.
#### 2\. PH Learn
PH Learn is an online learning resource for aspiring photographers and filmmakers. It offers tutorials for the Adobe Creative Cloud Suite, along with free samples you can use to practice.

Here is a free LUT photoshop pack for you to use. It features a variety of creative LUTs ideal for portraits and nature photography.
#### 3\. Free Presets
Free Presets is another valuable LUT photoshop resource you must check out. It offers a variety of LUTs compatible with all your favorite editing programs including Photoshop CC. You can start with this color grading LUT collection to practice.

#### 4\. Envato Elements
The site is full of LUTs you can use across a variety of creative programs. However, you need to pay a subscription to get full access. Regardless, you may find one of their time-limited freebies if you keep checking.

#### 5\. Giggster.com
Giggster.com is an online resource for aspiring filmmakers and photographers. You can find helpful guides and video tutorials on applying different finishes to your work, including color grading and effects.

Here is a free LUT photoshop pack you can use for your color grading projects. As you can see, the pack contains LUTs to transform your images into grayscale, adding a vintage yet crisp finish.
## Looking for LUTs for Video? Try Filmora
Filmora is an easy-to-use video editing program available for both macOS and Windows. It offers you an interactive interface with preset LUTs you can apply to achieve exceptional finishes for each project. Some of the adjustments you can perform with the program include color grading, monitor calibration, and color transfer across different software.
Here is how to use LUTs in Filmora.
#### 1\. Download Filmora
Check the Filmora website to download your compatible version. Then, proceed with the installation to start using the video editing program.
#### 2\. Upload your video
Select the video you want to edit and drop it on the FIlmora timeline. Ensure you click the video so that it is active for editing.
#### 3\. Apply your LUT
Select Tools from the top menu in your workspace. Then, click on Color Correction from the dropdown menu. This opens the LUT importer, where you will click on Load new LUT to choose from a variety of presets and custom LUTs from your device. Once you find the LUT you need, press OK to apply the LUT.
Here are a few things to consider before using LUTs on Filmora.
* You may need to color correct your video before applying any LUTs. For example, your white balance needs to be on point to achieve the best results.
* Videos vary in quality depending on the equipment you use. Therefore, you may not receive the same results from applying the same LUT.
* You will need a subscription to access all of Filmora’s editing tools.
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
For Win 7 or later (64-bit)
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
For macOS 10.12 or later
## Conclusion
**●** Regardless of the editing software you use, LUTs are essential to give your creations the extra boost they need to stand out. The LUT photoshop guide above is sufficient to help you unleash your creativity. Additionally, the free LUT resources give you the freedom to express your artform across different software. So, what are you waiting for? Put what you have read into practice and watch people craving more of your work. /p
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
With over two billion people posting videos and photos online, it is challenging to make your content stand out. However, some creators seem to always excel with their top-in-class creations. So, how do they do it?
Their success results from the effective use of editing programs and other enhancements to ensure their work is above the rest. For example, Adobe Photoshop CC allows you to effectively apply LUTs to your creations. Below is a complete guide on how to use luts photoshop to get you in the elite leagues.
#### In this article
01 [How to Use LUTs in Photoshop](#part1)
02 [Free LUTs to enhance your image in Photoshop CC.](#part2)
03 [Looking for LUTs for Video? Try Filmora.](#part3)
## How to Use LUTs in Photoshop
A Look Up Table (LUT) refers to a preset value of color calibrations you use in post-production. Some of the reasons for using LUTs include:
* Shorten your color grading time.
* Provide a base to develop your unique style.
* Quickly add color effects to your fast-turnaround videos.
You can use Adobe Photoshop CC to apply LUTs to your creation with ease. Additionally, it comes with preset LUTs to help you achieve a variety of color outcomes. For example, there are plenty of LUTs to give your image an artistic look, as if it was a painting. Additionally, you can use the program on both Windows and Mac devices, including handheld macOS devices.
With the basics out of the way, here is how to use LUTs in Photoshop:
#### 1\. Load your image to the workspace
You can load your photos directly from the program or launch them from your device. The most recent versions of the program store your media on the cloud.
#### 2\. Open the Color Lookup tool
The Color Lookup tool allows you to apply preset and custom LUTs to your image. Below is how to access it.
* Proceed to the Adjustments Panel and click Color Lookup from the dropdown menu. You will find this as the next option after Libraries, on the right side of your workspace. Most editions of Adobe Photoshop CC use a grid icon to represent Color Lookup.
* Alternatively, you may access Color Lookup from the Layers panel. Navigate to the bottom-right corner of your workspace and click the half-shaded icon. Then, select the Color Lookup option from the menu.
#### 3\. Loading your LUT in Photoshop CC
Once the Color Lookup tool is active, select the option Load 3D LUT to activate the dropdown menu. All your LUT presets will appear on the list, each with a different effect. You can also use custom LUTs in Photoshop CC. Here is how you access them.
* Click the Load 3D LUT entry from the dropdown menu. The program will open the File Explorer window that allows you to navigate directories on your device.
* Navigate to the directory that contains your custom luts photoshop, and select the one you need.
* Finally, click on Ok on the File Explorer window to complete the process.
* Make adjustments to your LUT in Photoshop CC.
Preset and custom LUTs may not give you the finish you anticipate. As such, you may need to make adjustments. Some of the adjustments you can make include:
* Color blending.
* Luminosity.
* Opacity.
* Saturation.
* Hues.
On the right side of your workspace is the Layers panel. It includes all the tools you need to edit your LUT. Remember, you need an Adjustment Layer to make changes to your LUTs. Additionally, you can save and export your custom LUTs for use across other video editing programs like Filmora.
## Free LUTs to enhance your image in Photoshop CC
You now have an understanding of how to use LUTs Photoshop to enhance your photos and films. However, the presets LUTs that come pre-installed are often basic and leave a lot to desire. So, what do you do to make your creations better?
Most creators resort to increasing their LUT library from external sources. You can also increase your collection by adding free LUTs from these sources. Furthermore, you will get a sample of what to expect from each LUT collection.
#### 1\. Fix the Photo
Fix the Photo is an online professional photo editing company that has been operating since 2003\. Despite offering a range of premium services, they also offer freebies for you to use in your DIY projects. Additionally, they give you samples of what you can achieve with each free LUT pack to help you in deciding what works best.

You can download this free Classical Monochrome LUT pack to give your photos a soft and gentle finish. The LUT pack is ideal for wedding photos, fashion, and lifestyle photos.
#### 2\. PH Learn
PH Learn is an online learning resource for aspiring photographers and filmmakers. It offers tutorials for the Adobe Creative Cloud Suite, along with free samples you can use to practice.

Here is a free LUT photoshop pack for you to use. It features a variety of creative LUTs ideal for portraits and nature photography.
#### 3\. Free Presets
Free Presets is another valuable LUT photoshop resource you must check out. It offers a variety of LUTs compatible with all your favorite editing programs including Photoshop CC. You can start with this color grading LUT collection to practice.

#### 4\. Envato Elements
The site is full of LUTs you can use across a variety of creative programs. However, you need to pay a subscription to get full access. Regardless, you may find one of their time-limited freebies if you keep checking.

#### 5\. Giggster.com
Giggster.com is an online resource for aspiring filmmakers and photographers. You can find helpful guides and video tutorials on applying different finishes to your work, including color grading and effects.

Here is a free LUT photoshop pack you can use for your color grading projects. As you can see, the pack contains LUTs to transform your images into grayscale, adding a vintage yet crisp finish.
## Looking for LUTs for Video? Try Filmora
Filmora is an easy-to-use video editing program available for both macOS and Windows. It offers you an interactive interface with preset LUTs you can apply to achieve exceptional finishes for each project. Some of the adjustments you can perform with the program include color grading, monitor calibration, and color transfer across different software.
Here is how to use LUTs in Filmora.
#### 1\. Download Filmora
Check the Filmora website to download your compatible version. Then, proceed with the installation to start using the video editing program.
#### 2\. Upload your video
Select the video you want to edit and drop it on the FIlmora timeline. Ensure you click the video so that it is active for editing.
#### 3\. Apply your LUT
Select Tools from the top menu in your workspace. Then, click on Color Correction from the dropdown menu. This opens the LUT importer, where you will click on Load new LUT to choose from a variety of presets and custom LUTs from your device. Once you find the LUT you need, press OK to apply the LUT.
Here are a few things to consider before using LUTs on Filmora.
* You may need to color correct your video before applying any LUTs. For example, your white balance needs to be on point to achieve the best results.
* Videos vary in quality depending on the equipment you use. Therefore, you may not receive the same results from applying the same LUT.
* You will need a subscription to access all of Filmora’s editing tools.
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
For Win 7 or later (64-bit)
[Try It Free](https://tools.techidaily.com/wondershare/filmora/download/)
For macOS 10.12 or later
## Conclusion
**●** Regardless of the editing software you use, LUTs are essential to give your creations the extra boost they need to stand out. The LUT photoshop guide above is sufficient to help you unleash your creativity. Additionally, the free LUT resources give you the freedom to express your artform across different software. So, what are you waiting for? Put what you have read into practice and watch people craving more of your work. /p
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="8358498916"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<span class="atpl-alsoreadstyle">Also read:</span>
<div><ul>
<li><a href="https://article-tips.techidaily.com/hdr-on-your-desk-a-windows-guide-to-color-mastery/"><u>HDR on Your Desk A Windows Guide to Color Mastery</u></a></li>
<li><a href="https://article-tips.techidaily.com/new-vanguard-visual-transformers-lenscrafters-art-for-2024/"><u>[New] Vanguard Visual Transformers LensCrafters' Art for 2024</u></a></li>
<li><a href="https://article-tips.techidaily.com/2024-approved-inshot-cut-mastery-creating-fluid-movements/"><u>2024 Approved Inshot Cut Mastery Creating Fluid Movements</u></a></li>
<li><a href="https://article-tips.techidaily.com/2024-approved-apk-gaming-revolution-welcome-funimate-pro-android-edition/"><u>2024 Approved APK Gaming Revolution Welcome Funimate Pro Android Edition</u></a></li>
<li><a href="https://article-tips.techidaily.com/updated-in-2024-wit-whisperer-visual-snap/"><u>[Updated] In 2024, Wit Whisperer Visual Snap</u></a></li>
<li><a href="https://article-tips.techidaily.com/2024-approved-broadcasting-hidden-voices-on-instagram-live/"><u>2024 Approved Broadcasting Hidden Voices on Instagram Live</u></a></li>
<li><a href="https://article-tips.techidaily.com/new-2024-approved-mastering-metaverse-life-your-ultimate-device-list/"><u>[New] 2024 Approved Mastering Metaverse Life Your Ultimate Device List</u></a></li>
<li><a href="https://article-tips.techidaily.com/updated-best-8-sbt-to-srtr-conversion-tools-pcmac-compatibility/"><u>[Updated] Best 8 SBT to SRTR Conversion Tools - PC/Mac Compatibility</u></a></li>
<li><a href="https://snapchat-videos.techidaily.com/new-2024-approved-twitter-elite-moments-live-on-snapchat/"><u>[New] 2024 Approved Twitter Elite Moments Live on Snapchat</u></a></li>
<li><a href="https://screen-capture.techidaily.com/updated-in-2024-efficient-techniques-to-record-and-store-facebook-calls/"><u>[Updated] In 2024, Efficient Techniques to Record and Store Facebook Calls</u></a></li>
<li><a href="https://smart-video-editing.techidaily.com/in-2024-transform-your-text-into-engaging-audio-files/"><u>In 2024, Transform Your Text Into Engaging Audio Files</u></a></li>
<li><a href="https://youtube-sure.techidaily.com/ed-in-2024-cutting-edge-youtube-end-card-tactics-and-layouts/"><u>[Updated] In 2024, Cutting Edge Youtube End Card Tactics & Layouts</u></a></li>
<li><a href="https://fake-location.techidaily.com/how-to-sharefake-gps-on-uber-for-itel-a05s-drfone-by-drfone-virtual-android/"><u>How to share/fake gps on Uber for Itel A05s | Dr.fone</u></a></li>
<li><a href="https://phone-solutions.techidaily.com/how-to-create-a-digital-signature-and-certificate-for-excel-2007-files-by-ldigisigner-sign-a-excel-sign-a-excel/"><u>How to create a digital signature and certificate for Excel 2007 files</u></a></li>
<li><a href="https://ai-vdieo-software.techidaily.com/the-ultimate-deal-final-cut-pro-at-a-fraction-of-the-cost-for-students/"><u>The Ultimate Deal Final Cut Pro at a Fraction of the Cost for Students</u></a></li>
<li><a href="https://ai-video-apps.techidaily.com/updated-in-2024-the-ultimate-list-of-lego-stop-motion-producers/"><u>Updated In 2024, The Ultimate List of Lego Stop Motion Producers</u></a></li>
<li><a href="https://activate-lock.techidaily.com/the-ultimate-guide-to-bypassing-icloud-activation-lock-from-apple-iphone-12-pro-by-drfone-ios/"><u>The Ultimate Guide to Bypassing iCloud Activation Lock from Apple iPhone 12 Pro</u></a></li>
</ul></div>
|
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { View, FlatList, StyleSheet, RefreshControl, SafeAreaView, TextInput, TouchableOpacity, Text, Vibration } from 'react-native';
import AreaRow from './partials/AreaRow';
import { colors, constant, sizes, sounds } from '../../themes/variables';
import Dialog from "react-native-dialog";
import Snackbar from "react-native-snackbar";
import createInstance from '../../../helpers/AxiosInstance';
import Spinner from 'react-native-loading-spinner-overlay';
import { useFocusEffect } from '@react-navigation/native';
import Notification from '../../components/Notification';
function ScanScreen({ navigation, route }) {
const [refreshing, setRefreshing] = useState(false);
const [listData, setListData] = useState([]);
const [modalVisible, setmodalVisible] = useState(false);
const [areaSelect, setAreaSelect] = useState({});
const [areaBarcode, setAreaBarcode] = useState('');
const [isLoading, setIsLoading] = useState(true);
const areaBarcodeRef = useRef(null);
const api = createInstance();
const onPressEvent = useCallback((area) => {
setAreaSelect(area)
setTimeout(() => areaBarcodeRef?.current?.focus(), constant.refDelay)
setmodalVisible(!modalVisible)
}, []);
const handlePressEnter = async () => {
// сверяем введный ШК с ШК из выбранной зоны
if (areaBarcode.trim() == areaSelect.barcode) {
sounds.beep.play()
setmodalVisible(!modalVisible)
navigation.navigate('ScanAreaStackRoute', { headerTitle: areaSelect.title, area: areaSelect, main: false })
return
}else{
setTimeout(() => areaBarcodeRef?.current?.focus(), constant.refDelay)
setTimeout( () => {
sounds.beep_fail.play()
Vibration.vibrate(constant.vibroTimeMedium)
Snackbar.show({ text: 'Введенный штрихкод не совпадает с выбраной зоной', textColor: colors.DANGER, backgroundColor: colors.LIGHT_DANGER, duration: Snackbar.LENGTH_SHORT });
}, constant.snackbarDelay)
}
};
const scanIndex = async (showSuccess = false) => {
api.get(`/scan/index/`)
.then(res => {
setListData(res.data)
setIsLoading(false)
if (showSuccess)
setTimeout(() => {
Snackbar.show({ text: 'Данные обновлены', textColor: colors.SUCCESS, backgroundColor: colors.LIGHT_SUCCESS, duration: Snackbar.LENGTH_SHORT });
}, constant.snackbarDelay)
})
.catch(e => {
setIsLoading(false)
setTimeout(() => {
Vibration.vibrate(constant.vibroTimeShort)
Snackbar.show({ text: e.message, textColor: colors.DANGER, backgroundColor: colors.LIGHT_DANGER, duration: Snackbar.LENGTH_SHORT })
}, constant.snackbarDelay)
})
}
useFocusEffect(
useCallback( () => {
//console.log('axios useFocusEffect scanIndex')
scanIndex()
}, [])
);
useEffect(() => {
//console.log('axios useEffect scanIndex')
scanIndex()
}, [])
const onRefresh = useCallback(() => {
setRefreshing(true)
scanIndex(true)
setRefreshing(false)
}, []);
return (
<SafeAreaView style={styles.wrapper}>
<Notification/>
<Spinner visible={isLoading} animation="fade" />
<FlatList
contentContainerStyle={styles.inner}
initialNumToRender={6}
removeClippedSubviews={true}
maxToRenderPerBatch={6}
windowSize={2}
data={listData}
keyExtractor={(item) => item.id}
renderItem={({ item }) => <AreaRow area={item} onPressEvent={onPressEvent} />}
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />}
/>
<View>
<Dialog.Container
headerStyle={styles.dialogHeader}
contentStyle={styles.dialogContent}
footerStyle={styles.dialogFooter}
visible={modalVisible}
onBackdropPress={() => setmodalVisible(!modalVisible)}
>
<Dialog.Title style={styles.dialogTitle}>{areaSelect.title}</Dialog.Title>
<View>
<TextInput
style={styles.dialogInput}
placeholder="Штрихкод зоны"
placeholderTextColor={colors.GRAY_500}
ref={areaBarcodeRef}
selectTextOnFocus={true}
autoCorrect={false}
onChangeText={setAreaBarcode}
onSubmitEditing={handlePressEnter}
/>
<TouchableOpacity
style={styles.dialogBtnFill}
activeOpacity={constant.activeOpacity}
accessibilityRole="button"
onPress={handlePressEnter}
>
<Text style={styles.dialogBtnFillText}>Войти</Text>
</TouchableOpacity>
</View>
<Dialog.Button label="Закрыть" style={styles.dialogClose} onPress={() => setmodalVisible(!modalVisible)} />
</Dialog.Container>
</View>
</SafeAreaView>
);
}
export const styles = StyleSheet.create({
wrapper: {
paddingVertical: sizes.padding,
backgroundColor: colors.BG,
height: '100%'
},
inner: {
paddingHorizontal: sizes.padding,
},
dialogHeader: { padding: 0, margin: 0 },
dialogContent: { borderRadius: sizes.radius, backgroundColor: colors.WHITE },
dialogFooter: { justifyContent: 'center' },
dialogTitle: { textAlign: 'center', fontSize: sizes.h4, fontWeight: '500', color: colors.GRAY_700, marginBottom: 15, },
dialogBtn: { fontSize: sizes.body3, color: colors.BLACK, textTransform: 'none' },
dialogBtnFill: { height: 50, width: '100%', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: colors.PRIMARY, borderRadius: sizes.radius, },
dialogBtnFillText: { color: colors.WHITE, fontSize: sizes.body3, fontWeight: '400' },
dialogClose: { fontSize: sizes.body4, color: colors.SECONDARY, textTransform: 'none' },
dialogInput: {
flexBasis: 55,
paddingHorizontal: 10,
width: '100%',
fontSize: sizes.body3,
backgroundColor: colors.WHITE,
color: colors.GRAY_700,
borderWidth: 1,
borderColor: colors.GRAY_300,
borderRadius: 7,
elevation: 3,
marginBottom: 12,
},
});
export default ScanScreen;
|
package Entity.Humans;
import Entity.Entity;
import Entity.Humans.Human;
import Graphic.Animation;
import Graphic.Assets;
import Item.Inventory;
import com.game.Handler;
import java.awt.*;
import java.awt.image.BufferedImage;
public class Player extends Human {
//Animation
private Animation animationDown,animationUp,animationLeft,animationRight;
private long lastAttackTimer, attackCooldown = 500, attackTimer = attackCooldown;
//IVNENTORY
private Inventory inventory;
public Player(Handler handler, float x, float y) {
super(handler,x, y,Human.DefaultWidth,Human.DefaultHeight);
bounds.x=25;
bounds.y=50;
bounds.width=50;
bounds.height=50;
animationDown=new Animation(500,Assets.playerDown);
animationUp=new Animation(500,Assets.playerUp);
animationLeft=new Animation(500,Assets.playerLeft);
animationRight=new Animation(500,Assets.playerRight);
inventory=new Inventory(handler);
}
public void tick() {
//Animations
animationDown.tick();
animationUp.tick();
animationRight.tick();
animationLeft.tick();
//Movement
getInput();
move();
handler.getGameCamera().centerOnEntity(this);
// Attack
checkAttacks();
inventory.tick();
}
private void checkAttacks(){
attackTimer += System.currentTimeMillis() - lastAttackTimer;
lastAttackTimer = System.currentTimeMillis();
if(attackTimer < attackCooldown)
return;
if(inventory.isActive()){
return;
}
Rectangle cb = getCollisionBounds(0, 0);
Rectangle ar = new Rectangle();
int arSize = 20;
ar.width = arSize;
ar.height = arSize;
if(handler.getKeyManager().aUp){
ar.x = cb.x + cb.width / 2 - arSize / 2;
ar.y = cb.y - arSize;
}else if(handler.getKeyManager().aDown){
ar.x = cb.x + cb.width / 2 - arSize / 2;
ar.y = cb.y + cb.height;
}else if(handler.getKeyManager().aLeft){
ar.x = cb.x - arSize;
ar.y = cb.y + cb.height / 2 - arSize / 2;
}else if(handler.getKeyManager().aRight){
ar.x = cb.x + cb.width;
ar.y = cb.y + cb.height / 2 - arSize / 2;
}else{
return;
}
attackTimer = 0;
for(Entity e : handler.getWorld().getEntityManager().getEntities()){
if(e.equals(this))
continue;
if(e.getCollisionBounds(0, 0).intersects(ar)){
e.hurt(1);
return;
}
}
}
public void die(){
System.out.println("You lose");
}
public void render(Graphics g) {
g.drawImage(getCurrentAnimationFrame(),(int)(x-handler.getGameCamera().getxOffset()),(int)(y-handler.getGameCamera().getyOffset()), width, height, null);
inventory.render(g);
//Visible hitbox
/*
g.setColor(Color.red);
g.fillRect((int) (x + bounds.x - handler.getGameCamera().getxOffset()),
(int) (y + bounds.y - handler.getGameCamera().getyOffset()),
bounds.width, bounds.height);
*/
}
public void postRender(Graphics g){
inventory.render(g);
}
private BufferedImage getCurrentAnimationFrame(){
if(xMove>0){
return animationLeft.getCurrentFrame();
}else if(xMove<0){
return animationRight.getCurrentFrame();
}else if(yMove<0){
return animationUp.getCurrentFrame();
}else{
return animationDown.getCurrentFrame();
}
}
//GETTERS && SETTERS
private void getInput(){
xMove = 0;
yMove = 0;
if(handler.getKeyManager().up)
yMove = -speed;
if(handler.getKeyManager().down)
yMove = speed;
if(handler.getKeyManager().left)
xMove = -speed;
if(handler.getKeyManager().right)
xMove = speed;
}
public Inventory getInventory() {
return inventory;
}
public void setInventory(Inventory inventory) {
this.inventory = inventory;
}
}
|
import express, { NextFunction, Request, Response } from "express";
import mongoose from "mongoose";
import Todo, { ITodo } from "../model/Todo.js";
import Controller from "../controller/index.js";
import { HttpStatusCode } from "../lib/index.js";
import { AuthenticatedRequest } from "../controller/userController.js";
import Folder from "../model/Folder.js";
const router = express.Router();
/**
* @route GET /all
* @description Fetch all todos
* @access Public
*/
router.get(
"/",
async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
console.log(req.user);
//@ts-ignore
const folder = await Folder.findByUserId(req.user.userId);
console.log(folder[0].todos);
const todos: ITodo[] = await Todo.findById(folder[0].todos);
res.status(HttpStatusCode.OK).json(todos);
} catch (error) {
next(error);
}
}
);
/**
* @route POST /create
* @description Create a new todo
* @access Public
*/
router.post(
"/create",
async (req: Request, res: Response, next: NextFunction) => {
try {
const { title, description, folderId } = req.body;
// Validate request body
if (!title || !description || !folderId) {
return res
.status(HttpStatusCode.BAD_REQUEST)
.json({ message: "Title, description, and folderId are required" });
}
// Call createTodo function to create a new todo
const todo: ITodo = await Controller.Todo.create(
title,
description,
folderId
);
res
.status(HttpStatusCode.CREATED)
.json({ message: "Todo created successfully", todo });
} catch (error) {
next(error);
}
}
);
/**
* @route DELETE /del/:todoID
* @description Delete a todo
* @access Public
*/
router.delete(
"/del/:todoID",
async (req: Request, res: Response, next: NextFunction) => {
const { todoID } = req.params;
// Validate the provided ID
if (!mongoose.Types.ObjectId.isValid(todoID)) {
return res
.status(HttpStatusCode.BAD_REQUEST)
.json({ error: true, message: "Invalid todo ID" });
}
try {
// Attempt to delete the todo
await Controller.Todo.delete(new mongoose.Types.ObjectId(todoID));
res
.status(HttpStatusCode.OK)
.json({ success: true, message: "Todo deleted successfully" });
} catch (error) {
next(error);
}
}
);
router.put(
"/update/:todoID",
async (req: Request, res: Response, next: NextFunction) => {
const { todoID } = req.params;
const updateData = req.body;
if (!mongoose.Types.ObjectId.isValid(todoID)) {
return res.status(HttpStatusCode.BAD_REQUEST).json({
error: true,
message: "Invalid todo ID",
});
}
try {
const updatedTodo = await Controller.Todo.update(
new mongoose.Types.ObjectId(todoID),
updateData
);
res.status(HttpStatusCode.OK).json({
success: true,
message: "Todo updated successfully",
data: updatedTodo,
});
} catch (error) {
next(error);
}
}
);
export default router;
|
# メモ
---
## VS Code の環境構築
[チュートリアル](https://learn.microsoft.com/ja-jp/aspnet/core/tutorials/first-web-api?view=aspnetcore-7.0&tabs=visual-studio-code)
### Solution を作る
`dotnet new sln`
### Solution にプロジェクトを追加する
`dotnet sln add <プロジェクトパス>`
---
## VS Code でAPIをテスト実行する
- `dotnet run --launch-profile https`
- 上記を実行後に、<https://localhost:portnumber/swagger>
---
## Swagger
Swagger is a popular tool for docmenting APIs and prividing a user friendly interface for testing and exploring the APIs.
---
## パッケージの追加
`dotnet add package [パッケージ名]`
- e.g. dotnet add package Microsoft.EntityFrameworkCore.SqlServer -v 7.0.0
---
## Microsoft.EntityFrameworkCore.Tools
This is the package that is responsible to run migrations, which will later on create a database for us.
---
## DbContext Class
- Maintaining Connection To Db
- Track Changes
- Perform CRUD operations
- Brige between domain models and the database
A Dbcontext class is a class that represents a session with a database and provides a set of APIs for performing database operations.
It also provides a way to define the database schema using entity classes or domain classes that we just built, which maps directly to database tables.
So we can say that the Dbcontext class is a bridge between your domain model classes and the database.
Controller <--> DbContext <--> Database
---
## Mac で Sqlserver は Docker にインストールする必要がある
- イメージのダウンロード
- `docker pull mcr.microsoft.com/azure-sql-edge`
- コンテナの起動
- `docker run --cap-add SYS_PTRACE -e 'ACCEPT_EULA=1' -e 'MSSQL_SA_PASSWORD=Password.1' -p 1433:1433 --name azuresqledge -d mcr.microsoft.com/azure-sql-edge`
---
## SqlServer の Docker-Compose を作成して、git にあげた
[github](https://github.com/hogendan/Docker-SqlServer)
---
## Run EF Core Migration
Package manager コンソールから以下を実行する
1. Add-Migration "Name Of Migration"
1. ex: Add-Migration "Initial Migration"
2. Update-Database
上記は VS Code ではできなかったので、以下のコマンドで実行する
[参考](https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli)
[参考(続き)](https://learn.microsoft.com/en-us/ef/core/cli/dotnet)
1. dotnet tool install --global dotnet-ef --version 7.0
2. dotnet tool update --global dotnet-ef --version 7.0
3. cd TMWalks/TMWalk.API
1. プロジェクトファイルがあるフォルダに移動する
4. dotnet ef migrations add "Initial Migration"
5. dotnet ef database update
1. ここで色々エラーが出て1つずつ潰していった
1. ConnectionString を以下のように変更して解決
1. "Server=localhost;Database=TMWalksDb;TrustServerCertificate=True;User ID=sa;Password=Password.1"
---
## Controller クラスの属性について
### ApiController
ApiController atribute will tell this application that this controller is for API use.
こういうの↓
``` c#
[ApiController]
public class RegionsController : ControllerBase
{
}
```
### Route
The Route attribute is basically defining the route whenever a user enters this route along with the application URL, it will be pointed to the region's controller.
例:<https://localhost:1234/api/regions>
``` c#
[Route("api/[controller]")]
public class RegionsController : ControllerBase
{
}
```
---
## DTOs
Data Transfer Objects
- Userd to transfer data between different layers
- Typically contain a subset of the properties in the domain model
- For example transferring data over a network
### DTOs vs Domain Models
Entityframework core domain models hava a mapping between the tables in the database and the domain models that are used internally in the application.
When you use entity framework to talk to a table, it gives us the domain model because the DbContext class only knows about the domain models, but because we have the domain models within the API, it is a good practice to add a layer of DTOs.
That is the data transfer objects and that is what we send back to the client.
So we never send the domain model back to the client, but we send the DTO instead.
### Advantages Of DTOs
- Separation of Concerns
- DTOs can be designed to match the business requirements.
- Performance
- Security
- Versioning
---
## Repository Pattern
- Desing pattern to separate the data access layer from the application
- Provides interface without exposing implementation
- Helps create abstraction
The Repository class is responsible for performing CRUD operations.
### Benefits
- Decoupling
- That is decoupling the data access layer from the rest of the application, which makes it easier to maintain and test the application.
- Consistency
- Providing a standard interface for accessing data which improves the consistency and readability of the code. Now every connection to the database goes through the repository.
- Performance
- Multiple data source (switchng)
- We can also improve the performance ot the application by using caching, batching or other optimization techniques supporting multiple data sources, which allows the application to switch between different data sources without affecting the application logic.
|
package com.emrekisa.roket.web.rest;
import com.codahale.metrics.annotation.Timed;
import com.emrekisa.roket.service.IlceService;
import com.emrekisa.roket.web.rest.errors.BadRequestAlertException;
import com.emrekisa.roket.web.rest.util.HeaderUtil;
import com.emrekisa.roket.web.rest.util.PaginationUtil;
import com.emrekisa.roket.service.dto.IlceDTO;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
/**
* REST controller for managing Ilce.
*/
@RestController
@RequestMapping("/api")
public class IlceResource {
private final Logger log = LoggerFactory.getLogger(IlceResource.class);
private static final String ENTITY_NAME = "ilce";
private final IlceService ilceService;
public IlceResource(IlceService ilceService) {
this.ilceService = ilceService;
}
/**
* POST /ilces : Create a new ilce.
*
* @param ilceDTO the ilceDTO to create
* @return the ResponseEntity with status 201 (Created) and with body the new ilceDTO, or with status 400 (Bad Request) if the ilce has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PostMapping("/ilces")
@Timed
public ResponseEntity<IlceDTO> createIlce(@Valid @RequestBody IlceDTO ilceDTO) throws URISyntaxException {
log.debug("REST request to save Ilce : {}", ilceDTO);
if (ilceDTO.getId() != null) {
throw new BadRequestAlertException("A new ilce cannot already have an ID", ENTITY_NAME, "idexists");
}
IlceDTO result = ilceService.save(ilceDTO);
return ResponseEntity.created(new URI("/api/ilces/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* PUT /ilces : Updates an existing ilce.
*
* @param ilceDTO the ilceDTO to update
* @return the ResponseEntity with status 200 (OK) and with body the updated ilceDTO,
* or with status 400 (Bad Request) if the ilceDTO is not valid,
* or with status 500 (Internal Server Error) if the ilceDTO couldn't be updated
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PutMapping("/ilces")
@Timed
public ResponseEntity<IlceDTO> updateIlce(@Valid @RequestBody IlceDTO ilceDTO) throws URISyntaxException {
log.debug("REST request to update Ilce : {}", ilceDTO);
if (ilceDTO.getId() == null) {
return createIlce(ilceDTO);
}
IlceDTO result = ilceService.save(ilceDTO);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, ilceDTO.getId().toString()))
.body(result);
}
/**
* GET /ilces : get all the ilces.
*
* @param pageable the pagination information
* @return the ResponseEntity with status 200 (OK) and the list of ilces in body
*/
@GetMapping("/ilces")
@Timed
public ResponseEntity<List<IlceDTO>> getAllIlces(Pageable pageable) {
log.debug("REST request to get a page of Ilces");
Page<IlceDTO> page = ilceService.findAll(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/ilces");
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
/**
* GET /ilces/:id : get the "id" ilce.
*
* @param id the id of the ilceDTO to retrieve
* @return the ResponseEntity with status 200 (OK) and with body the ilceDTO, or with status 404 (Not Found)
*/
@GetMapping("/ilces/{id}")
@Timed
public ResponseEntity<IlceDTO> getIlce(@PathVariable Long id) {
log.debug("REST request to get Ilce : {}", id);
IlceDTO ilceDTO = ilceService.findOne(id);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(ilceDTO));
}
/**
* DELETE /ilces/:id : delete the "id" ilce.
*
* @param id the id of the ilceDTO to delete
* @return the ResponseEntity with status 200 (OK)
*/
@DeleteMapping("/ilces/{id}")
@Timed
public ResponseEntity<Void> deleteIlce(@PathVariable Long id) {
log.debug("REST request to delete Ilce : {}", id);
ilceService.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
}
|
Ext.define('Admin.view.content.ArticleUpdatePanel', {
extend: 'Ext.panel.Panel',
xtype: 'main-panel-article',
// layout: 'border',
margin: 5,
requires: [
'Admin.view.content.ArticleUpdateController'
],
controller: 'main-panel-article',
layout: {
type: 'table',
columns: 5,
tableAttrs: {
style: {
width: '100%'
}
}
},
scrollable: true,
defaults: {
bodyPadding: '8 10',
border: false,
closable: false
},
viewModel: {
data: {
article: null
}
},
tbar: [
'->',
{
text: '关闭',
iconCls: 'x-fa fa-times',
name: 'content-btn-close',
action: 'close',
handler: 'onCloseBtnClicked'
},
{
xtype: 'button',
text: '取消',
hidden: true,
iconCls: 'x-fa fa-undo',
action: 'cancel'
},
{
xtype: 'button',
text: '保存',
hidden: true,
iconCls: 'x-fa fa-floppy-o',
action: 'save'
},
{
xtype: 'button',
text: '修改',
iconCls: 'x-fa fa-pencil-square-o',
action: 'update'
}
],
initComponent: function () {
var me = this,
vm = me.getViewModel();
var form = {
xtype: 'form',
scrollable: 'y',
// layout: 'form',
defaults: {
anchor: '100%',
labelAlign: 'right',
msgTarget: 'side'
},
items: [
{
xtype: 'fieldcontainer',
hidden: true,
itemId: 'submit-field',
defaults: {
labelWidth: 75,
labelAlign: 'left'
},
items: [
{
xtype: 'container',
layout: 'hbox',
defaultType: 'textfield',
margin: '0 0 5 0',
defaults: {
labelWidth: 75,
labelAlign: 'left',
margin: '0 10 0 0'
},
items: [
{
xtype: 'textfield',
name: 'title',
bind: '{article.title}',
fieldLabel: '<strong>文章标题</strong>',
width: '40%'
},
{
xtype: 'displayfield',
name: 'id',
fieldLabel: '<strong>文章ID</strong>',
bind: '{article.id}',
width: '20%'
},
{
xtype: 'fieldcontainer',
fieldLabel: '<strong>标签</strong>',
width: '40%',
layout: 'hbox',
publishes: 'value',
combineErrors: true,
defaultType: 'textfield',
// name: 'kId',
style: 'position: absolute;top: 10px;left: 49.5%;',
items: [
{
width: '100%',
xtype: 'tagfield',
name: 'kId',
bind: '{article.kId}',
store: {
proxy: {
type: 'ajax',
url: '/cn/article/getKeyWord',
reader: {
type: 'json',
rootProperty: 'rows'
}
},
autoLoad: true
},
displayField: 'name',
valueField: 'id',
queryMode: 'local', // 与autoLoad:true结合使用,避免手动输入标签时,下拉列表实时显示出来,影响操作
createNewOnEnter: true,
createNewOnBlur: true,
filterPickList: true,
allowBlank: false,
width: 350
}
]
}
]
},
{
xtype: 'container',
layout: 'hbox',
defaultType: 'textfield',
margin: '0 0 5 0',
defaults: {
labelWidth: 75,
labelAlign: 'left',
margin: '0 10 0 0'
},
items: [
{
xtype: 'displayfield',
name: 'url',
fieldLabel: '<strong>发布路径</strong>',
bind: '<a href="{article.url}" target="_blank">{article.url}</a>',
width: '40%'
},
{
xtype: 'textfield',
name: 'author',
fieldLabel: '<strong>作者</strong>',
bind: '{article.author}',
width: '20%'
},
{
xtype: 'displayfield',
name: 'creator',
fieldLabel: '<strong>录入人</strong>',
bind: '{article.creator}',
width: '40%'
}
]
},
{
xtype: 'textarea',
name: 'depict',
fieldLabel: '<strong>简介</strong>',
labelAlign: 'top',
bind: '{article.depict}',
width: '98%'
},
{
xtype: 'container',
layout: 'hbox',
defaultType: 'textfield',
margin: '0 0 5 0',
defaults: {
labelWidth: 75,
labelAlign: 'left',
margin: '0 30 0 0'
},
items: [
{
xtype: 'displayfield',
// fieldLabel: '<strong>状态</strong>',
// labelWidth: 35,
width: '20%',
bind: '{article.status}',
margin: '0 100 0 0',
listeners: {
afterrender: function (filed) {
var status = vm.get('article').get('status');
var value = '';
switch (status) {
case 0:
value = '<span style="color:#0066FF">初稿</span>';
break;
case 1:
value = '<span style="color: black">已签</span>';
break;
case 5:
value = '<span style="color:#FF6633">返工</span>';
break;
case 9:
value = '<span style="color:#7DB336">已发</span>';
break;
default:
value = '<span style="color:red">异常</span>';
break;
}
filed.setValue('<strong>状态:</strong>' + value);
}
}
},
{
xtype: 'displayfield',
fieldLabel: '<strong>创建于</strong>',
labelWidth: 45,
bind: '{article.createDate}'
},
{
xtype: 'displayfield',
fieldLabel: '<strong>最后更新于</strong>',
labelWidth: 75,
bind: '{article.updateDate}'
},
{
xtype: 'displayfield',
fieldLabel: '<strong>发布于</strong>',
labelWidth: 45,
bind: '{article.publishDate}'
},
{
xtype: 'fieldcontainer',
beforeLabelTextTpl: '',
fieldLabel: '连载',
labelWidth: 45,
layout: 'hbox',
combineErrors: true,
defaultType: 'textfield',
publishes: 'value',
/*style: {
"border": "1px solid red"
},*/
items: {
xtype: 'combobox',
name: 'sId',
bind: '{article.sId}',
/*style: {
"border": "1px solid blue",
"position": "absolute",
"left": "35px"
},*/
store: {
proxy: {
type: 'ajax',
url: '/cn/serial/serialQuery?status=5',
reader: {
type: 'json',
rootProperty: 'rows'
}
},
autoLoad: true
},
displayField: 'name',
valueField: 'id',
queryMode: 'remote',
editable: false, // 不可编辑
minChars: 1,
triggerAction: 'all',
// typeAhead: true, // 不启用组合编辑
forceSelection: true,
emptyText: '未连载',
// allowBlank: false, // 允许空白
// width: 100
}
},
]
},
{
xtype: 'kindEditorField',
name: 'content',
bind: '{article.content}',
width: '98%',
// height: 480,
// layout: 'fit',
border: false,
style: {
border: 'none'
},
listeners: {
render: function () {
setTimeout(function () { //有个加载次序的问题,需要延迟下 if(KindEditor){
me.kindEditor = KindEditor.create('textarea[name="' + me.name + '"]', {
// width: '95%',
// height: 480,
autoHeightMode: true,
allowPreviewEmoticons: false,
items: [
'fontname', 'fontsize', '|',
'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'removeformat', '|',
'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist', '|',
'table', 'emoticons', 'image', 'link', '|',
'quickformat', 'pagebreak', 'fullscreen'
],
allowFileUpload: false,
uploadJson: "/cn/admin/mediaCreate", // todo edit
fillDescAfterUploadImage: true,
formatUploadUrl: false,
extraFileUploadParams: {
type: 1,
rule: 0
},
afterCreate: function () {
this.loadPlugin('autoheight');
},
afterChange: function () {
me.value = this.html();
}
});
}, 100);
},
afterrender: function (filed, eOpts) {
KindEditor('#' + filed.id).hide();
filed.triggerWrap.dom.style.border = 'none';
}
}
}
]
},
{
xtype: 'fieldcontainer',
itemId: 'display-field',
items: [
{
xtype: 'container',
layout: 'hbox',
defaultType: 'textfield',
margin: '0 0 5 0',
defaults: {
labelWidth: 60,
labelAlign: 'left',
margin: '0 10 0 0'
},
items: [
{
xtype: 'displayfield',
bind: '{article.title}',
fieldLabel: '<strong>文章标题</strong>',
width: '40%'
},
{
xtype: 'displayfield',
fieldLabel: '<strong>文章ID</strong>',
bind: '{article.id}',
width: '20%'
},
{
xtype: 'displayfield',
itemId: 'cName',
fieldLabel: '<strong>标签</strong>',
width: '40%',
bind: '{article.cName}'
}
]
},
{
xtype: 'container',
layout: 'hbox',
defaultType: 'textfield',
margin: '0 0 5 0',
defaults: {
labelWidth: 60,
labelAlign: 'left',
margin: '0 10 0 0'
},
items: [
{
xtype: 'displayfield',
fieldLabel: '<strong>发布路径</strong>',
bind: '<a href="{article.url}" target="_blank">{article.url}</a>',
width: '40%'
},
{
xtype: 'displayfield',
fieldLabel: '<strong>作者</strong>',
bind: '{article.author}',
width: '20%'
},
{
xtype: 'displayfield',
fieldLabel: '<strong>录入人</strong>',
bind: '{article.creator}',
width: '40%'
}
]
},
{
xtype: 'displayfield',
fieldLabel: '<strong>简介</strong>',
labelAlign: 'top',
bind: '{article.depict}',
width: '97%'
},
{
xtype: 'container',
layout: 'hbox',
defaultType: 'textfield',
margin: '0 0 5 0',
defaults: {
labelWidth: 75,
labelAlign: 'left',
margin: '0 30 0 0'
},
items: [
{
xtype: 'displayfield',
// fieldLabel: '<strong>状态</strong>',
// labelWidth: 35,
width: '40%',
bind: '{article.status}',
// margin: '0 100 0 0',
listeners: {
afterrender: function (filed) {
var status = vm.get('article').get('status');
filed.setValue(status);
}
}
},
{
xtype: 'displayfield',
fieldLabel: '<strong>创建于</strong>',
labelWidth: 45,
bind: '{article.createDate}'
},
{
xtype: 'displayfield',
fieldLabel: '<strong>最后更新于</strong>',
labelWidth: 75,
bind: '{article.updateDate}'
},
{
xtype: 'displayfield',
fieldLabel: '<strong>发布于</strong>',
labelWidth: 45,
bind: '{article.publishDate}'
},
{
xtype: 'displayfield',
fieldLabel: '<strong>连载</strong>',
labelWidth: 45,
itemId: 'sName',
// labelWidth: 40,
listeners: {
afterrender: function (filed) {
var sId = vm.get('article').get('sId');
if (sId == 0) {
filed.setValue('未连载');
return false;
}
Ext.Ajax.request({
method: 'POST',
url: '/cn/serial/serialQueryForId?id=' + sId
}).then(function (response, opts) {
var obj = Ext.decode(response.responseText);
filed.setValue(obj.rows.name);
})
}
}
}
]
},
{
xtype: 'displayfield',
width: '98%',
style: {
'border-bottom': '1px solid #c2c2c2'
}
},
{
xtype: 'displayfield',
itemId: 'dis_content',
bind: '{article.content}',
width: '98%'
}
]
}
]
};
Ext.apply(me, {
layout: 'fit',
items: form,
listeners: {
beforeclose: function (tab, eOpts) {
// var grid = tab.up().down('content-mgrid');
// grid.getStore().reload();
// var ctrl = this;
// var view = ctrl.getView();
var id = location.hash;
if (id.indexOf('#') > -1) {
id = id.substring(1, id.length);
}
var grid = tab.up('contentPanel').getComponent('main-panel-' + id);
if (grid == null) {
grid = tab.up('contentPanel').getComponent('workbench').down('workbench-mgrid');
} else {
grid = grid.down('grid');
}
grid.getStore().reload();
grid.getSelectionModel().deselectAll();
}
}
});
me.callParent();
},
renderer: function (value, metaData, record, rowIndex, colIndex, store, view) {
var me = this,
headerCt = me.getHeaderContainer(),
column = headerCt.getHeaderAtIndex(colIndex),
dataIndex = column.dataIndex;
switch (dataIndex) {
case 'status':
switch (value) {
case 0:
metaData.tdStyle = 'color:#0066FF';
return '状态:初稿';
case 1:
metaData.tdStyle = 'color:blank';
return '状态:已签';
case 5:
metaData.tdStyle = 'color:#FF6633';
return '状态:返工';
case 9:
metaData.tdStyle = 'color:#7DB336';
return '状态:已发';
default:
metaData.tdStyle = 'color:red';
return value;
}
case 'hAId':
if (value == 0) {
return '<button class="x-fa fa-flag admin-label-button admin-color-purple" action="set-text-headline"></button>';
} else {
return '<button class="x-fa fa-flag admin-label-button admin-color-gray" action="cancel-text-headline"></button>';
}
case 'hPId':
if (value == 0) {
return '<button class="x-fa fa-picture-o admin-label-button admin-color-purple" action="set-picture-headline"></button>';
} else {
return '<button class="x-fa fa-picture-o admin-label-button admin-color-gray" action="cancel-picture-headline"></button>';
}
default:
return value;
}
}
});
|
import type { ReactNode } from "react";
import styles from "./container.module.scss";
type Props = {
children: ReactNode;
noPadding?: boolean;
fullWidth?: boolean;
className?: string;
};
export function Container({
children,
noPadding,
fullWidth,
className,
}: Props) {
return (
<div
className={[styles.container, className].join(" ")}
style={{
padding: noPadding ? 0 : undefined,
width: fullWidth ? "100%" : undefined,
}}
>
{children}
</div>
);
}
|
// Import React
import React, { useState } from "react";
// Import useMutation
import { useMutation } from "@apollo/client";
// Import LOGIN_USER from Mutations.js
import { LOGIN_USER } from "../utils/mutations";
// Import Auth
import Auth from "../utils/auth";
// Set up Login
const Login = () => {
// Set up login formState
const [formState, setFormState] = useState({ email: "", password: "" });
const [login, { error }] = useMutation(LOGIN_USER);
// Update state based on form input changes
const handleChange = (event) => {
const { name, value } = event.target;
setFormState({ ...formState, [name]: value });
};
// Submit Form
const handleFormSubmit = async (event) => {
event.preventDefault();
console.log({ ...formState });
try {
const { data } = await login({
variables: { ...formState },
});
Auth.login(data.login.token);
} catch (e) {
console.error(e);
}
// Clear form values
setFormState({
email: "",
password: "",
});
};
return (
<main className="flex-row justify-center mb-4">
<div className="col-12 col-md-6">
<div className="card">
<h4 className="card-header">Log In</h4>
<div className="card-body">
<form onSubmit={handleFormSubmit}>
{/* Set up form input */}
<input
className="form-input"
// Email
placeholder="Your email"
name="email"
type="email"
id="email"
value={formState.email}
onChange={handleChange}
required
/>
<input
className="form-input"
placeholder="******"
name="password"
type="password"
id="password"
value={formState.password}
onChange={handleChange}
required
/>
<button className=" btn-block btn-primary" type="submit">
Submit
</button>
</form>
{error && <div>Login failed!</div>}
</div>
</div>
</div>
</main>
);
};
// Export Login
export default Login;
|
**Objective**: Create an Express app for fetching paginated recipes using API responses.
**Routes**:
- **GET /recipes**: This route fetches all paginated recipes.
**Query Parameters**:
- `page` (optional): The page of the resource to be fetched. Defaults to 1.
- `limit` (optional): The number of items to be returned in a single page. Defaults to 3.
**Examples**:
1. **GET /recipes**:
- Description: A GET request to retrieve all recipes.
- Response:
```json
[
{ "id": 1, "name": "Crock Pot Roast" },
{ "id": 2, "name": "Roasted Asparagus" },
{ "id": 3, "name": "Curried Lentils and Rice" },
// Add more recipes as needed
]
```
2. **GET /recipes?page=1&limit=2**:
- Description: A GET request to retrieve the first page of recipes with a limit of 2 recipes per page.
- Response:
```json
[
{ "id": 1, "name": "Crock Pot Roast" },
{ "id": 2, "name": "Roasted Asparagus" }
]
```
3. **GET /recipes?page=2&limit=3**:
- Description: A GET request to retrieve the second page of recipes with a limit of 3 recipes per page.
- Response:
```json
[
{ "id": 4, "name": "Big Night Pizza" },
{ "id": 5, "name": "Cranberry and Apple Stuffed Acorn Squash Recipe" },
{ "id": 6, "name": "Mic's Yorkshire Puds" }
]
```
|
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import restaurantService from "./restaurantService";
const initialState = {
restaurants: [],
restaurantsById: [],
error: null,
loading: false,
restaurant: null
}
export const addRestaurant = createAsyncThunk('restaurants/add', async (formData, thunkAPI) => {
try {
return await restaurantService.createRestaurant(formData)
} catch(err) {
return thunkAPI.rejectWithValue(err.message)
}
})
export const getRestaurants = createAsyncThunk('/', async (_, thunkAPI) => {
try {
return await restaurantService.getAllRestaurants()
} catch(err) {
return thunkAPI.rejectWithValue(err.message)
}
})
export const getRestaurantsById = createAsyncThunk('/profile', async ({ids}, thunkAPI) => {
try {
return await restaurantService.getRestaurantsByIds(ids)
} catch(err) {
return thunkAPI.rejectWithValue(err.message)
}
})
export const getRestaurant = createAsyncThunk('/restaurants/fetchById', async ({collection, id}, thunkAPI) => {
try {
return await restaurantService.getRestaurant(collection, id)
} catch(err) {
return thunkAPI.rejectWithValue(err.message)
}
})
export const restaurantSlice = createSlice({
name: 'Restaurants',
initialState,
reducers: {},
extraReducers: (builder) => {
builder
.addCase(addRestaurant.pending, (state) => {
state.loading = true
})
.addCase(addRestaurant.fulfilled, (state, action) => {
state.loading = false
state.error = null;
state.restaurants = [...state.restaurants, action.payload]
})
.addCase(addRestaurant.rejected, (state, action) => {
state.loading = false
state.error = action.payload;
})
.addCase(getRestaurants.pending, (state) => {
state.loading = true
})
.addCase(getRestaurants.fulfilled, (state, action) => {
state.loading = false
state.error = null;
state.restaurants = action.payload
})
.addCase(getRestaurants.rejected, (state, action) => {
state.loading = false
state.error = action.payload;
})
.addCase(getRestaurant.pending, (state) => {
state.loading = true
})
.addCase(getRestaurant.fulfilled, (state, action) => {
state.loading = false
state.error = null;
state.restaurant = action.payload
})
.addCase(getRestaurant.rejected, (state, action) => {
state.loading = false
state.error = action.payload;
})
.addCase(getRestaurantsById.pending, (state) => {
state.loading = true
})
.addCase(getRestaurantsById.fulfilled, (state, action) => {
state.loading = false
state.error = null;
state.restaurantsById = action.payload
})
.addCase(getRestaurantsById.rejected, (state, action) => {
state.loading = false
state.error = action.payload;
})
}
})
export default restaurantSlice.reducer
|
package com.example.blog.service;
import com.example.blog.exceptions.ResourceNotFoundException;
import com.example.blog.model.Comment;
import com.example.blog.repository.CommentRepository;
import com.example.blog.util.ExceptionMessages;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CommentService {
@Autowired
private CommentRepository commentRepository;
public List<Comment> findAll() {
return commentRepository.findAll();
}
public Comment findById(Long id) {
return commentRepository.findById(id).orElseThrow(() ->
new ResourceNotFoundException(ExceptionMessages.COMMENT_NOT_FOUND_WITH_ID + id));
}
public Comment save(Comment comment) {
return commentRepository.save(comment);
}
public Comment update(Long id, Comment commentDetails) {
Comment existingComment = commentRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException(ExceptionMessages.COMMENT_NOT_FOUND_WITH_ID + id));
existingComment.setContent(commentDetails.getContent());
return commentRepository.save(existingComment);
}
public void deleteComment(Long id) {
Comment comment = commentRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException(ExceptionMessages.COMMENT_NOT_FOUND_WITH_ID + id));
commentRepository.delete(comment);
}
public List<Comment> findCommentsByPostId(Long postId) {
return commentRepository.findByPostId(postId);
}
}
|
using AutoMapper;
using Flight.Database;
using Flight.DTO;
using Flight.Entity;
using Flight.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
namespace Flight.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class FlightController : ControllerBase
{
private readonly IFlightService _flightService;
private readonly IMapper _mapper;
private readonly ILogger<FlightController> _logger;
public FlightController(IFlightService flightService, IMapper mapper, ILogger<FlightController> logger)
{
_flightService = flightService;
_mapper = mapper;
_logger = logger;
}
[HttpGet, Route("GetAllFlights")]
public IActionResult GetAllFlights()
{
try
{
List<flights> flights = _flightService.GetAllFlights();
List<FlightDTO> flightsDTO = _mapper.Map<List<FlightDTO>>(flights);
return StatusCode(200, flightsDTO);
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return StatusCode(500, ex.Message);
}
}
[HttpPost, Route("AddFlight")]
public IActionResult AddFlight(FlightDTO flightDTO)
{
try
{
flights flight = _mapper.Map<flights>(flightDTO);
_flightService.AddFlight(flight);
return StatusCode(200, flight);
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return StatusCode(500, ex.Message);
}
}
[HttpGet, Route("GetFlightById/{flightNumber}")]
public IActionResult GetFlightById(int flightNumber)
{
try
{
flights flight = _flightService.GetFlightById(flightNumber);
FlightDTO flightDTO = _mapper.Map<FlightDTO>(flight);
if (flight != null)
return StatusCode(200, flightDTO);
else
return StatusCode(404, new JsonResult("Invalid Flight Number"));
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return StatusCode(500, ex.Message);
}
}
[HttpPut, Route("UpdateFlight")]
public IActionResult UpdateFlight(FlightDTO flightDTO)
{
try
{
flights flight = _mapper.Map<flights>(flightDTO);
_flightService.UpdateFlight(flight);
return StatusCode(200, flight);
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return StatusCode(500, ex.Message);
}
}
[HttpDelete, Route("DeleteFlight/{flightNumber}")]
public IActionResult DeleteFlight(int flightNumber)
{
try
{
_flightService.DeleteFlight(flightNumber);
return StatusCode(200, new JsonResult($"Flight with Number {flightNumber} is Deleted"));
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return StatusCode(500, ex.Message);
}
}
[HttpGet, Route("GetFlightByName")]
public IActionResult GetFlightByName(string airline)
{
try
{
List<flights> flights = _flightService.GetFlightByName(airline);
List<FlightDTO> flightDTOs = _mapper.Map<List<FlightDTO>>(flights);
if (flights.Count > 0)
return StatusCode(200, flightDTOs);
else
return StatusCode(404, new JsonResult("No Flights found for the specified airline"));
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return StatusCode(500, ex.Message);
}
}
}
}
|
package application;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import db.DB;
public class Program {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = DB.getConnection();
statement = connection.createStatement();
// Selecionar tudo (*) de department
resultSet = statement.executeQuery("SELECT * FROM department");
// o resultSet começa no índice 0, que são os títulos
// após o primeiro next, está na posição 1
while (resultSet.next()) {
// para acessar as informações, usamos o resultSet.getAlgumaCoisa()
System.out.println(resultSet.getInt("Id") + ", " + resultSet.getString("Name"));
}
} catch(SQLException e) {
e.printStackTrace();
} finally { // É importante fechar depois de usar, pois são recursos externos e podem estourar a memória
// os closes foram criados como métodos estáticos da classe DB.java, para que não fiquem dentro do código
// do main e não tenham que ficar sendo tratados com try catch() a todo momento
DB.closeResultSet(resultSet);
DB.closeStatement(statement);
DB.closeConnection();
}
}
}
|
multiscale_statistics <- function(data, weights, sigmahat, grid){
# Function that calculates the multiscale statistics
#
# Arguments:
# data time series of length T
# weights kernel weights matrix produced by the function 'kernel_weights'
# sigmahat estimate of sqrt(long-run variance)
# grid grid of location-bandwidth points as produced by the function 'grid_construction',
# list with the elements 'gset', 'bws'
#
# Outputs: list with the elements
# values vector of individual test statistics (hat(psi)/sigmahat)
# for each point (u,h) in the location-bandwidth grid
# stat_ms value of the multiscale statistic
# stat_uncor value of the multiscale statistic (uncorrected version)
# stat_rows vector with length equal to the number of bandwidth levels in the
# location-bandwidth grid, stat_rows[i] is the maximum of the individual
# test statistics corresponding to the i-th bandwidth level
# stat_order corrected version of stat_rows, needed to compute the version of the
# multiscale statistics from Section ??
gset <- grid$gset
h.vec <- grid$bws
correct <- sqrt(2*log(1/(2*gset[,2])))
values <- weights %*% data
values <- as.vector(values/sigmahat)
stat.ms <- max(abs(values) - correct)
stat.uncor <- max(abs(values))
stat.rows <- rep(NA,length(h.vec))
stat.order <- rep(NA,length(h.vec))
for(ii in 1:length(h.vec))
{ temp <- (gset[,2] == h.vec[ii])
stat.rows[ii] <- max(abs(values[temp]))
stat.order[ii] <- stat.rows[ii] - sqrt(2*log(1/(2*h.vec[ii])))
}
return(list(values=values, stat_ms=stat.ms, stat_uncor=stat.uncor, stat_rows=stat.rows, stat_order=stat.order))
}
|
/*
* Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
*
* Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Totem.h"
#include "WorldPacket.h"
#include "MapManager.h"
#include "Log.h"
#include "Group.h"
#include "Player.h"
#include "ObjectMgr.h"
#include "SpellMgr.h"
Totem::Totem() : Creature()
{
m_isTotem = true;
m_duration = 0;
m_type = TOTEM_PASSIVE;
}
/// Updates the totem with time, removes is owner or itself died, or duration expired, or updates duration time
/// Paramteres: uint32 time, the difftime
/// Returns: nothing
void Totem::Update(uint32 time )
{
Unit *owner = GetOwner();
if (!owner || !owner->isAlive() || !this->isAlive())
{
UnSummon(); // remove self
return;
}
if (m_duration <= time)
{
UnSummon(); // remove self
return;
}
else
m_duration -= time;
Creature::Update(time);
}
/// Summons a totem
/// Parameters: Unit*, the owner of totem
/// Returns: nothing
void Totem::Summon(Unit* owner)
{
CreatureInfo const *cinfo = GetCreatureInfo();
if (owner->GetTypeId()==TYPEID_PLAYER && cinfo)
{
uint32 modelid = 0;
if (owner->ToPlayer()->GetTeam() == HORDE)
{
if (cinfo->Modelid_H1)
modelid = cinfo->Modelid_H1;
else if (cinfo->Modelid_H2)
modelid = cinfo->Modelid_H2;
}
else
{
if (cinfo->Modelid_A1)
modelid = cinfo->Modelid_A1;
else if (cinfo->Modelid_A2)
modelid = cinfo->Modelid_A2;
}
if (modelid)
SetDisplayId(modelid);
else
sLog.outErrorDb("Totem::Summon: Missing modelid information for entry %u, team %u, totem will use default values.",GetEntry(),owner->ToPlayer()->GetTeam());
}
// Only add if a display exists.
sLog.outDebug("AddObject at Totem.cpp line 49");
SetInstanceId(owner->GetInstanceId());
owner->GetMap()->Add(ToCreature());
WorldPacket data(SMSG_GAMEOBJECT_SPAWN_ANIM_OBSOLETE, 8);
data << GetGUID();
SendMessageToSet(&data,true);
AIM_Initialize();
switch(m_type)
{
case TOTEM_PASSIVE: CastSpell(this, GetSpell(), true); break;
case TOTEM_STATUE: CastSpell(GetOwner(), GetSpell(), true); break;
default: break;
}
if (GetEntry() == SENTRY_TOTEM_ENTRY)
SetReactState(REACT_AGGRESSIVE);
}
/// Removes the totem, stop it's combat, remove auras from it and thne clear
/// Parameters: nothing
/// Returns: nothing
void Totem::UnSummon()
{
SendObjectDeSpawnAnim(GetGUID());
CombatStop();
RemoveAurasDueToSpell(GetSpell());
Unit *owner = this->GetOwner();
if (owner)
{
// clear owenr's totem slot
for (int i = 0; i < MAX_TOTEM; ++i)
{
if (owner->m_TotemSlot[i]==GetGUID())
{
owner->m_TotemSlot[i] = 0;
break;
}
}
owner->RemoveAurasDueToSpell(GetSpell());
//remove aura all party members too
Group *pGroup = NULL;
if (owner->GetTypeId() == TYPEID_PLAYER)
{
// Not only the player can summon the totem (scripted AI)
pGroup = owner->ToPlayer()->GetGroup();
if (pGroup)
{
for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* Target = itr->getSource();
if (Target && pGroup->SameSubGroup(owner->ToPlayer(), Target))
Target->RemoveAurasDueToSpell(GetSpell());
}
}
}
}
CleanupsBeforeDelete();
AddObjectToRemoveList();
}
/// Set the owner of totem
/// Parameters: uint64 guid, the guid of charater/creature
/// Returns: nothing
void Totem::SetOwner(uint64 guid)
{
SetCreatorGUID(guid);
SetOwnerGUID(guid);
if (Unit *owner = GetOwner())
{
this->setFaction(owner->getFaction());
this->SetLevel(owner->getLevel());
}
}
/// Gets the owner of totem
/// Paramters: nothing
/// Returns: Unit* the owner's pointer
Unit *Totem::GetOwner()
{
uint64 ownerid = GetOwnerGUID();
if (!ownerid)
return NULL;
return ObjectAccessor::GetUnit(*this, ownerid);
}
/// Sets the totem's type
/// Parameters: SpellEntry const* the spell what called the totem
/// Returns: nothing
void Totem::SetTypeBySummonSpell(SpellEntry const * spellProto)
{
// Get spell casted by totem
SpellEntry const * totemSpell = sSpellStore.LookupEntry(GetSpell());
if (totemSpell)
{
// If spell have cast time -> so its active totem
if (GetSpellCastTime(totemSpell))
m_type = TOTEM_ACTIVE;
}
if (spellProto->SpellIconID==2056)
m_type = TOTEM_STATUE; //Jewelery statue
}
/// Gets true if totem is immune
/// See Creature::IsImmunedToSpell(SpellEntry const*,bool)
bool Totem::IsImmunedToSpell(SpellEntry const* spellInfo, bool useCharges)
{
/* for (int i=0;i<3;i++)
{
switch(spellInfo->EffectApplyAuraName[i])
{
case SPELL_AURA_PERIODIC_DAMAGE:
case SPELL_AURA_PERIODIC_LEECH:
return true;
default:
continue;
}
}*/
return Creature::IsImmunedToSpell(spellInfo, useCharges);
}
|
import 'package:flutter/material.dart';
import 'package:t/pages/pomodoro.dart';
import 'package:provider/provider.dart';
import './store/pomodoro_store.dart';
import './store/contador_store.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
Provider<PomodoroStore>(
create: (_) => PomodoroStore(),
),
],
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const Pomodoro(),
),
);
}
}
final store = ContadorStore();
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Contador'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Observer(
builder: (_) => Text(
'$store.contador',
style: Theme.of(context).textTheme.headline4,
),
)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: store.incrementar,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
|
package com.example.demo.entity;
import java.time.LocalDateTime;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.format.annotation.DateTimeFormat;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
//엔티티에 변화를 감지하는 리스너 지정 (엔티티에 변화시에 내용수행)
@EntityListeners(AuditingEntityListener.class)
//<- Project03Application.java의 @EnableJpaAuditing
//<- Project03Application.java의 @SpringBootApplication
@Entity // jpa 이용위해 반드시 적기 jpa->table에 매핑
@Table(name="tbl_board") // name = "테이블이름 명시"
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Board {
@Id // pk 지정
@GeneratedValue(strategy=GenerationType.IDENTITY) // auto_increament
int boardNo ;
@Column(length = 30, nullable = false)
String title;
@Column(length = 200)
String content;
@CreatedDate // 인스턴스가 생성되는 것을 감지하여 날짜를 저장 - // 한번 등록되고 안바뀜
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") // 날짜는 꼭 포맷을 지정해야함 - ISO8601 날짜와 관련된 표준에 따라 포맷지정
LocalDateTime createdDate ;
@LastModifiedDate // 인스턴스가 수정되는 것을 감지하여 날짜를 저장 - //수정할때마다 바뀜
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
LocalDateTime modifiedDate;
// 등록일자, 수정일자 셋트다.
// Date관련 - 1. LocalDateTime 클래스 / 2. Date 클래스
// <게시물>
// * 사용자가 입력하는지? 시스템이 입력하는지?
//
// 게시물번호 -> 시스템
// 제목 -> 사용자
// 내용 -> 사용자
// 등록일자 -> 시스템
// 수정일자 -> 시스템
}
|
TextWindow.BackgroundColor = "DarkGreen"
TextWindow.ForegroundColor = "White"
TextWindow.Clear() ' trick to change the console window to green bg
level = 1
score = 0
total = 5
question[1] = "What is the job title of the person in charge of the camera and lighting crews working on a film?"
answers[1] = "1=Production_Manager;2=Cinematographer;3=Unit_Manager;4=Gaffer;"
correctQuestion[1] = 2
question[2]="What is a baby rabbit called?"
answers[2]="1=Kitten;2=Pup;3=Rabee;4=Tuber"
correctQuestion[2]=1
question[3]="In January 1996 Bill Clinton challenged congress to 'Never, ever' do this again"
answers[3]="1=Kiss_Monica;2=Kiss_Hilary;3=Shutdown_government;4=Run_for_re-election"
correctQuestion[3]=3
question[4]="This Mississippi capital was named for a general who later became president?"
answers[4]="1=Topeka;2=Jackson;3=Richmond;4=Grant"
correctQuestion[4]=3
question[5]="This Honda minivan has a Homeric name"
answers[5]="1=Ulysses;2=Troy;3=Spartan;4=Odyssey"
correctQuestion[5]=4
Sub displayHeader
TextWindow.WriteLine("")
TextWindow.WriteLine(" Fiddle Faddle")
TextWindow.WriteLine("")
TextWindow.WriteLine(" Level: " + level + " Score: " + score + "/" + total)
TextWindow.WriteLine("")
EndSub
sub displayQuestion
displayHeader()
TextWindow.WriteLine(" " + question[ctr])
TextWindow.WriteLine("")
For i = 1 To 4
TextWindow.WriteLine(" " + i + " - " + answers[ctr][i])
TextWindow.WriteLine("")
EndFor
TextWindow.Write(" > ")
answer = TextWindow.ReadNumber()
if correctQuestion[ctr] = answer then
score = score + 1
EndIf
TextWindow.Clear()
EndSub
For ctr = 1 To 5
displayQuestion()
EndFor
TextWindow.WriteLine("")
TextWindow.WriteLine(" Game Over!")
TextWindow.WriteLine("")
TextWindow.WriteLine(" Your final score: " + score + "/" + total)
TextWindow.WriteLine("")
|
<!DOCTYPE html>
<html lang="fr">
<head>
@yield('meta')
@yield('title')
<!-- Bootstrap core CSS -->
<link href="{{ asset('bootstrap/css/bootstrap.css') }}" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="{{ asset('css/blog-home.css') }}" rel="stylesheet">
<link href="{{ asset('css/blog-post.css') }}" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="/">{{ setting('site.title') }}</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive"
aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<a class="nav-link" href="/">Accueil</a>
</li>
<li class="nav-item">
<a class="nav-link" href="https://www.gekkode.com/category/developpement/laravel/">Laravel
</a>
</li>
<li class="nav-item">
<a class="nav-link"
href="https://www.gekkode.com/category/developpement/tutoriel/">Tutoriels</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container">
@yield('content')
</div>
<!-- Pagination -->
<!-- Footer -->
<footer class="py-5 bg-dark">
<div class="container">
<p class="m-0 text-center text-white">Copyright
© {{ setting('site.title') }} <?php echo date('Y'); ?></p>
</div>
<!-- /.container -->
</footer>
<!-- Bootstrap core JavaScript -->
<script src="{{ asset('vendor/bootstrap/js/jquery/jquery.min.js') }}"></script>
<script src="{{ asset('vendor/bootstrap/js/bootstrap.bundle.min.js') }}"></script>
</body>
</html>
|
import { Column, Entity, OneToMany } from 'typeorm';
import { Role } from './enums/role.enum';
import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
import { BaseEntity } from 'src/shared/database/base.entity';
import { Follow } from 'src/follows/follow.entity';
import { Post } from 'src/posts/post.entity';
import { Comment } from 'src/comments/comment.entity';
import { Like } from 'src/like/like.entity';
@Entity()
export class User extends BaseEntity {
@IsString()
@IsNotEmpty()
@Column({ unique: true })
username: string;
@IsString()
@IsNotEmpty()
@Column({ unique: true })
@IsEmail()
email: string;
@IsString()
@IsNotEmpty()
@Column()
password: string;
@IsString()
@Column({ nullable: true })
profileImage: string;
@Column({ enum: Role, default: Role.Regular })
role: Role;
@OneToMany(() => Follow, (follow) => follow.follower, {
nullable: true,
cascade: ['remove'],
})
followers: User[];
@OneToMany(() => Follow, (follow) => follow.leader, {
nullable: true,
// cascade: true,
})
followings: User[];
@OneToMany(() => Post, (post) => post.user, {
nullable: true,
})
posts: Post[];
@OneToMany(() => Comment, (comment) => comment.author, {
nullable: true,
cascade: true,
})
comments: Comment[];
@OneToMany(() => Like, (like) => like.user)
likes: Like[];
}
|
import { useQueryClient, useMutation } from '@tanstack/react-query'
import { toast } from 'react-hot-toast'
import type { Note } from '&/modules/note/types'
import { NOTE_KEYS } from '&/modules/note/constants'
import type { TaskNote } from '../types'
import { TASK_NOTES_KEYS } from '../constants'
import { deleteTaskNote } from '../mutations'
export function useDeleteTaskNote() {
const queryClient = useQueryClient()
const { mutate } = useMutation({
mutationFn: deleteTaskNote,
onMutate: async (data) => {
// 🗝️ Keys
const taskNotesKey = TASK_NOTES_KEYS.list(data.task.id)
const noteKey = NOTE_KEYS.detail(data.note.id)
// ✖️ Cancel related queries
await queryClient.cancelQueries({ queryKey: taskNotesKey })
await queryClient.cancelQueries({ queryKey: noteKey })
// ⛳ Update Note item
const previousNote = queryClient.getQueryData(noteKey)
queryClient.setQueryData(noteKey, (old?: Note) => {
if (!old) return
if (!old.taskNotes) return old
const index = old.taskNotes.findIndex((item) => item.id === data.id)
if (index < 0) return old
const taskNotes = [...old.taskNotes.slice(0, index), ...old.taskNotes.slice(index + 1)]
return {
...old,
taskNotes,
}
})
// 🗃️ Update List
const previousTaskNoteList = queryClient.getQueryData(taskNotesKey)
queryClient.setQueryData(taskNotesKey, (old: Note[] = []) => {
const taskNoteIndex = old.findIndex((item) => item.id === data.id)
return [...old.slice(0, taskNoteIndex), ...old.slice(taskNoteIndex + 1)]
})
return { previousTaskNoteList, previousNote }
},
onError: (_err, item, context) => {
queryClient.setQueryData(TASK_NOTES_KEYS.list(item.task.id), context?.previousTaskNoteList)
queryClient.setQueryData(NOTE_KEYS.detail(item.note.id), context?.previousNote)
toast.error("Delete didn't work")
},
onSettled: (_data, _error, variables) => {
queryClient.invalidateQueries({ queryKey: TASK_NOTES_KEYS.list(variables.task.id) })
queryClient.invalidateQueries({ queryKey: NOTE_KEYS.detail(variables.note.id) })
},
})
const onDelete = (taskNote: TaskNote) => mutate(taskNote)
return { onDelete }
}
|
package com.sist.util;
import java.util.*;
import java.text.*;
public class 라이브러리_12 {
public static void main(String[] args) {
/*Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String today = sdf.format(date);
StringTokenizer st = new StringTokenizer(today,"-");
int year = Integer.parseInt(st.nextToken());
int month = Integer.parseInt(st.nextToken());
int day = Integer.parseInt(st.nextToken());*/
Scanner scan = new Scanner(System.in);
System.out.print("년도 입력");
int year = scan.nextInt();
System.out.print("월 입력");
int month = scan.nextInt();
System.out.print("일 입력");
int day = scan.nextInt();
System.out.printf("%d년도 %d월 %d일\n",year,month,day);
String[] strWeek= {"일","월","화","수","목","금","토"};
for (String s : strWeek) {
System.out.print(s+"\t");
}
System.out.println();
// 달력 출력 => 1의 요일 , 마지막 날짜
Calendar cal = Calendar.getInstance();
// 날짜 설정
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month-1);//0
cal.set(Calendar.DATE , 1);// 5월1일자의 요일
int week=cal.get(Calendar.DAY_OF_WEEK);
week = week-1; // week=1
int lastday = cal.getActualMaximum(Calendar.DATE);
// 출력
for (int i = 1; i <= lastday; i++) {
if(i==1) {
// 첫째 주의 공백 출력
for(int j=0; j<week; j++) {
System.out.print("\t");
}
}
System.out.printf("%2d\t",i);
week++;
if(week>6) {
// 한 줄에 7일씩 출력하고 줄바꿈
week=0;
System.out.println();
}
}
}
}
|
import { log, str, msg } from '../common/utils';
import { pattern } from '../common/ref';
import * as I from '../common/interfaces';
import Mirror from './mirror';
import { WebApi, getPersonalAccessTokenHandler } from 'azure-devops-node-api';
import { ProjectVisibility } from 'azure-devops-node-api/interfaces/CoreInterfaces';
export default class Azure extends Mirror {
constructor(config: I.Configuration) {
super(config);
log.debug(str.format(msg.ClassConstruct, Azure.name));
// baseUrl
super.baseUrl = 'https://dev.azure.com';
log.debug(str.format(msg.ClassPropertySet, ['baseUrl', this.baseUrl]));
// gitUrl
super.gitUrl = `${this.baseUrl.replace(
pattern.first.https,
`https://${config.token}@`
)}/${config.owner}/${config.project.replace(
pattern.all.whitespace,
'%20'
)}/_git/${config.repository.replace(pattern.all.whitespace, '%20')}`;
log.debug(str.format(msg.ClassPropertySet, ['gitUrl', this.gitUrl]));
}
private __webApi = async (): Promise<WebApi> =>
await new Promise<WebApi>((resolve, reject) => {
try {
resolve(
new WebApi(
`${this.baseUrl}/${this.config.owner}`,
getPersonalAccessTokenHandler(this.config.token)
)
);
} catch (e) {
reject(e);
log.error(e, '__webApi');
}
});
project = {
create: async () => {
const web = await this.__webApi();
const core = await web.getCoreApi();
let visibility: ProjectVisibility | undefined;
if (this.config.visibility) {
visibility =
this.config.visibility === 'private'
? ProjectVisibility.Private
: ProjectVisibility.Public;
}
return await this.request({
operation: I.Operation.create,
entity: {
type: I.EntityType.project,
name: this.config.project
},
asyncFunction: async () =>
await core.queueCreateProject({
name: this.config.project,
capabilities: {
versioncontrol: { sourceControlType: 'Git' },
processTemplate: {
templateTypeId: 'b8a3a935-7e91-48b8-a94c-606d37c3e9f2'
}
},
visibility
})
});
},
exists: async () => {
const web = await this.__webApi();
const core = await web.getCoreApi();
return await this.request({
operation: I.Operation.read,
entity: {
type: I.EntityType.project,
name: this.config.project
},
asyncFunction: async () => await core.getProject(this.config.project)
});
}
};
repository = {
create: async () => {
const web = await this.__webApi();
const git = await web.getGitApi();
return await this.request({
operation: I.Operation.create,
entity: {
type: I.EntityType.repository,
name: this.config.repository
},
asyncFunction: async () =>
await git.createRepository(
{
name: this.config.repository
},
this.config.project
)
});
},
exists: async (options?: {
repositoryId?: string;
maxAttempts?: number;
}) => {
const web = await this.__webApi();
const git = await web.getGitApi();
return await this.request({
operation: I.Operation.read,
entity: {
type: I.EntityType.repository,
name: options?.repositoryId ?? this.config.repository
},
asyncFunction: async () =>
await git.getRepository(
options?.repositoryId ?? this.config.repository,
this.config.project
),
maxAttempts: options?.maxAttempts
});
}
};
}
|
---
title: lazy
---
<Intro>
`lazy` আপনাকে component এর কোড বিলম্বিত করার সুযোগ দেয় যতক্ষণ না এটা প্রথম বারের মত রেন্ডার করা হচ্ছে।
```js
const SomeComponent = lazy(load)
```
</Intro>
<InlineToc />
---
## রেফারেন্স {/*reference*/}
### `lazy(load)` {/*lazy*/}
একটি lazy-loaded React component ডিক্লেয়ার করার জন্য আপনার component গুলোর বাইরে `lazy` কল করুনঃ
```js
import { lazy } from 'react';
const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));
```
[নিচে আরো উদাহরণ দেখুন।](#usage)
#### প্যারামিটার {/*parameters*/}
* `load`: একটি ফাংশন যা একটি [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) অথবা অন্য কোন *thenable* (`then` মেথড সহ একটি Promise-like অবজেক্ট) রিটার্ন করে। আপনি যতক্ষণ রিটার্ন হওয়া component লোড করার চেষ্টা করছেন ততক্ষণ React `load` কল করবে না। React প্রথম বার `load` কল করার পর, এটা resolved হবার অপেক্ষা করবে, এবং এর পরে resolved value React component হিসেবে রেন্ডার করবে। রিটার্ন হওয়া Promise এবং Promise এর resolved value cached হয়ে থাকবে, সুতরাং React একবারের বেশি `load` কল করবে না। যদি Promise reject করে, React rejection এর কারণ `throw` করবে যেন সবচেয়ে নিকটবর্তী error boundary সেটা হ্যান্ডেল করে।
#### রিটার্ন {/*returns*/}
`lazy` একটি React component রিটার্ন করে যা আপনি আপনার ট্রিতে রেন্ডার রক্তে পারবেন। যতক্ষণ পর্যন্ত lazy component এর কোড লোড হচ্ছে, এটাকে রেন্ডারের চেষ্টা *suspend* হবে। এটা লোডীং এর সময় লোডীং ইনডিকেটর দেখানোর জন্য [`<Suspense>`](/reference/react/Suspense) ব্যবহার করুন।
---
### `load` ফাংশন {/*load*/}
#### প্যারামিটার {/*load-parameters*/}
`load` কোন প্যারামিটার রিসিভ করে না।
#### রিটার্ন {/*load-returns*/}
আপনাকে একটি [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) অথবা অন্য কোন *thenable* (`then` মেথড সহ একটি Promise-like অবজেক্ট)। একে শেষমেশ একটি অবজেক্টে যেতে হবে যার `.default` প্রপার্টি একটি যথাযথ React কম্পোনেন্ট টাইপ , যেমন একটি ফাংশন, [`memo`](/reference/react/memo), অথবা একটি [`forwardRef`](/reference/react/forwardRef) component।
---
## ব্যবহার {/*usage*/}
### সাসপেন্স সহ লেইজি-লোডিং কম্পোনেন্টস {/*suspense-for-code-splitting*/}
সাধারণত, আপনি component ইমপোর্ট করেন static [`import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) ডিক্লেয়ারেশন সহঃ
```js
import MarkdownPreview from './MarkdownPreview.js';
```
এই component এর কোডের লোডীং প্রথম বার রেন্ডার হবার আগ পর্যন্ত বিলম্বিত করতে এই ইমপোর্ট নিচের কোড দিয়ে প্রতিস্থাপন করুনঃ
```js
import { lazy } from 'react';
const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));
```
এই কোড [dynamic `import()`,](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) এর উপর নির্ভর করে যার আপনার বান্ডলার বা ফ্রেমওয়ার্ক থেকে support এর দরকার পড়তে পারে। এই প্যাটার্ন ব্যবহার করলে এটা জরুরী যে আপনি যেই lazy কম্পোনেন্ট ইম্পোর্ট করছেন সেটা `default` এক্সপোর্ট হিসেবে এক্সপোর্ট করা হয়েছিল।
এখন যেহেতু আপনার component এর কোড চাহিদানুযায়ী লোড হয়, আপনাকে এটা নির্ধারণ করে দিতে হবে যে এটা লোডীং এর সময়ে কী ডিসপ্লে হওয়া উচিত। এটা আপনি করতে পারেন lazy component অথবা এর যেকোন parent কে [`<Suspense>`](/reference/react/Suspense) boundary এর মধ্যে wrap করার মাধ্যমেঃ
```js {1,4}
<Suspense fallback={<Loading />}>
<h2>Preview</h2>
<MarkdownPreview />
</Suspense>
```
এই উদাহরণে, `MarkdownPreview` এর কোড ততক্ষণ লোড হবে না যতক্ষণ আপনি এটা রেন্ডারের চেষ্টা করেন। যদি `MarkdownPreview` লোড না হয়ে থাকে, `Loading` তার নিজের জায়গায় দেখাবে। চেকবক্স টিক করে দেখুনঃ
<Sandpack>
```js App.js
import { useState, Suspense, lazy } from 'react';
import Loading from './Loading.js';
const MarkdownPreview = lazy(() => delayForDemo(import('./MarkdownPreview.js')));
export default function MarkdownEditor() {
const [showPreview, setShowPreview] = useState(false);
const [markdown, setMarkdown] = useState('Hello, **world**!');
return (
<>
<textarea value={markdown} onChange={e => setMarkdown(e.target.value)} />
<label>
<input type="checkbox" checked={showPreview} onChange={e => setShowPreview(e.target.checked)} />
Show preview
</label>
<hr />
{showPreview && (
<Suspense fallback={<Loading />}>
<h2>Preview</h2>
<MarkdownPreview markdown={markdown} />
</Suspense>
)}
</>
);
}
// Add a fixed delay so you can see the loading state
function delayForDemo(promise) {
return new Promise(resolve => {
setTimeout(resolve, 2000);
}).then(() => promise);
}
```
```js Loading.js
export default function Loading() {
return <p><i>Loading...</i></p>;
}
```
```js MarkdownPreview.js
import { Remarkable } from 'remarkable';
const md = new Remarkable();
export default function MarkdownPreview({ markdown }) {
return (
<div
className="content"
dangerouslySetInnerHTML={{__html: md.render(markdown)}}
/>
);
}
```
```json package.json hidden
{
"dependencies": {
"immer": "1.7.3",
"react": "latest",
"react-dom": "latest",
"react-scripts": "latest",
"remarkable": "2.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
```
```css
label {
display: block;
}
input, textarea {
margin-bottom: 10px;
}
body {
min-height: 200px;
}
```
</Sandpack>
এই ডেমো কৃত্রিম একটা বিলম্বের সাথে লোড হয়। এর পরের বার যখন আপনি চেকবক্স টিক করবেন এবং আনটিক করবেন, `Preview` এর cache হয়ে যাবে, সুতরাং কোন লোডীং state থাকবে না। লোডীং state আবার দেখতে চাইলে, স্যান্ডবক্সের উপর "Reset" বাটন ক্লিক করুন।
[Learn more about managing loading states with Suspense.](/reference/react/Suspense)
---
## ট্রাবলশ্যুট {/*troubleshooting*/}
### আমার `lazy` component এর state অপ্রত্যাশিতভাবে রিসেট হয়ে যায় {/*my-lazy-components-state-gets-reset-unexpectedly*/}
`lazy` component গুলোকে অন্যান্য component গুলোর *ভেতরে* ডিক্লেয়ার করবেন নাঃ
```js {4-5}
import { lazy } from 'react';
function Editor() {
// 🔴 Bad: This will cause all state to be reset on re-renders
const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));
// ...
}
```
তার বদলে, এগুলোকে সব সময় আপনার মডিউলের সর্বোচ্চ স্তরে ডিক্লেয়ার করুনঃ
```js {3-4}
import { lazy } from 'react';
// ✅ Good: Declare lazy components outside of your components
const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));
function Editor() {
// ...
}
```
|
# Памятка по использованию языка SQL
## Источники
[«SQL: Руководство по стилю»](https://www.sqlstyle.guide/ru/) Саймона Холиуэлла, перевод [denpatin](https://github.com/denpatin) ([СС-BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/))
[Интерактивный тренажер по SQL (часть 1.3, шаг 8)](https://stepik.org/lesson/297515/step/8), автор Александра Клинникова с комментариями Ильи Филимонова ([СС-BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/))
https://www.mysqltutorial.org/mysql-having.aspx/
https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-having/
## Порядок выполнения SQL запроса на выборку на сервере MySQL:
1. FROM
2. WHERE
3. GROUP BY
4. HAVING
5. DISTINCT
6. SELECT
7. ORDER BY
8. LIMIT
Сначала определяется таблица, из которой выбираются данные (`FROM`), затем из этой таблицы отбираются записи в соответствии с условием `WHERE`, выбранные данные агрегируются (`GROUP BY`), из агрегированных записей выбираются те, которые удовлетворяют условию после `HAVING`. Потом формируются данные результирующей выборки, как это указано после `SELECT` (вычисляются выражения, присваиваются имена и пр. ). Результирующая выборка сортируется, как указано после `ORDER BY`.
Для баз PostgreSQL пункты 5 и 6 меняются местами.
## Универсальные суффиксы
Приведённые ниже суффиксы универсальны, что гарантирует простоту понимания значения столбцов из кода SQL.
- **_id** — уникальный идентификатор, например первичный ключ.
- **_status** — флаг или любой статус, например publication_status.
- **_total** — общее количество или сумма значений.
- **_num** — поле, содержащее число.
- **_name** — любое имя, например first_name.
- **_seq** — непрерывная последовательность значений.
- **_date** — колонка, содержащая дату.
- **_tally** — счётчик.
- **_size** — размер или величина чего-либо, например размер файла.
- **_addr** — физический или абстрактный адрес, например ip_addr.
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
var storage = new Storage('shoppingCar');
//清空数据
storage.set();
//添加矿泉水
var item1 = {
name: '矿泉水',
price: '5'
};
storage.add(item1);
console.log(storage.get());
//添加冰红茶
var item2 = {
name: '冰红茶',
price: '10'
};
storage.add(item2);
console.log(storage.get());
//数据库对象,初始化时需要给key作为数据存储的key
function Storage(key){
//添加一项数据
//value: object
this.add = function(value){
if (value){
var v = this.get();
v.push(value);
this.set(v);
}
};
//设置数据
//value: array、 null
this.set = function(value){
if(value){
var v = JSON.stringify(value);
localStorage.setItem(key, v)
}
else {
localStorage.removeItem(key);
}
};
//获取数据
this.get = function(){
var value = localStorage.getItem(key) || '[]';
return JSON.parse(value);
};
}
</script>
</body>
</html>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>testing</title>
</head>
<body>
<h4>Testing event delegation</h4>
<input type="text" id="input">
<button id="add">add</button>
<ul id="output"></ul>
</body>
<script>
const output = document.querySelector('#output');
const n = new Array('one', 'two', 'three', 'four', 'five');
const add = document.querySelector('#add');
let input = document.querySelector('#input');
let addList = (word) => {
let li = document.createElement('li');
let content = document.createTextNode(word);
li.appendChild(content);
output.append(li);
}
n.map((el) => {
addList(el);
})
add.addEventListener('click', () => {
const input_value = input.value;
addList(input_value);
});
// Event deligation => parent layer control process
output.addEventListener('click', (el) => {
console.log(el.target.innerHTML);
});
</script>
</html>
|
import React, { useRef, useState } from 'react';
import Modal from '@material-ui/core/Modal';
import { makeStyles } from '@material-ui/core/styles';
import { useParams } from 'react-router-dom';
import EventsService from '../services/events';
const useStyles = makeStyles((theme) => ({
root: {
height: '100vh',
display: 'flex',
flexGrow: 1,
minWidth: 300,
transform: 'translateZ(0)',
// The position fixed scoping doesn't work in IE 11.
// Disable this demo to preserve the others.
'@media all and (-ms-high-contrast: none)': {
display: 'none',
},
},
modal: {
display: 'flex',
padding: theme.spacing(1),
alignItems: 'center',
justifyContent: 'center',
},
paper: {
width: 400,
backgroundColor: theme.palette.background.paper,
border: '2px solid #000',
boxShadow: theme.shadows[5],
padding: theme.spacing(2, 4, 3),
},
}));
function Confirmation(){
const classes = useStyles();
const { id } = useParams();
const [message, setMessage] = useState('Wait a couple of minutes...');
const rootRef = React.useRef(null);
const confirmToApi = () => {
EventsService.confirmGuestAttendance(id);
};
React.useEffect(
() => {
const timeout = setTimeout(() => {
confirmToApi();
setMessage('You are all set! See you next time');
}, 2000);
},
[],
);
return(
<div className={classes.root} ref={rootRef}>
<Modal
disablePortal
disableEnforceFocus
disableAutoFocus
open
aria-labelledby="server-modal-title"
aria-describedby="server-modal-description"
className={classes.modal}
container={() => rootRef.current}
>
<div className={classes.paper}>
<h2 id="server-modal-title">Confirming your invitation</h2>
<p id="server-modal-description">{message}</p>
</div>
</Modal>
</div>
)
}
export default Confirmation
|
import { NodeType } from 'prosemirror-model'
import { TextSelection } from 'prosemirror-state'
import { InputRule, InputRuleFinder, mergeAttributes, Node } from '@tiptap/core'
export interface HorizontalRuleOptions {
HTMLAttributes: Record<string, any>
}
declare module '@tiptap/core' {
interface Commands<ReturnType> {
horizontalRule: {
/**
* Add a horizontal rule
*/
setHorizontalRule: () => ReturnType
}
}
}
export const HorizontalRule = Node.create<HorizontalRuleOptions>({
name: 'horizontalRule',
addOptions() {
return {
HTMLAttributes: {},
}
},
group: 'block',
parseHTML() {
return [{ tag: 'hr' }]
},
renderHTML({ HTMLAttributes }) {
return ['hr', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]
},
addCommands() {
return {
setHorizontalRule:
() =>
({ chain }) => {
return (
chain()
.insertContent({ type: this.name })
// set cursor after horizontal rule
.command(({ tr, dispatch }) => {
if (dispatch) {
const { $to } = tr.selection
const posAfter = $to.end()
if ($to.nodeAfter) {
tr.setSelection(TextSelection.create(tr.doc, $to.pos))
} else {
// add node after horizontal rule if it’s the end of the document
const node = $to.parent.type.contentMatch.defaultType?.create()
if (node) {
tr.insert(posAfter, node)
tr.setSelection(TextSelection.create(tr.doc, posAfter))
}
}
tr.scrollIntoView()
}
return true
})
.run()
)
},
}
},
addInputRules() {
return [
hrInputRule({
find: /^(?:---|—-|___\s|\*\*\*\s)$/,
type: this.type,
}),
]
},
})
function hrInputRule(config: { find: InputRuleFinder; type: NodeType }) {
return new InputRule({
find: config.find,
handler: ({ state, range, match }) => {
const $start = state.doc.resolve(range.from)
const node = $start.node()
const newNode = config.type.create()
const from = Math.max(0, range.from - 1)
const to = Math.min(range.to, state.doc.nodeSize - 1)
if (node == state.doc.lastChild) {
state.tr.insertText('', to).split(to)
}
state.tr.replaceWith(from, to, newNode)
},
})
}
|
use crate::SortedSlice;
use std::{cmp::Ordering, collections::HashMap, hash::Hash};
pub trait Mode {
type Output;
fn mode(&self) -> Option<Vec<Self::Output>>;
}
impl<T> Mode for SortedSlice<'_, T>
where
T: Copy + PartialEq,
{
type Output = T;
fn mode(&self) -> Option<Vec<Self::Output>> {
match self.slice.len() {
0 => None,
1 => Some(vec![*self.slice.first().unwrap()]),
_ => {
let mut modes = Vec::new();
let mut curr_run_count = 1usize;
let mut max_run_count = 1usize;
for window in self.slice.windows(2) {
let (prev_elem, curr_elem) = (window[0], window[1]);
if prev_elem == curr_elem {
curr_run_count += 1;
} else {
match curr_run_count.cmp(&max_run_count) {
Ordering::Greater => {
max_run_count = curr_run_count;
modes.clear();
modes.push(prev_elem);
}
Ordering::Equal => modes.push(prev_elem),
Ordering::Less => (),
}
curr_run_count = 1;
}
}
match curr_run_count.cmp(&max_run_count) {
Ordering::Greater => {
modes.clear();
modes.push(*self.slice.last().unwrap());
}
Ordering::Equal => modes.push(*self.slice.last().unwrap()),
Ordering::Less => (),
}
Some(modes)
}
}
}
}
impl<T> Mode for [T]
where
T: Copy + Eq + Hash,
{
type Output = T;
fn mode(&self) -> Option<Vec<Self::Output>> {
if self.is_empty() {
None
} else {
let mut modes = Vec::new();
let mut occurrences = HashMap::new();
let mut max_occurrences = 0usize;
for item in self {
let curr_occurrences = occurrences.entry(item).or_insert(0usize);
*curr_occurrences += 1;
match (*curr_occurrences).cmp(&max_occurrences) {
Ordering::Greater => {
modes.clear();
modes.push(*item);
max_occurrences = *curr_occurrences;
}
Ordering::Equal => modes.push(*item),
Ordering::Less => (),
}
}
Some(modes)
}
}
}
|
#### 1. 什么是发布订阅?
发布/ 订阅系统 是 Web 系统中比较常用的一个功能。简单点说就是 发布者发布消息,订阅者接受消息,这有点类似于我们的报纸/ 杂志社之类的:

在redis中我们虽然可以使用一个 list 列表结构结合 lpush 和 rpop 来实现消息队列的功能,但是似乎很难实现实现 **消息多播** 的功能:

为了支持消息多播,Redis 不能再依赖于那 5 种基础的数据结构了,它单独使用了一个模块来支持消息多播,这个模块就是 PubSub,也就是 PublisherSubscriber (发布者/ 订阅者模式)。
我们从 上面的图 中可以看到,基于 list 结构的消息队列,是一种 Publisher 与 Consumer 点对点的强关联关系,Redis 为了消除这样的强关联,引入了另一种概念:**频道** (channel):

当 Publisher 往 channel 中发布消息时,关注了指定 channel 的 Consumer 就能够同时受到消息。但这里的 **问题 是,消费者订阅一个频道是必须 明确指定频道名称** 的,这意味着,如果我们想要 **订阅多个 频道**,那么就必须 显式地关注多个 名称。
为了简化订阅的繁琐操作,Redis 提供了 **模式订阅** 的功能 Pattern Subscribe,这样就可以 一次性关注多个频道 了,即使生产者新增了同模式的频道,消费者也可以立即受到消息:

在上图中wmyskxz.*的模式订阅 可以同时接受到wmyskxz.chat和wmyskxz.log频道发布的消息。
#### 2. 具体怎么使用?
在Redis的PubSub模块的使用常用命令如下:
```
1. # 订阅频道:
2. SUBSCRIBE channel [channel ....] # 订阅给定的一个或多个频道的信息
3. PSUBSCRIBE pattern [pattern ....] # 订阅一个或多个符合给定模式的频道
4. # 发布频道:
5. PUBLISH channel message # 将消息发送到指定的频道
6. # 退订频道:
7. UNSUBSCRIBE [channel [channel ....]] # 退订指定的频道
8. PUNSUBSCRIBE [pattern [pattern ....]] #退订所有给定模式的频道
```
#### 3. Redis的发布订阅实现原理是什么?
**每个 Redis 服务器进程维持着一个标识服务器状态 的 redis.h/redisServer 结构,其中就 保存着有订阅的频道** 以及 订阅模式 的信息:
```
1. struct redisServer {
2. // ...
3. dict *pubsub_channels; // 订阅频道
4. list *pubsub_patterns; // 订阅模式
5. // ...
6. };
```
##### 3.1 订阅频道
当客户端订阅某一个频道之后,Redis 就会往 pubsub_channels 这个字典中新添加一条数据,实际上这个 dict 字典维护的是一张链表,比如,下图展示的 pubsub_channels 示例中,client 1、client 2 就订阅了 channel 1,而其他频道也分别被其他客户端订阅:

- **SUBSCRIBE 命令**
SUBSCRIBE 命令的行为可以用下列的伪代码表示:
```
1. def SUBSCRIBE(client, channels):
2. # 遍历所有输入频道
3. for channel in channels:
4. # 将客户端添加到链表的末尾
5. redisServer.pubsub_channels[channel].append(client)
```
通过 pubsub_channels 字典,程序只要检查某个频道是否为字典的键,就可以知道该频道是否正在被客户端订阅;只要取出某个键的值,就可以得到所有订阅该频道的客户端的信息。
- **PUBLISH 命令**
了解 SUBSCRIBE,那么 PUBLISH 命令的实现也变得十分简单了,只需要通过上述字典定位到具体的客户端,再把消息发送给它们就好了:(伪代码实现如下)
```
1. def PUBLISH(channel, message):
2. # 遍历所有订阅频道 channel 的客户端
3. for client in server.pubsub_channels[channel]:
4. # 将信息发送给它们
5. send_message(client, message)
```
- **UNSUBSCRIBE 命令**
使用 UNSUBSCRIBE 命令可以退订指定的频道,这个命令执行的是订阅的反操作:它从 pubsub_channels 字典的给定频道(键)中,删除关于当前客户端的信息,这样被退订频道的信息就不会再发送给这个客户端。
##### 3.2 订阅模式

正如我们上面说到了,当发送一条消息到 wmyskxz.chat 这个频道时,Redis 不仅仅会发送到当前的频道,还会发送到匹配于当前模式的所有频道,实际上,pubsub_patterns 背后还维护了一个 redis.h/pubsubPattern 结构:
```
1. typedef struct pubsubPattern {
2. redisClient *client; // 订阅模式的客户端
3. robj *pattern; // 订阅的模式
4. } pubsubPattern;
```
每当调用 PSUBSCRIBE 命令订阅一个模式时,程序就创建一个包含客户端信息和被订阅模式的 pubsubPattern 结构,并将该结构添加到 redisServer.pubsub_patterns 链表中。
我们来看一个 pusub_patterns 链表的示例:

这个时候客户端 client 3 执行 PSUBSCRIBE wmyskxz.java.*,那么 pubsub_patterns 链表就会被更新成这样:

通过遍历整个 pubsub_patterns 链表,程序可以检查所有正在被订阅的模式,以及订阅这些模式的客户端。
- **PUBLISH 命令**
上面给出的伪代码并没有 完整描述 PUBLISH 命令的行为,因为 PUBLISH 除了将 message 发送到 所有订阅 channel 的客户端 之外,它还会将 channel 和 pubsub_patterns 中的 模式 进行对比,如果 channel 和某个模式匹配的话,那么也将 message 发送到 订阅那个模式的客户端。
完整描述 PUBLISH 功能的伪代码定于如下:
```
1. def PUBLISH(channel, message):
2. # 遍历所有订阅频道 channel 的客户端
3. for client in server.pubsub_channels[channel]:
4. # 将信息发送给它们
5. send_message(client, message)
6. # 取出所有模式,以及订阅模式的客户端
7. for pattern, client in server.pubsub_patterns:
8. # 如果 channel 和模式匹配
9. if match(channel, pattern):
10. # 那么也将信息发给订阅这个模式的客户端
11. send_message(client, message)
```
- **PUNSUBSCRIBE 命令**
使用 PUNSUBSCRIBE 命令可以退订指定的模式,这个命令执行的是订阅模式的反操作:序会删除 redisServer.pubsub_patterns 链表中,所有和被退订模式相关联的 pubsubPattern 结构,这样客户端就不会再收到和模式相匹配的频道发来的信息。
#### 4. Pub/Sub有什么不足之处吗?
尽管 Redis 实现了 PubSub 模式来达到了 多播消息队列 的目的,但在实际的消息队列的领域,几乎 找不到特别合适的场景,因为它的缺点十分明显:
1. **没有 Ack 机制**,也不保证数据的连续: PubSub 的生产者传递过来一个消息,Redis 会直接找到相应的消费者传递过去。如果没有一个消费者,那么消息会被直接丢弃。如果开始有三个消费者,其中一个突然挂掉了,过了一会儿等它再重连时,那么重连期间的消息对于这个消费者来说就彻底丢失了。
2. **不持久化消息**: 如果 Redis 停机重启,PubSub 的消息是不会持久化的,毕竟 Redis 宕机就相当于一个消费者都没有,所有的消息都会被直接丢弃。
基于上述缺点,Redis 的作者甚至单独开启了一个 **Disque** 的项目来专门用来做多播消息队列,不过该项目目前好像都没有成熟。不过后来在 2018 年 6 月,Redis 5.0 新增了 **Stream 数据结构**,这个功能给 Redis 带来了 持久化消息队列,**从此 PubSub 作为消息队列的功能可以说是就消失了..**
|
import { useState, useCallback } from 'react'
import { FileType, FileBlobItem } from '@/types'
import { FILE_STATUS } from '@/constants'
import { $info } from '@/utils'
export function useFiles() {
const [roomFiles, setRoomFiles] = useState<FileType[]>([])
/**
* 某个用户增加文件
* 直接追加文件
* @param {String} peerId 对方的peerId
*/
const addFiles = useCallback((peerId:string, files:FileType[]) => {
setRoomFiles(state => state.concat(files))
$info('有文件更新啦', { key: Date.now() })
console.log(`用户 ${ peerId } 的文件更新啦`, files)
}, [])
/**
* 删除已经离线节点的文件
*/
const delDisconnectedFiles = useCallback((peerId:string) => {
setRoomFiles(files => files.filter(file => file.peerId !== peerId))
}, [])
/**
* 根据fileId,更新文件的状态
*/
const updateFileStatus = useCallback((fileId:string, status: `${ FILE_STATUS }`) => {
setRoomFiles(files => files.map(file => file.id === fileId
? {
...file,
status
}
: file))
}, [])
/**
* 根据二进制流,下载某个文件
*/
const downloadFile = useCallback((file:FileType) => {
file.raw.sort((a, b) => a.index - b.index)
const blobs = file.raw.map(item => item.blob)
const compBlobs = blobs.flat()
const url = window.URL.createObjectURL(new Blob(compBlobs, { type: 'arraybuffer' }))
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', file.name)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}, [])
return {
roomFiles,
setRoomFiles,
addFiles,
downloadFile,
updateFileStatus,
delDisconnectedFiles
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- Обязательное задание.
Выполнить все задачи в теге script. Комментарии, в которых написаны задачи, не стирать, код с решением задачи пишем
под комментарием. -->
<input id="from" type="text">
В инпуте написано: <span></span>
<br>
<button class="messageBtn">Показать блок</button>
<div class="message">
Привет :)
</div>
<br>
<form>
<label>
Первый инпут:
<input class="form-control" type="text">
</label>
<br>
<br>
<label>
Второй инпут:
<select class="form-control">
<option value=""></option>
<option value="1">Один</option>
<option value="2">Два</option>
</select>
</label>
<br>
<br>
<button>Отправить</button>
</form>
<script>
"use strict";
// 1. При изменении значения в input с id="from", значение содержащееся в нем
// должно моментально отображаться в span. То есть при печати в input'е
// тег span также должен меняться.
const formId = document.querySelector("#from");
const span = document.querySelector("span");
const chageHead = () => {
span.innerText = formId.value;
}
formId.addEventListener('input', chageHead);
// 2. 2. При клике на кнопку с классом messageBtn необходимо элементу с классом message:
// - добавить два класса: animate_animated и animate_fadeInLeftBig
// - поставить данному элементу стиль visibility в значение 'visible'.
const messageBtn = document.querySelector(".messageBtn");
const message = document.querySelector(".message");
messageBtn.addEventListener('click', function () {
message.classList.add('animate_animated')
message.classList.add('animate_fadeInLeftBig');
message.style.visibility = 'visible';
});
// 3. Необходимо при отправке формы проверить, заполнены ли все поля в этой форме. Если
// какое-либо поле не заполнено, форма не должна отправляться, также должны быть подсвечены
// незаполненные поля (необходимо поставить класс error незаполненным полям). Как только
// пользователь начинает заполнять какое-либо поле, необходимо, при вводе в данное поле, произвести проверку:
// - Если поле пустое, необходимо данное поле подсветить (поставить класс error данному полю).
// - Если поле было чем-либо заполнено, подсветку (класс error) необходимо убрать.
const form = document.querySelector('form');
const formControl = document.querySelectorAll('.form-control');
const btn = document.querySelector('form button');
form.addEventListener('submit', (e) => {
e.preventDefault();
formControl.forEach((element) => {
if (element.tagName === 'INPUT') {
isValid(element);
} else if (element.tagName === 'SELECT') {
isValid(element);
}
});
});
function isValid(elem) {
if (elem.value === '') {
elem.style.backgroundColor = 'Yellow';
elem.classList.add('error');
elem.setCustomValidity('Пустое значение');
elem.reportValidity();
} else {
btn.textContent = 'ОК';
setTimeout(() => {
btn.textContent = 'Отправить';
}, 1000);
}
}
formControl.forEach((el) => {
el.addEventListener('input', () => {
el.setCustomValidity('');
el.removeAttribute('style');
el.classList.remove('error');
});
});
</script>
</body>
</html>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mayson Reader - Portfolio</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>
<body>
<div class="intro">
<div class="container">
<nav>
<ul class="nav-links">
<li><a href="#about">About</a></li>
<li><a href="#projects">Projects</a></li>
<li><a href="#skills">Skills</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
<button class="hamburger">
<span class="bar"></span>
<span class="bar"></span>
<span class="bar"></span>
</button>
</nav>
<div class="intro-text">
<h1 class="title">Hello, I'm Mayson Reader.</h1>
<p class="subtitle">Python Developer | Game Developer | Web Enthusiast</p>
<a href="#projects" class="btn">Explore My Work</a>
</div>
</div>
</div>
<section id="about" class="section">
<div class="container">
<h2 class="section-title">About Me</h2>
<div class="content">
<p>
I'm a passionate developer with a keen interest in Python, game development, and web development.<br> I love creating innovative and engaging experiences, whether it's building a complex algorithm or designing an immersive game world.
</p>
<p>
I'm constantly learning and exploring new technologies, and I'm always eager to collaborate on exciting projects.
</p>
<a href="#contact" class="btn">Get in Touch</a>
<a href="Resume.pdf" class="btn">My Resume</a>
</div>
</div>
</section>
<section id="projects" class="section">
<div class="container">
<h2 class="section-title">My Projects</h2>
<div class="projects-container">
<!-- Project 1 -->
<div class="project">
<img src="images/project1.png" alt="Project 1">
<div class="project-info">
<h3>The Deep End</h3>
<p>This project was created for the 2023 Gifted Online Game Jam made by Mika Brian and I. Built with Python.</p>
<a href="redirects/thedeepend.html" target="_blank" class="btn">Play Game</a>
</div>
</div>
<!-- Project 2 -->
<div class="project">
<img src="images/project2.png" alt="Project 2">
<div class="project-info">
<h3>Deathly Snail</h3>
<p>Deathly Snail is a game created using Python and was made for the 2022 Gifted Online Game Jam</p>
<a href="redirects/deathlysnail.html" target="_blank" class="btn">Play Game</a>
</div>
</div>
<!-- Project 3 -->
</div>
</div>
</section>
<section id="skills" class="section">
<div class="container">
<h2 class="section-title">My Skills</h2>
<div class="skills-container">
<div class="skill">
<i class="fab fa-python"></i>
<h3>Python</h3>
</div>
<div class="skill">
<div class="htmlcss">
<i class="fab fa-html5"></i>
<i class="fab fa-css3-alt"></i>
<h3>HTML & CSS</h3>
</div>
</div>
<div class="skill">
<i class="fas fa-gamepad"></i>
<h3>Game Development</h3>
</div>
<!-- Add more skills here -->
</div>
</div>
</section>
<section id="contact" class="section">
<div class="container">
<h2 class="section-title">Get in Touch</h2>
<div class="contact-info">
<p>I'm always open to new opportunities and collaborations. Feel free to reach out!</p>
<ul>
<li>
<i class="fab fa-linkedin"></i>
<a href="https://linkedin.com/in/mayson-reader-7281982a4" target="_blank">LinkedIn</a>
</li>
<li>
<i class="fab fa-github"></i>
<a href="https://github.com/mayreader" target="_blank">GitHub</a>
</li>
</ul>
</div>
</div>
</section>
<footer class="footer">
<div class="container">
<p>© 2024 Mayson Reader. All rights reserved.</p>
</div>
</footer>
<script src="script.js"></script>
</body>
</html>
|
// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:flutter/material.dart';
import 'package:whatsapp_clone/models/contacts_model.dart';
import 'package:whatsapp_clone/presentation/screens/chat_screen/msg_textfield.dart';
class ChatScreen extends StatefulWidget {
const ChatScreen({
super.key,
required this.contact,
});
final ContactsModel contact;
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
toolbarHeight: size.height * 0.07,
automaticallyImplyLeading: true,
leadingWidth: 24,
title: Row(
children: [
CircleAvatar(
radius: 18,
child: Image(
image: AssetImage(widget.contact.imageUrl),
fit: BoxFit.contain,
// height: 30,
),
),
SizedBox(width: size.width * 0.03),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.contact.name,
style: Theme.of(context).textTheme.bodyLarge!.copyWith(
color: Colors.white, fontWeight: FontWeight.bold),
),
Text(
'Last seen today at 09:29 AM',
style: Theme.of(context).textTheme.bodySmall!.copyWith(
color: Colors.white, fontWeight: FontWeight.normal),
),
],
)
],
),
actions: [
IconButton(
onPressed: () {}, icon: const Icon(Icons.video_call_rounded)),
IconButton(onPressed: () {}, icon: const Icon(Icons.phone)),
PopupMenuButton(
useRootNavigator: true,
position: PopupMenuPosition.under,
icon: const Icon(Icons.more_vert),
itemBuilder: (context) => [
const PopupMenuItem(child: Text('View contact')),
const PopupMenuItem(child: Text('Media, links and docs')),
const PopupMenuItem(child: Text('Search')),
const PopupMenuItem(child: Text('Unmute notifications')),
const PopupMenuItem(child: Text('Disappearing messages')),
const PopupMenuItem(child: Text('Wallpaper')),
const PopupMenuItem(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('More'),
Icon(
Icons.navigate_next_outlined,
color: Colors.black,
size: 20,
)
]))
],
)
],
),
body: Column(
children: [
Expanded(
child: Container(
width: double.maxFinite,
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/bg.png'),
fit: BoxFit.cover,
),
),
child: Stack(
children: [
Positioned(
bottom: 0,
left: 18,
right: 2,
child: ConstrainedBox(
constraints: const BoxConstraints(
minHeight: 80,
maxHeight: 100,
),
child: Container(
color: Colors.transparent,
child: const MessageTextFieldArea(),
),
),
),
],
),
),
),
],
));
}
}
|
import { useEffect, useState } from 'react'
import Header from '../../components/Header'
import Head from '../../components/Head'
import Avatar from '../../components/Avatar'
import Feed from '../../components/Feed'
import { useRouter } from 'next/router'
import { User, Role } from '../../scripts/mongo'
import Gql from '../../scripts/gql'
export default function UserPage({ currentUser, pageUser }) {
const router = useRouter()
return (
<>
<Head avatar={pageUser.image} titleContent={pageUser.username} description={`${pageUser}'s Repl Files profile`} />
<Header currentUser={currentUser} />
<div className='flex flex-col items-center justify-center'>
<div className='flex items-center justify-center space-x-7'>
<Avatar source={pageUser.image} large />
{pageUser.username === 'Bookie0' ? <h1 className='hidden md:inline'>@{pageUser.username}</h1> : <h1 className='hidden md:inline'>{pageUser.displayName} | @{pageUser.username}</h1>}
<h1 className='md:hidden inline'>@{pageUser.username}</h1>
</div>
<Feed currentUser={currentUser} user={pageUser} />
</div>
</>
)
}
export async function getServerSideProps({ params, req }) {
const gql = new Gql(process.env.CONNECT_SID);
const id = req.headers["x-replit-user-id"];
let userInDb = await User.findOne({ userId: id }).populate("userRoles");
let pageUserInDb = await User.findOne({ username: params.username }).populate('userRoles');
if (userInDb && !userInDb.banned) {
let userData = await gql.raw({
query: `query user($id: Int!) {
user(id: $id) {
image bio isFollowingCurrentUser
}
}`,
variables: {
id: Number(id)
}
});
let coolRole = userData?.data?.user?.isFollowingCurrentUser;
if (userData?.data?.user?.image) userInDb.image = userData.data.user.image;
if (userData?.data?.user?.bio) userInDb.bio = userData.data.user.bio;
if (coolRole && !userInDb.userRoles.some(x => x.name === "Banned")) {
if (!userInDb.userRoles.some(x => x.name === "Cool Person")) userInDb.userRoles.push(await Role.findOne({ name: "Cool Person" }))
}
userInDb.save();
} else {
return {
redirect: {
destination: '/login'
}
}
}
if (pageUserInDb && !pageUserInDb.banned) {
let pageUserData = await gql.raw({
query: `query user($id: Int!) {
user(id: $id) {
image bio isFollowingCurrentUser
}
}`,
variables: {
id: Number(pageUserInDb.userId)
}
});
let coolRole = pageUserData?.data?.user?.isFollowingCurrentUser;
if (pageUserData?.data?.user?.image) pageUserInDb.image = pageUserData.data.user.image;
if (pageUserData?.data?.user?.bio) pageUserInDb.bio = pageUserData.data.user.bio;
if (coolRole && !pageUserInDb.userRoles.some(x => x.name === "Banned")) {
if (!pageUserInDb.userRoles.some(x => x.name === "Cool Person")) pageUserInDb.userRoles.push(await Role.findOne({ name: "Cool Person" }))
}
pageUserInDb.save();
if (JSON.parse(JSON.stringify(userInDb)).userId == JSON.parse(JSON.stringify(pageUserInDb)).userId) {
return {
redirect: {
destination: '/dashboard'
}
}
} else {
return {
props: {
currentUser: JSON.parse(JSON.stringify(userInDb)),
pageUser: JSON.parse(JSON.stringify(pageUserInDb))
}
}
}
} else {
return {
redirect: {
destination: '/dashboard?type=error&msg=User not found'
}
}
}
}
|
import { createContext, useContext, useEffect, useReducer } from "react"
import { startFetchCategories } from "../actions/mealActions";
import { mealReducer } from "../reducres/mealReducer";
const initialState = {
categories: [],
categoryLoading: false,
categoryError: false,
categorMeals: [],
categoryMealsLoading: false,
categorMealsError: false,
meals: [],
mealsLoading: false,
mealsError: false,
meal: [],
mealLoading: false,
mealError: false
}
const MealContext = createContext({});
export const MealProvider = ({children}) => {
const [state, dispatch] = useReducer(mealReducer, initialState);
useEffect(() => {
startFetchCategories(dispatch);
}, [])
return (
<MealContext.Provider value={{
...state,
dispatch,
startFetchCategories
}}>
{children}
</MealContext.Provider>
)
}
export const useMealContext = () => {
return useContext(MealContext)
}
|
//
// MainViewModel.swift
// MovieSearchApp
//
// Created by 박세웅 on 2022/12/19.
//
import Foundation
import RxSwift
import RxRelay
protocol MainViewModelInput {
func viewDidLoad()
func searchButtonClicked(_ query: String?)
func itemSelected(_ index: Int, in section: CollectionKind)
}
protocol MainViewModelOutput {
var popularMovies: BehaviorRelay<[MoviePage]> { get }
var trendingMovies: BehaviorRelay<[MoviePage]> { get }
var upcomingMovies: BehaviorRelay<[MoviePage]> { get }
var errorOccured: PublishRelay<NetworkError> { get }
var selectedMovieId: BehaviorRelay<Int?> { get }
var search: PublishRelay<String> { get }
}
protocol MainViewModelable: MainViewModelInput, MainViewModelOutput {}
final class MainViewModel: MainViewModelable {
var popularMovies: BehaviorRelay<[MoviePage]> = .init(value: [])
var trendingMovies: BehaviorRelay<[MoviePage]> = .init(value: [])
var upcomingMovies: BehaviorRelay<[MoviePage]> = .init(value: [])
var errorOccured: PublishRelay<NetworkError> = .init()
var selectedMovieId: BehaviorRelay<Int?> = .init(value: nil)
var search: PublishRelay<String> = .init()
let mainViewUseCase: MainViewUseCase
init(_ mainViewUseCase: MainViewUseCase) {
self.mainViewUseCase = mainViewUseCase
}
func viewDidLoad() {
fetchPopularMoviesList()
fetchTrendingMoviesList()
fetchUpcomingMoviesList()
}
func searchButtonClicked(_ query: String?) {
if let query = query {
search.accept(query)
}
}
func itemSelected(_ index: Int, in section: CollectionKind) {
selectedMovieId.accept(matchedMovieItemId(section, index))
}
}
extension MainViewModel {
private func fetchPopularMoviesList() {
_ = mainViewUseCase.executeFetchPopular(media: .movie) { [weak self] result in
switch result {
case .success(let response):
self?.popularMovies.accept(response.movies)
case .failure(let error):
self?.errorOccured.accept(error)
}
}
}
private func fetchTrendingMoviesList() {
_ = mainViewUseCase.executeFetchTrending(media: .movie, timeWindow: .day) { [weak self] result in
switch result {
case .success(let data):
self?.trendingMovies.accept(data.movies)
case .failure(let error):
self?.errorOccured.accept(error)
}
}
}
private func fetchUpcomingMoviesList() {
_ = mainViewUseCase.executeFetchUpcoming(media: .movie) { [weak self] result in
switch result {
case .success(let data):
self?.upcomingMovies.accept(data.movies)
case .failure(let error):
self?.errorOccured.accept(error)
}
}
}
private func matchedMovieItemId(_ section: CollectionKind, _ index: Int) -> Int {
var id: Int? = nil
switch section {
case .popular:
id = popularMovies.value[index].id
case .trending:
id = trendingMovies.value[index].id
case .upcoming:
id = upcomingMovies.value[index].id
}
guard let id = id else {
return -1
}
return id
}
}
|
##### Population structure analaysis
###### 1. PCA analysis using PLINK
```bash
outdir="analysis/structure"
mkdir -p ${outdir}
plink_merged="analysis/qc_merged_data/merged_final_5FID_Fst"
bim_africans="analysis/AFR/africans_snps_specific.bim"
bim_overlapped="analysis/AFR/africans_snps_overlapped.bim"
cut -f2 ${bim_africans} > ${outdir}/snps.africans
cut -f2 ${bim_overlapped} > ${outdir}/snps.overlapped
#extract
# from merged that passed QC
#2773 samples (102 females, 136 males, 2535 ambiguous; 2773 founders) loaded
plink2 --bfile ${plink_merged} \
--extract ${outdir}/snps.africans \
--make-bed \
--out ${outdir}/snps.africans
plink2 --bfile ${plink_merged} \
--extract ${outdir}/snps.overlapped \
--make-bed \
--out ${outdir}/snps.overlapped
#PCA
plink2 --bfile ${outdir}/snps.africans --pca --out ${outdir}/pca_africans
plink2 --bfile ${outdir}/snps.overlapped --pca --out ${outdir}/pca_overlapped
```
###### 2. Plot PCA results
```R
rm(list = ls())
outdir="analysis/structure/"
eigenvec_africans <-read.table(
paste0(outdir,"pca_africans.eigenvec"),header=F)
eigenvec_overlapped <-read.table(
paste0(outdir,"pca_overlapped.eigenvec"),header=F)
eigenval_africans <-read.table(
paste0(outdir,"pca_africans.eigenval"),header=F)
eigenval_overlapped <-read.table(
paste0(outdir,"pca_overlapped.eigenval"),header=F)
ggbg2 <- function() {
points(0,0,pch=16, cex=1e6, col="lightgray")
grid(col="white", lty=1)
}
plotting_pca=function(eigenvec, eigenval, outputfile){
out_png=paste0(outdir,outputfile)
id_orders=order(eigenvec$V1)
png(paste0(outdir,outputfile,"_eigenvec.png"), width = 465, height = 225,
units='mm', res = 300)
plot(eigenvec$V3[id_orders],eigenvec$V4[id_orders],
col=factor(eigenvec$V1[id_orders]),
panel.first=ggbg2(),xlab="PC1", ylab="PC2",
main= "Global ancestry estimation"
)
legend(x = "topright",
legend=levels(factor(eigenvec$V1[id_orders])),
fill=unique(factor(eigenvec$V1[id_orders])),
lwd=0, cex = 1, xpd = TRUE, ncol = 2)
dev.off()
png(paste0(outdir,outputfile,"_eigenval.png"), width = 465, height = 225,
units='mm', res = 300)
plot(eigenval$V1,
panel.first=ggbg2(),
xlab="Eigen value index",
ylab="Eigen value", type='l')
dev.off()
}
plotting_pca(eigenvec_africans, eigenval_africans,
"pca_africans")
plotting_pca(eigenvec_overlapped, eigenval_overlapped,
"pca_overlapped")
```
###### 3. Population stratifications using Structure
```bash
outdir="analysis/structure/"
plink_africans="${outdir}/snps.africans.bed"
plink_overlapped="${outdir}/snps.overlapped.bed"
admixture -s 100 ${plink_africans} 5
mv snps.africans* ${outdir}/
admixture -s 100 ${plink_overlapped} 5
mv snps.overlapped* ${outdir}/
```
###### 4. plot population stratifications results
```R
rm(list = ls())
outdir="analysis/structure/"
#plink_africans="${outdir}/snps.africans.bed"
#plink_overlapped="${outdir}/snps.overlapped.bed"
Q_african=read.table(paste0(outdir,"snps.africans.5.Q")
,header=F)
fam_african=read.table(paste0(outdir,"snps.africans.fam")
,header=F)
Q_overlapped=read.table(paste0(outdir,"snps.overlapped.5.Q")
,header=F)
fam_overlapped=read.table(paste0(outdir,"snps.overlapped.fam")
,header=F)
plot_structure=function(Q, fam, outfile){
out_png=paste0(outdir,outfile)
png(out_png, width = 465, height = 225, units='mm', res = 300)
ordered_index_groups <- order(fam$V1)
populations = as.character(fam$V1[ordered_index_groups])
populations_names=unique(populations)
populations_labels=rep("",length(populations))
j=0;
pos=c()
for (i in 1:length(populations_names)){
#cat(populations_names[i])
index_label=length(which(populations==populations_names[i]))
populations_labels[j+round(index_label/2, digits = 0)] <- populations_names[i]
pos=c(pos,(j+index_label/2))
j=j+index_label
#cat(j)
}
par(mar = c(4, 4, 4, 1))
barplot(t(as.matrix(Q[ordered_index_groups,])),col=rainbow(5),
space=0,border=NA, ylab="Ancestry proportions",xaxt="n")
axis(1,at = pos,labels =populations_names, lwd = 0,las=1)
par(xpd=TRUE)
legend(1, 1.09,
legend=populations_names,
fill=rainbow(5),lwd=0, cex = 1, xpd = TRUE, ncol = 5)
dev.off()
}
plot_structure(Q_african,fam_african,"structure_african.png" )
plot_structure(Q_overlapped, fam_overlapped, "structure_overlapped.png")
```
|
using Auto_Intelligent_Wms.Core.Common.Enum;
using Auto_Intelligent_Wms.Core.Common.Utils;
using Auto_Intelligent_Wms.Core.IServices.IServices;
using Auto_Intelligent_Wms.Core.Model.BaseModel;
using Auto_Intelligent_Wms.Core.Model.Entities;
using Auto_Intelligent_Wms.Core.Model.ImExportTemplate.Area;
using Auto_Intelligent_Wms.Core.Model.ImExportTemplate.WareHouse;
using Auto_Intelligent_Wms.Core.Model.RequestDTO.Area;
using Auto_Intelligent_Wms.Core.Model.RequestDTO.WareHouse;
using Mapster;
using Mask_STK.Core.WebApi.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Auto_Intelligent_Wms.Core.Services.Services
{
public class AreaService : IAreaService
{
private readonly Auto_Inteligent_Wms_DbContext _db;
private readonly ILogger<AreaService> _log;
public readonly IWareHouseService _wareHouseService;
public AreaService(Auto_Inteligent_Wms_DbContext db, ILogger<AreaService> logger,IWareHouseService wareHouseService)
{
_db = db;
_log = logger;
_wareHouseService = wareHouseService;
}
/// <summary>
/// 创建库区信息
/// </summary>
/// <param name="createAreaDTO"></param>
/// <param name="currentUserId"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public async Task<long> CreateAsync([FromBody] CreateAreaDTO createAreaDTO, long currentUserId)
{
if (string.IsNullOrWhiteSpace(createAreaDTO.Code))
{
throw new Exception("The area code parameter is empty");
}
if (string.IsNullOrWhiteSpace(createAreaDTO.Name))
{
throw new Exception("The area name parameter is empty");
}
if (string.IsNullOrWhiteSpace(createAreaDTO.WareHouseCode))
{
throw new Exception("The WareHouseCode parameter is empty");
}
var warehouse = await _wareHouseService.GetWareHouseByCodeAsync(createAreaDTO.WareHouseCode);
if (warehouse == null)
{
throw new Exception("The WareHouseCode does not exist");
}
if (await IsExistAsync(createAreaDTO.Code))
{
throw new Exception("The area already exists");
}
Area area = new Area();
area.Code = createAreaDTO.Code;
area.Name = createAreaDTO.Name;
area.WareHouseId = warehouse.Id;
area.WareHouseCode = createAreaDTO.WareHouseCode;
area.CreateTime = DateTime.Now;
area.Creator = currentUserId;
area.Remark = createAreaDTO.Remark;
area.Status = (int)DataStatus.Normal;
var result = await _db.Areas.AddAsync(area);
await _db.SaveChangesAsync();
return result.Entity.Id;
}
/// <summary>
/// 根据库区id删除库区信息
/// </summary>
/// <param name="id"></param>
/// <param name="currentUserId"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public async Task<long> DelAsync(long id, long currentUserId)
{
if (id <= 0)
{
throw new Exception("The area id parameter is empty");
}
var area = await _db.Areas.Where(m => m.Id == id && m.Status == (int)DataStatus.Normal).SingleOrDefaultAsync();
if (area == null)
{
throw new Exception($"No information found for area,id is {id}");
}
if (await _db.MaterialStocks.AnyAsync(m => m.AreaId == id && m.Status == (int)DataStatus.Normal))
{
throw new Exception("The area is in use and cannot be deleted");
}
if (await _db.Locations.AnyAsync(m => m.AreaId == id && m.Status == (int)DataStatus.Normal))
{
throw new Exception("The area is in use and cannot be deleted");
}
area.Status = (int)DataStatus.Delete;
area.UpdateTime = DateTime.Now;
area.Updator = currentUserId;
return await _db.SaveChangesAsync();
}
/// <summary>
/// 导入
/// </summary>
/// <returns></returns>
public async Task<ActionResult<string>> DownloadTemplateAsync()
{
List<AreaDownloadTemplate> list = new List<AreaDownloadTemplate>();
return await MiniExcelUtil.ExportAsync("下载库区模板", list);
}
/// <summary>
/// 导出
/// </summary>
/// <param name="areaParamsDTO"></param>
/// <returns></returns>
public async Task<ActionResult<string>> ExportAsync([FromQuery] AreaParamsDTO areaParamsDTO)
{
var items = _db.Areas.Where(m => m.Status == (int)DataStatus.Normal).AsNoTracking();
if (!string.IsNullOrWhiteSpace(areaParamsDTO.Code))
{
items = items.Where(m => m.Code.StartsWith(areaParamsDTO.Code));
}
if (!string.IsNullOrWhiteSpace(areaParamsDTO.Name))
{
items = items.Where(m => m.Name.StartsWith(areaParamsDTO.Name));
}
var result = items.Adapt<List<AreaExportTemplate>>();
return await MiniExcelUtil.ExportAsync("库区信息", result);
}
/// <summary>
/// 根据库区code获取库区信息
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public async Task<Area> GetAreaByCodeAsync(string code)
{
if (string.IsNullOrWhiteSpace(code))
{
throw new Exception("The area code parameter is empty");
}
var area = await _db.Areas.Where(m => m.Code.Equals(code) && m.Status == (int)DataStatus.Normal).SingleOrDefaultAsync();
if (area == null)
{
throw new Exception($"No information found for area,code is {code}");
}
return area;
}
/// <summary>
/// 根据codes集合获取库区信息
/// </summary>
/// <param name="codes"></param>
/// <returns></returns>
public async Task<List<Area>> GetAreaByCodesAsync(string codes)
{
var list = new List<Area>();
if (!string.IsNullOrWhiteSpace(codes))
{
var codeList = codes.Split(',').ToList();
list = await _db.Areas.Where(m => codeList.Contains(m.Code) && m.Status == (int)DataStatus.Normal).ToListAsync();
}
return list;
}
/// <summary>
/// 根据库区id获取库区信息
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public async Task<Area> GetAreaByIdAsync(long id)
{
if (id <= 0)
{
throw new Exception("The area id parameter is empty");
}
var area = await _db.Areas.Where(m => m.Id == id && m.Status == (int)DataStatus.Normal).SingleOrDefaultAsync();
if (area == null)
{
throw new Exception($"No information found for area,id is {id}");
}
return area;
}
/// <summary>
/// 根据ids获取库区信息
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public async Task<List<Area>> GetAreaByIdsAsync(string ids)
{
var list = new List<Area>();
if (!string.IsNullOrWhiteSpace(ids))
{
var items = ids.Split(',').ToList();
List<long> idList = items.Select(s => long.Parse(s)).ToList();
list = await _db.Areas.Where(m => idList.Contains(m.Id) && m.Status == (int)DataStatus.Normal).ToListAsync();
}
return list;
}
/// <summary>
/// 查询库区信息
/// </summary>
/// <param name="code"></param>
/// <param name="name"></param>
/// <returns></returns>
public async Task<List<Area>> GetListAsync([FromQuery] AreaParamsDTO areaParamsDTO)
{
var items = _db.Areas.Where(m => m.Status == (int)DataStatus.Normal).AsNoTracking();
if (!string.IsNullOrWhiteSpace(areaParamsDTO.Code))
{
items = items.Where(m => m.Code.StartsWith(areaParamsDTO.Code));
}
if (!string.IsNullOrWhiteSpace(areaParamsDTO.Name))
{
items = items.Where(m => m.Name.StartsWith(areaParamsDTO.Name));
}
return await items.ToListAsync();
}
/// <summary>
/// 查询库区分页信息
/// </summary>
/// <param name="areaParamsDTO"></param>
/// <returns></returns>
public async Task<BasePagination<Area>> GetPaginationAsync([FromQuery] AreaParamsDTO areaParamsDTO)
{
var items = _db.Areas.Where(m => m.Status == (int)DataStatus.Normal).AsNoTracking();
if (!string.IsNullOrWhiteSpace(areaParamsDTO.Code))
{
items = items.Where(m => m.Code.StartsWith(areaParamsDTO.Code));
}
if (!string.IsNullOrWhiteSpace(areaParamsDTO.Name))
{
items = items.Where(m => m.Name.StartsWith(areaParamsDTO.Name));
}
return await PaginationService.PaginateAsync(items, areaParamsDTO.PageIndex, areaParamsDTO.PageSize);
}
/// <summary>
/// 导入
/// </summary>
/// <param name="path"></param>
/// <param name="currentUserId"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public async Task<string> ImportAsync(string path, long currentUserId)
{
var result = MiniExcelUtil.Import<AreaDownloadTemplate>(path).ToList();
if (result == null || result.Count <= 0)
{
throw new Exception("Import data is empty");
}
//判断库区编码有没有空值
if (result.Any(m => string.IsNullOrWhiteSpace(m.Code)))
{
throw new Exception("There is a null value in the imported area code");
}
//判断库区名称有没有空值
if (result.Any(m => string.IsNullOrWhiteSpace(m.Name)))
{
throw new Exception("There is a null value in the imported area name");
}
//判断仓库编码有没有空值
if (result.Any(m => string.IsNullOrWhiteSpace(m.WareHouseCode)))
{
throw new Exception("There is a null value in the imported area wareHouseCode");
}
//判断库区编码是否有重复
if (result.GroupBy(m => m.Code).Any(group => group.Count() > 1))
{
throw new Exception("area code duplication");
}
//判断库区是否存在
var areaCodeList = result.Select(m => m.Code).ToList();
var areaItems = await _db.Areas.Where(m => areaCodeList.Contains(m.Code) && m.Status == (int)DataStatus.Normal).ToListAsync();
if (areaItems != null && areaItems.Count > 0)
{
throw new Exception("area code already exists");
}
//判断仓库编码是否存在
var wareHouseCodeList = result.Select(m => m.WareHouseCode).Distinct().ToList();
var wareHouseitems = await _db.WareHouses.Where(m => wareHouseCodeList.Contains(m.Code) && m.Status == (int)DataStatus.Normal).Select(x => new { x.Id, x.Code }).ToListAsync();
if (wareHouseitems == null || wareHouseitems.Count < wareHouseCodeList.Count)
{
throw new Exception("wareHouse code does not exists");
}
var data = result.Join(wareHouseitems, i => i.WareHouseCode, o => o.Code, (i, o) => new { i, o }).Select(m => new Area
{
Name = m.i.Name,
Code = m.i.Code,
Status = (int)DataStatus.Normal,
WareHouseCode = m.i.WareHouseCode,
WareHouseId = m.o.Id,
Creator = currentUserId,
Remark = m.i.Remark,
CreateTime = DateTime.Now,
});
await _db.BulkInsertAsync(data);
await _db.SaveChangesAsync();
return "Import Area successful";
}
/// <summary>
/// 根据库区编码判断 该库区是否存在
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
public async Task<bool> IsExistAsync(string code)
{
if (string.IsNullOrWhiteSpace(code))
{
throw new Exception("The area code parameter is empty");
}
var area = await _db.Areas.Where(m => m.Code.Equals(code) && m.Status == (int)DataStatus.Normal).SingleOrDefaultAsync();
if (area == null)
{
return false;
}
return true;
}
}
}
|
package wns.controllers;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import wns.constants.Filter;
import wns.constants.Messages;
import wns.dto.ClientDTO;
import wns.dto.PageDataDTO;
import wns.entity.Client;
import wns.services.ClientsService;
import wns.services.PageableFilterService;
import wns.services.RoleContactService;
import wns.utils.ResponseHandler;
import java.util.List;
import java.util.Optional;
@Controller
@RequestMapping("clients")
@AllArgsConstructor
public class ClientsController {
private final ClientsService clientsService;
private final PageableFilterService pageableFilterService;
@GetMapping()
public String showPage(@RequestParam(value = "page", required = false) Optional<Integer> page,
@RequestParam(value = "size", required = false) Optional<Integer> size,
Model model) {
Page<Object> paginated_list = pageableFilterService.getListData(new PageDataDTO(page,size,Filter.ALL_CLIENTS));
pageableFilterService.addPageNumbers(paginated_list, model);
model.addAttribute("list_clients", paginated_list);
return "clients";
}
@PostMapping()
public String findClientsByName(@RequestParam String username, Model model) {
List<ClientDTO> listByName = clientsService.findListByName(username);
model.addAttribute("list_clients", listByName);
return "clients";
}
@GetMapping("/create")
public String creatingClient(Model model) {
model.addAttribute("client", new ClientDTO());
return "create_client";
}
@PostMapping("/create")
@ResponseBody
public ResponseEntity<Object> create(@RequestBody ClientDTO client) {
Messages message = clientsService.saveClient(client);
return ResponseHandler.generateResponse(message);
}
@GetMapping("/edit/{id}")
public String showClientForUpdate(@RequestParam(value = "page", required = false) Optional<Integer> page,
@RequestParam(value = "size", required = false) Optional<Integer> size,
@PathVariable("id") long id, Model model) {
Page<Object> paginated_list = pageableFilterService.getListData(new PageDataDTO(page,size,Filter.PROJECTS_BY_CLIENTS,id));
pageableFilterService.addPageNumbers(paginated_list, model);
Client client = clientsService.getById(id);
model.addAttribute("client", client);
model.addAttribute("list_projects", paginated_list);
return "create_client";
}
@PostMapping("/edit/{id}")
public ResponseEntity<Object> updateClient(@PathVariable("id") long id, @RequestBody Client client) {
client.setId(id);
Messages messages = clientsService.updateClient(client);
return ResponseHandler.generateResponse(messages);
}
@PostMapping("/delete/{id}")
public String deleteClient(@PathVariable("id") long id) {
clientsService.delete(id);
return "redirect:/clients";
}
}
|
var express = require('express');
var router = express.Router();
import nomineeApplicationSurveyController from '../controllers/nomineeApplicationSurvey';
/*
* Method: GET
* Parameter: None
* Return: JSON of nomineeApplicationSurvey
* Uses: To display nomineeApplicationSurvey
* URL:localhost:3000/nominee-application-surveys
*/
router.get('/', nomineeApplicationSurveyController.fetch_all_nominee_application_survey);
/*
* Method: GET
* Parameter: id
* Return: JSON of nomineeApplicationSurvey by id
* Uses: To display nomineeApplicationSurvey by id
* URL:localhost:3000/nominee-application-surveys/1
*/
router.get('/:id', nomineeApplicationSurveyController.fetch_nominee_application_survey_by_id);
/*
* Method: POST
* Body Parameters : nominee_application_id, award_survey_question_id, award_survey_option_id, status
* Return: JSON consist payload as object of created nomineeApplicationSurvey
* Uses: To save nomineeApplicationSurvey
* URL:localhost:3000/nominee-application-surveys
*/
router.post('/', nomineeApplicationSurveyController.create_new_nominee_application_survey);
/*
* Method: POST
* Body Parameters : nominee_application_id, questionOptions
* Return: JSON consist payload as array of nomineeApplicationSurvey
* Uses: To bulk save nomineeApplicationSurvey
* URL:localhost:3000/nominee-application-surveys/bulk
*/
router.post('/bulk', nomineeApplicationSurveyController.bulk_create_nominee_application_survey);
router.get('/nominated-application/:id', nomineeApplicationSurveyController.fetch_nominee_application_survey_by_nominee_application_id);
module.exports = router;
|
#include "lists.h"
/**
* list_len - find num of element in linked list
* @h: linked list
* Return: num of element
*/
size_t list_len(const list_t *h)
{
size_t elements = 0;
while (h)
{
elements++;
h = h->next;
}
return (elements);
}
|
/**
* 문제3
* 스탑워치 구현을 보고 ui 상태 interface 설계를 개선해주세요.
* https://online-stopwatch.ko.downloadastro.com/tools/
* */
// 예시 인터페이스이고, 본인이 생각하는 더 나은 인터페이스로 바꾸셔도 됩니다.
interface ButtonStyle {
color: string;
}
interface StopWatchState {
state: 'ready' | 'running' | 'stopped';
startButton?: {
icon: 'startButton';
style: ButtonStyle;
};
pauseButton?: {
icon: 'pauseButton';
style: ButtonStyle;
};
resetButton?: {
icon: 'resetButton';
style: ButtonStyle;
};
addLapButton?: {
icon: 'addLapButton';
style: ButtonStyle;
};
lappedTimeList?: string[];
timeFormStart: string;
timeFormLastLap: string;
}
|
/*
* Created by Iosif Haidu on 29/11/2021.
* Copyright (c) 2021 Iosif Haidu. All rights reserved.
*
* Description: Format values for cell layout
*/
#pragma once
#include "internal/gui/layout/format/alignment.h"
#include <tuple>
namespace GUI::Layout {
template <typename T>
class Format {
public:
Format()
: padM{}
, marginHorizM{}
, marginVertM{}
, horizAlignM{HorizAlign::CENTER}
, vertAlignM{VertAlign::CENTER}
, heightM{}
, widthM{}
{}
Format(Format const& rFormatP)
{
*this = rFormatP;
}
void setPad(T valueP)
{
padM = valueP;
}
T getPad() const
{
return padM;
}
void setMarginHoriz(T leftP, T rightP)
{
std::get<0>(marginHorizM) = leftP;
std::get<1>(marginHorizM) = rightP;
}
std::tuple<T, T> getMarginHoriz() const
{
return marginHorizM;
}
void setMarginVert(T topP, T bottomP)
{
std::get<0>(marginVertM) = topP;
std::get<1>(marginVertM) = bottomP;
}
std::tuple<T, T> getMarginVert() const
{
return marginVertM;
}
void setAlignHoriz(HorizAlign alignP)
{
horizAlignM = alignP;
}
HorizAlign getHorizAlign() const
{
return horizAlignM;
}
void setAlignVert(VertAlign alignP)
{
vertAlignM = alignP;
}
VertAlign getAlignVert() const
{
return vertAlignM;
}
void setHeight(T valueP)
{
heightM = valueP;
}
T getHeight() const
{
return heightM;
}
void setWidth(T valueP)
{
widthM = valueP;
}
T getWidth() const
{
return widthM;
}
Format<T>& operator=(Format<T> const& rValueP)
{
if (&rValueP != this) {
padM = rValueP.padM;
marginHorizM = rValueP.marginHorizM;
marginVertM = rValueP.marginVertM;
horizAlignM = rValueP.horizAlignM;
vertAlignM = rValueP.vertAlignM;
heightM = rValueP.heightM;
widthM = rValueP.widthM;
}
return *this;
}
protected:
T padM;
std::tuple<T, T> marginHorizM;
std::tuple<T, T> marginVertM;
HorizAlign horizAlignM;
VertAlign vertAlignM;
T heightM;
T widthM;
};
} // namespace Gui::Layout
|
package edu.web.persistence;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import static edu.web.domain.User.Entry.*;
import edu.web.domain.User;
public class UserDaoImpl implements UserDao {
private DataSource ds;
// singleton 패턴
private static UserDaoImpl instance = null;
private UserDaoImpl() {
ds = DataSourceUtil.getDataSource();
};
public static UserDaoImpl getInstance() {
if (instance == null) {
instance = new UserDaoImpl();
}
return instance;
}
@Override
public int update(int points, String userId) {
System.out.println("userDaoImple.update(" + points + ", " + userId + ") 메서드 호출");
int result = 0;
Connection conn = null;
PreparedStatement pstmt = null;
try {
// Connection Pool에서 Connection 객체를 빌려옴.
conn = ds.getConnection();
// DB에서 실행할 SQL 문장을 완성
pstmt = conn.prepareStatement(SQL_UPDATE_USER_POINTS);
System.out.println(SQL_UPDATE_USER_POINTS);
pstmt.setInt(1, points); // SQL의 첫번째 ?를 points(정수)로 대체.
pstmt.setString(2, userId); // SQL의 두변째 ?를 userId(문자열)로 대체.
// SQL 문장 실행
result = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 사용했던 리소스 반환 - Connection 객체를 Connection Pool로 반환.
try {
DataSourceUtil.close(conn, pstmt);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
@Override
public List<User> read() {
List<User> list = new ArrayList<User>();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = ds.getConnection();
pstmt = conn.prepareStatement(SQL_SELECT_ALL);
rs = pstmt.executeQuery();
while(rs.next()) {
String userId = rs.getString(COL_USERID);
String pwd = rs.getString(COL_PWD);
String email = rs.getString(COL_EMAIL);
int points = rs.getInt(COL_POINTS);
list.add(new User(userId, pwd, email, points));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
DataSourceUtil.close(conn, pstmt, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
@Override
public int create(User user) {
int result = 0;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = ds.getConnection();
pstmt = conn.prepareStatement(SQL_INSERT_USER);
pstmt.setString(1, user.getUserid());
pstmt.setString(2, user.getPwd());
pstmt.setString(3, user.getEmail());
result = pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
DataSourceUtil.close(conn, pstmt);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
@Override
public User read(String userid) {
User user = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = ds.getConnection();
pstmt = conn.prepareStatement(SQL_SELECT_BY_USERID);
pstmt.setString(1, userid);
rs = pstmt.executeQuery();
if(rs.next()) {
String userId = rs.getString(COL_USERID);
String pwd = rs.getString(COL_PWD);
String email = rs.getString(COL_EMAIL);
int points = rs.getInt(COL_POINTS);
user = new User(userId, pwd, email, points);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
DataSourceUtil.close(conn, pstmt);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return user;
}
}
|
import FlexY from 'component/atom/FlexY';
import FlexX from 'component/atom/FlexX';
import styled, { css } from 'styled-components';
import GlobalSearch from 'component/organism/GlobalSearch';
import AfreecaTVLogo from 'asset/logo.svg';
import { Color, ColorUI, Palette } from 'style/variable/color';
import Button from 'component/atom/Button';
import PopoverTip from 'asset/icon/ico_popovertip.svg';
import { Transition } from 'style/variable/transition';
import { IconBroadcast, IconBell, Icon3Dot, Icon4Dot } from 'lib/icon';
import { Length } from 'style/variable/spacing';
import { ZIndex } from 'style/variable/zIndex';
import GNB from 'component/organism/GNB';
import TopButton from 'component/morecule/TopButton';
import { useNavigate } from 'react-router-dom';
interface IProps {
children: JSX.Element;
}
const BaseLayout = ({ children }: IProps) => {
const navigate = useNavigate();
const handleClickLoginButton = () => {
navigate('/login');
};
return (
<>
<Header>
<LeftInfo>
<Logo>
<a href="/">afreeca tv</a>
</Logo>
<GlobalSearch />
</LeftInfo>
<Util>
<UtilButton src={IconBroadcast} popover={'방송하기'}>
방송하기
</UtilButton>
<UtilButton src={IconBell} popover={'알림'}>
알림
</UtilButton>
<LoginButton onClick={handleClickLoginButton}>로그인</LoginButton>
<UtilButton src={Icon3Dot} popover={'설정'}>
설정
</UtilButton>
<UtilButton src={Icon4Dot} popover={'더보기'}>
더보기
</UtilButton>
</Util>
</Header>
<Content>
<GNB />
<Main>{children}</Main>
</Content>
<TopButton />
<Footer>
<FooterSection>
<FooterMenus>
<li>
<a href="/">회사소개</a>
</li>
<li>
<a href="">서비스 소개</a>
</li>
<li>
<a href="">광고안내</a>
</li>
<li>
<a href="">인재채용</a>
</li>
<li>
<a href="">이용약관</a>
</li>
<li>
<a href="">개인정보처리방침</a>
</li>
<li>
<a href="">청소년보호정책</a>
</li>
<li>
<a href="">운영정책</a>
</li>
<li>
<a href="">권리침해신고센터</a>
</li>
<li>
<a href="">오픈스튜디오</a>
</li>
<li>
<a href="">Developers</a>
</li>
<li>
<a href="">주요서비스</a>
</li>
<li>
<select name="" id="">
<option value="">패밀리 사이트</option>
</select>
</li>
</FooterMenus>
</FooterSection>
<FooterSection>
<FooterInfos>
<li>(주)아프리카TV</li>
<li>대표이사 : 정찬용</li>
<li>사업자번호 : 220-81-10886</li>
<li>통신판매번호 제2010-경기성남-0834</li>
<li>사업자 정보 확인</li>
<li>호스팅 제공자 : ㈜아프리카TV</li>
<li>
주소 : 경기도 성남시 분당구 판교로228번길 15 판교세븐밴처밸리 1단지 2동 ㈜아프리카TV(삼평동)
</li>
<li>FAX : 031-622-8008</li>
<li>afreecaTV@afreecatv.com (1688-7022)</li>
</FooterInfos>
</FooterSection>
<FooterSection>
<Copyright>ⓒ AfreecaTV Corp.</Copyright>
</FooterSection>
</Footer>
</>
);
};
export default BaseLayout;
const Header = styled.header`
position: fixed;
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
height: ${Length.Header.Height};
padding: 0 28px;
border-bottom: 1px solid ${ColorUI.LayoutDivider};
background-color: ${ColorUI.Background};
z-index: ${ZIndex.Header};
`;
const LeftInfo = styled(FlexX)`
align-items: center;
column-gap: 60px;
`;
const Util = styled(FlexX)`
column-gap: 16px;
`;
const UtilButton = styled(Button)<{ src: React.FunctionComponent<React.SVGAttributes<SVGElement>>; popover?: string }>`
background-image: ${(props) => `url(${props.src})`};
width: 40px;
height: 40px;
background-size: 100%;
border-radius: 20px;
transition: ${Transition.Default};
position: relative;
&:hover {
background-color: ${Palette.Gray_f5f6f7};
&::after {
visibility: unset;
opacity: 1;
left: 50%;
transform: translateX(-50%);
}
&::before {
visibility: unset;
opacity: 1;
left: 50%;
transform: translateX(-50%);
}
}
${(props) =>
props.popover
? css`
&::after,
&::before {
position: absolute;
left: 50%;
transform: translateX(-60%);
transition: inherit;
opacity: 0;
visibility: hidden;
}
&::after {
content: '${props.popover}';
display: flex;
align-items: center;
justify-content: center;
bottom: -32px;
padding: 5px 10px;
font-size: 12px;
font-weight: 700;
color: white;
white-space: nowrap;
background-color: #373d40;
}
&::before {
content: '';
bottom: -8px;
display: block;
width: 100%;
height: 15px;
background-image: url(${PopoverTip});
background-position: 50% 100%;
background-repeat: no-repeat;
background-size: 10px 5px;
}
`
: undefined};
`;
const Content = styled(FlexX)``;
const Main = styled(FlexY).attrs({ as: 'main' })`
width: 100%;
/* padding-left: calc(46px + 210px); */
padding-left: ${Length.SideBar.Width};
/* padding-top: calc(32px + 80px); */
padding-top: ${Length.Header.Height};
min-height: calc(100vh - ${Length.Header.Height});
`;
const Logo = styled(FlexX).attrs({ as: 'h1' })`
a {
background-image: ${`url(${AfreecaTVLogo})`};
background-repeat: no-repeat;
background-position: center center;
background-size: contain;
width: 157px;
height: 50px;
color: transparent;
font-size: 0;
}
`;
const LoginButton = styled(FlexX).attrs({ as: 'button' })`
align-items: center;
justify-content: center;
font-size: 15px;
color: ${Color.Clearly};
border: 0;
padding: 0 6px;
height: 40px;
background-color: transparent;
transition: ${Transition.Default};
&:hover {
background-color: ${Palette.Gray_f5f6f7};
border-radius: 6px;
}
`;
const Footer = styled(FlexY).attrs({ as: 'footer' })`
align-items: center;
border-top: 1px solid ${Palette.Gray_e5e5e5};
margin-left: ${Length.SideBar.Width};
padding-top: 25px;
padding-bottom: 30px;
row-gap: 12px;
`;
const FooterSection = styled(FlexX).attrs({ as: 'section' })`
/* align-items: center;
justify-content: center; */
`;
const FooterMenus = styled(FlexX).attrs({ as: 'ul' })`
flex-wrap: wrap;
column-gap: 12px;
align-items: center;
justify-content: center;
a {
color: #666666;
font-size: 14px;
letter-spacing: -1px;
}
`;
const FooterInfos = styled(FlexX).attrs({ as: 'ul' })`
flex-wrap: wrap;
align-items: center;
justify-content: center;
column-gap: 8px;
row-gap: 6px;
width: 800px;
li,
a {
font-size: 11px;
color: ${Palette.Gray8};
}
`;
const Copyright = styled.p`
font-size: 12px;
font-weight: 900;
color: ${Palette.Gray_5f5f5f};
`;
|
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from './prisma.service';
import { CreateProdutoDto} from './create-produto.dto'
import { UpdateProdutoDto } from './update-produto.dto'
@Injectable()
export class ProdutoService {
constructor(private readonly prisma: PrismaService) {}
async create(createProdutoDto: CreateProdutoDto) {
return this.prisma.produto.create({ data: createProdutoDto });
}
async findAll() {
return this.prisma.produto.findMany();
}
async findOne(id: number) {
const produto = await this.prisma.produto.findUnique({ where: { id } });
if (!produto) {
throw new NotFoundException(`Produto com id ${id} não encontrado`);
}
return produto;
}
async update(id: number, updateProdutoDto: UpdateProdutoDto) {
await this.findOne(id);
return this.prisma.produto.update({
where: { id },
data: updateProdutoDto,
});
}
async remove(id: number) {
await this.findOne(id);
return this.prisma.produto.delete({ where: { id } });
}
}
|
//
// ChooseProfileImageView.swift
// BlockMe
//
// Created by Emily Zhang on 10/27/22.
//
import SwiftUI
import PhotosUI
struct ChooseProfileImageView: View {
@EnvironmentObject var appViewModel: AppViewModel
var email: String
var password: String
var firstName: String
var lastName: String
var phoneNumber: String
var venmoHandle: String
@State private var showSheet = false
@State private var showErrorAlert = false
@State private var error: String = ""
@State private var pickerResult: [UIImage] = []
@State private var loading: Bool = false
var body: some View {
ZStack {
Color("BlockMe Background").ignoresSafeArea()
VStack {
Group {
Text("Hello \(firstName)").font(.medLarge).padding(.top, 20).padding(.bottom, 5)
Text("You are almost there. Upload a profile photo").font(.regMed).frame(maxWidth: 352)}.frame(alignment: .top)
Spacer()
Image(uiImage: self.pickerResult.first ?? UIImage())
.resizable()
.frame(width: 200, height: 200)
.background(Color.black.opacity(0.2))
.aspectRatio(contentMode: .fill)
.clipShape(Circle())
Button(action: {
showSheet = true
}) {
Text("Choose Image")
}
Spacer()
Button(action: {
guard let image = self.pickerResult.first else {
error = "No profile image selected."
showErrorAlert = true
return
}
loading = true
DispatchQueue.main.async {
appViewModel.signUp(email: email, password: password, firstName: firstName, lastName: lastName, venmoHandle: venmoHandle, phoneNumber: phoneNumber, profileImage: image) { errorMsg in
if let errorMsg = errorMsg {
error = errorMsg
showErrorAlert = true
loading = false
}
}
}
}) {
Text("Create Account").font(.medSmall)
}
.buttonStyle(RedButton())
.disabled(loading)
Spacer()
}
.edgesIgnoringSafeArea(.bottom)
.sheet(isPresented: $showSheet) {
PhotoPicker(pickerResult: $pickerResult,
isPresented: $showSheet)
}
.alert(error, isPresented: $showErrorAlert) {
Button("Ok", role: .cancel) {
showErrorAlert = false
}
}
if loading {
Color.gray.opacity(0.5).ignoresSafeArea()
LoadingSpinner()
}
}
}
}
|
/*
Authors: Luke Bryant, Bella Henslee, Samuel Choi, Raphe Prince
Assignment Title: Final Project - Tetris
Assignment Description: Create a Tetris Game
Due Date: 5/4/2023
Date Created: 4/15/2023
Date Modified: 5/4/2023
*/
#include "font.h"
void letter::init(string fname){
//open file to get data for letter
ifstream input;
input.open(fname);
assert(input);
//this gets the size of the letter in the array and builds the array
input >> row >> col;
for(int r = 0; r < row; r++){
for (int c = 0; c < col; c++){
input >> data[r][c];
}
}
input.close();
}
void letter::display(ostream& out){
//this outputs the letter to the chosen ostream
//(not onto the plotter)
for(int r = 0; r < row; r++){
for(int c = 0; c < col; c++){
if(data[r][c]== '1'){
out << data[r][c];
}
else{
out << ' ';
}
}
out << endl;
}
}
void letter::draw(int n, point p, SDL_Plotter& g, color letterColor){
//plot the letter onto the plotter based on the size, location, and color chosen
for(int r = 0; r < row; r++){
for(int c = 0; c < col; c++){
if(data[r][c] == '1'){
for(int xOff = 0; xOff < n; xOff++){
for(int yOff = 0; yOff < n; yOff++){
g.plotPixel(xOff + p.x + c * n, yOff + p.y + r * n,letterColor);
}
}
}
}
}
}
Font::Font(){
//open the files and initialize the letters
string fname;
for(char c = 'A'; c <= 'Z'; c++){
fname = "font\\";
fname += c;
fname += ".txt";
data[c].init(fname);
}
//do the same for the each number
for(char c = '0'; c <= '9'; c++){
fname = "font\\";
fname += c;
fname += ".txt";
data[c].init(fname);
}
//set the initial location of the letters to (0,0) and size as 1
loc.x = 0;
loc.y = 0;
size = 1;
}
void Font::setLoc(point p){
//sets the location of the font to p
loc = p;
}
void Font::setSize(int n){
//sets the size of the font only if it is greater than or equal to 1
if(n >= 1){
size = n;
}
}
void Font::display(char c, ostream& out){
//displays the character to the ostream chosen
data[c].display(out);
}
void Font::draw(char c, SDL_Plotter& g, color shade){
//calls the draw function for the character c
data[c].draw(size,loc, g, shade);
}
void Font::draw(string word, SDL_Plotter& g, color shade){
//calls the draw function for each letter in the inputted string
for(int i = 0; i < word.size(); i++){
draw(word.at(i), g, shade);
loc.x += size * 9;
}
}
|
package com.example.todobackend.data;
import org.springframework.data.annotation.PersistenceCreator;
import javax.persistence.*;
import java.util.UUID;
@Entity
@Table(name = "TODO")
public class TodoEntity {
private Boolean completed;
private String title;
@Column(name = "slot")
private Integer order;
@Id
@GeneratedValue
private UUID id;
@PersistenceCreator
public TodoEntity(UUID id, String title, Boolean completed, Integer order) {
this.id = id;
this.title = title;
this.completed = completed;
this.order = order;
}
@PersistenceCreator
public TodoEntity(String title, Integer order) {
this.id = UUID.randomUUID();
this.title = title;
this.completed = false;
this.order = order;
}
protected TodoEntity() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Boolean isCompleted() {
return completed;
}
public void setCompleted(Boolean completed) {
this.completed = completed;
}
public Integer getOrder() {
return order;
}
public void setOrder(Integer order) {
this.order = order;
}
public void setId(UUID id) {
this.id = id;
}
public UUID getId() {
return id;
}
}
|
//
// Day13Description.swift
// aoc2015
//
// Created by Andrew McKnight on Dec 4, 2022.
//
/**
## --- Day 13: Knights of the Dinner Table ---
In years past, the holiday feast with your family hasn't gone so well.
Not everyone gets along! This year, you resolve, will be different.
You're going to find the *optimal seating arrangement* and avoid all
those awkward conversations.
You start by writing up a list of everyone invited and the amount their
happiness would increase or decrease if they were to find themselves
sitting next to each other person. You have a circular table that will
be just big enough to fit everyone comfortably, and so each person will
have exactly two neighbors.
For example, suppose you have only four attendees planned, and you <span
title="Finding a method to calculate happiness units is left as an exercise for the reader.">calculate</span>
their potential happiness as follows:
Alice would gain 54 happiness units by sitting next to Bob.
Alice would lose 79 happiness units by sitting next to Carol.
Alice would lose 2 happiness units by sitting next to David.
Bob would gain 83 happiness units by sitting next to Alice.
Bob would lose 7 happiness units by sitting next to Carol.
Bob would lose 63 happiness units by sitting next to David.
Carol would lose 62 happiness units by sitting next to Alice.
Carol would gain 60 happiness units by sitting next to Bob.
Carol would gain 55 happiness units by sitting next to David.
David would gain 46 happiness units by sitting next to Alice.
David would lose 7 happiness units by sitting next to Bob.
David would gain 41 happiness units by sitting next to Carol.
Then, if you seat Alice next to David, Alice would lose `2` happiness
units (because David talks so much), but David would gain `46` happiness
units (because Alice is such a good listener), for a total change of
`44`.
If you continue around the table, you could then seat Bob next to Alice
(Bob gains `83`, Alice gains `54`). Finally, seat Carol, who sits next
to Bob (Carol gains `60`, Bob loses `7`) and David (Carol gains `55`,
David gains `41`). The arrangement looks like this:
+41 +46
+55 David -2
Carol Alice
+60 Bob +54
-7 +83
After trying every other seating arrangement in this hypothetical
scenario, you find that this one is the most optimal, with a total
change in happiness of `330`.
What is the *total change in happiness* for the optimal seating
arrangement of the actual guest list?
*/
public enum Day13: String {
case sample = """
lice would gain 54 happiness units by sitting next to Bob.
Alice would lose 79 happiness units by sitting next to Carol.
Alice would lose 2 happiness units by sitting next to David.
Bob would gain 83 happiness units by sitting next to Alice.
Bob would lose 7 happiness units by sitting next to Carol.
Bob would lose 63 happiness units by sitting next to David.
Carol would lose 62 happiness units by sitting next to Alice.
Carol would gain 60 happiness units by sitting next to Bob.
Carol would gain 55 happiness units by sitting next to David.
David would gain 46 happiness units by sitting next to Alice.
David would lose 7 happiness units by sitting next to Bob.
David would gain 41 happiness units by sitting next to Carol.
"""
case input = """
Alice would lose 57 happiness units by sitting next to Bob.
Alice would lose 62 happiness units by sitting next to Carol.
Alice would lose 75 happiness units by sitting next to David.
Alice would gain 71 happiness units by sitting next to Eric.
Alice would lose 22 happiness units by sitting next to Frank.
Alice would lose 23 happiness units by sitting next to George.
Alice would lose 76 happiness units by sitting next to Mallory.
Bob would lose 14 happiness units by sitting next to Alice.
Bob would gain 48 happiness units by sitting next to Carol.
Bob would gain 89 happiness units by sitting next to David.
Bob would gain 86 happiness units by sitting next to Eric.
Bob would lose 2 happiness units by sitting next to Frank.
Bob would gain 27 happiness units by sitting next to George.
Bob would gain 19 happiness units by sitting next to Mallory.
Carol would gain 37 happiness units by sitting next to Alice.
Carol would gain 45 happiness units by sitting next to Bob.
Carol would gain 24 happiness units by sitting next to David.
Carol would gain 5 happiness units by sitting next to Eric.
Carol would lose 68 happiness units by sitting next to Frank.
Carol would lose 25 happiness units by sitting next to George.
Carol would gain 30 happiness units by sitting next to Mallory.
David would lose 51 happiness units by sitting next to Alice.
David would gain 34 happiness units by sitting next to Bob.
David would gain 99 happiness units by sitting next to Carol.
David would gain 91 happiness units by sitting next to Eric.
David would lose 38 happiness units by sitting next to Frank.
David would gain 60 happiness units by sitting next to George.
David would lose 63 happiness units by sitting next to Mallory.
Eric would gain 23 happiness units by sitting next to Alice.
Eric would lose 69 happiness units by sitting next to Bob.
Eric would lose 33 happiness units by sitting next to Carol.
Eric would lose 47 happiness units by sitting next to David.
Eric would gain 75 happiness units by sitting next to Frank.
Eric would gain 82 happiness units by sitting next to George.
Eric would gain 13 happiness units by sitting next to Mallory.
Frank would gain 77 happiness units by sitting next to Alice.
Frank would gain 27 happiness units by sitting next to Bob.
Frank would lose 87 happiness units by sitting next to Carol.
Frank would gain 74 happiness units by sitting next to David.
Frank would lose 41 happiness units by sitting next to Eric.
Frank would lose 99 happiness units by sitting next to George.
Frank would gain 26 happiness units by sitting next to Mallory.
George would lose 63 happiness units by sitting next to Alice.
George would lose 51 happiness units by sitting next to Bob.
George would lose 60 happiness units by sitting next to Carol.
George would gain 30 happiness units by sitting next to David.
George would lose 100 happiness units by sitting next to Eric.
George would lose 63 happiness units by sitting next to Frank.
George would gain 57 happiness units by sitting next to Mallory.
Mallory would lose 71 happiness units by sitting next to Alice.
Mallory would lose 28 happiness units by sitting next to Bob.
Mallory would lose 10 happiness units by sitting next to Carol.
Mallory would gain 44 happiness units by sitting next to David.
Mallory would gain 22 happiness units by sitting next to Eric.
Mallory would gain 79 happiness units by sitting next to Frank.
Mallory would lose 16 happiness units by sitting next to George.
"""
}
|
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from waiter.apps.home.forms import ContactForm, LoginForm
from django.core.mail import EmailMultiAlternatives #Enviamos html
from django.contrib.auth import login, logout, authenticate
from django.http import HttpResponseRedirect
from waiter.settings import LOGIN_URL, LOGIN_REDIRECT_URL
from django.contrib.auth.decorators import login_required
from waiter.apps.producto.models import Producto
# Create your views here.
#Vista con render_to_response
#def index_view(request):
# return render_to_response('home/index.html', context_instance = RequestContext(request))
#Vista con render
def index_view(request):
if request.user.is_authenticated():
return render(request, 'home/inicio.html')
else:
# Se redirecciona al carousel
return render(request, 'home/index.html')
def carousel_view(request):
return render(request, 'base/carousel.html')
def about_view(request):
mensaje = "A cerca de.."
ctx = {'msg':mensaje}
return render(request, 'home/about.html',ctx)
def contact_view(request):
info_enviado = False
email = ""
titulo = ""
texto = ""
if request.method == "POST":
formulario = ContactForm(request.POST)
if formulario.is_valid():
info_enviado = True
email = formulario.cleaned_data['Email']
titulo = formulario.cleaned_data['Titulo']
texto = formulario.cleaned_data['Texto']
#######
#CONFIGURACION DE MENSAJE GMAIL
to_admin= "mp.dianalexa@gmail.com"
html_content = "Informacion recibida <br> MENSAJE <br> %s"%(texto)
msg = EmailMultiAlternatives('Correo de contacto', html_content,'from@server.com', [to_admin])
msg.attach_alternative(html_content,'text/html')
msg.send()
#######
else:
formulario = ContactForm()
ctx = {"form":formulario, 'email':email, 'titulo':titulo, 'texto':texto, 'info_enviado':info_enviado}
return render(request, "home/contact.html",ctx)
@login_required(login_url=LOGIN_URL)
def panel_administracion_view(request):
ctx= {'sidebar':'administracion'}
return render(request, 'home/panel_administracion/panel_administracion.html', ctx)
@login_required(login_url=LOGIN_URL)
#CONFIG
def configurations_view(request):
ctx= {'sidebar':'administracion'}
return render(request, 'home/panel_administracion/configurations.html',ctx)
|
<?php
declare(strict_types=1);
/**
* Create a new connection to database.
*/
class DB
{
private mysqli $conn;
public mysqli_stmt $stmt;
/**
* Connect to a database. Credentials are automatically retrieved from global $settings.
* Create a new instance like so
* $conn = new DB();
* @see __destruct method. It automatically disconnects form the database when this instance gets out of scope.
* @param string $database name
* @throws mysqli_sql_exception on failed connection
*/
public function __construct(string $database)
{
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$hostname = $_ENV["DB_HOSTNAME"];
$username = $_ENV["DB_USERNAME"];
$password = $_ENV["DB_PASSWORD"];
# TODO: remove "svommer_" from table names in database
$this->conn = new mysqli($hostname, $username, $password, "svommer_" . $database);
if (!$this->conn->set_charset("utf8")) {
throw new mysqli_sql_exception("Failed to set charset");
}
}
public function prepare(string $sql)
{
$this->stmt = $this->conn->prepare($sql);
if (!$this->stmt) {
throw new mysqli_sql_exception("Could not prepare statement");
}
}
public function bind_param(string $types, &$var1, &...$_)
{
$this->stmt->bind_param($types, $var1, ...$_);
if (!$this->stmt) {
throw new mysqli_sql_exception("Could not bind params");
}
}
public function execute()
{
if (!$this->stmt->execute()) {
throw new mysqli_sql_exception("Could not execute statement");
}
}
public function store_result()
{
if (!$this->stmt->store_result()) {
throw new mysqli_sql_exception("Could not store result");
}
}
public function num_rows(): int
{
return $this->stmt->num_rows();
}
/**
* Execute @param $sql and return the result in an array.
*
* @param string $sql query / statement
* @param string $types data types for parameter binding in prepared statement
* @param mixed $var1
* @param mixed ...$_
* @return array results form db
*/
public function execute_and_fetch(string $sql, string $types, &$var1, &...$_): array
{
$this->prepare($sql);
$this->bind_param($types, $var1, ...$_);
$this->execute();
$meta = $this->stmt->result_metadata();
if ($meta === false) {
throw new mysqli_sql_exception("Could not retrieve metadata");
}
$params = [];
$row = [];
while ($field = $meta->fetch_field()) {
$params[] = &$row[$field->name];
}
call_user_func_array(array($this->stmt, 'bind_result'), $params);
while ($this->stmt->fetch()) {
foreach ($row as $key => $val) {
$c[$key] = $val;
}
$result[] = $c;
}
return $result;
}
/**
* Does not work. Cannot bind results to variable for some reason.
* @deprecated use $db->stmt->bind_params() in stead.
* @param [type] $var1
* @param [type] ...$_
* @return void
*/
public function bind_result(&$var1, &...$_)
{
if (!$this->stmt->bind_result($var1, $_)) {
throw new mysqli_sql_exception($this->error);
}
}
public function fetch()
{
$ret = $this->stmt->fetch();
if ($ret === false) {
throw new mysqli_sql_exception("Could not fetch data");
}
return $ret;
}
public function inserted_id()
{
return $this->conn->insert_id;
}
public function reset()
{
$ret = $this->stmt->reset();
if ($ret === false) {
throw new mysqli_sql_exception("Could not reset statement");
}
return $ret;
}
/**
* Disconnect from the database when DB class gets out of scope.
*/
public function __destruct()
{
// close statement if present
if (isset($this->stmt)) {
if (!$this->stmt->close()) {
throw new mysqli_sql_exception("Could not close prepared statement");
}
}
if (isset($this->conn)) {
if (!$this->conn->close()) {
throw new mysqli_sql_exception("Could not close connection to db");
}
}
}
}
|
# LabelAPI - Server program that provides API to manage training sets for machine learning image recognition models
# Copyright (C) 2020-2021 The Ocean Cleanup™
#
# 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 <https://www.gnu.org/licenses/>.
from flask import has_request_context, request
import logging
import flask_login
import sys
class RequestFormatter(logging.Formatter):
def format(self, record):
try:
if has_request_context():
if flask_login.current_user is not None:
try:
record.user = flask_login.current_user.email
except:
record.user = "anonymous"
else:
record.user = "anonymous"
record.url = request.url
record.method = request.method
record.remote_addr = request.remote_addr
else:
record.user = ""
record.url = ""
record.remote_addr = ""
record.method = ""
except:
record.user = ""
record.url = ""
record.remote_addr = ""
record.method = ""
return super().format(record)
def create_logger(loglevel):
""" Set logger to both file and stream logger"""
# Manual logger
logger = logging.getLogger('label-api')
if not logger.handlers:
ch = logging.StreamHandler(stream=sys.stdout)
log_format = \
RequestFormatter(
"%(levelname)s %(asctime)s [%(filename)s:%(lineno)s - "
"%(funcName)s() - %(method)s %(url)s - %(remote_addr)s - "
"%(user)s] %(message)s"
)
ch.setFormatter(log_format)
logger.addHandler(ch)
logger.setLevel(loglevel)
logger.propagate = False
return logger
|
/**
* Single device, multi-instance clique implementation via LocalConnection.
*
* (C)opyright 2014 to 2017
*
* This source code is protected by copyright and distributed under license.
* Please see the root LICENSE file for terms and conditions.
*
*/
package p2p3.netcliques {
import flash.events.Event;
import flash.net.LocalConnection;
import flash.events.EventDispatcher;
import flash.utils.ByteArray;
import p2p3.interfaces.INetClique;
import p2p3.interfaces.INetCliqueMember;
import p2p3.netcliques.NetCliqueMember;
import p2p3.interfaces.IPeerMessage;
import p2p3.events.NetCliqueEvent;
import flash.utils.getTimer;
import org.cg.DebugView;
import p2p3.PeerMessage;
import flash.external.ExternalInterface;
import flash.utils.setTimeout;
public class MultiInstance extends EventDispatcher implements INetClique {
public static const connectionNamePref:String = "_clique_localMI"; //local connection name prefix
private var _localConnection:LocalConnection = null;
private var _segmentID:String = null; //optional segment ID used for segregated communications ("newRoom" functionality)
private var _connectionIndex:uint = 0; //current node index
private var _localPeerID:String = null; //local peer ID generated by generateConnectionID
private var _connected:Boolean = false; //is clique connected?
private var _localPeerInfo:INetCliqueMember = null; //local (self) peer info
private var _connectedPeers:Vector.<INetCliqueMember> = new Vector.<INetCliqueMember>(); //all currently connected peers
private var _connectionNamesMap:Vector.<Object> = new Vector.<Object>(); //objects currently contain "peerID" and "connectionName" properties
private var _rooms:Vector.<INetClique> = new Vector.<INetClique>(); //registered segregated rooms as INetClique implementation instances
private var _parentClique:INetClique = null; //reference to parent INetClique implementation instance; if null this is the top-most parent
/**
* Creates a new instance.
*/
public function MultiInstance(parentClique:INetClique = null, segmentID:String = null) {
_parentClique = parentClique;
this._segmentID = segmentID;
if (this._segmentID != null) {
//allow time to create any necessary listeners
setTimeout(this.connect, 500);
}
}
/**
* True if the LocalConnection clique is currently connected.
*/
public function get connected():Boolean {
return (_connected);
}
/**
* A vector array of INetCliqueMember implementations representing currently connected peers.
*/
public function get connectedPeers():Vector.<INetCliqueMember> {
return (_connectedPeers);
}
/**
* An INetCliqueMember implementation containing local (self) peer information.
*/
public function get localPeerInfo():INetCliqueMember {
return (_localPeerInfo);
}
/**
* The local (self) peer ID associated with this instance.
*/
public function get localPeerID():String {
if ((_localPeerID == null) || (_localPeerID == "")) {
if (_parentClique != null) {
_localPeerID = MultiInstance(_parentClique).localPeerID;
} else {
_localPeerID = generateConnectionID();
}
}
return (_localPeerID);
}
/**
* @return A vector array of segragated INetClique implementation instances (MultiInstance), or rooms, registered with
* this instance.
*/
public function get rooms():Vector.<INetClique> {
return (this._rooms);
}
/**
* @return A reference to the parent INetClique implementation instance, or null if this is the parent (top-most) instance.
*/
public function get parentClique():INetClique {
return (this._parentClique);
}
/**
* Handler for emulated peer disconnections.
*
* @param peerID The peer ID being disconnected. Once disconnected the peer ID will be invalid for
* any subsequent calls.
*/
public function onDisconnect(peerID:String):void {
var event:NetCliqueEvent = new NetCliqueEvent(NetCliqueEvent.PEER_DISCONNECT);
var memberObj:INetCliqueMember = new NetCliqueMember(peerID);
event.memberInfo = memberObj;
//mimics RTMFP functionality where only parent instance dispatched CONNECT, DISCONNECT, and related events
if (_parentClique == null) {
dispatchEvent(event);
} else {
_parentClique.dispatchEvent(event);
}
}
/**
* Sends a message only to a specific connected peer.
*
* @param peers A connected peer, as an INetCliqueMember implementations to send the message to.
* @param msgObj The message to send to the specified peer.
*
* @return True if the message could be sent, false otherwise.
*/
public function sendToPeer(peer:INetCliqueMember, msgObj:IPeerMessage):Boolean {
msgObj.addSourcePeerID(localPeerID);
var targetConnectionName:String = getConnectionName(peer.peerID);
if (targetConnectionName != null) {
_localConnection.send(targetConnectionName, "message", connectionName, peer.peerID, msgObj.serializeToAMF3(true));
return (true);
}
return (false);
}
/**
* Sends a message only to a specific list of connected peers.
*
* @param peers A vector array of connected peers, as INetCliqueMember implementations, to send the message to.
* @param msgObj The message to send to the specified peers.
*
* @return A vector array containing boolean values for each supplied peer, in order, denoting whether or
* not the message could be sent. If true, the message could be sent to the specific peer, false otherwise.
*/
public function sendToPeers(peers:Vector.<INetCliqueMember>, msgObj:IPeerMessage):Vector.<Boolean> {
var successes:Vector.<Boolean> = new Vector.<Boolean>();
msgObj.addSourcePeerID(localPeerID);
for (var count:int = 0; count < peers.length; count++) {
var currentPeer:INetCliqueMember = peers[count];
var targetConnectionName:String = getConnectionName(currentPeer.peerID);
if (targetConnectionName != null) {
_localConnection.send(targetConnectionName, "message", connectionName, currentPeer.peerID, msgObj.serializeToAMF3(true));
successes.push(true);
} else {
successes.push(false);
}
}
return (successes);
}
/**
* Broadcasts a message to all connected peers.
*
* @param msgObj The message to broadcast.
*
* @return True if the message could be successfully broadcast, false otherwise (for example, not peers to broadcast to).
*/
public function broadcast(msgObj:IPeerMessage):Boolean {
if (_connectedPeers == null) {
return (false);
}
if (_connectedPeers.length == 0) {
return (false);
}
if ((msgObj.targetPeerIDs == "") || (msgObj.targetPeerIDs == null)) {
msgObj.targetPeerIDs = "*";
}
msgObj.addSourcePeerID(localPeerID);
for (var count:int = 0; count < _connectedPeers.length; count++) {
var currentPeer:INetCliqueMember = _connectedPeers[count];
var targetConnectionName:String = getConnectionName(currentPeer.peerID);
if (targetConnectionName != null) {
_localConnection.send(targetConnectionName, "message", connectionName, currentPeer.peerID, msgObj.serializeToAMF3(true));
}
}
return (true);
}
/**
* Initializes and connects the clique.
*
* @param ... args Optional arguments. May include:
* [0] - Segment identifier for segregated communication groups. Default (main) group has none.
*
* @return True if the clique connection was successfully initiated, false if the initiated connection attempt failed (already
* connected, for example).
*/
public function connect(... args):Boolean {
var success:Boolean = false;
var event:NetCliqueEvent = null;
try {
if (LocalConnection.isSupported) {
_localConnection = new LocalConnection();
_localConnection.client = this;
_localConnection.allowDomain("*");
_localConnection.allowInsecureDomain("*");
_localConnection.connect(connectionName);
_localPeerInfo = new NetCliqueMember(localPeerID);
var connNameMap:Object = new Object();
connNameMap.peerID = localPeerID;
connNameMap.connectionName = connectionName;
_connectionNamesMap.push(connNameMap);
_connected = true;
success = true;
sendStartupHandshake();
event = new NetCliqueEvent(NetCliqueEvent.CLIQUE_CONNECT);
if (ExternalInterface.available) {
//unreliable - is there a better way?
ExternalInterface.addCallback("_onunloadcb", disconnect);
var jsExecuteCallBack:String = "document.getElementsByName('"+ExternalInterface.objectID+"')[0]._onunloadcb();return('');";
var jsBindEvent:String = "function(){window.unload=function(){"+jsExecuteCallBack+"};}";
ExternalInterface.call(jsBindEvent);
}
} else {
event = new NetCliqueEvent(NetCliqueEvent.CLIQUE_ERROR);
success = false;
}
} catch (err:*) {
DebugView.addText(err);
_connected = false;
_localConnection = null;
if (err.errorID == 2082) {
//connection at this index already exists, try next one
_connectionIndex++;
connect.call(this, args);
success = true;
} else {
DebugView.addText(err);
event = new NetCliqueEvent(NetCliqueEvent.CLIQUE_ERROR);
success = false;
}
} finally {
if (event != null) {
dispatchEvent(event);
}
return (success);
}
}
/**
* Disconnects the current LocalConnection clique connection.
*
* @return True if the clique could be disconnected, false if the clique was not connected.
*/
public function disconnect():Boolean {
if (_localConnection != null) {
sendDisconnect();
_localConnection.close();
_localConnection = null;
_connected = false;
return (true);
} else {
return (false);
}
}
/**
* Handler for incoming LocalConnection handshakes.
*
* @param handshakeInfo The source/sending handshake information object being received.
*/
public function handshake(handshakeInfo:Object):void {
if (peerConnected(handshakeInfo.peerID) == false) {
var handshakeObject:Object = generateHandshakeObject();
var newMember:NetCliqueMember = new NetCliqueMember(handshakeInfo.peerID);
_connectedPeers.push(newMember);
var connNameMap:Object = new Object();
connNameMap.peerID = handshakeInfo.peerID;
connNameMap.connectionName = handshakeInfo.connectionName;
_connectionNamesMap.push(connNameMap);
_localConnection.send(handshakeInfo.connectionName, "handshake", handshakeObject);
var event:NetCliqueEvent = new NetCliqueEvent(NetCliqueEvent.PEER_CONNECT);
event.memberInfo = newMember;
dispatchEvent(event);
} else {
//member is already connected so ignore
}
}
/**
* Creates a new room or segregated INetClique implementation instance (MultiInstance).
*
* @param options Initialization options object to pass to the new MultiInstance instance's constructor.
*
* @return A newly created, segregated INetClique implementation (MultiInstance), or room.
*/
public function newRoom(options:Object):INetClique {
if (this.parentClique != null) {
return (this.parentClique.newRoom(options));
}
var newRoom:MultiInstance = new MultiInstance(this, options.groupName);
this._rooms.push(newRoom);
return (newRoom);
}
/**
* Handler for incoming LocalConnection messages.
*
* @param connectionID The unique source/sending LocalConnection connection ID.
* @param peerID The unique source/sending peer ID.
* @param messageObj The AMF3-encoded message being received.
*/
public function message(connectionID:String, peerID:String, messageObj:ByteArray):void {
var incomingMsg:PeerMessage = new PeerMessage(messageObj);
var event:NetCliqueEvent = new NetCliqueEvent(NetCliqueEvent.PEER_MSG);
event.memberInfo = getMemberInfo(peerID);
event.message = incomingMsg;
dispatchEvent(event);
}
/**
* Method invoked when a child MultiInstance instance is about to be destroyed.
*
* @param room The reference to the child room or INetClique implementation instance (MultiInstance) about to be destroyed.
*/
public function onChildDestroy(room:INetClique):void {
if (this.parentClique != null) {
try {
this.parentClique["onChildDestroy"](this);
} catch (err:*) {
}
}
if (this._rooms != null) {
for (var count:int = 0; count < this._rooms.length; count++) {
if (this._rooms[count] == room) {
this._rooms.splice(count, 1);
return;
}
}
}
}
/**
* Method invoked when the instance is about to be removed from memory. If this is a child instance, the parent's "onChildDestroy"
* is invoked first.
*/
public function destroy():void {
if (this.parentClique != null) {
try {
this.parentClique["onChildDestroy"](this);
} catch (err:*) {
}
}
this._localPeerID = "";
this.localPeerInfo.peerID = "";
if (_localConnection != null) {
_localConnection.close();
_localConnection = null;
}
}
/**
* Finds the unique Localconnection connection name for a specific peer ID.
*
* @param targetPeerID The peer ID for which to find a connection name.
*
* @return The connection name for the specified peer ID, or null if no match can be found.
*/
protected function getConnectionName(targetPeerID:String):String {
for (var count:int = 0; count < _connectedPeers.length; count++) {
var currentPeer:INetCliqueMember = _connectedPeers[count];
for (var count2:int = 0; count2 < _connectionNamesMap.length; count2++) {
var currentMap:Object = _connectionNamesMap[count2];
if (currentMap.peerID == targetPeerID) {
return (currentMap.connectionName);
}
}
}
return (null);
}
/**
* Sends an initial startup handshake message to all connected peers.
*/
protected function sendStartupHandshake():void {
var handshakeObj:Object = generateHandshakeObject();
for (var count:uint = 0; count < _connectionIndex; count++) {
try {
if (this._segmentID != null) {
var currentConnectionName:String = connectionNamePref +"_"+ this._segmentID +"_"+ String(count);
} else {
currentConnectionName = connectionNamePref + String(count);
}
_localConnection.send(currentConnectionName, "handshake", handshakeObj);
} catch (err:* ) {
}
}
}
/**
* Checks whether or not a specific peer ID is connected.
*
* @param peerID The peer ID to check.
*
* @return True if the specified peer is currently connected, false otherwise.
*/
protected function peerConnected(peerID:String):Boolean {
if (_connectedPeers == null) {
_connectedPeers = new Vector.<INetCliqueMember>();
}
for (var count:int = 0; count < _connectedPeers.length; count++) {
if (_connectedPeers[count].peerID == peerID) {
return (true);
}
}
return (false);
}
/**
* Emulates a local disconnection by sending a disconnect message to all connected peers.
*/
protected function sendDisconnect():void {
for (var count:int = 0; count < _connectedPeers.length; count++) {
var currentPeer:INetCliqueMember = _connectedPeers[count];
var targetConnectionName:String = getConnectionName(currentPeer.peerID);
if (targetConnectionName != null) {
_localConnection.send(targetConnectionName, "onDisconnect", localPeerID);
}
}
}
/**
* @return A unique connection ID for this LocalConnection peer. The ID is
* based on the current system date and time and elapsed time since startup. Since every
* instance of this class will execute on the same device it should be impossible for
* any two instances to have exactly the same ID.
*/
protected function generateConnectionID():String {
var IDString:String = new String();
var dateObj:Date = new Date();
IDString = String(dateObj.getFullYear());
IDString += String(dateObj.getMonth());
IDString += String(dateObj.getDay());
IDString += String(dateObj.getHours());
IDString += String(dateObj.getMinutes());
IDString += String(dateObj.getSeconds());
IDString += String(dateObj.getMilliseconds());
IDString += String(getTimer());
return (IDString);
}
/**
* Generates a handshake information object, usually sent after an initial peer connection is established.
*
* @return A handshake information object containing the local properties "peerID" and "connectionName".
*/
protected function generateHandshakeObject():Object {
var returnObj:Object = new Object();
//structure must match that expected in handshake method
returnObj.peerID = localPeerID;
returnObj.connectionName = connectionName;
return (returnObj);
}
/**
* The unique LocalConnection connection name currently being used by this instance.
*/
private function get connectionName():String {
if (this._segmentID != null) {
return (connectionNamePref +"_"+ this._segmentID +"_"+ String(_connectionIndex));
}
return (connectionNamePref + String(_connectionIndex));
}
/**
* Returns an INetCliqueMember implementation object for a matching peer ID.
*
* @param peerID The peer ID to search for.
*
* @return An INetCliqueMember implementation for the supplied peer ID, or null if none can be found.
*/
private function getMemberInfo(peerID:String):INetCliqueMember {
if (peerID == _localPeerID) {
return (_localPeerInfo);
}
for (var count:int = 0; count < _connectedPeers.length; count++) {
var currentMember:INetCliqueMember = _connectedPeers[count];
if (currentMember.peerID == peerID) {
return (currentMember);
}
}
return (null);
}
}
}
|
import express from "express";
import dotenv from "dotenv";
import cors from "cors";
import mongoose from "mongoose";
import { fileURLToPath } from "url";
import path from "path";
import authRoute from "./Routes/auth.js";
import userRoute from "./Routes/user.js";
import storeRoute from "./Routes/store.js";
import cookieParser from "cookie-parser";
import customerRoute from "./Routes/customer.js";
import { Server } from "socket.io";
import Chat from "./Models/chat.js";
import { createServer } from "http";
const app = express();
//const PORT = 5000;
const port = process.env.PORT || 3000;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
dotenv.config();
mongoose.connect(process.env.MONGOOSE_CONNECT);
// Websocketi
const httpServer = createServer(app);
httpServer.listen(port);
app.use(cookieParser());
app.use(
cors({
credentials: true,
origin: ["http://localhost:3001", "https://rocks-market.up.railway.app"],
})
);
app.use(express.json());
//app.listen(port, "0.0.0.0");
//app.listen(PORT);
app.use("/api/auth", authRoute);
app.use("/api/user", userRoute);
app.use("/api/store", storeRoute);
app.use("/api/customer", customerRoute);
app.use("/uploads", express.static(__dirname + "/uploads"));
const io = new Server(httpServer /*4005 port*/, {
cors: {
credentials: true,
origin: ["http://localhost:3001", "https://rocks-market.up.railway.app"],
},
});
io.on("connection", (socket) => {
console.log(`A user connected with socket id ${socket.id}`);
const handleChange = () => {
socket.emit("newChat");
};
const chatChange = Chat.watch();
chatChange.on("change", handleChange);
socket.on("disconnect", () => {
chatChange.removeListener("change", handleChange);
chatChange.close();
});
});
// MODEL WATCH
|
package com.example.basics.control_block_statements;
// 29.10.2023 - lesson arrange by Kuba Wąsikowski
//lekcja 48 https://www.udemy.com/course/kurs-java-od-podstaw-od-zera-do-mastera-zbuduj-wlasne-aplikacje/learn/lecture/23728422#overview
public class J39_ForLoop {
public static void main(String args[]) {
// Pętla for
// Pętle pozwalają na wykonanie instrucji tak długo jak warunek jest spełniony.
// Uwaga: warunek sprawdzany w iteracji nie powinien skutkować nieskończoną pętlą!
String names[] = { "Adam", "Ola", "Kasia" };
// a to wartość początkowa akumulatora
// W każdej interacji sprawdzana jest z względem długości tablicy
// jeśli true iteracja się wykona
// Po wykonaniu iteracji następuje inkrementacja a
for (int a = 0; a < names.length; a++) {
String str = names[a];
System.out.println("Osoba: " + str);
}
int arr[] = { 1, 5, 10, 15, 23, 34, 64, 98, 879, 1234, 23466, 6451135 };
for (int i = 0; i < arr.length; i += 2) {
int value = arr[i];
System.out.println("arr: " + value);
}
String names2[] = { "Adam", "Ola", "Kasia" };
for ( int i = names.length - 1; i >= 0; i-- ) {
String str2 = names[i];
System.out.println("Imię: " + str2);
}
}
}
|
Cara Install Software USB Modeswitch Secara Manual
Jadi kegunaan usb_modeswitch adalah untuk memindah dari storage mode ke network card mode pada modem usb yang saya gunakan, di package manager synaptics usb_modeswitch hanya ada versi 2.2.5 versi 2015 saja sedangkan saat ini sudah menjadi versi 2.5.1 2017 yang menurut saya sudah mempunyai banyak tambahan konfigurasi, nah dari konfigurasi usb_modeswitch inilah kita bisa mengkoneksikan internet menggunakan modem tanpa mempunyai kendala seperti modem tidak terdetek dan di lsusb muncul storage mode bukan networkcard mode.
Hal pertama yang harus dilakukan adalah mendownload software usb_modeswitch telebih dahulu.
$ cd Downloads
$ wget http://www.draisberghof.de/usb_modeswitch/usb-modeswitch-2.5.1.tar.bz2
Lalu kita harus extract file usb_modeswitch tersebut dengan cara.
$ tar -xf usb-modeswitch-2.5.1.tar.bz2
Jika sudah di extract silahkan move ke directory usb_modeswitch dengan cara.
$ cd usb-modeswitch-2.5.1
Harap diketahui bahwa usb_modeswitch membutuhkan libusb-1.x untuk melakukan proses instalasi dan beberapa library dari bahasa pemrograman C.
$ sudo apt-get install libusb-1.0
$ sudo apt-get install libc6-dev
Nah. beberapa paket diatas adalah yang wajib di download agar konfigurasi dan penginstalam usb_modeswitch berjalan secara lancar. Lanjut ke proses instalasi yaitu eksekusi command berikut.
$ sudo make install
Selesai, jika outputnya muncul seperti ini maka usb_modeswitch sudah terupgrade ke versi terbaru.
------------------------------------------------------
sed 's_!/usr/bin/tclsh_!'"/usr/bin/tclsh"'_' < usb_modeswitch.tcl > usb_modeswitch_dispatcher
install -D --mode=755 usb_modeswitch /usr/sbin/usb_modeswitch
install -D --mode=755 usb_modeswitch.sh /lib/udev/usb_modeswitch
install -D --mode=644 usb_modeswitch.conf /etc/usb_modeswitch.conf
install -D --mode=644 usb_modeswitch.1 /usr/share/man/man1/usb_modeswitch.1
install -D --mode=644 usb_modeswitch_dispatcher.1 /usr/share/man/man1/usb_modeswitch_dispatcher.1
install -D --mode=755 usb_modeswitch_dispatcher /usr/sbin/usb_modeswitch_dispatcher
install -d /var/lib/usb_modeswitch
test -d /etc/init -a -e /sbin/initctl && install --mode=644 usb-modeswitch-upstart.conf /etc/init || test 1
test -d /etc/systemd/system -a \( -e /usr/bin/systemctl -o -e /bin/systemctl \) && install --mode=644 usb_modeswitch@.service /etc/systemd/system || test 1
----------------------------------------------------------------------
Silahkan cek versi usb_modeswitch dengan cara.
$ sudo usb_modeswitch -e
Maka akan muncul seperti ini.
----------------------------------------------------------------
* usb_modeswitch: handle USB devices with multiple modes
* Version 2.5.1 (C) Josua Dietze 2017
* Based on libusb1/libusbx
! PLEASE REPORT NEW CONFIGURATIONS !
------------------------------------------------------------------
Selesai.
Author : Agus Purwantoro (aguxai)
Date : 27/09/2017
Version : 1.0
License : Free Document License (FDL). See more at https://www.gnu.org/licenses/fdl-1.3.en.html
|
#ifndef HOTELORDERSSEARCHRESPONSE_H
#define HOTELORDERSSEARCHRESPONSE_H
#include <TaoApiCpp/TaoResponse.h>
#include <QList>
#include <TaoApiCpp/domain/HotelOrder.h>
/**
* @brief TOP RESPONSE API: 此接口用于查询多个酒店订单,根据传入的查询条件查询订单信息。
*
* @author sd44 <sd44sdd44@yeah.net>
*/
class HotelOrdersSearchResponse : public TaoResponse
{
public:
virtual ~HotelOrdersSearchResponse() { }
QList<HotelOrder> getHotelOrders() const;
void setHotelOrders (QList<HotelOrder> hotelOrders); qlonglong getTotalResults() const;
void setTotalResults (qlonglong totalResults);
virtual void parseNormalResponse();
private:
/**
* @brief 多个订单结构,是否返回入住人列表根据参数决定
**/
QList<HotelOrder> hotelOrders;
/**
* @brief 符合条件的结果总数
**/
qlonglong totalResults;
};
#endif
|
import { GraphQLNonNull, GraphQLString } from 'graphql';
import { connectionDefinitions } from 'graphql-relay';
import usefazConnector from '~/database/usefazConnector';
import { SchoolReportModel } from '~/entities';
import type { IContext, IStudent } from '~/interfaces';
import { registerGraphQLNodeObjectType } from '../node/NodeType';
import SchoolReportType from '../schoolReport/SchoolReportType';
const StudentType = registerGraphQLNodeObjectType<IStudent>('student')({
name: 'Student',
fields() {
return {
RM: {
type: new GraphQLNonNull(GraphQLString),
},
firstname: {
type: new GraphQLNonNull(GraphQLString),
resolve: (student) => student.fullname.split(' ')[0],
},
lastname: {
type: GraphQLString,
description: "student's lastname (must not be equals firstname)",
resolve: (student) => {
const splittedStudentName = student.fullname.split(' ');
if (splittedStudentName.length === 1) {
return null;
}
return splittedStudentName[splittedStudentName.length - 1];
},
},
fullname: {
type: new GraphQLNonNull(GraphQLString),
},
avatarURL: {
type: GraphQLString,
resolve: (student) => student.avatar_url,
},
schoolReport: {
type: SchoolReportType,
resolve(student) {
const schoolReportEntity = SchoolReportModel(usefazConnector);
return schoolReportEntity.getOneByStudentId(student.id);
},
},
};
},
});
export const StudentConnection = connectionDefinitions({
name: 'Student',
nodeType: StudentType,
});
export const studentField = {
type: StudentType,
resolve(_root: IStudent | undefined, _args: unknown, context: IContext) {
return context.student;
},
};
export default StudentType;
|
@use '../util/' as u;
html
{
font-size: 100%;
box-sizing: border-box;
}
*,
*::before,
*::after
{
box-sizing: inherit;
}
body
{
margin: 0;
padding: 0;
font-family: u.$font;
line-height: 1.3;
font-weight: u.$weight-sm;
font-size: u.$font-med;
color: u.$darkBlue;
overflow-x: hidden;
@include u.breakpoint-up(large)
{
font-size: u.$font-med;
}
&.noscroll
{
overflow: hidden;
}
h1,
h2,
h3
{
margin-top: 0px;
font-weight: u.$weight-sm;
line-height: 1.2;
color: u.$darkBlue;
}
h1
{
font-size: u.$font-xlarge;
margin-bottom: 1.5rem;
@include u.breakpoint-up(xlarge)
{
font-size: u.$font-xxlarge;
}
}
h2
{
font-size: u.$font-large;
margin-bottom: 1.5625rem;
@include u.breakpoint-up(xlarge)
{
font-size: u.$font-xlarge;
margin-bottom: 2.25rem;
}
}
p
{
line-height: 1.5;
margin-bottom: 2.25rem;
}
}
a,
a:visited,
a:hover
{
text-decoration: none;
color: u.$grayishBlue;
}
.container
{
max-width: 69.375rem;
margin: 0 auto;
// pall stands for padding for all sides
&--pall
{
padding: 2.25rem 1.5rem;
}
// py stands for padding for top and bottom
&--py
{
padding-top: 2.25rem;
padding-bottom: 2.25rem;
}
// py stands for padding for left and right
&--px
{
padding-left: 1.5rem;
padding-right: 1.5rem;
}
// py stands for padding for bottom
&--pb
{
padding-bottom: 2.25rem;
}
// py stands for padding for top
&--pt
{
padding-top: 2.25rem;
}
// py stands for padding for right
&--pr
{
padding-right: 1.5rem;
}
// py stands for padding for left
&--pl
{
padding-left: 1.5rem;
}
}
// flexbox styles
.flex
{
display: flex;
&-jc-sb
{
justify-content: space-between;
}
&-jc-c
{
justify-content: center;
}
&-ai-c
{
align-items: center;
}
}
// Buttons
button,
.button
{
padding: 0.875rem 2.1875rem;
background: linear-gradient(to right, u.$limeGreen, u.$brightCyan);
border-radius: 50px;
cursor: pointer;
border: none;
font-weight: u.$weight-med;
color: u.$white;
transition: opacity 300ms ease-in-out;
&:hover
{
opacity: 0.75;
}
}
// visibility
.hide-for-mobile
{
@include u.breakpoint-down(medium)
{
display: none;
}
}
.hide-for-desktop
{
@include u.breakpoint-up(large)
{
display: none;
}
}
|
import { z } from "zod";
import { prisma } from "../../db";
import { createTRPCRouter, publicProcedure, protectedProcedure } from "../trpc";
import { TRPCError } from "@trpc/server";
import type { UploadApiResponse } from "cloudinary";
import { v2 } from "cloudinary";
import { MAX_IMAGE_COUNT } from "@/utils/general/constants";
import { printify } from "@/server/PrintifyClient";
export const galleryRouter = createTRPCRouter({
// uploadImagePrintify: protectedProcedure
// .input(z.object({ url: z.string(), file_name: z.string() }))
// .query(async ({ input: { url, file_name }, ctx: { session } }) => {
// return await printify.uploadImage({
// url,
// file_name,
// });
// }),
getStyle: protectedProcedure
.input(z.object({ styleId: z.string() }))
.query(async ({ input: { styleId }, ctx: { session } }) => {
return await prisma.userImage.findFirst({
where: {
id: styleId,
ownerId: session.user.id,
},
});
}),
getUserGallery: protectedProcedure
.input(
z.object({
userId: z.string().optional(),
limit: z.number().min(1).max(20).optional().default(12),
cursor: z.string().nullish(),
skip: z.number().optional(),
})
)
.query(async ({ input, ctx: { session } }) => {
const { skip, cursor, limit } = input;
const items = await prisma.userImage.findMany({
take: limit + 1,
skip,
cursor: cursor ? { id: cursor } : undefined,
where: {
ownerId: input?.userId ? input.userId : session.user.id,
},
});
let nextCursor: typeof cursor | undefined;
if (items.length > limit) {
const nextItem = items.pop();
nextCursor = nextItem?.id;
}
return { imgs: items, nextCursor };
}),
uploadStyle: protectedProcedure
.input(z.object({ picture: z.string() }))
.mutation(async ({ input: { picture }, ctx: { session } }) => {
const result: UploadApiResponse = await v2.uploader.upload(picture, {
filename_override: session?.user.name as string,
image_metadata: true,
});
const arr = await prisma.userImage.findMany({
where: {
ownerId: session.user.id,
id: result.public_id,
},
select: { ownerId: true },
});
if (arr.length >= MAX_IMAGE_COUNT) return;
const img = await prisma.userImage.create({
data: {
id: result.public_id,
ownerId: session.user.id,
url: result.url,
},
});
return img.id;
}),
deleteStyle: protectedProcedure
.input(
z.object({
styleId: z.string(),
})
)
.mutation(async ({ input: { styleId } }) => {
const image = await prisma.userImage.findFirst({
where: { id: styleId },
});
if (!image)
throw new TRPCError({ code: "BAD_REQUEST", message: "invalid id" });
await v2.uploader.destroy(image.id);
await prisma.userImage.delete({
where: { id: styleId },
});
}),
});
|
<nav class="navbar navbar-expand-lg navbar-dark bg-semi-dark p-3">
<div class="container">
<a class="navbar-brand fw-semibold p-2" routerLink="/">eAgenda Web<i
class="bi bi-clipboard2-check-fill ms-2"></i></a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"
(click)="estaColapsada = !estaColapsada">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" [ngbCollapse]="!estaColapsada">
<div class="links w-100 text-center" *ngIf="(usuarioLogado$ | async) as usuarioLogado">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link text-primary" routerLinkActive="fw-semibold" routerLink="/tarefas">Tarefas</a>
</li>
<li class="nav-item">
<a class="nav-link text-primary" routerLinkActive="fw-semibold" routerLink="/contatos">Contatos</a>
</li>
<li class="nav-item">
<a class="nav-link text-primary" routerLinkActive="fw-semibold" routerLink="/compromissos">Compromissos</a>
</li>
<li class="nav-item">
<a class="nav-link text-primary" routerLinkActive="fw-semibold" routerLink="/categorias">Categorias</a>
</li>
<li class="nav-item ms-0 ms-lg-auto">
<a class="nav-link text-primary" routerLinkActive="fw-semibold" routerLink="/dashboard"><i
class="bi bi-person-lines-fill me-1"></i>{{ usuarioLogado.nome }}</a>
</li>
<li class="nav-item ms-2">
<a class="btn btn-primary" role="button" (click)="sair()"><i class="bi bi-door-open me-1"></i>Sair</a>
</li>
</ul>
</div>
</div>
</div>
</nav>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.