text
stringlengths
184
4.48M
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { INote } from '../models/note'; @Component({ selector: 'app-create-note', templateUrl: './create-note.component.html', styleUrls: ['./create-note.component.scss'], }) export class CreateNoteComponent implements OnInit { @Input() categories: { title: string; id: number }[] = []; @Input() noteToEdit?: INote; @Output() noteCreated = new EventEmitter<{ text: string; categoryId: number; }>(); @Output() noteEdited = new EventEmitter<{ noteId: number; text: string; categoryId: number; }>(); text: string = ''; categoryId: number | null = null; handleNote() { if (!this.text || !this.categoryId) return; if (this.noteToEdit) { this.noteEdited.emit({ noteId: this.noteToEdit.id, text: this.text, categoryId: +this.categoryId, }); } else { this.noteCreated.emit({ text: this.text, categoryId: +this.categoryId, }); } this.text = ''; this.categoryId = null; } isDisabled() { return !this.text || !this.categoryId; } ngOnInit(): void { this.text = this.noteToEdit?.text || ''; this.categoryId = this.noteToEdit?.category.id || null; } }
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Subscription } from 'rxjs'; import { ArticleQueryOption } from 'src/app/_model/article-list-config.model'; import { ArticleService } from 'src/app/_service/article.service'; import { AuthService } from 'src/app/_service/auth.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { tags: string[]; loading_tags = false; list_query_options: ArticleQueryOption; is_logged_in: boolean; authState_subscription: Subscription; constructor( private articleService: ArticleService, private authService: AuthService, private router: Router ) { this.tags = []; this.list_query_options = { type: 'all', option: {} } as ArticleQueryOption; } ngOnInit(): void { this.getAuthState(); this.getTags(); } getTags() { this.loading_tags = true; this.articleService.getTags().subscribe( res => { this.tags = res.tags; this.loading_tags = false; } ) } // get articles getArticles(type: string = '', options: Object = {}) { if (type === 'feed' && !this.is_logged_in) { this.router.navigate(['/login']); return; } this.list_query_options = { type: type, option: options } } // get auth state getAuthState() { this.authState_subscription = this.authService.logged_in$.subscribe( auth => { this.is_logged_in = auth; if (auth) { this.getArticles('feed'); } else { this.getArticles('all'); } } ); } ngOnDestroy() { this.authState_subscription.unsubscribe(); } }
import pygame import sys import math # Initialize Pygame pygame.init() # Constants WIDTH, HEIGHT = 500, 900 FPS = 60 BLACK = (0, 0, 0) WHITE = (255, 255, 255) BIG_CIRCLE_RADIUS = 200 SMALL_CIRCLE_RADIUS = 20 ANGULAR_SPEED = 0.5 # Adjust the angular speed as needed # Create the window screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Moving Circles in a Big Circle") clock = pygame.time.Clock() def calculate_color_gradient(): # Create a color gradient for the big circle gradient_surface = pygame.Surface((2 * BIG_CIRCLE_RADIUS, 2 * BIG_CIRCLE_RADIUS), pygame.SRCALPHA) for i in range(BIG_CIRCLE_RADIUS): alpha = int((i / BIG_CIRCLE_RADIUS) * 255) pygame.draw.circle(gradient_surface, (255, 255, 255, alpha), (BIG_CIRCLE_RADIUS, BIG_CIRCLE_RADIUS), i) return gradient_surface color_gradient = calculate_color_gradient() # Game loop running = True angle = 0 while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Clear the screen screen.fill(BLACK) # Draw the big circle with color gradient screen.blit(color_gradient, (WIDTH // 2 - BIG_CIRCLE_RADIUS, HEIGHT // 2 - BIG_CIRCLE_RADIUS)) # Update the angle over time angle += ANGULAR_SPEED # Calculate the positions of three small circles moving in a big circle with smooth transition for i in range(3): current_angle = math.radians((360 / 3) * i + angle) # Add the angle to introduce motion x = WIDTH // 2 + BIG_CIRCLE_RADIUS * math.cos(current_angle) y = HEIGHT // 2 + BIG_CIRCLE_RADIUS * math.sin(current_angle) # Change the color of the small circle based on the angle color = ( int(255 * (1 + math.sin(angle * 2)) / 2), int(255 * (1 + math.cos(angle * 2)) / 2), int(255 * (1 - math.sin(angle * 2)) / 2) ) # Draw the small circle with varying size based on a sinusoidal function size = SMALL_CIRCLE_RADIUS + 10 * math.sin(angle * 2) pygame.draw.circle(screen, color, (int(x), int(y)), int(size)) # Update the display pygame.display.flip() # Cap the frame rate clock.tick(FPS) # Quit Pygame pygame.quit() sys.exit()
// AJAX and APIs Exercise // 1 const first = document.querySelector('#first'); const p1 = document.createElement('p'); const p2 = document.createElement('p'); first.append(p1, p2); `{"id":18,"type":"programming","setup":"Why did the programmer quit his job?","punchline":"Because he didn't get arrays."}`; const jokeJS1 = JSON.parse(`{"id":18,"type":"programming","setup":"Why did the programmer quit his job?","punchline":"Because he didn't get arrays."}`) console.log(`Question 1`); console.log(jokeJS1); console.log(jokeJS1.setup); p1.innerText = jokeJS1.setup console.log(jokeJS1.punchline); p2.innerText = jokeJS1.punchline // 2 const second = document.querySelector('#second'); const p3 = document.createElement('p'); const p4 = document.createElement('p'); second.append(p3, p4); axios.get(`https://friends-quotes-api.herokuapp.com/quotes/random`) .then( quote =>{ const friendsJS2 = quote.data console.log(quote); const friendsJS2 = quote.data console.log(friendsJS2); p3.innerText = friendsJS2.character p4.innerText = friendsJS2.quote } ) .catch(err=>{ console.log(err); }) // 3 const third = document.querySelector('#third'); const p5 = document.createElement('p'); const p6 = document.createElement('p'); third.append(p5, p6); async function quoteJS3(){ try{ const quoteJS3 = await axios.get(`https://friends-quotes-api.herokuapp.com/quotes/random`) console.log(`question 3`); console.log(quoteJS3.data); p5.innerText = quoteJS3.data.character p6.innerText = quote.data.quote }catch(err){ console.log(err); } } quoteJS3() // 4 const fourth = document.querySelector('#fourth'); const p7 = document.createElement('p'); fourth.append(p7); async function tvMazeFunc(){ try{ const show = await axios.get(`https://api.tvmaze.com/shows/38963/episodebynumber?season=2&number=8`) console.log(show); p7.innerText = show.data.name; }catch(err){ console.log(err); } } tvMazeFunc()
use jsonrpsee::server::Server; use jsonrpsee::RpcModule; use primitives::sync::{Arc, Mutex}; use primitives::types::EncryptedTransaction; use runtime::rpc::RpcParameter; use std::collections::HashMap; use std::sync::atomic::{AtomicBool, Ordering}; extern crate dotenv; use dotenv::dotenv; use std::env; type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; fn main() -> Result<()> { dotenv().ok(); tracing_subscriber::fmt().init(); let flag = Arc::new(AtomicBool::new(true)); let thread_count = env::var("WORKER_THREAD_COUNT") .expect("WORKER_THREAD_COUNT must be set") .parse()?; let runtime = tokio::runtime::Builder::new_multi_thread() .enable_all() .worker_threads(thread_count) .build()?; let server_flag = flag.clone(); runtime.spawn(async move { run_server(server_flag.clone()).await.unwrap(); }); loop { let mut input = String::new(); std::io::stdin().read_line(&mut input).unwrap(); match input.trim() { "`" => { flag.store(false, Ordering::SeqCst); break; } _ => continue, } } Ok(()) } async fn run_server(flag: Arc<AtomicBool>) -> Result<()> { let host = env::var("HOST").expect("HOST must be set"); let port = env::var("PORT").expect("PORT must be set"); let server = Server::builder() .build(format!("{}:{}", host, port)) .await?; let state = Mutex::new(HashMap::<String, usize>::new()); let mut module = RpcModule::new(state); module.register_async_method( EncryptedTransaction::method_name(), |parameters, _state| async move { let param = parameters.parse::<EncryptedTransaction>().unwrap(); param.handler().await }, )?; let addr = server.local_addr()?; tracing::info!("ws://{}", addr); let handle = server.start(module); tokio::spawn(async move { while flag.load(Ordering::SeqCst) {} handle.stop().unwrap(); }); Ok(()) }
import "preact/debug"; import React from "react"; import { render } from "react-dom"; import { ClientConfig } from "../../shared/clientConfig"; import { ApolloClient, ApolloLink, createHttpLink, InMemoryCache, makeVar, } from "@apollo/client"; import { AWS_REGION } from "../../shared/awsRegion"; import { createAuthLink } from "aws-appsync-auth-link"; import { createSubscriptionHandshakeLink } from "aws-appsync-subscription-link"; import { UrlInfo } from "aws-appsync-subscription-link/lib/types"; import { PinBoardApp } from "./app"; import * as Sentry from "@sentry/react"; import * as SentryHub from "@sentry/hub"; import { onError } from "@apollo/client/link/error"; import { GIT_COMMIT_HASH } from "../../GIT_COMMIT_HASH"; import { BUILD_NUMBER } from "../../BUILD_NUMBER"; import DebounceLink from "apollo-link-debounce"; import { IUserTelemetryEvent, UserTelemetryEventSender, } from "@guardian/user-telemetry-client"; import { IPinboardEventTags, TelemetryContext } from "./types/Telemetry"; import { APP } from "../../shared/constants"; import { CacheProvider } from "@emotion/react"; import createCache from "@emotion/cache"; const SENTRY_REROUTED_FLAG = "rerouted"; const DEFAULT_APOLLO_DEBOUNCE_DELAY = 0; // zero in-case used by mistake export function mount({ userEmail, appSyncConfig, sentryDSN, stage, }: ClientConfig): void { const sentryUser = { email: userEmail, }; const sentryConfig = { dsn: sentryDSN, release: `${BUILD_NUMBER} (${GIT_COMMIT_HASH})`, environment: window.location.hostname, tracesSampleRate: 1.0, // We recommend adjusting this value in production, or using tracesSampler for finer control }; const pinboardSpecificSentryClient = new Sentry.Hub( new Sentry.BrowserClient(sentryConfig) ); pinboardSpecificSentryClient.configureScope((scope) => scope.setUser(sentryUser) ); const currentHub = Sentry.getHubFromCarrier(SentryHub.getMainCarrier()); const existingSentryClient = currentHub.getClient(); // if host application doesn't have Sentry initialised, then init here to ensure the GlobalEventProcessor will do its thing if (!existingSentryClient) { Sentry.init(sentryConfig); Sentry.setUser(sentryUser); } Sentry.addGlobalEventProcessor((event, eventHint) => { if ( existingSentryClient && event.fingerprint?.includes(SENTRY_REROUTED_FLAG) && event.exception?.values?.find((exception) => exception.stacktrace?.frames?.find((frame) => frame.filename?.includes("pinboard.main") ) ) ) { pinboardSpecificSentryClient.captureEvent( { ...event, fingerprint: [...(event.fingerprint || []), SENTRY_REROUTED_FLAG], }, eventHint ); return null; // stop event from being sent to host application's Sentry project } return event; }); const telemetryDomain = stage === "PROD" ? "gutools.co.uk" : "code.dev-gutools.co.uk"; const telemetryEventService = new UserTelemetryEventSender( `https://user-telemetry.${telemetryDomain}` ); const sendTelemetryEvent = ( type: string, tags?: IUserTelemetryEvent["tags"] & IPinboardEventTags, value: boolean | number = true ): void => { const event = { app: APP, stage: stage, eventTime: new Date().toISOString(), type, value, tags: { ...tags, platform: window.location.hostname, // e.g. composer.gutools.co.uk }, }; telemetryEventService.addEvent(event); }; const apolloUrlInfo: UrlInfo = { url: appSyncConfig.graphqlEndpoint, region: AWS_REGION, auth: { type: "AWS_LAMBDA", token: appSyncConfig.authToken, }, }; const hasApolloAuthErrorVar = makeVar(false); const apolloErrorLink = onError(({ graphQLErrors, networkError }) => { graphQLErrors?.forEach(({ message, ...gqlError }) => { console.error( `[Apollo - GraphQL error]: Message: ${message}, Location: ${gqlError.locations}, Path: ${gqlError.path}` ); if ( (gqlError as unknown as Record<string, unknown>).errorType === "UnauthorizedException" || gqlError.extensions?.code === "UNAUTHENTICATED" ) { hasApolloAuthErrorVar(true); } else { pinboardSpecificSentryClient.captureException( Error(`Apollo GraphQL Error : ${message}`), { captureContext: { // eslint-disable-next-line @typescript-eslint/no-explicit-any extra: gqlError as Record<string, any>, }, } ); } }); if (networkError) { console.error(`[Apollo - Network error]`, networkError); if ( [401, 403].includes( (networkError as unknown as { statusCode: number })?.statusCode ) || ( networkError as unknown as { errors: Array<{ message: string }>; } )?.errors?.find((error) => error.message?.includes("UnauthorizedException") ) ) { hasApolloAuthErrorVar(true); } } }); const apolloSuppressorOnAuthErrorLink = new ApolloLink((operation, next) => { if (hasApolloAuthErrorVar()) { console.warn("Suppressing Apollo request due to auth error", operation); return null; } else { return next(operation); } }); const exposeOperationAsQueryParam = createHttpLink({ uri: (operation) => { const operationNames = operation?.query?.definitions?.flatMap((_) => // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore _.selectionSet?.selections.map((_) => _.name?.value) ); return operationNames?.length > 0 ? `${apolloUrlInfo.url}?_${operationNames}` : apolloUrlInfo.url; }, }); const apolloClient = new ApolloClient({ link: ApolloLink.from( /* ORDER IS IMPORTANT */ [ new DebounceLink(DEFAULT_APOLLO_DEBOUNCE_DELAY), apolloErrorLink, apolloSuppressorOnAuthErrorLink, createAuthLink(apolloUrlInfo), createSubscriptionHandshakeLink( apolloUrlInfo, exposeOperationAsQueryParam ), ] ), cache: new InMemoryCache(), defaultOptions: { watchQuery: { fetchPolicy: "cache-and-network", errorPolicy: "ignore", }, query: { fetchPolicy: "network-only", errorPolicy: "all", }, mutate: { errorPolicy: "all", }, }, }); const element = document.createElement("pinboard"); document.body.appendChild(element); // to ensure no conflict with host application's emotion cache const emotionCache = createCache({ key: "pinboard-emotion-cache" }); render( <TelemetryContext.Provider value={sendTelemetryEvent}> <CacheProvider value={emotionCache}> <PinBoardApp apolloClient={apolloClient} userEmail={userEmail} hasApolloAuthErrorVar={hasApolloAuthErrorVar} /> </CacheProvider> </TelemetryContext.Provider>, element ); if (module["hot"]) { module["hot"].accept(); } }
import { FunctionComponent } from "react"; import { Button } from "@mui/material"; import styles from "./Footer.module.css"; const Footer: FunctionComponent = () => { return ( <footer className={styles.footer}> <div className={styles.footerContent}> <h3 className={styles.chainhost}>ChainHost</h3> <div className={styles.appreciation}> <div className={styles.thankYouFor}> Thank you for choosing ChainHost as your crypto mining partner. Your trust in us drives our commitment to excellence. Feel free to explore our services, and if you have any questions, our support team is here to assist you. We look forward to being a part of your crypto mining journey. </div> </div> </div> <div className={styles.footerNavigation}> <div className={styles.quickLinks}> <div className={styles.quickLinks1}>Quick Links</div> <div className={styles.home}>Home</div> <div className={styles.ourStory}>Our Story</div> <div className={styles.eBooks}>E-books</div> <div className={styles.articles}>Articles</div> <div className={styles.contact}>Contact</div> </div> <div className={styles.legalLinks}> <div className={styles.legal}>Legal</div> <div className={styles.termsConditions}>{`Terms & Conditions`}</div> <div className={styles.refundPolicy}>Refund Policy</div> <div className={styles.cancellation}>Cancellation</div> <div className={styles.privacyPolicy}>Privacy Policy</div> </div> <div className={styles.notification}> <div className={styles.getNotified}>Get Notified!</div> <div className={styles.beTheFirst}> Be the first to know about the latest developments, market insights, and news in the world of cryptocurrencies. Subscribe to our newsletter to stay informed and never miss out on important updates. </div> <div className={styles.emailInputContainer}> <div className={styles.emailInputBorder} /> <div className={styles.emailInputPlaceholder}> <div className={styles.provideEmail}>Provide email</div> </div> <Button className={styles.emailInputContainerChild} disableElevation={true} variant="contained" sx={{ textTransform: "none", color: "#0e0e0e", fontSize: "16", background: "#0bd752", borderRadius: "100px", "&:hover": { background: "#0bd752" }, width: 200, height: 56, }} > Subscribe </Button> </div> </div> </div> </footer> ); }; export default Footer;
import { GitHub, Endpoints } from '../../github' import * as core from '@actions/core' import { GetResponseDataTypeFromEndpointMethod } from '@octokit/types' import assert from 'assert' type Issues = GetResponseDataTypeFromEndpointMethod< typeof Endpoints.search.issuesAndPullRequests > export function joinQueryParts(arr: string[], limit: number = 192): string[] { if (arr.length === 0) { return [] } else { return arr .slice(1) .reduce( (acc, s) => `${acc.at(-1)} ${s}`.length <= limit ? [...acc.slice(0, -1), `${acc.at(-1)} ${s}`] : [...acc, s], [arr[0]] ) } } export async function addIssuesToProject( org: string, projectNumber: number, query: string, dryRun: boolean ) { const q = `${query} -project:${org}/${projectNumber}` assert(q.length <= 256, `Query must be less than 256 characters, got ${q}`) const github = await GitHub.getGitHub() core.info(`Searching for project: ${org}/${projectNumber}`) // Find the project (we need its' id) const { organization: { projectV2: project } } = (await github.client.graphql( `query($login: String!, $number: Int!) { organization(login: $login) { projectV2(number: $number) { id } } }`, { login: org, number: projectNumber } )) as any core.info(`Found project: ${project.id}`) core.info(`Searching for issues with query: ${q}`) // Find that are not yet in the project const issues: Issues['items'] = await github.client.paginate( github.client.search.issuesAndPullRequests, { q } ) core.info(`Found ${issues.length} issues`) assert(issues.length <= 500, 'Too many issues, please refine your query') core.info(`Adding issues to ${org}/${projectNumber}`) // Add all the found issues to the project for (const issue of issues) { // If the issue is in a repo that is in the same org as the project, add the issue to the project // Otherwise, create a new draft item in the project with a link to the issue (it will get automatically turned into a proper item) if (issue.repository_url.split('/').reverse()[1] === org) { if (dryRun) { core.info( `Would have added ${issue.html_url} to ${org}/${projectNumber}` ) } else { core.info(`Adding ${issue.html_url} to ${org}/${projectNumber}`) try { const { addProjectV2ItemById: { item: item } } = (await github.client.graphql( `mutation($projectId: ID!, $contentId: ID!) { addProjectV2ItemById(input: {projectId: $projectId, contentId: $contentId}) { item { id } } }`, { projectId: project.id, contentId: issue.node_id } )) as any core.info( `Added ${issue.html_url} to ${org}/${projectNumber} as ${item.id}` ) } catch (e) { if ( (e as any)?.errors?.at(0)?.message === 'Content already exists in this project' ) { core.info( `Issue ${issue.html_url} already exists in ${org}/${projectNumber}` ) } } } } else { if (dryRun) { core.info( `Would have added ${issue.html_url} to ${org}/${projectNumber} (draft)` ) } else { core.info(`Adding ${issue.html_url} to ${org}/${projectNumber} (draft)`) try { const { addProjectV2DraftIssue: { projectItem: item } } = (await github.client.graphql( `mutation($projectId: ID!, $title: String!) { addProjectV2DraftIssue(input: { projectId: $projectId, title: $title }) { projectItem { id } } }`, { projectId: project.id, title: issue.html_url } )) as any core.info( `Added ${issue.html_url} to ${org}/${projectNumber} as ${item.id} (draft)` ) } catch (e) { if ( (e as any)?.errors?.at(0)?.message === 'Content already exists in this project' ) { core.info( `Issue ${issue.html_url} already exists in ${org}/${projectNumber}` ) } } } } } core.info(`Done`) }
import StateDailyData from '../models/StateDailyData.js'; import { DatabaseError, NotFound } from '../utils/errors.js'; import statesData from '../Database/Data/states.js'; import { invertObject } from '../middleware/helperFunctions.js'; /** * Retrieves all daily data for a specific state from the database * and sends it as a JSON response. * * @param {Object} req - The request object containing details about the HTTP request made by the client. * @param {Object} res - The response object used to send the response back to the client. */ export const getAllStateDailyData = async (req, res) => { const stateCode = req.params.stateCode; try { const stateData = await StateDailyData.findAll({ where: { stateCode } }); res.json(stateData); } catch (error) { throw new DatabaseError('Database Error', error); } }; /** * Retrieves data for a specific state and date from a * database and returns it as a JSON response. * * @param {Object} req - The request object containing details about the HTTP request made by the client. * @param {Object} res - The response object used to send the response back to the client. */ export const getStateDailyDataByDate = async (req, res) => { const stateCode = req.params.stateCode; const date = req.params.date; try { const data = await StateDailyData.findOne({ where: { stateCode, date } }); if (data) { res.json(data); } else { throw new NotFound('Data not found'); } } catch (error) { throw new DatabaseError('Database Error', error); } }; /** * Retrieves the state codes and names * * @param {Object} req - The request object containing details about the HTTP request made by the client. * @param {Object} res - The response object used to send the response back to the client. * @returns an array of arrays, where each inner array contains the state code and state name. */ export const getStates = (_req, res) => { res.json(invertObject(statesData)); }; /** * Retrieves the top 3 states with the highest total cases, total * deaths, and total testing from a database table and sends the data as a JSON * response. * @param {Object} req - The request object containing details about the HTTP request made by the client. * @param {Object} res - The response object used to send the response back to the client. */ export const getStatesTopsData = async (_req, res) => { try { const statesTops = await StateDailyData.findAll({ attributes: ['stateCode', 'stateName', 'date', 'total_cases', 'total_deaths', 'total_testing'], order: [['total_cases', 'DESC'], ['total_deaths', 'DESC'], ['total_testing', 'DESC']], limit: 3 }); res.json(statesTops); } catch (error) { throw new DatabaseError('Database Error', error); } };
//author: Daniel Santos package ex1; import java.rmi.*; import java.rmi.server.*; import java.rmi.registry.LocateRegistry; import java.util.Scanner; public class ServidorRMIv2 extends UnicastRemoteObject implements InterfaceContador{ int contador; static String nome; ServidorRMIv2() throws RemoteException { super(); contador = 0; } public static void main(String[] args) { try { ServidorRMIv2 serv = new ServidorRMIv2(); LocateRegistry.createRegistry(1099); nome = inputString("Nome do objeto remoto:"); Naming.rebind(nome,serv); //Naming.rebind("//localhost:1099/meuContador", serv); System.out.println("servidor RMI iniciado"); } catch (Exception e) { System.out.println(e); } } public int obtemValor() throws RemoteException { return contador; } public void incrementa() throws RemoteException { ++contador; } public void soma(int num) throws RemoteException { contador += num; } public static String inputString(String n) { Scanner myObj = new Scanner(System.in); System.out.print(n); String read = myObj.nextLine(); return read; } }
'use client' import { useState, useEffect } from 'react'; import SelectPlayer from './SelectPlayer'; import Display from './DisplayStatistics'; const Matchup = () => { const [ firstPlayer, setFirstPlayer ] = useState({name: "Select a player", image: "/baseball-outline.svg", position: 'Default'}); const [secondPlayer, setSecondPlayer] = useState({ name: "Select a player", image: "/baseball-outline.svg", position: 'Default' }); const [ stats, setStats ] = useState({}); useEffect(() => { if ((firstPlayer.position === 'P' && secondPlayer.position === 'P') || (firstPlayer.position !== 'P' && firstPlayer.position !== 'Default' && secondPlayer.position !== 'P' && secondPlayer.position !== 'Default')) { setSecondPlayer({ name: "Select a player", image: "/baseball-outline.svg", position: 'Default' }) } }, [firstPlayer]); useEffect(() => { if ((firstPlayer.position === 'P' && secondPlayer.position === 'P') || (firstPlayer.position !== 'P' && firstPlayer.position !== 'Default' && secondPlayer.position !== 'P' && secondPlayer.position !== 'Default')) { setFirstPlayer({ name: "Select a player", image: "/baseball-outline.svg", position: 'Default' }) } }, [secondPlayer]) useEffect(() => { if (firstPlayer.position !== 'Default' && secondPlayer.position !== 'Default') { if (firstPlayer.position === 'P') { (async () => { const response = await fetch(`/api/stats/${secondPlayer.id}/${firstPlayer.id}`, {next: {cache: 'no-store'}}) const data = await response.json(); //console.log(data); setStats(data); })(); } else { (async () => { const response = await fetch(`/api/stats/${firstPlayer.id}/${secondPlayer.id}`, { next: { cache: 'no-store' } }) const data = await response.json(); //console.log(data); setStats(data); })(); } } else { setStats({}); } }, [firstPlayer, secondPlayer]) return ( <> <div className='w-full flex flex-col max-w-full items-center md:items-start md:flex-row md:justify-center pb-8 space-y-4 md:space-y-0'> <SelectPlayer player={firstPlayer} setPlayer={setFirstPlayer} otherPosition={secondPlayer}/> <Display stats={stats}/> <SelectPlayer player={secondPlayer} setPlayer={setSecondPlayer} otherPosition={firstPlayer} /> </div> </> ) }; export default Matchup;
import React, { Component } from "react" import "./Main.css" import Investments from "./Investments" export default class Main extends Component { initialState = { Kpopers: 0, Fanclubs: 0, Albuns: 0, AlbumRequisito: 40, Tour: 0, TourRequisito: 2000, } state = { ...this.initialState } KClick = () => { this.setState({ Kpopers: this.state.Kpopers + 1 }) } lancarNovoAlbum = () => { this.setState({ Albuns: this.state.Albuns + 1 }) setInterval(() => { this.setState({ Kpopers: this.state.Kpopers + 1 }) }, 1000) this.setState({ AlbumRequisito: this.state.AlbumRequisito * 1.4 }) } iniciarNovoTour = () => { this.setState({ TourRequisito: this.state.Kpopers * 1.4 }) const barraProgresso = document.querySelector(".barraProgresso") barraProgresso.setAttribute("id", "iniciarProgresso") setTimeout(() => { this.setState({ Kpopers: Math.round(this.state.Kpopers * 1.2) }) barraProgresso.setAttribute("id", "") }, 20000) } render() { let iniciarTour let lancarAlbum if (this.state.Kpopers > this.state.AlbumRequisito - 1) { lancarAlbum = ( <div> <button className="botaoDentro" onClick={this.lancarNovoAlbum} > Lançar álbum </button> </div> ) } if (this.state.Kpopers > this.state.TourRequisito - 1) { iniciarTour = ( <div> <button className="botaoDentro" onClick={this.iniciarNovoTour} > Novo Tour </button> </div> ) } return ( <div className="frame"> <div className="iphone"> <div className="display"> <div className="barraProgressoContainer"> <div className="barraProgresso" /> </div> <h2>Kpopers: {this.state.Kpopers}</h2> <h4>Albuns: {this.state.Albuns}</h4> {lancarAlbum} {iniciarTour} </div> <button className="botaoIphone" onClick={this.KClick} ></button> </div> <div> <Investments data={this.state.Kpopers} /> </div> </div> ) } }
// Link on the task: https://leetcode.com/problems/insert-delete-getrandom-o1/description/ var RandomizedSet = function() { this.collection = new Set(); }; /** * @param {number} val * @return {boolean} */ RandomizedSet.prototype.insert = function(val) { if (this.collection.has(val)) { return false; } this.collection.add(val); return true; }; /** * @param {number} val * @return {boolean} */ RandomizedSet.prototype.remove = function(val) { return this.collection.delete(val); }; /** * @return {number} */ RandomizedSet.prototype.getRandom = function() { const values = Array.from(this.collection.values()); return values[Math.floor(Math.random() * values.length)]; }; /** * Your RandomizedSet object will be instantiated and called as such: * var obj = new RandomizedSet() * var param_1 = obj.insert(val) * var param_2 = obj.remove(val) * var param_3 = obj.getRandom() */
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { MapComponent } from './map.component'; import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { ObjectService } from 'src/app/service/object/object.service'; import { MapService } from 'src/app/service/map/map.service'; import { of } from "rxjs"; import { mapOptions } from "../../utils/const"; import {IObjects} from "../../interfaces/mapInterfaces"; const example = [{ id: 1, name: 'Ваз', longitude: 1001, latitude: 1000 }] describe('MapComponent ', () => { let component: MapComponent; let fixture: ComponentFixture<MapComponent>; const fakeObjectService = jasmine.createSpyObj('fakeObjectService', ['getAll', 'emitData']); const fakeMapService = jasmine.createSpyObj('fakeMapService', ['initMap']); beforeEach(() => { fakeObjectService.getAll.and.returnValue(of(example)) TestBed.configureTestingModule({ declarations: [MapComponent], providers: [{ provide: ObjectService, useValue: fakeObjectService, }, { provide: MapService, useValue: fakeMapService } ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }); fixture = TestBed.createComponent(MapComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('Должен создаваться', () => { expect(component).toBeTruthy(); }); it('ObjectService getAll должен вызываться при инициализации', () => { fakeObjectService.getAll.calls.reset() component.ngOnInit() expect(fakeObjectService.getAll).toHaveBeenCalled() }); it('ObjectService emitData должен вызываться при инициализации и в качестве аргумента передавать полученные объекты', () => { fakeObjectService.emitData.calls.reset() component.ngOnInit() expect(fakeObjectService.emitData).toHaveBeenCalledWith(example) }); it('MapService initMap должен вызываться при инициализации и в качестве аргумента передавать полученные объекты', () => { fakeMapService.initMap.calls.reset() component.ngOnInit() expect(fakeMapService.initMap).toHaveBeenCalledWith(mapOptions, example) }); it('ObjectService должен получать объекты', done => { fakeObjectService.getAll().subscribe((objects: any) => { component.objects = objects expect(component.objects).toEqual(example) done() }) }); });
package au.com.venilia.emailais.signalk.model; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonValue; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; /** * Special maneuver such as regional passing arrangement. (from ais) * */ @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonPropertyOrder({ "value" }) public class Maneuver { @JsonProperty("value") private Maneuver.Value value; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("value") public Maneuver.Value getValue() { return value; } @JsonProperty("value") public void setValue(Maneuver.Value value) { this.value = value; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } @Override public String toString() { return new ToStringBuilder(this).append("value", value).append("additionalProperties", additionalProperties).toString(); } @Override public int hashCode() { return new HashCodeBuilder().append(value).append(additionalProperties).toHashCode(); } @Override public boolean equals(Object other) { if (other == this) { return true; } if ((other instanceof Maneuver) == false) { return false; } Maneuver rhs = ((Maneuver) other); return new EqualsBuilder().append(value, rhs.value).append(additionalProperties, rhs.additionalProperties).isEquals(); } public enum Value { NOT_AVAILABLE("Not available"), NO_SPECIAL_MANEUVER("No special maneuver"), SPECIAL_MANEUVER("Special maneuver"); private final String value; private final static Map<String, Maneuver.Value> CONSTANTS = new HashMap<String, Maneuver.Value>(); static { for (Maneuver.Value c: values()) { CONSTANTS.put(c.value, c); } } private Value(String value) { this.value = value; } @Override public String toString() { return this.value; } @JsonValue public String value() { return this.value; } @JsonCreator public static Maneuver.Value fromValue(String value) { Maneuver.Value constant = CONSTANTS.get(value); if (constant == null) { throw new IllegalArgumentException(value); } else { return constant; } } } }
import { useEffect, useState } from "react"; import Button from "../Button"; import ToggleButton from "../ToggleButton"; import OurTeam from "./OurTeam"; import { getPricingSliderSection } from "../../api/PricingAPI"; export default function MonthlyAnnualy(props) { let [Heading, setHeading] = useState(props.heading); let [base_value, setbase_value] = useState(props.base_value); let [proffesion_owner_price, setproffesion_owner_price] = useState( Number(props.proffesion_owner_price.split("//")[0]) ); let [standard_owner_price, setstandard_owner_price] = useState( Number(props.standard_owner_price.split("//")[0]) ); let [discount, setDiscount] = useState( Number(props.proffesion_owner_price.split("//")[1]) ); let [stats, setstats] = useState(props.stats); let [memebers, setMembers] = useState("0"); let [Monthly, setMonthly] = useState(true); function calculateMonthlyPrice(type) { let ownerPrice = 0; if (type === "Professional") { ownerPrice = proffesion_owner_price; } else { ownerPrice = standard_owner_price; } let totalMembersCost = Number(base_value) * Number(memebers); return String(ownerPrice + totalMembersCost); } function calculateAnnualyPrice(type) { let total = Number(calculateMonthlyPrice(type)) * 12; return total - getPercentOf(total, discount); } function getPercentOf(value, percent) { return value * (percent / 100); } useEffect(() => { let fun = async () => { let data = await getPricingSliderSection(); let { heading, base_value, stats, proffesion_owner_price, standard_owner_price, } = data.data.attributes; setHeading(heading); setbase_value(base_value); setstats(stats); setproffesion_owner_price( Number(proffesion_owner_price.split("//")[0]) ); setstandard_owner_price( Number(standard_owner_price.split("//")[0]) ); setDiscount(Number(proffesion_owner_price.split("//")[1])); }; fun(); }, []); return ( <div className="flex flex-col mb-16 gap-8 md:flex-row md:p-8 justify-center md:justify-between mt-10 rounded-lg"> <OurTeam memebers={memebers} setMembers={setMembers} stats={stats} heading={Heading} base_value={base_value} /> <div className="flex m-auto flex-col w-full md:w-fit h-fit p-8 rounded-md shadow-md gap-8"> <div className="flex gap-4 items-center"> {" "} <span>Monthly</span> <ToggleButton value={Monthly} setValue={setMonthly} /> <span>Annual</span> </div> <div className="flex gap-4"> <div className="flex flex-col gap-4"> <span className="text-2xl text-blue-500"> <span className="text-[#060C3C] font-bold text-base"> {" "} Professional: </span>{" "} $ {Monthly ? calculateMonthlyPrice("Professional") : calculateAnnualyPrice("Professional")}{" "} / {Monthly ? "m" : "y"} </span> <span className="text-2xl text-blue-500"> <span className="text-[#060C3C] text-base font-bold"> {" "} Standard: </span>{" "} $ {Monthly ? calculateMonthlyPrice() : calculateAnnualyPrice()}{" "} / {Monthly ? "m" : "y"} </span> </div> <span className="bg-gray-300 h-fit text-base px-4 py-1 rounded-2xl"> Save {discount}% off </span> </div> <div className="w-full lg:w-[60%]"> <Button onClick={() => { window.location = "https://8okzn8zrvfp.typeform.com/to/CGtW7ylQ"; }} > Start 7-day free trial </Button> <p className="text-sm mt-4 leading-7 underline text-slate-700 "> Try Locom for free for 7 days with no credit card required </p> </div> </div> </div> ); }
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:get/get.dart'; import 'package:muatmuat/app/core/function/global_alert_dialog.dart'; import 'package:muatmuat/app/modules/api_profile.dart'; import 'package:muatmuat/app/modules/ubah_kelengkapan_legalitas/ubah_kelengkapan_legalitas_controller.dart'; import 'package:muatmuat/app/style/list_colors.dart'; import 'package:muatmuat/app/utils/download_utils.dart'; import 'package:muatmuat/app/widgets/custom_text.dart'; import '../../../../global_variable.dart'; class ItemUbahKelengkapanLegalitasIndividuComponent extends StatefulWidget { final String title; final String valueString; final FileKelengkapanLegalitasComponent child; const ItemUbahKelengkapanLegalitasIndividuComponent({ Key key, @required this.title, this.valueString, this.child, }) : super(key: key); @override _ItemUbahKelengkapanLegalitasIndividuComponentState createState() => _ItemUbahKelengkapanLegalitasIndividuComponentState(); } class _ItemUbahKelengkapanLegalitasIndividuComponentState extends State<ItemUbahKelengkapanLegalitasIndividuComponent> { @override Widget build(BuildContext context) { return Container( width: double.infinity, decoration: BoxDecoration( borderRadius: BorderRadius.circular(GlobalVariable.ratioWidth(context) * 4), border: Border.all( color: Color(ListColor.colorGrey3), width: GlobalVariable.ratioWidth(context) * 0.5, ), ), padding: EdgeInsets.fromLTRB( GlobalVariable.ratioWidth(context) * 14, GlobalVariable.ratioWidth(context) * 10, GlobalVariable.ratioWidth(context) * 14, GlobalVariable.ratioWidth(context) * 12, ), margin: EdgeInsets.only( bottom: GlobalVariable.ratioWidth(context) * 8, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( margin: EdgeInsets.only( top: (GlobalVariable.ratioWidth(context) * 14) * 2.3 / 11, ), child: RichText( text: TextSpan( text: widget.title, style: TextStyle( fontWeight: FontWeight.w500, fontSize: GlobalVariable.ratioWidth(context) * 14, color: Color(ListColor.colorGrey3), fontFamily: "AvenirNext", height: GlobalVariable.ratioWidth(context) * 1.2, ), ), ), ), SizedBox( height: GlobalVariable.ratioWidth(context) * 10, ), if (widget.valueString != null) CustomText(widget.valueString, fontWeight: FontWeight.w600, fontSize: 14, ) else if (widget.child != null) widget.child, ], ), ); } } class FileKelengkapanLegalitasComponent extends StatelessWidget { final String fileId; final String fileName; final String filePath; const FileKelengkapanLegalitasComponent({ @required this.fileId, @required this.fileName, @required this.filePath, }); @override Widget build(BuildContext context) { String iconAsset = ""; final fFormat = filePath.split(".").last.toUpperCase(); if (fFormat == "ZIP" || fFormat == "PDF" || fFormat == "PNG" || fFormat == "JPG" || fFormat == "XLS" ) { iconAsset = "assets/ic_$fFormat.svg"; } else if (fFormat == "JPEG") { iconAsset = "assets/ic_JPG.svg"; } else { iconAsset = "assets/ic_XLS.svg"; } return ConstrainedBox( constraints: BoxConstraints( maxHeight: GlobalVariable.ratioWidth(context) * 182, ), child: RawScrollbar( thumbColor: Color(ListColor.colorGrey3), thickness: GlobalVariable.ratioWidth(Get.context) * 4, radius: Radius.circular(GlobalVariable.ratioWidth(Get.context) * 20), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded( child: Row( children: [ SvgPicture.asset(iconAsset, width: GlobalVariable.ratioWidth(context) * 30, height: GlobalVariable.ratioWidth(context) * 30, ), SizedBox( width: GlobalVariable.ratioWidth(context) * 8, ), SizedBox( width: GlobalVariable.ratioWidth(context) * 210, child: CustomText(fileName, color: Color(ListColor.colorBlue), overflow: TextOverflow.ellipsis, fontWeight: FontWeight.w600, fontSize: 14, ), ), ], ), ), _iconDownload( context, fileId, ), ], ), ), ); } Widget _iconDownload( BuildContext context, String fileId, ) { return Container( margin: EdgeInsets.only( left: GlobalVariable.ratioWidth(context) * 12, ), child: InkWell( onTap: () { GlobalAlertDialog.showDialogWarningWithoutTitle( context: context, customMessage: Container( margin: EdgeInsets.only( bottom: GlobalVariable.ratioWidth(context) * 20, ), width: GlobalVariable.ratioWidth(Get.context) * 296, child: CustomText("Password Dokumen Anda merupakan gabungan dari \"6 digit terakhir No. KTP Pendaftar/Pemegang Akun dan Kode Referral", textAlign: TextAlign.center, fontSize: 14, height: 22 / 14, color: Colors.black, fontWeight: FontWeight.w500, withoutExtraPadding: true, ), ), labelButtonPriority1: "Unduh Dokumen", buttonWidth: 193, onTapPriority1: () async { try { final response = await ApiProfile( context: Get.context, isShowDialogLoading: true, isShowDialogError: true, ).zipFileOnDownload({ 'file': [fileId].toString(), }); DownloadUtils.doDownload( context: context, url: response['Data']['Link'], ); } catch (error) { print("Error : $error"); } }, ); }, child: SvgPicture.asset("assets/ic_download.svg", width: GlobalVariable.ratioWidth(context) * 18, height: GlobalVariable.ratioWidth(context) * 18, color: Color(ListColor.colorBlue), ), ), ); } }
import nconf from 'nconf'; import querystring from 'querystring'; import { Request, Response, NextFunction } from 'express'; import meta from '../meta'; import pagination from '../pagination'; import user from '../user'; import topics from '../topics'; import helpers from './helpers'; // The anys are typed because there is no way of determining the exact types of the arguments // since other files are not translated to TS yet /* eslint-disable @typescript-eslint/no-explicit-any */ interface Pagination { rel : any; } interface Breadcrumb { text: string; } interface Filter { selected: boolean; } interface UnreadData { topicCount: number; pageCount: number; pagination: Pagination; title: string; breadcrumbs?: Breadcrumb[]; showSelect: boolean; showTopicTools: boolean; allCategoriesUrl: string; selectedCategory?: any; selectedCids?: number[]; selectCategoryLabel: string; selectCategoryIcon: string; showCategorySelectLabel: boolean; filters: Filter[]; selectedFilter?: Filter; } interface UnreadController { get: ( req: Request & { uid: number }, res: Response ) => Promise<void>; unreadTotal: (req: Request, res: Response, next: NextFunction) => Promise<void>; } const unreadController = {} as UnreadController; const relative_path = nconf.get('relative_path') as string; interface CategoryData { selectedCategory?: any; selectedCids?: number[]; } interface UserSettings { topicsPerPage: number; usePagination: any; } type IsPrivileged = boolean; unreadController.get = async function (req: Request & { uid: number }, res: Response): Promise<void> { const { cid } = req.query; const filter = req.query.filter || ''; const [categoryData, userSettings, isPrivileged] = await Promise.all([ helpers.getSelectedCategory(cid) as CategoryData, // The next line calls a function in a module that has not been updated to TS yet // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call user.getSettings(req.uid) as UserSettings, user.isPrivileged(req.uid) as IsPrivileged, ]); const page = parseInt(req.query.page as string, 10) || 1; const start = Math.max(0, (page - 1) * userSettings.topicsPerPage); const stop = start + userSettings.topicsPerPage - 1; // The next line calls a function in a module that has not been updated to TS yet // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call const data = (await topics.getUnreadTopics({ cid: cid, uid: req.uid, start: start, stop: stop, filter: filter, query: req.query, })) as UnreadData; const isDisplayedAsHome = !(req.originalUrl.startsWith(`${relative_path}/api/unread`) || req.originalUrl.startsWith(`${relative_path}/unread`)); const baseUrl = isDisplayedAsHome ? '' : 'unread'; if (isDisplayedAsHome) { // The next line calls a function in a module that has not been updated to TS yet // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call data.title = meta.config.homePageTitle as string || '[[pages:home]]'; } else { data.title = '[[pages:unread]]'; data.breadcrumbs = helpers.buildBreadcrumbs([{ text: '[[unread:title]]' }]); } data.pageCount = Math.max(1, Math.ceil(data.topicCount / userSettings.topicsPerPage)); data.pagination = pagination.create(page, data.pageCount, req.query); // The next line calls router[verb] which is in a module that has not been updated to TS yet // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment helpers.addLinkTags({ url: 'unread', res: req.res, tags: data.pagination.rel }); if (userSettings.usePagination && (page < 1 || page > data.pageCount)) { req.query.page = String(Math.max(1, Math.min(data.pageCount, page))); return helpers.redirect(res, `/unread?${querystring.stringify(req.query as querystring.ParsedUrlQueryInput)}`); } data.showSelect = true; data.showTopicTools = isPrivileged; data.allCategoriesUrl = `${baseUrl}${helpers.buildQueryString(req.query, 'cid', '')}`; data.selectedCategory = categoryData.selectedCategory as CategoryData; data.selectedCids = categoryData.selectedCids; data.selectCategoryLabel = '[[unread:mark_as_read]]'; data.selectCategoryIcon = 'fa-inbox'; data.showCategorySelectLabel = true; data.filters = helpers.buildFilters(baseUrl, filter, req.query); data.selectedFilter = data.filters.find(filter => filter && filter.selected); res.render('unread', data); }; unreadController.unreadTotal = async function (req: Request & { uid: number }, res: Response, next: NextFunction) { const filter = req.query.filter || ''; try { // The next line calls a function in a module that has not been updated to TS yet // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call const unreadCount = await topics.getTotalUnread(req.uid, filter) as number; res.json(unreadCount); } catch (err) { next(err); } }; export = unreadController;
<template> <div id="chatting-room"> <div v-if="isVisible"> <div id="top-container"> <svg-loader id="svg-container" :svgFile="leftSvg" :width="30" :height="30" fill="gray" @click="prev" /> <div id="image-container"> <img src="https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&fname=http%3A%2F%2Fcfile23.uf.tistory.com%2Fimage%2F2207573D58CFDE2704BB29"> </div> <div> <span>{{ modelValue.name }}</span> </div> </div> <div id="main-container" /> <div id="bottom-container"> <div> <div id="input-container"> <input> <div> <svg-loader id="svg-container" :svgFile="sendSvg" :width="30" :height="30" fill="white" /> </div> </div> </div> </div> </div> </div> </template> <script> import left from '@/assets/left.svg' import send from '@/assets/send.svg' import { error } from '../notification' export default { name: 'ChattingRoom', props: { modelValue: { type: Object, default: Object, }, }, data: function () { return { leftSvg: left, sendSvg: send, directMessage: {}, event: {}, } }, computed: { isVisible: function () { return !(Object.keys(this.modelValue).length === 0) }, }, watch: { modelValue: function (newValue, oldValue) { this.createDirectMessage() }, event: function (newValue, oldValue) { console.log('watch') console.log(newValue) }, }, created: function () { // socket this.$socket.connect() this.$socket.socket.private('user.' + this.$store.getters.getUser.user_id).listen('BroadCastEvent', (e) => { this.event = e }) }, methods: { createDirectMessage: async function () { const payload = { name: this.modelValue.name, users: [ this.$store.getters.getUser.user_id, ], } if (this.$store.getters.getUser.user_id !== this.modelValue.id) { payload.users.push(this.modelValue.id) } const result = await this.$http('/direct-message', 'post', payload) if (result.status === 200) { this.directMessage = result.data.data } else { error(this, result.data.message) } }, prev: function () { this.$emit('update:modelValue', {}) }, }, } </script> <style scoped> #chatting-room { flex: 2; background-color: #f2f3f5; } #chatting-room > div { height: 100%; display: flex; flex-direction: column; } #top-container { flex: 1; background-color: #ebeced; display: flex; padding: 10px 0px; } #top-container div { align-self: center; } #svg-container { margin: 0px 11px; cursor: pointer; align-self: center; } #image-container { width: 60px; height: 60px; border-radius: 20px; overflow: hidden; margin-right: 10px; } #image-container img { width: 100%; height: 100%; object-fit: cover; } #main-container { flex: 25; } #bottom-container { flex: 1; padding: 10px; } #bottom-container > div { background-color: white; min-height: 60px; height: 100%; border-radius: 10px; display: flex; border: 2px solid gray; } #input-container { display: flex; overflow: hidden; width: 100%; padding: 0px 10px; } #input-container > input { width: 100%; height: 100%; align-self: center; border: none; padding: 10px; font-size: 20px; } #input-container > input:focus { outline: none; } #input-container > div { background-color: gray; width: 50px; min-height: 50px; height: 75%; border-radius: 50px; display: flex; align-self: center; } </style>
// // ViewController.swift // ProjectDay32 // // Created by admin on 2019/8/23. // Copyright © 2019 limice. All rights reserved. // import UIKit class ViewController: UITableViewController { var shoppingList = [String]() override func viewDidLoad() { super.viewDidLoad() title = "创建购物清单" navigationItem.leftBarButtonItem = UIBarButtonItem(title: "重置", style: .plain, target: self, action: #selector(clearData)) navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(inputGoodsAlert)) let shareItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareInfo)) toolbarItems = [shareItem] navigationController?.isToolbarHidden = false // Do any additional setup after loading the view. } @objc func inputGoodsAlert() { let ac = UIAlertController(title: "输入商品", message: nil, preferredStyle: .alert) ac.addTextField() ac.addAction(UIAlertAction(title: "确认", style: .default, handler: { (action: UIAlertAction) in if let textfield = ac.textFields?[0] { if let str = textfield.text { self.shoppingList.insert(str, at: 0) self.tableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: .automatic) } } })) present(ac, animated: true) } @objc func clearData () { shoppingList.removeAll() tableView.reloadData() } @objc func shareInfo() { if shoppingList.isEmpty { print("没有购物清单") return; } let shareInfo = shoppingList.joined(separator: "\n") let active = UIActivityViewController(activityItems: [shareInfo], applicationActivities: []) active.popoverPresentationController?.barButtonItem = navigationController?.toolbar.items?[0] present(active, animated: true) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return shoppingList.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Shopping", for: indexPath) cell.textLabel?.text = shoppingList[indexPath.row] return cell } }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* MateriaSource.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cscelfo <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/11/08 14:02:34 by cscelfo #+# #+# */ /* Updated: 2023/11/09 16:39:23 by cscelfo ### ########.fr */ /* */ /* ************************************************************************** */ #pragma once #ifndef MATERIASOURCE_HPP # define MATERIASOURCE_HPP #include "IMateriaSource.hpp" #include "AMateria.hpp" class MateriaSource : public IMateriaSource { private: AMateria* _materia[4]; public: MateriaSource( void ); MateriaSource( const MateriaSource& sourceClass ); ~MateriaSource( void ); MateriaSource& operator=( const MateriaSource& sourceClass ); virtual void learnMateria( AMateria* ); virtual AMateria* createMateria( const std::string& type ); }; #endif
<!DOCTYPE html> <html lang="en"> <head><title>Using</title></head> <body> <h4>Using</h4> <script src="/lib/jquery.js"></script> <script src="/lib/Rx4.js"></script> <script> const $document = $(document); const dispose = () => { log('Dispose', 'lime'); }; const source = Rx.Observable .fromEvent($document, 'mousemove') .map(({pageX, pageY}) => ({x: pageX, y: pageY})) .throttle(200) // limit the emits to one every 200ms .takeUntil(Rx.Observable.using( () => ({dispose}), () => Rx.Observable.fromEvent($document, 'click') )); source.subscribe( (x) => log(x, 'red'), () => log('Error', 'red'), () => log('Completed', 'red'), ); </script> </body> </html>
import { HttpException, HttpStatus, Injectable } from '@nestjs/common'; import { PrismaService } from 'src/prisma.service'; import { User } from '@prisma/client'; import { NewUser } from 'src/graphql'; import * as bcrypt from 'bcrypt'; @Injectable() export class UserService { constructor(private readonly prisma: PrismaService) {} async user(id: number): Promise<User | null> { return this.prisma.user.findFirst({ where: { id: Number(id) ? Number(id) : 0, }, }); } async userByEmail(email: string): Promise<User | null> { return this.prisma.user.findFirst({ where: { email: email, }, }); } async usersByLogin(login: string): Promise<User[] | null> { return this.prisma.user.findMany({ where: { login: login, } }) } async users(): Promise<User[]> { return this.prisma.user.findMany({}); } async me(id: number): Promise<User> { return this.prisma.user.findFirst({ where: { id: id, }, include: { class: true, }, }); } async changePassword(id: number, input: { lastPassword: string; newPassword }, isAdmin: boolean): Promise<any> { const user = await this.me(id); if (!user) return new HttpException('No User', HttpStatus.NOT_FOUND); const validatePassword = await bcrypt.compare(input.lastPassword, user.password); if (validatePassword || isAdmin) { const hashedPass = await bcrypt.hash(String(input.newPassword), 5); const upUser = await this.prisma.user.update({ where: { id: id, }, data: { password: hashedPass, }, }); if (!upUser) return new HttpException('User down', HttpStatus.CONFLICT); return 'Success'; } return new HttpException('Wrong Password', HttpStatus.FORBIDDEN); } async createUser(input: NewUser): Promise<User | HttpException> { const hashedPassword = await bcrypt.hash(String(input.password), 5); const role = await this.prisma.role.findFirst({ where: { id: input.roleId, }, }); const clas = await this.prisma.class.findFirst({ where: { id: input.classId, }, }); if (!role) { return new HttpException('No role', HttpStatus.NOT_FOUND); } if (!clas) { return new HttpException('No class', HttpStatus.NOT_FOUND); } return await this.prisma.user.create({ data: { dateOfCreation: new Date(), name: input.name, email: input.email, password: hashedPassword, age: input.age, avatarUrl: input.avatarUrl, phoneNumber: input.phoneNumber, lastName: input.lastName, patronymic: input.patronymic, userRate: input.userRate, roleObj: { connect: { id: role.id, }, }, class: { connect: { id: input.classId, }, }, balance: input.balance, login: input.login }, }); } async getBalance(id: number): Promise<number | HttpException> { const user = await this.prisma.user.findFirst({ where: { id: id, }, }); if(user) return user.balance; return new HttpException('No User', HttpStatus.NOT_FOUND); } async setBalance(id: number, newBalance:number): Promise<number | HttpException>{ const user = await this.prisma.user.findFirst({ where: { id: id, }, }); if(user) return (await this.prisma.user.update({ where: { id: user.id, }, data: { balance: newBalance, } })).balance return new HttpException('No User', HttpStatus.NOT_FOUND); } }
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home | Casa Verde</title> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Elsie+Swash+Caps&family=Montserrat:wght@400;700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="./css/Base/base.css"> <link rel="stylesheet" href="./css/Componentes/cabecalho.css"> <link rel="stylesheet" href="./css/Componentes/botoes.css"> <link rel="stylesheet" href="./css/Componentes/imput.css"> <link rel="stylesheet" href="./css/Componentes/cartao.css"> <link rel="stylesheet" href="./css/Componentes/item.css"> <link rel="stylesheet" href="./css/Componentes/produto.css"> <link rel="stylesheet" href="./css/Componentes/video.css"> <link rel="stylesheet" href="./css/Componentes/rodape.css"> <link rel="stylesheet" href="./css/chamada.css"> <link rel="stylesheet" href="./css/como-conseguir.css"> <link rel="stylesheet" href="./css/ofertas.css"> </head> <body> <harder class="cabecalho container"> <img src="./Imagens/logo.svg" alt="logo" class="cabecalho__logo"> <a href="#" aria-label="Carrinho de Compras"> <img src="./Icon/carrinho.svg" alt="carrinho" class="cabecalho__carrinho"> </a> </harder> <main> <section class="chamada container"> <h2 class="titulo"> Sua casa com as <span class="titulo--destaque"> melhores plantas </span> </h2> <p class="chamada__texto texto"> Encontre aqui uma vasta seleção de plantas para decorar a sua casa e torná-lo uma pessoa mais feliz no seu dia a dia. Entre com seu e-mail e assine nossa newsletter para saber das novidades da marca </p> <img src="./Imagens/planta-chamada.png" alt="produto" class="chamada__imagem"> <form action="#" class="chamada__formulario"> <input type="text" class="input input--icone input--email" placeholder="Insira seu E-mail" aria-label="Insira seu E-mail"> <button class="botao">Assinar Newsletter</button> </form> </section> <section class="como-conseguir container"> <article class="cartao"> <h2 class="titulo alinhamento--meio">Como conseguir <span class="titulo--destaque">minha planta</span> </h2> <ul class="lista-item"> <li class="item"> <span class="item__icone item__icone--cursor"></span> <p>Escolha suas plantas</p> </li> <li class="item"> <span class="item__icone item__icone--carrinho"></span> <p>Faça seu pedido</p> </li> <li class="item"> <span class="item__icone item__icone--caminhao"></span> <p>Aguarde na sua casa</p> </li> </ul> </article> </section> <section class="container"> <h2 class="titulo alinhamento--meio"> Conheça nossos <span class="titulo--destaque">produtos</span> </h2> <ul> <li class="produto"> <img src="./Imagens/produto-01.png" alt="Foto do Produto" class="produto__imagem"> <div class="produto__conteudo"> <h3 class="produto__titulo titulo--destaque">Ajuga reptans</h3> <p class="produto__preco">R$ 20,00</p> <a href="#" class="produto__comprar"> Comprar <span class="produto__comprar--icone"> </span> </a> </div> </li> <li class="produto"> <img src="./Imagens/produto-02.png" alt="Foto do Produto" class="produto__imagem"> <div class="produto__conteudo"> <h3 class="produto__titulo titulo--destaque">Cordyline fruticosa</h3> <p class="produto__preco">R$ 20,00</p> <a href="#" class="produto__comprar"> Comprar <span class="produto__comprar--icone"> </span> </a> </div> </li> <li class="produto"> <img src="./Imagens/produto-03.png" alt="Foto do Produto" class="produto__imagem"> <div class="produto__conteudo"> <h3 class="produto__titulo titulo--destaque">Crassula ovata</h3> <p class="produto__preco">R$ 20,00</p> <a href="#" class="produto__comprar"> Comprar <span class="produto__comprar--icone"> </span> </a> </div> </li> <li class="produto"> <img src="./Imagens/produto-04.png" alt="Foto do Produto" class="produto__imagem"> <div class="produto__conteudo"> <h3 class="produto__titulo titulo--destaque">Cyperus rotundus</h3> <p class="produto__preco">R$ 20,00</p> <a href="#" class="produto__comprar"> Comprar <span class="produto__comprar--icone"> </span> </a> </div> </li> <li class="produto"> <img src="./Imagens/produto-05.png" alt="Foto do Produto" class="produto__imagem"> <div class="produto__conteudo"> <h3 class="produto__titulo titulo--destaque">Delairea odorata</h3> <p class="produto__preco">R$ 20,00</p> <a href="#" class="produto__comprar"> Comprar <span class="produto__comprar--icone"> </span> </a> </div> </li> <li class="produto"> <img src="./Imagens/produto-06.png" alt="Foto do Produto" class="produto__imagem"> <div class="produto__conteudo"> <h3 class="produto__titulo titulo--destaque">Datura metel</h3> <p class="produto__preco">R$ 20,00</p> <a href="#" class="produto__comprar"> Comprar <span class="produto__comprar--icone"> </span> </a> </div> </li> </ul> </section> <section class="container"> <h2 class="titulo alinhamento--meio"> Veja aqui nossos <span class="titulo--destaque">vídeos</span> </h2> <ul> <li class="cartao-de-video container"> <div class="cartao-de-video__video"> <img src="https://picsum.photos/278/252" alt="Capa do video"> </div> <h3 class="cartao-de-video__titulo">Video XYZ</h3> <p>Publicado em novembro de 2022</p> </li> <li class="cartao-de-video container"> <div class="cartao-de-video__video"> <img src="https://picsum.photos/278/252" alt="Capa do video"> </div> <h3 class="cartao-de-video__titulo">Video XYZ</h3> <p>Publicado em novembro de 2022</p> </li> <li class="cartao-de-video container"> <div class="cartao-de-video__video"> <img src="https://picsum.photos/278/252" alt="Capa do video"> </div> <h3 class="cartao-de-video__titulo">Video XYZ</h3> <p>Publicado em novembro de 2022</p> </li> <li class="cartao-de-video container"> <div class="cartao-de-video__video"> <img src="https://picsum.photos/278/252" alt="Capa do video"> </div> <h3 class="cartao-de-video__titulo">Video XYZ</h3> <p>Publicado em novembro de 2022</p> </li> </ul> </section> </main> <footer class="container rodape"> <img src="./Imagens/logo.svg" alt="logo" class="rodape__logo"> <ul class="rodape__social"> <li> <a href="#" class="rodape__social-midia" title="Facebook"> <img src="./Icon/facebook.svg" alt="facebook"> </a> </li> <li> <a href="#" class="rodape__social-midia" title="Twitter"> <img src="./Icon/twitter.svg" alt="twitter"> </a> </li> <li> <a href="#" class="rodape__social-midia" title="Instagram"> <img src="./Icon/instagram.svg" alt="instagram"> </a> </li> </ul> <address class="rodape__unidade texto"> <span class="rodape__unidade-titulo">Rio de Janeiro</span> Rua Siqueira Campos, 171, 303 <br> Copacabana<br> Telefone: (21) 99876-0099<br> </address> <address class="rodape__unidade texto"> <span class="rodape__unidade-titulo">São Paulo</span> Rua Anita Garibaldi, 33, 13 <br> Sé <br> Telefone: (11) 99875-2201 <br> </address> </footer> </body> </html>
// Copyright 2021 Datafuse Labs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::BTreeMap; use itertools::Itertools; use serde::Deserialize; use serde::Serialize; #[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, Default)] #[serde(default)] pub struct UserDefinedConnection { pub name: String, pub storage_type: String, pub storage_params: BTreeMap<String, String>, } impl UserDefinedConnection { pub fn new(name: &str, storage_type: String, storage_params: BTreeMap<String, String>) -> Self { Self { name: name.to_string(), storage_type: storage_type.to_lowercase(), storage_params: storage_params .into_iter() .map(|(k, v)| (k.to_lowercase(), v)) .collect::<BTreeMap<_, _>>(), } } pub fn storage_params_display(&self) -> String { self.storage_params .iter() .map(|(k, v)| format!("{}={}", k, v)) .join(" ") } }
package EverGrowth.com.EverGrowthserver.service; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import EverGrowth.com.EverGrowthserver.entity.CarritoEntity; import EverGrowth.com.EverGrowthserver.entity.DetallePedidoEntity; import EverGrowth.com.EverGrowthserver.entity.PedidoEntity; import EverGrowth.com.EverGrowthserver.entity.ProductoEntity; import EverGrowth.com.EverGrowthserver.entity.UsuarioEntity; import EverGrowth.com.EverGrowthserver.exception.ResourceNotFoundException; import EverGrowth.com.EverGrowthserver.helper.DataGenerationHelper; import EverGrowth.com.EverGrowthserver.repository.UsuarioRepository; import jakarta.transaction.Transactional; import EverGrowth.com.EverGrowthserver.repository.DetallePedidoRepository; import EverGrowth.com.EverGrowthserver.repository.PedidoRepository; @Service public class PedidoService { private Long contadorFactura = 0L; @Autowired PedidoRepository pedidoRepository; @Autowired UsuarioRepository UsuarioRepository; @Autowired UsuarioService UsuarioService; @Autowired SesionService sesionService; @Autowired ProductoService oProductoService; @Autowired DetallePedidoRepository detallePedidoRepository; @Autowired CarritoService oCarritoService; public PedidoEntity get(Long id) { return pedidoRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Pedido not found")); } public Long create(PedidoEntity oPedidoEntity) { oPedidoEntity.setId(null); return pedidoRepository.save(oPedidoEntity).getId(); } public Long getTotalPedidos() { sesionService.onlyAdmins(); return pedidoRepository.count(); } public PedidoEntity update(PedidoEntity oPedidoEntityToSet) { sesionService.onlyAdmins(); return pedidoRepository.save(oPedidoEntityToSet); } public Long delete(Long id) { if (pedidoRepository.findById(id).isPresent()) { pedidoRepository.deleteById(id); return id; } else { throw new ResourceNotFoundException("El pedido con el ID " + id + " no existe"); } } public Page<PedidoEntity> getPage(Pageable oPageable, Long id_usuario) { sesionService.onlyAdminsOrUsers(); if (id_usuario == 0) { return pedidoRepository.findAll(oPageable); } else { return pedidoRepository.findByUser(id_usuario, oPageable); } } public Long populate(Integer cantidad) { sesionService.onlyAdmins(); // Variable booleana para alternar entre dos y tres días boolean alternar = false; for (int i = 0; i < cantidad; i++) { PedidoEntity pedido = new PedidoEntity(); pedido.setUser(UsuarioService.getOneRandom()); pedido.setEstado_pedido(false); // Obtener la fecha actual LocalDateTime fechaActual = LocalDateTime.now(); // Calcular la cantidad de días para la entrega (dos o tres días alternando) int diasEntrega = alternar ? 3 : 2; // Calcular la fecha de entrega sumando los días correspondientes LocalDateTime fechaEntrega = fechaActual.plusDays(diasEntrega); pedido.setFecha_entrega(fechaEntrega); pedido.setFecha_pedido(fechaActual); pedidoRepository.save(pedido); // Alternar el valor booleano para el próximo pedido alternar = !alternar; } return pedidoRepository.count(); } public PedidoEntity getOneRandom() { Pageable oPageable = PageRequest.of((int) (Math.random() * pedidoRepository.count()), 1); return pedidoRepository.findAll(oPageable).getContent().get(0); } @Transactional public Long empty() { sesionService.onlyAdmins(); pedidoRepository.deleteAll(); pedidoRepository.resetAutoIncrement(); pedidoRepository.flush(); return pedidoRepository.count(); } @Transactional public PedidoEntity realizarCompraProducto(ProductoEntity oProductoEntity, UsuarioEntity oUsuarioEntity, int cantidad) { sesionService.onlyAdminsOrUsersWithIisOwnData(oUsuarioEntity.getId()); PedidoEntity oPedidoEntity = new PedidoEntity(); oPedidoEntity.setUser(oUsuarioEntity); oPedidoEntity.setFecha_pedido(LocalDateTime.now()); oPedidoEntity.setEstado_pedido(false); // Obtener la fecha actual LocalDateTime fechaActual = LocalDateTime.now(); // Variable booleana para alternar entre dos y tres días boolean alternar = (fechaActual.getDayOfMonth() % 2 == 0); // Alternar basado en el día del mes actual // Calcular la cantidad de días para la entrega (dos o tres días alternando) int diasEntrega = alternar ? 3 : 2; // Calcular la fecha de entrega sumando los días correspondientes LocalDateTime fechaEntrega = fechaActual.plusDays(diasEntrega); oPedidoEntity.setFecha_entrega(fechaEntrega); pedidoRepository.save(oPedidoEntity); DetallePedidoEntity oDetallePedidoEntity = new DetallePedidoEntity(); oDetallePedidoEntity.setId(null); oDetallePedidoEntity.setPrecio_unitario(oProductoEntity.getprecio()); oDetallePedidoEntity.setCantidad(cantidad); oDetallePedidoEntity.setPedidos(oPedidoEntity); oDetallePedidoEntity.setProductos(oProductoEntity); oDetallePedidoEntity.setIva(oProductoEntity.getIva()); detallePedidoRepository.save(oDetallePedidoEntity); oProductoService.actualizarStock(oProductoEntity, cantidad); return oPedidoEntity; } @Transactional public PedidoEntity realizarCompraUnicoCarrito(CarritoEntity oCarritoEntity, UsuarioEntity oUsuarioEntity) { sesionService.onlyAdminsOrUsersWithIisOwnData(oUsuarioEntity.getId()); PedidoEntity oPedidoEntity = new PedidoEntity(); oPedidoEntity.setUser(oUsuarioEntity); oPedidoEntity.setFecha_pedido(LocalDateTime.now()); oPedidoEntity.setEstado_pedido(false); // Obtener la fecha actual LocalDateTime fechaActual = LocalDateTime.now(); // Variable booleana para alternar entre dos y tres días boolean alternar = (fechaActual.getDayOfMonth() % 2 == 0); // Alternar basado en el día del mes actual // Calcular la cantidad de días para la entrega (dos o tres días alternando) int diasEntrega = alternar ? 3 : 2; // Calcular la fecha de entrega sumando los días correspondientes LocalDateTime fechaEntrega = fechaActual.plusDays(diasEntrega); oPedidoEntity.setFecha_entrega(fechaEntrega); pedidoRepository.save(oPedidoEntity); DetallePedidoEntity oDetallePedidoEntity = new DetallePedidoEntity(); oDetallePedidoEntity.setId(null); oDetallePedidoEntity.setPrecio_unitario(oCarritoEntity.getProducto().getprecio()); oDetallePedidoEntity.setCantidad(oCarritoEntity.getCantidad()); oDetallePedidoEntity.setPedidos(oPedidoEntity); oDetallePedidoEntity.setIva(oCarritoEntity.getProducto().getIva()); oDetallePedidoEntity.setProductos(oCarritoEntity.getProducto()); detallePedidoRepository.save(oDetallePedidoEntity); ProductoEntity producto = oCarritoEntity.getProducto(); oProductoService.actualizarStock(producto, oCarritoEntity.getCantidad()); oCarritoService.delete(oCarritoEntity.getId()); return oPedidoEntity; } @Transactional public PedidoEntity realizarCompraTodosCarritos(Page<CarritoEntity> carritos, UsuarioEntity oUsuarioEntity) { sesionService.onlyAdminsOrUsersWithIisOwnData(oUsuarioEntity.getId()); PedidoEntity oPedidoEntity = new PedidoEntity(); oPedidoEntity.setUser(oUsuarioEntity); oPedidoEntity.setFecha_pedido(LocalDateTime.now()); oPedidoEntity.setEstado_pedido(false); // Obtener la fecha actual LocalDateTime fechaActual = LocalDateTime.now(); // Variable booleana para alternar entre dos y tres días boolean alternar = (fechaActual.getDayOfMonth() % 2 == 0); // Alternar basado en el día del mes actual // Calcular la cantidad de días para la entrega (dos o tres días alternando) int diasEntrega = alternar ? 3 : 2; // Calcular la fecha de entrega sumando los días correspondientes LocalDateTime fechaEntrega = fechaActual.plusDays(diasEntrega); oPedidoEntity.setFecha_entrega(fechaEntrega); // Generar el código de factura Long codigoFactura = generarCodigoFactura(); // Asignar el código de factura al pedido oPedidoEntity.setId_factura(codigoFactura); // Guardar el pedido en la base de datos pedidoRepository.save(oPedidoEntity); // Procesar cada carrito carritos.forEach(carrito -> { DetallePedidoEntity oDetallePedidoEntity = new DetallePedidoEntity(); oDetallePedidoEntity.setId(null); oDetallePedidoEntity.setPrecio_unitario(carrito.getProducto().getprecio()); oDetallePedidoEntity.setCantidad(carrito.getCantidad()); oDetallePedidoEntity.setPedidos(oPedidoEntity); oDetallePedidoEntity.setProductos(carrito.getProducto()); oDetallePedidoEntity.setIva(carrito.getProducto().getIva()); detallePedidoRepository.save(oDetallePedidoEntity); // Actualizar el stock del producto ProductoEntity producto = carrito.getProducto(); oProductoService.actualizarStock(producto, carrito.getCantidad()); }); // Eliminar los carritos del usuario oCarritoService.deleteByUsuario(oUsuarioEntity.getId()); // Retornar el pedido que contiene el código de factura generado return oPedidoEntity; } private Long generarCodigoFactura() { Long ultimoCodigo = pedidoRepository.findMaxCodigoFactura(); if (ultimoCodigo == null) { contadorFactura = 1L; } else { contadorFactura = ultimoCodigo + 1L; } return contadorFactura; } public Long cancelarCompra(Long id) { PedidoEntity pedido = pedidoRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("Error: Compra no encontrada.")); sesionService.onlyAdminsOrUsersWithIisOwnData(pedido.getUser().getId()); if (pedidoRepository.existsById(id)) { Page<DetallePedidoEntity> detallesCompra = detallePedidoRepository.findByPedido(id, PageRequest.of(0, 1000)); for (DetallePedidoEntity detalleCompra : detallesCompra) { ProductoEntity productos = detalleCompra.getProductos(); int cantidad = detalleCompra.getCantidad(); oProductoService.actualizarStock(productos, -cantidad); } detallePedidoRepository.deleteAll(detallesCompra); pedidoRepository.deleteById(id); return id; } else { throw new ResourceNotFoundException("Error: La compra no existe."); } } // Encontrar a las compras de un usuario public Page<PedidoEntity> getComprasUsuario(Long usuario_id, Pageable oPageable) { sesionService.onlyAdminsOrUsersWithIisOwnData(usuario_id); return pedidoRepository.findByUser(usuario_id, oPageable); } public Map<String, Integer> obtenerCantidadPedidosPorMes() { Map<String, Integer> cantidadPedidosPorMes = new LinkedHashMap<>(); // Crear un array con los nombres de los meses en el orden correcto String[] mesesOrdenados = { "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" }; // Iterar sobre cada mes para obtener la cantidad de pedidos for (int mes = 1; mes <= 12; mes++) { // Realizar la consulta para obtener los pedidos por mes List<PedidoEntity> pedidos = pedidoRepository.findByMes(mes); // Contar la cantidad de pedidos para este mes int cantidadPedidos = pedidos.size(); // Agregar la cantidad de pedidos al mapa cantidadPedidosPorMes.put(mesesOrdenados[mes - 1], cantidadPedidos); } return cantidadPedidosPorMes; } }
import { Meta, StoryFn } from '@storybook/react'; import React from 'react'; import { action } from '@storybook/addon-actions'; import CashKickModal, { CashKickModalProps } from '.'; export default { title: 'organisms/CashKickModal', component: CashKickModal } as Meta; const Template: StoryFn<CashKickModalProps> = (args) => <CashKickModal {...args} />; export const Default = Template.bind({}); Default.args = { width: '400px', isOpen: true, handleCrossIconClick: () => action('Cross icon clicked'), handleCancelClick: () => action('Cancel button clicked'), handleCreateClick: () => action('Create button clicked'), onNameChange: (newName: string) => action('Name changed:'), }; export const Modal = Template.bind({}); Modal.args = { ...Default.args, width: '600px', };
#ifndef MWGUI_SPELLWINDOW_H #define MWGUI_SPELLWINDOW_H #include <memory> #include "spellicons.hpp" #include "spellmodel.hpp" #include "windowpinnablebase.hpp" namespace MWGui { class SpellView; class WindowNavigator; class SpellWindow : public WindowPinnableBase, public NoDrop { public: SpellWindow(DragAndDrop* drag); void updateSpells(); void onFrame(float dt) override; /// Cycle to next/previous spell void cycle(bool next); std::string_view getWindowIdForLua() const override { return "Magic"; } void focus(); protected: MyGUI::Widget* mEffectBox; ESM::RefId mSpellToDelete; void onEnchantedItemSelected(MWWorld::Ptr item, bool alreadyEquipped); void onSpellSelected(const ESM::RefId& spellId); void onModelIndexSelected(SpellModel::ModelIndex index); void onFilterChanged(MyGUI::EditBox* sender); void onDeleteClicked(MyGUI::Widget* widget); void onDeleteSpellAccept(); void askDeleteSpell(const ESM::RefId& spellId); void onPinToggled() override; void onTitleDoubleClicked() override; void onOpen() override; void onKeyButtonPressed(MyGUI::Widget* sender, MyGUI::KeyCode key, MyGUI::Char character); SpellView* mSpellView; std::unique_ptr<SpellIcons> mSpellIcons; MyGUI::EditBox* mFilterEdit; protected: MyGUI::IntSize highlightSizeOverride() override; MyGUI::IntCoord highlightOffset() override; ControlSet getControlLegendContents() override; private: void gamepadHighlightSelected(); void onFocusGained(MyGUI::Widget* sender, MyGUI::Widget* oldFocus); void onFocusLost(MyGUI::Widget* sender, MyGUI::Widget* newFocus); float mUpdateTimer; int mGamepadSelected; std::unique_ptr<WindowNavigator> mWindowNavigator; }; } #endif
package com.example.foodordering.controller.admin; import com.example.foodordering.controller.base.MainLayoutServlet; import com.example.foodordering.dto.FoodCreateDto; import com.example.foodordering.service.CategoryService; import com.example.foodordering.service.FoodService; import jakarta.inject.Inject; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.MultipartConfig; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.Part; import java.io.IOException; import java.math.BigDecimal; import java.util.List; import java.util.stream.Collectors; @MultipartConfig( fileSizeThreshold = 1024 * 1024, maxFileSize = 1024 * 1024 * 10, maxRequestSize = 1024 * 1024 * 100) @WebServlet(name = "adminFoodCreateServlet", value = "/admin/food/create") public class AdminFoodCreateServlet extends MainLayoutServlet { @Inject private FoodService foodService; @Inject private CategoryService categoryService; @Override protected void doGetSafe(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); request.setAttribute("id", id); request.setAttribute("categories", categoryService.findAll()); renderView("admin/food/create", request, response); } @Override protected void doPostSafe(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Part imagePart = request.getPart("image"); String imageName = imagePart.getSubmittedFileName(); long categoryId = Long.parseLong(request.getParameter("category-id")); String title = request.getParameter("title"); String description = request.getParameter("description"); BigDecimal price = new BigDecimal(request.getParameter("price")); List<Part> imageParts = request.getParts().stream() .filter(part -> "image".equals(part.getName())) .collect(Collectors.toList()); FoodCreateDto foodDto = new FoodCreateDto( null, categoryId, title, description, null, imageName, getServletContext().getRealPath(""), // D:/Study/V/JakartaEE/..... price, imageParts); long id = foodService.create(foodDto); response.sendRedirect( String.format( "%s?id=%s", request.getHeader("referer"), id)); } }
import { authMiddleware } from '@/http/middlewares/auth' import { rolesSchema } from '@saas/auth' import { FastifyInstance } from 'fastify' import { ZodTypeProvider } from 'fastify-type-provider-zod' import z from 'zod' export async function getMembership(app: FastifyInstance) { app .withTypeProvider<ZodTypeProvider>() .register(authMiddleware) .get( '/organization/:slug/membership', { schema: { tags: ['organizations'], summary: 'Get user membership on organization', security: [ { bearerAuth: [], }, ], params: z.object({ slug: z.string(), }), response: { 200: z.object({ membership: z.object({ id: z.string().uuid(), userId: z.string().uuid(), role: rolesSchema, organizationId: z.string().uuid(), }), }), }, }, }, async (request, reply) => { const { slug } = request.params const { membership } = await request.getUserMembership(slug) console.log('membership', membership) return reply.status(200).send({ membership: { id: membership.id, userId: membership.userId, role: membership.role, organizationId: membership.organizationId, }, }) } ) }
defmodule WoombatWeb.Router do use WoombatWeb, :router use Coherence.Router pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_flash plug :protect_from_forgery plug :put_secure_browser_headers plug Coherence.Authentication.Session end pipeline :protected do plug :accepts, ["html"] plug :fetch_session plug :fetch_flash plug :protect_from_forgery plug :put_secure_browser_headers plug Coherence.Authentication.Session, protected: true plug :put_user_token end pipeline :api do plug :accepts, ["json"] end scope "/" do pipe_through :browser coherence_routes() end scope "/" do pipe_through :protected coherence_routes :protected end scope "/", WoombatWeb do pipe_through :browser # Use the default browser stack end scope "/", WoombatWeb do pipe_through :protected get "/", PageController, :index end defp put_user_token(conn, _) do current_user = Coherence.current_user(conn).id user_id_token = Phoenix.Token.sign(conn, "user_id", current_user) conn |> assign(:user_id, user_id_token) end end
@import Main._ @def lnk(txt: String, url: String) = a(txt, href:=url) @val exampleTests = wd/'upickle/'test/"src"/'upickle/'example/"ExampleTests.scala" @val derivationTests = wd/'upickle/'test/"src-3"/'upickle/"DerivationTests.scala" @val enumTests = wd/'upickle/'test/"src-3"/'upickle/"EnumTests.scala" @val jvmExampleTests = wd/'upickle/'test/"src-jvm-2"/'upickle/'example/"JvmExampleTests.scala" @val macroTests = wd/'upickle/'test/'src/'upickle/"MacroTests.scala" @val optionsAsNullTests = wd/'upickle/'test/"src"/'upickle/'example/"OptionsAsNullTests.scala" @a( href := "https://github.com/lihaoyi/upickle-pprint", img( position.absolute, top := 0, right := 0, border := 0, src := "https://camo.githubusercontent.com/365986a132ccd6a44c23a9169022c0b5c890c387/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67", alt := "Fork me on GitHub", data.`canonical-src` := "https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" ) ) @sect("uPickle 3.1.3") @div(display.flex, alignItems.center, flexDirection.column) @div @a(href := "https://gitter.im/lihaoyi/upickle")( img(src := "https://badges.gitter.im/Join%20Chat.svg") ) @span(" ") @a(href := "https://www.patreon.com/lihaoyi")( img(src := "https://img.shields.io/badge/patreon-sponsor-ff69b4.svg") ) @p uPickle (pronounced micro-pickle) is a lightweight JSON and binary (MessagePack) serialization library for Scala. It's key features are: @ul @li @sect.ref("Getting Started", "Simple to use"), with nice human-readable JSON output @li Very high @sect.ref{Performance}; faster than @lnk("Play-Json", "https://github.com/playframework/play-json"), @lnk("Circe", "https://github.com/circe/circe"), or @lnk("Argonaut", "https://github.com/argonaut-io/argonaut") by a large margin @li Simple & easy to understand @sect.ref("uJson", "JSON Processing API"), that should be instantly familiar to anyone whose processed JSON in Python, Ruby, or Javascript @li Flexible and easily @sect.ref("Customization", "customizable") @li Zero dependencies; can be included in any project without worrying about conflicts @li @sect.ref("ScalaJS") support, allowing transfer of structured data between the JVM and Javascript @li Supports binary serialization via the MessagePack format, for even faster serialization/de-serialization and smaller payloads. @p This documentation is meant as a thorough reference to this library. For a hands-on introduction, take a look at the following blog post: @ul @li @lnk("How to work with JSON in Scala", "http://www.lihaoyi.com/post/HowtoworkwithJSONinScala.html") @sect{Getting Started} @hl.scala "com.lihaoyi" %% "upickle" % "3.1.3" // SBT ivy"com.lihaoyi::upickle:3.1.3" // Mill @p And then you can immediately start writing and reading common Scala objects to strings: @hl.ref(exampleTests, Seq("\"simple\"", "")) @p Or to compact byte arrays, using the @lnk("MessagePack", "https://msgpack.org/index.html") format: @hl.ref(exampleTests, Seq("\"binary\"", "")) @sect{ScalaJS} @p For ScalaJS applications, use this dependencies instead: @hl.scala "com.lihaoyi" %%% "upickle" % "3.1.3" // SBT ivy"com.lihaoyi::upickle::3.1.3" // Mill @sect{Scala Versions} @p uPickle supports Scala 2.12, 2.13 and 3.1+ @sect{Basics} @sect{Builtins} @p This is a non-comprehensive list of what the most commonly-used types pickle to using uPickle. To begin, let's import upickle @hl.scala import upickle.default._ @sect{Primitives} @p Booleans are serialized as JSON booleans @hl.ref(exampleTests, Seq("\"more\"", "\"booleans\"", "")) @p Numbers are serialized as JSON numbers @hl.ref(exampleTests, Seq("\"more\"", "\"numbers\"", "")) @p Except for @hl.scala{Long}s, which too large for Javascript. These are serialized as JSON Strings, keeping the interchange format compatible with the browser's own JSON parser, which provides the best performance in Scala.js @hl.ref(exampleTests, Seq("\"more\"", "\"longs\"", "")) @p Special values of @hl.scala{Double}s and @hl.scala{Float}s are also serialized as Strings @hl.ref(exampleTests, Seq("\"more\"", "\"specialNumbers\"", "")) @p Both @hl.scala{Char}s and @hl.scala{String}s are serialized as Strings @hl.ref(exampleTests, Seq("\"more\"", "\"charStrings\"", "")) @sect{Collections} @p @code{Array}s and most immutable collections are serialized as JSON lists @hl.ref(exampleTests, Seq("\"more\"", "\"seqs\"", "")) @p @code{Option}s are serialized as JSON lists with 0 or 1 element @hl.ref(exampleTests, Seq("\"more\"", "\"options\"", "")) @p Tuples of all sizes (1-22) are serialized as heterogenous JSON lists @hl.ref(exampleTests, Seq("\"more\"", "\"tuples\"", "")) @p @code{Map}s with primitive keys are serialized into JSON dictionaries, while @code{Map} with complex keys are serialized into lists of 2-element tuples @hl.ref(exampleTests, Seq("\"more\"", "\"maps\"", "")) @sect{Case Classes} @p Case classes of sizes 1-64 are serialized as JSON dictionaries with the keys being the names of each field. To begin with, you need to define a serializer in the Case Class's companion object: @hl.scala import upickle.default.{ReadWriter => RW, macroRW} @p After that, you can begin serializing that case class. @hl.ref(exampleTests, Seq("object Simple", "")) @hl.ref(exampleTests, Seq("\"more\"", "\"caseClass\"", ""), " }") @p Sealed hierarchies are serialized as tagged values, the serialized object tagged with the full name of the instance's class: @hl.ref(exampleTests, Seq("object Sealed", "")) @hl.ref(exampleTests, Seq("\"more\"", "\"sealed\"", ""), " }") @p Serializability is recursive; you can serialize a type only if all its members are serializable. That means that collections, tuples and case-classes made only of serializable members are themselves serializable @hl.ref(exampleTests, Seq("object Recursive", "")) @hl.ref(exampleTests, Seq("\"more\"", "\"recursive\"", ""), " }") @sect{Scala 3 Deriving} @p In Scala 3, you can use the @hl.scala{derives} keyword on standalone @hl.scala{case class}es, @hl.scala{sealed trait} hierarchies, and @hl.scala{enum}s: @hl.ref(derivationTests, "case class Dog", "") @hl.ref(derivationTests, Seq("\"example\"", "\"dog\"", "")) @hl.ref(derivationTests, Seq("sealed trait Animal"), Seq("case object Cthulu", "")) @hl.ref(derivationTests, Seq("\"example\"", "\"animal\"", "")) @hl.ref(enumTests, "enum SimpleEnum", "end SimpleEnum") @hl.ref(enumTests, Seq("example", "simple", "")) @hl.ref(enumTests, "enum ColorEnum", "end ColorEnum") @hl.ref(enumTests, Seq("example", "color", "Enclosing")) @p Note that you only need to put the @hl.scala{derives} keyword on the @hl.scala{enum}s or @hl.scala{sealed trait}s, and not on all the individual @hl.scala{case class}es or @hl.scala{case object}s. @p Also, note that for @hl.scala{enum}s, the short un-qualified name is used for the type key, rather than the fully qualified name with package path. This is because unlike @hl.scala{sealed trait}s, @hl.scala{enum}s enforce that every case is in the same flat namespace, and thus the short name is enough to dis-ambiguate them. This behavior can be overriden with the @hl.scala("""@key("...")""") annotation in both cases, if a different type key is desired. @sect{Read/Writing Other Things} @p Apart from reading & writing @code{java.lang.String}s, allows you to easily read from alternate sources such as @code{CharSequence}s, @code{Array[Byte]}s, @code{java.io.File}s and @code{java.nio.file.Path}s: @hl.ref(exampleTests, Seq("\"sources\"", ""), " }") @hl.ref(jvmExampleTests, Seq("\"sources\"", ""), " }") @p Reading from large files is automatically streamed so you do not read the entire file into memory. You can use @code{writeTo} to serialize your data to an arbitrary @code{java.io.Writer}/@code{java.io.OutputStream}: this can be streamed directly to files or over the network without having to accumulate the serialized JSON in memory. @sect{Nulls} @p Nulls serialize into JSON nulls, as you would expect @hl.ref(exampleTests, Seq("\"more\"", "\"null\"", ""), " }") @p uPickle only throws exceptions on unpickling; if a pickler is properly defined, serializing a data structure to a @hl.scala{String} should never throw an exception. @p All these examples can be similarly serialized to MessagePack-formatted binaries, in the same way: JSON booleans become MessagePack booleans, lists become MessagePack lists, and so on. Reading and writing MessagePack binary data is typically significantly faster than reading and writing JSON, and the serialized data is also significantly smaller. @sect{Defaults} @p If a field is missing upon deserialization, uPickle uses the default value if one exists @hl.ref(exampleTests, Seq("\"defaults\"", "\"reading\"", ""), " }") @p If a field at serialization time has the same value as the default, uPickle leaves it out of the serialized blob @hl.ref(exampleTests, Seq("\"defaults\"", "\"writing\"", ""), " }") @p This allows you to make schema changes gradually, assuming you have already pickled some data and want to add new fields to the case classes you pickled. Simply give the new fields a default value (e.g. @hl.scala{""} for Strings, or wrap it in an @hl.scala{Option[T]} and make the default @hl.scala{None}) and uPickle will happily read the old data, filling in the missing field using the default value. @sect{Supported Types} @p Out of the box, uPickle supports writing and reading the following types: @ul @li @hl.scala{Boolean}, @code{Byte}, @code{Char}, @code{Short}, @code{Int}, @code{Long}, @code{Float}, @code{Double} @li @code{Tuple}s from 1 to 22 @li Immutable @code{Seq}, @code{List}, @code{Vector}, @code{Set}, @code{SortedSet}, @code{Option}, @code{Array}, @code{Map}s, and all other collections with a reasonable @hl.scala{CanBuildFrom} implementation @li @code{Duration}, @code{Either} @li Stand-alone @hl.scala{case class}es and @hl.scala{case object}s, and their generic equivalents, @li Non-generic @hl.scala{case class}es and @hl.scala{case object}s that are part of a @hl.scala{sealed trait} or @hl.scala{sealed class} hierarchy @li @hl.scala{sealed trait} and @hl.scala{sealed class}es themselves, assuming that all subclasses are picklable @li @code{UUID}s @li @hl.scala{null} @p Readability/writability is recursive: a container such as a @code{Tuple} or @hl.scala{case class} is only readable if all its contents are readable, and only writable if all its contents are writable. That means that you cannot serialize a @hl.scala{List[Any]}, since uPickle doesn't provide a generic way of serializing @code{Any}. Case classes are only serializable up to 64 fields. @p Case classes are serialized using the @hl.scala{apply} and @hl.scala{unapply} methods on their companion objects. This means that you can make your own classes serializable by giving them companions @hl.scala{apply} and @hl.scala{unapply}. @hl.scala{sealed} hierarchies are serialized as tagged unions: whatever the serialization of the actual object, together with the fully-qualified name of its class, so the correct class in the sealed hierarchy can be reconstituted later. @p That concludes the list of supported types. Anything else is not supported by default, but you can add support using @sect.ref{Custom Picklers} @sect{Common Operations} @p The following common operations are available on any uPickle module, e.g. @code{upickle.default} or @code{upickle.legacy}: @hl.ref(wd/'upickle/'src/'upickle/"Api.scala", Seq("trait Api"), "// End Api") @sect{Customization} @sect{Custom Picklers} @hl.ref(exampleTests, Seq("\"mapped\"", "\"simple\"", ""), "}") @p You can use the @code{readwriter[T].bimap[V]} function to create a pickler that reads/writes a type @code{V}, using the pickler for type @code{T}, by providing a conversion function between them. @p The type you are @code{.bimap}ing to doesn't need to be a case class, or be pickleable in any way, as long as the type you are @code{.bimap}ing from is pickleable. The following example demonstrates using @code{.bimap} to define a serializer for non-case Scala class @hl.ref(exampleTests, Seq("object Custom2", "")) @p Note that when writing custom picklers, it is entirely up to you to get it right, e.g. making sure that an object that gets round-trip pickled/unpickled comes out the same as when it started. @p Lastly, if you want more control over exactly how something is serialized, you can use @code{readwriter[Js.Value].bimap} to give yourself access to the raw JSON AST: @hl.ref(exampleTests, Seq("\"mapped\"", "\"Value\"", "")) @sect{Custom Keys} @p uPickle allows you to specify the key that a field is serialized with via a @hl.scala{@@key} annotation @hl.ref(exampleTests, Seq("object Keyed", "")) @hl.ref(exampleTests, Seq("\"keyed\"", "\"attrs\"", "")) @p Practically, this is useful if you want to rename the field within your Scala code while still maintaining backwards compatibility with previously-pickled objects. Simple rename the field and add a @hl.scala{@@key("...")} with the old name so uPickle can continue to work with the old objects correctly. @p You can also use @hl.scala{@@key} to change the name used when pickling the case class itself. Normally case classes are pickled without their name, but an exception is made for members of sealed hierarchies which are tagged with their fully-qualified name. uPickle allows you to use @hl.scala{@@key} to override what the class is tagged with: @hl.ref(exampleTests, Seq("object KeyedTag", "")) @hl.ref(exampleTests, Seq("\"keyed\"", "\"tag\"", "")) @p This is useful in cases where: @ul @li you wish to rename the class within your Scala code, or move it to a different package, but want to preserve backwards compatibility with previously pickled instances of that class @li you try to tackle the resource issue (bandwidth, storage, CPU) because FQNs might get quite long @sect{JSON Dictionary Formats} @p By default, serializing a @hl.scala{Map[K, V]} generates a nested array-of-arrays. This is because not all types @code{K} can be easily serialized into JSON strings, so keeping them as nested tuples preserves the structure of the serialized @code{K} values: @hl.ref(exampleTests, Seq("nonCustomMapKeys", "")) @p For types of @code{K} that you want to serialize to JSON strings in JSON dictionaries, you can wrap your @hl.scala{ReadWriter[K]} in a @hl.scala{stringKeyRW}. @hl.ref(exampleTests, Seq("customMapKeys", "")) @p Note that this only works for types @code{K} which serialize to JSON primitives: numbers, strings, booleans, and so on. Types of @code{K} that serialize to complex structures like JSON arrays or dictionaries are unsupported for use a JSON dictionary keys. @p Older versions of uPickle serialized almost all @hl.scala{Map[K, V]}s to nested arrays. Data already serialized in that format is forwards-compatible with the current implementation of uPickle, which can read both nested-json-arrays and json-dictionary formats without issue. @p These subtleties around deciding between nested-json-array v.s. json-dictionary formats only apply to uPickle's JSON backend. When serializing to MessagePack using @hl.scala{upickle.default.writeBinary} or @hl.scala{upickle.default.writeMsg}, it always uses the dictionary-based format, since MessagePack does not have the restriction that dictionary keys can only be strings: @hl.ref(exampleTests, Seq("msgPackMapKeys", "")) @sect{Custom Configuration} @p Often, there will be times that you want to customize something on a project-wide level. uPickle provides hooks in letting you subclass the @hl.scala{upickle.Api} trait to create your own bundles apart from the in-built @hl.scala{upickle.default} and @hl.scala{upickle.legacy}. The following example demonstrates how to customize a bundle to automatically @code{snake_case} all dictionary keys. @hl.ref(exampleTests, Seq("\"snakeCase\"", "")) @p If you are using uPickle to convert JSON from another source into Scala data structures, you can also configure it to map @hl.scala{Option[T]}s to @code{null}s when the option is @code{None}: @hl.ref(optionsAsNullTests, "object OptionPickler", "// end_ex") @p This custom configuration allows you to treat @hl.scala{null}s as @hl.scala{None}s and anything else as @hl.scala{Some(...)}s. Simply @hl.scala{import OptionPickler._} instead of the normal uPickle import throughout your project and you'll have the customized reading/writing available to you. @p You can also use a custom configuration to change how 64-bit @code{Long}s are handled. By default, small longs that can be represented exactly in 64-bit @code{Double}s are written as raw numbers, while larger values (n > 2^53) are written as strings. This is to ensure the values are not truncated when the serialized JSON is then manipulated, e.g. by Javascript which truncates all large numbers to Doubles. If you wish to always write Longs as Strings, or always write them as numbers (at risk of truncation), you can do so as follows: @hl.ref(exampleTests, Seq("stringLongs", "")) @sect{Limitations} @p uPickle doesn't currently support: @ul @li Circular object graphs @li Reflective reading and writing @li Read/writing of untyped values e.g. @code{Any} @li Read/writing arbitrarily shaped objects @li Read/writing case classes with multiple parameter lists. @p Most of these limitations are inherent in the fact that ScalaJS does not support reflection, and are unlikely to ever go away. In general, uPickle by default can serialize statically-typed, tree-shaped, immutable data structures. Anything more complex requires @sect.ref{Custom Picklers} @sect{Manual Sealed Trait Picklers} @p Due to a bug in the Scala compiler SI-7046, automatic sealed trait pickling can fail unpredictably. This can be worked around by instead using the @code{macroRW} and @code{merge} methods to manually specify which sub-types of a sealed trait to consider when pickling: @hl.ref(macroTests, "sealed trait TypedFoo", "// End TypedFoo") @sect{uJson} @p uJson is uPickle's JSON library, which can be used to easily manipulate JSON source and data structures without converting them into Scala case-classes. This all lives in the @code{ujson} package. Unlike many other Scala JSON libraries that come with their own zoo of new concepts, abstractions, and techniques, uJson has a simple & predictable JSON API that should be instantly familiar to anyone coming from scripting languages like Ruby, Python or Javascript. @p uJson comes bundled with uPickle, or can be used stand-alone via the following package coordinates: @hl.scala libraryDependencies += "com.lihaoyi" %% "ujson" % "0.9.6" @sect{Construction} @p You can use @code{ujson} to conveniently construct JSON blobs, either programmatically: @hl.ref(exampleTests, Seq("\"json\"", "\"construction\"", ""), "}") @p Or parsing them from strings, byte arrays or files: @hl.ref(exampleTests, Seq("\"json\"", "\"simple\"", ""), "}") @p @code{ujson.Js} ASTs are mutable, and can be modified before being re-serialized to strings: @hl.ref(exampleTests, Seq("\"json\"", "\"mutable\"", ""), "}") @p You can also use the `_` shorthand syntax to update a JSON value in place, without having to duplicate the whole path: @hl.ref(exampleTests, Seq("\"json\"", "\"update\"", ""), "}") @p case classes or other Scala data structures can be converted to @code{ujson.Js} ASTs using @code{upickle.default.writeJs}, and the @code{ujson.Js} ASTs can be converted back using @code{upickle.default.readJs} or plain @code{upickle.default.read}: @hl.ref(exampleTests, Seq("\"json\"", "\"intermediate\"", ""), "}") @sect{JSON Utilities} @p uJson comes with some convenient utilities on the `ujson` package: @hl.ref(wd/'ujson/'src/'ujson/"package.scala", Seq("package object ujson", ""), "// End ujson") @sect{Transformations} @p uJson allows you seamlessly convert between any of the following forms you may find your JSON in: @ul @li Case classes & Scala data-types @li @code{ujson.Js} ASTs @li @code{String}s @li @code{CharSequence}s @li @code{Array[Byte]}s @li Third-party JSON ASTs (Argonaut, Circe, Json4s, Play-Json) @p This is done using the @code{ujson.transform(source, dest)} function: @hl.ref(exampleTests, Seq("\"json\"", "\"misc\"", ""), "}") @p All transformations from A to B using @code{ujson.transform} happen in a direct fashion: there are no intermediate JSON ASTs being generated, and performance is generally very good. @p You can use @code{ujson.transform} to validate JSON in a streaming fashion: @hl.ref(exampleTests, Seq("\"json\"", "\"validate\"", ""), "}") @p The normal @code{upickle.default.read/write} methods to serialize Scala data-types is just shorthand for ujson.transform, using a @code{upickle.default.transform(foo)} as the source or a @code{upickle.default.reader[Foo]} as the destination: @hl.ref(exampleTests, Seq("\"json\"", "\"upickleDefault\"", ""), "}") @sect{Other ASTs} @p uJson does not provide any other utilities are JSON that other libraries do: zippers, lenses, combinators, etc.. However, uJson can be used to seamlessly convert between the JSON AST of other libraries! This means if some other library provides a more convenient API for some kind of processing you need to do, you can easily parse to that library's AST, do whatever you need, and convert back after. @p As mentioned earlier, conversions are fast and direct, and happen without creating intermediate JSON structures in the process. The following examples demonstrate how to use the conversion modules for @lnk("Argonaut", "http://argonaut.io/doc/"), @lnk("Circe", "https://github.com/circe/circe"), @lnk("Json4s", "https://github.com/json4s/json4s"), and @lnk("Play Json", "https://github.com/playframework/play-json"). @p Each example parses JSON from a string into that particular library's JSON AST, manipulates the AST using that library, un-pickles it into Scala data types, then serializes those data types first into that library's AST then back to a st.ring @sect{Argonaut} @b{Maven Coordinates} @hl.scala libraryDependencies += "com.lihaoyi" %% "ujson-argonaut" % "0.9.6" @b{Usage} @hl.ref(jvmExampleTests, Seq("\"argonaut\"", ""), "}") @sect{Circe} @b{Maven Coordinates} @hl.scala libraryDependencies += "com.lihaoyi" %% "ujson-circe" % "0.9.6" @b{Usage} @hl.ref(jvmExampleTests, Seq("\"circe\"", ""), "}") @sect{Play-Json} @b{Maven Coordinates} @hl.scala libraryDependencies += "com.lihaoyi" %% "ujson-play" % "0.9.6" @b{Usage} @hl.ref(jvmExampleTests, Seq("\"playJson\"", ""), "}") @sect{Json4s} @b{Maven Coordinates} @hl.scala libraryDependencies += "com.lihaoyi" %% "ujson-json4s" % "0.9.6" @b{Usage} @hl.ref(jvmExampleTests, Seq("\"json4s\"", ""), "}") @sect{Cross-Library Conversions} @p uJson lets you convert between third-party ASTs efficiently and with minimal overhead: uJson converts one AST to the other directly and without any temporary compatibility data structures. The following example demonstrates how this is done: we parse a JSON string using Circe, perform some transformation, convert it to a Play-Json AST, perform more transformations, and finally serialize it back to a String and check that both transformations were applied: @hl.ref(jvmExampleTests, Seq("\"crossAst\"", ""), "}") @sect{uPack} @p uPack is uPickle's MessagePack library, which can be used to easily manipulate MessagePack source and data structures without converting them into Scala case-classes. This all lives in the @code{upack} package. @p uPack comes bundled with uPickle, or can be used stand-alone via the following package coordinates: @hl.scala libraryDependencies += "com.lihaoyi" %% "upack" % "0.9.6" @p The following basic functions are provided in the @code{upack} package to let you read and write MessagePack structs: @hl.ref(wd/'upack/'src/'upack/"package.scala", Seq("package object upack", "")) @p MessagePack structs are represented using the @code{upack.Msg} type. You can construct ad-hoc MessagePack structs using @code{upack.Msg}, and can similarly parse binary data into @code{upack.Msg} for ad-hoc querying and manipulation, without needing to bind it to Scala case classes or data types: @hl.ref(wd/'upickle/'test/'src/'upickle/'example/"ExampleTests.scala", Seq("\"msgConstruction\"", "")) @p You can read/write Scala values to @code{upack.Msg}s using @code{readBinary}/@code{writeMsg}: @hl.ref(wd/'upickle/'test/'src/'upickle/'example/"ExampleTests.scala", Seq("\"msgReadWrite\"", "")) @p Or include @code{upack.Msg}s inside @code{Seq}s, case-classes and other data structures when you read/write them: @hl.ref(wd/'upickle/'test/'src/'upickle/'example/"ExampleTests.scala", Seq("\"msgInsideValue\"", "")) @p You can also convert the uPack messages or binaries to @code{ujson.Value}s via @code{upack.transform}. This can be handy to help debug what's going on in your binary message data: @hl.ref(wd/'upickle/'test/'src/'upickle/'example/"ExampleTests.scala", Seq("\"msgToJson\"", "")) @p Note that such a conversion between MessagePack structs and JSON data is lossy: some MessagePack constructs, such as binary data, cannot be exactly represented in JSON and have to be converted to strings. Thus you should not rely on being able to round-trip data between JSON <-> MessagePack and getting the same thing back, although round tripping data between Scala-data-types <-> JSON and Scala-data-types <-> MessagePack should always work. @p Some of the differences between the ways things are serialized in MessagePack and JSON include: @ul @li Large Longs in JSON are represented as @code{ujson.Str}s if n > 2^53; in MessagePack, they are represented as @code{upack.Int64}s or @code{upack.UInt64}s @li @code{Array[Byte]}s in JSON are represented as lists of numbers; in MessagePack, they are represented as @code{upack.Binary} @p If you need to construct Scala case classes or other data types from your MessagePack binary data, you should directly use @code{upickle.default.readBinary} and @code{upickle.default.writeBinary}: these bypass the @code{upack.Msg} struct entirely for the optimal performance. @sect{Performance} @p The uPickle has a small set of benchmarks in @code{bench/} that tests reading and writing performance of a few common JSON libraries on a small, somewhat arbitrary workload. The numbers below show how many times each library could read/write a small data structure in 25 seconds (bigger numbers better). In some libraries, caching the serializers rather than re-generating them each read/write also improves performance: that effect can be seen in the @code{(Cached)} columns. @sect{JVM Case Class Serialization Performance} @p uPickle runs 30-50% faster than Circe for reads/writes, and ~200% faster than play-json. @table(cls := "pure-table", textAlign.right) @thead @tr @th{Library} @th{Reads} @th{Writes} @th{Reads (Cached)} @th{Write (Cached)} @tbody @tr @td{Play Json 2.9.2} @td{331} @td{296} @td{361} @td{309} @tr @td{Circe 0.13.0} @td{517} @td{504} @td{526} @td{502} @tr @td{upickle.default 1.3.0 (JSON Strings)} @td{809} @td{728} @td{822} @td{864} @tr @td{upickle.default 1.3.0 (JSON Array[Byte])} @td{761} @td{706} @td{774} @td{830} @tr @td{upickle.default 1.3.0 (MsgPack Array[Byte])} @td{1652} @td{1264} @td{1743} @td{1753} @p As you can see, uPickle's JSON serialization is pretty consistently ~50% faster than Circe for reads and writes, and 100-200% faster than Play-Json, depending on workload. @p uPickle's binary MessagePack backend is then another 100% faster than uPickle JSON. @p uPickle achieves this speed by avoiding the construction of an intermediate JSON AST: while most libraries parse from @code{String -> AST -> CaseClass}, uPickle parses input directly from @code{String -> CaseClass}. uPickle also provides a @code{ujson.Js} AST that you can use to manipulate arbitrary JSON, but @code{ujson.Js} plays no part in parsing things to case-classes and is purely for users who want to manipulate JSON. @sect{JS Case Class Serialization Performance} @p While all libraries are much slower on Scala.js/Node.js than on the JVM, uPickle runs 4-5x as fast as Circe or Play-Json for reads and writes. @table(cls := "pure-table", textAlign.right) @thead @tr @th{Library} @th{Reads} @th{Writes} @th{Reads (Cached)} @th{Write (Cached)} @tbody @tr @td{Play Json 2.9.2} @td{64} @td{81} @td{66} @td{86} @tr @td{Circe 0.13.0} @td{98} @td{121} @td{99} @td{99} @tr @td{upickle.default 1.3.0 (JSON String)} @td{76} @td{40} @td{76} @td{44} @tr @td{upickle.default 1.3.0 (JSON Array[Byte]} @td{68} @td{107} @td{69} @td{112} @tr @td{upickle.default.web 1.3.0 (JSON String)} @td{349} @td{327} @td{353} @td{465} @tr @td{upickle.default 1.3.0 (MsgPack Array[Byte])} @td{85} @td{104} @td{85} @td{110} @p On Scala.js, uPickle's performance is comparable to othersl ike Play JSON or Circe. However, uPickle also exposes the @code{upickle.default.web} API, allowing you to use the JS runtime's built-in JSON parser to power serialization and deserialization. This ends up being 4-6x faster than the Scala-based JSON parsers of all the libraries compared (uPickle, Play-JSON, Circe) @p uJson is a fork of Erik Osheim's excellent [Jawn](https://github.com/non/jawn) JSON library, and inherits a lot of it's performance from Erik's work. @sect{Version History} @sect{3.1.3} @ul @li Fix reading of numbers as strings, e.g. @hl.scala{upickle.default.read[Seq[String]]("[12345678901234567890]") ==> Seq("12345678901234567890")}, for scenarios where you want to read JSON numbers "as is", preserving the exact string representation, without rounding, truncation, or overflow. @sect{3.1.2} @ul @li Fix parsing of large integers into @code{ujson.Num}s @lnk("#504", "https://github.com/com-lihaoyi/upickle/pull/504") @sect{3.1.1} @ul @li Bumped Scala versions: 3.3.0, @lnk("#492", "https://github.com/com-lihaoyi/upickle/pull/492"), 2.13.11 @lnk("#497", "https://github.com/com-lihaoyi/upickle/pull/497"), 2.12.18 @lnk("#496", "https://github.com/com-lihaoyi/upickle/pull/492"), @li Make empty arrays and dictionaries render compactly even when indent > 0 @lnk("#501", "https://github.com/com-lihaoyi/upickle/pull/501"), @li Improve @code{expected tagged dictionary} error message and make it work for non-empty dicts @lnk("#502", "https://github.com/com-lihaoyi/upickle/pull/502"), @sect{3.1.0} @ul @li Across-the-board performance optimizations @lnk("#467", "https://github.com/com-lihaoyi/upickle/pull/467") @li Make @hl.scala{derives} properly handle @hl.scala{abstract class}es in Scala 3 @lnk("#470", "https://github.com/com-lihaoyi/upickle/pull/470") @li Use a NotGiven implicit to avoid infinite loops caused by @code{superTypeWriter}/@code{superTypeReader} @lnk("#471", "https://github.com/com-lihaoyi/upickle/pull/471") @li Fix ClassCastException on @hl.scala{import given} @lnk("#472", "https://github.com/com-lihaoyi/upickle/pull/472") @li Added readwriters for @code{SortedMap} and @code{LinkedHashMap} @lnk("#479", "https://github.com/com-lihaoyi/upickle/pull/479") @sect{3.0.0} @ul @li Greatly improved speed and runtime-time safety for Scala 3 macros. These were previously much slower than Scala 2, and are now of roughly identical performance @lnk("#445", "https://github.com/com-lihaoyi/upickle/pull/445") @li Fixed infinite compile-loop issue on Scala 3 @li Support for the @hl.scala{deriving} keyword in Scala 3, on both @hl.scala{enum}s and @hl.scala{sealed trait}s @lnk("#453", "https://github.com/com-lihaoyi/upickle/pull/453") @li Ensured, that @code{ujson.Value}s behave properly as a direct target of reading and writing operations @lnk("#436", "https://github.com/com-lihaoyi/upickle/pull/436") @li @b{Updated geny dependency from 0.7.1 to 1.0.0. This breaks binary compatibility, hence we increased the major version number.} @li uPickle now applies Semantic Versioning and follows the SemVer spec @li @hl.scala{ujson.Bool} pattern matching is now exhaustive @lnk("#461", "https://github.com/com-lihaoyi/upickle/pull/461") @li Various library dependency updates @li Added readers and writers for the @hl.scala("java.lang") boxed versions of primitive types @lnk("#462", "https://github.com/com-lihaoyi/upickle/pull/462") @li Always use UTF-8 when reading JSON bytes regardless of JVM default charset @lnk("#464", "https://github.com/com-lihaoyi/upickle/pull/464") @sect{2.0.0} @ul @li @b{2.0.0 is a major breaking change in uPickle, including in the serialization format for many common data types (@hl.scala{Map}s, @hl.scala{case object}s, @hl.scala{Unit}, etc.). Please be careful upgrading and follow the instructions below.} @li If you are upgrading a system with multiple components from an earlier version of uPickle, please ensure you first upgrade every component to uPickle 1.6.0, which is forwards-compatible with the changes in uPickle 2.0.0. Only when every component is upgraded to 1.6.0 should you begin upgrading components to 2.0.0 @li Once every component is upgraded to 1.6.0, they will be able to @i{read} both the old and new serialization formats, though they will still be @i{writing} the old format. You can then upgrade your components piecemeal to 2.0.0 without any incompatibility. @li uPickle 2.0.0 will @i{write} using the new serialization formats, but will be able to @i{read} both old and new formats indefinitely. Thus if you have data in storage using the old format, you do not need to migrate it to the new format, and it can remain as-is until it needs to be re-written for other reasons. @li @b{Major serialization changes are below} @li @hl.scala{case object}s are now serialized as literal strings @hl.scala{"foo.bar.Qux"} rather than JSON dictionaries @hl.scala("""{"$type": "foo.bar.Qux"}""") @lnk("#382", "https://github.com/com-lihaoyi/upickle/pull/382"). This also applies to Scala 3 Enums @lnk("378", "https://github.com/com-lihaoyi/upickle/pull/378") @li @hl.scala{Map}s with primitive keys can now be serialized as JSON dictionaries @hl.scala("""{"foo": "bar", "baz": "qux"}"""), rather than as nested tuples @hl.scala("""[["foo", "bar"], ["baz", "qux"]]""") @lnk("#381", "https://github.com/com-lihaoyi/upickle/pull/381"). This applies to numbers, booleans, strings, @code{java.util.UUID}s, @code{BigIntegers}, @code{BigDecimals}, @code{scala.Symbol}s, @code{scala.concurrent.Duration}, and can be enabled for user-defined types. See @sect.ref{JSON Dictionary Formats} for more information @li @code{scala.Unit} now serializes as @hl.scala{null} rather than @hl.scala("{}") @sect{1.6.0} @ul @li Forwards compatibility for uPickle 2.x (@lnk("#385", "https://github.com/com-lihaoyi/upickle/pull/385")). This reduces the strictness of deserialization logic to allow parsing of both old and new formats: @code{Map}s can be deserialized from both JSON list-of-list and JSON dictionary formats, numbers can be deserialized from strings, and @code{Unit} can be deserialized from empty JSON dictionaries or nulls @li Automatic serialization of @hl.scala{case object}s has been removed, due to confusing bugs in how its implicit macro interacted with other implicit definitions. You now need to define @hl.scala{case object} serializers manually, via @hl.scala{implicit val rw: RW[MyCaseObject.type] = macroRW} @sect{1.5.0} @ul @li Support Scala-Native on Scala 3 @sect{1.4.3} @ul @li @code{MsgPackReader}: properly increment index in ext @lnk("#370", "https://github.com/com-lihaoyi/upickle/pull/370") @sect{1.4.2} @ul @li Bugfixes @lnk("#365", "https://github.com/com-lihaoyi/upickle/pull/365") @lnk("#366", "https://github.com/com-lihaoyi/upickle/pull/365") @sect{1.4.1} @ul @li BugFix: Util.parseLong (@lnk("#361", "https://github.com/lihaoyi/upickle/pull/361")) @li Implement visitFloat32, visitFloat64String for Byte/Short/Int/Long/Float/Double/Char (@lnk("#358", "https://github.com/lihaoyi/upickle/pull/358")) @sect{1.4.0} @ul @li Added support for large case classes with >64 fields @sect{1.3.11} @ul @li Publish for Scala 3.0.0-RC2 @sect{1.3.8} @ul @li Minor performance tweaks @sect{1.3.7} @ul @li Removed @code{ArrayIndexOutOfBound}s from parsing and replaced them with @code{ParsingFailedException}s @sect{1.3.0} @ul @li Significant improvements (30-50%) to performance of reading and writing large JSON files, especially working with binary data in byte arrays or input streams. @sect{1.2.0} @ul @li Add optional `trace = true` parameter to `ujson.read`, `upack.read`, `upickle.default.read` and `upickle.default.readBinary` to provide better error messages when parsing or deserialization fails @sect{0.9.6} @ul @li Bump Geny dependency @li Add ability to parse from any @lnk("geny.Readable", "https://github.com/lihaoyi/geny#readable") data type, such as @code{java.io.InputStream} @sect{0.9.0} @ul @li Basic support for GADTs @lnk("#288", "https://github.com/lihaoyi/upickle/pull/288") @li @code{ujson.Value} and @code{upack.Msg} now support the @lnk("geny.Writable", "https://github.com/lihaoyi/geny#writable") interface @li Added new @code{upickle.default.writable} and @code{upickle.default.writableBinary}, to serialize Scala data types via the @lnk("geny.Writable", "https://github.com/lihaoyi/geny#writable") interface @sect{0.8.0} @ul @li Improved performance by avoiding allocations in deserialization hot paths @lnk("#284", "https://github.com/lihaoyi/upickle/pull/284") @li Add null-safe cast helpers @lnk("#274", "https://github.com/lihaoyi/upickle/pull/274") @sect{0.7.5} @ul @li Support for Scala 2.13.0 final @sect{0.7.1} @ul @li Introduced new MessagePack backend for binary serialization! This is used via @code{upickle.default.writeBinary}/@code{upickle.default.readBinary}, or via the standalone @code{upack.read}/@code{upack.write} package. Binary serialization typically is 50-100% faster than JSON when running on the JVM. @li @code{ujson.Js.Value}, @code{ujson.Js.Obj}, etc. are now just @code{ujson.Value}, @code{ujson.Obj} @li Small @code{Long} 64-bit integers are now read/written as JSON numbers by default; only large values which cannot be precisely stored in @code{Double}-precision floating point (n > 2^53) are written as strings. You can revert to the old behavior via a @sect.ref{Custom Configuration} with: @hl.scala override implicit val LongWriter = new Writer[Long] { def write0[V](out: Visitor[_, V], v: Long) = out.visitInt64(v, -1) } @li @code{upickle.json.*} and @code{upickle.Js.*} have been removed (use @code{ujson.*}. @sect{0.6.7} @ul @li Added the @hl.scala{escapeUnicode: Boolean = false} flag to @code{ujson.Js#Render} and @code{ujson.Renderer}; pass in @hl.scala{false} to rrender unicode characters verbatim rather than escaping them. @sect{0.6.6} @ul @li Fix ability to construct single-element @code{Js.Obj} values without explicitly wrapping values [#230](https://github.com/lihaoyi/upickle/issues/230) @li Add @code{JsValue#bool} helper [#227](https://github.com/lihaoyi/upickle/pull/223) for extracting boolean values @sect{0.6.5} @ul @li Add ability to update a JSON dictionary key or array item in place via @hl.scala{json(0)("myFieldA") = _.num + 100} @sect{0.6.4} @ul @li Fix uJson direct dependency artifact naming @sect{0.6.3} @ul @li Added @code{ujson.copy} helper @li Added implicit constructors for @code{ujson.Js.Obj} and @code{Arr} @sect{0.6.2} @ul @li Fix conversion of case classes to other case classes via upickle.default.transform @sect{0.6.0} @ul @li ~3x faster than 0.5.1; uPickle now has the best @sect.ref{Performance} out of any of the commonly-used Scala JSON libraries @li The old @code{upickle.Js} JSON AST and @lnk("non/jawn", "https://github.com/non/jawn") dependency have been combined into the @sect.ref{uJson} standalone library. uJson provides high-performance streaming JSON processing that lets uPickle parse input strings directly to case classes without an intermediate AST. @li @code{upickle.Js} objects are now mutable, and had some implicits added to make @sect.ref{Construction} less awkward. @li The set of @sect.ref{Common Operations} and @sect.ref{JSON Utilities} has been fleshed out: you now have convenient helpers for streaming JSON re-formatting or validation, and can read from arbitrary inputs (strings, byte-arrays, files, ...) using the same @code{upickle.default.read} call @li The way you write @sect.ref{Custom Picklers} and @sect.ref{Custom Configuration} has changed. The new ways are hopefully more intuitive, allow much better back-end performance, and should be just as flexible as the old way, but if you have custom picklers/configurations in your code you'll have to go update them. @li uPickle now supports parsing to (and serializing) @sect.ref{Other ASTs}, from libraries such as Circe, Argonaut, Json4s or Play-Json. You can now also do high-performance/streaming @sect.ref{Cross-Library Conversions} to transform from one library's AST to another without any intermediate structures. @sect{0.5.1} @ul @li Strip out automatic "deep" case-class serialization: you must now define a serializer for each case class you want to deal with, preferably in the companion object @li Upgrade Jawn version to 0.11.0, add helpers in @code{ujson} to parse JSON coming from files. @li New @code{ujson.writeTo} function for serializing JSON directly to a @code{java.io.Writer}, rather than creating a @code{String} @li @code{ujson.write} now takes an optional `sortKeys` flag, if you want the JSON dictionaries to rendered in a standardized order @li Drop support fo Scala 2.10 @sect{0.4.3} @ul @li Support for @hl.scala{BigInt} and @hl.scala{BigDecimal}, thanks to @lnk("Jisoo Park", "https://github.com/guersam") @li @code{Js.Value}s are now serializable, thanks to @lnk("Felix Dietze", "https://github.com/fdietze") @li Made it easy to write @sect.ref{Manual Sealed Trait Picklers} in order to work around problems with SI-7046 @sect{0.4.1} @ul @li Changes to @lnk("PPrint", "http://www.lihaoyi.com/upickle-pprint/pprint/#0.4.2") @sect{0.4.1} @ul @li Changes to @lnk("PPrint", "http://www.lihaoyi.com/upickle-pprint/pprint/#0.4.1") @sect{0.4.0} @ul @li Allow custom handling for JSON @hl.scala{null}s via a @sect.ref{Custom Configuration} @li Made @hl.scala{upickle.key} a @hl.scala{case class} @li Remove unnecessary dependency of @hl.scala{derive} on default arguments #143 @li Fixed derivation allowing Caching Picklers in a @hl.scala{case class}'s companion object, potentially speeding up compilation times and runtimes @sect{0.3.9} @ul @li Add @hl.scala{.arr: Seq[Js.Value]}, @hl.scala{.obj: Map[String, Js.Value]}, @hl.scala{.str: String} and @hl.scala{.num: Double} helper methods on @hl.scala{Js.Value} to simplify usage as a simple JSON tree. @li @hl.scala{Invalid.Json} and @hl.scala{Invalid.Data} now have better exception messages by default, which should simplify debugging @li Some usages should compile faster due to fiddling with implicits (#138) @sect{0.3.8} @ul @li Tweaks to PPrint @sect{0.3.7} @ul @li You can now pass in an @hl.scala{indent} parameter to @hl.scala{upickle.default.write} in order to format/indent the JSON nicely across multiple lines @li Derivation based on sealed abstract classes works, in addition to traits (#104), thanks to @a("Voltir", href:="https://github.com/Voltir") @li Fix non-deterministic failure due to improperly implemented @code{equals}/@code{hashCode} in macro (#124), thanks to @a("Voltir", href:="https://github.com/lihaoyi/upickle-pprint/issues/124") @li Slightly improve hygiene of uPickle/PPrint macro expansion @li uPickle de-serialization failures should no longer throw @code{MatchErrors} (#101) @li Using case-class-derived @code{Reader}s/@code{Writer}s should no longer fail in class @code{extends} clauses (#108) @li @code{Float.NaN} and @code{Double.NaN} are now properly handled (#123) @li Provided an example of a @sect.ref{Custom Configuration} being used to @code{snake_case} case-class fields during serialization/de-serialization (#120) @sect{0.3.6} @ul @li Fix more bugs in PPrint derivation @sect{0.3.5} @ul @li Fix some bugs in PPrint derivation @sect{0.3.4} @ul @li Remove unnecessary shapeless dependency @sect{0.3.3} @ul @li Fix more edge cases to avoid diverging implicits @sect{0.3.2} @ul @li Fix more edge cases around typeclass derivation: #94, #95, #96 @li Don't get tripped up by custom Apply methods: #48 @sect{0.3.1} @ul @li Fixed edge cases around typeclass derivation @sect{0.3.0} @ul @li Top-to-bottom rewrite of type-class derivation macros. Much faster, more reliable, etc.. Still one or two cases where it misbehaves, but much fewer than before. Extracted it into the @hl.scala{derive} subproject @li Force users to choose between @hl.scala{import upickle.default._} which now renders sealed trait hierarchies as dictionaries with a @hl.scala{$type} attribute, and @hl.scala{import upickle.legacy._} which does the old-style array-wrapper. @li You can also now create your own custom subclass of @hl.scala{upickle.Api} if you wish to customize things further, e.g. changing the type-attribute or changing the rendering of case classes. @sect{0.2.8} @ul @li Support for @hl.scala{java.util.UUID}, which are serialized as strings in the standard format @sect{0.2.7} @ul @li Re-published for Scala.js 0.6.1 @sect{0.2.6} @ul @li @hl.scala{'Symbol}s are now read/write-able by default @li Added lots of warnings for common issues @li @hl.scala{Map[String, V]} now pickles to a JSON dictionary @hl.scala(""""key": "value", ...}"""). @hl.scala{Map[K, V]} for all other @hl.scala{K != String} are unchanged @li Source maps now point towards a reasonabel place on Github @sect{0.2.5} @ul @li Fixed [#23](https://github.com/lihaoyi/upickle/issues/23): self-recursive data structures are now supported. @li Fixed [#18](https://github.com/lihaoyi/upickle/issues/18): you can now auto-pickle classes in objects that originated from traits that were mixed in. @sect{0.2.4} @ul @li Support reading and writing @hl.scala{null} @li Fixed Reader/Writer macros for single-class sealed hierarchies @li Used @hl.scala{CanBuildFrom} to serialize a broader range of collections @sect{0.2.3} @ul @li Added a pickler for @hl.scala{Unit}/@hl.scala{()} @sect{0.2.2} @ul @li Swapped over from the hand-rolled parser to using @hl.scala{Jawn}/@hl.scala{JSON.parse} on the two platforms, resulting in a 10-15x speedup for JSON handling. @li Renamed @hl.scala("""Js.{String, Object, Array, Number}""") into @hl.scala("""Js.{Str, Obj, Arr, Num}"""), and made @hl.scala{Js.Arr} and @hl.scala{Js.Obj} use varargs, to allow for better direct-use. @li Documented and exposed JSON API for direct use by users of the library. @sect{0.2.1} @ul @li Improved error messages for unpickle-able types @li ScalaJS version now built against 0.5.3 @sect{0.2.0} @ul @li Members of sealed trait/class hierarchies are now keyed with the fully-qualified name of their class, rather than an index, as it is less likely to change due to adding or removing classes @li Members of sealed hierarchies and parameters now support a @hl.scala{upickle.key("...")} annotation, which allows you to override the default key used (which is the class/parameter name) with a custom one, allowing you to change the class/param name in your code while maintaining compatibility with serialized structures @li Default parameters are now supported: they are used to substitute missing keys when reading, and cause the key/value pair to be omitted if the serialized value matches the default when writing @li Missing keys when deserializing case classes now throws a proper @hl.scala{Invalid.Data} exception @li @hl.scala{object}s are now serialized as @hl.scala("""{}""") rather than @hl.scala{[]}, better matching the style of case classes @li 0-argument case classes, previously unsupported, now serialize to @hl.scala("""{}""") the same way as @hl.scala{object}s @li Fixed a bug that was preventing multi-level sealed class hierarchies from being serialized due to a compilation error @li Fixed a bug causing case classes nested in other packages/objects and referred to by their qualified paths to fail pickling @li Tightened up error handling semantics, swapping out several @hl.scala{MatchError}s with @hl.scala{Invalid.Data} errors @sect{0.1.7} @ul @li Cleaned up the external API, marking lots of things which should have been private private or stuffing them in the @hl.scala{Internals} namespace @li Organized things such that only a single import @hl.scala{import upickle._} is necessary to use the library @sect{0.1.6} @ul @li Tuples and case classes now have implicit picklers up to an arity limit of 22. @li Case classes now serialize as JSON dictionaries rather than as lists. @sect{0.1.5} @ul @li Simple case classes and case class hierarchies are now auto-serializable view Macros. No need to define your own implicit using @hl.scala{Case0ReadWriter} anymore! @sect{0.1.4} @ul @li Serialize numbers as JSON numbers instead of Strings. @sect{0.1.3} @ul @li Specification of the exception-throwing behavior: instead of failing with random @hl.scala{MatchError}s or similar, parse failures now are restricted to subclasses @hl.scala{upickle.Invalid} which define different failure modes.
<link href="styles.css" rel="stylesheet"/> Stylesheet -- 定义一个外部加载的样式表 <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 使页面样式在移动端看起来与在桌面或笔记本电脑上相似 text-align: center; 设置元素居中: margin-left: auto; margin-right: auto; 将 div 在水平方向上居中。 类选择器 .class-name { styles } 设置背景图片 background-image: url(http://127.0.0.1/cat.jpg) 为 item 的 class 为嵌套在元素中任何位置的所有 p 元素设置样式 .item p { } 如果设置了 display: inline-block,将保留上下外边距/内边距,而 display: inline 则不会。 display: inline-block 允许在元素上设置宽度和高度。 设置字体,备用字体可以与首选字体使用空格分开 font-family: sans-serif; hr元素:主题分割(水平分割线)元素; 当链接被实际访问时,你可以使用类似 a:visited { propertyName: propertyValue; } 的 pseudo-selector 来更改链接的属性; 当鼠标悬停在链接上时,你可以使用类似于 a:hover { propertyName: propertyValue; } 的 pseudo-selector 更改链接的属性。 当链接被实际点击时,你可以使用类似 a:active { propertyName: propertyValue; } 的 pseudo-selector 来更改链接的属性。
import io.github.martimm.HikingCompanion.GlobalVariables 0.1 import io.github.martimm.HikingCompanion.Config 0.3 import QtQuick 2.9 import QtQuick.Controls 2.2 // Select button placed on the tracks page. Button { id: selectButton Config { id: config // Function is triggered when click event on the select button // calls loadCoordinates function. onCoordinatesReady: { // Get the path of coordinates and show on map var path = config.coordinateList(); var mapPage = GlobalVariables.applicationWindow.mapPage; mapPage.featuresMap.trackCourse.setPath(path); // Get the boundaries of the set of coordinates to zoom in // on the track shown on the map. Using boundaries will zoom in until // the track touches the edge. To prevent this, zoom out a small bit. var bounds = config.boundary(); mapPage.hikingCompanionMap.visibleRegion = bounds; mapPage.hikingCompanionMap.zoomLevel = mapPage.hikingCompanionMap.zoomLevel - 0.2; // For safekeeping so we can zoom on it again later mapPage.featuresMap.trackCourse.boundary = bounds; // Show a line when we wander off track mapPage.featuresMap.wanderOffTrackNotation.setWanderOffTrackNotation(); // Make map visible GlobalVariables.menu.setMapPage(); } } Component.onCompleted: { init(GlobalVariables.ButtonRowButton); } text: qsTr("Select") onClicked: { // currentIndex is defined and set in TrackSelectPage and // is visible here config.setGpxFileIndexSetting(currentIndex); // Get the coordinates of the selected track and emit a // signal when ready. This signal is catched on the mapPage // where the coordinates are used. config.loadCoordinates(currentIndex); } }
import { NestMiddleware, Injectable } from '@nestjs/common'; import { UsersService } from '../users.service'; import { Request, Response, NextFunction } from 'express'; import { User } from '../user.entity'; /** * This declaration is used to tell typescript globally that in the module Express, * the interface Request may have a property currentUser that has a type User or * undefined */ declare global { namespace Express { interface Request { currentUser?: User; } } } @Injectable() // Injectable because we want to use UsersService export class CurrentUserMiddleware implements NestMiddleware { constructor(private usersService: UsersService) {} async use(req: Request, res: Response, next: NextFunction) { const userId = req.session?.userId; if (userId) { const user = await this.usersService.findOne(userId); req.currentUser = user; } next(); } }
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="{% static 'css/generalStyles.css' %}" /> <link rel="stylesheet" href="{% static 'css/alunosStyles.css' %}" /> <link rel="stylesheet" href="{% static 'css/escolasStyles.css' %}" /> <link rel="stylesheet" href="{% static 'css/matriculasStyles.css' %}" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script> <script src="{% static 'javascript/script.js' %}"></script> <script src="{% static 'javascript/jquery.js' %}"></script> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Meu Projeto</title> </head> <body> <div class="alunos_container"> <p class="generalPadding">Nome dos Alunos</p> <ul class="lista_de_alunos generalPadding" id="lista_de_alunos"> {% for aluno in alunos %} <li> {{aluno.nome}} <div class="links_container"> <button onclick="editarAlunoViaAjax('/editar-aluno-ajax/{{aluno.id}}','{{ csrf_token }}','{{aluno.id}}' )" type="button">Editar</button> <button onclick="excluirAlunoViaAjax('/excluir-aluno-ajax/{{aluno.id}}','{{ csrf_token }}','{{aluno.id}}' )" type="button">Excluir</button> </div> </li> {% endfor %} </ul> <!--<form class="adicionar_alunos generalPadding" action="inserir-aluno" method="post">--> <form class="adicionar_alunos generalPadding" method="post"> {% csrf_token %} <label for="campo_nome_do_aluno">Nome: </label> <input name="campo_nome_do_aluno" type="text" id="campo_nome_do_aluno" placeholder="Ex: Pedro Lucas" /> <input type="submit" value="Adicionar Aluno" class="margin_left_auto" id="inserir_aluno" /> </form> <button onclick="adicionarAlunoViaAjax('/inserir-aluno-ajax','{{ csrf_token }}')" type="button">enviar aluno ajax</button> </div> <div class="escolas_container"> <p class="generalPadding">Dados das Escolas</p> <ul class="lista_de_escolas generalPadding" id="lista_de_escolas"> {% for escola in escolas %} <li> {{escola.nome}} - {{escola.tipo}} <div class="links_container"> <button onclick="editarEscolaViaAjax('/editar-escola-ajax/{{escola.id}}','{{ csrf_token }}','{{escola.id}}' )" type="button">Editar</button> <button onclick="excluirEscolaViaAjax('/excluir-escola-ajax/{{escola.id}}','{{ csrf_token }}','{{escola.id}}' )" type="button">Excluir</button> </div> </li> {% endfor %} </ul> <form class="adicionar_escolas generalPadding" action="inserir-escola" method="post"> {% csrf_token %} <label for="campo_nome_da_escola">Nome: </label> <input type="text" id="campo_nome_da_escola" name="campo_nome_da_escola" placeholder="Ex: Colégio Expressão" /> <label for="campo_tipo_da_escola">Tipo: </label> <input type="text" id="campo_tipo_da_escola" name="campo_tipo_da_escola" placeholder="Ex: Ensino Médio" /> <input type="submit" value="Adicionar Escola" class="margin_left_auto" /> </form> <button onclick="adicionarEscolaViaAjax('/inserir-escola-ajax','{{ csrf_token }}')" type="button">enviar escola ajax</button> </div> <div class="matriculas_container"> <p class="generalPadding">Matriculas</p> <ul class="lista_de_matriculas generalPadding" id="lista_de_matriculas"> {% for matricula in matriculas %} <li> {{matricula.aluno.nome}} - {{matricula.escola.nome}} <div class="links_container"> <button onclick="editarMatriculaViaAjax('/editar-matricula-ajax/{{matricula.numero_de_matricula}}','{{ csrf_token }}','{{matricula.numero_de_matricula}}' )" type="button">Editar</button> | <button onclick="excluirMatriculaAjax('/excluir-matricula-ajax/{{matricula.numero_de_matricula}}','{{ csrf_token }}','{{matricula.numero_de_matricula}}' )" type="button">Excluir</button> </div> </li> {% endfor %} </ul> <form class="adicionar_matriculas generalPadding" action="inserir-matricula" method="post"> {% csrf_token %} <select name="aluno_id" id="aluno" required> {% for aluno in alunos %} <option value="{{aluno.id}}">{{aluno.nome}}</option> {% endfor %} </select> <select name="escola_id" id="escola" required> {% for escola in escolas %} <option value="{{escola.id}}">{{escola.nome}}</option> {% endfor %} </select> <input type="submit" value="Cadastrar Aluno na Escola" class="margin_left_auto" /> </form> <button onclick="adicionarMatriculaViaAjax('/inserir-matricula-ajax','{{ csrf_token }}')" type="button">enviar matricula ajax</button> <div id="edicao_matricula"></div> </div> </body> </html>
package co.id.dicoding.movieappdesign.model; import android.os.Parcel; import android.os.Parcelable; import java.util.ArrayList; @SuppressWarnings({"unused", "WeakerAccess"}) public class Trend implements Parcelable { private int id; private int vote_count; private Double vote_average; private String title; private String name; private String first_air_date; private String release_date; private String original_language; private String backdrop_path; private String overview; private String poster_path; private String media_type; private ArrayList<Integer> genre_ids; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getVote_count() { return vote_count; } public void setVote_count(int vote_count) { this.vote_count = vote_count; } public Double getVote_average() { return vote_average; } public void setVote_average(Double vote_average) { this.vote_average = vote_average; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFirst_air_date() { return first_air_date; } public void setFirst_air_date(String first_air_date) { this.first_air_date = first_air_date; } public String getRelease_date() { return release_date; } public void setRelease_date(String release_date) { this.release_date = release_date; } public String getOriginal_language() { return original_language; } public void setOriginal_language(String original_language) { this.original_language = original_language; } public String getBackdrop_path() { return backdrop_path; } public void setBackdrop_path(String backdrop_path) { this.backdrop_path = backdrop_path; } public String getOverview() { return overview; } public void setOverview(String overview) { this.overview = overview; } public String getPoster_path() { return poster_path; } public void setPoster_path(String poster_path) { this.poster_path = poster_path; } public String getMedia_type() { return media_type; } public void setMedia_type(String media_type) { this.media_type = media_type; } public ArrayList<Integer> getGenre_ids() { return genre_ids; } public void setGenre_ids(ArrayList<Integer> genre_ids) { this.genre_ids = genre_ids; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.id); dest.writeInt(this.vote_count); dest.writeValue(this.vote_average); dest.writeString(this.title); dest.writeString(this.name); dest.writeString(this.first_air_date); dest.writeString(this.release_date); dest.writeString(this.original_language); dest.writeString(this.backdrop_path); dest.writeString(this.overview); dest.writeString(this.poster_path); dest.writeString(this.media_type); dest.writeList(this.genre_ids); } public Trend() { } protected Trend(Parcel in) { this.id = in.readInt(); this.vote_count = in.readInt(); this.vote_average = (Double) in.readValue(Double.class.getClassLoader()); this.title = in.readString(); this.name = in.readString(); this.first_air_date = in.readString(); this.release_date = in.readString(); this.original_language = in.readString(); this.backdrop_path = in.readString(); this.overview = in.readString(); this.poster_path = in.readString(); this.media_type = in.readString(); this.genre_ids = new ArrayList<>(); in.readList(this.genre_ids, Integer.class.getClassLoader()); } public static final Creator<Trend> CREATOR = new Creator<Trend>() { @Override public Trend createFromParcel(Parcel source) { return new Trend(source); } @Override public Trend[] newArray(int size) { return new Trend[size]; } }; }
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; final class Channel extends Model { /** * Indicates if the model should be timestamped. * * @var bool */ public $timestamps = false; /** * The attributes that aren't mass assignable. * * @var array */ protected $guarded = []; /** * The attributes that should be mutated to dates. * * @var array */ protected $dates = [ 'published_at', 'updated_at', ]; /** * 頻道統計. * * @return HasMany */ public function statistics(): HasMany { return $this->hasMany(ChannelStatistic::class); } /** * 頻道影片. * * @return HasMany */ public function videos(): HasMany { return $this->hasMany(Video::class) ->orderByDesc('published_at'); } }
/** * This file contains the test suite for the SectionCard component. * It imports React, render, fireEvent and renderer from testing-library/react-native. * It also imports the SectionCard component from the components/section directory. * The useNavigation hook is mocked using jest.mock. * A sample section object is created for testing purposes. * The test suite includes tests for rendering the component with provided data, * displaying the correct status based on progress, and expanding and collapsing the component. * @module SectionCard.test */ import React from 'react'; import { render, fireEvent } from '@testing-library/react-native'; import renderer from 'react-test-renderer'; import SectionCard from '../../../components/section/SectionCard'; import { mockDataAsyncStorage } from '../../mockData/mockDataAsyncStorage'; // Mock the useNavigation hook outside the describe block jest.mock('@react-navigation/native', () => ({ ...jest.requireActual('@react-navigation/native'), useNavigation: () => ({ navigate: jest.fn(), }), })); let sectionCard; // Sample section data for testing const mockData = mockDataAsyncStorage(); beforeEach(async () => { sectionCard = renderer.create(<SectionCard section={mockData.section} />); }); afterAll(() => { jest.resetModules(); jest.restoreAllMocks(); }); describe('<SectionCard />', () => { it('Renders correctly with provided data', async () => { const { getByText } = render(<SectionCard section={mockData.section} />); // Check if title and description are displayed expect(getByText(mockData.section.title)).toBeTruthy(); expect(getByText(mockData.section.description)).toBeTruthy(); }); /*it('Displays correct status based on progress', async () => { const { queryByText } = render(<SectionCard section={mockData.section} />); // Use a regular expression to match the 0/total pattern const pattern = new RegExp(`0/${mockData.section.total}`); expect(queryByText(pattern)).toBeTruthy(); });*/ /** * Tests if the SectionCard component renders correctly. */ it('renders SectionCard correctly', async () => { expect(await sectionCard.toJSON()).toMatchSnapshot(); }); it('should expand and collapse when clicked', async () => { /** * Represents a sample section. * @typedef {Object} Section * @property {string} title - The title of the section. * @property {string} description - The description of the section. * @property {number} total - The total number of items in the section. */ const { getByTestId } = render(<SectionCard section={mockData.section} />); const collapsibleButton = getByTestId('collapsible'); // Ensure Collapsible content is initially hidden expect(getByTestId('chevron-down')).toBeTruthy(); // Click the Collapsible button to expand it fireEvent.press(collapsibleButton); // Ensure Collapsible content is now visible expect(getByTestId('chevron-up')).toBeTruthy(); // Click the Collapsible button to collapse it fireEvent.press(collapsibleButton); // Ensure Collapsible content is hidden again expect(getByTestId('chevron-down')).toBeTruthy(); }); });
using ClosedXML.Excel; using CsvHelper.Configuration; using CsvHelper; using EHealth.ManageItemLists.Application.DevicesAndAssets.UHIA.DTOs; using EHealth.ManageItemLists.Application.DevicesAndAssets.UHIA.Queries; using EHealth.ManageItemLists.Application.Drugs.UHIA.Commands; using EHealth.ManageItemLists.Application.Drugs.UHIA.DTOs; using EHealth.ManageItemLists.Application.Drugs.UHIA.Queries; using EHealth.ManageItemLists.Domain.Shared.Exceptions; using EHealth.ManageItemLists.Domain.Shared.Pagination; using EHealth.ManageItemLists.Domain.Shared.Repositories; using EHealth.ManageItemLists.Presentation.ExceptionHandlers; using MediatR; using Microsoft.AspNetCore.Mvc; using System.Data; using System.Globalization; using System.Text; using EHealth.ManageItemLists.Application.DoctorFees.UHIA.Commands; using Microsoft.AspNetCore.Authorization; namespace EHealth.ManageItemLists.Presentation.Controllers { [Route("api/[controller]")] [ApiController] public class DrugUHIAController : ControllerBase { private readonly IMediator _mediator; private readonly IDrugsUHIARepository _drugsUHIARepository; public DrugUHIAController(IMediator mediator, IDrugsUHIARepository drugsUHIARepository) { _mediator = mediator; _drugsUHIARepository = drugsUHIARepository; } [Authorize(Roles = "itemslist_drugs_uhia_add")] [HttpPost("BasicData/Create")] [ProducesResponseType(typeof(Guid), 200)] [ProducesResponseType(typeof(HttpException), GeideaHttpStatusCodes.DataNotValid)] [ProducesResponseType(typeof(HttpException), GeideaHttpStatusCodes.DataDuplicated)] public async Task<ActionResult<Guid>> BasicDataCreate([FromBody] CreateDrugUHIABasicDataDto request) { Guid id = await _mediator.Send(new CreateDrugUHIABasicDataCommand(request)); return Ok(id); } [Authorize(Roles = "itemslist_drugs_uhia_add")] [HttpPost("Prices/Create")] [ProducesResponseType(typeof(bool), 200)] [ProducesResponseType(typeof(HttpException), GeideaHttpStatusCodes.DataNotValid)] public async Task<ActionResult<bool>> PriceCreate([FromBody] CreateDrugUHIAPricesDto request) { var res = await _mediator.Send(new CreateDrugsUHIAPricesCommand(request, _drugsUHIARepository)); return Ok(res); } [Authorize(Roles = "itemslist_drugs_uhia_update")] [HttpPut("BasicData/Update")] [ProducesResponseType(typeof(bool), 200)] [ProducesResponseType(typeof(HttpException), GeideaHttpStatusCodes.DataNotValid)] [ProducesResponseType(typeof(HttpException), GeideaHttpStatusCodes.DataDuplicated)] public async Task<ActionResult<bool>> BasicDataUpdate([FromBody] UpdateDrugUHIABasicDataDto request) { bool res = await _mediator.Send(new UpdateDrugUHIABasicDataCommand(request, _drugsUHIARepository)); return Ok(res); } [Authorize(Roles = "itemslist_drugs_uhia_update")] [HttpPut("Prices/Update")] [ProducesResponseType(typeof(bool), 200)] [ProducesResponseType(typeof(HttpException), GeideaHttpStatusCodes.DataNotValid)] public async Task<ActionResult<bool>> PriceUpdate([FromBody] UpdateDrugUHIAPriceDto request) { bool res = await _mediator.Send(new UpdateDrugUHIAPricesCommand(request, _drugsUHIARepository)); return Ok(res); } [Authorize(Roles = "itemslist_drugs_uhia_delete")] [HttpDelete("{id:guid}")] [ProducesResponseType(typeof(bool), 200)] [ProducesResponseType(typeof(HttpException), GeideaHttpStatusCodes.DataNotFound)] public async Task<ActionResult<bool>> Delete([FromRoute] Guid id) { return Ok(await _mediator.Send(new DeleteDrugsUHIACommand { Id = id })); } [Authorize(Roles = "itemslist_drugs_uhia_view")] [HttpGet("[Action]")] [ProducesResponseType(typeof(PagedResponse<DrugsUHIADto>), 200)] public async Task<ActionResult<PagedResponse<DrugsUHIADto>>> Search([FromQuery] DrugUHIASearchQuery request) { return Ok(await _mediator.Send(request)); } [Authorize(Roles = "itemslist_drugs_uhia_details,itemslist_drugs_uhia_update")] [HttpGet("{id:guid}")] [ProducesResponseType(typeof(DrugUHIAGetByIdDto), 200)] [ProducesResponseType(typeof(HttpException), GeideaHttpStatusCodes.DataNotFound)] public async Task<ActionResult<DrugUHIAGetByIdDto>> Get([FromRoute] Guid id) { return Ok(await _mediator.Send(new DrugUHIAGetByIdQuery { Id = id })); } [Authorize(Roles = "itemslist_drugs_uhia_export")] [HttpGet("[Action]")] [ProducesResponseType(typeof(PagedResponse<DrugsUHIADto>), 200)] public async Task<ActionResult<PagedResponse<DrugsUHIADto>>> CreateTemplateDrugsUHIA([FromQuery] CreateTemplateDrugsUHIASearchQuery request) { var lang = Request.Headers["Lang"]; request.Lang = lang; var res = await _mediator.Send(request); if (request.FormatType.ToLower() == "excel") { var fileName = "DrugsUHIA.xlsx"; return GenerateExcel(fileName, res); } else { var fileName = "DrugsUHIA.csv"; return GenerateCSV(fileName, res); } } [Authorize(Roles = "itemslist_drugs_uhia_bulkupload")] [HttpGet("[Action]")] public async Task<IActionResult> DownloadBulkTemplate([FromQuery] DownloadDrugsUhiaBulkTemplateCommand request) { var result = await _mediator.Send(request); return File(result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Drugs - UHIA.xlsx"); } [Authorize(Roles = "itemslist_drugs_uhia_bulkupload")] [HttpPost("[Action]")] [ProducesResponseType(typeof(bool), 200)] [ProducesResponseType(typeof(HttpException), GeideaHttpStatusCodes.DataNotValid)] public async Task<IActionResult> BulkUpload([FromForm] IFormFile file) { var res = await _mediator.Send(new BulkUploadDrugsUhiaCreateCommand(file)); if (res != null) { var fileName = "Drug-UHIA-With-Errors.xlsx"; return File(res, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName); } return Ok(true); } private FileResult GenerateExcel(string fileName, DataTable dataTable) { using (XLWorkbook wb = new XLWorkbook()) { //wb.Worksheets.Add(dataTable); using (MemoryStream stream = new MemoryStream()) { wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center; wb.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center; wb.ColumnWidth = 20; wb.Worksheets.Add(dataTable); wb.SaveAs(stream); return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName); } } } private FileResult GenerateCSV(string fileName, DataTable dataTable) { var csv = new StringBuilder(); using (var csvWriter = new CsvWriter(new StringWriter(csv), new CsvConfiguration(CultureInfo.InvariantCulture))) { foreach (DataColumn column in dataTable.Columns) { csvWriter.WriteField(column.ColumnName); } csvWriter.NextRecord(); foreach (DataRow dataRow in dataTable.Rows) { for (int i = 0; i < dataTable.Columns.Count; i++) { csvWriter.WriteField(dataRow[i]); } csvWriter.NextRecord(); } byte[] bytes = Encoding.UTF8.GetBytes(csv.ToString()); return File(bytes, "text/csv", fileName); } } } }
import React, { useContext } from "react"; import { UserContext } from "./UserContext"; import { login } from "./login"; export function Index() { const { user, setUser } = useContext(UserContext); return ( <div> <h2>Home</h2> <pre>{JSON.stringify(user, null, 2)}</pre> { user ? <button onClick={() => { setUser(null); }}>logout</button> : <button onClick={async () => { const user = await login(); setUser(user); }}>login</button> } </div> ); }
#!/usr/bin/env python # -*-coding:utf-8 -*- """ @File : ci_dag.py @Time : 2023/11/24 16:50:41 """ import sys sys.path.append("/opt/airflow/") import os from datetime import timedelta from airflow import DAG from airflow.operators.python_operator import PythonOperator, BranchPythonOperator from airflow.operators.dummy import DummyOperator from airflow.utils.dates import days_ago from airflow.utils.timezone import datetime from src.processing.data_transformation import ( read_data, split_train_test, preprocess_data, ) from src.modeling.model_train import train_model from src.modeling.model_push import ( register_model, register_model_by_comparison, check_if_registered_model_exists, ) from src.modeling.model_validation import evaluate_model from src.config.core import _data_files, experiment_name, model_name, reg_model default_args = { "owner": "namnd00", "depends_on_past": False, "start_date": days_ago(0), "retries": 1, "retry_delay": timedelta(seconds=5), } dag = DAG( "ci_pipeline", default_args=default_args, description="Continuous Integration Pipeline", schedule_interval=timedelta(days=1), ) with dag: operator_read_data = PythonOperator( task_id="read_data", python_callable=read_data, op_kwargs={"data_files": _data_files}, ) operator_split_train_test = PythonOperator( task_id="split_train_test", python_callable=split_train_test, op_kwargs={"data_files": _data_files}, ) operator_preprocess_data = PythonOperator( task_id="preprocess_data", python_callable=preprocess_data, op_kwargs={"data_files": _data_files}, ) operator_model_training = PythonOperator( task_id="train_model", python_callable=train_model, op_kwargs={ "data_files": _data_files, "experiment_name": experiment_name, "model_name": model_name, "track_cv_performance": True, }, ) operator_register_model = PythonOperator( task_id="register_model", python_callable=register_model, op_kwargs={"model_name": model_name}, ) operator_check_if_registered_model_exists = BranchPythonOperator( task_id="check_if_registered_model_exists", python_callable=check_if_registered_model_exists, op_kwargs={"reg_model": reg_model}, ) operator_stop = DummyOperator( task_id="stop", dag=dag, trigger_rule="all_done", ) operator_register_model_by_comparison = PythonOperator( task_id="register_model_by_comparison", python_callable=register_model_by_comparison, op_kwargs={ "data_files": _data_files, "registered_model_uri": reg_model, "model_name": model_name, "push_to_production": True, }, ) ( operator_read_data >> operator_split_train_test >> operator_preprocess_data >> operator_model_training >> operator_check_if_registered_model_exists >> [ operator_stop, operator_register_model, operator_register_model_by_comparison, ] )
import { identity } from '@technically/lodash'; import classNames from 'classnames'; import RangeFix from 'rangefix'; import React, { useCallback, useRef, useState } from 'react'; import type { Editor } from 'slate'; import { ReactEditor, useSlateStatic } from 'slate-react'; import { convertClientRect, useIsMouseDown } from '#lib'; import type { Props as BasePortalV2Props } from './BasePortalV2'; import { BasePortalV2 } from './BasePortalV2'; import styles from './TextSelectionPortalV2.module.scss'; interface Props extends Omit<BasePortalV2Props, 'getBoundingClientRect'> { modifySelectionRect?: (rect: ClientRect) => ClientRect | null; } /** * TextSelectionPortalV2 is a modification of CursorPortalV2 that uses * selection start location as its origin to achieve better UX during editing. */ export function TextSelectionPortalV2({ children, className, containerElement, modifySelectionRect = identity, ...props }: Props) { const editor = useSlateStatic(); const lastRect = useRef<ClientRect | null>(null); // When making a selection with mouse, it's possible that mouse will be moved so quickly that // it will hover over the `children` of the `BasePortalV2` and it will interfere with the // selection that is being made. To make sure, we disable `pointer-events` when selection // is being made. const isMouseDown = useIsMouseDown(); const [isMouseDownInPortal, setIsMouseDownInPortal] = useState<boolean>(false); const getBoundingClientRect = useCallback( function () { const selectionRect = getSelectionRect(editor); const rect = selectionRect ? modifySelectionRect(selectionRect) : null; if ( editor.selection && rect === null && containerElement?.contains(document.activeElement) ) { return lastRect.current; } return (lastRect.current = rect || null); }, [editor, containerElement, modifySelectionRect], ); return ( <BasePortalV2 {...props} containerElement={containerElement} className={classNames(styles.TextSelectionPortal, className, { [styles.selecting]: isMouseDown && !isMouseDownInPortal, })} getBoundingClientRect={getBoundingClientRect} onMouseDown={() => setIsMouseDownInPortal(true)} onMouseUp={() => setIsMouseDownInPortal(false)} > {children} </BasePortalV2> ); } function getSelectionRect(editor: Editor): ClientRect | null { if (!editor.selection) return null; try { const range = ReactEditor.toDOMRange(editor, editor.selection); const [rect] = RangeFix.getClientRects(range) || []; return rect ? convertClientRect(rect) : null; } catch (error) { // Sometimes (for example, when resizing the contained image inside the editor), // the `getRangeAt(0)` will fail, because the selection is invalid at that moment: // "Failed to execute 'getRangeAt' on 'Selection': 0 is not a valid index." // There's noting to do with this error. return null; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Google Web </title> <!-- css files --> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/font-awesome.min.css"> <!-- font google --> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <!-- Start header --> <header class="header"> <div class="container"> <nav class="navbar"> <ul class="navbar-list"> <li class="pd"><a href="#">Gmail</a></li> <li class="pd"><a href="#">Images</a></li> <li class="droop"> <a href="#"><i class="material-icons">apps</i></a> <ul class="droop-box"> <li>Google apps</li> </ul> <!-- ./droop-box--> </li> <!-- ./droop--> <li class="droop-last"> <a href="#">b</a> </li> <!-- ./droop-last--> </ul> <!-- ./navbar-list--> </nav> <!-- ./navbar--> </div> <!-- ./container--> </header> <!-- ./header--> <section class="google-home"> <div class="container"> <div class="google-home-image"> <img src="images/google.png" alt="google logo"> </div><!-- ./google-home-image--> <form class="search"> <button type="submit"><i class="fa fa-search" aria-hidden="true"></i></button> <input type="search" name="search"> </form> <form class="btn"> <button class="btn1">Google Search</button> <button class="btn1">I'm Feeling Lucky</button> </form> <div class="google-home-offered"> <span class="google-home-text">Google offered in : <a href="#">العربية</a> </span> </div> <!-- ./google-home-offered--> </div> <!-- ./container--> </section> <!-- ./google-home--> <footer class="footer"> <div class="container"> <p>Palestine</p> <hr> <nav class="footer-navbar"> <ul class="footer-list-first"> <li><a href="#">About</a></li> <li><a href="#">Advertising</a></li> <li><a href="#">Business</a></li> <li><a href="#">How Search Work</a></li> </ul> <!-- ./footer-list-first--> <ul class="footer-list-secound"> <li><a href="#">Privacy</a></li> <li><a href="#">Terms</a></li> <li><a href="#">Settings</a></li> </ul> <!-- ./footer-list-secound--> </nav> <!-- ./footer-navbar--> </div> <!-- ./container--> </footer> <!-- ./footer--> </body> </html>
const express = require('express') const dotenv = require('dotenv') const morgan = require('morgan') const connectDB = require('./config/db') const color = require('colors') const errorHandler = require('./middleware/error') const cookieParser = require('cookie-parser') const cors = require('cors'); // Load env vars dotenv.config({ path: './config/config.env' }); //connect to database connectDB() //route files const bootcamps = require('./routes/bootcamps') const courses = require('./routes/courses') const auth = require('./routes/auth') const betSlips = require('./routes/betSlips') const app = express() // //Body parser app.use(express.json()) //Cookie parser app.use(cookieParser()) // Dev Logging middleware if(process.env.NODE_ENV === 'development') { app.use(morgan('dev')) app.use(cors({ origin: `http://localhost:3000` })); } //Mount routers app.use('/api/v1/bootcamps', bootcamps) app.use('/api/v1/courses', courses) app.use('/api/v1/auth', auth) app.use('/api/v1/betSlips', betSlips) //Mount error handler . app.use(errorHandler); const PORT = process.env.PORT || 5000; const server = app.listen( PORT, console.log( `Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold ) ); // Handle unhandled promise rejections process.on('unhandledRejection', (err, promise) =>{ console.log(`Error: ${err.message}`.red) //close server and exit process server.close(() => process.exit(1)) })
import React, { useEffect, useState } from "react"; import Box from "@mui/material/Box"; import Dialog from "@mui/material/Dialog"; import TextField from "@material-ui/core/TextField"; import "./Signup.css" import axios from "axios"; const API_ENDPOINT="https://gamingatoll.com" function Signup({ showLogin, closeHandler }) { const [email, setEmail] = useState(); const [password, setPassword] = useState(); const [username,setUsername] = useState(""); const [validateUsername,setValidateUsername] = useState(false); const [confirmPassword, setConfirmPassword] = useState(); useEffect(async()=>{ if(username!="") { const response = await axios.post(API_ENDPOINT+'/checkUsername',{username}) console.log(response," Response") if(response && response.data.status == true) { setValidateUsername(false); console.log(validateUsername) } else if(response && response.data.status == false) { setValidateUsername(true); console.log(validateUsername) } } },[username]) async function sendData() { if(validateUsername) return; let payload = { email, password, username, confirmPassword, }; const response = await axios.post(`${API_ENDPOINT}/signup`, payload); console.log(response); if (response.data.status == true) { showLogin(); } } function clearFields() { setEmail(""); setPassword(""); setConfirmPassword(""); } return ( <> <Dialog open={true}> <div className="login_container"> <div className="login_header"> <div onClick={closeHandler} style={{ fontWeight: "bold", fontSize: "20px", cursor: "pointer", }} > X </div> <h3 className="login_signup">Login Or Sign up</h3> <div></div> </div> <div className="login_box"> <div className="login_pane"> <div className="login_pane_heading"> <h3 className="heading">Welcome To Game A Toll</h3> </div> </div> <Box component="form" sx={{ "& > :not(style)": { m: 1, width: "25ch" }, }} noValidate autoComplete="off" className="text_field_box" > <TextField id="outlined-basic" label="Username" variant="outlined" className="text_field" type="text" error={validateUsername} helperText={validateUsername?"username already taken":""} onChange={(e) => { setUsername(e.target.value); }} /> <TextField id="outlined-basic" label="Email" variant="outlined" className="text_field" type="email" onChange={(e) => { setEmail(e.target.value); }} /> <TextField id="outlined-basic" type="password" label="Password" variant="outlined" className="text_field" onChange={(e) => { setPassword(e.target.value); }} /> <TextField id="outlined-basic" type="Password" label="Confirm Password" variant="outlined" className="text_field" onChange={(e) => { setConfirmPassword(e.target.value); }} /> </Box> <div className="login_btn"> <button className="continue_btn" onClick={sendData}> Continue </button> </div> <div className="or_line"> <div className="line"></div> <div>OR</div> <div className="line"></div> </div> <div className="social_btn"> <button> <div className="inside_social_btn"> <div className="inside_svg"> <img src="/assets/images/google.png" /> </div> <div className="ctn_with_btn"> <a className="gogle_btn" href={`${API_ENDPOINT}/auth/google`} > Continue With Google </a> </div> </div> </button> </div> <div className="social_btn"> <button> <div className="inside_social_btn"> <div className="inside_svg"> <img src="/assets/images/facebook.png" /> </div> <div className="ctn_with_btn"> <a href={`${API_ENDPOINT}/auth/facebook`}> Continue With Facebook </a> </div> </div> </button> </div> <div className="social_btn"> <button onClick={showLogin}> <div className="inside_social_btn"> <div className="inside_svg"></div> <div className="ctn_with_btn"> Already have an account? Please Login here </div> </div> </button> </div> </div> </div> </Dialog> </> ); } export default Signup;
class Complex { constructor(value) { this.value = value; } get x() { return this.value.x; } set x(x) { this.value.x = x; } get y() { return this.value.y; } set y(y) { this.value.y = y; } add(other) { this.x = this.x + other.x; this.y = this.y + other.y; return this; } pow2() { const x = (Math.pow(this.x, 2) - Math.pow(this.y, 2)) const y = ((this.x * this.y) + (this.x * this.y)) this.x = x this.y = y return this; } abs() { return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)); } } function calcZ(c, n) { let z = new Complex({ x: 0, y: 0 }); let i = 0; let abs = 0; do { z = z.pow2().add(c); abs = z.abs(); i += 1; } while (abs <= 2 && i < n); return [i, abs <= 2]; } export function mandelbrotJsV2(n, options, reporter, render) { console.log("[JS] Starting mandelbrot benchmark v2"); let report = { totalTime: 0, nthReport: [], }; const start = performance.now(); for (let i = 1; i <= n; i++) { let map = []; const startTime = performance.now(); const c = new Complex({ x: 0, y: 0}) for (let yMap = 0; yMap <= options.height; yMap++) { for (let xMap = 0; xMap <= options.width; xMap++) { c.x = options.xSet.start + (xMap / options.width) * (options.xSet.end - options.xSet.start) c.y = options.ySet.start + (yMap / options.height) * (options.ySet.end - options.ySet.start) const [z, isMandelBrot] = calcZ(c, i); map.push({ x: xMap, y: yMap, z, isMandelBrot }); } } const endTime = performance.now(); render ? reporter(i, map) : reporter(i); report.nthReport.push({ n: i, time: Math.round(endTime - startTime) }); } const end = performance.now(); console.log("[JS] Finished mandelbrot benchmark v2"); report.totalTime = Math.round(end - start); return report; }
import os import sys import forensicWace.Service as Service # Comment this to develop on local. Add to create package to download and install pip #import Service # Uncomment this to develop on local. Add to create package to download and install pip from reportlab.lib.pagesizes import landscape, A4 from reportlab.lib import colors from reportlab.lib.units import mm from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Spacer from reportlab.lib.colors import HexColor from reportlab.pdfgen import canvas basePath = os.path.dirname(os.path.abspath(__file__)).replace('\\','/') def CreateHorizontalDocHeaderAndFooter(canvas, doc): canvas.saveState() canvas.restoreState() page_num = canvas.getPageNumber() text = "Page %s" % page_num canvas.drawCentredString(148.5 * mm, 20 * mm, text) canvas.line(15 * mm, 25 * mm, 282 * mm, 25 * mm) def CreateVerticalDocHeaderAndFooter(canvas, doc): canvas.saveState() canvas.drawImage(basePath + "/assets/img/Logo.png", A4[0] / 2 - 158, A4[1] - 65, width=300, height=52.5) canvas.restoreState() page_num = canvas.getPageNumber() text = "Page %s" % page_num canvas.drawCentredString(105 * mm, 20 * mm, text) canvas.line(15 * mm, 25 * mm, 195 * mm, 25 * mm) def ChatListReport(outputPath, fileName, extractedDataList): data = [["Contact", "Username", "Phone number", "Number of messages", "Last Message Date"]] for extractedData in extractedDataList: data.append([extractedData["Contact"], extractedData["UserName"], Service.FormatPhoneNumber(extractedData["PhoneNumber"]), extractedData["NumberOfMessages"], extractedData["MessageDate"]]) outFileName = outputPath + fileName + "-ChatList.pdf" # Configurazione del documento doc = SimpleDocTemplate(outFileName, pagesize=A4) fileElements = [] table = Table(data, colWidths=[100, 110, 110, 110]) # Stili della tabella style = TableStyle([ ('BACKGROUND', (0, 0), (-1, 0), colors.grey), ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'), ('FONTSIZE', (0, 0), (-1, 0), 10), ('BOTTOMPADDING', (0, 0), (-1, 0), 11), ('BACKGROUND', (0, 1), (-1, -1), colors.beige), ('TEXTCOLOR', (0, 1), (-1, -1), colors.black), ('ALIGN', (0, 1), (-1, -1), 'CENTER'), ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'), ('FONTSIZE', (0, 1), (-1, -1), 8), ('BOTTOMPADDING', (0, 1), (-1, -1), 6), ]) table.setStyle(style) fileElements.append(table) # Scrittura del documento doc.build(fileElements, onFirstPage=CreateVerticalDocHeaderAndFooter, onLaterPages=CreateVerticalDocHeaderAndFooter) Service.CertificateReport(outFileName) # Verifica l'esistenza del file PDF appena creato. # SE esiste lo apre automaticamente # ALTRIMENTI stampa un messaggio di errore if os.path.exists(outFileName): if sys.platform.startswith('win'): # Windows os.system("start " + outFileName) elif sys.platform.startswith('darwin'): # macOS os.system("open " + outFileName) # elif sys.platform.startswith('linux'): # Linux else: print("Errore: il file PDF non è stato creato.") def PrivateChatReport(outputPath, phoneNumber, extractedData): outFileName = outputPath + phoneNumber + "-Chat.pdf" # Define pages margins left_margin = 50 right_margin = 50 bottom_margin = 100 top_margin = 100 # Create the canvas for the report c = canvas.Canvas(outFileName, pagesize=A4) # Get starting positions to start writing x_offset = left_margin y_offset = c._pagesize[1] - top_margin # Define message box characteristics message_box_height = 40 message_box_radius = 20 # Define colors to use message_box_color_green = HexColor('#DCF8C6') message_box_color_blue = HexColor('#C6E9F9') message_box_text_color = HexColor('#000000') # Set line height line_height = 30 # Insert logo and page number on the first page c.drawImage(basePath + "/assets/img/Logo.png", A4[0] / 2 - 150, A4[1] - 65, width=300, height=52.5) page_num = c.getPageNumber() text = "Page %s" % page_num c.drawCentredString(105 * mm, 20 * mm, text) c.line(15 * mm, 25 * mm, 195 * mm, 25 * mm) previousSender = 'NotAssigned' for chat in extractedData: # Check if the point where to write is inside the bottom margin # If YES save the ended page and update the position if y_offset < bottom_margin: c.showPage() y_offset = c._pagesize[1] - top_margin # Insert logo and page number on the page c.drawImage(basePath + "/assets/img/Logo.png", A4[0] / 2 - 150, A4[1] - 65, width=300, height=52.5) page_num = c.getPageNumber() text = "Page %s" % page_num c.drawCentredString(105 * mm, 20 * mm, text) c.line(15 * mm, 25 * mm, 195 * mm, 25 * mm) message_text = chat['text'] message_width = 0 if chat['ZMESSAGETYPE'] == 0: message_width = c.stringWidth(message_text, 'Helvetica', 12) message_box_width = message_width + 40 message_box_height = 40 allegati = -1 eliminato = "This message has been deleted by the sender" if chat['ZMESSAGETYPE'] == 1: allegati = 1 elif chat['ZMESSAGETYPE'] == 2: allegati = 2 message_width = c.stringWidth(Service.ConvertSeconds(chat['durata']), 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 3: allegati = 3 message_width = c.stringWidth(Service.ConvertSeconds(chat['durata']), 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 4: allegati = 4 message_width = c.stringWidth(chat["ZPARTNERNAME"], 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 5: allegati = 5 message_width = c.stringWidth(str(chat['latitudine']) + " , " + str(chat["longitudine"]), 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 6: allegati = 6 elif chat['ZMESSAGETYPE'] == 7: allegati = 7 elif chat['ZMESSAGETYPE'] == 8: allegati = 8 if chat['text'] != 'None': message_width = c.stringWidth(chat['text'], 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 11: # GIF ID allegati = 11 message_width = c.stringWidth("GIF", 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 14: allegati = 14 message_width = c.stringWidth(eliminato, 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 15: # Sticker ID allegati = 15 message_width = c.stringWidth("Sticker", 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 38: # Foto 1 visualizzazione allegati = 38 message_width = c.stringWidth("Image", 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 39: # Video 1 visualizzazione allegati = 39 message_width = c.stringWidth(Service.ConvertSeconds(chat['durata']), 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 46: allegati = 46 message_width = c.stringWidth("Poll", 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 0: allegati = 0 # Just a text message # Check if the box exceeds the margin # If NO then set the box dimensions if message_box_width > c._pagesize[0] - right_margin - left_margin: message_box_width = c._pagesize[0] - right_margin - left_margin # Check who wrote the message, then set the right color, user name and phone number if previousSender != chat['user']: if chat['user'] is not None: c.setFillColor(message_box_color_blue) c.drawString(x_offset, y_offset, chat['ZPARTNERNAME'] + " - " + "(" + Service.FormatPhoneNumber(chat['user']) + ")") y_offset -= 50 else: c.setFillColor(message_box_color_green) c.drawString(x_offset, y_offset, "Database Owner") y_offset -= 50 else: y_offset -= 30 # Split the text on multiple rows lines = [] line = '' if chat['ZMESSAGETYPE'] == 0: words = chat['text'].split() for word in words: if len(line + word) > 85: lines.append(line) line = word + ' ' message_box_height += 18 y_offset -= 18 else: line += word + ' ' lines.append(line) num_lines = len(lines) # Check if the point where to write is inside the bottom margin # If YES save the ended page and update the position if y_offset < bottom_margin: c.showPage() y_offset = c._pagesize[1] - top_margin - num_lines * 35 # Inserimento logo e numero di pagina sulla pagina c.drawImage(basePath + "/assets/img/Logo.png", A4[0] / 2 - 150, A4[1] - 65, width=300, height=52.5) page_num = c.getPageNumber() text = "Page %s" % page_num c.drawCentredString(105 * mm, 20 * mm, text) c.line(15 * mm, 25 * mm, 195 * mm, 25 * mm) # Set the right color and design the rectangle c.setFillColor(message_box_color_blue if chat['user'] is not None else message_box_color_green) c.roundRect(x_offset, y_offset, message_box_width, message_box_height, message_box_radius, stroke=0, fill=1) c.setFillColor(message_box_text_color) if allegati == 1: c.drawImage(basePath + "/src/icons/CameraNum.png" if chat['user'] is not None else basePath + "/src/icons/CameraUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 y_offset -= 16 elif allegati == 2: c.drawImage(basePath + "/src/icons/VideoNum.png" if chat['user'] is not None else basePath + "/src/icons/VideoUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, Service.ConvertSeconds(chat['durata'])) y_offset -= 16 elif allegati == 3: c.drawImage(basePath + "/src/icons/MicNum.png" if chat['user'] is not None else basePath + "/src/icons/MicUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, Service.ConvertSeconds(chat['durata'])) y_offset -= 16 elif allegati == 4: c.drawImage(basePath + "/src/icons/ContactNum.png" if chat['user'] is not None else basePath + "/src/icons/ContactUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, chat["ZPARTNERNAME"]) y_offset -= 16 elif allegati == 5: c.drawImage(basePath + "/src/icons/PositionNum.png" if chat['user'] is not None else basePath + "/src/icons/PositionUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, str(chat['latitudine']) + " , " + str(chat["longitudine"])) y_offset -= 16 elif allegati == 6: c.drawImage( basePath + "/src/icons/GroupNum.png" if chat['user'] is not None else basePath + "/src/icons/GroupUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 y_offset -= 16 elif allegati == 7: c.drawImage(basePath + "/src/icons/LinkNum.png" if chat['user'] is not None else basePath + "/src/icons/LinkUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 y_offset -= 16 elif allegati == 8: c.drawImage(basePath + "/src/icons/DocNum.png" if chat['user'] is not None else basePath + "/src/icons/DocUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 if chat["text"] != 'None': c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, chat['text']) y_offset -= 16 elif allegati == 11: c.drawImage(basePath + "/src/icons/GifNum.png" if chat['user'] == 'Database owner' else basePath + "/src/icons/GifUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, "GIF") y_offset -= 16 elif allegati == 14: c.drawImage(basePath + "/src/icons/BinNum.png" if chat['user'] is not None else basePath + "/src/icons/BinUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, eliminato) y_offset -= 16 elif allegati == 15: c.drawImage(basePath + "/src/icons/StickerNum.png" if chat['user'] is not None else basePath + "/src/icons/StickerUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, "Sticker") y_offset -= 16 elif allegati == 38: c.drawImage(basePath + "/src/icons/OneTimeNum.png" if chat['user'] is not None else basePath + "/src/icons/OneTimeUSer.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, "Image") y_offset -= 16 elif allegati == 39: c.drawImage(basePath + "/src/icons/OneTimeNum.png" if chat['user'] is not None else basePath + "/src/icons/OneTimeUSer.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, Service.ConvertSeconds(chat['durata'])) y_offset -= 16 elif allegati == 46: c.drawImage(basePath + "/src/icons/PollNum.png" if chat['user'] is not None else basePath + "/src/icons/PollUSer.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, "Poll") y_offset -= 16 # Check if the number of lines is >= 2 # If YES them update the Y coordinate if num_lines >= 2: y_offset += message_box_height / 2 - 20 # Print the message into the box for line in lines: c.drawString(x_offset + 20, y_offset + message_box_height / 2 - 6, line) y_offset -= 16 if chat['user'] is None: c.setFont("Helvetica", 8) c.drawString(x_offset, y_offset, "Send date: " + Service.GetSentDateTime(chat['dateTimeInfos'])) y_offset -= 12 c.drawString(x_offset, y_offset, "Reading date: " + Service.GetReadDateTime(chat['dateTimeInfos'])) else: c.setFont("Helvetica", 8) c.drawString(x_offset, y_offset, "Send date: " + chat['receiveDateTime'] + " UTC") y_offset -= 26 c.setFont("Helvetica", 12) previousSender = chat['user'] # Save the PDF file c.save() Service.CertificateReport(outFileName) # Verifica l'esistenza del file PDF appena creato. # SE esiste lo apre automaticamente # ALTRIMENTI stampa un messaggio di errore if os.path.exists(outFileName): if sys.platform.startswith('win'): # Windows os.system("start " + outFileName) elif sys.platform.startswith('darwin'): # macOS os.system("open " + outFileName) # elif sys.platform.startswith('linux'): # Linux else: print("Errore: il file PDF non è stato creato.") def GpsLocations(outputPath, fileName, extractedDataList): data = [["Sender", "Receiver", "Date", "Latitude", "Longitude"]] for extractedData in extractedDataList: data.append([Service.FormatPhoneNumber(extractedData["Sender"]), Service.FormatPhoneNumber(extractedData["Receiver"]), extractedData["MessageDate"], extractedData["Latitude"], extractedData["Longitude"]]) outFileName = outputPath + fileName + "-GpsLocations.pdf" # Configurazione del documento doc = SimpleDocTemplate(outFileName, pagesize=A4) fileElements = [] table = Table(data, colWidths=[100, 110, 110, 110]) # Stili della tabella style = TableStyle([ ('BACKGROUND', (0, 0), (-1, 0), colors.grey), ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'), ('FONTSIZE', (0, 0), (-1, 0), 10), ('BOTTOMPADDING', (0, 0), (-1, 0), 11), ('BACKGROUND', (0, 1), (-1, -1), colors.beige), ('TEXTCOLOR', (0, 1), (-1, -1), colors.black), ('ALIGN', (0, 1), (-1, -1), 'CENTER'), ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'), ('FONTSIZE', (0, 1), (-1, -1), 8), ('BOTTOMPADDING', (0, 1), (-1, -1), 6), ]) table.setStyle(style) fileElements.append(table) # Scrittura del documento doc.build(fileElements, onFirstPage=CreateVerticalDocHeaderAndFooter, onLaterPages=CreateVerticalDocHeaderAndFooter) Service.CertificateReport(outFileName) # Verifica l'esistenza del file PDF appena creato. # SE esiste lo apre automaticamente # ALTRIMENTI stampa un messaggio di errore if os.path.exists(outFileName): if sys.platform.startswith('win'): # Windows os.system("start " + outFileName) elif sys.platform.startswith('darwin'): # macOS os.system("open " + outFileName) # elif sys.platform.startswith('linux'): # Linux else: print("Errore: il file PDF non è stato creato.") def BlockedContactReport(outputPath, fileName, extractedDataList): data = [["Name", "Phone number"]] for extractedData in extractedDataList: if extractedData["Name"] == None: extractedData["Name"] = "Not Available" data.append([extractedData["Name"], Service.FormatPhoneNumber(extractedData["PhoneNumber"])]) outFileName = outputPath + fileName + "-BlockedContacts.pdf" # Configurazione del documento doc = SimpleDocTemplate(outFileName, pagesize=A4) fileElements = [] table = Table(data, colWidths=[100, 110, 110, 110]) # Stili della tabella style = TableStyle([ ('BACKGROUND', (0, 0), (-1, 0), colors.grey), ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'), ('FONTSIZE', (0, 0), (-1, 0), 10), ('BOTTOMPADDING', (0, 0), (-1, 0), 11), ('BACKGROUND', (0, 1), (-1, -1), colors.beige), ('TEXTCOLOR', (0, 1), (-1, -1), colors.black), ('ALIGN', (0, 1), (-1, -1), 'CENTER'), ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'), ('FONTSIZE', (0, 1), (-1, -1), 8), ('BOTTOMPADDING', (0, 1), (-1, -1), 6), ]) table.setStyle(style) fileElements.append(table) # Scrittura del documento doc.build(fileElements, onFirstPage=CreateVerticalDocHeaderAndFooter, onLaterPages=CreateVerticalDocHeaderAndFooter) Service.CertificateReport(outFileName) # Verifica l'esistenza del file PDF appena creato. # SE esiste lo apre automaticamente # ALTRIMENTI stampa un messaggio di errore if os.path.exists(outFileName): if sys.platform.startswith('win'): # Windows os.system("start " + outFileName) elif sys.platform.startswith('darwin'): # macOS os.system("open " + outFileName) # elif sys.platform.startswith('linux'): # Linux else: print("Errore: il file PDF non è stato creato.") def GroupListReport(outputPath, fileName, extractedDataList): data = [["Group Name", "Last message", "Number of messages", "Notification status"]] for extractedData in extractedDataList: if extractedData["Is_muted"] == None: extractedData["Is_muted"] = "Active" else: extractedData["Is_muted"] = "Disabled" data.append([extractedData["Group_Name"], extractedData["Message_Date"], extractedData["Number_of_Messages"], extractedData["Is_muted"]]) outFileName = outputPath + fileName + "-GroupList.pdf" # Configurazione del documento doc = SimpleDocTemplate(outFileName, pagesize=A4) fileElements = [] table = Table(data, colWidths=[100, 110, 110, 110]) # Stili della tabella style = TableStyle([ ('BACKGROUND', (0, 0), (-1, 0), colors.grey), ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'), ('FONTSIZE', (0, 0), (-1, 0), 10), ('BOTTOMPADDING', (0, 0), (-1, 0), 11), ('BACKGROUND', (0, 1), (-1, -1), colors.beige), ('TEXTCOLOR', (0, 1), (-1, -1), colors.black), ('ALIGN', (0, 1), (-1, -1), 'CENTER'), ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'), ('FONTSIZE', (0, 1), (-1, -1), 8), ('BOTTOMPADDING', (0, 1), (-1, -1), 6), ]) table.setStyle(style) fileElements.append(table) # Scrittura del documento doc.build(fileElements, onFirstPage=CreateVerticalDocHeaderAndFooter, onLaterPages=CreateVerticalDocHeaderAndFooter) Service.CertificateReport(outFileName) # Verifica l'esistenza del file PDF appena creato. # SE esiste lo apre automaticamente # ALTRIMENTI stampa un messaggio di errore if os.path.exists(outFileName): if sys.platform.startswith('win'): # Windows os.system("start " + outFileName) elif sys.platform.startswith('darwin'): # macOS os.system("open " + outFileName) # elif sys.platform.startswith('linux'): # Linux else: print("Errore: il file PDF non è stato creato.") def GroupChatReport(outputPath, groupName, extractedData): words = groupName.split() groupNameNoSpaces = ''.join(words) outFileName = outputPath + groupNameNoSpaces + "-Chat.pdf" # Define pages margins left_margin = 50 right_margin = 50 bottom_margin = 100 top_margin = 100 # Create the canvas for the report c = canvas.Canvas(outFileName, pagesize=A4) # Get starting positions to start writing x_offset = left_margin y_offset = c._pagesize[1] - top_margin # Define message box characteristics message_box_height = 40 message_box_radius = 20 # Define colors to use message_box_color_green = HexColor('#DCF8C6') message_box_color_blue = HexColor('#C6E9F9') message_box_text_color = HexColor('#000000') # Set line height line_height = 30 # Insert logo and page number on the first page c.drawImage(basePath + "/assets/img/Logo.png", A4[0] / 2 - 150, A4[1] - 65, width=300, height=52.5) page_num = c.getPageNumber() text = "Page %s" % page_num c.drawCentredString(105 * mm, 20 * mm, text) c.line(15 * mm, 25 * mm, 195 * mm, 25 * mm) previousSender = 'NotAssigned' for chat in extractedData: # Check if the point where to write is inside the bottom margin # If YES save the ended page and update the position if y_offset < bottom_margin: c.showPage() y_offset = c._pagesize[1] - top_margin # Insert logo and page number on the page c.drawImage(basePath + "/assets/img/Logo.png", A4[0] / 2 - 150, A4[1] - 65, width=300, height=52.5) page_num = c.getPageNumber() text = "Page %s" % page_num c.drawCentredString(105 * mm, 20 * mm, text) c.line(15 * mm, 25 * mm, 195 * mm, 25 * mm) message_text = chat['text'] message_width = 0 if chat['ZMESSAGETYPE'] == 0: message_width = c.stringWidth(message_text, 'Helvetica', 12) message_box_width = message_width + 40 message_box_height = 40 allegati = -1 eliminato = "This message has been deleted by the sender" if chat['ZMESSAGETYPE'] == 1: allegati = 1 elif chat['ZMESSAGETYPE'] == 2: allegati = 2 message_width = c.stringWidth(Service.ConvertSeconds(chat['durata']), 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 3: allegati = 3 message_width = c.stringWidth(Service.ConvertSeconds(chat['durata']), 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 4: allegati = 4 message_width = c.stringWidth(chat["ZPARTNERNAME"], 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 5: allegati = 5 message_width = c.stringWidth(str(chat['latitudine']) + " , " + str(chat["longitudine"]), 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 6: allegati = 6 elif chat['ZMESSAGETYPE'] == 7: allegati = 7 elif chat['ZMESSAGETYPE'] == 8: allegati = 8 if chat['text'] != 'None': message_width = c.stringWidth(chat['text'], 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 11: # GIF ID allegati = 11 message_width = c.stringWidth("GIF", 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 14: allegati = 14 message_width = c.stringWidth(eliminato, 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 15: # Sticker ID allegati = 15 message_width = c.stringWidth("Sticker", 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 38: # Foto 1 visualizzazione allegati = 38 message_width = c.stringWidth("Image", 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 39: # Video 1 visualizzazione allegati = 39 message_width = c.stringWidth(Service.ConvertSeconds(chat['durata']), 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 46: allegati = 46 message_width = c.stringWidth("Poll", 'Helvetica', 12) message_box_width = message_width + 52 elif chat['ZMESSAGETYPE'] == 0: allegati = 0 # Just a text message # Check if the box exceeds the margin # If NO then set the box dimensions if message_box_width > c._pagesize[0] - right_margin - left_margin: message_box_width = c._pagesize[0] - right_margin - left_margin # Check who wrote the message, then set the right color, user name and phone number if previousSender != chat['user']: if chat['user'] is not None: c.setFillColor(message_box_color_blue) c.drawString(x_offset, y_offset, chat['contactName'] + " - " + "(" + Service.FormatPhoneNumber(chat['user']) + ")") y_offset -= 50 else: c.setFillColor(message_box_color_green) c.drawString(x_offset, y_offset, "Database Owner") y_offset -= 50 else: y_offset -= 30 # Split the text on multiple rows lines = [] line = '' if chat['ZMESSAGETYPE'] == 0: words = chat['text'].split() for word in words: if len(line + word) > 85: lines.append(line) line = word + ' ' message_box_height += 18 y_offset -= 18 else: line += word + ' ' lines.append(line) num_lines = len(lines) # Check if the point where to write is inside the bottom margin # If YES save the ended page and update the position if y_offset < bottom_margin: c.showPage() y_offset = c._pagesize[1] - top_margin - num_lines * 35 # Inserimento logo e numero di pagina sulla pagina c.drawImage(basePath + "/assets/img/Logo.png", A4[0] / 2 - 150, A4[1] - 65, width=300, height=52.5) page_num = c.getPageNumber() text = "Page %s" % page_num c.drawCentredString(105 * mm, 20 * mm, text) c.line(15 * mm, 25 * mm, 195 * mm, 25 * mm) # Set the right color and design the rectangle c.setFillColor(message_box_color_blue if chat['user'] is not None else message_box_color_green) c.roundRect(x_offset, y_offset, message_box_width, message_box_height, message_box_radius, stroke=0, fill=1) c.setFillColor(message_box_text_color) if allegati == 1: c.drawImage(basePath + "/src/icons/CameraNum.png" if chat['user'] is not None else basePath + "/src/icons/CameraUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 y_offset -= 16 elif allegati == 2: c.drawImage(basePath + "/src/icons/VideoNum.png" if chat['user'] is not None else basePath + "/src/icons/VideoUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, Service.ConvertSeconds(chat['durata'])) y_offset -= 16 elif allegati == 3: c.drawImage(basePath + "/src/icons/MicNum.png" if chat['user'] is not None else basePath + "/src/icons/MicUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, Service.ConvertSeconds(chat['durata'])) y_offset -= 16 elif allegati == 4: c.drawImage(basePath + "/src/icons/ContactNum.png" if chat['user'] is not None else basePath + "/src/icons/ContactUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, chat["ZPARTNERNAME"]) y_offset -= 16 elif allegati == 5: c.drawImage(basePath + "/src/icons/PositionNum.png" if chat['user'] is not None else basePath + "/src/icons/PositionUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, str(chat['latitudine']) + " , " + str(chat["longitudine"])) y_offset -= 16 elif allegati == 6: c.drawImage(basePath + "/src/icons/GroupNum.png" if chat['user'] is not None else basePath + "/src/icons/GroupUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 y_offset -= 16 elif allegati == 7: c.drawImage(basePath + "/src/icons/LinkNum.png" if chat['user'] is not None else basePath + "/src/icons/LinkUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 y_offset -= 16 elif allegati == 8: c.drawImage(basePath + "/src/icons/DocNum.png" if chat['user'] is not None else basePath + "/src/icons/DocUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 if chat["text"] != 'None': c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, chat['text']) y_offset -= 16 elif allegati == 11: c.drawImage(basePath + "/src/icons/GifNum.png" if chat['user'] == 'Database owner' else basePath + "/src/icons/GifUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, "GIF") y_offset -= 16 elif allegati == 14: c.drawImage(basePath + "/src/icons/BinNum.png" if chat['user'] is not None else basePath + "/src/icons/BinUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, eliminato) y_offset -= 16 elif allegati == 15: c.drawImage(basePath + "/src/icons/StickerNum.png" if chat['user'] is not None else basePath + "/src/icons/StickerUser.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, "Sticker") y_offset -= 16 elif allegati == 38: c.drawImage(basePath + "/src/icons/OneTimeNum.png" if chat['user'] is not None else basePath + "/src/icons/OneTimeUSer.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, "Image") y_offset -= 16 elif allegati == 39: c.drawImage(basePath + "/src/icons/OneTimeNum.png" if chat['user'] is not None else basePath + "/src/icons/OneTimeUSer.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, Service.ConvertSeconds(chat['durata'])) y_offset -= 16 elif allegati == 46: c.drawImage(basePath + "/src/icons/PollNum.png" if chat['user'] is not None else basePath + "/src/icons/PollUSer.png", x_offset + 14, y_offset + message_box_height / 2 - 7, width=12, height=12) allegati = -1 c.drawString(x_offset + 32, y_offset + message_box_height / 2 - 6, "Poll") y_offset -= 16 # Check if the number of lines is >= 2 # If YES them update the Y coordinate if num_lines >= 2: y_offset += message_box_height / 2 - 20 # Print the message into the box for line in lines: c.drawString(x_offset + 20, y_offset + message_box_height / 2 - 6, line) y_offset -= 16 if chat['user'] is None: c.setFont("Helvetica", 8) c.drawString(x_offset, y_offset, "Send date: " + Service.GetSentDateTime(chat['dateTimeInfos'])) y_offset -= 12 c.drawString(x_offset, y_offset, "Reading date: " + Service.GetReadDateTime(chat['dateTimeInfos'])) else: c.setFont("Helvetica", 8) c.drawString(x_offset, y_offset, "Send date: " + chat['receiveDateTime'] + " UTC") y_offset -= 26 c.setFont("Helvetica", 12) previousSender = chat['user'] # Save the PDF file c.save() Service.CertificateReport(outFileName) # Verifica l'esistenza del file PDF appena creato. # SE esiste lo apre automaticamente # ALTRIMENTI stampa un messaggio di errore if os.path.exists(outFileName): if sys.platform.startswith('win'): # Windows os.system("start " + outFileName) elif sys.platform.startswith('darwin'): # macOS os.system("open " + outFileName) # elif sys.platform.startswith('linux'): # Linux else: print("Errore: il file PDF non è stato creato.") def DbHash(inputPath, outputPath, fileName): data = [["Database file name", "Hash code - SHA256"], [fileName, Service.CalculateSHA256(inputPath)]] outFileName = outputPath + fileName + "-DatabaseHash.pdf" # Configurazione del documento doc = SimpleDocTemplate(outFileName, pagesize=landscape(A4)) fileElements = [] table = Table(data, colWidths=[350, 350]) # Stili della tabella style = TableStyle([ ('BACKGROUND', (0, 0), (-1, 0), colors.grey), ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'), ('FONTSIZE', (0, 0), (-1, 0), 12), ('BOTTOMPADDING', (0, 0), (-1, 0), 12), ('BACKGROUND', (0, 1), (-1, -1), colors.beige), ('TEXTCOLOR', (0, 1), (-1, -1), colors.black), ('ALIGN', (0, 1), (-1, -1), 'CENTER'), ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'), ('FONTSIZE', (0, 1), (-1, -1), 8), ('BOTTOMPADDING', (0, 1), (-1, -1), 6), ]) table.setStyle(style) fileElements.append(table) fileElements.append(Spacer(1, 20)) # 1 unità di larghezza e 20 unità di altezza) data = [["Database file name", "Hash code - MD5"], [fileName, Service.CalculateMD5(inputPath)]] table = Table(data, colWidths=[350, 350]) table.setStyle(style) fileElements.append(table) # Scrittura del documento doc.build(fileElements, onFirstPage=CreateHorizontalDocHeaderAndFooter) Service.CertificateReport(outFileName) # Verifica l'esistenza del file PDF appena creato. # SE esiste lo apre automaticamente # ALTRIMENTI stampa un messaggio di errore if os.path.exists(outFileName): if sys.platform.startswith('win'): # Windows os.system("start " + outFileName) elif sys.platform.startswith('darwin'): # macOS os.system("open " + outFileName) # elif sys.platform.startswith('linux'): # Linux else: print("Errore: il file PDF non è stato creato.") def CalculateMediaSHA256(directory_path, outputPath, fileName): data = [["File PATH", "SHA256"]] for root, _, files in os.walk(directory_path): for file_name in files: file_path = os.path.join(root, file_name) relative_path = os.path.relpath(file_path, directory_path) print(relative_path) data.append([os.path.basename(file_path), Service.CalculateSHA256(file_path)]) outFileName = outputPath + fileName + "-Media-SHA256.pdf" # Configurazione del documento doc = SimpleDocTemplate(outFileName, pagesize=landscape(A4)) fileElements = [] table = Table(data, colWidths=[350, 350]) # Stili della tabella style = TableStyle([ ('BACKGROUND', (0, 0), (-1, 0), colors.grey), ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'), ('FONTSIZE', (0, 0), (-1, 0), 12), ('BOTTOMPADDING', (0, 0), (-1, 0), 12), ('BACKGROUND', (0, 1), (-1, -1), colors.beige), ('TEXTCOLOR', (0, 1), (-1, -1), colors.black), ('ALIGN', (0, 1), (-1, -1), 'CENTER'), ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'), ('FONTSIZE', (0, 1), (-1, -1), 8), ('BOTTOMPADDING', (0, 1), (-1, -1), 6), ]) table.setStyle(style) fileElements.append(table) # Scrittura del documento doc.build(fileElements, onFirstPage=CreateHorizontalDocHeaderAndFooter) Service.CertificateReport(outFileName) # Verifica l'esistenza del file PDF appena creato. # SE esiste lo apre automaticamente # ALTRIMENTI stampa un messaggio di errore if os.path.exists(outFileName): if sys.platform.startswith('win'): # Windows os.system("start " + outFileName) elif sys.platform.startswith('darwin'): # macOS os.system("open " + outFileName) # elif sys.platform.startswith('linux'): # Linux else: print("Errore: il file PDF non è stato creato.") def CalculateMediaMD5(directory_path, outputPath, fileName): data = [["File PATH", "MD5"]] for root, _, files in os.walk(directory_path): for file_name in files: file_path = os.path.join(root, file_name) relative_path = os.path.relpath(file_path, directory_path) print(relative_path) data.append([os.path.basename(file_path), Service.CalculateMD5(file_path)]) outFileName = outputPath + fileName + "-Media-MD5.pdf" # Configurazione del documento doc = SimpleDocTemplate(outFileName, pagesize=landscape(A4)) fileElements = [] table = Table(data, colWidths=[350, 350]) # Stili della tabella style = TableStyle([ ('BACKGROUND', (0, 0), (-1, 0), colors.grey), ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'), ('FONTSIZE', (0, 0), (-1, 0), 12), ('BOTTOMPADDING', (0, 0), (-1, 0), 12), ('BACKGROUND', (0, 1), (-1, -1), colors.beige), ('TEXTCOLOR', (0, 1), (-1, -1), colors.black), ('ALIGN', (0, 1), (-1, -1), 'CENTER'), ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'), ('FONTSIZE', (0, 1), (-1, -1), 8), ('BOTTOMPADDING', (0, 1), (-1, -1), 6), ]) table.setStyle(style) fileElements.append(table) # Scrittura del documento doc.build(fileElements, onFirstPage=CreateHorizontalDocHeaderAndFooter) Service.CertificateReport(outFileName) # Verifica l'esistenza del file PDF appena creato. # SE esiste lo apre automaticamente # ALTRIMENTI stampa un messaggio di errore if os.path.exists(outFileName): if sys.platform.startswith('win'): # Windows os.system("start " + outFileName) elif sys.platform.startswith('darwin'): # macOS os.system("open " + outFileName) # elif sys.platform.startswith('linux'): # Linux else: print("Errore: il file PDF non è stato creato.")
import React from "react"; import { Container, Nav, Navbar } from "react-bootstrap"; import { Link } from "react-router-dom"; import { Route } from "../../types"; import Logo from "../../assets/Logo.png"; import "./Navbar.scss"; interface NavBarProps { routes: Route[]; } export default function NavBar(props: NavBarProps) { const { routes } = props; return ( <Navbar className="nav-bar" bg="dark" variant="dark" fixed="top"> <Container> <Navbar.Brand> <img className="logo" src={Logo} alt={'logo'}/> </Navbar.Brand> <Nav className="me-auto"> {routes.map((route) => ( <Nav.Link> <Link className="nav-bar__link" to={route.path}> {route.name} </Link> </Nav.Link> ))} </Nav> </Container> </Navbar> ); }
import { NextFunction, Request, Response } from "express"; import User from "../models/User.js"; import { hash, compare } from "bcrypt"; import { createToken } from "../utils/token-manager.js"; import { COOKIE_NAME } from "../utils/constants.js"; export const getAllUsers = async ( req: Request, res: Response, next: NextFunction ) => { //get all users try { const users = await User.find(); return res.status(200).json({ message: "OK", users }); } catch (err) { console.log(err); return res.status(404).json({ message: "ERROR", cause: err.message }); } }; export const userSignup = async ( req: Request, res: Response, next: NextFunction ) => { //user signup try { const { name, email, password } = req.body; const existingUser = await User.findOne({ email }); if (existingUser) return res.status(401).send("User already registered"); const hashedPass = await hash(password, 10); const user = new User({ name, email, password: hashedPass, }); await user.save(); const token = createToken(user._id.toString(), user.email, "7d"); const expires = new Date(); expires.setDate(expires.getDate() + 7); res.cookie(COOKIE_NAME, token, { path: "/", expires, httpOnly: true, signed: true, }); return res.status(201).json({ message: "OK", name: user.name, email: user.email, }); } catch (err) { console.log(err); return res.status(404).json({ message: "ERROR", cause: err.message }); } }; export const userLogin = async ( req: Request, res: Response, next: NextFunction ) => { //user login console.log("test"); try { const { email, password } = req.body; const existingUser = await User.findOne({ email }); if (!existingUser) return res.status(401).send("User not registered"); const isPasswordCorrect = await compare(password, existingUser.password); if (!isPasswordCorrect) return res.status(403).send("Incorrect Password"); const token = createToken( existingUser._id.toString(), existingUser.email, "7d" ); const expires = new Date(); expires.setDate(expires.getDate() + 7); res.cookie(COOKIE_NAME, token, { path: "/", expires, httpOnly: true, signed: true, }); return res.status(201).json({ message: "OK", name: existingUser.name, email: existingUser.email, }); } catch (err) { console.log(err); return res.status(404).json({ message: "ERROR", cause: err.message }); } }; export const verifyUser = async ( req: Request, res: Response, next: NextFunction ) => { //user token check try { const existingUser = await User.findById(res.locals.jwtData.id); if (!existingUser) { return res.status(401).send("User not registered OR Token malfunctioned"); } if (existingUser._id.toString() !== res.locals.jwtData.id) { return res.status(401).send("Permissions didn't match"); } return res.status(200).json({ message: "OK", name: existingUser.name, email: existingUser.email, }); } catch (err) { console.log(err); return res.status(404).json({ message: "ERROR", cause: err.message }); } }; export const userLogout = async ( req: Request, res: Response, next: NextFunction ) => { //user token check try { const existingUser = await User.findById(res.locals.jwtData.id); if (!existingUser) return res.status(401).send("User not registered OR Token malfunctioned"); if (existingUser._id.toString() !== res.locals.jwtData.id) { return res.status(401).send("Permissions didn't match"); } res.clearCookie(COOKIE_NAME, { path: "/", httpOnly: true, signed: true, }); return res.status(201).json({ message: "OK", name: existingUser.name, email: existingUser.email, }); } catch (err) { console.log(err); return res.status(404).json({ message: "ERROR", cause: err.message }); } };
/* * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * Copyright 2022 Xyna GmbH, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ package com.gip.xyna.xnwh.xwarehousejobs; import java.util.concurrent.atomic.AtomicLong; import org.apache.log4j.Logger; import com.gip.xyna.CentralFactoryLogging; import com.gip.xyna.XynaFactory; import com.gip.xyna.utils.timing.TimedTasks; import com.gip.xyna.utils.timing.TimedTasks.Executor; import com.gip.xyna.xnwh.exceptions.XNWH_RetryTransactionException; import com.gip.xyna.xnwh.exceptions.XNWH_WarehouseJobScheduleParameterInvalidException; import com.gip.xyna.xprc.CronLikeOrderCreationParameter; import com.gip.xyna.xprc.XynaOrderServerExtension; import com.gip.xyna.xprc.exceptions.XPRC_CronLikeSchedulerException; import com.gip.xyna.xprc.xpce.dispatcher.DestinationKey; import com.gip.xyna.xprc.xpce.dispatcher.XynaDispatcher; import com.gip.xyna.xprc.xsched.cronlikescheduling.CronLikeOrder; import com.gip.xyna.xprc.xsched.cronlikescheduling.CronLikeOrderStatus; import com.gip.xyna.xprc.xsched.cronlikescheduling.CronLikeScheduler.CronLikeOrderPersistenceOption; public class WarehouseJobScheduleFactory { private static final Logger logger = CentralFactoryLogging.getLogger(WarehouseJobScheduleFactory.class); private static final Executor<DestinationKey> warehouseJobCleanupExecutor = new WarehouseJobCleanupExecutor(); private static final TimedTasks<DestinationKey> cleanupTasks = new TimedTasks<DestinationKey>("LateWarehouseJobCleanup", warehouseJobCleanupExecutor, true); public enum WarehouseJobScheduleType { CRONLS, SHUTDOWN, STARTUP, LIMIT; public static WarehouseJobScheduleType fromString(String s) { if (s == null) { throw new IllegalArgumentException("Argument may not be null"); } else if (s.equals(CRONLS.toString())) { return CRONLS; } else if (s.equals(SHUTDOWN.toString())) { return SHUTDOWN; } else if (s.equals(STARTUP.toString())) { return STARTUP; } else if (s.equals(LIMIT.toString())) { return LIMIT; } else { throw new IllegalArgumentException(WarehouseJobScheduleType.class.getSimpleName() + " '" + s + "' is unknown."); } } } private static AtomicLong cnt = new AtomicLong(0); private static final DestinationKey getNewDestinationKey(WarehouseJobScheduleType type) { return new DestinationKey(type.toString() + "_Job_" + cnt.getAndIncrement()); } /** * Creates a {@link WarehouseJobSchedule} object for a {@link WarehouseJobRunnable} that registers the runnable to be * executed on a regular basis. * * @param {@link WarehouseJobRunnable} - the job that is executed * @return {@link WarehouseJobSchedule} - the schedule object that can perform the registration and unregistration */ static WarehouseJobSchedule getCronSchedule(final WarehouseJobRunnable jobRunnable, final Long interval, final Long firstStartTime) { return new WarehouseJobSchedule() { CronLikeOrder underlyingCronLSJob; DestinationKey dk; private String[] scheduleParameters; @Override public final void registerInternally() { logger.debug("Registering "); dk = getNewDestinationKey(WarehouseJobScheduleType.CRONLS); XynaFactory.getInstance().getProcessing().getXynaProcessCtrlExecution().getXynaPlanning() .getPlanningDispatcher().setDestination(dk, XynaDispatcher.DESTINATION_DEFAULT_PLANNING, true); XynaFactory.getInstance().getProcessing().getXynaProcessCtrlExecution().getXynaExecution() .getExecutionEngineDispatcher().setDestination(dk, jobRunnable, true); XynaFactory.getInstance().getProcessing().getXynaProcessCtrlExecution().getXynaCleanup() .getCleanupEngineDispatcher().setDestination(dk, XynaDispatcher.DESTINATION_EMPTY_WORKFLOW, true); try { CronLikeOrderCreationParameter xocp = new CronLikeOrderCreationParameter(dk, firstStartTime, interval); underlyingCronLSJob = XynaFactory.getInstance().getProcessing().getXynaScheduler().getCronLikeScheduler() .createCronLikeOrder(xocp, CronLikeOrderPersistenceOption.REMOVE_ON_SHUTDOWN, null); } catch (XPRC_CronLikeSchedulerException e) { // TODO throw better exception? throw new RuntimeException("Error while registering cron warehouse job.", e); } catch (XNWH_RetryTransactionException e) { // TODO throw better exception? throw new RuntimeException("Error while registering cron warehouse job.", e); } } @Override public final void unregisterInternally() { XynaFactory.getInstance().getProcessing().getXynaProcessCtrlExecution().getXynaPlanning() .getPlanningDispatcher().removeDestination(dk); XynaFactory.getInstance().getProcessing().getXynaProcessCtrlExecution().getXynaExecution() .getExecutionEngineDispatcher().removeDestination(dk); cleanupTasks.addTask(System.currentTimeMillis() + 500, dk); if (underlyingCronLSJob != null) { try { XynaFactory.getInstance().getProcessing().getXynaScheduler().getCronLikeScheduler() .removeCronLikeOrder(underlyingCronLSJob); } catch (XPRC_CronLikeSchedulerException e) { // TODO throw better exception? throw new RuntimeException("Error while unregistering cron warehouse job.", e); } } else { logger.warn("Could not unregister " + getType().toString() + "-job '" + jobRunnable.getParentJob().getDescription() + "' because job information was not found"); } } @Override public final WarehouseJobScheduleType getType() { return WarehouseJobScheduleType.CRONLS; } @Override public String[] getScheduleParameters() { if (scheduleParameters == null) { scheduleParameters = new String[] {interval + "", firstStartTime + ""}; } return scheduleParameters; } @Override public boolean needsToRunAgain() { if (underlyingCronLSJob == null) { return false; } if (CronLikeOrderStatus.RUNNING_SINGLE_EXECUTION.equals(underlyingCronLSJob.getStatus())) { return false; } return true; } }; } /** * Creates a {@link WarehouseJobSchedule} object for a {@link WarehouseJobRunnable} that registers the runnable to be * executed every time the warehouse is shutdown. * @param {@link WarehouseJobRunnable} - the job that is executed * @return {@link WarehouseJobSchedule} - the schedule object that can perform the registration and unregistration */ static WarehouseJobSchedule getShutdownSchedule(final WarehouseJobRunnable jobRunnable) { return new WarehouseJobSchedule() { XynaOrderServerExtension xo; @Override public WarehouseJobScheduleType getType() { return WarehouseJobScheduleType.SHUTDOWN; } @Override public void registerInternally() { DestinationKey dk = getNewDestinationKey(WarehouseJobScheduleType.SHUTDOWN); xo = new XynaOrderServerExtension(dk); XynaFactory.getInstance().getProcessing().getXynaProcessCtrlExecution().getXynaPlanning() .getPlanningDispatcher().setDestination(dk, XynaDispatcher.DESTINATION_DEFAULT_PLANNING, true); XynaFactory.getInstance().getProcessing().getXynaProcessCtrlExecution().getXynaExecution() .getExecutionEngineDispatcher().setDestination(dk, jobRunnable, true); XynaFactory.getInstance().getProcessing().getXynaProcessCtrlExecution().getXynaCleanup() .getCleanupEngineDispatcher().setDestination(dk, XynaDispatcher.DESTINATION_EMPTY_WORKFLOW, true); XynaFactory.getInstance().getXynaNetworkWarehouse().addShutdownWarehouseJobOrder(xo); } @Override public void unregisterInternally() { if (xo != null) { XynaFactory.getInstance().getProcessing().getXynaProcessCtrlExecution().getXynaPlanning() .getPlanningDispatcher().removeDestination(xo.getDestinationKey()); XynaFactory.getInstance().getProcessing().getXynaProcessCtrlExecution().getXynaExecution() .getExecutionEngineDispatcher().removeDestination(xo.getDestinationKey()); XynaFactory.getInstance().getProcessing().getXynaProcessCtrlExecution().getXynaCleanup() .getCleanupEngineDispatcher().removeDestination(xo.getDestinationKey()); XynaFactory.getInstance().getXynaNetworkWarehouse().removeShutdownWarehouseJobOrder(xo); } else logger.warn("Could not unregister " + getType().toString() + "-job '" + jobRunnable.getParentJob().getDescription() + "' because job information was not found"); } @Override public String[] getScheduleParameters() { return new String[0]; } @Override public boolean needsToRunAgain() { return true; } }; } static WarehouseJobSchedule getScheduleByType(WarehouseJobRunnable runnable, WarehouseJobScheduleType scheduleType, String... parameters) throws XNWH_WarehouseJobScheduleParameterInvalidException { if (scheduleType == WarehouseJobScheduleType.CRONLS) { try { Long interval = parameters[0] == null || parameters[0].equals("null") ? null : Long.valueOf(parameters[0]); try { Long firstStartup = parameters[1] == null || parameters[1].equals("null") ? null : Long.valueOf(parameters[1]); return getCronSchedule(runnable, interval, firstStartup); } catch (NumberFormatException e) { throw new XNWH_WarehouseJobScheduleParameterInvalidException("firstStartup", parameters[1], e); } } catch (NumberFormatException e) { throw new XNWH_WarehouseJobScheduleParameterInvalidException("interval", parameters[0], e); } } else { throw new RuntimeException("Unsupported schedule type: " + scheduleType.toString()); } } private static class WarehouseJobCleanupExecutor implements Executor<DestinationKey> { public void execute(DestinationKey dk) { XynaFactory.getInstance().getProcessing().getXynaProcessCtrlExecution().getXynaCleanup() .getCleanupEngineDispatcher().removeDestination(dk); } public void handleThrowable(Throwable executeFailed) { logger.warn("WarehouseJobCleanup failed there might be left over entries in the CleanupDispatcher", executeFailed); } } }
import 'package:finder_app/constants/app_images.dart'; import 'package:finder_app/screens/company_screens/company_screens.dart'; import 'package:finder_app/screens/guest_screens.dart/guest_screens.dart'; import 'package:flutter/material.dart'; import '../constants/app_colors.dart'; class RegisterScreen extends StatefulWidget { const RegisterScreen({super.key}); @override State<RegisterScreen> createState() => _RegisterScreenState(); } class _RegisterScreenState extends State<RegisterScreen> with TickerProviderStateMixin { TextEditingController userNameController = TextEditingController(); TextEditingController passwordController = TextEditingController(); late final TabController _tabController; @override void initState() { super.initState(); _tabController = TabController(length: 2, vsync: this); } @override void dispose() { userNameController.dispose(); passwordController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { Size size = MediaQuery.sizeOf(context); return Scaffold( appBar: AppBar( toolbarHeight: size.height * .1, backgroundColor: Colors.transparent, title: Padding( padding: const EdgeInsets.only(top: 20), child: Image.asset( AppImages.logo, height: 80, width: 150, ), ), centerTitle: true, elevation: 0, bottom: TabBar( controller: _tabController, labelColor: AppColors.black, unselectedLabelStyle: TextStyle( letterSpacing: 0.50, fontSize: 14, fontWeight: FontWeight.w300, ), indicatorColor: AppColors.green, labelStyle: TextStyle( letterSpacing: 0.50, fontSize: 14, fontWeight: FontWeight.w600, ), tabs: const [ Tab( text: 'Register as Company', ), Tab( text: 'Register as Guest', ), ], ), ), body: Padding( padding: const EdgeInsets.all(8.0), child: TabBarView( controller: _tabController, children: const [RegisterCompanyScreen(), RegisterAsGuestScreen()], ), ), ); } }
import React, { useCallback, useEffect, useState } from "react"; import { useFormik } from "formik"; import { connect, ConnectedProps } from "react-redux"; import { useHistory } from "react-router-dom"; import { FormattedMessage, injectIntl, WrappedComponentProps } from "react-intl"; import { Checkbox, FormControlLabel, FormLabel, Radio, RadioGroup, TextField } from "@material-ui/core"; import * as Yup from "yup"; import { useSnackbar } from "notistack"; import { actions as authActions } from "../../store/ducks/auth.duck"; import ButtonWithLoader from "../../components/ui/Buttons/ButtonWithLoader"; import TermDialog from "./components/TermDialog"; import { IAppState } from "../../store/rootDuck"; import { TRole } from "../../interfaces/users"; import { roles } from "../home/users/utils/profileForm"; const Registration: React.FC<TPropsFromRedux & WrappedComponentProps> = ({ intl, fetch, fetchLoading, fetchError, clearReg, register, regLoading, regSuccess, regError, clearLoginByPhone, loginByPhone, loginByPhoneLoading, loginByPhoneSuccess, loginByPhoneError, clearSendCode, sendCodeConfirm, sendCodeLoading, sendCodeSuccess, sendCodeError, findInSystemError, clearFindInSystem, authData, }) => { const history = useHistory(); const [isAgreementOpen, setOpenUserAgreement] = useState(false); const [phoneRegPhase, setPhoneRegPhase] = useState(0); let validationSchema = {}; if (authData && authData.type === "email") { validationSchema = {}; } if (authData && authData.type === "phone") { if (phoneRegPhase === 0) { validationSchema = {}; } if (phoneRegPhase === 1) { validationSchema = { codeConfirm: Yup.string().required(intl.formatMessage({ id: "AUTH.VALIDATION.REQUIRED_FIELD" })), }; } } const backHandler = useCallback(() => { clearFindInSystem(); history.push("/auth"); }, [clearFindInSystem, history]); const { values, errors, touched, handleChange, handleBlur, handleSubmit } = useFormik({ enableReinitialize: true, initialValues: { codeConfirm: "", role: "ROLE_BUYER", acceptTerms: true, }, onSubmit: values => { if (authData && authData.type === "email") { register({ email: authData.value, roles: [values.role as TRole], login: authData.value, crop_ids: [1], }); } if (authData && authData.type === "phone") { if (phoneRegPhase === 0) { register({ phone: authData.value, roles: [values.role as TRole], crop_ids: [1], }); } if (phoneRegPhase === 1) { loginByPhone({ phone: authData.value, code: values.codeConfirm, }); } } }, validationSchema: Yup.object().shape(validationSchema), }); const { enqueueSnackbar } = useSnackbar(); useEffect(() => { if (regError) { enqueueSnackbar(regError, { variant: "error", }); clearReg(); } if (regSuccess) { if (authData && authData.type === "email") history.push("/auth/email-sent/registration"); if (authData && authData.type === "phone") { enqueueSnackbar(intl.formatMessage({ id: "AUTH.VALIDATION.CODE.CONFIRM" }), { variant: "success", }); setPhoneRegPhase(1); } clearReg(); } }, [clearReg, enqueueSnackbar, history, regError, regSuccess, authData, intl]); useEffect(() => { if (sendCodeSuccess || sendCodeError) { enqueueSnackbar(sendCodeSuccess ? intl.formatMessage({ id: "AUTH.VALIDATION.CODE.CONFIRM" }) : sendCodeError, { variant: sendCodeSuccess ? "success" : "error", }); clearSendCode(); } }, [enqueueSnackbar, sendCodeSuccess, sendCodeError, clearSendCode, intl]); useEffect(() => { if (loginByPhoneSuccess || loginByPhoneError) { enqueueSnackbar(loginByPhoneSuccess ? "Пользователь успешно создан" : "Произошла ошибка!", { variant: loginByPhoneSuccess ? "success" : "error", }); clearLoginByPhone(); } }, [enqueueSnackbar, loginByPhoneSuccess, loginByPhoneError, clearLoginByPhone, history]); useEffect(() => { if (fetchError) { enqueueSnackbar(fetchError, { variant: "error", }); } }, [fetchError, enqueueSnackbar]); useEffect(() => { if (loginByPhoneSuccess) { fetch(); clearLoginByPhone(); } }, [loginByPhoneSuccess, fetch, clearLoginByPhone]); useEffect(() => { if (!findInSystemError) { history.push("/auth"); } return () => { clearFindInSystem(); }; }, []); return ( <> <TermDialog isOpen={isAgreementOpen} handleClose={() => setOpenUserAgreement(false)} /> <div className="kt-login__body"> <div className="kt-login__form"> <div className="kt-login__title"> <h3> <FormattedMessage id="AUTH.REGISTER.TITLE" /> </h3> </div> <form onSubmit={handleSubmit} noValidate autoComplete="off"> {!phoneRegPhase ? ( <> <RadioGroup name="role" value={values.role} onChange={handleChange}> <FormLabel component="legend">{intl.formatMessage({ id: "AUTH.REGISTER.ROLE_TITLE" })}</FormLabel> <FormControlLabel value="ROLE_BUYER" control={<Radio />} label={roles.find(role => role.id === "ROLE_BUYER")?.value} /> <FormControlLabel value="ROLE_VENDOR" control={<Radio />} label={roles.find(role => role.id === "ROLE_VENDOR")?.value} /> <FormControlLabel value="ROLE_TRANSPORTER" control={<Radio />} label={roles.find(role => role.id === "ROLE_TRANSPORTER")?.value} /> </RadioGroup> <div className="form-group mb-0"> <FormControlLabel label={ <> {intl.formatMessage({ id: "AUTH.REGISTER.AGREE_TERM" })}{" "} <div className="kt-link" onClick={() => setOpenUserAgreement(true)}> {intl.formatMessage({ id: "AUTH.GENERAL.LEGAL" })} </div> </> } control={ <Checkbox color="primary" name="acceptTerms" onBlur={handleBlur} onChange={handleChange} checked={values.acceptTerms} /> } /> </div> </> ) : ( <div className="form-group mb-0"> <TextField label={intl.formatMessage({ id: "AUTH.INPUT.CODE" })} margin="normal" className="kt-width-full" name="codeConfirm" onBlur={handleBlur} onChange={handleChange} value={values.codeConfirm} helperText={touched.codeConfirm && errors.codeConfirm} error={Boolean(touched.codeConfirm && errors.codeConfirm)} /> </div> )} <div className="kt-login__actions" style={{ display: "flex", justifyContent: "flex-start", alignItems: "center" }}> <button onClick={backHandler} type="button" className="btn btn-secondary btn-elevate kt-login__btn-secondary" style={{ marginRight: 30 }} > {intl.formatMessage({ id: "AUTH.GENERAL.BACK_BUTTON" })} </button> <ButtonWithLoader disabled={regLoading || !values.acceptTerms || loginByPhoneLoading || fetchLoading} onPress={handleSubmit} loading={regLoading} > {intl.formatMessage({ id: "AUTH.BUTTON.REGISTER" })} </ButtonWithLoader> </div> </form> </div> </div> </> ); }; const connector = connect( (state: IAppState) => ({ fetchLoading: state.auth.loading, fetchError: state.auth.error, regLoading: state.auth.regLoading, regSuccess: state.auth.regSuccess, regError: state.auth.regError, loginByPhoneLoading: state.auth.loginByPhoneLoading, loginByPhoneSuccess: state.auth.loginByPhoneSuccess, loginByPhoneError: state.auth.loginByPhoneError, sendCodeLoading: state.auth.sendCodeConfirmLoading, sendCodeSuccess: state.auth.sendCodeConfirmSuccess, sendCodeError: state.auth.sendCodeConfirmError, findInSystemError: state.auth.findInSystemError, authData: state.auth.authData, }), { fetch: authActions.fetchRequest, register: authActions.regRequest, clearReg: authActions.clearReg, loginByPhone: authActions.loginByPhoneRequest, clearLoginByPhone: authActions.clearLoginByPhone, sendCodeConfirm: authActions.sendCodeRequest, clearSendCode: authActions.clearSendCode, clearFindInSystem: authActions.clearFindInSystem, } ); type TPropsFromRedux = ConnectedProps<typeof connector>; export default connector(injectIntl(Registration));
> OVIRT_HOST_PM (/usr/lib/python2.7/dist-packages/ansible/modules/cloud/ovirt/ovirt_host_pm.py) Module to manage power management of hosts in oVirt/RHV. * This module is maintained by The Ansible Community OPTIONS (= is mandatory): - address Address of the power management interface. [Default: (null)] = auth Dictionary with values needed to create HTTP/HTTPS connection to oVirt: suboptions: ca_file: description: - A PEM file containing the trusted CA certificates. - The certificate presented by the server will be verified using these CA certificates. - If `ca_file' parameter is not set, system wide CA certificate store is used. - Default value is set by `OVIRT_CAFILE' environment variable. type: str headers: description: - Dictionary of HTTP headers to be added to each API call. type: dict hostname: description: - A string containing the hostname of the server, usually something like ``server.example.com'`. - Default value is set by `OVIRT_HOSTNAME' environment variable. - Either `url' or `hostname' is required. type: str insecure: description: - A boolean flag that indicates if the server TLS certificate and host name should be checked. type: bool kerberos: description: - A boolean flag indicating if Kerberos authentication should be used instead of the default basic authentication. type: bool password: description: - The password of the user. - Default value is set by `OVIRT_PASSWORD' environment variable. required: true type: str token: description: - Token to be used instead of login with username/password. - Default value is set by `OVIRT_TOKEN' environment variable. type: str url: description: - A string containing the API URL of the server, usually something like ``https://server.example.com/ovirt-engine/api'`. - Default value is set by `OVIRT_URL' environment variable. - Either `url' or `hostname' is required. type: str username: description: - The name of the user, something like `admin@internal'. - Default value is set by `OVIRT_USERNAME' environment variable. required: true type: str type: dict - encrypt_options If `true' options will be encrypted when send to agent. (Aliases: encrypt)[Default: (null)] type: bool - fetch_nested If `True' the module will fetch additional data from the API. It will fetch IDs of the VMs disks, snapshots, etc. User can configure to fetch other attributes of the nested entities by specifying `nested_attributes'. [Default: (null)] type: bool version_added: 2.3 = name Name of the host to manage. (Aliases: host) - nested_attributes Specifies list of the attributes which should be fetched from the API. This parameter apply only when `fetch_nested' is `true'. [Default: (null)] type: list version_added: 2.3 - options Dictionary of additional fence agent options (including Power Management slot). Additional information about options can be found at https://github.com/ClusterLabs/fence- agents/blob/master/doc/FenceAgentAPI.md. [Default: (null)] - order Integer value specifying, by default it's added at the end. [Default: (null)] version_added: 2.5 - password Password of the user specified in `username' parameter. [Default: (null)] - poll_interval Number of the seconds the module waits until another poll request on entity status is sent. [Default: 3] type: int - port Power management interface port. [Default: (null)] - state Should the host be present/absent. (Choices: present, absent)[Default: present] - timeout The amount of time in seconds the module should wait for the instance to get into desired state. [Default: 180] type: int - type Type of the power management. oVirt/RHV predefined values are `drac5', `ipmilan', `rsa', `bladecenter', `alom', `apc', `apc_snmp', `eps', `wti', `rsb', `cisco_ucs', `drac7', `hpblade', `ilo', `ilo2', `ilo3', `ilo4', `ilo_ssh', but user can have defined custom type. [Default: (null)] - username Username to be used to connect to power management interface. [Default: (null)] - wait `yes' if the module should wait for the entity to get into desired state. [Default: True] type: bool NOTES: * In order to use this module you have to install oVirt Python SDK. To ensure it's installed with correct version you can create the following task: `pip: name=ovirt-engine-sdk-python version=4.3.0' REQUIREMENTS: python >= 2.7, ovirt-engine-sdk-python >= 4.3.0 AUTHOR: Ondra Machacek (@machacekondra) METADATA: status: - preview supported_by: community EXAMPLES: # Examples don't contain auth parameter for simplicity, # look at ovirt_auth module to see how to reuse authentication: # Add fence agent to host 'myhost' - ovirt_host_pm: name: myhost address: 1.2.3.4 options: myoption1: x myoption2: y username: admin password: admin port: 3333 type: ipmilan # Add fence agent to host 'myhost' using 'slot' option - ovirt_host_pm: name: myhost address: 1.2.3.4 options: myoption1: x myoption2: y slot: myslot username: admin password: admin port: 3333 type: ipmilan # Remove ipmilan fence agent with address 1.2.3.4 on host 'myhost' - ovirt_host_pm: state: absent name: myhost address: 1.2.3.4 type: ipmilan RETURN VALUES: id: description: ID of the agent which is managed returned: On success if agent is found. type: str sample: 7de90f31-222c-436c-a1ca-7e655bd5b60c agent: description: "Dictionary of all the agent attributes. Agent attributes can be found on your oVirt/RHV instance at following url: http://ovirt.github.io/ovirt-engine-api-model/master/#types/agent." returned: On success if agent is found. type: dict
create schema AlkeWallet; use AlkeWallet; -- ************************** -- DB SQL `Alke Wallet`. -- Usuarios = User -- ************************** CREATE TABLE User ( user_id INT PRIMARY KEY AUTO_INCREMENT, user_name VARCHAR(45) NOT NULL, user_email VARCHAR(45) NOT NULL, user_password VARCHAR(45) DEFAULT NULL, balance INT NOT NULL, creation_date DATETIME DEFAULT NOW() ); -- ************************** -- DB SQL `Alke Wallet`. -- Moneda - Currency -- ************************** CREATE TABLE Currency ( currency_id INT PRIMARY KEY AUTO_INCREMENT, currency_name VARCHAR(25) NOT NULL, currency_symbol VARCHAR(5) NOT NULL ); -- ************************** -- DB SQL `Alke Wallet`. -- `Transacciones` -- ************************** CREATE TABLE transactions ( transaction_id INT PRIMARY KEY AUTO_INCREMENT, sender_user_id INT NOT NULL, /* Enviar dinero DESDE UNA CUENTA */ receiver_user_id INT NOT NULL, /* recibe dinero DESDE UNA CUENTA NUEVA.*/ currency_id INT NOT NULL, transaction_amount INT NOT NULL, transaction_date DATETIME NOT NULL, transaction_type VARCHAR (30) NOT NULL, FOREIGN KEY (sender_user_id) REFERENCES User(user_id), FOREIGN KEY (receiver_user_id) REFERENCES User(user_id), FOREIGN KEY (currency_id) REFERENCES Currency(currency_id) ); -- ************************** -- Proyecto SQL "Alke Wallet` -- Insert de datos Usuarios -- ************************** INSERT INTO User (user_name, user_email, user_password, balance) VALUES ('Juan Perez', '[email protected]', 'password123', 10000), ('María González', '[email protected]', 'securepass', 20500), ('Pedro Ramirez', '[email protected]', '123456', 5000), ('Ana López', '[email protected]', 'pass1234', 15000), ('Luis Hernandez', '[email protected]', 'abcdef', 20000), ('Laura Martinez', '[email protected]', 'qwerty', 30000), ('Carlos Sanchez', '[email protected]', 'password', 7000), ('Sofia Rodriguez', '[email protected]', 'passpass', 4000), ('Miguel Diaz', '[email protected]', '12345678', 6000), ('Diana Castro', '[email protected]', 'ilovecoding', 8000); select * from User; -- ************************** -- Proyecto SQL "Alke Wallet` -- Insert Monedas -- ************************** INSERT INTO Currency (currency_name, currency_symbol) VALUES ('Peso chileno', 'CLP'), ('Dolar estadounidense', 'USD'), ('Euro', 'EUR'), ('Libra esterlina', 'GBP'), ('Yen japonés', 'JPY'), ('Peso mexicano', 'MXN'); select * from Currency; -- ************************** -- Proyecto SQL "Alke Wallet` -- Insert Transacciones -- ************************** INSERT INTO transactions (sender_user_id, receiver_user_id, currency_id, transaction_amount, transaction_date, transaction_type) VALUES (1, 2, 1, 500, '2024-03-21 09:00:00', 'Compra'), (2, 3, 2, 200, '2024-03-21 09:30:00', 'Venta'), (3, 4, 1, 150, '2024-03-21 10:00:00', 'Transferencia'), (4, 5, 3, 300, '2024-03-21 10:30:00', 'Compra'), (5, 6, 2, 100, '2024-03-21 11:00:00', 'Venta'), (6, 7, 1, 400, '2024-03-21 11:30:00', 'Compra'), (7, 8, 4, 700, '2024-03-21 12:00:00', 'Venta'), (8, 9, 3, 250, '2024-03-21 12:30:00', 'Transferencia'), (9, 10, 2, 150, '2024-03-21 13:00:00', 'Compra'), (10, 1, 1, 200, '2024-03-21 13:30:00', 'Venta'); SELECT * FROM transactions; -- ************************** -- Crear consultas SQL para: -- ************************** -- Consulta para obtener el nombre de la moneda elegida por un usuario específico SELECT c.currency_name FROM transactions t JOIN Currency c ON t.currency_id = c.currency_id WHERE t.sender_user_id = 7 -- Consulta para obtener todas las transacciones registradas SELECT * FROM transactions; -- Consulta para obtener todas las transacciones realizadas por un usuario específico SELECT * FROM transactions WHERE sender_user_id = 3 OR receiver_user_id = 3; -- Consulta para obtener todas las transacciones realizadas a partir de una fecha específica SELECT * FROM transactions WHERE transaction_date >= '2024-03-21 12:30:00'; -- Sentencia DML para modificar el campo correo electrónico de un usuario específico UPDATE usuarios SET user_email = '[email protected]' WHERE user_id = 5; -- Sentencia para eliminar los datos de una transacción (eliminado de la fila completa) DELETE FROM transactions WHERE transaction_id = 3;
#!/usr/bin/env Rscript # Author_and_contribution: Niklas Mueller-Boetticher; created template # Author_and_contribution: Søren Helweg Dam; implemented method suppressPackageStartupMessages({ library(optparse) library(jsonlite) library(SingleCellExperiment) library(Matrix) library(SpatialExperiment) library(Banksy) }) option_list <- list( make_option( c("-c", "--coordinates"), type = "character", default = NULL, help = "Path to coordinates (as tsv)." ), make_option( c("-m", "--matrix"), type = "character", default = NA, help = "Path to (transformed) counts (as mtx)." ), make_option( c("-f", "--features"), type = "character", default = NULL, help = "Path to features (as tsv)." ), make_option( c("-o", "--observations"), type = "character", default = NULL, help = "Path to observations (as tsv)." ), make_option( c("-n", "--neighbors"), type = "character", default = NA, help = "Path to neighbor definitions. Square matrix (not necessarily symmetric) where each row contains the neighbors of this observation (as mtx)." ), make_option( c("-d", "--out_dir"), type = "character", default = NULL, help = "Output directory." ), make_option( c("--dim_red"), type = "character", default = NA, help = "Reduced dimensionality representation (e.g. PCA)." ), make_option( c("--image"), type = "character", default = NA, help = "Path to H&E staining." ), make_option( c("--n_clusters"), type = "integer", default = NULL, help = "Number of clusters to return." ), make_option( c("--technology"), type = "character", default = NULL, help = "The technology of the dataset (Visium, ST, imaging-based)." ), make_option( c("--seed"), type = "integer", default = NULL, help = "Seed to use for random operations." ), make_option( c("--config"), type = "character", default = NA, help = "Optional config file (json) used to pass additional parameters." ) ) description <- "BANKSY cluster cells in a feature space" opt_parser <- OptionParser( usage = description, option_list = option_list ) opt <- parse_args(opt_parser) out_dir <- opt$out_dir # Output files label_file <- file.path(out_dir, "domains.tsv") embedding_file <- file.path(out_dir, "embedding.tsv") # if additional output files are required write it also to out_dir # Use these filepaths as input ... coord_file <- opt$coordinates feature_file <- opt$features observation_file <- opt$observations if (!is.na(opt$neighbors)) { neighbors_file <- opt$neighbors } if (!is.na(opt$matrix)) { matrix_file <- opt$matrix } if (!is.na(opt$dim_red)) { dimred_file <- opt$dim_red } if (!is.na(opt$image)) { image_file <- opt$image } if (!is.na(opt$config)) { config_file <- opt$config config <- fromJSON(config_file) } technology <- opt$technology n_clusters <- opt$n_clusters # You can get SpatialExperiment directly get_SpatialExperiment <- function( feature_file, observation_file, coord_file, matrix_file = NA, reducedDim_file = NA, assay_name = "counts", reducedDim_name = "reducedDim") { rowData <- read.delim(feature_file, stringsAsFactors = FALSE, row.names = 1) colData <- read.delim(observation_file, stringsAsFactors = FALSE, row.names = 1) coordinates <- read.delim(coord_file, sep = "\t", row.names = 1) coordinates <- as.matrix(coordinates[rownames(colData), ]) coordinates[,c(1:2)] <- as.numeric(coordinates[,c(1:2)]) spe <- SpatialExperiment::SpatialExperiment( rowData = rowData, colData = colData, spatialCoords = coordinates ) if (!is.na(matrix_file)) { assay(spe, assay_name, withDimnames = FALSE) <- as(Matrix::t(Matrix::readMM(matrix_file)), "CsparseMatrix") #assay(spe, "logcounts", withDimnames = FALSE) <- as(Matrix::t(Matrix::readMM(matrix_file)), "CsparseMatrix") } # Filter features and samples if ("selected" %in% colnames(rowData(spe))) { spe <- spe[as.logical(rowData(spe)$selected), ] } if ("selected" %in% colnames(colData(spe))) { spe <- spe[, as.logical(colData(spe)$selected)] } if (!is.na(reducedDim_file)) { dimRed <- read.delim(reducedDim_file, stringsAsFactors = FALSE, row.names = 1) reducedDim(spe, reducedDim_name) <- as.matrix(dimRed[colnames(spe), ]) } return(spe) } # Load configuration lambda <- config$lambda k_geom <- config$k_geom npcs <- config$npcs method <- config$method use_agf <- config$use_agf assay_name <- "normcounts" # Seed seed <- opt$seed # You can use the data as SpatialExperiment spe <- get_SpatialExperiment(feature_file = feature_file, observation_file = observation_file, coord_file = coord_file, matrix_file = matrix_file) # Extract proper coordinates if (technology %in% c("ST", "Visium")){ coord_names <- c("row", "col") } else { coord_names <- NULL } ## Your code goes here set.seed(seed) if (!("selected" %in% colnames(rowData(spe)))) { library(Seurat) counts <- assay(spe, "counts") scale.factor <- median(colSums(counts)) seu <- CreateSeuratObject(counts = counts) seu <- NormalizeData(seu, normalization.method = 'RC', scale.factor = scale.factor, verbose = FALSE) seu <- FindVariableFeatures(seu, nfeatures = 2000, verbose = FALSE) spe <- spe[VariableFeatures(seu), ] } # Normalization to mean library size spe <- scuttle::computeLibraryFactors(spe) assay(spe, assay_name) <- scuttle::normalizeCounts(spe, log = FALSE) # Run BANKSY spe <- Banksy::computeBanksy(spe, assay_name = assay_name, k_geom = k_geom, compute_agf = use_agf, coord_names = coord_names) spe <- Banksy::runBanksyPCA(spe, lambda = lambda, npcs = npcs, use_agf = use_agf) # Resolution optimization binary_search <- function( spe, do_clustering, n_clust_target, resolution_boundaries, num_rs = 100, tolerance = 1e-3, ...) { # Initialize boundaries lb <- rb <- NULL n_clust <- -1 lb <- resolution_boundaries[1] rb <- resolution_boundaries[2] i <- 0 while ((rb - lb > tolerance || lb == rb) && i < num_rs) { mid <- sqrt(lb * rb) message("Resolution: ", mid) result <- do_clustering(spe, resolution = mid, ...) # Adjust cluster_ids extraction per method cluster_ids <- colData(result)[, clusterNames(result)] n_clust <- length(unique(cluster_ids)) if (n_clust == n_clust_target || lb == rb) break if (n_clust > n_clust_target) { rb <- mid } else { lb <- mid } i <- i + 1 } # Warning if target not met if (n_clust != n_clust_target) { warning(sprintf("Warning: n_clust = %d not found in binary search, return best approximation with res = %f and n_clust = %d. (rb = %f, lb = %f, i = %d)", n_clust_target, mid, n_clust, rb, lb, i)) } return(result) } # The data.frames with observations may contain a column "selected" which you need to use to # subset and also use to subset coordinates, neighbors, (transformed) count matrix #cnames <- colnames(colData(spe)) bank <- binary_search(spe, n_clust_target = n_clusters, resolution_boundaries = c(0.1, 2), do_clustering = Banksy::clusterBanksy, # Banksy specific lambda = lambda, use_pcs = TRUE, npcs = npcs, seed = seed, method = method, assay_name = assay_name, use_agf = use_agf) label_df <- data.frame("label" = colData(bank)[, clusterNames(bank)], row.names=rownames(colData(bank))) # data.frame with row.names (cell-id/barcode) and 1 column (label) if (use_agf) embedding_df <- as.data.frame(t(assay(bank, "H1"))) # optional, data.frame with row.names (cell-id/barcode) and n columns ## Write output dir.create(out_dir, showWarnings = FALSE, recursive = TRUE) colnames(label_df) <- c("label") write.table(label_df, file = label_file, sep = "\t", col.names = NA, quote = FALSE) if (exists("embedding_df")) { write.table(embedding_df, file = embedding_file, sep = "\t", col.names = NA, quote = FALSE) }
# %% from GroundingDINO.groundingdino.util.inference import load_model, load_image, predict, annotate import cv2 from matplotlib import pyplot as plt import os import shutil import torch import yaml import numpy as np from tqdm import tqdm # check if cuda is available device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # %% # load model model = load_model("GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py", "GroundingDINO/weights/groundingdino_swint_ogc.pth") # model to gpu model.to(device) IMAGE_PATH = "simple_images/safety glasses/safety glasses_47.jpg" TEXT_PROMPT = 'a person with a hard hat and safety glasses' BOX_TRESHOLD = 0.5 TEXT_TRESHOLD = 0.25 # load image image_source, image = load_image(IMAGE_PATH) # move image to gpu image.to(device) boxes, logits, phrases = predict( model=model, image=image, caption=TEXT_PROMPT, box_threshold=BOX_TRESHOLD, text_threshold=TEXT_TRESHOLD ) annotated_frame = annotate(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases) # show the image using opencv and matplotlib plt.imshow(cv2.cvtColor(annotated_frame, cv2.COLOR_BGR2RGB)) plt.show() # %% # parameters CLEAN_FOLDER = True PLOT_IMAGES = False BREAK_AFTER = 0 # if > 0, break after this many images BOX_TRESHOLD = 0.5 TEXT_TRESHOLD = 0.25 TEXT_PROMPT = 'a person with a hard hat and safety glasses' classes = ['hard hat', 'safety glasses', 'person'] input_folder = 'simple_images' output_folder = '/media/datasets/safety' image_folder = os.path.join(output_folder, 'images') annotation_folder = os.path.join(output_folder, 'labels') # if clean folder is true, delete the output folder if CLEAN_FOLDER and os.path.exists(output_folder): shutil.rmtree(output_folder) # if output folder does not exist, create it if not os.path.exists(output_folder): os.makedirs(output_folder) os.makedirs(image_folder) os.makedirs(annotation_folder) # TODO create yaml file # # create the dictionary to be converted to YAML # data = { # 'path': output_folder, # 'train': 'images', # 'val': 'images', # 'nc': len(classes), # 'names': '[' # } # # convert the dictionary to YAML # yaml_data = yaml.dump(data) # # write the YAML data to a file # with open(output_folder + '.yaml', 'w') as f: # f.write(yaml_data) # get all directories in input folder directories = os.listdir(input_folder) # iterate over all directories for directory in directories: print('Processing directory:', directory) print('-'*10) # get all images in the input folder images = os.listdir(os.path.join(input_folder, directory)) if BREAK_AFTER and len(images) > BREAK_AFTER: images = images[:BREAK_AFTER] # for each image in the input folder for idx, file in enumerate(tqdm(images)): # create the full input path and read the file input_path = os.path.join(input_folder, directory, file) image_source, image = load_image(input_path) # move image to gpu image.to(device) # for each class for class_name in classes: with torch.no_grad(): # predict the bounding boxes, logits and phrases boxes, logits, phrases = predict( model=model, image=image, caption=TEXT_PROMPT, box_threshold=BOX_TRESHOLD, text_threshold=TEXT_TRESHOLD ) # modify phrases with classes names for c in classes: for idx, p in enumerate(phrases): if c in p: phrases[idx] = c # if the model finds any bounding boxes if len(boxes) > 0: if PLOT_IMAGES: # create annotations show the image using opencv and matplotlib annotated_frame = annotate(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases) plt.imshow(cv2.cvtColor(annotated_frame, cv2.COLOR_BGR2RGB)) plt.show() # write the image to the image folder image_path = os.path.join(image_folder, file) cv2.imwrite(image_path, cv2.cvtColor(image_source, cv2.COLOR_BGR2RGB)) # create the annotation file annotation_file = file.replace('.jpg', '.txt') annotation_path = os.path.join(annotation_folder, annotation_file) # open the annotation file with open(annotation_path, 'w') as f: # convert out phrases to indices out_phrases = [classes.index(s) for s in phrases] # for each bounding box for box, logits, phrase in zip(boxes, logits, out_phrases): # write the bounding box to the file f.write(f"{phrase} {box[0]} {box[1]} {box[2]} {box[3]}\n")
import Big from "big.js"; import { trimUnderNegativeExponent, trimTrailingZeros, } from "core/utils/numberFormatter"; import React, { useCallback, useEffect, useMemo, useState } from "react"; interface InputProps { negativeExponent: number; max: string; min?: string; placeholder?: string; } const useInput = ({ negativeExponent, max: _max, min: _min = "0", placeholder = "0", }: InputProps) => { const [rawInput, setRawInput] = useState(""); const [input, setInput] = useState(""); const [errorMessage, setErrorMessage] = useState(""); const max = useMemo( () => trimTrailingZeros(trimUnderNegativeExponent(_max, negativeExponent)), [_max, negativeExponent], ); const min = useMemo( () => trimTrailingZeros(trimUnderNegativeExponent(_min, negativeExponent)), [_min, negativeExponent], ); const half = useMemo( () => trimTrailingZeros( Big(_max).div(2).toFixed(negativeExponent, Big.roundDown), ), [_max, negativeExponent], ); const isMax = useMemo(() => { return Big(max).eq(input || placeholder); }, [max, input, placeholder]); const isMin = useMemo(() => { return Big(min).eq(input || placeholder); }, [min, input, placeholder]); const isHalf = useMemo(() => { return Big(half).eq(input || placeholder); }, [half, input, placeholder]); const isOverMax = useMemo(() => { return Big(input || placeholder).gt(max); }, [input, max, placeholder]); const toggleMax = useCallback(() => { if (isMax) { setInput(rawInput); } else { setInput(max); } }, [isMax, max, rawInput]); const toggleMin = useCallback(() => { if (isMin) { setInput(rawInput); } else { setInput(min); } }, [isMin, min, rawInput]); const toggleHalf = useCallback(() => { if (isHalf) { setInput(rawInput); } else { setInput(half); } }, [isHalf, half, rawInput]); useEffect(() => { setInput(rawInput); }, [rawInput]); useEffect(() => { if (Big(input || placeholder).gt(max)) { setErrorMessage("Insufficient Balance"); } if (Big(input || placeholder).lt(min)) { setErrorMessage(`Input can't be less than ${min}`); } }, [input, max, min, placeholder]); const _setInput = useCallback( (value: string) => { const precisionParsedValue = trimUnderNegativeExponent( value, negativeExponent, ); setRawInput(precisionParsedValue); /** * should be set synchronously * otherwise, cursor jumps * ref: https://stackoverflow.com/questions/28922275/in-reactjs-why-does-setstate-behave-differently-when-called-synchronously/28922465#28922465 */ setInput(precisionParsedValue); }, [negativeExponent], ); const resetInput = useCallback(() => { setInput(""); setRawInput(""); }, []); const handleChange: React.ChangeEventHandler<HTMLInputElement> = useCallback( (e) => { _setInput(e.target.value); }, [_setInput], ); const handleBlur: React.FocusEventHandler<HTMLInputElement> = () => { if (rawInput === "") { // to preserve empty string return; } setRawInput((rawInput) => trimTrailingZeros(Big(rawInput).toFixed(negativeExponent, Big.roundDown)), ); }; return { input, setInput: _setInput, resetInput, errorMessage, isMax, isMin, isHalf, isOverMax, toggleMax, toggleMin, toggleHalf, handleChange, handleBlur, placeholder, }; }; export default useInput;
import React from 'react'; import { QueryClientProvider } from '@tanstack/react-query'; import queryClient from '../lib/react-query'; import { BrowserRouter as Router } from 'react-router-dom'; import { ThemeProvider, createTheme } from '@mui/material/styles'; import { StyledEngineProvider } from '@mui/material/styles'; import { FilterProvider } from '../context/SeasonContext'; import Spinner from "../assets/f1-car.gif" const theme = createTheme({ palette: { type: 'light', primary: { main: '#E10700', }, secondary: { main: '#FFFFFF', }, }, }); function AppProvider({ children }) { return ( <React.Suspense fallback={ <div className="flex items-center justify-center w-screen h-screen"> <img src={Spinner} alt="Loading"/> </div> } > <ThemeProvider theme={theme}> <QueryClientProvider client={queryClient}> <StyledEngineProvider injectFirst> <FilterProvider> <Router>{children}</Router> </FilterProvider> </StyledEngineProvider> </QueryClientProvider> </ThemeProvider> </React.Suspense> ); } export default AppProvider;
import javax.swing.*; public class ConversorMoedas { public static void main(String[] args) { exibirMenu(); } public static void exibirMenu() { boolean opcaoValida = false; String[] opcoes = {"Conversão de Moedas", "Conversão de Temperatura", "Sair"}; String escolha = (String) JOptionPane.showInputDialog(null, "Escolha uma opção:", "Conversor de Moedas", JOptionPane.PLAIN_MESSAGE, null, opcoes, opcoes[0]); if (escolha != null) { switch (escolha) { case "Conversão de Moedas": realizarConversaoDeMoedas(); break; case "Conversão de Temperatura": converterTemperatura(); break; case "Sair": JOptionPane.showMessageDialog(null, "Obrigado por usar o Conversor de Moedas!", "Conversor de Moedas", JOptionPane.INFORMATION_MESSAGE); System.exit(0); break; default: JOptionPane.showMessageDialog(null, "Opção inválida.", "Erro", JOptionPane.ERROR_MESSAGE); exibirMenu(); } } } public static void realizarConversaoDeMoedas() { String[] moedas = {"Real (BRL)", "Dólar (USD)", "Euro (EUR)"}; String moedaEscolhida = (String) JOptionPane.showInputDialog(null, "Escolha a moeda de conversão:", "Conversor de Moedas - Escolha a Moeda", JOptionPane.PLAIN_MESSAGE, null, moedas, moedas[0]); if (moedaEscolhida != null) { double valor = obterValorValidado(); String[] moedasDestino = new String[moedas.length - 1]; int index = 0; for (String moeda : moedas) { if (!moeda.equals(moedaEscolhida)) { moedasDestino[index] = moeda; index++; } } String moedaDestinoEscolhida = (String) JOptionPane.showInputDialog(null, "Escolha a moeda de destino:", "Conversor de Moedas - Escolha a Moeda de Destino", JOptionPane.PLAIN_MESSAGE, null, moedasDestino, moedasDestino[0]); if (moedaDestinoEscolhida != null) { double valorConvertido = realizarConversao(valor, moedaEscolhida, moedaDestinoEscolhida); mostrarResultado(valor, moedaEscolhida, valorConvertido, moedaDestinoEscolhida); int opcao = JOptionPane.showConfirmDialog(null, "Deseja fazer outra conversão?", "Continuar?", JOptionPane.YES_NO_CANCEL_OPTION); if (opcao == JOptionPane.YES_OPTION) { exibirMenu(); } else if (opcao == JOptionPane.NO_OPTION) { JOptionPane.showMessageDialog(null, "Programa finalizado.", "Fim do programa", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } else if (opcao == JOptionPane.CANCEL_OPTION) { JOptionPane.showMessageDialog(null, "Programa concluído.", "Fim do programa", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } } } } public static double obterValorValidado() { double valor = 0.0; boolean entradaValida = false; while (!entradaValida) { String valorStr = JOptionPane.showInputDialog(null, "Digite o valor a ser convertido", "Conversor de Moedas - Digite o Valor", JOptionPane.PLAIN_MESSAGE); if (validarEntradaNumerica(valorStr)) { valor = Double.parseDouble(valorStr); entradaValida = true; } else { JOptionPane.showMessageDialog(null, "Valor inválido. Digite um valor válido.", "Erro", JOptionPane.ERROR_MESSAGE); } } return valor; } public static boolean validarEntradaNumerica(String valorStr) { try { Double.parseDouble(valorStr); return true; } catch (NumberFormatException e) { return false; } } public static double realizarConversao(double valor, String moedaOrigem, String moedaDestino) { double taxaConversao = 0.0; if (moedaOrigem.equals("Real (BRL)") && moedaDestino.equals("Dólar (USD)")) { taxaConversao = 0.2; } else if (moedaOrigem.equals("Dólar (USD)") && moedaDestino.equals("Real (BRL)")) { taxaConversao = 5.0; } else if (moedaOrigem.equals("Real (BRL)") && moedaDestino.equals("Euro (EUR)")) { taxaConversao = 0.18; } else if (moedaOrigem.equals("Euro (EUR)") && moedaDestino.equals("Real (BRL)")) { taxaConversao = 5.5; } return valor * taxaConversao; } public static void mostrarResultado(double valorOrigem, String moedaOrigem, double valorDestino, String moedaDestino) { String mensagem = String.format("%.2f %s é equivalente a %.2f %s.", valorOrigem, moedaOrigem, valorDestino, moedaDestino); JOptionPane.showMessageDialog(null, mensagem, "Resultado da Conversão", JOptionPane.INFORMATION_MESSAGE); } public static void converterTemperatura() { JOptionPane.showMessageDialog(null, "Função de conversão em manutenção", "Aviso", JOptionPane.WARNING_MESSAGE); } }
const prisma = require("../../../utils/db"); const bcrypt = require("bcrypt"); const { JWT_SECRET_ACCESS_TOKEN, JWT_ACCESS_TOKEN_EXPIRED } = process.env; const jwt = require("jsonwebtoken"); const { validateLogin } = require("../../../validations/user.validation"); const login = async (req, res) => { try { const { email, password } = req.body; //validate data const { error } = validateLogin(req.body); if (error) { return res.status(400).json({ status: "error", message: error.message, }); } const user = await prisma.user.findUnique({ where: { email, }, }); if (!user) { return res.status(400).json({ status: "error", message: "email not found", }); } const isValidPassword = await bcrypt.compare(password, user.password); if (!isValidPassword) { return res.status(400).json({ status: "error", message: "password is invalid", }); } const token = jwt.sign({ id: user.id, email: user.email, name: user.name, role:user.role }, JWT_SECRET_ACCESS_TOKEN, { expiresIn: JWT_ACCESS_TOKEN_EXPIRED, }); res.status(200).json({ status: "Login success", data: { userId: user.id, name: user.name, email: user.email, token: token, }, }); } catch (error) { res.status(500).json({ status: "error", message: error.message, }); } }; module.exports = login;
\ \ I2C driver for stm32g0 series \ \ Ralph Sahli, 2019 \ \ resources used: \ - I2C1 \ - PA9 or PB6 -> SCL \ - PA10 or PB7 -> SDA \ or \ - I2C2 \ - PA11 or PB10 -> SCL \ - PA12 or PB11 ->SDA \ can be changed at run time, must be called before i2c-init PA11 variable SCL PA12 variable SDA \$40005400 constant I2C \ I2C1 $40005800 constant I2C \ I2C2 I2C $00 + constant I2C.CR1 \ control register 1 I2C $04 + constant I2C.CR2 \ control register 2 I2C $10 + constant I2C.TIMINGR \ Timing register I2C $18 + constant I2C.ISR \ Interrupt and status register I2C $1C + constant I2C.ICR \ Interrupt clear register I2C $24 + constant I2C.RXDR \ Receive data register I2C $28 + constant I2C.TXDR \ Transmit data register : .i2cTimingErr ( -- ) cr ." timing not supported for " mHZ@ . ." MHz" quit ; : i2c?Length ( Len:Addr -- Len:Addr) dup 16 rshift 255 > if cr ." length > 255 not supported" quit then ; \ timing: SM ( standard mode ) 100 KHz -> get value from tool : i2c-SM ( -- ) mHZ@ case 16 of $00503D5A endof 64 of $60302730 endof .i2cTimingErr endcase I2C.TIMINGR ! ; \ timing: FM ( fast mode ) 400 KHz -> get value from tool : i2c-FM ( -- ) mHZ@ case 16 of $00300619 endof 64 of $00C0216C endof .i2cTimingErr endcase I2C.TIMINGR ! ; : i2c-init ( -- ) \ initialise I2C hardware, We need to connect external pullup R to SCL and SDA MODE-AF OD + PU + 6 AF# + SCL @ io-mode! \ Alternate function mode: AF6 MODE-AF OD + PU + 6 AF# + SDA @ io-mode! \ Alternate function mode: AF6 SCL @ PA9 = if \ remap IO 0 bit RCC.APB2ENR bis! \ enable SYSCFG clock 3 bit 4 bit + SYSCFG bis! \ remap PA11 + PA12 then I2C $40005400 = if 21 else 22 then \ enable I2C1 or I2C2 bit RCC.APB1ENR bis! \ set I2CEN 0 bit I2C.CR1 bic! \ PE, disable device i2c-SM ; \ standard mode : i2c-Start ( -- f ) 0 bit I2C.CR1 bis! \ I2C enable 13 bit I2C.CR2 bis! \ set START bit begin pause 13 bit I2C.CR2 bit@ not \ start bit cleared ? 4 bit I2C.ISR bit@ or \ or NACK ? until 4 bit I2C.ISR bit@ \ flag -> NACK 4 bit I2C.ICR bis! ; \ clear NACK : i2c-Stop ( -- ) begin pause 6 bit I2C.ISR bit@ \ tranfer complete ? until 14 bit I2C.CR2 bis! \ set STOP bit begin pause 5 bit I2C.ISR bit@ \ STOP bit? until 5 bit I2C.ICR bis! \ clear STOP 0 bit I2C.CR1 bic! ; \ I2C disable \ start and send device-address for read : i2c-rx ( addr -- f ) i2c?Length I2C.CR2 ! \ length + address 10 bit I2C.CR2 bis! \ Master requests a read transfer i2c-Start ; \ start and send device-address for write : i2c-tx ( addr -- f ) i2c?Length I2C.CR2 ! \ length + address i2c-Start ; \ read 1 byte : i2c@ ( -- c ) begin pause 2 bit I2C.ISR bit@ \ wait for RxNE until I2C.RXDR @ ; \ write 1 byte : i2c! ( c -- ) begin pause 1 bit I2C.ISR bit@ \ wait for Txe until I2C.TXDR ! ; \ write 1 byte and stop : >i2cData ( c -- ) i2c! i2c-Stop ; \ write n bytes from cAddr and stop : >>i2cData ( cAddr n -- ) 0 do dup c@ i2c! 1+ \ send n bytes from addr loop drop i2c-Stop ; \ read 1 byte and stop : i2cData> ( -- c ) i2c@ i2c-Stop ; \ read n bytes to cAddr and stop : i2cData>> ( cAddr n -- ) 0 do i2c@ over c! 1+ loop drop i2c-Stop ; \ scan and report all I2C devices on the bus : i2cScan. ( -- ) i2c-init 128 0 do cr i 2#h. ." :" 16 0 do space i j + 2* dup i2c-tx if drop ." --" else i2c-Stop 2#h. then 2 delay-ms loop 16 +loop ; : i2c. ( -- ) I2C $30 dump ;
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using proyectef; using proyectef.Models; var builder = WebApplication.CreateBuilder(args); builder.Services.AddSqlServer<TareasContext>(builder.Configuration.GetConnectionString("cnTareas")); // Las lineas comentadas anteriormente se ponen en el archivo de appsettings.json var app = builder.Build(); app.MapGet("/", () => "Hello World!"); app.MapGet("/dbConexion", ([FromServices] TareasContext dbContext) => { dbContext.Database.EnsureCreated(); return Task.FromResult(Results.Ok("Base de datos en memoria " + dbContext.Database.IsInMemory())); }); app.MapGet("/api/tareas", ([FromServices] TareasContext dbContext) => { return Task.FromResult(Results.Ok(dbContext.Tareas)); }); app.MapGet("/api/tareas-with-filtro", ([FromServices] TareasContext dbContext) => { return Task.FromResult(Results.Ok(dbContext.Tareas.Include(p => p.Categoria).Where(p => p.PrioridadTarea == proyectef.Models.Prioridad.Baja))); }); app.MapPost("/api/crearTareas", async ([FromServices] TareasContext dbContext, [FromBody] Tarea tarea ) => { // Se Inicializan los datos de la tarea a guardar: tarea.TareaId = Guid.NewGuid(); tarea.FechaCreacion = DateTime.Now; await dbContext.AddAsync(tarea); // await dbContext.Tareas.AddAsync(tarea); await dbContext.SaveChangesAsync(); return Results.Ok("La tarea se registro con exito."); }); app.MapPut("/api/update-tareas/{id}", async ([FromServices] TareasContext dbContext, [FromBody] Tarea tarea, [FromRoute] Guid id) => { // Se consulta el id tarea por medio de la URL: var tareaActual = dbContext.Tareas.Find(id); if(tareaActual != null) { tareaActual.Titulo = tarea.Titulo; tareaActual.PrioridadTarea = tarea.PrioridadTarea; tareaActual.Descripcion = tarea.Descripcion; await dbContext.SaveChangesAsync(); return Results.Ok("La tarea se actualizo con exito."); } else { return Results.NotFound($"No se encontró ninguna tarea con el id {id}"); } }); app.MapDelete("/api/delete-tareas/{id}", async ([FromServices] TareasContext dbContext, [FromRoute] Guid id) => { var tareaActual = dbContext.Tareas.Find(id); if(tareaActual != null) { dbContext.Remove(tareaActual); await dbContext.SaveChangesAsync(); return Results.Ok("La tarea se eliminó con exito."); } else { return Results.NotFound($"No se encontró ninguna tarea con el id {id}"); } }); app.Run();
import {useEffect, useState} from "react"; import axios from "axios"; import {HotelInfoResponse} from "../../types/HotelResponse"; export const useFetch = (url: string) => { const [data, setData] = useState<string[] | HotelInfoResponse[]>(['']); const [loading, setLoading] = useState<boolean>(false); const [error, setError] = useState<boolean | Error>(false); useEffect(() => { const fetchData = async () => { setLoading(true); try { const res = await axios.get(url); setData(res.data); } catch (err: Error | any) { setError(err); } setLoading(false); } (async () => { await fetchData(); })(); }, []); const reFetch = async () => { setLoading(true); try { const res = await axios.get(url); setData(res.data); } catch (err: Error | any) { setError(err); } setLoading(false); } return {data, loading, error, reFetch}; };
using System; using System.Globalization; using System.Threading; namespace PizzaCalories { public class Program { public static void Main(string[] args) { Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB"); var pizzaName = Console.ReadLine().Split()[1]; var doughData = Console.ReadLine().Split(); var flourType = doughData[1]; var bakingTechnique = doughData[2]; var weight = int.Parse(doughData[3]); try { var dough = new Dough(flourType, bakingTechnique, weight); var pizza = new Pizza(pizzaName, dough); var line = Console.ReadLine(); while (line != "END") { line = Console.ReadLine(); var parts = line.Split(); var toppingName = parts[1]; var toppingWeight = int.Parse(parts[2]); var topping = new Topping(toppingName, toppingWeight); pizza.AddTopping(topping); } Console.WriteLine($"{pizza.Name} - {pizza.GetCalories():f2} Calories."); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
import ErrorResponse from '../utils/errorResponse.mjs' import asyncHandler from '../middleware/async.mjs' import geocoder from '../utils/geocoder.mjs' import Bootcamp from '../models/Bootcamp.mjs' // @desc Get all bootcamps // @route GET /api/v1/bootcamps // @access Public export const getBootcamps = asyncHandler(async (req, res, next) => { const bootcamps = await Bootcamp.find() res .status(200) .json({ success: true, count: bootcamps.length, data: bootcamps }) }) // @desc Get single bootcamp // @route GET /api/v1/bootcamps/:id // @access Public export const getBootcamp = asyncHandler(async (req, res, next) => { const bootcamp = await Bootcamp.findById(req.params.id) if (!bootcamp) return next( new ErrorResponse(`Bootcamp not found with id of ${req.params.id}`, 404) ) res.status(200).json({ success: true, data: bootcamp }) }) // @desc Create a bootcamp // @route POST /api/v1/bootcamps/:id // @access Private export const createBootcamp = asyncHandler(async (req, res, next) => { const bootcamp = await Bootcamp.create(req.body) res.status(201).json({ success: true, data: bootcamp }) }) // @desc Update a bootcamp // @route PUT /api/v1/bootcamps/:id // @access Private export const updateBootcamp = asyncHandler(async (req, res, next) => { const bootcamp = await Bootcamp.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true, }) if (!bootcamp) return next( new ErrorResponse(`Bootcamp not found with id of ${req.params.id}`, 404) ) res.status(200).json({ success: true, data: bootcamp }) }) // @desc Delete a bootcamp // @route DELETE /api/v1/bootcamps/:id // @access Private export const deleteBootcamp = asyncHandler(async (req, res, next) => { const bootcamp = await Bootcamp.findByIdAndDelete(req.params.id) if (!bootcamp) return next( new ErrorResponse(`Bootcamp not found with id of ${req.params.id}`, 404) ) res.status(200).json({ success: true }) }) // @desc Get bootcamps within a radius // @route GET /api/v1/bootcamps/radius/:zipcode/:distance/:unit // @access Private export const getBootcampsInRadius = asyncHandler(async (req, res, next) => { const { zipcode, distance, unit } = req.params if (unit !== 'km' && unit !== 'mile') { return next(new ErrorResponse('Please specify unit as km or mile', 400)) } // Get lat/lng from geocoder const loc = await geocoder.geocode(zipcode) const lat = loc[0].latitude const lng = loc[0].longitude // Calc radius using radians // Divide dist by radius of Earth // Earth Radius = 6378 Km / 3963 Miles const radius = unit === 'km' ? distance / 6378 : distance / 3963 const bootcamps = await Bootcamp.find({ location: { $geoWithin: { $centerSphere: [[lng, lat], radius] } }, }) res.status(200).json({ success: true, count: bootcamps.length, data: bootcamps, }) })
<?php namespace App\Http\Controllers; use App\Models\User; use Illuminate\Support\Str; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Validator; class AuthController extends Controller { public function __construct() { // semua method butuh login dulu kecuali method untuk login dan register $this->middleware('auth:api', ['except' => ['login','register']]); } public function register() { $validator = Validator::make(request()->all(),[ 'name'=>'required', 'email'=>'required|email|unique:users', 'password'=>'required' ]); if ($validator->fails()) { return response()->json($validator->messages()); } $user = User::create([ 'name'=>request('name'), 'email'=>request('email'), 'password'=>Hash::make(request('password')), 'role'=>1, ]); if ($user) { return response()->json(['message' => 'berhasil menambahkan user']); }else{ return response()->json(['message' => 'gagal menambahkan user']); } } /** * Get a JWT via given credentials. * * @return \Illuminate\Http\JsonResponse */ public function login() { $credentials = request(['email', 'password']); if (! $token = auth()->attempt($credentials)) { return response()->json(['error' => 'Unauthorized'], 401); } return $this->respondWithToken($token); } /** * Get the authenticated User. * * @return \Illuminate\Http\JsonResponse */ public function me() { return response()->json(auth()->user()); } /** * Log the user out (Invalidate the token). * * @return \Illuminate\Http\JsonResponse */ public function logout() { auth()->logout(); return response()->json(['message' => 'Successfully logged out']); } /** * Refresh a token. * * @return \Illuminate\Http\JsonResponse */ public function refresh() { return $this->respondWithToken(auth()->refresh()); } /** * Get the token array structure. * * @param string $token * * @return \Illuminate\Http\JsonResponse */ protected function respondWithToken($token) { return response()->json([ 'access_token' => $token, 'token_type' => 'bearer', 'expires_in' => auth()->factory()->getTTL() * 60 ]); } }
use crate::index::dict::default::DefaultDict; use crate::index::dict::IndexDictionaryEditor; use crate::Result; use bytestore::backend::growable::GrowableBackend; use bytestore::backend::Backend; use bytestore::components::map::hashing; use bytestore::traits::deser::Deser; use std::cmp::Ordering; /// Edits SimpleDicts and allows insertion of new terms. pub struct DictEditor<'a, B, T> { dict: &'a mut DefaultDict<B, T>, } impl<'a, B, T> DictEditor<'a, B, T> { #[inline] pub(crate) fn new(dict: &'a mut DefaultDict<B, T>) -> Self { Self { dict } } } impl<'a, B, T> DictEditor<'a, B, T> where B: Backend, T: Deser + Ord + hashing::Hash, { /// Improves lookup time for items returning a higher ordering than other items. #[inline] pub fn optimize<C>(&mut self, mut cmp: C) -> Result<()> where C: FnMut(&T, &T) -> Ordering, { self.dict .map .rehash_with_relevance(|a, b| cmp(a.key(), b.key()))?; Ok(()) } /// Improves lookup time for terms with higher frequency. #[inline] pub fn optimize_with_termfreqs<F>(&mut self, mut tf: F) where F: FnMut(&T) -> usize, { self.optimize(|a, b| tf(a).cmp(&tf(b))).unwrap(); } } impl<'a, B, T> IndexDictionaryEditor<T> for DictEditor<'a, B, T> where B: GrowableBackend, T: Deser + Ord + Clone + hashing::Hash, { #[inline] fn announce_new_terms(&mut self, terms: usize, term_size: usize) -> Result<()> { let map = &mut self.dict.map; map.grow_to(map.len() + terms)?; map.reserve_storage(terms, term_size * terms)?; Ok(()) } #[inline] fn insert_or_get_single(&mut self, term: &T) -> Result<u32> { if let Some(k) = self.dict.map.get(term) { return Ok(k); } let id = self.dict.map.len(); Ok(self.dict.map.insert(term, &(id as u32))?) } }
package com.example.tfg.mapOptions.otrosLugares.penaFrancia; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.core.text.HtmlCompat; import androidx.fragment.app.DialogFragment; import android.annotation.SuppressLint; import android.app.Dialog; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.tfg.GestorDB; import com.example.tfg.R; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; public class lacasabajaFragment extends DialogFragment { private StorageReference storageRef; @SuppressLint({"InflateParams", "SetTextI18n"}) @NonNull @Override public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { super.onCreateDialog(savedInstanceState); AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity()); // Get the layout inflater LayoutInflater inflater = requireActivity().getLayoutInflater(); final View infoView = inflater.inflate(R.layout.fragment_lacasabaja, null); // Inflate and set the layout for the dialog // Pass null as the parent view because its going in the dialog layout builder.setView(infoView); assert getArguments() != null; String idioma = getArguments().getString("idioma"); Button back = infoView.findViewById(R.id.buttonVolverCasa); TextView info = infoView.findViewById(R.id.casainfotext1); TextView info2 = infoView.findViewById(R.id.casainfotext2); TextView info3 = infoView.findViewById(R.id.casainfotext3); TextView info4 = infoView.findViewById(R.id.casainfotext4); TextView info5 = infoView.findViewById(R.id.casainfotext5); TextView info6 = infoView.findViewById(R.id.casainfotext6); TextView info7 = infoView.findViewById(R.id.casainfotext7); ImageView img1 = infoView.findViewById(R.id.casaimg1); ImageView img2 = infoView.findViewById(R.id.casaimg2); ImageView img3 = infoView.findViewById(R.id.casaimg3); ImageView img4 = infoView.findViewById(R.id.casaimg4); String[] datos; try (GestorDB dbHelper = GestorDB.getInstance(getContext())) { datos = dbHelper.obtenerInfoLugares(idioma, "lacasabaja", "peñadefrancia", 7); } info.setText(datos[0] + HtmlCompat.fromHtml("<br>", HtmlCompat.FROM_HTML_MODE_LEGACY)); info2.setText(datos[1] + HtmlCompat.fromHtml("<br>", HtmlCompat.FROM_HTML_MODE_LEGACY)); info3.setText(datos[2] + HtmlCompat.fromHtml("<br>", HtmlCompat.FROM_HTML_MODE_LEGACY)); info4.setText(datos[3] + HtmlCompat.fromHtml("<br>", HtmlCompat.FROM_HTML_MODE_LEGACY)); info5.setText(datos[4] + HtmlCompat.fromHtml("<br>", HtmlCompat.FROM_HTML_MODE_LEGACY)); info6.setText(datos[5] + HtmlCompat.fromHtml("<br>", HtmlCompat.FROM_HTML_MODE_LEGACY)); info7.setText(datos[6] + HtmlCompat.fromHtml("<br>", HtmlCompat.FROM_HTML_MODE_LEGACY)); storageRef = FirebaseStorage.getInstance().getReference(); obtenerImagenFirebase("mapas/otros/penafrancia/casabaja1.png", img1); obtenerImagenFirebase("mapas/otros/penafrancia/casabaja2.png", img2); obtenerImagenFirebase("mapas/otros/penafrancia/casabaja3.png", img3); obtenerImagenFirebase("mapas/otros/penafrancia/casabaja4.png", img4); back.setOnClickListener(view -> dismiss()); return builder.create(); } /** Método utilizado para obtener la imagen de Firebase Storage */ private void obtenerImagenFirebase(String path, ImageView img){ StorageReference pathReference = storageRef.child(path); pathReference.getDownloadUrl().addOnSuccessListener(uri -> Glide.with(requireContext()).load(uri).into(img)); } }
import simplifile import gleam/io import gleam/int import gleam/string import gleam/map import gleam/result import gleam/list const filename = "inputs/day3" const digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] const non_special = [".", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] type NumberInGrid { NumberInGrid(number: Int, coords: List(#(Int, Int))) } pub fn solve() { let assert Ok(contents) = simplifile.read(filename) io.debug(part1(contents)) io.debug(part2(contents)) } pub fn part1(input: String) { let chars_with_coords = to_coords_chars(input) let numbers = parse_numbers(chars_with_coords) let special_chars = chars_with_coords |> list.filter(fn(x) { !list.contains(non_special, x.1) }) |> map.from_list() numbers |> list.filter(fn(x) { adjacent_to_chars(x.coords, special_chars) }) |> list.map(fn(x) { x.number }) |> int.sum() } pub fn part2(input: String) { let chars_with_coords = to_coords_chars(input) let numbers = parse_numbers(chars_with_coords) let gears = chars_with_coords |> list.filter(fn(x) { x.1 == "*" }) |> list.map(fn(x) { x.0 }) gears |> list.map(fn(gear_coords) { adjacent_numbers(gear_coords, numbers) }) |> list.filter(fn(adj_numbers) { list.length(adj_numbers) == 2 }) |> list.map(fn(adj_numbers) { adj_numbers |> list.map(fn(n) { n.number }) |> int.product() }) |> int.sum() } fn to_coords_chars(input: String) -> List(#(#(Int, Int), String)) { input |> string.split(on: "\n") |> list.index_map(fn(idx, row) { #(idx, row) }) |> list.flat_map(fn(idx_row) { let assert #(row_idx, row) = idx_row row |> string.to_graphemes() |> list.index_map(fn(col_idx, grapheme) { #(#(row_idx, col_idx), grapheme) }) }) } fn parse_numbers(chars_coords: List(#(#(Int, Int), String))) { let start_numbers: List(NumberInGrid) = [] let current_number_type: List(#(Int, Int)) = [] let coords_map = map.from_list(chars_coords) let contiguous_numbers = chars_coords |> list.filter(fn(coord_val) { list.contains(digits, coord_val.1) }) |> list.fold( #(#(0, -1), current_number_type, start_numbers), fn(acc, coord_val) { let assert #(coord, _) = coord_val let assert #(prev_coord, current_number, total_acc) = acc case contiguous_coord(prev_coord, coord) { True -> // Number continues #(coord, list.append(current_number, [coord]), total_acc) False -> // New Number #( coord, [coord], list.prepend(total_acc, build_number(current_number, coords_map)), ) } }, ) // Need to also parse the final number let #(_, current, final) = contiguous_numbers list.prepend(final, build_number(current, coords_map)) } fn build_number(coords, coords_map) { let number = coords |> list.map(fn(coord) { let assert Ok(digit) = map.get(coords_map, coord) digit }) |> string.join("") |> int.parse() |> result.unwrap(0) NumberInGrid(number: number, coords: coords) } fn contiguous_coord(coord1: #(Int, Int), coord2: #(Int, Int)) { coord1.0 == coord2.0 && coord1.1 == { coord2.1 - 1 } } fn adjacent_to_chars(coords, chars_map) { coords |> list.flat_map(adjacent_coords) |> list.any(fn(c) { map.has_key(chars_map, c) }) } fn adjacent_coords(coord) { let assert #(x, y) = coord [ #(x - 1, y - 1), #(x - 1, y), #(x - 1, y + 1), #(x, y - 1), #(x, y + 1), #(x + 1, y - 1), #(x + 1, y), #(x + 1, y + 1), ] } fn adjacent_numbers(gear_coords, numbers: List(NumberInGrid)) { let adjacent_gear_coords = adjacent_coords(gear_coords) numbers |> list.filter(fn(number) { list.any( number.coords, fn(coord) { list.contains(adjacent_gear_coords, coord) }, ) }) }
--- # Only the main Sass file needs front matter (the dashes are enough) --- @charset "utf-8"; // Our variables $base-font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif; $base-font-size: 16px; $base-font-weight: 300; $small-font-size: $base-font-size * 0.875; $base-line-height: 1.5; $spacing-unit: 30px; $text-color: #2e2e2c; $background-color:#fdfdfd; $brand-color: #2a7ae2; $brand-color-light: lighten($brand-color, 25%); $brand-color-dark: darken($brand-color, 25%); $js-color: #f3df49; $grey-color: #2e2e2c; $grey-color-light: lighten($grey-color, 75%); $grey-color-dark: darken($grey-color, 25%); // Width of the content area $content-width: 900px; $on-palm: 600px; $on-laptop: 800px; $breakpoints: ( small: 480px, medium: 768px, large: 1024px, xlarge: 1200px ); $h1-font-sizes: ( null: 3em, small: 4em, medium: 5em, large: 6em, xlarge: 7em ); $h2-font-sizes: ( null: 1em, small: 1.09em, medium: 1.75em, large: 2em, xlarge: 2em ); $h3-font-sizes: ( null: 2em, small: 3em, medium: 4em, large: 6em, xlarge: 6em ); @mixin font-size($fs-map, $fs-breakpoints: $breakpoints) { @each $fs-breakpoint, $fs-font-size in $fs-map { @if $fs-breakpoint == null { font-size: $fs-font-size; } @else { @if map-has-key($fs-breakpoints, $fs-breakpoint) { $fs-breakpoint: map-get($fs-breakpoints, $fs-breakpoint); } @media screen and (min-width: $fs-breakpoint) { font-size: $fs-font-size; } } } } // Use media queries like this: // @include media-query($on-palm) { // .wrapper { // padding-right: $spacing-unit / 2; // padding-left: $spacing-unit / 2; // } // } @mixin media-query($device) { @media screen and (max-width: $device) { @content; } } // Import partials from `sass_dir` (defaults to `_sass`) @import "base", "layout", "syntax-highlighting" ;
<!-- s-extra <section class="s-extra"> <div class="row top"> <div class="col-eight md-six tab-full popular"> <h3><?php _e('Popular Posts','philosophy'); ?></h3> <div class="block-1-2 block-m-full popular__posts"> <?php $philosophy_popular_post = new wp_query(array( 'posts_per_page' => 6, 'ignore_sticky_posts' => 1, 'orderby' => 'comment_count' )); while($philosophy_popular_post->have_posts()): $philosophy_popular_post->the_post(); ?> <article class="col-block popular__post"> <a href="<?php the_permalink(); ?>" class="popular__thumb"> <?php the_post_thumbnail(); ?> </a> <h5><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h5> <section class="popular__meta"> <span class="popular__author"><span><?php _e('By','philosophy'); ?></span> <a href="<?php echo esc_url(get_author_posts_url(get_the_author_meta("ID"))); ?>"> <?php the_author(); ?></a></span> <span class="popular__date"><span><?php _e('on','philosophy'); ?></span> <time datetime="2017-12-19"><?php echo get_the_time(); ?></time></span> </section> </article> <?php endwhile; wp_reset_query(); ?> </div> <!-- end popular_posts --> </div> <!-- end popular --> <div class="col-four md-six tab-full about"> <?php if(is_active_sidebar('before_footer')){ dynamic_sidebar('before_footer'); } ?> <ul class="about__social"> <li> <a href="#0"><i class="fa fa-facebook" aria-hidden="true"></i></a> </li> <li> <a href="#0"><i class="fa fa-twitter" aria-hidden="true"></i></a> </li> <li> <a href="#0"><i class="fa fa-instagram" aria-hidden="true"></i></a> </li> <li> <a href="#0"><i class="fa fa-pinterest" aria-hidden="true"></i></a> </li> </ul> <!-- end header__social --> </div> <!-- end about --> </div> <!-- end row --> <div class="row bottom tags-wrap"> <div class="col-full tags"> <h3><?php _e('Tags','philosophy'); ?></h3> <div class="tagcloud"> <?php the_tags('','',''); ?> </div> <!-- end tagcloud --> </div> <!-- end tags --> </div> <!-- end tags-wrap --> </section> <!-- end s-extra --> <!-- s-footer <footer class="s-footer"> <div class="s-footer__main"> <div class="row"> <div class="col-two md-four mob-full s-footer__sitelinks"> <h4><?php _e('Quick Links','philosophy'); ?></h4> <?php wp_nav_menu(array( 'theme_location' => 'footer_left', 'menu_class' => 's-footer__linklist', 'menu_id' => 'footer_left' )); ?> </div> <!-- end s-footer__sitelinks --> <div class="col-two md-four mob-full s-footer__archives"> <h4>Archives</h4> <?php wp_nav_menu(array( 'theme_location' => 'footer_middle', 'menu_class' => 's-footer__linklist', 'menu_id' => 'footer_middle' )); ?> </div> <!-- end s-footer__archives --> <div class="col-two md-four mob-full s-footer__social"> <h4>Social</h4> <?php wp_nav_menu(array( 'theme_location' => 'footer_right', 'menu_class' => 's-footer__linklist', 'menu_id' => 'footer_right' )); ?> </div> <!-- end s-footer__social --> <div class="col-five md-full end s-footer__subscribe"> <?php if(is_active_sidebar('footer_new')){ dynamic_sidebar('footer_new'); } ?> <div class="subscribe-form"> <form id="mc-form" class="group" novalidate="true"> <input type="email" value="" name="EMAIL" class="email" id="mc-email" placeholder="Email Address" required=""> <input type="submit" name="subscribe" value="Send"> <label for="mc-email" class="subscribe-message"></label> </form> </div> </div> <!-- end s-footer__subscribe --> </div> </div> <!-- end s-footer__main --> <div class="s-footer__bottom"> <div class="row"> <div class="col-full"> <div class="s-footer__copyright"> <?php if(is_active_sidebar('copyright')){ dynamic_sidebar('copyright'); } ?> </div> <div class="go-top"> <a class="smoothscroll" title="Back to Top" href="#top"></a> </div> </div> </div> </div> <!-- end s-footer__bottom --> </footer> <!-- end s-footer --> <!-- preloader <div id="preloader"> <div id="loader"> <div class="line-scale"> <div></div> <div></div> <div></div> <div></div> <div></div> </div> </div> </div> </body> <?php wp_footer(); ?> </html>
import WindowsImg from '../../img/Windows.png' import BrowerImg from '../../img/Browser.png' import { Link } from 'react-router-dom' const Top4GamesCard = (props) => { return ( <article> <div> <img className="top4pic" src={props.thumbnail} alt={"Thumbnail of " + (props.title)} /> </div> <div className="top4div"> <div> <h3>{props.title}</h3> {/* <p className="">{props.short_description}</p> */} <Link className='readMore' to={`/details/${props.id}`}>Read More</Link> </div> <div className="top4bottom"> {(() => { if (props.platform === "PC (Windows)") { return ( <div className='windows animated-box in'> <img src={WindowsImg} alt="windowsImg" /> </div> ) } else if (props.platform === "Web Browser") { return ( <div className='browser animated-box in'> <img src={BrowerImg} alt="browserImg" /> </div> ) } })()} <div className='animated-box in'> <p> {props.genre} </p> </div> </div> </div> <div className='testKey'>{props.counter}</div> </article> ) } export default Top4GamesCard
<!doctype html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <title>tuanpaph26902</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"/> <link rel="stylesheet" th:href="@{/style.css}"> </head> <body> <header class="container"> <div class="row"> <div class="col-2"> <a href="/kinh-mat"> <img src="https://kinhmatanna.com/wp-content/uploads/2022/06/logo-anna.svg" alt="logo"/></a> </div> <div class="col-8 header_menu"> <ul class="nav justify-content-center"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/kinh-mat">Trang chủ</a> </li> <li class="nav-item "> <a class="nav-link " href="/san-pham">Sản phẩm</a> </li> <li class="nav-item"> <a class="nav-link" href="/user/history">Lịch sử hóa đơn</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Giới thiệu</a> </li> </ul> </div> <div class="col-2 header_icon"> <ul class="nav justify-content-center"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#"> <i class="fa-solid fa-magnifying-glass"></i> </a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> <i class="fa-solid fa-user"></i> </a> <ul class="dropdown-menu"> <li> <a class="dropdown-item" href="/login"> Login </a> </li> <li> <form class="" th:action="@{/logout}" method="post" style="border: none" > <button type="submit" class="dropdown-item">logout</button> </form> </li> </ul> </li> <li class="nav-item"> <a class="nav-link" href="/gio-hang" > <div class="cart-icon"> <i class="fas fa-shopping-cart"></i> <span class="cart-count" th:text="${count}"></span> </div> </a> </li> </ul> </div> </div> </header><!-- add cart --> <section class="line text-center"> <span class="text-white title">tuanpaph26902</span> </section> <section class="banner"> <img src="https://kinhmatanna.com/wp-content/uploads/2023/02/Untitled-3-01-1-2048x665.png" alt="banner"/> </section> <section class="banner_3 container"> <div class="row"> <div class="col-6"> <img src="https://kinhmatanna.com/wp-content/uploads/2023/04/261kb-1024x643.jpg" alt=""/> </div> <div class="col-3"> <img th:src="@{/images/Untitled-4-01-01-03-768x983.jpg}" alt=""/> </div> <div class="col-3"> <img th:src="@{images/Untitled-4-01-01-06-768x983.jpg}" alt=""/> </div> </div> </section> <div style="background-color: #f5f5f5"> <h1 th:text="${user}"></h1> <div class="container-fluid"> <div class="row mt-5 p-5 gx-5"> <div class="col-3"> <form action="/san-pham/filter" th:object="${filter}" method="get"> <div class="list-group w-75"> <select class="form-select" aria-label="Default select example" th:field="*{categoryId}"> <option value="">Danh mục</option> <option th:each="x : ${listCate}" th:value="${x.id}" th:text="${x.name}"></option> </select> </div> <div class="list-group w-75"> <select class="form-select" aria-label="Default select example" th:field="*{material}"> <option value="">Chất liệu</option> <option th:each="x : ${listMaterial}" th:value="${x.id}" th:text="${x.name}"></option> </select> </div> <div class="list-group w-75"> <select class="form-select" aria-label="Default select example" th:field="*{colorId}"> <option value="">Màu sắc</option> <option th:each="x : ${listColor}" th:value="${x.id}" th:text="${x.name}"></option> </select> </div> <div class="list-group w-75"> <select class="form-select" aria-label="Default select example" th:field="*{manufacturerId}"> <option value="">Nhà sản xuất</option> <option th:each="x : ${listManu}" th:value="${x.id}" th:text="${x.name}"></option> </select> </div> <div class="list-group w-75"> <select class="form-select" aria-label="Default select example" th:field="*{brandId}"> <option value="" selected>THương hiệu</option> <option th:each="x : ${listBrand}" th:value="${x.id}" th:text="${x.name}"></option> </select> </div> <div class="mt-5"> <button type="submit" class="btn btn-success">filter</button> </div> </form> </div> <div class="col-9"> <h3>Sản phẩm</h3> <div class="row row-cols-1 row-cols-md-4 g-4"> <div class="col" th:each="x : ${listProduct.content}"> <div class="card h-100"> <a th:href="@{/san-pham/chi-tiet-san-pham/{id}(id=${x.id})}"> <img th:src="${ x.image }" class="card-img-top" th:alt="${ x.name }"></a> <div class="card-body"> <h5 class="card-title"> <a class="text-decoration-none" th:href="@{/user/buy-product/{id}(id=${x.id})}" th:text="${ x.name }"></a> </h5> <p class="card-text text-danger" th:text="${format.formatPrice(x.price)}"></p> </div> </div> </div> </div> <%-- Pagination --%> <br> <div class="row mt-5"> <ul class="pagination justify-content-center" th:if="${isFilter != true}"> <li th:each="page : ${#numbers.sequence(0, listProduct.totalPages-1)}" class="page-item"> <a class="page-link" th:href="@{/san-pham(page=${page})}" th:text="${page + 1}"></a> </li> </ul> <ul class="pagination justify-content-center" th:if="${isFilter}"> <li th:each="page : ${#numbers.sequence(0, listProduct.totalPages-1)}" class="page-item"> <a class="page-link" th:href="@{/san-pham/filter(page=${page}, cateId=${cate}, material=${mar}, colorId=${color}, manufacturerId=${manu}, brandId=${brand})}" th:classappend="(listProduct.number == page) ? 'active' : ''" th:text="${page + 1}"></a> </li> </ul> </div> </div> </div> </div> </div> <section class="banner_qc container"> <h1 class="banner_qc_title">Tìm kính phù hợp</h1> <div class="row"> <div class="col-6"> <img class="qc-img" th:src="@{images/banner-4.jpg}" alt=""/> </div> <div class="col-6 d-flex justify-content-center flex-wrap"> <div class="qc-logo"> <img th:src="@{/images/g2.svg}" alt=""/> </div> <h1 class="qc-title" style="flex-basis: 100%">Kính thước khung</h1> <p class="qc-text text-center">Lựa chọn Kích thước khung phù hợp nhất để giúp dễ dàng vừa vặn, thoải mái và tiện lợi cho bạn.</p> </div> </div> <!-- --> <div class="row"> <div class="col-6 d-flex justify-content-center flex-wrap"> <div class="qc-logo"> <img th:src="@{images/g2.svg}" alt=""/> </div> <h1 class="qc-title" style="flex-basis: 100%">Kính thước khung</h1> <p class="qc-text text-center">Lựa chọn Kích thước khung phù hợp nhất để giúp dễ dàng vừa vặn, thoải mái và tiện lợi cho bạn.</p> </div> <div class="col-6"> <img class="qc-img" th:src="@{images/baner-5.jpg}" alt=""/> </div> </div> </section> <footer class="text-center text-lg-start bg-light text-muted"> <!-- Section: Social media --> <section class="d-flex justify-content-center justify-content-lg-between p-4 border-bottom"> <!-- Left --> <div class="me-5 d-none d-lg-block"> <span>Get connected with us on social networks:</span> </div> <!-- Left --> <!-- Right --> <div> <a href="" class="me-4 text-reset"> <i class="fab fa-facebook-f"></i> </a> <a href="" class="me-4 text-reset"> <i class="fab fa-twitter"></i> </a> <a href="" class="me-4 text-reset"> <i class="fab fa-google"></i> </a> <a href="" class="me-4 text-reset"> <i class="fab fa-instagram"></i> </a> <a href="" class="me-4 text-reset"> <i class="fab fa-linkedin"></i> </a> <a href="" class="me-4 text-reset"> <i class="fab fa-github"></i> </a> </div> <!-- Right --> </section> <!-- Section: Social media --> <!-- Section: Links --> <section class=""> <div class="container text-center text-md-start mt-5"> <!-- Grid row --> <div class="row mt-3"> <!-- Grid column --> <div class="col-md-3 col-lg-4 col-xl-3 mx-auto mb-4"> <!-- Content --> <h6 class="text-uppercase fw-bold mb-4"> <img src="https://kinhmatanna.com/wp-content/uploads/2022/06/logo-anna.svg" alt="logo"/> Company name </h6> <p>Here you can use rows and columns to organize your footer content. Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> </div> <!-- Grid column --> <!-- Grid column --> <div class="col-md-2 col-lg-2 col-xl-2 mx-auto mb-4"> <!-- Links --> <h6 class="text-uppercase fw-bold mb-4">Products</h6> <p> <a href="#!" class="text-reset">Angular</a> </p> <p> <a href="#!" class="text-reset">React</a> </p> <p> <a href="#!" class="text-reset">Vue</a> </p> <p> <a href="#!" class="text-reset">Laravel</a> </p> </div> <!-- Grid column --> <!-- Grid column --> <div class="col-md-3 col-lg-2 col-xl-2 mx-auto mb-4"> <!-- Links --> <h6 class="text-uppercase fw-bold mb-4">Useful links</h6> <p> <a href="#!" class="text-reset">Pricing</a> </p> <p> <a href="#!" class="text-reset">Settings</a> </p> <p> <a href="#!" class="text-reset">Orders</a> </p> <p> <a href="#!" class="text-reset">Help</a> </p> </div> <!-- Grid column --> <!-- Grid column --> <div class="col-md-4 col-lg-3 col-xl-3 mx-auto mb-md-0 mb-4"> <!-- Links --> <h6 class="text-uppercase fw-bold mb-4">Contact</h6> <p><i class="fas fa-home me-3"></i> New York, NY 10012, US</p> <p> <i class="fas fa-envelope me-3"></i> [email protected] </p> <p><i class="fas fa-phone me-3"></i> + 01 234 567 88</p> <p><i class="fas fa-print me-3"></i> + 01 234 567 89</p> </div> <!-- Grid column --> </div> <!-- Grid row --> </div> </section> <!-- Section: Links --> <!-- Copyright --> <div class="text-center p-4" style="background-category: rgba(0, 0, 0, 0.05)"> © 2021 Copyright: <a class="text-reset fw-bold" href="https://mdbootstrap.com/">MDBootstrap.com</a> </div> <!-- Copyright --> </footer><!-- Footer --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous" ></script> </body> </html>
import { faCommentAlt, faPaperPlane, faTimes, faUserFriends } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import ItemChat from './ItemChat' import databasedb from '../../../sever/firebase'; import { useAuth } from "../../../contexts/AuthContext"; import { ref, onValue, orderByChild, push, set, onChildChanged, onChildAdded, child, onDisconnect, remove } from '@firebase/database'; import { useEffect, useState } from "react"; import '../StyleCallPage/Messenger.scss'; const Messenger = () => { const roomID = window.location.pathname.replaceAll('/', ''); const { currentUser } = useAuth(); const id_user = currentUser.email.replaceAll('.', '_').replaceAll('@', '_'); const db = ref(databasedb, 'users/' + id_user + '/username'); let username = null; onValue(db, (snap) => { username = snap.val(); }); const [inputValue, setInputValue] = useState(""); const onChangeHandler = event => { setInputValue(event.target.value); }; const dbRef = ref(databasedb, `${roomID}/message`); const checkSize = ref(databasedb, `${roomID}/participants`); const [chatHistory, setChatHistory] = useState([]); const sent = () => { if (inputValue !== "") { const newPost = push(dbRef); let today = new Date(); let time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds(); set(newPost, { username, time: time, message: inputValue }); } setInputValue(""); } const listItems = chatHistory.map((number) => <ItemChat key={number.key} username={number.username} message={number.message} time={number.time} /> ) useEffect(() => { try { onValue(checkSize, (snapshot) => { let i = 0; snapshot.forEach((childSnapshot) => { i ++; }); if (i == 1) { const onDisconnectRef = onDisconnect(dbRef); onDisconnectRef.remove(); } }, { onlyOnce: false }) onValue(dbRef, (snapshot) => { let childData = []; snapshot.forEach((childSnapshot) => { childData.push(childSnapshot.val()); }); setChatHistory(childData); }, { onlyOnce: false }) } catch (e) { } }, []); return ( <div className="messenger-container"> <div className="messenger-header"> </div> <div className="messenger-header-tabs"> {/* <div className="tab"> <FontAwesomeIcon className="icon" icon={faUserFriends} /> <p>Thành viên (10)</p> </div> */} <div className="tab active"> <FontAwesomeIcon className="icon" icon={faCommentAlt} /> <p>Tin nhắn</p> </div> </div> {/* item */} <div className="chat-section"> {listItems} </div> <div className="send-msg-section"> <input type="text" placeholder="Send a message to everyone" onChange={onChangeHandler} value={inputValue} /> <FontAwesomeIcon className="icon" icon={faPaperPlane} onClick={sent} /> </div> </div> ) } export default Messenger;
import { Database } from "bun:sqlite"; import { AdddresType, type Transaction, type Web3Transaction } from "./types"; import * as XLSX from "xlsx"; import { mkdirSync, existsSync } from "fs"; import * as path from "path"; import { LogLevel, logger } from "./logger"; const dbPath = Bun.env.DB_FILE; const tag = "utils"; export function dbCreateTables(chainId: bigint) { const txSchema = `CREATE TABLE IF NOT EXISTS txs_${chainId.toString()} ( id INTEGER PRIMARY KEY, blockNumber TEXT, blockHash TEXT, addrFrom TEXT, addrTo TEXT, value TEXT, transactionIndex TEXT, hash TEXT UNIQUE );`; const blockSchema = `CREATE TABLE IF NOT EXISTS block ( id INTEGER PRIMARY KEY, chainId INTEGER UNIQUE, blockNumber INTEGER );`; // keeps target and alias addresses // type: 0 for target, 1 for alias const addrSchema = `CREATE TABLE IF NOT EXISTS addresses ( id INTEGER PRIMARY KEY, type INTEGER, -- 0 for target, 1 for alias name TEXT, address TEXT UNIQUE );`; const db = new Database(dbPath); // create tx schema if not exist db.run(txSchema); // create block history if not exist db.run(blockSchema); // create addresses table if not exist db.run(addrSchema); db.close(); // console.log("create db tables"); logger(LogLevel.Debug, tag, "creat db tables"); } export function dbInsertTxs(chainId: bigint, txs: Transaction[]) { const db = new Database(dbPath); // insert txs into db for (const tx of txs) { logger(LogLevel.Debug, tag, `db add tx: ${tx.hash}`); db.query( `INSERT OR IGNORE INTO txs_${chainId.toString()} (blockNumber, blockHash, addrFrom, addrTo, value, transactionIndex, hash) VALUES (?, ?, ?, ?, ?, ?, ?);`, ).run( tx.blockNumber ? tx.blockNumber.toString() : "", tx.blockHash ? tx.blockHash : "", tx.from, tx.to ? tx.to : "", tx.value.toString(), tx.transactionIndex ? tx.transactionIndex.toString() : "0", tx.hash, ); } db.close(); } export function dbInsertAddr(addr: string, name: string, type: AdddresType) { const db = new Database(dbPath); const inst = `INSERT INTO addresses (type, name, address) VALUES (${type}, '${name}', '${addr}') ON CONFLICT DO UPDATE SET name='${name}', type=${type};`; // console.log(inst); db.prepare(inst).run(); logger( LogLevel.Debug, tag, `insert name: ${name}, type: ${type === AdddresType.Alias ? "alias" : "target"}, add: ${addr}`, ); db.close(); } export function dbGetAddr() { const db = new Database(dbPath); // update the latest block in db const addrList = db.query(`SELECT * from addresses;`).all(); db.close(); return addrList; } export function dbSetLatestBlockNum(chainId: bigint, Num: bigint) { const db = new Database(dbPath); // update the latest block in db const query = `INSERT INTO block (chainid, blockNumber) VALUES (${chainId.toString()}, ${Num.toString()}) ON CONFLICT (chainid) DO UPDATE SET blockNumber=${Num.toString()};`; // insert tx to db db.prepare(query).run(); logger(LogLevel.Debug, tag, `db update latest block: ${Num}`); db.close(); } export function dbGetLatestBlockNum(chainId: bigint) { const db = new Database(dbPath); // update the latest block in db const num = db.query(`SELECT blockNumber from block WHERE chainId = ${chainId};`).values(); db.close(); return num; } export const parsingTx = (wTx: Web3Transaction) => { return { blockHash: wTx.blockHash, blockNumber: wTx.blockNumber, hash: wTx.hash, from: wTx.from, to: wTx.to, transactionIndex: wTx.transactionIndex, value: wTx.value, } as Transaction; }; export function parsingTransactions(web3Txs: Web3Transaction[]) { const txs: Transaction[] = []; for (const tx of web3Txs) { txs.push(parsingTx(tx)); } return txs; } export function tx2file(filePath: string) { const db = new Database(dbPath, { readonly: true }); const qchainIds = db.query(`SELECT chainID from block;`); let ids = qchainIds.values(); // console.log(ids); let rowCount = 0; // create a new book const workbook = XLSX.utils.book_new(); // write table data to sheets for (const id of ids) { // console.log("parsing id " + id); const query = db.query(`SELECT * from txs_${id};`); let rows = query.all(); rowCount += rows.length; const worksheet = XLSX.utils.json_to_sheet(rows); XLSX.utils.book_append_sheet(workbook, worksheet, `txs_${id}`); } // add address to workbook const addrList = db.query("SELECT * from addresses;").all(); const addrWorkseet = XLSX.utils.json_to_sheet(addrList); XLSX.utils.book_append_sheet(workbook, addrWorkseet, `addresses`); // make sure dir is existing const dir = path.dirname(filePath); if (!existsSync(dir)) { mkdirSync(dir, { recursive: true }); } // Write to an Excel file XLSX.writeFile(workbook, filePath); db.close(); return rowCount; }
#include <Arduino.h> #include <esp_dmx.h> #include "LEDHandler.h" int transmitPin = 17; int receivePin = 16; int enablePin = 21; dmx_port_t dmxPort = 1; byte data[DMX_PACKET_SIZE]; bool dmxIsConnected = false; unsigned long lastUpdate = millis(); LEDHandler<WS2811, 23> leds(34); // LEDHandler<WS2812B, 23> leds(100); void setup() { Serial.begin(9600); // led setup leds.setAll(CRGB(255, 0, 0)); leds.show(); sleep(2); // dmx setup dmx_config_t config = DMX_CONFIG_DEFAULT; dmx_personality_t personalities[] = {{3, "RGB"}}; int personality_count = 1; dmx_driver_install(dmxPort, &config, personalities, personality_count); dmx_set_pin(dmxPort, transmitPin, receivePin, enablePin); } void loop() { dmx_packet_t packet; if (dmx_receive(dmxPort, &packet, DMX_TIMEOUT_TICK)) { unsigned long now = millis(); if (!packet.err) { /* If this is the first DMX data we've received, lets log it! */ if (!dmxIsConnected) { Serial.println("DMX is connected!"); dmxIsConnected = true; } dmx_read(dmxPort, data, packet.size); for (int i = 0; i < leds.getNumLeds(); i++) { unsigned int index = i * 3; leds[i].r = data[index + 1]; leds[i].g = data[index + 2]; leds[i].b = data[index + 3]; } leds.show(); // ledHandler.setAll(data + 1, packet.size); // ledHandler.show(); // if (now - lastUpdate > 10000) // { // /* Print the received start code - it's usually 0. */ // for (int i = 0; i < packet.size; i++) // { // if (i % 16 == 0) // Serial.println(); // Serial.printf("0x%02X ", data[i]); // } // lastUpdate = now; // } } else { Serial.println("A DMX error occurred."); } } else if (dmxIsConnected) { /* If DMX times out after having been connected, it likely means that the DMX cable was unplugged. When that happens in this example sketch, we'll uninstall the DMX driver. */ Serial.println("DMX was disconnected."); dmx_driver_delete(dmxPort); /* Stop the program. */ while (true) yield(); } }
/* categoriesXProductsSlice categoriesXProductsSlice categoriesXProductsSlice */ import { CategoryXProduct } from "@/src/types/types"; import { createAsyncThunk, createSlice } from "@reduxjs/toolkit"; import type { PayloadAction } from "@reduxjs/toolkit"; import { RootState } from ".."; import { config } from "@/src/config/config"; import { adminAction } from "./adminSlice"; export interface CategoriesXProductsState { items: CategoryXProduct[]; isLoading: boolean; error: Error | null; } const initialState: CategoriesXProductsState = { items: [], isLoading: false, error: null, }; export const fetchCategoriesXProducts = createAsyncThunk( "categoriesXProducts/fetchCategoriesXProducts", async (arg: void, thunkAPI) => { const dispatch = thunkAPI.dispatch; dispatch(adminAction.setLoading(true)); const response = await fetch(`${config.apiAdminUrl}/categoriesXProducts`); if (!response.ok) { return alert("something worng"); } const responseData = (await response.json()) as CategoryXProduct[]; dispatch(categoriesXProductsAction.setCategoriesXProducts(responseData)); dispatch(adminAction.setLoading(false)); } ); export const categoriesXProductsSlice = createSlice({ name: "categoriesXProducts", initialState, reducers: { setCategoriesXProducts: ( state, action: PayloadAction<CategoryXProduct[]> ) => { state.items = action.payload; }, addCategoryXProduct: (state, action: PayloadAction<CategoryXProduct>) => { state.items = [...state.items, action.payload]; }, archiveCategoryXProduct: ( state, action: PayloadAction<{ productId: number }> ) => { state.items = state.items.filter( (item) => !item.isArchive && item.productId !== action.payload.productId ); }, }, }); // Action creators are generated for each case reducer function export const selectCategoriesXProducts = (state: RootState) => state.categoriesXProducts.items; export const categoriesXProductsAction = categoriesXProductsSlice.actions; export default categoriesXProductsSlice.reducer;
const metroURL = 'https://metro.muze.nl/details/' export const symbols = { isProxy: Symbol('isProxy'), source: Symbol('source') } class Client { #options = { url: typeof window != 'undefined' ? window.location : 'https://localhost' } #verbs = ['get','post','put','delete','patch','head','options','query'] static tracers = {} constructor(...options) { for (let option of options) { if (typeof option == 'string' || option instanceof String) { this.#options.url = ''+option } else if (option instanceof Client) { Object.assign(this.#options, option.#options) } else if (option instanceof Function) { this.#addMiddlewares([option]) } else if (option && typeof option == 'object') { for (let param in option) { if (param == 'middlewares') { this.#addMiddlewares(option[param]) } else if (typeof option[param] == 'function') { this.#options[param] = option[param](this.#options[param], this.#options) } else { this.#options[param] = option[param] } } } } if (this.#options.verbs) { this.#verbs = this.#options.verbs delete this.#options.verbs } for (const verb of this.#verbs) { this[verb] = async function(...options) { return this.#fetch(request( this.#options, ...options, {method: verb.toUpperCase()} )) } } Object.freeze(this) } #addMiddlewares(middlewares) { if (typeof middlewares == 'function') { middlewares = [ middlewares ] } let index = middlewares.findIndex(m => typeof m != 'function') if (index>=0) { throw metroError('metro.client: middlewares must be a function or an array of functions ' +metroURL+'client/invalid-middlewares-value/', middlewares[index]) } if (!Array.isArray(this.#options.middlewares)) { this.#options.middlewares = [] } this.#options.middlewares = this.#options.middlewares.concat(middlewares) } #fetch(req) { if (!req.url) { throw metroError('metro.client.'+r.method.toLowerCase()+': Missing url parameter '+metroURL+'client/missing-url-param/', req) } let metrofetch = async (req) => { if (req[symbols.isProxy]) { // even though a Proxy is supposed to be 'invisible' // fetch() doesn't work with the proxy (in Firefox), // you need the actual Request object here req = req[symbols.source] } return response(await fetch(req)) } let middlewares = [metrofetch].concat(this.#options?.middlewares?.slice() || []) let options = this.#options //@TODO: do this once in constructor? let next for (let middleware of middlewares) { next = (function(next, middleware) { return async function(req) { let res let tracers = Object.values(Client.tracers) for(let tracer of tracers) { if (tracer.request) { tracer.request.call(tracer, req) } } res = await middleware(req, next) for(let tracer of tracers) { if (tracer.response) { tracer.response.call(tracer, res) } } return res } })(next, middleware) } return next(req) } with(...options) { return new Client(this, ...options) } } export function client(...options) { return new Client(...options) } function appendHeaders(r, headers) { if (!Array.isArray(headers)) { headers = [headers] } headers.forEach((header) => { if (typeof header == 'function') { let result = header(r.headers, r) if (result) { if (!Array.isArray(result)) { result = [result] } headers = headers.concat(result) } } }) headers.forEach((header) => { Object.entries(header).forEach(([name,value]) => { r.headers.append(name, value) }) }) } function bodyProxy(body, r) { let source = r.body if (!source) { //Firefox does not allow access to Request.body (undefined) //Chrome and Nodejs do, so mimic the correct (documented) //result here if (body === null) { source = new ReadableStream() } else if (body instanceof ReadableStream) { source = body } else if (body instanceof Blob) { source = body.stream() } else { source = new ReadableStream({ start(controller) { let chunk switch(typeof body) { case 'object': if (typeof body.toString == 'function') { // also catches URLSearchParams chunk = body.toString() } else if (body instanceof FormData) { chunk = new URLSearchParams(body).toString() } else if (body instanceof ArrayBuffer || ArrayBuffer.isView(body) ) { // catchs TypedArrays - e.g. Uint16Array chunk = body } else { throw metroError('Cannot convert body to ReadableStream', body) } break case 'string': case 'number': case 'boolean': chunk = body break default: throw metroError('Cannot convert body to ReadableStream', body) break } controller.enqueue(chunk) controller.close() } }) } } return new Proxy(source, { get(target, prop, receiver) { switch (prop) { case symbols.isProxy: return true break case symbols.source: return body break case 'toString': return function() { return ''+body } break } if (typeof body == 'object') { if (prop in body) { if (typeof body[prop] == 'function') { return function(...args) { return body[prop].apply(body, args) } } return body[prop] } } if (prop in target && prop != 'toString') { // skipped toString, since it has no usable output // and body may have its own toString if (typeof target[prop] == 'function') { return function(...args) { return target[prop].apply(target, args) } } return target[prop] } }, has(target, prop) { return prop in body }, ownKeys(target) { return Reflect.ownKeys(body) }, getOwnPropertyDescriptor(target, prop) { return Object.getOwnPropertyDescriptor(body,prop) } }) } function getRequestParams(req, current) { let params = current || {} if (!params.url && current.url) { params.url = current.url } // function to fetch all relevant properties of a Request for(let prop of ['method','headers','body','mode','credentials','cache','redirect', 'referrer','referrerPolicy','integrity','keepalive','signal', 'priority','url']) { if (typeof req[prop] == 'function') { req[prop](params[prop], params) } else if (typeof req[prop] != 'undefined') { if (prop == 'url') { params.url = url(params.url, req.url) } else { params[prop] = req[prop] } } } return params } export function request(...options) { // the standard Request constructor is a minefield // so first gather all the options together into a single // javascript object, then set it in one go let requestParams = { url: typeof window != 'undefined' ? window.location : 'https://localhost/', duplex: 'half' // required when setting body to ReadableStream, just set it here by default already } for (let option of options) { if (typeof option == 'string' || option instanceof URL || option instanceof URLSearchParams ) { requestParams.url = url(requestParams.url, option) } else if (option && typeof option == 'object') { Object.assign(requestParams, getRequestParams(option, requestParams)) } } let body = requestParams.body if (body) { if (typeof body == 'object' && !(body instanceof String) && !(body instanceof ReadableStream) && !(body instanceof Blob) && !(body instanceof ArrayBuffer) && !(body instanceof DataView) && !(body instanceof FormData) && !(body instanceof URLSearchParams) && (typeof TypedArray=='undefined' || !(body instanceof TypedArray)) ) { requestParams.body = JSON.stringify(body) } } let r = new Request(requestParams.url, requestParams) Object.freeze(r) return new Proxy(r, { get(target, prop, receiver) { switch(prop) { case symbols.source: return target break case symbols.isProxy: return true break case 'with': return function(...options) { return request(target, ...options) } break case 'toString': case 'toJSON': return function() { return target[prop].apply(target) } break case 'blob': case 'text': case 'json': return function() { return target[prop].apply(target) } break case 'body': // Request.body is always a ReadableStream // which is a horrible API, if you want to // allow middleware to alter the body // so we keep the original body, wrap a Proxy // around it to keep the ReadableStream api // accessible, but allow access to the original // body value as well if (!body) { body = target.body } if (body) { if (body[symbols.isProxy]) { return body } return bodyProxy(body, target) } break } return target[prop] } }) } function getResponseParams(res, current) { // function to fetch all relevant properties of a Response let params = current || {} if (!params.url && current.url) { params.url = current.url } for(let prop of ['status','statusText','headers','body','url','type','redirected']) { if (typeof res[prop] == 'function') { res[prop](params[prop], params) } else if (typeof res[prop] != 'undefined') { if (prop == 'url') { params.url = new URL(res.url, params.url || 'https://localhost/') } else { params[prop] = res[prop] } } } return params } export function response(...options) { let responseParams = {} for (let option of options) { if (typeof option == 'string') { responseParams.body = option } else if (option instanceof Response) { Object.assign(responseParams, getResponseParams(option, responseParams)) } else if (option && typeof option == 'object') { if (option instanceof FormData || option instanceof Blob || option instanceof ArrayBuffer || option instanceof DataView || option instanceof ReadableStream || option instanceof URLSearchParams || option instanceof String || (typeof TypedArray != 'undefined' && option instanceof TypedArray) ) { responseParams.body = option } else { Object.assign(responseParams, getResponseParams(option, responseParams)) } } } let r = new Response(responseParams.body, responseParams) Object.freeze(r) return new Proxy(r, { get(target, prop, receiver) { switch(prop) { case symbols.isProxy: return true break case symbols.source: return target break case 'with': return function(...options) { return response(target, ...options) } break case 'body': if (responseParams.body) { if (responseParams.body[symbols.isProxy]) { return responseParams.body } return bodyProxy(responseParams.body, target) } else { return bodyProxy('',target) } break case 'ok': return (target.status>=200) && (target.status<400) break case 'headers': return target.headers break default: if (prop in responseParams && prop != 'toString') { return responseParams[prop] } if (prop in target && prop != 'toString') { // skipped toString, since it has no usable output // and body may have its own toString if (typeof target[prop] == 'function') { return function(...args) { return target[prop].apply(target, args) } } return target[prop] } break } return undefined } }) } function appendSearchParams(url, params) { if (typeof params == 'function') { params(url.searchParams, url) } else { params = new URLSearchParams(params) params.forEach((value,key) => { url.searchParams.append(key, value) }) } } export function url(...options) { let validParams = ['hash','host','hostname','href', 'password','pathname','port','protocol','username','search','searchParams'] let u = new URL('https://localhost/') for (let option of options) { if (typeof option == 'string' || option instanceof String) { // option is a relative or absolute url u = new URL(option, u) } else if (option instanceof URL || (typeof Location != 'undefined' && option instanceof Location) ) { u = new URL(option) } else if (option instanceof URLSearchParams) { appendSearchParams(u, option) } else if (option && typeof option == 'object') { for (let param in option) { if (param=='search') { if (typeof option.search == 'function') { option.search(u.search, u) } else { u.search = new URLSearchParams(option.search) } } else if (param=='searchParams') { appendSearchParams(u, option.searchParams) } else { if (!validParams.includes(param)) { throw metroError('metro.url: unknown url parameter '+metroURL+'url/unknown-param-name/', param) } if (typeof option[param] == 'function') { option[param](u[param], u) } else if ( typeof option[param] == 'string' || option[param] instanceof String || typeof option[param] == 'number' || option[param] instanceof Number || typeof option[param] == 'boolean' || option[param] instanceof Boolean ) { u[param] = ''+option[param] } else if (typeof option[param] == 'object' && option[param].toString) { u[param] = option[param].toString() } else { throw metroError('metro.url: unsupported value for '+param+' '+metroURL+'url/unsupported-param-value/', options[param]) } } } } else { throw metroError('metro.url: unsupported option value '+metroURL+'url/unsupported-option-value/', option) } } Object.freeze(u) return new Proxy(u, { get(target, prop, receiver) { switch(prop) { case symbols.isProxy: return true break case symbols.source: return target break case 'with': return function(...options) { return url(target, ...options) } break case 'toString': case 'toJSON': return function() { return target[prop]() } break } return target[prop] } }) } export function formdata(...options) { var params = new FormData() for (let option of options) { if (option instanceof FormData) { for (let entry of option.entries()) { params.append(entry[0],entry[1]) } } else if (option && typeof option == 'object') { for (let entry of Object.entries(option)) { if (Array.isArray(entry[1])) { for (let value of entry[1]) { params.append(entry[0], value) } } else { params.append(entry[0],entry[1]) } } } else { throw new metroError('metro.formdata: unknown option type, only FormData or Object supported',option) } } Object.freeze(params) return new Proxy(params, { get: (target,prop,receiver) => { switch(prop) { case symbols.isProxy: return true break case symbols.source: return target break case 'with': return function(...options) { return formdata(target, ...options) } break case 'toString': case 'toJSON': return function() { return target[prop]() } break } return target[prop] } }) } const metroConsole = { error: (message, ...details) => { console.error('Ⓜ️ ',message, ...details) }, info: (message, ...details) => { console.info('Ⓜ️ ',message, ...details) }, group: (name) => { console.group('Ⓜ️ '+name) }, groupEnd: (name) => { console.groupEnd('Ⓜ️ '+name) } } export function metroError(message, ...details) { metroConsole.error(message, ...details) return new Error(message, ...details) } export const trace = { add(name, tracer) { Client.tracers[name] = tracer }, delete(name) { delete Client.tracers[name] }, clear() { Client.tracers = {} }, group() { let group = 0; return { request: (req) => { group++ metroConsole.group(group) metroConsole.info(req?.url, req) }, response: (res) => { metroConsole.info(res?.body ? res.body[symbols.source]: null, res) metroConsole.groupEnd(group) group-- } } } }
import { ChangeEvent, FormEvent, useEffect, useState } from "react"; import { useAppDispatch, useAppSelectore } from "../../../hooks/reduxHooks"; import { createPost, updatePost, } from "../../../redux/features/post/postActionCreators"; import { useHandleUpload } from "../../../hooks/useImageUploder"; import CircularLoading from "../../loading/CircularLoading"; import SubmitBtn from "../../buttons/SubmitBtn"; import BookCover from "../../../assets/images/book-cover-min.jpg"; import Input from "../Input"; import "./style.scss"; import { usePostFormValidator } from "../../../hooks/formValidators"; import ErrorMessage from "../../Error/Error"; import CloseBtn from "../../buttons/CloseBtn"; type PostFormStateProps = { title: string; bookAuthor: string; desc: string; coverUrl: string; }; type FormErr = { isError: boolean; msg: string; }; const formErrInitialState = { isError: false, msg: "", }; const postFromInitialState: PostFormStateProps = { title: "", bookAuthor: "", desc: "", coverUrl: "", }; const PostForm: React.FC<{ isUpdate: boolean }> = ({ isUpdate }) => { const [selectedImage, setSelectedImage] = useState<File | null>(null); const [formData, setFormData] = useState<PostFormStateProps>(postFromInitialState); const [formErr, setFormErr] = useState<FormErr>(formErrInitialState); const { selectedPost, allPosts } = useAppSelectore((state) => state.post); const { isValid, errMessage } = usePostFormValidator(formData); const { isError: uploadImageError, isLoading: uploadImageLoading, coverUrl: uploadImageUrl, } = useHandleUpload({ selectedImage }); const dispatch = useAppDispatch(); const changeHandler = ( e: ChangeEvent<HTMLInputElement> | ChangeEvent<HTMLTextAreaElement> ) => setFormData({ ...formData, [e.target.name]: e.target.value }); const changeImageHandler = (e: ChangeEvent<HTMLInputElement>) => { const file = e.target.files?.[0]; if (file) { setSelectedImage(file); } }; useEffect(() => { setFormData({ ...formData, coverUrl: uploadImageUrl }); }, [uploadImageUrl]); // last formData useEffect(() => { if (isUpdate && selectedPost) setFormData({ ...selectedPost }); else setFormData(postFromInitialState); }, [isUpdate, selectedPost]); const submitHandler = async (e: FormEvent<HTMLFormElement>) => { e.preventDefault(); if (!isValid) return setFormErr({ isError: true, msg: errMessage }); if (isUpdate) dispatch(updatePost({ _id: selectedPost._id, updatedPost: formData })); if (!isUpdate) dispatch(createPost(formData)); }; return ( <form className="authForm postForm" onSubmit={submitHandler}> <CloseBtn /> {isUpdate ? ( <i className={`bx bx-edit-alt postForm__icon`}></i> ) : ( <h2 style={{ marginBottom: "1rem" }}>Create and share </h2> )} <Input type="text" name="title" value={formData.title} changeHandler={changeHandler} /> <Input type="text" name="bookAuthor" value={formData.bookAuthor} changeHandler={changeHandler} /> <Input type="text-field" name="desc" value={formData.desc} changeHandler={changeHandler} /> <span style={{ fontSize: "0.85rem" }}>{formData.desc.length}</span> <input onChange={changeImageHandler} type="file" /> <img className="postForm__img" alt="book" src={ !isUpdate ? //if creates new post--form selectedImage ? URL.createObjectURL(selectedImage) : BookCover : //if updates post--form selectedImage ? URL.createObjectURL(selectedImage) : selectedPost.coverUrl === "" ? BookCover : selectedPost.coverUrl } /> <SubmitBtn disable={uploadImageLoading} isLoading={allPosts.isLoading} tag={isUpdate ? "save" : "create"} /> {uploadImageLoading && <CircularLoading isBoth={true} />} {formErr.isError && <ErrorMessage errMessage={formErr.msg} />} {allPosts.error && <ErrorMessage errMessage={allPosts.error} />} {uploadImageError && ( <ErrorMessage errMessage="Image upload has been failed!" /> )} </form> ); }; export default PostForm;
using AdventureAlternatives.Services; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AdventureAlternatives { public class Startup { private readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins"; public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy(name: MyAllowSpecificOrigins, builder => { builder.WithOrigins("http://localhost:3000", "https://testadventurealternatives.zohosites.com") .AllowAnyHeader() .AllowAnyMethod(); }); }); services.AddControllers().AddNewtonsoftJson(setupAction => { setupAction.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); setupAction.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; }); services.Configure<ApiBehaviorOptions>(options => { options.SuppressModelStateInvalidFilter = true; }); services.AddScoped<ICampService, CampService>(); services.AddScoped<IAuthService, AuthService>(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Adventure Alternatives API", Version = "v1" }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("swagger/v1/swagger.json", "Roxus API (v1)"); // serve UI at root c.RoutePrefix = string.Empty; }); } app.UseHttpsRedirection(); app.UseSwagger(); app.UseRouting(); app.UseCors(MyAllowSpecificOrigins); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
import io from typing import BinaryIO import csv from aiogram import Router, Bot from aiogram.enums import ContentType from aiogram.types import CallbackQuery, Message from aiogram_dialog import Window, Dialog, DialogManager from aiogram_dialog.widgets.input import MessageInput from aiogram_dialog.widgets.kbd import Cancel, Button from aiogram_dialog.widgets.text import Const from infrastructure.supabase.supabase_dao import TableDAO from infrastructure.supabase.table_transfer import Table from src.bot.structures.FSM import admin async def csv_handler( message: Message, message_input: MessageInput, manager: DialogManager, **kwargs ): await message.answer("Обрабатываю...") bot: Bot = manager.middleware_data.get("bot") table_dao: TableDAO = manager.middleware_data.get("table_dao") csv_file: BinaryIO = await bot.download(message.document) reader = csv.reader(io.TextIOWrapper(csv_file)) filtered_array = [] for row in reader: counter = dict((i, row.count(i)) for i in row) empty_space: int | None = counter.get('', None) if not empty_space: filtered_array.append(row) else: if empty_space <= 3: if row != ['', '', '']: filtered_array.append(row) header = filtered_array[0] for i in range(len(header)): if header[i] == '\ufeffname': header[i] = 'name' if header[i] == 'brief': header[i] = 'tags' if header[i] == 'slug': header[i] = 'key' if header[i] == 'general': header[i] = 'basic_description' if header[i] == 'deep': header[i] = 'deep_level' if header[i] == 'card': header[i] = 'pic_url' if header[i] == 'relations': header[i] = 'relationship' result: list[dict] = [] for arcana in filtered_array[1:]: data = dict.fromkeys(header) for key, column in zip(header, arcana): data[key] = column result.append(data) table_dto: Table = Table(title="arcana", rows=result) table_dao.save(table_name="arcana", obj=table_dto) await manager.next() async def on_finish(callback: CallbackQuery, button: Button, manager: DialogManager): await callback.message.answer("Вы вышли из режима админа. Функционал доступен по команде /admin") await manager.done() CSV_HANDLE = Window( Const(text="Скинь csv файл."), MessageInput(csv_handler, content_types=[ContentType.DOCUMENT]), Cancel(), state=admin.ServiceSG.WAIT ) CSV_PROCESSED = Window( Const(text="Готово."), Button(Const("✅ Завершить"), on_click=on_finish, id="finish"), state=admin.ServiceSG.DONE ) service_dialog = Dialog( CSV_HANDLE, CSV_PROCESSED ) service_dialog_router = Router() service_dialog_router.include_routers( service_dialog )
<template> <div> <Navbar/> <div class="row" style="min-height: 100vh;"> <Sidebar class="h-auto" style="z-index: 0;"></Sidebar> <div class="col mt-2"> <div class="container-fluid"> <nav aria-label="breadcrumb" class="mt-2"> <ol class="breadcrumb"> <li class="breadcrumb-item"><router-link class="" to="/admin">Dashboard</router-link></li> <li class="breadcrumb-item text-muted" aria-current="page"><router-link to="/admin/potensi-das">List Potensi Sub DAS</router-link></li> </ol> </nav> <h3 class="my-3"> <!-- <router-link to="/admin" class="btn btn-dark mr-1"> <i class="bi bi-arrow-left"></i> </router-link> --> List <strong>Potensi Sub DAS</strong> </h3> <div class="form-inline"> <input v-model="search" type="search" class="form-control text-center mr-auto" style="width: 50vw;" placeholder="Cari Potensi, Nama Sub DAS, dll ..." aria-label="Cari" aria-describedby="basic-addon1" /> </div> <div class="p-0 bg-white mx-auto table-responsive table-striped table-bordered mt-3"> <table class="table"> <thead class="text-center text-nowrap"> <tr> <th>ID</th> <th>Thumbnail</th> <th>Sub DAS</th> <th>Nama Potensi</th> <th>Kategori Potensi</th> </tr> </thead> <tbody class="text-center"> <tr v-for="potensidas in paginateData" :key="potensidas.id" @click="detail(potensidas.id)"> <th>{{ potensidas.id }}</th> <td class="py-2 px-0 justify-content-center align-items-center"> <img :src="'/images/potensi/' + potensidas.thumbnail" class="img-fluid" onerror="this.src='/images/default.png'" style="object-fit: scale-down; width: 100px;"> </td> <td>{{ potensidas.das_name }}</td> <td>{{ potensidas.potensi_das_name }}</td> <td>{{ potensidas.potensi_name }}</td> </tr> </tbody> </table> </div> <div class="form-inline align-items-center justify-content-center mb-3"> <ul class="pagination mt-3"> <li class="page-item" :class="{ 'disabled': currentPage === 1 }"> <button class="page-link" @click="previousPage">Previous</button> </li> <div class="page-item" v-for="n in totalPages" :key="n" @click="goToPage(n)" :class="{ 'active': n === currentPage }"> <li style="cursor: pointer;"><a class="page-link">{{ n }}</a></li> </div> <li class="page-item" :class="{ 'disabled': currentPage === totalPages}"> <a class="page-link" @click="nextPage" style="cursor: pointer;">Next</a> </li> </ul> <select v-model="itemsPerPage" @change="onItemsPerPageChange" class="ml-2 page-link radius"> <option value="10">10</option> <option value="20">20</option> <option value="50">50</option> </select> <div class="data-length"> <strong> {{ paginateData.length }} </strong> of <strong> {{ potensidas.length }} </strong> data </div> </div> </div> </div> </div> </div> </template> <script> import Sidebar from "@/components/Sidebar.vue"; import Navbar from "@/components/Navbar.vue"; import axios from "axios"; import API_URL from "../../../services/api"; export default { name: "ListPotensiSubDas", components: { Sidebar, Navbar, }, data() { return { potensidas: [], search: '', currentPage: 1, itemsPerPage: 10, }; }, created() { this.fetchPotensiSubDas(); }, mounted() { }, computed: { currentUser() { return this.$store.state.auth.user; }, //Universal search filteredData() { const filteredPotensiDas = this.potensidas.filter((potensidas) => { // Search by all in searchbar const isSearched = !this.search || Object.values(potensidas) .map((val) => String(val).toLowerCase()) .some((val) => val.includes(this.search.toLowerCase())); return isSearched; }); return filteredPotensiDas; }, paginateData() { const start = (this.currentPage - 1) * this.itemsPerPage const end = start + this.itemsPerPage return this.filteredData.slice(start, end) }, totalPages() { return Math.ceil(this.filteredData.length / this.itemsPerPage) }, }, methods: { async fetchPotensiSubDas() { try { const response = await axios.get(API_URL + "/api/potensi-das"); this.potensidas = response.data.potensidas; } catch (err) { console.log(err); } }, detail(id) { this.$router.push(`/admin/subdas/potensi/${id}`) }, previousPage() { if (this.currentPage > 1) { this.currentPage--; } window.scrollTo(0, 0); }, nextPage() { if (this.currentPage < this.totalPages) { this.currentPage++; } window.scrollTo(0, 0); }, goToPage(n) { this.currentPage = n; window.scrollTo(0, 0); }, onItemsPerPageChange() { this.currentPage = 1; window.scrollTo(0, 0); }, }, }; </script>
/* global Line noise Blob */ // eslint-disable-next-line no-unused-vars /** * * NOTE TO THE READER (that's you) * * This is my own messy code to make SVG files for sending to the AxiDraw without having * to deal with Illustrator. * * This is NOT good code, this is not the "proper" way to write helpful libraries like this * but it does what I need it to do in a way that helps me debug easily in the console * etc. etc. etc. The "cull/bisectLines" functions are particularly terrible. * * There is no versioning, no changelogs, no githib repo, the latest version probable lives here. * */ /** * The page object (which you'd expect to be a class but isn't for various dull reasons) * controls the display of lines on a canvas, the saving of those lines into svgs * and other various bits and bobs * * Page * @namespace * @property {function} resize * @property {function} scaleX * @property {function} scaleY * @property {function} isInside * @property {function} intersect * @property {function} bisectLines * @property {function} cullOutside * @property {function} cullInside * @property {function} translate * @property {function} rotate * @property {function} getBoundingBox * @property {function} sortPointsClockwise * @property {function} makeCircle */ const page = { /** * precision - is used when we do some rounding on floats. We can often end up with two floats * like 1.9999999999998 and 2.0000000000001, which are the same for the purposes of plotting pen * on paper, but won't pass checks to be === equal. So sometimes we'll round the numbers when we * want to check things. * @constant {number} * @access private * */ precision: 2, /** * dpi - the dots per inch that we are working with. Used to calculate x,y co-ords to printable dimensions * @constant {number} * @access private */ dpi: 300, /** * printStore - This is where we hold things to be printed */ printStore: {}, /** * Returns a rounded value based on the {@private precision} * @access private * @param {number} val The value to be rounded * @returns {number} The rounded value */ rounding: (val) => { return val // return parseFloat(val.toFixed(page.precision)) }, /** * Calculates if a point is inside a polygon defined by an array of points * @param {object} point A single point in the format of [x, y] * @param {Array} vs An array of points (vertexes) that make up the polygon i.e. [[0, 0], [10, 0], [10, 10], [0, 10]] * @returns {boolean} Is the point inside the array or not */ isInside: (point, vs, forceSort = false) => { // ray-casting algorithm based on // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html const x = point.x const y = point.y let sortedVs = vs if (forceSort) sortedVs = page.sortPointsClockwise(vs) let inside = false for (let i = 0, j = sortedVs.length - 1; i < sortedVs.length; j = i++) { const xi = sortedVs[i].x const yi = sortedVs[i].y const xj = sortedVs[j].x const yj = sortedVs[j].y const intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi) if (intersect) inside = !inside } return inside }, /** * Determine the intersection point of two line segments * line intercept math by Paul Bourke http://paulbourke.net/geometry/pointlineplane/ * @param {object} line1 A single {@link Line} object, consisting of two points, a start and end point. * @param {object} line2 A single {@link Line} object, consisting of two points, a start and end point. * @returns {boolean} Returns if the lines intersect or not */ intersect: (line1, line2) => { // Round all this stuff off /* line1.x1 = page.rounding(line1.x1) line1.y1 = page.rounding(line1.y1) line1.x2 = page.rounding(line1.x2) line1.y2 = page.rounding(line1.y2) line2.x1 = page.rounding(line2.x1) line2.y1 = page.rounding(line2.y1) line2.x2 = page.rounding(line2.x2) line2.y2 = page.rounding(line2.y2) */ // Check if none of the lines are of length 0 if ((line1.x1 === line1.x2 && line1.y1 === line1.y2) || (line2.x1 === line2.x2 && line2.y1 === line2.y2)) { return false } const denominator = ((line2.y2 - line2.y1) * (line1.x2 - line1.x1) - (line2.x2 - line2.x1) * (line1.y2 - line1.y1)) // Lines are parallel if (denominator === 0) { return false } const ua = ((line2.x2 - line2.x1) * (line1.y1 - line2.y1) - (line2.y2 - line2.y1) * (line1.x1 - line2.x1)) / denominator const ub = ((line1.x2 - line1.x1) * (line1.y1 - line2.y1) - (line1.y2 - line1.y1) * (line1.x1 - line2.x1)) / denominator // is the intersection along the segments if (ua < 0 || ua > 1 || ub < 0 || ub > 1) { return false } // Return a object with the x and y coordinates of the intersection const x = (line1.x1 + ua * (line1.x2 - line1.x1)) const y = (line1.y1 + ua * (line1.y2 - line1.y1)) // If the intersection point is the same as any of the line1 points, then it // doesn't count // if (line1.x1 === x && line1.y1 === y) return false // if (line1.x2 === x && line1.y2 === y) return false return { x, y } }, /** * This takes in an array of lines, and then splits the lines based on a "cutter/culler" * second set of lines, returning the new cut lines. For example if a single line passing * through a square is passed in. The line will be split into three parts the two outside * the square parts, and the single inside part. This function is normally used in conjunction * with the cullInside/Outside functions. But you could bisect something (say inside a circle) * duplicate the results. Then cull the inside of one copy and the outside of the other, so you * can rotate the inside set of lines independently of the outside ones. * * NOTE: * REALLY NOTE: * * This code kinda, sorta, doesn't work, like 100% of the time. After the line is bisected we end * up with line who's point falls exactly on the bisecting line, which will count as bisecting, and * therefor will bisect again and again. We have a counter to bail us out of this, but it does mean * we need to clean up lines that are like 0 distance long. And I haven't written the code to do that * yet. * * TODO: * * Write code to remove lines are are under a certain threshold in length * Write code to remove duplicate lines when they are within a certain threshold of each other * Join lines up when the end points of the line are close enough to the end points of another * line * * @param {(Array|object)} lines An array of {@link Line} objects, or a single {@link Line} object * @param {object} culler A single {@link Line} object * @returns {Array} An array of {@link Line} objects */ bisectLines: (lines, culler) => { // Make sure we have an array of lines let counter = 0 let maxDepth = 0 if (!Array.isArray(lines)) lines = [lines] // Turn the culler into a set of lines we can check against const cullLines = [] const points = culler.getPoints() for (let p = 0; p < points.length - 1; p++) { const subline = { x1: points[p].x, y1: points[p].y, x2: points[p + 1].x, y2: points[p + 1].y } cullLines.push(subline) } const keepLines = [] let checkLines = lines while (counter < 10000 && checkLines.length > 0) { if (counter > maxDepth) maxDepth = counter // Now go through all the lines we want to bisect const checkedLines = [] checkLines.forEach((line) => { // Now loop through all the lines to check against all the lines // in the culler, each time the line doesn't bisect then we add it // to the newLine let newLine = new Line(line.getZindex()) newLine.splitHappened = false let splitFound = false // Go through all the points, turning them into lines const points = line.getPoints() for (let p = 0; p < points.length - 1; p++) { const subline = { x1: points[p].x, y1: points[p].y, x2: points[p + 1].x, y2: points[p + 1].y } const isFirstPoint = (p === 0) const isLastPoint = (p === points.length - 2) // Always add the first point to the line newLine.addPoint(subline.x1, subline.y1) if (splitFound === false) { cullLines.forEach((cullLine) => { if (splitFound === false) { const result = page.intersect(subline, cullLine) // If we have an intersection then we need to stop this line // and start a new one let setTrue = true if (result) { if (isFirstPoint && page.getDistance({ x: subline.x1, y: subline.y1 }, result) < 0.0001) setTrue = false if (isLastPoint && page.getDistance({ x: subline.x2, y: subline.y2 }, result) < 0.0001) setTrue = false } else { setTrue = false } if (result !== false && setTrue === true) { splitFound = true newLine.addPoint(result.x, result.y) // Add the bisection point newLine.splitHappened = true checkedLines.push(newLine) newLine = new Line(newLine.getZindex()) // Start a new line newLine.splitHappened = true newLine.addPoint(result.x, result.y) // Add this point onto it } } }) } } newLine.addPoint(points[points.length - 1].x, points[points.length - 1].y) if (newLine.getPoints().length > 1) checkedLines.push(newLine) // Add it to the list of returned lines }) // Go through the checkedLines and push them onto one array or another checkLines = [] checkedLines.forEach((line) => { if (line.splitHappened === true) { checkLines.push(line) } else { keepLines.push(line) } }) counter++ } return page.cleanLines(keepLines) }, /** * When passed an array of lines, and a single line to act as a "culler", * this method will remove all the lines on the outside of the "culler" * and return a new array of lines. * NOTE: The culler needs to be a closed polygon, i.e. the last point * needs to be the same as the first point, otherwise the inside/outside * part of the calculation will not function correctly * @param {(Array|object)} lines An array of {@link Line} objects, or a single {@link Line} object * @param {object} culler A single {@link Line} object * @returns {Array} An array of {@link Line} objects */ cullOutside: (lines, culler, forceSort = false) => { // TODO: Add a check in to make sure the culler is closed const newLines = page.bisectLines(lines, culler) // gets an array of lines back const keepLines = [] newLines.forEach((line) => { let anyPointOutside = false const points = line.getPoints() for (let p = 0; p < points.length - 1; p++) { const subline = { x1: points[p].x, y1: points[p].y, x2: points[p + 1].x, y2: points[p + 1].y } const midPoint = { x: subline.x1 + ((subline.x2 - subline.x1) / 2), y: subline.y1 + ((subline.y2 - subline.y1) / 2) } const isInside = page.isInside(midPoint, culler.getPoints(), forceSort) if (isInside === false) anyPointOutside = true } if (anyPointOutside === false) keepLines.push(line) }) return keepLines }, /** * When passed an array of lines, and a single line to act as a "culler", * this method will remove all the lines on the outside of the "culler" * and return a new array of lines * NOTE: The culler needs to be a closed polygon, i.e. the last point * needs to be the same as the first point, otherwise the inside/outside * part of the calculation will not function correctly * @param {(Array|object)} lines An array of {@link Line} objects, or a single {@link Line} object * @param {object} culler A single {@link Line} object * @returns {Array} An array of {@link Line} objects */ cullInside: (lines, culler, forceSort = false) => { // TODO: Add a check in to make sure the culler is closed // bisect the lines where they pass over the culler const newLines = page.bisectLines(lines, culler) const keepLines = [] newLines.forEach((line) => { let anyPointInside = false const points = line.getPoints() for (let p = 0; p < points.length - 1; p++) { const subline = { x1: points[p].x, y1: points[p].y, x2: points[p + 1].x, y2: points[p + 1].y } const midPoint = { x: subline.x1 + ((subline.x2 - subline.x1) / 2), y: subline.y1 + ((subline.y2 - subline.y1) / 2) } const isInside = page.isInside(midPoint, culler.getPoints(), forceSort) if (isInside === true) anyPointInside = true } if (anyPointInside === false) keepLines.push(line) }) return keepLines }, /** * A utility method to translate a single line or an array of lines * by the passed values. It always returns an array of lines * @param {(Array|object)} lines An array of {@link Line} objects, or a single {@link Line} object * @param {number} x The x offset * @param {number} y The y offset * @param {number} z The z offset * @returns {Array} An array of {@link Line} objects */ translate: (lines, x, y, z = 0) => { const newLines = [] if (!Array.isArray(lines)) lines = [lines] lines.forEach((line) => { const newLine = new Line(line.getZindex()) const points = line.getPoints() points.forEach((point) => { newLine.addPoint(page.rounding(point.x + x), page.rounding(point.y + y), page.rounding(point.z + z)) }) newLines.push(newLine) }) return newLines }, /** * A utility method to translate a single line or an array of lines * by the passed values. It always returns an array of lines * @param {(Array|object)} lines An array of {@link Line} objects, or a single {@link Line} object * @param {number} angle The angle in degrees to rotate around * @param {boolean} aroundOwnMidpoint Rotate around it's own middle if true, around 0,0 origin if false * @returns {Array} An array of {@link Line} objects */ rotate: (lines, angle, aroundOwnMidpoint = true) => { // Convert the angle from degree to radians const adjustedAngle = (-angle * Math.PI / 180) // This will hold our final lines for us let newLines = [] // Make sure the lines are an array if (!Array.isArray(lines)) lines = [lines] // Grab the bouding box in case we need it const bb = page.getBoundingBox(lines) // If we are rotating around it's own center then translate it to 0,0 if (aroundOwnMidpoint) { lines = page.translate(lines, -bb.mid.x, -bb.mid.y) } // Now rotate all the points lines.forEach((line) => { const newLine = new Line(line.getZindex()) const points = line.getPoints() points.forEach((point) => { newLine.addPoint((Math.cos(adjustedAngle) * point.x) + (Math.sin(adjustedAngle) * point.y), (Math.cos(adjustedAngle) * point.y) - (Math.sin(adjustedAngle) * point.x), point.z) }) newLines.push(newLine) }) // If we are rotating around the center now we need to move it back // to it's original position if (aroundOwnMidpoint) { newLines = page.translate(newLines, bb.mid.x, bb.mid.y) } // Send the lines back return newLines }, /** * A utility method to translate a single line or an array of lines * by the passed values. It always returns an array of lines * @param {(Array|object)} lines An array of {@link Line} objects, or a single {@link Line} object * @param {number} angle The angle in degrees to rotate around * @param {boolean} aroundOwnMidpoint Rotate around it's own middle if true, around 0,0 origin if false * @returns {Array} An array of {@link Line} objects */ rotateXYZ: (lines, angle, aroundOwnMidpoint = true) => { // This will hold our final lines for us let newLines = [] // Make sure the lines are an array if (!Array.isArray(lines)) lines = [lines] // Grab the bouding box in case we need it const bb = page.getBoundingBox(lines) // If we are rotating around it's own center then translate it to 0,0 if (aroundOwnMidpoint) { lines = page.translate(lines, -bb.mid.x, -bb.mid.y, -bb.mid.z) } // Now rotate all the points lines.forEach((line) => { const newLine = new Line(line.getZindex()) const points = line.getPoints() points.forEach((point) => { const newPoint = page.rotatePoint(point, angle) newLine.addPoint(newPoint.x, newPoint.y, newPoint.z) }) newLines.push(newLine) }) // If we are rotating around the center now we need to move it back // to it's original position if (aroundOwnMidpoint) { newLines = page.translate(newLines, bb.mid.x, bb.mid.y, bb.mid.z) } // Send the lines back return newLines }, zSort: (lines) => { // This will hold our final lines for us let newLines = [] // Make sure the lines are an array const linesMap = {} const linesIndex = [] if (!Array.isArray(lines)) lines = [lines] // Go through the lines lines.forEach((line) => { // Grab the bbox const bb = page.getBoundingBox(line) // Grab the zIndex of the line let z = bb.mid.z // Now adjust it *very* slightly based on the x and y values... the greater the x/y values // the furure it will be away from the middle, so we push that zindex a little further out. // This is of course a terrible HACK, and there is much wrong with this way of doing zSorting! z -= (Math.max(Math.abs(bb.max.x), Math.abs(bb.min.x)) / 100) z -= (Math.max(Math.abs(bb.max.y), Math.abs(bb.min.y)) / 100) line.setZindex(z) if (!linesMap[z]) linesMap[z] = [] linesMap[z].push(line) linesIndex.push(z) // newLines.push(line) }) // Now we have built up a map and index of all the lines, we need to sort the zIndex and then push the lines // into the newLines stack in that order linesIndex.sort(function (a, b) { return a - b }) linesIndex.forEach((i) => { newLines = [...newLines, ...linesMap[i]] }) return newLines }, flatten: (lines, zoom) => { // This will hold our final lines for us const newLines = [] // Make sure the lines are an array if (!Array.isArray(lines)) lines = [lines] lines.forEach((line) => { const newLine = new Line(line.getZindex()) const points = line.getPoints() points.forEach((point) => { const newPoint = page.projectPoint(point, zoom) newLine.addPoint(newPoint.x, newPoint.y, newPoint.z) }) newLines.push(newLine) }) return newLines }, /** * A utility method to translate a single line or an array of lines * by the passed values. It always returns an array of lines * @param {(Array|object)} lines An array of {@link Line} objects, or a single {@link Line} object * @param {displacement} amount Length and direction of dotify * @returns {Array} An array of {@link Line} objects */ dotify: (lines, displacement) => { if (!displacement) { displacement = { amplitude: 0, resolution: 1, xNudge: 0, yNudge: 0, zNudge: 0, xScale: 1, yScale: 1, zScale: 1, addTime: false, timeMod: 1 } } // This will hold our final lines for us const newLines = [] // Make sure the lines are an array if (!Array.isArray(lines)) lines = [lines] // If we are supposed to do time, then do it let ttMod = 0 if (displacement.addTime) ttMod = new Date().getTime() / 1000 / displacement.timeMod // Now displace all the points lines.forEach((line) => { const points = line.getPoints() points.forEach((point) => { const newPoint = { x: point.x, y: point.y, z: point.z } newPoint.x += noise.perlin3((point.x + displacement.xNudge + ttMod) / displacement.resolution, (point.y + displacement.xNudge + ttMod) / displacement.resolution, (point.z + displacement.xNudge + ttMod) / displacement.resolution) * displacement.xScale * displacement.amplitude newPoint.y += noise.perlin3((point.x + displacement.yNudge + ttMod) / displacement.resolution, (point.y + displacement.yNudge + ttMod) / displacement.resolution, (point.z + displacement.yNudge + ttMod) / displacement.resolution) * displacement.yScale * displacement.amplitude newPoint.z += noise.perlin3((point.x + displacement.zNudge + ttMod) / displacement.resolution, (point.y + displacement.zNudge + ttMod) / displacement.resolution, (point.z + displacement.zNudge + ttMod) / displacement.resolution) * displacement.zScale * displacement.amplitude // Make sure we always have something if (point.x === newPoint.x && point.y === newPoint.y && point.z === newPoint.z) { newPoint.x += 0.02 newPoint.y += 0.02 newPoint.y += 0.02 } const newLine = new Line(line.getZindex()) newLine.addPoint(point.x, point.y, point.z) newLine.addPoint(newPoint.x, newPoint.y, newPoint.z) newLines.push(newLine) }) }) // Send the lines back return newLines }, /** * A utility method to translate a single line or an array of lines * by the passed values. It always returns an array of lines * @param {(Array|object)} lines An array of {@link Line} objects, or a single {@link Line} object * @param {displacement} vectorObjects The angle in degrees to rotate around * @returns {Array} An array of {@link Line} objects */ displace: (lines, displacement) => { // This will hold our final lines for us const newLines = [] // Make sure the lines are an array if (!Array.isArray(lines)) lines = [lines] // If we are supposed to do time, then do it let ttMod = 0 if (displacement.addTime) ttMod = new Date().getTime() / 1000 / displacement.timeMod if (displacement.layout) ttMod += displacement.layout * Math.PI * 1000000 const midPoint = { x: page.size[0] / 2, y: page.size[1] / 2 } const d = new Date().getTime() const cornerDistance = (midPoint.x * midPoint.x) + (midPoint.y * midPoint.y) // Now displace all the points lines.forEach((line) => { const newLine = new Line(line.getZindex()) const points = line.getPoints() points.forEach((point) => { const newPoint = { x: point.x, y: point.y, z: point.z } // Do the hoop jumping to const weightPoint = { x: point.x + page.size[0] / 2 + displacement.xShift, y: point.y + page.size[1] / 2 + displacement.yShift, z: point.z } let finalWeightingMod = 1 if (displacement.direction === 'topDown') finalWeightingMod = (1 - weightPoint.y / page.size[1]) * 1 if (displacement.direction === 'leftRight') finalWeightingMod = (1 - weightPoint.x / page.size[0]) * 1 if (displacement.direction === 'middle') { const thisDist = ((midPoint.x - weightPoint.x) * (midPoint.x - weightPoint.x)) + ((midPoint.y - weightPoint.y) * (midPoint.y - weightPoint.y)) finalWeightingMod = (0.71 - (thisDist / cornerDistance - (displacement.middleDist / 1000)) * 1) } if (displacement.direction === 'noise') { finalWeightingMod = ((noise.perlin3(weightPoint.x / 20 + (d / 721), weightPoint.y / 20 + (d / 883), d / 1000) + 1) / 2) } if (displacement.weighting !== 0) finalWeightingMod *= displacement.weighting if (displacement.invert) finalWeightingMod = 1 - finalWeightingMod newPoint.x += noise.perlin3((point.x + displacement.xNudge + ttMod) / displacement.resolution, (point.y + displacement.xNudge + ttMod) / displacement.resolution, (point.z + displacement.xNudge + ttMod) / displacement.resolution) * displacement.xScale * displacement.amplitude * finalWeightingMod newPoint.y += noise.perlin3((point.x + displacement.yNudge + ttMod) / displacement.resolution, (point.y + displacement.yNudge + ttMod) / displacement.resolution, (point.z + displacement.yNudge + ttMod) / displacement.resolution) * displacement.yScale * displacement.amplitude * finalWeightingMod newPoint.z += noise.perlin3((point.x + displacement.zNudge + ttMod) / displacement.resolution, (point.y + displacement.zNudge + ttMod) / displacement.resolution, (point.z + displacement.zNudge + ttMod) / displacement.resolution) * displacement.zScale * displacement.amplitude * finalWeightingMod newLine.addPoint(newPoint.x, newPoint.y, newPoint.z) // newLine.addPoint((Math.cos(adjustedAngle) * point.x) + (Math.sin(adjustedAngle) * point.y), (Math.cos(adjustedAngle) * point.y) - (Math.sin(adjustedAngle) * point.x)) }) newLines.push(newLine) }) // Send the lines back return newLines }, /** * A utility method to scale a single line or an array of lines * by the passed values. It always returns an array of lines * @param {(Array|object)} lines An array of {@link Line} objects, or a single {@link Line} object * @param {number} xScale The amount to scale in the x direction * @param {number} yScale The amount to scale in the y direction, if null, then uses the same value as xScale * @param {number} zScale The amount to scale in the z direction, if null, then uses the same value as xScale * @param {boolean} aroundOwnMidpoint Scale around it's own middle if true, around 0,0 origin if false * @returns {Array} An array of {@link Line} objects */ scale: (lines, xScale, yScale = null, zScale = null, aroundOwnMidpoint = true) => { // This will hold our final lines for us let newLines = [] // Make sure the lines are an array if (!Array.isArray(lines)) lines = [lines] // Grab the bouding box in case we need it const bb = page.getBoundingBox(lines) // If we are rotating around it's own center then translate it to 0,0 if (aroundOwnMidpoint) { lines = page.translate(lines, -bb.mid.x, -bb.mid.y) } if (yScale === null) yScale = xScale if (zScale === null) zScale = xScale // Now scale all the points lines.forEach((line) => { const newLine = new Line(line.getZindex()) const points = line.getPoints() points.forEach((point) => { newLine.addPoint(xScale * point.x, yScale * point.y, zScale * point.z) }) newLines.push(newLine) }) // If we are scaling around the center now we need to move it back // to it's original position if (aroundOwnMidpoint) { newLines = page.translate(newLines, bb.mid.x, bb.mid.y, bb.mid.z) } // Send the lines back return newLines }, getDistance: (p1, p2) => { if (!p1.z || isNaN(p1.z)) p1.z = 0 if (!p2.z || isNaN(p2.z)) p2.z = 0 return Math.cbrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2) + Math.pow(p1.z - p2.z, 2)) }, /** * This utility method gets the bounding box from an array of lines, it also * calculates the midpoint * @param {(Array|object)} lines An array of {@link Line} objects, or a single {@link Line} object * @returns {object} And object containing the min/max points and the mid points */ getBoundingBox: (lines) => { if (!Array.isArray(lines)) lines = [lines] const max = { x: -999999999, y: -999999999, z: -999999999 } const min = { x: 999999999, y: 999999999, z: 999999999 } lines.forEach((line) => { const points = line.getPoints() points.forEach((point) => { if (point.x < min.x) min.x = point.x if (point.x > max.x) max.x = point.x if (point.y < min.y) min.y = point.y if (point.y > max.y) max.y = point.y if (point.z < min.z) min.z = point.z if (point.z > max.z) max.z = point.z }) }) return { min, max, mid: { x: page.rounding(min.x + ((max.x - min.x) / 2)), y: page.rounding(min.y + ((max.y - min.y) / 2)), z: page.rounding(min.z + ((max.z - min.z) / 2)) } } }, /** * A utility method for converting an array of points into a clockwise order * (or at least I think it's clockwise, it's suddenly struck me that there's * a slim chance it's anti-clockwise, TODO: check clockwiseyness) * @param {array} points An array of points objects * @returns {array} A sorted array of point objects */ sortPointsClockwise: (points) => { // Get the mid points of the points const max = { x: -999999999, y: -999999999, z: -999999999 } const min = { x: 999999999, y: 999999999, z: 999999999 } points.forEach((point) => { if (point.x < min.x) min.x = point.x if (point.x > max.x) max.x = point.x if (point.y < min.y) min.y = point.y if (point.y > max.y) max.y = point.y if (point.z < min.z) min.z = point.z if (point.z > max.z) max.z = point.z }) const mid = { x: page.rounding(min.x + ((max.x - min.x) / 2)), y: page.rounding(min.y + ((max.y - min.y) / 2)), z: page.rounding(min.z + ((max.z - min.z) / 2)) } // Now calculate the angle between the mid point and // all the points in turn let sortedPoints = [] points.forEach((point) => { sortedPoints.push({ x: point.x, y: point.y, z: point.z, angle: Math.atan2(point.y - mid.y, point.x - mid.x) * 180 / Math.PI }) }) sortedPoints = sortedPoints.sort((a, b) => parseFloat(a.angle) - parseFloat(b.angle)) return sortedPoints }, /** * A utility method to duplicate an array, so we end up with a deep copy * rather than a linked copy. There's a bunch of ways of doing this, I'm gunna * do it this way :) * @param {Array} lines The lines (or array of lines to duplicate) * @returns {Array} The duplicated lines */ duplicate: (lines) => { if (!Array.isArray(lines)) lines = [lines] const newLines = [] lines.forEach((line) => { const newLine = new Line(parseInt(line.zIndex)) const points = line.getPoints() points.forEach((p) => { newLine.addPoint(p.x, p.y, p.z) }) newLines.push(newLine) }) return newLines }, cleanLines: (lines) => { const keepLines = [] const wasArray = Array.isArray(lines) if (!Array.isArray(lines)) lines = [lines] // Go through each line lines.forEach((line) => { const points = line.getPoints() const minDist = 0.01 // This is going to keep track of the points we want to keep const newPoints = [] // grab the first point let previousPoint = points.shift() newPoints.push(previousPoint) while (points.length) { // grab the next point const checkPoint = points.shift() // work out the distance const xs = checkPoint.x - previousPoint.x const ys = checkPoint.y - previousPoint.y const zs = checkPoint.z - previousPoint.z const dist = page.rounding(Math.cbrt(Math.abs(xs) + Math.abs(ys) + Math.abs(zs))) // if the distance is greater then the minimum allowed, we keep the point if (dist >= minDist) { // Keep the point newPoints.push(checkPoint) // set the previous point to the one we just had previousPoint = checkPoint } } // Set the points back into the line line.points = newPoints if (line.points.length > 1) keepLines.push(line) }) if (!wasArray) return keepLines[0] return keepLines }, /** * A utility function to remove duplicate lines * NOTE: This doesn't work!!! * TODO: Make it work * @param {(Array|object)} lines An array of {@link Line} objects, or a single {@link Line} object * @returns {array} A sorted array of point objects */ dedupe: (lines) => { const keepLines = [] if (!Array.isArray(lines)) lines = [lines] lines.forEach((line) => { const points = line.getPoints() const x1 = page.rounding(points[0].x) const y1 = page.rounding(points[0].y) const z1 = page.rounding(points[0].z) const x2 = page.rounding(points[points.length - 1].x) const y2 = page.rounding(points[points.length - 1].y) const z2 = page.rounding(points[points.length - 1].z) const xs = x2 - x1 const ys = y2 - y1 const zs = z2 - z1 const dist = page.rounding(Math.cbrt(Math.abs(xs) + Math.abs(ys) + Math.abs(zs))) line.dist = dist if (dist > 0.01) { const pointsString = JSON.stringify(points) line.hash = pointsString line.reverseHash = JSON.stringify(points.reverse()) keepLines.push(line) } }) const reallyKeepLines = [] while (keepLines.length > 0) { const checkLine = keepLines.pop() let hasMatch = false // Now go through all the rest of them if (keepLines.length > 0) { keepLines.forEach((check) => { if (checkLine.hash === check.hash || checkLine.hash === check.reverseHash) { hasMatch = true } }) } if (hasMatch === false) reallyKeepLines.push(checkLine) } return reallyKeepLines }, /** * A utility method that will return a circle, well, technically a * polygon based on the number of segments and radius. The zIndex is * also set here. The polygon returned is centered on 0,0. * @param {number} segments The number of segments in the circle * @param {number} radius The radius of the polygon * @param {number} zIndex The zIndex to be applied to the returned {@link Line} * @returns {Array} Returns an Array containing a single {@link Line} object */ makeCircle: (segments, radius, zIndex) => { const circle = new Line(zIndex) const angle = 360 / segments for (let s = 0; s <= segments; s++) { const adjustedAngle = ((angle * s) * Math.PI / 180) const x = page.rounding(Math.cos(adjustedAngle) * radius) const y = page.rounding(Math.sin(adjustedAngle) * radius) circle.addPoint(x, y) } return [circle] }, /** * Crazy 3D stuff here */ // Blah blah, lazy rotate rotatePoint: (point, values) => { const radmod = Math.PI / 180 const newPoint = { x: 0, y: 0, z: 0 } const newValues = {} newValues.x = values.x * radmod newValues.y = values.y * radmod newValues.z = values.z * radmod newPoint.x = point.x newPoint.y = point.y * Math.cos(newValues.x) - point.z * Math.sin(newValues.x) // rotate about X newPoint.z = point.y * Math.sin(newValues.x) + point.z * Math.cos(newValues.x) // rotate about X point.x = parseFloat(newPoint.x) point.z = parseFloat(newPoint.z) newPoint.x = point.z * Math.sin(newValues.y) + point.x * Math.cos(newValues.y) // rotate about Y newPoint.z = point.z * Math.cos(newValues.y) - point.x * Math.sin(newValues.y) // rotate about Y point.x = parseFloat(newPoint.x) point.y = parseFloat(newPoint.y) newPoint.x = point.x * Math.cos(newValues.z) - point.y * Math.sin(newValues.z) // rotate about Z newPoint.y = point.x * Math.sin(newValues.z) + point.y * Math.cos(newValues.z) // rotate about Z return newPoint }, // Convert a point from 3D to 2D projectPoint: (point, perspective) => { const f = 1 + (point.z / (perspective * perspective)) const newPoint = { x: (point.x * f), y: (point.y * f), z: 0 } // send the point back return newPoint }, // Optimise the draw order of the lines optimise: (lines, threshold) => { let paths = lines.map((line) => line.points) let finalPaths = [] let keepGoing = true while (keepGoing) { finalPaths = [] let foundNewJoin = false while (paths.length >= 1) { // Grab the first path const firstPath = paths.shift() const endPoint = firstPath[firstPath.length - 1] // This is where we are going to keep the merge path let mergePath = null // This is where we are going to keep the rest of them let rejectPaths = [] /* Now we are going to go through all the paths, looking to see if the END POINT of the first path, matches any of the FIRST POINTS of the other paths. If it does, then we keep the marge path, and put the rest into the rejects */ const x1 = endPoint.x const y1 = endPoint.y paths.forEach((p) => { const x2 = p[0].x const y2 = p[0].y const dist = Math.sqrt(Math.pow(Math.abs(x1 - x2), 2) + Math.pow(Math.abs(y1 - y2), 2)) if (dist <= threshold && !mergePath) { mergePath = p foundNewJoin = true } else { rejectPaths.push(p) } }) // If we didn't find a mergePath then go again but with all the paths reversed if (!mergePath) { rejectPaths = [] paths = paths.map((p) => p.reverse()) paths.forEach((p) => { const x2 = p[0].x const y2 = p[0].y const dist = Math.sqrt(Math.pow(Math.abs(x1 - x2), 2) + Math.pow(Math.abs(y1 - y2), 2)) if (dist <= threshold && !mergePath) { mergePath = p foundNewJoin = true } else { rejectPaths.push(p) } }) } // If we have a path to merge, then stick them together and put them back in the stack // so they can go around again, if there was still nothing to merge then we put the // path into the finalPaths, where it will live and not get checked again if (mergePath) { // remove the last entry from the first path firstPath.pop() // Now put it back into the array of rejected paths, so it can go around again rejectPaths.push([...firstPath, ...mergePath]) } else { // If there was nothing to merge, put it on the finalPaths instead, so we can // remove it all from future checking finalPaths.push(firstPath) } paths = rejectPaths } // If we didn't find a new join, then we can stop if (!foundNewJoin) { keepGoing = false } else { paths = finalPaths finalPaths = [] } } return finalPaths.map((points) => { const line = new Line(0) line.points = points return line }) }, /** * The method to convert a {@link Line} or an array of {@link Line}s into SVG markup. * @param {(Array|object)} lines An array of {@link Line} objects, or a single {@link Line} object * @param {string} id The id to name the layer. NOTE: we don't actually name the layer (that would be a TODO:) * @returns {string} The string representation of the SVG */ svg: (lines, id, strokeWidth = 1.0) => { if (!Array.isArray(lines)) lines = [lines] let output = ` <g> <path d="` lines.forEach((line) => { const points = line.getPoints() output += `M ${page.rounding(page.rounding(points[0].x) * 0.393701 * page.dpi)} ${page.rounding(page.rounding(points[0].y) * 0.393701 * page.dpi)} ` for (let p = 1; p < points.length; p++) { output += `L ${page.rounding(page.rounding(points[p].x) * 0.393701 * page.dpi)} ${page.rounding(page.rounding(points[p].y) * 0.393701 * page.dpi)} ` } }) output += `" fill="none" stroke="black" stroke-width="${strokeWidth}"/> </g>` return output }, /** * Take an svg or an array of svgs and wraps them in the XML needed to export an SVG file * @param {(Array|string)} svgs An array of svgs strings, or a single svg string * @param {string} id A unique ID that we can use to reference this set of SVG files * @param {string} filename The filename (without the trailing '.svg') to save the file as, if we are going to save it * @returns {string} Returns the wrapped svgs string, into a final SVG formatted text chunk */ wrapSVG: (svgs, id = 'plot', filename) => { if (!Array.isArray(svgs)) svgs = [svgs] let output = `<?xml version="1.0" standalone="no" ?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" id="${id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0" y="0" viewBox="0 0 ${page.size[0] * 0.393701 * page.dpi} ${page.size[1] * 0.393701 * page.dpi}" width="${page.size[0]}cm" height="${page.size[1]}cm" xml:space="preserve">` svgs.forEach((svg) => { output += svg }) output += '</svg>' page.printStore[id] = { output, filename } return page.printStore[id].output }, /** * Function to "print" i.e. save the files down onto disk * @param {string} id The id of the layer to print */ print: (id) => { if (page.printStore[id]) { page.download(`${page.printStore[id].filename}.svg`, page.printStore[id].output) console.log('Try using the following commands to optimise, start and resume plotting') console.log(`svgsort ${page.printStore[id].filename}.svg ${page.printStore[id].filename}-opt.svg --no-adjust`) console.log(`axicli ${page.printStore[id].filename}-opt.svg --model 2 -o progress01.svg -s 30 --report_time`) console.log('axicli progress01.svg --model 2 -o progress02.svg -s 30 --report_time --mode res_plot') } }, /** * Utility function to force the downloading of the text file, which is normally our SVG file * @param {string} filename The filename of the downloaded document * @param {string} text The text content of the files we want downloaded (normall the wrapped SVG) */ download: (filename, text) => { const element = document.createElement('a') element.setAttribute('download', filename) element.style.display = 'none' document.body.appendChild(element) // Blob code via gec @3Dgec https://twitter.com/3Dgec/status/1226018489862967297 element.setAttribute('href', window.URL.createObjectURL(new Blob([text], { type: 'text/plain;charset=utf-8' }))) element.click() document.body.removeChild(element) } }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import {ProductAddComponent} from "./pages/product/product-add/product-add.component"; import {ProductListComponent} from "./pages/product/product-list/product-list.component"; import {ProductGroupAddComponent} from "./pages/product-group/product-group-add/product-group-add.component"; import {ProductGroupListComponent} from "./pages/product-group/product-group-list/product-group-list.component"; import {ProductEditComponent} from "./pages/product/product-edit/product-edit.component"; import {ProductGroupEditComponent} from "./pages/product-group/product-group-edit/product-group-edit.component"; import {CustomerAddComponent} from "./pages/customer/customer-add/customer-add.component"; import {CustomerEditComponent} from "./pages/customer/customer-edit/customer-edit.component"; import {CustomerListComponent} from "./pages/customer/customer-list/customer-list.component"; const routes: Routes = [ { path: 'product/add', component: ProductAddComponent, }, { path: 'product/edit/:id', component: ProductEditComponent, }, { path: 'product/list', component: ProductListComponent, }, { path: "product-group/add", component: ProductGroupAddComponent, }, { path:"product-group/edit/:id", component: ProductGroupEditComponent, }, { path: "product-group/list", component: ProductGroupListComponent, }, { path: "customer/add", component: CustomerAddComponent }, { path: "customer/edit/:id", component: CustomerEditComponent }, { path: "customer/list", component: CustomerListComponent }, { path :'**', redirectTo: 'product/list' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
import React, { useContext, useRef } from "react"; import "./Loginv.css"; import Reg from "../../lottie/Log" import { loginCall } from "../../apiCalls"; import { AuthContext } from "../../context/AuthContext"; import { CircularProgress } from "@material-ui/core"; import { useNavigate } from "react-router-dom"; import { Navigate } from "react-router-dom"; export default function Login() { const email = useRef(); const password = useRef(); const navigate = useNavigate(); const { user, isFetching, error, dispatch } = useContext(AuthContext) const handleClick = (e) =>{ e.preventDefault(); loginCall({email: email.current.value, password: password.current.value}, dispatch) } console.log(user) return ( <div className="login"> <div className="loginWrapper" style={{padding:"20px",border:"1px solid white"}}> <div className="loginLeft"> <h2 className="loginLogo">VConnect</h2> <Reg/> <span className="loginDesc" style={{color:"white",textAlign:"center"}}> VConnect you to the world🌐 </span> <h3 style={{color:"white",marginTop:"15px",textAlign:"center"}}>Login Here ➡️</h3> </div> <div className="loginRight"> <form className="loginBox" onSubmit={handleClick}> <input placeholder="Email" type="email" className="loginInput" ref={email} /> <input placeholder="Password" type="password" className="loginInput" ref={password} /> <button className="loginButton" disabled={isFetching}>{isFetching ? <CircularProgress size="25px" /> : "Log In"}</button> <span className="loginForgot">Forgot Password?</span> <button className="loginRegisterButton"> {isFetching ? <CircularProgress size="25px" /> : "Create An Account"} </button> </form> </div> </div> </div> ); }
import { StyleSheet, Text, View, Button, Pressable } from 'react-native' import React from 'react' import PressableButton from './PressableButton'; import { EvilIcons } from '@expo/vector-icons'; export default function GoalItem({ goalObj, deleteFunction, detailFunction }) { function deleteHandler() { deleteFunction(goalObj.id); } return ( <View> <Pressable style={({pressed}) => [styles.textContainer, pressed && styles.pressed]} onPress={() => detailFunction(goalObj)} android_ripple={{color:"#e9e"}}> <Text style={styles.text}>{goalObj.text}</Text> <View style={styles.buttonContainer}> {/* <Button color={"black"} title='X' onPress={deleteHandler}/> */} <PressableButton customStyle={styles.deleteButton} onPressFunction={deleteHandler}> <EvilIcons name="trash" size={36} color="black" /> </PressableButton> </View> </Pressable> </View> ) } const styles = StyleSheet.create({ pressed: { opacity: 0.5, backgroundColor: 'yellow', }, text: { textAlign: 'center', fontSize: 30, color: '#929', padding: 5, margin: 5, }, textContainer: { borderRadius: 10, backgroundColor: '#aaa', marginTop: 35, flexDirection: 'row', justifyContent: 'center', }, buttonContainer: { alignItems: 'center', justifyContent: 'center', }, deleteButton: { borderRadius: 5, } })
import {AxiosRequestConfig, AxiosPromise, AxiosResponse} from './types/index' import {parseHeaders} from './helpers/headers' import {createError} from './helpers/error' import { readSync } from 'fs'; export default function xhr(config: AxiosRequestConfig):AxiosPromise { return new Promise((resolve, reject) => { const {data = null, url, method = 'get', headers, responseType, timeout, cancelToken} = config; const request = new XMLHttpRequest(); if (responseType) { request.responseType = responseType } request.open(method.toUpperCase(), url!, true); if (timeout) { request.timeout = timeout } request.onerror = function handleError() { reject(createError('Network Error', config, null, request)) } request.ontimeout = function handleTimeout() { reject(createError(`Timeout of ${timeout} ms exceeded`, config, 'ECONNABORTED', request)) } request.onreadystatechange = function handleChange() { if (request.readyState !== 4) { return } if (request.status === 0) { return } const responseHeaders = parseHeaders(request.getAllResponseHeaders()) const responseData = responseType !== 'text' ? request.response : request.responseText const response:AxiosResponse = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config, request } handleResponse(response) } Object.keys(headers).forEach((name) => { if (data === null && name.toLowerCase() === 'content-type') { delete headers[name] } else { request.setRequestHeader(name, headers[name]) } }) if (cancelToken) { cancelToken.promise.then(reason => { request.abort() reject(reason) }) } request.send(data); function handleResponse(response: AxiosResponse):void { if (response.status >= 200 && response.status <= 300 ) { resolve(response) } else { reject(createError(`request failed with ${response.status}`, config, null, request, response)) } } }) }
namespace Moulding.Domain.MouldCards; /// <summary> /// Mould card entity class /// </summary> public class MouldCard { public MouldCardId Id { get; private set; } public MouldingMachineId MouldingMachineId { get; private set; } public int CycleTimeInSeconds { get; private set; } public int InjectionTimeInSeconds { get; private set; } public double InletTemperatureInCelcius { get; private set; } public PressureValue Airflow { get; private set; } public PressureValue Waterflow { get; private set; } /// <summary> /// Create an instance of the mould card entity. /// Should be used when generating new mould cards. /// </summary> /// <param name="mouldingMachineId">The ID of the moulding machine the card is associated with</param> /// <param name="cycleTimeInSeconds">The time it takes to complete a moulding process for a mould, measured in seconds</param> /// <param name="injecetionTimeInSeconds">The time used to fill the mould with material, measured in seconds</param> /// <param name="inletTemperatureInCelcius">The temperature at the inlet where materials flow through, measured in Celsius</param> /// <param name="airflow">The pressure of the airflow to cool down the mould, measured in psi or bar</param> /// <param name="waterflow">The pressure of the waterflow to cool down the mould, measured in psi or bar</param> public MouldCard( MouldingMachineId mouldingMachineId, int cycleTimeInSeconds, int injecetionTimeInSeconds, double inletTemperatureInCelcius, PressureValue airflow, PressureValue waterflow ) { Id = new MouldCardId(); MouldingMachineId = mouldingMachineId; CycleTimeInSeconds = cycleTimeInSeconds; InjectionTimeInSeconds = injecetionTimeInSeconds; InletTemperatureInCelcius = inletTemperatureInCelcius; Airflow = airflow; Waterflow = waterflow; } /// <summary> /// Create an instance of the mould card entity. /// Should be used when recreating existing mould cards. /// </summary> /// <param name="mouldCardId">The ID of the mould card</param> /// <param name="mouldingMachineId">The ID of the moulding machine the card is associated with</param> /// <param name="cycleTimeInSeconds">The time it takes to complete a moulding process for a mould, measured in seconds</param> /// <param name="injecetionTimeInSeconds">The time used to fill the mould with material, measured in seconds</param> /// <param name="inletTemperatureInCelcius">The temperature at the inlet where materials flow through, measured in Celsius</param> /// <param name="airflow">The pressure of the airflow to cool down the mould, measured in psi or bar</param> /// <param name="waterflow">The pressure of the waterflow to cool down the mould, measured in psi or bar</param> public MouldCard( MouldCardId mouldCardId, MouldingMachineId mouldingMachineId, int cycleTimeInSeconds, int injectionTimeInSeconds, double inletTemperatureInCelcius, PressureValue airflow, PressureValue waterflow ) { Id = mouldCardId; MouldingMachineId = mouldingMachineId; CycleTimeInSeconds = cycleTimeInSeconds; InjectionTimeInSeconds = injectionTimeInSeconds; InletTemperatureInCelcius = inletTemperatureInCelcius; Airflow = airflow; Waterflow = waterflow; } }
package de.telran.g_280323_m_be_shop.domain.entity.jpa; import de.telran.g_280323_m_be_shop.domain.entity.interfaces.Customer; import jakarta.persistence.*; import jakarta.validation.constraints.*; import org.hibernate.validator.constraints.UniqueElements; @Entity @Table(name="customer") public class JpaCustomer implements Customer { @Id @GeneratedValue (strategy= GenerationType.IDENTITY) @Column(name="customer_id") private int id; @Column(name="name") @Pattern(regexp="[A-Z][a-z]+") private String name; @Column(name="email") @Email private String email; @Column(name="age") @Min(14) @Max(110) private int age; @OneToOne(mappedBy="customer", cascade=CascadeType.REMOVE) private JpaCart cart; public JpaCustomer() { } public JpaCustomer(int id, String name) { this.id=id; this.name=name; } public JpaCustomer(int id, String name, String email, int age) { this.id=id; this.name=name; this.email=email; this.age=age; } @Override public int getId() { return id; } public void setId(int id) { this.id=id; } @Override public String getName() { return name; } public void setName(String name) { this.name=name; } @Override public String getEMail() { return email; } @Override public int getAge() { return age; } @Override public JpaCart getCart() { return cart; } public void setCart(JpaCart cart) { this.cart=cart; } }
--- title: HashMap源码解析 date: 2021/3/27 description: HashMap源码解析 top_img: https://fabian.oss-cn-hangzhou.aliyuncs.com/img/LuciolaCruciata_ZH-CN9063767400_1920x1080.jpg cover: https://fabian.oss-cn-hangzhou.aliyuncs.com/img/LuciolaCruciata_ZH-CN9063767400_1920x1080.jpg categories: - jdk源码 tags: - java - 源码 - jdk - HashMap abbrlink: 14375 --- # HashMap源码解析 作为面试必问的hashmap,我们今天来一起来探究一下他的源码。这里先贴一张 hashmap 的内部类和部分方法函数 <img src="https://fabian.oss-cn-hangzhou.aliyuncs.com/img/image-20210921204040629.png" alt="image-20210921204040629" style="zoom: 67%;" /> ## 一、什么是 哈希, 哈希函数(散列函数) > Hash,一般翻译做散列、杂凑,或音译为哈希,是把任意长度的[输入](https://baike.baidu.com/item/输入/5481954)(又叫做预映射pre-image)通过散列算法变换成固定长度的[输出](https://baike.baidu.com/item/输出/11056752),该输出就是散列值。这种转换是一种[压缩映射](https://baike.baidu.com/item/压缩映射/5114126),也就是,散列值的空间通常远小于输入的空间,不同的输入可能会散列成相同的输出,所以不可能从散列值来确定唯一的输入值。简单的说就是一种将任意长度的消息压缩到某一固定长度的[消息摘要](https://baike.baidu.com/item/消息摘要/4547744)的函数。 上面是百度百科的解释。我们可以简单的概括为 - hash 就是将 **任意的输入** 通过 一种 **特殊的算法** 变成 **长度固定** 的输出。 - 可以类似于一种摘要算法,获取我们输入内容的特征来生成一个简短的摘要 - 由于算法可以保证:相同的输入每次都是可以得到相同的输出,即hash值 - 但是也会发生:不同的输入哈希之后会得到相同的结果 **即 哈希冲突** ### object 中的 hashcode 方法 ~~~java public native int hashCode(); ~~~ 方法本身是 native 方法,调用了底层的的类库,根据注释: hashCode 遵守着如下的约定: - Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. - If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. - It is not required that if two objects are unequal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables. 翻译一下就是 - 在程序一次执行的过程中,无论何时被调用,这个方法都会返回相同的值。但是程序的多次执行就不能保证每一次都相等 - 如果两个对象的 equals 方法返回 true,那么他们调用此方法就一定返回相同的结果 - 当然也不一定要确保:两个对象如果根据重写的 equals 方法返回为 false,那么此方法的返回结果一定不同。 > 即:两个对象 根据重写的equals判断为不相等,此时的 hashcode 也可以相同 > > 不过我们在写程序时应该注意尽量是不同的对象返回不同的hashcode,以便加强哈希效率,避免哈希冲突 ### hashmap 采用的哈希方法 ~~~java static final int hash(Object key) { int h; // 这里当 key 不为 null 的时候,将key的哈希值 和 右移16位的哈希值 做异或运算 return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } ~~~ ![image-20210924132832294](https://fabian.oss-cn-hangzhou.aliyuncs.com/img/image-20210924132832294.png) 将h无符号右移16为相当于将高区16位移动到了低区的16位,再与原hashcode做异或运算,可以**将高低位二进制特征混合起来**。即**哈希扰动**。 从上文可知高区的16位与原hashcode相比没有发生变化,低区的16位发生了变化。 我们都知道重新计算出的新哈希值在后面将会参与hashmap中数组槽位的计算,计算公式:(n - 1) & hash,假如这时数组槽位有16个,则槽位计算如下: ![image-20210924133141544](https://fabian.oss-cn-hangzhou.aliyuncs.com/img/image-20210924133141544.png) **高区的16位很有可能会被数组槽位数的二进制码屏蔽,如果我们不做刚才移位异或运算,那么在计算槽位时将丢失高区特征** 也许你可能会说,即使丢失了高区特征不同hashcode也可以计算出不同的槽位来,但是细想当两个哈希码很接近时,那么这高区的一点点差异就**可能导致一次哈希碰撞**,所以这也是将性能做到极致的一种体现 ### 取余 % 和位运算 & 我们看到源码中存放值的时候:`(n - 1) & hash` 一般来说我们的认为都是将 哈希值 和数组的长度进行取模运算来获得数组的下标 - 那么这里主要考虑到的是:**位运算相比取模运算效率更高** 关于为什么位运算能代替取模运算可以参考这个 👉[**由HashMap哈希算法引出的求余%和与运算&转换问题**](https://www.cnblogs.com/ysocean/p/9054804.html) > **当 lenth = 2n 时,X % length = X & (length - 1)** > > - 也就是说,长度为2的n次幂时,模运算 % 可以变换为按位与 & 运算。 > >   比如:9 % 4 = 1,9的二进制是 1001 ,4-1 = 3,3的二进制是 0011。 9 & 3 = 1001 & 0011 = 0001 = 1 > >   再比如:12 % 8 = 4,12的二进制是 1100,8-1 = 7,7的二进制是 0111。12 & 7 = 1100 & 0111 = 0100 = 4 > > - 上面两个例子4和8都是2的n次幂,结论是成立的,那么当长度不为2的n次幂呢? > >   比如:9 % 5 = 4,9的二进制是 1001,5-1 = 4,4的二进制是0100。9 & 4 = 1001 & 0100 = 0000 = 0。显然是不成立的。 ## 二、存储方式和数据结构 > 问:HashMap的底层数据结构是什么 > > 答:数组+链表+红黑树 ![image-20210924142231035](https://fabian.oss-cn-hangzhou.aliyuncs.com/img/image-20210924142231035.png) 从上面的图中我们可以看出hashmap的存储结构,默认是数组+链表的结构。 当**链表的长度大于 8 (默认)** 的时候,链表会转换为红黑树。 - node 的数组 ~~~java /** * The table, initialized on first use, and resized as * necessary. When allocated, length is always a power of two. * (We also tolerate length zero in some operations to allow * bootstrapping mechanics that are currently not needed.) */ transient Node<K,V>[] table; ~~~ - node 结点 ~~~java /** * Basic hash bin node, used for most entries. (See below for * TreeNode subclass, and in LinkedHashMap for its Entry subclass.) */ static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; Node<K,V> next; Node(int hash, K key, V value, Node<K,V> next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } public final K getKey() { return key; } public final V getValue() { return value; } public final String toString() { return key + "=" + value; } /** * node结点的哈希值:将 key 的哈希值和 value 的哈希值进行异或运算 */ public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); } public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } public final boolean equals(Object o) { if (o == this) return true; if (o instanceof Map.Entry) { Map.Entry<?,?> e = (Map.Entry<?,?>)o; if (Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue())) return true; } return false; } } ~~~ - treenode 结点 ~~~java /** * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn * extends Node) so can be used as extension of either regular or * linked node. */ static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> { TreeNode<K,V> parent; // red-black tree links TreeNode<K,V> left; TreeNode<K,V> right; TreeNode<K,V> prev; // needed to unlink next upon deletion boolean red; TreeNode(int hash, K key, V val, Node<K,V> next) { super(hash, key, val, next); } } ~~~ > Hashmap中的链表大小超过八个时会自动转化为红黑树,当删除小于六时重新变为链表 ## 三、构造方法和初始化 ```java /** * Constructs an empty <tt>HashMap</tt> with the specified initial * capacity and load factor. * * @param initialCapacity the initial capacity * @param loadFactor the load factor * @throws IllegalArgumentException if the initial capacity is negative * or the load factor is nonpositive */ public HashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor; this.threshold = tableSizeFor(initialCapacity); } ``` 这个是最后被调用的构造方法,本质上就是先给 hashmap 初始两个值:**initialCapacity** 和 **loadFactor**:即初始容量和负载因子 ### 1. 初始容量 initialCapacity ```java /** * 获取 比 cap 大的最小的二进制数 * Returns a power of two size for the given target capacity. */ static final int tableSizeFor(int cap) { // 避免 输入为2的幂时 返回了 cap * 2 int n = cap - 1; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; } ``` 这里我们以输入 9 为例 1. n = cap - 1; **这里如果直接没有 -1 操作,如果输入的为2的幂,补1之后再+1,就不会返回原值而是 cap*2** n = 00000000 00000000 00000000 00001000 2. n |= n >>> 1 00000000 00000000 00000000 00001000 n 00000000 00000000 00000000 00000100 n >>> 1 00000000 00000000 00000000 00001100 => n 3. n |= n >>> 2 00000000 00000000 00000000 00001101 n 00000000 00000000 00000000 00000011 n >>> 2 00000000 00000000 00000000 00001111 => n 4. 后续操作使得后续全为一 5. 最后检查 大于零且小于最大值,将结果加一返回:16 ### 2. 负载因子 loadFactor ```java /** * The load factor used when none specified in constructor. * 这里我们可以看到 jdk 默认的负载因子为 0.75。当初始化未指定时就采用此值。 */ static final float DEFAULT_LOAD_FACTOR = 0.75f; ``` 这个值和我们hashmap的扩容有关:**比如说当前的容器容量是16,负载因子是0.75,16\*0.75=12,也就是说,当容量达到了12的时候就会进行扩容操作** 此处我们可以从时间和空间的角度来考虑: - **当负载因子的值为 1** - 此时只有当 node 数组被填满时才会进行扩容 - 既然哈希碰撞是不可避免的,那么此时底层的红黑树结构就会变得异常复杂,明显会降低查询效率 - 时间换空间 - **当负载因子的值为 0.5** - 此时当 node 数组被填充超过一半就会进行扩容 - 那么虽然可以降低底层红黑树的结构提高查找效率,也无疑牺牲了一半的存储空间 - 空间换时间 所以 0.75 的选择可以说是空间和时间的权衡。但最后的 0.75 也并不是简单的 0.5 和 1 的折中。 根据源码的注释,里面涉及到一些统计学方面的泊松分布的计算,这里就不展开细说了。 ```java /** * Ideally, under random hashCodes, the frequency of * nodes in bins follows a Poisson distribution * (http://en.wikipedia.org/wiki/Poisson_distribution) with a * parameter of about 0.5 on average for the default resizing * threshold of 0.75, although with a large variance because of * resizing granularity. Ignoring variance, the expected * occurrences of list size k are (exp(-0.5) * pow(0.5, k) / * factorial(k)). The first values are: * * 0: 0.60653066 * 1: 0.30326533 * 2: 0.07581633 * 3: 0.01263606 * 4: 0.00157952 * 5: 0.00015795 * 6: 0.00001316 * 7: 0.00000094 * 8: 0.00000006 * more: less than 1 in ten million */ ``` ## 四、添加元素和查找元素 ### 1. put 方法 ```java /** * Associates the specified value with the specified key in this map. * If the map previously contained a mapping for the key, the old * value is replaced. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt>. * (A <tt>null</tt> return can also indicate that the map * previously associated <tt>null</tt> with <tt>key</tt>.) */ public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } ``` **这里贴一张流程图并且附上加了注释的源码** ![image-20210927232504843](https://fabian.oss-cn-hangzhou.aliyuncs.com/img/image-20210927232504843.png) ```java /** * Implements Map.put and related methods. * * @param hash 密钥的散列 * @param key 键值 * @param value 要放置的值 * @param onlyIfAbsent 如果为真,则不更改现有值 * @param evict 如果为 false,则表处于创建模式。 * @return 以前的值,如果没有,则为 null */ final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; // table数组为空或者长度为零则 调用 resize() 来初始化数组 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; // 计算数组下标,如果结点为空则新建结点放入 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; // 如果和头节点哈希值相等,则直接命中头节点 if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; // 如果是树节点进行红黑树的操作 else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); // 剩下的就是链表节点操作 else { for (int binCount = 0; ; ++binCount) { // 走到尾结点则新建节点追加在后面 if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); // 如果链表长度超过阈值则转化为红黑树 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } // 当未走到尾结点时,根据哈希值是否相等来判断是否命中 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } if (e != null) { // existing mapping for key V oldValue = e.value; // 根据标识位判断是否替换 if (!onlyIfAbsent || oldValue == null) e.value = value; // 提供给 LinkedHashMap 的回调 afterNodeAccess(e); return oldValue; } } // 更新修改次数来保证迭代器的快速失败机制 ++modCount; // 超过阈值就扩容 if (++size > threshold) resize(); // 提供给 LinkedHashMap 的回调 afterNodeInsertion(evict); return null; } ``` ### 2. get 方法 和 containsKey 方法 ```java public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; } ``` ```java public boolean containsKey(Object key) { return getNode(hash(key), key) != null; } ``` > 这里我们可以看到底层都是调用了 `getNode()`这个方法通过哈希值和键值去搜索结点 > > `containsKey`:如果找到结点则返回 true,否则返回 false > > `get`:如果找到结点返回结点的 value 值,否则返回 null > > - 不过要注意的是,这里如果返回了 null 可能有**两种原因**: > 1. **key 不存在** > 2. **key 存在,但是存储的结果为 null** ```java final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { // 先对头节点做判断 if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { // 如果是红黑树结点 if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); // 最后遍历链表 do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; } ``` ## 五、扩容和rehash 这里我们先上`resize()`函数的源码 ```java final Node<K,V>[] resize() { Node<K,V>[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length; int oldThr = threshold; int newCap, newThr = 0; // 当原结构有数据的时候 if (oldCap > 0) { // 如果之前的容量大于最大容量,即将阈值调整到最大并不再扩容 if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } // 当新容量小于最大容量 旧容量大于默认初始值时,对阈值 double else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold } // 如果一开始给定了初始容量,就取初始化时的值 else if (oldThr > 0) // initial capacity was placed in threshold newCap = oldThr; // 最后采取默认值 else { // zero initial threshold signifies using defaults newCap = DEFAULT_INITIAL_CAPACITY; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } // 通过最大容量和负载因子计算阈值 if (newThr == 0) { float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } threshold = newThr; // 根据 newCap 创建新的数组 @SuppressWarnings({"rawtypes","unchecked"}) Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; table = newTab; // 如果不为空,搬运之前map的存储内容,遍历每一个数组 if (oldTab != null) { for (int j = 0; j < oldCap; ++j) { Node<K,V> e; if ((e = oldTab[j]) != null) { oldTab[j] = null; if (e.next == null) newTab[e.hash & (newCap - 1)] = e; else if (e instanceof TreeNode) ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { // preserve order // 将链表分成两个组,根据哈希值一部分留在原来数组位置,一部分向前 oldCap Node<K,V> loHead = null, loTail = null; Node<K,V> hiHead = null, hiTail = null; Node<K,V> next; do { next = e.next; if ((e.hash & oldCap) == 0) { if (loTail == null) loHead = e; else loTail.next = e; loTail = e; } else { if (hiTail == null) hiHead = e; else hiTail.next = e; hiTail = e; } } while ((e = next) != null); if (loTail != null) { loTail.next = null; newTab[j] = loHead; } if (hiTail != null) { hiTail.next = null; newTab[j + oldCap] = hiHead; } } } } } return newTab; } ``` 这个函数一般提供两个功能: - 在构造函数之后,第一次`put()`发现数组为空则会调用,实现懒加载 - 当存储的数据超过阈值时调用,来实现扩容 **经过rehash之后,元素的位置要么是在原位置,要么是在原位置再移动2次幂的位置** ![image-20210929231418128](https://fabian.oss-cn-hangzhou.aliyuncs.com/img/image-20210929231418128.png) ![image-20210929231439803](https://fabian.oss-cn-hangzhou.aliyuncs.com/img/image-20210929231439803.png) ![image-20210929231504675](https://fabian.oss-cn-hangzhou.aliyuncs.com/img/image-20210929231504675.png) > - 扩容是一个特别耗性能的操作,所以当程序员在使用HashMap的时候,估算map的大小,初始化的时候给一个大致的数值,避免map进行频繁的扩容。 > > - 负载因子是可以修改的,也可以大于1,但是建议不要轻易修改,除非情况非常特殊。 ## 六、头插法和尾插法 > JDK8以前是头插法,JDK8后是尾插法 头插法和尾插法,顾名思义就是插入链表的时候插入在链表头部还是尾部。 **由于`HashMap`在扩容时采用头插法会造成链表死循环,故在JDK8之后调整为尾插法**。 这里贴一个别人的分析 - 前提条件: 1. hash算法为简单的用key mod链表的大小。 2. 最开始hash表size=2,key=3,7,5,则都在table[1]中。 3. 然后进行resize,使size变成4。 4. 未resize前的数据结构如下: ![Image](https://mmbiz.qpic.cn/mmbiz_png/JdLkEI9sZfecWQvk4vhdQnUBzictjvKTV8KojY8VrMVmMVK0mT4Ric2icyc3icUzVuQCuLGpzOgZxOeHd8MgfgNuXQ/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1) 如果在单线程环境下,最后的结果如下: ![Image](https://mmbiz.qpic.cn/mmbiz_png/JdLkEI9sZfecWQvk4vhdQnUBzictjvKTVCB9USBX1WYQPWzj7iciaTjlyHZpq2MlWRasFGPLvXEM1zf0tiaictibYSsg/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1) 这里的转移过程,不再进行详述,只要理解transfer函数在做什么,其转移过程以及如何对链表进行反转应该不难。 然后在多线程环境下,假设有两个线程A和B都在进行put操作。线程A在执行到transfer函数中第11行代码处挂起,因为该函数在这里分析的地位非常重要,因此再次贴出来。 ![Image](https://mmbiz.qpic.cn/mmbiz_png/JdLkEI9sZfecWQvk4vhdQnUBzictjvKTVRtdI81vOOgiayBNwiaru5saibodJiaUAxBsic9Clib8qu2SZWQd6MlokUF9g/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1) 此时线程A中运行结果如下: ![Image](https://mmbiz.qpic.cn/mmbiz_png/JdLkEI9sZfecWQvk4vhdQnUBzictjvKTVCrq6iaOLPVE0kE1zgCQYmWKTUPBGAm1icoUUR8ADvhUwTLoQ0jZzBr1g/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1) 线程A挂起后,此时线程B正常执行,并完成resize操作,结果如下: ![Image](https://mmbiz.qpic.cn/mmbiz_png/JdLkEI9sZfecWQvk4vhdQnUBzictjvKTVGWwiboVcEoovrdg7qUibUcwrLTuww3rbptiaFoZI11NaTj0tDAxybhwag/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1) **这里需要特别注意的点:由于线程B已经执行完毕,根据Java内存模型,现在newTable和table中的Entry都是主存中最新值:7.next=3,3.next=null。** 此时切换到线程A上,在线程A挂起时内存中值如下:e=3,next=7,newTable[3]=null,代码执行过程如下: ``` newTable[3]=e ----> newTable[3]=3 e=next ----> e=7 ``` 此时结果如下: ![Image](https://mmbiz.qpic.cn/mmbiz_png/JdLkEI9sZfecWQvk4vhdQnUBzictjvKTVSPJ6RwE1NHxILdUiaIFib3NHncYPI6hfE0NvKWKu0UANfsFsWPicWKOvA/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1) 继续循环: ``` e=7 next=e.next ----> next=3【从主存中取值】 e.next=newTable[3] ----> e.next=3【从主存中取值】 newTable[3]=e ----> newTable[3]=7 e=next ----> e=3 ``` 结果如下: ![Image](https://mmbiz.qpic.cn/mmbiz_png/JdLkEI9sZfecWQvk4vhdQnUBzictjvKTVlVDoSg5Kvo0maS6h9RNZVRd7sMsZtu5homM7KI9ibEk47WtJXibgXfcg/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1) 再次进行循环: ``` e=3 next=e.next ----> next=null e.next=newTable[3] ----> e.next=7 即:3.next=7 newTable[3]=e ----> newTable[3]=3 e=next ----> e=null ``` 注意此次循环:e.next=7,而在上次循环中7.next=3,出现环形链表,并且此时e=null循环结束。 结果如下: **![Image](https://mmbiz.qpic.cn/mmbiz_png/JdLkEI9sZfecWQvk4vhdQnUBzictjvKTVU7APPu5l0lKpFRwBS0KFISCE1h9iarAQnv7zpXz2k9DnZPIr2AWqhiaw/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1)** 在后续操作中只要涉及轮询hashmap的数据结构,就会在这里发生死循环,造成悲剧。
<?php namespace App\Http\Resources\Api\Orders; use App\Http\Resources\Api\Driver\DriverResource; use App\Http\Resources\Api\Offers\OfferResource; use App\Http\Resources\Api\Services\ServiceResource; use App\Http\Resources\Api\Users\UserResource; use App\Models\Employee; use App\Models\Service; use Carbon\Carbon; use Illuminate\Http\Resources\Json\JsonResource; class OrderItemResource extends JsonResource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable */ public function toArray($request) { return [ 'id' => $this->id, 'number' => $this->order_num, 'service'=> $this->Service ? [ 'id'=> $this->Service->id, 'name'=> $this->Service->name, 'image'=> asset('storage/' . $this->Service->main_image) , 'rate'=> '4.5' , 'category'=> $this->Service->Category->name , 'hotel'=> $this->Hotel ? $this->Hotel->name : null , 'distance'=>'212.2' ?? $this->getDistance($this->Hotel->lng , $this->Hotel->lat), ] : null , 'author_details' => [ 'author_name'=> $this->author_name, 'author_phone'=> $this->author_phone, 'author_email'=> $this->author_email, ] , 'book_date'=> $this->book_date, 'price'=> $this->price, 'created_at'=> $this->created_at->format('y-m-d') , ]; } public function getDistance($lng , $lat) { } }
import streamlit as st import pandas as pd import re from datetime import datetime from instagrapi import Client from instagrapi.exceptions import ( BadPassword, ChallengeRequired, FeedbackRequired, LoginRequired, PleaseWaitFewMinutes, RecaptchaChallengeForm, ReloginAttemptExceeded, SelectContactPointRecoveryForm, UserNotFound, ) from loguru import logger import os import time import random # Constants SESSION_DURATION = 86400 # 24 hours in seconds LOG_FILE = "app.log" # Configure Loguru logger.add(LOG_FILE, rotation="10 MB") # Define Account Class with Exception Handling class Account: def __init__(self, username, password): self.username = username self.password = password def get_client(self): def handle_exception(client, e): if isinstance(e, BadPassword): logger.error(f"Bad Password: {e}") client.set_proxy(client.next_proxy().href) if client.relogin_attempt > 0: self.freeze("Manual login required", days=7) raise ReloginAttemptExceeded(e) client.settings = client.rebuild_client_settings() return client.update_client_settings(client.get_settings()) elif isinstance(e, LoginRequired): logger.error(f"Login Required: {e}") client.relogin() return client.update_client_settings(client.get_settings()) elif isinstance(e, ChallengeRequired): api_path = client.last_json.get("challenge", {}).get("api_path") if api_path == "/challenge/": client.set_proxy(client.next_proxy().href) client.settings = client.rebuild_client_settings() else: try: client.challenge_resolve(client.last_json) except ChallengeRequired as e: self.freeze("Manual Challenge Required", days=2) raise e except (ChallengeRequired, SelectContactPointRecoveryForm, RecaptchaChallengeForm) as e: self.freeze(str(e), days=4) raise e client.update_client_settings(client.get_settings()) return True elif isinstance(e, FeedbackRequired): message = client.last_json["feedback_message"] logger.warning(f"Feedback Required: {message}") if "This action was blocked. Please try again later" in message: self.freeze(message, hours=12) elif "We restrict certain activity to protect our community" in message: self.freeze(message, hours=12) elif "Your account has been temporarily blocked" in message: self.freeze(message) elif isinstance(e, PleaseWaitFewMinutes): logger.warning(f"Please Wait: {e}") self.freeze(str(e), hours=1) raise e cl = Client() cl.handle_exception = handle_exception try: cl.login(self.username, self.password) except Exception as e: handle_exception(cl, e) return cl def freeze(self, message, hours=0, days=0): duration = hours * 3600 + days * 86400 logger.warning(f"Account frozen: {message} for {duration} seconds") # Helper Functions def is_session_valid(session_file): if os.path.exists(session_file): file_age = time.time() - os.path.getmtime(session_file) if file_age < SESSION_DURATION: return True return False def extract_ig_username(url): if isinstance(url, str): match = re.search(r"instagram\.com/([^/?]+)", url) return match.group(1) if match else None return None def extract_ig_usernames(text): lines = text.splitlines() usernames = [] for line in lines: parts = line.split() for part in parts: if 'instagram.com' in part: username = extract_ig_username(part) if username: usernames.append(username) elif 'IG:' in part: username = part.split('IG:')[-1].strip().replace('/', '') if username: usernames.append(username) elif re.match(r'^[\w.]+$', part.strip()): # For simple usernames not part of a URL usernames.append(part.strip()) return list(filter(None, usernames)) def count_posts_for_month(user_id, year, month, client): posts = client.user_medias(user_id, amount=1000) start_date = datetime(year, month, 1) end_date = datetime(year, month + 1, 1) if month < 12 else datetime(year + 1, 1, 1) count = 0 links = [] for post in posts: post_date = post.taken_at.replace(tzinfo=None) if post.taken_at.tzinfo else post.taken_at if start_date <= post_date < end_date: count += 1 links.append(f"https://www.instagram.com/p/{post.code}/") return count, links def manual_search(username, start_year, start_month, end_year, end_month, client): all_posts = [] try: user_id = client.user_id_from_username(username) for year in range(start_year, end_year + 1): for month in range(start_month if year == start_year else 1, end_month + 1 if year == end_year else 13): start_time = time.time() post_count, post_links = count_posts_for_month(user_id, year, month, client) month_name = datetime(year, month, 1).strftime('%B') all_posts.append({ "Instagram ID": username, "Post Count": post_count, "Year": str(year), # Ensure the year is stored as a string "Month": month_name if month_name else "-", "Links": " | ".join(post_links) }) elapsed_time = time.time() - start_time completion_message = f"Completed {username} | {month_name} {year} | Posts: {post_count} | Time: {elapsed_time:.2f} sec" st.write(completion_message) logger.info(completion_message) time.sleep(random.uniform(0.5, 1.5)) except UserNotFound: error_message = f"Error: User {username} not found." st.error(error_message) logger.error(error_message) all_posts.append({ "Instagram ID": username, "Post Count": 0, "Year": "-", "Month": "-", "Links": "User not found" }) except Exception as e: if client: client.handle_exception(client, e) st.error(f"Error retrieving posts for {username}: {e}") all_posts.append({ "Instagram ID": username, "Post Count": 0, "Year": "-", "Month": "-", "Links": "Error occurred" }) return all_posts def save_to_csv(data): df = pd.DataFrame(data) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") csv_filename = f"instagram_results_{timestamp}.csv" df.to_csv(csv_filename, index=False) return csv_filename def clean_up_files(file_list): for file in file_list: if os.path.exists(file): os.remove(file) logger.info(f"Removed file: {file}") # Streamlit App st.title("Instagram Data Processor") # Sidebar for User Credentials with st.sidebar: st.header("Instagram Credentials") USERNAME = st.text_input("Instagram Username") PASSWORD = st.text_input("Instagram Password", type="password") login_button = st.button("Login") # Session Management if 'client' not in st.session_state: st.session_state['client'] = None session_file = f"session_{USERNAME}.json" # Moved up for visibility # Initialize Instagram Client in Session State if not already present if 'client' not in st.session_state or not st.session_state.client: if USERNAME and is_session_valid(session_file): try: st.session_state.client = Client() st.session_state.client.load_settings(session_file) st.sidebar.success(f"Session loaded for {USERNAME}") logger.info(f"Session loaded successfully for user: {USERNAME}") except Exception as e: logger.error(f"Failed to load session for user {USERNAME}: {e}") st.sidebar.error("Failed to load existing session. Please log in again.") elif USERNAME and PASSWORD and login_button: account = Account(USERNAME, PASSWORD) try: st.session_state.client = account.get_client() st.session_state.client.dump_settings(session_file) st.sidebar.success(f"Logged in as {USERNAME}") logger.info(f"Logged in and saved session for user: {USERNAME}") except Exception as e: logger.error(f"Login failed for user {USERNAME}: {e}") st.sidebar.error("Login failed. Please check your credentials.") else: st.sidebar.error("Please enter both username and password.") # Main App Section for Inputs st.header("Input Details") # User ID Input Section st.subheader("Social Media Handles") user_input = st.text_area("Enter Social Media Handles (one per line)") instagram_usernames = extract_ig_usernames(user_input) # Date Range Input st.subheader("Specify Date Range") col1, col2 = st.columns(2) with col1: start_year = st.number_input("Start Year", min_value=2000, max_value=datetime.now().year, value=datetime.now().year) start_month = st.selectbox("Start Month", [datetime(2000, i, 1).strftime('%B') for i in range(1, 13)], key="start_month") with col2: end_year = st.number_input("End Year", min_value=2000, max_value=datetime.now().year, value=datetime.now().year) end_month = st.selectbox("End Month", [datetime(2000, i, 1).strftime('%B') for i in range(1, 13)], key="end_month") # Convert month names to numbers start_month_num = datetime.strptime(start_month, '%B').month end_month_num = datetime.strptime(end_month, '%B').month # Check Date Range Validity valid_date_range = True if (end_year < start_year) or (end_year == start_year and end_month_num < start_month_num): valid_date_range = False st.warning("End date cannot be earlier than start date.") # Initialize results container if 'results' not in st.session_state: st.session_state.results = [] # Process All User IDs if valid and client is initialized if valid_date_range: process_button = st.button("Process All IDs") if process_button: if not instagram_usernames: st.warning("No valid Instagram usernames found.") elif 'client' not in st.session_state or not st.session_state.client: st.warning("Please log in before processing IDs.") else: # Clear previous results before processing new ones st.session_state.results = [] progress_bar = st.progress(0) total_ids = len(instagram_usernames) processed_usernames = set() # To avoid duplicate processing for idx, username in enumerate(instagram_usernames): if username not in processed_usernames: posts_info = manual_search(username, start_year, start_month_num, end_year, end_month_num, st.session_state.client) st.session_state.results.extend(posts_info) processed_usernames.add(username) progress_bar.progress((idx + 1) / total_ids) st.write(f"Completed processing for {username}.") st.session_state['process_all'] = True # Display results results_df = pd.DataFrame(st.session_state.results) # Utility Functions (make sure to define these properly) def generate_csv(results): """Generate and cache the CSV file for download.""" df = pd.DataFrame(results) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") csv_filename = f"instagram_results_{timestamp}.csv" df.to_csv(csv_filename, index=False) return csv_filename def generate_log_file(): """Generate and cache the log file for download.""" timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") log_filename = f"processed_logs_{timestamp}.log" with open(LOG_FILE, "r") as log_file, open(log_filename, "w") as filtered_log_file: for line in log_file: if "Completed" in line or "Error" in line: filtered_log_file.write(line) return log_filename # Display results st.header("Results") if 'results' in st.session_state and st.session_state.results: results_df = pd.DataFrame(st.session_state.results) st.dataframe(results_df) # Generate and provide a download button for the results CSV csv_filename = generate_csv(st.session_state.results) with open(csv_filename, "rb") as file: st.download_button("Download CSV", file.read(), csv_filename, "text/csv") os.remove(csv_filename) # Clean up the file immediately after use # Logging and Downloads st.header("Download Logs") if os.path.exists(LOG_FILE): log_filename = generate_log_file() with open(log_filename, "rb") as file: st.download_button("Download Log File", file.read(), log_filename, "text/plain") os.remove(log_filename) # Clean up the log file immediately after use # Clean up old session files and processed files if is_session_valid(session_file) and (time.time() - os.path.getmtime(session_file)) >= SESSION_DURATION: os.remove(session_file) logger.info(f"Old session file {session_file} removed.")
SUID (Set UID) 会创建出 s 与 t 的权限,是为了让一般用户在执行某些程序的时候, 能够暂时的具有该程序拥有者的权限。  举例来说,我们知道账号与密码的存放档案其实是 /etc/passwd 与 /etc/shadow 。 而 /etc/shadow 这个文件的权限是什么呢? # ls -l /etc/shadow ----------. 1 root root 1407 4月 6 14:05 /etc/shadow 是『----------』。且他的拥有者是 root !在这个权限中,仅有 root 可以强制储存,其他人是连看都没有办法看! 但是偏偏我们使用 xiaoluo 这个一般身份用户去更新自己的密码时,使用的就是 /usr/bin/passwd 这个程序, 却是可以更新自己的密码的,也就是说, xiaoluo 这个一般身份使用者可以存取 /etc/shadow 这个密码文件! 但是我们也可以看到,明明 /etc/shadow 就是没有 xiaoluo 可以存取的权限!所以这就是 s 这个权限的用处了! 当 s 这个权限在 user 的 x 时,也就是类似上表的 -r-s--x--x ,称为 Set UID ,简称为 SUID , 这个 UID 代表的是 User 的 ID ,而 User 代表的则是这个程序 (/usr/bin/passwd) 的拥有者 (当然就是root了 !)。 那么由上面的定义中,我们知道了,当 xiaoluo 这个使用者执行 /usr/bin/passwd 时,他就会 暂时 的得到文件拥有人 root 的权限。 SUID 仅可用在【二进制制档案(binary file)】上, SUID 因为是程序在执行的过程中拥有文件拥有者的权限,因此,他仅可用于 binary file , 不能够用在批处理文件 (shell script) 上面的! 这是因为 shell script 只是将很多的 binary 执行档叫进来执行而已!所以 SUID 的权限部分,还是得要看 shell script 呼叫进来的程序的设定, 而不是 shell script 本身。 当然,SUID 对于目录也是无效的,这点要特别留意。所以总结一点:SUID是只能作用在文件上的,不能作用在目录上。 linux中除了常见的读(r)、写(w)、执行(x)权限以外,还有3个特殊的权限,分别是setuid、setgid和stick bit 将三个特殊位的用八进制数值表示,放于 u/g/o 位之前。其中 suid :4 sgid:2  sticky:1 例: 对某个目录: #chmod  4551  file  // 权限: r-sr-x—x,s占去了原来u的x的位置,减去s则为chmod 0551 file,或chmod u-s file #chmod  2551  file  // 权限: r-xr-s—x,s占去了原来g的x的位置,减去s则为chmod 0551 file,或chmod g-s file #chmod  1551  file  // 权限: r-xr-x—t,t占去了原来o的x的位置,减去t则为chmod 0551 file,或chmod -t file #chmod –t file #chmod a+s file 3、如何设置以上特殊权限 setuid:chmod u+s file setgid: chmod g+s file stick bit : chmod o+t file SUID:对一个可执行文件,不是以发起者身份来获取资源,而是以可执行文件的属主身份来执行。 SGID对一个可执行文件,不是以发起者身份来获取资源,而是以可执行文件的属组身份来执行。 STICKY:粘滞位,通常对目录而言。通常对于全局可写目录(other也可写)来说,让该目录具有sticky后,删除只对属于自己的文件有效(但是仍能编辑修改别人的文件,除了root的)。不能根据安全上下文获取对别人的文件的写权限。 SUID:置于 u 的 x 位,原位置有执行权限,就置为 s,没有了为 S . SGID:置于 g 的 x 位,原位置有执行权限,就置为 s,没有了为 S . STICKY:粘滞位,置于 o 的 x 位,原位置有执行权限,就置为 t ,否则为T . setuid就是:让普通用户拥有可以执行“只有root权限才能执行”的特殊权限,setgid同理指”组“ 作为普通用户是没有权限修改/etc/passwd文件的,但给/usr/bin/passwd以setuid权限后,普通用户就可以通过执行passwd命令,临时的拥有root权限,去修改/etc/passwd文件了 stick bit (粘贴位) 再看个实例,查看/tmp目录的权限 # ls -dl /tmp drwxrwxrwt 6 root root 4096 08-22 11:37 /tmp tmp目录是所有用户共有的临时文件夹,所有用户都拥有读写权限,这就必然出现一个问题,A用户在/tmp里创建了文件a.file,此时B用户看了不爽,在/tmp里把它给删了(因为拥有读写权限),那肯定是不行的。实际上是不会发生这种情况,因为有特殊权限stick bit(粘贴位)权限,正如drwxrwxrwt中的最后一个t stick bit (粘贴位)就是:除非目录的属主和root用户有权限删除它,除此之外其它用户不能删除和修改这个目录。 也就是说,在/tmp目录中,只有文件的拥有者和root才能对其进行修改和删除,其他用户则不行,避免了上面所说的问题产生。 用途一般是把一个文件夹的的权限都打开,然后来共享文件,象/tmp目录一样。
import { ILedgerEntry, ITransactionsByCustomersFilter, ITransactionsByCustomersService, ITransactionsByCustomersStatement, } from '@bigcapital/libs-backend'; import Ledger from '@bigcapital/server/services/Accounting/Ledger'; import TenancyService from '@bigcapital/server/services/Tenancy/TenancyService'; import { Tenant } from '@bigcapital/server/system/models'; import moment from 'moment'; import * as R from 'ramda'; import { Inject } from 'typedi'; import TransactionsByCustomers from './TransactionsByCustomers'; import { TransactionsByCustomersMeta } from './TransactionsByCustomersMeta'; import TransactionsByCustomersRepository from './TransactionsByCustomersRepository'; export class TransactionsByCustomersSheet implements ITransactionsByCustomersService { @Inject() private tenancy: TenancyService; @Inject() private reportRepository: TransactionsByCustomersRepository; @Inject() private transactionsByCustomersMeta: TransactionsByCustomersMeta; /** * Defaults balance sheet filter query. * @return {ICustomerBalanceSummaryQuery} */ private get defaultQuery(): ITransactionsByCustomersFilter { return { fromDate: moment().startOf('month').format('YYYY-MM-DD'), toDate: moment().format('YYYY-MM-DD'), numberFormat: { precision: 2, divideOn1000: false, showZero: false, formatMoney: 'total', negativeFormat: 'mines', }, comparison: { percentageOfColumn: true, }, noneZero: false, noneTransactions: true, customersIds: [], }; } /** * Retrieve the customers opening balance ledger entries. * @param {number} tenantId * @param {Date} openingDate * @param {number[]} customersIds * @returns {Promise<ILedgerEntry[]>} */ private async getCustomersOpeningBalanceEntries( tenantId: number, openingDate: Date, customersIds?: number[], ): Promise<ILedgerEntry[]> { const openingTransactions = await this.reportRepository.getCustomersOpeningBalanceTransactions( tenantId, openingDate, customersIds, ); return R.compose( R.map(R.assoc('date', openingDate)), R.map(R.assoc('accountNormal', 'debit')), )(openingTransactions); } /** * Retrieve the customers periods ledger entries. * @param {number} tenantId * @param {Date} fromDate * @param {Date} toDate * @returns {Promise<ILedgerEntry[]>} */ private async getCustomersPeriodsEntries( tenantId: number, fromDate: Date | string, toDate: Date | string, ): Promise<ILedgerEntry[]> { const transactions = await this.reportRepository.getCustomersPeriodTransactions(tenantId, fromDate, toDate); return R.compose( R.map(R.assoc('accountNormal', 'debit')), R.map((trans) => ({ ...trans, referenceTypeFormatted: trans.referenceTypeFormatted, })), )(transactions); } /** * Retrieve transactions by by the customers. * @param {number} tenantId * @param {ITransactionsByCustomersFilter} query * @return {Promise<ITransactionsByCustomersStatement>} */ public async transactionsByCustomers( tenantId: number, query: ITransactionsByCustomersFilter, ): Promise<ITransactionsByCustomersStatement> { const { accountRepository } = this.tenancy.repositories(tenantId); const i18n = this.tenancy.i18n(tenantId); // Retrieve tenant information. const tenant = await Tenant.query().findById(tenantId).withGraphFetched('metadata'); const filter = { ...this.defaultQuery, ...query, }; const accountsGraph = await accountRepository.getDependencyGraph(); // Retrieve the report customers. const customers = await this.reportRepository.getCustomers(tenantId, filter.customersIds); const openingBalanceDate = moment(filter.fromDate).subtract(1, 'days').toDate(); // Retrieve all ledger transactions of the opening balance of. const openingBalanceEntries = await this.getCustomersOpeningBalanceEntries(tenantId, openingBalanceDate); // Retrieve all ledger transactions between opeing and closing period. const customersTransactions = await this.getCustomersPeriodsEntries(tenantId, query.fromDate, query.toDate); // Concats the opening balance and period customer ledger transactions. const journalTransactions = [...openingBalanceEntries, ...customersTransactions]; const journal = new Ledger(journalTransactions); // Transactions by customers data mapper. const reportInstance = new TransactionsByCustomers( customers, accountsGraph, journal, filter, tenant.metadata.baseCurrency, i18n, ); const meta = await this.transactionsByCustomersMeta.meta(tenantId, filter); return { data: reportInstance.reportData(), query: filter, meta, }; } }
import { AnimatePresence, motion } from "framer-motion"; import React from "react"; interface Props { open?: boolean; onClose?: () => void; children?: React.ReactNode; } function Modal({ open, onClose, children }: Props) { return ( <AnimatePresence> {open && ( <div className="fixed w-screen h-screen z-10 flex flex-col "> <div className="h-full absolute w-full bg-stone-500 opacity-50" onClick={() => { console.log("clicked outside"); onClose?.(); }} ></div> <motion.div className="w-full h-5/6 sm:h-3/4 mt-auto flex justify-center relative"> <motion.div initial={{ clipPath: "circle(120px at 50% 226px)", }} animate={{ clipPath: "circle(100% at 50% 226px)", }} exit={{ clipPath: "circle(120px at 50% 226px)", }} transition={{ clipPath: { duration: 0.5, type: "tween", ease: "easeInOut", }, }} className="bg-white w-full h-full absolute bottom-0 rounded-t-3xl overflow-auto" > {children} </motion.div> </motion.div> </div> )} </AnimatePresence> ); } export default Modal;
from person import Person class Buyer(Person): def __init__(self, name, age, money, product): super().__init__(name, age, money) self.product = product def buy(self, other, how_many): total = other.price * how_many other.product -= how_many self.product += how_many self.give_money(other, total) def __str__(self): return super().__str__() + ''' I am a buyer. I have {} products'''.format(self.product) from retailer import Retailer if __name__ == "__main__": b1 = Buyer("grag", 18, 10000, 0) r1 = Retailer("kim", 25, 2000, 20) print(b1) print(r1) b1.buy(r1, 3) print(b1) print(r1)
import 'package:flutter/material.dart'; import 'package:ass4_provider/DataBase/DataBaseHelper.dart'; import 'package:ass4_provider/screens/AllTasks.dart'; import 'package:ass4_provider/screens/CompleteTasks.dart'; import 'package:ass4_provider/screens/InCompleteTasks.dart'; import 'package:ass4_provider/modelSheet.dart'; class HomePage extends StatelessWidget { var db = DBHelper(); @override Widget build(BuildContext context) { return DefaultTabController( length: 3, child: Scaffold( // drawer is empty : drawer: Drawer(), floatingActionButton: FloatingActionButton( backgroundColor: Colors.pink, onPressed: () { showModalBottomSheet( context: context, builder: (context) => ModalSheet(), elevation: 7.0); }, child: Icon(Icons.add), ), appBar: AppBar( backgroundColor: Colors.pink, title: Text('Todo App'), bottom: TabBar( tabs: [ Tab( text: 'All Tasks', ), Tab( text: 'complete Tasks', ), Tab( text: 'incomplete Tasks', ) ], isScrollable: true, ), ), body: TabBarView( children: [AllTasks(), CompleteTasks(), InCompleteTasks()], ))); } }
import path from 'path'; import express from 'express'; import webpack from 'webpack'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; import config from './webpack.config.dev'; import api from './src/api'; const app = express(); const compiler = webpack(config); app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath, })); app.use(webpackHotMiddleware(compiler)); app.use('/api', api); app.get('/users', (req, res) => { res.sendFile(path.join(__dirname, 'src/users-app/index.html')); }); app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'src/contest-app/index.html')); }); // Serve Ace Editor sources locally (it requires files using RequireJS) app.use(express.static('node_modules/ace-builds/src-min')); app.use(express.static('node_modules/font-awesome')); app.listen(3000, (err) => { if (err) { console.log(err); return; } console.log('Listening at http://localhost:3000'); });
<template> <div class="app"> <h2>{{ msg }}</h2> <!-- 1. 利用props方法完成子传父 --> <School :getSchoolName="getSchoolName"></School> <!-- 2.1 父组件给子组件绑定自定义事件, v-on:xxx='yyy'或@xxx='yyy'的形式, 完成数据子传父 --> <!-- <Student v-on:alkEvent="getStudentName"></Student> --> <!-- 2.2 父组件给子组件绑定多个自定义事件, 然后解绑 --> <Student v-on:alkEvent="getStudentName" @alkEvent2="otherGetStudentName"></Student> <!-- 3. 父组件给子组件绑定自定义事件, 利用ref, 配合mounted勾子, 完成数据子传父, 可以更具自由性(比如可以在勾子里写定时器) --> <Student ref="student"></Student> </div> </template> <script> // 引入组件 import School from "./components/School.vue"; import Student from "./components/Student.vue"; export default { name: "App", data() { return { msg: "你好啊!", }; }, components: { School, Student }, methods: { getSchoolName(value) { console.log("获取到学校名字:", value); }, /* 可以接收多个子组件传来的数据, 可用...的方式解构 */ getStudentName(value, ...parms) { console.log("获取到学生名字:", value, parms); }, otherGetStudentName() { console.log("触发第二个自定义事件"); }, }, mounted() { this.$refs.student.$on("alkEvent", this.getStudentName); }, }; </script> <style scoped> .app { background-color: #ddd; padding-left: 10px; padding-bottom: 10px; } </style>