text
stringlengths
184
4.48M
package com.springboot.course.coursemanagementapp.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.springboot.course.coursemanagementapp.dao.CourseDao; import com.springboot.course.coursemanagementapp.entities.Course; import jakarta.transaction.Transactional; import java.util.List; import java.util.Optional; @Service public class CourseServiceImpl implements CourseService { @Autowired private CourseDao courseDao; @Autowired public CourseServiceImpl(CourseDao courseDao) { this.courseDao = courseDao; } @Override public List<Course> getCourses() { return courseDao.findAll(); } @Override public Course getCourse(long id) { Optional<Course> courseOptionalObject = courseDao.findById(id); if(courseOptionalObject.isPresent()) return courseOptionalObject.get(); else return null; } @Override @Transactional public Course addCourse(Course course) { courseDao.save(course); return course; } @Override @Transactional public Course updateCourse(Course course) { courseDao.save(course); return course; } @Override @Transactional public void deleteCourse(long courseID) { Course course = courseDao.findById(courseID).get(); courseDao.delete(course); } }
import { Injectable } from '@angular/core'; import { RemoteSocketService } from '../../../core/services/electron/remote-socket.service'; import { Actions, createEffect, ofType } from '@ngrx/effects'; import { Store } from '@ngrx/store'; import { GamePlayAudioService } from '../services/game-play-audio.service'; import { gamePlayActions } from './game-play.actions'; import { selectCurrentSlide, selectGamePlay } from './game-play.selectors'; import { filter, mergeMap, of, withLatestFrom } from 'rxjs'; import { SlideType } from '../../editor/state/editor.state'; @Injectable() export class GamePlayAudioEffects { constructor( private actions: Actions, private store: Store, private audio: GamePlayAudioService, ) {} RoundSlideBackgroundMusic = createEffect( () => this.actions.pipe( ofType(gamePlayActions.changeSlide), withLatestFrom(this.store.select(selectCurrentSlide)), filter(([_, slide]) => slide.type === SlideType.round), mergeMap(() => { this.audio.playSoundUntil( 'roundPhonk', this.actions.pipe(ofType(gamePlayActions.changeSlide)), ); return of(gamePlayActions.ok); }), ), { dispatch: false }, ); countDownSound = createEffect( () => this.actions.pipe( ofType(gamePlayActions.startCountdown), mergeMap(() => { this.audio.playSoundUntil( 'timer', this.actions.pipe(ofType(gamePlayActions.askQuestion)), ); return of(gamePlayActions.ok); }), ), { dispatch: false }, ); fightSound = createEffect( () => this.actions.pipe( ofType(gamePlayActions.startFight, gamePlayActions.addPlayerToFight), mergeMap(() => { this.audio.playSound('fight'); return of(gamePlayActions.ok); }), ), { dispatch: false }, ); breakSound = createEffect( () => this.actions.pipe( ofType(gamePlayActions.changeSlide), withLatestFrom(this.store.select(selectCurrentSlide)), filter(([_, slide]) => slide.type === SlideType.break), mergeMap(() => { this.audio.playSound('break'); return of(gamePlayActions.ok); }), ), { dispatch: false }, ); AnswerSound = createEffect( () => this.actions.pipe( ofType(gamePlayActions.answerVerdict), mergeMap(({ result }) => { if (result === 'WRONG') { this.audio.playSound('wrongAnswer'); } else { this.audio.playSound('correctAnswer'); } return of(gamePlayActions.ok); }), ), { dispatch: false }, ); resultSlideBackgroundMusic = createEffect( () => this.actions.pipe( ofType(gamePlayActions.changeSlide), withLatestFrom(this.store.select(selectCurrentSlide)), filter(([_, slide]) => slide.type === SlideType.result), mergeMap(() => { this.audio.playSoundUntil( 'result', this.actions.pipe(ofType(gamePlayActions.changeSlide)), ); return of(gamePlayActions.ok); }), ), { dispatch: false }, ); }
<%@ page contentType="text/html; charset=utf-8" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>회원 가입</title> <script type="text/javascript"> function checkForm() { if (!document.formMemberInsert.id.value) { alert("아이디를 입력하세요."); return false; } if (!document.formMemberInsert.password.value) { alert("비밀번호를 입력하세요."); return false; } if (document.formMemberInsert.password.value !== document.formMemberInsert.password_confirm.value) { alert("비밀번호를 동일하게 입력하세요."); return false; } } </script> </head> <body> <jsp:include page="../inc/header.jsp" /> <div class="jumbotron"> <div class="container"> <h1 class="display-3">회원 가입</h1> </div> </div> <div class="container"> <form name="formMemberInsert" class="form-horizontal" action="process_add_member.jsp" method="post" onsubmit="return checkForm()"> <div class="form-group row"> <label class="col-sm-2 ">아이디</label> <div class="col-sm-3"> <input name="id" type="text" class="form-control" placeholder="id"> <span class="idCheck"></span> <br><input type="button" name="btnIsDuplication" value="팝업 아이디 중복 확인"> <br><input type="button" name="btnIsDuplication2nd" value="ajax 아이디 중복 확인"> </div> </div> <div class="form-group row"> <label class="col-sm-2">비밀번호</label> <div class="col-sm-3"> <input name="password" type="text" class="form-control" placeholder="password"> </div> </div> <div class="form-group row"> <label class="col-sm-2">비밀번호확인</label> <div class="col-sm-3"> <input name="password_confirm" type="text" class="form-control" placeholder="password confirm"> </div> </div> <div class="form-group row"> <label class="col-sm-2">성명</label> <div class="col-sm-3"> <input name="name" type="text" class="form-control" placeholder="name"> </div> </div> <div class="form-group row"> <label class="col-sm-2">성별</label> <div class="col-sm-10"> <input name="gender" type="radio" value="남"> 남 <input name="gender" type="radio" value="여"> 여 </div> </div> <div class="form-group row"> <label class="col-sm-2">생일</label> <div class="col-sm-4 "> <input type="text" name="birthyy" maxlength="4" placeholder="년(4자)" size="6"> <select name="birthmm"> <option value="">월</option> <option value="01">1</option> <option value="02">2</option> <option value="03">3</option> <option value="04">4</option> <option value="05">5</option> <option value="06">6</option> <option value="07">7</option> <option value="08">8</option> <option value="09">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> </select> <input type="text" name="birthdd" maxlength="2" placeholder="일" size="4"> </div> </div> <div class="form-group row"> <label class="col-sm-2">이메일</label> <div class="col-sm-10"> <input type="text" name="mail1" maxlength="50">@ <select name="mail2"> <option>naver.com</option> <option>daum.net</option> <option>gmail.com</option> <option>nate.com</option> </select> </div> </div> <div class="form-group row"> <label class="col-sm-2">전화번호</label> <div class="col-sm-3"> <input name="phone" type="text" class="form-control" placeholder="phone"> </div> </div> <div class="form-group row"> <label class="col-sm-2 ">주소</label> <div class="col-sm-5"> <input name="address" type="text" class="form-control" placeholder="address"> </div> </div> <div class="form-group row"> <div class="col-sm-offset-2 col-sm-10 "> <input type="submit" class="btn btn-primary " value="등록 "> <input type="reset" class="btn btn-primary " value="취소 " onclick="reset()"> </div> </div> </form> <script> document.addEventListener("DOMContentLoaded", function () { // const inputID = document.querySelector('input[name=id]'); const formMemberInsert = document.formMemberInsert; //폼을 들고옴 //팝업을 이용한 ID 중복 확인 //팝업을 띄우는 이유는, 현재 페이지에서 데이터베이스에 중복 조회를 할려면 페이지 새로고침 이외에는 방법이 없음 const btnIsDuplication = document.querySelector('input[name=btnIsDuplication]'); btnIsDuplication.addEventListener('click', function () { const id = formMemberInsert.id.value; //아이디 input 에 있는 값 if (id === "") { alert('아이디를 입력해주세요'); formMemberInsert.id.focus(); return; } //아이디 중복 확인을 위해 팝업을 띄움. window.open('popup_id_check.jsp?id=' + id, 'IdCheck', 'width = 500, height = 500, top = 100, left = 200, location = no'); }); //2. ajax를 이용한 alert 방식의 ID 중복확인 const xhr = new XMLHttpRequest(); //XMLHttpRequest 객체 생성 const btnIsDuplication2nd = document.querySelector('input[name=btnIsDuplication2nd]'); btnIsDuplication2nd.addEventListener('click', function () { const id = formMemberInsert.id.value; //아이디 input에 있는 값 xhr.open('GET', 'ajax_id_check.jsp?id=' + id); //HTTP 요청 초기화. 통신 방식과 url 설정 xhr.send(); //url에 요청을 보냄. //이벤트 등록. XMLHttpRequest 객체의 readyState 프로퍼티 값이 변할 때마다 자동으로 호출. xhr.onreadystatechange = () => { //readyState 프로퍼티의 값이 DONE : 요청한 데이터의 처리가 완료되어 응답할 준비가 완료됨. if (xhr.readyState !== XMLHttpRequest.DONE) return; if (xhr.status === 200) { //서버(url) 에 문서가 존재함 console.log(xhr.response); const json = JSON.parse(xhr.response); if (json.result === 'true') { alert('동일한 아이디가 있습니다.') } else { alert('동일한 아이디가 없습니다.') } } else { //서버(url)에 문서가 존재하지 않음. console.error('Error', xhr.status, xhr.statusText); } } }); //ajax를 이용한 실시간 ID 중복확인 const inputId = document.querySelector('input[name=id]'); inputId.addEventListener('keyup', function () { const id = formMemberInsert.id.value; //아이디 input에 있는 값 const idCheck = document.querySelector('.idCheck'); //결과 문자열이 표현될 영역 xhr.open('GET', 'ajax_id_check.jsp?id=' + id); //HTTP 요청 초기화. 통신 방식과 url 설정 xhr.send(); //url에 요청을 보냄. //이벤트 등록. XMLHttpRequest 객체의 readyState 프로퍼티 값이 변할 때마다 자동으로 호출. xhr.onreadystatechange = () => { //readyState 프로퍼티의 값이 DONE : 요청한 데이터의 처리가 완료되어 응답할 준비가 완료됨. if (xhr.readyState !== XMLHttpRequest.DONE) return; if (xhr.status === 200) { //서버(url) 에 문서가 존재함 const json = JSON.parse(xhr.response); if (json.result === 'true') { idCheck.style.color = 'red'; idCheck.innerHTML = '동일한 아이디가 있습니다.'; } else { idCheck.style.color = 'gray'; idCheck.innerHTML = '동일한 아이디가 없습니다'; } } else { //서버(url)에 문서가 존재하지 않음. console.error('Error', xhr.status, xhr.statusText); } } }); }); </script> </div> <jsp:include page="../inc/footer.jsp"/> </body> </html>
package repository import ( "context" "ApuestaTotal/internal/products/domain/dto" "ApuestaTotal/internal/products/domain/entity" "ApuestaTotal/internal/products/domain/ports" "ApuestaTotal/internal/products/infrastructure/adapters/model" "gorm.io/gorm" ) type productRepository struct { db *gorm.DB } func NewProductRepository(db *gorm.DB) ports.Product { return &productRepository{ db, } } func (repository productRepository) GetById(ctx context.Context, id uint) (entity.Product, error) { var modelProduct model.Product if result := repository.db.WithContext(ctx).First(&modelProduct, id); result.Error != nil { return entity.Product{}, result.Error } return modelProduct.ToProductDomain(), nil } func (repository productRepository) GetAll(ctx context.Context) ([]entity.Product, error) { var modelProducts model.MultipleProduct if result := repository.db.WithContext(ctx).Find(&modelProducts); result.Error != nil { return []entity.Product{}, result.Error } return modelProducts.ToProductDomainSlice(), nil } func (repository productRepository) Create(ctx context.Context, newProduct dto.ProductCreate) (entity.Product, error) { var modelProduct = model.Product{ Name: newProduct.Name, Price: newProduct.Price, Stock: newProduct.Stock, } if err := repository.db.WithContext(ctx). Create(&modelProduct). Error; err != nil { return entity.Product{}, err } return modelProduct.ToProductDomain(), nil } func (repository productRepository) Update(ctx context.Context, updateProduct dto.ProductUpdate) error { var modelProduct model.Product if err := repository.db.WithContext(ctx). Model(&modelProduct). Where("id = ?", updateProduct.ID). Updates(&updateProduct).Error; err != nil { return err } return nil }
import { randomUUID } from 'crypto'; import { existsSync, readFileSync, writeFileSync } from 'fs'; import { createServer as createHttpServer, IncomingMessage, request as httpRequest, Server as HttpServer, ServerResponse, } from 'http'; import { createServer as createHttpsServer, request as httpsRequest, Server as HttpsServer, ServerOptions, } from 'https'; import { sync as mkdirpSync } from 'mkdirp'; import { connect } from 'net'; import { pki } from 'node-forge'; import path, { dirname } from 'path'; import ProxyAgent from 'proxy-agent'; import { Duplex } from 'stream'; import { encodeRequestBody, isEqualRequestBody, parse, parseRequestBody, stringifyRequest, stringifyResponse, RequestBody, ResponseBody, } from '@vuloon/body-parser'; import { Ca } from './ca'; import { Semaphore } from './semaphore'; export interface RequestData { header: IncomingMessage; body: RequestBody; } export interface ResponseData { header: IncomingMessage; body: ResponseBody; } export type RequestListenerParameter = { request: RequestData; rawHttp: string }; export type AfterTamperingRequestListenerParameter = RequestListenerParameter & { tampering: boolean }; export type RequestListener = (id: string, data: RequestListenerParameter) => void; export type AfterTamperingRequestListener = (id: string, data: AfterTamperingRequestListenerParameter) => void; export type TamperingRequestListener = (id: string, data: RequestListenerParameter) => Promise<RequestData | void>; export type ResponseListenerParameter = { response: ResponseData; rawHttp: string }; export type ResponseListener = ( id: string, data: ResponseListenerParameter, requestData: AfterTamperingRequestListenerParameter ) => void; export interface Options { port?: number; nextProxy?: string; keepAlive?: string; ssl: { port?: number; caDir: string; }; } interface SslServer { sslServer?: HttpServer; port: number; } export class Proxy { #port: number; #sslPort: number; #nextProxy?: URL; #server!: HttpServer; #sslServer!: HttpsServer; #beforeTamperingRequestListeners: Record<string, Record<string, RequestListener>>; #tamperingRequestListeners: Record<string, Record<string, TamperingRequestListener>>; #afterTamperingRequestListeners: Record<string, Record<string, AfterTamperingRequestListener>>; #responseListeners: Record<string, Record<string, ResponseListener>>; #options: Options; #connectRequests: Record<string, IncomingMessage> = {}; #sslServers: Record<string, SslServer> = {}; #sslSemaphores: Record<string, Semaphore> = {}; #ca!: Ca; #RootKeyFilePath = 'root/key.pem'; #RootCertFilePath = 'root/cert.pem'; get port(): number { return this.#port; } get rootKeyPath(): string { return path.join(this.#options.ssl.caDir, this.#RootKeyFilePath); } get rootCertPath(): string { return path.join(this.#options.ssl.caDir, this.#RootCertFilePath); } get keyPath(): string { return path.join(this.#options.ssl.caDir, 'keys'); } get certPath(): string { return path.join(this.#options.ssl.caDir, 'certs'); } /** * Create new Proxy. Call {@link Proxy.start} to listen on specified port(or default port, 5110) * @param port proxy port (default: 5110) * @param nextProxy next proxy url if using multi proxy */ constructor(options: Options) { this.#beforeTamperingRequestListeners = {}; this.#tamperingRequestListeners = {}; this.#afterTamperingRequestListeners = {}; this.#responseListeners = {}; this.#options = options; this.#port = options.port || 5110; this.#sslPort = options.ssl.port || 5443; const nextProxyUrl = options.nextProxy ? new URL(options.nextProxy) : undefined; this.#nextProxy = nextProxyUrl; this.#initializeServer(); this.#initializeHttpsServer(); this.#initializeCa(); this.#registerOnClose(); } #initializeCa(): void { const rootKeyFilePath = this.rootKeyPath; const isRootKeyFileExists = existsSync(rootKeyFilePath); const rootCertFilePath = this.rootCertPath; const isRootCertFileExists = existsSync(rootCertFilePath); if (!isRootCertFileExists || !isRootKeyFileExists) { const keyParentDir = dirname(this.rootKeyPath); const certParentDir = dirname(this.rootCertPath); mkdirpSync(keyParentDir); mkdirpSync(certParentDir); const { privateKey, certificate } = Ca.createRootCertificate(); writeFileSync(rootKeyFilePath, pki.privateKeyToPem(privateKey)); writeFileSync(rootCertFilePath, pki.certificateToPem(certificate)); } if (!existsSync(this.keyPath)) { mkdirpSync(this.keyPath); } if (!existsSync(this.certPath)) { mkdirpSync(this.certPath); } this.#ca = new Ca(rootKeyFilePath, rootCertFilePath); } #initializeServer(): void { this.#server = createHttpServer(this.#onRequest.bind(this, false)) .on('error', this.#onError.bind(this, 'http_server_error')) .on('clientError', this.#onError.bind(this, 'http_server_client_error')) .on('connect', this.#onHttpsConnect.bind(this)); } #initializeHttpsServer(): void { this.#sslServer = this.#createHttpsServer({}); this.#sslServer.timeout = 0; } #createHttpsServer(options: ServerOptions): HttpsServer { return createHttpsServer(options, this.#onRequest.bind(this, true)) .on('error', this.#onError.bind(this, 'https_server_error')) .on('clientError', this.#onError.bind(this, 'https_client_server_error')) .on('connect', this.#onHttpsConnect.bind(this)); } #registerOnClose(): void { process.on('exit', () => { this.stop(); }); process.on('SIGINT', () => { this.stop(); }); } /** * Start to listen. */ start(): void { this.#startServer(); this.#startSslServer(); } #startServer(): void { this.#server.listen(this.#port); } #startSslServer(): void { this.#sslServer.listen(this.#sslPort); } /** * Close proxy. */ stop(): void { this.#stopServer(); this.#stopSslServer(); } #stopServer(): void { this.#server.close(); } #stopSslServer(): void { this.#sslServer.close(); Object.values(this.#sslServers).forEach((server) => { server.sslServer?.close(); }); } updatePort({ port, sslPort }: { port?: number; sslPort?: number }): void { if (port) { this.#port = port; this.#stopServer(); this.#startServer(); } if (sslPort) { this.#sslPort = sslPort; this.#stopSslServer(); this.#startSslServer(); } } /** * Add listener on proxy response. * @param moduleName module name to register the listener * @param id the listener id for remove. * @param listener response listener */ addResponseListener(moduleName: string, id: string, listener: ResponseListener): void { if (!this.#responseListeners[moduleName]) { this.#responseListeners[moduleName] = {}; } this.#responseListeners[moduleName][id] = listener; } removeAllResponseListener(moduleName: string): void { delete this.#responseListeners[moduleName]; } removeResponseListener(moduleName: string, id: string): void { delete this.#responseListeners[moduleName][id]; } /** * Add listener on proxy request. * @param moduleName module name to register the listener * @param id listener id for remove. * @param listener response listener */ addRequestListener(moduleName: string, id: string, listener: TamperingRequestListener): void { if (!this.#tamperingRequestListeners[moduleName]) { this.#tamperingRequestListeners[moduleName] = {}; } this.#tamperingRequestListeners[moduleName][id] = listener; } removeAllRequestListener(moduleName: string): void { delete this.#tamperingRequestListeners[moduleName]; } removeRequestListener(moduleName: string, id: string): void { delete this.#tamperingRequestListeners[moduleName][id]; } /** * Add listener on proxy request before tampering. * @param moduleName module name to register the listener * @param id listener id for remove. * @param listener response listener */ addBeforeTamperingRequestListener(moduleName: string, id: string, listener: TamperingRequestListener): void { if (!this.#beforeTamperingRequestListeners[moduleName]) { this.#beforeTamperingRequestListeners[moduleName] = {}; } this.#beforeTamperingRequestListeners[moduleName][id] = listener; } removeAllBeforeTamperingRequestListener(moduleName: string): void { delete this.#beforeTamperingRequestListeners[moduleName]; } removeBeforeTamperingRequestListener(moduleName: string, id: string): void { delete this.#beforeTamperingRequestListeners[moduleName][id]; } /** * Add listener on proxy request after tampering. * @param moduleName module name to register the listener * @param id listener id for remove. * @param listener response listener */ addAfterTamperingRequestListener(moduleName: string, id: string, listener: TamperingRequestListener): void { if (!this.#afterTamperingRequestListeners[moduleName]) { this.#afterTamperingRequestListeners[moduleName] = {}; } this.#afterTamperingRequestListeners[moduleName][id] = listener; } removeAllAfterTamperingRequestListener(moduleName: string): void { delete this.#afterTamperingRequestListeners[moduleName]; } removeAfterTamperingRequestListener(moduleName: string, id: string): void { delete this.#afterTamperingRequestListeners[moduleName][id]; } #onRequest(isSsl: boolean, requestData: IncomingMessage, response: ServerResponse): void { let buffer: Buffer = Buffer.from([]); requestData.on('data', (data: Uint8Array) => { buffer = Buffer.concat([buffer, data]); }); requestData.on('end', async () => { if (!requestData.url) { return; } const parseHost = this.#parseHost(requestData, isSsl ? 443 : 80); if (!parseHost) { response.writeHead(400); response.write('vuloon proxy'); response.end(); return; } const { host, port } = parseHost; const body = parseRequestBody(buffer, requestData.headers); const uuid = randomUUID(); const rawHttp = stringifyRequest(requestData, body); const beforeRequestData = { request: { header: requestData, body, }, rawHttp: rawHttp, }; this.#emitBeforeListener(uuid, beforeRequestData); const tamperedData = await this.#emitTamperingListener(uuid, beforeRequestData); const data = encodeRequestBody(tamperedData.body, requestData.headers['content-type']); requestData.headers['content-length'] = data.length.toString(); const tampering = this.#isEqualHeaderAndBody( beforeRequestData.request, tamperedData, requestData.headers['content-type'] ); this.#appendProxyHeader(requestData); const afterRequestData = { request: tamperedData, rawHttp: rawHttp, tampering, }; this.#emitAfterListener(uuid, afterRequestData); const headers: Record<string, string | string[] | undefined> = {}; for (const h in requestData.headers) { // don't forward proxy- headers if (!/^proxy-/i.test(h)) { headers[h] = requestData.headers[h]; } } const request = isSsl ? httpsRequest : httpRequest; const serverRequest = request({ host: host, port: port, method: requestData.method, path: requestData.url, headers: requestData.headers, agent: this.#nextProxy ? new ProxyAgent(this.#nextProxy.toString()) : undefined, }) .on('error', () => response.writeHead(502).end()) .on('timeout', () => response.writeHead(504).end()) .on('response', this.#onResponse.bind(this, uuid, afterRequestData)) .on('response', (serverResponse) => { serverResponse.headers['x-vuloon-proxy'] = 'true'; response.writeHead(serverResponse.statusCode!, serverResponse.headers); serverResponse.pipe(response); }); serverRequest.write(data); serverRequest.end(); }); } #onResponse(uuid: string, requestData: AfterTamperingRequestListenerParameter, response: IncomingMessage): void { const header = response.headers; let buffer = Buffer.from([]); response.on('data', (data: Uint8Array) => { buffer = Buffer.concat([buffer, data]); }); response.on('end', () => { const body = parse(buffer, header); const rawHttp = stringifyResponse(response, body); const responseData = { response: { header: response, body, }, rawHttp, }; this.#emitResponseListener(uuid, responseData, requestData); }); } #emitBeforeListener(...[uuid, data]: Parameters<RequestListener>): void { Object.values(this.#beforeTamperingRequestListeners).forEach((moduleListener) => { Object.values(moduleListener).forEach((listener) => { try { listener(uuid, data); } catch { // } }); }); } async #emitTamperingListener(...[uuid, data]: Parameters<TamperingRequestListener>): Promise<RequestData> { let header = data.request.header; let body = data.request.body; for (const modulesListeners of Object.values(this.#tamperingRequestListeners)) { for (const listener of Object.values(modulesListeners)) { const rawHttp = stringifyRequest(header, body); const takeParameter: Parameters<TamperingRequestListener>[1] = { request: { header, body, }, rawHttp, }; try { const result = await listener(uuid, takeParameter); if (result) { header = result.header; body = result.body; } } catch (e) { // } } } return { header, body }; } #emitAfterListener(...[uuid, data]: Parameters<AfterTamperingRequestListener>): void { Object.values(this.#afterTamperingRequestListeners).forEach((moduleListener) => { Object.values(moduleListener).forEach((listener) => { try { listener(uuid, data); } catch { // } }); }); } #emitResponseListener(...[uuid, data, requestData]: Parameters<ResponseListener>): void { Object.values(this.#responseListeners).forEach((moduleListener) => { Object.values(moduleListener).forEach((listener) => { listener(uuid, data, requestData); }); }); } #appendProxyHeader(requestData: IncomingMessage) { requestData.headers['x-vuloon-proxy'] = 'true'; requestData.headers['proxy-connection'] = 'keep-alive'; requestData.headers['connection'] = 'keep-alive'; } #onHttpsConnect(clientRequest: IncomingMessage, clientSocket: Duplex, clientHead: Buffer): void { clientSocket.on('error', this.#onError.bind(this, 'client_socket_error')); if (!clientHead || clientHead.length === 0) { clientSocket.once('data', this.#onHttpServerConnectData.bind(this, clientRequest, clientSocket)); clientSocket.write('HTTP/1.1 200 OK\r\n'); if (this.#options.keepAlive && clientRequest.headers['proxy-connection'] === 'keep-alive') { clientSocket.write('Proxy-Connection: keep-alive\r\n'); clientSocket.write('Connection: keep-alive\r\n'); } clientSocket.write('\r\n'); } } #onHttpServerConnectData(request: IncomingMessage, socket: Duplex, head: Buffer): void { socket.pause(); /* * Detect TLS from first bytes of data * TLS record should start with 22(0x16). */ if (head[0] == 0x16) { // URL is in the form 'hostname:port' const hostname = request.url!.split(':', 2)[0]; const sslServer = this.#sslServers[hostname]; if (sslServer) { this.#makeConnection(request, socket, head, sslServer.port); return; } const wildcardHost = hostname.replace(/[^.]+\./, '*.'); let semaphore = this.#sslSemaphores[wildcardHost]; if (!semaphore) { semaphore = this.#sslSemaphores[wildcardHost] = new Semaphore(1); } semaphore.use(async () => { if (this.#sslServers[hostname]) { this.#makeConnection(request, socket, head, this.#sslServers[hostname].port); return; } this.#generateHttpsServer(hostname); this.#makeConnection(request, socket, head, this.#sslPort); }); return; } else { this.#makeConnection(request, socket, head, this.#port); return; } } #onError(at: string, error: Error): void { console.error(`Error occured at ${at}`); console.error(error); } #makeConnection(request: IncomingMessage, socket: Duplex, head: Buffer, port: number): void { // open a TCP connection to the remote host const conn = connect( { port: port, host: 'localhost', allowHalfOpen: true, }, () => { // create a tunnel between the two hosts conn.on('finish', () => { socket.destroy(); }); socket.on('close', () => { conn.end(); }); const connectKey = conn.localPort + ':' + conn.remotePort; this.#connectRequests[connectKey] = request; socket.pipe(conn); conn.pipe(socket); socket.emit('data', head); conn.on('end', () => { delete this.#connectRequests[connectKey]; }); socket.resume(); return; } ); conn.on('error', this.#onError.bind(this, 'connect_error')); } #generateHttpsServer(hostname: string): void { const { privateKeyPem, certificatePem } = this.#generateServerKeyAndCertificate(hostname); if (!hostname.match(/^[\d.]+$/)) { this.#sslServer.addContext(hostname, { key: privateKeyPem, cert: certificatePem, }); this.#sslServers[hostname] = { port: this.#sslPort }; return; } else { const server = this.#createHttpsServer({ key: privateKeyPem, cert: certificatePem }); const address = server.address(); if (address && typeof address !== 'string') { const sslServer = { server: server, port: address.port, }; this.#sslServers[hostname] = sslServer; } } } #generateServerKeyAndCertificate(host: string): { privateKeyPem: string; certificatePem: string; } { const keyFile = this.#getKeyFile(host); const isKeyFileExists = existsSync(keyFile); const certFile = this.#getCertFile(host); const isCertFileExists = existsSync(certFile); if (isKeyFileExists && isCertFileExists) { return { privateKeyPem: readFileSync(keyFile).toString(), certificatePem: readFileSync(certFile).toString(), }; } else { const { privateKey, certificate } = this.#ca.generateServerCertificates(host); const privateKeyPem = pki.privateKeyToPem(privateKey); writeFileSync(keyFile, privateKeyPem); const certificatePem = pki.certificateToPem(certificate); writeFileSync(certFile, certificatePem); return { privateKeyPem, certificatePem, }; } } #parseHost( request: IncomingMessage, port: number ): { host: string; port: string | number; } | null { const _parseHost = (host: string, defaultPort: number) => { const match = host.match(/^https?:\/\/(.*)/); if (match) { const parsedUrl = new URL(host); return { host: parsedUrl.hostname, port: parsedUrl.port, }; } const hostPort = host.split(':'); const _host = hostPort[0]; const _port = hostPort.length === 2 ? hostPort[1] : defaultPort; return { host: _host, port: _port, }; }; if (!request.url) { return null; } const match = request.url.match(/^https?:\/\/([^/]+)(.*)/); if (match) { return _parseHost(match[1], port); } else if (request.headers.host) { return _parseHost(request.headers.host, port); } else { return null; } } /** * Compare request data. * Only the header and body are compared. * @param left RequestData * @param right RequestData */ #isEqualHeaderAndBody(left: RequestData, right: RequestData, contentType: string | undefined): boolean { return ( this.#isEqualHeader(left.header.headers, right.header.headers) && isEqualRequestBody(left.body, right.body, contentType) ); } /** * compare headers */ #isEqualHeader(left: IncomingMessage['headers'], right: IncomingMessage['headers']): boolean { const hasAll = (target: IncomingMessage['headers'], compare: IncomingMessage['headers']): boolean => { return Object.entries(target).every(([name, value]) => { const comparedValue = compare[name]; if (Array.isArray(value)) { return Array.isArray(comparedValue) && value.every((v, i) => v === comparedValue[i]); } return value === comparedValue; }); }; return hasAll(left, right) && hasAll(right, left); } #getKeyFile(host: string): string { return `${this.#options.ssl.caDir}/keys/${host}.key`; } #getCertFile(host: string): string { return `${this.#options.ssl.caDir}/certs/${host}.crt`; } } export * from '@vuloon/body-parser/lib/types';
## DESCRIPTION ## Calculus One, approximating areas. ## ENDDESCRIPTION ## DBsubject(Calculus - single variable) ## DBchapter(Techniques of integration) ## DBsection(Partial fractions) ## Date(09/18/2018) ## Institution(Community College of Denver, Colorado Community College System) ## Author(Percy Makita) ## KEYWORDS('Calculus', 'Techniques of Integration', 'Partial Fractions') ########################### # Initialization DOCUMENT(); loadMacros( "PGstandard.pl", "MathObjects.pl", "AnswerFormatHelp.pl", "PGML.pl", "PGcourse.pl", "parserRadioButtons.pl", ); TEXT(beginproblem()); $showPartialCorrectAnswers = 1; ########################### # Setup $a=non_zero_random(-6,6); $b=random(1,10); $num1=Formula("$a*x^2")->reduce; $num2=Formula("-$a*$b")->reduce; $den1=Formula("x^2+$b")->reduce; $den2=Formula("x^2+$a")->reduce; $f1=Formula("($a*x^2)/(x^2+$b)")->reduce(); $f2=Formula("$a*$b+$b/(x^2+$a)")->reduce(); $f3=Formula("$b-($a*$b)/(x^2+$b)")->reduce(); $f4=Formula("$a-($a*$b)/(x^2+$b)")->reduce(); $radio=RadioButtons([["\(\frac{$num1}{$den1}\)","\($num2 + \frac{$b}{$den2}\)","\($b-\frac{$num2}{$den1}\)","\($a+\frac{$num2}{$den1}\)"]],"\($a+\frac{$num2}{$den1}\)"); ########################### # Main text BEGIN_PGML Express the rational function [``[$f1]``] as a sum or difference of two simpler rational expressions. Select the right answer below. [_____________]{$radio } END_PGML ############################ # Solution #BEGIN_PGML_SOLUTION #Solution explanation goes here. #END_PGML_SOLUTION COMMENT('MathObject version. Uses PGML.'); ENDDOCUMENT();
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Noticias</title> <style> @import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;700&display=swap"); </style> </head> <body> <section class="escritorio"> <div class="header"> <div class="botonVolver"> <button class="btnRegresar" (click)="Redireccionar()"> Regresar </button> </div> <h1 class="tituloMision24" (click)="Redireccionar()">Mision 24</h1> <h2 class="slogan">El punto exacto de la noticia</h2> </div> <br /> <div class="contenido"> <div class="sectorImagenes"> <img *ngFor="let item of firstTwoImages" [src]="item.path" [alt]="item.nombre" class="imagenNoticia" /> <button class="masContenido" *ngIf="!ocultarBoton" (click)="abrirCarrusel()" > Ver mas contenido </button> </div> <div class="textoNoticia" *ngIf="notita"> <div class="contenedorTitulo"> <h1 class="tituloNota">{{ notita.titulo }}</h1> <h2 class="fechaNota">Fecha: {{ notita.createdAt }}</h2> <div class="divisor"></div> </div> <div class="contenidoNoticia"> <div [innerHTML]="notita.descripcion"></div> </div> </div> </div> <div *ngIf="mostrarCarrusel" class="modal fade show" tabindex="-1" aria-labelledby="exampleModalLabel" aria-modal="true" style="display: block; background: rgba(0, 0, 0, 0.5)" > <button class="btn btn-danger position-absolute top-0 end-0 m-3" (click)="cerrarCarrusel()" > <i class="bi bi-trash3-fill"></i> <!-- Ícono de cierre --> </button> <div class="modal-dialog modal-xl"> <div class="modal-content"> <!-- Carrusel Bootstrap --> <div id="carouselExampleCaptions" class="carousel slide"> <div id="carouselExampleCaptions" class="carousel slide"> <div class="carousel-indicators"> <!-- Genera los indicadores de diapositivas --> <button *ngFor="let image of allImages | ObjToArray; let i = index" type="button" [attr.data-bs-target]="'#carouselExampleCaptions'" [attr.data-bs-slide-to]="i" [class.active]="i === indiceDiapositivaActiva" [attr.aria-current]="i === 0 ? 'true' : 'false'" [attr.aria-label]="'Slide ' + (i + 1)" ></button> </div> <div class="carousel-inner"> <!-- Genera las diapositivas --> <div *ngFor="let image of allImages | ObjToArray; let i = index" class="carousel-item" [class.active]="i === indiceDiapositivaActiva" > <img [src]="image.path" class="d-block w-100" [alt]="image.nombre" /> </div> </div> <!-- Controles de navegación --> <button class="carousel-control-prev" type="button" (click)=" indiceDiapositivaActiva = (indiceDiapositivaActiva - 1 + allImages.length) % allImages.length " > <span class="carousel-control-prev-icon" aria-hidden="true" ></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" (click)=" indiceDiapositivaActiva = (indiceDiapositivaActiva + 1) % allImages.length " > <span class="carousel-control-next-icon" aria-hidden="true" ></span> <span class="visually-hidden">Next</span> </button> </div> </div> </div> </div> </div> </section> <section class="mobile"> <div class="headerMobile"> <h1 class="Mision24Mobile" (click)="Redireccionar()">Mision 24</h1> <h2 class="SloganMobile">El punto exacto de la noticia</h2> </div> <br /> <div class="contenidoMobile"> <img *ngFor="let item of firstTwoImages" [src]="item.path" [alt]="item.nombre" class="imagenMobile" /> <button class="botonMasContenidoMobile" (click)="abrirCarrusel()"> Ver mas contenido </button> <h1 class="tituloNoticiaMobile">{{ notita.titulo }}</h1> <h2 class="fechaNotaMobile">Fecha: {{ notita.createdAt }}</h2> <div class="noticiaTextoMobile"> <p [innerHTML]="notita.descripcion"></p> </div> </div> </section> </body> </html>
**The current status of this chapter is draft. I will finish it later when I have time** In the modern workplace, stress and anxiety can be significant barriers to productivity and overall well-being. This chapter explores various strategies for managing stress and anxiety using mindfulness techniques, empowering individuals to cultivate a mindful workplace mentality. 1. Mindful Awareness -------------------- * Start by cultivating a sense of mindful awareness throughout your day. * Pay attention to your thoughts, emotions, and physical sensations without judgment. * Notice when stress or anxiety arises and acknowledge its presence. * By cultivating mindful awareness, you can catch stress and anxiety triggers early on and respond appropriately. 2. Breathing Exercises ---------------------- * Employ deep breathing exercises to help manage stress and anxiety in the moment. * Find a quiet space and take slow, deep breaths, focusing on the sensation of the breath entering and leaving your body. * Deep breathing activates the body's relaxation response, calming the mind and reducing stress. 3. Mindful Rest and Relaxation ------------------------------ * Dedicate time each day for mindful rest and relaxation. * Engage in activities that promote relaxation, such as taking a walk in nature, listening to calming music, or practicing gentle yoga. * Use this time to focus on the present moment and let go of stress and anxiety. 4. Thought Observation ---------------------- * Practice observing your thoughts without getting caught up in them. * Imagine your thoughts as passing clouds in the sky, allowing them to come and go without attachment. * By cultivating a non-judgmental attitude towards your thoughts, you can reduce their impact on your stress and anxiety levels. 5. Mindful Time Management -------------------------- * Use mindfulness to manage your time effectively and minimize stress. * Prioritize tasks based on their importance and urgency. * Focus on one task at a time, avoiding multitasking, which can lead to increased stress and decreased productivity. * Set realistic goals and deadlines, allowing for breaks and self-care. 6. Gratitude Practice --------------------- * Cultivate a gratitude practice to counteract stress and anxiety. * Each day, reflect on three things you are grateful for in your work or personal life. * This practice shifts focus towards positivity and encourages a more balanced perspective. 7. Mindful Communication ------------------------ * Use mindfulness during interpersonal interactions to reduce stress and improve communication. * Listen actively, giving your full attention to the speaker. * Notice any judgments or assumptions that arise and let them go. * Respond mindfully, with compassion and understanding, rather than reacting impulsively. 8. Regular Mindfulness Practice ------------------------------- * Establish a regular mindfulness practice to build resilience against stress and anxiety. * Set aside dedicated time each day for meditation, guided mindfulness exercises, or other mindfulness activities. * Consistency is key to reaping the benefits of mindfulness and managing stress effectively. Conclusion ---------- By implementing these strategies for managing stress and anxiety with mindfulness, individuals can foster a mindful workplace mentality. The practices of mindful awareness, breathing exercises, mindful rest, thought observation, mindful time management, gratitude, mindful communication, and regular mindfulness practice empower individuals to navigate stress and anxiety with greater clarity and focus. With these tools, individuals can create a more harmonious work environment, leading to increased productivity, well-being, and overall success in the workplace.
import React from "react"; import { useRouter } from "next/router"; import { Typography, Button, Card, Form, Input, notification } from "antd"; import Cookies from "js-cookie"; import Link from "next/link"; import UserService from "../../service/user.service"; import { useWallet } from "@solana/wallet-adapter-react"; import { useDispatch } from "react-redux"; import { updateWalletAddress } from "../../store/wallet/wallet.slice"; const { Text, Title } = Typography; type NotificationType = "success" | "error"; const Login = () => { const [api, contextHolder] = notification.useNotification(); const router = useRouter(); const { publicKey } = useWallet(); const dispatch = useDispatch(); const openNotification = ( type: NotificationType, message: string, description: string ) => { api[type]({ message, description, }); }; const onFinish = async (formData: any) => { const [response] = await UserService.login({ email: formData.email, password: formData.password, }); if (response?.error) { openNotification("error", "Fail to sign in", response.error.message); return; } const { accessToken, user } = response.data; const { wallet_address } = user; // store access token in memory and refresh token in cookies Cookies.set("accessToken", accessToken); dispatch(updateWalletAddress(wallet_address)); if (wallet_address === "") return router.push("/connect-wallet"); if (!publicKey) return router.push("/unmatched-wallet"); console.log("publicKey: ", publicKey?.toBase58()); console.log("wallet_address: ", wallet_address); if (publicKey?.toBase58() === wallet_address) router.push("/"); else router.push("/unmatched-wallet"); }; return ( <div style={{ height: "100vh", padding: "150px" }}> {contextHolder} <Card style={{ width: 400, margin: "auto" }}> <Title level={2} style={{ marginBottom: "30px" }}> Sign in </Title> <Form name="basic" layout="vertical" initialValues={{ remember: true }} onFinish={onFinish} autoComplete="off" > <Form.Item label="Email" name="email" rules={[ { required: true, message: "Please input your email!", }, { pattern: new RegExp( /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ ), message: "Invalid email!", }, ]} > <Input size="large" /> </Form.Item> <Form.Item label="Password" name="password" rules={[{ required: true, message: "Please input your password!" }]} > <Input.Password size="large" /> </Form.Item> <Form.Item> <Button size="large" type="primary" htmlType="submit" style={{ width: "100%", marginTop: "10px" }} > Submit </Button> </Form.Item> <Text> Need an account? <Link href="/signup"> Sign up</Link> </Text> </Form> </Card> </div> ); }; export default Login;
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('lodging_hotel_facility', function (Blueprint $table) { $table->uuid('uuid_lodging'); $table->unsignedInteger('hotel_facility_id'); $table->timestamps(); $table->foreign('uuid_lodging') ->references('uuid_lodging') ->on('lodgings') ->cascadeOnUpdate() ->cascadeOnDelete(); $table->foreign('hotel_facility_id') ->references('id') ->on('hotel_facilities') ->cascadeOnUpdate() ->cascadeOnDelete(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('lodging_hotel_facility'); } };
package org.planify.contract.domain; import jakarta.persistence.*; import org.planify.Identifiable; import org.planify.client.domain.Client; import org.planify.provider.domain.Provider; import org.planify.service.domain.Service; import java.math.BigInteger; import java.time.LocalDateTime; import java.util.UUID; @Entity @Table(name = "contract") public class Contract extends Identifiable { @ManyToOne(optional = false, fetch = FetchType.EAGER) private Client client; @ManyToOne(optional = false, fetch = FetchType.EAGER) private Provider provider; @Column(nullable = false) @Enumerated(EnumType.STRING) private ContractStatus status; @ManyToOne(optional = false) private Service service; @Column(nullable = false) private BigInteger price; @Column(nullable = false) private BigInteger advancePayment; @Column(nullable = false) private String providerNotes; @Column(nullable = false) private String clientNotes; @Column(nullable = false) private LocalDateTime contractDate; public Contract() { } public Contract(UUID id, Client client, Provider provider, ContractStatus status, Service service, BigInteger price, BigInteger advancePayment, String providerNotes, String clientNotes, LocalDateTime contractDate) { super(id); this.client = client; this.provider = provider; this.status = status; this.service = service; this.price = price; this.advancePayment = advancePayment; this.providerNotes = providerNotes; this.clientNotes = clientNotes; this.contractDate = contractDate; } public Contract(Client client, Provider provider, ContractStatus status, Service service, BigInteger price, BigInteger advancePayment, String providerNotes, String clientNotes, LocalDateTime contractDate) { this.client = client; this.provider = provider; this.status = status; this.service = service; this.price = price; this.advancePayment = advancePayment; this.providerNotes = providerNotes; this.clientNotes = clientNotes; this.contractDate = contractDate; } public BigInteger getAdvancePayment() { return advancePayment; } public void setAdvancePayment(BigInteger advancePayment) { this.advancePayment = advancePayment; } public String getProviderNotes() { return providerNotes; } public void setProviderNotes(String providerNotes) { this.providerNotes = providerNotes; } public String getClientNotes() { return clientNotes; } public void setClientNotes(String clientNotes) { this.clientNotes = clientNotes; } public LocalDateTime getContractDate() { return contractDate; } public void setContractDate(LocalDateTime contractDate) { this.contractDate = contractDate; } public Client getClient() { return client; } public void setClient(Client client) { this.client = client; } public Provider getProvider() { return provider; } public void setProvider(Provider provider) { this.provider = provider; } public ContractStatus getStatus() { return status; } public void setStatus(ContractStatus status) { this.status = status; } public Service getService() { return service; } public void setService(Service service) { this.service = service; } public BigInteger getPrice() { return price; } public void setPrice(BigInteger price) { this.price = price; } }
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <!-- <script th:src="@{/webjars/jquery/2.1.3/jquery.min.js}"></script> --> <script th:src="@{//cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js}">...</script> <script th:src="@{//cdnjs.cloudflare.com/ajax/libs/sweetalert/0.5.0/sweet-alert.min.js}"></script> <script th:src="@{/js/guestbook.js}"></script> <script th:src="@{/js/swal-form.js}"></script> <script th:src="@{/js/comment.js}"></script> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" /> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" /> <link rel="stylesheet" href="/css/style.css" type="text/css" /> <link rel="stylesheet" href="/css/swal-form.css" type="text/css" /> <title th:text="#{guestbook.title}">Guestbook</title> </head> <body> <h1 class="text-center" th:text="#{guestbook.title}">Guestbook</h1> <div class="checkbox text-center"> <input type="checkbox" id="use_ajax" /> <label for="use_ajax" th:text="#{guestbook.useajax}">Use Ajax</label> </div> <div id="entries"> <div th:each="entry, it : ${entries}" th:with="index = ${it.count}"> <div class="panel panel-default" th:fragment="entry" th:id="entry+${entry.id}"> <div class="panel-heading" > <!-- <form th:method="delete" th:action="@{/guestbook/} + ${entry.id}" th:attr="data-entry-id=${entry.id}"> <button class="btn btn-default pull-right" > <span class="glyphicon glyphicon-remove"></span> </button> </form> --> <h3 th:text="${index} + '. ' + ${entry.name}">1. Posting</h3> </div> <div class="panel-body"> <blockquote class="entrytext" th:text="${entry.comment}"></blockquote> <h4>Replies:</h4> <div id="replies"> <ul th:each="reply, it : ${entry.guestReplies}" th:with="index = ${it.count}"> <li th:text="${reply.comment} + '. ' + 'replied by ---> ' + ${reply.name} "></li> </ul> </div> <button th:class="reply" th:id="${entry.id}" th:onclick="'reply('+${entry.id}+')'">Reply</button> <!-- <input type="hidden" th:id="guest_id" th:class="guest_id" th:value="${entry.id}" /> --> <!-- <footer class="date" th:text="${#temporals.format(entry.date, 'dd. MMMM yyyy - HH:mm')}">Date</footer> --> </div> </div> </div> </div> <form method="post" role="form" class="gb-form" id="form" th:action="@{/guestbook}" th:object="${form}"> <div class="form-group"> <label for="name" th:text="#{guestbook.form.name}">Name</label><br /> <input class="form-control" type="text" th:field="*{name}" th:errorclass="fieldError" required="required" /><br /> </div> <div class="form-group" > <label for="email" th:text="#{guestbook.form.email}">Email</label><br /> <input class="form-control" type="email" th:field="*{email}" /><br /> <span th:if="${#fields.hasErrors('email')}" th:errors="*{email}" class="help-block">error!</span><br /> </div> <div class="form-group"> <label for="text" th:text="#{guestbook.form.comment}">Comment</label><br /> <textarea th:field="*{comment}" th:errorclass="fieldError" class="form-control" required="required"></textarea><br /> </div> <input type="submit" class="btn btn-default" th:value="#{guestbook.form.submit}" value="Sender" /> </form> </body> </html>
import React, { useState, useEffect } from "react"; import Card from "../../../components/Card/Card"; import { verifyOtp } from "../../../helpers/http/index"; import { useSelector, useDispatch } from "react-redux"; import { setAuth } from "../../../store/auth"; import { setName } from "../../../store/userdata"; import { useHistory } from "react-router-dom"; import { sendOtp } from "../../../helpers/http/index"; import { setOtp } from "../../../store/auth"; import style from "./StepOtp.module.css"; const StepOtp = ({ onPrev }) => { const [otp1, setotp] = useState(new Array(6).fill("")); const dispatch = useDispatch(); const { phone, hash } = useSelector((state) => state.auth.otp); const name = useSelector((state) => state.userdata.name); const email = useSelector((state) => state.userdata.email); const [counter, setCounter] = useState(60); const [error, setError] = useState(""); const history = useHistory(); useEffect(() => { const timer = counter > 0 && setInterval(() => setCounter(counter - 1), 1000); return () => clearInterval(timer); }, [counter]); async function submit() { try { let otp = parseInt(otp1.join("")); if (otp.toString().length === 6) { const { data } = await verifyOtp({ otp, phone, hash, name, email }); dispatch(setAuth(data)); dispatch(setName(data.user.name)); history.goBack(); } else { setError("Please Enter 6 digits OTP"); } } catch (err) { console.log("érr", err.message); } } const handleChange = (element, index) => { if (isNaN(element.value)) return false; setotp([...otp1.map((d, idx) => (idx === index ? element.value : d))]); if (element.nextSibling) { element.nextSibling.focus(); } if (element.value.length === 0) { if (element.previousElementSibling) { element.previousElementSibling.focus(); } else { element.focus(); } } }; async function resend() { try { const { data } = await sendOtp({ phone }); console.log(data); setCounter(60); dispatch(setOtp({ phone: data.phone, hash: data.hash })); } catch (err) { console.log("resend", err.message); } } // function goback() { // onPrev(); // } return ( <Card title="Enter OTP"> <div style={{ marginBottom: "1.5px", marginTop: "-10px", letterSpacing: "1px", }} > OTP Sent to {phone} </div> <div className={`${style.userInput}`}> {otp1.map((data, index) => { return ( <input type="text" className={`${style.otp_input}`} maxLength="1" key={index} value={data} onChange={(e) => handleChange(e.target, index)} /> ); })} </div> <button text="VERIFY" onClick={submit} className={`${style.button} root_button`} > Verify </button> {error ? ( <p style={{ color: "red", fontSize: "12px", marginTop: "10px" }}> {error} </p> ) : ( "" )} <p className={`${style.resend}`}> {counter > 0 ? counter > 9 ? `Resend OTP in 00:${counter} ` : `Resend OTP in 00:0${counter} ` : `Didn't receive the otp?`} {counter > 0 ? ( "" ) : ( <span className={`${style.resend_button}`} onClick={resend}> Resend OTP </span> )} </p> {/* <div className="flex items-center justify-center bg-gray-100 px-2 py-1.5 " style={{ borderRadius: "42px", cursor: "pointer" }} onClick={goback} > <img src="./images/leftarrow.svg" alt="go back" style={{ width: "11px" }} /> <button style={{ fontSize: "14px", marginLeft: "5px" }} className="text-gray-700" > Go back </button> </div> */} </Card> ); }; export default StepOtp;
<?php namespace WebApp\Auth; use \WebApp\Application; use \WebApp\DataModel\UserRole; /** * Checks the roles of a user (required method on principal is getRoles(). */ class UserRoleAuthorizator extends AbstractAuthorizator { public function __construct(Application $app, $config = NULL) { parent::__construct($app, $config); if (isset($this->config['roles'])) { $this->roles = json_decode(json_encode($this->config['roles']), TRUE); } else { $this->roles = array(); } // Caching $this->grantResults = array(); $this->subroles = array(); } protected function init() { parent::init(); } /** * Authorizes a user. * @param Principal $user - the user to be authorized. * @param mixed $required - the required role. * @return TRUE when principal was authorized */ public function authorize($user, $required) { // Least privilege: everyone if ($required == UserRole::ROLE_GUEST) return TRUE; // From here on we need a user object if ($user != NULL) { if (!isset($this->grantResult[$required.'-'.$user->uid])) { // Least privilege: any user if ($required == UserRole::ROLE_USER) { $this->grantResult[$required.'-'.$user->uid] = TRUE; } else { $roles = $user->getRoles(); // Superadmins are always authorized if (in_array(UserRole::ROLE_SUPERADMIN, $roles)) { $this->grantResult[$required.'-'.$user->uid] = TRUE; } else { // Search the specific role $this->grantResult[$required.'-'.$user->uid] = $this->isGranted($required, $roles); } } } return $this->grantResult[$required.'-'.$user->uid]; } return FALSE; } protected function isGranted($required, $granted) { $grantedExploded = $this->explodeRoles($granted); return in_array($required, $grantedExploded); } /** List all roles that are explicitely and implicitely part of the given roles */ protected function explodeRoles($roles) { $rc = array(); foreach ($roles AS $role) { if (!isset($this->subroles[$role])) { // The granted role itself of course $this->subroles[$role] = array($role); // And all its children foreach ($this->getRoleChildren($role) AS $child) { $this->subroles[$role][] = $child; } } $rc = array_merge($rc, $this->subroles[$role]); } return $rc; } protected function getRoleChildren($role) { // Search the tree; $tree = $this->getRoleTree($role, $this->roles); // Not found => No children if ($tree == NULL) return array(); // Flatten the hierarchy return $this->collectSubRoles($tree); } /** Can return NULL when needle not found. Otherwise returns the array with children. */ protected function getRoleTree($needle, $treeNode) { foreach ($treeNode AS $key => $value) { if (is_int($key) && ($value == $needle)) { // simple role name, no children return array(); } else if (is_string($key)) { if ($key == $needle) return $value; else { $found = $this->getRoleTree($needle, $value); if ($found != NULL) return $found; } } } return NULL; } /** Takes the tree and returns all defined roles in there */ protected function collectSubRoles($node) { $rc = array(); foreach ($node AS $key => $value) { if (is_int($key)) $rc[] = $value; else { $rc[] = $key; $rc = array_merge($rc, $this->collectSubRoles($value)); } } return $rc; } }
Please act as a professional verilog designer. Implement the design of 4bit unsigned number pipeline multiplier. It consists of two levels of registers to store intermediate values and control the multiplication process. Module name: multi_pipe_4bit Input ports: clk: Clock signal used for synchronous operation. rst_n: Active-low reset signal. Defined as 0 for chip reset and 1 for reset signal inactive. mul_a: Input signal representing the multiplicand with a data width of "size" bits. mul_b: Input signal representing the multiplier with a data width of "size" bits. Output ports: mul_out: Product output signal with a data width of 2*size bits. Parameter: size = 4 Implementation: Extension of input signals: The input signals (mul_a and mul_b) are extended by adding "size" number of zero bits at the most significant bit positions. Multiplication operation: The module uses a generate block to perform multiplication for each bit position of the multiplier (mul_b) and generate the partial products. For each bit position i from 0 to size-1, the partial product is calculated as follows: If the corresponding bit in the multiplier is 1, the multiplicand is left-shifted by i positions. If the corresponding bit in the multiplier is 0, the partial product is set to 0 ('d0). Add of partial products: The module uses registers to store the intermediate sum values. On the positive edge of the clock signal (clk) or the falling edge of the reset signal (rst_n), the module performs add operations. If the reset signal (rst_n) is low, indicating a reset condition, the registers are set to 0. If the reset signal (rst_n) is high, the registers are updated with the sum of the corresponding partial products. Final product calculation: On the positive edge of the clock signal (clk) or the falling edge of the reset signal (rst_n), the module calculates the final product. If the reset signal (rst_n) is low, indicating a reset condition, the product output (mul_out) is set to 0. If the reset signal (rst_n) is high, the product output (mul_out) is updated with the sum of registers. Give me the complete code.
/** * */ package com.br.sobieskiproducoes.geradormateriasjoomla.cargaemmassa.service; import java.time.LocalDateTime; import java.util.List; import java.util.UUID; import org.springframework.stereotype.Service; import com.br.sobieskiproducoes.geradormateriasjoomla.cargaemmassa.controller.dto.RequisicaoCaragMassaDTO; import com.br.sobieskiproducoes.geradormateriasjoomla.cargaemmassa.model.CargaMassaEntity; import com.br.sobieskiproducoes.geradormateriasjoomla.cargaemmassa.repository.CargaMassaRepository; import com.br.sobieskiproducoes.geradormateriasjoomla.dto.StatusProcessamentoEnum; import com.br.sobieskiproducoes.geradormateriasjoomla.mapaperguntas.controller.dto.MapaPerguntaDTO; import com.br.sobieskiproducoes.geradormateriasjoomla.mapaperguntas.service.GerarMapaPerguntasService; import com.br.sobieskiproducoes.geradormateriasjoomla.utils.MateriaUtils; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; import lombok.extern.java.Log; /** * @author Jorge Demetrio * @since 25 de fev. de 2024 09:44:23 * @version 1.0.0 */ @Log @RequiredArgsConstructor @Service public class CargaMateriaEmMassaService { private final GerarMapaPerguntasService gerarMapaPerguntasService; private final CargaMassaRepository repository; private final ObjectMapper objectMapper; public List<MapaPerguntaDTO> processar(final RequisicaoCaragMassaDTO request) throws Exception { log.info("Inicio processamento ".concat(LocalDateTime.now().toString())); final String uuid = UUID.randomUUID().toString(); final List<MapaPerguntaDTO> itens = gerarMapaPerguntasService.gerarMapa(request.getIdeias(), uuid); try { repository.save(new CargaMassaEntity(null, uuid, StatusProcessamentoEnum.PROCESSAR, MateriaUtils.getLocalDateTime(request.getDataInicioPublicacao(), request.getHorario()), MateriaUtils.getLocalDateTime(request.getDataFimPublicacao(), request.getHorario()), null, null, null, objectMapper.writeValueAsString(request))); } catch (final JsonProcessingException e) { log.info("Falha ao realizar o salvamento do processo em lote ".concat(uuid)); } log.info("Concluído processamento dos mapas e vai iniciar os da materias em lote".concat(LocalDateTime.now().toString())); return itens; } }
import {Component, OnInit} from '@angular/core'; import {Customer} from "../customer.model"; import {Purchase} from "../purchase.model" import {PurchaseService} from "../purchase.service"; import {CustomerService} from "../customer.service"; import {Pet} from "../pet.model"; import {PetsService} from "../pets.service"; @Component({ selector: 'app-purchase', templateUrl: './purchase.component.html', styleUrls: ['./purchase.component.css'] }) export class PurchaseComponent implements OnInit { pets: Pet[]; customers: Customer[]; selectedPet: Pet; selectedCustomer: Customer; purchases: Purchase[]; selectedPurchase: Purchase; constructor(private purchaseService: PurchaseService, private petsService: PetsService, private customerService: CustomerService) { } makePurchase(price: string, dateAcquired: string, review: string) { console.log(price) console.log(dateAcquired) console.log(review) this.purchaseService.add({ pet: this.selectedPet, customer: this.selectedCustomer, price: Number(price), dateAcquired: new Date(dateAcquired), review: Number(review) } as Purchase).subscribe( _ => this.getPurchases() ) } filterWithReview(review: string) { this.purchaseService.getPurchasesWithMinimumReview(Number(review)).subscribe(purchases => this.purchases = purchases.purchases); } onSelect(purchase: Purchase) { this.selectedPurchase = purchase; console.log(purchase) } onSelectPet(pet: Pet) { this.selectedPet = pet; } onSelectCustomer(customer: Customer) { this.selectedCustomer = customer; } delete(purchase: Purchase) { this.purchaseService.delete(purchase.pet.id, purchase.customer.id).subscribe( _ => this.getPurchases() ) } getPurchases() { this.purchaseService.getPurchases().subscribe( purchases => this.purchases = purchases.purchases ) } getPets() { this.petsService.getPets().subscribe( pets => this.pets = pets.pets ) } getCustomers() { this.customerService.getCustomers().subscribe( customers => this.customers = customers.customers ) } ngOnInit(): void { this.getPurchases(); this.getPets(); this.getCustomers(); } }
# pv entity setLabelsByUniqueAttribute [Command Reference](../../../README.md#command-reference) > [entity](./main.md) > setLabelsByUniqueAttribute ## Description Overwrite labels for an entity identified by its type and unique attributes. ## Syntax ``` pv entity setLabelsByUniqueAttribute --typeName=<val> --qualifiedName=<val> --payloadFile=<val> ``` ## Required Arguments `--typeName` (string) The name of the type. `--qualifiedName` (string) The qualified name of the entity. `--payloadFile` (string) File path to a valid JSON document. ## Optional Arguments *None* ## API Mapping Catalog Data Plane > Entity > [Set labels to a given entity identified by its type and unique attributes.](https://docs.microsoft.com/en-us/rest/api/purview/catalogdataplane/entity/set-labels-by-unique-attribute) ``` POST https://{accountName}.purview.azure.com/catalog/api/atlas/v2/entity/uniqueAttribute/type/{typeName}/labels ``` ## Examples Overwrite labels property for an existing entity identified by its type and unique attributes. ```powershell pv entity setLabelsByUniqueAttribute --typeName "azure_datalake_gen2_resource_set" --qualifiedName "https://STORAGE_ACCOUNT.dfs.core.windows.net/bing/data/{N}/QueriesByCountry_{Year}-{Month}-{Day}_{N}-{N}-{N}.tsv" --payloadFile "/path/to/file.json" ``` <details><summary>Example payload.</summary> <p> ```json [ "a", "b", "c" ] ``` </p> </details>
#include "request_parser.h" #include "json_processing/json_reader.h" #include "exceptions.h" #include "json_processing/exceptions.h" #include <optional> ParsedInboundMessage InboundMessageParser::parseRawInboundMessage(const RawInboundMessage& rawInboundMessage) { const MessageType messageType = parseRequestType(rawInboundMessage); const CorrelationId& correlationId = parseCorrelationId(rawInboundMessage); return ParsedInboundMessage(messageType, rawInboundMessage.getMessageBody(), rawInboundMessage.getSenderId(), correlationId); } MessageType InboundMessageParser::parseRequestType(const RawInboundMessage& rawInboundMessage) { try { JsonReader jsonReader(rawInboundMessage.getMessageBody().toString()); if(jsonReader.hasKey(MessageContract::TYPE)) { const std::string messageType = jsonReader.getStringValue(MessageContract::TYPE); if(messageType == MessageContract::MessageType::RequestType::GET_CONFIG_REQUEST) { return MessageType(MessageContract::MessageType::RequestType::GET_CONFIG_REQUEST); } else if(messageType == MessageContract::MessageType::RequestType::CALCULATE_EXCHANGE_REQUEST) { return MessageType(MessageContract::MessageType::RequestType::CALCULATE_EXCHANGE_REQUEST); } else if(messageType == MessageContract::MessageType::RequestType::UPDATE_CACHE_REQUEST) { return MessageType(MessageContract::MessageType::RequestType::UPDATE_CACHE_REQUEST); } else { throw InboundMessageError("Error, unrecognized message type: " + messageType); } } else { throw InboundMessageError("Error, message does not have type"); } } catch(const JsonParseError& jsonParseError) { throw InboundMessageError("Error, message is not a valid JSON"); } } CorrelationId InboundMessageParser::parseCorrelationId(const RawInboundMessage& rawInboundMessage) { JsonReader jsonReader(rawInboundMessage.getMessageBody().toString()); if(jsonReader.hasKey(MessageContract::CORRELATION_ID)) { return static_cast<CorrelationId>(jsonReader.getStringValue(MessageContract::CORRELATION_ID)); } else { throw InboundMessageError("Error, message does not have correlation ID"); } } GetConfigRequest InboundMessageParser::parseToGetConfigRequest(const ParsedInboundMessage& parsedInboundMessage) { JsonReader jsonReader(parsedInboundMessage.getMessageBody().toString()); return {parsedInboundMessage.getMessageBody(), parsedInboundMessage.getCorrelationId()}; } CalculateExchangeRequest InboundMessageParser::parseToCalculateExchangeRequest(const ParsedInboundMessage& parsedInboundMessage) { JsonReader jsonReader(parsedInboundMessage.getMessageBody().toString()); std::optional<CurrencyCode> sourceCurrencyCode; std::optional<CurrencyCode> targetCurrencyCode; std::optional<MoneyAmount> moneyAmount; if(jsonReader.hasKey(MessageContract::MessageContent::CalculateExchangeRequestContract::SOURCE_CURRENCY)) { sourceCurrencyCode = CurrencyCode(jsonReader.getStringValue(MessageContract::MessageContent::CalculateExchangeRequestContract::SOURCE_CURRENCY)); } else { std::string errorMessage = "Error, " + MessageContract::MessageType::RequestType::CALCULATE_EXCHANGE_REQUEST + " does not have field: " + MessageContract::MessageContent::CalculateExchangeRequestContract::SOURCE_CURRENCY; throw InboundMessageError(errorMessage); } if(jsonReader.hasKey(MessageContract::MessageContent::CalculateExchangeRequestContract::TARGET_CURRENCY)) { targetCurrencyCode = CurrencyCode(jsonReader.getStringValue(MessageContract::MessageContent::CalculateExchangeRequestContract::TARGET_CURRENCY)); } else { std::string errorMessage = "Error, " + MessageContract::MessageType::RequestType::CALCULATE_EXCHANGE_REQUEST + " does not have field: " + MessageContract::MessageContent::CalculateExchangeRequestContract::TARGET_CURRENCY; throw InboundMessageError(errorMessage); } if(jsonReader.hasKey(MessageContract::MessageContent::CalculateExchangeRequestContract::MONEY_AMOUNT)) { moneyAmount = MoneyAmount(jsonReader.getStringValue(MessageContract::MessageContent::CalculateExchangeRequestContract::MONEY_AMOUNT)); } else { std::string errorMessage = "Error, " + MessageContract::MessageType::RequestType::CALCULATE_EXCHANGE_REQUEST + " does not have field: " + MessageContract::MessageContent::CalculateExchangeRequestContract::MONEY_AMOUNT; throw InboundMessageError(errorMessage); } return {parsedInboundMessage.getMessageBody(), parsedInboundMessage.getCorrelationId(), sourceCurrencyCode.value(), targetCurrencyCode.value(), moneyAmount.value()}; } UpdateCacheRequest InboundMessageParser::parseToUpdateCacheRequest(const ParsedInboundMessage& parsedInboundMessage) { JsonReader jsonReader(parsedInboundMessage.getMessageBody().toString()); return {parsedInboundMessage.getMessageBody(), parsedInboundMessage.getCorrelationId()}; }
import React, {useState} from 'react'; import { CircularProgress, Grid, Typography, InputLabel, MenuItem, FormControl, Select } from '@material-ui/core'; import PlaceDetails from '../PlaceDetails/PlaceDetails'; import useStyles from './styles'; const List = () => { const classes = useStyles(); const [type, setType] = useState('restaurant'); const [rating, setRating] = useState('0'); const places = [ {name: 'dubai'}, {name: 'morocco'}, {name: 'miami'}, {name: 'mumbai'}, {name: 'dubai'}, {name: 'morocco'}, ] return( <div className={classes.container}> <Typography variant='h4'>Restaurants, Hotels & Attractions around you</Typography> <FormControl className={classes.formControl}> <InputLabel>Type</InputLabel> <Select value={type} onChange={(e) => setType(e.target.value)}> <MenuItem value='restaurant'>Restaurants</MenuItem> <MenuItem value='hotel'>Hotels</MenuItem> <MenuItem value='attraction'>Attractions</MenuItem> </Select> </FormControl> <FormControl className={classes.formControl}> <InputLabel>Rating</InputLabel> <Select value={rating} onChange={(e) => setRating(e.target.value)}> <MenuItem value='0'>All</MenuItem> <MenuItem value='3'>Above 3</MenuItem> <MenuItem value='4'>Above 4</MenuItem> <MenuItem value='5'>Above 4.5</MenuItem> </Select> </FormControl> <Grid container spacing={3} className={classes.list}> {places?.map((place, i) =>( <Grid item key={i} xs={12}> <PlaceDetails place={place} /> </Grid> ))} </Grid> </div> ); } export default List;
local devotion_kill = CreatureEvent("devotion_kill") local bossPoints = { ["Scarlett Etzel"] = 10, ["Grand Master Oberon"] = 20, } function devotion_kill.onKill(player, target) if target:isPlayer() or target:getMaster() then return true end local targetName = target:getName() local devotion = bossPoints[targetName] local damageMap = target:getDamageMap() for key, value in pairs(damageMap) do local attackerPlayer = Player(key) if attackerPlayer then if devotion then attackerPlayer:sendTextMessage(MESSAGE_EVENT_ADVANCE, "For killing the Boss " .. targetName .. " you were awarded " .. devotion .. " Devotion Points.") attackerPlayer:addDevotion(devotion) end end end return true end devotion_kill:register() local devotionLogin = CreatureEvent("devotionLogin") function devotionLogin.onLogin(player) player:registerEvent("devotion_kill") return true end devotionLogin:register() local talk = TalkAction("!devotion") local exhaust = {} local exhaustTime = 2 local skill = {MagicLevel = 700, Fist = 200, Club = 500, Sword = 500, Axe = 500, Distance = 600, HealthMax = 1200, ManaMax = 1200} function talk.onSay(player, words, param) local playerId = player:getId() local currentTime = os.time() if exhaust[playerId] and exhaust[playerId] > currentTime then player:sendCancelMessage("You are on cooldown, wait (0." .. exhaust[playerId] - currentTime .. "s).") return false end if param == "magic level" then local skillCost = skill.MagicLevel if player:getDevotion() >= skillCost then player:addDevotion(-skillCost) player:popupFYI("[Devotion System]\nYou just added +1 Magic Level per "..skillCost.." Devotion Points.\n\nNow you have:\n[+] "..player:getDevotion().." Devotion Points.") player:addMagicLevel(1) return false else player:popupFYI("[Devotion System]\nYou don't have enough devotion points.") exhaust[playerId] = currentTime + exhaustTime return false end elseif param == "fist" or param == "fist fighting" then local skillCost = skill.Fist if player:getDevotion() >= skillCost then player:addDevotion(-skillCost) player:popupFYI("[Devotion System]\nYou just added +1 Fist Fighting per "..skillCost.." Devotion Points.\n\nNow you have:\n[+] "..player:getDevotion().." Devotion Points.") player:addSkillTries(SKILL_FIST, player:getVocation():getRequiredSkillTries(SKILL_FIST, player:getSkillLevel(SKILL_FIST) + 1) - player:getSkillTries(SKILL_FIST), true) return false else player:popupFYI("[Devotion System]\nYou don't have enough devotion points.") exhaust[playerId] = currentTime + exhaustTime return false end elseif param == "club" or param == "club fighting" then local skillCost = skill.Club if player:getDevotion() >= skillCost then player:addDevotion(-skillCost) player:popupFYI("[Devotion System]\nYou just added +1 Club Fighting per "..skillCost.." Devotion Points.\n\nNow you have:\n[+] "..player:getDevotion().." Devotion Points.") player:addSkillTries(SKILL_CLUB, player:getVocation():getRequiredSkillTries(SKILL_CLUB, player:getSkillLevel(SKILL_CLUB) + 1) - player:getSkillTries(SKILL_CLUB), true) return false else player:popupFYI("[Devotion System]\nYou don't have enough devotion points.") exhaust[playerId] = currentTime + exhaustTime return false end elseif param == "sword" or param == "sword fighting" then local skillCost = skill.Sword if player:getDevotion() >= skillCost then player:addDevotion(-skillCost) player:popupFYI("[Devotion System]\nYou just added +1 Sword Fighting per "..skillCost.." Devotion Points.\n\nNow you have:\n[+] "..player:getDevotion().." Devotion Points.") player:addSkillTries(SKILL_SWORD, player:getVocation():getRequiredSkillTries(SKILL_SWORD, player:getSkillLevel(SKILL_SWORD) + 1) - player:getSkillTries(SKILL_SWORD), true) return false else player:popupFYI("[Devotion System]\nYou don't have enough devotion points.") exhaust[playerId] = currentTime + exhaustTime return false end elseif param == "axe" or param == "axe fighting" then local skillCost = skill.Axe if player:getDevotion() >= skillCost then player:addDevotion(-skillCost) player:popupFYI("[Devotion System]\nYou just added +1 Axe Fighting per "..skillCost.." Devotion Points.\n\nNow you have:\n[+] "..player:getDevotion().." Devotion Points.") player:addSkillTries(SKILL_AXE, player:getVocation():getRequiredSkillTries(SKILL_AXE, player:getSkillLevel(SKILL_AXE) + 1) - player:getSkillTries(SKILL_AXE), true) return false else player:popupFYI("[Devotion System]\nYou don't have enough devotion points.") exhaust[playerId] = currentTime + exhaustTime return false end elseif param == "distance" or param == "distance fighting" then local skillCost = skill.Distance if player:getDevotion() >= skillCost then player:addDevotion(-skillCost) player:popupFYI("[Devotion System]\nYou just added +1 Distance Fighting per "..skillCost.." Devotion Points.\n\nNow you have:\n[+] "..player:getDevotion().." Devotion Points.") player:addSkillTries(SKILL_DISTANCE, player:getVocation():getRequiredSkillTries(SKILL_DISTANCE, player:getSkillLevel(SKILL_DISTANCE) + 1) - player:getSkillTries(SKILL_DISTANCE), true) return false else player:popupFYI("[Devotion System]\nYou don't have enough devotion points.") exhaust[playerId] = currentTime + exhaustTime return false end elseif param == "health" or param == "health max" then local skillCost = skill.HealthMax if player:getDevotion() >= skillCost then player:addDevotion(-skillCost) player:popupFYI("[Devotion System]\nYou just added +10 Health Max per "..skillCost.." Devotion Points.\n\nNow you have:\n[+] "..player:getDevotion().." Devotion Points.") player:setMaxHealth(player:getMaxHealth() + 10) return false else player:popupFYI("[Devotion System]\nYou don't have enough devotion points.") exhaust[playerId] = currentTime + exhaustTime return false end elseif param == "mana" or param == "mana max" then local skillCost = skill.ManaMax if player:getDevotion() >= skillCost then player:addDevotion(-skillCost) player:popupFYI("[Devotion System]\nYou just added +10 Mana Max per "..skillCost.." Devotion Points.\n\nNow you have:\n[+] "..player:getDevotion().." Devotion Points.") player:setMaxMana(player:getMaxMana() + 10) return false else player:popupFYI("[Devotion System]\nYou don't have enough devotion points.") exhaust[playerId] = currentTime + exhaustTime return false end return false end local text = "[Devotion System]\nPoints are stored as you kill bosses.\n\nYou have:\n[+] "..player:getDevotion().." Devotion Points.\n---------->\nRemember that you can use these points to get an\nextra skill or increase life or mana.\n\nMagic Level: Sword Fighting:\n[+] "..skill.MagicLevel.." Devotion Points. [+] "..skill.Sword.." Devotion Points.\n\nFist Fighting: Axe Fighting:\n[+] "..skill.Fist.." Devotion Points. [+] "..skill.Axe.." Devotion Points.\n\nClub Fighting: Distance Fighting:\n[+] "..skill.Club.." Devotion Points. [+] "..skill.Distance.." Devotion Points.\n---------->\nKeep in mind that you only add 1 to the skill, if you\nchoose Magic Level then +1 will be added to both the\nother skills.\n\nExtra attributes:\nHealth Max: Mana Max:\n[+] "..skill.HealthMax.." Devotion Points. [+] "..skill.ManaMax.." Devotion Points.\n---------->\nFor health you would add 10 life points for both\n10 mana points.\n\nTo use the points, just say !devotion [skillname]\nEx: !devotion magic level." player:popupFYI(text) exhaust[playerId] = currentTime + exhaustTime return false end talk:separator(" ") talk:register()
import * as crypto from "crypto"; import Block from "./block"; import Transaction from "./transaction"; class Chain { public static instance = new Chain(); chain: Array<Block>; constructor() { this.chain = [new Block(null, new Transaction(1000, "genesis", "turtle"))]; } get lastBlock(): Block { return this.chain[this.chain.length - 1]; } private mine(nonce: number) { let solution = 1; console.log("mining..."); while (true) { const hash = crypto.createHash("MD5"); hash.update((nonce + solution).toString()).end; const attempt = hash.digest("hex"); if (attempt.substr(0, 4) === "0000") { console.log(`Solved: ${solution}`); return solution; } solution++; } } public addBlock( transaction: Transaction, senderPublicKey: string, signature: Buffer ) { const verifier = crypto.createVerify("SHA256"); verifier.update(transaction.toString()); const isValid = verifier.verify(senderPublicKey, signature); if (!isValid) return; const newBlock = new Block(this.lastBlock.hash, transaction); this.mine(newBlock.nonce); this.chain.push(newBlock); } } export default Chain;
<h1>Pedro Lucas dos Santos Rodrigues</h1> </br> <img src="imagens/foto perfil.jpg" width="350"> </p> <h2>Projeto 1: 2º Semestre de 2020</h2> <H3> Easy Way </H3> <H4> Interno - FATEC </H4> <img width="250" src="imagens/Quadrados_Pretos_e_Brancos_Industrial_Logotipo.png"> <h3>Descrição do Projeto</h3> O aplicativo "Easy Way" visa resolver os problemas enfrentados pelos motoristas de vans em relação ao gerenciamento de rotas e tempo de viagem. Muitas vezes, os motoristas enfrentam dificuldades quando os usuários não comunicam previamente sua intenção de utilizar o serviço, resultando em perda de tempo e gastos extras. Além disso, quando os usuários comunicam, ainda há a necessidade de ajustar as rotas, o que também consome tempo. Portanto, o VanConnect é uma solução que visa otimizar esses processos, garantindo uma experiência mais eficiente para motoristas e passageiros. <h3>Tecnologias Utilizadas</h3> <h4>AppInventor</h4> <img width="250" src="imagens/AppInventor.png"> O App Inventor é uma ferramenta de desenvolvimento de aplicativos para Android criada pelo Google e agora mantida pelo MIT. Ele permite que pessoas sem conhecimento avançado em programação criem aplicativos móveis usando uma interface gráfica intuitiva de arrastar e soltar, tornando o desenvolvimento de aplicativos mais acessível para uma variedade de usuários. <h4>Firebase</h4> <img width="250" src="imagens/Firebase.jpg"> O Firebase é uma plataforma de desenvolvimento de aplicativos oferecida pelo Google, que fornece uma variedade de serviços úteis, como armazenamento em nuvem, autenticação de usuários e banco de dados em tempo real. Ele simplifica o desenvolvimento de aplicativos, permitindo que os desenvolvedores se concentrem na lógica do aplicativo, enquanto o Firebase cuida da infraestrutura de back-end. ## Contribuições pessoais Por ser o primeiro projeto, dediquei meu tempo aos estudos e trabalhar em conjunto com o time de desenvolvimento da equipe, atuando principalmente na parte logica o AppInventor para construir tanto a interface grafica quanto suas funcionalidades. Atuei na construção de métodos para expor os dados de maneira clara e organizada. <h2>Projeto 2: 1º Semestre de 2022</h2> ### Empresa parceira <p align="center"> <b>Dom Rock</b> </br> <img src="https://github.com/alantrs/Bertoti/blob/efd7a4e3055f78276feb65f55b0702623e0f2636/metodologia/Imagens/domrock2.png" alt="Logo dom rock"> </p> ## Descrição do projeto Este projeto visa gerenciar a ativação de clientes na plataforma Dom Rock. A solução proposta concentra-se na entrada de dados, incluindo parâmetros e variáveis específicas de cada cliente, para efetuar a alocação adequada de recursos na plataforma. A abordagem inclui a estimativa de consumo de recursos, considerando fatores como o volume de dados do cliente e o número de usuários. Adicionalmente, a solução é projetada para gerar relatórios e consultas. ## Tecnologias utilizadas - **Java**: Linguagem orientada a objetos, foi escolhida para o desenvolvimento do back-end devido à familiaridade prévia da equipe, ampla utilização no mercado e extensa documentação, facilitando a implementação do projeto. - **PostgreSQL**: PostgreSQL é um sistema de gerenciamento de banco de dados relacional de código aberto que é amplamente utilizado em aplicações empresariais e científicas, devido à sua confiabilidade, escalabilidade e recursos avançados. Além disso, o PostgreSQL é compatível com muitas linguagens de programação, incluindo Java, que foi usada neste projeto. ## Contribuições pessoais Fui o administrador do banco de dados da equipe. Desenvolvi a modelagem de dados e a criação da base de dados por completo. Ajudei a equipe de backend sendo solicitado por melhorias na distribuição dos dados promovendo a maior facilidade para manipulação dos mesmos. <br> <details> <summary><b>Modelagem do banco de dados</b></summary> <br> Nesse projeto, o objetivo da modelagem de dados foi representar os dados inseridos pelo cliente e como seria distribuido na nossa base. Utilizei o Modelo Entidade-Relacionamento (MER) como uma representação visual para entender a distribuição das tabelas com seus atributos e relacionamento entre elas. ![Modelagem do banco de dados](https://github.com/alantrs/Bertoti/blob/778fd69f6e9fecddd2342af75295ff9542562f1e/metodologia/Imagens/modelagem-domrock.jpeg) </details> <details> <summary><b>Implementação física do banco de dados</b></summary> <br> A implementação física é uma etapa fundamental na modelagem de dados, pois envolve a tradução do modelo conceitual em uma estrutura de dados real e eficiente para armazenar e processar os dados em um sistema de banco de dados. Ela é importante para garantir a eficiência, a integridade, a segurança e o desempenho do banco de dados, bem como sua escalabilidade e facilidade de manutenção. ```SQL CREATE TABLE public.produto ( solucao character varying COLLATE pg_catalog."default" NOT NULL, nome_produto character varying COLLATE pg_catalog."default" NOT NULL, id_produto serial NOT NULL, CONSTRAINT produto_pkey PRIMARY KEY (id_produto), CONSTRAINT produto_nome_produto_key UNIQUE (nome_produto) ) CREATE TABLE public.funcionalidade ( id_funcionalidade serial NOT NULL, nome_funcionalidade character varying COLLATE pg_catalog."default" NOT NULL, CONSTRAINT funcionalidade_pkey PRIMARY KEY (id_funcionalidade), CONSTRAINT funcionalidade_nome_funcionalidade_key UNIQUE (nome_funcionalidade) ) CREATE TABLE public.core ( id_core serial NOT NULL, nome_core character varying COLLATE pg_catalog."default" NOT NULL, CONSTRAINT core_pkey PRIMARY KEY (id_core), CONSTRAINT core_nome_core_unique UNIQUE (nome_core) ) ``` </details> ## Aprendizados efetivos Aprendi a base para criar um banco de dados. Como iniciar uma modelagem de dados, definir cardinalidades e tranformar o modelo conceitual em script SQL. Aprendi alguns comandos básicos para trabalhar com versionamento de código com Git. ### Hard Skills <details> <summary><b>Recursos básicos de Banco de dados: sei fazer com autonomia</b></summary> <br> <ul> <li>Estrutura do banco, distribuição das tabelas</li> <Li>Modelo conceitual, Modelo lógico e Modelo físico</Li> <Li>Criar script</Li> <Li>Realizar querys simples</Li> </ul> </details> <details> <summary><b>Git: sei fazer com autonomia</b></summary> <br> <ul> <li>Comandos básicos: git add, git commit, git pull, git push</li> <Li>Criar branches</Li> </ul> </details> ### Soft Skills <details> <summary><b>Adaptação</b></summary> <br> <ul> <li>Lidar com uma equipe totalmente nova exigiu rápida adaptação e flexibilidade para nos ajustarmos ao ambiente e às dinâmicas de trabalho. A capacidade de ser flexível e adaptável foi essencial para responder de forma eficaz às mudanças e desafios que surgiram, permitindo-nos manter o foco no objetivo final e atender às necessidades do cliente de maneira ágil e eficiente</li> </ul> </details> <details> <summary><b>Aprendizado contínuo</b></summary> <br> <ul> <li>A partir desse semetre foi introduzido a tecnologia de banco de dados para a aplicação a ser desenvolvida, e foi necessário estudar para aprender sobre SQL e sobre PostgreSQL.</li> </ul> </details> <hr> <h2>Projeto 3: 2º Semestre de 2022</h2> <h3>Parceiro Acadêmico</h3> <img width="250" src="https://www.iacit.com.br/imgs/meta-image.jpg"> <h3>Descrição do Projeto</h3> Foi criado um sistema avançado para o manejo eficiente de dados meteorológicos, com recursos de importação, pesquisa e geração de relatórios. Além disso, o sistema integra-se de forma automatizada ao banco de dados desenvolvido para ter a maior eficiencia no gerenciamento do mesmo, permitindo a obtenção e armazenamento dos dados disponibilizados por eles. A interface web do sistema oferece uma ampla gama de opções de filtragem, possibilitando a seleção precisa dos registros com base em datas, regiões, estados, localidades e tipos de dados específicos. A apresentação dos dados é realizada por meio de gráficos visualmente atrativos, e os usuários têm a opção de exportar um relatório personalizado com base na consulta efetuada. Esse sistema oferece uma solução completa para o acompanhamento e análise detalhada das condições meteorológicas, com facilidade de acesso e uso intuitivo. <h3>Tecnologias Utilizadas</h3> <h4>PostgreSQL</h4> <img width="250" src="https://www.luiztools.com.br/wp-content/uploads/2021/02/postgres.jpg"> O sistema utiliza o PostgreSQL como banco de dados principal para armazenar e gerenciar as informações. O PostgreSQL é uma escolha confiável para lidar com grandes volumes de dados meteorológicos. Ele oferece recursos avançados de consulta e recuperação eficiente dos dados. Além disso, o PostgreSQL possui medidas de segurança abrangentes, como controle de acesso e permissões, para proteger as informações armazenadas, que foi amplamente utilizados no projeto. Sua utilização garante a integridade e consistência dos dados, proporcionando um ambiente confiável para o sistema. <h4>Java Spring</h4> <img width="250" src="https://4.bp.blogspot.com/-ou-a_Aa1t7A/W6IhNc3Q0gI/AAAAAAAAD6Y/pwh44arKiuM_NBqB1H7Pz4-7QhUxAgZkACLcBGAs/s1600/spring-boot-logo.png"> O back end do sistema foi desenvolvido usando o Java Spring. O Java Spring é um framework poderoso que nos permite criar a lógica e manipular os dados do banco de dados de forma centralizada. Ele facilita o processamento das solicitações, o acesso aos dados e a implementação das regras de negócio. Com o Java Spring, podemos importar os dados meteorológicos, realizar pesquisas e filtragens, gerar relatórios e disponibilizar os dados para a interface web. Além disso, ele facilita a integração com o PostgreSQL, garantindo um acesso eficiente aos dados armazenados. O uso do Java Spring torna o desenvolvimento do back end mais organizado e eficiente, permitindo uma manipulação otimizada dos dados. <h4>JavaScript</h4> <img width="250" src="https://static.javatpoint.com/images/javascript/javascript_logo.png"> JavaScript é uma linguagem de programação amplamente utilizada no desenvolvimento web. Ela oferece interatividade e dinamismo às páginas, permitindo a manipulação de elementos HTML, estilos CSS e a interação com o usuário. Uma das vantagens do JavaScript é sua capacidade de ser executado em diferentes plataformas, independentemente do sistema operacional. Além disso, JavaScript evoluiu ao longo dos anos, com a criação de bibliotecas e frameworks que facilitam o desenvolvimento de aplicações web mais complexas. Um exemplo disso é o REST (Representational State Transfer), uma arquitetura para criação de APIs que utiliza os princípios da web e é compatível com JavaScript. Com o uso do REST, é possível construir aplicações web escaláveis, flexíveis e de fácil integração com outros sistemas. <h4>Chart.js</h4> <img width="250" src="https://avatars.githubusercontent.com/u/10342521?s=280&v=4"> A biblioteca Chart.js é uma poderosa ferramenta em JavaScript para exibir dados em forma de gráficos em páginas da web. No nosso projeto, essa biblioteca desempenhou um papel fundamental na interface, permitindo que apresentássemos os dados meteorológicos selecionados e filtrados de maneira interativa para os usuários. Além disso, com o Chart.js, tivemos a flexibilidade de personalizar as propriedades de design dos gráficos, possibilitando a exibição personalizada de diferentes tipos de dados. <h3>Contribuições Individuais</h3> <details> <summary>Desenvolvimento e personalização dos endpoints no back-end.</summary> </br> Para que tudo isso sejá possivel, criamos um código que implementa uma API REST para manipulação de usuários em um sistema. A classe UsuarioController define os endpoints e os métodos que lidam com as requisições HTTP relacionadas aos usuários, como listar usuários, criar um novo usuário, editar um usuário existente e excluir um usuário. Através desses endpoints, os clientes podem interagir com o sistema, enviando requisições para obter informações dos usuários, criar novos usuários, atualizar informações existentes e excluir usuários. O controlador utiliza a classe UsuarioService para executar a lógica de negócio relacionada aos usuários, como acessar o banco de dados, realizar validações e manipular os objetos de usuário. Portanto, o objetivo principal do código é fornecer uma interface para a manipulação de usuários em um sistema, seguindo as práticas e convenções do padrão REST. Isso permite que os clientes interajam com o sistema de forma padronizada e eficiente, através de requisições HTTP bem definidas. ```java private UsuarioService usuarioService; public UsuarioController(UsuarioService usuarioService){ this.usuarioService = usuarioService; } @GetMapping public ResponseEntity<List<Usuario>> listaUsuarios(){ return ResponseEntity.status(200).body(usuarioService.listarUsuario()); } @PostMapping public ResponseEntity<Usuario> criarUsuario(@RequestBody Usuario usuario){ return ResponseEntity.status(201).body(usuarioService.criarUsuario(usuario)); } @PutMapping() public ResponseEntity<Usuario> editarUsuario(@RequestBody Usuario usuario){ return ResponseEntity.status(200).body(usuarioService.editarUsuario(usuario)); } @DeleteMapping("/{id}") public ResponseEntity<?> excluirUsuario(@PathVariable Integer id){ usuarioService.excluirUsuario(id); return ResponseEntity.status(204).build(); } ``` </details> <details> <summary>Consulta e manipulação de endpoints personalizados do backend.</summary> </br> Os modelos de conexão para recuperar dados do backend: Faz uma solicitação assíncrona para obter dados JSON do servidor. Armazena os dados recebidos em variáveis. Realiza iterações e manipulações nos dados para extrair informações específicas. Atualiza o conteúdo de elementos HTML no documento com os dados processados. Em resumo, o código está obtendo dados sobre temperaturas máximas de diferentes estações, realizando operações nos dados recebidos e exibindo os resultados no documento HTML. ```javascript $(document).ready(function(){ $.getJSON("/temperatura_max",function(data){ var estacoes = [] for(var i = 0; i<data.length;i++){ if(estacoes.indexOf(data[i].estacao) == -1 || estacoes.length == 0) estacoes.push(data[i].estacao) } const inventory = data; var tempMin = [] for(var i = 0;i<estacoes.length;i++){ function isCherries(fruit){ return fruit.estacao === estacoes[i]; } var usuario = inventory.find(isCherries); tempMin.push(usuario) } $(document).ready(function(){ $.getJSON("/estacoes",function(data2){ console.log("SP dado 1: "+data2[0].nome_estacao) for(var i = 0;i<5;i++){ function nomeEstacao(nomear){ return nomear.codigo == estacoes[i]; } var esta = data2.find(nomeEstacao); const prec_data = new Date(tempMin[i].temp_data); prec_data.setDate(prec_data.getDate()+1); $("#tempMinEstacaoM"+i).prepend(esta.nome_estacao) $("#tempMinM"+i).prepend("Temperatura Mínima: "+tempMin[i].temp_min+"°C") $("#tempMaxM"+i).prepend("Temperatura Máxima: "+tempMin[i].temp_max+"°C") $("#tempMinOrvalhoMinM"+i).prepend("Ponto de Orvalho Mínimo: "+tempMin[i].temp_orvalho_min+"°C") $("#tempMinOrvalhoM"+i).prepend("Ponto de Orvalho: "+tempMin[i].temp_ponto_orvalho+"°C") $("#tempMinOrvalhoMaxM"+i).prepend("Ponto de Orvalho Máximo: "+tempMin[i].temp_orvalho_max+"°C") $("#tempDataM"+i).prepend("DATA: "+prec_data.toLocaleDateString("pt-BR")) const a = document.querySelector("#verDetalhesM"+i); a.href = "/charts=temperatura="+tempMin[i].estacao+"="+tempMin[i].temp_data+"="+tempMin[i].temp_data; } }); }); }); }); ``` </details> No projeto desenvolvido, foi implementada uma solução para armazenar dados climáticos em um banco de dados e apresentá-los por meio de gráficos interativos. Você criou o backend utilizando Java Spring Boot, responsável por gerenciar as comunicações com o banco de dados e fornecer os endpoints necessários para acessar os dados. Além disso, você também realizou as comunicações no frontend, utilizando JavaScript para fazer requisições assíncronas para o backend e obter os dados climáticos. Por meio de filtros, os usuários têm a possibilidade de personalizar a visualização dos registros por datas, localidade e tipo de dado, permitindo uma análise mais precisa e específica. No aspecto visual, você desenvolveu os gráficos que apresentam os dados climáticos de forma clara e compreensível. Utilizando HTML e CSS, você criou a interface necessária para exibir os gráficos e as informações relevantes relacionadas aos dados climáticos. Em resumo, o projeto consiste em uma solução completa que engloba o desenvolvimento do backend, as comunicações no frontend e a criação dos gráficos para análise dos dados climáticos. <h4>Aprendizados Efetivos</h4> <details> <summary>Spring Framework</summary> <ul> <li>Arquitetura REST: Implementação da arquitetura REST (Representational State Transfer) para criação de APIs web.</li> <li>Integração com Banco de Dados: Integração da aplicação com banco de dados para armazenamento e recuperação de dados.</li> <li>Injeção de Dependências: Utilização do recurso de injeção de dependências do Spring para facilitar o gerenciamento de componentes e suas dependências.</li> <li>Desenvolvimento Orientado a Interfaces: Desenvolvimento de código seguindo o princípio de programação orientada a interfaces, que promove a modularidade e flexibilidade do sistema.</li> <li>Integração com Banco de Dados: Realização da integração da aplicação com banco de dados para armazenamento e recuperação de dados.</li> </ul> </details> <details> <summary>Banco de dados</summary> <ul> <li>Linguagem SQL: Familiarizei-me com a linguagem SQL (Structured Query Language) utilizada para manipulação e consulta de dados em bancos de dados relacionais. Aprendi a escrever consultas eficientes para recuperar e manipular informações.</li> <li>Bancos de Dados Relacionais: Entendi os fundamentos e características dos bancos de dados relacionais, como tabelas, chaves primárias, chaves estrangeiras, índices e normalização.</li> <li>Consultas com Condições: Entender como adicionar condições às consultas SQL para filtrar os resultados com base em critérios específicos.</li> <li>Backup e Restauração de Banco de Dados: Compreender a importância de fazer backups regulares de bancos de dados e como restaurar um backup em caso de falha.</li> </details> <details> <summary>JavaScript</summary> <ul> <li>Manipulação do DOM: Aprender a interagir com o Document Object Model (DOM) para manipular elementos HTML, como adicionar ou remover elementos, alterar conteúdo e estilos.</li> <li>Manipulação de Arrays: Compreender as operações básicas de manipulação de arrays, como adicionar elementos, remover elementos, percorrer e realizar transformações nos dados.</li> <li>AJAX e Requisições Assíncronas: Aprender a fazer requisições assíncronas usando a técnica AJAX (Asynchronous JavaScript and XML) para interagir com servidores e atualizar o conteúdo da página sem recarregá-la.</li> <li>Manipulação de Dados JSON: Aprender a trabalhar com dados JSON (JavaScript Object Notation), incluindo a serialização e desserialização de dados, e a interação com APIs que retornam dados nesse formato.</li> </ul> </details> # <h2>Projeto 2: 1º Semestre de 2023</h2> ### Empresa parceira <p align="center"> <b>Embraer</b> <img src="https://github.com/alantrs/Bertoti/blob/09db3eee9ca94737bc0fc52ef7fc1313ae6cdf71/metodologia/Imagens/embraer.png" alt="Logo embraer"> </p> ## Descrição do projeto Sistema de gerenciamento de equipamentos de voo e versões de software instalados na aeronave para pilotos freelancers. A solução foi um sistema que armazenava todas as regras de composição de itens em um banco de dados. Quando um número de chassi era consultado, o sistema recuperava as regras de composição correspondentes desse chassi no banco de dados. Em seguida, os itens compatíveis com o chassi consultado eram exibidos na tela para o usuário. ## Tecnologias utilizadas - **Java e Spring boot**: A linguagem Java foi utilizada para desenvolver todo o back-end da aplicação, utilizando o framework Spring Boot. O Spring Boot é uma estrutura que permite aos desenvolvedores criar rapidamente aplicativos web em Java, fornecendo um conjunto de ferramentas e bibliotecas que tornam a construção de aplicativos mais rápida e fácil. - **Vue.js**: Vue.js é um framework de desenvolvimento web de código aberto e progressivo. Sua arquitetura centrada em componentes oferece uma abordagem modular que facilita a construção eficiente de aplicativos complexos. Utilizamos Vue.js para o frontend da aplicação. - **Autonomous Database Oracle**: O Oracle Autonomous Database é uma solução de banco de dados em nuvem que se destaca pela automação completa, autogerenciamento e uso de machine learning. Elimina tarefas manuais, otimiza o desempenho, garante segurança e oferece escalabilidade automática, proporcionando eficiência e economia de custos. Utilizamos o autonomous database para armazenar nossa lógica de negócio. - **Ambiente Cloud Oracle**: O ambiente Cloud Oracle oferece uma infraestrutura altamente escalável e eficiente para hospedar aplicativos empresariais. Utilizamos para hospedar nossa aplicação. ## Contribuições pessoais Nesse projeto fui novamente o DBA da equipe. Desenvolvi toda estrutura da base de dados, de forma estratégica para construir um esquema robusto e que comportasse os relacionamentos complexos da melhor forma. Apliquei funções e procedures para tratamento da logica de instalação de itens em uma aeronave. Apliquei o uso de triggers para fins de auditoria para captar eventos. Apliquei o uso de views para visualização de dados. <br> <details> <summary><b>Modelagem do banco de dados</b></summary> <br> No caso deste projeto, o objetivo da modelagem de dados foi representar os dados de boletins de serviço, itens e chassi. Essa modelagem foi estratégica para facilitar a consulta da lógica interna de instalações de itens em uma aeronave. O objetivo central era estruturar as tabelas de maneira que exitisse uma hierarquia de condições recebidas pela empresa, facilitando assim para o backend tratar e ter códigos mais limpos e de fácil manutenção. ![Modelagem do banco de dados](https://github.com/alantrs/Bertoti/blob/7f11e2e448aaac2afb7da5aab6d272305d2051aa/metodologia/Imagens/diagrama-embraer.jpg) </details> <details> <br> <summary><b>Funções e procedures</b></summary> <br> Essa é uma procedure em PL/SQL que tem como objetivo verificar se determinados itens estão instalados de fábrica em uma aeronave. Ela percorre as tabelas chassi e logica_fabrica e, para cada combinação de chassi e item, utiliza a função verificar_instalacao_fabrica para determinar se o item está instalado. A lógica principal está na cláusula MERGE, que realiza operações de atualização e inserção na tabela chassi_item. Se houver uma correspondência entre o chassi e o item na tabela chassi_item, ela atualiza o status de instalação. Se não houver correspondência, insere um novo registro indicando se o item está ou não instalado de fábrica. ```SQL CREATE OR REPLACE PROCEDURE verificar_e_inserir_instalacao_fabrica AS v_chassi chassi.id_chassi%TYPE; v_item logica_fabrica.id_item%TYPE; v_instalado NUMBER; BEGIN FOR r_chassi IN (SELECT id_chassi FROM chassi) LOOP FOR r_item IN (SELECT id_item FROM logica_fabrica) LOOP v_instalado := verificar_instalacao_fabrica(r_chassi.id_chassi, r_item.id_item); MERGE INTO chassi_item ci USING ( SELECT r_chassi.id_chassi AS id_chassi, r_item.id_item AS id_item, v_instalado AS instalado FROM dual ) temp ON ( ci.id_chassi = temp.id_chassi AND ci.id_item = temp.id_item ) WHEN MATCHED THEN UPDATE SET ci.instalado = temp.instalado WHEN NOT MATCHED THEN INSERT (id_chassi, id_item, instalado) VALUES (temp.id_chassi, temp.id_item, temp.instalado); END LOOP; END LOOP; END verificar_e_inserir_instalacao_fabrica; / </details> <details> <br> <summary><b>Triggers</b></summary> Essa trigger foi criada para realizar auditoria na tabela CHASSI_BOLETIM após operações de atualização no campo STATUS. Quando uma atualização ocorre, a trigger gera um novo identificador de auditoria utilizando a sequência SEQ_CHASSI_BOLETIM_AUDIT e registra os dados relevantes na tabela de auditoria CHASSI_BOLETIM_AUDIT. Isso inclui o ID de auditoria, IDs de chassi e boletim, status anterior e novo, além do responsável pela modificação, armazenado na coluna MODIFICADO_POR. Essa abordagem proporciona um histórico detalhado das alterações de status na tabela principal, contribuindo para a transparência e rastreabilidade das modificações realizadas no sistema. ```SQL CREATE OR REPLACE TRIGGER TRG_AUDIT_CHASSI_BOLETIM AFTER UPDATE OF STATUS ON CHASSI_BOLETIM FOR EACH ROW DECLARE V_ID_AUDITORIA INTEGER; BEGIN -- Gerar um novo ID de auditoria SELECT SEQ_CHASSI_BOLETIM_AUDIT.NEXTVAL INTO V_ID_AUDITORIA FROM DUAL; -- Inserir os dados na tabela de auditoria INSERT INTO CHASSI_BOLETIM_AUDIT (ID_AUDITORIA, ID_CHASSI, ID_BOLETIM, STATUS_ANTERIOR, STATUS_NOVO, modificado_por) VALUES (V_ID_AUDITORIA, :OLD.ID_CHASSI, :OLD.ID_BOLETIM, :OLD.STATUS, :NEW.STATUS, :NEW.MODIFICADO_POR); END; / ``` </details> <details> <br> <summary><b>Views</b></summary> Essa view retorna um caminho hierarquico das lógicas, facilitando o tratamento para o backend, onde é possivel definir uma entrada (buscando a dependencia ou buscando pelo nivel) para recuperar a lógica de aplicação de um determinado item. ```SQL -- view que retorna o caminho hierarquico das logicas CREATE OR REPLACE VIEW v_hierarquia AS SELECT id_logica, logica_boletim.id_Item, ITEM.NOME, input1, operacao, input2, dependencia, LEVEL AS nivel, CONNECT_BY_ROOT(ID_logica) AS no_raiz, SYS_CONNECT_BY_PATH(ID_logica, '/') AS caminho_hierarquia FROM Logica_Boletim JOIN item ON logica_boletim.id_item = item.id_item START WITH dependencia IS NULL CONNECT BY PRIOR ID_logica = dependencia; ``` </details> ## Aprendizados efetivos Este projeto proporcionou a oportunidade de aprendizado sobre tópicos avançados em banco de dados. Durante o desenvolvimento, adquiri habilidades como a criação e execução de funções e procedimentos, o que me permitiu entender melhor a manipulação e gestão de dados. Tive a oportunidade de trabalhar com auditoria usando triggers, o que me deu uma visão mais profunda sobre a segurança e integridade dos dados. Além disso, a visualização de dados com views me permitiu entender como apresentar dados de uma maneira mais eficiente e eficaz. Aprofundei meus conhecimentos na linguagem PL/SQL da Oracle, o que me permitiu desenvolver soluções mais robustas e eficientes. ### Hard Skills <details> <summary><b>Funções e Procedures com PL/SQL: sei fazer com ajuda</b></summary> <br> <ul> <li>Estrutura e funcionamento de uma função</li> <li>Estrutura e funcionamento de uma procedure</li> <Li>Como executar funções e procedures</Li> </ul> </details> <details> <summary><b>Triggers: sei fazer com autonomia</b></summary> <br> <ul> <li>Estrutura e funcionamento de uma trigger</li> <li>Utilização e vantagens</li> </ul> </details> <details> <summary><b>Views: sei fazer com autonomia</b></summary> <br> <ul> <li>Estrutura e funcionamento de uma view</li> <li>Utilização e vantagens</li> <Li>Hierarquia de dados no oracle com connect_by</Li> </ul> </details> ### Soft Skills <details> <summary><b>Proatividade</b></summary> <br> <ul> <li>Utilizando uma tecnologia nova, o Autonomous Database da Oracle, precisei ser proativo em aprender sobre a ferramenta e descobrir funcionalidades que ajudariam no controle da lógica do projeto. Essa soft skill me permitiu aprender muito e ver minha capacidade de tomar a frente de uma responsabilidade que era fundamental para o funcionamento do projeto.</li> </ul> </details> <details> <summary><b>Trabalho em equipe</b></summary> <br> <ul> <li>Apresentei pra equipe meus conhecimentos adquiridos na ferramenta de banco de dados para facilitar o desenvolvimento do back-end.</li> </ul> </details> <hr>
/** * * Copyright (c) 2005-2023 by Pierre-Henri WUILLEMIN(_at_LIP6) & Christophe GONZALES(_at_AMU) * info_at_agrum_dot_org * * 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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see <http://www.gnu.org/licenses/>. * */ /** * @file * @brief Headers of the MultiDimWithOffset class. * * @author Pierre-Henri WUILLEMIN(_at_LIP6) & Christophe GONZALES(_at_AMU) */ #include <limits> // to ease IDE parsers... #include <agrum/tools/multidim/implementations/multiDimImplementation.h> #include <agrum/tools/multidim/implementations/multiDimWithOffset.h> namespace gum { // Default constructor: creates an empty null dimensional matrix template < typename GUM_SCALAR > MultiDimWithOffset< GUM_SCALAR >::MultiDimWithOffset() : MultiDimImplementation< GUM_SCALAR >() { // for debugging purposes GUM_CONSTRUCTOR(MultiDimWithOffset); } // copy constructor template < typename GUM_SCALAR > MultiDimWithOffset< GUM_SCALAR >::MultiDimWithOffset( const MultiDimWithOffset< GUM_SCALAR >& from) : MultiDimImplementation< GUM_SCALAR >(from), gaps_(from.gaps_) { // for debugging purposes GUM_CONS_CPY(MultiDimWithOffset); } // destructor template < typename GUM_SCALAR > MultiDimWithOffset< GUM_SCALAR >::~MultiDimWithOffset() { // for debugging purposes GUM_DESTRUCTOR(MultiDimWithOffset); // no need to unregister all slaves as it will be done by // MultiDimImplementation } // add a new dimension, needed for updating the offsets_ & gaps_ template < typename GUM_SCALAR > INLINE void MultiDimWithOffset< GUM_SCALAR >::add(const DiscreteVariable& v) { Size lg = this->domainSize(); if (lg > std::numeric_limits< Idx >::max() / v.domainSize()) { GUM_ERROR(OutOfBounds, "Out of bounds !") } MultiDimImplementation< GUM_SCALAR >::add(v); gaps_.insert(&v, lg); } // removes a dimension, needed for updating the offsets_ & gaps_ template < typename GUM_SCALAR > INLINE void MultiDimWithOffset< GUM_SCALAR >::erase(const DiscreteVariable& v) { Sequence< const DiscreteVariable* > variables = this->variablesSequence(); Idx pos = variables.pos(&v); // throw a NotFound if necessary if (variables.size() == 1) { gaps_.clear(); } else { // update the gaps_ Size v_size = v.domainSize(); gaps_.erase(variables[pos]); for (Idx i = pos + 1; i < variables.size(); ++i) { gaps_[variables[i]] /= v_size; } } MultiDimImplementation< GUM_SCALAR >::erase(v); } // listen to change in each recorded Instantiation. template < typename GUM_SCALAR > INLINE void MultiDimWithOffset< GUM_SCALAR >::changeNotification(const Instantiation& i, const DiscreteVariable* const var, Idx oldval, Idx newval) { GUM_ASSERT(offsets_.exists(&i)); GUM_ASSERT(offsets_[&i] < this->domainSize()); GUM_ASSERT(newval < var->domainSize()); GUM_ASSERT(oldval < var->domainSize()); if (newval >= oldval) { offsets_[&i] += gaps_[var] * (newval - oldval); GUM_ASSERT(offsets_[&i] < this->domainSize()); } else { GUM_ASSERT(offsets_[&i] >= gaps_[var] * (oldval - newval)); offsets_[&i] -= gaps_[var] * (oldval - newval); } } // listen to an assignment of a value in a Instantiation template < typename GUM_SCALAR > INLINE void MultiDimWithOffset< GUM_SCALAR >::setChangeNotification(const Instantiation& i) { GUM_ASSERT(offsets_.exists(&i)); offsets_[&i] = getOffs_(i); } // listen to setFirst in each recorded Instantiation. template < typename GUM_SCALAR > INLINE void MultiDimWithOffset< GUM_SCALAR >::setFirstNotification(const Instantiation& i) { GUM_ASSERT(offsets_.exists(&i)); offsets_[&i] = 0; } // listen to setLast in each recorded Instantiation. template < typename GUM_SCALAR > INLINE void MultiDimWithOffset< GUM_SCALAR >::setLastNotification(const Instantiation& i) { GUM_ASSERT(offsets_.exists(&i)); offsets_[&i] = this->domainSize() - 1; } // listen to increment in each recorded Instantiation. template < typename GUM_SCALAR > INLINE void MultiDimWithOffset< GUM_SCALAR >::setIncNotification(const Instantiation& i) { GUM_ASSERT(offsets_.exists(&i)); GUM_ASSERT(offsets_[&i] != this->domainSize() - 1); ++offsets_[&i]; } // listen to increment in each recorded Instantiation. template < typename GUM_SCALAR > INLINE void MultiDimWithOffset< GUM_SCALAR >::setDecNotification(const Instantiation& i) { GUM_ASSERT(offsets_.exists(&i)); GUM_ASSERT(offsets_[&i] != 0); --offsets_[&i]; } // add a Instantiation as a slave template < typename GUM_SCALAR > INLINE bool MultiDimWithOffset< GUM_SCALAR >::registerSlave(Instantiation& i) { if (MultiDimImplementation< GUM_SCALAR >::registerSlave(i)) { GUM_ASSERT(!offsets_.exists(&i)); offsets_.insert(&i, getOffs_(i)); return true; } return false; } // remove a registered slave instantiation template < typename GUM_SCALAR > INLINE bool MultiDimWithOffset< GUM_SCALAR >::unregisterSlave(Instantiation& i) { MultiDimImplementation< GUM_SCALAR >::unregisterSlave(i); offsets_.erase(&i); return true; } // Compute the offset of a Instantiation /** If the instantiation is not fully compatible with the MultiDimWithOffset, * no exception thrown * but 0 is assumed for dimensions not present in the instantiation. * for instance : M<<a<<b<<c; with i=b:1|c:2|d:1 then M.getOffs_(i) give the * offset of a:0|b:1|c:2. */ template < typename GUM_SCALAR > INLINE Size MultiDimWithOffset< GUM_SCALAR >::getOffs_(const Instantiation& i) const { Idx off = 0; for (auto iter = gaps_.begin(); iter != gaps_.end(); ++iter) if (i.contains(iter.key())) off += iter.val() * i.valFromPtr(iter.key()); else GUM_ERROR(InvalidArgument, iter.key()->name() << " not present in the instantiation " << i) return off; } /* template < typename GUM_SCALAR > INLINE Size MultiDimWithOffset< GUM_SCALAR >::getOffs_(const Instantiation& i) const { Idx off = 0; for (HashTableConstIteratorSafe< const DiscreteVariable*, Size > iter = gaps_.beginSafe(); iter != gaps_.endSafe(); ++iter) if (i.contains(iter.key())) off += iter.val() * i.valFromPtr(iter.key()); else GUM_ERROR(InvalidArgument, iter.key()->name() << " not present in the instantiation " << i) return off; }*/ // For a given indice of a value in the vector values_, this method computes // the corresponding instantiation /** * @param result the result of this methods, we assume that the given * instantiation already contains all the variables * contained in the multidimarray (if V is the set of variables * of this tab, V must be a subset of variables in * result or the exact set) * @param indice indice in the vector values_ */ template < typename GUM_SCALAR > INLINE void MultiDimWithOffset< GUM_SCALAR >::computeInstantiationValue_(Instantiation& result, Size indice) const { for (Idx i = 0; i < this->nbrDim(); ++i) { const DiscreteVariable& var = this->variable(i); Idx domainSize = var.domainSize(); result.chgVal(var, indice % domainSize); indice = indice / domainSize; } GUM_ASSERT(indice == 0); } // string representation of internal data about i in this. template < typename GUM_SCALAR > INLINE std::string MultiDimWithOffset< GUM_SCALAR >::toString(const Instantiation* i) const { if (i->isMaster(this)) { std::stringstream s; s << offsets_[i]; std::string res; s >> res; return res; } else { return "--"; } } template < typename GUM_SCALAR > INLINE Size MultiDimWithOffset< GUM_SCALAR >::toOffset(const Instantiation& i) const { return getOffs_(i); } // set the Instantiation to the values corresponding to the offset (in this // array) template < typename GUM_SCALAR > INLINE Instantiation& MultiDimWithOffset< GUM_SCALAR >::fromOffset(Instantiation& i, Size offset) const { this->computeInstantiationValue_(i, offset); return i; } } /* namespace gum */
import React from "react"; import { IconArrowRight } from "../icon"; import { Link } from "react-router-dom"; const NavigateCourse = ({ active = "Most popular", array = ["New", "Trending"], arrow = false, }) => { return ( <nav className={`mb-4`}> <ul className={`flex items-center text-purpleTextC0 font-bold`}> <Link to={`/topic/${active}`} className={`cursor-pointer`}> {active} </Link> {array.map((items) => ( <Link to={`/topic/${items}`} className={`flex items-center cursor-pointer`} key={items} > {arrow && ( <IconArrowRight className="mx-2 text-white" size={12} stroke={2.5} ></IconArrowRight> )} {items} </Link> ))} </ul> </nav> ); }; export default NavigateCourse;
import IconArrowLeft from "@src/icons/IconArrowLeft"; import IconArrowRight from "@src/icons/IconArrowRight"; import classNames from "classnames"; import React, { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react"; // import s from "./CarouselCommon.module.scss"; import s from './CarouselCommon.module.scss'; import Slider, { Settings } from "react-slick"; interface Props extends Settings { children: React.ReactNode, carouselRef?: any, dotPosition?: string, slidesToShowMobile?: number, slidesToShowTablet?: number, total: number, isScrollSingleSlide?: boolean, center?: boolean, } export const CarouselCommon = ({ children, autoplay, dotPosition, carouselRef, dots = true, beforeChange, afterChange, slidesToShow = 1, slidesToShowMobile = 1, slidesToShowTablet = 1, total = 1, isScrollSingleSlide = false, swipeToSlide = true, infinite = true, arrows = false, center = false, }: Props) => { const nodeRef = useRef<any>(null); const [slideNum, setSlideNum] = useState(slidesToShow); const [isShowNextArrow, setIsShowNextArrow] = useState(false); const [isShowPrevArrow, setIsShowPrevArrow] = useState(false); const [currentIndex, setCurrentIndex] = useState(0); const infiniteValue = useMemo(() => { if (total <= slideNum) { return false; } return infinite; }, [slideNum, total, infinite]); useEffect(() => { if (total <= slideNum) { setIsShowNextArrow(false); setIsShowPrevArrow(false); } else { setIsShowNextArrow(true); } }, [total, slideNum]); const handleResize = useCallback(() => { // eslint-disable-next-line no-undef const width = window.innerWidth; if (width < 641) { setSlideNum(slidesToShowMobile); } else if (width < 1008) { setSlideNum(slidesToShowTablet); } else { setSlideNum(slidesToShow); } }, [slidesToShowMobile, slidesToShowTablet, slidesToShow]); useEffect(() => { handleResize(); }, [handleResize]); useEffect(() => { handleResize(); }, [handleResize]); useEffect(() => { // eslint-disable-next-line no-undef window.addEventListener('resize', handleResize); return () => { // eslint-disable-next-line no-undef window.removeEventListener('resize', handleResize); }; }, [handleResize]); useImperativeHandle(carouselRef, () => ({ next: () => { nodeRef.current.slickNext(); }, prev: () => { nodeRef.current.slickPrev(); }, goTo: (index) => { nodeRef.current.slickGoTo(index); }, getCurrent: () => { return currentIndex }, })); //get the currentslide const handleChange = (firstIndexInView) => { afterChange && afterChange(firstIndexInView); if (total > slideNum) { if (firstIndexInView === 0) { setIsShowPrevArrow(false); setIsShowNextArrow(true); } else { setIsShowPrevArrow(true); if (firstIndexInView + slideNum >= total) { setIsShowNextArrow(false); } else { setIsShowNextArrow(true); } } } }; const handleBeforeChange = (currentSlide, nextSlide) => { setCurrentIndex(nextSlide) beforeChange && beforeChange(currentSlide, nextSlide) }; return ( <Slider infinite={infiniteValue} ref={nodeRef} className={classNames(s.carousel, { arrows, center, [s['next-arrow']]: isShowNextArrow, [s['next-arrow']]: isShowPrevArrow, })} beforeChange={handleBeforeChange} afterChange={handleChange} autoplay={autoplay} // dotPosition={dotPosition} dots={dots} slidesToShow={slideNum} swipeToSlide={swipeToSlide} arrows={arrows} swipe // prevArrow={ // } prevArrow={ isShowPrevArrow ? ( <button> <IconArrowLeft /> </button> ) : <div></div> } nextArrow={ isShowNextArrow ? ( <button> <IconArrowRight /> </button> ) : <div></div> } slidesToScroll={isScrollSingleSlide ? 1 : slideNum} > {children} </Slider> ); }; export default CarouselCommon;
import React, { useState } from 'react' import axios from 'axios' import {Navigate, useNavigate} from 'react-router-dom'; import './index.css' const Login = ({setToken}) => { const navigate = useNavigate(); const [formData, setFormData] = useState({ username: '', password: '' }); const move = () => { navigate('/'); } const handleChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value }); } const handleSubmit = async (e) => { e.preventDefault(); try { const response = await axios.post('http://localhost:5000/api/login', formData); const { token } = response.data; setToken(token); // Store the token in your app.js state localStorage.setItem('token', token); // history.push('/protected'); navigate('/home') } catch (error) { console.error(error.response.data.message); } } return ( <div className='container'> <h2>Login</h2> <form onSubmit={handleSubmit}> <div> <input type='text' placeholder="Username" id='username' name='username' onChange={handleChange} value={formData.username} required className="form-control col mr-2" ></input> </div> <div> <input className="form-control col mr-2" type='password' placeholder="Password" id='password' name='password' onChange={handleChange} value={formData.password} required ></input> </div> <button className="btn btn-success" type="submit">Login</button> <button className="btn btn-success" onClick={move}>Register</button> </form> </div> ) } export default Login
package libiscdhcpd import ( "errors" "fmt" "log" "strings" ) type TokenType int func (t TokenType) String() string { switch t { case TokenTypeUnknown: return "unknown" case TokenTypeComment: return "comment" case TokenTypeDirective: return "directive" case TokenTypeStartBlock: return "startblock" case TokenTypeEndBlock: return "endblock" case TokenTypeEmptyLine: return "emptyline" default: return "unset" } } const ( TokenTypeUnknown TokenType = iota TokenTypeComment TokenTypeDirective TokenTypeStartBlock TokenTypeEndBlock TokenTypeEmptyLine ) type Token struct { Type TokenType `json:"type"` Spans []LexerSpan `json:"spans"` } func (t *Token) Start() int { return t.Spans[0].Start } func (t *Token) Stop() int { return t.Spans[len(t.Spans)-1].Stop } func (t *Token) Value() string { s := "" for _, span := range t.Spans { s = s + span.Value } return s } func (t *Token) String() string { return fmt.Sprintf("%7d:%7d [%s]: %s", t.Start(), t.Stop(), t.Type, strings.TrimSuffix(t.Value(), "\n")) } func TokenizeWords(start int, spans []LexerSpan) (Token, int, error) { token := Token{} token.Type = TokenTypeUnknown token.Spans = make([]LexerSpan, 0) progress := start done := false for i := start; i < len(spans); i++ { span := spans[i] token.Spans = append(token.Spans, span) progress = progress + 1 switch span.Type { case SpanTypeComment: token.Type = TokenTypeComment case SpanTypeSemicolon: if token.Type == TokenTypeUnknown { token.Type = TokenTypeDirective } case SpanTypeOpenCurly: if token.Type == TokenTypeUnknown { token.Type = TokenTypeStartBlock } case SpanTypeCloseCurly: if token.Type == TokenTypeUnknown { token.Type = TokenTypeEndBlock } case SpanTypeNewline: if token.Type == TokenTypeUnknown { token.Type = TokenTypeEmptyLine } done = true } if done { break } } return token, progress, nil } func Tokenize(spans []LexerSpan) ([]Token, error) { tokens := make([]Token, 0) if len(spans) == 0 { return tokens, errors.New("no spans") } for i := 0; i < len(spans); i++ { span := spans[i] switch span.Type { default: token, progress, err := TokenizeWords(i, spans) if err != nil { log.Println(err) continue } tokens = append(tokens, token) i = progress - 1 } } return tokens, nil }
import 'package:batsystem/loginscreen.dart'; import 'package:batsystem/pages/regpage.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/cupertino.dart'; import 'package:batsystem/sign-up.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class AuthenticationService { final FirebaseAuth _firebaseAuth; AuthenticationService(this._firebaseAuth); /// Changed to idTokenChanges as it updates depending on more cases. Stream<User> get authStateChanges => _firebaseAuth.idTokenChanges(); /// This won't pop routes so you could do something like /// Navigator.of(context).pushNamedAndRemoveUntil('/', (Route<dynamic> route) => false); /// after you called this method if you want to pop all routes. Future<void> signOut() async { await FirebaseAuth.instance.signOut(); } /// There are a lot of different ways on how you can do exception handling. /// This is to make it as easy as possible but a better way would be to /// use your own custom class that would take the exception and return better /// error messages. That way you can throw, return or whatever you prefer with that instead. Future<String> signIn({String email, String password}) async { try { await _firebaseAuth.signInWithEmailAndPassword( email: email, password: password); return "Signed in"; } on FirebaseAuthException catch (e) { return e.message; } } void showdialog(BuildContext context) { var alertDialog = AlertDialog( backgroundColor: Colors.cyan[900], elevation: 6, title: Text("Registration Complete", style: TextStyle(color: Colors.white)), actions: [ Row(children: <Widget>[ FlatButton( onPressed: () { context.read<AuthenticationService>().signOut(); Navigator.push(context, new MaterialPageRoute(builder: (context) => LoginScreen())); }, child: Text("Ok")) ]) ], ); showDialog( context: context, builder: (BuildContext context) { return alertDialog; }); } /// There are a lot of different ways on how you can do exception handling. /// This is to make it as easy as possible but a better way would be to /// use your own custom class that would take the exception and return better /// error messages. That way you can throw, return or whatever you prefer with that instead. Future<String> signUp( {String email, String password, BuildContext context}) async { try { await _firebaseAuth.createUserWithEmailAndPassword( email: email, password: password); return "Signed up"; } on FirebaseAuthException catch (e) { return e.message; } } }
package test0401; /* 구동 클래스를 실행 했을 때 다음의 결과가 나오도록 RemoteControl 인터페이스 완성하기 [결과] TV를 켭니다. Tv의 볼륨을 10으로 설정합니다. TV를 끕니다. Audio를 켭니다. Audio의 볼륨을 20으로 설정합니다. Audio를 끕니다. */ interface RemoteControl { void turnOn(); void turnOff(); void setVolume(int volumn); } class Television implements RemoteControl{ public void turnOn() { System.out.println("TV를 켭니다."); } public void turnOff() { System.out.println("TV를 끕니다."); } public void setVolume(int volumn) { System.out.println("Tv의 볼륨을 "+volumn+"으로 설정합니다."); } } class Audio implements RemoteControl{ public void turnOn() { System.out.println("Audio를 켭니다."); } public void turnOff() { System.out.println("Audio를 끕니다."); } public void setVolume(int volumn) { System.out.println("Audio의 볼륨을 "+volumn+"으로 설정합니다."); } } public class Test2 { public static void main(String[] args) { RemoteControl rc = new Television(); rc.turnOn(); rc.setVolume(10); rc.turnOff(); rc = new Audio(); rc.turnOn(); rc.setVolume(20); rc.turnOff(); } }
#!/usr/bin/python3 '''Student class''' class Student: '''Student class''' def __init__(self, first_name, last_name, age): '''Initialize a new instance''' self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): '''Retrieves a dictionary''' if attrs is None or not all(isinstance(attr, str) for attr in attrs): return self.__dict__ _dict = {} for key in attrs: if hasattr(self, key): _dict[key] = getattr(self, key) return _dict def reload_from_json(self, json): '''Replaces all attribute''' for key, value in json.items(): setattr(self, key, value)
"use strict"; const products = [ { id: 1, name: "Gaming Laptop", price: 1500, image: "https://via.placeholder.com/150", categories: ["Laptops", "Gaming"], }, { id: 2, name: "Wireless Mouse", price: 50, image: "https://via.placeholder.com/150", categories: ["Accessories", "Peripherals"], }, { id: 3, name: "Mechanical Keyboard", price: 100, image: "https://via.placeholder.com/150", categories: ["Accessories", "Peripherals"], }, { id: 4, name: "External Hard Drive", price: 120, image: "https://via.placeholder.com/150", categories: ["Storage", "Accessories"], }, { id: 5, name: "Graphics Card", price: 500, image: "https://via.placeholder.com/150", categories: ["Components", "Gaming"], }, { id: 6, name: "Portable SSD", price: 200, image: "https://via.placeholder.com/150", categories: ["Storage", "Accessories"], }, { id: 7, name: "Gaming Monitor", price: 300, image: "https://via.placeholder.com/150", categories: ["Monitors", "Gaming"], }, { id: 8, name: "All-in-One Printer", price: 150, image: "https://via.placeholder.com/150", categories: ["Peripherals", "Printers"], }, ]; let selectedCategory = null; class Cart { constructor() { this.cart = []; } getProductIndexInCart(productId) { return this.cart.findIndex(function (product) { return product.id === productId; }); } isProductExistInCart(productId) { return this.getProductIndexInCart(productId) !== -1; } addToCart(product) { if (this.isProductExistInCart(product.id)) { alert("This product is already in the cart."); return; } this.cart.push(product); this.renderCart(); } removeProductFromCart(productId) { const productIndex = this.getProductIndexInCart(productId); if (productIndex === -1) { alert("Product is not in the cart!!!"); return; } this.cart.splice(productIndex, 1); this.renderCart(); } clearCart() { this.cart = []; } renderCart() { const cartItemList = document.getElementById("cart-items"); cartItemList.innerHTML = ""; const self = this; this.cart.forEach(function (product) { const cartItemElement = document.createElement("li"); cartItemElement.innerText = `${product.name} - $${product.price} x ${1}`; const removeBtn = document.createElement("button"); removeBtn.innerText = "Remove"; removeBtn.classList.add("text-red-500", "ml-2"); removeBtn.addEventListener("click", function () { self.removeProductFromCart(product.id); }); cartItemElement.appendChild(removeBtn); cartItemList.appendChild(cartItemElement); }); } } const cart = new Cart(); function getProductImageElement({ productImage, productName }) { const productImageElement = document.createElement("img"); productImageElement.src = productImage; productImageElement.alt = productName; productImageElement.classList.add("w-full", "mb-4"); return productImageElement; } function getProductNameElement(productName) { const productNameElement = document.createElement("h3"); productNameElement.innerText = productName; productNameElement.classList.add("text-lg", "font-semibold"); return productNameElement; } function getProductPriceElement(productPrice) { const productPriceElement = document.createElement("p"); productPriceElement.textContent = `$${productPrice}`; productPriceElement.classList.add("text-gray-700"); return productPriceElement; } function getAddToCartButton(product) { const addToCartBtn = document.createElement("button"); addToCartBtn.innerText = "Add to Cart"; addToCartBtn.classList.add( "bg-blue-500", "hover:bg-blue-700", "text-white", "font-bold", "py-2", "px-4", "rounded", "mt-2" ); addToCartBtn.addEventListener("click", function () { cart.addToCart(product); }); return addToCartBtn; } function getProductCard(product) { const card = document.createElement("div"); card.classList.add("bg-white", "p-4", "rounded", "shadow"); const productImage = getProductImageElement({ productImage: product.image, productName: product.name, }); card.appendChild(productImage); const productName = getProductNameElement(product.name); card.appendChild(productName); const productPrice = getProductPriceElement(product.price); card.appendChild(productPrice); const addToCartButton = getAddToCartButton(product); card.appendChild(addToCartButton); return card; } function renderProducts() { const productListContainer = document.getElementById("product-list"); productListContainer.innerHTML = ""; let categorizedProducts = products; if (selectedCategory) { categorizedProducts = products.filter(function (product) { return product.categories.includes(selectedCategory); }); } categorizedProducts.forEach(function (product) { const productCard = getProductCard(product); productListContainer.appendChild(productCard); }); } function getProductCategories() { const productCategories = products.map(function (product) { return product.categories; }); const categoryFlatList = productCategories.flat(); const uniqueCategories = new Set(categoryFlatList); return [...uniqueCategories]; } function renderCategories() { const categoryContainer = document.getElementById("category-filters"); categoryContainer.innerHTML = ""; const categories = getProductCategories(); categories.forEach(function (category) { const categoryBtn = document.createElement("button"); categoryBtn.innerText = category; categoryBtn.classList.add( "bg-gray-200", "hover:bg-gray-300", "text-gray-800", "font-semibold", "py-2", "px-4", "rounded", "mr-2" ); categoryBtn.addEventListener("click", function () { selectedCategory = category; renderProducts(); }); categoryContainer.appendChild(categoryBtn); }); } renderProducts(); renderCategories(); const clearFilterBtn = document.getElementById("clear-filters-btn"); clearFilterBtn.addEventListener("click", function () { selectedCategory = null; renderProducts(); }); const checkoutBtn = document.getElementById("checkout-btn"); checkoutBtn.addEventListener("click", function () { cart.clearCart(); cart.renderCart(); });
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Try to make my first Portfolio</title> <link rel="stylesheet" href="style.css"> <script src="https://kit.fontawesome.com/1bd19cd81b.js" crossorigin="anonymous"></script> </head> <body> <div id="header"> <div class="container"> <nav> <img src="images/logo4.png" alt="logo.png" class="logo"> <ul id="sidemenu"> <li><a href="#header">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#services">Services</a></li> <li><a href="#portfolio">Portfolio</a></li> <li><a href="#contact">Contact</a></li> <i class="fas fa-times" onclick="closemenu()"></i> </ul> <i class="fas fa-bars" onclick="openmenu()"></i> </nav> <div class="header-text"> <p>Student</p> <h1>Hi, I'm <span>Sarbeswar</span><br>From India</h1> </div> </div> </div> <div id="about"> <div class="container"> <div class="row"> <div class="about-col-1"> <img src="images/user.png" alt="images/user.png"> </div> <div class="about-col-2"> <h1 class="sub-title">About Me</h1> <p>Software developers use programming and design knowledge to build software that meets the needs of users. Typically, they will meet with a client who has a need for software to be developed, and then will build, test and deploy that software based on the specifications they have received.</p> <br> <div class="tab-titles"> <p class="tab-links active-link" onclick="opentab('skills')">Skills</p> <p class="tab-links" onclick="opentab('experience')">Experience</p> <p class="tab-links" onclick="opentab('education')">Education</p> </div> <div class="tab-contents active-tab" id="skills"> <ul> <li><span>Student</span><br>Designing web/App interface</li> <li><span>Web Development</span><br>Website Development</li> <li><span>App Development</span><br>Building Android apps</li> </ul> </div> <div class="tab-contents" id="experience" > <ul> <li><span>2004</span><br>Enter To The World</li> <li><span>2009</span><br>Start My Education journey</li> <li><span>2019</span><br>COVID-19 came To India</li> </ul> </div> <div class="tab-contents" id="education"> <ul> <li><span>2021-current</span><br>Complete Board</li> <li><span>2020-2021</span><br>Board first year</li> <li><span>2000</span><br>Complete Matriculation </li> </ul> </div> </div> </div> </div> <!----srvices---> <div id="services"> <div class="container"> <h1 class="sub-title">My Services</h1> <div class="services-list"> <div> <i class="fa-solid fa-code"></i> <h2>Web Design</h2> <p>Web development is the work involved in developing a website for the Internet or an intranet. Web development can range from developing a simple single static page of plain text to complex web applications, electronic businesses, and social network services.</p> <a href="#">Learn More</a> </div> <div> <i class="fa-solid fa-crop"></i> <h2>UI Design</h2> <p>User interface design or user interface engineering is the design of user interfaces for machines and software, such as computers, home appliances, mobile devices, and other electronic devices, with the focus on maximizing usability and the user experience</p> <a href="#">Learn More</a> </div> <div> <i class="fa-solid fa-spider"></i> <h2>App Design</h2> <p>It provides a visual hierarchy to elements and drives consistent scalability with fewer decisions to make while maintaining a quality rhythm. When designing the UI look clean, better, and beautiful.</p> <a href="#">Learn More</a> </div> </div> </div> </div> <!----portfolio---> <div id="portfolio"> <div class="container"> <h1 class="sub-title">My Work</h1> <div class="work-list"> <div class="work"> <img src="images/work-1.png" alt="work-1.png"> <div class="layer"> <h3>Social Media</h3> <p>Social media app to connect with everyone</p> <a href="#"><i class="fa-sharp fa-solid fa-arrow-up-right-from-square"></i></a> </div> </div> <div class="work"> <img src="images/work-2.png" alt="work-2.png"> <div class="layer"> <h3>Music App</h3> <p>Variety of Music are available </p> <a href="#"><i class="fa-sharp fa-solid fa-arrow-up-right-from-square"></i></a> </div> </div> <div class="work"> <img src="images/work-3.png" alt="work-3.png"> <div class="layer"> <h3>Shopping App</h3> <p>Get every Items in best price</p> <a href="#"><i class="fa-sharp fa-solid fa-arrow-up-right-from-square"></i></a> </div> </div> </div> </div> <a href="#" class="btn">See more</a> </div> </div> <!------------contact-----------------> <div id="contact"> <div class="container"> <div class="row"> <div class="contact-left"> <h1 class="sub-title">Contact Me</h1> <p><i class="fas fa-paper-plane"></i> sarbes60@gmail.com</p> <p><i class="fas fa-phone-square-alt"></i>919337956084</p> <div class="social-icons"> <a href=""><i class="fab fa-facebook"></i></a> <a href=""><i class="fab fa-twitter-square"></i></a> <a href=""><i class="fab fa-instagram"></i></a> <a href=""><i class="fab fa-linkedin"></i></a> </div> <a href="images/my-cv.pdf" Download class="btn btn2">Download CV</a> </div> <div class="contact-right"> <form> <input type="text" name="Name" placeholder="Your Name" required> <input type="email" name="email" placeholder="Your Email" required> <textarea name="Message" rows="6" placeholder="Your Message"></textarea> <button type="submit" class="btn btn2">Submit</button> </form> </div> </div> </div> <div class="copyright"> <p>Copyright ©️ Sarbeswar Made With <i class="fa-solid fa-heart"></i> By Spark Code Editor </p> </div> </div> <script> var tablinks = document.getElementsByClassName("tab-links"); var tabcontents = document.getElementsByClassName("tab-contents"); function opentab(tabname){ for(tablink of tablinks){ tablink.classList.remove("active-link"); } for (tabcontent of tabcontents) { tabcontent.classList.remove("active-tab"); } event.currentTarget.classList.add("active-link"); document.getElementById(tabname).classList.add("active-tab") } </script> <script> var sidemenu = document.getElementById('sidemenu'); function openmenu(){ sidemenu.style.right = "0"; } function closemenu(){ sidemenu.style.right = "-200px"; } </script> </body> </html>
import Foundation import UIKit extension UIImage { func resized(toWidth width: CGFloat, height: CGFloat) -> UIImage? { let newSize = CGSize(width: width, height: height) UIGraphicsBeginImageContextWithOptions(newSize, false, scale) defer { UIGraphicsEndImageContext() } draw(in: CGRect(origin: .zero, size: newSize)) return UIGraphicsGetImageFromCurrentImageContext() } func roundedImage(withRadius radius: CGFloat) -> UIImage? { UIGraphicsBeginImageContextWithOptions(size, false, scale) defer { UIGraphicsEndImageContext() } let bounds = CGRect(origin: .zero, size: size) UIBezierPath(roundedRect: bounds, cornerRadius: radius).addClip() draw(in: bounds) return UIGraphicsGetImageFromCurrentImageContext() } }
import Quill from 'quill'; import type { QuillOptionsStatic } from 'quill'; import type BubbleThemeClass from 'quill/themes/snow'; import type ThemeClass from 'quill/core/theme'; import { RichEditorTooltip } from './RichEditorTooltip'; const BubbleTheme: typeof BubbleThemeClass = Quill.import('themes/snow'); const Theme: typeof ThemeClass = Quill.import('core/theme'); const icons = Quill.import('ui/icons'); const TOOLBAR_CONFIG = [ [{ header: ['1', '2', '3', false] }], ['bold', 'italic', 'underline', 'strike'], ['formula'], [ { list: 'ordered' }, { list: 'bullet' } ], ['align', 'link', 'image'] ]; const BUBBLE_DEFAULTS = BubbleTheme.DEFAULTS; export class RichEditorTheme extends Theme { static DEFAULTS = { ...BUBBLE_DEFAULTS, modules: { ...BUBBLE_DEFAULTS.modules, toolbar: { ...BUBBLE_DEFAULTS.modules.toolbar, handlers: { ...BUBBLE_DEFAULTS.modules.toolbar.handlers, link(value: string) { if (value) { const range = this.quill.getSelection(); if (range == null || range.length === 0) return; let preview = this.quill.getText(range); if (/^\S+@\S+\.\S+$/.test(preview) && preview.indexOf('mailto:') !== 0) { preview = `mailto:${preview}`; } this.quill.theme.tooltip.edit('link', preview); } else { this.quill.format('link', false); } } } } } }; public tooltip: RichEditorTooltip; public buildButtons: typeof BubbleTheme.prototype.buildButtons; public buildPickers: typeof BubbleTheme.prototype.buildPickers; constructor(quill: Quill, options: QuillOptionsStatic) { if ( options.modules && options.modules.toolbar != null && options.modules.toolbar.container == null ) { options.modules.toolbar.container = TOOLBAR_CONFIG; } super(quill, options); (this.quill as any).container.classList.add('ql-rich-editor'); } extendToolbar(toolbar: any) { toolbar.container.classList.add('ql-rich-editor'); this.tooltip = new RichEditorTooltip(this.quill, this.options.bounds); this.tooltip.root.appendChild(toolbar.container); this.buildButtons(toolbar.container.querySelectorAll('button'), icons); this.buildPickers(toolbar.container.querySelectorAll('select'), icons); } } RichEditorTheme.prototype.init = BubbleTheme.prototype.init; RichEditorTheme.prototype.addModule = BubbleTheme.prototype.addModule; RichEditorTheme.prototype.buildButtons = BubbleTheme.prototype.buildButtons; RichEditorTheme.prototype.buildPickers = BubbleTheme.prototype.buildPickers; Quill.register('themes/rich-editor', RichEditorTheme, true);
'use client' import useCrewList from '@/hooks/useCrewList' import * as x from '@mui/x-data-grid' import { useRouter, useSearchParams } from 'next/navigation' import React, { FC } from 'react' import useStore from '../store/useStore' import { Button } from './Button' import Dialog from './Dialog' import Table from './Table' import Paragraph from './Paragraph' import SelectTable from './SelectTable' import axios from 'axios' import { alert } from '@/lib/alert' import { errorHandlerClient } from '@/lib/error-handler' import { mutate } from 'swr' import { Info, Loader2Icon, Printer, Trash } from 'lucide-react' import CrewReport from './CrewReport' import { useSession } from 'next-auth/react' const CrewTable: FC = () => { const router = useRouter() const { crewTableColumns, deleteCrew, loadingDelete } = useStore() const session = useSession() const isAdmin = session.data?.user.role === 'admin' const [open, setOpen] = React.useState(false) const [previewReport, setPreviewReport] = React.useState(false) const [openStatus, setOpenStatus] = React.useState(false) const [loadingStatus, setLoadingStatus] = React.useState(false) const [id, setId] = React.useState<x.GridRowId>() const searchParams = useSearchParams() const status = searchParams?.get('status') ?? null const { data, loading } = useCrewList(status) if (loading) return <div>loading...</div> const statusOpts = [ { name: 'Crew Standby', value: 'standby' }, { name: 'Crew Onboarding', value: 'onboarding' }, { name: 'Ex-Crew Standby', value: 'ex-standby' }, { name: 'Out', value: 'out' }, ] const changeCrewStatus = async (status: string, id: string) => { try { setLoadingStatus(true) const { data } = await axios.put('/api/crew/status', { id, status }) alert(data.message) setLoadingStatus(false) setOpenStatus(false) mutate('crewList') } catch (error) { errorHandlerClient(error) } } return ( <> <Dialog open={open} setOpen={setOpen}> <div className="space-y-3"> <Paragraph>Do you really want to delete this data?</Paragraph> <Button onClick={async () => { await deleteCrew(id!) setOpen(false) }} isLoading={loadingDelete} > Delete </Button> </div> </Dialog> <CrewReport data={data} previewReport={previewReport} setPreviewReport={setPreviewReport} /> <div className="ml-auto"> <Button onClick={() => setPreviewReport(true)}> <Printer className="mr-3" /> Download Report </Button> </div> <Table header={[ ...crewTableColumns.map((col) => ({ ...col, renderCell( params: x.GridRenderCellParams< any, any, any, x.GridTreeNodeWithRender > ) { return <div className="font-sans">{params.value}</div> }, })), { field: 'col5', headerName: 'Status', width: 200, renderCell( params: x.GridRenderCellParams< any, any, any, x.GridTreeNodeWithRender > ) { return ( <div className="z-50 font-sans"> <button onClick={() => setOpenStatus(true)}> {statusOpts.find((opt) => opt.value === params.value)?.name} </button> <Dialog open={openStatus} setOpen={setOpenStatus}> {loadingStatus ? ( <div className="flex justify-center"> <Loader2Icon className="animate-spin dark:stroke-white" /> </div> ) : ( <> <Paragraph className="mb-3"> Change Crew Status </Paragraph> <SelectTable options={statusOpts} value={params.value} onChange={(value) => changeCrewStatus(value, params.id.toString()) } /> </> )} </Dialog> </div> ) }, }, { field: 'col6', type: 'actions', getActions: (params: x.GridRowParams) => [ <x.GridActionsCellItem key={params.id} icon={<Info className="stroke-blue-500" />} onClick={() => router.push(`/crew/${params.id}`)} label="Edit" />, <x.GridActionsCellItem key={params.id} icon={<Trash className="stroke-red-500" />} onClick={() => { setOpen(true) setId(params.id) }} label="Delete" disabled={!isAdmin} />, ], }, ]} data={data.map((request: any) => ({ id: request.id, col1: request.idNumber, col2: `${request.givenName} ${request.surName}`, col3: request.phoneNumber, col4: request.mainRank, col5: request.status, }))} /> </> ) } export default CrewTable
package com.example.BackendProyIntegrador.service.impl; import com.example.BackendProyIntegrador.dto.CategoriaDTO; import com.example.BackendProyIntegrador.entity.Categoria; import com.example.BackendProyIntegrador.repository.ICategoriaRepository; import com.example.BackendProyIntegrador.service.ICategoriaService; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class CategoriaService implements ICategoriaService { @Autowired ICategoriaRepository iCategoriaRepository; @Autowired ObjectMapper mapper; @Override public void guardar(CategoriaDTO categoria) { Categoria categoriaNueva = mapper.convertValue(categoria, Categoria.class); iCategoriaRepository.save(categoriaNueva); } @Override public List<CategoriaDTO> listarTodos() { List<CategoriaDTO> listar = new ArrayList<>(); for (Categoria c: iCategoriaRepository.findAll()) { listar.add(mapper.convertValue(c, CategoriaDTO.class)); } return listar; } @Override public CategoriaDTO listarId(Long id) throws Exception { Optional<Categoria> found = iCategoriaRepository.findById(id); if(found.isPresent()) return mapper.convertValue(found, CategoriaDTO.class); else throw new Exception("La categoria no existe"); } @Override public void eliminar(Long id) { iCategoriaRepository.deleteById(id); } @Override public void actualizar(CategoriaDTO categoria) { guardar(categoria); } }
package com.example.testtask.di import com.example.testtask.data.remote.NaPolkeService import com.example.testtask.utils.Constants.Companion.BASE_URL import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object NetworkModule { @Singleton @Provides fun provideHttpClient(): OkHttpClient { val logging = HttpLoggingInterceptor() logging.setLevel(HttpLoggingInterceptor.Level.BODY) return OkHttpClient.Builder() .addInterceptor(logging) .readTimeout(15, TimeUnit.SECONDS) .connectTimeout(15, TimeUnit.SECONDS) .build() } @Singleton @Provides fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit { return Retrofit.Builder() .baseUrl(BASE_URL) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .build() } @Singleton @Provides fun provideApiService(retrofit: Retrofit): NaPolkeService { return retrofit.create(NaPolkeService::class.java) } }
<!DOCTYPE html> <html> <head> <title>Ejemplo secuencia </title> <script type="text/javascript" src="jquery-3.3.1.js"></script> <script type="text/javascript"> //En este ejemplo se muestra el una secuencia de funciones que encadenan efectos que se ejecutan en el tiempo que reciben como parámetro //La idea es mostrar que el parámetro de tiempo (en milisegundos) solo funciona con funciones relacionadas con efectos //Por ejemplo, si incluimos la función css entre medias, se ejecutará sin tener en cuenta el parámetro de tiempo //También se muestra el funcionamiento de la función callback, que se ejecuta inmediatamente después de cada efecto var ocultar=function () { $("#misdivs3").css({"background": "green"}); $("#misdivs3").fadeIn(2000); }; $(document).ready(function() { $("#misdivs").fadeOut(2000).css({"background": "blue"}).fadeIn(2000); //Se ejecuta primero css $("#misdivs2").fadeOut(2000, function(){ //Se ejecuta primero fadeOut, luego css y luego fadeIn $("#misdivs2").css({"background": "red"}); $("#misdivs2").fadeIn(2000); }); $("#misdivs3").fadeOut(2000, ocultar); }); </script> <style> body { background: #666; } h1{color:#00CC00;} .misdivs {background: #623; } </style> </head> <body> <h1> Titulo </h1> <div id="misdivs">mis divs</div> <div id="misdivs2">mis divs</div> <div id="misdivs3">mis divs</div> </body> </html>
#include <stdexcept> template<typename T> class ABS { private: T* _dataStack; unsigned int _currentSize; unsigned int _capacity; float _SCALE_FACTOR; public: ABS(); ABS(int capacity); ABS(const ABS& d); ABS& operator=(const ABS& d); ~ABS(); void push(T data); T pop(); T peek(); unsigned int getSize(); unsigned int getMaxCapacity(); T* getData(); }; template<typename T> ABS<T>::ABS() { _capacity = 1; _currentSize = 0; _dataStack = new T[_capacity]; _SCALE_FACTOR = 2.0; } template<typename T> ABS<T>::ABS(int capacity) { _capacity = capacity; _currentSize = 0; _dataStack = new T[_capacity]; _SCALE_FACTOR = 2.0; } template<typename T> ABS<T>::ABS(const ABS &d) { _capacity = d._capacity; _currentSize = d._currentSize; _dataStack = new T[_capacity]; _SCALE_FACTOR = 2.0; for (unsigned int i = 0; i < _currentSize; i++) { _dataStack[i] = d._dataStack[i]; } } template<typename T> ABS<T>& ABS<T>::operator=(const ABS &d) { if (this == &d) { return *this; } _capacity = d._capacity; _currentSize = d._currentSize; _SCALE_FACTOR = 2.0; delete[] _dataStack; _dataStack = new T[_capacity]; for (unsigned int i = 0; i < _currentSize; i++) { _dataStack[i] = d._dataStack[i]; } return *this; } template<typename T> ABS<T>::~ABS() { delete[] _dataStack; } template<typename T> void ABS<T>::push(T data) { if (_currentSize == _capacity) { _capacity *= _SCALE_FACTOR; } T* temp_dataStack = new T[_capacity]; for (unsigned int i = 0; i < _currentSize; i++) { temp_dataStack[i] = _dataStack[i]; } delete[] _dataStack; _dataStack = temp_dataStack; _dataStack[_currentSize] = data; _currentSize++; } template<typename T> T ABS<T>::pop() { if (_currentSize == 0) { throw std::runtime_error("Stack is empty"); } _currentSize--; if (static_cast<float>(_currentSize)/_capacity < 1/_SCALE_FACTOR){ _capacity /= static_cast<int>(_SCALE_FACTOR); } T poppedElement = _dataStack[_currentSize]; T* temp_dataStack = new T[_capacity]; for (unsigned int i = 0; i < _currentSize; i++) { temp_dataStack[i] = _dataStack[i]; } delete[] _dataStack; _dataStack = temp_dataStack; return poppedElement; } template<typename T> T ABS<T>::peek() { if (_currentSize == 0) { throw std::runtime_error("Stack is empty"); } return _dataStack[_currentSize - 1]; } template<typename T> unsigned int ABS<T>::getSize() { return _currentSize; } template<typename T> unsigned int ABS<T>::getMaxCapacity() { return _capacity; } template<typename T> T* ABS<T>::getData() { return _dataStack; }
#pragma once #include "Entity.h" #include "Assert.h" #include <cassert> namespace ecs { template <typename T> class Container; template <typename T> class Reference { public: Reference() : myContainer(nullptr), myEntity(ecs::nullentity) {} Reference(Entity aEntity, Container<T>* aContainer) : myEntity(aEntity), myContainer(aContainer) {} Reference(const Reference&) = default; Reference& operator=(const Reference&) = default; Reference(Reference&& aReference) noexcept : myEntity(aReference.myEntity), myContainer(aReference.myContainer) { aReference.myEntity = ecs::nullentity; aReference.myContainer = nullptr; } Reference& operator=(Reference&& aReference) noexcept { myEntity = aReference.myEntity; aReference.myEntity = ecs::nullentity; myContainer = aReference.myContainer; aReference.myContainer = nullptr; return *this; } bool Valid() const { return myContainer && myEntity != nullentity && myContainer->Contains(myEntity); } operator bool() const { return Valid(); } T& operator*() { ECS_ASSERT(Valid() && "reference invalid"); return myContainer->Get(myEntity); } const T& operator*() const { ECS_ASSERT(Valid() && "reference invalid"); return myContainer->Get(myEntity); } T* operator->() { ECS_ASSERT(Valid() && "reference invalid"); return &myContainer->Get(myEntity); } const T* operator->() const { ECS_ASSERT(Valid() && "reference invalid"); return &myContainer->Get(myEntity); } Entity GetEntity() const { ECS_ASSERT(Valid() && "reference invalid"); return myEntity; } bool operator==(const Reference& aOther) const { return myEntity == aOther.myEntity && myContainer == aOther.myContainer; } private: Entity myEntity; Container<T>* myContainer; }; }
import { Injectable } from '@nestjs/common'; import { Cron, CronExpression } from '@nestjs/schedule'; import { OutboxMessageService } from '../outbox/outbox-message.service'; import { SqsService } from '@ssut/nestjs-sqs'; import { TaskMessage } from './task-message'; import { Task } from './task.entity'; import { PinoLogger } from 'nestjs-pino'; @Injectable() export class TaskMessagePublisher { constructor( private outboxMessageService: OutboxMessageService, private readonly sqsService: SqsService, private readonly logger: PinoLogger, ) { this.logger.setContext(TaskMessagePublisher.name); } @Cron(CronExpression.EVERY_10_SECONDS) async publish() { await this.outboxMessageService.process({ type: 'task', callback: async (manager, msg) => { this.logger.debug( { msgId: msg.id, ...msg.metadata }, 'publishing message to task queue', ); const taskMessage = TaskMessage.fromRawObject(msg.data); const task = await manager.findOneBy(Task, { id: taskMessage.taskId }); if (!task) { this.logger.error( { msgId: msg.id, ...taskMessage.metadata }, 'failed to publish a message to task queue. Task not found', ); throw new Error(`task (id ${taskMessage.taskId}) not found`); } this.logger.debug( { msgId: msg.id, taskId: task.id, ...taskMessage.metadata }, 'sending task to queue', ); const result = await this.sqsService.send('taskQueue', { id: msg.id, body: msg.data, }); const awsMsgId = result[0].MessageId || 'empty-aws-msg-id'; // why it can be undefined? this.logger.debug( { msgId: msg.id, taskId: task.id, awsMsgId, ...taskMessage.metadata, }, 'task published to queue', ); this.logger.debug( { taskId: task.id, awsMsgId, ...taskMessage.metadata }, 'marking task as processing', ); task.processing({ processorId: awsMsgId }); await manager.update(Task, { id: task.id }, task); }, }); } }
import { DateTime } from 'luxon'; import Hash from '@ioc:Adonis/Core/Hash'; import { BaseModel, beforeSave, column } from '@ioc:Adonis/Lucid/Orm'; export default class User extends BaseModel { @column({ isPrimary: true, }) public id: number; @column() public publicId: string; @column() public username: string; @column() public email: string; @column({ serializeAs: null }) public password: string; @column() public rememberMeToken: string | null; @column() public forgotPasswordToken: string | null; @column.dateTime() public forgotPasswordTokenExpiresAt: DateTime | null; @column.dateTime({ autoCreate: true }) public createdAt: DateTime; @column.dateTime({ autoCreate: true, autoUpdate: true }) public updatedAt: DateTime; @beforeSave() public static async hashPassword(user: User) { if (user.$dirty.password) { user.password = await Hash.make(user.password); } } }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Quick Wins for Accessible WordPress Themes</title> <!-- metadata --> <meta name="generator" content="S5" /> <meta name="version" content="S5 1.1" /> <meta name="presdate" content="20130813" /> <meta name="author" content="David A. Kennedy" /> <meta name="company" content="Rock Creek Strategic Marketing" /> <!-- configuration parameters --> <meta name="zenView" content="slideshow" /> <meta name="controlVis" content="hidden" /> <!-- style sheet links --> <link href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,700italic,400,700,600' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="ui/zen/slides.css" type="text/css" media="projection" id="slideProj" /> <link rel="stylesheet" href="ui/zen/outline.css" type="text/css" media="screen" id="outlineStyle" /> <link rel="stylesheet" href="ui/zen/print.css" type="text/css" media="print" id="slidePrint" /> <!-- S5 JS --> <script src="ui/zen/slides.js" type="text/javascript"></script> </head> <body> <div class="layout"> <div id="controls"><!-- DO NOT EDIT --></div> <div id="currentSlide"><!-- DO NOT EDIT --></div> <div id="header"></div> <div id="footer"> <h1>WordPress DC | August 13, 2013</h1> <h2>Quick Wins for Accessible WordPress Themes</h2> </div> </div> <div class="presentation"> <div class="slide"> <h1>Quick Wins for Accessible WordPress Themes</h1> <h2>davidakennedy.com/2013/quick-wins-for-accessible-wordpress-themes</h2> <h3>David A. Kennedy</h3> <h4>Interactive Designer | Rock Creek Strategic Marketing</h4> </div> <div class="slide"> <h1>What is Web Accessibility?</h1> <p>Definitions vary</p> <blockquote>The practice of making websites and applications<br /> usable by people of all abilities.</blockquote> </div> <div class="slide"> <h1>1. Start with Accessibility in Mind</h1> <p>Accessibility spans all the disciplines:</p> <ul> <li>Project management</li> <li>User Experience</li> <li>Design</li> <li>Development</li> <li>Testing</li> </ul> </div> <div class="slide"> <h1>2. Find a Good Base</h1> <p>You don't have do do it all:</p> <ul> <li><a href="http://underscores.me/">Starter theme: Underscores</a></li> <li><a href="http://wordpress.org/themes/twentythirteen">zen theme: Twenty Thirteen</a></li> <li><a href="https://github.com/RRWD/accessible-twenty-eleven-theme">Child theme: Accessible Twenty Eleven</a></li> <li><a href="http://wordpress.org/themes/blaskan">Custom theme: Blaskan</a></li> <li><a href="https://github.com/davidakennedy/accessible-zen">Custom theme: Accessible Zen</a></li> </ul> </div> <div class="slide"> <h1>3. Color Matters</h1> <p>High contrast helps everyone</p> <ul> <li>Text and images of text have a contrast ratio of at least 4.5:1</li> <li>Large text (over 18 point or 14 point bold) has a contrast ratio of at least 3:1</li> </ul> <p>Choose wisely:</p> <ul> <li><a href="http://accessibility.oit.ncsu.edu/tools/color-contrast/index.php">Color Palette Accessibility Checker</a></li> <li><a href="http://0to255.com/">0 to 255</a></li> </ul> </div> <div class="slide"> <h1>4. Sweat the Small Stuff</h1> <p>Because it can make a big difference</p> <ul> <li>Be mindful of your reading order</li> <li>Skip nav links = awesome</li> <li>Keep the underline on links and define focus styles</li> <li>Relative units on fonts = also awesome</li> <li>Keep titles with "Read more..." links</li> </ul> </div> <div class="slide"> <h1>5. Wait a Minute!</h1> <p>You didn't really talk too much about WordPress themes?</p> <p>That's because accessibility is about <strong>people</strong>, not technology.</p> </div> </div> </body> </html>
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Item extends Model { use HasFactory, SoftDeletes; protected $fillable = [ 'user_id', 'name', 'slug', 'price', 'description', 'status', 'archived_at', 'ordering', ]; /** * -------------------------------------------- * ---- Relationship ---- * -------------------------------------------- */ /** * User */ public function user() { return $this->belongsTo(User::class); } /** * Gallery */ public function gallery() { return $this->hasMany(ItemGallery::class, 'item_id', 'id'); } }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {EventEmitter} from '@angular/core'; import {Observable} from 'rxjs'; import {composeAsyncValidators, composeValidators} from './directives/shared'; import {AsyncValidatorFn, ValidationErrors, ValidatorFn} from './directives/validators'; import {toObservable} from './validators'; /** * Reports that a FormControl is valid, meaning that no errors exist in the input value. * * 表示此 FormControl 有效,也就是说它的输入值中没有错误。 * * @see `status` */ export const VALID = 'VALID'; /** * Reports that a FormControl is invalid, meaning that an error exists in the input value. * * 表示此 FormControl 无效,也就是说它的输入值中存在错误。 * * @see `status` */ export const INVALID = 'INVALID'; /** * Reports that a FormControl is pending, meaning that that async validation is occurring and * errors are not yet available for the input value. * * 表示此 FormControl 处于未决状态,表示正在进行异步验证,还不知道输入值中有没有错误。 * * @see `markAsPending` * @see `status` */ export const PENDING = 'PENDING'; /** * Reports that a FormControl is disabled, meaning that the control is exempt from ancestor * calculations of validity or value. * * 表示此 FormControl 被禁用了,表示该控件不会参与各级祖先对值的有效性的计算。 * * @see `markAsDisabled` * @see `status` */ export const DISABLED = 'DISABLED'; function _find(control: AbstractControl, path: Array<string|number>| string, delimiter: string) { if (path == null) return null; if (!(path instanceof Array)) { path = (<string>path).split(delimiter); } if (path instanceof Array && (path.length === 0)) return null; return (<Array<string|number>>path).reduce((v: AbstractControl, name) => { if (v instanceof FormGroup) { return v.controls.hasOwnProperty(name as string) ? v.controls[name] : null; } if (v instanceof FormArray) { return v.at(<number>name) || null; } return null; }, control); } function coerceToValidator( validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null): ValidatorFn| null { const validator = (isOptionsObj(validatorOrOpts) ? (validatorOrOpts as AbstractControlOptions).validators : validatorOrOpts) as ValidatorFn | ValidatorFn[] | null; return Array.isArray(validator) ? composeValidators(validator) : validator || null; } function coerceToAsyncValidator( asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null): AsyncValidatorFn|null { const origAsyncValidator = (isOptionsObj(validatorOrOpts) ? (validatorOrOpts as AbstractControlOptions).asyncValidators : asyncValidator) as AsyncValidatorFn | AsyncValidatorFn | null; return Array.isArray(origAsyncValidator) ? composeAsyncValidators(origAsyncValidator) : origAsyncValidator || null; } export type FormHooks = 'change' | 'blur' | 'submit'; /** * Interface for options provided to an `AbstractControl`. * * 提供给 `AbstractControl` 的配置项接口。 * * @experimental */ export interface AbstractControlOptions { /** * List of validators applied to control. * * 应用于该控件的验证器列表。 * */ validators?: ValidatorFn|ValidatorFn[]|null; /** * List of async validators applied to control. * * 应用于该控件的异步验证器列表。 * */ asyncValidators?: AsyncValidatorFn|AsyncValidatorFn[]|null; /** * The event name for control to update upon. * * 会导致更新控件的事件名称。 * */ updateOn?: 'change'|'blur'|'submit'; } function isOptionsObj( validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null): boolean { return validatorOrOpts != null && !Array.isArray(validatorOrOpts) && typeof validatorOrOpts === 'object'; } /** * This is the base class for `FormControl`, `FormGroup`, and `FormArray`. * * 这是 `FormControl`、`FormGroup` 和 `FormArray` 的基类。 * * It provides some of the shared behavior that all controls and groups of controls have, like * running validators, calculating status, and resetting state. It also defines the properties * that are shared between all sub-classes, like `value`, `valid`, and `dirty`. It shouldn't be * instantiated directly. * * 它提供了一些所有控件和控件组共有的行为,比如运行验证器、计算状态和重置状态。 * 它还定义了一些所有子类共享的属性,如 `value`、`valid` 和 `dirty`。不允许直接实例化它。 * * @see [Forms Guide](/guide/forms) * * [表单](/guide/forms) * * @see [Reactive Forms Guide](/guide/reactive-forms) * * [响应式表单](/guide/reactive-forms) * * @see [Dynamic Forms Guide](/guide/dynamic-form) * * [动态表单](/guide/dynamic-form) * */ export abstract class AbstractControl { /** @internal */ // TODO(issue/24571): remove '!'. _pendingDirty !: boolean; /** @internal */ // TODO(issue/24571): remove '!'. _pendingTouched !: boolean; /** @internal */ _onCollectionChange = () => {}; /** @internal */ // TODO(issue/24571): remove '!'. _updateOn !: FormHooks; // TODO(issue/24571): remove '!'. private _parent !: FormGroup | FormArray; private _asyncValidationSubscription: any; /** * The current value of the control. * * 控件的当前值。 * * * For a `FormControl`, the current value. * * 对于 `FormControl`,它是当前值。 * * * For a `FormGroup`, the values of enabled controls as an object * with a key-value pair for each member of the group. * * 对于 `FormGroup`,它是由组中的每个已启用的成员控件的名称和值组成的对象。 * * * For a `FormArray`, the values of enabled controls as an array. * * 对于 `FormArray`,它是有所有已启用的控件的值组成的数组。 * */ public readonly value: any; /** * Initialize the AbstractControl instance. * * 初始化这个 AbstractControl 实例。 * * @param validator The function that determines the synchronous validity of this control. * * 用于决定该控件有效性的同步函数。 * * @param asyncValidator The function that determines the asynchronous validity of this * control. * * 用于决定该控件有效性的异步函数。 * */ constructor(public validator: ValidatorFn|null, public asyncValidator: AsyncValidatorFn|null) {} /** * The parent control. * * 父控件。 */ get parent(): FormGroup|FormArray { return this._parent; } /** * The validation status of the control. There are four possible * validation status values: * * 控件的有效性状态。有四个可能的值: * * * **VALID**: This control has passed all validation checks. * * **VALID**: 该控件通过了所有有效性检查。 * * * **INVALID**: This control has failed at least one validation check. * * **INVALID** 该控件至少有一个有效性检查失败了。 * * * **PENDING**: This control is in the midst of conducting a validation check. * * **PENDING**:该控件正在进行有效性检查,处于中间状态。 * * * **DISABLED**: This control is exempt from validation checks. * * **DISABLED**:该控件被禁用,豁免了有效性检查。 * * These status values are mutually exclusive, so a control cannot be * both valid AND invalid or invalid AND disabled. * * 这些状态值是互斥的,因此一个控件不可能同时处于有效状态和无效状态或无效状态和禁用状态。 */ // TODO(issue/24571): remove '!'. public readonly status !: string; /** * A control is `valid` when its `status` is `VALID`. * * 当控件的 `status` 为 `VALID` 时,它就是 `valid` 的。 * * @see `status` * * @returns True if the control has passed all of its validation tests, * false otherwise. * * 如果该控件通过了所有有效性检查,则为 `true`,否则为 `false`。 */ get valid(): boolean { return this.status === VALID; } /** * A control is `invalid` when its `status` is `INVALID`. * * 当控件的 `status` 为 `INVALID` 时,它就是 `invalid` 的。 * * @see `status` * * @returns True if this control has failed one or more of its validation checks, * false otherwise. * * 如果该控件的一个或多个有效性检查失败了,则为 `true`,否则为 `false`。 */ get invalid(): boolean { return this.status === INVALID; } /** * A control is `pending` when its `status` is `PENDING`. * * 当控件的 `status` 为 `PENDING` 时,它就是 `pending` 的。 * * @see `status` * * @returns True if this control is in the process of conducting a validation check, * false otherwise. * * 如果该控件正在进行有效性检查,则为 `true`,否则为 `false`。 */ get pending(): boolean { return this.status == PENDING; } /** * A control is `disabled` when its `status` is `DISABLED`. * * 当控件的 `status` 为 `DISABLED` 时,它就是 `disabled`。 * @see `status` * * Disabled controls are exempt from validation checks and * are not included in the aggregate value of their ancestor * controls. * * 被禁用的控件会豁免有效性检查,并且它的值不会聚合进其祖先控件中。 * * @returns True if the control is disabled, false otherwise. * * 如果该控件被禁用了,则为 `true`,否则为 `false`。 */ get disabled(): boolean { return this.status === DISABLED; } /** * A control is `enabled` as long as its `status` is not `DISABLED`. * * 如果控件的 `status` 不是 `DISABLED` 时,它就是 `enabled`。 * * @see `status` * * @returns True if the control has any status other than 'DISABLED', * false if the status is 'DISABLED'. * * 如果该控件处于 'DISABLED' 之外的任何状态,则为 `true`,否则为 `false`。 * */ get enabled(): boolean { return this.status !== DISABLED; } /** * An object containing any errors generated by failing validation, * or null if there are no errors. * * 一个对象,包含由失败的验证所生成的那些错误,如果没出错则为 null。 */ // TODO(issue/24571): remove '!'. public readonly errors !: ValidationErrors | null; /** * A control is `pristine` if the user has not yet changed * the value in the UI. * * 如果用户尚未修改 UI 中的值,则该控件是 `pristine`(原始状态)的。 * * @returns True if the user has not yet changed the value in the UI; compare `dirty`. * Programmatic changes to a control's value do not mark it dirty. * * 如果用户尚未修改过 UI 中的值,则为 `true`,与 `dirty` 相反。 * 以编程的方式修改控件的值不会把它标记为 `dirty`。 */ public readonly pristine: boolean = true; /** * A control is `dirty` if the user has changed the value * in the UI. * * 如果用户修改过 UI 中的值,则控件是 `dirty`(脏) 的。 * * @returns True if the user has changed the value of this control in the UI; compare `pristine`. * Programmatic changes to a control's value do not mark it dirty. * * 如果用户在 UI 中修改过该控件的值,则为 `true`;与 `pristine` 相对。 * 用编程的方式修改控件的值不会将其标记为 `dirty`。 */ get dirty(): boolean { return !this.pristine; } /** * True if the control is marked as `touched`. * * 如果控件被标记为 `touched`(碰过) 则为 `true`。 * * A control is marked `touched` once the user has triggered * a `blur` event on it. * * 一旦用户在控件上触发了 `blur` 事件,则会将其标记为 `touched`。 */ public readonly touched: boolean = false; /** * True if the control has not been marked as touched * * 如果该控件尚未标记为 `touched`,则为 `true`。 * * A control is `untouched` if the user has not yet triggered * a `blur` event on it. * * 如果用户尚未在控件上触发过 `blur` 事件,则该控件为 `untouched`。 */ get untouched(): boolean { return !this.touched; } /** * A multicasting observable that emits an event every time the value of the control changes, in * the UI or programmatically. * * 一个多播 Observable(可观察对象),每当控件的值发生变化时,它就会发出一个事件 —— 无论是通过 UI 还是通过程序。 */ // TODO(issue/24571): remove '!'. public readonly valueChanges !: Observable<any>; /** * A multicasting observable that emits an event every time the validation `status` of the control * recalculates. * * 一个多播 Observable(可观察对象),每当控件的验证 `status` 被重新计算时,就会发出一个事件。 */ // TODO(issue/24571): remove '!'. public readonly statusChanges !: Observable<any>; /** * Reports the update strategy of the `AbstractControl` (meaning * the event on which the control updates itself). * Possible values: `'change'` | `'blur'` | `'submit'` * Default value: `'change'` * * 报告这个 `AbstractControl` 的更新策略(表示控件用来更新自身状态的事件)。 * 可能的值有 `'change'` | `'blur'` | `'submit'`,默认值是 `'change'`。 */ get updateOn(): FormHooks { return this._updateOn ? this._updateOn : (this.parent ? this.parent.updateOn : 'change'); } /** * Sets the synchronous validators that are active on this control. Calling * this overwrites any existing sync validators. * * 设置该控件上所激活的同步验证器。调用它将会覆盖所有现存的同步验证器。 */ setValidators(newValidator: ValidatorFn|ValidatorFn[]|null): void { this.validator = coerceToValidator(newValidator); } /** * Sets the async validators that are active on this control. Calling this * overwrites any existing async validators. * * 设置该控件上所激活的异步验证器。调用它就会覆盖所有现存的异步验证器。 */ setAsyncValidators(newValidator: AsyncValidatorFn|AsyncValidatorFn[]|null): void { this.asyncValidator = coerceToAsyncValidator(newValidator); } /** * Empties out the sync validator list. * * 清空同步验证器列表。 */ clearValidators(): void { this.validator = null; } /** * Empties out the async validator list. * * 清空异步验证器列表。 */ clearAsyncValidators(): void { this.asyncValidator = null; } /** * Marks the control as `touched`. A control is touched by focus and * blur events that do not change the value; compare `markAsDirty`; * * 把该控件标记为 `touched`。控件获得焦点并失去焦点不会修改这个值。与 `markAsDirty` 相对。 * * @param opts Configuration options that determine how the control propagates changes * and emits events events after marking is applied. * * 在应用完此标记后,该配置项会决定控件如何传播变更及发出事件。 * * * `onlySelf`: When true, mark only this control. When false or not supplied, * marks all direct ancestors. Default is false. * * `onlySelf`:如果为 `true` 则只标记当前控件。如果为 `false` 或不提供,则标记它所有的直系祖先。默认为 `false`。 */ markAsTouched(opts: {onlySelf?: boolean} = {}): void { (this as{touched: boolean}).touched = true; if (this._parent && !opts.onlySelf) { this._parent.markAsTouched(opts); } } /** * Marks the control as `untouched`. * * 把该控件标记为 `untouched`。 * * If the control has any children, also marks all children as `untouched` * and recalculates the `touched` status of all parent controls. * * 如果该控件有任何子控件,还会把所有子控件标记为 `untouched`,并重新计算所有父控件的 `touched` 状态。 * * @param opts Configuration options that determine how the control propagates changes * and emits events after the marking is applied. * * 在应用完此标记后,该配置项会决定控件如何传播变更及发出事件。 * * * `onlySelf`: When true, mark only this control. When false or not supplied, * marks all direct ancestors. Default is false. * * `onlySelf`:如果为 `true` 则只标记当前控件。如果为 `false` 或不提供,则标记它所有的直系祖先。默认为 `false`。 * */ markAsUntouched(opts: {onlySelf?: boolean} = {}): void { (this as{touched: boolean}).touched = false; this._pendingTouched = false; this._forEachChild( (control: AbstractControl) => { control.markAsUntouched({onlySelf: true}); }); if (this._parent && !opts.onlySelf) { this._parent._updateTouched(opts); } } /** * Marks the control as `dirty`. A control becomes dirty when * the control's is changed through the UI; compare `markAsTouched`. * * 把控件标记为 `dirty`。当控件通过 UI 修改过时控件会变成 `dirty` 的;与 `markAsTouched` 相对。 * * @param opts Configuration options that determine how the control propagates changes * and emits events after marking is applied. * * 在应用完此标记后,该配置项会决定控件如何传播变更以及发出事件。 * * * `onlySelf`: When true, mark only this control. When false or not supplied, * marks all direct ancestors. Default is false. * * `onlySelf`:如果为 `true` 则只标记当前控件。如果为 `false` 或不提供,则标记它所有的直系祖先。默认为 `false`。 * */ markAsDirty(opts: {onlySelf?: boolean} = {}): void { (this as{pristine: boolean}).pristine = false; if (this._parent && !opts.onlySelf) { this._parent.markAsDirty(opts); } } /** * Marks the control as `pristine`. * * 把该控件标记为 `pristine`(原始状态)。 * * If the control has any children, marks all children as `pristine`, * and recalculates the `pristine` status of all parent * controls. * * 如果该控件有任何子控件,则把所有子控件标记为 `pristine`,并重新计算所有父控件的 `pristine` 状态。 * * @param opts Configuration options that determine how the control emits events after * marking is applied. * * 在应用完此标记后,该配置项会决定控件如何传播更改以及发出事件。 * * * `onlySelf`: When true, mark only this control. When false or not supplied, * marks all direct ancestors. Default is false.. * * `onlySelf`:如果为 `true` 则只标记当前控件。如果为 `false` 或不提供,则标记它所有的直系祖先。默认为 `false`。 * */ markAsPristine(opts: {onlySelf?: boolean} = {}): void { (this as{pristine: boolean}).pristine = true; this._pendingDirty = false; this._forEachChild((control: AbstractControl) => { control.markAsPristine({onlySelf: true}); }); if (this._parent && !opts.onlySelf) { this._parent._updatePristine(opts); } } /** * Marks the control as `pending`. * * 把该控件标记为 `pending`(待定)的。 * * A control is pending while the control performs async validation. * * 当控件正在执行异步验证时,该控件是 `pending` 的。 * * @param opts Configuration options that determine how the control propagates changes and * emits events after marking is applied. * * 在应用完此标记后,该配置项会决定控件如何传播变更以及发出事件。 * * * `onlySelf`: When true, mark only this control. When false or not supplied, * marks all direct ancestors. Default is false.. * * `onlySelf`:如果为 `true` 则只标记当前控件。如果为 `false` 或不提供,则标记它所有的直系祖先。默认为 `false`。 * * * `emitEvent`: When true or not supplied (the default), the `statusChanges` * observable emits an event with the latest status the control is marked pending. * When false, no events are emitted. * * `emitEvent`:如果为 `true` 或未提供(默认值),则 `statusChanges`(Observable)会发出一个事件,传入控件的最近状态,并把控件标记为 `pending` 状态。 * 如果为 `false`,则不会发出事件。 * */ markAsPending(opts: {onlySelf?: boolean, emitEvent?: boolean} = {}): void { (this as{status: string}).status = PENDING; if (opts.emitEvent !== false) { (this.statusChanges as EventEmitter<any>).emit(this.status); } if (this._parent && !opts.onlySelf) { this._parent.markAsPending(opts); } } /** * Disables the control. This means the control is exempt from validation checks and * excluded from the aggregate value of any parent. Its status is `DISABLED`. * * 禁用此控件。这意味着该控件在表单验证检查时会被豁免,并且从其父控件的聚合值中排除它的值。它的状态是 `DISABLED`。 * * If the control has children, all children are also disabled. * * 如果该控件有子控件,则所有子控件也会被禁用。 * * @param opts Configuration options that determine how the control propagates * changes and emits events after the control is disabled. * * 在该控件被禁用之后,该配置项决定如何传播更改以及发出事件。 * * * `onlySelf`: When true, mark only this control. When false or not supplied, * marks all direct ancestors. Default is false.. * * `onlySelf`:如果为 `true`,则只标记当前控件。如果为 `false` 或没有提供,则标记所有直系祖先。默认为 `false`。 * * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and * `valueChanges` * observables emit events with the latest status and value when the control is disabled. * When false, no events are emitted. * * `emitEvent`:如果为 `true` 或没有提供(默认),则当控件被禁用时,`statusChanges` 和 `valueChanges` 这两个 Observable 都会发出最近的状态和值。 * 如果为 `false`,则不会发出事件。 * */ disable(opts: {onlySelf?: boolean, emitEvent?: boolean} = {}): void { (this as{status: string}).status = DISABLED; (this as{errors: ValidationErrors | null}).errors = null; this._forEachChild( (control: AbstractControl) => { control.disable({...opts, onlySelf: true}); }); this._updateValue(); if (opts.emitEvent !== false) { (this.valueChanges as EventEmitter<any>).emit(this.value); (this.statusChanges as EventEmitter<string>).emit(this.status); } this._updateAncestors(opts); this._onDisabledChange.forEach((changeFn) => changeFn(true)); } /** * Enables the control. This means the control is included in validation checks and * the aggregate value of its parent. Its status recalculates based on its value and * its validators. * * 启用该控件。这意味着该控件包含在有效性检查中,并会出现在其父控件的聚合值中。它的状态会根据它的值和验证器而重新计算。 * * By default, if the control has children, all children are enabled. * * 默认情况下,如果该控件具有子控件,则所有子控件都会被启用。 * * @param opts Configure options that control how the control propagates changes and * emits events when marked as untouched * * 当标记为 `untouched` 时,该配置项会决定该控件如何传播变更以及发出事件。 * * * `onlySelf`: When true, mark only this control. When false or not supplied, * marks all direct ancestors. Default is false.. * * `onlySelf`:如果为 `true`,则只标记当前控件。如果为 `false` 或没有提供,则标记所有直系祖先。默认为 `false`。 * * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and * `valueChanges` * observables emit events with the latest status and value when the control is enabled. * When false, no events are emitted. * * `emitEvent`:如果为 `true` 或没有提供(默认),则当控件被启用时,`statusChanges` 和 `valueChanges` 这两个 Observable 都会发出最近的状态和值。 * 如果为 `false`,则不会发出事件。 */ enable(opts: {onlySelf?: boolean, emitEvent?: boolean} = {}): void { (this as{status: string}).status = VALID; this._forEachChild( (control: AbstractControl) => { control.enable({...opts, onlySelf: true}); }); this.updateValueAndValidity({onlySelf: true, emitEvent: opts.emitEvent}); this._updateAncestors(opts); this._onDisabledChange.forEach((changeFn) => changeFn(false)); } private _updateAncestors(opts: {onlySelf?: boolean, emitEvent?: boolean}) { if (this._parent && !opts.onlySelf) { this._parent.updateValueAndValidity(opts); this._parent._updatePristine(); this._parent._updateTouched(); } } /** * @param parent Sets the parent of the control * * 设置该控件的父控件 */ setParent(parent: FormGroup|FormArray): void { this._parent = parent; } /** * Sets the value of the control. Abstract method (implemented in sub-classes). * * 设置该控件的值。这是一个抽象方法(由子类实现)。 */ abstract setValue(value: any, options?: Object): void; /** * Patches the value of the control. Abstract method (implemented in sub-classes). * * 修补(patch)该控件的值。这是一个抽象方法(由子类实现)。 */ abstract patchValue(value: any, options?: Object): void; /** * Resets the control. Abstract method (implemented in sub-classes). * * 重置控件。这是一个抽象方法(由子类实现)。 */ abstract reset(value?: any, options?: Object): void; /** * Recalculates the value and validation status of the control. * * 重新计算控件的值和校验状态。 * * By default, it also updates the value and validity of its ancestors. * * 默认情况下,它还会更新其直系祖先的值和有效性状态。 * * @param opts Configuration options determine how the control propagates changes and emits events * after updates and validity checks are applied. * * 当更新和进行有效性检查之后,该配置项会决定控件如何传播变更并发出事件。 * * * `onlySelf`: When true, only update this control. When false or not supplied, * update all direct ancestors. Default is false.. * * `onlySelf`:如果为 `true`,则只标记当前控件。如果为 `false` 或没有提供,则标记所有直系祖先。默认为 `false`。 * * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and * `valueChanges` * observables emit events with the latest status and value when the control is updated. * When false, no events are emitted. * * `emitEvent`:如果为 `true` 或没有提供(默认),则当控件被启用时,`statusChanges` 和 `valueChanges` 这两个 Observable 都会发出最近的状态和值。 * 如果为 `false`,则不会发出事件。 * */ updateValueAndValidity(opts: {onlySelf?: boolean, emitEvent?: boolean} = {}): void { this._setInitialStatus(); this._updateValue(); if (this.enabled) { this._cancelExistingSubscription(); (this as{errors: ValidationErrors | null}).errors = this._runValidator(); (this as{status: string}).status = this._calculateStatus(); if (this.status === VALID || this.status === PENDING) { this._runAsyncValidator(opts.emitEvent); } } if (opts.emitEvent !== false) { (this.valueChanges as EventEmitter<any>).emit(this.value); (this.statusChanges as EventEmitter<string>).emit(this.status); } if (this._parent && !opts.onlySelf) { this._parent.updateValueAndValidity(opts); } } /** @internal */ _updateTreeValidity(opts: {emitEvent?: boolean} = {emitEvent: true}) { this._forEachChild((ctrl: AbstractControl) => ctrl._updateTreeValidity(opts)); this.updateValueAndValidity({onlySelf: true, emitEvent: opts.emitEvent}); } private _setInitialStatus() { (this as{status: string}).status = this._allControlsDisabled() ? DISABLED : VALID; } private _runValidator(): ValidationErrors|null { return this.validator ? this.validator(this) : null; } private _runAsyncValidator(emitEvent?: boolean): void { if (this.asyncValidator) { (this as{status: string}).status = PENDING; const obs = toObservable(this.asyncValidator(this)); this._asyncValidationSubscription = obs.subscribe((errors: ValidationErrors | null) => this.setErrors(errors, {emitEvent})); } } private _cancelExistingSubscription(): void { if (this._asyncValidationSubscription) { this._asyncValidationSubscription.unsubscribe(); } } /** * Sets errors on a form control when running validations manually, rather than automatically. * * 在手动(而不是自动)运行校验之后,设置表单控件上的错误信息。 * * Calling `setErrors` also updates the validity of the parent control. * * 调用 `setErrors` 还会更新父控件的有效性状态。 * * ### Manually set the errors for a control * * ### 手动设置控件上的错误信息。 * * ``` * const login = new FormControl('someLogin'); * login.setErrors({ * notUnique: true * }); * * expect(login.valid).toEqual(false); * expect(login.errors).toEqual({ notUnique: true }); * * login.setValue('someOtherLogin'); * * expect(login.valid).toEqual(true); * ``` */ setErrors(errors: ValidationErrors|null, opts: {emitEvent?: boolean} = {}): void { (this as{errors: ValidationErrors | null}).errors = errors; this._updateControlsErrors(opts.emitEvent !== false); } /** * Retrieves a child control given the control's name or path. * * 根据指定的控件名称或路径获取子控件。 * * @param path A dot-delimited string or array of string/number values that define the path to the * control. * * 一个由点号(`.`)分隔的字符串或 "字符串/数字" 数组定义的控件路径。 * * ### Retrieve a nested control * * ### 获取嵌套的控件 * * For example, to get a `name` control nested within a `person` sub-group: * * 比如,要获取子控件组 `person` 中的 `name` 控件: * * * `this.form.get('person.name');` * * -OR- * * - 或 - * * * `this.form.get(['person', 'name']);` */ get(path: Array<string|number>|string): AbstractControl|null { return _find(this, path, '.'); } /** * Reports error data for a specific error occurring in this control or in another control. * * 获取发生在该控件或其他控件中发生的指定错误的出错数据。 * * @param errorCode The error code for which to retrieve data * * 要获取的数据的错误码 * * @param path The path to a control to check. If not supplied, checks for the error in this * control. * * 要检查的控件的路径。如果没有提供该参数,则检查该控件中的错误。 * * @returns The error data if the control with the given path has the given error, otherwise null * or undefined. * * 如果指定路径下的控件具有指定的错误,则返回出错数据,否则为 `null` 或 `undefined`。 */ getError(errorCode: string, path?: string[]): any { const control = path ? this.get(path) : this; return control && control.errors ? control.errors[errorCode] : null; } /** * Reports whether the control with the given path has the error specified. * * 报告指定路径下的控件上是否有指定的错误。 * * @param errorCode The error code for which to retrieve data * * 要获取的数据的错误码 * * @param path The path to a control to check. If not supplied, checks for the error in this * control. * * 要检查的控件的路径。如果没有提供该参数,则检查该控件中的错误。 * * @returns True when the control with the given path has the error, otherwise false. * * 如果指定路径下的控件有这个错误则返回 `true`,否则返回 `false`。 */ hasError(errorCode: string, path?: string[]): boolean { return !!this.getError(errorCode, path); } /** * Retrieves the top-level ancestor of this control. * * 获取该控件的顶级祖先。 * */ get root(): AbstractControl { let x: AbstractControl = this; while (x._parent) { x = x._parent; } return x; } /** @internal */ _updateControlsErrors(emitEvent: boolean): void { (this as{status: string}).status = this._calculateStatus(); if (emitEvent) { (this.statusChanges as EventEmitter<string>).emit(this.status); } if (this._parent) { this._parent._updateControlsErrors(emitEvent); } } /** @internal */ _initObservables() { (this as{valueChanges: Observable<any>}).valueChanges = new EventEmitter(); (this as{statusChanges: Observable<any>}).statusChanges = new EventEmitter(); } private _calculateStatus(): string { if (this._allControlsDisabled()) return DISABLED; if (this.errors) return INVALID; if (this._anyControlsHaveStatus(PENDING)) return PENDING; if (this._anyControlsHaveStatus(INVALID)) return INVALID; return VALID; } /** @internal */ abstract _updateValue(): void; /** @internal */ abstract _forEachChild(cb: Function): void; /** @internal */ abstract _anyControls(condition: Function): boolean; /** @internal */ abstract _allControlsDisabled(): boolean; /** @internal */ abstract _syncPendingControls(): boolean; /** @internal */ _anyControlsHaveStatus(status: string): boolean { return this._anyControls((control: AbstractControl) => control.status === status); } /** @internal */ _anyControlsDirty(): boolean { return this._anyControls((control: AbstractControl) => control.dirty); } /** @internal */ _anyControlsTouched(): boolean { return this._anyControls((control: AbstractControl) => control.touched); } /** @internal */ _updatePristine(opts: {onlySelf?: boolean} = {}): void { (this as{pristine: boolean}).pristine = !this._anyControlsDirty(); if (this._parent && !opts.onlySelf) { this._parent._updatePristine(opts); } } /** @internal */ _updateTouched(opts: {onlySelf?: boolean} = {}): void { (this as{touched: boolean}).touched = this._anyControlsTouched(); if (this._parent && !opts.onlySelf) { this._parent._updateTouched(opts); } } /** @internal */ _onDisabledChange: Function[] = []; /** @internal */ _isBoxedValue(formState: any): boolean { return typeof formState === 'object' && formState !== null && Object.keys(formState).length === 2 && 'value' in formState && 'disabled' in formState; } /** @internal */ _registerOnCollectionChange(fn: () => void): void { this._onCollectionChange = fn; } /** @internal */ _setUpdateStrategy(opts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions|null): void { if (isOptionsObj(opts) && (opts as AbstractControlOptions).updateOn != null) { this._updateOn = (opts as AbstractControlOptions).updateOn !; } } } /** * Tracks the value and validation status of an individual form control. * * 跟踪独立表单控件的值和验证状态。 * * This is one of the three fundamental building blocks of Angular forms, along with * `FormGroup` and `FormArray`. It extends the `AbstractControl` class that * implements most of the base functionality for accessing the value, validation status, * user interactions and events. * * 它和 `FormGroup` 和 `FormArray` 是 Angular 表单的三大基本构造块之一。 * 它扩展了 `AbstractControl` 类,并实现了关于访问值、验证状态、用户交互和事件的大部分基本功能。 * * @see `AbstractControl` * @see [Reactive Forms Guide](guide/reactive-forms) * * [响应式表单](guide/reactive-forms) * * @see [Usage Notes](#usage-notes) * * [注意事项](#usage-notes) * * @usageNotes * * ### Initializing Form Controls * * ### 初始化表单控件 * * Instantiate a `FormControl`, with an initial value. * * 用一个初始值初始化 `FormControl`。 * * ```ts * const ctrl = new FormControl('some value'); * console.log(ctrl.value); // 'some value' *``` * * The following example initializes the control with a form state object. The `value` * and `disabled` keys are required in this case. * * 下面的例子用一个表单状态对象初始化控件。这里用到的是 `value` 和 `disabled` 键。 * * ```ts * const ctrl = new FormControl({ value: 'n/a', disabled: true }); * console.log(ctrl.value); // 'n/a' * console.log(ctrl.status); // 'DISABLED' * ``` * * The following example initializes the control with a sync validator. * * 下面的例子使用一个同步验证器初始化了该控件。 * * ```ts * const ctrl = new FormControl('', Validators.required); * console.log(ctrl.value); // '' * console.log(ctrl.status); // 'INVALID' * ``` * * The following example initializes the control using an options object. * * 下面的例子使用一个配置对象初始化了该控件。 * * ```ts * const ctrl = new FormControl('', { * validators: Validators.required, * asyncValidators: myAsyncValidator * }); * ``` * * ### Configure the control to update on a blur event * * ### 配置该控件,使其在发生 `blur` 事件时更新 * * Set the `updateOn` option to `'blur'` to update on the blur `event`. * * 把 `updateOn` 选项设置为 `'blur'`,可以在发生 `blur` 事件时更新。 * * ```ts * const ctrl = new FormControl('', { updateOn: 'blur' }); * ``` * * ### Configure the control to update on a submit event * * ### 配置该控件,使其在发生 `submit` 事件时更新 * * Set the `updateOn` option to `'submit'` to update on a submit `event`. * * 把 `updateOn` 选项设置为 `'submit'`,可以在发生 `submit` 事件时更新。 * ```ts * const ctrl = new FormControl('', { updateOn: 'submit' }); * ``` * * ### Reset the control back to an initial value * * ### 把该控件重置回初始值 * * You reset to a specific form state by passing through a standalone * value or a form state object that contains both a value and a disabled state * (these are the only two properties that cannot be calculated). * * * 通过传递包含值和禁用状态的独立值或表单状态对象,可以将其重置为特定的表单状态(这是所支持的仅有的两个非计算状态)。 * * ```ts * const ctrl = new FormControl('Nancy'); * * console.log(control.value); // 'Nancy' * * control.reset('Drew'); * * console.log(control.value); // 'Drew' * ``` * * ### Reset the control back to an initial value and disabled * * ### 把该控件重置回初始值并禁用。 * * ``` * const ctrl = new FormControl('Nancy'); * * console.log(control.value); // 'Nancy' * console.log(this.control.status); // 'DISABLED' * * control.reset({ value: 'Drew', disabled: true }); * * console.log(this.control.value); // 'Drew' * console.log(this.control.status); // 'DISABLED' * */ export class FormControl extends AbstractControl { /** @internal */ _onChange: Function[] = []; /** @internal */ _pendingValue: any; /** @internal */ _pendingChange: any; /** * Creates a new `FormControl` instance. * * 创建新的 `FormControl` 实例。 * * @param formState Initializes the control with an initial value, * or an object that defines the initial value and disabled state. * * 使用一个初始值或定义了初始值和禁用状态的对象初始化该控件。 * * @param validatorOrOpts A synchronous validator function, or an array of * such functions, or an `AbstractControlOptions` object that contains validation functions * and a validation trigger. * * 一个同步验证器函数或其数组,或者一个包含验证函数和验证触发器的 `AbstractControlOptions` 对象。 * * @param asyncValidator A single async validator or array of async validator functions * * 一个异步验证器函数或其数组。 * */ constructor( formState: any = null, validatorOrOpts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions|null, asyncValidator?: AsyncValidatorFn|AsyncValidatorFn[]|null) { super( coerceToValidator(validatorOrOpts), coerceToAsyncValidator(asyncValidator, validatorOrOpts)); this._applyFormState(formState); this._setUpdateStrategy(validatorOrOpts); this.updateValueAndValidity({onlySelf: true, emitEvent: false}); this._initObservables(); } /** * Sets a new value for the form control. * * 设置该表单控件的新值。 * * @param value The new value for the control. * * 控件的新值。 * * @param options Configuration options that determine how the control proopagates changes * and emits events when the value changes. * The configuration options are passed to the {@link AbstractControl#updateValueAndValidity * updateValueAndValidity} method. * * 当值发生变化时,该配置项决定如何传播变更以及发出事件。 * 该配置项会传递给 {@link AbstractControl#updateValueAndValidity * updateValueAndValidity} 方法。 * * * `onlySelf`: When true, each change only affects this control, and not its parent. Default is * false. * * `onlySelf`:如果为 `true`,则每次变更只影响该控件本身,不影响其父控件。默认为 `false`。 * * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and * `valueChanges` * observables emit events with the latest status and value when the control value is updated. * When false, no events are emitted. * * `emitEvent`:如果为 `true` 或未提供(默认),则当控件值变化时, * `statusChanges` 和 `valueChanges` 这两个 Observable 都会以最近的状态和值发出事件。 * 如果为 `false`,则不会发出事件。 * * * `emitModelToViewChange`: When true or not supplied (the default), each change triggers an * `onChange` event to * update the view. * * `emitModelToViewChange`:如果为 `true` 或未提供(默认),则每次变化都会触发一个 `onChange` 事件以更新视图。 * * * `emitViewToModelChange`: When true or not supplied (the default), each change triggers an * `ngModelChange` * event to update the model. * * `emitViewToModelChange`:如果为 `true` 或未提供(默认),则每次变化都会触发一个 `ngModelChange` 事件以更新模型。 * */ setValue(value: any, options: { onlySelf?: boolean, emitEvent?: boolean, emitModelToViewChange?: boolean, emitViewToModelChange?: boolean } = {}): void { (this as{value: any}).value = this._pendingValue = value; if (this._onChange.length && options.emitModelToViewChange !== false) { this._onChange.forEach( (changeFn) => changeFn(this.value, options.emitViewToModelChange !== false)); } this.updateValueAndValidity(options); } /** * Patches the value of a control. * * 修补控件的值。 * * This function is functionally the same as {@link FormControl#setValue setValue} at this level. * It exists for symmetry with {@link FormGroup#patchValue patchValue} on `FormGroups` and * `FormArrays`, where it does behave differently. * * 在 `FormControl` 这个层次上,该函数的功能和 {@link FormControl#setValue setValue} 完全相同。 * 但 `FormGroup` 和 `FormArray` 上的 {@link FormGroup#patchValue patchValue} 则具有不同的行为。 * * @see `setValue` for options * * `setValue` 的配置项 */ patchValue(value: any, options: { onlySelf?: boolean, emitEvent?: boolean, emitModelToViewChange?: boolean, emitViewToModelChange?: boolean } = {}): void { this.setValue(value, options); } /** * Resets the form control, marking it `pristine` and `untouched`, and setting * the value to null. * * 重置该表单控件,把它标记为 `pristine` 和 `untouched`,并把它的值设置为 `null`。 * * @param formState Resets the control with an initial value, * or an object that defines the initial value and disabled state. * * 使用初始值或一个包含初始值和禁用状态的对象来重置该控件。 * * @param options Configuration options that determine how the control propagates changes * and emits events after the value changes. * * 当值发生变化时,该配置项会决定控件如何传播变更以及发出事件。 * * * `onlySelf`: When true, each change only affects this control, and not its parent. Default is * false. * * `onlySelf`:如果为 `true` ,则每个变更只会影响当前控件而不会影响父控件。默认为 `false`。 * * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and * `valueChanges` * observables emit events with the latest status and value when the control is reset. * When false, no events are emitted. * * `emitEvent`:如果为 `true` 或未提供(默认),则当控件被重置时, * `statusChanges` 和 `valueChanges` 这两个 Observable 都会以最近的状态和值发出事件。 * 如果为 `false`,则不会发出事件。 */ reset(formState: any = null, options: {onlySelf?: boolean, emitEvent?: boolean} = {}): void { this._applyFormState(formState); this.markAsPristine(options); this.markAsUntouched(options); this.setValue(this.value, options); this._pendingChange = false; } /** * @internal */ _updateValue() {} /** * @internal */ _anyControls(condition: Function): boolean { return false; } /** * @internal */ _allControlsDisabled(): boolean { return this.disabled; } /** * Register a listener for change events. * * 注册变更事件的监听器。 * * @param fn The method that is called when the value changes * * 当值变化时,就会调用该方法。 */ registerOnChange(fn: Function): void { this._onChange.push(fn); } /** * @internal */ _clearChangeFns(): void { this._onChange = []; this._onDisabledChange = []; this._onCollectionChange = () => {}; } /** * Register a listener for disabled events. * * 注册禁用事件的监听器。 * * @param fn The method that is called when the disabled status changes. * * 当禁用状态发生变化时,就会调用该方法。 */ registerOnDisabledChange(fn: (isDisabled: boolean) => void): void { this._onDisabledChange.push(fn); } /** * @internal */ _forEachChild(cb: Function): void {} /** @internal */ _syncPendingControls(): boolean { if (this.updateOn === 'submit') { if (this._pendingDirty) this.markAsDirty(); if (this._pendingTouched) this.markAsTouched(); if (this._pendingChange) { this.setValue(this._pendingValue, {onlySelf: true, emitModelToViewChange: false}); return true; } } return false; } private _applyFormState(formState: any) { if (this._isBoxedValue(formState)) { (this as{value: any}).value = this._pendingValue = formState.value; formState.disabled ? this.disable({onlySelf: true, emitEvent: false}) : this.enable({onlySelf: true, emitEvent: false}); } else { (this as{value: any}).value = this._pendingValue = formState; } } } /** * Tracks the value and validity state of a group of `FormControl` instances. * * 跟踪一组 `FormControl` 实例的值和有效性状态。 * * A `FormGroup` aggregates the values of each child `FormControl` into one object, * with each control name as the key. It calculates its status by reducing the status values * of its children. For example, if one of the controls in a group is invalid, the entire * group becomes invalid. * * `FormGroup` 把每个子 `FormControl` 的值聚合进一个对象,它的 key 是每个控件的名字。 * 它通过归集其子控件的状态值来计算出自己的状态。 * 比如,如果组中的任何一个控件是无效的,那么整个组就是无效的。 * * `FormGroup` is one of the three fundamental building blocks used to define forms in Angular, * along with `FormControl` and `FormArray`. * * `FormGroup` 是 Angular 中用来定义表单的三大基本构造块之一,就像 `FormControl`、`FormArray` 一样。 * * When instantiating a `FormGroup`, pass in a collection of child controls as the first * argument. The key for each child registers the name for the control. * * 当实例化 `FormGroup` 时,在第一个参数中传入一组子控件。每个子控件会用控件名把自己注册进去。 * * @usageNotes * * ### Create a form group with 2 controls * * ### 创建一个带有两个控件的表单组 * * ``` * const form = new FormGroup({ * first: new FormControl('Nancy', Validators.minLength(2)), * last: new FormControl('Drew'), * }); * * console.log(form.value); // {first: 'Nancy', last; 'Drew'} * console.log(form.status); // 'VALID' * ``` * * ### Create a form group with a group-level validator * * ### 创建一个具有组级验证器的表单组 * * You include group-level validators as the second arg, or group-level async * validators as the third arg. These come in handy when you want to perform validation * that considers the value of more than one child control. * * 你可以用第二个参数传入一些组级验证器或用第三个参数传入一些组级异步验证器。 * 当你要根据一个以上子控件的值来决定有效性时,这很好用。 * * ``` * const form = new FormGroup({ * password: new FormControl('', Validators.minLength(2)), * passwordConfirm: new FormControl('', Validators.minLength(2)), * }, passwordMatchValidator); * * * function passwordMatchValidator(g: FormGroup) { * return g.get('password').value === g.get('passwordConfirm').value * ? null : {'mismatch': true}; * } * ``` * * Like `FormControl` instances, you choose to pass in * validators and async validators as part of an options object. * * 像 `FormControl` 实例一样,你也可以在配置对象中传入验证器和异步验证器。 * * ``` * const form = new FormGroup({ * password: new FormControl('') * passwordConfirm: new FormControl('') * }, { validators: passwordMatchValidator, asyncValidators: otherValidator }); * ``` * * ### Set the updateOn property for all controls in a form group * * ### 为表单组中的所有空间设置 `updateOn` 属性 * * The options object is used to set a default value for each child * control's `updateOn` property. If you set `updateOn` to `'blur'` at the * group level, all child controls default to 'blur', unless the child * has explicitly specified a different `updateOn` value. * * 该选项对象可用来为每个子控件的 `updateOn` 属性设置默认值。 * 如果在组级把 `updateOn` 设置为 `'blur'`,则所有子控件的默认值也是 `'blur'`,除非这个子控件显式的指定了另一个 `updateOn` 值。 * * ```ts * const c = new FormGroup({ * one: new FormControl() * }, { updateOn: 'blur' }); * ``` */ export class FormGroup extends AbstractControl { /** * Creates a new `FormGroup` instance. * * 创建一个新的 `FormGroup` 实例 * * @param controls A collection of child controls. The key for each child is the name * under which it is registered. * * 一组子控件。每个子控件的名字就是它注册时用的 `key`。 * * @param validatorOrOpts A synchronous validator function, or an array of * such functions, or an `AbstractControlOptions` object that contains validation functions * and a validation trigger. * * 一个同步验证器函数或其数组,或者一个包含验证函数和验证触发器的 `AbstractControlOptions` 对象。 * * @param asyncValidator A single async validator or array of async validator functions * * 单个的异步验证器函数或其数组。 * */ constructor( public controls: {[key: string]: AbstractControl}, validatorOrOpts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions|null, asyncValidator?: AsyncValidatorFn|AsyncValidatorFn[]|null) { super( coerceToValidator(validatorOrOpts), coerceToAsyncValidator(asyncValidator, validatorOrOpts)); this._initObservables(); this._setUpdateStrategy(validatorOrOpts); this._setUpControls(); this.updateValueAndValidity({onlySelf: true, emitEvent: false}); } /** * Registers a control with the group's list of controls. * * 向组内的控件列表中注册一个控件。 * * This method does not update the value or validity of the control. * Use {@link FormGroup#addControl addControl} instead. * * 该方法不会更新控件的值或其有效性。 * 使用 {@link FormGroup#addControl addControl} 代替。 * * @param name The control name to register in the collection * * 注册到集合中的控件名 * * @param control Provides the control for the given name * * 提供这个名字对应的控件 * */ registerControl(name: string, control: AbstractControl): AbstractControl { if (this.controls[name]) return this.controls[name]; this.controls[name] = control; control.setParent(this); control._registerOnCollectionChange(this._onCollectionChange); return control; } /** * Add a control to this group. * * 往组中添加一个控件。 * * This method also updates the value and validity of the control. * * 该方法还会更新本空间的值和有效性。 * * @param name The control name to add to the collection * * 要注册到集合中的控件名 * * @param control Provides the control for the given name * * 提供与该控件名对应的控件。 * */ addControl(name: string, control: AbstractControl): void { this.registerControl(name, control); this.updateValueAndValidity(); this._onCollectionChange(); } /** * Remove a control from this group. * * 从该组中移除一个控件。 * * @param name The control name to remove from the collection * * 要从集合中移除的控件名 * */ removeControl(name: string): void { if (this.controls[name]) this.controls[name]._registerOnCollectionChange(() => {}); delete (this.controls[name]); this.updateValueAndValidity(); this._onCollectionChange(); } /** * Replace an existing control. * * 替换现有控件。 * * @param name The control name to replace in the collection * * 要从集合中替换掉的控件名 * * @param control Provides the control for the given name * * 提供具有指定名称的控件 * */ setControl(name: string, control: AbstractControl): void { if (this.controls[name]) this.controls[name]._registerOnCollectionChange(() => {}); delete (this.controls[name]); if (control) this.registerControl(name, control); this.updateValueAndValidity(); this._onCollectionChange(); } /** * Check whether there is an enabled control with the given name in the group. * * 检查组内是否有一个具有指定名字的已启用的控件。 * * Reports false for disabled controls. If you'd like to check for existence in the group * only, use {@link AbstractControl#get get} instead. * * 对于已禁用的控件,返回 `false`。如果你只想检查它是否存在于该组中,请改用 {@link AbstractControl#get get} 代替。 * * @param name The control name to check for existence in the collection * * 要在集合中检查是否存在的控件名 * * @returns false for disabled controls, true otherwise. * * 对于已禁用的控件返回 `false`,否则返回 `true`。 */ contains(controlName: string): boolean { return this.controls.hasOwnProperty(controlName) && this.controls[controlName].enabled; } /** * Sets the value of the `FormGroup`. It accepts an object that matches * the structure of the group, with control names as keys. * * 设置此 `FormGroup` 的值。它接受一个与组结构对应的对象,以控件名作为 key。 * * ### Set the complete value for the form group * * ### 设置表单组的完整值 * * ``` * const form = new FormGroup({ * first: new FormControl(), * last: new FormControl() * }); * * console.log(form.value); // {first: null, last: null} * * form.setValue({first: 'Nancy', last: 'Drew'}); * console.log(form.value); // {first: 'Nancy', last: 'Drew'} * * ``` * @throws When strict checks fail, such as setting the value of a control * that doesn't exist or if you excluding the value of a control. * * 当严格的检查失败时,比如设置了不存在的或被排除出去的控件的值。 * * @param value The new value for the control that matches the structure of the group. * * 控件的新值,其结构必须和该组的结构相匹配。 * * @param options Configuration options that determine how the control propagates changes * and emits events after the value changes. * The configuration options are passed to the {@link AbstractControl#updateValueAndValidity * updateValueAndValidity} method. * * 当值变化时,此配置项会决定该控件会如何传播变更以及发出事件。该配置项会被传给 {@link AbstractControl#updateValueAndValidity * updateValueAndValidity} 方法。 * * * `onlySelf`: When true, each change only affects this control, and not its parent. Default is * false. * * `onlySelf`::如果为 `true`,则每个变更仅仅影响当前控件,而不会影响父控件。默认为 `false`。 * * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and * `valueChanges` * observables emit events with the latest status and value when the control value is updated. * When false, no events are emitted. * * `emitEvent`:如果为 `true` 或未提供(默认),则当控件值发生变化时,`statusChanges` 和 `valueChanges` 这两个 `Observable` 分别会以最近的状态和值发出事件。 * 如果为 `false` 则不发出事件。 * */ setValue(value: {[key: string]: any}, options: {onlySelf?: boolean, emitEvent?: boolean} = {}): void { this._checkAllValuesPresent(value); Object.keys(value).forEach(name => { this._throwIfControlMissing(name); this.controls[name].setValue(value[name], {onlySelf: true, emitEvent: options.emitEvent}); }); this.updateValueAndValidity(options); } /** * Patches the value of the `FormGroup`. It accepts an object with control * names as keys, and does its best to match the values to the correct controls * in the group. * * 修补此 `FormGroup` 的值。它接受一个以控件名为 key 的对象,并尽量把它们的值匹配到组中正确的控件上。 * * It accepts both super-sets and sub-sets of the group without throwing an error. * * 它能接受组的超集和子集,而不会抛出错误。 * * ### Patch the value for a form group * * ### 修补表单组的值 * * ``` * const form = new FormGroup({ * first: new FormControl(), * last: new FormControl() * }); * console.log(form.value); // {first: null, last: null} * * form.patchValue({first: 'Nancy'}); * console.log(form.value); // {first: 'Nancy', last: null} * * ``` * * @param value The object that matches the structure of the group * * 与该组的结构匹配的对象 * * @param options Configure options that determines how the control propagates changes and * emits events after the value is patched * * 在修补了该值之后,此配置项会决定控件如何传播变更以及发出事件。 * * * `onlySelf`: When true, each change only affects this control, and not its parent. Default is * true. * * `onlySelf`::如果为 `true`,则每个变更仅仅影响当前控件,而不会影响父控件。默认为 `false`。 * * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and * `valueChanges` * observables emit events with the latest status and value when the control value is updated. * When false, no events are emitted. * The configuration options are passed to the {@link AbstractControl#updateValueAndValidity * updateValueAndValidity} method. * * `emitEvent`:如果为 `true` 或未提供(默认),则当控件值发生变化时,`statusChanges` 和 `valueChanges` 这两个 `Observable` 分别会以最近的状态和值发出事件。 * 如果为 `false` 则不发出事件。 * 该配置项会被传给 {@link AbstractControl#updateValueAndValidity * updateValueAndValidity} 方法。 * */ patchValue(value: {[key: string]: any}, options: {onlySelf?: boolean, emitEvent?: boolean} = {}): void { Object.keys(value).forEach(name => { if (this.controls[name]) { this.controls[name].patchValue(value[name], {onlySelf: true, emitEvent: options.emitEvent}); } }); this.updateValueAndValidity(options); } /** * Resets the `FormGroup`, marks all descendants are marked `pristine` and `untouched`, and * the value of all descendants to null. * * 重置这个 `FormGroup`,把它的各级子控件都标记为 `pristine` 和 `untouched`,并把它们的值都设置为 `null`。 * * You reset to a specific form state by passing in a map of states * that matches the structure of your form, with control names as keys. The state * is a standalone value or a form state object with both a value and a disabled * status. * * 你可以通过传入一个与表单结构相匹配的以控件名为 key 的 Map,来把表单重置为特定的状态。 * 其状态可以是一个单独的值,也可以是一个同时具有值和禁用状态的表单状态对象。 * * @param formState Resets the control with an initial value, * or an object that defines the initial value and disabled state. * * 使用一个初始值或包含初始值与禁用状态的对象重置该控件。 * * @param options Configuration options that determine how the control propagates changes * and emits events when the group is reset. * * 当该组被重置时,此配置项会决定该控件如何传播变更以及发出事件。 * * * `onlySelf`: When true, each change only affects this control, and not its parent. Default is * false. * * `onlySelf`::如果为 `true`,则每个变更仅仅影响当前控件,而不会影响父控件。默认为 `false`。 * * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and * `valueChanges` * observables emit events with the latest status and value when the control is reset. * When false, no events are emitted. * The configuration options are passed to the {@link AbstractControl#updateValueAndValidity * updateValueAndValidity} method. * * `emitEvent`:如果为 `true` 或未提供(默认),则当控件值发生变化时,`statusChanges` 和 `valueChanges` 这两个 `Observable` 分别会以最近的状态和值发出事件。 * 如果为 `false` 则不发出事件。 * 该配置项会被传给 {@link AbstractControl#updateValueAndValidity * updateValueAndValidity} 方法。 * * @usageNotes * * ### Reset the form group values * * ### 重置该表单组的值 * * ```ts * const form = new FormGroup({ * first: new FormControl('first name'), * last: new FormControl('last name') * }); * * console.log(form.value); // {first: 'first name', last: 'last name'} * * form.reset({ first: 'name', last: 'last name' }); * * console.log(form.value); // {first: 'name', last: 'last name'} * ``` * * ### Reset the form group values and disabled status * * ### 重置该表单组的值以及禁用状态 * * ``` * const form = new FormGroup({ * first: new FormControl('first name'), * last: new FormControl('last name') * }); * * form.reset({ * first: {value: 'name', disabled: true}, * last: 'last' * }); * * console.log(this.form.value); // {first: 'name', last: 'last name'} * console.log(this.form.get('first').status); // 'DISABLED' * ``` */ reset(value: any = {}, options: {onlySelf?: boolean, emitEvent?: boolean} = {}): void { this._forEachChild((control: AbstractControl, name: string) => { control.reset(value[name], {onlySelf: true, emitEvent: options.emitEvent}); }); this.updateValueAndValidity(options); this._updatePristine(options); this._updateTouched(options); } /** * The aggregate value of the `FormGroup`, including any disabled controls. * * 这个 `FormGroup` 的聚合值,包括所有已禁用的控件。 * * Retrieves all values regardless of disabled status. * The `value` property is the best way to get the value of the group, because * it excludes disabled controls in the `FormGroup`. * * 获取所有控件的值而不管其禁用状态。 * `value` 属性是获取组中的值的最佳方式,因为它从 `FormGroup` 中排除了所有已禁用的控件。 */ getRawValue(): any { return this._reduceChildren( {}, (acc: {[k: string]: AbstractControl}, control: AbstractControl, name: string) => { acc[name] = control instanceof FormControl ? control.value : (<any>control).getRawValue(); return acc; }); } /** @internal */ _syncPendingControls(): boolean { let subtreeUpdated = this._reduceChildren(false, (updated: boolean, child: AbstractControl) => { return child._syncPendingControls() ? true : updated; }); if (subtreeUpdated) this.updateValueAndValidity({onlySelf: true}); return subtreeUpdated; } /** @internal */ _throwIfControlMissing(name: string): void { if (!Object.keys(this.controls).length) { throw new Error(` There are no form controls registered with this group yet. If you're using ngModel, you may want to check next tick (e.g. use setTimeout). `); } if (!this.controls[name]) { throw new Error(`Cannot find form control with name: ${name}.`); } } /** @internal */ _forEachChild(cb: (v: any, k: string) => void): void { Object.keys(this.controls).forEach(k => cb(this.controls[k], k)); } /** @internal */ _setUpControls(): void { this._forEachChild((control: AbstractControl) => { control.setParent(this); control._registerOnCollectionChange(this._onCollectionChange); }); } /** @internal */ _updateValue(): void { (this as{value: any}).value = this._reduceValue(); } /** @internal */ _anyControls(condition: Function): boolean { let res = false; this._forEachChild((control: AbstractControl, name: string) => { res = res || (this.contains(name) && condition(control)); }); return res; } /** @internal */ _reduceValue() { return this._reduceChildren( {}, (acc: {[k: string]: AbstractControl}, control: AbstractControl, name: string) => { if (control.enabled || this.disabled) { acc[name] = control.value; } return acc; }); } /** @internal */ _reduceChildren(initValue: any, fn: Function) { let res = initValue; this._forEachChild( (control: AbstractControl, name: string) => { res = fn(res, control, name); }); return res; } /** @internal */ _allControlsDisabled(): boolean { for (const controlName of Object.keys(this.controls)) { if (this.controls[controlName].enabled) { return false; } } return Object.keys(this.controls).length > 0 || this.disabled; } /** @internal */ _checkAllValuesPresent(value: any): void { this._forEachChild((control: AbstractControl, name: string) => { if (value[name] === undefined) { throw new Error(`Must supply a value for form control with name: '${name}'.`); } }); } } /** * Tracks the value and validity state of an array of `FormControl`, * `FormGroup` or `FormArray` instances. * * 跟踪一个控件数组的值和有效性状态,控件可以是 `FormControl`、`FormGroup` 或 `FormArray` 的实例。 * * A `FormArray` aggregates the values of each child `FormControl` into an array. * It calculates its status by reducing the status values of its children. For example, if one of * the controls in a `FormArray` is invalid, the entire array becomes invalid. * * `FormArray` 聚合了数组中每个表单控件的值。 * 它还会根据其所有子控件的状态总结出自己的状态。比如,如果 `FromArray` 中的任何一个控件是无效的,那么整个数组也会变成无效的。 * * `FormArray` is one of the three fundamental building blocks used to define forms in Angular, * along with `FormControl` and `FormGroup`. * * `FormArray` 是 Angular 表单中定义的三个基本构造块之一,就像 `FormControl` 和 `FormGroup` 一样。 * * @usageNotes * * ### Create an array of form controls * * ### 创建表单控件的数组 * * ``` * const arr = new FormArray([ * new FormControl('Nancy', Validators.minLength(2)), * new FormControl('Drew'), * ]); * * console.log(arr.value); // ['Nancy', 'Drew'] * console.log(arr.status); // 'VALID' * ``` * * ### Create a form array with array-level validators * * ### 创建一个带有数组级验证器的表单数组 * * You include array-level validators and async validators. These come in handy * when you want to perform validation that considers the value of more than one child * control. * * 你可以定义数组级的验证器和异步验证器。当你需要根据一个或多个子控件的值来进行有效性验证时,这很有用。 * * The two types of validators are passed in separately as the second and third arg * respectively, or together as part of an options object. * * 这两种类型的验证器分别通过第二个和第三个参数或作为配置对象的一部分传进去。 * * ``` * const arr = new FormArray([ * new FormControl('Nancy'), * new FormControl('Drew') * ], {validators: myValidator, asyncValidators: myAsyncValidator}); * ``` * * ### Set the updateOn property for all controls in a form array * * ### 为表单数组中的所有控件设置 `updateOn` 属性 * * The options object is used to set a default value for each child * control's `updateOn` property. If you set `updateOn` to `'blur'` at the * array level, all child controls default to 'blur', unless the child * has explicitly specified a different `updateOn` value. * * 该配置对象可以为每个子控件的 `updateOn` 属性设置默认值。 * 如果在数组级把 `updateOn` 设置为 `'blur'`,则所有子控件的默认值也是 `'blur'`,除非这个子控件显式的指定了另一个 `updateOn` 值。 * * ```ts * const arr = new FormArray([ * new FormControl() * ], {updateOn: 'blur'}); * ``` * * ### Adding or removing controls from a form array * * ### 从表单数组中添加或删除控件 * * To change the controls in the array, use the `push`, `insert`, or `removeAt` methods * in `FormArray` itself. These methods ensure the controls are properly tracked in the * form's hierarchy. Do not modify the array of `AbstractControl`s used to instantiate * the `FormArray` directly, as that result in strange and unexpected behavior such * as broken change detection. * * 要改变数组中的控件列表,可以使用 `FormArray` 本身的 `push`、`insert` 或 `removeAt` 方法。这些方法能确保表单数组正确的跟踪这些子控件。 * 不要直接修改实例化 `FormArray` 时传入的那个 `AbstractControl` 数组,否则会导致奇怪的、非预期的行为,比如破坏变更检测机制。 * */ export class FormArray extends AbstractControl { /** * Creates a new `FormArray` instance. * * 创建一个新的 `FormArray` 实例 * * @param controls An array of child controls. Each child control is given an index * wheh it is registered. * * 一个子控件数组。在注册后,每个子控件都会有一个指定的索引。 * * @param validatorOrOpts A synchronous validator function, or an array of * such functions, or an `AbstractControlOptions` object that contains validation functions * and a validation trigger. * * 一个同步验证器函数或其数组,或者一个包含验证函数和验证触发器的 `AbstractControlOptions` 对象。 * * @param asyncValidator A single async validator or array of async validator functions * * 单个的异步验证器函数或其数组。 * */ constructor( public controls: AbstractControl[], validatorOrOpts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions|null, asyncValidator?: AsyncValidatorFn|AsyncValidatorFn[]|null) { super( coerceToValidator(validatorOrOpts), coerceToAsyncValidator(asyncValidator, validatorOrOpts)); this._initObservables(); this._setUpdateStrategy(validatorOrOpts); this._setUpControls(); this.updateValueAndValidity({onlySelf: true, emitEvent: false}); } /** * Get the `AbstractControl` at the given `index` in the array. * * 获取数组中指定 `index` 处的 `AbstractControl`。 * * @param index Index in the array to retrieve the control * * 要获取的控件在数组中的索引 */ at(index: number): AbstractControl { return this.controls[index]; } /** * Insert a new `AbstractControl` at the end of the array. * * 在数组的末尾插入一个新的 `AbstractControl`。 * * @param control Form control to be inserted * * 要插入的表单控件 * */ push(control: AbstractControl): void { this.controls.push(control); this._registerControl(control); this.updateValueAndValidity(); this._onCollectionChange(); } /** * Insert a new `AbstractControl` at the given `index` in the array. * * 在数组中的指定 `index` 处插入一个新的 `AbstractControl`。 * * @param index Index in the array to insert the control * * 要插入该控件的索引序号 * * @param control Form control to be inserted * * 要插入的表单控件 * */ insert(index: number, control: AbstractControl): void { this.controls.splice(index, 0, control); this._registerControl(control); this.updateValueAndValidity(); } /** * Remove the control at the given `index` in the array. * * 移除位于数组中的指定 `index` 处的控件。 * * @param index Index in the array to remove the control * * 要移除的控件在数组中的索引 * */ removeAt(index: number): void { if (this.controls[index]) this.controls[index]._registerOnCollectionChange(() => {}); this.controls.splice(index, 1); this.updateValueAndValidity(); } /** * Replace an existing control. * * 替换现有控件。 * * @param index Index in the array to replace the control * * 要替换的控件在数组中的索引 * * @param control The `AbstractControl` control to replace the existing control * * 要用来替换现有控件的 `AbstractControl` 控件 */ setControl(index: number, control: AbstractControl): void { if (this.controls[index]) this.controls[index]._registerOnCollectionChange(() => {}); this.controls.splice(index, 1); if (control) { this.controls.splice(index, 0, control); this._registerControl(control); } this.updateValueAndValidity(); this._onCollectionChange(); } /** * Length of the control array. * * 控件数组的长度。 */ get length(): number { return this.controls.length; } /** * Sets the value of the `FormArray`. It accepts an array that matches * the structure of the control. * * 设置此 `FormArray` 的值。它接受一个与控件结构相匹配的数组。 * * This method performs strict checks, and throws an error if you try * to set the value of a control that doesn't exist or if you exclude the * value of a control. * * 该方法会执行严格检查,如果你视图设置不存在或被排除出去的控件的值,就会抛出错误。 * * ### Set the values for the controls in the form array * * ### 设置表单数组中各个控件的值 * * ``` * const arr = new FormArray([ * new FormControl(), * new FormControl() * ]); * console.log(arr.value); // [null, null] * * arr.setValue(['Nancy', 'Drew']); * console.log(arr.value); // ['Nancy', 'Drew'] * ``` * * @param value Array of values for the controls * * 要传给这些控件的值的数组 * * @param options Configure options that determine how the control propagates changes and * emits events after the value changes * * 当值变化时,此配置项会决定该控件会如何传播变更以及发出事件。 * * * `onlySelf`: When true, each change only affects this control, and not its parent. Default * is false. * * `onlySelf`::如果为 `true`,则每个变更仅仅影响当前控件,而不会影响父控件。默认为 `false`。 * * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and * `valueChanges` * observables emit events with the latest status and value when the control value is updated. * When false, no events are emitted. * The configuration options are passed to the {@link AbstractControl#updateValueAndValidity * updateValueAndValidity} method. * * `emitEvent`:如果为 `true` 或未提供(默认),则当控件值发生变化时,`statusChanges` 和 `valueChanges` 这两个 `Observable` 分别会以最近的状态和值发出事件。 * 如果为 `false` 则不发出事件。 * 该配置项会被传给 {@link AbstractControl#updateValueAndValidity * updateValueAndValidity} 方法。 * */ setValue(value: any[], options: {onlySelf?: boolean, emitEvent?: boolean} = {}): void { this._checkAllValuesPresent(value); value.forEach((newValue: any, index: number) => { this._throwIfControlMissing(index); this.at(index).setValue(newValue, {onlySelf: true, emitEvent: options.emitEvent}); }); this.updateValueAndValidity(options); } /** * Patches the value of the `FormArray`. It accepts an array that matches the * structure of the control, and does its best to match the values to the correct * controls in the group. * * 修补此 `FormArray` 的值。它接受一个与该控件的结构相匹配的数组,并尽量把它们的值匹配到组中正确的控件上。 * * It accepts both super-sets and sub-sets of the array without throwing an error. * * 它能接受数组的超集和子集,而不会抛出错误。 * * ### Patch the values for controls in a form array * * ### 修补表单数组中各个控件的值 * * ``` * const arr = new FormArray([ * new FormControl(), * new FormControl() * ]); * console.log(arr.value); // [null, null] * * arr.patchValue(['Nancy']); * console.log(arr.value); // ['Nancy', null] * ``` * * @param value Array of latest values for the controls * * 由各个控件最近的值组成的数组 * * @param options Configure options that determine how the control propagates changes and * emits events after the value changes * * 在修补了该值之后,此配置项会决定控件如何传播变更以及发出事件。 * * * `onlySelf`: When true, each change only affects this control, and not its parent. Default * is false. * * `onlySelf`::如果为 `true`,则每个变更仅仅影响当前控件,而不会影响父控件。默认为 `false`。 * * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and * `valueChanges` * observables emit events with the latest status and value when the control value is updated. * When false, no events are emitted. * The configuration options are passed to the {@link AbstractControl#updateValueAndValidity * updateValueAndValidity} method. * * `emitEvent`:如果为 `true` 或未提供(默认),则当控件值发生变化时,`statusChanges` 和 `valueChanges` 这两个 `Observable` 分别会以最近的状态和值发出事件。 * 如果为 `false` 则不发出事件。 * 该配置项会被传给 {@link AbstractControl#updateValueAndValidity * updateValueAndValidity} 方法。 * */ patchValue(value: any[], options: {onlySelf?: boolean, emitEvent?: boolean} = {}): void { value.forEach((newValue: any, index: number) => { if (this.at(index)) { this.at(index).patchValue(newValue, {onlySelf: true, emitEvent: options.emitEvent}); } }); this.updateValueAndValidity(options); } /** * Resets the `FormArray` and all descendants are marked `pristine` and `untouched`, and the * value of all descendants to null or null maps. * * 重置这个 `FormArray`,把它的各级子控件都标记为 `pristine` 和 `untouched`,并把它们的值都设置为 `null`。 * * You reset to a specific form state by passing in an array of states * that matches the structure of the control. The state is a standalone value * or a form state object with both a value and a disabled status. * * 你可以通过传入一个与表单结构相匹配的状态数组,来把表单重置为特定的状态。 * 每个状态可以是一个单独的值,也可以是一个同时具有值和禁用状态的表单状态对象。 * * ### Reset the values in a form array * * ### 重置表单数组中的各个值 * * ```ts * const arr = new FormArray([ * new FormControl(), * new FormControl() * ]); * arr.reset(['name', 'last name']); * * console.log(this.arr.value); // ['name', 'last name'] * ``` * * ### Reset the values in a form array and the disabled status for the first control * * ### 重置表单数组中的各个值和第一个控件的禁用状态 * * ``` * this.arr.reset([ * {value: 'name', disabled: true}, * 'last' * ]); * * console.log(this.arr.value); // ['name', 'last name'] * console.log(this.arr.get(0).status); // 'DISABLED' * ``` * * @param value Array of values for the controls * * 各个控件值的数组 * * @param options Configure options that determine how the control propagates changes and * emits events after the value changes * * 当值变化时,此配置项会决定该控件如何传播变更以及发出事件。 * * * `onlySelf`: When true, each change only affects this control, and not its parent. Default * is false. * * `onlySelf`::如果为 `true`,则每个变更仅仅影响当前控件,而不会影响父控件。默认为 `false`。 * * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and * `valueChanges` * observables emit events with the latest status and value when the control is reset. * When false, no events are emitted. * The configuration options are passed to the {@link AbstractControl#updateValueAndValidity * updateValueAndValidity} method. * * `emitEvent`:如果为 `true` 或未提供(默认),则当控件值发生变化时,`statusChanges` 和 `valueChanges` 这两个 `Observable` 分别会以最近的状态和值发出事件。 * 如果为 `false` 则不发出事件。 * 该配置项会被传给 {@link AbstractControl#updateValueAndValidity * updateValueAndValidity} 方法。 * */ reset(value: any = [], options: {onlySelf?: boolean, emitEvent?: boolean} = {}): void { this._forEachChild((control: AbstractControl, index: number) => { control.reset(value[index], {onlySelf: true, emitEvent: options.emitEvent}); }); this.updateValueAndValidity(options); this._updatePristine(options); this._updateTouched(options); } /** * The aggregate value of the array, including any disabled controls. * * 这个 `FormArray` 的聚合值,包括所有已禁用的控件。 * * Reports all values regardless of disabled status. * For enabled controls only, the `value` property is the best way to get the value of the array. * * 获取所有控件的值而不管其禁用状态。 * 如果只想获取已启用的控件的值,则最好使用 `value` 属性来获取此数组的值。 */ getRawValue(): any[] { return this.controls.map((control: AbstractControl) => { return control instanceof FormControl ? control.value : (<any>control).getRawValue(); }); } /** @internal */ _syncPendingControls(): boolean { let subtreeUpdated = this.controls.reduce((updated: boolean, child: AbstractControl) => { return child._syncPendingControls() ? true : updated; }, false); if (subtreeUpdated) this.updateValueAndValidity({onlySelf: true}); return subtreeUpdated; } /** @internal */ _throwIfControlMissing(index: number): void { if (!this.controls.length) { throw new Error(` There are no form controls registered with this array yet. If you're using ngModel, you may want to check next tick (e.g. use setTimeout). `); } if (!this.at(index)) { throw new Error(`Cannot find form control at index ${index}`); } } /** @internal */ _forEachChild(cb: Function): void { this.controls.forEach((control: AbstractControl, index: number) => { cb(control, index); }); } /** @internal */ _updateValue(): void { (this as{value: any}).value = this.controls.filter((control) => control.enabled || this.disabled) .map((control) => control.value); } /** @internal */ _anyControls(condition: Function): boolean { return this.controls.some((control: AbstractControl) => control.enabled && condition(control)); } /** @internal */ _setUpControls(): void { this._forEachChild((control: AbstractControl) => this._registerControl(control)); } /** @internal */ _checkAllValuesPresent(value: any): void { this._forEachChild((control: AbstractControl, i: number) => { if (value[i] === undefined) { throw new Error(`Must supply a value for form control at index: ${i}.`); } }); } /** @internal */ _allControlsDisabled(): boolean { for (const control of this.controls) { if (control.enabled) return false; } return this.controls.length > 0 || this.disabled; } private _registerControl(control: AbstractControl) { control.setParent(this); control._registerOnCollectionChange(this._onCollectionChange); } }
import { useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Link } from 'react-router-dom'; import { addItems } from '../redux/slices/cartSlice'; import { RootState } from '../redux/store'; export type PizzaBlockProps = { title: string; price: number; imageUrl: string; sizes: number[]; types: number[]; id: number; descr: string; }; const PizzaBlock: React.FC<PizzaBlockProps> = ({ title, price, imageUrl, sizes, types, id, descr, }) => { const pizzaTypes = ['тонкое', 'традиционное']; const cartItem = useSelector((state: RootState) => state.cart.items.filter((obj: any) => obj.title == title) ); const [activeType, setActiveType] = useState( types.length > 1 ? 'тонкое' : pizzaTypes[types[0]] ); const [activeSize, setActiveSize] = useState(0); const dispatch = useDispatch(); const addToCart = () => { dispatch( addItems({ title, price, imageUrl, size: sizes[activeSize], type: activeType, id, }) ); }; const total = cartItem .map((item: any) => { return item.count; }) .reduce(function (sum: number, current: number) { return sum + current; }, 0); return ( <div className="pizza-block-wrapper"> <div className="pizza-block"> <Link to={`/pizza/${id}`}> <img className="pizza-block__image" src={imageUrl} alt="Pizza" /> <h4 className="pizza-block__title">{title}</h4> </Link> <div className="pizza-block__selector"> <ul> {types.map((index, i, arr) => { return ( <li key={i} onClick={() => setActiveType(pizzaTypes[index])} className={activeType === pizzaTypes[index] ? 'active' : ''} > {pizzaTypes[index]} </li> ); })} </ul> <ul> {sizes.map((elem, i) => { return ( <li key={elem} onClick={() => setActiveSize(i)} className={activeSize === i ? 'active' : ''} > {elem} см. </li> ); })} </ul> </div> <div className="pizza-block__bottom"> <div className="pizza-block__price">от {price} ₽</div> <div onClick={addToCart} className="button button--outline button--add" > <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M10.8 4.8H7.2V1.2C7.2 0.5373 6.6627 0 6 0C5.3373 0 4.8 0.5373 4.8 1.2V4.8H1.2C0.5373 4.8 0 5.3373 0 6C0 6.6627 0.5373 7.2 1.2 7.2H4.8V10.8C4.8 11.4627 5.3373 12 6 12C6.6627 12 7.2 11.4627 7.2 10.8V7.2H10.8C11.4627 7.2 12 6.6627 12 6C12 5.3373 11.4627 4.8 10.8 4.8Z" fill="white" /> </svg> <span>Добавить</span> <i>{cartItem ? total : 0}</i> </div> </div> </div> </div> ); }; export default PizzaBlock;
import Loader from './components/Loader' import { useState } from 'react' import Topbar from './components/Topbar' import Leftbar from './components/Leftbar' import Newsfeed from './components/Newsfeed' import EditMessage from './components/EditMessage' import RightBar from './components/Rightbar' function App() { const [isLoading, setIsLoading] = useState(true); const handleLoaderFinished = () => { setIsLoading(false); }; return ( <> {isLoading ? ( <Loader onLoaderFinished={handleLoaderFinished} /> ) : ( <> <Topbar/> <Leftbar/> <Newsfeed/> <EditMessage/> <RightBar/> </> )} </> ) } export default App
package com.example.fintrack import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.EditText import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.room.Room import com.google.android.material.floatingactionbutton.FloatingActionButton import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { private val db by lazy { Room.databaseBuilder( applicationContext, FinTrackDataBase::class.java, "database-FinTrack" ).build() } private val categoryDAO by lazy { db.getCategoryDAO() } private val expenseDAO by lazy { db.getExpenseDAO() } companion object { private const val REQUEST_COLOR_FROM_COLOR_SELECTOR_ACTIVITY = 1 private const val REQUEST_ICON_FROM_ICON_SELECTOR_ACTIVITY = 2 } private lateinit var expenseAdapter: ExpenseAdapter private lateinit var categoryAdapter: CategoryAdapter private lateinit var tvTotalSpent: TextView private val expenses = mutableListOf<Expense>() private val categories = mutableListOf<Category>() private var selectedCategory: String = "All" @Deprecated("Deprecated in Java") override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) Log.d("MainActivity", "onActivityResult called with requestCode: $requestCode, resultCode: $resultCode") if (resultCode == Activity.RESULT_OK && data != null) { when (requestCode) { REQUEST_COLOR_FROM_COLOR_SELECTOR_ACTIVITY -> { val selectedColor = data.getIntExtra("selectedColor", 0) val intentIcon = Intent(this, IconSelectorActivity::class.java) intentIcon.putExtra("selectedColor", selectedColor) startActivityForResult(intentIcon, REQUEST_ICON_FROM_ICON_SELECTOR_ACTIVITY) } REQUEST_ICON_FROM_ICON_SELECTOR_ACTIVITY -> { val selectedIcon = data.getIntExtra("selectedIcon", 0) val selectedColor = data.getIntExtra("selectedColor", 0) val expenseName = data.getStringExtra("expenseName") ?: "New Expense" val expenseValue = data.getDoubleExtra("expenseValue", 0.0) addExpense(expenseName, selectedIcon, selectedColor, expenseValue, selectedCategory) } } } } private fun addExpense(expenseName: String, iconResId: Int, colorResId: Int, expenseValue: Double, category: String) { val newExpense = Expense(name = expenseName, barColor = colorResId, icon = iconResId, value = expenseValue, category = category) GlobalScope.launch(Dispatchers.IO) { expenseDAO.insertAll(listOf(newExpense)) getExpensesFromDataBase(expenseAdapter) } expenseAdapter.submitList(ArrayList(expenses)) updateExpensesList() updateTotalSpent() expenseAdapter.notifyDataSetChanged() } @SuppressLint("NotifyDataSetChanged") private fun updateExpensesList() { val filteredExpenses = if (selectedCategory == "All") { expenses } else { expenses.filter { it.category == selectedCategory } } expenseAdapter.submitList(filteredExpenses) expenseAdapter.notifyDataSetChanged() } @SuppressLint("DefaultLocale") private fun updateTotalSpent() { val totalSpent = expenses.sumOf { it.value } tvTotalSpent.text = String.format("%.2f", totalSpent) } private fun filterExpensesByCategory(category: String) { selectedCategory = category updateExpensesList() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) insertDefaultCategory() insertDefaultExpense() tvTotalSpent = findViewById(R.id.tv_total_spent) val btnAdd: FloatingActionButton = findViewById(R.id.btn_add) btnAdd.setOnClickListener { startActivityForResult(Intent(this, ColorSelectorActivity::class.java), REQUEST_COLOR_FROM_COLOR_SELECTOR_ACTIVITY) } val btnAddCategory: FloatingActionButton = findViewById(R.id.btn_add2) btnAddCategory.setOnClickListener { showAddCategoryDialog() } val rvExpense = findViewById<RecyclerView>(R.id.rv_expense) expenseAdapter = ExpenseAdapter { expense -> showDeleteExpenseDialog(expense) } rvExpense.adapter = expenseAdapter getExpensesFromDataBase(expenseAdapter) rvExpense.layoutManager = LinearLayoutManager(this) val rvCategory = findViewById<RecyclerView>(R.id.rv_categories) categoryAdapter = CategoryAdapter( onCategorySelected = { category -> filterExpensesByCategory(category.name) categoryAdapter.selectCategory(category) }, onCategoryLongClicked = { category -> showDeleteCategoryDialog(category) } ) rvCategory.adapter = categoryAdapter getCategoriesFromDataBase(categoryAdapter) rvCategory.layoutManager = LinearLayoutManager(this).apply { orientation = LinearLayoutManager.HORIZONTAL } } private fun insertDefaultCategory(){ val categoriesEntity = categories.map { CategoryEntity( name = it.name ) } GlobalScope.launch(Dispatchers.IO) { categoryDAO.insertAll(categoriesEntity) updateTotalSpent() } } private fun insertDefaultExpense(){ val expensesEntity = expenses.map{ Expense( name = it.name, barColor = it.barColor, icon = it.icon, value = it.value, category = it.category ) } GlobalScope.launch(Dispatchers.IO) { expenseDAO.insertAll(expensesEntity) updateTotalSpent() } } private fun getExpensesFromDataBase(expenseListAdapter: ExpenseAdapter) { GlobalScope.launch(Dispatchers.IO) { val expensesFromDb = expenseDAO.getAll() val expensesUiData = expensesFromDb.map{ Expense( name = it.name, barColor = it.barColor, icon = it.icon, value = it.value, category = it.category ) } launch(Dispatchers.Main) { expenses.clear() expenses.addAll(expensesUiData) expenseListAdapter.submitList(ArrayList(expenses)) updateTotalSpent() } } } private fun getCategoriesFromDataBase(categoryListAdapter: CategoryAdapter) { GlobalScope.launch(Dispatchers.IO) { val categoriesFromDb = categoryDAO.getAll() val categoriesUiData = categoriesFromDb.map { Category( name = it.name ) } launch(Dispatchers.Main) { categories.clear() categories.addAll(categoriesUiData) categoryListAdapter.submitList(ArrayList(categories)) } } } @SuppressLint("NotifyDataSetChanged") private fun showAddCategoryDialog() { val dialogView = layoutInflater.inflate(R.layout.dialog_add_category, null) val etCategoryName = dialogView.findViewById<EditText>(R.id.et_category_name) AlertDialog.Builder(this) .setTitle("Adicionar Categoria") .setView(dialogView) .setPositiveButton("Adicionar") { dialog, which -> val categoryName = etCategoryName.text.toString() if (categoryName.isNotBlank()) { val newCategory = CategoryEntity(name = categoryName) GlobalScope.launch(Dispatchers.IO) { categoryDAO.insertAll(listOf(newCategory)) getCategoriesFromDataBase(categoryAdapter) // Atualiza a lista de categorias no adaptador } } } .setNegativeButton("Cancelar", null) .show() } private fun showDeleteExpenseDialog(expense: Expense) { AlertDialog.Builder(this) .setTitle("Delete Expense") .setMessage("Are you sure you want to delete this expense?") .setPositiveButton("Yes") { _, _ -> deleteExpense(expense) } .setNegativeButton("No", null) .show() } private fun deleteExpense(expense: Expense) { expenses.remove(expense) GlobalScope.launch(Dispatchers.IO) { expenseDAO.delete( Expense( name = expense.name, barColor = expense.barColor, icon = expense.icon, value = expense.value, category = expense.category) ) getExpensesFromDataBase(expenseAdapter) updateTotalSpent() //expenseAdapter.notifyDataSetChanged() } } private fun showDeleteCategoryDialog(category: Category) { AlertDialog.Builder(this) .setTitle("Delete category") .setMessage("Are you sure you want to delete this category?") .setPositiveButton("Yes") { _, _ -> deleteCategory(category) } .setNegativeButton("No", null) .show() } private fun deleteCategory(category: Category) { categories.remove(category) categoryAdapter.submitList(ArrayList(categories)) categoryAdapter.notifyDataSetChanged() GlobalScope.launch(Dispatchers.IO) { categoryDAO.delete(CategoryEntity(name = category.name)) } } }
import React, { lazy, Suspense } from 'react'; import { BrowserRouter, Route, Routes } from 'react-router-dom'; import BasePage from 'Layouts/BasePage'; import Loading from 'Components/Loading'; const Home = lazy(() => import('Pages/Home')); const About = lazy(() => import('Pages/About')); const DevelopmentPlan = lazy(() => import('Pages/DevelopmentPlan')); const FlowAssurance = lazy(() => import('Pages/FlowAssurance')); const HSE = lazy(() => import('Pages/HSE')); const PowerPlant = lazy(() => import('Pages/PowerPlant')); const App = () => { return ( <BrowserRouter> <BasePage> <Suspense fallback={<Loading />}> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/development-plan" element={<DevelopmentPlan />} /> <Route path="/flow-assurance" element={<FlowAssurance />} /> <Route path="/hse" element={<HSE />} /> <Route path="/power-plant" element={<PowerPlant />} /> </Routes> </Suspense> </BasePage> </BrowserRouter> ); }; export default App;
import React, { useState } from 'react'; const Contact = () => { const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [message, setMessage] = useState(''); const encode = (data) => { return Object.keys(data) .map( (key) => encodeURIComponent(key) + '=' + encodeURIComponent(data[key]) ) .join('&'); }; function handleSubmit(e) { e.preventDefault(); fetch('/', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: encode({ 'form-name': 'contact', name, email, message }), }) .then(() => alert('Message sent!')) .catch((error) => alert(error)); } const renderForm = () => { return ( <form data-netlify="true" name="contact" className="ui form" onSubmit={handleSubmit} > <div className="field"> <label htmlFor="name">Name</label> <input type="text" name="name" id="name" onChange={(e) => setName(e.target.value)} /> </div> <div className="field"> <label htmlFor="email">Email</label> <input type="email" name="email" id="email" onChange={(e) => setEmail(e.target.value)} /> </div> <div className="field"> <label htmlFor="message">Message</label> <textarea name="message" id="message" onChange={(e) => setMessage(e.target.value)} /> </div> <button type="submit" className="ui basic violet button"> Submit </button> </form> ); }; return ( <div id="contact"> <div class="ui divider"></div> <h1>Contact</h1> <div className="ui hidden divider"></div> {renderForm()} {console.log(name, email, message)} </div> ); }; export default Contact; <form netlify name="contact" className="lg:w-1/3 md:w-1/2 flex flex-col md:ml-auto w-full md:py-8 mt-8 md:mt-0" > <h2 className="text-white sm:text-4xl text-3xl mb-1 font-medium title-font"> Hire Me </h2> <p className="leading-relaxed mb-5"> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Illum suscipit officia aspernatur veritatis. Asperiores, aliquid? </p> <div className="relative mb-4"> <label htmlFor="name" className="leading-7 text-sm text-gray-400"> Name </label> <input type="text" id="name" name="name" className="w-full bg-gray-800 rounded border border-gray-700 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-900 text-base outline-none text-gray-100 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out" /> </div> <div className="relative mb-4"> <label htmlFor="email" className="leading-7 text-sm text-gray-400"> Email </label> <input type="email" id="email" name="email" className="w-full bg-gray-800 rounded border border-gray-700 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-900 text-base outline-none text-gray-100 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out" /> </div> <div className="relative mb-4"> <label htmlFor="message" className="leading-7 text-sm text-gray-400"> Message </label> <textarea id="message" name="message" className="w-full bg-gray-800 rounded border border-gray-700 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-900 h-32 text-base outline-none text-gray-100 py-1 px-3 resize-none leading-6 transition-colors duration-200 ease-in-out" /> </div> <button type="submit" className="text-white bg-indigo-500 border-0 py-2 px-6 focus:outline-none hover:bg-indigo-600 rounded text-lg" > Submit </button> </form>;
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { AdminComponent } from './admin/admin.component'; import { AuthComponent } from './auth/auth.component'; import { CourseFormComponent } from './course-form/course-form.component'; import { CoursesComponent } from './courses/courses.component'; import { AuthGuard } from './guard/auth.guard'; const routes: Routes = [ {path: 'auth', component: AuthComponent}, {path: 'admin', component: AdminComponent, canActivate: [AuthGuard]}, {path: 'courses', component: CoursesComponent}, {path: 'newCourse', component:CourseFormComponent}, {path: '', pathMatch: 'full', redirectTo: 'auth'} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
import { render } from 'preact'; import { App } from '../components/App'; import { RenamedOptionsWarning } from '../components/Warning'; import { evaluatePresetIconItemsToIcons } from '../lib/options'; import { getEditor } from '../lib/scrapbox'; import { Matcher, PresetIconsItem } from '../types'; type Options = { /** * ポップアップを開くキーかどうかを判定するコールバック。キーが押下される度に呼び出される。 * `true` ならポップアップを開くキーだと判定される。 * */ isLaunchIconSuggestionKey?: (e: KeyboardEvent) => boolean; /** * ポップアップを閉じるキーかどうかを判定するコールバック。キーが押下される度に呼び出される。 * `true` ならポップアップを閉じるキーだと判定される。 * */ isExitIconSuggestionKey?: (e: KeyboardEvent) => boolean; /** * クエリを `[query.icon]` として挿入するかどうかを判定するコールバック。キーが押下される度に呼び出される。 * */ isInsertQueryAsIconKey?: (e: KeyboardEvent) => boolean; /** @deprecated use `isLaunchIconSuggestionKey` */ isSuggestionOpenKeyDown?: (e: KeyboardEvent) => boolean; /** @deprecated use `isExitIconSuggestionKey` */ isSuggestionCloseKeyDown?: (e: KeyboardEvent) => boolean; /** @deprecated use `isInsertQueryAsIconKey` */ isInsertQueryKeyDown?: (e: KeyboardEvent) => boolean; /** @deprecated use `defaultIsShownPresetIcons` */ defaultSuggestPresetIcons?: boolean; /** suggest に含めたいプリセットアイコンのリスト */ presetIcons?: PresetIconsItem[]; /** * ポップアップを開いた直後にプリセットアイコンを候補として表示するか。 * `true` なら表示、`false` なら非表示。 * @default true * */ defaultIsShownPresetIcons?: boolean; /** * suggest されたアイコンを絞り込むために利用される matcher。 */ matcher?: Matcher; scrapbox?: Scrapbox; editor?: HTMLElement; }; export async function registerIconSuggestion(options?: Options) { // 直接 editor に mount すると scrapbox 側の react renderer と干渉して壊れるので、 // editor 内に差し込んだ container に mount する const container = document.createElement('div'); const editor = options?.editor ?? getEditor(); editor.appendChild(container); const warningMessageContainer = document.createElement('div'); document.querySelector('.app')?.prepend(warningMessageContainer); if ( options?.isSuggestionOpenKeyDown !== undefined || options?.isSuggestionCloseKeyDown !== undefined || options?.isInsertQueryKeyDown !== undefined || options?.defaultSuggestPresetIcons !== undefined ) { render(<RenamedOptionsWarning />, warningMessageContainer); return; } const presetIcons = options?.presetIcons ? await evaluatePresetIconItemsToIcons(options.presetIcons) : undefined; render( <App isLaunchIconSuggestionKey={options?.isLaunchIconSuggestionKey} isExitIconSuggestionKey={options?.isExitIconSuggestionKey} isInsertQueryAsIconKey={options?.isInsertQueryAsIconKey} presetIcons={presetIcons} defaultIsShownPresetIcons={options?.defaultIsShownPresetIcons} matcher={options?.matcher} />, container, ); }
import matplotlib.pyplot as plt import cv2 import os import numpy as np import tifffile as tiff import json import torch import shutil from torchvision import transforms def plot_data(image_names, annotations): """ Plots images with bounding boxes based on provided annotations. Parameters: - image_names (list): List of image file paths. - annotations (dict): Annotations data in COCO format. """ fig , ax = plt.subplots(1,2,figsize = (10,10)) for i, img_name in enumerate(image_names): # We can use cv2 to read the image image = cv2.imread(img_name) # Get the img file name to be able to find the corresponding data img_file_name = os.path.basename(img_name) # Get the image id from the data img_id = [item for item in annotations["images"] if item["file_name"] == img_file_name][0]["id"] # Get the boxes corresponding to the image boxes = [item for item in annotations["annotations"] if item["image_id"] == img_id] for box in boxes: points = np.array(box["segmentation"]).reshape((-1, 1, 2)).astype(np.int32) # Draw the bounding box cv2.polylines(image, [points], isClosed=True, color=(0, 0, 255), thickness=2) ax[i].imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) plt.show() def create_mask(json_file, mask_output_folder, image_output_folder, original_image_dir): """ Creates masks for images based on annotations and saves them to specified folders. Parameters: - json_file (str): Path to the JSON file containing annotations. - mask_output_folder (str): Path to the folder where masks will be saved. - image_output_folder (str): Path to the folder where images will be saved. - original_image_dir (str): Path to the folder containing original images. """ with open(json_file) as f: data = json.load(f) images = data["images"] annotations = data["annotations"] if not os.path.exists(mask_output_folder): os.makedirs(mask_output_folder) if not os.path.exists(image_output_folder): os.makedirs(image_output_folder) for img in images: mask_np = np.zeros((img["height"], img["width"]), dtype=np.uint8) for annotation in annotations: if(annotation["image_id"] == img["id"]): for segment in annotation["segmentation"]: points = np.array(segment).reshape((-1, 1, 2)).astype(np.int32) cv2.fillPoly(mask_np, [points], 255) mask_path = os.path.join(mask_output_folder, img["file_name"].replace(".png", ".jpg")) tiff.imsave(mask_path, mask_np) original_image_path = os.path.join(original_image_dir, img['file_name']) new_image_path = os.path.join(image_output_folder, os.path.basename(original_image_path)) shutil.copy(original_image_path, new_image_path) def plot_mask(mask_dir, image_dir): """ Plots masks alongside original images. Parameters: - mask_dir (str): Path to the folder containing masks. - image_dir (str): Path to the folder containing original images. """ mask_files = os.listdir(mask_dir) image_files = os.listdir(image_dir) for i, mask_file in enumerate(mask_files): mask_path = os.path.join(mask_dir, mask_file) image_path = os.path.join(image_dir, image_files[i]) mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE) image = cv2.imread(image_path) mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) fig, ax = plt.subplots(1, 2, figsize=(10, 10)) ax[0].imshow(mask) ax[1].imshow(image) plt.show() break def compare_folders(folder1, folder2): """ Compares files in two folders and removes any files not present in both. Parameters: - folder1 (str): Path to the first folder. - folder2 (str): Path to the second folder. """ files1 = os.listdir(folder1) files2 = os.listdir(folder2) files_only_in_folder1 = set(files1) - set(files2) for file_name in files_only_in_folder1: file_path = os.path.join(folder1, file_name) os.remove(file_path) print(f"Deleted file: {file_path}") files_only_in_folder2 = set(files2) - set(files1) for file_name in files_only_in_folder2: file_path = os.path.join(folder2, file_name) os.remove(file_path) print(f"Deleted file: {file_path}") def visualize_model_output(test_loader, device, model): """ Visualizes model predictions on test dataset. Parameters: - test_loader (DataLoader): DataLoader for the test dataset. - device (str): Device to run the model on (e.g., 'cpu', 'cuda'). - model (torch.nn.Module): Trained model. """ batch_count = 0 with torch.no_grad(): for images, masks in test_loader: images = images.to(device) masks = masks.to(device) predicted_masks = model(images) images_np = images.cpu().numpy() masks_np = masks.cpu().numpy() predicted_masks_np = predicted_masks.cpu().numpy() for i in range(images_np.shape[0]): plt.figure(figsize=(18, 6)) plt.subplot(1, 3, 1) plt.imshow(transforms.ToPILImage()(images_np[i].transpose(1, 2, 0)), cmap='gray') plt.title('Original Image') plt.axis('off') plt.subplot(1, 3, 2) plt.imshow(masks_np[i][0], cmap='gray') plt.title('True Mask') plt.axis('off') plt.subplot(1, 3, 3) plt.imshow(masks_np[i][0], cmap='gray') plt.imshow(predicted_masks_np[i][0], alpha=0.5, cmap='gray', interpolation='none') plt.title('Predicted Mask Overlay') plt.axis('off') batch_count += 1 if batch_count == 2: break
import thunk from 'redux-thunk' import configureMockStore from 'redux-mock-store' import axios from 'axios' import { ACTION_TYPES as GENERAL_ACTION_TYPES } from '../../general/actions' import * as actions from '../actions' import { ACTION_TYPES } from '../constants' const middleware = [thunk] const mockStore = configureMockStore(middleware) describe('PersonalInfo action creators', () => { describe('sync actions', () => { it('should create `setPersonalInfo` action', () => { const personalInfo = { test: 'data' } const action = actions.setPersonalInfo(personalInfo) expect(action).toEqual({ type: ACTION_TYPES.SET_INFO, payload: personalInfo, }) }) it('should create `updatePersonalInfo` action', () => { const personalInfo = { test: 'data' } const merge = false const action = actions.updatePersonalInfo(personalInfo, merge) expect(action).toEqual({ type: ACTION_TYPES.UPDATE_INFO, payload: { personalInfo, merge }, }) }) it('should create `setCurrentFiling` action', () => { const filing = { test: 'data' } const merge = false const action = actions.setCurrentFiling(filing, merge) expect(action).toEqual({ type: ACTION_TYPES.SET_CURRENT_FILING, payload: { filing, merge }, }) }) it('should create `clearCurrentFiling` action', () => { const action = actions.clearCurrentFiling() expect(action).toEqual({ type: ACTION_TYPES.CLEAR_CURRENT_FILING, }) }) it('should create `deleteFiling` action', () => { const filingId = 'testing-filing-id' const action = actions.deleteFiling(filingId) expect(action).toEqual({ type: ACTION_TYPES.DELETE_FILING, payload: filingId, }) }) }) describe('async actions', () => { it('should handle `setCurrentFilingById` action without localFilings', async () => { const store = mockStore({ personalInfo: { localFilings: [], }, }) const filingId = 'testing-filing-id' const filing = { id: filingId, } const merge = false axios.get.mockResolvedValueOnce({ data: filing }) await store.dispatch(actions.setCurrentFilingById(filingId, merge)) expect(store.getActions()).toEqual([ { type: GENERAL_ACTION_TYPES.ADD_LOADING_COUNT }, { type: GENERAL_ACTION_TYPES.REMOVE_LOADING_COUNT }, { type: ACTION_TYPES.SET_CURRENT_FILING, payload: { filing, merge } }, ]) expect(axios.get).toHaveBeenCalled() }) it('should handle `setCurrentFilingById` action with localFilings', async () => { const filingId = 'testing-filing-id' const filing = { id: filingId, } const store = mockStore({ personalInfo: { localFilings: [filing], }, }) const merge = false await store.dispatch(actions.setCurrentFilingById(filingId, merge)) expect(store.getActions()).toEqual([ { type: ACTION_TYPES.SET_CURRENT_FILING, payload: { filing, merge } }, ]) expect(axios.get).not.toHaveBeenCalled() }) it('should handle `setCurrentFilingById` action with localFilings and `forceFetch`', async () => { const filingId = 'testing-filing-id' const filing = { id: filingId, } const store = mockStore({ personalInfo: { localFilings: [filing], }, }) const merge = false axios.get.mockResolvedValueOnce({ data: filing }) await store.dispatch(actions.setCurrentFilingById(filingId, merge, true)) expect(store.getActions()).toEqual([ { type: GENERAL_ACTION_TYPES.ADD_LOADING_COUNT }, { type: GENERAL_ACTION_TYPES.REMOVE_LOADING_COUNT }, { type: ACTION_TYPES.SET_CURRENT_FILING, payload: { filing, merge } }, ]) expect(axios.get).toHaveBeenCalled() }) it('should handle `fetchPersonalInfo` action', async () => { const store = mockStore({ personalInfo: { id: 'testing-id', changingValue: 'initial', }, }) axios.get.mockResolvedValueOnce({ data: { changingValue: 'updated' } }) await store.dispatch(actions.fetchPersonalInfo()) expect(store.getActions()).toEqual([ { type: GENERAL_ACTION_TYPES.ADD_LOADING_COUNT }, { type: ACTION_TYPES.UPDATE_INFO, payload: { merge: true, personalInfo: { changingValue: 'updated', }, }, }, { type: GENERAL_ACTION_TYPES.REMOVE_LOADING_COUNT }, ]) expect(axios.get).toHaveBeenCalled() }) }) })
import React, { Component } from 'react'; import { Text, StyleSheet, View, SafeAreaView, Dimensions, Animated, } from 'react-native'; import { red, blue, white } from '../assets/colors'; const { height, width } = Dimensions.get('window'); export default class Historique extends Component { constructor(props) { super(props); this.state = { showItem: new Animated.Value(1), }; } shouldComponentUpdate(nextProps, nextState) { const { index } = this.props; if (index == nextProps.index) { return false; } else { return true; } } componentDidMount() { this._animateItem(); } _animateItem() { this.state.showItem.setValue(0.01); Animated.spring(this.state.showItem, { toValue: 1, tension: 10, friction: 5, useNativeDriver: false, }).start(); } render() { const { name, action, hours, minutes, index } = this.props; const animItemTransform = { transform: [{ scale: this.state.showItem }], }; let displayedName = name; if (name != null) { displayedName = displayedName + ' '; } return ( <Animated.View style={[styles.containerItem, animItemTransform]}> <View style={styles.containerText}> <View style={styles.containerDesc}> <Text style={styles.text}> {displayedName}{action} </Text> </View> <View style={styles.containerHours}> <Text style={styles.textHours}> {' '} {hours} : {minutes}{' '} </Text> </View> </View> </Animated.View> ); } } let fontSize; if (height > 800) { fontSize = height / 60; } else { fontSize = height / 50; } const styles = StyleSheet.create({ containerItem: { flex: 1, backgroundColor: blue, borderRadius: 15, width: width - 50, alignSelf: 'center', marginVertical: 3, marginHorizontal: 15, elevation: 5, }, containerText: { flexDirection: 'row', alignItems: 'center', marginVertical: 7, }, containerDesc: { flex: 1, marginLeft: 10, }, containerHours: { marginRight: 5, }, text: { fontFamily: 'montserrat-regular', fontSize: fontSize, color: white, marginRight: 5, }, textHours: { fontFamily: 'montserrat-bold', fontSize: fontSize, color: red, }, });
import { _decorator, assetManager, AssetManager, Component, error, instantiate, Label, Prefab, ProgressBar, resources, warn } from 'cc'; import SceneMgr, { SceneCfg } from './SceneMgr'; import { ResConfig } from '../../data'; import { ResourcesMgr } from '../module/mgr/ResourcesMgr'; import { PoolUnit } from '../module/pool/PoolUnit'; import { NodePoolMgr } from '../module/pool/NodePoolMgr'; const { ccclass, property } = _decorator; @ccclass('LoadingScene') export class LoadingScene extends Component { @property({ type: ProgressBar, tooltip: "进度条" }) progress: ProgressBar = null; @property({ type: Label, tooltip: "进度条进度" }) progressLbl: Label = null; onLoad() { this._loadSceneAssets(); } async _loadSceneAssets() { let sceneName = SceneMgr.instance.getNextSceneName(); let assetsList = SceneCfg[sceneName]; let totalCount = await this._getTotalAssetsNum(assetsList); let loadIndex: number = 0; //加载进度条 for (let i = 0; i < assetsList.length; i++) { const element = assetsList[i]; if (element.isfloderPath) { //加载资源 let files = await ResourcesMgr.instance.getFloderByBundle(element.path, element.type); for (let j = 0; j < files.length; j++) { const filsData = files[j]; ResourcesMgr.instance.loadFile(filsData.path, element.type, (error, data) => { this._putPrefabToPool(element, data); loadIndex++; this.updateProgress(loadIndex, totalCount); }) } } else { ResourcesMgr.instance.loadFile(element.path, element.type, (error, data) => { if (element.isPool && element.type !== Prefab) { warn("%s", element.path, element.type, "节点池配置错误暂不支持除perfab之外的类型"); return } this._putPrefabToPool(element, data); loadIndex++; this.updateProgress(loadIndex, totalCount); }); } } } _putPrefabToPool(element, itemNode: Prefab) { if (element.isPool) { if (element.type !== Prefab) { warn("%s", element.path, element.type, "节点池配置错误暂不支持除perfab之外的类型"); return } let prefabNode = instantiate(itemNode); let poolUnit: PoolUnit = prefabNode.getComponent(PoolUnit); if (!poolUnit) { warn("%s", itemNode.name, "未挂载poolUnit组件,无法由节点池管理器创建"); return } let registerNum = poolUnit.num; let poolName = poolUnit.getPoolName(); for (let i = 0; i < registerNum; i++) NodePoolMgr.instance.putNodeToPool(prefabNode); } } //获取预加载的总文件数量 async _getTotalAssetsNum(assetsList: Array<ResConfig>) { let totalFilesCount = 0; for (let i = 0; i < assetsList.length; i++) { const element = assetsList[i]; if (element.isfloderPath) { //目录 let files = await ResourcesMgr.instance.getFloderByBundle(element.path, element.type); totalFilesCount += (files.length || 0); } else { totalFilesCount += 1; } } return totalFilesCount; } updateProgress(loadIndex, totalCount) { this.progressLbl.string = `${loadIndex}/${totalCount}`; this.progress.progress = loadIndex / totalCount; if (loadIndex >= totalCount) { SceneMgr.instance.loadScene(); } } }
# dotfiles <!-- omit from toc --> - [Instalación](#instalación) - [Común](#común) - [MacOS](#macos) - [Dependencias](#dependencias) - [Symlinks](#symlinks) - [Linux](#linux) - [Dependencias](#dependencias-1) - [Symlinks](#symlinks-1) - [Vim](#vim) Custom dot files ## Instalación ```console git clone git@github.com:sdelquin/dotfiles.git ~/.dotfiles ``` ## Común ### Dependencias <!-- omit from toc --> ```console pyenv pip install flake8 mypy black ``` ### Symlinks <!-- omit from toc --> ```console ln -s ~/.dotfiles/common/gitconfig .gitconfig ln -s ~/.dotfiles/common/flake8 .flake8 ln -s ~/.dotfiles/common/mypy.ini .mypy.ini ln -s ~/.dotfiles/common/black .config/black ``` ## MacOS ### Dependencias ```console brew install lsd bat ripgrep delta zoxide ``` ### Symlinks ```console ln -s ~/.dotfiles/macos/vimrc .vimrc ``` Añadir al final del fichero `~/.zshrc`: ```bash export DOTFILES=$HOME/.dotfiles source $DOTFILES/macos/zshrc.zsh ``` ## Linux ### Dependencias ```console curl -LO https://github.com/Peltoche/lsd/releases/download/0.23.1/lsd-musl_0.23.1_amd64.deb sudo dpkg -i lsd-musl_0.23.1_amd64.deb curl -LO https://github.com/sharkdp/bat/releases/download/v0.22.1/bat-musl_0.22.1_amd64.deb sudo dpkg -i bat-musl_0.22.1_amd64.deb curl -LO https://github.com/BurntSushi/ripgrep/releases/download/13.0.0/ripgrep_13.0.0_amd64.deb sudo dpkg -i ripgrep_13.0.0_amd64.deb curl -LO https://github.com/dandavison/delta/releases/download/0.15.1/git-delta-musl_0.15.1_amd64.deb sudo dpkg -i git-delta-musl_0.15.1_amd64.deb curl -sS https://raw.githubusercontent.com/ajeetdsouza/zoxide/main/install.sh | bash ``` Para usar la función `copy()` necesitamos instalar la [Shell Integration de iTerm2](https://iterm2.com/documentation-utilities.html). En otro caso se puede usar la función `xcopy()` que hace uso de `xclip`. ```console sudo apt install -y xclip fonts-noto-color-emoji ``` > 💡 Para que funcione `xclip` necesitamos disponer de un servidor X ### Symlinks ```console ln -s ~/.dotfiles/linux/vimrc .vimrc ``` Añadir al final del fichero `~/.bashrc`: ```bash export DOTFILES=$HOME/.dotfiles source $DOTFILES/linux/bashrc ``` ## Vim Instalar el gestor de paquetes **vim plug**: ```console curl -fLo ~/.vim/autoload/plug.vim --create-dirs \ https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim ``` Instalar los plugins: ```console vi +'PlugInstall --sync' +qa ``` ### Sólo para Linux <!-- omit from toc --> Habilitar `sudo` para que utilice las mismas configuraciones `vim`: ```console sudo -- sh -c "ln -sf $HOME/.vimrc /root/.vimrc; ln -sf $HOME/.vim /root/.vim" ```
import { groupByKey, toTitleCase } from "@/lib/utils"; import { JobApplication, JobApplicationTodo } from "@/types"; import { useState } from "react"; import { api } from "@/api/backend"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { Label } from "@/components/ui/label"; import { Tabs, TabsContent, TabsList, TabsTrigger, } from "@/components/ui/tabs"; import { useMutation, useQueryClient } from "@tanstack/react-query"; import { toast } from "sonner"; import TodoForm from "./TodoForm"; export default function JobApplicationTodoManager({ todos: passedTodos, applicationId, }: { todos: string; applicationId: string; }) { const queryClient = useQueryClient(); const { mutateAsync: editJobApplication } = useMutation({ mutationFn: api.applications.editJobApplication, onSuccess: (editedApplication: JobApplication) => { queryClient.setQueryData( ["jobApplications"], (oldData: JobApplication[]) => { return oldData.map((ja) => { if (ja.id === editedApplication.id) { return editedApplication; } return ja; }); } ); toast.success("Todos saved"); }, onError: (error: any) => { toast.error("Failed to save todos" + error.response.data.error); }, }); let parsedTodos: JobApplicationTodo[] = []; if (passedTodos.length > 0) { parsedTodos = JSON.parse(passedTodos); } const [todos, setTodos] = useState<JobApplicationTodo[]>(parsedTodos); const addTodo = (todo: JobApplicationTodo) => { setTodos([...todos, todo]); }; function handleSaveTodos() { editJobApplication({ application: { todos: JSON.stringify(todos), }, applicationId, type: "todosChange", }); } function handleChange(todo: JobApplicationTodo, checked: boolean) { const updatedTodos = todos.map((t) => { if (t.id === todo.id) { return { ...t, isCompleted: checked, }; } return t; }); setTodos(updatedTodos); } const groupedByStatus = groupByKey(todos, "relatedTo"); const keys = Object.keys(groupedByStatus); console.log("groupedByStatus", groupedByStatus); return ( <div> <div> <Tabs defaultValue={keys[0]} className=""> <TabsList className="flex gap-2 justify-start"> {keys.map((key) => { return ( <TabsTrigger key={key} value={key}> {toTitleCase(key)} </TabsTrigger> ); })} </TabsList> {keys.map((key) => { return ( <TabsContent key={key} value={key} className="px-2"> {groupedByStatus[key].map( (todo: JobApplicationTodo) => { return ( <div key={todo.id} className="flex gap-1 items-center mb-1 " > <Checkbox className="h-5 w-5" id={todo.id} checked={todo.isCompleted} onCheckedChange={(checked) => handleChange(todo, checked as boolean) } /> <Label htmlFor={todo.id} className="text-sm"> {todo.text} </Label> </div> ); } )} </TabsContent> ); })} </Tabs> <TodoForm addTodo={addTodo} /> <Button className="mt-2" onClick={handleSaveTodos} size={"sm"} > Save Todos </Button> </div> </div> ); }
import { supportRAF } from "./caniuse"; /** * Creates a debounced function. */ export function debounce<T extends (...args: any[]) => any>(fn: T, delay: number) { const isNextTick = (delay === 0 && supportRAF()); let timer: number; let invokeArgs: any[] | undefined; let invokeThis: any | undefined; function invoke() { const args = invokeArgs ?? []; const thisArg = invokeThis; invokeArgs = undefined; invokeThis = undefined; fn.apply(thisArg, args); } return function debounced(this: any, ...args: Parameters<T>) { invokeArgs = args; invokeThis = this; if (isNextTick) { window.cancelAnimationFrame(timer); timer = window.requestAnimationFrame(invoke); } else { window.clearTimeout(timer); timer = window.setTimeout(invoke, delay); } }; }
# Циклически генерирует последовательность значений 0-9, # по достижении 9 снова начинается генерация последовательности 0-9 и т.д. # т.е. получается генератор бесконечной последовательности. # аналог itertools.cycle('0123456789') def chargen(): # i = 0 # добавил для наглядности при генерации спискового выражения while True: for c in '0123456789': # print(i, c) # добавил для наглядности при генерации спискового выражения yield c # i += 1 # добавил для наглядности при генерации спискового выражения # списковое выражение [c + c for c in chargen()] никогда не будет завершено коррректно, т.к. бесконечный генератор. # words = [c + c for c in chargen()][:10] # print(words) # Можно использовать генератор для 10 значений def chargen_n1(): for c in '0123456789': yield c words1 = [c + c for c in chargen_n1()] print(words1) # или же взять бесконечный генератор за основу и использовать только n раз def chargen_n2(n): c = chargen() for _ in range(n): ret = next(c) yield ret words2 = [c + c for c in chargen_n2(20)] print(words2)
require('dotenv').config(); const express = require('express'); const app = express(); const {sequelize} = require('./config/db_connect'); const JwtStrategy = require("passport-jwt").Strategy; const { cookieExtractor } = require('./middlewares/isAuth'); const PORT = process.env.PORT; const cookieParser = require('cookie-parser'); const passport = require('passport'); const userModel = require('./models/userModel'); const opts = { jwtFromRequest:cookieExtractor, secretOrKey:process.env.SECRET_KEY } passport.use(new JwtStrategy(opts, async (jwt_payload, done) => { const user = await userModel.findOne({where : {id : jwt_payload.id}}) if(!user) return done(null,false) return done(null,user) })) app.get('/', (req, res) => { res.send('HOME'); }) app.use(express.json()) app.use(cookieParser()); app.use("/user", require("./routes/userRoute")); app.use("/post", require("./routes/postRoute")); app.use("/comment", require("./routes/commentRoute")); app.get('/*', (req, res) => { res.json({ message : 'Bad Request', error : 'YOU MADE MISTAKE IN PATH OF URL' }) }) sequelize.authenticate().then(() => { console.log('DB CONNECTED!'); app.listen(PORT, () => { console.log(`SERVER STARTED ON PORT ${PORT}`); }) })
package com.microservice.authservice.models.controller; import com.microservice.authservice.models.dao.IConectividadDAO; import com.microservice.authservice.models.dao.IPersonaDAO; import com.microservice.authservice.models.dao.IRolDAO; import com.microservice.authservice.models.dao.IUserDAO; import com.microservice.authservice.models.dto.ConectividadDTO; import com.microservice.authservice.models.dto.TokenDTO; import com.microservice.authservice.models.dto.UsuarioDTO; import com.microservice.authservice.models.entity.Persona; import com.microservice.authservice.models.entity.Rol; import com.microservice.authservice.models.entity.Usuario; import com.microservice.authservice.models.errors.ResourceNotFoundException; import com.microservice.authservice.models.service.AuthUserService; import com.microservice.authservice.models.service.ConectividadService; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.*; import java.util.Collections; import java.util.List; @RestController @RequestMapping("/auth") public class AuthUserController { private static JSONObject json = null; @Autowired private AuthUserService authUserService; @Autowired private IConectividadDAO conectividadDAO; ConectividadService conectividadService; IRolDAO rolDAO; IUserDAO userDAO; IPersonaDAO personaDao; PasswordEncoder passwordEncoder; @GetMapping("/conectividad") public ResponseEntity<?> listadoConectividad(){ List<ConectividadDTO> listaDeRol= conectividadService.obtenerListar(); return ResponseEntity.ok(listaDeRol); } @GetMapping("/conectividad/{id}") public ResponseEntity<?> listadoConectividadUno(@PathVariable(name = "id") long id){ return ResponseEntity.ok(conectividadDAO.findById(id)); } @PostMapping("/login") public ResponseEntity<TokenDTO> login(@RequestBody UsuarioDTO usuarioDTO){ TokenDTO tokenDTO= authUserService.login(usuarioDTO); if(tokenDTO==null) return ResponseEntity.badRequest().build(); return ResponseEntity.ok(tokenDTO); } @PostMapping("/validate") public ResponseEntity<TokenDTO> validate(@RequestBody String token){ TokenDTO tokenDTO= authUserService.validate(token); if(tokenDTO==null) return ResponseEntity.badRequest().build(); return ResponseEntity.ok(tokenDTO); } @PostMapping("/create") public ResponseEntity<?> create(@RequestBody UsuarioDTO usuarioDTO){ System.out.println("LLEGO A a la primera parte del crear"); /* if(userDAO.existsByUsername(usuarioDTO.getUsername())) { return new ResponseEntity<>("Ese nombre de usuario ya existe", HttpStatus.BAD_REQUEST); } System.out.println("LLEGO A a la segunda parte del crear"); Usuario usuario = new Usuario(); usuario.setIdUser(usuarioDTO.getIdUser()); usuario.setUsername(usuarioDTO.getUsername()); usuario.setEstado(usuarioDTO.getEstado()); usuario.setPassword(passwordEncoder.encode(usuarioDTO.getPassword())); System.out.println("LLEGO A a la tercera parte del crear"); Rol roles = rolDAO.findById(usuarioDTO.getIdRol()).get(); usuario.setRol(Collections.singleton(roles)); Persona persona= personaDao. findById(usuarioDTO.getIdPersona()).orElseThrow(()->new ResourceNotFoundException("Persona", "id", usuarioDTO.getIdPersona())); usuario.setPersona(persona); System.out.println("LLEGO A a la cuarta parte del crear"); userDAO.save(usuario); json = new JSONObject(); return new ResponseEntity<>(json.put("message", "se Registro exitosamente!!!").toString(), HttpStatus.OK); */ return new ResponseEntity<>(authUserService.save(usuarioDTO), HttpStatus.CREATED); } }
#include "DifferentialDriveRobot.h" #include "MobileRobot.h" #include "OmnidirectionalDriveRobot.h" #include "Robot.h" #include "Wheel.h" using namespace std; const int ROBOT_TYPE_DIFF = 1; const int ROBOT_TYPE_OMNI = 2; ofstream myFile; // for filewrite int main(void) { int type; double radius; double wheelDist; double lVel, rVel; double lrDist, fbDist; double flVel, frVel, blVel, brVel; myFile.open("result.txt"); // for filewrite /*TODO: create a MobileRobot-typed object pointer named robot*/ // // MobileRobot bot(); // CHECK // Robot *robot; MobileRobot* robot; cin >> type; switch (type) { case ROBOT_TYPE_DIFF: { // receive the values of wheel radius and distances cin >> radius >> wheelDist; /*TODO: make the object pointer robot point to a new object of DifferentialDriveRobot*/ //DifferentialDriveRobot diffRobot = DifferentialDriveRobot("2",2,2); // diffRobot = DifferentialDriveRobot(); // DifferentialDriveRobot robot = new DifferentialDriveRobot("DifferentialDrive",radius, wheelDist); // receive the values of wheel velocities cin >> lVel >> rVel; /*TODO: downcast the pointer type of robot to DifferentialDriveRobot * and assign the result to a DifferentialDriveRobot-typed object pointer named diff*/ DifferentialDriveRobot* diff = dynamic_cast<DifferentialDriveRobot*>(robot); // set the wheel velocities if (diff) { diff->setLeftWheelVelocity(lVel); diff->setRightWheelVelocity(rVel); } else { cout << "Bad Diff Robot, check config" << endl; } // print information robot->print(); break; } case ROBOT_TYPE_OMNI: { // receive the values of wheel radius and distances cin >> radius >> lrDist >> fbDist; /*TODO: make the object pointer robot point to a new object of OmnidirectionalDriveRobot*/ robot = new OmnidirectionalDriveRobot("Omnidirectional Drive", "robot", radius, lrDist, fbDist); // receive the values of wheel velocities cin >> flVel >> frVel >> blVel >> brVel; /*TODO: downcast the pointer type of robot to OmnidirectionalDriveRobot * and assign the result to an OmnidirectionalDriveRobot-typed object pointer named omni*/ OmnidirectionalDriveRobot* omni = dynamic_cast<OmnidirectionalDriveRobot*>(robot); // set the wheel velocities if (omni) { omni->setFrontLeftWheelVelocity(flVel); omni->setFrontRightWheelVelocity(frVel); omni->setBackLeftWheelVelocity(blVel); omni->setBackRightWheelVelocity(brVel); } else { cout << "Bad Omni Robot, check config" << endl; } // print information robot->print(); break; } default: cout << "Incorrect robot type" << endl; break; } delete robot; // deallocate dynamic memory allocated to the object return 0; }
import { useEffect, useState } from 'react'; import fetchJsonp from 'fetch-jsonp'; import { Song } from '../types'; import { hasAlreadyRated } from '../actions/hasAlreadyRated'; const useRandomSong = (): [Song | null, () => void] => { const [song, setSong] = useState<Song | null>(null); useEffect(() => { const checkIfUserRated = async (id: number): Promise<boolean> => { if (await hasAlreadyRated(id.toString())) { console.log('--- Provided ID already rated, trying again...'); return true; } else { console.log('--- Provided ID is correct'); return false; } }; const generateSongData = async (id: number) => { const response = await fetchJsonp( `https://api.deezer.com/track/${id}&output=jsonp` ); return await response.json(); }; const fetchRandomSong = async () => { if (song !== null) return; const id = Math.floor(Math.random() * 10000000); const data = await generateSongData(id); console.log(`--- Got API data`); if (data.error || data.preview === '') { console.log('--- Data is invalid, trying again...'); fetchRandomSong(); return; } if (await checkIfUserRated(id)) { fetchRandomSong(); return; } console.log(`--- Found valid id: ${id}`); console.log('--------------------------'); setSong(data); }; if (song === null) { fetchRandomSong(); } }, [song]); const newSong = () => { setSong(null); }; return [song, newSong]; }; export default useRandomSong;
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { NgForm , FormsModule, NgModel } from '@angular/forms'; import { HttpClient, HttpClientModule } from '@angular/common/http'; import { RouterModule } from '@angular/router'; import { DashboardComponent } from './dashboard/dashboard.component'; import { UserComponent } from './user/user.component'; import { PerfectScrollbarModule, PERFECT_SCROLLBAR_CONFIG, PerfectScrollbarConfigInterface } from 'ngx-perfect-scrollbar'; import { CommonModule } from '@angular/common'; import { ViewAllTaskComponent } from './dashboard/view-all-task/view-all-task.component'; import { ProfileComponent } from './dashboard/profile/profile.component'; import { AddTaskComponent } from './dashboard/add-task/add-task.component'; const P_SCROLLBAR_CONFIG: PerfectScrollbarConfigInterface = { suppressScrollX: true }; @NgModule({ declarations: [ AppComponent, UserComponent, DashboardComponent, ViewAllTaskComponent, ProfileComponent, AddTaskComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, HttpClientModule, FormsModule, RouterModule.forRoot([ {path: 'user/dashBoard', component: DashboardComponent}, {path: 'user', component: UserComponent}, {path: '', redirectTo: '/user', pathMatch: 'full'}, //{path: '**' ,component: PageNotFound} ]), PerfectScrollbarModule, CommonModule ], providers: [{provide:PERFECT_SCROLLBAR_CONFIG,useValue: P_SCROLLBAR_CONFIG}], bootstrap: [AppComponent] }) export class AppModule { } //#Ab1sh12345
package com.jonathanmojica.examenandroid.utils class Resource<out T>(val status: Status, val data: T?, val message: String?) { companion object { fun <T> success(data: T?): Resource<T> { return Resource(Status.SUCCESS, data, null) } fun <T> error(message: String?, data: T?): Resource<T> { return Resource(Status.ERROR, data, message) } fun <T> loading(data: T?): Resource<T> { return Resource(Status.LOADING, data, null) } fun <T> stopLoader(data: T?) : Resource<T> { return Resource(Status.STOP, data, null) } fun <T> throwError(message: String?, data: T?) : Resource<T> { return Resource(Status.THROW, data, message) } fun <T> setReset(data : T?) : Resource<T> { return Resource(Status.RESET, data, null) } } }
import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Map; public class Account { private static final double MIN_BALANCE = 100; private static final double CHARGE_AMOUNT = 10; private Account account; private String accountNumber; private double balance; private List<String> transactions; private String accountHolderName; // New field for the account holder's name private String transactionId; private static int counter = 001; public Account(String accountNumber, double initialBalance, String accountHolderName) { this.accountNumber = accountNumber; this.balance = initialBalance; this.accountHolderName = accountHolderName; // Initialize the account holder's name this.transactions = new ArrayList<>(); } public String getAccountNumber() { return accountNumber; } public double getBalance() { return balance; } public String getAccountHolderName() { return accountHolderName; } public List<String> getTransactions() { return transactions; } public void deposit(double amount) { balance += amount; transactions.add("Deposit: +" + amount); } public void withdraw(double amount) { if (balance - amount >= MIN_BALANCE) { balance -= amount; transactions.add("Withdrawal: -" + amount); } else { if (amount > MIN_BALANCE) System.out.println("Insufficient fund"); else { transactions.add("Failed Withdrawal: Insufficient funds. A charge of $" + CHARGE_AMOUNT + " has been applied."); balance -= CHARGE_AMOUNT; // Apply charge for going below the minimum balance } } } public String generateTransactionId() { this.transactionId = this.accountHolderName.substring(this.accountHolderName.length() - 3).toLowerCase() + ++Account.counter; return this.transactionId; } public void transferTo(Account recipient, double amount) { if (balance - amount >= MIN_BALANCE) { balance -= amount; recipient.deposit(amount); transactions.add("Transfer to " + recipient.getAccountNumber() + ": -" + amount); } else { if (amount > MIN_BALANCE) System.out.println("Insufficient fund"); else { transactions.add( "Failed Transfer: Insufficient funds. A charge of $" + CHARGE_AMOUNT + " has been applied."); balance -= CHARGE_AMOUNT; // Apply charge for going below the minimum balance } } } public void displayAccountDetails() { System.out.println("Account Number: " + accountNumber); System.out.println("Balance: $" + balance); System.out.println("Name: " + accountHolderName); System.out.println("ID: " + generateTransactionId()); System.out.println("Transaction History:"); for (String transaction : transactions) { System.out.println("- " + transaction); } } } public class Bank { private String name; private Map<String, Account> accounts; public Bank(String name) { this.name = name; this.accounts = new HashMap<>(); } public String getName() { return name; } public Map<String, Account> getAccounts() { return accounts; } public void addAccount(String accountNumber, double initialBalance, String accountHolderName) { if (!accounts.containsKey(accountNumber)) { Account account = new Account(accountNumber, initialBalance, accountHolderName); accounts.put(accountNumber, account); System.out.println("Account created successfully."); } else { System.out.println("Account already exists with this account number."); } } public void removeAccount(String accountNumber) { if (accounts.containsKey(accountNumber)) { accounts.remove(accountNumber); System.out.println("Account removed successfully."); } else { System.out.println("Account not found with this account number."); } } public Account getAccount(String accountNumber) { return accounts.get(accountNumber); } public void displayBankDetails() { System.out.println("Bank Name: " + name); System.out.println("Accounts:"); for (Account account : accounts.values()) { System.out.println("------------------------------"); account.displayAccountDetails(); System.out.println("------------------------------"); } } } public class Banksystem { public static void main(String[] args) { // Creating a bank Bank bank = new Bank("MyBank"); // Adding accounts to the bank bank.addAccount("12345", 1000, "Shivangi"); bank.addAccount("67890", 500, "Harsh"); // Provide account holder's name for this account Account account1 = bank.getAccount("12345"); Account account2 = bank.getAccount("67890"); account1.deposit(1000); account1.transferTo(account2, 100); // Displaying bank details bank.displayBankDetails(); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.12; /// @title VOTES SIMULATOR /// @author dimitrix1337 /// @notice You can use this contract for everything. /// @dev I HAVE AN ERROR WHILE THE OWNER DECIDE TO ADD A CANDIDATE, THE TRANSACTION IS REVERT BUT I DON'T FOUNDED THE ERROR, IF SOMEONE HELPS ME, THANKS A LOT. /// @custom:experimental This is an experimental contract. contract Votes { address owner; uint256 i = 0; uint256 time_started; uint256 days_remaining = 2 days; constructor () { owner = msg.sender; time_started = block.timestamp; } struct Person { string name; uint32 age; bool voted; } struct Candidate { string name; uint256 votes; bool finalized; } modifier Finalize { require(FinalizeVotes(), "Error: is not time to finalize, wait 3 days after time started."); _; } modifier OnlyOwner() { require(!(owner != msg.sender), "Error: only owner can do this."); _; } modifier not_voted(uint256 _dni) { require(list_person[_dni].voted != true, "Error: this person already voted."); _; } modifier candidate_not_exist(string memory candidate_name) { require(CandidateExists(candidate_name), "Error: candidate not exists"); _; } mapping(uint256 => Person) list_person; Candidate[] candidates; function FinalizeVotes() private view OnlyOwner() returns(bool) { uint256 time_to_finalize = time_started + days_remaining; if (time_to_finalize <= block.timestamp) { for (uint256 p = 0; p <= candidates.length ; p++) { candidates[p].finalized == true; } return true; } else { return false; } } function Ready_To_Finalize() public view Finalize() { assert(msg.sender == owner); FinalizeVotes(); } function CandidateExists(string memory candidate_name) private view returns(bool) { for (uint256 h=0;h<=candidates.length;h++) { if (keccak256(abi.encodePacked(candidates[h].name)) == keccak256(abi.encodePacked(candidate_name))) { return true; } } return false; } function Vote(string memory candidate_name, uint256 _dni, string memory name, uint32 age) public not_voted(_dni) returns(bool) { assert(list_person[_dni].voted != true); for (uint256 j=0;j<=candidates.length;j++) { if (keccak256(abi.encodePacked(candidates[j].name)) == keccak256(abi.encodePacked(candidate_name)) && candidates[j].finalized != true) { candidates[j].votes++; list_person[_dni].name = name; list_person[_dni].age = age; list_person[_dni].voted = true; return true; } } return false; } function AddCandidate(string memory _name) payable public { uint256 j = i; candidates[j].name = _name; candidates[j].votes = 0; i++; } }
package com.jvosantos.examples.domain; import javax.persistence.*; import java.util.Date; @Entity public class Post { @Id @GeneratedValue private Long id; private String title; private String body; private Date postedOn; @ManyToOne private Author author; private Post() {} public Post(String title) { this.title = title; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public Date getPostedOn() { return postedOn; } public void setPostedOn(Date postedOn) { this.postedOn = postedOn; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } @Override public String toString() { return "Post: " + title; } }
defmodule Truckspotting.AccountsFixtures do @moduledoc """ This module defines test helpers for creating entities via the `Truckspotting.Accounts` context. """ alias Truckspotting.Factory alias Truckspotting.Accounts alias Truckspotting.Accounts.Roles alias Truckspotting.Accounts.Users @doc """ Generate a unique user email_address. """ def unique_user_email_address, do: "some email_address#{System.unique_integer([:positive])}" @doc """ Generate a unique user username. """ def unique_user_username, do: "some username#{System.unique_integer([:positive])}" @doc """ Generate a user. """ def user_fixture(attrs \\ %{}) do {:ok, user} = attrs |> Enum.into(%{ avatar: "some avatar", email_address: unique_user_email_address(), first_name: "some first_name", home_city: "some home_city", last_name: "some last_name", latitude: "120.5", longitude: "120.5", password: "some password", username: unique_user_username() }) |> Users.create_user() user end @doc """ Generate a role. """ def role_fixture(attrs \\ %{}) do {:ok, role} = attrs |> Enum.into(%{ name: :user, description: "some description" }) |> Roles.create_role() role end @doc """ Generate a user_role. """ def user_role_fixture(attrs \\ %{}) do {:ok, user_role} = attrs |> Enum.into(%{ user_id: Factory.insert!(:user).id, role_id: Factory.insert!(:role).id }) |> Accounts.create_user_role() user_role end end
from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser class CustomManager(BaseUserManager): def create_user(self, email, username, password=None, **extra_fields): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError("Users must have an email address") user = self.model( email=self.normalize_email(email), username=username, **extra_fields, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email=email, username=email, password=password, **extra_fields, ) user.is_admin = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser): email = models.EmailField( verbose_name="Email address", max_length=255, unique=True) username = models.CharField( verbose_name="Username", max_length=200, unique=True, blank=True) first_name = models.CharField( verbose_name="First Name", max_length=200, blank=True, null=True) last_name = models.CharField( verbose_name="Last Name", max_length=200, blank=True, null=True) password = models.CharField(verbose_name="Password", max_length=255) confirm_password = models.CharField( verbose_name="Confirm Password", max_length=255) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) objects = CustomManager() USERNAME_FIELD = "email" def __str__(self): return self.email @property def full_name(self): return f"{self.first_name} {self.last_name}" @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return self.is_admin def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True # class UserProfile(models.Model): # user = models.OneToOneField( # CustomUser, on_delete=models.CASCADE, blank=True, null=True) # profile_image = models.ImageField( # verbose_name="Avatar", default='images/user.jpg', upload_to='users/', blank=True, null=True) # about_user = models.TextField( # verbose_name="About User", null=True, blank=True) # address = models.CharField( # verbose_name="Address", max_length=512, blank=True, null=True) # city = models.CharField(max_length=32, blank=True, null=True) # state = models.CharField(max_length=32, blank=True, null=True) # country = models.CharField(max_length=32, blank=True, null=True) # phone = models.CharField(max_length=32, blank=True) # created_at = models.DateTimeField(auto_now_add=True) # def __str__(self): # return self.user.email
import { EditorState } from "@codemirror/state"; import { EditorView, keymap, // plugins highlightSpecialChars, drawSelection, rectangularSelection, lineNumbers, placeholder, } from "@codemirror/view"; import { syntaxHighlighting, indentOnInput, HighlightStyle, indentUnit, } from "@codemirror/language"; import { CompletionContext, autocompletion, closeBrackets, } from "@codemirror/autocomplete"; import { markdown, markdownKeymap, markdownLanguage, } from "@codemirror/lang-markdown"; import { history, indentWithTab } from "@codemirror/commands"; import { tags } from "@lezer/highlight"; import { HandleCustomElements } from "../assets/ClientFixMarkdown"; import { ParseMarkdown } from "./Markdown"; // create theme const highlight = HighlightStyle.define([ { tag: tags.heading1, fontWeight: "700", fontSize: "2.5rem", }, { tag: tags.heading2, fontWeight: "700", fontSize: "2rem", }, { tag: tags.heading3, fontWeight: "700", fontSize: "1.75rem", }, { tag: tags.heading4, fontWeight: "700", fontSize: "1.5rem", }, { tag: tags.heading5, fontWeight: "700", fontSize: "1.25rem", }, { tag: tags.heading6, fontWeight: "700", fontSize: "1rem", }, { tag: tags.strong, fontWeight: "600", }, { tag: tags.emphasis, fontStyle: "italic", }, { tag: tags.link, textDecoration: "underline", color: "var(--blue2)", }, { tag: tags.tagName, color: "var(--red)", fontFamily: "monospace", }, { tag: tags.monospace, fontFamily: "monospace", color: "var(--red3)", }, { tag: tags.angleBracket, fontFamily: "monospace", color: "var(--blue2)", }, ]); /** * @function BasicCompletion * * @param {CompletionContext} context * @return {*} */ function BasicCompletion(context: CompletionContext): any { let word = context.matchBefore(/\w*/); if (!word || (word.from == word.to && !context.explicit)) return null; return { from: word.from, options: [ // html special elements { label: "<hue>", type: "function", info: "Controls page hue when your paste is viewed, integer", apply: "<% hsl hue {hue here} %>", detail: "Special Elements", }, { label: "<sat>", type: "function", info: "Controls page saturation when your paste is viewed, percentage", apply: "<% hsl sat {sat here} %>", detail: "Special Elements", }, { label: "<lit>", type: "function", info: "Controls page lightness when your paste is viewed, percentage", apply: "<% hsl lit {lightness here} %>", detail: "Special Elements", }, { label: "comment", type: "keyword", info: "Invisible element", apply: "<comment></comment>", detail: "Special Elements", }, // themes { label: "dark theme", type: "variable", info: "Sets the user's theme when viewing the paste to dark", apply: "<% theme dark %>", detail: "Themes", }, { label: "light theme", type: "variable", info: "Sets the user's theme when viewing the paste to light", apply: "<% theme light %>", detail: "Themes", }, { label: "purple theme", type: "variable", info: "Sets the user's theme when viewing the paste to purple", apply: "<% theme purple %>", detail: "Themes", }, { label: "blue theme", type: "variable", info: "Sets the user's theme when viewing the paste to blue", apply: "<% theme blue %>", detail: "Themes", }, { label: "pink theme", type: "variable", info: "Sets the user's theme when viewing the paste to pink", apply: "<% theme pink %>", detail: "Themes", }, { label: "green theme", type: "variable", info: "Sets the user's theme when viewing the paste to green", apply: "<% theme green %>", detail: "Themes", }, // markdown { label: "h1", type: "keyword", apply: "# ", detail: "Headings", }, { label: "h2", type: "keyword", apply: "## ", detail: "Headings", }, { label: "h3", type: "keyword", apply: "### ", detail: "Headings", }, { label: "h4", type: "keyword", apply: "#### ", detail: "Headings", }, { label: "h5", type: "keyword", apply: "##### ", detail: "Headings", }, { label: "h6", type: "keyword", apply: "###### ", detail: "Headings", }, { label: "unordered list", type: "keyword", apply: "- ", detail: "Lists", }, { label: "ordered list", type: "keyword", apply: "1. ", detail: "Lists", }, { label: "note", type: "function", apply: "!!! note ", detail: "Notes", }, { label: "danger", type: "function", apply: "!!! danger ", detail: "Notes", }, { label: "warning", type: "function", apply: "!!! warn ", detail: "Notes", }, // extras { label: "timestamp", type: "text", apply: `<% time ${new Date().toUTCString().replaceAll(" ", "_")} %>`, detail: "Extras", }, { label: "table of contents", type: "function", info: "Add a table of contents to the paste", apply: "[TOC]", detail: "extras", }, { label: "center", type: "function", info: "Center paste content", apply: "-> ...content here... <-", detail: "extras", }, { label: "right", type: "function", info: "Align paste content to the right", apply: "-> ...content here... ->", detail: "extras", }, { label: "enable template", type: "function", apply: `<% enable template %>`, detail: "Extras", }, { label: "add class", type: "function", apply: `<% class class1 class2 %> content <% close class %>`, detail: "Extras", }, { label: "add id", type: "function", apply: `<% id id1 %> content <% close id %>`, detail: "Extras", }, // animations { label: "fade in animation", type: "function", apply: "<% animation FadeIn 1s %>\nContent goes here!\n\n<% close animation %>", detail: "Animations", }, { label: "fade out animation", type: "function", apply: "<% animation FadeOut 1s %>\nContent goes here!\n\n<% close animation %>", detail: "Animations", }, { label: "float animation", type: "function", apply: "<% animation Float 1s 0s infinite inline %>\nContent goes here!\n\n<% close animation %>", detail: "Animations", }, { label: "grow/shrink animation", type: "function", apply: "<% animation GrowShrink 1s 0s infinite %>\nContent goes here!\n\n<% close animation %>", detail: "Animations", }, { label: "blink animation", type: "function", apply: "<% animation Blink 1s 0s infinite inline %>\nContent goes here!\n\n<% close animation %>", detail: "Animations", }, // align { label: "align center (row)", type: "function", apply: "-> align center <-", detail: "Alignments", }, { label: "align right (row)", type: "function", apply: "-> align right ->", detail: "Alignments", }, { label: "align center (row flex)", type: "function", apply: "->> align center <<-", detail: "Alignments", }, { label: "align right (row flex)", type: "function", apply: "->> align right ->>", detail: "Alignments", }, ], }; } /** * @function CreateEditor * * @export * @param {string} ElementID */ export default function CreateEditor(ElementID: string, content: string) { const element = document.getElementById(ElementID)!; // load extensions const ExtensionsList = [ keymap.of(markdownKeymap), highlightSpecialChars(), drawSelection(), rectangularSelection(), EditorView.lineWrapping, closeBrackets(), history(), placeholder(`# ${new Date().toLocaleDateString()}`), EditorView.updateListener.of(async (update) => { if (update.docChanged) { const content = update.state.doc.toString(); if (content === "") return; // basic session save window.localStorage.setItem("doc", content); const html = await ParseMarkdown(content, false); window.localStorage.setItem("gen", html); (window as any).EditorContent = content; // update TOC const TOCElement = document.getElementById("_toc_area"); if (TOCElement) { const TableOfContents = ( await ParseMarkdown( `[TOC]\n{{@TABLE_OF_CONTENTS}}\n${content}` ) ).split("{{@TABLE_OF_CONTENTS}}")[0]; TOCElement.innerHTML = TableOfContents; } } }), EditorState.allowMultipleSelections.of(true), indentOnInput(), indentUnit.of(" "), keymap.of([ // we're creating this keymap because of a weird issue in firefox where // (if there is no text before or after), a new line is not created // ...we're basically just manually inserting the new line here { key: "Enter", run: (): boolean => { // get current line const CurrentLine = view.state.doc.lineAt( view.state.selection.main.head ); // get indentation string (for automatic indent) let IndentationString = // gets everything before the first non-whitespace character CurrentLine.text.split(/[^\s]/)[0]; let ExtraCharacters = ""; // if last character of the line is }, add an indentation // } because it's automatically added after opened braces! if ( CurrentLine.text[CurrentLine.text.length - 1] === "{" || CurrentLine.text[CurrentLine.text.length - 1] === "}" ) { IndentationString += " "; ExtraCharacters = "\n"; // auto insert line break after } // start transaction const cursor = view.state.selection.main.head; const transaction = view.state.update({ changes: { from: cursor, insert: `\n${IndentationString}${ExtraCharacters}`, }, selection: { anchor: cursor + 1 + IndentationString.length, }, scrollIntoView: true, }); if (transaction) { view.dispatch(transaction); } // return return true; }, }, { key: "<", run: (): boolean => { // get current line const CurrentLine = view.state.doc.lineAt( view.state.selection.main.head ); // start transaction const cursor = view.state.selection.main.head; const transaction = view.state.update({ changes: { from: cursor, insert: "<>", }, selection: { anchor: cursor + 1, }, scrollIntoView: true, }); if (transaction) { view.dispatch(transaction); } // return return true; }, }, indentWithTab, ]), // markdown syntaxHighlighting(highlight), markdown({ base: markdownLanguage, }), autocompletion({ override: [BasicCompletion], activateOnTyping: window.location.search.includes("hints=true") || window.localStorage.getItem("bundles:user.EditorHints") === "true", }), ]; if (window.localStorage.getItem("bundles:user.ShowLineNumbers") === "true") ExtensionsList.push(lineNumbers()); // bad system for testing if we're editing something else // checks if first 10 characters are changed, clears doc if they are if ( (window.localStorage.getItem("doc") && !window.localStorage .getItem("doc")! .startsWith(decodeURIComponent(content).substring(0, 9))) || window.location.search.includes("new-paste") ) window.localStorage.removeItem("doc"); // save/check LastEditURL if (window.localStorage.getItem("LastEditURL") !== window.location.href) window.localStorage.removeItem("doc"); window.localStorage.setItem("LastEditURL", window.location.href); // create editor const view = new EditorView({ // @ts-ignore state: EditorState.create({ doc: // display the saved document or given content window.localStorage.getItem("doc")! || decodeURIComponent(content) || "", extensions: ExtensionsList, }), parent: element, }); // prerender (async () => { window.localStorage.setItem( "gen", await ParseMarkdown( window.localStorage.getItem("doc")! || decodeURIComponent(content) || "", false ) ); (window as any).EditorContent = decodeURIComponent(content); })(); // add attributes const contentField = document.querySelector( "#editor-tab-text .cm-editor .cm-scroller .cm-content" )!; contentField.setAttribute("spellcheck", "true"); contentField.setAttribute("aria-label", "Content Editor"); // set value of contentInput if we have window.sessionStorage.doc const doc = window.localStorage.getItem("doc"); if (doc) (window as any).EditorContent = doc; } // handle tabs function CloseAllTabs() { for (let element of document.getElementsByClassName( "editor-tab" ) as any as HTMLElement[]) { element.classList.remove("active"); const button = document.getElementById( `editor-open-${element.id.split("editor-")[1] || ""}` ); if (button) button.classList.add("secondary"); } } document.getElementById("editor-open-tab-text")!.addEventListener("click", () => { CloseAllTabs(); document.getElementById("editor-open-tab-text")!.classList.remove("secondary"); document.getElementById("editor-tab-text")!.classList.add("active"); document.getElementById("-editor")!.style.borderTopLeftRadius = "0"; }); document.getElementById("editor-open-tab-preview")!.addEventListener("click", () => { CloseAllTabs(); const tab = document.getElementById("editor-tab-preview")!; tab.innerHTML = window.localStorage.getItem("gen") || ""; tab.classList.add("active"); document.getElementById("-editor")!.style.borderTopLeftRadius = "var(--u-04)"; document .getElementById("editor-open-tab-preview")! .classList.remove("secondary"); // fix markdown rendering HandleCustomElements(); }); document.querySelector(".tab-container")!.addEventListener("click", () => { if (document.getElementById("editor-open-tab-text")!.style.display === "none") return; (document.querySelector(".cm-content")! as HTMLElement).focus(); }); // check CustomURL const CustomURLInput: HTMLInputElement | null = document.getElementById( "CustomURL" ) as any; const GroupNameInput: HTMLInputElement | null = document.getElementById( "GroupName" ) as any; let URLInputTimeout: any = undefined; if (CustomURLInput) CustomURLInput.addEventListener("keyup", (event: any) => { let value = event.target.value.trim(); // make sure value isn't too short if (value.length < 1) { CustomURLInput.classList.remove("invalid"); return; } // add group name if (GroupNameInput && GroupNameInput.value.trim().length > 1) value = `${GroupNameInput.value.trim()}/${value}`; // create timeout if (URLInputTimeout) clearTimeout(URLInputTimeout); URLInputTimeout = setTimeout(async () => { // fetch url const exists = (await (await fetch(`/api/exists/${value}`)).text()) === "true"; if (!exists) { // paste does not exist CustomURLInput.classList.remove("invalid"); return; } // set input to invalid CustomURLInput.classList.add("invalid"); }, 500); }); // details auto focus for (let element of document.querySelectorAll( "details" ) as any as HTMLDetailsElement[]) { // check if element has an input const input = element.querySelector("input"); if (!input) continue; // add event listener element.querySelector("summary")!.addEventListener("click", () => { if (element.getAttribute("open") !== null) return; // element must be open, // should not have attribute // already when event is fired // auto focus input setTimeout(() => { input.focus(); }, 0); }); } // clear stored content only if ref isn't the homepage (meaning the paste was created properly) if ( !document.referrer.endsWith(`${window.location.host}/`) && // homepage !document.referrer.endsWith("%20already%20exists!") && // already exists error (still homepage) !document.referrer.startsWith( // edit mode `${window.location.protocol}//${window.location.host}/?mode=edit` ) && !document.referrer.startsWith( // edit error `${window.location.protocol}//${window.location.host}/?err=Invalid` ) ) { window.sessionStorage.removeItem("doc"); window.sessionStorage.removeItem("gen"); }
<template> <div class="register-body"> <div class="bg"></div> <div class="bg bg2"></div> <div class="bg bg3"></div> <div class="content"> <h1>欢 迎 注 册</h1> <el-form class="form-form" ref="form" :model="form" label-width="80px"> <el-form-item label="用户名"> <el-input v-model="form.username" id="username"></el-input> </el-form-item> <el-form-item label="昵称"> <el-input v-model="form.name" id="name"></el-input> </el-form-item> <el-form-item label="邮箱"> <el-input v-model="form.email" id="email"></el-input> </el-form-item> <el-form-item label="密码"> <el-input type="password" v-model="form.passwd" id="password"></el-input> </el-form-item> <el-form-item> <el-button @click="goLogin" id="goLogin">去 登 录</el-button> <el-button type="primary" @click="registerClick()" id="register">注 册</el-button> </el-form-item> </el-form> </div> </div> </template> <script> import {register} from "../network/login"; export default { name: "Register", data(){ return{ form: { username: '', passwd: '', name: '', email: '' } } }, methods: { registerClick(){ register(this.form).then(res => { //console.log(res) if (res.data.results.sign_up_status == 1){ this.$message({ //id: 'success_register', message: '注册成功', type: 'success' }); this.$router.push("/login") } else if (res.data.results.sign_up_status !== 1){ this.$message.error(res.data.res.sign_up_msg); } }) .catch(error => { console.log(error) }) }, goLogin(){ this.$router.push("/login") } } } </script> <style scoped> html { height: 100%; } body { margin: 0; } .bg { animation: slide 3s ease-in-out infinite alternate; background-image: linear-gradient(-60deg, #6c3 50%, #09f 50%); bottom: 0; left: -50%; opacity: .5; position: fixed; right: -50%; top: 0; z-index: -1; } .bg2 { animation-direction: alternate-reverse; animation-duration: 4s; } .bg3 { animation-duration: 5s; } .content { background-color: rgba(255, 255, 255, .8); border-radius: .25em; box-shadow: 0 0 .25em rgba(0, 0, 0, .25); box-sizing: border-box; left: 50%; padding: 10vmin; position: fixed; text-align: center; top: 50%; transform: translate(-50%, -50%); } h1 { font-family: monospace; } @keyframes slide { 0% { transform: translateX(-25%); } 100% { transform: translateX(25%); } } </style>
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/internal/Observable'; import { environment } from 'src/environments/environment'; import { Employee } from '../models/employee.model'; @Injectable({ providedIn: 'root' }) export class EmployeesService { apiLink: string; constructor(private http: HttpClient) { this.apiLink = environment.baseURL; } //get employee detail by id getById(id: number) { return this.http.get<Employee>(`${this.apiLink}/employees/${id}`); } //get all employee detail from db getEmployees(): Observable<Employee[]> { return this.http.get<Employee[]>(`${this.apiLink}/employees`); } //save employee detail to db createEmployee(data: Employee): Observable<Employee> { return this.http.post<Employee>(`${this.apiLink}/employees`, data); } //update employee detail to db at specific id updateEmployee(id: number, data: Employee): Observable<Employee> { return this.http.put<Employee>(`${this.apiLink}/employees/${id}`, data); } //detele employee detail at db with id deleteEmployee(id: number): Observable<number> { return this.http.delete<number>(`${this.apiLink}/employees/${id}`); } }
/* * WPA Supplicant - wired Ethernet driver interface * Copyright (c) 2005-2007, Jouni Malinen <j@w1.fi> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * Alternatively, this software may be distributed under the terms of BSD * license. * * See README and COPYING for more details. */ #include "includes.h" #include <sys/ioctl.h> #include <net/if.h> #ifdef __linux__ #include <netpacket/packet.h> #endif /* __linux__ */ #if defined(__FreeBSD__) || defined(__DragonFly__) #include <net/if_dl.h> #endif /* defined(__FreeBSD__) || defined(__DragonFly__) */ #include "common.h" #include "driver.h" static const u8 pae_group_addr[ETH_ALEN] = { 0x01, 0x80, 0xc2, 0x00, 0x00, 0x03 }; struct wpa_driver_wired_data { void *ctx; int pf_sock; char ifname[IFNAMSIZ + 1]; int membership, multi, iff_allmulti, iff_up; }; static int wpa_driver_wired_get_ssid(void *priv, u8 *ssid) { ssid[0] = 0; return 0; } static int wpa_driver_wired_get_bssid(void *priv, u8 *bssid) { /* Report PAE group address as the "BSSID" for wired connection. */ os_memcpy(bssid, pae_group_addr, ETH_ALEN); return 0; } static int wpa_driver_wired_get_ifflags(const char *ifname, int *flags) { struct ifreq ifr; int s; s = socket(PF_INET, SOCK_DGRAM, 0); if (s < 0) { perror("socket"); return -1; } os_memset(&ifr, 0, sizeof(ifr)); os_strlcpy(ifr.ifr_name, ifname, IFNAMSIZ); if (ioctl(s, SIOCGIFFLAGS, (caddr_t) &ifr) < 0) { perror("ioctl[SIOCGIFFLAGS]"); close(s); return -1; } close(s); *flags = ifr.ifr_flags & 0xffff; return 0; } static int wpa_driver_wired_set_ifflags(const char *ifname, int flags) { struct ifreq ifr; int s; s = socket(PF_INET, SOCK_DGRAM, 0); if (s < 0) { perror("socket"); return -1; } os_memset(&ifr, 0, sizeof(ifr)); os_strlcpy(ifr.ifr_name, ifname, IFNAMSIZ); ifr.ifr_flags = flags & 0xffff; if (ioctl(s, SIOCSIFFLAGS, (caddr_t) &ifr) < 0) { perror("ioctl[SIOCSIFFLAGS]"); close(s); return -1; } close(s); return 0; } static int wpa_driver_wired_multi(const char *ifname, const u8 *addr, int add) { struct ifreq ifr; int s; s = socket(PF_INET, SOCK_DGRAM, 0); if (s < 0) { perror("socket"); return -1; } os_memset(&ifr, 0, sizeof(ifr)); os_strlcpy(ifr.ifr_name, ifname, IFNAMSIZ); #ifdef __linux__ ifr.ifr_hwaddr.sa_family = AF_UNSPEC; os_memcpy(ifr.ifr_hwaddr.sa_data, addr, ETH_ALEN); #endif /* __linux__ */ #if defined(__FreeBSD__) || defined(__DragonFly__) { struct sockaddr_dl *dlp; dlp = (struct sockaddr_dl *) &ifr.ifr_addr; dlp->sdl_len = sizeof(struct sockaddr_dl); dlp->sdl_family = AF_LINK; dlp->sdl_index = 0; dlp->sdl_nlen = 0; dlp->sdl_alen = ETH_ALEN; dlp->sdl_slen = 0; os_memcpy(LLADDR(dlp), addr, ETH_ALEN); } #endif /* defined(__FreeBSD__) || defined(__DragonFly__) */ #if defined(__NetBSD__) || defined(__OpenBSD__) || defined(__APPLE__) { struct sockaddr *sap; sap = (struct sockaddr *) &ifr.ifr_addr; sap->sa_len = sizeof(struct sockaddr); sap->sa_family = AF_UNSPEC; os_memcpy(sap->sa_data, addr, ETH_ALEN); } #endif /* defined(__NetBSD__) || defined(__OpenBSD__) || defined(__APPLE__) */ if (ioctl(s, add ? SIOCADDMULTI : SIOCDELMULTI, (caddr_t) &ifr) < 0) { perror("ioctl[SIOC{ADD/DEL}MULTI]"); close(s); return -1; } close(s); return 0; } static int wpa_driver_wired_membership(struct wpa_driver_wired_data *drv, const u8 *addr, int add) { #ifdef __linux__ struct packet_mreq mreq; if (drv->pf_sock == -1) return -1; os_memset(&mreq, 0, sizeof(mreq)); mreq.mr_ifindex = if_nametoindex(drv->ifname); mreq.mr_type = PACKET_MR_MULTICAST; mreq.mr_alen = ETH_ALEN; os_memcpy(mreq.mr_address, addr, ETH_ALEN); if (setsockopt(drv->pf_sock, SOL_PACKET, add ? PACKET_ADD_MEMBERSHIP : PACKET_DROP_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) { perror("setsockopt"); return -1; } return 0; #else /* __linux__ */ return -1; #endif /* __linux__ */ } static void * wpa_driver_wired_init(void *ctx, const char *ifname) { struct wpa_driver_wired_data *drv; int flags; drv = os_zalloc(sizeof(*drv)); if (drv == NULL) return NULL; os_strlcpy(drv->ifname, ifname, sizeof(drv->ifname)); drv->ctx = ctx; #ifdef __linux__ drv->pf_sock = socket(PF_PACKET, SOCK_DGRAM, 0); if (drv->pf_sock < 0) perror("socket(PF_PACKET)"); #else /* __linux__ */ drv->pf_sock = -1; #endif /* __linux__ */ if (wpa_driver_wired_get_ifflags(ifname, &flags) == 0 && !(flags & IFF_UP) && wpa_driver_wired_set_ifflags(ifname, flags | IFF_UP) == 0) { drv->iff_up = 1; } if (wpa_driver_wired_membership(drv, pae_group_addr, 1) == 0) { wpa_printf(MSG_DEBUG, "%s: Added multicast membership with " "packet socket", __func__); drv->membership = 1; } else if (wpa_driver_wired_multi(ifname, pae_group_addr, 1) == 0) { wpa_printf(MSG_DEBUG, "%s: Added multicast membership with " "SIOCADDMULTI", __func__); drv->multi = 1; } else if (wpa_driver_wired_get_ifflags(ifname, &flags) < 0) { wpa_printf(MSG_INFO, "%s: Could not get interface " "flags", __func__); os_free(drv); return NULL; } else if (flags & IFF_ALLMULTI) { wpa_printf(MSG_DEBUG, "%s: Interface is already configured " "for multicast", __func__); } else if (wpa_driver_wired_set_ifflags(ifname, flags | IFF_ALLMULTI) < 0) { wpa_printf(MSG_INFO, "%s: Failed to enable allmulti", __func__); os_free(drv); return NULL; } else { wpa_printf(MSG_DEBUG, "%s: Enabled allmulti mode", __func__); drv->iff_allmulti = 1; } return drv; } static void wpa_driver_wired_deinit(void *priv) { struct wpa_driver_wired_data *drv = priv; int flags; if (drv->membership && wpa_driver_wired_membership(drv, pae_group_addr, 0) < 0) { wpa_printf(MSG_DEBUG, "%s: Failed to remove PAE multicast " "group (PACKET)", __func__); } if (drv->multi && wpa_driver_wired_multi(drv->ifname, pae_group_addr, 0) < 0) { wpa_printf(MSG_DEBUG, "%s: Failed to remove PAE multicast " "group (SIOCDELMULTI)", __func__); } if (drv->iff_allmulti && (wpa_driver_wired_get_ifflags(drv->ifname, &flags) < 0 || wpa_driver_wired_set_ifflags(drv->ifname, flags & ~IFF_ALLMULTI) < 0)) { wpa_printf(MSG_DEBUG, "%s: Failed to disable allmulti mode", __func__); } if (drv->iff_up && wpa_driver_wired_get_ifflags(drv->ifname, &flags) == 0 && (flags & IFF_UP) && wpa_driver_wired_set_ifflags(drv->ifname, flags & ~IFF_UP) < 0) { wpa_printf(MSG_DEBUG, "%s: Failed to set the interface down", __func__); } if (drv->pf_sock != -1) close(drv->pf_sock); os_free(drv); } const struct wpa_driver_ops wpa_driver_wired_ops = { .name = "wired", .desc = "wpa_supplicant wired Ethernet driver", .get_ssid = wpa_driver_wired_get_ssid, .get_bssid = wpa_driver_wired_get_bssid, .init = wpa_driver_wired_init, .deinit = wpa_driver_wired_deinit, };
import React, { memo, useCallback, useEffect } from 'react'; import { FormProvider, useForm } from 'react-hook-form'; import { yupResolver } from '@hookform/resolvers/yup'; import { Grid } from '@mui/material'; import { HFCheckbox } from 'components/HookForm/HFCheckbox'; import { HFSelect } from 'components/HookForm/HFSelect'; import { HFTextField } from 'components/HookForm/HFTextField'; import { Button } from 'components/UI/Button/Button'; import { IconButton } from 'components/UI/IconButton/IconButton'; import { OrderProfileDto } from 'types/dto/order/profile.dto'; import { useLocalTranslation } from 'hooks/useLocalTranslation'; import { color } from 'themes'; import translations from './Form.i18n.json'; import { getValidationSchema } from './validation'; import DeleteIcon from '@mui/icons-material/DeleteForeverOutlined'; const sx = { mainCheck: { display: 'flex', alignItems: 'center', }, checkbox: { display: 'flex', alignItems: 'center', }, actions: { display: 'flex', justifyContent: 'flex-end', alignItems: 'center', }, closeBtn: { margin: '0 6px 0 12px', }, }; const addressFields = ['street', 'house', 'apartment', 'entrance', 'floor']; type PAProfilesFormProps = { defaultValues?: OrderProfileDto; cities: { value: number; label: string; }[]; onSave(orderProfile: OrderProfileDto): void; onDelete(): void; }; export const PAProfilesForm = memo(({ defaultValues, cities, onSave, onDelete }: PAProfilesFormProps) => { const { t } = useLocalTranslation(translations); const schema = getValidationSchema(t); const values = useForm<OrderProfileDto>({ resolver: yupResolver(schema), mode: 'onBlur', defaultValues, }); const submit = (data: OrderProfileDto) => onSave(data); const reset = useCallback(() => values.reset(defaultValues), [defaultValues, values]); useEffect(() => reset(), [defaultValues, reset]); return ( <FormProvider {...values}> <form onSubmit={values.handleSubmit(submit)}> <Grid container spacing={2}> <Grid item xs={12} md={6} container spacing={2}> <Grid item xs={12} sm={6}> <HFSelect name='cityId' options={cities} label={t('city')} placeholder={t('cityPlaceholder')} /> </Grid> {addressFields.map(field => ( <Grid key={field} item xs={12} sm={6}> <HFTextField name={field} label={t(field)} /> </Grid> ))} </Grid> <Grid item xs={12} md={6} container spacing={2}> <Grid item xs={12}> <HFTextField name='title' label={t('title')} /> </Grid> <Grid item xs={12}> <HFTextField rows={4} multiline name='comment' label={t('comment')} /> </Grid> </Grid> <Grid item xs={12} md={6} sx={sx.mainCheck}> <HFCheckbox name='isMain' label={t('isMain')} sx={sx.checkbox} /> </Grid> <Grid item xs={12} md={6} container sx={sx.actions}> <Button type='submit' size='small'> {t('save')} </Button> {!defaultValues && ( <Button variant='outlined' size='small' onClick={reset} sx={sx.closeBtn}> {t('reset')} </Button> )} <IconButton> <DeleteIcon htmlColor={color.muted} onClick={onDelete} /> </IconButton> </Grid> </Grid> </form> </FormProvider> ); });
{% load static %}<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1" name="viewport" /> <title>RSSer</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="shortcut icon" href="{% static 'rsser/images/favicon.png' %}" type="image/x-icon"> <link rel="stylesheet" href="{% static "rsser/css/index.css" %}"> <meta name="yandex-verification" content="b0f16a26840a0994" /> </head> <body> <div class="stations-container"> {% for station in stations %} <div class="station-name"> <h1>{{ station.name }}</h1> </div> <div class="accordion programs-container" id="container-{{ station.short_latin_name }}"> {% for program in station.programs.all %} <div class="card program"> <div class="card-header program-header" id="heading-{{ program.title_en }}"> <h5 class="mb-0 program-title"> <button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapse-{{ program.title_en }}"> {{ program.title_ru }} </button> </h5> </div> <div id="collapse-{{ program.title_en }}" {# class="collapse show"#} class="collapse" data-parent="#container-{{ station.short_latin_name }}"> <div class="card-body program-info"> <div class="program-description"> {{ program.description }} </div> <a class="btn btn-primary btn-program-url" href="{{ program.url }}" target="_blank">Страница программы </a> <a class="btn btn-primary btn-feed-url" href="{{ program.feed_url }}" target="_blank">RSS </a> </div> </div> </div> {% endfor %} </div> {% endfor %} </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> </body> </html>
package com.challenge.microservice.repository; import com.challenge.microservice.model.Alumno; import com.challenge.microservice.model.Estado; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** * Interfaz que define operaciones de acceso a datos para la entidad Alumno. */ public interface IAlumnoRepository { /** * Guarda un objeto Alumno en el repositorio. * * @param alumno El objeto Alumno a guardar. * @return Un Mono que representa la finalización exitosa de la operación. */ public Mono<Void> save(Alumno alumno); /** * Recupera una página de objetos Alumno filtrados por estado. * * @param estado Estado por el cual filtrar los alumnos. * @param page Número de página (basado en cero) a recuperar. * @param size Tamaño de la página (cantidad de elementos por página). * @return Un Flux que emite objetos Alumno que cumplen con los criterios de * filtrado y paginación. */ public Flux<Alumno> findByEstadoPaged(Estado estado, int page, int size); /** * Calcula la cantidad de objetos Alumno con el estado dado. * * @param estado Estado por el cual contar los alumnos. * @return Un Mono que emite la cantidad de alumnos que cumplen con el estado * dado. */ public Mono<Long> countByEstado(Estado estado); /** * Verifica si existe un objeto Alumno con el ID dado. * * @param id Identificador único del alumno. * @return Un Mono que emite true si existe un alumno con el ID dado, false en * caso contrario. */ public Mono<Boolean> existsById(Long id); }
<?php namespace App\Controller; use App\Controller\AppController; /** * Publicaciones Controller * * @property \App\Model\Table\PublicacionesTable $Publicaciones * * @method \App\Model\Entity\Publicacione[] paginate($object = null, array $settings = []) */ class PublicacionesController extends AppController { /** * Index method * * @return \Cake\Http\Response|void */ public function index() { $this->paginate = [ 'contain' => ['Users'] ]; $publicaciones = $this->paginate($this->Publicaciones); $this->loadModel('Users'); $users = $this->Users->find('all')->contain(['UsersPerfiles'])->where(['UsersPerfiles.user_id' => $this->Auth->user('id')]) ->hydrate(false) ->toArray(); $this->set(compact('users')); $this->set(compact('publicaciones')); $this->set('_serialize', ['publicaciones']); } /** * View method * * @param string|null $id Publicacione id. * @return \Cake\Http\Response|void * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. */ public function view($id = null) { $publicacione = $this->Publicaciones->get($id, [ 'contain' => ['Users'] ]); $this->loadModel('Users'); $user = $this->Users->find('all')->contain(['UsersPerfiles'])->where(['UsersPerfiles.user_id' => $this->Auth->user('id')]) ->hydrate(false) ->toArray(); //$total_public = $this->Publicaciones->find('all')->where(['Publicaciones.id' => $id)]);//->count(); //$id_menor = $this->Publicaciones->find('first')->where(['Publicaciones.id' < $id)]); $id_menor = $this->Publicaciones->find('all', ['limit' => 1,'order' => 'Publicaciones.id DESC']) ->where(['Publicaciones.id <' => $id])->limit(1) ->hydrate(false) ->toArray(); $id_mayor = $this->Publicaciones->find('all', ['limit' => 1,'order' => 'Publicaciones.id ASC']) ->where(['Publicaciones.id >' => $id])->limit(1) ->hydrate(false) ->toArray(); $total_public = $this->Publicaciones->find('all')->count(); $this->set('publ_actual', $id); $this->set('tot_publ', $total_public); $this->set('user', $user[0]); $this->set('id_menor', isset($id_menor[0]['id'])?$id_menor[0]['id']:null); $this->set('id_mayor', isset($id_mayor[0]['id'])?$id_mayor[0]['id']:null); $this->set('publicacione', $publicacione); $this->set('_serialize', ['publicacione']); } /** * Add method * * @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise. */ public function add() { $publicacione = $this->Publicaciones->newEntity(); if ($this->request->is('post')) { $publicacione = $this->Publicaciones->patchEntity($publicacione, $this->request->getData()); if ($this->Publicaciones->save($publicacione)) { $this->Flash->success(__('The publicacione has been saved.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('The publicacione could not be saved. Please, try again.')); } $users = $this->Publicaciones->Users->find('list', ['limit' => 200]); $this->set(compact('publicacione', 'users')); $this->set('_serialize', ['publicacione']); } /** * Edit method * * @param string|null $id Publicacione id. * @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise. * @throws \Cake\Network\Exception\NotFoundException When record not found. */ public function edit($id = null) { $publicacione = $this->Publicaciones->get($id, [ 'contain' => [] ]); if ($this->request->is(['patch', 'post', 'put'])) { $publicacione = $this->Publicaciones->patchEntity($publicacione, $this->request->getData()); if ($this->Publicaciones->save($publicacione)) { $this->Flash->success(__('Publicacion Editada con exito.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('La publicacion no pudo ser guardada')); } $users = $this->Publicaciones->Users->find('list', ['limit' => 200]); $this->set(compact('publicacione', 'users')); $this->set('_serialize', ['publicacione']); } /** * Delete method * * @param string|null $id Publicacione id. * @return \Cake\Http\Response|null Redirects to index. * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. */ public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $publicacione = $this->Publicaciones->get($id); if ($this->Publicaciones->delete($publicacione)) { $this->Flash->success(__('La Publicacion fue eliminada con exito.')); } else { $this->Flash->error(__('La aplicacion no se puedo eliminar')); } return $this->redirect(['action' => 'index']); } }
# # (C) Tenable Network Security, Inc. # # The descriptive text and package checks in this plugin were # extracted from Red Hat Security Advisory RHSA-2016:2674 and # CentOS Errata and Security Advisory 2016:2674 respectively. # include("compat.inc"); if (description) { script_id(94741); script_version("$Revision: 2.4 $"); script_cvs_date("$Date: 2016/12/27 14:29:49 $"); script_cve_id("CVE-2016-6313"); script_osvdb_id(143068); script_xref(name:"RHSA", value:"2016:2674"); script_name(english:"CentOS 6 / 7 : libgcrypt (CESA-2016:2674)"); script_summary(english:"Checks rpm output for the updated packages"); script_set_attribute( attribute:"synopsis", value:"The remote CentOS host is missing one or more security updates." ); script_set_attribute( attribute:"description", value: "An update for libgcrypt is now available for Red Hat Enterprise Linux 6 and Red Hat Enterprise Linux 7. Red Hat Product Security has rated this update as having a security impact of Moderate. A Common Vulnerability Scoring System (CVSS) base score, which gives a detailed severity rating, is available for each vulnerability from the CVE link(s) in the References section. The libgcrypt library provides general-purpose implementations of various cryptographic algorithms. Security Fix(es) : * A design flaw was found in the libgcrypt PRNG (Pseudo-Random Number Generator). An attacker able to obtain the first 580 bytes of the PRNG output could predict the following 20 bytes. (CVE-2016-6313) Red Hat would like to thank Felix Dorre and Vladimir Klebanov for reporting this issue." ); # http://lists.centos.org/pipermail/centos-announce/2016-November/022141.html script_set_attribute( attribute:"see_also", value:"http://www.nessus.org/u?e6dd1dc1" ); # http://lists.centos.org/pipermail/centos-cr-announce/2016-November/003680.html script_set_attribute( attribute:"see_also", value:"http://www.nessus.org/u?171a51f2" ); script_set_attribute( attribute:"solution", value:"Update the affected libgcrypt packages." ); script_set_cvss_base_vector("CVSS2#AV:N/AC:L/Au:N/C:P/I:N/A:N"); script_set_cvss_temporal_vector("CVSS2#E:F/RL:OF/RC:ND"); script_set_cvss3_base_vector("CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N"); script_set_cvss3_temporal_vector("CVSS:3.0/E:F/RL:O/RC:X"); script_set_attribute(attribute:"exploitability_ease", value:"Exploits are available"); script_set_attribute(attribute:"exploit_available", value:"true"); script_set_attribute(attribute:"plugin_type", value:"local"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:centos:centos:libgcrypt"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:centos:centos:libgcrypt-devel"); script_set_attribute(attribute:"cpe", value:"cpe:/o:centos:centos:6"); script_set_attribute(attribute:"cpe", value:"cpe:/o:centos:centos:7"); script_set_attribute(attribute:"patch_publication_date", value:"2016/11/12"); script_set_attribute(attribute:"plugin_publication_date", value:"2016/11/14"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_copyright(english:"This script is Copyright (C) 2016 Tenable Network Security, Inc."); script_family(english:"CentOS Local Security Checks"); script_dependencies("ssh_get_info.nasl"); script_require_keys("Host/local_checks_enabled", "Host/CentOS/release", "Host/CentOS/rpm-list"); exit(0); } include("audit.inc"); include("global_settings.inc"); include("rpm.inc"); if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED); if (!get_kb_item("Host/CentOS/release")) audit(AUDIT_OS_NOT, "CentOS"); if (!get_kb_item("Host/CentOS/rpm-list")) audit(AUDIT_PACKAGE_LIST_MISSING); cpu = get_kb_item("Host/cpu"); if (isnull(cpu)) audit(AUDIT_UNKNOWN_ARCH); if ("x86_64" >!< cpu && cpu !~ "^i[3-6]86$") audit(AUDIT_LOCAL_CHECKS_NOT_IMPLEMENTED, "CentOS", cpu); flag = 0; if (rpm_check(release:"CentOS-6", reference:"libgcrypt-1.4.5-12.el6_8")) flag++; if (rpm_check(release:"CentOS-6", reference:"libgcrypt-devel-1.4.5-12.el6_8")) flag++; if (rpm_check(release:"CentOS-7", cpu:"x86_64", reference:"libgcrypt-1.5.3-13.el7_3.1")) flag++; if (rpm_check(release:"CentOS-7", cpu:"x86_64", reference:"libgcrypt-devel-1.5.3-13.el7_3.1")) flag++; if (flag) { if (report_verbosity > 0) security_warning(port:0, extra:rpm_report_get()); else security_warning(0); exit(0); } else audit(AUDIT_HOST_NOT, "affected");
import { Camera, CameraType } from 'expo-camera'; import { useEffect, useState } from 'react'; import { Button, StyleSheet, Text, TouchableOpacity, View } from 'react-native'; export default function CameraScreen() { const [type, setType] = useState(CameraType.back); const [permission, requestPermission] = Camera.useCameraPermissions(); async function getPermission() { const cameraPermission = await Camera.requestCameraPermissionsAsync(); requestPermission(cameraPermission); } if(!permission) { getPermission(); return <Text>Camera não permitida. Por favor, permita acesso a sua camera</Text> } if(permission.granted === false) { getPermission(); return <Text>Camera não permitida. Por favor, permita acesso a sua camera</Text> } function toggleCameraType() { setType(current => (current === CameraType.back ? CameraType.front : CameraType.back)); } return ( <> <View style={styles.container}> <Camera style={styles.camera} type={type}> <View style={styles.buttonContainer}> <TouchableOpacity style={styles.button} onPress={toggleCameraType}> <Text style={styles.text}>Flip Camera</Text> </TouchableOpacity> </View> </Camera> </View> </> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', }, camera: { flex: 1, }, buttonContainer: { flex: 1, flexDirection: 'row', backgroundColor: 'transparent', margin: 64, }, button: { flex: 1, alignSelf: 'flex-end', alignItems: 'center', }, text: { fontSize: 24, fontWeight: 'bold', color: 'white', }, });
package com.bachlinh.order.web.repository.implementer; import com.bachlinh.order.core.annotation.ActiveReflection; import com.bachlinh.order.core.annotation.DependenciesInitialize; import com.bachlinh.order.core.annotation.RepositoryComponent; import com.bachlinh.order.core.container.DependenciesContainerResolver; import com.bachlinh.order.entity.model.Product; import com.bachlinh.order.entity.model.ProductMedia; import com.bachlinh.order.entity.model.ProductMedia_; import com.bachlinh.order.web.repository.spi.AbstractRepository; import com.bachlinh.order.repository.RepositoryBase; import com.bachlinh.order.repository.query.Operation; import com.bachlinh.order.repository.query.SqlBuilder; import com.bachlinh.order.repository.query.SqlSelect; import com.bachlinh.order.repository.query.SqlWhere; import com.bachlinh.order.repository.query.Where; import com.bachlinh.order.repository.utils.QueryUtils; import com.bachlinh.order.web.repository.spi.ProductMediaRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; @RepositoryComponent @ActiveReflection public class ProductMediaRepositoryImpl extends AbstractRepository<Integer, ProductMedia> implements ProductMediaRepository, RepositoryBase { private final Logger log = LoggerFactory.getLogger(getClass()); @DependenciesInitialize @ActiveReflection public ProductMediaRepositoryImpl(DependenciesContainerResolver containerResolver) { super(ProductMedia.class, containerResolver.getDependenciesResolver()); } @Override public ProductMedia loadMedia(int id) { Where idWhere = Where.builder().attribute(ProductMedia_.ID).value(id).operation(Operation.EQ).build(); SqlBuilder sqlBuilder = getSqlBuilder(); SqlSelect sqlSelect = sqlBuilder.from(getDomainClass()); SqlWhere sqlWhere = sqlSelect.where(idWhere); String query = sqlWhere.getNativeQuery(); Map<String, Object> attributes = QueryUtils.parse(sqlWhere.getQueryBindings()); return getSingleResult(query, attributes, getDomainClass()); } @Override public void saveMedia(ProductMedia productMedia) { save(productMedia); } @Override public void deleteMedia(String id) { try { int mediaId = Integer.parseInt(id); deleteById(mediaId); } catch (NumberFormatException e) { log.warn("Id [{}] is not a valid id", id); } } @Override public void deleteMedia(Product product) { Where productWhere = Where.builder().attribute(ProductMedia_.PRODUCT).value(product).operation(Operation.EQ).build(); SqlBuilder sqlBuilder = getSqlBuilder(); SqlSelect sqlSelect = sqlBuilder.from(getDomainClass()); SqlWhere sqlWhere = sqlSelect.where(productWhere); String query = sqlWhere.getNativeQuery(); Map<String, Object> attributes = QueryUtils.parse(sqlWhere.getQueryBindings()); ProductMedia productMedia = getSingleResult(query, attributes, getDomainClass()); delete(productMedia); } @Override public RepositoryBase getInstance(DependenciesContainerResolver containerResolver) { return new ProductMediaRepositoryImpl(containerResolver); } @Override public Class<?>[] getRepositoryTypes() { return new Class[]{ProductMediaRepository.class}; } }
#pragma once #if defined(STM32) #include "AudioPWM/PWMAudioBase.h" #include "AudioTimer/AudioTimer.h" namespace audio_tools { // forward declaration class PWMAudioStreamSTM32; typedef PWMAudioStreamSTM32 PWMAudioStream; /** * @brief Audio output to PWM pins for STM32. We use one timer to generate the sample rate and * one timer for the PWM signal. * @author Phil Schatzmann * @copyright GPLv3 */ class PWMAudioStreamSTM32 : public PWMAudioStreamBase { /// @brief PWM information for a single pin struct PWMPin { HardwareTimer *p_timer; int channel; int max_value; bool active=false; int pin; int pwm_frequency; PWMPin() = default; PWMPin(HardwareTimer *p_timer, int channel, int pin, int maxValue, int pwmFrequency=30000){ this->p_timer = p_timer; this->channel = channel; this->pin = pin; this->max_value = maxValue; this->pwm_frequency = pwmFrequency; } void begin(){ TRACEI(); p_timer->setPWM(channel, pin, pwm_frequency, 50); // 30k Hertz, 50% dutycycle active = true; } void setRate(int rate){ if (active){ uint16_t sample = 100.0 * rate / max_value; p_timer->setCaptureCompare(channel, sample, PERCENT_COMPARE_FORMAT); // 50% } } }; class PWM { public: PWM() = default; void begin(HardwareTimer *pwm_timer, int pwm_frequency, int maxValue){ this->p_timer = pwm_timer; this->pwm_frequency = pwm_frequency; this->max_value = maxValue; } void end() { p_timer->pause(); } bool addPin(int pin){ LOGI("addPin: %d", pin); TIM_TypeDef *p_instance = (TIM_TypeDef *)pinmap_peripheral(digitalPinToPinName(pin), PinMap_PWM); channel = STM_PIN_CHANNEL(pinmap_function(digitalPinToPinName(pin), PinMap_PWM)); PWMPin pwm_pin{p_timer, channel, pin, max_value, pwm_frequency}; pins.push_back(pwm_pin); // make sure that all pins use the same timer ! if (p_timer->getHandle()->Instance!=p_instance){ LOGE("Invalid pin %d with timer %s for timer %s",pin, getTimerStr(p_instance), getTimerStr(p_timer->getHandle()->Instance)); return false; } LOGI("Using Timer %s for PWM",getTimerStr(p_instance)); pins[pins.size()-1].begin(); return true; } void setRate(int idx, int rate){ if (idx < pins.size()){ pins[idx].setRate(rate); } else { LOGE("Invalid index: %d", idx); } } protected: HardwareTimer *p_timer; Vector<PWMPin> pins; int channel; int max_value; int pwm_frequency; const char* getTimerStr(TIM_TypeDef* inst){ if (inst==TIM1) return "TIM1"; else if (inst==TIM2) return "TIM2"; else if (inst==TIM3) return "TIM3"; else if (inst==TIM4) return "TIM4"; else if (inst==TIM5) return "TIM5"; return "N/A"; } }; public: PWMAudioStreamSTM32(){ LOGD("PWMAudioStreamSTM32"); } // Ends the output virtual void end() override { TRACED(); ticker.end(); // it does not hurt to call this even if it has not been started pwm.end(); // stop pwm timer is_timer_started = false; if (buffer!=nullptr){ delete buffer; buffer = nullptr; } } /// Defines the timer which is used to generate the PWM signal void setPWMTimer(HardwareTimer &t){ p_pwm_timer = &t; } protected: TimerAlarmRepeating ticker{DirectTimerCallback, PWM_FREQ_TIMER_NO}; // calls a callback repeatedly with a timeout HardwareTimer *p_pwm_timer=nullptr; PWM pwm; int64_t max_value; /// when we get the first write -> we activate the timer to start with the output of data virtual void startTimer() override { if (!is_timer_started){ TRACED(); uint32_t time = AudioUtils::toTimeUs(audio_config.sample_rate); ticker.setCallbackParameter(this); ticker.begin(defaultPWMAudioOutputCallback, time, US); is_timer_started = true; } } /// Setup PWM Pins virtual void setupPWM(){ TRACED(); // setup pwm timer if (p_pwm_timer==nullptr){ p_pwm_timer = new HardwareTimer(PWM_DEFAULT_TIMER); } // setup pins for output int ch = 0; pwm.begin(p_pwm_timer, audio_config.pwm_frequency, maxOutputValue()); for (auto gpio : audio_config.pins()){ LOGD("Processing channel %d -> pin: %d", ch++, gpio); pwm.addPin(gpio); } } virtual void setupTimer() { } /// One timer supports max 4 output pins virtual int maxChannels() { return 4; }; /// provides the max value for the configured resulution virtual int maxOutputValue(){ return 10000; } /// write a pwm value to the indicated channel. The max value depends on the resolution virtual void pwmWrite(int channel, int value){ //analogWrite(pins[channel], value); pwm.setRate(channel, value); } /// timer callback: write the next frame to the pins static inline void defaultPWMAudioOutputCallback(void *obj) { PWMAudioStreamSTM32* accessAudioPWM = (PWMAudioStreamSTM32*) obj; if (accessAudioPWM!=nullptr){ accessAudioPWM->playNextFrame(); } } }; } // Namespace #endif
package org.zoo.modelo.animal; import org.zoo.modelo.MenuItem; import org.zoo.modelo.habitat.Habitat; import org.zoo.modelo.Sprite; import org.zoo.utilities.ZooPoint; /** * Enumeracion que contiene informacion de los animales que contiene el programa, * cada elemento de la enumeración hace referencia a un <code>Animal</code> en especifico. */ public enum EnumAnimal implements MenuItem { CAT("Gato", Cat.class, Sprite.CAT_IDLE, "/animal/cat/CatIdle1.png"), ELEPHANT("Elefante", Elephant.class, Sprite.ELEPHANT_IDLE, "/animal/elephant/ElephantIdle1.png"), LION("León", Lion.class, Sprite.LION_IDLE, "/animal/lion/LionIdle1.png"), MONKEY("Mono", Monkey.class, Sprite.MONKEY_IDLE, "/animal/monkey/MonkeyIdle.png"), PANDA("Panda", Panda.class, Sprite.PANDA_IDLE, "/animal/panda/PandaIdle.png"), PENGUIN("Pingüino", Penguin.class, Sprite.PENGUIN_IDLE, "/animal/penguin/PenguinIdle.png"); /** * Nombre del <code>Animal</code>, util para imprimirlo al usuario */ private final String nombre; /** * Clase que modela al <code>Animal</code> */ private final Class<?> tipo; /** * Sprite representativo del <code>Animal</code> */ private final Sprite sprite; /** * Ruta del archivo que contiene una imagen portada del <code>Animal</code> */ private final String labelPath; EnumAnimal(String nombre, Class<?> tipo, Sprite sprite, String labelPath) { this.nombre = nombre; this.tipo = tipo; this.sprite = sprite; this.labelPath = labelPath; } /** * Permite obtener la clase que modela al <code>Animal</code> * @return Clase que modela al <code>Animal</code> */ public Class<?> getTipo() { return tipo; } /** * Permite obtener el nombre del <code>Animal</code> * @return String del nombre del <code>Animal</code> */ public String getNombre() { return nombre; } /** * Permite obtener el sprite representativo del <code>Animal</code> en el juego * @return Sprite representativo del <code>Animal</code> */ @Override public Sprite getInGameSprite() { return sprite; } /** * Permite obtener la ruta del archivo que contiene una imagen portada del <code>Animal</code> * @return String que contiene una ruta de archivo */ public String getLabelPath() { return labelPath; } /** * Permite crear una instancia del <code>Animal</code> referenciado en el elemento de la enumaración * @param habitat Habitat que va a contener al <code>Animal</code> * @param point Punto del habitat donde se va a crear el <code>Animal</code> * @return Instancia de <code>Animal</code> creada */ public Animal newInstance(Habitat habitat, ZooPoint point) { Animal animal = null; try { animal = (Animal) tipo.getDeclaredConstructor(Habitat.class, ZooPoint.class).newInstance(habitat, point); } catch (Exception e) { e.printStackTrace(); } return animal; } }
# TheBook.co.il Project Setup Guide Welcome to the setup guide for TheBook.co.il project. This guide will help you get your development environment ready in a few simple steps. ## 📋 Prerequisites - A system capable of running Python (Windows, macOS, Linux). - Git for version control. ## 🛠️ Installation Steps ### 1️⃣ Install Python 3.11.4 1. Visit the [official Python website](https://www.python.org/downloads/). 2. Download and install **Python 3.11.4**. 3. To verify the installation, open a terminal or command prompt and run: `python3 --version` You should see `Python 3.11.4`. ### 2️⃣ Clone the Repository Clone the project from GitHub: `git clone https://github.com/RuslanKovalyov/TheBook.git` and navigate to the project directory: `cd TheBook` ### 3️⃣ Create a Virtual Environment Using the `venv` module, set up a virtual environment: `python3.11 -m venv venv` This command creates a new virtual environment named `venv`. ### 4️⃣ Activate the Virtual Environment - On **macOS and Linux**: `source venv/bin/activate` ### 5️⃣ Install Required Packages Install the necessary packages: `pip install --upgrade pip` `pip install -r requirements.txt` This command will install Django 4.2.4 and any other dependencies. ### 6️⃣ Begin Development You're all set! Start your development, run migrations, or launch the Django development server. ### 7️⃣ Deactivate the Virtual Environment When you're done with your development tasks, you can deactivate the virtual environment: `deactivate`
/* * Luisalberto Castaneda * 12/07/2021 * ITSE 1430 */ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Nile { /// <summary>Represents a product.</summary> public class Product : IValidatableObject { /// <summary>Gets or sets the unique identifier.</summary> public int Id { get; set; } /// <summary>Gets or sets the name.</summary> /// <value>Never returns null.</value> public string Name { get { return _name ?? ""; } set { _name = value?.Trim(); } } /// <summary>Gets or sets the description.</summary> public string Description { get { return _description ?? ""; } set { _description = value?.Trim(); } } /// <summary>Gets or sets the price.</summary> public decimal Price { get; set; } = 0; /// <summary>Determines if discontinued.</summary> public bool IsDiscontinued { get; set; } public override string ToString() { return Name; } public IEnumerable<ValidationResult> Validate ( ValidationContext validationContext ) { var errors = new List<ValidationResult>(); if (Id < 0) errors.Add(new ValidationResult("Id must be greater than or equal to 0", new[] { nameof(Id) })); if (String.IsNullOrEmpty(Name)) errors.Add(new ValidationResult("Name is required", new[] { nameof(Name) })); if (Price < 0) errors.Add(new ValidationResult("Price must be greater than or equal to 0", new[] { nameof(Price) })); return errors; } #region Private Members private string _name; private string _description; #endregion } }
import { Component } from "react" import ReactDOM from "react-dom" const portalRoot = typeof document !== `undefined` ? document.getElementById("portal") : null export default class Portal extends Component { el: any constructor(props: any) { super(props) this.el = typeof document !== `undefined` ? document.createElement("div") : null } componentDidMount = () => { portalRoot ? portalRoot.appendChild(this.el) : null } componentWillUnmount = () => { portalRoot ? portalRoot.removeChild(this.el) : null } render() { const { children } = this.props if (this.el) { return ReactDOM.createPortal(children, this.el) } else { return null } } }
<html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous" /> <link rel="stylesheet" type="text/css" href="/css/style.css" /> <title>MVP Techblog</title> </head> <body> <nav class="navbar border rounded navbar-expand-lg"> <div class="container-fluid"> <a class="navbar-brand" href="/">The Tech Blog</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/">Home</a> </li> {{#if loggedIn}} <li class="nav-item"> <a class="nav-link" id="logout"href="/api/users/logout">Logout</a> </li> <li class="nav-item"> <a class="nav-link" href="/dashboard">Dashboard</a> </li> {{else}} <li class="nav-item"> <a class="nav-link" href="/login">Login</a> </li> {{/if}} </ul> </div> </div> </nav> {{{body}}} {{#if loggedIn}} <script src="/js/logout.js"></script> {{/if}} <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous" ></script> </body> </html>
import React, { useCallback, useEffect } from "react"; import { Row, Col, Anchor, Form as BootstrapForm } from "react-bootstrap"; import { Field, Form } from "react-final-form"; import { LinkContainer } from "react-router-bootstrap"; import TextField from "../../components/TextField"; import { useSearchParams } from "react-router-dom"; import { RequestPasswordResetRequest, useRequestPasswordResetMutation } from "../api/authSlice"; import LoadingButton from "../../components/LoadingButton"; import { RootState } from "../../app/store"; import { ConnectedProps, connect } from "react-redux"; import { setResult, reset } from "./requestPasswordResetSlice"; import { ErrorCode } from "../api/apiSlice"; const mapStateToProps = (state: RootState) => ({ result: state.requestPasswordReset.result, }); const mapDispatchToProps = { setResult, reset, }; const connector = connect(mapStateToProps, mapDispatchToProps); type PropsFromRedux = ConnectedProps<typeof connector>; const RequestPasswordReset: React.FC<PropsFromRedux> = props => { const { result, setResult, reset, } = props; const [searchParams] = useSearchParams(); const [requestPasswordReset, { isLoading, }] = useRequestPasswordResetMutation(); const onSubmit = useCallback(async (values: Record<string, any>) => { const request: RequestPasswordResetRequest = { phoneNumber: values.phoneNumber, }; const response = await requestPasswordReset(request).unwrap(); setResult({ isRequested: response.succeeded, error: response.errorCode, }); }, [requestPasswordReset, setResult]); useEffect(() => { return () => { reset(); }; }, [reset]); return ( <Form onSubmit={onSubmit} render={({ handleSubmit }) => ( <BootstrapForm onSubmit={handleSubmit}> <Row> <Col md={{offset: 2, span: 8}} lg={{offset: 3, span: 6}} xxl={{offset: 4, span: 4}}> <h2 className="mb-3">Відновлення паролю</h2> <Field id="phoneNumber" name="phoneNumber" type="tel" pattern="\+380[0-9]{9}" placeholder="Номер телефону" className="mb-2" required={true} disabled={result?.isRequested} component={TextField} /> <div className="d-flex flex-column mt-2"> <LoadingButton type="submit" className="mt-2 fw-semibold" variant="primary" isLoading={isLoading} disabled={result?.isRequested}> Продовжити </LoadingButton> <LinkContainer to={{ pathname: "/auth/signIn", search: searchParams.toString(), }}> <Anchor className="text-muted align-self-center text-decoration-none mt-1"> Увійти </Anchor> </LinkContainer> </div> {result?.isRequested && ( <div className="lh-1 text-center mt-2"> <BootstrapForm.Text className="text-success">Посилання на відновлення паролю було відправлено у месенджери, прив'язані до вказаного номера</BootstrapForm.Text> </div> )} {result?.error === ErrorCode.UserNotFound && ( <BootstrapForm.Text className="text-danger">Користувача із вказаним номером телефону не знайдено</BootstrapForm.Text> )} </Col> </Row> </BootstrapForm> )} /> ); }; export default connector(RequestPasswordReset);
package leetcode.easy; public class BestTimeToBuyAndSellAStock { public static int maxProfit(int[] prices) { int buy_price = prices[0]; int profit = 0; for(int i=1; i < prices.length; i++) { if (prices[i] < buy_price) { buy_price = prices[i]; } profit = Math.max(profit, prices[i] - buy_price); } return profit; } // Two Pointer Approach public static int maxProfit2(int[] prices) { int left = 0; // Buy Price int right = 1; // Sell Price int profit = 0; while(right < prices.length) { if(prices[left] < prices[right]) { profit = Math.max(profit, prices[right] - prices[left]); } else { left = right; } right++; } return profit; } }
import mongoose from "mongoose"; const ReportedSchema = new mongoose.Schema({ gameID: { type: mongoose.Schema.Types.ObjectId, ref: "Game", }, templateID: { type: mongoose.Schema.Types.ObjectId, ref: "Template", }, submittingUserID: { type: mongoose.Schema.Types.ObjectId, ref: "Submitting User", required: [true, "Reference to the submitting user is required"] }, reportedUserID: { type: mongoose.Schema.Types.ObjectId, ref: "Reported User", }, reason: { type: String, required: [true, "Reason for the report is required"], maxlength: [500, "Limit reason to 500 characters"] }, additionalComments: { type: String, maxlength: [1000, "Limit additional comments to 1000 characters"] }, status: { type: String, enum: ["Pending", "Reviewed", "Resolved"], default: "Pending" }, reviewedBy: { type: mongoose.Schema.Types.ObjectId, ref: "User" }, resolutionComments: { type: String, maxlength: [1000, "Limit resolution comments to 1000 characters"] } }, { timestamps: true }); const Reported = mongoose.model("Reported", ReportedSchema); export default Reported;
<?php class waContactsCollection { protected $hash; protected $order_by; protected $group_by; protected $where; protected $where_fields = array(); protected $joins; protected $title = ''; protected $count; protected $options = array( 'check_rights' => false ); protected $update_count; protected $post_fields; protected $prepared; protected $alias_index = array(); protected $models; /** * Constructor for collection of contacts * * @param string $hash - search hash * @param array $options * @example * All contacts where name contains John * $collection = new contactsCollection('/search/name*=John/'); * * All contacts in the list with id 100500 * $collection = new contactsCollection('/list/100500/'); * * Contacts with ids from list * $collection = new contactsCollection('/id/1,10,100,500/'); * or * $collection = new contactsCollection('/search/id=1,10,100,500/'); * * All contacts * $collection = new contactsCollection(); */ public function __construct($hash = '', $options = array()) { foreach ($options as $k => $v) { $this->options[$k] = $v; } $this->setHash($hash); } protected function setHash($hash) { if (is_array($hash)) { $hash = '/id/'.implode(',', $hash); } if (substr($hash, 0, 1) == '#') { $hash = substr($hash, 1); } $this->hash = trim($hash, '/'); if (substr($this->hash, 0 ,9) == 'contacts/') { $this->hash = substr($this->hash, 9); } if ($this->hash == 'all') { $this->hash = ''; } $this->hash = explode('/', $this->hash); } /** * Returns count of the all contacts in collection * * @return int */ public function count() { if ($this->count === null) { $sql = $this->getSQL(); $sql = "SELECT COUNT(".($this->joins ? 'DISTINCT ' : '')."c.id) ".$sql; $this->count = (int)$this->getModel()->query($sql)->fetchField(); if ($this->update_count && $this->count != $this->update_count['count']) { $this->update_count['model']->updateCount($this->update_count['id'], $this->count); } } return $this->count; } public function getTitle() { if ($this->title === null) { $this->prepare(); } return $this->title; } protected function getFields($fields) { $contact_model = $this->getModel(); if ($fields == '*') { $fields = $contact_model->getMetadata(); unset($fields['password']); $fields = array_keys($fields); $this->post_fields['_internal'] = array('_online_status'); $this->post_fields['email'] = array('email'); $this->post_fields['data'] = array(); return 'c.'.implode(",c.", $fields); } $required_fields = array('id' => 'c'); // field => table, to be added later in any case if (!is_array($fields)) { $fields = explode(",", $fields); } // Add required fields to select and delete fields for getting data after query foreach ($fields as $i => $f) { if (!$contact_model->fieldExists($f)) { if ($f == 'email') { $this->post_fields['email'][] = $f; } elseif ($f == '_online_status') { $required_fields['last_datetime'] = 'c'; $required_fields['login'] = 'c'; $this->post_fields['_internal'][] = $f; } elseif ($f == '_access') { $this->post_fields['_internal'][] = $f; } elseif ($f == 'photo_url' || substr($f, 0, 10) == 'photo_url_') { $required_fields['photo'] = 'c'; $this->post_fields['_internal'][] = $f; } else { $this->post_fields['data'][] = $f; } unset($fields[$i]); continue; } if (isset($required_fields[$f])) { $fields[$i] = ($required_fields[$f] ? $required_fields[$f]."." : '').$f; unset($required_fields[$f]); } } foreach ($required_fields as $field => $table) { $fields[] = ($table ? $table."." : '').$field; } return implode(",", $fields); } /** * Get data for contacts in this collection. * @param string|array $fields * @param int $offset * @param int $limit * @return array [contact_id][field] = field value in appropriate field format * @throws waException */ public function getContacts($fields = "id", $offset = 0, $limit = 50) { $sql = "SELECT ".($this->joins ? 'DISTINCT ' : '').$this->getFields($fields)." ".$this->getSQL(); $sql .= $this->getGroupBy(); $sql .= $this->getOrderBy(); $sql .= " LIMIT ".($offset ? $offset.',' : '').(int)$limit; //header("X-SQL: ".str_replace("\n", " ", $sql)); $data = $this->getModel()->query($sql)->fetchAll('id'); $ids = array_keys($data); // // Load fields from other storages // if ($ids && $this->post_fields) { // $fill[table][field] = null // needed for all rows to always contain all apropriate keys // in case when we're asked to load all fields from that table $fill = array_fill_keys(array_keys($this->post_fields), array()); foreach (waContactFields::getAll('enabled') as $fid => $field) { /** * @var waContactField $field */ $fill[$field->getStorage(true)][$fid] = false; } foreach ($this->post_fields as $table => $fields) { if ($table == '_internal') { foreach ($fields as $f) { /** * @var $f string */ if ($f == 'photo_url' || substr($f, 0, 10) == 'photo_url_') { if ($f == 'photo_url') { $size = null; } else { $size = substr($f, 10); } foreach ($data as $id => &$v) { $v[$f] = waContact::getPhotoUrl($id, $v['photo'], $size); } unset($v); } else { switch($f) { case '_online_status': foreach($data as &$v) { $v['_online_status'] = waUser::getStatusByInfo($v); } unset($v); break; case '_access': $rm = new waContactRightsModel(); $accessStatus = $rm->getAccessStatus($ids); foreach($data as $id => &$v) { if (!isset($accessStatus[$id])) { $v['_access'] = ''; continue; } $v['_access'] = $accessStatus[$id]; } unset($v); break; default: throw new waException('Unknown internal field: '.$f); } } } continue; } $data_fields = $fields; foreach ($data_fields as $k => $field_id) { $f = waContactFields::get($field_id); if ($f && $f instanceof waContactCompositeField) { unset($data_fields[$k]); $data_fields = array_merge($data_fields, $f->getField()); } } $model = $this->getModel($table); $post_data = $model->getData($ids, $data_fields); foreach ($post_data as $contact_id => $contact_data) { foreach ($contact_data as $field_id => $value) { if (!($f = waContactFields::get($field_id))) { continue; } if (!$f->isMulti()) { $post_data[$contact_id][$field_id] = isset($value[0]['data']) ? $value[0]['data'] : $value[0]['value']; } } } if ($fields) { $fill[$table] = array_fill_keys($fields, ''); } else if (!isset($fill[$table])) { $fill[$table] = array(); } foreach ($data as $contact_id => $v) { if (isset($post_data[$contact_id])) { $data[$contact_id] += $post_data[$contact_id]; } $data[$contact_id] += $fill[$table]; } } } return $data; } protected function prepare($new = false, $auto_title = true) { if (!$this->prepared || $new) { $type = $this->hash[0]; if ($type) { $method = strtolower($type).'Prepare'; if (method_exists($this, $method)) { $this->$method(isset($this->hash[1]) ? $this->hash[1] : '', $auto_title); } } elseif ($auto_title) { $this->addTitle(_ws('All contacts')); } if ($this->prepared) { return; } $this->prepared = true; if ($this->options['check_rights'] && !wa()->getUser()->getRights('contacts', 'category.all')) { // Add user rights $group_ids = waSystem::getInstance()->getUser()->getGroups(); $group_ids[] = 0; $group_ids[] = -waSystem::getInstance()->getUser()->getId(); $this->joins[] = array( 'table' => 'wa_contact_categories', 'alias' => 'cc', ); $this->joins[] = array( 'table' => 'contacts_rights', 'alias' => 'r', 'on' => 'r.category_id = cc.category_id AND r.group_id IN ('.implode(",", $group_ids).')' ); } } } protected function idPrepare($ids) { $ids = explode(',', $ids); foreach ($ids as $k => $v) { $v = (int)$v; if ($v) { $ids[$k] = $v; } else { unset($ids[$k]); } } if ($ids) { $this->where[] = "c.id IN (".implode(",", $ids).")"; } } protected function searchPrepare($query, $auto_title = true) { if ($auto_title || !isset($this->alias_index['data'])) { $this->alias_index['data'] = 0; } $query = urldecode($query); // `&` can be escaped in search request. Need to split by not escaped ones only. $escapedBS = 'ESCAPED_BACKSLASH'; while(FALSE !== strpos($query, $escapedBS)) { $escapedBS .= rand(0, 9); } $escapedAmp = 'ESCAPED_AMPERSAND'; while(FALSE !== strpos($query, $escapedAmp)) { $escapedAmp .= rand(0, 9); } $query = str_replace('\\&', $escapedAmp, str_replace('\\\\', $escapedBS, $query)); $query = explode('&', $query); $model = $this->getModel(); $title = array(); foreach ($query as $part) { if (! ( $part = trim($part))) { continue; } $part = str_replace(array($escapedBS, $escapedAmp), array('\\\\', '\\&'), $part); $parts = preg_split("/(\\\$=|\^=|\*=|==|!=|>=|<=|=|>|<|@=)/uis", $part, 2, PREG_SPLIT_DELIM_CAPTURE); if ($parts) { if ($parts[0] == 'email') { if (!isset($this->joins['email'])) { $this->joins['email'] = array( 'table' => 'wa_contact_emails', 'alias' => 'e' ); } $title[] = waContactFields::get($parts[0])->getName().$parts[1].$parts[2]; $this->where[] = 'e.email'.$this->getExpression($parts[1], $parts[2]); } elseif ($model->fieldExists($parts[0])) { if ($f = waContactFields::get($parts[0])) { $title[] = $f->getName().$parts[1].$parts[2]; } else { $title[] = $parts[0].$parts[1].$parts[2]; } $this->where[] = 'c.'.$parts[0].$this->getExpression($parts[1], $parts[2]); } else if ($parts[0] == 'category') { if (!isset($this->joins['categories'])) { $this->joins['categories'] = array( 'table' => 'wa_contact_categories', 'alias' => 'cc' ); } $title[] = _ws('Category').$parts[1].$parts[2]; $this->where[] = 'cc.category_id'.$this->getExpression($parts[1], $parts[2]); } else { $alias = "d".($this->alias_index['data']++); $field_parts = explode('.', $parts[0]); $f = $field_parts[0]; if ($fo = waContactFields::get($f)) { $title[] = $fo->getName().$parts[1].$parts[2]; } $ext = isset($field_parts[1]) ? $field_parts[1] : null; $on = $alias.'.contact_id = c.id AND '.$alias.".field = '".$model->escape($f)."'"; $on .= ' AND '.$alias.".value ".$this->getExpression($parts[1], $parts[2]); if ($ext !== null) { $on .= " AND ".$alias.".ext = '".$model->escape($ext)."'"; } $this->joins[] = array( 'table' => 'wa_contact_data', 'alias' => $alias, 'on' => $on ); $this->where_fields[] = $f; } } } if ($title) { $title = implode(', ', $title); // Strip slashes from search title. $bs = '\\\\'; $title = preg_replace("~{$bs}(_|%|&|{$bs})~", '\1', $title); } if ($auto_title) { $this->addTitle($title, ' '); } } public function addTitle($title, $delim = ', ') { if (!$title) { return; } if ($this->title) { $this->title .= $delim; } $this->title .= $title; } public function getWhereFields() { return $this->where_fields; } protected function categoryPrepare($id) { $category_model = new waContactCategoryModel(); $category = $category_model->getById($id); if ($category) { $this->title = $category['name']; $this->update_count = array( 'model' => $category_model, 'id' => $id, 'count' => isset($category['cnt']) ? $category['cnt'] : 0 ); } $this->joins[] = array( 'table' => 'wa_contact_categories', 'alias' => 'ct', ); $this->where[] = "ct.category_id = ".(int)$id; } protected function usersPrepare($params, $auto_title = true) { $this->where[] = 'c.is_user = 1'; if ($auto_title) { $this->addTitle(_ws('All users')); } } /** * Add joins and conditions for hash /group/$group_id * @param int $id */ protected function groupPrepare($id) { $group_model = new waGroupModel(); $group = $group_model->getById($id); if ($group) { $this->title = $group['name']; $this->update_count = array( 'model' => $group_model, 'id' => $id, 'count' => isset($group['cnt']) ? $group['cnt'] : 0 ); } $this->joins[] = array( 'table' => 'wa_user_groups', 'alias' => 'cg', ); $this->where[] = "cg.group_id = ".(int)$id; } /** * Returns ORDER BY clause * @return string */ protected function getOrderBy() { if ($this->order_by) { return " ORDER BY ".$this->order_by; } else { return ""; } } /** * Returns GROUP BY clause * @return string */ protected function getGroupBy() { if ($this->group_by) { return " GROUP BY ".$this->group_by; } else { return ""; } } /** * Returns contacts model * * @param string $type * @return waContactModel|waContactDataModel|waContactEmailsModel */ protected function getModel($type = null) { switch ($type) { case 'data': if (!isset($this->models[$type])) { $this->models[$type] = new waContactDataModel(); } return $this->models[$type]; case 'email': if (!isset($this->models[$type])) { $this->models[$type] = new waContactEmailsModel(); } return $this->models[$type]; default: $type = 'default'; if (!isset($this->models[$type])) { $this->models[$type] = new waContactModel(); } return $this->models[$type]; } } /** * Returns expression for SQL * * @param string $op - operand ==, >=, etc * @param string $value - value * @return string */ protected function getExpression($op, $value) { $model = $this->getModel(); switch ($op) { case '>': case '>=': case '<': case '<=': case '!=': return " ".$op." '".$model->escape($value)."'"; case "^=": return " LIKE '".$model->escape($value)."%'"; case "$=": return " LIKE '%".$model->escape($value)."'"; case "*=": return " LIKE '%".$model->escape($value)."%'"; case '@=': $values = array(); foreach (explode(',', $value) as $v) { $values[] = "'".$model->escape($v)."'"; } return ' IN ('.implode(',', $values).')'; case "==": case "="; default: return " = '".$model->escape($value)."'"; } } public function getSQL($with_primary_email = false) { $this->prepare(); $sql = "FROM wa_contact c"; if ($this->joins) { foreach ($this->joins as $join) { $alias = isset($join['alias']) ? $join['alias'] : ''; if (isset($join['on'])) { $on = $join['on']; } else { $on = "c.id = ".($alias ? $alias : $join['table']).".contact_id"; } $sql .= (isset($join['type']) ? " ".$join['type'] : '')." JOIN ".$join['table']." ".$alias." ON ".$on; } } if ($with_primary_email) { $sql .= " JOIN wa_contact_emails _e ON c.id = _e.contact_id"; } if ($this->where) { $where = $this->where; if ($with_primary_email) { $where[] = "_e.sort = 0"; } $sql .= " WHERE ".implode(" AND ", $where); } return $sql; } /** * Save requested fields of the collection in temporary table * * @param string $table - name of the temporary table * @param string $fields - fields for select * @param bool $ignore * @return bool - result */ public function saveToTable($table, $fields = 'id', $ignore = false) { if (!is_array($fields)) { $fields = explode(",", $fields); $fields = array_map("trim", $fields); } $primary_email = false; $insert_fields = $select_fields = array(); foreach ($fields as $k => $v) { if (is_numeric($k)) { $insert_fields[] = $v; $select_fields[] = "c.".$v; } else { $insert_fields[] = $k; if (strpos($v, '.') !== false || is_numeric($v)) { $select_fields[] = $v; } else { if ($v == '_email') { $select_fields[] = "_e.email"; $primary_email = true; } else { $select_fields[] = "c.".$v; } } } } $sql = "INSERT ".($ignore ? "IGNORE " : "")."INTO ".$table." (".implode(",", $insert_fields).") SELECT DISTINCT ".implode(",", $select_fields)." ".$this->getSQL($primary_email).$this->getOrderBy(); return $this->getModel()->exec($sql); } /** * Set order by clause for select * * @param string $field * @param string $order * @return string */ public function orderBy($field, $order = 'ASC') { if (strtolower(trim($order)) == 'desc') { $order = 'DESC'; } else { $order = 'ASC'; } $field = trim($field); if ($field == '~data') { $this->joins[] = array( 'table' => 'wa_contact_data', 'alias' => 'd', 'type' => 'LEFT' ); $this->group_by = 'c.id'; return $this->order_by = 'count(*) '.$order; } else if ($field) { $contact_model = $this->getModel(); if ($contact_model->fieldExists($field)) { return $this->order_by = $field." ".$order; } } return ''; } }
--- sidebar: sidebar permalink: use/manage.html keywords: disaster recovery, bluexp disaster recovery, failover, failback, replicate, fail over, fail back, vmware, vcenter summary: NetApp BlueXP Disaster Recovery ist ein Cloud-basierter Disaster Recovery Service, der Disaster Recovery Workflows automatisiert. --- = Verwalten von Standorten, Plänen, Datastores und Informationen zu virtuellen Maschinen :hardbreaks: :allow-uri-read: :icons: font :imagesdir: ../media/use/ [role="lead"] Sie erhalten einen schnellen Überblick über alle Disaster Recovery-Ressourcen oder sehen sich die einzelnen Ressourcen im Detail an: * Standorte * Replizierungspläne * Datenspeicher * Virtual Machines * Ressourcengruppen == VCenter-Sites verwalten Sie können den vCenter-Standortnamen und den Standorttyp (On-Premises oder AWS) bearbeiten. .Schritte . Wählen Sie im oberen Menü *Sites* aus. . Wählen Sie die Option *actions* image:../use/icon-horizontal-dots.png["Actions-Menü-Symbol im BlueXP Disaster Recovery Service"] Rechts neben dem vCenter-Namen und wählen Sie *Bearbeiten*. . Bearbeiten Sie den Namen und den Speicherort des vCenter-Standorts. == Verwalten von Replikationsplänen Sie können Replikationspläne deaktivieren, aktivieren und löschen. * Wenn Sie einen Replikationsplan vorübergehend anhalten möchten, können Sie ihn deaktivieren und später aktivieren. * Wenn Sie den Plan nicht mehr benötigen, können Sie ihn löschen. .Schritte . Wählen Sie im oberen Menü *Replikationspläne* aus. . Um die Plandetails anzuzeigen, wählen Sie die Option *actions* image:../use/icon-horizontal-dots.png["Actions-Menü-Symbol im BlueXP Disaster Recovery Service"] Und wählen Sie *Plandetails anzeigen*. . Führen Sie einen der folgenden Schritte aus: + ** Um die Plandetails zu bearbeiten (Wiederholung ändern), wählen Sie die Registerkarte *Plandetails* und wählen Sie das Symbol *Bearbeiten* rechts. ** Um die Ressourcenzuordnungen zu bearbeiten, wählen Sie die Registerkarte *Failover Mapping* und wählen Sie das Symbol *Bearbeiten*. ** Um die virtuellen Maschinen hinzuzufügen oder zu bearbeiten, wählen Sie die Registerkarte *Virtuelle Maschine* und wählen Sie das *Bearbeiten*-Symbol. . Kehren Sie zur Liste der Pläne zurück, indem Sie in den Semmelbröseln oben links „Replikationspläne“ auswählen. . Um Aktionen mit dem Plan auszuführen, wählen Sie aus der Liste der Replikationspläne die Option *actions* aus image:../use/icon-horizontal-dots.png["Actions-Menü-Symbol im BlueXP Disaster Recovery Service"] Rechts neben dem Plan und wählen Sie eine der Optionen aus, wie z. B. *Zeitpläne bearbeiten*, *Failover testen*, *Failover*, *Failback*, *Deaktivieren*, *enable*, oder *Delete*. == Anzeigen von Datenspeicherinformationen Sie können Informationen darüber anzeigen, wie viele Datastores auf der Quelle und auf dem Ziel vorhanden sind. . Wählen Sie im oberen Menü *Dashboard*. . Wählen Sie das vCenter in der Standortzeile aus. . Wählen Sie *Datastores*. . Anzeigen der Datenspeicherinformationen. == Zeigen Sie Informationen zu virtuellen Maschinen an Sie können Informationen darüber anzeigen, wie viele virtuelle Maschinen auf der Quelle und auf dem Ziel zusammen mit CPU, Arbeitsspeicher und verfügbarer Kapazität vorhanden sind. . Wählen Sie im oberen Menü *Dashboard*. . Wählen Sie das vCenter in der Standortzeile aus. . Wählen Sie *Virtuelle Maschinen*. . Zeigen Sie die Informationen zu virtuellen Maschinen an. == Verwalten von Ressourcengruppen Sie können zwar eine Ressourcengruppe als Teil des Erstellens eines Replikationsplans hinzufügen, jedoch ist es möglicherweise bequemer, die Gruppen separat hinzuzufügen und später diese Gruppen im Plan zu verwenden. Sie können auch Ressourcengruppen bearbeiten und löschen. .Schritte . Wählen Sie im oberen Menü *Ressourcengruppen* aus. . Um eine Ressourcengruppe hinzuzufügen, wählen Sie *Gruppe hinzufügen*. . Um Aktionen mit der Ressourcengruppe durchzuführen, wählen Sie die Option *actions* aus image:../use/icon-horizontal-dots.png["Actions-Menü-Symbol im BlueXP Disaster Recovery Service"] Wählen Sie rechts eine der Optionen aus, wie z.B. *Ressourcengruppe bearbeiten* oder *Ressourcengruppe löschen*.
import { BrowserRouter, Routes, Route } from "react-router-dom"; import { AuthProvider } from "@/contexts/Auth"; import { ToastContainer } from "react-toastify"; import { PrivateRoute } from "./PrivateRoute"; import "react-toastify/dist/ReactToastify.min.css"; import HomePage from "./HomePage"; import Nav from "./Nav"; import ErrorPage from "@/features/ui/ErrorPage"; import ToBeContinued from "@/features/ui/ToBeContinued"; import RegisterClient from "./LogReg/Reg"; import Login from "./LogReg/Login"; import MyAccount from "./MyAccount"; import MyReservations from "./Reservations"; import City from "./City" import Locations from "./Locations"; import Restaurant from "./Restaurant"; import MyRestaurants from './Admin/MyRestaurants' import ResetPassword from "./MyAccount/ResetPasswd"; import EditReservationCl from "./Reservations/EditR"; import AddEditRestaurant from "./Admin/MyRestaurants/AddEdit"; export default function App() { return ( <BrowserRouter> <AuthProvider> <Nav /> <Routes> <Route path="/register" element={<RegisterClient />} /> <Route path="/login" element={<Login />} /> <Route path="/" element={<HomePage />} /> <Route path="/my-account" element={<PrivateRoute><MyAccount/></PrivateRoute>}/> <Route path="/my-account/passwordReset" element={<PrivateRoute><ResetPassword/></PrivateRoute>}/> <Route path='/reservations' element={<PrivateRoute><MyReservations/></PrivateRoute>} /> <Route path='/reservations/edit/:rsvId/:restaurantName' element={<PrivateRoute><EditReservationCl/></PrivateRoute>} /> <Route path='/city/:cityName' element={<City />} /> <Route path='/locations' element={<Locations />} /> <Route path='restaurant/:cityName/:restaurantSlug' element={<Restaurant />} /> <Route path='/admin/restaurants' element={<PrivateRoute allowedRoles={['admin','manager']}><MyRestaurants/></PrivateRoute>}/> <Route path='/admin/restaurants/addEdit/:id?' element={<PrivateRoute allowedRoles={['admin','manager']}><AddEditRestaurant/></PrivateRoute>}/> <Route path='/admin/restaurants/reservations/:id' element={<PrivateRoute allowedRoles={['admin','manager']}><ToBeContinued/></PrivateRoute>}/> <Route path='*' element={<ErrorPage error={404} shortMsg={'Not Found'}/>}/> </Routes> <footer className="h-60"> {''} </footer> <ToastContainer position="top-right" autoClose={5000} hideProgressBar={false} newestOnTop={false} closeOnClick rtl={false} pauseOnFocusLoss draggable theme="light" /> </AuthProvider> </BrowserRouter> ); }
<?php namespace App\Exports\Merchant; use App\User; use Platform\Models\History; use Illuminate\Support\Facades\Auth; use Maatwebsite\Excel\Concerns\Exportable; use Maatwebsite\Excel\Concerns\WithMapping; use Maatwebsite\Excel\Concerns\WithHeadings; use Maatwebsite\Excel\Concerns\FromCollection; use Maatwebsite\Excel\Concerns\ShouldAutoSize; class RewardHistoryExport implements ShouldAutoSize, FromCollection, WithHeadings, WithMapping { use Exportable; private User $user; public function __construct() { $this->user = User::query()->find(Auth::id()); } /** * @return \Illuminate\Support\Collection */ public function collection() { return History::withoutGlobalScopes() ->with([ 'customer:id,name', 'campaign:id,name', 'staff:id,name', 'reward:id,title' ]) ->where('created_by', $this->user->id) ->whereNotNull('reward_id') ->orderByDesc('created_at') ->get(); } public function headings(): array { return [ 'Website', 'Customer', 'Reward', 'Cost', 'Event', 'Staff', 'Date' ]; } public function map($row): array { return [ $row->campaign->name, $row->customer->name, $row->reward->title, abs((int) $row->points), $row->event, ($row->staff) ? $row->staff->name : null, $row->created_at->format('M d, Y H:i A') ]; } }
#include <iostream> #include <queue> #include <vector> using namespace std; template <typename T> class Node { public: T data; Node<T> *next; Node(T data) { this->data = data; this->next = NULL; } }; template <typename T> class BinaryTreeNode { public: T data; BinaryTreeNode<T> *left; BinaryTreeNode<T> *right; BinaryTreeNode(T data) { this->data = data; left = NULL; right = NULL; } }; BinaryTreeNode<int> *takeInput() { int rootData; cin >> rootData; if (rootData == -1) { return NULL; } BinaryTreeNode<int> *root = new BinaryTreeNode<int>(rootData); queue<BinaryTreeNode<int> *> q; q.push(root); while (!q.empty()) { BinaryTreeNode<int> *currentNode = q.front(); q.pop(); int leftChild, rightChild; cin >> leftChild; if (leftChild != -1) { BinaryTreeNode<int> *leftNode = new BinaryTreeNode<int>(leftChild); currentNode->left = leftNode; q.push(leftNode); } cin >> rightChild; if (rightChild != -1) { BinaryTreeNode<int> *rightNode = new BinaryTreeNode<int>(rightChild); currentNode->right = rightNode; q.push(rightNode); } } return root; } void print(Node<int> *head) { Node<int> *temp = head; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } cout << endl; } vector<Node<int> *> constructLinkedListForEachLevel(BinaryTreeNode<int> *root) { vector<Node<int> *> output; if (root == NULL) { return output; } queue<BinaryTreeNode<int> *> pendingNodes; pendingNodes.push(root); pendingNodes.push(NULL); Node<int> *currentHead = NULL; Node<int> *currentTail = NULL; while (pendingNodes.size() != 0) { BinaryTreeNode<int> *front = pendingNodes.front(); pendingNodes.pop(); if (front == NULL) { output.push_back(currentHead); currentHead = NULL; currentTail = NULL; if (!pendingNodes.empty()) { pendingNodes.push(NULL); } } else { Node<int>*newNode=new Node<int>(front->data); if(currentHead==NULL){ currentHead=newNode; currentTail=newNode; } else{ currentTail->next=newNode; currentTail=newNode; } if (front->left) { pendingNodes.push(front->left); } if (front->right) { pendingNodes.push(front->right); } } } return output; } int main() { BinaryTreeNode<int> *root = takeInput(); vector<Node<int> *> ans = constructLinkedListForEachLevel(root); for (int i = 0; i < ans.size(); i++) { print(ans[i]); } } // 5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1
## DESCRIPTION ## Statistics: Descriptive statistics ## ENDDESCRIPTION ## naw tagged this problem. ## DBsubject(Probability) ## DBchapter(Laws, theory) ## DBsection(Chebychev's inequality) ## Date(06/01/2005) ## Institution(UVA) ## Author(Nolan A. Wages) ## Level(2) ## TitleText1('Statistics for Management and Economics') ## AuthorText1('Keller, Warrack') ## EditionText1('6') ## Section1('.') ## Problem1('') ## KEYWORDS('statistics', 'descriptive statistics') DOCUMENT(); # This should be the first executable line in the problem. loadMacros( "PGstandard.pl", "PGchoicemacros.pl", "PGnumericalmacros.pl", "PGstatisticsmacros.pl", "PGcourse.pl" ); TEXT(beginproblem()); $showPartialCorrectAnswers = 0; install_problem_grader(~~&std_problem_grader); $mc[1] = new_multiple_choice(); $mc[1]->qa('Chebyshevs Theorem states that the percentage of measurements in a data set that fall within three standard deviations of their mean is: ', 'at least 89$PERCENT' ); $mc[1]->extra( '75$PERCENT', 'at least 75$PERCENT', '89$PERCENT' ); $mc[2] = new_multiple_choice(); $mc[2]->qa('The Empirical Rule states that the approximate percentage of measurements in a data set (providing that the data set has a bell-shaped distribution) that fall within two standard deviations of their mean is approximately:', '95$PERCENT' ); $mc[2]->extra( '68$PERCENT', '75$PERCENT', '99$PERCENT' ); $mc[3] = new_multiple_choice(); $mc[3]->qa('Which of the following summary measures is affected most by outliers?', 'The range' ); $mc[3]->extra( 'The median', 'The geometric mean', 'The interquartile range' ); $mc[3]->makeLast( 'All of the above' ); $mc[4] = new_multiple_choice(); $mc[4]->qa('Since the population is always larger than the sample, the population mean:', 'can be smaller than, larger than, or equal to the sample mean' ); $mc[4]->extra( 'is always larger than the sample mean', 'is always larger than or equal to the sample mean', 'is always smaller than the sample mean', 'is always smaller than or equal to the sample mean' ); $mc[5] = new_multiple_choice(); $mc[5]->qa('Which of the following summary measures cannot be easily approximated from a box-and-whisker plot?', 'The standard deviation' ); $mc[5]->extra( 'The range', 'The interquartile range', 'The second quartile' ); $mc[5]->makeLast( 'All of the above' ); $a = random(1,5,1); $b = random(1,5,1); while ($a == $b) { $b = random(1,5,1); } BEGIN_TEXT $PAR \{ $mc[$a]->print_q() \} \{ $mc[$a]->print_a() \} $PAR \{ $mc[$b]->print_q() \} \{ $mc[$b]->print_a() \} $PAR END_TEXT ANS(radio_cmp($mc[$a]->correct_ans)); ANS(radio_cmp($mc[$b]->correct_ans)); ENDDOCUMENT(); # This should be the last executable line in the problem.
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:party_radar/common/models.dart'; import 'package:party_radar/profile/tabs/friends_tab.dart'; import 'package:party_radar/profile/tabs/friendship_requests_tab.dart'; import 'package:party_radar/profile/tabs/posts_tab.dart'; import 'package:party_radar/common/services/friendship_service.dart'; import 'package:party_radar/common/services/post_service.dart'; class ProfileTabsWidget extends StatefulWidget { const ProfileTabsWidget( {super.key, required this.tabController, this.initialIndex = 0}); final TabController tabController; final int initialIndex; @override State<ProfileTabsWidget> createState() => _ProfileTabsWidgetState(); } class _ProfileTabsWidgetState extends State<ProfileTabsWidget> { static const _pageSize = 10; @override Widget build(BuildContext context) { return DefaultTabController( length: 3, initialIndex: 0, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ TabBar( controller: widget.tabController, tabs: [ Tab( child: FutureBuilder( future: PostService.getPostCount( FirebaseAuth.instance.currentUser?.displayName), builder: (context, snapshot) { return _getTabText( snapshot.hasData ? '${snapshot.data} ' : '', 'Post${snapshot.data == 1 ? '' : 's'}'); }), ), Tab( child: FutureBuilder( future: FriendshipService.getFriendshipsCount( FriendshipStatus.accepted), builder: (context, snapshot) { return _getTabText( snapshot.hasData ? '${snapshot.data} ' : '', 'Friend${snapshot.data == 1 ? '' : 's'}'); }, ), ), Tab( child: FutureBuilder( future: FriendshipService.getFriendshipsCount( FriendshipStatus.requested), builder: (context, snapshot) { return _getTabText( snapshot.hasData ? '${snapshot.data} ' : '', 'Request${snapshot.data == 1 ? '' : 's'}'); }, ), ), ], ), Flexible( child: TabBarView( controller: widget.tabController, physics: const BouncingScrollPhysics(), children: [ UserPostsTab(pageSize: _pageSize, onUpdate: () => _refresh()), FriendsTab(pageSize: _pageSize, onUpdate: () => _refresh()), FriendshipRequestsTab( pageSize: _pageSize, updateTabCounter: () => _refresh()), ], ), ), ], ), ); } void _refresh() { setState(() {}); } Row _getTabText(String value, String text) { return Row( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Text( value, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 18), ), Text( text, style: const TextStyle(fontSize: 18), ), ], ); } }
// // Copyright (C) 2006 Paul Lalonde enrg. // // This program is free software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the Free Software Foundation; // either version 2 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A // PARTICULAR PURPOSE. See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with this // program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, // Suite 330, Boston, MA 02111-1307 USA // #ifndef BFontPanel_H_ #define BFontPanel_H_ #pragma once // standard headers #include <string> // system headers #include <Carbon/Carbon.h> // library headers #include <boost/utility.hpp> // B headers #include "BEventTarget.h" namespace B { class FontPanel { public: static bool IsVisible(); static void Show(); static void Hide(); static void Toggle(); template <typename T> static void SetSelection( T inObj); template <typename T> static void SetSelection( ATSUStyle style, T inObj); template <typename T, typename ITER> static void SetSelection( ITER begin, ITER end, T inObj); static void ClearSelection(); static void ApplyFontSelectionToStyle( const Event<kEventClassFont, kEventFontSelection>& inEvent, ATSUStyle inStyle); private: static void PrivateSetSelection( const ATSUStyle* styles, size_t count, EventTargetRef inEventTargetRef); FontPanel(); }; // ------------------------------------------------------------------------------------------ template <typename T> inline void FontPanel::SetSelection( T inObj) { PrivateSetSelection(NULL, 0, EventTarget::GetEventTarget(inObj)); } // ------------------------------------------------------------------------------------------ template <typename T> inline void FontPanel::SetSelection( ATSUStyle style, T inObj) { PrivateSetSelection(&style, 1, EventTarget::GetEventTarget(inObj)); } // ------------------------------------------------------------------------------------------ template <typename T, typename ITER> inline void FontPanel::SetSelection( ITER begin, ITER end, T inObj) { EventTargetRef target = EventTarget::GetEventTarget(inObj); std::vector<ATSUStyle> styles(begin, end); if (!styles.empty()) PrivateSetSelection(&styles[0], styles.size(), target); else PrivateSetSelection(NULL, 0, target); } } // namespace B #endif // BFontPanel_H_