text
stringlengths 184
4.48M
|
---|
import React, { useContext, useEffect, useState } from 'react'
import CartIcon from '../Cart/CartIcon'
import classes from './HeaderCartButton.module.css'
import CartContext from '../../store/cartContext'
const HeaderCartButton = (props) => {
const [buttonIsHighlighted, setButtonIsHighlighted] = useState(false)
const cartCtx = useContext(CartContext)
const { items } = cartCtx
const numberOfCartItems = items.reduce((curNumber, item) => {
return curNumber + item.amount
}, 0)
const btnClasses = `${classes.button} ${buttonIsHighlighted ? classes.bump : ''}`
useEffect(() => {
if (items.length === 0) {
return
}
setButtonIsHighlighted(true);
const timer = setTimeout(() => {
setButtonIsHighlighted(false)
}, 300);
// always clene up timeout function
return () => {
clearTimeout(timer)
}
}, [items])
return (
<button className={btnClasses} onClick={props.onClick} >
<span className={classes.icon} >
<CartIcon />
</span>
<span>Visit Your Cart </span>
<span className={classes.badge} >{numberOfCartItems}</span>
</button>
)
}
export default HeaderCartButton |
<!DOCTYPE html>
<html>
<head>
<title>Clonebook</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= favicon_link_tag asset_path("favicon.ico") %>
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
<%= javascript_importmap_tags %>
</head>
<body>
<header data-controller="hidden viewed links">
<div class="logo-link"><a href="/"><%= render 'shared/logo', size: 'small' %></a></div>
<% if user_signed_in? %>
<div class="header-links">
<div class="header-link" data-links-target="linkDiv">
<%= link_to current_user.profile.first_name, current_user_path %>
</div>
<div class="header-link" data-links-target="linkDiv">
<%= link_to 'Find Friends', strangers_path %>
</div>
<div class="header-link" data-links-target="linkDiv">
<%= notifications_link %>
</div>
<div class="header-link" data-links-target="linkDiv">
<%= link_to 'Sign Out', destroy_user_session_path, data: { turbo_method: :delete } %>
</div>
<%= turbo_frame_tag 'notifications',
target: '_top',
class: 'hidden',
data: { hidden_target: 'toggle' } %>
</div>
<nav>
<div class="navbar-links">
<div class="navbar-link" data-links-target="linkDiv"><%= link_to 'Timeline', posts_path %></div>
<div class="navbar-link" data-links-target="linkDiv"><%= link_to 'Friends', friends_path %></div>
<div class="navbar-link" data-links-target="linkDiv"><%= friend_request_link %></div>
<div class="navbar-link" data-links-target="linkDiv"><%= link_to 'Edit Profile', edit_profile_path %></div>
<% if current_user.native_login? %>
<div class="navbar-link" data-links-target="linkDiv"><%= link_to 'Edit Account', edit_user_registration_path %></div>
<% end %>
</div>
</nav>
<% end %>
</header>
<section class="content <%= yield :page_classes %>">
<% if content_for?(:flash) %>
<%= yield :flash %>
<% else %>
<%= render 'shared/flash' %>
<% end %>
<section class="page-content"><%= yield %></section>
</section>
</body>
</html> |
import { useEffect, useState } from "react";
const useFetch = (url) => {
const [data, setData] = useState(null);
const [isPending, setIsPending] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch(url)
.then(res => {
if(!res.ok){
throw Error('Could not fetch the data for that resource')
}
return res.json()
})
.then(response => {
setData(response)
setError(null)
setIsPending(false)
})
.catch( err => {
setError(err.message)
setIsPending(false)
});
}, [url]);
return {data, isPending, error}
}
export default useFetch; |
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Catalog;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test for simple product fragment.
*/
class ProductFragmentTest extends GraphQlAbstract
{
/**
* @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
*/
public function testSimpleProductFragment()
{
$sku = 'simple';
$name = 'Simple Product';
$price = 10;
$query = <<<QUERY
query GetProduct {
products(filter: { sku: { eq: "$sku" } }) {
items {
sku
...BasicProductInformation
}
}
}
fragment BasicProductInformation on ProductInterface {
sku
name
price {
regularPrice {
amount {
value
}
}
}
}
QUERY;
$result = $this->graphQlQuery($query);
$actualProductData = $result['products']['items'][0];
$this->assertNotEmpty($actualProductData);
$this->assertEquals($name, $actualProductData['name']);
$this->assertEquals($price, $actualProductData['price']['regularPrice']['amount']['value']);
}
} |
import numpy as np
import seaborn as sns # for nicer plots
sns.set(style="darkgrid") # default style
import tensorflow as tf
from tensorflow import keras
import os
import pickle
import neuralNetwork as nn
AccuracyList = []
def build_ANN(kernel_size=(5,5),strides=(1, 1),pool_size=(2, 2),learning_rate=0.001, cnn=False, hidden_cnn=[]):
model = keras.models.Sequential()
if cnn:
# add first convolution layer to the model
for i in range(len(hidden_cnn)):
model.add(tf.keras.layers.Conv2D(filters=hidden_cnn[i],kernel_size=kernel_size,strides=strides,
padding='same',data_format='channels_last',name=f'conv_{i}',activation='relu'))
# add a max pooling layer with pool size and strides
model.add(tf.keras.layers.MaxPool2D(pool_size=pool_size,name=f'pool_{i}'))
model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(300, activation="relu"))
model.add(keras.layers.Dense(100, activation="relu"))
model.add(keras.layers.Dense(6, activation='softmax'))
# build model and print summary
tf.random.set_seed(1)
model.build(input_shape=(None, 128, 128, 1))
optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)
model.compile(optimizer=optimizer,
loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=['accuracy'])
return model
def train_and_evaluate(X_train, X_test, Y_train, Y_test, file_name='', num_epochs = 5, batch_size=32, params={}, train_datagen=None):
model= None
history = None
if os.path.exists(file_name + '.keras'):
model = keras.models.load_model(file_name + '.keras')
with open(file_name + '.pkl', 'rb') as file:
history = pickle.load(file)
print(f"The file {file_name} already exists.")
else:
tf.random.set_seed(1234)
np.random.seed(1234)
model = build_ANN(**params)
X_train = tf.expand_dims(X_train, axis=-1) # Assuming grayscale, add channel dimension
X_test = tf.expand_dims(X_test, axis=-1)
print('Training...')
if train_datagen != None :
history = model.fit(train_datagen.flow(X_train,Y_train,batch_size=64, seed=27,shuffle=False),
epochs=num_epochs,verbose=1, validation_data=(X_test, Y_test))
else:
history = model.fit(X_train, Y_train, epochs=num_epochs, batch_size= batch_size, validation_data=(X_test, Y_test))
model.save(file_name + '.keras')
# Save the training history separately
with open(file_name + '.pkl', 'wb') as file:
pickle.dump(history, file)
# Retrieve the training metrics (after each train epoch) and the final test
# accuracy.
train_accuracy = history.history['accuracy']
val_accuracy = history.history['val_accuracy']
loss_values = history.history['loss']
val_loss_values = history.history['val_loss']
test_accuracy = model.evaluate(x=X_test, y=Y_test, verbose=0,
return_dict=True)['accuracy']
accuracy = nn.AccuracyClass(train_accuracy, val_accuracy, num_epochs, file_name, model, test_accuracy, loss_values, val_loss_values)
AccuracyList.append(accuracy)
return test_accuracy |
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { Request } from 'express';
type JwtPayload = {
sub: string;
email: string;
};
@Injectable()
export class AcccessTokenStrategiest extends PassportStrategy(Strategy, 'jwt') {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromExtractors([
(request: Request) => {
const authHeader = request.header('authorization');
if(!authHeader) throw new UnauthorizedException();
const data = authHeader.replace('Bearer', '').trim();
if (!data) {
return null;
}
return data;
},
]),
secretOrKey: process.env.JWT_SECRET,
});
}
async validate(payload: JwtPayload) {
if (!payload) {
throw new UnauthorizedException();
}
return payload;
}
} |
package hw04lrucache
import (
"math/rand"
"strconv"
"sync"
"testing"
"github.com/stretchr/testify/require"
)
func TestCache(t *testing.T) {
t.Run("empty cache", func(t *testing.T) {
c := NewCache(10)
_, ok := c.Get("aaa")
require.False(t, ok)
_, ok = c.Get("bbb")
require.False(t, ok)
})
t.Run("simple", func(t *testing.T) {
c := NewCache(5)
wasInCache := c.Set("aaa", 100)
require.False(t, wasInCache)
wasInCache = c.Set("bbb", 200)
require.False(t, wasInCache)
val, ok := c.Get("aaa")
require.True(t, ok)
require.Equal(t, 100, val)
val, ok = c.Get("bbb")
require.True(t, ok)
require.Equal(t, 200, val)
wasInCache = c.Set("aaa", 300)
require.True(t, wasInCache)
val, ok = c.Get("aaa")
require.True(t, ok)
require.Equal(t, 300, val)
val, ok = c.Get("ccc")
require.False(t, ok)
require.Nil(t, val)
})
t.Run("purge logic", func(t *testing.T) {
c := NewCache(3)
c.Set("key1", 1)
c.Set("key2", 2)
c.Set("key3", 3)
c.Set("key4", 4)
res, ok := c.Get("key1")
require.False(t, ok)
require.Nil(t, res)
res, ok = c.Get("key2")
require.True(t, ok)
require.Equal(t, 2, res)
})
t.Run("LRU evict logic", func(t *testing.T) {
c := NewCache(3)
c.Set("key1", 1)
c.Set("key2", 2)
c.Set("key3", 3)
c.Get("key1")
c.Get("key2")
c.Set("key1", 100)
c.Set("key2", 200)
res, ok := c.Get("key1")
require.True(t, ok)
require.Equal(t, 100, res)
res, ok = c.Get("key2")
require.True(t, ok)
require.Equal(t, 200, res)
c.Set("key4", 4)
res, ok = c.Get("key3")
require.False(t, ok)
require.Nil(t, res)
})
}
func TestCacheMultithreading(t *testing.T) {
// t.Skip() // Remove me if task with asterisk completed.
c := NewCache(10)
wg := &sync.WaitGroup{}
wg.Add(2)
go func() {
defer wg.Done()
for i := 0; i < 1_000_000; i++ {
c.Set(Key(strconv.Itoa(i)), i)
}
}()
go func() {
defer wg.Done()
for i := 0; i < 1_000_000; i++ {
c.Get(Key(strconv.Itoa(rand.Intn(1_000_000))))
}
}()
wg.Wait()
}
func TestCanSetAndGetCacheItems(t *testing.T) {
c := NewCache(5)
c.Set("test_key", 122)
c.Set("test_key_2", 900)
res, ok := c.Get("test_key")
require.True(t, ok)
require.Equal(t, 122, res)
res, ok = c.Get("test_key_2")
require.True(t, ok)
require.Equal(t, 900, res)
}
func TestCanClearCache(t *testing.T) {
c := NewCache(3)
c.Set("test_key", 122)
c.Set("test_key_2", 900)
c.Set("test_key_3", 500)
c.Clear()
item, ok := c.Get("test_key")
require.Nil(t, item)
require.False(t, ok)
} |
import type { ISignature, MaybeElement } from '../types'
import { insertElement } from '../event/insertElement'
import { removeElement } from '../event/removeElement'
import { useEventListener } from '../event/useEventListener'
import { useKeyBoard } from '../event/useKeyBoard'
export class CreateSignatureCanvas implements ISignature {
canvas: HTMLCanvasElement = document.createElement('canvas')
ctx: CanvasRenderingContext2D = this.canvas.getContext('2d')!
stop: (() => void)[] = []
active = false
historyStack: ImageData[] = []
resetStack: ImageData[] = []
color = '#000000'
constructor(lineWidth = 2, w = 400, h = 400, color = '#000000') {
this.color = color
this.createCanvas(lineWidth, w, h)
window.onunload = () => this.unmount()
}
createCanvas(lineWidth = 2, w = 400, h = 400) {
this.canvas.width = w * devicePixelRatio
this.canvas.height = h * devicePixelRatio
this.ctx.fillStyle = 'rgba(255, 255, 255, 0)'
this.ctx.fillRect(0, 0, w, h)
this.ctx.strokeStyle = this.color
this.ctx.lineWidth = lineWidth
this.ctx.lineCap = 'round'
let offsetY = 0
let offsetX = 0
this.stop.push(
useEventListener(
this.canvas,
'touchstart',
(e) => {
offsetY = this.canvas.offsetTop
offsetX = this.canvas.offsetLeft
this.ctx.beginPath()
this.ctx.moveTo(
e.changedTouches[0].pageX + 2 - offsetX,
e.changedTouches[0].pageY - offsetY,
)
},
false,
),
)
let down = false
this.stop.push(
useEventListener(
this.canvas,
'mousedown',
(e) => {
offsetY = this.canvas.offsetTop
offsetX = this.canvas.offsetLeft
down = true
this.ctx.beginPath()
this.ctx.moveTo(e.pageX + 2 - offsetX, e.pageY - offsetY)
},
false,
),
)
this.stop.push(
useEventListener(
this.canvas,
'mousemove',
(e) => {
if (!down)
return
this.ctx.lineTo(e.pageX + 2 - offsetX, e.pageY - offsetY)
this.ctx.stroke()
},
false,
),
)
this.stop.push(
useEventListener(this.canvas, 'mouseup', () => (down = false)),
)
this.stop.push(
useEventListener(this.canvas, 'mouseout', () => (down = false)),
)
this.stop.push(
useEventListener(
this.canvas,
'touchmove',
(e) => {
this.ctx.lineTo(
e.changedTouches[0].pageX + 2 - offsetX,
e.changedTouches[0].pageY - offsetY,
)
this.ctx.stroke()
},
false,
),
)
}
clearCanvas() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
}
mount(el: MaybeElement) {
insertElement(el, this.canvas, null)
this.listen()
return this
}
setColor(color: string) {
this.color = color
this.ctx.strokeStyle = color
}
unmount() {
removeElement(this.canvas)
this.stop.forEach(s => s())
}
listen() {
useEventListener(this.canvas, 'mousedown', () => {
this.active = true
})
useEventListener(this.canvas, 'mouseup', () => {
this.active = false
const { width, height } = this.canvas
const imageData = this.ctx.getImageData(0, 0, width, height)
this.historyStack.push(imageData)
})
useEventListener(this.canvas, 'mouseout', () => {
this.active = false
})
useKeyBoard('Ctrl+z', () => this.undo())
useKeyBoard('Ctrl+x', () => this.redo())
}
undo() {
if (this.historyStack.length === 0)
return
// 清空画布
this.clearCanvas()
// 删除当前操作
this.resetStack.push(this.historyStack.pop()!)
// 逐个执行绘图动作进行重绘
this.historyStack.forEach(imageData =>
this.ctx.putImageData(imageData, 0, 0),
)
}
redo() {
if (this.resetStack.length === 0)
return
// 清空画布
this.clearCanvas()
// 删除当前操作
this.historyStack.push(this.resetStack.pop()!)
// 逐个执行绘图动作进行重绘
this.historyStack.forEach(imageData =>
this.ctx.putImageData(imageData, 0, 0),
)
}
erase(lineWidth = 2) {
this.ctx.lineWidth = lineWidth
this.ctx.strokeStyle = 'rgba(255, 255, 255, 1)'
this.ctx.globalCompositeOperation = 'destination-out'
}
unerased() {
this.ctx.strokeStyle = this.color
this.ctx.globalCompositeOperation = 'source-over'
}
save() {
return this.canvas.toDataURL('image/png')
}
} |
// components/RegisterForm.js
"use client"
import React, { useState } from 'react';
import { useRouter } from "next/navigation";
import { toast } from "react-toastify";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
const FormEduc = () => {
const schema = yup
.object({
titulo: yup.string().required("El titulo es obligatorio"),
institucion: yup.string().required("La institución es obligatoria"),
localidad: yup.string().required("La localidad es obligatoria"),
fecha_inicio: yup.string().required("La fecha de inicio es obligatoria"),
fecha_fin: yup.string().required("La fecha de fin es obligatorio"),
descripcion: yup.string().required("La descripción es obligatorio"),
})
.required();
const router = useRouter();
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: yupResolver(schema),
});
// const handleRegister = async (e, redirectToNextForm) => {
// e.preventDefault();
// try {
// // Realiza la solicitud de registro a tu API
// const response = await fetch('/api/education', {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json',
// },
// body: JSON.stringify({ id_curri:"6",titulo, institucion, localidad, fecha_inicio, fecha_fin, descripcion }),
// });
// if (response.ok) {
// // Registro exitoso
// const userData = await response.json();
// console.log('Registro hecho', userData);
// toast.success('Registro hecho');
// if (redirectToNextForm) {
// // Redirigir a la siguiente página
// router.push('/dashboard/form_edu');
// } else {
// // No redirigir, simplemente actualizar la página
// location.reload();
// }
// } else {
// // Maneja el error en el registro
// const errorData = await response.json();
// console.error('Error en el registro:', errorData.message);
// toast.error('Error en el registro');
// }
// } catch (error) {
// console.error('Error en el registro:', error.message);
// toast.error('Error en el registro');
// }
// };
const onSubmit = async (data) => {
try {
const response = await fetch("/api/education", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
if (response.ok) {
toast.success("Registro exitoso");
router.push("/dashboard/form_educ");
} else {
const errData = await response.json();
toast.error("Error en el registro");
}
} catch (error) {
console.error("Error en el registro:", error);
toast.error("Error en el registro");
}
};
return (
<div className="max-w-md mx-auto p-6 bg-white rounded-md shadow-lg ">
<h1 className='text-black font-bold text-xl text-center mb-2'>Educación</h1>
<form onSubmit={handleSubmit(onSubmit)}>
<div className='flex space-x-6'>
<div>
<div className="mb-4">
<label htmlFor="Titulo" className="block text-sm font-semibold text-gray-600">
Titulo
</label>
<input
type="text"
id="titulo"
className="mt-1 p-2 w-full border rounded-md focus:outline-none focus:ring focus:border-blue-300 text-slate-600"
{...register("titulo")}
/>
<p className="text-red-600">{errors.titulo?.message}</p>
</div>
<div className="mb-4">
<label htmlFor="Institucion" className="block text-sm font-semibold text-gray-600">
Institucion
</label>
<input
type="text"
id="institucion"
className="mt-1 p-2 w-full border rounded-md focus:outline-none focus:ring focus:border-blue-300 text-slate-600"
{...register("institucion")}
/>
<p className="text-red-600">{errors.institucion?.message}</p>
</div>
<div className="mb-4">
<label htmlFor="localidad" className="block text-sm font-semibold text-gray-600">
Localidad
</label>
<input
type="text"
id="localidad"
className="mt-1 p-2 w-full border rounded-md focus:outline-none focus:ring focus:border-blue-300 text-slate-600"
{...register("localidad")}
/>
<p className="text-red-600">{errors.nombre?.message}</p>
</div>
</div>
<div>
<div className="mb-4">
<label htmlFor="fecha_inicio" className="block text-sm font-semibold text-gray-600">
Fecha de Inicio
</label>
<input
type="date"
id="telefono"
className="mt-1 p-2 w-full border rounded-md focus:outline-none focus:ring focus:border-blue-300 text-slate-600"
{...register("fecha_inicio")}
/>
<p className="text-red-600">{errors.fecha_inicio?.message}</p>
</div>
<div className="mb-4">
<label htmlFor="fecha_fin" className="block text-sm font-semibold text-gray-600">
Fecha de Fin
</label>
<input
type="date"
id="fecha_fin"
className="mt-1 p-2 w-full border rounded-md focus:outline-none focus:ring focus:border-blue-300 text-slate-600"
{...register("fecha_fin")}
/>
<p className="text-red-600">{errors.fecha_fin?.message}</p>
</div>
</div>
</div>
<div className="mb-4">
<label htmlFor="contra" className="block text-sm font-semibold text-gray-600">
Descripción
</label>
<input
type="text"
id="descripcion"
className="mt-1 p-2 w-full border rounded-md focus:outline-none focus:ring focus:border-blue-300 text-slate-600"
{...register("descripcion")}
/>
<p className="text-red-600">{errors.descripcion?.message}</p>
</div>
<div className='flex justify-between'>
<button
type="submit"
className="w-32 bg-blue-500 text-white py-2 rounded-sm font-bold hover:bg-blue-600"
>
Agregar más
</button>
<button
type="submit"
className="w-32 bg-blue-500 text-white py-2 rounded-sm font-bold hover:bg-blue-600"
>
Siguiente
</button>
</div>
</form>
</div>
);
};
export default FormEduc; |
import { Injectable } from '@angular/core';
import { Observable, of, from } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators'
import { User } from './user';
import { MessageService } from './message.service';
import { Guid } from 'guid-typescript';
@Injectable({
providedIn: 'root'
})
export class UserService {
private UserUrl = 'http://localhost:5000/api/users'; //Url da API
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
/*Método contrutor*/
constructor(
private http: HttpClient,
private messageService: MessageService) { }
/*GET ALL Users*/
getUsers(): Observable<User[]> {
return this.http.get<User[]>(this.UserUrl)
.pipe(
tap(_ => this.log('fetched heroes')),
catchError(this.handleError<User[]>('getUsers', []))
);
}
/** GET User by id. Will 404 if id not found */
getUser(id: string): Observable<User> {
const url = `${this.UserUrl}/${id}`;
return this.http.get<User>(url).pipe(
tap(_ => this.log(`fetched hero id=${id}`)),
catchError(this.handleError<User>(`getHero id=${id}`))
);
}
/** GET hero by id. Return `undefined` when id not found */
getUserNo404<Data>(id: number): Observable<User> {
const url = `${this.UserUrl}/?id=${id}`;
return this.http.get<User[]>(url)
.pipe(
map(heroes => heroes[0]), // returns a {0|1} element array
tap(h => {
const outcome = h ? `fetched` : `did not find`;
this.log(`${outcome} hero id=${id}`);
}),
catchError(this.handleError<User>(`getHero id=${id}`))
);
}
/* GET User whose name contains search term */
searchUser(term: string): Observable<User[]> {
if (!term.trim()) {
// if not search term, return empty hero array.
return of([]);
}
return this.http.get<User[]>(`${this.UserUrl}/?name=${term}`).pipe(
tap(_ => this.log(`found heroes matching "${term}"`)),
catchError(this.handleError<User[]>('searchHeroes', []))
);
}
//////// Save methods //////////
/** POST: add a new User to the server */
addUser(use: User): Observable<User> {
return this.http.post<User>(this.UserUrl, use, this.httpOptions).pipe(
tap((newUser: User) => this.log(`added User w/ id=${newUser.id}`)),
catchError(this.handleError<User>('addUser'))
);
}
/** PUT: update the User on the server */
updateUser(use: User): Observable<any> {
return this.http.put(this.UserUrl, use, this.httpOptions).pipe(
tap(_ => this.log(`updated User id=${use.id}`)),
catchError(this.handleError<any>('updateUser'))
);
}
/** DELETE: delete the User from the server */
deleteUser(user: string): Observable<User> {
const url = `${this.UserUrl}/${user}`;
return this.http.delete<User>(url).pipe(
tap(_ => this.log(`deleted User`)),
catchError(this.handleError<User>('deleteUser'))
);
}
/** DELETE: delete the User from the server */
deleteUser2(user: User | string): Observable<User> {
const id = typeof user === 'string' ? user : user.id;
const url = `${this.UserUrl}/${id}`;
return this.http.delete<User>(url, this.httpOptions).pipe(
tap(_ => this.log(`deleted User id=${id}`)),
catchError(this.handleError<User>('deleteUser'))
);
}
/**
* Handle Http operation that failed.
* Let the app continue.
* @param operation - name of the operation that failed
* @param result - optional value to return as the observable result
*/
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
this.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
}
}
/*Método que envia a mensagem de log */
private log(message: string) {
this.messageService.add(`HeroService: ${message}`);
}
} |
<template>
<section :style="`background-image: url(${Image})`"
class="h-full bg-no-repeat bg-cover bg-center">
<div class="text-white h-full w-full bg-black/20 backdrop-brightness-50">
<div class="flex flex-col items-center justify-center">
<h1 class="text-6xl mx-12 font-bold mt-12">Having any issues? <br><span
class="text-4xl flex mt-6 justify-center items-center text-center">
We are here to help</span></h1>
<p class="mt-5 lg:w-6/12 mx-12 text-lg text-center">
We are here to answer any questions you may have.
Reach Out to Our Team Today!
</p>
</div>
<div class="flex justify-center items-center flex-col gap-12 mx-12 my-12">
<div class="lg:w-8/12 justify-center items-center p-5 w-full flex flex-col gap-2 order-2">
<h1 class="text-3xl mb-3">Interested in learning more about our solutions?</h1>
<div class="flex w-1/2 mx-auto gap-6 items-center">
<FontAwesomeIcon :icon="faEnvelope"/>
<h4 class="text-center">info@erev.co.ke</h4>
</div>
<div class="flex gap-6 w-1/2 mx-auto items-center">
<FontAwesomeIcon :icon="faPhone"/>
<h4>+254 706 798 820</h4>
</div>
</div>
<div class="lg:w-8/12 w-full px-5 rounded">
<div class="font-thin text-sm ">
<form novalidate @submit="onSubmit"
class="">
<div class="flex gap-3 lg:flex-row flex-col">
<FormInput
label="Enter Your First Name"
name="firstname"
class="text-white w-full text-sm tracking-wide"
placeholder="Enter your first name"
type="text"
/>
<FormInput
label="Enter Your Last Name"
name="lastname"
class="text-white w-full text-sm tracking-wide"
placeholder="Enter your last name"
type="text"
/>
</div>
<div class="flex gap-3 lg:flex-row flex-col">
<FormInput
label="Enter Email Address"
name="email"
class="text-white w-full text-sm tracking-wide"
placeholder="Enter your Email"
type="email"
/>
<FormInput
label="Enter Phone Number"
name="email"
class="text-white w-full text-sm tracking-wide"
placeholder="Enter your Phone Number"
type="number"
/>
</div>
<RadioButton
:options="options"
title="Select Subject"
name="subject"/>
<FormTextBox
name="message"
label="Enter Message"
placeholder="Enter your message"/>
<button type="submit" class="login-button mb-1 w-full mt-4">SubMit
</button>
</form>
</div>
</div>
</div>
</div>
</section>
</template>
<script lang='ts' setup>
import Image from '@assets/images/contact.svg';
import {faEnvelope, faPhone} from '@fortawesome/free-solid-svg-icons';
import {FontAwesomeIcon} from '@fortawesome/vue-fontawesome';
import {useForm} from 'vee-validate';
import {ref} from 'vue';
import FormInput from '@/common/components/FormInput.vue';
import FormTextBox from '@/common/components/FormTextBox.vue';
import RadioButton from '@/common/components/RadioButton.vue';
import useUnexpectedErrorHandler from '@/common/composables/useUnexpectedErrorHandler';
import ValidationError from '@/common/errors/ValidationError';
const options = ref([
{name: 'Support', value: 'support'},
{name: 'Error', value: 'error'},
{name: 'Complaint', value: 'complaint'},
{name: 'Compliment', value: 'compliment'},
{name: 'General', value: 'general'},
]);
const handleUnexpectedError = useUnexpectedErrorHandler();
const {handleSubmit, setErrors, setFieldError, setFieldValue} = useForm<{
firstname: string;
lastname: string;
email: string;
subject: string;
remember: boolean;
}>({
initialValues: {
firstname: '',
lastname: '',
email: '',
subject: '',
remember: false,
},
});
const onSubmit = handleSubmit(async (values) => {
try {
console.log(values); // eslint-disable-line
} catch (err) {
if (err instanceof ValidationError) {
setErrors(err.messages);
if (err.messages._) {
setFieldError('email', err.messages._);
}
} else {
setFieldError('email', 'Something went wrong.');
handleUnexpectedError(err);
}
} finally {
setFieldValue('firstname', '');
}
});
</script>
<style scoped>
.login-button {
@apply bg-secondary text-white flex items-center justify-center font-bold;
@apply rounded-md h-12;
@apply uppercase;
}
</style> |
import DBService from '../db/DBService'
import supabase from '../config/supabase'
import { PacientePayload, PacienteResponse } from '../types/paciente'
export default class PacienteService implements DBService {
async getOne(id: string): Promise<PacienteResponse | null> {
const { data: pacientes, error } = await supabase
.from('paciente')
.select('*')
.eq('id', id)
if (error) {
console.log(error)
}
if (!pacientes || pacientes.length === 0) {
throw new Error('No se encontró ningún paciente con el ID proporcionado')
}
const paciente = pacientes[0] as PacienteResponse
return paciente
}
async getMany(offset: number, limit: number): Promise<PacienteResponse[]> {
const { data: pacientes, error } = await supabase
.from('paciente')
.select('*')
.range(offset, limit + offset - 1)
if (error) {
console.log(error)
}
return pacientes as PacienteResponse[]
}
async createOne(payload: PacientePayload): Promise<PacienteResponse> {
const { data: pacientes, error } = await supabase
.from('paciente')
.insert([{ ...payload }])
.select('*')
if (error) {
console.log(error)
}
if (!pacientes || pacientes.length === 0) {
throw new Error('No se encontró ningún paciente con el ID proporcionado')
}
return pacientes[0] as PacienteResponse
}
async deleteOne(id: string): Promise<void> {
const { error } = await supabase.from('paciente').delete().eq('id', id)
if (error) {
console.log(error)
}
}
async updateOne(
id: string,
payload: PacientePayload,
): Promise<PacienteResponse> {
const { data: pacientes, error } = await supabase
.from('paciente')
.update({ ...payload })
.eq('id', id)
.select('*')
if (error) {
console.log(error)
}
if (!pacientes || pacientes.length === 0) {
throw new Error('No se encontró ningún paciente con el ID proporcionado')
}
const paciente = pacientes[0] as PacienteResponse
return paciente
}
} |
# Explore the data as follows:
import pandas as pd
# Downloading the file and loading it into a Pandas dataframe
url = 'https://e.centennialcollege.ca/content/enforced/1010634-COMP309401_2023F/Misissagua_dealer.txt?_&d2lSessionVal=AJOR2OlmrARDauUz5Y2Dwd7cB'
df2_fatimah = pd.read_csv(url, delimiter='\t')
# Explore the data
# 1. Print the names of columns
print("Column Names:")
print(df2_fatimah.columns)
# 2. Print the types of columns
print("\nColumn Types:")
print(df2_fatimah.dtypes)
# 3. Print statistics count, min, mean, std, 1st quartile, median, 3rd quartile, max of numeric columns
print("\nNumeric Column Statistics:")
print(df2_fatimah.describe())
# 4. Print the first three records
print("\nFirst Three Records:")
print(df2_fatimah.head(3))
# 5. Print a summary of all missing values in all columns
print("\nSummary of Missing Values:")
print(df2_fatimah.isnull().sum())
# Preprocess the data:
import pandas as pd
from sklearn.preprocessing import StandardScaler
# Step 1: Convert categorical columns into numeric values using get_dummies and drop original columns
df2_fatimah_numeric = pd.get_dummies(df2_fatimah, drop_first=True)
# Step 2: Check for missing values
if df2_fatimah_numeric.isnull().sum().sum() == 0:
print("\nNo Missing Values in the DataFrame.")
# Step 3: Save the new numeric dataset
df2_fatimah_numeric.to_csv('df2_fatimah_numeric.csv', index=False)
# Step 4: Standardize the numeric dataframe
scaler = StandardScaler()
df2_fatimah_standardized = pd.DataFrame(scaler.fit_transform(df2_fatimah_numeric), columns=df2_fatimah_numeric.columns)
# Step 5: Print statistics for the standardized dataframe
statistics_df = df2_fatimah_standardized.describe()
print("\nStatistics for Standardized DataFrame:")
print(statistics_df)
# Step 6: Save the standardized dataframe
df2_fatimah_standardized.to_csv('df2_fatimah_standardized.csv', index=False)
# Build a model
import pandas as pd
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
# Load the standardized dataframe
df2_fatimah_standardized = pd.read_csv('df2_fatimah_standardized.csv')
# Perform K-means clustering with 5 clusters
kmeans = KMeans(n_clusters=5, random_state=42)
df2_fatimah_standardized['cluster_fatimah'] = kmeans.fit_predict(df2_fatimah_standardized)
# Plot a histogram of the clusters
plt.figure(figsize=(8, 6))
plt.hist(df2_fatimah_standardized['cluster_fatimah'], bins=range(6), align='left', edgecolor='black', alpha=0.7)
plt.title("fatimah_clusters")
plt.xlabel("Cluster Number")
plt.ylabel("Number of Observations")
plt.xticks(range(5))
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()
# Print the number of observations in each cluster
cluster_counts = df2_fatimah_standardized['cluster_fatimah'].value_counts()
print("\nNumber of Observations in Each Cluster:")
print(cluster_counts) |
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { map } from 'rxjs/operators';
import { tokenNotExpired } from "angular2-jwt";
@Injectable({
providedIn: 'root'
})
export class AuthService {
authToken: any;
user: any;
constructor(private http: HttpClient) { }
registerUser(user) {
let headers = new HttpHeaders().set('Content-Type', 'application/json');
return this.http.post('http://localhost:5000/users/register', user, { headers: headers }).pipe(map((res: any) => res));
}
authenticateUser(user) {
let headers = new HttpHeaders().set('Content-Type', 'application/json');
return this.http.post('http://localhost:5000/users/authenticate', user, { headers: headers }).pipe(map((res: any) => res));
}
getProfile() {
this.loadToken();
let headers = new HttpHeaders().set('Content-Type', 'application/json');
console.log(this.authToken);
headers.append('Authorization',this.authToken);
return this.http.get('http://localhost:5000/users/profile', { headers: headers }).pipe(map((res: any) => res));
}
storeUserData(token, user) {
localStorage.setItem('id_token', token);
localStorage.setItem('user', JSON.stringify(user));
this.authToken = token;
this.user = user;
}
loadToken(){
const token = localStorage.getItem('id_token');
this.authToken = token;
}
loggedIn(){
return true;
}
logout() {
this.authToken = null;
this.user = null;
localStorage.clear();
}
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>자바스크립트</title>
<body>
<h1>함수 객체와 메서드</h1>
<script>
"use strict"
function f1(){
console.log("Hello!");
}
//함수 = 객체 + 함수 몸체(코드)
// => 함수 호출을 통해 함수 코드를 실행할 수 있다.
f1();
// => 또한 함수도 객체이기 때문에 프로퍼티를 마음껏 추가할 수 있다.
//같은 소속 동료 = this
f1.value=100;
f1.plus=function(v){this.value += v}; //f1.plus=function(v){f1.value += v};
f1.hello = function(){console.log("hello~~~")};
f1.plus(200);
console.log(f1.value);
f1.hello();
</script>
</body>
</html> |
<template>
<div class="bg-white dark:bg-black dark:text-white py-12">
<div class="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
<div class="lg:text-center">
<h2 class="text-lg font-semibold text-secondary">Benefits</h2>
<p class="mt-2 text-3xl font-bold leading-8 tracking-tight text-primary sm:text-4xl">The world's only megaconglomerate</p>
<p class="mt-4 max-w-2xl text-xl text-gray-500 lg:mx-auto">From airlines, to zoos, Ryan Enterprises is the world's premire megaconglomerate. Offering a wide range of services, we are the only company in the world that offers these benefits. </p>
</div>
<div class="mt-10">
<dl class="space-y-10 md:grid md:grid-cols-2 md:gap-x-8 md:gap-y-10 md:space-y-0">
<div v-for="feature in features" :key="feature.name" class="relative">
<dt>
<div class="absolute flex h-12 w-12 items-center justify-center rounded-md bg-primary text-white">
<component :is="feature.icon" class="h-6 w-6" aria-hidden="true" />
</div>
<p class="ml-16 text-lg font-medium leading-6 text-gray-900">{{ feature.name }}</p>
</dt>
<dd class="mt-2 ml-16 text-base text-gray-500">{{ feature.description }}</dd>
</div>
</dl>
</div>
</div>
</div>
</template>
<script setup>
import newspaper from '../../node_modules/bootstrap-icons/icons/newspaper.svg'
import box from '../../node_modules/bootstrap-icons/icons/box.svg'
import geo from '../../node_modules/bootstrap-icons/icons/geo-fill.svg'
import shield from '../../node_modules/bootstrap-icons/icons/shield.svg'
const features = [
{
name: 'Free, passive marketing',
description:
'Studies show that customers are 300% more likely to buy a product if the brand is part of Ryan Enterprises',
icon: newspaper,
},
{
name: 'End-to-end supply chain coverage',
description:
'From concept, to manufacturing, to sales and marketing, we\'ve got you covered every step of the way',
icon: box,
},
{
name: 'Endless locations',
description:
'With locations all across the United States, and loacations in China, France, Sweden, and Canada, you\'re always close to a location.',
icon: geo,
},
{
name: 'Tax Security',
description:
'All Ryan Enterprises subsidiaries are exempt from taxes. Federal, State, Municipal, Organizational... you name it, Ryan Enterprises companies are exempt',
icon: shield,
},
]
</script> |
import 'package:flutter/material.dart';
import 'package:quizapp/models/question.dart';
import 'package:quizapp/screens/check_answer.dart';
class QuizFinishedPage extends StatefulWidget {
final List<Question> questions;
final Map<int, dynamic> answers;
QuizFinishedPage({Key? key, required this.questions, required this.answers})
: super(key: key);
@override
State<QuizFinishedPage> createState() => _QuizFinishedPageState();
}
class _QuizFinishedPageState extends State<QuizFinishedPage> {
int? correctAnswer;
@override
Widget build(BuildContext context) {
int correct = 0;
this.widget.answers.forEach((index, value) {
if (this.widget.questions[index].correctAnswer == value) correct++;
});
final TextStyle titleStyle = TextStyle(
color: Colors.black87, fontSize: 16.0, fontWeight: FontWeight.w500);
final TextStyle trailingStyle = TextStyle(
color: Theme.of(context).primaryColor,
fontSize: 20.0,
fontWeight: FontWeight.bold);
return Scaffold(
appBar: AppBar(
title: Text('Result'),
elevation: 0,
),
body: Container(
height: double.infinity,
width: double.infinity,
decoration: BoxDecoration(
gradient: LinearGradient(colors: [
Theme.of(context).primaryColor,
Theme.of(context).colorScheme.secondary
], begin: Alignment.topCenter, end: Alignment.bottomCenter)),
child: SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Column(children: <Widget>[
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0)),
child: ListTile(
contentPadding: const EdgeInsets.all(10.0),
title: Text(
"Total Questions",
style: titleStyle,
),
trailing: Text(
"${widget.questions.length}",
style: trailingStyle,
),
),
),
SizedBox(
height: 10,
),
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0)),
child: ListTile(
contentPadding: const EdgeInsets.all(16.0),
title: Text("Score", style: titleStyle),
trailing: Text("${correct / widget.questions.length * 100}%",
style: trailingStyle),
),
),
SizedBox(height: 10.0),
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0)),
child: ListTile(
contentPadding: const EdgeInsets.all(16.0),
title: Text("Correct Answers", style: titleStyle),
trailing: Text("$correct/${widget.questions.length}",
style: trailingStyle),
),
),
SizedBox(height: 10.0),
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0)),
child: ListTile(
contentPadding: const EdgeInsets.all(16.0),
title: Text("Incorrect Answers", style: titleStyle),
trailing: Text(
"${widget.questions.length - correct}/${widget.questions.length}",
style: trailingStyle),
),
),
SizedBox(height: 20.0),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(
horizontal: 16.0, vertical: 20.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0)),
backgroundColor: Theme.of(context)
.colorScheme
.secondary
.withOpacity(0.8),
),
onPressed: () => Navigator.pop(context),
child: Text("Go to Home")),
ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(
horizontal: 16.0, vertical: 20.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
backgroundColor: Theme.of(context).primaryColor,
),
child: Text("Check Answers"),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => CheckAnswersPage(
questions: widget.questions,
answers: widget.answers,
)));
},
),
],
)
]),
),
));
}
} |
import React from 'react';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { useTranslation } from 'react-i18next';
import HomeNavigator from './home';
import ShoppingCartNavigator from './shoppingCart';
import FriendListNavigator from './friendList';
import { Image } from 'react-native';
const Tab = createBottomTabNavigator();
const getSource = (route: string, focused: boolean) => {
switch (route) {
case 'Home':
return focused ?
require('../assets/tab/home-activated.png') :
require('../assets/tab/home-inactivated.png');
case 'ShoppingCartTab':
return focused ?
require('../assets/tab/shoppingcart-activated.png') :
require('../assets/tab/shoppingcart-inactivated.png');
case 'FriendList':
return focused ?
require('../assets/tab/message-activated.png') :
require('../assets/tab/message-inactivated.png');
default:
break
}
}
const TabNavigator = () => {
const { i18n, t } = useTranslation();
return (
<Tab.Navigator
screenOptions={({ route }) => ({
tabBarIcon: ({ focused }) => (
<Image
style={{ resizeMode: 'cover', width: 28, height: 28 }}
source={getSource(route.name, focused)}
/>
),
tabBarOptions: {
activeTintColor: 'red',
}
})}>
<Tab.Screen name="Home" component={HomeNavigator} options={{ title: i18n.t('header.home')}}/>
<Tab.Screen name="ShoppingCartTab" component={ShoppingCartNavigator} options={{ title: i18n.t('tab.shoppingCart')}}/>
<Tab.Screen name="FriendList" component={FriendListNavigator} options={{ title: i18n.t('tab.friendList')}}/>
</Tab.Navigator>
);
}
export default TabNavigator; |
import { useQuery, useMutation } from '@apollo/client'
import { Box, Container, FormControl, FormErrorMessage, FormHelperText, FormLabel, Input, Modal, ModalBody, ModalCloseButton, ModalContent, ModalHeader, ModalOverlay, Text, useDisclosure, Button, ModalFooter, InputRightElement, InputGroup } from '@chakra-ui/react'
import React, { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { CHECKRESET } from '../utils/queries'
import { ADDRESETREQUEST, UPDATEPASSWORDRESET } from '../utils/mutations'
export default function PasswordReset() {
//Get the request id from the url if it is there
const { passwordResetId } = useParams()
const navigate = useNavigate()
//States to handle the form data
const [email, setEmail] = useState('')
const [emailError, setEmailError] = useState('')
const [newPassword, setNewPassword] = useState('')
const [newPasswordError, setNewPasswordError] = useState('')
const [newPasswordShow, setNewPasswordShow] = useState(false)
const [confirmPassword, setConfirmPassword] = useState('')
const [confirmPasswordError, setConfirmPasswordError] = useState('')
const [confirmPasswordShow, setConfirmPasswordShow] = useState(false)
const [modalMessage, setModalMessage] = useState('')
const [modalUrl, setModalUrl] = useState('')
const { isOpen, onOpen, onClose } = useDisclosure()
//Consts for the queries and mutations
const { data, loading, error } = useQuery(CHECKRESET, {
variables: { id: passwordResetId },
skip: !passwordResetId
})
const [addResetRequest] = useMutation(ADDRESETREQUEST)
const [updatePasswordReset] = useMutation(UPDATEPASSWORDRESET)
//Functions for the functionality of the request form
const handleEmailChange = (e) => {
setEmail(e.target.value)
setEmailError('')
}
const handleEmailBlur = (e) => {
if (e.target.value === "" || !/^([a-z0-9_.-]+)@([\da-z.-]+)\.([a-z.]{2,6})$/.test(e.target.value)) {
setEmailError("Invalid email")
}
}
const handleRequestFormSubmit = async (e) => {
e.preventDefault()
try {
await addResetRequest({
variables: { email: email }
})
setModalMessage('If there is an email associated with this account, then a password reset will be sent to the email. Make sure to check spam folders for the email. The request will expire in 1 hour.')
onOpen()
setEmail("")
} catch (e) {
if (e.message.includes('No user with email')) {
setEmailError('No user with email')
} else {
setEmailError('Password reset already exists')
}
}
}
//Functions for the functionality of the reset form
const handlePasswordChange = (e) => {
setNewPasswordError("")
setNewPassword(e.target.value)
}
const handleConfirmPasswordChange = (e) => {
setConfirmPasswordError('')
setConfirmPassword(e.target.value)
}
const handlePasswordBlur = (e) => {
if (e.target.value === "" || !/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&#^()_\-+=.])[A-Za-z\d@$!%*?&#^()_\-+=.]{8,16}$/.test(e.target.value)) {
setNewPasswordError("Invalid Password")
}
}
const handleConfirmPasswordBlur = (e) => {
if (confirmPassword !== newPassword) {
setConfirmPasswordError("Password do not match")
}
}
const handleNewPasswordFormSubmit = async (e) => {
e.preventDefault()
if (data.passwordReset.used) {
setModalMessage("Password reset already used. Please try again")
setModalUrl('/passwordreset')
onOpen()
}
try {
if (newPassword && !newPasswordError) {
await updatePasswordReset({
variables: { id: passwordResetId, newPassword: newPassword }
})
setModalMessage('Password updated')
setModalUrl('/login')
onOpen()
}
} catch (e) {
alert(e)
}
}
useEffect(() => {
if (!loading) {
if (passwordResetId && !data) {
if (error.message.includes("Password reset already used")) {
setModalMessage("Password reset already used. Please try again.")
setModalUrl("/passwordreset")
onOpen()
} else {
setModalMessage("Invalid reset token, please try again")
setModalUrl("/passwordreset")
onOpen()
}
}
}
}, [data, onOpen, passwordResetId, loading, error])
if (passwordResetId && data) {
return (
<Box bgGradient="linear(to-r, #24102c, #110914, #24102c)" p={6} h='100Vh'>
<Text fontSize="6xl" textAlign='center' color='white'>Password Reset</Text>
<Text fontSize="1xl" textAlign='center' color='white'>Reset your password with the form below</Text>
<Container boxShadow='dark-lg' borderRadius="6px" >
<form onSubmit={handleNewPasswordFormSubmit}>
<FormControl isInvalid={newPasswordError} isRequired aria-required>
<FormLabel id='newPassword' htmlFor='newPassword' color="white">New Password:</FormLabel>
<InputGroup>
<Input
id='newPassword'
autoComplete='new-password'
focusBorderColor="#8c34eb"
boxShadow='dark-lg'
boxSizing="border-box"
width="100%"
padding="12px 20px"
m="8px 0"
border="2px solid #8c34eb"
color="white"
type={newPasswordShow ? 'text' : 'password'}
value={newPassword}
placeholder='New Password'
onChange={handlePasswordChange}
onBlur={handlePasswordBlur}
/>
<InputRightElement w='4.5 rem' m="8px 0">
<Button tabIndex='-1' h='1.75 rem' size="sm" colorScheme="purple" onMouseEnter={() => setNewPasswordShow(!newPasswordShow)} onMouseLeave={() => setNewPasswordShow(!newPasswordShow)} >{newPasswordShow ? 'Hide' : 'Show'}</Button>
</InputRightElement>
</InputGroup>
{newPasswordError ? (
<FormErrorMessage>
Invalid password
</FormErrorMessage>
) : (
<FormHelperText>
Pick a strong password 8-16 characters long containing at least one uppercase letter, one lowercase letter, one number, and at least one special character
</FormHelperText>
)}
</FormControl>
<FormControl isInvalid={confirmPasswordError} isRequired aria-required>
<FormLabel id='confirmNewPassword' htmlFor='confirmNewPassword' color="white">Confirm Password:</FormLabel>
<InputGroup>
<Input
id='confirmNewPassword'
autoComplete='true'
focusBorderColor="#8c34eb"
boxShadow='dark-lg'
boxSizing="border-box"
width="100%"
padding="12px 20px"
m="8px 0"
border="2px solid #8c34eb"
color="white"
type={confirmPasswordShow ? 'text' : 'password'}
value={confirmPassword}
placeholder='New Password'
onChange={handleConfirmPasswordChange}
onBlur={handleConfirmPasswordBlur}
/>
<InputRightElement w='4.5 rem' m="8px 0">
<Button tabIndex='-1' h='1.75 rem' size="sm" colorScheme="purple" onMouseEnter={() => setConfirmPasswordShow(!confirmPasswordShow)} onMouseLeave={() => setConfirmPasswordShow(!confirmPasswordShow)} >{confirmPasswordShow ? 'Hide' : 'Show'}</Button>
</InputRightElement>
</InputGroup>
</FormControl>
{confirmPasswordError && (
<FormErrorMessage>
{confirmPasswordError}
</FormErrorMessage>
)}
<FormControl>
<Button type="submit" colorScheme="purple" onClick={handleNewPasswordFormSubmit} m='4' shadow='md' _hover={{
bg: 'purple.800',
transform: 'scale(1.05)'
}}> Reset Password
</Button>
</FormControl>
</form>
</Container>
<Modal isOpen={isOpen} onClose={() => {
onClose()
if (modalUrl) {
navigate(modalUrl)
setModalUrl('')
}
}}>
<ModalOverlay />
<ModalContent>
<ModalHeader>Password Reset</ModalHeader>
<ModalCloseButton />
<ModalBody>
{modalMessage}
</ModalBody>
<ModalFooter>
<Button colorScheme='blue' mr={3} onClick={() => {
onClose()
if (modalUrl) {
navigate(modalUrl)
setModalUrl('')
}
}}>
Close
</Button>
</ModalFooter>
</ModalContent>
</Modal>
</Box>
)
} else {
return (
<Box bgGradient="linear(to-r, #24102c, #110914, #24102c)" p={6} h='100Vh'>
<Text fontSize="6xl" textAlign='center' color='white'>Password Reset</Text>
<Text fontSize="1xl" textAlign='center' color='white'>Reset your password with the form below</Text>
<Container boxShadow='dark-lg' borderRadius="6px" >
<form onSubmit={handleRequestFormSubmit}>
<FormControl isInvalid={emailError} isRequired aria-required>
<FormLabel id='emailLabel' htmlFor='email' color='white'>Email:</FormLabel>
<Input
id="email"
autoComplete="true"
focusBorderColor="#8c34eb"
boxShadow='dark-lg'
boxSizing="border-box"
width="100%"
padding="12px 20px"
m="8px 0"
border="2px solid #8c34eb"
color="white"
type="email"
value={email}
placeholder="Email"
onChange={handleEmailChange}
onBlur={handleEmailBlur}
/>
{emailError ? (
<FormErrorMessage>
{emailError}
</FormErrorMessage>
) : (
<FormHelperText>
Use the email you signed up with
</FormHelperText>
)}
</FormControl>
<FormControl>
<Button type='button' colorScheme='green' onClick={handleRequestFormSubmit} m='4' shadow='md' _hover={{
bg: 'teal.600',
transform: 'scale(1.05)'
}}>Submit</Button>
<Button type='button' colorScheme='purple' onClick={() => window.location.href = "/login"} m='4' shadow='md' _hover={{
bg: "purple.800",
transform: 'scale(1.05)'
}}>Back to Login</Button>
</FormControl>
</form>
</Container>
<Modal isOpen={isOpen} onClose={() => {
onClose()
if (modalUrl) {
navigate(modalUrl)
setModalUrl('')
}
}}>
<ModalOverlay />
<ModalContent>
<ModalHeader>Password Reset</ModalHeader>
<ModalCloseButton />
<ModalBody>
{modalMessage}
</ModalBody>
<ModalFooter>
<Button colorScheme='blue' mr={3} onClick={() => {
onClose()
if (modalUrl) {
navigate(modalUrl)
setModalUrl('')
}
}}>
Close
</Button>
</ModalFooter>
</ModalContent>
</Modal>
</Box>
)
}
} |
package com.maxpri.common.network;
import com.maxpri.common.entities.Person;
import java.io.Serializable;
import java.util.Collection;
import java.util.stream.Collectors;
public class Response implements Serializable {
private String message;
private Collection<Person> persons;
public Response(String message) {
this.message = message;
}
public Response(Collection<Person> persons) {
this.persons = persons;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void showResult() {
if (persons != null) {
if (persons.isEmpty()) {
System.out.println("Collection is empty.");
return;
}
System.out.println(persons.stream()
.map(Person::toString)
.collect(Collectors.joining("\n")));
return;
}
System.out.println(message);
}
@Override
public String toString() {
return "Response{"
+ "message='" + message + '\''
+ '}';
}
} |
<template>
<div>
<!-- <div id="move-ball-one" class="move-ball">
<i class="el-icon-cold-drink"></i>
</div> -->
<div class="flex">
<el-card class="to-do-list-card" shadow="hover" v-for="item in cardData" :key="item.title">
<template #header>
<div class="card-header">
<div class="col-center">
{{item.title}}
<i class="el-icon-caret-bottom"></i>
</div>
<el-button type="primary" @click="addCount(item)">详情</el-button>
</div>
</template>
<el-drawer v-model="item.cardDetailVisible" direction="ltr" modal-class="drawer-modal-class">
<el-row gutter="5%">
<el-col :span="24">
<span>{{item.target}}</span>
</el-col>
<el-col :span="24">
<el-date-picker value-format="YYYY-MM-DD" @change="dateChange" v-model="item.datePickerData"
type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
</el-date-picker>
</el-col>
<el-col :span="24">
<span>{{item.target}}</span>
</el-col>
</el-row>
<el-button type="primary" @click="onSaveBtnClick(item)">保存</el-button>
</el-drawer>
</el-card>
<div class="to-do-list-card child-center border-1">
<div class="add-icon"></div>
</div>
</div>
<!-- <div class="flex">
<div class="run-ball" style="width: 100%;height: 500px;background: rgb(180, 178, 178);position: relative;">000
</div>
</div> -->
<!-- <a></a> -->
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs,onMounted } from 'vue'
export default defineComponent({
setup() {
const data = reactive({
cardData: [
{
title: 'card1',
count: 0,
cardDetailVisible: false,
target: 'aaaa',
datePickerData: ''
},
{
title: 'card2',
count: 0,
cardDetailVisible: false,
datePickerData: ''
}
]
})
const addCount = function (item: any) {
// console.log(item)
item.count++
// item.cardDetailVisible = true
}
const changeTitle = function () {
data.cardData[1].title = 'ca'
}
const dateChange = function (date: any) {
// console.log(date,date[1],date[2])
}
const onSaveBtnClick = function (item: any) {
// console.log(item)
localStorage.setItem(item.title, JSON.stringify(item))
const getItem = JSON.parse(localStorage.getItem(item.title) + "")
console.log('wwwwwwwwww', getItem)
// console.log(JSON.parse('{"title":"card1","count":1,"cardDetailVisible":true,"target":"aaaa","datePickerData":["2022-03-04","2022-04-12"]}'))
}
// setTimeout(()=>{
// changeTitle()
// }, 1000)
const toRefsData = toRefs(data)
onMounted(()=>{
const moveBallOne = document.getElementById('move-ball-one') as HTMLElement
document.addEventListener('click', function(e){
moveBallOne.style.transform = 'translateY(' + (e.clientY - 50) + 'px)'
moveBallOne.style.transform += 'translateX(' + (e.clientX - 50) + 'px)'
})
const aaa = function() {
console.log('mousemove')
}
})
return {
...toRefsData,
addCount,
dateChange,
onSaveBtnClick
}
}
})
</script>
<style lang="scss" scoped>
.to-do-list-card {
width: 240px;
margin: 5px;
height: 320px;
}
.run-ball:before {
width: 20%;
height: 20%;
/* background: url('../assets/img/6.jpg'); */
background-size: contain;
background-repeat: no-repeat;
z-index: 1111;
position: absolute;
content: '';
margin: 0 0 0 -36%;
}
.run-ball:hover:before {
animation-duration: 10s;
animation-name: runcycle;
/* 循环次数 infinite无限循环*/
animation-iteration-count: infinite;
/* 反着再播一遍 */
animation-direction: alternate;
}
@keyframes runcycle {
from {
margin: 0 0 0 -36%;
}
25% {
margin: 0 0 0 44%;
filter: drop-shadow(16px 16px 20px rgb(245, 255, 110)) invert(75%);
}
50% {
margin: 50% 0 0 44%;
filter: drop-shadow(16px 16px 20px rgb(177, 255, 249)) invert(5%);
}
75% {
margin: 50% 0 0 -36%;
filter: drop-shadow(16px 16px 20px rgb(255, 170, 244)) invert(75%);
}
to {
margin: 0 0 0 -36%;
filter: drop-shadow(16px 16px 20px rgb(139, 255, 145)) invert(5%);
}
}
.col-center {
margin: auto 0;
}
.row-center {
margin: 0 auto;
}
.drawer-modal-class {
background: aqua;
}
.card-header {
display: flex;
justify-content: space-between;
}
.child-center {
display: flex;
justify-content: center;
align-items: center;
}
.border-1 {
border: 1px solid #000;
}
.move-ball{
width: 50px;
height: 50px;
border-radius: 50%;
background: #58c2ff;
z-index: 111;
/* 脱离文档流 */
position: fixed;
transition: 1s;
}
/* .add-icon{
} */
.add-icon {
/* position: absolute; */
width: 60px;
height: 60px;
background: #58c2ff;
-webkit-transform: translate(0, 0) rotate(0deg);
transform: translate(0, 0) rotate(0deg);
border-radius: 50%;
cursor: pointer;
z-index: 100;
/* -webkit-transition: 0.4s cubic-bezier(0.2, 0.6, 0.3, 1.1); */
/* transition: 0.4s cubic-bezier(0.2, 0.6, 0.3, 1.1); */
}
/* .add-icon:after {
content: '';
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
height: 2px;
width: 50%;
background: white;
}
.add-icon:before {
content: '';
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
height: 50%;
width: 2px;
background: white;
}
.add-icon.clicked {
-webkit-transform: translate(-50%, -50%) rotate(360deg);
transform: translate(-50%, -50%) rotate(360deg);
background: #CC2A41;
}
.add-icon.clicked:before {
width: 0;
} */
.flex {
display: flex;
}
* {
margin: 0;
padding: 0;
}
body {
background-color: #000;
}
a {
text-decoration: none;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
font-size: 24px;
background: linear-gradient(90deg, #03a9f4, #f441a5, #03a9f4);
background-size: 400%;
width: 400px;
height: 100px;
color: white;
text-align: center;
line-height: 100px;
text-transform: uppercase;
border-radius: 50px;
}
a:hover::before {
animation: sun 8s infinite;
}
a::before {
content: "";
position: absolute;
left: -5px;
right: -5px;
top: -5px;
bottom: -5px;
/* border: 1px solid red; */
background: linear-gradient(90deg, #03a9f4, #f441a5, #03a9f4);
background-size: 400%;
border-radius: 50px;
filter: blur(20px);
z-index: -1;
}
@keyframes sun {
100% {
background-position: -400% 0;
}
}
</style> |
import { useEffect } from "react";
import { type ActionFunctionArgs, json } from "@remix-run/node";
import { useFetcher } from "@remix-run/react";
import { DescriptionList } from "~/components/custom/DescriptionList";
import { getDescriptions } from "~/services/get-descriptions.server";
import { updateDescription } from "~/services/update-description.server";
import { deleteDescription } from "~/services/delete-description.server";
import type { ShouldRevalidateFunction } from "@remix-run/react";
export async function loader() {
const data = await getDescriptions();
return json(data);
}
export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData();
const formItems = Object.fromEntries(formData);
let data: any = null;
switch (formItems._action) {
case "update":
data = await updateDescription(formItems, formItems.videoId as string);
return json({ data: data, message: "Updated!" });
case "delete":
data = await deleteDescription(formItems.videoId as string);
case "chat":
return json({ data: { description: data, videoId: formItems.videoId } });
default:
return json({ data: null, message: "No action found!" });
}
}
export const shouldRevalidate: ShouldRevalidateFunction = ({ formData }) => {
if (formData?.get("_action") === "chat") return false;
if (formData?.get("_action") === "bookmark") return false;
return true;
};
export function DescriptionListLoader() {
const fetcher = useFetcher();
useEffect(() => {
if (fetcher.state === "idle") {
fetcher.load("/resources/videos");
}
}, []);
const data = fetcher.data;
if (fetcher.state === "loading" || !data) return <p>Loading...</p>;
return <DescriptionList data={data} />;
} |
/*******************************************************************************
* Welcome to the pedestrian simulation framework MomenTUM.
* This file belongs to the MomenTUM version 2.0.2.
*
* This software was developed under the lead of Dr. Peter M. Kielar at the
* Chair of Computational Modeling and Simulation at the Technical University Munich.
*
* All rights reserved. Copyright (C) 2017.
*
* Contact: peter.kielar@tum.de, https://www.cms.bgu.tum.de/en/
*
* Permission is hereby granted, free of charge, to use and/or copy this software
* for non-commercial research and education purposes if the authors of this
* software and their research papers are properly cited.
* For citation information visit:
* https://www.cms.bgu.tum.de/en/31-forschung/projekte/456-momentum
*
* However, further rights are not granted.
* If you need another license or specific rights, contact us!
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
******************************************************************************/
package tum.cms.sim.momentum.model.operational.standing.JohannsonStandingModel;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.math3.util.FastMath;
import tum.cms.sim.momentum.data.agent.pedestrian.state.operational.StandingState;
import tum.cms.sim.momentum.data.agent.pedestrian.state.tactical.TacticalState.Motoric;
import tum.cms.sim.momentum.data.agent.pedestrian.types.IOperationalPedestrian;
import tum.cms.sim.momentum.data.agent.pedestrian.types.IPedestrian;
import tum.cms.sim.momentum.data.agent.pedestrian.types.IPedestrianExtension;
import tum.cms.sim.momentum.data.agent.pedestrian.types.IRichPedestrian;
import tum.cms.sim.momentum.data.layout.obstacle.Obstacle;
import tum.cms.sim.momentum.infrastructure.execute.SimulationState;
import tum.cms.sim.momentum.model.operational.standing.StandingModel;
import tum.cms.sim.momentum.utility.geometry.GeometryFactory;
import tum.cms.sim.momentum.utility.geometry.Segment2D;
import tum.cms.sim.momentum.utility.geometry.Vector2D;
public class JohannsonStanding extends StandingModel {
/**
* Relaxation time [s] (necessary for acceleration).
*/
private double relaxation_time;
/**
* Parameters for level of mass behaviour.
*/
private double mass_behaviour_A; // e.g. = 1.0;
private double mass_behaviour_B;
/**
* Large constants for body force and sliding friction force.
*/
private double physical_interaction_kappa = Double.NEGATIVE_INFINITY; // [kg / s^2]
private double physical_interaction_k = Double.NEGATIVE_INFINITY; // [kg / (m*s)]
/**
* Constant to prevent division by zero and therefore the corruption of the
* algorithm.
*/
public double koesterEpsilon = 10e-6;
private int waitingCase;
/*
* f�r die verschiedenen Ans�tze von Johannson.
* 0= Prefered Velocity; 1= Prefered Position;2=Adapted Prefered
* Position
*/
private double massWaitingPoint = 0.0;
public void callPreProcessing(SimulationState simulationState) {
relaxation_time = this.properties.getDoubleProperty("relaxation_time");
physical_interaction_kappa = this.properties.getDoubleProperty("physical_interaction_kappa");
physical_interaction_k = this.properties.getDoubleProperty("physical_interaction_k");
mass_behaviour_A = this.properties.getDoubleProperty("mass_behaviour_A");
mass_behaviour_B = this.properties.getDoubleProperty("mass_behaviour_B");
waitingCase = this.properties.getIntegerProperty("waiting_case");
massWaitingPoint =this.properties.getDoubleProperty("massWaitingPoint");
}
public void callPostProcessing(SimulationState simulationState) {
}
public void callBeforeBehavior(SimulationState simulationState, Collection<IRichPedestrian> pedestrians) {
pedestrians.stream().forEach(pedestrian -> {
if(pedestrian.getMotoricTask() == null || pedestrian.getMotoricTask() != Motoric.Standing) {
JohannsonPedestrianExtension extension = (JohannsonPedestrianExtension) pedestrian.getExtensionState(this);
extension.setPositionWaitingPoint(null);
extension.setVelocityWaitingPoint(null);
}
});
}
public void callPedestrianBehavior(IOperationalPedestrian pedestrian, SimulationState simulationState) {
JohannsonPedestrianExtension extension = (JohannsonPedestrianExtension) pedestrian.getExtensionState(this);
if(extension.getPositionWaitingPoint() == null) {
extension.setPositionWaitingPoint(pedestrian.getNextWalkingTarget().copy());
extension.setVelocityWaitingPoint(GeometryFactory.createVector(0, 0));
}
List<IPedestrian> otherPedestrians = perception.getAllPedestrians(pedestrian)
.stream()
.filter(ped -> ped.getPosition().distance(pedestrian.getPosition()) < 5.0)
.collect(Collectors.toList());;//.getNearestPedestrians(pedestrian, 3.0);
List<Obstacle> obstacles = this.scenarioManager.getObstacles()
.stream()
.filter(obstacle -> obstacle.getGeometry().distanceBetween(pedestrian.getPosition()) < 5.0)
.collect(Collectors.toList());
Vector2D acceleration = this.computeNewAcceleration(pedestrian,
otherPedestrians,
obstacles);
Vector2D deltaVelocity = acceleration.multiply(simulationState.getTimeStepDuration());
Vector2D velocity = pedestrian.getVelocity().sum(deltaVelocity);
if (velocity.getMagnitude() > pedestrian.getMaximalVelocity()) {
velocity = velocity.getNormalized().multiply(pedestrian.getMaximalVelocity());
}
Vector2D deltaPosition = velocity.multiply(simulationState.getTimeStepDuration());
Vector2D position = pedestrian.getPosition().sum(deltaPosition);
Vector2D heading;
if (waitingCase == 2) {// Berechnung des verschobenen Wartestandpunktes fur die Case2
Vector2D velocityWaitingPoint = extension.getVelocityWaitingPoint();
Vector2D positionWaitingPoint = extension.getPositionWaitingPoint();
Vector2D accelerationWaitingPoint = this.computeAccelerationWaitingPoint(pedestrian, velocityWaitingPoint);
Vector2D deltaVelocityWaitingPoint = accelerationWaitingPoint
.multiply(simulationState.getTimeStepDuration());
Vector2D NewVelocityWaitingPoint = velocityWaitingPoint.sum(deltaVelocityWaitingPoint);
Vector2D deltaPositionWaitingPoint = NewVelocityWaitingPoint
.multiply(simulationState.getTimeStepDuration());
Vector2D NewPositionWaitingPoint = positionWaitingPoint.sum(deltaPositionWaitingPoint);
extension.setPositionWaitingPoint(NewPositionWaitingPoint);
extension.setVelocityWaitingPoint(NewVelocityWaitingPoint);
heading = this.computeHeading(pedestrian,extension.getPositionWaitingPoint());
}
else {
heading = pedestrian.getNextHeading();
}
StandingState novelState = new StandingState(position, velocity, heading);
pedestrian.setStandingState(novelState);
}
public IPedestrianExtension onPedestrianGeneration(IRichPedestrian pedestrian) {
return new JohannsonPedestrianExtension();
}
public void onPedestrianRemoval(IRichPedestrian pedestrian) {
// nothing to do
}
private Vector2D computeAccelerationWaitingPoint(IOperationalPedestrian pedestrian, Vector2D velocityWaitingPoint) {
Vector2D currentVelocity = pedestrian.getVelocity();
Vector2D individualDirection = this.computeIndividualDirection(pedestrian);
Vector2D desiredVelocityVector = this.computeDesiredVelocityVector(pedestrian,
individualDirection);
Vector2D selfDrivingForce = (desiredVelocityVector.subtract(currentVelocity)).multiply(1.0 / relaxation_time);
Vector2D acceleration = (selfDrivingForce
.sum(velocityWaitingPoint.multiply((massWaitingPoint + 1) / relaxation_time)))
.multiply(1 / massWaitingPoint)
.getNegative();
return acceleration;
}
private Vector2D computeHeading(IOperationalPedestrian me, Vector2D target) {
return target.subtract(me.getPosition()).getNormalized();
}
private Vector2D computeNewAcceleration(IOperationalPedestrian pedestrian, Collection<IPedestrian> otherPedestrians,
Collection<Obstacle> obstacles) {
Vector2D currentVelocity = pedestrian.getVelocity();
Vector2D individualDirection = this.computeIndividualDirection(pedestrian);
Vector2D desiredVelocityVector = this.computeDesiredVelocityVector(pedestrian,
individualDirection);
Vector2D sumOfPedestrianInteractionForces = GeometryFactory.createVector(0, 0);
Vector2D pedestrianInteractionForce = null;
for (IPedestrian other : otherPedestrians) {
pedestrianInteractionForce = this.computePedestrianInteractionForce(pedestrian, other);
sumOfPedestrianInteractionForces = sumOfPedestrianInteractionForces.sum(pedestrianInteractionForce);
}
Vector2D sumOfObstacleInteractionForces = GeometryFactory.createVector(0, 0);
Vector2D obstacleInteractionForce = null;
for (Obstacle obstacle : obstacles) {
for (Segment2D part : obstacle.getObstacleParts()) {
obstacleInteractionForce = this.computeObstacleInteractionForce(pedestrian, part);
sumOfObstacleInteractionForces = sumOfObstacleInteractionForces.sum(obstacleInteractionForce);
}
}
Vector2D selfDrivingForce = desiredVelocityVector.subtract(currentVelocity).multiply(1.0 / relaxation_time);
Vector2D newAcceleration = selfDrivingForce.sum(sumOfObstacleInteractionForces)
.sum(sumOfPedestrianInteractionForces);
return newAcceleration;
}
//Berechnung der Geschwindigkeit f�r SelfDrivingForce
private Vector2D computeDesiredVelocityVector(IOperationalPedestrian pedestrian, Vector2D individualDirection) {
JohannsonPedestrianExtension extension = (JohannsonPedestrianExtension) pedestrian.getExtensionState(this);
Vector2D desiredVelocity_vector = null;
switch (waitingCase) {
case 0:
desiredVelocity_vector = individualDirection.multiply(0);
break;
case 1:
case 2:
double radiusPreferedPosition;
Vector2D target;
if (waitingCase == 1) {
target = pedestrian.getNextWalkingTarget();
radiusPreferedPosition = 4 * pedestrian.getDesiredVelocity() * relaxation_time;
} else {
target = extension.getPositionWaitingPoint();
radiusPreferedPosition = 4 * pedestrian.getDesiredVelocity() * relaxation_time*((massWaitingPoint +1)/massWaitingPoint);
}
double distance = target.distance(pedestrian.getPosition());
if (distance <= radiusPreferedPosition) {
desiredVelocity_vector = target.subtract(pedestrian.getPosition())
.multiply(pedestrian.getDesiredVelocity() / radiusPreferedPosition);
} else
desiredVelocity_vector = target.subtract(pedestrian.getPosition())
.multiply(pedestrian.getDesiredVelocity() / distance);
break;
}
return desiredVelocity_vector;
}
private Vector2D computePedestrianInteractionForce(IOperationalPedestrian me, IPedestrian you) {
Vector2D bodyForce = this.computeBodyForce(me, you);
Vector2D slidingFrictionForce = this.computeSlidingFrictionForce(me, you);
Vector2D repulsiveInteractionForce = this.computeRepulsiveInteractionForce(me, you);
Vector2D pedestrianInteractionForce = bodyForce.sum(repulsiveInteractionForce).sum(slidingFrictionForce);
return pedestrianInteractionForce;
}
private Vector2D computeBodyForce(IOperationalPedestrian me, IPedestrian you) {
double sumOfRadii = me.getBodyRadius() + you.getBodyRadius();
Vector2D mePosition = me.getPosition();
Vector2D youPosition = you.getPosition();
double distance = mePosition.distance(youPosition);
Vector2D bodyForce = null;
if (distance > sumOfRadii) {
bodyForce = GeometryFactory.createVector(0, 0);
}
else {
Vector2D normalizedDirection = (mePosition.subtract(youPosition)).multiply(1 / (distance + koesterEpsilon));
bodyForce = normalizedDirection.multiply(physical_interaction_k * (sumOfRadii - distance));
}
return bodyForce;
}
private Vector2D computeSlidingFrictionForce(IOperationalPedestrian me, IPedestrian you) {
double sumOfRadii = me.getBodyRadius() + you.getBodyRadius();
Vector2D mePosition = me.getPosition();
Vector2D youPosition = you.getPosition();
double distance = mePosition.distance(youPosition);
Vector2D slidingFrictionForce = null;
if (distance > sumOfRadii) {
slidingFrictionForce = GeometryFactory.createVector(0, 0);
}
else {
Vector2D normalizedDirection = (mePosition.subtract(youPosition)).multiply(1 / (distance + koesterEpsilon));
Vector2D tangentialDirection = GeometryFactory.createVector(-normalizedDirection.getComponents()[1],
normalizedDirection.getComponents()[0]);
Vector2D meVelocity = me.getVelocity();
Vector2D youVelocity = you.getVelocity();
double tangentialVelocityDifference = youVelocity.subtract(meVelocity).dot(tangentialDirection);
slidingFrictionForce = tangentialDirection
.multiply(physical_interaction_kappa * (sumOfRadii - distance) * tangentialVelocityDifference);
}
return slidingFrictionForce;
}
private Vector2D computeRepulsiveInteractionForce(IOperationalPedestrian me, IPedestrian you) {
double massFactor = 1.0;
double sumOfRadii = me.getBodyRadius() + you.getBodyRadius();
Vector2D mePosition = me.getPosition();
Vector2D youPosition = you.getPosition();
double distance = mePosition.distance(youPosition);
Vector2D normalizedDirection = (mePosition.subtract(youPosition)).multiply(1 / (distance + koesterEpsilon));
Vector2D repulsiveInteractionForce = normalizedDirection.multiply(
mass_behaviour_A * FastMath.exp(-1.0 * ((distance - sumOfRadii) / (massFactor * mass_behaviour_B))));
return repulsiveInteractionForce;
}
private Vector2D computeObstacleInteractionForce(IOperationalPedestrian pedestrian, Segment2D obstaclePart) {
Vector2D bodyForce = this.computeBodyForce(pedestrian, obstaclePart);
Vector2D slidingFrictionForce = this.computeSlidingFrictionForce(pedestrian, obstaclePart);
Vector2D repulsiveInteractionForce = this.computeRepulsiveInteractionForce(pedestrian, obstaclePart);
Vector2D obstacleInteractionForce = bodyForce.sum(repulsiveInteractionForce).subtract(slidingFrictionForce);
return obstacleInteractionForce;
}
private Vector2D computeBodyForce(IOperationalPedestrian pedestrian, Segment2D obstaclePart) {
double pedestrianRadius = pedestrian.getBodyRadius();
Vector2D pedestrianPosition = pedestrian.getPosition();
Vector2D inBetweenVector = obstaclePart.vectorBetween(pedestrianPosition).negate();
double distance = inBetweenVector.getMagnitude();
Vector2D bodyForce = null;
if (distance > pedestrianRadius) {
bodyForce = GeometryFactory.createVector(0, 0);
}
else {
Vector2D normalizedDirection = inBetweenVector.multiply(1 / (distance + koesterEpsilon));
bodyForce = normalizedDirection.multiply(physical_interaction_k * (pedestrianRadius - distance));
}
return bodyForce;
}
private Vector2D computeSlidingFrictionForce(IOperationalPedestrian pedestrian, Segment2D obstaclePart) {
double pedestrianRadius = pedestrian.getBodyRadius();
Vector2D pedestrianPosition = pedestrian.getPosition();
Vector2D inBetweenVector = obstaclePart.vectorBetween(pedestrianPosition).negate();
double distance = inBetweenVector.getMagnitude();
Vector2D slidingFrictionForce = null;
if (distance > pedestrianRadius) {
slidingFrictionForce = GeometryFactory.createVector(0, 0);
}
else {
Vector2D normalizedDirection = inBetweenVector.multiply(1 / (distance + koesterEpsilon));
Vector2D tangentialDirection = GeometryFactory.createVector(-normalizedDirection.getComponents()[1],
normalizedDirection.getComponents()[0]);
Vector2D meVelocity = pedestrian.getVelocity();
double tangentialVelocityDifference = meVelocity.dot(tangentialDirection);
slidingFrictionForce = tangentialDirection.multiply(
physical_interaction_kappa * (pedestrianRadius - distance) * tangentialVelocityDifference);
}
return slidingFrictionForce;
}
private Vector2D computeRepulsiveInteractionForce(IOperationalPedestrian pedestrian, Segment2D obstaclePart) {
double pedestrianRadius = pedestrian.getBodyRadius();
Vector2D pedestrianPosition = pedestrian.getPosition();
Vector2D inBetweenVector = obstaclePart.vectorBetween(pedestrianPosition).negate();
double distance = inBetweenVector.getMagnitude();
Vector2D normalizedDirection = inBetweenVector.multiply(1 / (distance + koesterEpsilon));
Vector2D repulsiveInteractionForce = normalizedDirection
.multiply(mass_behaviour_A * FastMath.exp(-1.0 * ((distance - pedestrianRadius) / mass_behaviour_B)));
return repulsiveInteractionForce;
}
private Vector2D computeIndividualDirection(IOperationalPedestrian pedestrian) {
return pedestrian.getHeading().getNormalized();
}
public void callAfterBehavior(SimulationState simulationState, Collection<IRichPedestrian> pedestrians) {
// nothing to do, no overall pedestrian behavior
}
} |
// TortoiseSVN - a Windows shell extension for easy version control
// Copyright (C) 2007-2009, 2011-2012 - TortoiseSVN
// 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,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
#pragma once
#include "SettingsPropPage.h"
#include "Tooltip.h"
#include "registry.h"
#include "ILogReceiver.h"
class CProgressDlg;
/**
* \ingroup TortoiseProc
* Settings page to configure miscellaneous stuff.
*/
class CSettingsLogCaches
: public ISettingsPropPage
, private ILogReceiver
{
DECLARE_DYNAMIC(CSettingsLogCaches)
public:
CSettingsLogCaches();
virtual ~CSettingsLogCaches();
UINT GetIconID() override {return IDI_CACHELIST;}
// update cache list
virtual BOOL OnSetActive();
// Dialog Data
enum { IDD = IDD_SETTINGSLOGCACHELIST };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual BOOL OnInitDialog();
virtual BOOL PreTranslateMessage(MSG* pMsg);
virtual BOOL OnKillActive();
virtual BOOL OnQueryCancel();
afx_msg void OnBnClickedDetails();
afx_msg void OnBnClickedUpdate();
afx_msg void OnBnClickedExport();
afx_msg void OnBnClickedDelete();
afx_msg LRESULT OnRefeshRepositoryList (WPARAM wParam, LPARAM lParam);
afx_msg void OnNMDblclkRepositorylist(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnLvnItemchangedRepositorylist(NMHDR *pNMHDR, LRESULT *pResult);
DECLARE_MESSAGE_MAP()
private:
CToolTips m_tooltips;
CListCtrl m_cRepositoryList;
/// current repository list
typedef std::multimap<CString, CString> TRepos;
typedef TRepos::value_type TRepo;
typedef TRepos::const_iterator IT;
TRepos repos;
TRepo GetSelectedRepo();
void FillRepositoryList();
static UINT WorkerThread(LPVOID pVoid);
volatile LONG m_bThreadRunning;
/// used by cache update
CProgressDlg* progress;
svn_revnum_t headRevision;
void ReceiveLog ( TChangedPaths* changes
, svn_revnum_t rev
, const StandardRevProps* stdRevProps
, UserRevPropArray* userRevProps
, const MergeInfo* mergeInfo) override;
}; |
import 'package:flutter/material.dart';
import 'package:tutachef_project/core/app_core.dart';
import 'package:tutachef_project/core/widgets/custom_button.dart';
import 'package:tutachef_project/views/categories/card_categorie.dart';
import '../../controllers/home_controller.dart';
import '../../core/widgets/custom_appbar.dart';
import '../../core/widgets/custom_drawer.dart';
import '../../core/widgets/custom_textField.dart';
class IngredientsCadastradosView extends StatelessWidget {
const IngredientsCadastradosView({Key? key, required this.controller})
: super(key: key);
final HomeController controller;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: CustomAppBarWidget(controller: controller),
endDrawer: CustomDrawer(
controller: controller,
),
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.white,
onPressed: () {
Navigator.of(context).pop();
},
child: Icon(Icons.arrow_back, color: Colors.orange[700]),
),
floatingActionButtonLocation: FloatingActionButtonLocation.miniStartFloat,
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(height: 20),
const Text(
'Cadastrar Ingrediente',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 24),
),
const SizedBox(height: 20),
const Text(
'Ingredientes cadastrados',
style: TextStyle(color: Colors.grey),
),
CustomTextField(
hint: 'Pesquisar...',
),
Expanded(
child: ListView.builder(
itemCount: AppCore.ingredientesMock.length,
itemBuilder: (context, index) {
return CardCategorie(
categorie: AppCore.ingredientesMock[index],
type: AppCore.ingredientesMock[index]);
}),
),
const SizedBox(height: 20),
SizedBox(
width: 250,
child: CustomButton(
textButton: 'Cadastrar Ingrediente',
function: () {
_showOptionsDialog(context);
},
),
),
],
),
),
);
}
void _showOptionsDialog(BuildContext context) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Cadastrar Ingrediente'),
content: CustomTextField(
hint: 'Informe o ingrediente...',
),
actions: <Widget>[
ElevatedButton(
onPressed: () {
Navigator.of(context).pop();
AppCore().successDialog(
context,
'Ingrediente adicionado com sucesso!',
);
},
child: const Text(
'Adicionar',
style: TextStyle(color: Colors.green),
),
),
],
);
},
);
}
} |
const express = require("express");
const router = express.Router();
const Note = require("../models/Note");
const fetchuser = require("../middleware/fetchuser");
const { body, validationResult } = require("express-validator");
// Route-1: Fetch all notes: GET "/api/notes/fetchallnotes". login required
router.get("/fetchallnotes", fetchuser, async (req, res) => {
try {
const notes = await Note.find({ user: req.user.id });
res.json(notes);
} catch (error) {
console.log(error.message);
res.status(500).send("Internal Server Error");
}
});
// Route-2: Add a new notes: POST "/api/notes/addnote". login required
router.post(
"/addnote",
fetchuser,
[
body("title", "Enter a valid title").isLength({ min: 3 }),
body("description", "Description must be above 5 characters").isLength({
min: 5,
}),
],
async (req, res) => {
try {
// if there are errors return bad request
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { title, description, tag } = req.body;
const note = new Note({
title,
description,
tag,
user: req.user.id,
});
const savenote = await note.save();
res.json(savenote);
} catch (error) {
console.log(error.message);
res.status(500).send("Internal Server Error");
}
}
);
// Route-3: Update existing new notes: POST "/api/notes/updatenote/:id". login required
router.put("/updatenote/:id", fetchuser, async (req, res) => {
const { title, description, tag } = req.body;
try {
const newNote = {};
if (title) {
newNote.title = title;
}
if (description) {
newNote.description = description;
}
if (tag) {
newNote.tag = tag;
}
// find note to be updated
let note = await Note.findById(req.params.id);
if (!note) {
return res.status(404).send("Not Found");
}
if (note.user.toString() !== req.user.id) {
return res.status(404).send("Not Allowed");
}
note = await Note.findByIdAndUpdate(
req.params.id,
{ $set: newNote },
{ new: true }
);
res.json(note);
} catch (error) {
console.log(error.message);
res.status(500).send("Internal Server Error");
}
});
// Route-4: Delete existing notes: POST "/api/notes/deletenote/:id". login required
router.delete("/deletenote/:id", fetchuser, async (req, res) => {
try {
// find note to be delete
let note = await Note.findById(req.params.id);
if (!note) {
return res.status(404).send("Not Found");
}
if (note.user.toString() !== req.user.id) {
return res.status(404).send("Not Allowed");
}
note = await Note.findByIdAndDelete(req.params.id)
res.json({"success": "Note has been deleted", note})
} catch (error) {
console.log(error.message);
res.status(500).send("Internal Server Error");
}
});
module.exports = router; |
################ Additional Data Tools ################
############## Currently not being used ###############
#' Landscape Index Main
#'
#' The landscape index main calls all required function and produces the rating
#' for landscape over the study site.
#' @param slopePercent Slope percentage.
#' @param slopeLength Slope length based on LS calculation.
#' @param surfaceStoniness Surface stoniness in annual removal (cubic m/ha)
#' @param coarseFragment Coarse fragment content as a percentage of volume.
#' @param woodContent Wood content as a percentage of volume.
#' @return Landscape rating
#' @export
landscapeIndexMain <- function(slopePercent,slopeLength,surfaceStoniness, coarseFragment, woodContent){
one <- mapply(basicLandscapeRating,slopePercent,slopeLength)
two <- mapply(interimLandscapeRating,surfaceStoniness,coarseFragment,woodContent)
three <- 0
result <- mapply(landscapeRating,one,two,three)
return(result)
}
#' Basic landscape rating
#'
#' The basic landscape rating returns the point deduction for the percent
#' slope and landscape type.
#' @param slopePercent Slope percentage.
#' @param slopeLength Slope length based on LS calculation.
#' @return Deduction points for the basic landscape rating.
#' @export
basicLandscapeRating <- function(slopePercent,slopeLength){
if(is.na(slopePercent) || is.na(slopeLength)){
pointDeduct <- 0
}
# Simple landscapes. Nominal slope lengths equal to or over 100m
else if(slopeLength >= 100){
pointDeduct <- 66.560928 + 2.156809 * slopePercent - sqrt((-38.609623 + 2.156809 * slopePercent) ^ 2 + 54.877374 ^ 2)
}
# Complex landscapes. Nominal slope lengths less than 100m
else if(slopeLength < 100){
pointDeduct <- 128.20977 + 8.5212186 * slopePercent - sqrt((24.148183 + 8.5212186 * slopePercent) ^ 2 + 126.64124 ^ 2)
} else {
pointDeduct <- 0
}
pointDeduct <- 100 - pointDeduct
pointDeduct[pointDeduct < 0] <- 0
pointDeduct[pointDeduct > 100] <- 100
return(pointDeduct)
}
#' Interim landscape rating
#'
#' The interim landscape rating returns the point deduction as a percent deduction
#' from the basic landscape rating. This parameter is currently not being used.
#' @param surfaceStoniness Surface stoniness in annual removal (cubic m/ha)
#' @param coarseFragment Coarse fragment content as a percentage of volume.
#' @param woodContent Wood content as a percentage of volume.
#' @return Deduction points for the interim landscape rating.
#' @export
interimLandscapeRating <- function(surfaceStoniness,coarseFragment,woodContent){
pointDeduct <- 0
if(is.na(surfaceStoniness) && is.na(coarseFragment) && is.na(woodContent)){
pointDeduct <- 0
}
# Surface stoniness deduction
if(!is.na(surfaceStoniness)){
pointDeduct <- pointDeduct + 50 * (surfaceStoniness) + 5
}
# Coarse fragment deduction
if(!is.na(coarseFragment)){
ifelse(coarseFragment >= 7.5,
pointDeduct <- pointDeduct + (50 * coarseFragment + 5),
pointDeduct <- pointDeduct + (0.96285714 * coarseFragment - 9 - 0.0057142857 * coarseFragment ^ 2))
}
# Wood content deduction
if(!is.na(woodContent)){
pointDeduct <- pointDeduct
}
return(pointDeduct)
}
#' Landscape rating
#'
#' The landscape rating calculates the rating class for the landscape index.
#' @param basicLandscape Basic landscape rating calculated
#' @param coarseFragmentModifications Coarse fragment modifications.
#' @param otherModifiers Other modifying factors such as pattern and flooding.
#' @return The landscape rating.
#' @export
landscapeRating <- function(basicLandscape, coarseFragmentModifications, otherModifiers){
# Basic landscape rating is lower of moisture component and temperature factor.
# The basicLandscapeRating function returns the minimum of the two so no further
# calculations are required.
a <- basicLandscape
# Coarse fragment modifications is a percentage deduction modifier for the
# interim landscape rating function. The CFM uses stoniness (cubic m / ha),
# coarse fragments (% vol / ha), wood content (% by volume).
b <- a * (coarseFragmentModifications / 100)
c <- a - b
# Other modifiers is the percentage deduction for pattern and flooding.
d <- c * (otherModifiers / 100)
# landscape rating
rating <- (a - b - d)
rating[rating < 0] <- 0
rating[rating > 100] <- 100
return(rating)
} |
use api_servico;
CREATE TABLE setor (
id INT AUTO_INCREMENT PRIMARY KEY,
nome VARCHAR(100) NOT NULL,
codigo VARCHAR(50) UNIQUE NOT NULL
)ENGINE=INNODB;
-- Criar a tabela equipamento com o novo atributo setor
CREATE TABLE equipamento (
id INT AUTO_INCREMENT PRIMARY KEY,
nome VARCHAR(100) NOT NULL,
marca VARCHAR(100) NOT NULL,
descricao VARCHAR(150) NOT NULL,
codigo VARCHAR(50) UNIQUE NOT NULL,
valor DECIMAL(10, 2) NOT NULL,
setor_id INT,
FOREIGN KEY (setor_id) REFERENCES setor(id)
)ENGINE=INNODB;
-- Criar a tabela ordem_de_servico
CREATE TABLE ordem_de_servico (
id INT AUTO_INCREMENT PRIMARY KEY,
descricao VARCHAR(150) NOT NULL,
codigo VARCHAR(50) UNIQUE NOT NULL,
equipamento_id INT,
tipo_manutencao VARCHAR(50) NOT NULL,
data_emissao TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (equipamento_id) REFERENCES equipamento(id)
)ENGINE=INNODB;
-- Inserir dados na tabela setor
INSERT INTO setor (nome, codigo) VALUES
('Produção de Peças', 'PP001'),
('Manutenção de Máquinas', 'MM002'),
('Controle de Qualidade', 'CQ003');
-- Inserir dados na tabela equipamento
INSERT INTO equipamento (nome, marca, descricao, codigo, valor, setor_id) VALUES
('Torno CNC', 'Mazak', 'Máquina de usinagem CNC para produção', 'CNC001', 80000.00, 1),
('Fresadora Vertical', 'Haas', 'Máquina de fresagem para produção', 'FRS002', 60000.00, 1),
('Máquina de Solda a Arco', 'Lincoln Electric', 'Máquina de solda para processos de fabricação', 'SOL003', 5000.50, 2);
-- Inserir dados na tabela ordem_de_servico
INSERT INTO ordem_de_servico (descricao, codigo, equipamento_id, tipo_manutencao) VALUES
('Substituição de Ferramenta de Corte', 'OS001', 1, 'Manutenção Corretiva'),
('Calibração de Fresadora', 'OS002', 2, 'Calibração Mecânica'),
('Manutenção Preventiva em Máquina de Solda', 'OS003', 3, 'Manutenção Preventiva');
-- Inserir dados na tabela setor
INSERT INTO setor (nome, codigo) VALUES
('Fundição', 'FND001'),
('Usinagem de Precisão', 'UP002'),
('Montagem', 'MTG003');
-- Inserir dados na tabela equipamento
INSERT INTO equipamento (nome, marca, descricao, codigo, valor, setor_id) VALUES
('Forno de Indução', 'Inductotherm', 'Forno para fundição de metais', 'FRN001', 120000.00, 1),
('Torno Vertical CNC', 'Doosan', 'Máquina para usinagem de peças grandes', 'CNC002', 100000.00, 2),
('Robô de Solda', 'ABB', 'Robô para soldagem automatizada', 'ROB003', 25000.50, 3);
-- Inserir dados na tabela ordem_de_servico
INSERT INTO ordem_de_servico (descricao, codigo, equipamento_id, tipo_manutencao) VALUES
('Troca de Cadinho no Forno de Indução', 'OS004', 1, 'Manutenção Corretiva'),
('Ajuste Fino do Torno CNC', 'OS005', 2, 'Ajuste de Precisão'),
('Atualização de Software no Robô de Solda', 'OS006', 3, 'Manutenção de Software'); |
require 'rails_helper'
RSpec.describe Admin::UsersController, type: :controller do
let!(:user) { FactoryBot.create(:user) }
let!(:manager) { FactoryBot.create(:user, role: :manager) }
let!(:admin) { FactoryBot.create(:user, role: :admin) }
describe 'GET #index' do
before do
sign_in_as(resource)
get :index
end
context 'admin' do
let(:resource) { admin }
it 'allows admin to receive users list' do
expect(response).to be_successful
expect(response_json.size).to eq 3
end
end
context 'manager' do
let(:resource) { manager }
it 'allows manager to receive users list' do
expect(response).to be_successful
expect(response_json.size).to eq 3
end
end
context 'user' do
let(:resource) { user }
it 'does not allow regular user to receive users list' do
expect(response).to have_http_status(403)
end
end
end
describe 'GET#show' do
before do
sign_in_as(resource)
get :show, params: { id: user.id }
end
context 'admin' do
let(:resource) { admin }
it 'allows admin to get a user' do
expect(response).to be_successful
end
end
context 'manager' do
let(:resource) { manager }
it 'allows manager to get a user' do
expect(response).to be_successful
end
end
context 'user' do
let(:resource) { user }
it 'does not allow regular user to get a user' do
expect(response).to have_http_status(403)
end
end
end
describe 'PATCH#update' do
before do
sign_in_as(resource)
patch :update, params: { id: user.id, user: { role: :manager } }
end
context 'admin' do
let(:resource) { admin }
it 'allows admin to update a user' do
expect(response).to be_successful
expect(user.reload.role).to eq 'manager'
end
it 'does not allow admin to update their own role' do
patch :update, params: { id: admin.id, user: { role: :manager } }
expect(response).to have_http_status(400)
end
end
context 'manager' do
let(:resource) { manager }
it 'does not allow manager to update a user' do
expect(response).to have_http_status(403)
end
end
context 'user' do
let(:resource) { user }
it 'does not allow user to update a user' do
expect(response).to have_http_status(403)
end
end
end
end |
import React, { useState } from 'react';
import { Flex, Rate, Typography, ConfigProvider, Tooltip } from 'antd';
import { useTranslation } from 'react-i18next';
import './CustomRate.less';
const { Text } = Typography;
const CustomRate = ({ onRateChange }) => {
const [value, setValue] = useState(0);
const { t } = useTranslation();
const descriptions = [
t('notSelected'),
t('iDontKnow'),
t('iKnowTheory'),
t('iApplyIt'),
t('professional'),
];
const handleChange = (value) => {
setValue(value);
onRateChange(value);
};
return (
<div className="customRate" style={{ minWidth: '205px' }}>
<Flex align="center" justify="end" gap="middle" vertical>
<Rate
onChange={handleChange}
value={value}
tooltips={descriptions.slice(1)}
count={4}
/>
<Text style={{ width: '100%', textAlign: 'center', fontWeight: 400 }}>
{t('myLevel')}:{' '}
<span style={{ fontWeight: 700 }}>{descriptions[value]}</span>
</Text>
</Flex>
</div>
);
};
export default CustomRate; |
前面的几个小节,我们从 Vite 双引擎的角度了解了 Vite 的整体架构,也系统学了双引擎本身的基础知识。从本小节开始,我们正式学习 **Vite 高级应用**。
这一模块中,我们将深入应用 Vite 的各项高级能力,遇到更多有挑战的开发场景。你不仅能学会一系列有难度的**解决方案**,直接运用到实际项目中,还能系统提高自己的**知识深度**,体会复杂项目场景中构建工具如何提供高度自定义的能力,以及如何对项目进行性能优化。
说到自定义的能力,你肯定很容易想到`插件机制`,利用一个个插件来扩展构建工具自身的能力。没错,这一节中我们将系统学习 Vite 的插件机制,带你掌握 Vite 插件开发的基本知识以及实战开发技巧。
虽然 Vite 的插件机制是基于 Rollup 来设计的,并且上一小节我们也已经对 Rollup 的插件机制进行了详细的解读,但实际上 Vite 的插件机制也包含了自己独有的一部分,与 Rollup 的各个插件 Hook 并非完全兼容,因此本节我们将重点关注 Vite 独有的部分以及和 Rollup 所区别的部分,而对于 Vite 和 Rollup 中相同的 Hook (如`resolveId`、`load`、`transform`)只是稍微提及,就不再展开赘述了。
让我们先从一个简单的例子入手吧!
## 一个简单的插件示例
Vite 插件与 Rollup 插件结构类似,为一个`name`和各种插件 Hook 的对象:
```ts
{
// 插件名称
name: 'vite-plugin-xxx',
load(code) {
// 钩子逻辑
},
}
```
> 如果插件是一个 npm 包,在`package.json`中的包命名也推荐以`vite-plugin`开头
一般情况下因为要考虑到外部传参,我们不会直接写一个对象,而是实现一个返回插件对象的`工厂函数`,如下代码所示:
```ts
// myPlugin.js
export function myVitePlugin(options) {
console.log(options)
return {
name: 'vite-plugin-xxx',
load(id) {
// 在钩子逻辑中可以通过闭包访问外部的 options 传参
}
}
}
// 使用方式
// vite.config.ts
import { myVitePlugin } from './myVitePlugin';
export default {
plugins: [myVitePlugin({ /* 给插件传参 */ })]
}
```
## 插件 Hook 介绍
### 1. 通用 Hook
在[双引擎架构](https://juejin.cn/book/7050063811973218341/section/7060398408430780431)这一节中介绍过,Vite **开发阶段**会模拟 Rollup 的行为:

其中 Vite 会调用一系列与 Rollup 兼容的钩子,这个钩子主要分为三个阶段:
- **服务器启动阶段**: `options`和`buildStart`钩子会在服务启动时被调用。
- **请求响应阶段**: 当浏览器发起请求时,Vite 内部依次调用`resolveId`、`load`和`transform`钩子。
- **服务器关闭阶段**: Vite 会依次执行`buildEnd`和`closeBundle`钩子。
除了以上钩子,其他 Rollup 插件钩子(如`moduleParsed`、`renderChunk`)均不会在 Vite **开发阶段**调用。而生产环境下,由于 Vite 直接使用 Rollup,Vite 插件中所有 Rollup 的插件钩子都会生效。
### 2. 独有 Hook
接下来给大家介绍 Vite 中特有的一些 Hook,这些 Hook 只会在 Vite 内部调用,而放到 Rollup 中会被直接忽略。
#### 2.1 给配置再加点料: config
Vite 在读取完配置文件(即`vite.config.ts`)之后,会拿到用户导出的配置对象,然后执行 config 钩子。在这个钩子里面,你可以对配置文件导出的对象进行自定义的操作,如下代码所示:
```ts
// 返回部分配置(推荐)
const editConfigPlugin = () => ({
name: 'vite-plugin-modify-config',
config: () => ({
alias: {
react: require.resolve('react')
}
})
})
```
官方推荐的姿势是在 config 钩子中返回一个配置对象,这个配置对象会和 Vite 已有的配置进行深度的合并。不过你也可以通过钩子的入参拿到 config 对象进行自定义的修改,如下代码所示:
```ts
const mutateConfigPlugin = () => ({
name: 'mutate-config',
// command 为 `serve`(开发环境) 或者 `build`(生产环境)
config(config, { command }) {
// 生产环境中修改 root 参数
if (command === 'build') {
config.root = __dirname;
}
}
})
```
在一些比较深层的对象配置中,这种直接修改配置的方式会显得比较麻烦,如 `optimizeDeps.esbuildOptions.plugins`,需要写很多的样板代码,类似下面这样:
```ts
// 防止出现 undefined 的情况
config.optimizeDeps = config.optimizeDeps || {}
config.optimizeDeps.esbuildOptions = config.optimizeDeps.esbuildOptions || {}
config.optimizeDeps.esbuildOptions.plugins = config.optimizeDeps.esbuildOptions.plugins || []
```
因此这种情况下,建议直接返回一个配置对象,这样会方便很多:
```ts
config() {
return {
optimizeDeps: {
esbuildOptions: {
plugins: []
}
}
}
}
```
#### 2.2 记录最终配置: configResolved
Vite 在解析完配置之后会调用`configResolved`钩子,这个钩子一般用来记录最终的配置信息,而不建议再修改配置,用法如下图所示:
```ts
const exmaplePlugin = () => {
let config
return {
name: 'read-config',
configResolved(resolvedConfig) {
// 记录最终配置
config = resolvedConfig
},
// 在其他钩子中可以访问到配置
transform(code, id) {
console.log(config)
}
}
}
```
#### 2.3 获取 Dev Server 实例: configureServer
这个钩子仅在**开发阶段**会被调用,用于扩展 Vite 的 Dev Server,一般用于增加自定义 server 中间件,如下代码所示:
```ts
const myPlugin = () => ({
name: 'configure-server',
configureServer(server) {
// 姿势 1: 在 Vite 内置中间件之前执行
server.middlewares.use((req, res, next) => {
// 自定义请求处理逻辑
})
// 姿势 2: 在 Vite 内置中间件之后执行
return () => {
server.middlewares.use((req, res, next) => {
// 自定义请求处理逻辑
})
}
}
})
```
#### 2.4 转换 HTML 内容: transformIndexHtml
这个钩子用来灵活控制 HTML 的内容,你可以拿到原始的 html 内容后进行任意的转换:
```ts
const htmlPlugin = () => {
return {
name: 'html-transform',
transformIndexHtml(html) {
return html.replace(
/<title>(.*?)</title>/,
`<title>换了个标题</title>`
)
}
}
}
// 也可以返回如下的对象结构,一般用于添加某些标签
const htmlPlugin = () => {
return {
name: 'html-transform',
transformIndexHtml(html) {
return {
html,
// 注入标签
tags: [
{
// 放到 body 末尾,可取值还有`head`|`head-prepend`|`body-prepend`,顾名思义
injectTo: 'body',
// 标签属性定义
attrs: { type: 'module', src: './index.ts' },
// 标签名
tag: 'script',
},
],
}
}
}
}
```
#### 2.5 热更新处理: handleHotUpdate
> 关于热更新的概念和原理,我们会在下一节具体讲解。
这个钩子会在 Vite 服务端处理热更新时被调用,你可以在这个钩子中拿到热更新相关的上下文信息,进行热更模块的过滤,或者进行自定义的热更处理。下面是一个简单的例子:
```ts
const handleHmrPlugin = () => {
return {
async handleHotUpdate(ctx) {
// 需要热更的文件
console.log(ctx.file)
// 需要热更的模块,如一个 Vue 单文件会涉及多个模块
console.log(ctx.modules)
// 时间戳
console.log(ctx.timestamp)
// Vite Dev Server 实例
console.log(ctx.server)
// 读取最新的文件内容
console.log(await read())
// 自行处理 HMR 事件
ctx.server.ws.send({
type: 'custom',
event: 'special-update',
data: { a: 1 }
})
return []
}
}
}
// 前端代码中加入
if (import.meta.hot) {
import.meta.hot.on('special-update', (data) => {
// 执行自定义更新
// { a: 1 }
console.log(data)
window.location.reload();
})
}
```
以上就是 Vite 独有的五个钩子,我们来重新梳理一下:
- `config`: 用来进一步修改配置。
- `configResolved`: 用来记录最终的配置信息。
- `configureServer`: 用来获取 Vite Dev Server 实例,添加中间件。
- `transformIndexHtml`: 用来转换 HTML 的内容。
- `handleHotUpdate`: 用来进行热更新模块的过滤,或者进行自定义的热更新处理。
### 3. 插件 Hook 执行顺序
好,现在我们学习到了 Vite 的通用钩子和独有钩子,估计你现在脑子里面一点乱: 这么多的钩子,到底谁先执行、谁后执行呢?
下面,我们就来复盘一下上述的两类钩子,并且通过一个具体的代码示例来汇总一下所有的钩子。我们可以在 Vite 的脚手架工程中新建 `test-hooks-plugin.ts`:
```ts
// test-hooks-plugin.ts
// 注: 请求响应阶段的钩子
// 如 resolveId, load, transform, transformIndexHtml在下文介绍
// 以下为服务启动和关闭的钩子
export default function testHookPlugin () {
return {
name: 'test-hooks-plugin',
// Vite 独有钩子
config(config) {
console.log('config');
},
// Vite 独有钩子
configResolved(resolvedCofnig) {
console.log('configResolved');
},
// 通用钩子
options(opts) {
console.log('options');
return opts;
},
// Vite 独有钩子
configureServer(server) {
console.log('configureServer');
setTimeout(() => {
// 手动退出进程
process.kill(process.pid, 'SIGTERM');
}, 3000)
},
// 通用钩子
buildStart() {
console.log('buildStart');
},
// 通用钩子
buildEnd() {
console.log('buildEnd');
},
// 通用钩子
closeBundle() {
console.log('closeBundle');
}
}
```
将插件加入到 Vite 配置文件中,然后启动,你可以观察到各个 Hook 的执行顺序:

由此我们可以梳理出 Vite 插件的执行顺序:

- 服务启动阶段: `config`、`configResolved`、`options`、`configureServer`、`buildStart`
- 请求响应阶段: 如果是 `html` 文件,仅执行`transformIndexHtml`钩子;对于非 HTML 文件,则依次执行`resolveId`、`load`和`transform`钩子。相信大家学过 Rollup 的插件机制,已经对这三个钩子比较熟悉了。
- 热更新阶段: 执行`handleHotUpdate`钩子。
- 服务关闭阶段: 依次执行`buildEnd`和`closeBundle`钩子。
## 插件应用位置
梳理完 Vite 的各个钩子函数之后,接下来让我们来了解一下 Vite 插件的**应用情景**和**应用顺序**。
默认情况下 Vite 插件同时被用于开发环境和生产环境,你可以通过`apply`属性来决定应用场景:
```ts
{
// 'serve' 表示仅用于开发环境,'build'表示仅用于生产环境
apply: 'serve'
}
```
`apply`参数还可以配置成一个函数,进行更灵活的控制:
```ts
apply(config, { command }) {
// 只用于非 SSR 情况下的生产环境构建
return command === 'build' && !config.build.ssr
}
```
同时,你也可以通过`enforce`属性来指定插件的执行顺序:
```ts
{
// 默认为`normal`,可取值还有`pre`和`post`
enforce: 'pre'
}
```
Vite 中插件的执行顺序如下图所示:

Vite 会依次执行如下的插件:
>
- Alias (路径别名)相关的插件。
- ⭐️ 带有 `enforce: 'pre'` 的用户插件。
- Vite 核心插件。
- ⭐️ 没有 enforce 值的用户插件,也叫`普通插件`。
- Vite 生产环境构建用的插件。
- ⭐️ 带有 `enforce: 'post'` 的用户插件。
- Vite 后置构建插件(如压缩插件)。
## 插件开发实战
接下来我们进入插件开发的实战环节中,在这个部分我们将一起编写两个 Vite 插件,分别是`虚拟模块加载插件`和`Svgr 插件`,你将学会从插件开发的常见套路和各种开发技巧。话不多说,让我们现在开始实战吧。
### 实战案例 1: 虚拟模块加载
首先我们来实现一个虚拟模块的加载插件,可能你会有疑问: 什么是虚拟模块呢?
作为构建工具,一般需要处理两种形式的模块,一种存在于真实的磁盘文件系统中,另一种并不在磁盘而在内存当中,也就是`虚拟模块`。通过虚拟模块,我们既可以把自己手写的一些代码字符串作为单独的模块内容,又可以将内存中某些经过计算得出的**变量**作为模块内容进行加载,非常灵活和方便。接下来让我们通过一些具体的例子来实操一下,首先通过脚手架命令初始化一个`react + ts`项目:
```ts
npm init vite
```
然后通过`pnpm i`安装依赖,接着新建`plugins`目录,开始插件的开发:
```ts
// plugins/virtual-module.ts
import { Plugin } from 'vite';
// 虚拟模块名称
const virtualFibModuleId = 'virtual:fib';
// Vite 中约定对于虚拟模块,解析后的路径需要加上`\0`前缀
const resolvedFibVirtualModuleId = '\0' + virtualFibModuleId;
export default function virtualFibModulePlugin(): Plugin {
let config: ResolvedConfig | null = null;
return {
name: 'vite-plugin-virtual-module',
resolveId(id) {
if (id === virtualFibModuleId) {
return resolvedFibVirtualModuleId;
}
},
load(id) {
// 加载虚拟模块
if (id === resolvedFibVirtualModuleId) {
return 'export default function fib(n) { return n <= 1 ? n : fib(n - 1) + fib(n - 2); }';
}
}
}
}
```
接着我们在项目中来使用这个插件:
```ts
// vite.config.ts
import virtual from './plugins/virtual-module.ts'
// 配置插件
{
plugins: [react(), virtual()]
}
```
然后在`main.tsx`中加入如下的代码:
```ts
import fib from 'virtual:fib';
alert(`结果: ${fib(10)}`)
```
这里我们使用了 `virtual:fib` 这个虚拟模块,虽然这个模块不存在真实的文件系统中,但你打开浏览器后可以发现这个模块导出的函数是可以正常执行的:

接着我们来尝试一下如何通过虚拟模块来读取内存中的变量,在`virtual-module.ts`中增加如下代码:
```diff
import { Plugin, ResolvedConfig } from 'vite';
const virtualFibModuleId = 'virtual:fib';
const resolvedFibVirtualModuleId = '\0' + virtualFibModuleId;
+ const virtualEnvModuleId = 'virtual:env';
+ const resolvedEnvVirtualModuleId = '\0' + virtualEnvModuleId;
export default function virtualFibModulePlugin(): Plugin {
+ let config: ResolvedConfig | null = null;
return {
name: 'vite-plugin-virtual-fib-module',
+ configResolved(c: ResolvedConfig) {
+ config = c;
+ },
resolveId(id) {
if (id === virtualFibModuleId) {
return resolvedFibVirtualModuleId;
}
+ if (id === virtualEnvModuleId) {
+ return resolvedEnvVirtualModuleId;
+ }
},
load(id) {
if (id === resolvedFibVirtualModuleId) {
return 'export default function fib(n) { return n <= 1 ? n : fib(n - 1) + fib(n - 2); }';
}
+ if (id === resolvedEnvVirtualModuleId) {
+ return `export default ${JSON.stringify(config!.env)}`;
+ }
}
}
}
```
在新增的这些代码中,我们注册了一个新的虚拟模块`virtual:env`,紧接着我们去项目去使用:
```ts
// main.tsx
import env from 'virtual:env';
console.log(env)
```
你可以去浏览器观察一下输出的情况:

Vite 环境变量能正确地在浏览器中打印出来,说明在内存中计算出来的`virtual:env`模块的确被成功地加载了。从中你可以看到,虚拟模块的内容完全能够被动态计算出来,因此它的灵活性和可定制程度非常高,实用性也很强,在 Vite 内部的插件被深度地使用,社区当中也有不少知名的插件(如 `vite-plugin-windicss`、`vite-plugin-svg-icons`等)也使用了虚拟模块的技术。
### 实战案例 2: Svg 组件形式加载
在一般的项目开发过程中,我们有时候希望能将 svg 当做一个组件来引入,这样我们可以很方便地修改 svg 的各种属性,相比于`img`标签的引入方式也更加优雅。但 Vite 本身并不支持将 svg 转换为组件的代码,需要我们通过插件来实现。
接下来我们就来写一个 Vite 插件,实现在 React 项目能够通过组件方式来使用 svg 资源。首先安装一下需要的依赖:
```bash
pnpm i resolve @svgr/core -D
```
接着在`plugins`目录新建 `svgr.ts`:
```ts
import { Plugin } from 'vite';
import * as fs from 'fs';
import * as resolve from 'resolve';
interface SvgrOptions {
// svg 资源模块默认导出,url 或者组件
defaultExport: 'url' | 'component';
}
export default function viteSvgrPlugin(options: SvgrOptions) {
const { defaultExport='url' } = options;
return {
name: 'vite-plugin-svgr',
async transform(code ,id) {
// 转换逻辑: svg -> React 组件
}
}
}
```
让我们先来梳理一下开发需求,用户通过传入`defaultExport`可以控制 svg 资源的默认导出:
- 当 `defaultExport`为 `component`,默认当做组件来使用,即:
```ts
import Logo from './Logo.svg'
// 在组件中直接使用
<Logo />
```
- 当`defaultExports`为`url`,默认当做 url 使用,如果需要用作组件,可以通过`具名导入`的方式来支持:
```ts
import logoUrl, { ReactComponent as Logo } from './logo.svg';
// url 使用
<img src={logoUrl} />
// 组件方式使用
<Logo />
```
明确了需求之后,接下来让我们来整理一下插件开发的整体思路,主要逻辑在 `transform`钩子中完成,流程如下:
- 1. 根据 id 入参过滤出 svg 资源;
- 1. 读取 svg 文件内容;
- 1. 利用 `@svgr/core` 将 svg 转换为 React 组件代码;
- 1. 处理默认导出为 url 的情况;
- 1. 将组件的 jsx 代码转译为浏览器可运行的代码。
下面是插件的完整的代码,你可以参考学习:
```js
import { Plugin } from 'vite';
import * as fs from 'fs';
import * as resolve from 'resolve';
interface SvgrOptions {
defaultExport: 'url' | 'component';
}
export default function viteSvgrPlugin(options: SvgrOptions): Plugin {
const { defaultExport='component' } = options;
return {
name: 'vite-plugin-svgr',
async transform(code, id) {
// 1. 根据 id 入参过滤出 svg 资源;
if (!id.endsWith('.svg')) {
return code;
}
const svgrTransform = require('@svgr/core').transform;
// 解析 esbuild 的路径,后续转译 jsx 会用到,我们这里直接拿 vite 中的 esbuild 即可
const esbuildPackagePath = resolve.sync('esbuild', { basedir: require.resolve('vite') });
const esbuild = require(esbuildPackagePath);
// 2. 读取 svg 文件内容;
const svg = await fs.promises.readFile(id, 'utf8');
// 3. 利用 `@svgr/core` 将 svg 转换为 React 组件代码
const svgrResult = await svgrTransform(
svg,
{},
{ componentName: 'ReactComponent' }
);
// 4. 处理默认导出为 url 的情况
let componentCode = svgrResult;
if (defaultExport === 'url') {
// 加上 Vite 默认的 `export default 资源路径`
componentCode += code;
componentCode = svgrResult.replace('export default ReactComponent', 'export { ReactComponent }');
}
// 5. 利用 esbuild,将组件中的 jsx 代码转译为浏览器可运行的代码;
const result = await esbuild.transform(componentCode, {
loader: 'jsx',
});
return {
code: result.code,
map: null // TODO
};
},
};
}
```
接下来让我们在项目中使用这个插件:
```ts
// vite.config.ts
import svgr from './plugins/svgr';
// 返回的配置
{
plugins: [
// 省略其它插件
svgr()
]
}
```
接着我们在项目中用组件的方式引入 svg:
```ts
// App.tsx
import Logo from './logo.svg'
function App() {
return (
<>
<Logo />
</>
)
}
export default App;
```
打开浏览器,可以看到组件已经正常显示:

### 调试技巧
另外,在开发调试插件的过程,我推荐大家在本地装上`vite-plugin-inspect`插件,并在 Vite 中使用它:
```ts
// vite.config.ts
import inspect from 'vite-plugin-inspect';
// 返回的配置
{
plugins: [
// 省略其它插件
inspect()
]
}
```
这样当你再次启动项目时,会发现多出一个调试地址:

你可以通过这个地址来查看项目中各个模块的编译结果:

点击特定的文件后,你可以看到这个模块经过各个插件处理后的中间结果,如下图所示:

通过这个面板,我们可以很清楚地看到相应模块经过插件处理后变成了什么样子,让插件的调试更加方便。
## 小结
好,本节的内容到这里就接近尾声了。本节你需要重点掌握 Vite **插件钩子的含义**、**作用顺序**以及**插件的实战开发**。
首先我通过一个最简单的示例让你对 Vite 插件的结构有了初步的印象,然后对 Vite 中的各种钩子函数进行了介绍,主要包括`通用钩子`和`独有钩子`,通用钩子与 Rollup 兼容,而独有钩子在 Rollup 中会被忽略。而由于上一节已经详细介绍了 Rollup 的插件机制,对于通用钩子我们没有继续展开,而是详细介绍了 5 个独有钩子,分别是: `config`、`configResolved`、`configureServer`、`transformIndexHtml`和`handleHotUpdate`。不仅如此,我还给你从宏观角度分析了 Vite 插件的作用场景和作用顺序,你可以分别通过`apply`和`enforce`两个参数来进行手动的控制。
接下来我们正式进入插件开发实战的环节,实现了`虚拟模块加载插件`和`Svg 组件加载插件`,相信你已经对虚拟模块的概念和使用有了直观的了解,也能通过后者的开发过程了解到如何在 Vite 中集成其它的前端编译工具。总体来说,Vite 插件的设计秉承了 Rollup 的插件设计理念,通过一个个语义化的 Hook 来组织,十分简洁和灵活,上手难度并不大,但真正难的地方在于如何利用 Vite 插件去解决实际开发过程的问题,由于篇幅所限,本文的示例并不能覆盖所有的开发场景,你也不必着急,我们会在后面的几个小节中接触到更加高级的开发场景,你也将接触过越来越多的插件,当然,你的插件开发技能也能越来越纯熟。大家继续加油💪🏻!
留言

发表评论
全部评论(2)
[](https://juejin.cn/user/1917967359548344)
[鼠子的前端CodeLife](https://juejin.cn/user/1917967359548344)
学生,个人公众号主 @ 西安电子科技大学5小时前
虚拟模块引入到tsx中会报“找不到模块“virtual:fib”或其相应的类型声明。” 的错误,虽然运行时没问题,但是tsc检查肯定是通不过的,该怎么声明这个虚拟模块?
点赞
回复
[](https://juejin.cn/user/3139860939935565)
[打王者叫我](https://juejin.cn/user/3139860939935565)
CV工程师 @ 王者峡谷2天前
get |
/* Copyright (c) 2001-2002, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hsqldb;
import org.hsqldb.lib.HsqlObjectToIntMap;
/**
* Provides an enumeration of the token types commonly encountered
* while processing database commands. <p>
*
* @author Nitin Chauhan
* @since HSQLDB 1.7.2
* @version 1.7.2
*/
class Token {
private static HsqlObjectToIntMap commandSet;
//
static final String T_ASTERISK = "*";
static final String T_COMMA = ",";
static final String T_CLOSEBRACKET = ")";
static final String T_EQUALS = "=";
static final String T_OPENBRACKET = "(";
static final String T_SEMICOLON = ";";
//
static final String T_ADD = "ADD";
static final String T_ALIAS = "ALIAS";
static final String T_ALL = "ALL";
static final String T_ALTER = "ALTER";
static final String T_AS = "AS";
static final String T_ASC = "ASC";
static final String T_AUTOCOMMIT = "AUTOCOMMIT";
static final String T_BY = "BY";
static final String T_CACHED = "CACHED";
static final String T_CALL = "CALL";
static final String T_CHECKPOINT = "CHECKPOINT";
static final String T_COLUMN = "COLUMN";
static final String T_COMMIT = "COMMIT";
static final String T_CONNECT = "CONNECT";
static final String T_CONSTRAINT = "CONSTRAINT";
static final String T_CREATE = "CREATE";
static final String T_DELETE = "DELETE";
static final String T_DESC = "DESC";
static final String T_DISCONNECT = "DISCONNECT";
static final String T_DISTINCT = "DISTINCT";
static final String T_DROP = "DROP";
static final String T_ESCAPE = "ESCAPE";
static final String T_EXCEPT = "EXCEPT";
static final String T_EXPLAIN = "EXPLAIN";
static final String T_FOR = "FOR";
static final String T_FOREIGN = "FOREIGN";
static final String T_FROM = "FROM";
static final String T_GRANT = "GRANT";
static final String T_GROUP = "GROUP";
static final String T_HAVING = "HAVING";
static final String T_IGNORECASE = "IGNORECASE";
static final String T_INDEX = "INDEX";
static final String T_INNER = "INNER";
static final String T_INSERT = "INSERT";
static final String T_INTERSECT = "INTERSECT";
static final String T_INTO = "INTO";
static final String T_JOIN = "JOIN";
static final String T_LEFT = "LEFT";
static final String T_LIMIT = "LIMIT";
static final String T_LOGSIZE = "LOGSIZE";
static final String T_LOGTYPE = "LOGTYPE";
static final String T_MAXROWS = "MAXROWS";
static final String T_MEMORY = "MEMORY";
static final String T_MINUS = "MINUS";
static final String T_NOT = "NOT";
static final String T_ON = "ON";
static final String T_ORDER = "ORDER";
static final String T_OUTER = "OUTER";
static final String T_PASSWORD = "PASSWORD";
static final String T_PLAN = "PLAN";
static final String T_PRIMARY = "PRIMARY";
static final String T_PROPERTY = "PROPERTY";
static final String T_READONLY = "READONLY";
static final String T_REFERENTIAL_INTEGRITY = "REFERENTIAL_INTEGRITY";
static final String T_RENAME = "RENAME";
static final String T_REVOKE = "REVOKE";
static final String T_ROLLBACK = "ROLLBACK";
static final String T_SAVEPOINT = "SAVEPOINT";
static final String T_SCRIPT = "SCRIPT";
static final String T_SELECT = "SELECT";
static final String T_SET = "SET";
static final String T_SHUTDOWN = "SHUTDOWN";
static final String T_SOURCE = "SOURCE";
static final String T_TABLE = "TABLE";
static final String T_TEMP = "TEMP";
static final String T_TEXT = "TEXT";
static final String T_TOP = "TOP";
static final String T_TRIGGER = "TRIGGER";
static final String T_UNION = "UNION";
static final String T_UNIQUE = "UNIQUE";
static final String T_UPDATE = "UPDATE";
static final String T_USER = "USER";
static final String T_VALUES = "VALUES";
static final String T_VIEW = "VIEW";
static final String T_WHERE = "WHERE";
static final String T_WRITE_DELAY = "WRITE_DELAY";
//
static final int UNKNOWN = -1;
static final int ADD = 1;
static final int ALIAS = 2;
static final int ALTER = 3;
static final int AUTOCOMMIT = 4;
static final int CACHED = 5;
static final int CALL = 6;
static final int CHECKPOINT = 7;
static final int COLUMN = 8;
static final int COMMIT = 9;
static final int CONNECT = 10;
static final int CONSTRAINT = 11;
static final int CREATE = 12;
static final int DELETE = 13;
static final int DISCONNECT = 14;
static final int DROP = 15;
static final int EXPLAIN = 16;
static final int FOREIGN = 17;
static final int GRANT = 18;
static final int IGNORECASE = 19;
static final int INDEX = 20;
static final int INSERT = 21;
static final int LOGSIZE = 22;
static final int LOGTYPE = 23;
static final int MAXROWS = 24;
static final int MEMORY = 25;
static final int PASSWORD = 26;
static final int PLAN = 27;
static final int PRIMARY = 28;
static final int PROPERTY = 29;
static final int READONLY = 30;
static final int REFERENTIAL_INTEGRITY = 31;
static final int RENAME = 32;
static final int REVOKE = 33;
static final int ROLLBACK = 34;
static final int SAVEPOINT = 35;
static final int SCRIPT = 36;
static final int SELECT = 37;
static final int SEMICOLON = 38;
static final int SET = 39;
static final int SHUTDOWN = 40;
static final int SOURCE = 41;
static final int TABLE = 42;
static final int TEXT = 43;
static final int TRIGGER = 44;
static final int UNIQUE = 45;
static final int UPDATE = 46;
static final int USER = 47;
static final int VIEW = 48;
static final int WRITE_DELAY = 49;
//
static {
commandSet = newCommandSet();
}
/**
* Retrieves a new map from set of string tokens to numeric tokens for
* commonly encountered database command token occurences.
*
* @return a new map for the database command token set
*/
private static HsqlObjectToIntMap newCommandSet() {
HsqlObjectToIntMap commandSet;
commandSet = new HsqlObjectToIntMap(67);
commandSet.put(T_SEMICOLON, SEMICOLON);
commandSet.put(T_ADD, ADD);
commandSet.put(T_ALIAS, ALIAS);
commandSet.put(T_ALTER, ALTER);
commandSet.put(T_AUTOCOMMIT, AUTOCOMMIT);
commandSet.put(T_CACHED, CACHED);
commandSet.put(T_CALL, CALL);
commandSet.put(T_CHECKPOINT, CHECKPOINT);
commandSet.put(T_COLUMN, COLUMN);
commandSet.put(T_COMMIT, COMMIT);
commandSet.put(T_CONNECT, CONNECT);
commandSet.put(T_CONSTRAINT, CONSTRAINT);
commandSet.put(T_CREATE, CREATE);
commandSet.put(T_DELETE, DELETE);
commandSet.put(T_DISCONNECT, DISCONNECT);
commandSet.put(T_DROP, DROP);
commandSet.put(T_EXPLAIN, EXPLAIN);
commandSet.put(T_FOREIGN, FOREIGN);
commandSet.put(T_GRANT, GRANT);
commandSet.put(T_IGNORECASE, IGNORECASE);
commandSet.put(T_INDEX, INDEX);
commandSet.put(T_INSERT, INSERT);
commandSet.put(T_LOGSIZE, LOGSIZE);
commandSet.put(T_LOGTYPE, LOGTYPE);
commandSet.put(T_MAXROWS, MAXROWS);
commandSet.put(T_MEMORY, MEMORY);
commandSet.put(T_PASSWORD, PASSWORD);
commandSet.put(T_PLAN, PLAN);
commandSet.put(T_PRIMARY, PRIMARY);
commandSet.put(T_PROPERTY, PROPERTY);
commandSet.put(T_READONLY, READONLY);
commandSet.put(T_REFERENTIAL_INTEGRITY, REFERENTIAL_INTEGRITY);
commandSet.put(T_RENAME, RENAME);
commandSet.put(T_REVOKE, REVOKE);
commandSet.put(T_ROLLBACK, ROLLBACK);
commandSet.put(T_SAVEPOINT, SAVEPOINT);
commandSet.put(T_SCRIPT, SCRIPT);
commandSet.put(T_SELECT, SELECT);
commandSet.put(T_SET, SET);
commandSet.put(T_SHUTDOWN, SHUTDOWN);
commandSet.put(T_SOURCE, SOURCE);
commandSet.put(T_TABLE, TABLE);
commandSet.put(T_TEXT, TEXT);
commandSet.put(T_TRIGGER, TRIGGER);
commandSet.put(T_UNIQUE, UNIQUE);
commandSet.put(T_UPDATE, UPDATE);
commandSet.put(T_USER, USER);
commandSet.put(T_VIEW, VIEW);
commandSet.put(T_WRITE_DELAY, WRITE_DELAY);
return commandSet;
}
static int get(String token) {
return commandSet.get(token);
}
} |
/*--------------------------------------------------------------------------*\
| |
| Copyright (C) 2017 |
| |
| , __ , __ |
| /|/ \ /|/ \ |
| | __/ _ ,_ | __/ _ ,_ |
| | \|/ / | | | | \|/ / | | | |
| |(__/|__/ |_/ \_/|/|(__/|__/ |_/ \_/|/ |
| /| /| |
| \| \| |
| |
| Enrico Bertolazzi |
| Dipartimento di Ingegneria Industriale |
| Universita` degli Studi di Trento |
| email: enrico.bertolazzi@unitn.it |
| |
\*--------------------------------------------------------------------------*/
#include "Alglin.hh"
#ifdef __clang__
#pragma clang diagnostic ignored "-Wexit-time-destructors"
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
using namespace alglin;
static Utils::Console msg( &std::cout,4);
static
bool
fun( real_type const x[4], real_type & res ) {
res = x[0] + sin(x[1]) + exp(x[2]*x[3]) + x[0]*x[1]*x[2];
return true;
}
static
bool
fun_grad( real_type const x[4], real_type grad[4] ) {
grad[0] = 1+x[1]*x[2];
grad[1] = cos(x[1])+ x[0]*x[2];
grad[2] = exp(x[2]*x[3])*x[3]+x[0]*x[1];
grad[3] = exp(x[2]*x[3])*x[2];
return true;
}
static
bool
fun_jac( real_type const x[4], real_type jac[4*4] ) {
jac[0+0*4] = 0;
jac[0+1*4] = x[2];
jac[0+2*4] = x[1];
jac[0+3*4] = 0;
jac[1+0*4] = x[2];
jac[1+1*4] = -sin(x[1]);
jac[1+2*4] = x[0];
jac[1+3*4] = 0;
jac[2+0*4] = x[1];
jac[2+1*4] = x[0];
jac[2+2*4] = exp(x[2]*x[3])*x[3]*x[3];
jac[2+3*4] = exp(x[2]*x[3]) + exp(x[2]*x[3])*x[2]*x[3];
jac[3+0*4] = 0;
jac[3+1*4] = 0;
jac[3+2*4] = exp(x[2]*x[3])+exp(x[2]*x[3])*x[2]*x[3];
jac[3+3*4] = exp(x[2]*x[3])*x[2]*x[2];
return true;
}
class fun_class {
public:
bool operator () ( real_type const x[4], real_type & res ) {
return fun(x,res);
}
};
class fun_class1 {
public:
bool operator () ( real_type const x[4], real_type res[4] ) {
return fun_grad( x, res );
}
};
int
main() {
using namespace std;
integer dim_x = 4;
real_type x[4] = { 1, 2, 1, 4 };
real_type gradFD[4], grad[4], jac[4*4], jacFD[4*4];
fun_class ff;
fun_class1 gg;
bool ok = finite_difference_gradient( x, dim_x, ff, gradFD );
ok = fun_grad( x, grad );
real_type epsi = 1e-6;
fmt::print(
"\n\nCheck Gradient\n{}Done\n",
finite_difference_check_gradient( x, dim_x, ff, grad, epsi )
);
fmt::print("diff grad(FD)[0] = {:>12.6}\n", gradFD[0] - grad[0]);
fmt::print("diff grad(FD)[1] = {:>12.6}\n", gradFD[1] - grad[1]);
fmt::print("diff grad(FD)[2] = {:>12.6}\n", gradFD[2] - grad[2]);
fmt::print("diff grad(FD)[3] = {:>12.6}\n", gradFD[3] - grad[3]);
fmt::print("diff grad(FD)[0] = {:>12.6}\n", (gradFD[0] - grad[0])/max(1.0,abs(grad[0])));
fmt::print("diff grad(FD)[1] = {:>12.6}\n", (gradFD[1] - grad[1])/max(1.0,abs(grad[1])));
fmt::print("diff grad(FD)[2] = {:>12.6}\n", (gradFD[2] - grad[2])/max(1.0,abs(grad[2])));
fmt::print("diff grad(FD)[3] = {:>12.6}\n", (gradFD[3] - grad[3])/max(1.0,abs(grad[3])));
std::vector<real_type> work(4*dim_x);
ok = fun_jac( x, jac );
ok = finite_difference_jacobian(
x, dim_x, gg, dim_x, jacFD, dim_x,
work.data(), work.size()
);
fmt::print(
"\n\nCheck Jacobian\n{}Done\n",
finite_difference_check_jacobian(
x, dim_x, gg, dim_x, jac, dim_x,
epsi, work.data(), work.size()
)
);
for ( int i = 0; i < dim_x; ++i ) {
for ( int j = 0; j < dim_x; ++j ) {
fmt::print(
"jac[{},{}] = {:<12.6} err = {:<12.6}\n",
i, j, jac[i+j*dim_x], abs(jac[i+j*dim_x]-jacFD[i+j*dim_x])
);
}
}
ok = finite_difference_hessian( x, dim_x, ff, jacFD, dim_x );
fmt::print("ok = {}\n",ok);
for ( int i = 0; i < dim_x; ++i ) {
for ( int j = 0; j < dim_x; ++j ) {
fmt::print(
"Hess[{0},{1}] = {2:<12.6} HessFD[{0},{1}] = {3:<12.6} err = {4:<12.6}\n",
i, j, jac[i+j*dim_x], jacFD[i+j*dim_x], abs(jac[i+j*dim_x]-jacFD[i+j*dim_x])
);
}
}
fmt::print(
"\n\nCheck Hessian\n{}Done\n",
finite_difference_check_hessian( x, dim_x, ff, jac, dim_x, epsi )
);
msg.green( "All done!\n" );
return 0;
} |
**AreaMobile & OpenPicus** is glad to present you:
DooIP Firmware & AreaPICs APIs
A few weeks ago we were wondering about the fact that Android, the Google operating system for Smartphones which is
now a huge ecosystem with hundreds of thousands of daily activations,become too important. Then we should to have an
easy-to-build integration with our openPICUS FlyPort ecosystem.
Today, an Android Developers who wants to communicate with the real world, is provided only with a development
environment, the so-called Android Open Accessory Development Kit, released directly by BigG several months ago.
It is based on USB connection and it leverages the compatibility with the beloved Arduino boards, allowing you to
develop Android accessories such as docking stations, usb speakers, etc...
Anyone, who has actually used it, knows that Android OADK has some limitations. OADK is based on USB communication
between Android and an external device and its commands are strongly based on the USB protocol. Using OADK a physical
cable (USB) connection is required in order to communicate between the endpoints and it is basically possible to connect
only one device at a time.
The overall picture makes the OADK a not properly fitting solution when it comes to domotics for example: imagining
your "home" as an Android accessory is probably hard.
The question was: how to create a system that will allow you to connect as many devices as you want with your Android
terminal also helping you to do it remotely and wirelessly?
Our choice: Simplicity and Freedom: UDP, JSON and a Java API library
Once again we have chosen standardization, simplicity and performance. That means using using UDP as a transport
protocol and JSON as a communication protocol. For those not familiar with it, JSON is a specific lighweight client-server
communication protocol that is lighter and easier to manage - in comparison with XML for example - that is reallly
widespread these days. As Wikipedia says:
JSON JavaScript Object Notation,is a lightweight text-based open standard designed for human-readable data interchange.
It is derived from the JavaScript scripting language for representing what simple data structures and associative arrays,
Called objects. Despite its relationship to JavaScript, it is language-independent, with parsers available for many
languages.
So a lightweight, multi-platform and essentially human readable protocol is de-facto a standard, adopted because of its
simplicity, by the most important Internet players before openPICUS (among them are Yahoo or Google).
So, firstly we have developed a new firmware for our FlyPort (called DOoIP) that is able to receive, interpret and
execute JSON commands. It would be similar to development of a lighter and more manageable version of UPNP that is
text/JSON based instead of XML and verbose. Once done you will see it available on our page on Google Code (or on
Download section of openpicus.com). All the developments are now under the test and will be available in a couple of
weeks.
With the development of the JSON based discovery and remote controlling protocol, we will have a new simple and powerful
tool that will, at the end of the day, will let you directly talk and command Flyports via the Internet, without even
put your hands on the IDE.
And, furthermore, to make it even easier to you, we started to develop a number of secondary endpoints that we will be
bringing to the community in the future. The first one that is going be released contextually with DOoIP - will be a
connector for the absolutely pervasive Android system.
Thanks to the fruitful cooperation with our friends from AreaMobile, we have encapsulated the generation of commands
that are needed to control the FlyPort via DOoIP remotely in an Android java library that is easily adoptable by the
developer (great jobe mates!).
The openPicus team working with the mates from Areamobile
To command a Flyport from an Android device just include the library in your app and you can use it right away. Your app
could be published and downloadable from the Google Play market.
The procedure is straightforward and easy and neither does require the knowledge of JSON and of low-level communication
formalisms.
At the end of the day, this choice led us to develop a technology that is:
Simple and Standard: using JSON and UDP
Extendable and Reusable: in the future we can simply write new libraries for iPhone, WindowsPhone, etc. … or you
can write it!
Powerful: is wireless and multipoint
It’s easy for an Android developer: thanks to the availability of the Android library
All that will allow you to create, for example, home automation applications without having to learn complex communication
protocols or technologies: you just need to check the documentation that we’ll made available, and download the library!
A lot of Ideas!
After we had completed this work, we began to think a multiplicity of ideas that anyone of you can build using this new
technology.
You know that Italians are coffee lovers? We never start our workday without a steaming cup of coffee! Incidentially,
this is a common practice even beyond the borders of this beautiful country!
So, think of an Android application that "wakes you up" and, in addition to getting you out of the bed with your favorite
music, it turns on the coffee machine and makes you the first morning coffee! Wouldn't it be pretty amazing.
Imagine it as a hack, that every "maker" can do "hacking" his own old and good coffee machine, but also think this as an
extension that any coffee-machine manufacturer might adopt for its own product: imagine buying a machine that is able to
communicate with your Android phone - since it contains a FlyPort module - and you download the "Wake me up with coffee"
application right from the Google Play: that's it! (Message to the reader: if you are a machine manufacturer, and not
only of coffee machines, drop us an email here and let’s do it!)
Why not to think even of a system that stores your favorite lighting-settings presets, and is activated via the device?
Maybe by using the amazing Android built-in features such as facial recognition or Speech-to-Text. This would allow us
to activate our illumination profile simply by smiling at our smartphone (or maybe at the usb camera connected to an
Android set top box), or by talking in a natural way with the system.
As you can imagine a number of potential developments and the potential of this new techology is huge and truly exciting. |
import React, { useState } from "react";
import { changeEmailProfessional } from "../../../../features/apiPetitions";
import style from './ChangeEmail.module.css'
function ChangeEmail() {
const [emailData, setEmailData] = useState({
currentEmail: "",
newEmail: "",
});
const [verifyNewEmail, setVerifyNewEmail] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
if (!emailData.currentEmail) {
alert("Debe ingresar su correo electrónico actual.");
return;
}
if (!emailData.newEmail) {
alert("Debe ingresar su nuevo correo electrónico.");
return;
}
if (!verifyNewEmail || verifyNewEmail !== emailData.newEmail) {
alert("Debe verificar su nueva dirección de correo electrónico.");
return;
}
await changeEmailProfessional({ email: emailData.newEmail });
setEmailData({
currentEmail: emailData.newEmail,
newEmail: "",
});
setVerifyNewEmail("");
};
return (
<div className={style.changeContainer}>
<h2 className={style.emailTitle}>Cambiar correo electrónico</h2>
<form className={style.changeForm} onSubmit={handleSubmit}>
<label className={style.formLabel} htmlFor="current-email">Correo electrónico actual:</label>
<div className={style.changeField}>
<input
type="email"
id="current-email"
value={emailData.currentEmail}
onChange={(e) =>
setEmailData({ ...emailData, currentEmail: e.target.value })
}
required
/>
</div>
<label className={style.formLabel} htmlFor="new-email">Nuevo correo electrónico:</label>
<div className={style.changeField}>
<input
type="email"
id="new-email"
value={emailData.newEmail}
onChange={(e) =>
setEmailData({ ...emailData, newEmail: e.target.value })
}
required
/>
</div>
<label className={style.formLabel} htmlFor="verify-new-email">Verifica tu correo:</label>
<div className={style.changeField}>
<input
type="email"
id="verify-new-email"
value={verifyNewEmail}
onChange={(e) => setVerifyNewEmail(e.target.value)}
required
/>
</div>
<button className={style.submitButton} type="submit">Guardar cambios</button>
</form>
</div>
);
}
export default ChangeEmail; |
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
return self.helper(nums, 0, len(nums)-1)
def helper(self, nums, start, end):
if(start> end):
return None
mid = (start+end) //2
#print(mid)
root = TreeNode(nums[mid])
root.left = self.helper(nums,start,mid-1)
root.right = self.helper(nums,mid+1,end)
return root |
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Role } from '../enum/role.enum';
import { jwtDecode } from 'jwt-decode';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requireRoles = this.reflector.getAllAndOverride<Role[]>('roles', [
context.getHandler(),
context.getClass(),
]);
if (!requireRoles) {
return true;
}
const request: Request = context.switchToHttp().getRequest();
const token: string = request.headers['authorization'].split(' ')[1];
const decodedToken = jwtDecode(token) as any;
const { user } = context.switchToHttp().getRequest();
return requireRoles.some((role) => decodedToken.roles.includes(role));
}
} |
<!DOCTYPE html>
<html lang="en" layout:decorate="~{layout.html}">
<head>
<title>Students Page</title>
</head>
<body>
<div layout:fragment="content">
<!-- DELETE WARNING MODAL -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Confirm delete !</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
Are you sure you want to delete this instance ?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-danger"> Delete </button>
</div>
</div>
</div>
</div>
<div class="d-flex justify-content-around align-items-center">
<h1> Students </h1>
<a class="btn btn-primary" href="student-add"> Ajouter </a>
</div>
<table class="table">
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Course</th>
<th></th>
</tr>
<tr th:each="student : ${studentList} ">
<td th:text="${student.id}"></td>
<td th:text="${student.firstName}"></td>
<td th:text="${student.lastName}"></td>
<td th:text="${student.course.name}"></td>
<td>
<div class="btn-group" role="group" aria-label="Basic example">
<a class="btn btn-outline-primary" th:href="@{/student-info(id=${student.id})}"> Detail </a>
<button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteModal">
Delete
</button>
</div>
</td>
</tr>
</table>
</div>
</body>
</html> |
import { Pane } from 'tweakpane';
import type { View } from '../view.ts';
import type { GameObject } from '../components';
const createToggleGuiButton = (pane: Pane) => {
const button = document.createElement('button');
button.innerText = '⚙️';
button.style.position = 'absolute';
button.style.zIndex = '100';
button.style.top = '10px';
button.style.right = '10px';
button.style.cursor = 'pointer';
button.title = 'Show control panel';
button.addEventListener('click', () => {
pane.hidden = !pane.hidden;
button.innerText = pane.hidden ? '⚙️' : '❌';
});
pane.hidden = false;
return button;
};
/**
* https://cocopon.github.io/tweakpane/
*/
export const addControlPanel = ({
view,
gameObject,
animations,
}: {
view: View;
gameObject: GameObject;
animations: string[];
}): {
pane: Pane;
button: HTMLButtonElement;
} => {
const pane = new Pane();
const tab = pane.addTab({ pages: [{ title: 'Unit' }] });
const [unitPage] = tab.pages;
const animationOptions = Object.values(animations)
.sort()
.reduce(
(prev, nextKey) => {
prev[nextKey] = nextKey;
return prev;
},
{} as Record<string, string>,
);
const animationState = {
name: animations[0],
fadeDuration: 0,
};
unitPage.addBinding(animationState, 'name', {
label: 'name',
options: animationOptions,
});
unitPage.addBinding(animationState, 'fadeDuration', {
label: 'fade duration (sec)',
step: 0.1,
min: 0,
max: 4,
});
unitPage
.addButton({
title: 'Play',
})
.on('click', () => {
gameObject.stopActions(1);
gameObject.playAction(animationState.name, 1);
});
unitPage
.addButton({
title: 'Stop',
})
.on('click', () => {
gameObject.stopActions();
});
void view;
pane.element.style.position = 'absolute';
pane.element.style.top = '20px';
pane.element.style.right = '20px';
pane.element.style.zIndex = '1000';
const button = createToggleGuiButton(pane);
return {
pane,
button,
};
}; |
//##################################################################################################
//
// Custom Visualization Core library
// Copyright (C) 2011-2013 Ceetron AS
//
// This library may be used under the terms of either the GNU General Public License or
// the GNU Lesser General Public License as follows:
//
// GNU General Public License Usage
// This library 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 library 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 at <<http://www.gnu.org/licenses/gpl.html>>
// for more details.
//
// GNU Lesser General Public License Usage
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library 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 Lesser General Public License at <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include <vector>
#include <QString>
#include <QStringList>
#include <QTextStream>
namespace caf
{
/// An enum class to make it easier to handle IO and UI based on the enum.
/// Usage:
/// In Header file of SomeClass:
/// enum SomeEnumType
/// {
/// A = 2,
/// B = 7
/// };
/// caf::AppEnum<SomeEnumType> m_enumValue;
///
/// In C++ file :
/// namespace caf {
/// template<>
/// void caf::AppEnum<SomeClass::SomeEnumType>::setUp()
/// {
/// addItem(SomeClass::A, "A", "An A letter");
/// addItem(SomeClass::B, "B", "A B letter");
/// setDefault(SomeClass::B);
/// }
/// }
/// General use:
///
/// m_enumValue = A;
/// if (m_enumValue == A || m_enumValue != B ){}
///
/// switch (m_enumValue)
/// {
/// case A:
/// break;
/// case B:
/// break;
/// }
///
/// cout << m_enumValue.text();
/// m_enumValue.setFromText("A");
///
/// for (size_t i = 0; i < caf::AppEnum<SomeClass::SomeEnumType>::size(); ++i)
/// cout << caf::AppEnum<SomeClass::SomeEnumType>::text(caf::AppEnum<SomeClass::SomeEnumType>::fromIndex(i)) << endl;
///
template <class T>
class AppEnum
{
public:
AppEnum() { m_value = EnumMapper::instance()->defaultValue();}
AppEnum(T value): m_value(value) {}
bool operator== (T value) const { return m_value == value;}
bool operator!= (T value) const { return m_value != value;}
operator T () const { return m_value;}
QString text() const { return EnumMapper::instance()->text(m_value);}
QString uiText() const { return EnumMapper::instance()->uiText(m_value);}
AppEnum& operator= (T value) { m_value = value; return *this; }
bool setFromText(const QString& text){ return EnumMapper::instance()->enumVal(m_value, text);}
bool setFromIndex (size_t index) { return EnumMapper::instance()->enumVal(m_value, index); }
// Static interface to access the properties of the enum definition
static bool isValid(const QString& text) { return EnumMapper::instance()->isValid(text);}
static bool isValid(size_t index) { return index < EnumMapper::instance()->size();}
static size_t size() { return EnumMapper::instance()->size();}
static QStringList uiTexts() { return EnumMapper::instance()->uiTexts(); }
static T fromIndex (size_t idx) { T val; EnumMapper::instance()->enumVal(val, idx); return val;}
static T fromText(const QString& text) { T val; EnumMapper::instance()->enumVal(val, text); return val;}
static size_t index (T enumValue) { return EnumMapper::instance()->index(enumValue);}
static QString text (T enumValue) { return EnumMapper::instance()->text(enumValue);}
static QString textFromIndex (size_t idx) { return text(fromIndex(idx));}
static QString uiText(T enumValue) { return EnumMapper::instance()->uiText(enumValue);}
static QString uiTextFromIndex(size_t idx) { return uiText(fromIndex(idx)); }
private:
/// The setup method is supposed to be specialized for each and every type instantiation of this class,
/// and is supposed to set up the mapping between enum values, text and ui-text using the \m addItem
/// method. It may also set a default value using \m setDefault
static void setUp();
static void addItem(T enumVal, const QString& text, const QString& uiText)
{
EnumMapper::instance()->addItem(enumVal, text, uiText);
}
static void setDefault( T defaultEnumValue)
{
EnumMapper::instance()->setDefault(defaultEnumValue);
}
T m_value;
/// A private class to handle the instance of the mapping vector.
/// all access methods could have been placed directly in the \class AppEnum class,
/// but AppEnum implementation gets nicer this way.
/// The real core of this class is the vector map member and the static instance method
class EnumMapper
{
private:
struct Triplet
{
Triplet(T enumVal, const QString& text, QString uiText) :
m_enumVal(enumVal), m_text(text), m_uiText(uiText)
{}
T m_enumVal;
QString m_text;
QString m_uiText;
};
public:
void addItem(T enumVal, const QString& text, QString uiText)
{
instance()->m_mapping.push_back(Triplet(enumVal, text, uiText));
}
static EnumMapper * instance()
{
static EnumMapper * storedInstance = 0;
if (!storedInstance)
{
storedInstance = new EnumMapper;
AppEnum<T>::setUp();
}
return storedInstance;
}
void setDefault(T defaultEnumValue)
{
m_defaultValue = defaultEnumValue;
m_defaultValueIsSet = true;
}
T defaultValue() const
{
if (m_defaultValueIsSet)
{
return m_defaultValue;
}
else
{
// assert(m_mapping.size());
return m_mapping[0].m_enumVal;
}
}
bool isValid( const QString& text) const
{
size_t idx;
for(idx = 0; idx < m_mapping.size(); ++idx)
{
if (text == m_mapping[idx].m_text) return true;
}
return false;
}
size_t size() const
{
return m_mapping.size();
}
bool enumVal(T& value, const QString& text) const
{
value = defaultValue();
size_t idx;
for(idx = 0; idx < m_mapping.size(); ++idx)
{
if (text == m_mapping[idx].m_text)
{
value = m_mapping[idx].m_enumVal;
return true;
}
}
return false;
}
bool enumVal(T& value, size_t index) const
{
value = defaultValue();
if (index < m_mapping.size())
{
value = m_mapping[index].m_enumVal;
return true;
}
else
return false;
}
size_t index(T enumValue) const
{
size_t idx;
for(idx = 0; idx < m_mapping.size(); ++idx)
{
if (enumValue == m_mapping[idx].m_enumVal)
return idx;
}
return idx;
}
QString uiText(T value) const
{
size_t idx;
for(idx = 0; idx < m_mapping.size(); ++idx)
{
if (value == m_mapping[idx].m_enumVal) return m_mapping[idx].m_uiText;
}
return "";
}
QStringList uiTexts () const
{
QStringList uiTextList;
size_t idx;
for(idx = 0; idx < m_mapping.size(); ++idx)
{
uiTextList.append(m_mapping[idx].m_uiText);
}
return uiTextList;
}
QString text(T value) const
{
size_t idx;
for(idx = 0; idx < m_mapping.size(); ++idx)
{
if (value == m_mapping[idx].m_enumVal) return m_mapping[idx].m_text;
}
return "";
}
private:
EnumMapper() : m_defaultValueIsSet(false) { }
friend class AppEnum<T>;
std::vector<Triplet> m_mapping;
T m_defaultValue;
bool m_defaultValueIsSet;
};
};
}
/// Cant remember why we need those comparison operators...
template<class T>
bool operator == ( T value, const caf::AppEnum<T>& appEnum)
{
return (appEnum == value);
}
template<class T>
bool operator != ( T value, const caf::AppEnum<T>& appEnum)
{
return (appEnum != value);
}
/// Implementation of stream operators to make PdmField<AppEnum<> > work smoothly
/// Assumes that the stream ends at the end of the enum text
template < typename T >
void operator >> (QTextStream& str, caf::AppEnum<T>& appEnum)
{
QString text;
str >> text;
appEnum.setFromText(text);
}
template < typename T >
void operator << (QTextStream& str, const caf::AppEnum<T>& appEnum)
{
str << appEnum.text();
} |
require 'minitest'
require 'minitest/autorun'
require './lib/attendee'
class AttendeeTest < MiniTest::Test
def test_it_exists
attendee = Attendee.new
assert_kind_of Attendee, attendee
end
def test_it_is_initialized_from_a_hash_of_data
data = { :first_name => 'George', :last_name => 'Washington', :phone_number => '2024556677'}
attendee = Attendee.new(data)
assert_equal data[:first_name], attendee.first_name
assert_equal data[:last_name], attendee.last_name
assert_equal data[:phone_number], attendee.phone_number
end
def test_it_can_change_first_names
data = {:first_name => "George"}
attendee = Attendee.new(data)
assert_equal data[:first_name], attendee.first_name
attendee.first_name = "Thomas"
assert_equal "Thomas", attendee.first_name
end
end |
import { defaultCommands } from './commands';
import { defaultKeybindings } from './keybindings';
/**
* Defaults that a new Unixorn component will
* be initialized with if its props are not set.
*/
export const defaultConfiguration: UnixornConfiguration = {
autoFocus: false,
commands: defaultCommands,
keybindings: defaultKeybindings,
prompt: '> ',
startupMessage: 'Welcome to Unixorn. Enter `help` for basic information.',
};
/**
* The props of a Unixorn component.
*/
export interface UnixornConfiguration {
/**
* Whether the component should take focus when the page loads.
*/
autoFocus?: boolean;
/**
* List of commands to use instead of the default commands.
*/
commands?: UnixornCommand[];
/**
* List of keybindings to use instead of the default keybindings.
*/
keybindings?: UnixornKeybinding[];
/**
* The string to use instead of the default prompt.
*/
prompt?: string;
/**
* The message to show when Unixorn starts.
*/
startupMessage?: string;
}
/**
* A command that can be run on the command line.
*/
export interface UnixornCommand {
/**
* The name of the command.
*/
name: string;
/**
* A string that demonstrates how the command is used.
*/
usage: string;
/**
* A brief description of the purpose of the command.
*/
summary: string;
/**
* The actual code of the command.
*/
action: (kernel: UnixornKernel, tokens: string[]) => void;
}
/**
* A keybinding that can be triggered on the command line.
*/
export interface UnixornKeybinding {
/**
* Whether the control key should be held.
*/
ctrl: boolean;
/**
* Whether the meta key should be held.
* On a standard keyboard, the meta key is marked "alt".
*/
meta: boolean;
/**
* The non-modifier key of the keybinding.
*/
key: string;
/**
* A brief description of the purpose of the keybinding.
*/
summary: string;
/**
* The actual code of the keybinding.
*/
action: (kernel: UnixornKernel) => void;
}
/**
* The set of Unixorn system calls.
*/
export interface UnixornKernel {
/**
* Clear input and output that has been rendered to screen.
*/
clearScreen: () => void;
/**
* Get the list of available commands.
*/
commands: () => UnixornCommand[];
/**
* Delete all characters after cursor.
*/
deleteToEnd: () => void;
/**
* Delete all characters before cursor.
*/
deleteToStart: () => void;
/**
* Execute a statement.
*/
execute: (stmt: string[]) => void;
/**
* Get the list of available keybindings.
*/
keybindings: () => UnixornKeybinding[];
/**
* Move the cursor to the end of the line.
*/
moveCursorToEnd: () => void;
/**
* Move the cursor to the start of the line.
*/
moveCursorToStart: () => void;
/**
* Split a list of tokens into a
* list of statements.
*/
parse: (tokens: string[]) => string[][];
/**
* Print text to stderr.
*/
printErr: (text: string) => void;
/**
* Print text to stdout.
*/
printOut: (text: string) => void;
/**
* Split the text of a program into a
* list of tokens.
*/
tokenize: (programText: string) => string[];
/**
* Visit a URL.
*/
visit: (url: string) => void;
} |
/*----------------------------------------------------------------------------*/
/*
* PropertySphere.h
*
* Created on: 22 mars 2012
* Author: ledouxf
*/
/*----------------------------------------------------------------------------*/
#ifndef PROPERTYSPHERE_H_
#define PROPERTYSPHERE_H_
/*----------------------------------------------------------------------------*/
//inclusion de fichiers de la STL
#include <string>
/*----------------------------------------------------------------------------*/
#include "Utils/Point.h"
#include "Utils/Constants.h"
#include "Geom/GeomProperty.h"
/*----------------------------------------------------------------------------*/
namespace Mgx3D {
/*----------------------------------------------------------------------------*/
namespace Geom {
/*----------------------------------------------------------------------------*/
/**
* \class PropertySphere
* \brief Décrit les propriétés d'une sphère
*/
class PropertySphere: public GeomProperty {
public:
/*------------------------------------------------------------------------*/
/** \brief Constructeur
*
* \param center le centre de la sphère
* \param radius le rayon de la sphère
* \param angle l'angle de la portion de sphère
* \param portion le type de portion de sphère créée
*/
PropertySphere(const Utils::Math::Point& center, const double radius,
const Utils::Portion::Type& type, const double angle);
/*------------------------------------------------------------------------*/
/** \brief Destructeur
*/
virtual ~PropertySphere();
/*------------------------------------------------------------------------*/
/** \brief Accesseur sur le type de propriété
*/
GeomProperty::type getType() const;
/*------------------------------------------------------------------------*/
/** \brief Accesseur et modificateur sur le centre de la sphère
*/
Utils::Math::Point const& getCenter() const;
void setCenter(const Utils::Math::Point& c);
/*------------------------------------------------------------------------*/
/** \brief Accesseur et modificateur sur le rayon de la sphère
*/
double getRadius() const;
void setRadius(const double r);
/*------------------------------------------------------------------------*/
/** \brief Accesseur et modificateur sur l'angle de la sphère
*/
double getAngle() const;
void setAngle(const double r);
/*------------------------------------------------------------------------*/
/** \brief Accesseur sur le type de portion de sphère
*/
Utils::Portion::Type getPortionType() const;
/*------------------------------------------------------------------------*/
/** permet l'affichage des propriétés spécifiques de l'objet */
virtual void addDescription(Utils::SerializedRepresentation& geomProprietes) const;
protected:
/** centre */
Utils::Math::Point m_center;
/** rayon */
double m_radius;
/** type de portion */
Utils::Portion::Type m_portion;
/** angle */
double m_angle;
};
/*----------------------------------------------------------------------------*/
} // end namespace Geom
/*----------------------------------------------------------------------------*/
} // end namespace Mgx3D
/*----------------------------------------------------------------------------*/
#endif /* PROPERTYSPHERE_H_ */
/*----------------------------------------------------------------------------*/ |
<?php
namespace Drupal\yamlform;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Handles YAML form requests.
*/
class YamlFormRequest implements YamlFormRequestInterface {
/**
* The entity manager.
*
* @var \Drupal\Core\Entity\EntityManagerInterface $entity_manager
*/
protected $entityManager;
/**
* The current route match.
*
* @var \Drupal\Core\Routing\RouteMatchInterface
*/
protected $routeMatch;
/**
* Constructs a YamlFormSubmissionExporter object.
*
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
* The entity manager.
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The current route match.
*/
public function __construct(EntityManagerInterface $entity_manager, RouteMatchInterface $route_match) {
$this->entityManager = $entity_manager;
$this->routeMatch = $route_match;
}
/**
* {@inheritdoc}
*/
public function getCurrentSourceEntity($ignored_types = NULL) {
$entity_types = $this->entityManager->getEntityTypeLabels();
if ($ignored_types) {
if (is_array($ignored_types)) {
$entity_types = array_diff_key($entity_types, array_flip($ignored_types));
}
else {
unset($entity_types[$ignored_types]);
}
}
foreach ($entity_types as $entity_type => $entity_label) {
$entity = $this->routeMatch->getParameter($entity_type);
if ($entity instanceof EntityInterface) {
return $entity;
}
}
return NULL;
}
/**
* {@inheritdoc}
*/
public function getCurrentYamlForm() {
$source_entity = self::getCurrentSourceEntity('yamlform');
if ($source_entity && method_exists($source_entity, 'hasField') && $source_entity->hasField('yamlform')) {
return $source_entity->yamlform->entity;
}
else {
return $this->routeMatch->getParameter('yamlform');
}
}
/**
* {@inheritdoc}
*/
public function getYamlFormEntities() {
$yamlform = $this->getCurrentYamlForm();
$source_entity = $this->getCurrentSourceEntity('yamlform');
return [$yamlform, $source_entity];
}
/**
* {@inheritdoc}
*/
public function getYamlFormSubmissionEntities() {
$yamlform_submission = $this->routeMatch->getParameter('yamlform_submission');
$source_entity = $this->getCurrentSourceEntity('yamlform_submission');
return [$yamlform_submission, $source_entity];
}
/****************************************************************************/
// Routing helpers
/****************************************************************************/
/**
* {@inheritdoc}
*/
public function getRouteName(EntityInterface $yamlform_entity, EntityInterface $source_entity = NULL, $route_name) {
return $this->getBaseRouteName($yamlform_entity, $source_entity) . '.' . $route_name;
}
/**
* {@inheritdoc}
*/
public function getRouteParameters(EntityInterface $yamlform_entity, EntityInterface $source_entity = NULL) {
// Get source entity from the YAML form submission.
if (!$source_entity && $yamlform_entity instanceof YamlFormSubmissionInterface) {
$source_entity = $yamlform_entity->getSourceEntity();
}
if (self::isValidSourceEntity($yamlform_entity, $source_entity)) {
if ($yamlform_entity instanceof YamlFormSubmissionInterface) {
return [
'yamlform_submission' => $yamlform_entity->id(),
$source_entity->getEntityTypeId() => $source_entity->id(),
];
}
else {
return [$source_entity->getEntityTypeId() => $source_entity->id()];
}
}
elseif ($yamlform_entity instanceof YamlFormSubmissionInterface) {
return [
'yamlform_submission' => $yamlform_entity->id(),
'yamlform' => $yamlform_entity->getYamlForm()->id(),
];
}
else {
return [$yamlform_entity->getEntityTypeId() => $yamlform_entity->id()];
}
}
/**
* {@inheritdoc}
*/
public function getBaseRouteName(EntityInterface $yamlform_entity, EntityInterface $source_entity = NULL) {
if ($yamlform_entity instanceof YamlFormSubmissionInterface) {
$yamlform = $yamlform_entity->getYamlForm();
$source_entity = $yamlform_entity->getSourceEntity();
}
elseif ($yamlform_entity instanceof YamlFormInterface) {
$yamlform = $yamlform_entity;
}
else {
throw new \InvalidArgumentException('YAML form entity');
}
if (self::isValidSourceEntity($yamlform, $source_entity)) {
return 'entity.' . $source_entity->getEntityTypeId();
}
else {
return 'entity';
}
}
/**
* {@inheritdoc}
*/
public function isValidSourceEntity(EntityInterface $yamlform_entity, EntityInterface $source_entity = NULL) {
if ($yamlform_entity instanceof YamlFormSubmissionInterface) {
$yamlform = $yamlform_entity->getYamlForm();
$source_entity = $yamlform_entity->getSourceEntity();
}
elseif ($yamlform_entity instanceof YamlFormInterface) {
$yamlform = $yamlform_entity;
}
else {
throw new \InvalidArgumentException('YAML form entity');
}
if ($source_entity
&& method_exists($source_entity, 'hasField')
&& $source_entity->hasField('yamlform')
&& $source_entity->yamlform->target_id == $yamlform->id()
) {
return TRUE;
}
else {
return FALSE;
}
}
} |
/*
* Copyright (c) 2022. HW Tech Services, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hwtsllc.fix.enums.fix44;
import com.hwtsllc.fix.interfaces.MyTestValues;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
/**
* 946
* CollInquiryResult
* int
* <p></p>
* Result returned in response to Collateral Inquiry
* <p></p>
* 4000+ Reserved and available for bi-laterally agreed upon user-defined values
* <p></p>
* Valid values:
* <p> 0 - Successful (default)
* <p> 1 - Invalid or unknown instrument
* <p> 2 - Invalid or unknown collateral type
* <p> 3 - Invalid Parties
* <p> 4 - Invalid Transport Type requested
* <p></p>
* <p> 5 - Invalid Destination requested
* <p> 6 - No collateral found for the trade specified
* <p> 7 - No collateral found for the order specified
* <p> 8 - Collateral inquiry type not supported
* <p> 9 - Unauthorized for collateral inquiry
* <p></p>
* <p> 99 - Other (further information in Text (58) field)
* <p></p>
* <p> or any value conforming to the data type Reserved100Plus
*/
class Enum946CollInquiryResultTest {
@Test
void EnumTest() {
Enum946CollInquiryResult enumType;
enumType = Enum946CollInquiryResult.SUCCESSFUL;
assertEquals( "0", enumType.toFIXIDString() );
assertEquals( "SUCCESSFUL", enumType.toFIXNameString() );
assertEquals( "0 - Successful (default)", enumType.toFIXDescriptionString() );
assertNotEquals( MyTestValues.JUNK_ID, enumType.toFIXIDString());
assertNotEquals( MyTestValues.JUNK_NAME, enumType.toFIXNameString());
assertNotEquals( MyTestValues.JUNK_DESCRIPTION, enumType.toFIXDescriptionString());
enumType = Enum946CollInquiryResult.INVALID_INSTRUMENT;
assertEquals( "1", enumType.toFIXIDString() );
assertEquals( "INVALID_INSTRUMENT", enumType.toFIXNameString() );
assertEquals( "1 - Invalid or unknown instrument", enumType.toFIXDescriptionString() );
assertNotEquals( MyTestValues.JUNK_ID, enumType.toFIXIDString());
assertNotEquals( MyTestValues.JUNK_NAME, enumType.toFIXNameString());
assertNotEquals( MyTestValues.JUNK_DESCRIPTION, enumType.toFIXDescriptionString());
enumType = Enum946CollInquiryResult.UNKNOWN_COLLATERAL_TYPE;
assertEquals( "2", enumType.toFIXIDString() );
assertEquals( "UNKNOWN_COLLATERAL_TYPE", enumType.toFIXNameString() );
assertEquals( "2 - Invalid or unknown collateral type", enumType.toFIXDescriptionString() );
assertNotEquals( MyTestValues.JUNK_ID, enumType.toFIXIDString());
assertNotEquals( MyTestValues.JUNK_NAME, enumType.toFIXNameString());
assertNotEquals( MyTestValues.JUNK_DESCRIPTION, enumType.toFIXDescriptionString());
enumType = Enum946CollInquiryResult.INVALID_PARTIES;
assertEquals( "3", enumType.toFIXIDString() );
assertEquals( "INVALID_PARTIES", enumType.toFIXNameString() );
assertEquals( "3 - Invalid Parties", enumType.toFIXDescriptionString() );
assertNotEquals( MyTestValues.JUNK_ID, enumType.toFIXIDString());
assertNotEquals( MyTestValues.JUNK_NAME, enumType.toFIXNameString());
assertNotEquals( MyTestValues.JUNK_DESCRIPTION, enumType.toFIXDescriptionString());
enumType = Enum946CollInquiryResult.INVALID_TRANSPORT_TYPE;
assertEquals( "4", enumType.toFIXIDString() );
assertEquals( "INVALID_TRANSPORT_TYPE", enumType.toFIXNameString() );
assertEquals( "4 - Invalid Transport Type requested", enumType.toFIXDescriptionString() );
assertNotEquals( MyTestValues.JUNK_ID, enumType.toFIXIDString());
assertNotEquals( MyTestValues.JUNK_NAME, enumType.toFIXNameString());
assertNotEquals( MyTestValues.JUNK_DESCRIPTION, enumType.toFIXDescriptionString());
enumType = Enum946CollInquiryResult.INVALID_DESTINATION;
assertEquals( "5", enumType.toFIXIDString() );
assertEquals( "INVALID_DESTINATION", enumType.toFIXNameString() );
assertEquals( "5 - Invalid Destination requested", enumType.toFIXDescriptionString() );
assertNotEquals( MyTestValues.JUNK_ID, enumType.toFIXIDString());
assertNotEquals( MyTestValues.JUNK_NAME, enumType.toFIXNameString());
assertNotEquals( MyTestValues.JUNK_DESCRIPTION, enumType.toFIXDescriptionString());
enumType = Enum946CollInquiryResult.NO_COLLATERAL_FOUND_FOR_TRADE;
assertEquals( "6", enumType.toFIXIDString() );
assertEquals( "NO_COLLATERAL_FOUND_FOR_TRADE", enumType.toFIXNameString() );
assertEquals( "6 - No collateral found for the trade specified", enumType.toFIXDescriptionString() );
assertNotEquals( MyTestValues.JUNK_ID, enumType.toFIXIDString());
assertNotEquals( MyTestValues.JUNK_NAME, enumType.toFIXNameString());
assertNotEquals( MyTestValues.JUNK_DESCRIPTION, enumType.toFIXDescriptionString());
enumType = Enum946CollInquiryResult.NO_COLLATERAL_FOUND_FOR_ORDER;
assertEquals( "7", enumType.toFIXIDString() );
assertEquals( "NO_COLLATERAL_FOUND_FOR_ORDER", enumType.toFIXNameString() );
assertEquals( "7 - No collateral found for the order specified", enumType.toFIXDescriptionString() );
assertNotEquals( MyTestValues.JUNK_ID, enumType.toFIXIDString());
assertNotEquals( MyTestValues.JUNK_NAME, enumType.toFIXNameString());
assertNotEquals( MyTestValues.JUNK_DESCRIPTION, enumType.toFIXDescriptionString());
enumType = Enum946CollInquiryResult.COLLATERAL_INQUIRY_NOT_SUPPORTED;
assertEquals( "8", enumType.toFIXIDString() );
assertEquals( "COLLATERAL_INQUIRY_NOT_SUPPORTED", enumType.toFIXNameString() );
assertEquals( "8 - Collateral inquiry type not supported", enumType.toFIXDescriptionString() );
assertNotEquals( MyTestValues.JUNK_ID, enumType.toFIXIDString());
assertNotEquals( MyTestValues.JUNK_NAME, enumType.toFIXNameString());
assertNotEquals( MyTestValues.JUNK_DESCRIPTION, enumType.toFIXDescriptionString());
enumType = Enum946CollInquiryResult.UNAUTHORIZED_COLLATERAL_INQUIRY;
assertEquals( "9", enumType.toFIXIDString() );
assertEquals( "UNAUTHORIZED_COLLATERAL_INQUIRY", enumType.toFIXNameString() );
assertEquals( "9 - Unauthorized for collateral inquiry", enumType.toFIXDescriptionString() );
assertNotEquals( MyTestValues.JUNK_ID, enumType.toFIXIDString());
assertNotEquals( MyTestValues.JUNK_NAME, enumType.toFIXNameString());
assertNotEquals( MyTestValues.JUNK_DESCRIPTION, enumType.toFIXDescriptionString());
enumType = Enum946CollInquiryResult.OTHER;
assertEquals( "99", enumType.toFIXIDString() );
assertEquals( "OTHER", enumType.toFIXNameString() );
assertEquals( "99 - Other (further information in Text (58) field)", enumType.toFIXDescriptionString() );
assertNotEquals( MyTestValues.JUNK_ID, enumType.toFIXIDString());
assertNotEquals( MyTestValues.JUNK_NAME, enumType.toFIXNameString());
assertNotEquals( MyTestValues.JUNK_DESCRIPTION, enumType.toFIXDescriptionString());
}
} |
from django.shortcuts import render
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from todo.models import Task
# Create your views here.
class TaskListView(ListView):
model = Task
template_name = "todo_task_list.html"
context_object_name = "tasks"
class TaskCreateView(CreateView):
model = Task
template_name = "todo_task_form.html"
fields = ['title', 'completed']
success_url = "/tasks/"
class TaskUpdateView(UpdateView):
model = Task
template_name = "todo_task_form.html"
fields = ['title', 'completed']
success_url = "/tasks/"
class TaskDeleteView(DeleteView):
model = Task
template_name = "todo_task_confirm_delete.html"
success_url = "/tasks/" |
/* eslint-disable no-console */
/**
* Teleport
* Copyright (C) 2023 Gravitational, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { useState, useEffect, useRef } from 'react';
import { Attempt } from 'shared/hooks/useAttemptNext';
import { NotificationItem } from 'shared/components/Notification';
import { debounce } from 'shared/utils/highbar';
import { TdpClient, ButtonState, ScrollAxis } from 'teleport/lib/tdp';
import {
ClientScreenSpec,
ClipboardData,
PngFrame,
} from 'teleport/lib/tdp/codec';
import { getHostName } from 'teleport/services/api';
import cfg from 'teleport/config';
import { Sha256Digest } from 'teleport/lib/util';
import { TopBarHeight } from './TopBar';
import {
ClipboardSharingState,
DirectorySharingState,
Setter,
clipboardSharingPossible,
defaultClipboardSharingState,
defaultDirectorySharingState,
isSharingClipboard,
} from './useDesktopSession';
import { KeyboardHandler } from './KeyboardHandler';
import type { BitmapFrame } from 'teleport/lib/tdp/client';
declare global {
interface Navigator {
userAgentData?: { platform: any };
}
}
export default function useTdpClientCanvas(props: Props) {
const {
username,
desktopName,
clusterId,
setTdpConnection,
setWsConnection,
clipboardSharingState,
setClipboardSharingState,
setDirectorySharingState,
setWarnings,
} = props;
const [tdpClient, setTdpClient] = useState<TdpClient | null>(null);
const initialTdpConnectionSucceeded = useRef(false);
const encoder = useRef(new TextEncoder());
const latestClipboardDigest = useRef('');
const keyboardHandler = useRef(new KeyboardHandler());
useEffect(() => {
keyboardHandler.current = new KeyboardHandler();
// On unmount, clear all the timeouts on the keyboardHandler.
return () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
keyboardHandler.current.dispose();
};
}, []);
useEffect(() => {
const addr = cfg.api.desktopWsAddr
.replace(':fqdn', getHostName())
.replace(':clusterId', clusterId)
.replace(':desktopName', desktopName)
.replace(':username', username);
setTdpClient(new TdpClient(addr));
}, [clusterId, username, desktopName]);
/**
* Synchronize the canvas resolution and display size with the
* given ClientScreenSpec.
*/
const syncCanvas = (canvas: HTMLCanvasElement, spec: ClientScreenSpec) => {
const { width, height } = spec;
canvas.width = width;
canvas.height = height;
console.debug(`set canvas.width x canvas.height to ${width} x ${height}`);
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
console.debug(
`set canvas.style.width x canvas.style.height to ${width} x ${height}`
);
};
// Default TdpClientEvent.TDP_PNG_FRAME handler (buffered)
const clientOnPngFrame = (
ctx: CanvasRenderingContext2D,
pngFrame: PngFrame
) => {
// The first image fragment we see signals a successful TDP connection.
if (!initialTdpConnectionSucceeded.current) {
syncCanvas(ctx.canvas, getDisplaySize());
setTdpConnection({ status: 'success' });
initialTdpConnectionSucceeded.current = true;
}
ctx.drawImage(pngFrame.data, pngFrame.left, pngFrame.top);
};
// Default TdpClientEvent.TDP_BMP_FRAME handler (buffered)
const clientOnBitmapFrame = (
ctx: CanvasRenderingContext2D,
bmpFrame: BitmapFrame
) => {
// The first image fragment we see signals a successful TDP connection.
if (!initialTdpConnectionSucceeded.current) {
setTdpConnection({ status: 'success' });
initialTdpConnectionSucceeded.current = true;
}
ctx.putImageData(bmpFrame.image_data, bmpFrame.left, bmpFrame.top);
};
// Default TdpClientEvent.TDP_CLIENT_SCREEN_SPEC handler.
const clientOnClientScreenSpec = (
cli: TdpClient,
canvas: HTMLCanvasElement,
spec: ClientScreenSpec
) => {
syncCanvas(canvas, spec);
};
// Default TdpClientEvent.TDP_CLIPBOARD_DATA handler.
const clientOnClipboardData = async (clipboardData: ClipboardData) => {
if (
clipboardData.data &&
(await sysClipboardGuard(clipboardSharingState, 'write'))
) {
navigator.clipboard.writeText(clipboardData.data);
let digest = await Sha256Digest(clipboardData.data, encoder.current);
latestClipboardDigest.current = digest;
}
};
// Default TdpClientEvent.TDP_ERROR and TdpClientEvent.CLIENT_ERROR handler
const clientOnTdpError = (error: Error) => {
setDirectorySharingState(defaultDirectorySharingState);
setClipboardSharingState(defaultClipboardSharingState);
setTdpConnection({
status: 'failed',
statusText: error.message || error.toString(),
});
};
// Default TdpClientEvent.TDP_WARNING and TdpClientEvent.CLIENT_WARNING handler
const clientOnTdpWarning = (warning: string) => {
setWarnings(prevState => {
return [
...prevState,
{
content: warning,
severity: 'warn',
id: crypto.randomUUID(),
},
];
});
};
const clientOnTdpInfo = (info: string) => {
setDirectorySharingState(defaultDirectorySharingState);
setClipboardSharingState(defaultClipboardSharingState);
setTdpConnection({
status: '', // gracefully disconnecting
statusText: info,
});
};
const clientOnWsClose = (statusText: string) => {
setWsConnection({ status: 'closed', statusText });
};
const clientOnWsOpen = () => {
setWsConnection({ status: 'open' });
};
const canvasOnKeyDown = (cli: TdpClient, e: KeyboardEvent) => {
keyboardHandler.current.handleKeyboardEvent({
cli,
e,
state: ButtonState.DOWN,
});
// The key codes in the if clause below are those that have been empirically determined not
// to count as transient activation events. According to the documentation, a keydown for
// the Esc key and any "shortcut key reserved by the user agent" don't count as activation
// events: https://developer.mozilla.org/en-US/docs/Web/Security/User_activation.
if (e.key !== 'Meta' && e.key !== 'Alt' && e.key !== 'Escape') {
// Opportunistically sync local clipboard to remote while
// transient user activation is in effect.
// https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/readText#security
sendLocalClipboardToRemote(cli);
}
};
const canvasOnKeyUp = (cli: TdpClient, e: KeyboardEvent) => {
keyboardHandler.current.handleKeyboardEvent({
cli,
e,
state: ButtonState.UP,
});
};
const canvasOnFocusOut = () => {
keyboardHandler.current.onFocusOut();
};
const canvasOnMouseMove = (
cli: TdpClient,
canvas: HTMLCanvasElement,
e: MouseEvent
) => {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
cli.sendMouseMove(x, y);
};
const canvasOnMouseDown = (cli: TdpClient, e: MouseEvent) => {
if (e.button === 0 || e.button === 1 || e.button === 2) {
cli.sendMouseButton(e.button, ButtonState.DOWN);
}
// Opportunistically sync local clipboard to remote while
// transient user activation is in effect.
// https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/readText#security
sendLocalClipboardToRemote(cli);
};
const canvasOnMouseUp = (cli: TdpClient, e: MouseEvent) => {
if (e.button === 0 || e.button === 1 || e.button === 2) {
cli.sendMouseButton(e.button, ButtonState.UP);
}
};
const canvasOnMouseWheelScroll = (cli: TdpClient, e: WheelEvent) => {
e.preventDefault();
// We only support pixel scroll events, not line or page events.
// https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaMode
if (e.deltaMode === WheelEvent.DOM_DELTA_PIXEL) {
if (e.deltaX) {
cli.sendMouseWheelScroll(ScrollAxis.HORIZONTAL, -e.deltaX);
}
if (e.deltaY) {
cli.sendMouseWheelScroll(ScrollAxis.VERTICAL, -e.deltaY);
}
}
};
// Block browser context menu so as not to obscure the context menu
// on the remote machine.
const canvasOnContextMenu = () => false;
const windowOnResize = debounce(
(cli: TdpClient) => {
const spec = getDisplaySize();
cli.resize(spec);
},
250,
{ trailing: true }
);
const sendLocalClipboardToRemote = async (cli: TdpClient) => {
if (await sysClipboardGuard(clipboardSharingState, 'read')) {
navigator.clipboard.readText().then(text => {
Sha256Digest(text, encoder.current).then(digest => {
if (text && digest !== latestClipboardDigest.current) {
cli.sendClipboardData({
data: text,
});
latestClipboardDigest.current = digest;
}
});
});
}
};
return {
tdpClient,
clientScreenSpecToRequest: getDisplaySize(),
clientOnPngFrame,
clientOnBitmapFrame,
clientOnClientScreenSpec,
clientOnTdpError,
clientOnClipboardData,
clientOnWsClose,
clientOnWsOpen,
clientOnTdpWarning,
clientOnTdpInfo,
canvasOnKeyDown,
canvasOnKeyUp,
canvasOnFocusOut,
canvasOnMouseMove,
canvasOnMouseDown,
canvasOnMouseUp,
canvasOnMouseWheelScroll,
canvasOnContextMenu,
windowOnResize,
};
}
// Calculates the size (in pixels) of the display.
// Since we want to maximize the display size for the user, this is simply
// the full width of the screen and the full height sans top bar.
function getDisplaySize() {
return {
width: window.innerWidth,
height: window.innerHeight - TopBarHeight,
};
}
type Props = {
username: string;
desktopName: string;
clusterId: string;
setTdpConnection: Setter<Attempt>;
setWsConnection: Setter<{ status: 'open' | 'closed'; statusText?: string }>;
clipboardSharingState: ClipboardSharingState;
setClipboardSharingState: Setter<ClipboardSharingState>;
setDirectorySharingState: Setter<DirectorySharingState>;
setWarnings: Setter<NotificationItem[]>;
};
/**
* To be called before any system clipboard read/write operation.
*/
async function sysClipboardGuard(
clipboardSharingState: ClipboardSharingState,
checkingFor: 'read' | 'write'
): Promise<boolean> {
// If we're not allowed to share the clipboard according to the acl
// or due to the browser we're using, never try to read or write.
if (!clipboardSharingPossible(clipboardSharingState)) {
return false;
}
// If the relevant state is 'prompt', try the operation so that the
// user is prompted to allow it.
const checkingForRead = checkingFor === 'read';
const checkingForWrite = checkingFor === 'write';
const relevantStateIsPrompt =
(checkingForRead && clipboardSharingState.readState === 'prompt') ||
(checkingForWrite && clipboardSharingState.writeState === 'prompt');
if (relevantStateIsPrompt) {
return true;
}
// Otherwise try only if both read and write permissions are granted
// and the document has focus (without focus we get an uncatchable error).
//
// Note that there's no situation where only one of read or write is granted,
// but the other is denied, and we want to try the operation. The feature is
// either fully enabled or fully disabled.
return isSharingClipboard(clipboardSharingState) && document.hasFocus();
} |
import 'dart:ui';
import 'package:flutter/material.dart';
class BigCard extends StatelessWidget {
final temp;
final weather;
final icon;
const BigCard(
{super.key,
required this.temp,
required this.weather,
required this.icon});
@override
Widget build(BuildContext context) {
return SizedBox(
width: double.infinity,
child: Card(
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
//ClipRReact is used to add radius for blur
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
//back drop filter is for blur effect
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
Text(
"$temp °C",
style: const TextStyle(fontSize: 32, letterSpacing: 1),
),
const SizedBox(
height: 15,
),
Icon(
icon,
size: 32,
),
const SizedBox(
height: 15,
),
Text(
"$weather",
style: const TextStyle(fontSize: 20),
)
],
),
),
),
),
),
);
}
} |
const Sequelize = require("sequelize");
const PostModel = require("../models/post.model");
const UserModel = require("../models/user.model");
const CommentModel = require("../models/comment.model");
const fs = require("fs");
const { where } = require("sequelize/dist");
// POST
exports.createPost = (req, res, next) => {
if (req.body.image === "null" && !req.body.text) {
return res
.status(400)
.json({ message: "Votre post ne peut pas être vide." });
} else {
const post = new PostModel({
UserId: req.token.userId,
text: req.body.text,
image: req.file
? `${req.protocol}://${req.get("host")}/images/${req.file.filename}`
: null,
});
post
.save()
.then(() =>
res.status(201).json({
message: "Post enregistré !",
})
)
.catch((error) =>
res.status(400).json({
error,
})
);
}
};
// PUT
exports.modifyPost = (req, res, next) => {
PostModel.findOne({
where: { id: req.params.id },
})
.then((post) => {
if (post.UserId === req.token.userId || req.token.isAdmin === true) {
if (req.file != undefined) {
if (post.image != undefined) {
const filename = post.image.split("/images/")[1];
fs.unlink(`images/${filename}`, function (err) {
if (err) console.log("error", err);
});
}
post.image = `${req.protocol}://${req.get("host")}/images/${
req.file.filename
}`;
}
if (req.body.text) {
post.text = req.body.text;
}
post
.save()
.then(() =>
res.status(201).json({
message: "Post modifié !",
})
)
.catch((error) =>
res.status(400).json({
error,
})
);
} else {
res.status(403).json({
message: "403: unauthorized request !",
});
}
})
.catch((err) =>
res.status(400).json({
err,
})
);
};
// DELETE
exports.deletePost = (req, res, next) => {
PostModel.findOne({
where: { id: req.params.id },
})
.then((post) => {
if (post.UserId === req.token.userId || req.token.isAdmin === true) {
if (post.image) {
const filename = post.image.split("/images/")[1];
fs.unlink(`images/${filename}`, function (err) {
if (err) console.log("error", err);
});
}
PostModel.destroy({
where: { id: req.params.id },
})
.then(() =>
res.status(200).json({
message: "Post supprimé !",
})
)
.catch((error) =>
res.status(400).json({
error,
})
);
} else {
res.status(403).json({
message: "403: unauthorized request !",
});
}
})
.catch((error) =>
res.status(500).json({
error,
})
);
};
// GET ALL
exports.getAllPosts = (req, res, next) => {
PostModel.findAll({
order: [["createdAt", "DESC"]],
include: [
{
model: UserModel,
attributes: ["firstName", "lastName"],
},
{
model: CommentModel,
include: [
{
model: UserModel,
attributes: ["firstName", "lastName"],
},
],
},
],
})
.then((posts) => {
res.status(200).json(posts);
})
.catch((error) => {
res.status(400).json({
error: error,
});
});
};
// GET BY ID
exports.getOnePost = (req, res, next) => {
PostModel.findOne({
where: { id: req.params.id },
})
.then((post) => {
res.status(200).json(post);
})
.catch((error) => {
res.status(404).json({
error: error,
});
});
}; |
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// #include <algorithm>
// } Driver Code Ends
class Solution
{
public:
// arr: input array
// n: size of array
// Function to sort the array into a wave-like array.
void convertToWave(int n, vector<int> &arr)
{
// Your code here
for (int i = 0; i < n; i += 2)
{
// Check if there is an element at arr[i+1] to swap with
if (i + 1 < n)
swap(arr[i], arr[i + 1]);
}
}
};
//{ Driver Code Starts.
int main()
{
int t, n;
cin >> t; // Input testcases
while (t--) // While testcases exist
{
cin >> n; // input size of array
vector<int> a(n); // declare vector of size n
for (int i = 0; i < n; i++)
cin >> a[i]; // input elements of array
sort(a.begin(), a.end());
Solution ob;
ob.convertToWave(n, a);
for (int i = 0; i < n; i++)
cout << a[i] << " "; // print array
cout << endl;
}
}
// } Driver Code Ends |
// Based on Radix Tooltip (https://www.radix-ui.com/docs/primitives/components/tooltip)
import { keyframes } from '@emotion/react'
import styled from '@emotion/styled'
import * as TooltipPrimitive from '@radix-ui/react-tooltip'
import { ReactNode } from 'react'
import { Text, theme } from 'ui'
type Props = {
message: string
children: ReactNode
}
export const Tooltip = ({ children, message }: Props) => {
return (
<TooltipPrimitive.Provider>
<TooltipPrimitive.Root delayDuration={0}>
<TooltipPrimitive.Trigger asChild={true}>{children}</TooltipPrimitive.Trigger>
<TooltipPrimitive.Portal>
<Content sideOffset={5} onClick={(event) => event.stopPropagation()}>
<Text size="xs" color="textNegative" align="center">
{message}
</Text>
<TooltipPrimitive.Arrow />
</Content>
</TooltipPrimitive.Portal>
</TooltipPrimitive.Root>
</TooltipPrimitive.Provider>
)
}
const slideUpAndFadeAnimation = keyframes({
'0%': { opacity: 0, transform: 'translateY(10px)' },
'100%': { opacity: 1, transform: 'translateY(0)' },
})
const slideDownAndFadeAnimation = keyframes({
'0%': { opacity: 0, transform: 'translateY(-10px)' },
'100%': { opacity: 1, transform: 'translateY(0)' },
})
const Content = styled(TooltipPrimitive.Content)({
paddingInline: theme.space.sm,
paddingBlock: theme.space.xs,
paddingBottom: `calc(${theme.space.xs} + 2px)`,
backgroundColor: theme.colors.gray1000,
borderRadius: theme.radius[1],
maxWidth: '20rem',
maxHeight: 'var(--radix-tooltip-content-available-height)',
animationDuration: '0.6s',
animationTimingFunction: 'cubic-bezier(0.16, 1, 0.3, 1)',
transformOrigin: 'var(--radix-tooltip-content-transform-origin)',
'&[data-side="top"]': {
animationName: slideUpAndFadeAnimation,
},
'&[data-side="bottom"]': {
animationName: slideDownAndFadeAnimation,
},
}) |
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Creates screen dataset with tfExample proto in TFRecord format.
For all the valid xml or json files in the input directory, it parses their
view hierarchy attributes, extracts the feature data into tf.train.Example proto
and saves the results with TFRecord format in the output
directory as multiple sharded files. A file containing the dimension data for
padding purpose is also created.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import operator
import os
import threading
import concurrent.futures
import numpy as np
import tensorflow.compat.v1 as tf
import json
import glob
import json
from PIL import Image
import common
import config
import proto_utils
import real_action_generator
import view_hierarchy
gfile = tf.gfile
flags = tf.flags
FLAGS = flags.FLAGS
_INPUT_DIR = '/tmp/input'
_OUTPUT_DIR = '/tmp/'
_FILTER_FILE = '/tmp/'
_NUM_THREADS_DEFAULT = 10
_PADDING_DIMENSIONS_FILE_NAME = 'padding_dimensions.txt'
_TOKEN_TYPE = 'subtoken'
_NUM_SHARDS_DEFAULT = 10 # config.SHARD_NUM
_MAX_WORD_NUM_UPPER_DEFAULT = config.MAX_WORD_NUM_UPPER_BOUND
_MAX_WORD_LENGTH_UPPER_DEFAULT = config.MAX_WORD_LENGTH_UPPER_BOUND
_DATASET_TYPE_DEFAULT = 'motif'
_STATS_DIMENSIONS = True
_MAX_WORD_NUM = 200
_MAX_WORD_LENGTH = 50
_FREQ_OBJ_TYPE = [
view_hierarchy.UIObjectType.UNKNOWN,
view_hierarchy.UIObjectType.BUTTON,
view_hierarchy.UIObjectType.IMAGEVIEW,
view_hierarchy.UIObjectType.TEXTVIEW,
]
_INFREQUENT_OBJ_TYPE_MAX_RATIO = 0.9
_FILTER_ACTIONS_BY_NAME = True
_FILTER_ACTION_BY_TYPE = True
flags.DEFINE_enum(
'split', 'all', ['uu', 'us', 'su_curr', 'su_all', 'all'],
'Full path to the directory for saving filter file or RICO.')
flags.DEFINE_string(
'input_dir', _INPUT_DIR,
'Full path to the directory containing the data files for a set of tasks.')
flags.DEFINE_string(
'output_dir', _OUTPUT_DIR,
'Full path to the directory for saving the tf record file.')
flags.DEFINE_boolean(
'use_high_level_goal', True,
'Whether the instruction is defined as the high level goal or step by step instruction.')
flags.DEFINE_integer(
'num_threads', _NUM_THREADS_DEFAULT,
'The number of threads to process the data files concurrently.')
flags.DEFINE_integer(
'num_shards', _NUM_SHARDS_DEFAULT,
'The number of sharded files to save the created dataset.')
flags.DEFINE_integer('max_word_num_upper', _MAX_WORD_NUM_UPPER_DEFAULT,
'The max number of words for building model features.')
flags.DEFINE_integer('max_word_length_upper', _MAX_WORD_LENGTH_UPPER_DEFAULT,
'The max length of words for building model features.')
flags.DEFINE_enum('dataset', _DATASET_TYPE_DEFAULT,
['android_settings', 'rico', 'motif'],
'The type of supported dataset.')
flags.DEFINE_enum('file_to_generate', 'tf_example',
['tf_example', 'corpus'],
'Whether generate feature tfexample or corpus txt.')
longest_stats = collections.Counter()
distributions = collections.defaultdict(collections.Counter)
def get_kept_view_hierarchies(traces):
vh_to_load = []
screen_dims = []
for tr in traces:
json_path = os.path.join('seq2act_9_5', tr + '.json') # processed_motif_deduped
if os.path.exists(json_path):
with open(json_path) as f:
trace_info = json.load(f)
views_kept = trace_info['images']
view_paths = [os.path.join(FLAGS.input_dir, trace_info['app'], tr, 'view_hierarchies', v + '.jpg') for v in views_kept]
vh_to_load += view_paths
for i in range(len(view_paths)):
screen_dims.append([trace_info['vh_w'], trace_info['vh_h']])
else:
continue
return vh_to_load, screen_dims
def _get_data_dimensions(input_dir, splits):
"""Processes the dimension data.
The dimension data includes maximum word numbers and maximum word lengths
from all the ui objects across all the .xml/.json files in input_dir.
It will be used for padding purpose.
The results are written in <output_dir>/padding_dimensions.txt.
Args:
input_dir: The directory that contains the input xml/json files.
Returns:
A tuple (max_word_num_all_files, max_word_length_all_files)
max_word_num_all_files: The max number of words from all the ui objects
across all the .xml/.json files.
max_word_length_all_files: The max length of words from all the ui objects
across all the .xml/.json files.
"""
max_word_num_all_files = 0
max_word_length_all_files = 0
all_files, all_dims = get_kept_view_hierarchies(splits)
print('%d view hierarchies to load' % len(all_files))
# We can use ThreadPool since these are IO-bound operations.
with concurrent.futures.ThreadPoolExecutor(FLAGS.num_threads) as executor:
futures = []
for i in range(len(all_files)):
file_path = all_files[i]
w, h = all_dims[i]
futures.append(executor.submit(common.get_word_statistics, file_path, True, w, h))
for future in concurrent.futures.as_completed(futures):
_, max_word_num_one_file, max_word_length_one_file = future.result()
max_word_num_all_files = max(max_word_num_all_files,
max_word_num_one_file)
max_word_length_all_files = max(max_word_length_all_files,
max_word_length_one_file)
tf.logging.info('max_word_num_all_files=%d, max_word_length_all_files=%d',
max_word_num_all_files, max_word_length_all_files)
return max_word_num_all_files, max_word_length_all_files
def _process_dimensions(input_dir, output_dir, splits):
"""Processes the dimension data.
The dimension data includes maximum word numbers and maximum word lengths
from all the ui objects across all the .xml/.json files in input_dir.
It will be used for padding purpose.
The results are written in <output_dir>/padding_dimensions.txt.
Args:
input_dir: The directory that contains the input xml/json files.
output_dir: The directory that saves output dimension data.
Returns:
A tuple (max_word_num, max_word_length)
max_word_num: The max number of words for building model features.
max_word_length: The max length of words for building model features.
"""
tf.logging.info('Processing data dimensions...')
max_word_num, max_word_length = _get_data_dimensions(input_dir, splits) # [200, 50]
print((max_word_num, max_word_length))
tf.logging.info('Done...max word num = %d, max word length = %d' % (max_word_num, max_word_length))
# Apply pre-configured upper bound to clip possibly rare outlier values.
max_word_num = min(max_word_num, FLAGS.max_word_num_upper)
max_word_length = min(max_word_length, FLAGS.max_word_length_upper)
tf.logging.info('After clipping...max word num = %d, max word length = %d' % (max_word_num, max_word_length))
with gfile.GFile(
os.path.join(output_dir, _PADDING_DIMENSIONS_FILE_NAME), 'w+') as f:
f.write('max_word_num: %d\nmax_word_length: %d\n' %
(max_word_num, max_word_length))
return max_word_num, max_word_length
def add_back_action_info(action):
input_str_pos_padding = [
config.LABEL_DEFAULT_VALUE_INT, config.LABEL_DEFAULT_VALUE_INT
]
input_prep_word = action.instruction_str[:-len(action.obj_desc_str)].strip(' ').split(' ')[-1]
action.verb_str_pos = [0, _count_chars(action.verb_str)]
swipe_prep_word = ('until ' if 'until' in action.instruction_str else 'to ')
if action.action_type in [common.ActionTypes.CLICK]:
action.obj_str_pos = [
_count_chars(action.verb_str) + 1,
_count_chars(action.instruction_str)
]
action.input_str_pos = input_str_pos_padding
elif action.action_type in [common.ActionTypes.INPUT]:
action.input_str_pos = [
_count_chars(action.verb_str) + 1,
_count_chars('%s %s' % (action.verb_str, action.input_content_str))
]
action.obj_str_pos = [
_count_chars(
'%s %s %s' %
(action.verb_str, action.input_content_str, input_prep_word)) + 1,
_count_chars(action.instruction_str)
]
# All the rests are swipe actions
else:
action.input_str_pos = input_str_pos_padding
start = _count_chars(action.verb_str) + 1
if 'to the left' in action.instruction_str:
start += _count_chars('to the left ')
elif 'to the right' in action.instruction_str:
start += _count_chars('to the right ')
elif 'down' in action.instruction_str:
start += _count_chars('down ')
else:
start += _count_chars('up ')
start += _count_chars(swipe_prep_word)
action.obj_str_pos = [start, _count_chars(action.instruction_str)]
def _get_full_feature_dict(file_path, max_word_num,
max_word_length, use_goal):
"""Gets full padded feature dictionary from xml/json file_path.
Args:
dataset_type: The supported dataset type.
file_path: The full path of xml/json file.
max_word_num: The max number of words in each ui object.
max_word_length: The max length of words in each ui object.
Returns:
padded_feature_dict: A dictionary that contains ui_object features, view
hierarchy leaf node adjacency matrix features and synthetic actionq
features. Each value of the feature dicionary is padded. The padding shape
is as follow:
feature_dict = {
'instruction_str': synthetic action strings, np array of string,
shape = (phrase_count,)
'instruction_word_id_seq': encoded action words, np int array, shape =
(phrase_count, max_word_num)
'instruction_rule_id': representing action rule(single_object_rule/
grid_context_rule/neighbor_context_rule), np int array,
shape = (phrase_count,)
'ui_obj_str_seq': string of ui object name/content_description/resourceid,
np string array, shape = (ui_object_num)
'ui_obj_word_id_seq': encoded word sequence, np int array, shape =
(ui_object_num, max_word_num)
'ui_obj_type_id_seq': object type ids, np int array, shape =
(ui_object_num,)
'ui_obj_clickable_seq': clickable sequence, np int array, shape =
(ui_object_num,)
'ui_obj_cord_x_seq': x coordinate sequence, np float array, shape =
(ui_object_num*2,)
'ui_obj_cord_y_seq': y coordinate sequence, np float array, shape =
(ui_object_num*2,)
'ui_obj_v_distance': vertical relation matrix, np float array, shape =
(ui_object_num, ui_object_num)
'ui_obj_h_distance': horizontal relation matrix, np float array, shape =
(ui_object_num, ui_object_num)
'ui_obj_dom_distance': dom relation matrix, np int array, shape =
(ui_object_num, ui_object_num)
'ui_obj_dom_location_seq': index of pre-order/in-order/post-order in view
hierarchy tree. np int array, shape = (ui_object_num*3,)
'verb_id_seq': representing action verb id(click/input/swipe), np int
array, shape = (phrase_count,)
'verb_str_position_seq': index of verb string, np int array,
shape = (phrase_count*2,)
'ui_target_id_seq': index of ui object target, np int array,
shape = (phrase_count,)
'input_str_position_seq': input words' start end position in instruction,
np int array, shape = (phrase_count*2,)
'obj_desc_position_seq': target object words' start end position,
np int array, shape = (phrase_count*2,)
}
"""
with open(file_path) as f:
trace_info = json.load(f)
full_feature = {}
ui_object_nums = []
vh_leaf_nodes = []
for view in trace_info['images'][:-1]:
view_path = os.path.join(FLAGS.input_dir, trace_info['app'], trace_info['trace_id'], 'view_hierarchies', view + '.jpg')
view_hierarchy_leaf_nodes = common.get_view_hierarchy_list(view_path, trace_info['vh_w'], trace_info['vh_h'])
ui_object_num = len(view_hierarchy_leaf_nodes)
ui_object_nums.append(ui_object_num)
ui_obj_list = [ele.uiobject for ele in view_hierarchy_leaf_nodes]
vh_leaf_nodes.append(view_hierarchy_leaf_nodes)
# initialize first set of view hierarchy features
# will concat rest of time steps after
# 140 was the max logged
max_ui_object_num = 140 # max(ui_object_nums)
# print('MAX UI NUM = %d' % max_ui_object_num)
padded_obj_feature_dict = proto_utils.get_ui_objects_feature_dict(
vh_leaf_nodes[0],
padding_shape=(max_ui_object_num, max_word_num, max_word_length),
lower_case=True)
for key in padded_obj_feature_dict:
padded_obj_feature_dict[key] = np.expand_dims(padded_obj_feature_dict[key], axis=0)
full_feature.update(padded_obj_feature_dict)
for vh in vh_leaf_nodes[1:]:
padded_obj_feature_dict = proto_utils.get_ui_objects_feature_dict(
vh,
padding_shape=(max_ui_object_num, max_word_num, max_word_length),
lower_case=True)
for key in padded_obj_feature_dict:
padded_obj_feature_dict[key] = np.expand_dims(padded_obj_feature_dict[key], axis=0)
# concat along step_num dim
full_feature[key] = np.concatenate((full_feature[key], padded_obj_feature_dict[key]), axis=0)
# only need to load and pad actions once
action_list = []
for i in range(len(trace_info['instr'])):
instr = trace_info['instr'][i]
verb_str = trace_info['verb_str'][i]
obj_desc_str = trace_info['obj_desc_str'][i]
input_content_str = trace_info['input_str'][i]
if trace_info['actions'][i] == 'click':
action_type = common.ActionTypes.CLICK
elif trace_info['actions'][i] == 'type':
action_type = common.ActionTypes.INPUT
else:
action_type = common.ActionTypes.SWIPE
target_object_idx = trace_info['ui_target_idxs'][i]
action = common.Action(instruction_str=instr.lower(),
verb_str=verb_str.lower(),
obj_desc_str=obj_desc_str.lower(),
input_content_str=input_content_str.lower(),
action_type=action_type,
action_rule=common.ActionRules.REAL,
target_obj_idx=target_object_idx)
add_back_action_info(action)
action_list.append(action)
padded_syn_feature_dict, missing_ref = real_action_generator.get_real_feature_dict(action_list, max_word_num, max_word_length, use_goal, trace_info['goal'])
full_feature.update(padded_syn_feature_dict)
full_feature['ui_obj_cord_x_seq'] = full_feature['ui_obj_cord_x_seq'] / float(trace_info['vh_w'])
full_feature['ui_obj_cord_y_seq'] = full_feature['ui_obj_cord_y_seq'] / float(trace_info['vh_h'])
return full_feature, missing_ref
def _assert_feature_value(feature):
"""Asserts feature value doesn't have -1, except for anchor features."""
# ui target id seq can have -1 bc it includes swipe actions
anchor_features = [
'instruction_word_id_seq', 'ui_obj_type_id_seq', 'verb_id_seq', 'ui_target_id_seq'
]
for key in feature:
if key in anchor_features:
continue
if -1 in feature[key]:
tf.logging.info('[FATAL]: Feature %s contains -1', key)
return False
return True
def _assert_feature_shape(feature, expected_shape):
"""Asserts feature shape is legal, same as expected_shape."""
assert set(feature.keys()) == set(expected_shape.keys(
)), '[FATAL] feature keys %s different from expected %s' % (
sorted(feature.keys()), sorted(expected_shape.keys()))
for key in feature:
if feature[key].shape != expected_shape[key]:
print(key)
print(feature[key].shape)
print(expected_shape[key])
tf.logging.info('[FATAL] feature %s shape is different from expected',
key)
return False
return True
def _count_chars(char_string):
return len(char_string)
def _process_features(tf_record_writer, writer_lock, dataset_type, file_path, max_word_num, max_word_length, use_goal):
"""Processes features from one xml/json file.
Args:
dataset_type: The supported dataset type.
file_path: The full path of xml/json file.
max_word_num: The max number of words in each ui object.
max_word_length: The max length of words in each ui object. synthetic input
actions.
"""
feature_dict, missing_ref = _get_full_feature_dict(
file_path,
max_word_num,
max_word_length,
use_goal
)
ui_object_num = feature_dict['ui_obj_str_seq'].shape[1]
step_num = feature_dict['ui_target_id_seq'].shape[0]
expected_feature_shape = {
'instruction_str': (step_num,),
'instruction_word_id_seq': (step_num, max_word_num),
'instruction_rule_id': (step_num,),
'ui_obj_str_seq': (step_num, ui_object_num),
'ui_obj_word_id_seq': (step_num, ui_object_num, max_word_num),
'ui_obj_type_id_seq': (step_num, ui_object_num),
'ui_obj_clickable_seq': (step_num, ui_object_num),
'ui_obj_cord_x_seq': (step_num, ui_object_num * 2),
'ui_obj_cord_y_seq': (step_num, ui_object_num * 2),
'ui_obj_v_distance': (step_num, ui_object_num, ui_object_num),
'ui_obj_h_distance': (step_num, ui_object_num, ui_object_num),
'ui_obj_dom_distance': (step_num, ui_object_num, ui_object_num),
'ui_obj_dom_location_seq': (step_num, ui_object_num * 3),
'verb_id_seq': (step_num,),
'ui_target_id_seq': (step_num,),
'verb_str_position_seq': (step_num * 2,),
'input_str_position_seq': (step_num * 2,),
'obj_desc_position_seq': (step_num * 2,),
}
# When feature_dict['verb_id_seq'] is not always padded value,
# generate tfexample
bool1 = _assert_feature_shape(feature_dict, expected_feature_shape)
bool2 = _assert_feature_value(feature_dict)
bool3 = (not np.array(feature_dict['verb_id_seq'] == config.LABEL_DEFAULT_INVALID_INT).all())
if bool1 and bool2 and bool3:
tf_proto = proto_utils.features_to_tf_example(feature_dict)
with writer_lock:
tf_record_writer.write(tf_proto.SerializeToString())
def _write_dataset(dataset_type, input_dir, output_dir, traces, max_word_num,
max_word_length):
"""Processes features from xml/json files and writes results to dataset files.
Args:
dataset_type: The supported dataset type.
input_dir: The directory that contains the input xml/json files.
output_dir: The directory that saves output dimension data.
max_word_num: The max number of words in each ui object.
max_word_length: The max length of words in each ui object. synthetic input
actions.
"""
tf.logging.info('Processing data features...')
tf_record_writers = []
writer_locks = []
for shard in range(FLAGS.num_shards):
tf_record_writers.append(
tf.python_io.TFRecordWriter(
os.path.join(
output_dir, '%s_%d.tfrecord' %
(dataset_type, shard))))
writer_locks.append(threading.Lock())
num_processed_files = 0
# We can use ThreadPool since these are IO-bound operations.
with concurrent.futures.ThreadPoolExecutor(FLAGS.num_threads) as executor:
futures = []
for tr in sorted(traces):
file_path = os.path.join('seq2act_9_5', tr + '.json') # processed_motif_deduped
shard = num_processed_files % FLAGS.num_shards
if os.path.exists(file_path):
futures.append(
executor.submit(_process_features, tf_record_writers[shard],
writer_locks[shard], dataset_type, file_path,
max_word_num, max_word_length, FLAGS.use_high_level_goal))
num_processed_files += 1
else:
print('Missing %s' % tr)
continue
concurrent.futures.wait(futures)
for shard in range(FLAGS.num_shards):
tf_record_writers[shard].close()
print('NUMBER OF PROCESSED FILES = %d' % num_processed_files)
def create_dataset(dataset_type, input_dir, output_dir, splits):
"""Converts xml/json files in input_dir to tfExample files in output_dir.
tfExample file contains multiple tf.Example proto and the feature dictionary
of tf.Example proto defined by _get_full_feature_dict()
Args:
dataset_type: The supported dataset type.
input_dir: The directory that contains input xml/json file.
output_dir: The directory that saves output files.
"""
if _STATS_DIMENSIONS:
max_word_num, max_word_length = _process_dimensions(input_dir, output_dir, splits)
else:
max_word_num, max_word_length = _MAX_WORD_NUM, _MAX_WORD_LENGTH
_write_dataset(dataset_type, input_dir, output_dir, splits, max_word_num, max_word_length)
def main(_):
if not os.path.isdir(FLAGS.output_dir):
os.mkdir(FLAGS.output_dir)
with open('eccv_motif_app_seen_task_unseen_all.json') as f:
traces_to_process_su_all = json.load(f)['test']
with open('eccv_motif_app_seen_task_unseen_curr.json') as f:
traces_to_process_su_curr = json.load(f)['test']
with open('eccv_motif_app_unseen_task_unseen.json') as f:
traces_to_process_uu = json.load(f)['test']
with open('eccv_motif_app_unseen_task_seen.json') as f:
traces_to_process_us = json.load(f)['test']
if FLAGS.split == 'all':
traces_to_process = traces_to_process_su_all + traces_to_process_su_curr + traces_to_process_uu + traces_to_process_us
elif FLAGS.split == 'uu':
traces_to_process = traces_to_process_uu
elif FLAGS.split == 'us':
traces_to_process = traces_to_process_us
elif FLAGS.split == 'su_all':
traces_to_process = traces_to_process_su_all
else:
traces_to_process = traces_to_process_su_curr
traces_to_process = list(set(traces_to_process))
print('Test traces to process %d' % len(traces_to_process))
create_dataset(FLAGS.dataset, FLAGS.input_dir, FLAGS.output_dir, traces_to_process)
sums = collections.defaultdict(int)
tf.logging.info('\n\n%s\n\n', longest_stats)
with open(os.path.join(FLAGS.output_dir, 'stats.txt'), 'w+') as writer:
for key, distribution in distributions.items():
writer.write(
'%s: %s\n' %
(key, sorted(distribution.items(), key=operator.itemgetter(0))))
for key, distribution in sums.items():
writer.write('%s: %s\n' %
(key, sorted(sums.items(), key=operator.itemgetter(0))))
if __name__ == '__main__':
FLAGS.set_default('logtostderr', True)
tf.app.run(main) |
package com.example.waypoint.database.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import com.example.waypoint.database.DBOpenHelper;
import com.example.waypoint.database.model.HospedagemModel;
import java.util.ArrayList;
public class HospedagemDAO extends AbstrataDAO {
private final String[] colunas = {
HospedagemModel.COLUNA_ID,
HospedagemModel.COLUNA_CUSTO_MEDIO,
HospedagemModel.COLUNA_TOTAL_NOITES,
HospedagemModel.COLUNA_TOTAL_QUARTOS,
HospedagemModel.COLUNA_TOTAL,
HospedagemModel.COLUNA_ID_USUARIO,
HospedagemModel.COLUNA_ID_VIAGEM,
};
public HospedagemDAO(Context context) { db_helper = new DBOpenHelper(context);
}
public long Insert(HospedagemModel hospedagemModel) {
long rowId = -1;
try {
Open();
ContentValues values = new ContentValues();
values.put(HospedagemModel.COLUNA_CUSTO_MEDIO, hospedagemModel.getCustoMedio());
values.put(HospedagemModel.COLUNA_TOTAL_NOITES, hospedagemModel.getTotalNoites());
values.put(HospedagemModel.COLUNA_TOTAL_QUARTOS, hospedagemModel.getTotalQuartos());
values.put(HospedagemModel.COLUNA_TOTAL, hospedagemModel.getTotal());
values.put(HospedagemModel.COLUNA_ID_USUARIO, hospedagemModel.getIdUsuario());
values.put(HospedagemModel.COLUNA_ID_VIAGEM, hospedagemModel.getIdViagem());
rowId = db.insert(HospedagemModel.TABELA_NOME, null, values);
}
finally {
Close();
}
return rowId;
}
public long Update(HospedagemModel hospedagemModel) {
long rowId = -1;
try {
Open();
ContentValues values = new ContentValues();
values.put(HospedagemModel.COLUNA_CUSTO_MEDIO, hospedagemModel.getCustoMedio());
values.put(HospedagemModel.COLUNA_TOTAL_NOITES, hospedagemModel.getTotalNoites());
values.put(HospedagemModel.COLUNA_TOTAL_QUARTOS, hospedagemModel.getTotalQuartos());
values.put(HospedagemModel.COLUNA_TOTAL, hospedagemModel.getTotal());
rowId = db.update(
HospedagemModel.TABELA_NOME,
values,
HospedagemModel.COLUNA_ID + " = ?",
new String[]{String.valueOf(hospedagemModel.getId())}
);
}
finally {
Close();
}
return rowId;
}
public long Delete(HospedagemModel hospedagemModel) {
long rowId = -1;
try {
Open();
rowId = db.delete(
HospedagemModel.TABELA_NOME,
HospedagemModel.COLUNA_ID + " = ?",
new String[]{String.valueOf(hospedagemModel.getId())}
);
}
finally {
Close();
}
return rowId;
}
public boolean DeleteById(long idViagem) {
try {
Open();
int rowsAffected = db.delete(
HospedagemModel.TABELA_NOME,
HospedagemModel.COLUNA_ID_VIAGEM + " = ?",
new String[]{String.valueOf(idViagem)}
);
return rowsAffected > 0;
} finally {
Close();
}
}
public ArrayList<HospedagemModel> selectAll(long idUsuario) {
Open();
ArrayList<HospedagemModel> listaHospedagem = new ArrayList<>();
Cursor c = db.query(
HospedagemModel.TABELA_NOME,
colunas,
HospedagemModel.COLUNA_ID_USUARIO + " = ?",
new String[]{String.valueOf(idUsuario)},
null,
null,
null
);
c.moveToFirst();
while (!c.isAfterLast()) {
HospedagemModel hospedagemModel = new HospedagemModel();
hospedagemModel.setId(c.getInt(0));
hospedagemModel.setCustoMedio(c.getFloat(1));
hospedagemModel.setTotalNoites(c.getFloat(2));
hospedagemModel.setTotalQuartos(c.getFloat(3));
hospedagemModel.setTotal(c.getFloat(4));
hospedagemModel.setIdUsuario(c.getInt(5));
hospedagemModel.setIdViagem(c.getInt(6));
listaHospedagem.add(hospedagemModel);
c.moveToNext();
}
Close();
return listaHospedagem;
}
public ArrayList<HospedagemModel> selectByViagemId(long idViagem) {
Open();
ArrayList<HospedagemModel> listaHospedagem = new ArrayList<>();
Cursor c = db.query(
HospedagemModel.TABELA_NOME,
colunas,
HospedagemModel.COLUNA_ID_VIAGEM + " = ?",
new String[]{String.valueOf(idViagem)},
null,
null,
null
);
if (c.moveToFirst()) {
while (!c.isAfterLast()) {
HospedagemModel hospedagemModel = new HospedagemModel();
hospedagemModel.setId(c.getInt(0));
hospedagemModel.setCustoMedio(c.getFloat(1));
hospedagemModel.setTotalNoites(c.getFloat(2));
hospedagemModel.setTotalQuartos(c.getFloat(3));
hospedagemModel.setTotal(c.getFloat(4));
hospedagemModel.setIdUsuario(c.getInt(5));
hospedagemModel.setIdViagem(c.getInt(6));
listaHospedagem.add(hospedagemModel);
c.moveToNext();
}
}
c.close();
Close();
return listaHospedagem;
}
} |
import styled from 'styled-components';
export interface InputProps {
title: string;
type?: string;
name?: string;
value: string | number | readonly string[];
onChange: React.ChangeEventHandler<HTMLInputElement>;
onFocus?: React.FocusEventHandler<HTMLInputElement>;
onBlur?: React.FocusEventHandler<HTMLInputElement>;
errorMessage?: string;
}
export const Input = ({
title,
type = 'text',
name,
value,
onChange,
onFocus,
onBlur,
errorMessage,
}: InputProps) => {
return (
<Container>
<Body>{title}</Body>
<StyledInput
type={type}
name={name}
value={value}
onChange={onChange}
onFocus={onFocus}
onBlur={onBlur}
$isError={!!errorMessage}
/>
{!!errorMessage && <HelperText>{errorMessage}</HelperText>}
</Container>
);
};
const Container = styled.div`
display: flex;
flex-direction: column;
gap: 6px;
width: 100%;
`;
const Body = styled.h3`
${({ theme }) => theme.typography.body1};
color: ${({ theme }) => theme.color.gray1};
`;
const StyledInput = styled.input<{ $isError: boolean }>`
padding: 14px 16px;
border-radius: 12px;
border: 1px solid
${({ $isError, theme }) => ($isError ? theme.color.red : theme.color.gray3)};
color: ${({ theme }) => theme.color.gray1};
${({ theme }) => theme.typography.body1};
&:hover {
border: 1px solid
${({ $isError, theme }) =>
$isError ? theme.color.red : theme.color.gray2};
}
&:-webkit-autofill,
&:-webkit-autofill:hover,
&:-webkit-autofill:focus,
&:-webkit-autofill:active {
-webkit-text-fill-color: ${({ theme }) => theme.color.gray1};
}
&:active {
border: 1px solid
${({ $isError, theme }) =>
$isError ? theme.color.red : theme.color.gray1};
}
&:focus {
border: 1px solid
${({ $isError, theme }) =>
$isError ? theme.color.red : theme.color.gray1};
}
`;
const HelperText = styled.h3`
color: ${({ theme }) => theme.color.red};
${({ theme }) => theme.typography.body1};
`; |
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>add_user</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.7.0.js" integrity="sha256-JlqSTELeR4TLqP0OG9dxM7yDPqX1ox/HfgiSLBj8+kM=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</head>
<body>
<h1>사용자 추가</h1>
<label>이름</label><input type="text" name="name" id="nameInput"><br>
<label>생년월일</label><input type="text" name="birthday" id="birthdayInput"><br>
<label>이메일</label><input type="text" name="email" id="emailInput"><button type="button" id="duplicateBtn">중복확인</button><br>
<label>자기소개</label><br><textarea rows="5" cols="50" name="introduce" id="introuceInput"></textarea><br>
<button type="button" id="addBtn">추가</button>
<script>
$(document).ready(function(){
$("#duplicateBtn").on("click",function(){
let email = $("#emailInput").val();
if(email == ""){
alert("이메일을 입력하세요");
return;
}
$.ajax({
type:"get"
,url:"/ajax/user/email_confirm"
,data:{"email":email}
,success:function(data){
if(data.isDuplicate){//중복됨 : data={"isDuplicate":true}
alert("중복된이메일입니다");
return;
}
else{//중복안됨 : data={"isDuplicate":false}
alert("사용가능한 이메일입니다.");
}
}
,error:function(){
alert("중복확인 에러");
}
});
});
$("#addBtn").on("click",function(){
alert();
//유효성검사
let name = ${"#nameInput"}.val();
let birthday= ${"#birthdayInput"}.val();
let email = ${"#emailInput"}.val();
let introduce = ${"#introduceInput"}.val();
if(name == ""){
alert("이름을 입력하세요.");
return;
}
if(birthday == ""){
alert("생년월일을 입력하세요.");
return;
}
if(email == ""){
alert("이메일을 입력하세요.");
return;
}
if(introduce == ""){
alert("소개를 입력하세요.");
return;
}
$.ajax({
type:"get"
,url:"/ajax/user/add"
,data:{"name":name
,"birthday":birthday
,"email":email
,"introduce":introduce}
,success:function(data){
if(data.result == "success"){
//리스트페이지로이동
location.href ="/ajax/user/list";
}
else{
alert("추가 실패!")
}
}
,error:function(){
alert("추가에러!")
}
});
});
});
</script>
</body>
</html> |
<template>
<div>
<div v-if="user">
<section class="recipes-section lg:mt-5 px-5 lg:px-0">
<ProfileHeader :user="user" />
<div class="max-w-6xl xxl:max-w-screen-xl mx-auto">
<div class="channel-recipies-wrapper mb-6 md:mb-12">
<div
class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 xxl:grid-cols-5 gap-6 flex-wrapper"
>
<div v-if="user.recipes.length < 1">
<h2 class="text-base tracking-widest text-gray-800">
Nothing here yet, working on it.
</h2>
</div>
<div
v-else
class="relative recipe-item border dark:border-gray-700 rounded-lg overflow-hidden hover:shadow-xl transition duration-300 ease-in-out"
v-for="(recipe, i) in user.recipes"
:key="i"
>
<SingleRecipe :recipe="recipe" />
</div>
<!-- recipe item end -->
</div>
<!-- grid end -->
<hr
class="mt-6 dark:border-gray-700 md:mt-12"
v-show="isValidUser"
/>
</div>
<!-- channels recipies wrappper end -->
<div class="saved-recipies-wrapper" v-show="isValidUser">
<div class="section-header mb-5">
<h2
class="capitalize text-2xl text-gray-900 dark:text-gray-300 leading-none"
>
Saved recipes
</h2>
</div>
<div
class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 xxl:grid-cols-5 gap-6 flex-wrapper"
>
<div v-if="user.recipes.length < 1">
<h2 class="text-base tracking-widest text-gray-800">
No saved recipes.
</h2>
</div>
<div
v-else
class="pb-10 relative recipe-item border dark:border-gray-700 rounded-lg overflow-hidden hover:shadow-xl transition duration-300 ease-in-out"
v-for="(recipe, i) in user.recipes"
:key="i"
>
<SingleRecipe :recipe="recipe" />
</div>
<!-- recipe item end -->
</div>
<!-- grid end -->
</div>
<!-- channels recipies wrappper end -->
</div>
<!-- container end -->
</section>
</div>
<div v-else>
<div
class="h-screen px-10 md:h-25rem w-full flex items-center justify-center"
>
<div class="text-center">
<span
class="text-xl leading-none md:text-6xl font-light md:font-hairline text-gray-800 uppercase tracking-widest block"
>page Not Found!</span
>
<span
class="text-xs md:mt-0 mt-1 md:text-xl font-light block text-gray-700"
>The page may deleted or private</span
>
</div>
</div>
</div>
</div>
</template>
<script>
import gql from "graphql-tag";
import User from "~/gql/queries/Userbyname";
import SingleRecipe from "~/components/profile/SingleRecipe";
import ProfileHeader from "~/components/profile/ProfileHeader";
export default {
head() {
return {
title: this.user.name + " | Chatfata.com"
};
},
scrollToTop: true,
components: {
SingleRecipe,
ProfileHeader
},
data() {
return {};
},
computed: {
smallAvatar() {
if (this.currentUser) {
return this.user.avatar.replace(/(\.[\w\d_-]+)$/i, "-small$1");
}
},
storageUrl() {
return this.$store.state.storageUrl;
},
isAuthenticated() {
return this.$store.getters["user/isAuthenticated"];
},
isVerified() {
return this.$store.getters["user/isVerified"];
},
isChannel() {
return this.$store.getters["user/isChannel"];
},
currentUser() {
return this.$store.state.user.loggedInUser;
},
isValidUser() {
if (this.currentUser) {
return this.user.id == this.currentUser.id ? true : false;
}
},
isThisProfileChannel() {
if (this.user.roles) {
let roles = this.user.roles.map(e => {
return e.name;
});
return roles.includes("channel");
}
}
},
methods: {
onLogout() {
this.$store.dispatch("user/removeToken");
}
},
async asyncData({ app, params }) {
const client = app.apolloProvider.defaultClient;
const user = await client
.query({
query: User,
variables: {
username: params.profile
}
})
.then(({ data }) => data && data.userbyname);
return {
user
};
}
};
</script> |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;
contract Twitter {
uint16 constant MAX_TWEET_LENGTH = 280;
struct Tweet{
address author;
string content;
uint256 timestamp;
uint256 likes;
}
mapping(address => Tweet[]) public tweets;
function createTweet(string memory _tweet) public {
require(bytes(_tweet).length <= 200, "Tweet is too long bruh!");
Tweet memory newTweet = Tweet({
author: msg.sender,
content:_tweet,
timestamp : block.timestamp,
likes : 0
});
tweets[msg.sender].push(newTweet);
}
function getTweet(uint _i) public view returns (Tweet memory) {
return tweets[msg.sender][_i];
}
function getAllTweets(address _owner) public view returns (Tweet[] memory) {
return tweets[_owner];
}
} |
/* eslint-disable material-ui/no-empty-box */
import * as React from 'react';
import { styled } from '@mui/zero-runtime';
declare module '@mui/zero-runtime/theme' {
interface ThemeArgs {
theme: {
palette: {
primary: Record<string, string>;
};
mixins: {
toolbar: Record<string, string>;
};
typography: {
body1: Record<string, string>;
};
};
}
}
const B = styled('a')<{ isRed?: boolean }>(({ theme }) => ({
color: (props) => (props.isRed ? 'red' : 'blue'),
backgroundColor: [theme.palette.primary.main, theme.palette.primary.darkMain],
'&:enabled': {
color: 'beige',
},
'@layer utils': {},
'@media (min-width:360px)': {
'.globalClass': {
color: [theme.palette.primary.main, theme.palette.primary.darkMain],
},
},
variants: [
{
props: {
isRed: true,
},
style: {
color: ({ isRed }) => (isRed ? 'red' : 'blue'),
},
},
{
props: {
isBlue: true,
},
style: {
color: ({ isRed }) => (isRed ? 'red' : 'blue'),
},
},
],
}));
const A = styled(B, {
overridesResolver(props) {
return false;
},
})<{ isBlue?: boolean }>({
color: 'red',
backgroundColor: (props) => (props.isBlue ? 'red' : 'blue'),
});
const Box = styled('div')(({ theme }) => ({
color: theme.palette.primary.main,
}));
function WorksWithNoTheme() {
<Box />;
}
const StyledToolbar = styled('div')(({ theme }) => ({
...theme.mixins.toolbar,
}));
const StyledSpan = styled('span')(({ theme }) => ({
...theme.typography.body1,
}));
// https://github.com/mui/material-ui/issues/28844
interface PropsFooVariant {
variant: 'foo';
}
interface PropsBarVariant {
variant: 'bar';
}
function Component(props: PropsFooVariant | PropsBarVariant) {
return <div />;
}
const StyledComponent = styled(Component)(({ theme }) => ({}));
const rendered = (
<React.Fragment>
<StyledComponent variant="foo" />
<StyledComponent variant="bar" />
</React.Fragment>
);
/**
*/
/**
* Test styleOverrides callback types
*/
interface ButtonProps {
startIcon?: React.ReactNode;
endIcon?: React.ReactNode;
color?: 'primary';
variant?: 'contained';
}
const ButtonRoot = styled('button', {
name: 'MuiButton',
slot: 'Root',
overridesResolver: (props, styles) => styles.root,
})<{ ownerState: ButtonProps }>({});
const ButtonIcon = styled('span', {
name: 'MuiButton',
slot: 'Icon',
overridesResolver: (props, styles) => styles.icon,
})<{ ownerState: ButtonProps }>({});
function Button({
children,
startIcon,
endIcon,
color = 'primary',
variant = 'contained',
...props
}: React.PropsWithChildren<ButtonProps>) {
const ownerState = { startIcon, endIcon, color, variant, ...props };
return (
<ButtonRoot ownerState={ownerState}>
{startIcon && <ButtonIcon ownerState={ownerState}>{startIcon}</ButtonIcon>}
{children}
{endIcon && <ButtonIcon ownerState={ownerState}>{endIcon}</ButtonIcon>}
</ButtonRoot>
);
}
function variantsAPI() {
const ObjectSyntax = styled('div')<{ foo?: string; bar?: number }>({
variants: [
{
props: { foo: 'a' },
style: { color: 'blue' },
},
],
});
const FunctionSyntax = styled('div')<{ foo?: string; bar?: number }>(() => ({
variants: [
{
props: { foo: 'a' },
style: { color: 'blue' },
},
],
}));
const WrongUsage = styled('div')<{ foo?: string; bar?: number }>({
color: [
{
// @ts-expect-error the API is not valid for CSS properties
props: { foo: 'a' },
style: { color: 'blue' },
},
],
});
} |
import React from 'react';
// Import Components
import { Row, Col, Card, Media } from "react-bootstrap";
//Import Data Table
import DataTable from 'react-data-table-component';
import DataTableExtensions from 'react-data-table-component-extensions';
import 'react-data-table-component-extensions/dist/index.css';
// Import Icons
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faDownload, faPencilAlt, faPlus, faTrash } from '@fortawesome/fontawesome-free-solid';
import Img1 from '../../assets/img/profiles/avatar-01.jpg';
const data = [
{
id: 'PRE2309',
name: 'Aaliyah',
class: '10',
subject: 'English',
startTime: '10:00 AM',
endTime: '01:00 PM',
date: '23 Apr 2020',
action: ''
},
{
id: 'PRE2209',
name: 'Malynne',
class: '1',
subject: 'Botony',
startTime: '10:00 AM',
endTime: '01:00 PM',
date: '23 Apr 2020',
action: ''
},
{
id: 'PRE2213',
name: 'Levell Scott',
class: '9',
subject: 'Biology',
startTime: '01:00 PM',
endTime: '04:00 PM',
date: '26 Nov 2020',
action: ''
},
{
id: 'PRE2143',
name: 'Minnie',
class: '8',
subject: 'Science',
startTime: '01:00 PM',
endTime: '04:00 PM',
date: '18 Sep 2020',
action: ''
},
{
id: 'PRE2009',
name: 'Lois A',
class: '7',
subject: 'History',
startTime: '01:00 PM',
endTime: '04:00 PM',
date: '23 Jul 2020',
action: ''
},
{
id: 'PRE2431',
name: 'Calvin',
class: '2',
subject: 'Biology',
startTime: '10:00 AM',
endTime: '01:00 PM',
date: '15 Oct 2020',
action: ''
},
{
id: 'PRE1534',
name: 'Vincent',
class: '6',
subject: 'Botony',
startTime: '10:00 AM',
endTime: '01:00 PM',
date: '02 Jun 2020',
action: ''
},
{
id: 'PRE2153',
name: 'Kozma Tatari',
class: '12',
subject: 'Mathematics',
startTime: '10:00 AM',
endTime: '01:00 PM',
date: '23 Apr 2020',
action: ''
},
];
const columns = [
{
name: 'ID',
selector: 'id',
sortable: true,
},
{
name: 'Name',
sortable: true,
cell: row => <Media className="user-dt"><a><img src={Img1} className="avatar-img rounded-circle avatar avatar-sm mr-2" /></a><Media.Body><a>{row.name}</a></Media.Body></Media>
},
{
name: 'Class',
selector: 'class',
sortable: true,
},
{
name: 'Subject',
selector: 'subject',
sortable: true,
},
{
name: 'Start Time',
selector: 'startTime',
sortable: true,
},
{
name: 'End Time',
selector: 'endTime',
sortable: true,
},
{
name: 'Date',
selector: 'date',
sortable: true,
},
{
name: 'Action',
selector: 'action',
sortable: true,
cell: () => <div className="d-flex"><a href="/edit-time-table" className="btn btn-sm bg-success-light mr-2">
<FontAwesomeIcon icon={faPencilAlt} /> </a> <a href="#" className="btn btn-sm bg-danger-light"> <FontAwesomeIcon icon={faTrash} /> </a></div>
},
];
class TimeTable extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
render() {
const tableData = {
columns,
data,
};
return (
<div>
<div className="page-header">
<div className="page-header">
<Row>
<Col className="col">
<h3 className="page-title">Time Table</h3>
<ul className="breadcrumb">
<li className="breadcrumb-item"><a href="/dashboard">Dashboard</a></li>
<li className="breadcrumb-item active">Time Table</li>
</ul>
</Col>
<Col className="col-auto text-right float-right ml-auto">
<a href="#" className="btn btn-outline-primary mr-2"><FontAwesomeIcon icon={faDownload} /> Download</a>
<a href="/add-time-table" className="btn btn-primary"><FontAwesomeIcon icon={faPlus} /></a>
</Col>
</Row>
</div>
</div>
<Card>
<DataTableExtensions
{...tableData}
>
<DataTable
noHeader
defaultSortField="id"
defaultSortAsc={false}
pagination
highlightOnHover
/>
</DataTableExtensions>
</Card>
</div>
)
}
}
export { TimeTable }; |
#Problem APEX 2.4.18
DOCUMENT();
# Load whatever macros you need for the problem
loadMacros(
"PGstandard.pl",
"PGchoicemacros.pl",
"MathObjects.pl",
"PGcourse.pl"
);
## DBsubject(Calculus - single variable)
## DBchapter(Differentiation)
## DBsection(Quotient rule (with trigonometric functions))
## Institution('Valdosta State University')
## Author('S. V. Ault')
## TitleText1('APEX Calculus')
## AuthorText1('Hartman')
## EditionText1('3.0')
## Section1('2.4')
## Problem1('18')
$showPartialCorrectAnswers = 1;
$a = random(2,8,1);
$a1 = $a - 1;
$b = random(2,10,1)*random(-1,1,2);
$c = random(2,8,1);
$bc = $b * $c;
$c1 = $c - 1;
$f = "t^{$a}";
$fp = "$a t^{$a1}";
$g = "\cos t + $b t^{$c}";
$gp = "-\sin t + $bc t^{$c1}";
$g_ans = "cos(t) + $b t^$c";
$gp_ans = "-sin(t) + $bc t^$c1";
$gs = "(\cos t + $b t^{$c})^2";
$gs_ans = "($g_ans)^2";
$ans1 = "($g_ans)($fp) - ($f)($gp_ans)";
$ans2 = $gs_ans;
TEXT(beginproblem());
BEGIN_TEXT
Compute the derivative of the given function.
$PAR
\[
g(t) = \frac{$f}{$g}
\]
$PAR
The derivative may be expressed as a fraction
\(\displaystyle g'(t) = \frac{p(t)}{q(t)}\), where
$BR
\(p(t) =\)\{ ans_rule(25) \}, and
$BR
\(q(t) =\)\{ ans_rule(25) \}.
END_TEXT
ANS( fun_cmp( $ans1, vars=>['t'] ));
ANS( fun_cmp( $ans2, vars=>['t'] ));
SOLUTION(EV3(<<'END_SOLUTION'));
$BR$BBOLD Solution:$EBOLD
$PAR
Use the Quotient Rule.
$PAR
\[
g'(t) = \frac{($g)($fp) - ($f)($gp)}{$gs}.
\]
END_SOLUTION
ENDDOCUMENT(); |
<template>
<div>
<!-- 服务器API -->
</div>
</template>
<script>
import axios from 'axios'
export default {
name: "myApi",
methods: {
// sj--未完成 对接接口
async getAllBooks(){
/**
* 从服务器获取所有书籍信息
* @return: {Promise} { code, msg, data {Array} }
* */
let option = {
url: 'http://127.0.0.1:8003/orderservice/findAll',
method: 'get'
}
try {
let apiRe = await axios(option);
return apiRe.data;
} catch {
return {
code: -1,
msg: 'API获取书籍数据失败',
}
}
},
async deleteBookById(_id){
/**
* 根据书籍id删除服务器书籍
* @param: {Number} _id 书籍id
* @return: {Promise} 删除情况 {code, msg}
* */
let option = {
url: `http://127.0.0.1:8003/orderservice/delete/${_id}`,
method: 'delete'
}
try {
let apiRe = await axios(option);
return apiRe.data;
} catch {
return {
code: -1,
msg: 'API删除书籍数据失败',
}
}
},
async updateBook(book) {
let option = {
url: 'http://127.0.0.1:8003/orderservice/update',
method: 'put',
data: book
}
try {
return await axios(option)
} catch {
return null
}
},
async createBook(book) {
let option = {
url: 'http://127.0.0.1:8003/orderservice/add',
method: 'post',
data: book
}
try {
return await axios(option)
} catch {
return null
}
},
}
}
</script>
<style scoped>
</style> |
mod map;
use std::{
fmt::{Debug, Display, Formatter, Result as FmtResult},
marker::PhantomData,
num::NonZeroU64,
};
use rkyv::{
out_field,
with::{ArchiveWith, DeserializeWith, SerializeWith},
Archive, Archived, Deserialize, Fallible,
};
use twilight_model::id::Id;
pub use self::map::{ArchivedIdOption, IdRkyvMap};
/// Used to archive [`Id<T>`].
///
/// # Example
///
/// ```
/// # use rkyv::Archive;
/// use redlight::rkyv_util::id::IdRkyv;
/// use twilight_model::id::Id;
///
/// #[derive(Archive)]
/// struct Cached<T> {
/// #[with(IdRkyv)]
/// id: Id<T>,
/// }
/// ```
pub struct IdRkyv;
/// An archived [`Id<T>`].
#[repr(transparent)]
pub struct ArchivedId<T> {
value: Archived<NonZeroU64>,
phantom: PhantomData<fn(T) -> T>,
}
impl<T> ArchivedId<T> {
/// Return the inner primitive value.
pub fn get(self) -> u64 {
self.into_nonzero().get()
}
/// Return the [`NonZeroU64`] representation of the ID.
pub fn into_nonzero(self) -> NonZeroU64 {
// the .into() is necessary in case the `archive_le` or `archive_be`
// features are enabled in rkyv
#[allow(clippy::useless_conversion)]
self.value.into()
}
/// Cast an archived ID from one type to another.
pub const fn cast<New>(self) -> ArchivedId<New> {
ArchivedId {
value: self.value,
phantom: PhantomData,
}
}
}
impl<T> Clone for ArchivedId<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for ArchivedId<T> {}
impl<T> Display for ArchivedId<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
Display::fmt(&self.value, f)
}
}
impl<T> Debug for ArchivedId<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
Display::fmt(self, f)
}
}
impl<T> From<Id<T>> for ArchivedId<T> {
fn from(value: Id<T>) -> Self {
Self {
// the .into() is necessary in case the `archive_le` or `archive_be`
// features are enabled in rkyv
#[allow(clippy::useless_conversion)]
value: value.into_nonzero().into(),
phantom: PhantomData,
}
}
}
impl<T> From<ArchivedId<T>> for Id<T> {
fn from(id: ArchivedId<T>) -> Self {
// the `from` is necessary in case the `archive_le` or `archive_be`
// features are enabled in rkyv
#[allow(clippy::useless_conversion)]
Id::from(NonZeroU64::from(id.value))
}
}
impl<T> PartialEq for ArchivedId<T> {
fn eq(&self, other: &Self) -> bool {
self.value == other.value
}
}
impl<T> Eq for ArchivedId<T> {}
impl<T> PartialEq<Id<T>> for ArchivedId<T> {
fn eq(&self, other: &Id<T>) -> bool {
self.value == other.into_nonzero()
}
}
impl<T> PartialEq<ArchivedId<T>> for Id<T> {
fn eq(&self, other: &ArchivedId<T>) -> bool {
other.eq(self)
}
}
#[cfg(feature = "validation")]
#[cfg_attr(docsrs, doc(cfg(feature = "validation")))]
const _: () = {
use std::ptr::addr_of;
use rkyv::{bytecheck::NonZeroCheckError, CheckBytes};
impl<C: ?Sized, T> CheckBytes<C> for ArchivedId<T> {
type Error = NonZeroCheckError;
unsafe fn check_bytes<'bytecheck>(
value: *const Self,
context: &mut C,
) -> Result<&'bytecheck Self, Self::Error> {
Archived::<NonZeroU64>::check_bytes(addr_of!((*value).value), context)?;
Ok(&*value)
}
}
};
impl<T> ArchiveWith<Id<T>> for IdRkyv {
type Archived = ArchivedId<T>;
type Resolver = ();
unsafe fn resolve_with(
id: &Id<T>,
pos: usize,
resolver: Self::Resolver,
out: *mut Self::Archived,
) {
let (fp, fo) = out_field!(out.value);
id.into_nonzero().resolve(pos + fp, resolver, fo);
}
}
impl<T, S: Fallible + ?Sized> SerializeWith<Id<T>, S> for IdRkyv {
fn serialize_with(_: &Id<T>, _: &mut S) -> Result<Self::Resolver, <S as Fallible>::Error> {
Ok(())
}
}
impl<T, D: Fallible + ?Sized> DeserializeWith<ArchivedId<T>, Id<T>, D> for IdRkyv {
fn deserialize_with(
archived: &ArchivedId<T>,
deserializer: &mut D,
) -> Result<Id<T>, <D as Fallible>::Error> {
archived.deserialize(deserializer)
}
}
impl<D: Fallible + ?Sized, T> Deserialize<Id<T>, D> for ArchivedId<T> {
fn deserialize(&self, _: &mut D) -> Result<Id<T>, <D as Fallible>::Error> {
Ok(Id::from(self.into_nonzero()))
}
}
#[cfg(test)]
mod tests {
use rkyv::{with::With, Infallible};
use super::*;
#[test]
fn test_rkyv_id() {
type Wrapper = With<Id<()>, IdRkyv>;
let id = Id::new(123);
let bytes = rkyv::to_bytes::<_, 0>(Wrapper::cast(&id)).unwrap();
#[cfg(not(feature = "validation"))]
let archived = unsafe { rkyv::archived_root::<Wrapper>(&bytes) };
#[cfg(feature = "validation")]
let archived = rkyv::check_archived_root::<Wrapper>(&bytes).unwrap();
let deserialized: Id<()> = archived.deserialize(&mut Infallible).unwrap();
assert_eq!(id, deserialized);
}
} |
import React from "react";
import {
Box,
Heading,
Text,
Input,
Button,
FormControl,
FormLabel,
InputGroup,
InputRightElement,
Link,
ScaleFade,
} from "@chakra-ui/react";
import { AiOutlineEyeInvisible, AiOutlineEye } from "react-icons/ai";
import { authAPI } from "utils/api";
import { useCallback, useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { FcGoogle } from "react-icons/fc";
import { useGoogleLogin } from "@react-oauth/google";
import { useRouter } from "next/router";
import { signIn } from "next-auth/react";
import { successToast, errorToast } from "@lib/toast";
const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{8,}/;
const schema = z.object({
user_name: z.string().min(3),
email: z.string().email(),
password: z.string().regex(regex),
});
type SignUpFormSchema = z.infer<typeof schema>;
export default function SignupForm() {
const router = useRouter();
const [show, setShow] = React.useState(false);
const handleClick = () => setShow(!show);
const [isSubmitting, setIsSubmitting] = useState(false);
const [googleLoading, setGoogleLoading] = useState(false);
const {
register,
handleSubmit,
reset,
formState: { errors },
} = useForm<SignUpFormSchema>({
resolver: zodResolver(schema),
});
const onSubmit = useCallback(
async (data) => {
setIsSubmitting(true);
const output = {
...data,
link: `https://anonry.netlify.app/verify-email?email=${data.email}`,
};
try {
const result = await authAPI.signup(output);
if (result) {
reset();
successToast({ message: "OTP has been sent to your email" });
}
} catch (err: any) {
errorToast({ message: err ?? "An error occured, Try again" });
} finally {
setIsSubmitting(false);
}
},
[reset]
);
const onGoogleLogin = useCallback(
async (data) => {
setGoogleLoading(true);
const output = {
token: data?.access_token,
};
try {
const result: any = await signIn("google", {
...output,
redirect: false,
});
if (result.error) {
errorToast({ message: "An error occured, Try again" });
}
if (result.ok) {
successToast({ message: "Signed in, Redirecting..." });
router.push("/dashboard");
}
} catch (err: any) {
errorToast({ message: "An error occured, Try again" });
} finally {
setGoogleLoading(false);
}
},
[router]
);
const googleLogin = useGoogleLogin({
onSuccess: (tokenResponse) => onGoogleLogin(tokenResponse),
});
return (
<Box bg="white">
<Box
maxW="min(100%, 1600px)"
mx="auto"
px={{ base: "1rem", lg: "3.5rem" }}
py="2rem"
>
<Box maxW="540px" mx="auto">
<Link
letterSpacing="-2px"
fontWeight="800"
color="#000000"
fontSize="2xl"
_hover={{ textDecoration: "none" }}
>
Anonry
</Link>
<ScaleFade initialScale={0.8} in={true}>
<Box mt="1rem" border="1px solid #424242" borderRadius={5} p="2rem">
<Heading
color="#000000"
fontSize="xl"
opacity="0.8"
fontWeight="semibold"
>
Create an Anonry account
</Heading>
<Box mt="1.5rem">
<Button
variant="primary"
minH="50px"
borderRadius={5}
w="100%"
_focus={{ outline: "none" }}
_active={{ bg: "none" }}
type="button"
fontSize="sm"
iconSpacing={4}
leftIcon={<FcGoogle size="1.3rem" />}
onClick={() => googleLogin()}
isLoading={googleLoading}
>
Sign up with Google
</Button>
</Box>
<Box as="form" onSubmit={handleSubmit(onSubmit)}>
<FormControl
color="#000000"
mt="1.5rem"
isInvalid={Boolean(errors.email)}
>
<FormLabel fontSize="sm" htmlFor="email">
Email
</FormLabel>
<Input
type="email"
id="email"
_focus={{ border: "1px solid #00000090" }}
h="50px"
{...register("email")}
/>
</FormControl>
<FormControl
color="#000000"
mt="1.5rem"
isInvalid={Boolean(errors.user_name)}
>
<FormLabel fontSize="sm" htmlFor="userName">
Username
</FormLabel>
<Input
type="text"
id="userName"
_focus={{ border: "1px solid #00000090" }}
h="50px"
{...register("user_name")}
/>
</FormControl>
<FormControl
color="#000000"
mt="1.5rem"
isInvalid={Boolean(errors.password)}
>
<FormLabel fontSize="sm" htmlFor="password">
Password
</FormLabel>
<InputGroup size="md">
<Input
type={show ? "text" : "password"}
id="password"
_focus={{ border: "1px solid #00000090" }}
h="50px"
{...register("password")}
/>
<InputRightElement h="100%">
<Button
px="0px"
minW="0px"
_focus={{ outline: "none" }}
_active={{ bg: "none" }}
_hover={{ bg: "none" }}
bg="none"
onClick={handleClick}
type="button"
>
{show ? (
<AiOutlineEye size="1.4rem" />
) : (
<AiOutlineEyeInvisible size="1.4rem" />
)}
</Button>
</InputRightElement>
</InputGroup>
</FormControl>
<Button
variant="primary"
w="100%"
mt="1.5rem"
_focus={{ outline: "none" }}
minH="50px"
type="submit"
isLoading={isSubmitting}
>
Continue
</Button>
<Box mt="1rem" fontSize="sm" color="#000000">
<Text>
Have an account?{" "}
<Link
href="/login"
textDecoration="underline"
_focus={{ outline: "none" }}
>
Login
</Link>
</Text>
</Box>
</Box>
</Box>
</ScaleFade>
</Box>
</Box>
</Box>
);
} |
import { ConfigModule } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { Test, TestingModule } from '@nestjs/testing';
import { databaseProviders } from '@/database/database.providers';
import { MailModule } from '@/mail/mail.module';
import { UsersModule } from '@/users/users.module';
import { authProviders } from './auth.providers';
import { AuthService } from './auth.service';
import { Tokens } from './types';
describe('AuthService', () => {
let service: AuthService;
const dto = {
username: 'username',
password: 'password',
email: 'email@email.com',
};
const mockUsersService = {
create: jest.fn(dto => {
return {
id: Date.now(),
username: dto.username,
email: dto.email,
};
}),
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
JwtModule.register({}),
MailModule,
UsersModule,
],
providers: [...databaseProviders, ...authProviders, AuthService],
}).compile();
service = module.get<AuthService>(AuthService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
it('should be able to signup', async () => {
const password = await service.generateHash(dto.password);
const newUser = mockUsersService.create({
...dto,
password,
});
const tokens: Tokens = await service.generateTokens(
newUser.id,
newUser.username,
newUser.email,
);
expect(!!tokens.accessToken).toBe(true);
expect(typeof tokens.accessToken).toBe('string');
expect(!!tokens.refreshToken).toBe(true);
expect(typeof tokens.refreshToken).toBe('string');
});
}); |
/* eslint-disable @next/next/no-img-element */
import { ArrowDown2, Clock } from "iconsax-react";
import TimeAgo from "react-timeago";
import useSWR from "swr";
import { Review, TMDBResponse } from "../../../typing";
import fetchData from "../../utils/fetchData";
import { config } from "../../utils/tmdb";
import truncate from "../../utils/truncate";
import { Avatar } from "./Cast";
const ReviewCard = ({ id, type }: { id: number; type: string }) => {
const { data } = useSWR<TMDBResponse<Review[]>>(
`${config.BASE_URL}${type}/${id}/reviews?api_key=${config.API_KEY}&language=en-US&page=1`,
async (url) => await fetchData(url)
);
return (
<div className="my-2 lg:w-[70%]">
<div className="flex items-center justify-between">
<p className="text-white text-md font-semibold">Reviews</p>
{data?.results && data?.results?.length > 5 && (
<span className="w-[35px] h-[35px] flex items-center justify-center transition-all duration-300 hover:bg-white/10 hover:scale-105 active:scale-95 rounded-full">
<ArrowDown2 size={25} className="text-white" />
</span>
)}
</div>
{data?.results && data?.results?.length > 0 ? (
<div className="">
{data?.results?.slice(0, 5).map((result: Review, index: number) => (
<Card key={index} {...result} />
))}
</div>
) : (
<div className="text-white ">There aren't any reviews yet </div>
)}
</div>
);
};
const Card = (props: Review) => {
const { author_details, updated_at, created_at, content } = props;
return (
<div className="flex w-full my-2">
<Avatar
src={`${config.IMAGE_URL + author_details?.avatar_path}`}
className="h-[50px] w-[50px] mt-1"
/>
<div className="w-full">
<span className="flex items-center justify-between px-2">
<p className="text-md text-white font-bold">
{author_details.username || author_details.name}
</p>
<span className="flex text-white items-start justify-start">
<Clock variant="Bold" size={18} className="text-neutral-600" />{" "}
<p className="pl-1 text-sm text-neutral-600">
<TimeAgo date={updated_at ?? created_at} />
</p>
</span>
</span>
<p className="text-neutral-400 px-2 text-sm">
{truncate(content, 200)}
</p>
</div>
</div>
);
};
export default ReviewCard; |
import { Component, OnInit, PLATFORM_ID } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ActivatedRoute } from '@angular/router';
import { Select, Store } from '@ngxs/store';
import { OrcamentoState } from 'apps/app-web/src/app/data/store/state';
import { Orcamento, Pedido } from 'libs/data/src/lib/classes';
import { StatusOrcamento } from 'libs/data/src/lib/enums';
import { Observable } from 'rxjs';
import { AdicionarOrcamento, ResetarOrcamento } from 'apps/app-web/src/app/data/store/actions/orcamento.actions';
import { MercadoPagoPayment } from 'libs/data/src/lib/interfaces';
import { IncrementarVendaProduto } from 'apps/app-web/src/app/data/store/actions/produto.actions';
import { isPlatformBrowser } from '@angular/common';
import { PageScrollService } from 'apps/app-web/src/app/shared/services/page-scroll.service';
import { CheckoutService } from '../../checkout.service';
import { PedidoService } from 'apps/app-web/src/app/data/service';
@Component({
selector: 'personalizados-lopes-resultado-pagamento',
templateUrl: './resultado-pagamento.component.html',
styleUrls: ['./resultado-pagamento.component.scss']
})
export class ResultadoPagamentoComponent implements OnInit {
@Select(OrcamentoState.ObterOrcamentos) Orcamento$: Observable<Orcamento>;
Orcamento: Orcamento;
Pedido: Pedido;
Finalizado:boolean = false;
Loading:boolean = false;
state='flipped';
payment:MercadoPagoPayment;
status:StatusPagamento;
StatusPagamento = StatusPagamento;
_init_point:{};
constructor(
private pedidoService:PedidoService,
private activeRoute:ActivatedRoute,
private snack: MatSnackBar,
private checkoutService: CheckoutService,
private scrollService:PageScrollService,
private store:Store) { }
ngOnInit(): void {
this.Orcamento$.subscribe(x=>{
this.Orcamento = x;
this.Pedido = new Pedido(x);
if(this.Orcamento.Produto){
this.Orcamento.Produto.forEach(prod=>{
if(!prod.Produto.Vendas)
Object.assign(prod.Produto,{Vendas:0})
prod.Produto.Vendas++;
this.store.dispatch(new IncrementarVendaProduto(prod.Produto._id));
})
}
if(this.Orcamento.Status == StatusOrcamento.enviado)
this.Finalizado = true;
})
setTimeout(()=>{
this.flip()
this.LerParametros();
},0);
}
LerParametros(){
this.activeRoute.queryParams.subscribe(params => {
this.PreencherDadosPagamentoNoPedido(params);
switch(params.status){
case ("approved"): {
this.status = StatusPagamento.aprovado;
break;
}
case("rejected"):{
this.status = StatusPagamento.rejeitado;
this.goCheckout();
break;
}
case("failure"):{
this.status = StatusPagamento.rejeitado;
this.goCheckout();
break;
}
case("pending"):{
this.status = StatusPagamento.pendente;
break;
}
default:{
this.status = StatusPagamento.desistencia;
}
}
if(!params.status||params.status == 'null'){
this.status = StatusPagamento.desistencia;
}
this.SalvarPedido();
});
}
PreencherDadosPagamentoNoPedido(resultadoPagamento:any){
this.Pedido.ResultadoPagamentoMP = {
collection_id: resultadoPagamento.collection_id ?? 0,
collection_status: resultadoPagamento.collection_status ?? '',
site_id: resultadoPagamento.site_id ?? '',
status: resultadoPagamento.status ?? '',
merchant_account_id: resultadoPagamento.merchant_account_id ?? 0,
external_reference: resultadoPagamento.external_reference ??' ',
payment_id: resultadoPagamento.payment_id ?? 0,
merchant_order_id: resultadoPagamento.merchant_order_id ?? 0,
preference_id: resultadoPagamento.eference_id ?? '',
payment_type: resultadoPagamento.payment_type ?? '',
processing_mode: resultadoPagamento.processing_mode ??''
}
}
SalvarPedido(){
if(this.OrcamentoValido()){
if(this.Orcamento.Preco >0) {
this.AdicionarOrcamento();
this.AdicionarPedido();
}
}
}
OrcamentoValido(){
return this.Orcamento.Usuario.Email&&
!this.Finalizado&&
!localStorage.getItem('Orcamento'+this.Orcamento.Produto[0].codOrcamento);
}
AdicionarOrcamento(){
//this.store.dispatch(new AdicionarOrcamento()).subscribe(()=>{
setTimeout(()=>{
this.Finalizado = true;
localStorage.setItem('Orcamento'+this.Orcamento.Produto[0].codOrcamento,"true");
if(isPlatformBrowser(PLATFORM_ID))
this.scrollService.scrollDown();
this.Loading = false;
if(this.status == StatusPagamento.aprovado || this.status == StatusPagamento.pendente){
this.Orcamento.Status = StatusOrcamento.enviado;
this.store.dispatch(new ResetarOrcamento())
}
},3500)
//});
}
AdicionarPedido(){
this.pedidoService.Incluir(this.Pedido).subscribe(()=>{
this.snack.open("Pedido enviado com sucesso.","fechar",{
verticalPosition:'top',
duration:5000
});
});
}
ngOnDestroy(){
this.flip()
}
flip(){
if (this.state === "default") {
this.state = "flipped";
} else {
this.state = "default";
}
}
goCheckout(){
this.Orcamento$.subscribe(orcamento => {
this.Loading = true;
if(orcamento.Usuario.Email)
this.checkoutService.goCheckout(orcamento).subscribe(result => {
this._init_point = result;
this.Loading = false;
if(isPlatformBrowser(PLATFORM_ID))
this.scrollService.scrollDown();
})
else{
this.snack.open("Carrinho inválido, tente finalizar o pedido no carrinho novamente para concluir o pagamento.","fechar",{
verticalPosition:'top',
duration:5000
});
}
})
}
}
export enum StatusPagamento{
aprovado,
pendente,
rejeitado,
desistencia
} |
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {AuthContainerComponent} from 'src/app/auth-container/auth-container.component';
import {LoginComponent} from 'src/app/login/login.component';
import {RegisterComponent} from 'src/app/register/register.component';
const routes: Routes = [
{
path: '',
component: AuthContainerComponent,
children: [
{
path: 'login',
component: LoginComponent
},
{
path: 'register',
component: RegisterComponent
}
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class AuthRoutingModule { } |
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\ProductCategory;
use App\Models\ProductGallery;
use App\Helpers\ResponseFormatter;
class ProductController extends Controller
{
// index
public function index(Request $request)
{
$paginate = $request->input('paginate');
$id = $request->input('id');
$name = $request->input('name');
$stock = $request->input('stock');
$price_from = $request->input('price_from');
$price_to = $request->input('price_to');
$category = $request->input('category');
if ($id) {
$product = Product::with('productCategory', 'galleries', 'sizes')->find($id);
if ($product) {
return ResponseFormatter::success(
$product,
'Product data successfully retrieved'
);
} else {
return ResponseFormatter::error(
null,
'Product not found',
404
);
}
}
$product = Product::with('productCategory', 'galleries', 'sizes');
if ($name) {
$product->where('name', 'like', '%' . $name . '%');
}
if ($stock) {
$product->where('stock', '>=', $stock);
}
if ($price_from) {
$product->where('price', '>=', $price_from);
}
if ($price_to) {
$product->where('price', '<=', $price_to);
}
if ($category) {
$product->where('product_category_id', '=', $category);
}
return ResponseFormatter::success(
$product->paginate($paginate ?? 10),
'Product data successfully retrieved'
);
}
// function category
public function category(Request $request)
{
$id = $request->input('id');
$paginate = $request->input('paginate');
$name = $request->input('name');
if ($id) {
$category = ProductCategory::with('products')->find($id);
if ($category) {
return ResponseFormatter::success(
$category,
'Category data successfully retrieved'
);
} else {
return ResponseFormatter::error(
null,
'Category not found',
404
);
}
}
$category = ProductCategory::query();
if ($name) {
$category->where('name', 'like', '%' . $name . '%');
}
return ResponseFormatter::success(
$category->paginate($paginate ?? 10),
'Category data successfully retrieved'
);
}
} |
#include "../../lv_examples.h"
#if LV_USE_OBSERVER && LV_USE_ARC && LV_USE_LABEL && LV_USE_BUTTON && LV_USE_SPINNER && LV_BUILD_EXAMPLES
typedef enum {
FW_UPDATE_STATE_IDLE,
FW_UPDATE_STATE_CONNECTING,
FW_UPDATE_STATE_CONNECTED,
FW_UPDATE_STATE_DOWNLOADING,
FW_UPDATE_STATE_CANCEL,
FW_UPDATE_STATE_READY,
} fw_update_state_t;
static void fw_upload_manager_observer_cb(lv_observer_t * observer, lv_subject_t * subject);
static void fw_update_btn_clicked_event_cb(lv_event_t * e);
static void fw_update_close_event_cb(lv_event_t * e);
static void fw_update_win_observer_cb(lv_observer_t * observer, lv_subject_t * subject);
static lv_subject_t fw_download_percent_subject;
static lv_subject_t fw_update_status_subject;
/**
* Show how to handle a complete firmware update process with observers.
* Normally it's hard to implement a firmware update process because in some cases
* - the App needs to was for the UI (wait for a button press)
* - the UI needs to wait for the App (connecting or downloading)
* With observers these complex mechanisms can be implemented a simple and clean way.
*/
void lv_example_observer_5(void)
{
lv_subject_init_int(&fw_download_percent_subject, 0);
lv_subject_init_int(&fw_update_status_subject, FW_UPDATE_STATE_IDLE);
lv_subject_add_observer(&fw_update_status_subject, fw_upload_manager_observer_cb, NULL);
/*Create start FW update button*/
lv_obj_t * btn = lv_button_create(lv_screen_active());
lv_obj_add_event_cb(btn, fw_update_btn_clicked_event_cb, LV_EVENT_CLICKED, NULL);
lv_obj_center(btn);
lv_obj_t * label = lv_label_create(btn);
lv_label_set_text(label, "Firmware update");
}
static void fw_update_btn_clicked_event_cb(lv_event_t * e)
{
LV_UNUSED(e);
lv_obj_t * win = lv_win_create(lv_screen_active());
lv_obj_set_size(win, lv_pct(90), lv_pct(90));
lv_obj_set_height(lv_win_get_header(win), 40);
lv_obj_set_style_radius(win, 8, 0);
lv_obj_set_style_shadow_width(win, 24, 0);
lv_obj_set_style_shadow_offset_x(win, 2, 0);
lv_obj_set_style_shadow_offset_y(win, 3, 0);
lv_obj_set_style_shadow_color(win, lv_color_hex3(0x888), 0);
lv_win_add_title(win, "Firmware update");
lv_obj_t * btn = lv_win_add_button(win, LV_SYMBOL_CLOSE, 40);
lv_obj_add_event_cb(btn, fw_update_close_event_cb, LV_EVENT_CLICKED, NULL);
lv_obj_center(win);
lv_subject_set_int(&fw_update_status_subject, FW_UPDATE_STATE_IDLE);
lv_subject_add_observer_obj(&fw_update_status_subject, fw_update_win_observer_cb, win, NULL);
}
static void fw_update_close_event_cb(lv_event_t * e)
{
LV_UNUSED(e);
lv_subject_set_int(&fw_update_status_subject, FW_UPDATE_STATE_CANCEL);
}
static void restart_btn_click_event_cb(lv_event_t * e)
{
lv_obj_t * win = lv_event_get_user_data(e);
lv_obj_delete(win);
lv_subject_set_int(&fw_update_status_subject, FW_UPDATE_STATE_IDLE);
}
static void fw_update_win_observer_cb(lv_observer_t * observer, lv_subject_t * subject)
{
lv_obj_t * win = lv_observer_get_target(observer);
lv_obj_t * cont = lv_win_get_content(win);
fw_update_state_t status = lv_subject_get_int(&fw_update_status_subject);
if(status == FW_UPDATE_STATE_IDLE) {
lv_obj_clean(cont);
lv_obj_t * spinner = lv_spinner_create(cont);
lv_obj_center(spinner);
lv_obj_set_size(spinner, 130, 130);
lv_obj_t * label = lv_label_create(cont);
lv_label_set_text(label, "Connecting");
lv_obj_center(label);
lv_subject_set_int(subject, FW_UPDATE_STATE_CONNECTING);
}
else if(status == FW_UPDATE_STATE_DOWNLOADING) {
lv_obj_clean(cont);
lv_obj_t * arc = lv_arc_create(cont);
lv_arc_bind_value(arc, &fw_download_percent_subject);
lv_obj_center(arc);
lv_obj_set_size(arc, 130, 130);
lv_obj_remove_flag(arc, LV_OBJ_FLAG_CLICKABLE);
lv_obj_t * label = lv_label_create(cont);
lv_label_bind_text(label, &fw_download_percent_subject, "%d %%");
lv_obj_center(label);
}
else if(status == FW_UPDATE_STATE_READY) {
lv_obj_clean(cont);
lv_obj_t * label = lv_label_create(cont);
lv_label_set_text(label, "Firmware update is ready");
lv_obj_align(label, LV_ALIGN_CENTER, 0, -20);
lv_obj_t * btn = lv_button_create(cont);
lv_obj_align(btn, LV_ALIGN_CENTER, 0, 20);
lv_obj_add_event_cb(btn, restart_btn_click_event_cb, LV_EVENT_CLICKED, win);
label = lv_label_create(btn);
lv_label_set_text(label, "Restart");
}
else if(status == FW_UPDATE_STATE_CANCEL) {
lv_obj_delete(win);
}
}
static void connect_timer_cb(lv_timer_t * t)
{
if(lv_subject_get_int(&fw_update_status_subject) != FW_UPDATE_STATE_CANCEL) {
lv_subject_set_int(&fw_update_status_subject, FW_UPDATE_STATE_CONNECTED);
}
lv_timer_delete(t);
}
static void download_timer_cb(lv_timer_t * t)
{
if(lv_subject_get_int(&fw_update_status_subject) == FW_UPDATE_STATE_CANCEL) {
lv_timer_delete(t);
return;
}
int32_t v = lv_subject_get_int(&fw_download_percent_subject);
if(v < 100) {
lv_subject_set_int(&fw_download_percent_subject, v + 1);
}
else {
lv_subject_set_int(&fw_update_status_subject, FW_UPDATE_STATE_READY);
lv_timer_delete(t);
}
}
/**
* Emulate connection and FW dowlading by timers
*/
static void fw_upload_manager_observer_cb(lv_observer_t * observer, lv_subject_t * subject)
{
LV_UNUSED(subject);
LV_UNUSED(observer);
fw_update_state_t state = lv_subject_get_int(&fw_update_status_subject);
if(state == FW_UPDATE_STATE_CONNECTING) {
lv_timer_create(connect_timer_cb, 2000, NULL);
}
else if(state == FW_UPDATE_STATE_CONNECTED) {
lv_subject_set_int(&fw_download_percent_subject, 0);
lv_subject_set_int(&fw_update_status_subject, FW_UPDATE_STATE_DOWNLOADING);
lv_timer_create(download_timer_cb, 50, NULL);
}
}
#endif |
from bibgrafo.grafo_lista_adjacencia import GrafoListaAdjacencia
from bibgrafo.grafo_errors import *
class MeuGrafo(GrafoListaAdjacencia):
def vertices_nao_adjacentes(self):
'''
Provê um conjunto de vértices não adjacentes no grafo.
O conjunto terá o seguinte formato: {X-Z, X-W, ...}
Onde X, Z e W são vértices no grafo que não tem uma aresta entre eles.
:return: Um objeto do tipo set que contém os pares de vértices não adjacentes
'''
vna = set()
for v in self.vertices:
va = []
for a in self.arestas:
if self.arestas[a].v2.rotulo == v.rotulo:
v1 = self.arestas[a].v1.rotulo
va.append(v1)
elif self.arestas[a].v1.rotulo == v.rotulo:
v2 = self.arestas[a].v2.rotulo
va.append(v2)
for vt in self.vertices:
if vt.rotulo != v.rotulo and vt.rotulo not in va:
if f'{vt}-{v.rotulo}' not in vna:
vna.add(f'{v.rotulo}-{vt}')
return vna
def ha_laco(self):
'''
Verifica se existe algum laço no grafo.
:return: Um valor booleano que indica se existe algum laço.
'''
for a in self.arestas:
if self.arestas[a].v1.rotulo == self.arestas[a].v2.rotulo:
return True
return False
def grau(self, V=''):
'''
Provê o grau do vértice passado como parâmetro
:param V: O rótulo do vértice a ser analisado
:return: Um valor inteiro que indica o grau do vértice
:raises: VerticeInvalidoError se o vértice não existe no grafo
'''
if not self.existe_vertice(self.get_vertice(V)):
raise VerticeInvalidoError()
else:
g = 0
for a in self.arestas:
if self.arestas[a].v1.rotulo == V:
g += 1
if self.arestas[a].v2.rotulo == V:
g += 1
return g
def ha_paralelas(self):
'''
Verifica se há arestas paralelas no grafo
:return: Um valor booleano que indica se existem arestas paralelas no grafo.
'''
ca = []
for a in self.arestas:
ar = (self.arestas[a].v1.rotulo, self.arestas[a].v2.rotulo)
if ar in ca or ar[::-1] in ca:
return True
else:
ca.append(ar)
return False
def arestas_sobre_vertice(self, V):
'''
Provê uma lista que contém os rótulos das arestas que incidem sobre o vértice passado como parâmetro
:param V: Um string com o rótulo do vértice a ser analisado
:return: Uma lista os rótulos das arestas que incidem sobre o vértice
:raises: VerticeInvalidoException se o vértice não existe no grafo
'''
if not self.existe_vertice(self.get_vertice(V)):
raise VerticeInvalidoError()
else:
asv = set()
for a in self.arestas:
if self.arestas[a].v1.rotulo == V or self.arestas[a].v2.rotulo == V:
asv.add(self.arestas[a].rotulo)
return asv
def eh_completo(self):
'''
Verifica se o grafo é completo.
:return: Um valor booleano que indica se o grafo é completo
'''
if self.ha_paralelas() or self.ha_laco():
return False
else:
c = len(self.vertices) - 1
v = self.vertices
for x in v:
if self.grau(x.rotulo) != c:
return False
return True |
NAME
Catalyst::Controller::BindLex - Stash your lexical goodness.
SYNOPSIS
package MyApp::Controller::Moose;
use base qw/Catalyst::Controller::BindLex/;
sub bar : Local {
my ( $self, $c ) = @_;
my $x : Stashed;
my %y : Stashed;
$x = 100;
do_something( $c->stash->{x} ); # 100
$c->forward( "gorch" );
}
sub gorch : Private {
my ( $self, $c ) = @_;
my $x : Stashed;
do_something( $x ); # still 100
}
sub counter : Local {
my ( $self, $c ) = @_;
my $count : Session;
$c->res->body( "request number " . ++$count );
}
DESCRIPTION
This plugin lets you put your lexicals on the stash and elsewhere very
easily.
It uses some funky modules to get its job done: PadWalker,
Array::RefElem, Devel::Caller, Devel::LexAlias, and attributes. In some
people's opinion this hurts this plugin's reputation ;-).
If you use the same name for two variables with the same storage binding
attribute they will be aliased to each other, so you can use this for
reading as well as writing values across controller subs. This is almost
like sharing your lexical scope.
WHY ISN'T THIS A PLUGIN?
The way attributes are handled this can't be a plugin - the
MODIFY_SCALAR_ATTRIBUTES methods and friends need to be in the class
where the lexical is attributed, and this is typically a controller.
CONFIGURATION
You can add attributes to the configaration by mapping attributes to
handlers.
Handlers are either strings of methods to be called on $c with no
arguments, which are expected to return a hash reference (like "stash",
"session", etc), or code references invoked with $c, a reference to the
variable we're binding, and the name of the variable we're binding, also
expected to return a hash reference.
DEFAULT ATTRIBUTES
Some default attributes are pre-configured:
Stash, Stashed
Session, Sessioned
Flash, Flashed
Bind the variable to a key in "stash", "session", or "flash"
respectively.
The latter two require the use of a session; see
Catalyst::Plugin::Session.
METHODS
bindlex_default_config( )
MODIFY_ARRAY_ATTRIBUTES( )
MODIFY_HASH_ATTRIBUTES( )
MODIFY_SCALAR_ATTRIBUTES( )
RECIPES
Param
To get
my $username : Param;
add
__PACKAGE__->config->{bindlex}{Param} => sub { $_[0]->req->params };
AUTHORS
Matt S. Trout
Yuval Kogman
SEE ALSO
PadWalker, Array::RefElem, Devel::Caller, Devel::LexAlias,
Sub::Parameters
COPYRIGHT & LICENSE
Copyright (c) 2005 the aforementioned authors. All rights
reserved. This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself. |
'use strict';
const express = require('express');
const router = express.Router();
const { body, param, matchedData } = require('express-validator');
const { validateRequest } = require('../middleware/validate-request');
const { checkJwt } = require('../middleware/authentication');
const { isEmptyObject, isValidMongoId } = require('../utils/helpers');
const { BadRequestError } = require('../utils/errors');
const {
createLearningMaterial,
getLearningMaterial,
allLearningMaterial,
updateLearningMaterial,
deleteLearningMaterial,
} = require('../controllers/learningMaterial-controller');
router.post(
'/learning-material',
checkJwt('isAdminOrSupervisor'),
body('name').not().isEmpty().isString().trim().escape().isLength({ min: 4, max: 255 }),
body('link').not().isEmpty().isString().trim().isURL().isLength({ max: 255 }),
body('img').isString().trim().isLength({ max: 255 }).optional({ nullable: true }),
body('description').isString().trim().isLength({ max: 255 }).optional({ nullable: true }),
body('learningMaterialTypeId')
.not()
.isEmpty()
.isString()
.trim()
.escape()
.custom((value) => isValidMongoId(value)),
validateRequest,
async (req, res, next) => {
try {
const bodyData = matchedData(req, { locations: ['body'] });
if (isEmptyObject(bodyData)) throw new BadRequestError('No body');
const response = await createLearningMaterial(bodyData);
if (response) res.status(201).send({ message: 'Learning material was successfully created.' });
else res.status(400).send({ message: 'Learning material was not created.' });
} catch (error) {
next(error);
}
},
);
router.get(
'/learning-material/:learningMaterialId',
checkJwt(),
param('learningMaterialId')
.not()
.isEmpty()
.isString()
.trim()
.escape()
.custom((value) => isValidMongoId(value)),
validateRequest,
async (req, res, next) => {
try {
const { learningMaterialId } = req.params;
const response = await getLearningMaterial(learningMaterialId);
res.status(200).send(response);
} catch (error) {
next(error);
}
},
);
router.get('/learning-materials', checkJwt('isAdminOrSupervisor'), validateRequest, async (req, res, next) => {
try {
const response = await allLearningMaterial();
res.status(200).send(response);
} catch (error) {
next(error);
}
});
router.patch(
'/learning-material/:learningMaterialId',
checkJwt('isAdminOrSupervisor'),
param('learningMaterialId')
.not()
.isEmpty()
.isString()
.trim()
.escape()
.custom((value) => isValidMongoId(value)),
body('name').isString().trim().escape().isLength({ min: 4, max: 255 }).optional({ nullable: true }),
body('link').isString().trim().isLength({ max: 255 }).isURL().optional({ nullable: true }),
body('img').isString().trim().isLength({ max: 255 }).optional({ nullable: true }),
body('description').isString().trim().isLength({ max: 255 }).optional({ nullable: true }),
body('learningMaterialTypeId')
.isString()
.trim()
.escape()
.optional({ nullable: true })
.custom((value) => isValidMongoId(value)),
validateRequest,
async (req, res, next) => {
try {
const { learningMaterialId } = req.params;
const bodyData = matchedData(req, { locations: ['body'] });
if (isEmptyObject(bodyData)) throw new BadRequestError('No body');
const response = await updateLearningMaterial(learningMaterialId, bodyData);
if (response) res.status(201).send({ message: 'Learning material was successfully updated.' });
else res.status(400).send({ message: 'Learning material was not updated.' });
} catch (error) {
next(error);
}
},
);
router.delete(
'/learning-material/:learningMaterialId',
checkJwt('isAdminOrSupervisor'),
param('learningMaterialId')
.not()
.isEmpty()
.isString()
.trim()
.escape()
.custom((value) => isValidMongoId(value)),
validateRequest,
async (req, res, next) => {
try {
const { learningMaterialId } = req.params;
const response = await deleteLearningMaterial(learningMaterialId);
if (response) res.status(201).send({ message: 'Learning material was successfully deleted.' });
else res.status(400).send({ message: 'Learning material was not deleted.' });
} catch (error) {
next(error);
}
},
);
module.exports = {
learningMaterialRoute: router,
}; |
// Example for library:
// https://github.com/Bodmer/TJpg_Decoder
// This example is for an ESP8266 or ESP32, it fetches a Jpeg file
// from the web and saves it in a LittleFS file. You must have LittleFS
// space allocated in the IDE.
// Chenge next 2 lines to suit your WiFi network
#define WIFI_SSID "Your_SSID"
#define PASSWORD "Your password"
// Include the jpeg decoder library
#include <TJpg_Decoder.h>
// Include LittleFS
#include <FS.h>
#include "LittleFS.h"
// Include WiFi and http client
#ifdef ESP8266
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFiMulti.h>
#include <WiFiClientSecureBearSSL.h>
#else
#include <WiFi.h>
#include <HTTPClient.h>
#endif
// Load tabs attached to this sketch
#include "List_LittleFS.h"
#include "Web_Fetch.h"
// Include the TFT library https://github.com/Bodmer/TFT_eSPI
#include "SPI.h"
#include <TFT_eSPI.h> // Hardware-specific library
TFT_eSPI tft = TFT_eSPI(); // Invoke custom library
// This next function will be called during decoding of the jpeg file to
// render each block to the TFT. If you use a different TFT library
// you will need to adapt this function to suit.
bool tft_output(int16_t x, int16_t y, uint16_t w, uint16_t h, uint16_t* bitmap)
{
// Stop further decoding as image is running off bottom of screen
if ( y >= tft.height() ) return 0;
// This function will clip the image block rendering automatically at the TFT boundaries
tft.pushImage(x, y, w, h, bitmap);
// Return 1 to decode next block
return 1;
}
void setup()
{
Serial.begin(115200);
Serial.println("\n\n Testing TJpg_Decoder library");
// Initialise LittleFS
if (!LittleFS.begin()) {
Serial.println("LittleFS initialisation failed!");
while (1) yield(); // Stay here twiddling thumbs waiting
}
Serial.println("\r\nInitialisation done.");
// Initialise the TFT
tft.begin();
tft.fillScreen(TFT_BLACK);
// The jpeg image can be scaled by a factor of 1, 2, 4, or 8
TJpgDec.setJpgScale(1);
// The byte order can be swapped (set true for TFT_eSPI)
TJpgDec.setSwapBytes(true);
// The decoder must be given the exact name of the rendering function above
TJpgDec.setCallback(tft_output);
WiFi.begin(WIFI_SSID, PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println();
// This is for demoe purposes only so that file is fetched each time this is run
if (LittleFS.exists("/M81.jpg") == true) {
Serial.println("For test only, removing file");
LittleFS.remove("/M81.jpg");
//LittleFS.remove("/F35.jpg");
}
}
void loop()
{
// List files stored in LittleFS
listLittleFS();
// Time recorded for test purposes
uint32_t t = millis();
// Fetch the jpg file from the specified URL, examples only, from imgur
bool loaded_ok = getFile("https://i.imgur.com/C77RWcq.jpg", "/M81.jpg"); // Note name preceded with "/"
//bool loaded_ok = getFile("https://i.imgur.com/OnW2qOO.jpg", "/F35.jpg");
t = millis() - t;
if (loaded_ok) { Serial.print(t); Serial.println(" ms to download"); }
// List files stored in LittleFS, should have the file now
listLittleFS();
t = millis();
// Now draw the LittleFS file
TJpgDec.drawFsJpg(0, 0, "/M81.jpg", LittleFS);
//TJpgDec.drawFsJpg(0, 0, "/F35.jpg", LittleFS);
t = millis() - t;
Serial.print(t); Serial.println(" ms to draw to TFT");
// Wait forever
while(1) yield();
} |
package uniandes.isis2304.epsandes.persistencia;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import uniandes.isis2304.epsandes.negocio.Medico;
public class SQLMedico {
/* ****************************************************************
* Constantes
*****************************************************************/
/**
* Cadena que representa el tipo de consulta que se va a realizar en las sentencias de acceso a la base de datos
* Se renombra acá para facilitar la escritura de las sentencias
*/
private final static String SQL = PersistenciaEPSAndes.SQL;
/* ****************************************************************
* Atributos
*****************************************************************/
/**
* El manejador de persistencia general de la aplicación
*/
private PersistenciaEPSAndes pp;
/* ****************************************************************
* Métodos
*****************************************************************/
/**
* Constructor
* @param pp - El Manejador de persistencia de la aplicación
*/
public SQLMedico (PersistenciaEPSAndes pp)
{
this.pp = pp;
}
public long adicionarMedico (PersistenceManager pm, Long id, String tipo, String pNombre, String pEspecialidad, int pNRegistroMedico)
{
Query q = pm.newQuery(SQL, "INSERT INTO " + pp.darTablaMedico () + "(id, especialidad, registroMedico, idEmpleado) values (?, ?, ?, ?)");
q.setParameters(id, pEspecialidad, pNRegistroMedico, tipo, pNombre);
return (long) q.executeUnique();
}
/**
* Crea y ejecuta la sentencia SQL para eliminar TODAS LAS VISITAS de la base de datos de Parranderos
* @param pm - El manejador de persistencia
* @return EL número de tuplas eliminadas
*/
public long eliminarMedico (PersistenceManager pm)
{
Query q = pm.newQuery(SQL, "DELETE FROM " + pp.darTablaMedico ());
return (long) q.executeUnique();
}
/**
* Crea y ejecuta la sentencia SQL para ELIMINAR TODAS LAS VISITAS DE UN BEBEDOR de la base de datos de Parranderos, por su identificador
* @param pm - El manejador de persistencia
* @param idMedico - El identificador del orden
* @return EL número de tuplas eliminadas
*/
public long eliminarMedicoPorIdMedico (PersistenceManager pm, long idMedico)
{
Query q = pm.newQuery(SQL, "DELETE FROM " + pp.darTablaMedico () + " WHERE id = ?");
q.setParameters(idMedico);
return (long) q.executeUnique();
}
/**
* Crea y ejecuta la sentencia SQL para encontrar la información de los Medico de la
* base de datos de Parranderos
* @param pm - El manejador de persistencia
* @return Una lista de objetos Medico
*/
public List<Medico> darMedico (PersistenceManager pm)
{
Query q = pm.newQuery(SQL, "SELECT * FROM " + pp.darTablaMedico ());
q.setResultClass(Medico.class);
return (List<Medico>) q.execute();
}
public Medico darMedicoPorId (PersistenceManager pm, long idMedico)
{
Query q = pm.newQuery(SQL, "SELECT * FROM " + pp.darTablaMedico () + " WHERE id = ?");
q.setResultClass(Medico.class);
q.setParameters(idMedico);
return (Medico) q.executeUnique();
}
} |
<p align="center">
<a href="https://laravel.com" target="_blank"><img src="https://www.azapfy.com.br/wp-content/uploads/2020/07/logo_Prancheta-1-1536x1022.png" width="200" alt="Laravel Logo"></a>
<h3 align="center">velocidade para fazer!</h3>
</p>
<p align="center">
<img src="https://img.shields.io/badge/Laravel-FF2D20?style=for-the-badge&logo=laravel&logoColor=white" alt="Laravel">
<img src="https://img.shields.io/badge/PHP-777BB4?style=for-the-badge&logo=php&logoColor=white" alt="PHP">
<img src="https://img.shields.io/badge/MySQL-00000F?style=for-the-badge&logo=mysql&logoColor=white" alt="MySQL">
</p>
# Gerenciador de Notas Fiscais 📈
# Desafio Técnico - Desenvolvedor backend AZAPFY
## 🚀 API Rest desenvolvida em:<br/>
✔️**PHP 8+**<br/>
✔️**Framework Laravel 10+**<br/>
✔️**Banco de dados MySql**<br/>
✔️**JWT**<br/>
✔️**Form request** (na validação de dados enviados na requisição)<br/>
✔️**Api Resources** (para declaração das rotas da API de forma padronizada)<br/>
✔️**Polices Gates** (para validações de acesso aos métodos e dados dentro do sistema)<br/>
✔️**Notifications** (no disparo de novas notas fiscais para o e-mail do usuário logado em Fila para o envio de forma assíncrona)<br/>
✔️Testes Automáticos com **PHPUnit**<br/>
✔️**Documentação com Postman**<br/>
## 🚀 Bônus realizados do Desafio:<br/>
🎉**Docker**🐋<br/>
🎉**Pipeline no Github Actions (CI/CD)**<br/>
## 🚀 API
-> Endpoints do **CRUD dos Usuários** do sistema:
Show/index/store/update/destroy de Usuário
-> Endpoints do **CRUD para o gerenciamento das notas fiscais**
Show/index/store/update/destroy de NF
-> Endpoints de **acessos** dos Usuários no sistema (auth):
Login
Logout
_**Todos os endpoints contam com devidos retornos de response e http status code.**_
## 🚀 Sobre a Autenticação no Sistema
### NF
_Todos os endpoints de Notas Fiscais necessitam de autenticação._
Qualquer nível de usuário pode utilizá-las, tendo _acesso apenas a suas próprias notas fiscais_ cadastradas.
## Users
_Endpoints de usuários possuem autenticação em todas suas rotas._
Necessitando de usuário Admin para Show/index/update/destroy, exceto para o endpoint de criação (store) de novo usuário.
# 🚀 Como rodar o projeto:
> Primeiro certifique-se de ter o docker e docker compose instalado em sua máquina.<br/><br/>
> Copie o conteudo de .env.example para .env e altere os seguintes parâmetros de acordo com o projeto:
```
APP_NAME=nf_laravel
APP_URL=http://localhost:8989
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=dbname
DB_USERNAME=root
DB_PASSWORD=root
CACHE_DRIVER=redis
QUEUE_CONNECTION=redis
SESSION_DRIVER=redis
REDIS_HOST=redis
REDIS_PASSWORD=null
REDIS_PORT=6379
```
<br/><br/>
> Para que as Notifications funcionem, é necessário adicionar e configurar as seguintes variáveis no seu env:
```
MAIL_MAILER=smtp
MAIL_HOST=
MAIL_PORT=
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
```
<br/><br/>
> Para executar o projeto no Docker execute os comandos no terminal (necessário estar dentro da raiz do projeto):
```
docker ps (para listar os containers/imagens e poder copiar o id do container do projeto que estará com a imagem de nome _nf-laravel-app_)
docker-compose up -d
docker exec -it ID_DO_CONTAINER_COPIADO /bin/bash
```
<br/><br/>
> Dentro do container (após executar o container pelo id ou name do container)
```
composer install
```
<br/><br/>
> Para configurar o projeto ainda dentro do container
```
php artisan jwt:secret
php artisan key:generate
php artisan migrate
php artisan seed (caso desejar criar um usuário admin)
```
<br/><br/>
> Para execução dos testes dentro do container
```
php artisan test
```
<br/><br/>
# 🚀 Acesse...
- [Documentação Postman aqui](https://documenter.getpostman.com/view/12476316/2s9YkoeMhB#a7bd3a9a-188d-403c-a777-3e87ec85c892).
<p align="center">
<a href="https://laravel.com" target="_blank"><img src="https://www.azapfy.com.br/wp-content/uploads/2020/08/NOVA-LOGO-AZAPFY_03-212x62.png" width="150" alt="Laravel Logo"></a>
<h5 align="center">Desenvolvido com ♥ por JF - 2023</h5>
</p> |
from django.db import models
from django.db.models import Count, Max, Min, Avg
class RealEstateListingManager(models.Manager):
def by_property_type(self, property_type):
return self.filter(property_type=property_type)
def in_price_range(self, min_price, max_price):
return self.filter(price__range=(min_price, max_price))
def with_bedrooms(self, bedrooms_count):
return self.filter(bedrooms=bedrooms_count)
def popular_locations(self):
return self.values('location').annotate(location_count=Count('location')).order_by('id')[:2]
class VideoGameManager(models.Manager):
def games_by_genre(self, genre):
return self.filter(genre=genre)
def recently_released_games(self, year):
return self.filter(release_year__gte=year)
def highest_rated_game(self):
return self.annotate(max_rating=Max('rating')).order_by('-max_rating').first()
def lowest_rated_game(self):
return self.annotate(min_rating=Min('rating')).order_by('min_rating').first()
def average_rating(self):
average_rating = self.aggregate(average_rating=Avg('rating'))['average_rating']
return f"{average_rating:.1f}" |
<link rel="stylesheet" href="../../../stylesheet.css">
# Story_01 — Naïve Bayes
## Contexte
> Découvrir naïve Bayes et se familiariser avec son fonctionnement.
## Mots clefs
- <def-of>Théorème de Bayes</def-of> : *permet de déterminer la probabilité qu'un événement arrive à partir d'un autre évènement qui s'est réalisé, notamment quand ces deux évènements sont interdépendants.*
$$ P(A\,|\,B) = \frac{P(B\,|\,A)\,\cdot\,P(A)}{P(B)} $$
- <def-of>Classifieur linéaire</def-of> : *Modèle de machine learning qui tente de séparer des données en classes en utilisant une frontière de décision linéaire. L'idée principale est de trouver un hyperplan (une dimension de moins que l'espace de caractéristiques) qui divise l'espace des caractéristiques en deux régions, chaque région étant associée à une classe différente.*
- <def-of>KDD (Knowledge Discovery in Databases)</def-of> : **
- <def-of>Apprentissage supervisé</def-of> : *L'objectif de l'apprentissage supervisé est d'apprendre une fonction qui mappe les entrées aux sorties, en se basant sur les exemples fournis dans l'ensemble d'entraînement.*
- <def-of>Apprentissage non supervisé</def-of> : *Contrairement à l'apprentissage supervisé, où le modèle apprend à partir d'exemples étiquetés, l'apprentissage non supervisé cherche à extraire des modèles ou des structures intrinsèques à partir des données sans avoir d'informations sur les résultats attendus.*
- <def-of>Apprentissage par renforcement</def-of> : *Branche de l'apprentissage machine où un agent interagit avec un environnement dynamique et apprend à prendre des décisions pour maximiser une récompense cumulée.*
- <def-of>CRISP-DM</def-of> : *Modèle de processus standard ouvert qui décrit les approches courantes utilisées par les experts en exploration de données. Il s’agit de l’un des modèles d’analyse les plus utilisés.*
- <def-of>Evènement</def-of> : *C’est une observation (enregistrement), élément d'information qui est utilisé pour entraîner ou évaluer un modèle de prédiction.*
- <def-of>OneR (One-Rule)</def-of> : *Un algorithme simple de classification basé sur une seule règle, qui choisit la variable la plus prédictive (le champ dominant) pour faire des prédictions.*
## Problématiques
1. Comment fonctionne un classifieur Naïve Bayes ?
1. Comment utiliser Naïve Bayes ?
1. Quelles sont les avantages et les limites de Naïve Bayes ?
## Hypothèses
- <u>Naîve Bayes est sous-optimales pour des données ou il existe une forte dépendence entre les variables</u> <h-t/>
- *Plus la dépendance est grande, moins la précision est grande*
- <u>?</u> <h-t/> : *!;*
- <u>?</u> <h-t/> : *!;*
- <u>?</u> <h-t/> : *!;*
- <u>?</u> <h-t/> : *!;*
- <u>?</u> <h-t/> : *!;*
- <u>?</u> <h-t/> : *!;*
- <u>?</u> <h-t/> : *!;*
## Plan d'action
1. Investigation des ressources
6. Définitions des mots clefs;
7. Vérifier les hypothèses;
8. Répondre aux questions.
# RER
## Validation Croisée en ML
> En divisant l'ensemble de données nous pouvons:
> - Evaluer les performances du modèle
> - Déterminer le pouvoir prédictif du modèle
## Principales différences des apprentissages
| Critère | Apprentissage Supervisé | Apprentissage Non Supervisé | Apprentissage par Renforcement |
| --------------------------------| ----------------------------- | ----------------------------- | ------------------------------- |
| **Données d'entraînement** | Données étiquetées | Données non étiquetées | Interaction avec l'environnement |
| **Objectif principal** | Prédire les sorties | Identifier des structures | Maximiser la récompense cumulée |
| **Exemples d'applications** | Classification, régression | Clustering, réduction de dimension | Jeux, robotique, gestion de ressources |
| **Évaluation du modèle** | Comparaison avec les étiquettes | Évaluation de la structure des données | Maximisation de la récompense |
| **Supervision des données** | Étiquettes nécessaires | Aucune étiquette requise | Récompenses du système |
| **Exemples d'algorithmes** | SVM, réseaux de neurones | K-moyennes, PCA | Q-learning, méthodes de politique gradient |
| **Utilisation des prédictions** | Généralisation à de nouvelles données | Identification de modèles, recommandation | Séquence de décisions optimales |

> L’apprentissage profond automatise une grande partie de l’extraction des fonctionnalités du processus, éliminant ainsi une partie de l’intervention humaine manuelle requise. Il permet également d’utiliser de grands ensembles de données, ce qui lui vaut le titre d’apprentissage automatique évolutif. Cette capacité est passionnante à l’heure où nous explorons plus en profondeur l’utilisation de données non structurées, d’autant plus que l’on estime que plus de 80 % des données d’une organisation sont non structurées. |
import 'package:admin/blocs/admin_bloc.dart';
import 'package:admin/configs/config.dart';
import 'package:admin/services/firebase_service.dart';
import 'package:admin/utils/content_preview.dart';
import 'package:admin/utils/dialog.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:line_icons/line_icons.dart';
import 'package:provider/provider.dart';
import '../models/category.dart';
class EditContent extends StatefulWidget {
final String? imageUrl, timestamp, category;
final int? loves;
const EditContent(
{Key? key,
required this.imageUrl,
this.timestamp,
this.loves,
this.category})
: super(key: key);
@override
State<EditContent> createState() => _EditContentState();
}
class _EditContentState extends State<EditContent> {
final FirebaseFirestore firestore = FirebaseFirestore.instance;
var formKey = GlobalKey<FormState>();
var imageUrlCtrl = TextEditingController();
var scaffoldKey = GlobalKey<ScaffoldState>();
bool updateStarted = false;
late Future _categories;
late String _selectedCategory;
String? _selectedImagePath;
Future _pickImage() async {
final ImagePicker picker = ImagePicker();
XFile? image = await picker.pickImage(
source: ImageSource.gallery);
if (image != null) {
setState(() {
_selectedImagePath = image.path;
imageUrlCtrl.text = image.path;
});
}
}
Future<String?> _uploadToFirebaseHosting() async {
//return download link
String? imageUrl;
Uint8List imageData = await XFile(_selectedImagePath!).readAsBytes();
final Reference storageReference = FirebaseStorage.instance.ref().child('images/${_selectedImagePath.hashCode}.png');
final SettableMetadata metadata = SettableMetadata(contentType: 'image/png');
final UploadTask uploadTask = storageReference.putData(imageData, metadata);
await uploadTask.whenComplete(() async {
imageUrl = await storageReference.getDownloadURL();
});
return imageUrl;
}
void handleUpdate() async {
String? userRole = context.read<AdminBloc>().userRole;
final bool hasAccess = userRole != null && userRole == 'admin';
if (formKey.currentState!.validate()) {
formKey.currentState!.save();
if (!hasAccess) {
openDialog(context, Config.testingDialog, '');
} else {
if(_selectedImagePath != null){
//local image
setState(()=> updateStarted = true);
await _uploadToFirebaseHosting().then((String? imageUrl){
if(imageUrl != null){
setState(()=> imageUrlCtrl.text = imageUrl);
_updateProcedure();
}else{
setState(() {
_selectedImagePath = null;
imageUrlCtrl.clear();
updateStarted = false;
});
}
});
}else{
//network image
setState(()=> updateStarted = true);
_updateProcedure();
}
}
}
}
Future _updateProcedure () async{
await updateDatabase().then((value){
setState(() => updateStarted = false);
openDialog(context, 'Updated Successfully', '');
});
}
void handlePreview() async {
if (formKey.currentState!.validate()) {
formKey.currentState!.save();
await showContentPreview(context, imageUrlCtrl.text);
}
}
Future updateDatabase() async {
final DocumentReference ref = firestore.collection('contents').doc(widget.timestamp);
await ref.update({'image url': imageUrlCtrl.text, 'category': _selectedCategory});
}
@override
void initState() {
super.initState();
imageUrlCtrl.text = widget.imageUrl!;
_selectedCategory = widget.category!;
_categories = FirebaseService().getCategories();
}
@override
Widget build(BuildContext context) {
double w = MediaQuery.of(context).size.width;
double h = MediaQuery.of(context).size.height;
return Scaffold(
appBar: PreferredSize(
preferredSize: const Size.fromHeight(60),
child: Center(
child: AppBar(
elevation: 1,
title: const Text('Edit Content Data'),
actions: <Widget>[
Container(
margin: const EdgeInsets.all(8),
padding: const EdgeInsets.only(left: 10, right: 10),
decoration: BoxDecoration(
color: Colors.deepPurpleAccent,
borderRadius: BorderRadius.circular(25),
),
child: TextButton.icon(
style: ButtonStyle(
shape: MaterialStateProperty.resolveWith((states) =>
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25)))),
icon: const Icon(
LineIcons.eye,
color: Colors.white,
size: 20,
),
label: const Text(
'Preview',
style: TextStyle(
fontWeight: FontWeight.w400,
color: Colors.white,
fontSize: 16),
),
onPressed: () {
handlePreview();
},
),
),
const SizedBox(
width: 20,
)
],
),
),
),
key: scaffoldKey,
body: Container(
margin: const EdgeInsets.only(left: 30, right: 30, top: 30),
padding: EdgeInsets.only(
left: w * 0.05,
right: w * 0.20,
),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(0),
boxShadow: <BoxShadow>[
BoxShadow(
color: Colors.grey[300]!, blurRadius: 10, offset: const Offset(3, 3))
],
),
child: Form(
key: formKey,
child: ListView(
children: <Widget>[
SizedBox(
height: h * 0.10,
),
const Text(
'Edit Content',
style: TextStyle(fontSize: 30, fontWeight: FontWeight.w800),
),
const SizedBox(
height: 40,
),
FutureBuilder(
future: _categories,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
List<Category> categories = snapshot.data;
return categoryDropdown(categories);
}
return const Center(child: CircularProgressIndicator());
},
),
const SizedBox(
height: 25,
),
TextFormField(
controller: imageUrlCtrl,
validator: (value) {
if (value!.isEmpty) return 'Value is empty';
return null;
},
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5)),
hintText: 'Enter Image Url or Select Image',
suffixIcon: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.close),
onPressed: () {
imageUrlCtrl.clear();
setState(() {
_selectedImagePath = null;
});
},
),
IconButton(
tooltip: 'Select Image',
icon: const Icon(Icons.image_outlined),
onPressed: () => _pickImage(),
),
],
),
),
),
const SizedBox(
height: 100,
),
Container(
color: Colors.deepPurpleAccent,
height: 45,
child: updateStarted == true
? const Center(
child: SizedBox(
height: 35,
width: 35,
child: CircularProgressIndicator()),
)
: TextButton(
child: const Text(
'Update Data',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w600),
),
onPressed: () {
handleUpdate();
})),
const SizedBox(
height: 200,
),
],
)),
),
);
}
Widget categoryDropdown(List<Category> categories) {
return Container(
height: 50,
padding: const EdgeInsets.only(left: 15, right: 15),
decoration: BoxDecoration(
color: Colors.grey[200],
border: Border.all(color: Colors.grey[300]!),
borderRadius: BorderRadius.circular(30)),
child: DropdownButtonFormField(
itemHeight: 50,
decoration: const InputDecoration(border: InputBorder.none),
onChanged: (dynamic value) {
setState(() {
_selectedCategory = value;
});
},
value: _selectedCategory,
hint: const Text('Select Category'),
items: categories.map((f) {
return DropdownMenuItem(
value: f.name,
child: Text(f.name!),
);
}).toList()));
}
} |
const express = require('express');
const winston = require('winston');
const app = express();
const port = 3000;
// Winston logger configuration
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
defaultMeta: { service: 'calculator-microservice' },
transports: [
new winston.transports.Console({
format: winston.format.simple(),
}),
new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
new winston.transports.File({ filename: 'logs/combined.log' }),
],
});
// Middleware to log requests
app.use((req, res, next) => {
logger.log({
level: 'info',
message: `Received ${req.method} request for ${req.url} from ${req.ip}`,
});
next();
});
// Addition endpoint
app.get('/add', (req, res) => {
const num1 = parseFloat(req.query.num1);
const num2 = parseFloat(req.query.num2);
if (isNaN(num1) || isNaN(num2)) {
logger.log({
level: 'error',
message: 'Invalid input parameters for addition',
});
res.status(400).send('Invalid input parameters for addition');
} else {
const result = num1 + num2;
res.send(`Result: ${result}`);
}
});
// Subtraction endpoint
app.get('/subtract', (req, res) => {
const num1 = parseFloat(req.query.num1);
const num2 = parseFloat(req.query.num2);
if (isNaN(num1) || isNaN(num2)) {
logger.log({
level: 'error',
message: 'Invalid input parameters for subtraction',
});
res.status(400).send('Invalid input parameters for subtraction');
} else {
const result = num1 - num2;
res.send(`Result: ${result}`);
}
});
// Multiplication endpoint
app.get('/multiply', (req, res) => {
const num1 = parseFloat(req.query.num1);
const num2 = parseFloat(req.query.num2);
if (isNaN(num1) || isNaN(num2)) {
logger.log({
level: 'error',
message: 'Invalid input parameters for multiplication',
});
res.status(400).send('Invalid input parameters for multiplication');
} else {
const result = num1 * num2;
res.send(`Result: ${result}`);
}
});
// Division endpoint
app.get('/divide', (req, res) => {
const num1 = parseFloat(req.query.num1);
const num2 = parseFloat(req.query.num2);
if (isNaN(num1) || isNaN num2 || num2 === 0) {
logger.log({
level: 'error',
message: 'Invalid input parameters for division',
});
res.status(400).send('Invalid input parameters for division');
} else {
const result = num1 / num2;
res.send(`Result: ${result}`);
}
});
// Exponentiation endpoint
app.get('/exponentiate', (req, res) => {
const base = parseFloat(req.query.base);
const exponent = parseFloat(req.query.exponent);
if (isNaN(base) || isNaN(exponent)) {
logger.log({
level: 'error',
message: 'Invalid input parameters for exponentiation',
});
res.status(400).send('Invalid input parameters for exponentiation');
} else {
const result = Math.pow(base, exponent);
res.send(`Result: ${result}`);
}
});
// Square root endpoint
app.get('/squareroot', (req, res) => {
const num = parseFloat(req.query.num);
if (isNaN(num) || num < 0) {
logger.log({
level: 'error',
message: 'Invalid input parameter for square root',
});
res.status(400).send('Invalid input parameter for square root');
} else {
const result = Math.sqrt(num);
res.send(`Result: ${result}`);
}
});
// Modulo endpoint
app.get('/modulo', (req, res) => {
const dividend = parseFloat(req.query.dividend);
const divisor = parsefloat(req.query.divisor);
if (isNaN(dividend) || isNaN(divisor) || divisor === 0) {
logger.log({
level: 'error',
message: 'Invalid input parameters for modulo operation',
});
res.status(400).send('Invalid input parameters for modulo operation');
} else {
const result = dividend % divisor;
res.send(`Result: ${result}`);
}
});
// Absolute value endpoint
app.get('/abs', (req, res) => {
const num = parseFloat(req.query.num);
if (isNaN(num)) {
logger.log({
level: 'error',
message: 'Invalid input parameter for absolute value',
});
res.status(400).send('Invalid input parameter for absolute value');
} else {
const result = Math.abs(num);
res.send(`Result: ${result}`);
}
});
// Health check endpoint
app.get('/health', (req, res) => {
res.status(200).json({ status: 'healthy' });
});
// Root path handling
app.get('/', (req, res) => {
res.send('Welcome to the Advanced Arithmetic Operations API. Use /add, /subtract, /multiply, /divide, /exponentiate, /squareroot, /modulo endpoints to perform arithmetic operations.');
});
// Error handling middleware
app.use((err, req, res, next) => {
logger.log({
level: 'error',
message: err.message,
});
res.status(500).send('Internal Server Error');
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
}); |
import 'package:chat_app/helper/constants.dart';
import 'package:chat_app/helper/helperfunctions.dart';
import 'package:chat_app/services/auth.dart';
import 'package:chat_app/services/database.dart';
import 'package:chat_app/widgets/widget.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:chat_app/views/chatRoomScreen.dart';
class SignIn extends StatefulWidget {
final Function toggle;
SignIn(this.toggle);
@override
_SignInState createState() => _SignInState();
}
class _SignInState extends State<SignIn> {
AuthMethods authMethods = new AuthMethods();
DatabaseMethods dataBaseMethods = new DatabaseMethods();
final formKey = GlobalKey<FormState>();
TextEditingController emailTextEditingController = new TextEditingController();
TextEditingController passwordTextEditingController = new TextEditingController();
bool isLoading = false;
bool showPassword = false;
QuerySnapshot snapShotUserInfo;
// Sing in method
signIn() {
if(formKey.currentState.validate()) {
setState(() {
isLoading = true;
});
HelperFunctions.saveUserEmailSharedPreference(emailTextEditingController.text);
dataBaseMethods.getUserByEmail(emailTextEditingController.text)
.then((value) {
snapShotUserInfo = value;
HelperFunctions
.saveUserNameSharedPreference(snapShotUserInfo.documents[0].data["name"]);
});
authMethods.signInWithEmailAndPassword
(emailTextEditingController.text, passwordTextEditingController.text).then((value) {
if(value != null) {
HelperFunctions.saveUserLoggedInSharedPreference(true);
Navigator.pushReplacement(context, MaterialPageRoute(
builder: (context) => ChatRoom()
));
}
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: appBarMain(),
body: isLoading ?
Container(
child: Center(child: CircularProgressIndicator()),
) :
SingleChildScrollView(
child: Container(
height: MediaQuery.of(context).size.height - 100,
alignment: Alignment.bottomCenter,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Form(
key: formKey,
child: Column(
children: [
TextFormField(
validator: (email) {
return RegExp(
r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+"
).hasMatch(email) ?
null :
"Please provide a valid email id";
},
controller: emailTextEditingController,
style: simpleStyle(),
decoration: textFieldInputDecoration("email")
),
TextFormField(
obscureText: showPassword == true ? false : true,
validator: (password){
return password.length > 6 ?
null :
"Please provide a password which has more than 6 characters";
},
controller: passwordTextEditingController,
style: simpleStyle(),
decoration: textFieldInputDecoration("password")
),
],
),
),
SizedBox(height: 8,),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
alignment: Alignment.centerLeft,
child: GestureDetector(
onTap: () {
setState(() {
showPassword = !showPassword;
});
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: showPassword ?
Text("Hide password", style: TextStyle(fontSize: 13, color: Colors.white38),) :
Text("Show password", style: TextStyle(fontSize: 13, color: Colors.white38),),
),
),
),
Container(
alignment: Alignment.centerRight,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Text("Forgot Password?", style: simpleStyle(),),
),
),
],
),
SizedBox(height: 16,),
GestureDetector(
onTap: () {
signIn();
},
child: Container(
alignment: Alignment.center,
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.symmetric(vertical: 20),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xff007EF4), Color(0xff2A75BC)]
),
borderRadius: BorderRadius.circular(30)
),
child: Text("Sign In", style: mediumStyle(Colors.white),),
),
),
SizedBox(height: 16,),
Container(
alignment: Alignment.center,
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.symmetric(vertical: 20),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(30)
),
child: Text("Sign In with Google", style: mediumStyle(Colors.black),)
),
SizedBox(height: 16,),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Don't have an account? ", style: mediumStyle(Colors.white)),
GestureDetector(
onTap: () {
widget.toggle();
},
child: Container(
padding: EdgeInsets.symmetric(vertical: 8),
child: Text("Register Now", style: TextStyle(
color: Colors.white,
fontSize: 17,
decoration: TextDecoration.underline
)),
),
)
],
),
SizedBox(height: 50,)
],
),
),
),
),
);
}
} |
package data
import (
"project-common/encrypts"
"project-common/tms"
"project-project/pkg/model"
)
// Project 数据库类型
type Project struct {
Id int64
Cover string
Name string
Description string
AccessControlType int
WhiteList string
Sort int
Deleted int
TemplateCode int64
Schedule float64
CreateTime int64
OrganizationCode int64
DeletedTime string
Private int
Prefix string
OpenPrefix int
Archive int
ArchiveTime int64
OpenBeginTime int
OpenTaskPrivate int
TaskBoardTheme string
BeginTime int64
EndTime int64
AutoUpdateSchedule int
}
func (p *Project) TableName() string {
return "ms_project"
}
func ToProjectMap(list []*Project) map[int64]*Project {
m := make(map[int64]*Project, len(list))
for _, v := range list {
m[v.Id] = v
}
return m
}
// ProjectMember 数据库类型
type ProjectMember struct {
Id int64
ProjectCode int64
MemberCode int64
JoinTime int64
IsOwner int64
Authorize int64
}
func (*ProjectMember) TableName() string {
return "ms_project_member"
}
// ProjectAndMember 响应类型 project && Member 结果汇总
type ProjectAndMember struct {
Project
ProjectCode int64
MemberCode int64
JoinTime int64
IsOwner int64
Authorize int64
OwnerName string
Collected int
}
func (m *ProjectAndMember) GetAccessControlType() string {
if m.AccessControlType == 0 {
return "open"
}
if m.AccessControlType == 1 {
return "private"
}
if m.AccessControlType == 2 {
return "custom"
}
return ""
}
func (m *Project) GetAccessControlType() string {
if m.AccessControlType == 0 {
return "open"
}
if m.AccessControlType == 1 {
return "private"
}
if m.AccessControlType == 2 {
return "custom"
}
return ""
}
func ToMap(orgs []*ProjectAndMember) map[int64]*ProjectAndMember {
m := make(map[int64]*ProjectAndMember)
for _, v := range orgs {
m[v.Id] = v
}
return m
}
// ProjectCollection 数据库struct
type ProjectCollection struct {
Id int64
ProjectCode int64
MemberCode int64
CreateTime int64
}
func (*ProjectCollection) TableName() string {
return "ms_project_collection"
}
// ProjectTemplate 数据库struct
type ProjectTemplate struct {
Id int
Name string
Description string
Sort int
CreateTime int64
OrganizationCode int64
Cover string
MemberCode int64
IsSystem int
}
func (*ProjectTemplate) TableName() string {
return "ms_project_template"
}
// ProjectTemplateAll 响应类型
type ProjectTemplateAll struct {
Id int
Name string
Description string
Sort int
CreateTime string
OrganizationCode string
Cover string
MemberCode string
IsSystem int
TaskStages []*TaskStagesOnlyName
Code string
}
// Convert : 将生成的 TaskStagesOnlyName 以及数据库里的 ProjectTemplate 结构转换为 ProjectTemplateAll
func (pt *ProjectTemplate) Convert(taskStages []*TaskStagesOnlyName) *ProjectTemplateAll {
organizationCode, _ := encrypts.EncryptInt64(pt.OrganizationCode, model.AESKey)
memberCode, _ := encrypts.EncryptInt64(pt.MemberCode, model.AESKey)
code, _ := encrypts.EncryptInt64(int64(pt.Id), model.AESKey)
pta := &ProjectTemplateAll{
Id: pt.Id,
Name: pt.Name,
Description: pt.Description,
Sort: pt.Sort,
CreateTime: tms.FormatByMill(pt.CreateTime),
OrganizationCode: organizationCode,
Cover: pt.Cover,
MemberCode: memberCode,
IsSystem: pt.IsSystem,
TaskStages: taskStages,
Code: code,
}
return pta
}
// ToProjectTemplateIds => ProjectTemplate 模板id列表
func ToProjectTemplateIds(pts []ProjectTemplate) []int {
var ids []int
for _, v := range pts {
ids = append(ids, v.Id)
}
return ids
}
//CREATE TABLE `ms_project` (
//`id` bigint(0) UNSIGNED NOT NULL AUTO_INCREMENT,
//`cover` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '封面',
//`name` varchar(90) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '名称',
//`description` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '描述',
//`access_control_type` tinyint(0) NULL DEFAULT 0 COMMENT '访问控制l类型',
//`white_list` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '可以访问项目的权限组(白名单)',
//`order` int(0) UNSIGNED NULL DEFAULT 0 COMMENT '排序',
//`deleted` tinyint(1) NULL DEFAULT 0 COMMENT '删除标记',
//`template_code` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '项目类型',
//`schedule` double(5, 2) NULL DEFAULT 0.00 COMMENT '进度',
//`create_time` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建时间',
//`organization_code` bigint(0) NULL DEFAULT NULL COMMENT '组织id',
//`deleted_time` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '删除时间',
//`private` tinyint(1) NULL DEFAULT 1 COMMENT '是否私有',
//`prefix` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '项目前缀',
//`open_prefix` tinyint(1) NULL DEFAULT 0 COMMENT '是否开启项目前缀',
//`archive` tinyint(1) NULL DEFAULT 0 COMMENT '是否归档',
//`archive_time` bigint(0) NULL DEFAULT NULL COMMENT '归档时间',
//`open_begin_time` tinyint(1) NULL DEFAULT 0 COMMENT '是否开启任务开始时间',
//`open_task_private` tinyint(1) NULL DEFAULT 0 COMMENT '是否开启新任务默认开启隐私模式',
//`task_board_theme` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT 'default' COMMENT '看板风格',
//`begin_time` bigint(0) NULL DEFAULT NULL COMMENT '项目开始日期',
//`end_time` bigint(0) NULL DEFAULT NULL COMMENT '项目截止日期',
//`auto_update_schedule` tinyint(1) NULL DEFAULT 0 COMMENT '自动更新项目进度',
//PRIMARY KEY (`id`) USING BTREE,
//INDEX `project`(`order`) USING BTREE
//) ENGINE = InnoDB AUTO_INCREMENT = 13043 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '项目表' ROW_FORMAT = COMPACT;
//CREATE TABLE `ms_project_member` (
//`id` bigint(0) NOT NULL AUTO_INCREMENT,
//`project_code` bigint(0) NULL DEFAULT NULL COMMENT '项目id',
//`member_code` bigint(0) NULL DEFAULT NULL COMMENT '成员id',
//`join_time` bigint(0) NULL DEFAULT NULL COMMENT '加入时间',
//`is_owner` bigint(0) NULL DEFAULT 0 COMMENT '拥有者',
//`authorize` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '角色',
//PRIMARY KEY (`id`) USING BTREE,
//UNIQUE INDEX `unique`(`project_code`, `member_code`) USING BTREE
//) ENGINE = InnoDB AUTO_INCREMENT = 37 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '项目-成员表' ROW_FORMAT = COMPACT; |
package neural_network.functions;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
/** A class to represent the transfer function of a neural network, which
* creates a linear combination of {@code weights} from {@code values} of
* {@code Neurons}.
*
*/
public class TransferFunction implements Activator<List<Double>> {
private final List<Double> weights = new ArrayList<>();
private double bias = Double.NaN;
/** Implementation of the transfer function, which returns a sum of
* w_ij * o_j where w_ij are weights and o_j are values of {@code Neurons}
* in the left {@code Layer}. Note that we must call {@code bindWeights}
* before this function.
*
* @param o A vector of values from {@code Neurons} in the left {@code Layer}.
* @throws IllegalStateException This method should not be called if
* weights or bias have not been bound.
* @return The output of the transfer function.
*/
@Override
public double call(List<Double> o) {
int o_size = o.size();
// weights must contain all weights of edges connected to the previous
// layer from one right neuron
if (! (weights.size() == o_size)) {
throw new IllegalStateException("weights must have same size as o," +
"check that weights have been bound (%d != %d)"
.formatted(weights.size(), o_size));
} else if (Double.isNaN(bias)) {
throw new IllegalStateException("bias has not yet been bound, cannot" +
"call this method");
}
double weightedSum = IntStream
.iterate(0, j -> j < o_size, j -> j + 1)
.mapToDouble(j -> o.get(j) * weights.get(j))
.sum();
double transferValue = weightedSum + bias;
// Reset the weights and bias for next time
weights.clear();
bias = Double.NaN;
return transferValue;
}
/** Gradient of the transfer function.
*
* @param o A vector of values from {@code Neurons} in the left
* * {@code Layer}.
* @return Gradient of transfer function w.r.t weights and bias.
*/
@Override
public List<Double> gradient(List<Double> o) {
// We need to add the bias gradient
o.add(0.0);
return o;
}
/** Binds {@code weights} from the {@code Edges} to the
* {@code TransferFunction}.
*
* @param weights The new weights to be bound.
*/
public void bindWeights(List<Double> weights) {
this.weights.clear();
this.weights.addAll(weights);
}
/** Binds the {@code bias} from the right {@code Neuron} to the
* {@code TransferFunction}.
*
* @param bias The new bias to be bound.
*/
public void bindBias(double bias) {
this.bias = bias;
}
} |
import numpy as np
import torch
from torch import nn
import pdb
from progress import Progress, Silent
from helpers import (
cosine_beta_schedule,
extract,
apply_conditioning,
Losses,
)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class GaussianDiffusion_jayaram(nn.Module):
def __init__(self, model, horizon, observation_dim, action_dim, device, n_timesteps=256,
loss_type='l2', clip_denoised=True, predict_epsilon=False,
action_weight=1.0, loss_discount=1.0, loss_weights=None,
):
super().__init__()
self.horizon = horizon
self.model = model #this is temporalUNET, get this from model.pkl file
self.observation_dim = observation_dim
self.action_dim = 0 #lets not consider action for now
self.transition_dim = observation_dim + action_dim
betas = cosine_beta_schedule(n_timesteps)
alphas = 1. - betas
alphas_cumprod = torch.cumprod(alphas, axis=0)
alphas_cumprod_prev = torch.cat([torch.ones(1), alphas_cumprod[:-1]])
self.n_timesteps = int(n_timesteps)
self.clip_denoised = clip_denoised
self.predict_epsilon = predict_epsilon
self.register_buffer('betas', betas)
self.register_buffer('alphas_cumprod', alphas_cumprod)
self.register_buffer('alphas_cumprod_prev', alphas_cumprod_prev)
# calculations for diffusion q(x_t | x_{t-1}) and others
self.register_buffer('sqrt_alphas_cumprod', torch.sqrt(alphas_cumprod))
self.register_buffer('sqrt_one_minus_alphas_cumprod', torch.sqrt(1. - alphas_cumprod))
self.register_buffer('log_one_minus_alphas_cumprod', torch.log(1. - alphas_cumprod))
self.register_buffer('sqrt_recip_alphas_cumprod', torch.sqrt(1. / alphas_cumprod))
self.register_buffer('sqrt_recipm1_alphas_cumprod', torch.sqrt(1. / alphas_cumprod - 1))
# calculations for posterior q(x_{t-1} | x_t, x_0)
posterior_variance = betas * (1. - alphas_cumprod_prev) / (1. - alphas_cumprod)
self.register_buffer('posterior_variance', posterior_variance)
## log calculation clipped because the posterior variance
## is 0 at the beginning of the diffusion chain
self.register_buffer('posterior_log_variance_clipped',
torch.log(torch.clamp(posterior_variance, min=1e-20)))
self.register_buffer('posterior_mean_coef1',
betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))
self.register_buffer('posterior_mean_coef2',
(1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod))
## get loss coefficients and initialize objective
loss_weights = self.get_loss_weights(action_weight, loss_discount, loss_weights).to(device)
self.loss_fn = Losses[loss_type](loss_weights, self.action_dim)
def get_loss_weights(self, action_weight, discount, weights_dict):
'''
sets loss coefficients for trajectory
action_weight : float
coefficient on first action loss
discount : float
multiplies t^th timestep of trajectory loss by discount**t
weights_dict : dict
{ i: c } multiplies dimension i of observation loss by c
'''
self.action_weight = action_weight
dim_weights = torch.ones(self.transition_dim, dtype=torch.float32)
## set loss coefficients for dimensions of observation
if weights_dict is None: weights_dict = {}
for ind, w in weights_dict.items():
dim_weights[self.action_dim + ind] *= w
## decay loss with trajectory timestep: discount**t
discounts = discount ** torch.arange(self.horizon, dtype=torch.float)
discounts = discounts / discounts.mean()
loss_weights = torch.einsum('h,t->ht', discounts, dim_weights)
## manually set a0 weight
loss_weights[0, :self.action_dim] = action_weight
return loss_weights
#------------------------------------------ sampling ------------------------------------------#
def predict_start_from_noise(self, x_t, t, noise):
'''
if self.predict_epsilon, model output is (scaled) noise;
otherwise, model predicts x0 directly
'''
if self.predict_epsilon:
return (
extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
extract(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
)
else:
return noise
def q_posterior(self, x_start, x_t, t):
posterior_mean = (
extract(self.posterior_mean_coef1, t, x_t.shape) * x_start +
extract(self.posterior_mean_coef2, t, x_t.shape) * x_t
)
posterior_variance = extract(self.posterior_variance, t, x_t.shape)
posterior_log_variance_clipped = extract(self.posterior_log_variance_clipped, t, x_t.shape)
return posterior_mean, posterior_variance, posterior_log_variance_clipped
def p_mean_variance(self, x, cond, t):
x_recon = self.predict_start_from_noise(x, t=t, noise=self.model(x, cond, t))
if self.clip_denoised:
x_recon.clamp_(-1., 1.)
else:
assert RuntimeError()
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(
x_start=x_recon, x_t=x, t=t)
return model_mean, posterior_variance, posterior_log_variance
@torch.no_grad()
def p_sample(self, x, cond, t):
b, *_, device = *x.shape, x.device
model_mean, _, model_log_variance = self.p_mean_variance(x=x, cond=cond, t=t)
noise = torch.randn_like(x)
# no noise when t == 0
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
@torch.no_grad()
def p_sample_loop(self, shape, cond, verbose=True, return_diffusion=False):
device = self.betas.device
batch_size = shape[0]
x = torch.randn(shape, device=device)
x = apply_conditioning(x, cond, self.action_dim)
if return_diffusion: diffusion = [x]
progress = Progress(self.n_timesteps) if verbose else Silent()
for i in reversed(range(0, self.n_timesteps)):
timesteps = torch.full((batch_size,), i, device=device, dtype=torch.long)
x = self.p_sample(x, cond, timesteps)
x = apply_conditioning(x, cond, self.action_dim)
progress.update({'t': i})
if return_diffusion: diffusion.append(x)
progress.close()
if return_diffusion:
return x, torch.stack(diffusion, dim=1)
else:
return x
@torch.no_grad()
def conditional_sample(self, cond, *args, horizon=None, **kwargs):
'''
conditions : [ (time, state), ... ]
'''
device = self.betas.device
batch_size = len(cond[0])
horizon = horizon or self.horizon
shape = (batch_size, horizon, self.transition_dim)
return self.p_sample_loop(shape, cond, *args, **kwargs)
#------------------------------------------ training ------------------------------------------#
def q_sample(self, x_start, t, noise=None):
if noise is None:
noise = torch.randn_like(x_start)
sample = (
extract(self.sqrt_alphas_cumprod.to(device), t, x_start.shape) * x_start +
extract(self.sqrt_one_minus_alphas_cumprod.to(device), t, x_start.shape) * noise
)
return sample
def p_losses(self, x_start, cond, t): #x_start: [32, 384, 6] , cond: dict of states (0, 383) of len 4, t is random timestep in entire horizon (say 155)
#here x_start means start timestep of forward diffusion (not the start state of agent in the current path)
noise = torch.randn_like(x_start) #[32, 384, 6] #gaussian dist
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) #[32, 384, 6] -- forward pass of diffusion
x_noisy = apply_conditioning(x_noisy, cond, self.action_dim) #fix x_noisy[0][0], x_noisy[0][383] with start and goal points i.e cond[0], cond[383]
x_recon = self.model(x_noisy, cond, t) #[32, 384, 6] using Temporal UNET (error: expected double but got float)
x_recon = apply_conditioning(x_recon, cond, self.action_dim)
assert noise.shape == x_recon.shape
if self.predict_epsilon:
loss = self.loss_fn(x_recon, noise)
# loss, info = self.loss_fn(x_recon, noise)
else:
loss = self.loss_fn(x_recon, x_start)
# loss, info = self.loss_fn(x_recon, x_start)
return loss
# return loss, info
def loss(self, x, *args): #x.shape: (b, 384, 6) , cond : batch[1], cond[0].shape: (b, 4) and cond[1].shape: (b, 4)
batch_size = len(x)
t = torch.randint(0, self.n_timesteps, (batch_size,), device=x.device).long() #choose a random timestep uniformly in reverse diffusion process
return self.p_losses(x, *args, t)
def forward(self, cond, *args, **kwargs):
return self.conditional_sample(cond=cond, *args, **kwargs)
class ValueDiffusion_jayaram(GaussianDiffusion_jayaram):
def p_losses(self, x_start, cond, target, t): #target is scalar
noise = torch.randn_like(x_start) #torch.Size([32, 4, 23])
#target shape: (32, 1)
#cond shape: (32, 17)
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) #forward diffusion process, compute x_t from x_0 for each sample in batch based on t (for that sample)
x_noisy = apply_conditioning(x_noisy, cond, self.action_dim)
pred = self.model(x_noisy, cond, t).view(-1) #scalars, so this value fn predicts rewards/values from noisy trajectories. Each traj shape: (4, 23), it has info of both (a, s)
loss = nn.MSELoss()(pred, target)
return loss
def forward(self, x, cond, t):
return self.model(x, cond, t) |
//! Configure tracing subscribers for Arti
use anyhow::{anyhow, Context, Result};
use derive_builder::Builder;
use educe::Educe;
use fs_mistrust::Mistrust;
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::str::FromStr;
use tor_config::impl_standard_builder;
use tor_config::{define_list_builder_accessors, define_list_builder_helper};
use tor_config::{CfgPath, ConfigBuildError};
use tor_error::warn_report;
use tracing::{error, Subscriber};
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::prelude::*;
use tracing_subscriber::{filter::Targets, fmt, registry, Layer};
mod time;
/// Structure to hold our logging configuration options
#[derive(Debug, Clone, Builder, Eq, PartialEq)]
#[non_exhaustive] // TODO(nickm) remove public elements when I revise this.
#[builder(build_fn(error = "ConfigBuildError"))]
#[builder(derive(Debug, Serialize, Deserialize))]
pub struct LoggingConfig {
/// Filtering directives that determine tracing levels as described at
/// <https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/targets/struct.Targets.html#impl-FromStr>
///
/// You can override this setting with the -l, --log-level command line parameter.
///
/// Example: "info,tor_proto::channel=trace"
#[builder(default = "default_console_filter()", setter(into, strip_option))]
console: Option<String>,
/// Filtering directives for the journald logger.
///
/// Only takes effect if Arti is built with the `journald` filter.
#[builder(
setter(into),
field(build = r#"tor_config::resolve_option(&self.journald, || None)"#)
)]
journald: Option<String>,
/// Configuration for one or more logfiles.
///
/// The default is not to log to any files.
#[builder_field_attr(serde(default))]
#[builder(sub_builder, setter(custom))]
files: LogfileListConfig,
/// If set to true, we disable safe logging on _all logs_, and store
/// potentially sensitive information at level `info` or higher.
///
/// This can be useful for debugging, but it increases the value of your
/// logs to an attacker. Do not turn this on in production unless you have
/// a good log rotation mechanism.
//
// TODO: Eventually we might want to make this more complex, and add a
// per-log mechanism to turn off unsafe logging. Alternatively, we might do
// that by extending the filter syntax implemented by `tracing` to have an
// "unsafe" flag on particular lines.
#[builder_field_attr(serde(default))]
#[builder(default)]
log_sensitive_information: bool,
/// An approximate granularity with which log times should be displayed.
///
/// This value controls every log time that arti outputs; it doesn't have any
/// effect on times written by other logging programs like `journald`.
///
/// We may round this value up for convenience: For example, if you say
/// "2.5s", we may treat it as if you had said "3s."
///
/// The default is "1s", or one second.
#[builder(default = "std::time::Duration::new(1,0)")]
#[builder_field_attr(serde(default, with = "humantime_serde::option"))]
time_granularity: std::time::Duration,
}
impl_standard_builder! { LoggingConfig }
/// Return a default tracing filter value for `logging.console`.
#[allow(clippy::unnecessary_wraps)]
fn default_console_filter() -> Option<String> {
Some("info".to_owned())
}
/// Local type alias, mostly helpful for derive_builder to DTRT
type LogfileListConfig = Vec<LogfileConfig>;
define_list_builder_helper! {
struct LogfileListConfigBuilder {
files: [LogfileConfigBuilder],
}
built: LogfileListConfig = files;
default = vec![];
}
define_list_builder_accessors! {
struct LoggingConfigBuilder {
pub files: [LogfileConfigBuilder],
}
}
/// Configuration information for an (optionally rotating) logfile.
#[derive(Debug, Builder, Clone, Eq, PartialEq)]
#[builder(derive(Debug, Serialize, Deserialize))]
#[builder(build_fn(error = "ConfigBuildError"))]
pub struct LogfileConfig {
/// How often to rotate the file?
#[builder(default)]
rotate: LogRotation,
/// Where to write the files?
path: CfgPath,
/// Filter to apply before writing
filter: String,
}
impl_standard_builder! { LogfileConfig: !Default }
/// How often to rotate a log file
#[derive(Debug, Clone, Educe, Serialize, Deserialize, Copy, Eq, PartialEq)]
#[educe(Default)]
#[non_exhaustive]
#[serde(rename_all = "lowercase")]
pub enum LogRotation {
/// Rotate logs daily
Daily,
/// Rotate logs hourly
Hourly,
/// Never rotate the log
#[educe(Default)]
Never,
}
/// As [`Targets::from_str`], but wrapped in an [`anyhow::Result`].
//
// (Note that we have to use `Targets`, not `EnvFilter`: see comment in
// `setup_logging()`.)
fn filt_from_str_verbose(s: &str, source: &str) -> Result<Targets> {
Targets::from_str(s).with_context(|| format!("in {}", source))
}
/// As filt_from_str_verbose, but treat an absent filter (or an empty string) as
/// None.
fn filt_from_opt_str(s: &Option<String>, source: &str) -> Result<Option<Targets>> {
Ok(match s {
Some(s) if !s.is_empty() => Some(filt_from_str_verbose(s, source)?),
_ => None,
})
}
/// Try to construct a tracing [`Layer`] for logging to stdout.
fn console_layer<S>(config: &LoggingConfig, cli: Option<&str>) -> Result<impl Layer<S>>
where
S: Subscriber + for<'span> tracing_subscriber::registry::LookupSpan<'span>,
{
let timer = time::new_formatter(config.time_granularity);
let filter = cli
.map(|s| filt_from_str_verbose(s, "--log-level command line parameter"))
.or_else(|| filt_from_opt_str(&config.console, "logging.console").transpose())
.unwrap_or_else(|| Ok(Targets::from_str("debug").expect("bad default")))?;
// We used to suppress safe-logging on the console, but we removed that
// feature: we cannot be certain that the console really is volatile. Even
// if isatty() returns true on the console, we can't be sure that the
// terminal isn't saving backlog to disk or something like that.
Ok(fmt::Layer::default().with_timer(timer).with_filter(filter))
}
/// Try to construct a tracing [`Layer`] for logging to journald, if one is
/// configured.
#[cfg(feature = "journald")]
fn journald_layer<S>(config: &LoggingConfig) -> Result<impl Layer<S>>
where
S: Subscriber + for<'span> tracing_subscriber::registry::LookupSpan<'span>,
{
if let Some(filter) = filt_from_opt_str(&config.journald, "logging.journald")? {
Ok(Some(tracing_journald::layer()?.with_filter(filter)))
} else {
// Fortunately, Option<Layer> implements Layer, so we can just return None here.
Ok(None)
}
}
/// Try to construct a non-blocking tracing [`Layer`] for writing data to an
/// optionally rotating logfile.
///
/// On success, return that layer, along with a WorkerGuard that needs to be
/// dropped when the program exits, to flush buffered messages.
fn logfile_layer<S>(
config: &LogfileConfig,
granularity: std::time::Duration,
mistrust: &Mistrust,
) -> Result<(impl Layer<S> + Send + Sync + Sized, WorkerGuard)>
where
S: Subscriber + for<'span> tracing_subscriber::registry::LookupSpan<'span> + Send + Sync,
{
use tracing_appender::{
non_blocking,
rolling::{RollingFileAppender, Rotation},
};
let timer = time::new_formatter(granularity);
let filter = filt_from_str_verbose(&config.filter, "logging.files.filter")?;
let rotation = match config.rotate {
LogRotation::Daily => Rotation::DAILY,
LogRotation::Hourly => Rotation::HOURLY,
_ => Rotation::NEVER,
};
let path = config.path.path()?;
let directory = path.parent().unwrap_or_else(|| Path::new("."));
mistrust.make_directory(directory)?;
let fname = path
.file_name()
.ok_or_else(|| anyhow!("No path for log file"))
.map(Path::new)?;
let appender = RollingFileAppender::new(rotation, directory, fname);
let (nonblocking, guard) = non_blocking(appender);
let layer = fmt::layer()
.with_writer(nonblocking)
.with_timer(timer)
.with_filter(filter);
Ok((layer, guard))
}
/// Try to construct a tracing [`Layer`] for all of the configured logfiles.
///
/// On success, return that layer along with a list of [`WorkerGuard`]s that
/// need to be dropped when the program exits.
fn logfile_layers<S>(
config: &LoggingConfig,
mistrust: &Mistrust,
) -> Result<(impl Layer<S>, Vec<WorkerGuard>)>
where
S: Subscriber + for<'span> tracing_subscriber::registry::LookupSpan<'span> + Send + Sync,
{
let mut guards = Vec::new();
if config.files.is_empty() {
// As above, we have Option<Layer> implements Layer, so we can return
// None in this case.
return Ok((None, guards));
}
let (layer, guard) = logfile_layer(&config.files[0], config.time_granularity, mistrust)?;
guards.push(guard);
// We have to use a dyn pointer here so we can build up linked list of
// arbitrary depth.
let mut layer: Box<dyn Layer<S> + Send + Sync + 'static> = Box::new(layer);
for logfile in &config.files[1..] {
let (new_layer, guard) = logfile_layer(logfile, config.time_granularity, mistrust)?;
layer = Box::new(layer.and_then(new_layer));
guards.push(guard);
}
Ok((Some(layer), guards))
}
/// Configure a panic handler to send everything to tracing, in addition to our
/// default panic behavior.
fn install_panic_handler() {
// TODO library support: There's a library called `tracing-panic` that
// provides a hook we could use instead, but that doesn't have backtrace
// support. We should consider using it if it gets backtrace support in the
// future. We should also keep an eye on `tracing` to see if it learns how
// to do this for us.
let default_handler = std::panic::take_hook();
std::panic::set_hook(Box::new(move |panic_info| {
// Note that if we were ever to _not_ call this handler,
// we would want to abort on nested panics and !can_unwind cases.
default_handler(panic_info);
// This statement is copied from stdlib.
let msg = match panic_info.payload().downcast_ref::<&'static str>() {
Some(s) => *s,
None => match panic_info.payload().downcast_ref::<String>() {
Some(s) => &s[..],
None => "Box<dyn Any>",
},
};
// TODO MSRV 1.65: std::backtrace::Backtrace is stable; maybe we should be using
// that instead?
let backtrace = backtrace::Backtrace::new();
match panic_info.location() {
Some(location) => error!("Panic at {}: {}\n{:?}", location, msg, backtrace),
None => error!("Panic at ???: {}\n{:?}", msg, backtrace),
};
}));
}
/// Opaque structure that gets dropped when the program is shutting down,
/// after logs are no longer needed. The `Drop` impl flushes buffered messages.
#[cfg_attr(feature = "experimental-api", visibility::make(pub))]
pub(crate) struct LogGuards {
/// The actual list of guards we're returning.
#[allow(unused)]
guards: Vec<WorkerGuard>,
/// A safelog guard, for use if we have decided to disable safe logging.
#[allow(unused)]
safelog_guard: Option<safelog::Guard>,
}
/// Set up logging.
///
/// Note that the returned LogGuard must be dropped precisely when the program
/// quits; they're used to ensure that all the log messages are flushed.
#[cfg_attr(feature = "experimental-api", visibility::make(pub))]
#[cfg_attr(docsrs, doc(cfg(feature = "experimental-api")))]
pub(crate) fn setup_logging(
config: &LoggingConfig,
mistrust: &Mistrust,
cli: Option<&str>,
) -> Result<LogGuards> {
// Important: We have to make sure that the individual layers we add here
// are not filters themselves. That means, for example, that we can't add
// an `EnvFilter` layer unless we want it to apply globally to _all_ layers.
//
// For a bit of discussion on the difference between per-layer filters and filters
// that apply to the entire registry, see
// https://docs.rs/tracing-subscriber/0.3.5/tracing_subscriber/layer/index.html#global-filtering
let registry = registry().with(console_layer(config, cli)?);
#[cfg(feature = "journald")]
let registry = registry.with(journald_layer(config)?);
let (layer, guards) = logfile_layers(config, mistrust)?;
let registry = registry.with(layer);
registry.init();
let safelog_guard = if config.log_sensitive_information {
match safelog::disable_safe_logging() {
Ok(guard) => Some(guard),
Err(e) => {
// We don't need to propagate this error; it isn't the end of
// the world if we were unable to disable safe logging.
warn_report!(e, "Unable to disable safe logging");
None
}
}
} else {
None
};
install_panic_handler();
Ok(LogGuards {
guards,
safelog_guard,
})
} |
import router from '../../router/router'
const app = {
namespaced: true,
state: {
routesTree: [], // 路由数据原始的关系树
menuList: [],
pageOpenedList: [{
title: '欢迎页demo',
name: 'home',
selected: true
}],
currentPath: [],
currentMenuOpenNames: [],
asyncRoutesCompleted: false, // 是否添加过动态路由数据
btnLimitedCodes: []
},
mutations: {
// 添加动态路由
updateAppRouter (state, routes) {
router.addRoutes(routes)
state.asyncRoutesCompleted = true
},
// 设置左侧菜单数据
setMenuList (state, menus) {
state.menuList = state.menuList.concat(menus)
},
// 保存路由数据原始的关系树
setRoutesTree (state, tree) {
state.routesTree = state.routesTree.concat(tree)
},
// 设置PageOpenedList数据
setPageOpenedList (state, params = null) {
// 设置前先读取本地保存的打开列表数据
state.pageOpenedList = sessionStorage.pageOpenedList
? JSON.parse(sessionStorage.pageOpenedList) : [{
title: '欢迎页demo',
name: 'home',
selected: true
}]
if (!params) {
return
}
if (params.index === -1) {
// 新打开一个页面
state.pageOpenedList.push({
title: params.route.meta.title,
name: params.route.name,
selected: false
})
params.index = state.pageOpenedList.length - 1
}
// 更新selected值
for (let i = 0; i < state.pageOpenedList.length; i++) {
if (params.index === i) {
state.pageOpenedList[i].selected = true
} else {
state.pageOpenedList[i].selected = false
}
}
// 更新下本地新的打开页面列表数据
sessionStorage.pageOpenedList = JSON.stringify(state.pageOpenedList)
},
// 移除PageOpenedList
removePageOpenedList (state, params = null) {
if (!params) {
return
}
if (typeof params.action === 'number') {
state.pageOpenedList.splice(params.action, 1)
} else {
state.pageOpenedList = [{
title: '欢迎页demo',
name: 'home',
selected: true
}]
if (params.action === 'closeOthers' && params.route.name !== 'home') {
state.pageOpenedList[0].selected = false
state.pageOpenedList.push({
title: params.route.meta.title,
name: params.route.name,
selected: true
})
}
}
// 更新下本地新的打开页面列表数据
sessionStorage.pageOpenedList = JSON.stringify(state.pageOpenedList)
},
// 设置当前header上面包屑路径
setCurrentPath (state, currentPathArr = []) {
console.log(state, currentPathArr)
state.currentPath = []
state.currentPath = state.currentPath.concat(currentPathArr)
},
// 设置当前左侧菜单的openNames属性
setCurrentMenuOpenNames (state, routeMatched) {
if (routeMatched.length === 0 || typeof routeMatched[0] === 'string') {
state.currentMenuOpenNames = routeMatched
} else {
state.currentMenuOpenNames = []
for (const menu of state.menuList) {
if (menu.name === routeMatched[0].name) {
state.currentMenuOpenNames.push(menu.name)
if (routeMatched[1] && routeMatched[1].meta.parentName) {
state.currentMenuOpenNames.push(routeMatched[1].meta.parentName)
}
break
}
}
}
},
closePage (state, params) {
// 移除fromName的tag
for (let i = 0; i < state.pageOpenedList.length; i++) {
if (state.pageOpenedList[i].name === params.fromName) {
state.pageOpenedList.splice(i, 1)
break
}
}
sessionStorage.pageOpenedList = JSON.stringify(state.pageOpenedList)
params.vm.$router.push({ name: params.toName })
},
// 保存权限码
setBtnLimitedCodes (state, codes) {
state.btnLimitedCodes = codes
}
}
}
export default app |
#
# Copyright EndlessOS Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Authors:
# Daniel Garcia <danigm@endlessos.org>
import os
import sqlite3
import shutil
import contextlib
import urllib.request
import json
from dataclasses import dataclass
from buildstream import Source, SourceError, utils, Consistency
STUDIO = 'https://kolibri-content.endlessos.org'
API = '/api/public/v1/channels/lookup/'
@dataclass
class SourceFile:
filename: str
path: str
dst: str
class KolibriChannelSource(Source):
def configure(self, node):
self.node_validate(node, ['token', 'id', 'version'] +
Source.COMMON_CONFIG_KEYS)
self.load_ref(node)
self.channel_id = self.node_get_member(node, str, 'id', None)
self.token = self.node_get_member(node, str, 'token', None)
if self.channel_id is None and self.token is None:
raise SourceError(f'{self}: Missing token or id')
self.version = self.node_get_member(node, int, 'version', 1)
def preflight(self):
pass
def get_unique_key(self):
return [self.channel_id, self.version]
def load_ref(self, node):
self.channel_id = self.node_get_member(node, str, 'id', None)
self.version = self.node_get_member(node, int, 'version', 1)
def get_ref(self):
if self.channel_id is None or self.version is None:
return None
return {
'id': self.channel_id,
'version': self.version,
}
def set_ref(self, ref, node):
node['id'] = self.channel_id = ref['id']
node['version'] = self.version = ref['version']
def track(self):
lookup = self.channel_id or self.token
studio_api = STUDIO + API + lookup
request = urllib.request.Request(studio_api)
request.add_header('Accept', '*/*')
request.add_header('User-Agent', 'BuildStream/1')
urlopen = urllib.request.urlopen(request)
payload = json.loads(urlopen.read())
channel = payload[0]
if not channel:
raise SourceError(
f'{self}: Cannot find any channel for {lookup}')
return channel
def _download_content(self, path, dst):
url = f'{STUDIO}/content{path}'
default_name = os.path.basename(url)
request = urllib.request.Request(url)
request.add_header('Accept', '*/*')
request.add_header('User-Agent', 'BuildStream/1')
urlopen = urllib.request.urlopen(request)
with contextlib.closing(urlopen) as response:
info = response.info()
filename = info.get_filename(default_name)
filename = os.path.basename(filename)
if not os.path.exists(dst):
os.makedirs(dst)
local_file = os.path.join(dst, filename)
with open(local_file, 'wb') as dest:
shutil.copyfileobj(response, dest)
def _get_channel_db(self, channel_id, version):
mirror = self._get_mirror_dir(channel_id, version)
databases = os.path.join(mirror, 'databases')
return os.path.join(databases, f'{channel_id}.sqlite3')
def _get_channel_files(self, channel_id, version):
files = []
mirror = self._get_mirror_dir(channel_id, version)
storage = os.path.join(mirror, 'storage')
with sqlite3.connect(self._get_channel_db(channel_id, version)) as db:
cur = db.cursor()
cur.execute('select id, extension from content_localfile')
for row in cur:
id = row[0]
filename = f'{id}.{row[1]}'
path = f'/storage/{id[0]}/{id[1]}/{filename}'
dst = os.path.join(storage, id[0], id[1])
files.append(SourceFile(filename=filename,
path=path,
dst=dst))
return files
def _fetch_db(self, channel_id, version):
mirror = self._get_mirror_dir(channel_id, version)
databases = os.path.join(mirror, 'databases')
if not os.path.isdir(databases):
os.makedirs(databases)
path = f'/databases/{channel_id}.sqlite3'
try:
self._download_content(path, databases)
except (urllib.error.URLError,
urllib.error.ContentTooShortError,
OSError) as e:
raise SourceError(f"{self}: Error mirroring {path}: {e}") from e
def _fetch_files(self, channel_id, version):
mirror = self._get_mirror_dir(channel_id, version)
storage = os.path.join(mirror, 'storage')
if not os.path.isdir(storage):
os.makedirs(storage)
files = self._get_channel_files(channel_id, version)
for f in files:
try:
self._download_content(f.path, f.dst)
except (urllib.error.URLError,
urllib.error.ContentTooShortError,
OSError) as e:
raise SourceError(f"{self}: Error mirroring {f.path}: {e}") from e
def fetch(self):
self._fetch_db(self.channel_id, self.version)
self._fetch_files(self.channel_id, self.version)
def _stage_db(self, directory, channel_id, version):
mirror = self._get_mirror_dir(channel_id, version)
databases = os.path.join(mirror, 'databases')
dbdir = os.path.join(directory, 'databases')
if not os.path.exists(dbdir):
os.makedirs(dbdir)
shutil.copy(self._get_channel_db(channel_id, version), dbdir)
def _stage_files(self, directory, channel_id, version):
mirror = self._get_mirror_dir(channel_id, version)
storage = os.path.join(mirror, 'storage')
for root, dirs, files in os.walk(storage):
for name in files:
file = os.path.join(storage, name[0], name[1], name)
dst = os.path.join(directory, 'storage', name[0], name[1])
if not os.path.exists(dst):
os.makedirs(dst)
shutil.copy(file, dst)
def stage(self, directory):
self._stage_db(directory, self.channel_id, self.version)
self._stage_files(directory, self.channel_id, self.version)
def get_consistency(self):
if self.channel_id is None or self.version is None:
return Consistency.INCONSISTENT
mirrordir = self._get_mirror_dir(self.channel_id, self.version)
if os.path.isdir(mirrordir):
return Consistency.CACHED
return Consistency.RESOLVED
def _get_mirror_dir(self, channel_id, channel_version):
return os.path.join(self.get_mirror_directory(),
utils.url_directory_name(self.name),
f'{channel_id}.{channel_version}')
def setup():
return KolibriChannelSource |
// Copyright 2022 Dynatrace LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package util
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
)
const ENV_KEY = "TEST_KEY"
func TestGetStringFromEnvWithDefault_UseEnvIfSet(t *testing.T) {
defer os.Unsetenv(ENV_KEY)
os.Setenv(ENV_KEY, "foo")
assert.Equal(t, GetStringFromEnvWithDefault(ENV_KEY, "bar"), "foo")
os.Setenv(ENV_KEY, "")
assert.Equal(t, GetStringFromEnvWithDefault(ENV_KEY, "bar"), "")
}
func TestGetStringFromEnvWithDefault_UseDefault(t *testing.T) {
assert.Equal(t, GetStringFromEnvWithDefault(ENV_KEY, "bar"), "bar")
assert.Equal(t, GetStringFromEnvWithDefault(ENV_KEY, ""), "")
}
func TestGetIntFromEnvWithDefault_UseEnvIfSet(t *testing.T) {
defer os.Unsetenv(ENV_KEY)
os.Setenv(ENV_KEY, "123")
assert.Equal(t, GetIntFromEnvWithDefault(ENV_KEY, 456), 123)
os.Setenv(ENV_KEY, "0")
assert.Equal(t, GetIntFromEnvWithDefault(ENV_KEY, 456), 0)
}
func TestGetIntFromEnvWithDefault_UseDefaultForInvalidValue(t *testing.T) {
defer os.Unsetenv(ENV_KEY)
os.Setenv(ENV_KEY, "foo")
assert.Equal(t, GetIntFromEnvWithDefault(ENV_KEY, 456), 456)
os.Setenv(ENV_KEY, "")
assert.Equal(t, GetIntFromEnvWithDefault(ENV_KEY, 456), 456)
}
func TestGetIntFromEnvWithDefault_UseDefault(t *testing.T) {
assert.Equal(t, GetIntFromEnvWithDefault(ENV_KEY, 456), 456)
assert.Equal(t, GetIntFromEnvWithDefault(ENV_KEY, 0), 0)
assert.Equal(t, GetIntFromEnvWithDefault(ENV_KEY, -1), -1)
}
func TestGetBoolFromEnvWithDefault_UseEnvIfSet(t *testing.T) {
defer os.Unsetenv(ENV_KEY)
os.Setenv(ENV_KEY, "false")
assert.Equal(t, GetBoolFromEnvWithDefault(ENV_KEY, true), false)
os.Setenv(ENV_KEY, "0")
assert.Equal(t, GetBoolFromEnvWithDefault(ENV_KEY, true), false)
os.Setenv(ENV_KEY, "FALSE")
assert.Equal(t, GetBoolFromEnvWithDefault(ENV_KEY, true), false)
os.Setenv(ENV_KEY, "False")
assert.Equal(t, GetBoolFromEnvWithDefault(ENV_KEY, true), false)
os.Setenv(ENV_KEY, "true")
assert.Equal(t, GetBoolFromEnvWithDefault(ENV_KEY, false), true)
os.Setenv(ENV_KEY, "1")
assert.Equal(t, GetBoolFromEnvWithDefault(ENV_KEY, false), true)
}
func TestGetBoolFromEnvWithDefault_UseDefaultIfInvalidValue(t *testing.T) {
defer os.Unsetenv(ENV_KEY)
os.Setenv(ENV_KEY, "foo")
assert.Equal(t, GetBoolFromEnvWithDefault(ENV_KEY, true), true)
assert.Equal(t, GetBoolFromEnvWithDefault(ENV_KEY, false), false)
os.Setenv(ENV_KEY, "fAlSe")
assert.Equal(t, GetBoolFromEnvWithDefault(ENV_KEY, true), true)
assert.Equal(t, GetBoolFromEnvWithDefault(ENV_KEY, false), false)
os.Setenv(ENV_KEY, "tRuE")
assert.Equal(t, GetBoolFromEnvWithDefault(ENV_KEY, false), false)
assert.Equal(t, GetBoolFromEnvWithDefault(ENV_KEY, true), true)
}
func TestGetBoolFromEnvWithDefault_UseDefault(t *testing.T) {
assert.Equal(t, GetBoolFromEnvWithDefault(ENV_KEY, true), true)
assert.Equal(t, GetBoolFromEnvWithDefault(ENV_KEY, false), false)
}
func TestGetStringSliceFromEnvWithDefault_UseEnvIfSet(t *testing.T) {
defer os.Unsetenv(ENV_KEY)
os.Setenv(ENV_KEY, "foo:bar:baz")
assert.Equal(t, GetStringSliceFromEnvWithDefault(ENV_KEY, []string{"a", "b", "c"}), []string{"foo", "bar", "baz"})
os.Setenv(ENV_KEY, "")
assert.Equal(t, GetStringSliceFromEnvWithDefault(ENV_KEY, []string{"a", "b", "c"}), []string{""})
os.Setenv(ENV_KEY, "foo,bar,baz")
assert.Equal(t, GetStringSliceFromEnvWithDefault(ENV_KEY, []string{"a", "b", "c"}), []string{"foo,bar,baz"})
os.Setenv(ENV_KEY, "foo;bar;baz")
assert.Equal(t, GetStringSliceFromEnvWithDefault(ENV_KEY, []string{"a", "b", "c"}), []string{"foo;bar;baz"})
}
func TestGetStringSliceFromEnvWithDefault_UseDefault(t *testing.T) {
assert.Equal(t, GetStringSliceFromEnvWithDefault(ENV_KEY, []string{"a", "b", "c"}), []string{"a", "b", "c"})
assert.Equal(t, GetStringSliceFromEnvWithDefault(ENV_KEY, []string{}), []string{})
} |
// const Product = require('../model/product');
const User=require('../model/user');
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
// Create Product ---ADMIN
exports.createUser = async (req, res) => {
console.log("hit the create user api")
try {
let user = await User.findOne({ telegramid: req.body.telegramid });
if (user) {
return res.json({ token: user.token, message: 'User already registered.' });
// return res.status(400).json({ success: false, message: 'User already exists!' });
} else {
const telegramId=req.body.telegramid
const token = jwt.sign(
{ userId: telegramId },
process.env.JWT_TOKEN_SECRET_KEY,
{ expiresIn: "7d" }
);
// const token = jwt.sign({ telegramId }, 'your_secret_key');
user = new User({
telegramid: req.body.telegramid,
name: req.body.name,
last: req.body.last,
token:token
})
user = await user.save();
res.status(201).json({
success: true,
user
});
}
} catch (error) {
return res.status(400).json({ message: error.message });
}
};
exports.getUserDetails = async (req, res, next) => {
console.log("hit the getUserDetails user api")
try {
const user = await User.findOne({telegramid:req.params.telegramid});
if(user){
res.status(200).json({
success: true,
user,
});
}else{
res.status(500).json({
success: false,
message: "user not found!"
});
}
}catch (error) {
res.status(500).json({ error: error.message });
}
}
exports.updateUserDetails = async (req, res, next) => {
console.log("hit the updateUserDetails user api")
try {
let user = await User.findOne({ telegramid: req.params.telegramid });
if (!user) {
return res.status(404).json({ success: false, message: 'User not found!' });
}
user = await User.findByIdAndUpdate(user._id, req.body, { new: true });
if (!user) {
return res.status(400).json({ success: false, message: 'User update failed!' });
}
res.status(200).json({
success: true,
user
});
} catch (err) {
res.status(500).json({ success: false, message: 'Server error!' });
}
}
exports.deleteAuser = async (req, res, next) => {
console.log("hit the delete user api")
try {
let user = await User.findOne({ telegramid: req.params.telegramid });
if (!user) {
return res.status(404).json({ success: false, message: 'User not found!' });
}
user = await User.findByIdAndRemove(user._id);
if (!user) {
return res.status(400).json({ success: false, message: 'User deletion failed!' });
}
res.status(200).json({
success: true,
message: 'User deleted successfully!'
});
} catch (err) {
res.status(500).json({ success: false, message: 'Server error!' });
}
}
exports.getAllAuser = async (req, res, next) => {
console.log("hit the get all user api")
try {
let users = await User.find();
if(users) {
res.status(201).json({
success: true,
users
});
}
} catch (err) {
res.status(500).json({ success: false, message: 'Server error!' });
}
}
exports.adminLogin = async (req, res) => {
console.log("hit the adminlogin api")
try {
const { email, password } = req.body;
const query = { email: email };
const user = await User.findOne(query);
if (!user) {
return res.status(404).json({ message: "User Doestn't Exist. Try Sign Up!" });
}
if (user && await bcrypt.compare(password, user.password)) {
// Create token
const token = jwt.sign(
{ user_id: user._id, email },
process.env.JWT_TOKEN_SECRET_KEY,
{
expiresIn: "1d",
}
);
await User.findOneAndUpdate(
{ email: email },
{ token: token },
{ new: true }
);
return res.status(200).json({ User: user });
}
res.status(400).send("Invalid Credentials");
} catch (error) {
return res.status(500).send({ message: error });
}
}
exports.adminCreate = async (req, res) => {
console.log("hit the admin create api")
let userData = req.body;
const { email, password } = req.body;
const phoneORemailExist = await User.findOne({
email: email
});
if (phoneORemailExist) {
return res
.status(400)
.send({ message: "PHONE_EMAIL_ALREADY_EXISTS_ERR" });
}
const encryptedPassword = await bcrypt.hash(password, 10);
userData.password = encryptedPassword;
const newUser = await User.create(userData);
const token = jwt.sign(
{ user_id: newUser._id, email },
process.env.JWT_TOKEN_SECRET_KEY,
{
expiresIn: "1d",
}
);
newUser.token = token;
res
.status(201)
.send({
user: newUser,
message: "Account Created Saved Succesfully !",
});
}
// exports.getCategorys = async (req, res) => {
// console.log("hit get all category api")
// const categoryList = await Category.find();
// if(!categoryList) {
// res.status(500).json({success: false})
// }
// res.status(201).json({
// success: true,
// categoryList
// });
// };
// exports.getSingleCategory =async (req, res) => {
// try {
// console.log("hit the getsingle category api")
// const category = await Category.findById(req.params.id);
// if(!category) {
// res.status(500).json({message: 'The category with the given ID was not found.'})
// }
// res.status(200).json({
// category
// });
// } catch (error) {
// res.status(500).json({ error: error.message });
// }
// };
// exports.updateCategory =async (req, res) => {
// try {
// console.log("hit the update category api")
// const category = await Category.findByIdAndUpdate(
// req.params.id,
// {
// name: req.body.name,
// icon: req.body.icon || category.icon,
// },
// { new: true}
// )
// if(!category)
// return res.status(400).send('the category cannot be created!')
// res.status(200).json({
// category
// });
// } catch (error) {
// res.status(500).json({ error: error.message });
// }
// };
// exports.deleteCategory =async (req, res) => {
// console.log("hit delete category api")
// Category.findByIdAndRemove(req.params.id).then(category =>{
// if(category) {
// return res.status(200).json({success: true, message: 'the category is deleted!'})
// } else {
// return res.status(404).json({success: false , message: "category not found!"})
// }
// }).catch(err=>{
// return res.status(500).json({success: false, error: err})
// })
// }; |
module Solution where
import qualified Data.ByteString.Lazy.Char8 as B
import Utils (Solution)
import D1 (day1part1, day1part2)
import D2 (day2part1, day2part2)
import D3 (day3part1, day3part2)
import D4 (day4part1, day4part2)
import D5 (day5part1, day5part2)
runSolution :: [String] -> IO ()
runSolution args =
let
argInBS = B.pack $ head args
(solution, path) = solutionByArg argInBS
in
do
bs <- B.readFile path
print $ solution bs
getSolution :: [String] -> IO (String)
getSolution args =
let
argInBS = B.pack $ head args
(solution, path) = solutionByArg argInBS
in
do
bs <- B.readFile path
pure $ solution bs
solutionByArg :: B.ByteString -> (Solution, String)
-- Day 1
solutionByArg "1.1" = (day1part1, "data/day1.txt")
solutionByArg "1.1e" = (day1part1, "data/example1.txt")
solutionByArg "1.2" = (day1part2, "data/day1.txt")
solutionByArg "1.2e" = (day1part2, "data/example1_2.txt")
-- Day 2
solutionByArg "2.1" = (day2part1, "data/day2.txt")
solutionByArg "2.1e" = (day2part1, "data/example2.txt")
solutionByArg "2.2" = (day2part2, "data/day2.txt")
solutionByArg "2.2e" = (day2part2, "data/example2.txt")
-- Day 3
solutionByArg "3.1" = (day3part1, "data/day3.txt")
solutionByArg "3.1e" = (day3part1, "data/example3.txt")
solutionByArg "3.2" = (day3part2, "data/day3.txt")
solutionByArg "3.2e" = (day3part2, "data/example3.txt")
-- Day 4
solutionByArg "4.1" = (day4part1, "data/day4.txt")
solutionByArg "4.1e" = (day4part1, "data/example4.txt")
solutionByArg "4.2" = (day4part2, "data/day4.txt")
solutionByArg "4.2e" = (day4part2, "data/example4.txt")
-- Day 5
solutionByArg "5.1" = (day5part1, "data/day5.txt")
solutionByArg "5.1e" = (day5part1, "data/example5.txt")
solutionByArg "5.2" = (day5part2, "data/day5.txt")
solutionByArg "5.2e" = (day5part2, "data/example5.txt")
solutionByArg _ = (day1part1, "data/day1.txt") |
package com.praim.inventory.product.dtos;
import java.math.BigDecimal;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.DecimalMin;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
public class ProductDTO {
@NotNull(message = "Product name is required")
@Size(min = 2, max = 100, message = "Product name must be between 2 and 100 characters")
private String name;
@Size(max = 500, message = "Product description must not exceed 500 characters")
private String description;
@NotNull(message = "Product price is required")
@DecimalMin(value = "0.01", message = "Price must be greater than zero")
private BigDecimal price;
@NotNull(message = "variant is required")
private List<ProductVariantDTO> variants;
@JsonProperty("image_url")
@NotNull(message = "main image is required")
private String imageUrl; // Main image URL
@NotNull(message = "images is required")
private List<ProductImageDTO> images; // List of image DTOs
@NotNull(message = "categories is required")
private List<ProductCategoryDTO> categories; // List of category DTOs
} |
import React, {useEffect, useState} from 'react';
import '../App.css';
import RecommenderInput from "../RecommenderInput";
import Box from '@mui/material/Box';
import Paper from '@mui/material/Paper';
import {Button, Card, CardActions, CardContent, Typography} from "@mui/material";
import {Authentication} from "../App";
import axios from "axios";
import {currentUser} from "../MyTypes"
function MyRecommendations(props: {authentication: Authentication}) {
const [isClicked, setIsClicked] = useState<boolean>(false);
const [recType, setRecType] = useState<number | number[]>(1);
const [songWeight, setSongWeight] = useState<number | number[]>(50);
const [artistWeight, setArtistWeight] = useState<number | number[]>(50);
const [genreWeight, setGenreWeight] = useState<number | number[]>(50);
const [recOutput, setRecOutput] = useState<currentUser[]>([]);
async function getRecommendations() {
setIsClicked(true)
console.log("button clicked!")
console.log("Is clicked: " + isClicked)
console.log("Rec type: " + recType)
console.log("Song weight: " + songWeight)
console.log("Artist weight: " + artistWeight)
console.log("Genre weight: " + genreWeight)
let mSame : boolean = true;
if (recType === 0) {
mSame = false;
}
const config = {
headers: {
'Authentication': props.authentication.sessionToken,
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*',
}
}
const postData = {
songs: {matchSame : mSame, matchWeight : songWeight},
genres: {matchSame : mSame, matchWeight : genreWeight},
artists: {matchSame : mSame, matchWeight : artistWeight},
}
await axios.post(process.env.REACT_APP_POST_CREATE_RECS as string, postData, config).then(
response => {console.log(response)}
);
await axios.get(process.env.REACT_APP_GET_RECS as string, config)
.then(
response => {
console.log(response.data)
setRecOutput(response.data)
},
reason => console.log(reason),
);
}
return (
<div id={"mainWindow"} className={"Main-window"}>
<div id="recsHeader" className={"Recommendations-header"}>
My Recommendations
</div>
<hr style={{margin:'10px'}} className = {"Profile-horizontal-line"}/>
<RecommenderInput title={"Find users whose music taste is..."} type={0} val={recType} updateValue={setRecType}/>
<hr style={{margin:'10px'}} className = {"Recommender-divider"}/>
<RecommenderInput title={"Importance of songs:"} type={1} val={songWeight} updateValue={setSongWeight}/>
<hr style={{margin:'10px'}} className = {"Recommender-divider"}/>
<RecommenderInput title={"Importance of artists:"} type={1} val={artistWeight} updateValue={setArtistWeight}/>
<hr style={{margin:'10px'}} className = {"Recommender-divider"}/>
<RecommenderInput title={"Importance of genres:"} type={1} val={genreWeight} updateValue={setGenreWeight}/>
<hr style={{margin:'10px'}} className = {"Recommender-divider"}/>
<Button variant="outlined" color={"secondary"} onClick={getRecommendations}>Get recommendations</Button>
<br/>
{recOutput.map(x => <div>Display Name: {x.displayName} User ID: {x.id}</div>)}
</div>
)
}
export default MyRecommendations; |
from django.db import models
from django.core.validators import MaxValueValidator
from django.utils import timezone
# Função para obter o ano atual
def current_year():
return timezone.now().year
# Validador para garantir que o ano é menor ou igual ao ano atual
def max_value_current_year(value):
return MaxValueValidator(current_year())(value)
class Integrante(models.Model):
TIPOS = [
('IC', 'Iniciação Científica'),
('ME', 'Mestrando'),
('DO', 'Doutorando'),
('PD', 'Pós-Doutorando'),
('PR', 'Professor'),
]
nome = models.CharField(max_length=100)
tipo = models.CharField(max_length=2, choices=TIPOS)
foto = models.ImageField(upload_to='fotos_integrantes/', blank=True, null=True)
def __str__(self):
return self.nome
class Publicacao(models.Model):
titulo = models.CharField(max_length=200)
ano_publicacao = models.PositiveIntegerField(validators=[max_value_current_year])
veiculo_publicacao = models.CharField(max_length=200)
autores = models.ManyToManyField(Integrante)
def __str__(self):
return f"{self.titulo} ({self.ano_publicacao})" |
% ------------------------------------------------------------------------------
% Print dates in output CSV file.
%
% SYNTAX :
% print_dates_in_csv_file_215_216( ...
% a_cycleStartDate, ...
% a_descentToParkStartDate, ...
% a_firstStabDate, a_firstStabPres, ...
% a_descentToParkEndDate, ...
% a_descentToProfStartDate, ...
% a_descentToProfEndDate, ...
% a_ascentStartDate, ...
% a_ascentEndDate, ...
% a_transStartDate, ...
% a_gpsDate, ...
% a_eolStartDate, ...
% a_firstGroundingDate, a_firstGroundingPres, ...
% a_secondGroundingDate, a_secondGroundingPres, ...
% a_firstEmergencyAscentDate, a_firstEmergencyAscentPres, ...
% a_descProfDate, a_descProfPres, ...
% a_parkDate, a_parkPres, ...
% a_ascProfDate, a_ascProfPres, ...
% a_nearSurfDate, a_nearSurfPres, ...
% a_inAirDate, a_inAirPres, ...
% a_evAct, a_pumpAct, a_dataStartPos)
%
% INPUT PARAMETERS :
% a_cycleStartDate : cycle start date
% a_descentToParkStartDate : descent to park start date
% a_firstStabDate : first stabilisation date
% a_firstStabPres : first stabilisation pressure
% a_descentToParkEndDate : descent to park end date
% a_descentToProfStartDate : descent to profile start date
% a_descentToProfEndDate : descent to profile end date
% a_ascentStartDate : ascent start date
% a_ascentEndDate : ascent end date
% a_transStartDate : transmission start date
% a_gpsDate : date associated to the GPS location
% a_eolStartDate : EOL start date
% a_firstGroundingDate : first grounding date
% a_firstGroundingPres : first grounding pressure
% a_secondGroundingDate : second grounding date
% a_secondGroundingPres : second grounding pressure
% a_firstEmergencyAscentDate : first emergency ascent ascent date
% a_firstEmergencyAscentPres : first grounding pressure
% a_descProfDate : descending profile dates
% a_descProfPres : descending profile PRES
% a_parkDate : drift meas dates
% a_parkPres : drift meas PRES
% a_ascProfDate : ascending profile dates
% a_ascProfPres : ascending profile PRES
% a_nearSurfDate : "near surface" profile dates
% a_nearSurfPres : "near surface" profile PRES
% a_inAirDate : "in air" profile dates
% a_inAirPres : "in air" profile PRES
% a_evAct : decoded hydraulic (EV) data
% a_pumpAct : decoded hydraulic (pump) data
% a_dataStartPos : position of the first hydraulic data
%
% OUTPUT PARAMETERS :
%
% EXAMPLES :
%
% SEE ALSO :
% AUTHORS : Jean-Philippe Rannou (Altran)(jean-philippe.rannou@altran.com)
% ------------------------------------------------------------------------------
% RELEASES :
% 08/30/2017 - RNU - creation
% ------------------------------------------------------------------------------
function print_dates_in_csv_file_215_216( ...
a_cycleStartDate, ...
a_descentToParkStartDate, ...
a_firstStabDate, a_firstStabPres, ...
a_descentToParkEndDate, ...
a_descentToProfStartDate, ...
a_descentToProfEndDate, ...
a_ascentStartDate, ...
a_ascentEndDate, ...
a_transStartDate, ...
a_gpsDate, ...
a_eolStartDate, ...
a_firstGroundingDate, a_firstGroundingPres, ...
a_secondGroundingDate, a_secondGroundingPres, ...
a_firstEmergencyAscentDate, a_firstEmergencyAscentPres, ...
a_descProfDate, a_descProfPres, ...
a_parkDate, a_parkPres, ...
a_ascProfDate, a_ascProfPres, ...
a_nearSurfDate, a_nearSurfPres, ...
a_inAirDate, a_inAirPres, ...
a_evAct, a_pumpAct, a_dataStartPos)
% current float WMO number
global g_decArgo_floatNum;
% current cycle number
global g_decArgo_cycleNum;
% output CSV file Id
global g_decArgo_outputCsvFileId;
% default values
global g_decArgo_dateDef;
global g_decArgo_presDef;
global g_decArgo_presCountsDef;
global g_decArgo_durationDef;
% offset between float days and julian days
global g_decArgo_julD2FloatDayOffset;
tabDate = [];
tabLabel = [];
tabPres = [];
% cycle timings
if (~isempty(a_cycleStartDate))
tabDate(end+1) = a_cycleStartDate;
tabLabel{end+1} = 'CYCLE_START_TIME';
tabPres(end+1) = g_decArgo_presDef;
end
if (~isempty(a_descentToParkStartDate))
tabDate(end+1) = a_descentToParkStartDate;
tabLabel{end+1} = 'DESCENT_TO_PARK_START_TIME';
tabPres(end+1) = g_decArgo_presDef;
end
if (~isempty(a_firstStabDate))
tabDate(end+1) = a_firstStabDate;
tabLabel{end+1} = 'FIRST_STABILIZATION_TIME';
tabPres(end+1) = a_firstStabPres;
end
if (~isempty(a_descentToParkEndDate))
tabDate(end+1) = a_descentToParkEndDate;
tabLabel{end+1} = 'PARK_START_TIME';
tabPres(end+1) = g_decArgo_presDef;
end
if (~isempty(a_descentToProfStartDate))
tabDate(end+1) = a_descentToProfStartDate;
tabLabel{end+1} = 'PARK_END_TIME';
tabPres(end+1) = g_decArgo_presDef;
end
if (~isempty(a_descentToProfEndDate))
tabDate(end+1) = a_descentToProfEndDate;
tabLabel{end+1} = 'DEEP_PARK_START_TIME';
tabPres(end+1) = g_decArgo_presDef;
end
if (~isempty(a_ascentStartDate))
tabDate(end+1) = a_ascentStartDate;
tabLabel{end+1} = 'ASCENT_START_TIME';
tabPres(end+1) = g_decArgo_presDef;
end
if (~isempty(a_ascentEndDate))
tabDate(end+1) = a_ascentEndDate;
tabLabel{end+1} = 'ASCENT_END_TIME';
tabPres(end+1) = g_decArgo_presDef;
end
if (~isempty(a_transStartDate))
tabDate(end+1) = a_transStartDate;
tabLabel{end+1} = 'TRANSMISSION_START_TIME';
tabPres(end+1) = g_decArgo_presDef;
end
if (~isempty(a_gpsDate))
tabDate(end+1) = a_gpsDate;
tabLabel{end+1} = 'GPS_LOCATION_TIME';
tabPres(end+1) = g_decArgo_presDef;
end
if (~isempty(a_eolStartDate))
tabDate(end+1) = a_eolStartDate;
tabLabel{end+1} = 'EOL_START_TIME';
tabPres(end+1) = g_decArgo_presDef;
end
if (~isempty(a_firstGroundingDate))
tabDate(end+1) = a_firstGroundingDate;
tabLabel{end+1} = 'FIRST_GROUNDING_TIME';
tabPres(end+1) = a_firstGroundingPres;
end
if (~isempty(a_secondGroundingDate))
tabDate(end+1) = a_secondGroundingDate;
tabLabel{end+1} = 'SECOND_GROUNDING_TIME';
tabPres(end+1) = a_secondGroundingPres;
end
if (~isempty(a_firstEmergencyAscentDate))
tabDate(end+1) = a_firstEmergencyAscentDate;
tabLabel{end+1} = 'FIRST_EMERGENCY_ASCENT_TIME';
tabPres(end+1) = a_firstEmergencyAscentPres;
end
% CTDO dated measurements
idDated = find(a_descProfDate ~= g_decArgo_dateDef);
if (~isempty(idDated))
tabDate = [tabDate a_descProfDate(idDated)'];
tabLabel = [tabLabel repmat({'Dated level of descent profile'}, 1, length(idDated))];
tabPres = [tabPres a_descProfPres(idDated)'];
end
idDated = find(a_parkDate ~= g_decArgo_dateDef);
if (~isempty(idDated))
tabDate = [tabDate a_parkDate(idDated)'];
tabLabel = [tabLabel repmat({'Park drift meas.'}, 1, length(idDated))];
tabPres = [tabPres a_parkPres(idDated)'];
end
idDated = find(a_ascProfDate ~= g_decArgo_dateDef);
if (~isempty(idDated))
tabDate = [tabDate a_ascProfDate(idDated)'];
tabLabel = [tabLabel repmat({'Dated level of ascent profile'}, 1, length(idDated))];
tabPres = [tabPres a_ascProfPres(idDated)'];
end
idDated = find(a_nearSurfDate ~= g_decArgo_dateDef);
if (~isempty(idDated))
tabDate = [tabDate a_nearSurfDate(idDated)'];
tabLabel = [tabLabel repmat({'Near surface meas. date'}, 1, length(idDated))];
tabPres = [tabPres a_nearSurfPres(idDated)'];
end
idDated = find(a_inAirDate ~= g_decArgo_dateDef);
if (~isempty(idDated))
tabDate = [tabDate a_inAirDate(idDated)'];
tabLabel = [tabLabel repmat({'In air meas. date'}, 1, length(idDated))];
tabPres = [tabPres a_inAirPres(idDated)'];
end
% hydraulic actions
for idP = 1:size(a_evAct, 1)
data = a_evAct(idP, a_dataStartPos:end);
for idPoint = 1:15
if ~((data(idPoint) == g_decArgo_dateDef) && ...
(data(idPoint+15) == g_decArgo_presCountsDef) && ...
(data(idPoint+15*2) == g_decArgo_durationDef))
tabDate(end+1) = data(idPoint) + g_decArgo_julD2FloatDayOffset;
tabLabel{end+1} = 'EV action';
tabPres(end+1) = data(idPoint+15);
else
break
end
end
end
for idP = 1:size(a_pumpAct, 1)
data = a_pumpAct(idP, a_dataStartPos:end);
for idPoint = 1:15
if ~((data(idPoint) == g_decArgo_dateDef) && ...
(data(idPoint+15) == g_decArgo_presCountsDef) && ...
(data(idPoint+15*2) == g_decArgo_durationDef))
tabDate(end+1) = data(idPoint) + g_decArgo_julD2FloatDayOffset;
tabLabel{end+1} = 'Pump action';
tabPres(end+1) = data(idPoint+15);
else
break
end
end
end
% sort the collected dates in chronological order
[tabDate, idSorted] = sort(tabDate);
tabLabel = tabLabel(idSorted);
tabPres = tabPres(idSorted);
% add vertical velocities
tabVertSpeed = ones(1, length(tabDate))*99999;
tabMeanVertSpeed = ones(1, length(tabDate))*99999;
for id = 1:3
if (id == 1)
idF1 = find (strcmp(tabLabel, 'DESCENT_TO_PARK_START_TIME') == 1);
idF2 = find (strcmp(tabLabel, 'PARK_START_TIME') == 1);
sign = 1;
elseif (id == 2)
idF1 = find (strcmp(tabLabel, 'PARK_END_TIME') == 1);
idF2 = find (strcmp(tabLabel, 'DEEP_PARK_START_TIME') == 1);
sign = 1;
elseif (id == 3)
idF1 = find (strcmp(tabLabel, 'ASCENT_START_TIME') == 1);
idF2 = find (strcmp(tabLabel, 'ASCENT_END_TIME') == 1);
sign = -1;
end
if (~isempty(idF1) && ~isempty(idF2))
idSlice = idF1+1:idF2-1;
idPres = find(tabPres(idSlice) ~= g_decArgo_presDef);
for idP = 2:length(idPres)
if (tabDate(idSlice(idPres(idP))) ~= tabDate(idSlice(idPres(idP-1))))
vertSpeed = (tabPres(idSlice(idPres(idP)))-tabPres(idSlice(idPres(idP-1))))*100 / ...
((tabDate(idSlice(idPres(idP)))-tabDate(idSlice(idPres(idP-1))))*86400);
tabVertSpeed(idF1+idP) = sign*vertSpeed;
end
if (tabDate(idSlice(idPres(idP))) ~= tabDate(idSlice(idPres(1))))
meanVertSpeed = (tabPres(idSlice(idPres(idP)))-tabPres(idSlice(idPres(1))))*100 / ...
((tabDate(idSlice(idPres(idP)))-tabDate(idSlice(idPres(1))))*86400);
tabMeanVertSpeed(idF1+idP) = sign*meanVertSpeed;
end
end
end
end
if (~isempty(tabDate))
fprintf(g_decArgo_outputCsvFileId, '%d; %d; Dates; Description; UTC time; pressure (dbar); vert. speed (cm/s); mean vert. speed (cm/s)\n', ...
g_decArgo_floatNum, g_decArgo_cycleNum);
for id = 1:length(tabDate)
if (tabPres(id) == g_decArgo_presDef)
fprintf(g_decArgo_outputCsvFileId, '%d; %d; Dates; %s; %s\n', ...
g_decArgo_floatNum, g_decArgo_cycleNum, ...
tabLabel{id}, julian_2_gregorian_dec_argo(tabDate(id)));
else
if (tabVertSpeed(id) == 99999)
fprintf(g_decArgo_outputCsvFileId, '%d; %d; Dates; %s; %s; %.1f\n', ...
g_decArgo_floatNum, g_decArgo_cycleNum, ...
tabLabel{id}, julian_2_gregorian_dec_argo(tabDate(id)), tabPres(id));
else
fprintf(g_decArgo_outputCsvFileId, '%d; %d; Dates; %s; %s; %.1f; %.1f; %.1f\n', ...
g_decArgo_floatNum, g_decArgo_cycleNum, ...
tabLabel{id}, julian_2_gregorian_dec_argo(tabDate(id)), tabPres(id), tabVertSpeed(id), tabMeanVertSpeed(id));
end
end
end
end
return |
package uk.gov.esos.api.web.controller.authorization;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import uk.gov.esos.api.authorization.core.domain.dto.RoleDTO;
import uk.gov.esos.api.authorization.core.service.RoleService;
import uk.gov.esos.api.authorization.regulator.domain.RegulatorRolePermissionsDTO;
import uk.gov.esos.api.authorization.regulator.service.RegulatorRoleService;
import uk.gov.esos.api.web.constants.SwaggerApiInfo;
import uk.gov.esos.api.web.controller.exception.ErrorResponse;
import uk.gov.esos.api.web.security.Authorized;
import java.util.List;
import static uk.gov.esos.api.web.constants.SwaggerApiInfo.INTERNAL_SERVER_ERROR;
import static uk.gov.esos.api.web.constants.SwaggerApiInfo.OK;
@RestController
@RequestMapping(path = "/v1.0/authorities")
@Tag(name = "Authorities")
@RequiredArgsConstructor
public class RoleController {
private final RoleService roleService;
private final RegulatorRoleService regulatorRoleService;
/**
* Returns all operator roles.
*
* @return List of {@link RoleDTO}
*/
@GetMapping(path = "/account/{accountId}/operator-role-codes")
@Operation(summary = "Retrieves the operator roles")
@ApiResponse(responseCode = "200", description = OK, content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, array = @ArraySchema(schema = @Schema(implementation = RoleDTO.class))))
@ApiResponse(responseCode = "403", description = SwaggerApiInfo.FORBIDDEN, content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = ErrorResponse.class))})
@ApiResponse(responseCode = "500", description = INTERNAL_SERVER_ERROR, content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = ErrorResponse.class))})
@Authorized(resourceId = "#accountId")
public ResponseEntity<List<RoleDTO>> getOperatorRoleCodes(
@PathVariable("accountId") @Parameter(description = "The account id") Long accountId) {
List<RoleDTO> roles = roleService.getOperatorRoles();
return new ResponseEntity<>(roles, HttpStatus.OK);
}
/**
* Returns all regulator roles.
* @return List of {@link RegulatorRolePermissionsDTO}
*/
@GetMapping(path = "/regulator-roles")
@Operation(summary = "Returns all regulator roles")
@ApiResponse(responseCode = "200", description = OK, content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, array = @ArraySchema(schema = @Schema(implementation = RegulatorRolePermissionsDTO.class))))
@ApiResponse(responseCode = "403", description = SwaggerApiInfo.FORBIDDEN, content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = ErrorResponse.class))})
@ApiResponse(responseCode = "500", description = INTERNAL_SERVER_ERROR, content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = ErrorResponse.class))})
@Authorized
public ResponseEntity<List<RegulatorRolePermissionsDTO>> getRegulatorRoles() {
return new ResponseEntity<>(regulatorRoleService.getRegulatorRoles(), HttpStatus.OK);
}
@GetMapping(path = "/verifier-role-codes")
@Operation(summary = "Retrieves the verifier role codes")
@ApiResponse(responseCode = "200", description = OK, content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, array = @ArraySchema(schema = @Schema(implementation = RoleDTO.class))))
@ApiResponse(responseCode = "403", description = SwaggerApiInfo.FORBIDDEN, content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = ErrorResponse.class))})
@ApiResponse(responseCode = "500", description = INTERNAL_SERVER_ERROR, content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = ErrorResponse.class))})
@Authorized
public ResponseEntity<List<RoleDTO>> getVerifierRoleCodes() {
return new ResponseEntity<>(roleService.getVerifierRoleCodes(), HttpStatus.OK);
}
} |
import React from "react";
import { motion } from "framer-motion";
import { QUICK_ACCESS_FEATURES } from "../../utils/constants";
import QuickAccessCard from "./QuickAccessCard";
import Underline from "../Underline";
import { XIcon } from "@heroicons/react/outline";
export type QuickAccessProps = {
shown: boolean;
showQuickAccess: (shown: boolean) => void;
};
const QuickAccess = ({ shown, showQuickAccess }: QuickAccessProps) => {
const variants = {
shown: {
maxHeight: "auto",
top: 0,
overflow: "auto",
},
hidden: {
maxHeight: 0,
top: "-200%",
overflow: "hidden",
},
};
return (
<motion.div
className="min-h-screen w-full fixed top-0 left-0 z-40 bg-gradient-to-b from-black to-violet text-white flex items-center justify-center"
initial="hidden"
animate={shown ? "shown" : "hidden"}
transition={{ stiffness: 0, duration: 0.5 }}
variants={variants}
>
<div className="relative w-full max-w-screen-xl py-8">
<div className="mb-8">
<h2 className="text-4xl font-medium text-center mb-3">AKSES CEPAT</h2>
<Underline backgroundColor="#fff" width={60} height={2} center />
</div>
<div className="grid grid-cols-2 sm:grid-cols-6 gap-2 px-4">
{QUICK_ACCESS_FEATURES.map((feature, i) => (
<QuickAccessCard
key={i}
{...feature}
shown={shown}
showQuickAccess={showQuickAccess}
/>
))}
</div>
</div>
<button
className="absolute right-4 top-4 md:right-8 md:top-8"
onClick={() => showQuickAccess(false)}
>
<XIcon className="w-8 h-8 text-white" />
</button>
</motion.div>
);
};
export default QuickAccess; |
import 'package:flutter/material.dart';
import 'package:rupee_elf/common/common_image.dart';
import 'package:rupee_elf/component/home/product_item_cell.dart';
import 'package:rupee_elf/models/product_model.dart';
import 'package:rupee_elf/models/space_detail_model.dart';
import 'package:rupee_elf/network_service/index.dart';
import 'package:rupee_elf/util/constants.dart';
import 'package:rupee_elf/util/hexcolor.dart';
import 'package:rupee_elf/widgets/base_view_widget.dart';
class ProductPurchaseSuccessedPage extends StatefulWidget {
final List<ProductModel> products;
const ProductPurchaseSuccessedPage({super.key, this.products = const []});
@override
State<ProductPurchaseSuccessedPage> createState() =>
_ProductPurchaseSuccessedPageState();
}
class _ProductPurchaseSuccessedPageState
extends State<ProductPurchaseSuccessedPage> {
void itemCellOnTap(String productId) async {
SpaceDetailModel? model =
await NetworkService.checkUserSpaceDetail(productId);
if (model == null) return;
if (model.spaceStatus == 2) {
if (context.mounted) {
Navigator.pushNamed(context, '/productDetail',
arguments: model.loanProduct);
}
} else {
if (context.mounted) {
Navigator.of(context)
.pushNamed('/orderDetail/${model.orderInfo?.loanOrderNo}');
}
}
}
@override
Widget build(BuildContext context) {
return BaseViewWidget(
title: 'Detail',
child: Container(
margin: const EdgeInsets.only(top: 88),
width: MediaQuery.of(context).size.width,
color: HexColor('F5F4F3'),
child: Stack(
alignment: Alignment.topCenter,
clipBehavior: Clip.none,
children: [
const Positioned(
top: -74.0,
child: CommonImage(src: 'static/icons/alert_successed_icon.png'),
),
Column(
children: [
const Padding(padding: EdgeInsets.only(top: 56.0)),
Text(
'You have successfully applied',
style: TextStyle(
fontSize: 16.0, color: Constants.themeTextColor),
),
Container(
decoration: BoxDecoration(
color: Constants.themeColor,
borderRadius: const BorderRadius.all(
Radius.circular(20.0),
),
),
margin: const EdgeInsets.only(
top: 14.0,
left: 12.0,
bottom: 14.0,
right: 12.0,
),
padding: const EdgeInsets.only(
top: 16.0,
left: 34.0,
bottom: 16.0,
right: 34.0,
),
child: const Text(
'You can now apply for other loan products.',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18.0,
color: Colors.white,
),
),
),
Expanded(
child: ListView(
children: widget.products
.map(
(item) => ProductItemCell(
isOdd: widget.products.indexOf(item) % 2 == 0,
product: item,
onTap: () {
itemCellOnTap(item.productId.toString());
},
),
)
.toList()),
)
],
),
],
),
),
);
}
} |
use std::{
net::{IpAddr, ToSocketAddrs, SocketAddr},
str::from_utf8,
time::{Duration, Instant},
};
use argh::FromArgs;
use pnet::{
datalink::NetworkInterface,
packet::{ip::IpNextHeaderProtocols, udp::{self, UdpPacket}, Packet},
transport::{transport_channel, udp_packet_iter, TransportChannelType, TransportProtocol, TransportSender, TransportReceiver, UdpTransportChannelIterator},
};
const DEFAULT_PORT: u16 = 17178;
const MAX_IP: usize = 65535;
const DEF_MTU: usize = 1500;
/*
fn joo() -> Result<(), Box<dyn Error>> {
let my_addr = "2404:7a80:9621:7100:a98e:5d1e:242d:ec8d:1234".to_socket_addrs()?
.into_iter()
.next()
.ok_or("no domain found")?
.ip();
let peer_addr = "mon.lan:1234"
.to_socket_addrs()?
.into_iter()
.next()
.ok_or("no domain found")?
.ip();
println!("My: {}, Peer: {}", my_addr, peer_addr);
let udp = IpNextHeaderProtocols::Udp;
let (mut sx, mut rx) = transport_channel(
MAX_IP,
TransportChannelType::Layer4(
match peer_addr {
IpAddr::V4(_) => TransportProtocol::Ipv4(udp),
IpAddr::V6(_) => TransportProtocol::Ipv6(udp),
}
),
)?;
let ip_buf = &mut [0_u8; MAX_IP];
let mut packet = pnet::packet::udp::MutableUdpPacket::new(&mut ip_buf[0..12]).ok_or("mäh TODO")?;
packet.set_source(1234);
packet.set_destination(1234);
packet.set_length(12);
packet.set_payload(b"haha");
println!("{:?}", packet.to_immutable().packet());
let checksum = match (peer_addr, my_addr) {
(IpAddr::V4(pa), IpAddr::V4(my)) =>
udp::ipv4_checksum(&packet.to_immutable(), &my, &pa),
(IpAddr::V6(pa), IpAddr::V6(my)) =>
udp::ipv6_checksum(&packet.to_immutable(), &my, &pa),
_ => unreachable!(),
};
packet.set_checksum(checksum);
println!("{:?}", packet);
sx.send_to(packet, peer_addr)?;
println!("sent");
let mut rx_iter = udp_packet_iter(&mut rx);
while let Ok((packet, addr)) = rx_iter.next() {
println!("Rx! {:?}, {}", from_utf8(packet.payload())?, addr);
}
Ok(())
} */
fn logic<'a, 'state>(state: &'a mut State<'state>, time: Instant) -> IoOp<'a, 'state> {
IoOp::Receive(Duration::from_secs(1), &mut state.packet)
}
#[derive(Debug)]
enum IoOp<'a, 'state> {
Log(LogMsg),
Resolve(&'a str, &'a mut Option<SocketAddr>),
Send(u8),
Receive(Duration, &'a mut Option<(UdpPacket<'state>, IpAddr)>),
}
#[derive(Debug)]
struct State<'state> {
peers: Vec<Peer>,
my_iface: NetworkInterface,
my_addr: IpAddr,
packet: Option<(UdpPacket<'state>, IpAddr)>,
}
struct Io<'a> {
sx: TransportSender,
rx: UdpTransportChannelIterator<'a>,
}
#[derive(Debug)]
enum Error {
NoInterfaceWithSpecifiedNameFound,
NoInterfaceWithSpecifiedIpFound,
NoGlobalIpFound,
NoInterfacesWithGlobalIpsFound,
InvalidIpAddress,
DnsResolveFailed,
ErrorOpeningSocket,
UdpReceiveFailed,
}
impl Io<'_> {
fn log(&self, msg: LogMsg) {
println!("{:?}", msg)
}
fn resolve(dns: &str) -> Result<SocketAddr, Error> {
dns.to_socket_addrs().or(Err(Error::DnsResolveFailed))?.into_iter().next().ok_or(Error::DnsResolveFailed)
}
fn get_iface(args: &Args) -> Result<(NetworkInterface, IpAddr), Error> {
fn get_addr(iface: &NetworkInterface) -> Option<IpAddr> {
iface.ips.iter().find(|inet| match inet.ip() {
IpAddr::V4(_) => true,
IpAddr::V6(ip) => (ip.segments()[0] & 0xffc0) != 0xfe80,
}).map(|ipnet| ipnet.ip())
}
if let Some(arg_iface) = &args.iface {
for iface in pnet::datalink::interfaces() {
if iface.name == *arg_iface {
if let Some(addr) = get_addr(&iface) {
return Ok((iface, addr))
} else {
return Err(Error::NoGlobalIpFound)
}
}
}
return Err(Error::NoInterfaceWithSpecifiedNameFound)
} else if let Some(arg_ip) = &args.ip {
let arg_ip: IpAddr = arg_ip.parse().or(Err(Error::InvalidIpAddress))?;
for iface in pnet::datalink::interfaces() {
if let Some(ipnet) = iface.ips.iter().find(|ipnet| ipnet.ip() == arg_ip) {
let addr = ipnet.ip();
return Ok((iface, addr))
}
}
return Err(Error::NoInterfaceWithSpecifiedIpFound)
} else {
for iface in pnet::datalink::interfaces() {
if iface.is_up() && !iface.is_loopback() {
if let Some(addr) = get_addr(&iface) {
return Ok((iface, addr))
}
}
}
return Err(Error::NoInterfacesWithGlobalIpsFound)
}
}
fn receive(&mut self, dur: Duration) -> Result<Option<()>, Error> {
println!("receive!");
dbg!(self.rx.next_with_timeout(dur).or(Err(Error::UdpReceiveFailed)).map(|a| a.map(|a| println!("{:?}", a))))
}
fn time() -> Instant {
std::time::Instant::now()
}
}
#[derive(Debug)]
enum LogMsg {
SentRequest(),
ReceivedRequest(),
SentResponse(),
ReceivedResponse(),
ResolvedDns(),
}
#[derive(FromArgs)]
/// Juuh
struct Args {
/// interface
#[argh(option)]
iface: Option<String>,
/// my IP
#[argh(option)]
ip: Option<String>,
/// peers
#[argh(positional)]
peers: Vec<String>,
}
#[derive(Debug)]
struct Peer {
dns: Option<String>,
addr: Option<SocketAddr>,
}
fn main() -> Result<(), Error> {
let args: Args = argh::from_env();
let (my_iface, my_addr) = Io::get_iface(&args)?;
let udp = IpNextHeaderProtocols::Udp;
let (sx, mut rx) = transport_channel(
MAX_IP,
TransportChannelType::Layer4(
match my_addr {
IpAddr::V4(_) => TransportProtocol::Ipv4(udp),
IpAddr::V6(_) => TransportProtocol::Ipv6(udp),
}
),
).or(Err(Error::ErrorOpeningSocket))?;
let mut io = Io {
sx,
rx: udp_packet_iter(&mut rx),
};
let mut peers = Vec::with_capacity(args.peers.len());
for mut peer in args.peers {
if peer.rsplit_once(":").is_none() {
peer = format!("{peer}:{DEFAULT_PORT}");
}
peers.push(
if let Ok(addr) = peer.parse::<SocketAddr>() {
Peer {
dns: None,
addr: Some(addr),
}
} else {
let addr = Io::resolve(&peer).ok();
Peer {
dns: Some(peer),
addr,
}
}
)
}
let mut state = State {
peers,
my_iface,
my_addr,
packet: None,
};
dbg!(&state);
loop {
match logic(&mut state, Io::time()) {
IoOp::Log(msg) => io.log(msg),
IoOp::Resolve(dns, target) => *target = Io::resolve(dns).ok(),
IoOp::Send(_) => todo!(),
IoOp::Receive(dur, target) => { io.receive(dur); },
}
}
Ok(())
} |
import { Zoho } from "@trieb.work/zoho-ts";
import { ILogger } from "@eci/pkg/logger";
import { PrismaClient, Prisma, ZohoApp } from "@eci/pkg/prisma";
import { id } from "@eci/pkg/ids";
import { normalizeStrings } from "@eci/pkg/normalization";
type ZohoAppWithTenant = ZohoApp & Prisma.TenantInclude;
export interface ZohoWarehouseSyncConfig {
logger: ILogger;
zoho: Zoho;
db: PrismaClient;
zohoApp: ZohoAppWithTenant;
}
export class ZohoWarehouseSyncService {
private readonly logger: ILogger;
private readonly zoho: Zoho;
private readonly db: PrismaClient;
private readonly zohoApp: ZohoAppWithTenant;
public constructor(config: ZohoWarehouseSyncConfig) {
this.logger = config.logger;
this.zoho = config.zoho;
this.db = config.db;
this.zohoApp = config.zohoApp;
}
public async syncToECI() {
// Get all active Warehouses from Zoho
const warehouses = await this.zoho.warehouse.list();
const tenantId = this.zohoApp.tenantId;
// Loop through every warehouse and upsert the corresponding warehouse
for (const warehouse of warehouses) {
const normalizedWarehouseName = normalizeStrings.warehouseNames(
warehouse.warehouse_name,
);
const warehouseCreateOrConnect = {
connectOrCreate: {
where: {
normalizedName_tenantId: {
tenantId,
normalizedName: normalizedWarehouseName,
},
},
create: {
id: id.id("warehouse"),
name: warehouse.warehouse_name,
normalizedName: normalizedWarehouseName,
tenant: {
connect: {
id: tenantId,
},
},
},
},
};
await this.db.zohoWarehouse.upsert({
where: {
id_zohoAppId: {
zohoAppId: this.zohoApp.id,
id: warehouse.warehouse_id,
},
},
create: {
id: warehouse.warehouse_id,
warehouse: warehouseCreateOrConnect,
zohoApp: {
connect: {
id: this.zohoApp.id,
},
},
},
update: {
warehouse: warehouseCreateOrConnect,
},
});
}
this.logger.info(
`Sync finished for ${warehouses.length} Zoho Warehouse`,
);
}
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_RECORDS 100
#define MAX_DATA_LENGTH 50
struct Record {
char data[MAX_DATA_LENGTH];
};
struct File {
struct Record records[MAX_RECORDS];
int current_position;
};
void initializeFile(struct File *file) {
file->current_position = 0;
}
void addRecord(struct File *file, const char *data) {
if (file->current_position < MAX_RECORDS) {
strcpy(file->records[file->current_position].data, data);
file->current_position++;
printf("Record added successfully.\n");
} else {
printf("File is full. Cannot add more records.\n");
}
}
void printRecords(struct File *file) {
printf("Records in the file:\n");
for (int i = 0; i < file->current_position; i++) {
printf("Record %d: %s\n", i + 1, file->records[i].data);
}
}
int main() {
struct File file;
initializeFile(&file);
// Adding some sample records
addRecord(&file, "First record");
addRecord(&file, "Second record");
addRecord(&file, "Third record");
// Printing all records
printRecords(&file);
return 0;
} |
# Copyright 2018-2021 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Tests for the MPS template.
"""
# pylint: disable=too-many-arguments
import pytest
import numpy as np
import pennylane as qml
from pennylane.templates.tensornetworks.mps import compute_indices_MPS, MPS
# pylint: disable=protected-access
def test_flatten_unflatten():
"""Test the flatten and unflatten methods."""
def block(weights, wires, use_CNOT=True):
if use_CNOT:
qml.CNOT(wires=[wires[0], wires[1]])
qml.RY(weights[0], wires=wires[0])
qml.RY(weights[1], wires=wires[1])
n_wires = 4
n_block_wires = 2
n_params_block = 2
n_blocks = qml.MPS.get_n_blocks(range(n_wires), n_block_wires)
template_weights = [[0.1, -0.3]] * n_blocks
wires = qml.wires.Wires((0, 1, 2, 3))
op = qml.MPS(wires, n_block_wires, block, n_params_block, template_weights, use_CNOT=True)
data, metadata = op._flatten()
assert len(data) == 1
assert qml.math.allclose(data[0], template_weights)
assert metadata[0] == wires
assert dict(metadata[1]) == op.hyperparameters
# make sure metadata hashable
assert hash(metadata)
new_op = qml.MPS._unflatten(*op._flatten())
assert qml.equal(new_op, op)
assert new_op._name == "MPS" # make sure acutally initialized
assert new_op is not op
class TestIndicesMPS:
"""Test function that computes MPS indices"""
@pytest.mark.parametrize(
("n_wires", "n_block_wires"),
[
(3, 4),
(6, 8),
(10, 14),
],
)
def test_exception_n_block_wires_large(self, n_wires, n_block_wires):
"""Verifies that an exception is raised when n_block_wires is too large."""
with pytest.raises(
ValueError,
match="n_block_wires must be smaller than or equal to the number of wires; "
f"got n_block_wires = {n_block_wires} and number of wires = {n_wires}",
):
compute_indices_MPS(range(n_wires), n_block_wires)
def test_exception_n_block_wires_small(self):
"""Verifies that an exception is raised when n_block_wires is less than 2."""
n_wires = 2
n_block_wires = 0
with pytest.raises(
ValueError,
match=f"number of wires in each block must be larger than or equal to 2; "
f"got n_block_wires = {n_block_wires}",
):
compute_indices_MPS(range(n_wires), n_block_wires)
@pytest.mark.parametrize(
("n_wires", "n_block_wires", "offset"),
[
(18, 6, 6),
(12, 4, 0),
(10, 4, 4),
],
)
def test_exception_offset(self, n_wires, n_block_wires, offset):
"""Verifies that an exception is raised when abs(offset) is more than n_block_wires / 2."""
with pytest.raises(
ValueError,
match="Provided offset is outside the expected range; "
f"the expected range for n_block_wires = {n_block_wires}",
):
compute_indices_MPS(range(n_wires), n_block_wires, offset)
@pytest.mark.parametrize(
("wires", "n_block_wires", "offset", "expected_indices"),
[
([1, 2, 3, 4], 2, 1, ((1, 2), (2, 3), (3, 4))),
(["a", "b", "c", "d"], 2, 1, (("a", "b"), ("b", "c"), ("c", "d"))),
([1, 2, 3, 4, 5, 6, 7, 8], 4, 3, ((1, 2, 3, 4), (4, 5, 6, 7))),
(
["a", "b", "c", "d", "e", "f", "g", "h"],
4,
1,
(
("a", "b", "c", "d"),
("b", "c", "d", "e"),
("c", "d", "e", "f"),
("d", "e", "f", "g"),
("e", "f", "g", "h"),
),
),
],
)
def test_indices_output(self, wires, n_block_wires, offset, expected_indices):
"""Verifies the indices are correct for both integer and string wire labels."""
indices = compute_indices_MPS(wires, n_block_wires, offset)
assert indices == expected_indices
class TestTemplateInputs:
"""Test template inputs and pre-processing (ensure the correct exceptions are thrown for the inputs)"""
@pytest.mark.parametrize(
("block", "n_params_block", "wires", "n_block_wires", "offset", "msg_match"),
[
(
None,
None,
[1, 2, 3, 4],
6,
None,
"n_block_wires must be smaller than or equal to the number of wires; "
"got n_block_wires = 6 and number of wires = 4",
),
(
None,
None,
[1, 2, 3, 4],
0,
None,
"The number of wires in each block must be larger than or equal to 2; "
"got n_block_wires = 0",
),
(
None,
None,
[1, 2, 3, 4, 5, 6, 7, 8],
4,
4,
"Provided offset is outside the expected range; ",
),
],
)
def test_exception_wrong_input(
self, block, n_params_block, wires, n_block_wires, offset, msg_match
):
"""Verifies that an exception is raised if the number of wires or n_block_wires is incorrect."""
with pytest.raises(ValueError, match=msg_match):
MPS(wires, n_block_wires, block, n_params_block, offset=offset)
def test_warning_many_wires(self):
"""Verifies that a warning is raised if n_wires doesn't correspond to n_block_wires."""
n_block_wires = 4
wires = [1, 2, 3, 4, 5]
n_wires = len(wires)
n_params_block = 1
with pytest.warns(
Warning,
match=f"The number of wires should be a multiple of {int(n_block_wires/2)}; got {n_wires}",
):
MPS(wires, n_block_wires, block=None, n_params_block=n_params_block)
@pytest.mark.parametrize(
("block", "n_params_block", "wires", "n_block_wires", "block_weights", "msg_match"),
[
(
None,
2,
[1, 2, 3, 4],
2,
[[1, 2, 3], [1, 2, 3], [1, 2, 3]],
"Weights tensor must have last dimension of length 2; got 3",
),
(
None,
2,
[1, 2, 3, 4],
2,
[[1, 2], [2, 3], [4, 5], [6, 7]],
"Weights tensor must have first dimension of length 3; got 4",
),
],
)
def test_exception_wrong_weight_shape(
self, block, n_params_block, wires, n_block_wires, block_weights, msg_match
):
"""Verifies that an exception is raised if the weights shape is incorrect."""
with pytest.raises(ValueError, match=msg_match):
MPS(wires, n_block_wires, block, n_params_block, block_weights)
class TestAttributes:
"""Tests additional methods and attributes"""
@pytest.mark.parametrize(
("wires", "n_block_wires"),
[(range(7), 4), (range(13), 6)],
)
def test_get_n_blocks_warning(self, wires, n_block_wires):
"""Test that get_n_blocks() warns the user when there are too many wires."""
with pytest.warns(
Warning,
match=f"The number of wires should be a multiple of {int(n_block_wires/2)}; "
f"got {len(wires)}",
):
qml.MPS.get_n_blocks(wires, n_block_wires)
@pytest.mark.filterwarnings("ignore")
@pytest.mark.parametrize(
("wires", "n_block_wires", "expected_n_blocks"),
[
(range(4), 2, 3),
(range(5), 2, 4),
(range(6), 2, 5),
(range(10), 4, 4),
(range(11), 4, 4),
],
)
def test_get_n_blocks(self, wires, n_block_wires, expected_n_blocks):
"""Test that the number of blocks attribute returns the correct number of blocks."""
assert qml.MPS.get_n_blocks(wires, n_block_wires) == expected_n_blocks
@pytest.mark.filterwarnings("ignore")
@pytest.mark.parametrize(
("wires", "n_block_wires"),
[(range(4), 5), (range(9), 20)],
)
def test_get_n_blocks_error(self, wires, n_block_wires):
"""Test that the number of blocks attribute raises an error when
n_block_wires is too large."""
with pytest.raises(
ValueError,
match=f"n_block_wires must be smaller than or equal to the number of wires; "
f"got n_block_wires = {n_block_wires} and number of wires = {len(wires)}",
):
qml.MPS.get_n_blocks(wires, n_block_wires)
@pytest.mark.filterwarnings("ignore")
@pytest.mark.parametrize(
("wires", "n_block_wires", "offset", "expected_n_blocks"),
[
(range(14), 4, 1, 11),
(range(15), 4, 3, 4),
(range(18), 6, 1, 13),
(range(20), 6, 5, 3),
],
)
def test_get_n_blocks_with_offset(self, wires, n_block_wires, offset, expected_n_blocks):
"""Test that the number of blocks attribute returns the correct number of blocks with offset."""
assert qml.MPS.get_n_blocks(wires, n_block_wires, offset) == expected_n_blocks
@pytest.mark.filterwarnings("ignore")
@pytest.mark.parametrize(
("wires", "n_block_wires", "offset"),
[(range(12), 6, 6), (range(9), 4, 0)],
)
def test_get_n_blocks_error_with_offset(self, wires, offset, n_block_wires):
"""Test that the number of blocks attribute raises an error when offset is out of bounds."""
with pytest.raises(
ValueError,
match=r"Provided offset is outside the expected range; "
f"the expected range for n_block_wires = {n_block_wires}",
):
qml.MPS.get_n_blocks(wires, n_block_wires, offset)
class TestTemplateOutputs:
"""Test the output of the MPS template."""
@staticmethod
def circuit1_block(weights, wires):
qml.RZ(weights[0], wires=wires[0])
qml.RZ(weights[1], wires=wires[1])
@staticmethod
def circuit1_MPS(weights, wires):
qml.RZ(weights[0][0], wires=wires[0])
qml.RZ(weights[0][1], wires=wires[1])
qml.RZ(weights[1][0], wires=wires[1])
qml.RZ(weights[1][1], wires=wires[2])
qml.RZ(weights[2][0], wires=wires[2])
qml.RZ(weights[2][1], wires=wires[3])
@staticmethod
def circuit2_block(weights, wires):
SELWeights = np.array(
[[[weights[0], weights[1], weights[2]], [weights[0], weights[1], weights[2]]]]
)
qml.StronglyEntanglingLayers(SELWeights, wires)
@staticmethod
def circuit2_MPS(weights, wires):
SELWeights1 = np.array(
[
[
[weights[0][0], weights[0][1], weights[0][2]],
[weights[0][0], weights[0][1], weights[0][2]],
]
]
)
SELWeights2 = np.array(
[
[
[weights[1][0], weights[1][1], weights[1][2]],
[weights[1][0], weights[1][1], weights[1][2]],
]
]
)
qml.StronglyEntanglingLayers(SELWeights1, wires=wires[0:2])
qml.StronglyEntanglingLayers(SELWeights2, wires=wires[1:3])
@staticmethod
def circuit3_block(wires, k=None):
qml.MultiControlledX(wires=[wires[i] for i in range(len(wires))])
assert k == 2
@staticmethod
def circuit3_MPS(wires, **kwargs): # pylint: disable=unused-argument
qml.MultiControlledX(wires=[wires[0], wires[1], wires[2], wires[3]])
qml.MultiControlledX(wires=[wires[1], wires[2], wires[3], wires[4]])
qml.MultiControlledX(wires=[wires[2], wires[3], wires[4], wires[5]])
qml.MultiControlledX(wires=[wires[3], wires[4], wires[5], wires[6]])
qml.MultiControlledX(wires=[wires[4], wires[5], wires[6], wires[7]])
@staticmethod
def circuit4_MPS(wires, **kwargs): # pylint: disable=unused-argument
qml.MultiControlledX(wires=[wires[0], wires[1], wires[2], wires[3]])
qml.MultiControlledX(wires=[wires[2], wires[3], wires[4], wires[5]])
qml.MultiControlledX(wires=[wires[4], wires[5], wires[6], wires[7]])
@pytest.mark.parametrize(
(
"block",
"n_params_block",
"wires",
"n_block_wires",
"template_weights",
"offset",
"kwargs",
"expected_circuit",
),
[
(
"circuit1_block",
2,
[1, 2, 3, 4],
2,
[[0.1, 0.2], [-0.2, 0.3], [0.3, 0.4]],
None,
{},
"circuit1_MPS",
),
(
"circuit2_block",
3,
[1, 2, 3],
2,
[[0.1, 0.2, 0.3], [0.2, 0.3, -0.4]],
None,
{},
"circuit2_MPS",
),
(
"circuit3_block",
0,
[1, 2, 3, 4, 5, 6, 7, 8],
4,
None,
1,
{"k": 2},
"circuit3_MPS",
),
(
"circuit3_block",
0,
[1, 2, 3, 4, 5, 6, 7, 8, 9],
5,
None,
2,
{"k": 2},
"circuit4_MPS",
),
],
)
def test_output(
self,
block,
n_params_block,
wires,
n_block_wires,
template_weights,
offset,
kwargs,
expected_circuit,
):
"""Verifies that the output of the circuits is correct."""
dev = qml.device("default.qubit", wires=wires)
block = getattr(self, block)
expected_circuit = getattr(self, expected_circuit)
@qml.qnode(dev)
def circuit_template():
qml.MPS(
wires,
n_block_wires,
block,
n_params_block,
template_weights,
offset=offset,
**kwargs,
)
return qml.expval(qml.PauliZ(wires=wires[-1]))
template_result = circuit_template()
@qml.qnode(dev)
def circuit_manual():
expected_circuit(weights=template_weights, wires=wires)
return qml.expval(qml.PauliZ(wires=wires[-1]))
manual_result = circuit_manual()
assert np.isclose(template_result, manual_result) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.