text
stringlengths
184
4.48M
/** * @param {Function} fn * @return {Function} */ var curry = function(fn) { return function curried() { if (arguments.length >= fn.length) { return fn(...arguments); } else { return (...nextArgs) => curried(...arguments, ...nextArgs); } }; }; /** * function sum(a, b) { return a + b; } * const csum = curry(sum); * csum(1)(2) // 3 */
import React, {useEffect, useState} from "react"; import {workingHoursCreate, workingHoursGet} from "../../../../http.js"; import Text from "../../components/Text.jsx"; import Button from "../Button.jsx"; import {hourFormat, parsed} from "../../../../hours.js"; export default function Hours({}) { const [hours, setHours] = useState(null); useEffect(() => { workingHoursGet() .then(_hours => { setHours(_hours); }) .catch(error => { if (error.response.status === 404) { setHours(false); } }) }, []); function storeHours(start, duration) { workingHoursCreate(start, duration / 60); } return <div> <h3 className="text-xl mb-6"> <Text>Working hours</Text> </h3> <div> <HoursSetForm hours={hours} onSave={storeHours}/> </div> </div>; } function HoursSetForm({hours, onSave}) { if (hours === null) { return 'Loading...'; } if (hours === false) { return <div> Hours not set <NewHoursSection initialStart={7 * 60} initialDuration={8 * 60} onSave={onSave} /> </div>; } return <div> <HoursDisplay start={hours.start} duration={hours.duration}/> <NewHoursSection initialStart={hours.start} initialDuration={hours.duration} onSave={onSave} /> </div>; } function NewHoursSection({initialDuration, initialStart, onSave}) { const [start, setStart] = useState(initialStart); const [duration, setDuration] = useState(initialDuration); return <> <h3 className="text-xl mt-12 mb-4"> <Text>New working hours</Text> </h3> <div> <p className="mt-3 mb-2"> <Text>Work start</Text> </p> <p> <MinuteField value={start} onChange={setStart}/>, {hourFormat(start)}h </p> <p className="mt-3 mb-2"> <Text>Work duration</Text> </p> <p> <MinuteField value={duration} onChange={setDuration}/>, <Duration minutes={duration}/> </p> <div className="mt-4"> <Button onClick={() => onSave(start, duration)}> Save </Button> </div> </div> </>; } function MinuteField({value, onChange}) { return <> <input className="border w-14" type="number" value={value} min={0} onChange={event => { const minimalTime = Math.max(event.target.value, 0); const maximalTime = Math.min(minimalTime, 60 * 24 - 1); return onChange(maximalTime); }}/> <Text>minutes</Text> </>; } function HoursDisplay({duration, start}) { return <div> <p> <Text>Work start</Text>: {hourFormat(start)} </p> <p> <Text>Work duration</Text>: <Duration minutes={duration}/> </p> </div>; } function Duration({minutes}) { const [hours, _minutes] = parsed(minutes); return <>{hours} <Text>hours and</Text> {_minutes} <Text>minutes</Text></>; }
<%@page import="java.sql.PreparedStatement"%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <%@page import="java.sql.Connection" %> <%@page import="java.sql.DriverManager" %> <%@page import="java.sql.ResultSet" %> <%@page import="java.sql.Statement" %> <%@page import="java.sql.SQLException" %> <%! public String user="root"; public String password=""; public String dbName="dersler"; public String driverName="com.mysql.jdbc.Driver"; Connection con=null; Statement state=null; %> <% try{ Class.forName(driverName); con=DriverManager.getConnection("jdbc:mysql://localhost/"+dbName+"?user="+user+"&password="+password); if (con==null) out.print("Veritabani baglantisi basarisiz!"); else out.print("Veritabani baglantisi basarili!"); } catch(Exception e){ out.print(e+"<br>"); } //NOT: Birden fazla islem metodu ayni anda calistirilacaksa metotlar icinden baglanti kapatilmamalidir! // out.print(ogrenciGetir("Alp")); // out.print("<br>"+ogrenciEkle("Gülşah", "Parlar", "BBT", 96, 75)); // out.print(dersAdiGuncelle(10, "Görkem", "Caymaz", "Oyun Programlama")); out.print(ogrenciSil(21, "Gülşah", "Parlar")); %> <%! //Tum ogrenci kayitlarini getirir. String ogrenciGetir(){ String sorgu="SELECT * FROM notlar"; try{ state=con.createStatement(); ResultSet set=state.executeQuery(sorgu); state.close(); con.close(); String tmp="<p>"; while (set.next()) { tmp+=set.getInt("id")+" "+set.getString("ad")+" "+set.getString("soyad")+" "+set.getString("dersad")+"<br>"; } return tmp; }catch(SQLException e) {return "Hata meydana geldi!"+e; } } //Sadece belirtilen isimdeki ogrencilerin kayitlarini getirir. String ogrenciGetir(String ad){ String sorgu="SELECT * FROM notlar WHERE ad=?"; try{ PreparedStatement ps=con.prepareStatement(sorgu); ps.setString(1,ad); ResultSet set=ps.executeQuery(); ps.close(); con.close(); String tmp="<p>"; while (set.next()) { tmp+=set.getInt("id")+" "+ set.getString("ad")+" "+ set.getString("soyad")+" "+ set.getString("dersad")+" "+ set.getString("vize")+" "+ set.getString("final")+"<br>"; } return tmp; }catch(SQLException e) {return "Hata meydana geldi!"+e; } } String ogrenciEkle(String ad,String soyad,String dersad,int vize,int _final){ String sorgu="INSERT INTO notlar(ad,soyad,dersad,vize,final) VALUES (?,?,?,?,?)"; try{ PreparedStatement ps=con.prepareStatement(sorgu); ps.setString(1, ad); ps.setString(2, soyad); ps.setString(3,dersad); ps.setInt(4, vize); ps.setInt(5, _final); ps.executeUpdate(); ps.close(); con.close(); }catch(SQLException e){ return "<br>Bir hata meydana geldi: <br>"+e; } return ad+" "+soyad+" isimli öğrenci için kayıt başarıyla oluşturuldu!"; } String dersAdiGuncelle(int id,String ad,String soyad,String yeniDersAdi){ String sorgu="UPDATE notlar SET dersad=? WHERE id=? AND ad=? AND soyad=?"; try{ PreparedStatement ps=con.prepareStatement(sorgu); ps.setString(1, yeniDersAdi); ps.setInt(2,id); ps.setString(3,ad); ps.setString(4, soyad); ps.executeUpdate(); ps.close(); con.close(); return "Guncelleme basarili!"; }catch(SQLException e){return "Guncelleme sirasinda hata olustu! : "+e;} } String ogrenciSil(int id,String ad,String soyad){ String sorgu="DELETE FROM notlar WHERE id=? AND ad=? AND soyad=?"; try{ PreparedStatement ps=con.prepareStatement(sorgu); ps.setInt(1, id); ps.setString(2, ad); ps.setString(3, soyad); ps.executeUpdate(); ps.close(); con.close(); return "<p>"+ad+" "+soyad+" isim ve soyisimli ogrencinin kaydı silinmiştir."; }catch(SQLException e){ return "<p>Silme islemi sirasinda hata olustu! : "+e; } } %> </body> </html>
from flask_wtf import FlaskForm from wtforms import StringField,PasswordField,BooleanField,SubmitField from wtforms.validators import InputRequired,Email,EqualTo from ..models import User from wtforms import ValidationError class RegistrationForm(FlaskForm): email = StringField('Email Address',validators=[InputRequired(),Email()]) username = StringField('Enter your username',validators = [InputRequired()]) password = PasswordField('Password',validators = [InputRequired(), EqualTo('password_confirm',message = 'Passwords must match')]) password_confirm = PasswordField('Confirm Passwords',validators = [InputRequired()]) submit = SubmitField('Sign Up') class LoginForm(FlaskForm): email = StringField('Your Email Address',validators=[InputRequired(),Email()]) password = PasswordField('Password',validators=[InputRequired()]) remember = BooleanField('remember me') submit = SubmitField('Sign In') # password and email verification def validate_email(self,data_field): if User.query.filter_by(email = data_field.data).first(): raise ValidationError("User account already exists") def validate_username(self,data_field): if User.query.filter_by(username=data_field.data).first(): raise ValidationError("User name is not available")
<template> <img :src="`/img/${intro.icon}`" :alt="intro.title" class="intro__icon" /> <div class="intro__wrapper"> <picture> <source media="(max-width: 768px)" :srcset="`/img/${intro.img[0]}/Mobile/${intro.img[1]}.webp`" type="image/webp" /> <source media="(min-width: 769px)" :srcset="`/img/${intro.img[0]}/PC/${intro.img[1]}.webp`" type="image/webp" /> <source :srcset="`/img/${intro.img[0]}/JPG/${intro.img[1]}.png`" type="image/png" /> <img :srcset="`/img/${intro.img[0]}/PC/${intro.img[1]}.webp`" :alt="intro.title" type="image/webp" class="intro__img" /> </picture> <div class="intro"> <div class="intro__column"> <img :src="`/img/${intro.logo}`" :alt="intro.title" class="intro__logo" /> <p class="intro__text"> <strong>{{ intro.title }}&nbsp;</strong> <span v-html="intro.description"></span> </p> <h4 class="intro__title">Проект</h4> <p class="intro__list">{{ intro.tags }}</p> </div> </div> </div> </template> <script> // import { gsap } from 'gsap'; // import { ScrollTrigger } from 'gsap/ScrollTrigger'; // import { VueScrollmagic, TweenMax } from 'vue-scrollmagic'; export default { name: 'IntroTemplate', props: { intro: { icon: '', img: [], logo: '', title: '', description: '', tags: '', }, }, mounted() { // let controller = new VueScrollmagic.Controller(); // build tween // let tween = TweenMax.to('#animate', 0.5, { scale: 1.3, repeat: 5, yoyo: true }); // build scene and set duration to window height // eslint-disable-next-line // let scene = new VueScrollmagic.Scene({ triggerElement: '#trigger', duration: '100%' }) // .setTween(tween) // .addIndicators() // add indicators (requires plugin) // .addTo(controller); // gsap.registerPlugin(ScrollTrigger); // gsap.to('.intro__img', { // scrollTrigger: { // trigger: '.intro__img', // start: '-200 top', // end: '+=1000', // scrub: 1, // }, // scale: 1.2, // ease: 'none', // duration: 3, // }); let images = document.querySelectorAll('.intro__img'); window.addEventListener('scroll', () => { let h = document.documentElement, b = document.body, st = 'scrollTop'; let percent = (h[st] || b[st]) / (8000 - h.clientHeight); let scale = 1 + percent; // console.log(scale, b[sh]); images.forEach((image) => { image.style.scale = scale; }); }); }, }; </script> <style lang="sass" scoped> .intro max-width: 1370px width: 100% margin: 0 auto padding: 100px 36px 270px height: 860px &__icon position: absolute top: 0 left: 0 max-width: 100% z-index: -1 &__img position: absolute top: -70px left: -270px z-index: 0 max-width: 1300px width: 80% max-height: 930px object-fit: cover object-position: top transform: translateZ(0) scale: 1 transition: .3s linear z-index: -1 &__column padding-top: 25px max-width: 440px display: flex flex-direction: column margin-left: auto align-items: flex-start &__logo margin-bottom: 45px max-height: 74px width: auto object-fit: contain object-position: left &__text font-size: 20px margin-bottom: 162px strong font-weight: 700 &__title margin-bottom: 10px font-size: 30px font-weight: 700 &__wrapper position: relative width: 100% // overflow: hidden max-width: 1920px margin: 0 auto @media (max-width: 1024px) .intro padding: 83px 108px 94px height: 584px &__logo max-height: 52px &__column max-width: 337px padding-top: 0 &__text margin-bottom: 45px font-size: 18px line-height: 22px &__title font-size: 25px &__img max-width: 743px left: -233px @media (max-width: 768px) .intro padding: 75px 44px 0 height: auto &__title font-size: 22px &__wrapper display: flex flex-direction: column-reverse &__img width: calc(100% + 100px) position: relative left: -50px margin-bottom: -77px top: 0 margin-top: 50px &__logo height: 52px max-width: 80% &__column max-width: 500px margin: 0 auto @media (max-width: 425px) .intro padding: 60px 44px 0 &__text margin-bottom: 51px font-size: 16px &__title font-size: 30px margin-bottom: 16px &__logo height: 46px margin-bottom: 33px </style>
import { useState } from 'react'; import Navbar from './Navbar'; import Body from './Body' import Alert from './Alert'; export default function Home() { const [mode, setMode] = useState('gray-100') const [alert, setAlert] = useState(null) const showAlert = (massege) => { setAlert({ msg : massege }) setTimeout( () => { setAlert(null) },3000) } const toggleMode = () => { if (mode === "gray-100") { setMode('slate-600'); document.body.style.backgroundColor = "#18181b" showAlert("Dark mode enabled") }else{ setMode('gray-100'); document.body.style.backgroundColor = "#cbd5e1" showAlert("Light mode enabled") } } return ( <div className='flex w-full h-screen justify-center mt-10'> <div className={`bg-${mode} w-4/5 `} > <Navbar toggleMode = {toggleMode} /> <Alert alert={alert} /> <Body mode={mode} showAlert={showAlert} /> </div> </div> ) }
<?php namespace App\Filament\Resources\ResolveLogResource\Widgets; use App\Models\ResolveLog; use Filament\Widgets\ChartWidget; use Illuminate\Support\Facades\DB; class DnsRequestsByStatus extends ChartWidget { protected static ?string $heading = 'DNS Requests by Status'; protected function getData(): array { $data = ResolveLog::query() ->select([ 'resolve_status', DB::raw('count(*) as count'), ]) ->groupBy('resolve_status') ->get(); $statusColors = $data->pluck('resolve_status')->map(function ($status) { return $status === 'failed' ? 'rgba(255, 99, 132, 0.6)' : 'rgba(75, 192, 192, 0.6)'; // red for failed, teal for others }); $statusBorderColors = $data->pluck('resolve_status')->map(function ($status) { return $status === 'failed' ? 'rgba(255, 99, 132, 1)' : 'rgba(75, 192, 192, 1)'; // red for failed, teal for others }); return [ 'datasets' => [ [ 'label' => 'Resolve status', 'data' => $data->pluck('count'), 'backgroundColor' => $statusColors, 'borderColor' => $statusBorderColors, 'borderWidth' => 1, ], ], 'labels' => $data->pluck('resolve_status'), ]; } protected function getType(): string { return 'doughnut'; } }
t <- readRDS("data/derived/fia_trees.rds") %>% mutate(tree_id = paste(subplot_id, designcd, tree)) s <- readRDS("data/derived/fia_seedlings.rds") sp <- 318 # sugar maple # identify (sub?)plots surveyed in 2+ years under same designcd p <- bind_rows(t, s) %>% select(plot_id, lon, lat, invyr, spcd, designcd) %>% distinct() %>% mutate(series = paste(plot_id, designcd)) %>% group_by(series, lon, lat) %>% filter(sp %in% spcd) %>% filter(length(unique(invyr)) > 1) %>% ungroup() %>% select(-spcd) %>% distinct() mpd <- map_data("state") plt <- p %>% count(series, lon, lat) %>% # summarize(n = length(unique(invyr)), # lon = mean(lon), # lat = mean(lat)) %>% ggplot(aes(lon, lat, color = n)) + geom_polygon(data = mpd, aes(long, lat, group = group), fill = "gray80", color = NA) + geom_point() + scale_color_viridis_c() + coord_cartesian(xlim = range(p$lon), ylim = range(p$lat)) + theme_minimal() + theme(axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank()) + labs(color = "n surveys", title = "FIA plots that contain sugar maple and were surveyed 2+ times under a single designcd") ggsave("figures/acer_saccharum/map_nyears.png", plt, width = 8, height = 6, units = "in") x <- p %>% group_by(series) %>% filter(length(unique(invyr)) > 1) %>% arrange(invyr) %>% summarize(years = paste(invyr, collapse = "_")) %>% ungroup() %>% select(years) %>% distinct() %>% separate(years, paste0("y", 1:6), remove = F) %>% gather(i, year, y1:y6) %>% #filter(years == years[1]) na.omit() %>% mutate(year = as.integer(year)) %>% filter(year < 2023) %>% group_by(years) %>% mutate(n = length(year)) plt <- ggplot(x, aes(year, years, group = years)) + facet_wrap(~n, scales = "free", nrow = 1, labeller = label_both) + geom_line(size = .25) + geom_point(size = .75) + theme_bw() + theme(axis.text.y = element_blank(), axis.title.y = element_blank(), axis.ticks.y = element_blank(), panel.grid = element_blank()) + labs(title = "unique visit schedules for FIA plots containing sugar maple") ggsave("figures/acer_saccharum/invyr.png", plt, width = 8, height = 5, units = "in") # tree-seedling co-observation patterns (tangent) bind_rows(t %>% mutate(stage = "tree"), s %>% mutate(stage = "seedling")) %>% mutate(series = paste(plot_id, designcd)) %>% filter(series %in% unique(p$series)) %>% group_by(series, stage, invyr) %>% summarize(pres = sp %in% spcd) %>% ungroup() %>% unite(occ, stage, pres) %>% group_by(series, invyr) %>% summarize(occ = paste(occ, collapse = ", ")) %>% ungroup() %>% count(occ) x <- t %>% filter(!is.na(dia), spcd == sp) %>% filter(tree_id %in% sample(tree_id, 1000)) %>% count(tree_id) pd <- t %>% filter(tree_id %in% sample(x$tree_id[x$n >= 2], 100)) %>% mutate(status = recode(statuscd, "1" = "live", "2" = "dead", "3" = "harvested")) plt <- pd %>% ggplot(aes(invyr, dia, group = tree_id, color = status)) + geom_hline(yintercept = 5, color = "dodgerblue") + geom_line(size = .25) + geom_point(size = .75) + scale_y_log10() + scale_color_manual(values = c("red", "green", "black"), na.value = "yellow") + theme_minimal() + labs(title = "DBH tracjectories for random sugar maples") ggsave("figures/acer_saccharum/dbh_trajectories.png", plt, width = 7, height = 5, units = "in") # note: still need to figure out whether there are implicit deaths, # in addition to the explicit deaths counted here x <- t %>% filter(!is.na(dia), spcd == sp) %>% mutate(status = recode(statuscd, "1" = "live", "2" = "dead", "3" = "harvested"), class = ifelse(dia >= 5, "tree", "sapling")) %>% group_by(tree_id) %>% arrange(dia) %>% mutate(dia_next = lead(dia), invyr_next = lead(invyr), class_next = lead(class), status_next = lead(status)) %>% ungroup() %>% filter(is.finite(invyr), is.finite(invyr_next), !is.na(status), status == "live", status_next != "harvested") %>% mutate(trans = case_when(status == status_next & class == class_next ~ "survived", status == "live" & status_next == "dead" ~ "died", class == "sapling" & class_next == "tree" ~ "graduated", class == "tree" & class_next == "sapling" ~ "reverted", TRUE ~ "other"), years = invyr_next - invyr) x %>% group_by(status, class, trans) %>% summarize(n_events = n(), n_years = sum(years)) %>% group_by(status, class) %>% mutate(p_event = n_events / sum(n_events), p_year = n_events / sum(n_years), p_year = ifelse(trans == "survived", 1-sum(p_year[trans != "survived"]), p_year)) ## model fits ############## library(nnet) library(raster) # climate data ll <- x %>% dplyr::select(plot_id, lon, lat) %>% distinct() climate <- list.files("f:/chelsa/v2/climatology/raw/", pattern = "_bio1", full.names = T) %>% stack() climate <- extract(climate, dplyr::select(ll, lon, lat) %>% as.matrix()) %>% as.data.frame() %>% as.tibble() %>% setNames(c("temp", "prec")) %>% mutate(plot_id = ll$plot_id) md <- x %>% filter(class == "sapling") %>% left_join(climate) %>% mutate(rtrans = relevel(factor(trans), ref = "survived")) # density data density <- t %>% filter(!is.na(dia)) %>% group_by(subplot_id, invyr) %>% summarize(n_trees = length(dia[dia >= 5 & spcd == sp]) %>% sqrt(), n_saplings = length(dia[dia < 5 & spcd == sp]) %>% sqrt()) md <- left_join(density, md) # fit multinomial model fit <- multinom(trans ~ dia + temp + prec + n_saplings + n_trees, data = md) pred <- md %>% ungroup() %>% select(dia, temp, prec, n_saplings, n_trees) %>% na.omit() %>% bind_cols(predict(fit, ., type = "probs") %>% as.data.frame()) %>% gather(trans, value, died:survived) %>% mutate(n_saplings = n_saplings ^ 2, n_trees = n_trees ^ 2) ggplot(pred %>% filter(round(dia, 0) == 4), aes(n_trees, value, color = n_saplings)) + facet_wrap(~trans, scales = "free") + geom_point() + scale_color_viridis_c() + scale_x_sqrt() + theme_bw() pred <- md %>% ungroup() %>% filter(is.finite(temp), is.finite(dia)) %>% mutate(temp = median(temp), prec = median(prec), dia = 4, n_trees = round(n_trees, 1), n_saplings = round(n_saplings, 1)) %>% select(temp, prec, dia, n_trees, n_saplings) %>% distinct() %>% bind_cols(predict(fit, ., type = "probs") %>% as.data.frame()) %>% mutate(n_saplings = n_saplings ^ 2, n_trees = n_trees ^ 2) %>% gather(trans, value, died:survived) plt <- ggplot(pred, aes(n_trees, value, alpha = n_saplings, color = trans, group = paste(trans, n_saplings))) + facet_wrap(~ trans, scales = "free", nrow = 1) + geom_line(size = 1) + scale_alpha_continuous(trans = "sqrt", range = c(.3, 1)) + theme_bw() + labs(color = "transition", y = "probability", title = "multiniomial logistic fits of sugar maple sapling outcomes") ggsave("figures/acer_saccharum/sapling_multinom_density.png", plt, width = 8, height = 5, units = "in") ######## pred <- md %>% mutate(temp = round(temp), prec = plyr::round_any(prec, 500), dia = round(dia, 0)) %>% select(temp, prec, dia) %>% distinct() %>% bind_cols(predict(fit, ., type = "probs") %>% as.data.frame()) %>% gather(trans, value, died:survived) %>% rename(dbh = dia) plt <- ggplot(pred, aes(temp, value, alpha = prec, color = trans, group = paste(trans, prec))) + facet_grid(. ~ dbh, scales = "free", labeller = label_both) + geom_line(size = 1) + scale_alpha_continuous(range = c(.25, 1)) + scale_color_manual(values = c("darkred", "darkgreen", "darkblue")) + theme_bw() + theme(legend.position = "bottom", legend.box = "vertical") + labs(color = "transition", alpha = "precipitation", x = "temperature", y = "probability", title = "multiniomial logistic fits of sugar maple sapling outcomes") ggsave("figures/acer_saccharum/sapling_multinom.png", plt, width = 7, height = 5, units = "in") pred <- climate %>% left_join(select(md, plot_id, lon, lat)) %>% mutate(dia = 4) %>% bind_cols(predict(fit, ., type = "probs") %>% as.data.frame()) %>% gather(trans, value, died:survived) plt <- pred %>% filter(trans != "survived") %>% ggplot(aes(lon, lat, color = value)) + facet_wrap(~ trans) + geom_polygon(data = mpd, aes(long, lat, group = group), fill = "gray80", color = NA) + geom_point() + scale_color_viridis_c() + coord_cartesian(xlim = range(p$lon), ylim = range(p$lat)) + theme_minimal() + theme(axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank()) + labs(color = "prob", title = "sugar maple saplings: predicted transition probabilities based on climate") ggsave("figures/acer_saccharum/sapling_multinom_map.png", plt, width = 10, height = 4, units = "in") #################### # if we assume that seedlings are in equilibrium: # - we can use their counts, plus appearances of new saplings, to calculate mean graduation rates # - we can use their mean age to calculate turnover rates (but virtually never reported) ## find instances of seedling-sapling transition ## # identify all seedling survey events that were followed by sapling survey events # count seedlings in those surveys (including on plots that had no sapling appearance), # and saplings that newly appeared in the following survey # subplot time series with seedlings for focal species seedlings <- s %>% filter(spcd == sp) %>% mutate(series_id = paste(subplot_id, designcd)) %>% select(series_id, invyr, treecount) %>% distinct() # subplot time series in which saplings of any species were counted series <- t %>% filter(dia < 5, !is.na(dia)) %>% mutate(series_id = paste(subplot_id, designcd)) %>% select(series_id, invyr) %>% distinct() %>% group_by(series_id) %>% summarize(series_start = min(invyr)) # new appearances of saplings of focal species saplings <- t %>% filter(spcd == sp, dia < 5, !is.na(dia)) %>% mutate(series_id = paste(subplot_id, designcd)) %>% select(series_id, tree_id, invyr, dia) %>% group_by(series_id, tree_id) %>% filter(invyr == min(invyr)) %>% rename(sapling_start = invyr) %>% left_join(series) %>% filter(sapling_start > series_start) # seedling-sapling transitions ss <- left_join(seedlings, saplings) %>% filter(is.finite(treecount), sapling_start > invyr | is.na(sapling_start)) %>% group_by(series_id) %>% mutate(n = n()) %>% ungroup() %>% group_by(series_id) %>% mutate(next_year = unique(c(invyr, sapling_start))[ match(invyr, unique(c(invyr, sapling_start))) + 1]) %>% group_by(series_id, invyr) %>% summarize(seedlings = treecount[1], new_saplings = sum(sapling_start == next_year & !is.na(sapling_start))) %>% ungroup() sum(ss$new_saplings) / sum(ss$seedlings)
package org.kiwiproject.dropwizard.jakarta.xml.ws; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import io.dropwizard.validation.Validated; import io.dropwizard.validation.ValidationMethod; import jakarta.validation.Valid; import jakarta.validation.Validation; import jakarta.validation.ValidationException; import jakarta.validation.constraints.NotEmpty; import jakarta.xml.ws.AsyncHandler; import org.apache.cxf.annotations.UseAsyncMethod; import org.apache.cxf.message.Exchange; import org.apache.cxf.message.Message; import org.apache.cxf.service.invoker.Invoker; import org.apache.cxf.service.model.BindingOperationInfo; import org.apache.cxf.service.model.OperationInfo; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; class ValidatingInvokerTest { ValidatingInvoker invoker; Invoker underlying; Exchange exchange; static class ChildParam { @NotEmpty private final String foo; public ChildParam(String foo) { this.foo = foo; } @ValidationMethod(message = "foo may not be 'John'") public boolean isNotJohn() { return !("John".equals(foo)); } } @SuppressWarnings("all") static class RootParam1 { @Valid private final ChildParam child; public RootParam1(ChildParam childParam) { this.child = childParam; } } @SuppressWarnings("all") static class RootParam2 { @NotEmpty private final String foo; public RootParam2(String foo) { this.foo = foo; } } @SuppressWarnings("all") static class DummyService { public void noParams() { } public void noValidation(RootParam1 rootParam1, RootParam2 rootParam2) { } public void withValidation(@Valid RootParam1 rootParam1, @Valid RootParam2 rootParam2) { } public void withDropwizardValidation(@Validated() String foo) { } @UseAsyncMethod public void asyncMethod(String foo) { } public void asyncMethodAsync(String foo, AsyncHandler<String> asyncHandler) { } } @BeforeEach void setup() { underlying = mock(Invoker.class); invoker = new ValidatingInvoker(underlying, Validation.buildDefaultValidatorFactory().getValidator()); exchange = mock(Exchange.class); when(exchange.getInMessage()).thenReturn(mock(Message.class)); BindingOperationInfo boi = mock(BindingOperationInfo.class); when(exchange.getBindingOperationInfo()).thenReturn(boi); OperationInfo oi = mock(OperationInfo.class); when(boi.getOperationInfo()).thenReturn(oi); } /** * Utility method that mimics runtime CXF behaviour. Enables AbstractInvoker.getTargetMethod to work properly * during the test. */ private void setTargetMethod(Exchange exchange, String methodName, Class<?>... parameterTypes) { try { OperationInfo oi = exchange.getBindingOperationInfo().getOperationInfo(); when(oi.getProperty(Method.class.getName())) .thenReturn(DummyService.class.getMethod(methodName, parameterTypes)); } catch (Exception e) { throw new RuntimeException("setTargetMethod failed", e); } } @Test void invokeWithoutParams() { setTargetMethod(exchange, "noParams"); invoker.invoke(exchange, null); verify(underlying).invoke(exchange, null); } @Test void invokeWithoutValidation() { setTargetMethod(exchange, "noValidation", RootParam1.class, RootParam2.class); List<Object> params = Arrays.asList(null, null); invoker.invoke(exchange, params); verify(underlying).invoke(exchange, params); params = Arrays.asList(new RootParam1(null), new RootParam2(null)); invoker.invoke(exchange, params); verify(underlying).invoke(exchange, params); } @Test void invokeWithAsyncHandler() { setTargetMethod(exchange, "asyncMethod", String.class); List<Object> params = Arrays.asList(null, (AsyncHandler<String>) res -> { // no-op }); invoker.invoke(exchange, params); verify(underlying).invoke(exchange, params); params = Arrays.asList("foo", (AsyncHandler<String>) res -> { // no-op }); invoker.invoke(exchange, params); verify(underlying).invoke(exchange, params); } @Test void invokeWithValidation() { setTargetMethod(exchange, "withValidation", RootParam1.class, RootParam2.class); var params1 = List.of(new RootParam1(new ChildParam("")), new RootParam2("ok")); assertThatThrownBy(() -> invoker.invoke(exchange, params1)) .isExactlyInstanceOf(ValidationException.class); var params2 = List.of(new RootParam1(new ChildParam("ok")), new RootParam2("")); assertThatThrownBy(() -> invoker.invoke(exchange, params2)) .isExactlyInstanceOf(ValidationException.class); var params3 = List.of(new RootParam1(new ChildParam("John")), new RootParam2("ok")); assertThatThrownBy(() -> invoker.invoke(exchange, params3)) .isExactlyInstanceOf(ValidationException.class) .hasMessageContaining("foo may not be 'John'"); verifyNoMoreInteractions(underlying); var params = List.of(new RootParam1(new ChildParam("ok")), new RootParam2("ok")); invoker.invoke(exchange, params); verify(underlying).invoke(exchange, params); } }
# Python Programming: A Brain-Friendly Guide to Object-Oriented Programming Welcome to the world of Python programming! In this guide, we'll explore the fascinating world of Object-Oriented Programming (OOP) in Python. Whether you're a beginner or a seasoned programmer, Python's simplicity and versatility make it an awesome choice for building amazing software. Let's dive right in and unravel the magic of Python OOP. ## Table of Contents 1. [Why Python Programming is Awesome](#why-python-programming-is-awesome) 2. [Understanding Object-Oriented Programming (OOP)](#understanding-object-oriented-programming-oop) 3. [Exploring Classes and Objects](#exploring-classes-and-objects) 4. [Attributes: The Building Blocks](#attributes-the-building-blocks) 5. [Access Control: Public, Protected, and Private Attributes](#access-control-public-protected-and-private-attributes) 6. [The 'self' Parameter](#the-self-parameter) 7. [Methods: Functions with Superpowers](#methods-functions-with-superpowers) 8. [Special Method '__init__'](#special-method-init) 9. [Data Abstraction, Data Encapsulation, and Information Hiding](#data-abstraction-data-encapsulation-and-information-hiding) 10. [Properties: Attributes with a Twist](#properties-attributes-with-a-twist) 11. [Attribute vs. Property in Python](#attribute-vs-property-in-python) 12. [Pythonic Getters and Setters](#pythonic-getters-and-setters) 13. [Dynamically Creating Attributes](#dynamically-creating-attributes) 14. [Binding Attributes](#binding-attributes) 15. ['__dict__': Uncovering Class and Instance Attributes](#dict-uncovering-class-and-instance-attributes) 16. [Attribute Lookup in Python](#attribute-lookup-in-python) 17. [Using 'getattr' Function](#using-getattr-function) ### 1. Why Python Programming is Awesome <a name="why-python-programming-is-awesome"></a> Python's simplicity, readability, and extensive libraries make it an awesome choice for both beginners and experienced programmers. Let's explore the core concepts of Python's Object-Oriented Programming (OOP). ### 2. Understanding Object-Oriented Programming (OOP) <a name="understanding-object-oriented-programming-oop"></a> OOP is a programming paradigm that models real-world entities using classes and objects. Python embraces OOP principles, allowing you to structure your code in a more organized and efficient way. ### 3. Exploring Classes and Objects <a name="exploring-classes-and-objects"></a> A **class** is a blueprint for creating objects, while an **object** is an instance of a class. Think of classes as cookie cutters and objects as the cookies they produce. ### 4. Attributes: The Building Blocks <a name="attributes-the-building-blocks"></a> An **attribute** is a variable associated with an object, storing its characteristics or properties. ### 5. Access Control: Public, Protected, and Private Attributes <a name="access-control-public-protected-and-private-attributes"></a> Python offers control over attribute visibility: - **Public**: Accessible from anywhere. - **Protected**: Accessible within the class and its subclasses. - **Private**: Accessible only within the class itself. ### 6. The 'self' Parameter <a name="the-self-parameter"></a> The 'self' parameter represents the instance of a class and is used to access attributes and methods within that class. ### 7. Methods: Functions with Superpowers <a name="methods-functions-with-superpowers"></a> **Methods** are functions defined inside a class and can perform actions on the class's attributes. ### 8. Special Method '__init__' <a name="special-method-init"></a> The '__init__' method is a special constructor method used to initialize object attributes when an object is created from a class. ### 9. Data Abstraction, Data Encapsulation, and Information Hiding <a name="data-abstraction-data-encapsulation-and-information-hiding"></a> These concepts help organize data, hide complex implementations, and provide controlled access to attributes. ### 10. Properties: Attributes with a Twist <a name="properties-attributes-with-a-twist"></a> Properties allow you to add getter and setter methods to control attribute access and modification. ### 11. Attribute vs. Property in Python <a name="attribute-vs-property-in-python"></a> Attributes are direct values, while properties allow you to execute code when getting or setting values. ### 12. Pythonic Getters and Setters <a name="pythonic-getters-and-setters"></a> In Python, we use properties to create getter and setter methods in a more elegant way. ### 13. Dynamically Creating Attributes <a name="dynamically-creating-attributes"></a> Python allows you to add new attributes to existing instances of a class dynamically. ### 14. Binding Attributes <a name="binding-attributes"></a> Attributes can be bound to both classes and objects, allowing for flexibility in Python programming. ### 15. '__dict__': Uncovering Class and Instance Attributes <a name="dict-uncovering-class-and-instance-attributes"></a> The '__dict__' attribute of a class or instance contains a dictionary of its attributes and values. ### 16. Attribute Lookup in Python <a name="attribute-lookup-in-python"></a> Learn how Python finds attributes for objects and classes, including the order of attribute resolution. ### 17. Using 'getattr' Function <a name="using-getattr-function"></a> The 'getattr' function in Python retrieves the value of an attribute dynamically. With these concepts in mind, you're well on your way to becoming a Python OOP master. Feel free to explore each topic in-depth and experiment with Python's endless possibilities. Happy coding!
// // RecruitItems.swift // Task // // Created by trost.jk on 2022/09/16. // import Foundation // MARK: - RecruitItems struct RecruitItems: ModelType { let recruitItems: [RecruitItem] enum CodingKeys: String, CodingKey { case recruitItems = "recruit_items" } } // MARK: - RecruitItem struct RecruitItem: ModelType { let id: Int let title: String let reward: Int let appeal: String let imageURL: String let company: Company var isBookmark: Bool = false enum CodingKeys: String, CodingKey { case id, title, reward, appeal case imageURL = "image_url" case company } } // MARK: - Company struct Company: ModelType { let name: String let logoPath: String let ratings: [Rating] enum CodingKeys: String, CodingKey { case name case logoPath = "logo_path" case ratings } } // MARK: - Rating struct Rating: ModelType { let type: String let rating: Double }
// app.service.ts import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import * as OktaAuth from '@okta/okta-auth-js'; @Injectable() export class OktaAuthService { oktaAuth = new OktaAuth({ url: 'https://dev-256664.okta.com', clientId: '{clientId}', issuer: 'https://dev-256664.okta.com/oauth2/default', redirectUri: 'http://localhost:4200/callback', headers:{ 'Access-Control-Allow-Origin': '*', } }); constructor(private router: Router) {} async isAuthenticated() { // Checks if there is a current accessToken in the TokenManger. return !!(await this.oktaAuth.tokenManager.get('accessToken')); } login() { // Launches the login redirect. this.oktaAuth.token.getWithRedirect({ responseType: ['id_token', 'token'], scopes: ['openid', 'email', 'profile'] }); alert('login call'); } async handleAuthentication() { const tokens = await this.oktaAuth.token.parseFromUrl(); tokens.forEach(token => { if (token.idToken) { this.oktaAuth.tokenManager.add('idToken', token); } if (token.accessToken) { this.oktaAuth.tokenManager.add('accessToken', token); } }); } async logout() { alert('logout'); console.log(JSON.stringify(this.oktaAuth)); this.oktaAuth.tokenManager.clear(); await this.oktaAuth.signOut(); } }
<?php namespace App\Providers; use Illuminate\Auth\Events\Registered; use Illuminate\Auth\Listeners\SendEmailVerificationNotification; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; use Illuminate\Support\Facades\Event; class EventServiceProvider extends ServiceProvider { /** * The event to listener mappings for the application. * * @var array<class-string, array<int, class-string>> */ protected $listen = [ Registered::class => [ SendEmailVerificationNotification::class, ], \App\Events\SomeonePostedEvent::class => [ \App\Listners\SomeonePostedListner::class, ], \App\Events\FriendRequestReceivedEvent::class => [ \App\Listners\FriendRequestReceivedListner::class, ], \App\Events\FriendRequestAcceptedEvent::class => [ \App\Listners\FriendRequestAcceptedListner::class, ], \App\Events\NewChatMessageEvent::class => [ \App\Listners\NewChatMessageListner::class, ], \App\Events\ClubEventEvent::class => [ \App\Listners\ClubEventListner::class, ], \App\Events\ClubRequestAcceptedEvent::class => [ \App\Listners\ClubRequestAcceptedListner::class, ], ]; /** * Register any events for your application. * * @return void */ public function boot() { // } /** * Determine if events and listeners should be automatically discovered. * * @return bool */ public function shouldDiscoverEvents() { return false; } }
package com.recipe.search.ui.view.auth.login import android.app.AlertDialog import android.content.Intent import android.os.Bundle import android.text.method.HideReturnsTransformationMethod import android.text.method.PasswordTransformationMethod import android.view.View import android.widget.ImageView import com.recipe.search.base.MvpBaseActivity import com.recipe.search.databinding.ActivityLoginBinding import com.recipe.search.ui.view.auth.appwrite_auth.AppwriteRegistrationActivity import com.recipe.search.ui.view.auth.signUp.SignUpActivity import com.recipe.search.ui.view.dashboard.DashBoardActivity import com.recipe.search.utils.AppwriteInit import com.recipe.search.utils.Navigator import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch class LoginActivity : MvpBaseActivity<LoginPresenter>(), LoginContract.View { private lateinit var binding: ActivityLoginBinding private lateinit var appwriteInit: AppwriteInit private var isPinVisible = false private val VISIBLE: HideReturnsTransformationMethod = HideReturnsTransformationMethod.getInstance() private val HIDDEN: PasswordTransformationMethod = PasswordTransformationMethod.getInstance() private lateinit var login: Login override fun getContentView(): View { binding = ActivityLoginBinding.inflate(layoutInflater) val view = binding.root return view } override fun onViewReady(savedInstanceState: Bundle?, intent: Intent) { appwriteInit = AppwriteInit(this) login = Login(this) binding.ivPinVisibility.setOnClickListener { isPinVisible = !isPinVisible binding.ivPinVisibility.isSelected = isPinVisible binding.etPin.transformationMethod = if (isPinVisible) VISIBLE else HIDDEN binding.etPin.setSelection(binding.etPin.text!!.length) } binding.btnLogin.setOnClickListener { showProgressDialog("") val user_email = binding.etUserEmail.text.toString() val user_pass = binding.etPin.text.toString() val data = login.checkSignupValidation(user_email,user_pass ) if (data) { GlobalScope.launch { appwriteInit.login(user_email, user_pass) hideProgressDialog() } }else{ appwriteInit.loader?.cancel() } } binding.llSignupBtn.setOnClickListener { Navigator.sharedInstance.navigate(this, AppwriteRegistrationActivity::class.java) } } }
# Copyright 2024 The HuggingFace Team. All rights reserved. # # 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. import inspect from typing import Any, Callable, Dict, List, Optional, Union import numpy as np import PIL.Image import torch import torch.nn.functional as F from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from ...callbacks import MultiPipelineCallbacks, PipelineCallback from ...image_processor import PipelineImageInput, VaeImageProcessor from ...loaders import FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin from ...models import AutoencoderKL, ControlNetXSAdapter, UNet2DConditionModel, UNetControlNetXSModel from ...models.lora import adjust_lora_scale_text_encoder from ...schedulers import KarrasDiffusionSchedulers from ...utils import ( USE_PEFT_BACKEND, deprecate, logging, replace_example_docstring, scale_lora_layers, unscale_lora_layers, ) from ...utils.torch_utils import is_compiled_module, is_torch_version, randn_tensor from ..pipeline_utils import DiffusionPipeline, StableDiffusionMixin from ..stable_diffusion.pipeline_output import StableDiffusionPipelineOutput from ..stable_diffusion.safety_checker import StableDiffusionSafetyChecker logger = logging.get_logger(__name__) # pylint: disable=invalid-name EXAMPLE_DOC_STRING = """ Examples: ```py >>> # !pip install opencv-python transformers accelerate >>> from diffusers import StableDiffusionControlNetXSPipeline, ControlNetXSAdapter >>> from diffusers.utils import load_image >>> import numpy as np >>> import torch >>> import cv2 >>> from PIL import Image >>> prompt = "aerial view, a futuristic research complex in a bright foggy jungle, hard lighting" >>> negative_prompt = "low quality, bad quality, sketches" >>> # download an image >>> image = load_image( ... "https://hf.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png" ... ) >>> # initialize the models and pipeline >>> controlnet_conditioning_scale = 0.5 >>> controlnet = ControlNetXSAdapter.from_pretrained( ... "UmerHA/Testing-ConrolNetXS-SD2.1-canny", torch_dtype=torch.float16 ... ) >>> pipe = StableDiffusionControlNetXSPipeline.from_pretrained( ... "stabilityai/stable-diffusion-2-1-base", controlnet=controlnet, torch_dtype=torch.float16 ... ) >>> pipe.enable_model_cpu_offload() >>> # get canny image >>> image = np.array(image) >>> image = cv2.Canny(image, 100, 200) >>> image = image[:, :, None] >>> image = np.concatenate([image, image, image], axis=2) >>> canny_image = Image.fromarray(image) >>> # generate image >>> image = pipe( ... prompt, controlnet_conditioning_scale=controlnet_conditioning_scale, image=canny_image ... ).images[0] ``` """ class StableDiffusionControlNetXSPipeline( DiffusionPipeline, StableDiffusionMixin, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin ): r""" Pipeline for text-to-image generation using Stable Diffusion with ControlNet-XS guidance. This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods implemented for all pipelines (downloading, saving, running on a particular device, etc.). The pipeline also inherits the following loading methods: - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings - [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights - [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights - [`loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files Args: vae ([`AutoencoderKL`]): Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations. text_encoder ([`~transformers.CLIPTextModel`]): Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)). tokenizer ([`~transformers.CLIPTokenizer`]): A `CLIPTokenizer` to tokenize text. unet ([`UNet2DConditionModel`]): A [`UNet2DConditionModel`] used to create a UNetControlNetXSModel to denoise the encoded image latents. controlnet ([`ControlNetXSAdapter`]): A [`ControlNetXSAdapter`] to be used in combination with `unet` to denoise the encoded image latents. scheduler ([`SchedulerMixin`]): A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`]. safety_checker ([`StableDiffusionSafetyChecker`]): Classification module that estimates whether generated images could be considered offensive or harmful. Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details about a model's potential harms. feature_extractor ([`~transformers.CLIPImageProcessor`]): A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`. """ model_cpu_offload_seq = "text_encoder->unet->vae" _optional_components = ["safety_checker", "feature_extractor"] _exclude_from_cpu_offload = ["safety_checker"] _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"] def __init__( self, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: Union[UNet2DConditionModel, UNetControlNetXSModel], controlnet: ControlNetXSAdapter, scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessor, requires_safety_checker: bool = True, ): super().__init__() if isinstance(unet, UNet2DConditionModel): unet = UNetControlNetXSModel.from_unet(unet, controlnet) if safety_checker is None and requires_safety_checker: logger.warning( f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure" " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." ) if safety_checker is not None and feature_extractor is None: raise ValueError( "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety" " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead." ) self.register_modules( vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, unet=unet, controlnet=controlnet, scheduler=scheduler, safety_checker=safety_checker, feature_extractor=feature_extractor, ) self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True) self.control_image_processor = VaeImageProcessor( vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False ) self.register_to_config(requires_safety_checker=requires_safety_checker) # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt def _encode_prompt( self, prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt=None, prompt_embeds: Optional[torch.Tensor] = None, negative_prompt_embeds: Optional[torch.Tensor] = None, lora_scale: Optional[float] = None, **kwargs, ): deprecation_message = "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()` instead. Also, be aware that the output format changed from a concatenated tensor to a tuple." deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False) prompt_embeds_tuple = self.encode_prompt( prompt=prompt, device=device, num_images_per_prompt=num_images_per_prompt, do_classifier_free_guidance=do_classifier_free_guidance, negative_prompt=negative_prompt, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, lora_scale=lora_scale, **kwargs, ) # concatenate for backwards comp prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]]) return prompt_embeds # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt def encode_prompt( self, prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt=None, prompt_embeds: Optional[torch.Tensor] = None, negative_prompt_embeds: Optional[torch.Tensor] = None, lora_scale: Optional[float] = None, clip_skip: Optional[int] = None, ): r""" Encodes the prompt into text encoder hidden states. Args: prompt (`str` or `List[str]`, *optional*): prompt to be encoded device: (`torch.device`): torch device num_images_per_prompt (`int`): number of images that should be generated per prompt do_classifier_free_guidance (`bool`): whether to use classifier free guidance or not negative_prompt (`str` or `List[str]`, *optional*): The prompt or prompts not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`). prompt_embeds (`torch.Tensor`, *optional*): Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, text embeddings will be generated from `prompt` input argument. negative_prompt_embeds (`torch.Tensor`, *optional*): Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input argument. lora_scale (`float`, *optional*): A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded. clip_skip (`int`, *optional*): Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that the output of the pre-final layer will be used for computing the prompt embeddings. """ # set lora scale so that monkey patched LoRA # function of text encoder can correctly access it if lora_scale is not None and isinstance(self, LoraLoaderMixin): self._lora_scale = lora_scale # dynamically adjust the LoRA scale if not USE_PEFT_BACKEND: adjust_lora_scale_text_encoder(self.text_encoder, lora_scale) else: scale_lora_layers(self.text_encoder, lora_scale) if prompt is not None and isinstance(prompt, str): batch_size = 1 elif prompt is not None and isinstance(prompt, list): batch_size = len(prompt) else: batch_size = prompt_embeds.shape[0] if prompt_embeds is None: # textual inversion: process multi-vector tokens if necessary if isinstance(self, TextualInversionLoaderMixin): prompt = self.maybe_convert_prompt(prompt, self.tokenizer) text_inputs = self.tokenizer( prompt, padding="max_length", max_length=self.tokenizer.model_max_length, truncation=True, return_tensors="pt", ) text_input_ids = text_inputs.input_ids untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal( text_input_ids, untruncated_ids ): removed_text = self.tokenizer.batch_decode( untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1] ) logger.warning( "The following part of your input was truncated because CLIP can only handle sequences up to" f" {self.tokenizer.model_max_length} tokens: {removed_text}" ) if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: attention_mask = text_inputs.attention_mask.to(device) else: attention_mask = None if clip_skip is None: prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask) prompt_embeds = prompt_embeds[0] else: prompt_embeds = self.text_encoder( text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True ) # Access the `hidden_states` first, that contains a tuple of # all the hidden states from the encoder layers. Then index into # the tuple to access the hidden states from the desired layer. prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)] # We also need to apply the final LayerNorm here to not mess with the # representations. The `last_hidden_states` that we typically use for # obtaining the final prompt representations passes through the LayerNorm # layer. prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds) if self.text_encoder is not None: prompt_embeds_dtype = self.text_encoder.dtype elif self.unet is not None: prompt_embeds_dtype = self.unet.dtype else: prompt_embeds_dtype = prompt_embeds.dtype prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device) bs_embed, seq_len, _ = prompt_embeds.shape # duplicate text embeddings for each generation per prompt, using mps friendly method prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1) prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1) # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance and negative_prompt_embeds is None: uncond_tokens: List[str] if negative_prompt is None: uncond_tokens = [""] * batch_size elif prompt is not None and type(prompt) is not type(negative_prompt): raise TypeError( f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" f" {type(prompt)}." ) elif isinstance(negative_prompt, str): uncond_tokens = [negative_prompt] elif batch_size != len(negative_prompt): raise ValueError( f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" " the batch size of `prompt`." ) else: uncond_tokens = negative_prompt # textual inversion: process multi-vector tokens if necessary if isinstance(self, TextualInversionLoaderMixin): uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer) max_length = prompt_embeds.shape[1] uncond_input = self.tokenizer( uncond_tokens, padding="max_length", max_length=max_length, truncation=True, return_tensors="pt", ) if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: attention_mask = uncond_input.attention_mask.to(device) else: attention_mask = None negative_prompt_embeds = self.text_encoder( uncond_input.input_ids.to(device), attention_mask=attention_mask, ) negative_prompt_embeds = negative_prompt_embeds[0] if do_classifier_free_guidance: # duplicate unconditional embeddings for each generation per prompt, using mps friendly method seq_len = negative_prompt_embeds.shape[1] negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device) negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1) negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1) if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND: # Retrieve the original scale by scaling back the LoRA layers unscale_lora_layers(self.text_encoder, lora_scale) return prompt_embeds, negative_prompt_embeds # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker def run_safety_checker(self, image, device, dtype): if self.safety_checker is None: has_nsfw_concept = None else: if torch.is_tensor(image): feature_extractor_input = self.image_processor.postprocess(image, output_type="pil") else: feature_extractor_input = self.image_processor.numpy_to_pil(image) safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device) image, has_nsfw_concept = self.safety_checker( images=image, clip_input=safety_checker_input.pixel_values.to(dtype) ) return image, has_nsfw_concept # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents def decode_latents(self, latents): deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead" deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False) latents = 1 / self.vae.config.scaling_factor * latents image = self.vae.decode(latents, return_dict=False)[0] image = (image / 2 + 0.5).clamp(0, 1) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 image = image.cpu().permute(0, 2, 3, 1).float().numpy() return image # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs def prepare_extra_step_kwargs(self, generator, eta): # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) extra_step_kwargs = {} if accepts_eta: extra_step_kwargs["eta"] = eta # check if the scheduler accepts generator accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys()) if accepts_generator: extra_step_kwargs["generator"] = generator return extra_step_kwargs def check_inputs( self, prompt, image, negative_prompt=None, prompt_embeds=None, negative_prompt_embeds=None, controlnet_conditioning_scale=1.0, control_guidance_start=0.0, control_guidance_end=1.0, callback_on_step_end_tensor_inputs=None, ): if callback_on_step_end_tensor_inputs is not None and not all( k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs ): raise ValueError( f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}" ) if prompt is not None and prompt_embeds is not None: raise ValueError( f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to" " only forward one of the two." ) elif prompt is None and prompt_embeds is None: raise ValueError( "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined." ) elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)): raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") if negative_prompt is not None and negative_prompt_embeds is not None: raise ValueError( f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:" f" {negative_prompt_embeds}. Please make sure to only forward one of the two." ) if prompt_embeds is not None and negative_prompt_embeds is not None: if prompt_embeds.shape != negative_prompt_embeds.shape: raise ValueError( "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but" f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`" f" {negative_prompt_embeds.shape}." ) # Check `image` and `controlnet_conditioning_scale` is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance( self.unet, torch._dynamo.eval_frame.OptimizedModule ) if ( isinstance(self.unet, UNetControlNetXSModel) or is_compiled and isinstance(self.unet._orig_mod, UNetControlNetXSModel) ): self.check_image(image, prompt, prompt_embeds) if not isinstance(controlnet_conditioning_scale, float): raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.") else: assert False start, end = control_guidance_start, control_guidance_end if start >= end: raise ValueError( f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}." ) if start < 0.0: raise ValueError(f"control guidance start: {start} can't be smaller than 0.") if end > 1.0: raise ValueError(f"control guidance end: {end} can't be larger than 1.0.") def check_image(self, image, prompt, prompt_embeds): image_is_pil = isinstance(image, PIL.Image.Image) image_is_tensor = isinstance(image, torch.Tensor) image_is_np = isinstance(image, np.ndarray) image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image) image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor) image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray) if ( not image_is_pil and not image_is_tensor and not image_is_np and not image_is_pil_list and not image_is_tensor_list and not image_is_np_list ): raise TypeError( f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}" ) if image_is_pil: image_batch_size = 1 else: image_batch_size = len(image) if prompt is not None and isinstance(prompt, str): prompt_batch_size = 1 elif prompt is not None and isinstance(prompt, list): prompt_batch_size = len(prompt) elif prompt_embeds is not None: prompt_batch_size = prompt_embeds.shape[0] if image_batch_size != 1 and image_batch_size != prompt_batch_size: raise ValueError( f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}" ) def prepare_image( self, image, width, height, batch_size, num_images_per_prompt, device, dtype, do_classifier_free_guidance=False, ): image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32) image_batch_size = image.shape[0] if image_batch_size == 1: repeat_by = batch_size else: # image batch size is the same as prompt batch size repeat_by = num_images_per_prompt image = image.repeat_interleave(repeat_by, dim=0) image = image.to(device=device, dtype=dtype) if do_classifier_free_guidance: image = torch.cat([image] * 2) return image # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None): shape = ( batch_size, num_channels_latents, int(height) // self.vae_scale_factor, int(width) // self.vae_scale_factor, ) if isinstance(generator, list) and len(generator) != batch_size: raise ValueError( f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" f" size of {batch_size}. Make sure the batch size matches the length of the generators." ) if latents is None: latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype) else: latents = latents.to(device) # scale the initial noise by the standard deviation required by the scheduler latents = latents * self.scheduler.init_noise_sigma return latents @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.guidance_scale def guidance_scale(self): return self._guidance_scale @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.clip_skip def clip_skip(self): return self._clip_skip @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.do_classifier_free_guidance def do_classifier_free_guidance(self): return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.cross_attention_kwargs def cross_attention_kwargs(self): return self._cross_attention_kwargs @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.num_timesteps def num_timesteps(self): return self._num_timesteps @torch.no_grad() @replace_example_docstring(EXAMPLE_DOC_STRING) def __call__( self, prompt: Union[str, List[str]] = None, image: PipelineImageInput = None, height: Optional[int] = None, width: Optional[int] = None, num_inference_steps: int = 50, guidance_scale: float = 7.5, negative_prompt: Optional[Union[str, List[str]]] = None, num_images_per_prompt: Optional[int] = 1, eta: float = 0.0, generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, latents: Optional[torch.Tensor] = None, prompt_embeds: Optional[torch.Tensor] = None, negative_prompt_embeds: Optional[torch.Tensor] = None, output_type: Optional[str] = "pil", return_dict: bool = True, cross_attention_kwargs: Optional[Dict[str, Any]] = None, controlnet_conditioning_scale: Union[float, List[float]] = 1.0, control_guidance_start: float = 0.0, control_guidance_end: float = 1.0, clip_skip: Optional[int] = None, callback_on_step_end: Optional[ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks] ] = None, callback_on_step_end_tensor_inputs: List[str] = ["latents"], ): r""" The call function to the pipeline for generation. Args: prompt (`str` or `List[str]`, *optional*): The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`. image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,: `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`): The ControlNet input condition to provide guidance to the `unet` for generation. If the type is specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in `init`, images must be passed as a list such that each element of the list can be correctly batched for input to a single ControlNet. height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`): The height in pixels of the generated image. width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`): The width in pixels of the generated image. num_inference_steps (`int`, *optional*, defaults to 50): The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference. guidance_scale (`float`, *optional*, defaults to 7.5): A higher guidance scale value encourages the model to generate images closely linked to the text `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`. negative_prompt (`str` or `List[str]`, *optional*): The prompt or prompts to guide what to not include in image generation. If not defined, you need to pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`). num_images_per_prompt (`int`, *optional*, defaults to 1): The number of images to generate per prompt. eta (`float`, *optional*, defaults to 0.0): Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers. generator (`torch.Generator` or `List[torch.Generator]`, *optional*): A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation deterministic. latents (`torch.Tensor`, *optional*): Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image generation. Can be used to tweak the same generation with different prompts. If not provided, a latents tensor is generated by sampling using the supplied random `generator`. prompt_embeds (`torch.Tensor`, *optional*): Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not provided, text embeddings are generated from the `prompt` input argument. negative_prompt_embeds (`torch.Tensor`, *optional*): Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument. output_type (`str`, *optional*, defaults to `"pil"`): The output format of the generated image. Choose between `PIL.Image` or `np.array`. return_dict (`bool`, *optional*, defaults to `True`): Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a plain tuple. cross_attention_kwargs (`dict`, *optional*): A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0): The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set the corresponding scale as a list. control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0): The percentage of total steps at which the ControlNet starts applying. control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0): The percentage of total steps at which the ControlNet stops applying. clip_skip (`int`, *optional*): Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that the output of the pre-final layer will be used for computing the prompt embeddings. callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*): A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of each denoising step during the inference. with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by `callback_on_step_end_tensor_inputs`. callback_on_step_end_tensor_inputs (`List`, *optional*): The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the `._callback_tensor_inputs` attribute of your pipeine class. Examples: Returns: [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned, otherwise a `tuple` is returned where the first element is a list with the generated images and the second element is a list of `bool`s indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content. """ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)): callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs unet = self.unet._orig_mod if is_compiled_module(self.unet) else self.unet # 1. Check inputs. Raise error if not correct self.check_inputs( prompt, image, negative_prompt, prompt_embeds, negative_prompt_embeds, controlnet_conditioning_scale, control_guidance_start, control_guidance_end, callback_on_step_end_tensor_inputs, ) self._guidance_scale = guidance_scale self._clip_skip = clip_skip self._cross_attention_kwargs = cross_attention_kwargs self._interrupt = False # 2. Define call parameters if prompt is not None and isinstance(prompt, str): batch_size = 1 elif prompt is not None and isinstance(prompt, list): batch_size = len(prompt) else: batch_size = prompt_embeds.shape[0] device = self._execution_device # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. do_classifier_free_guidance = guidance_scale > 1.0 # 3. Encode input prompt text_encoder_lora_scale = ( cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None ) prompt_embeds, negative_prompt_embeds = self.encode_prompt( prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, lora_scale=text_encoder_lora_scale, clip_skip=clip_skip, ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes if do_classifier_free_guidance: prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds]) # 4. Prepare image image = self.prepare_image( image=image, width=width, height=height, batch_size=batch_size * num_images_per_prompt, num_images_per_prompt=num_images_per_prompt, device=device, dtype=unet.dtype, do_classifier_free_guidance=do_classifier_free_guidance, ) height, width = image.shape[-2:] # 5. Prepare timesteps self.scheduler.set_timesteps(num_inference_steps, device=device) timesteps = self.scheduler.timesteps # 6. Prepare latent variables num_channels_latents = self.unet.in_channels latents = self.prepare_latents( batch_size * num_images_per_prompt, num_channels_latents, height, width, prompt_embeds.dtype, device, generator, latents, ) # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) # 8. Denoising loop num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order self._num_timesteps = len(timesteps) is_controlnet_compiled = is_compiled_module(self.unet) is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1") with self.progress_bar(total=num_inference_steps) as progress_bar: for i, t in enumerate(timesteps): # Relevant thread: # https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428 if is_controlnet_compiled and is_torch_higher_equal_2_1: torch._inductor.cudagraph_mark_step_begin() # expand the latents if we are doing classifier free guidance latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) # predict the noise residual apply_control = ( i / len(timesteps) >= control_guidance_start and (i + 1) / len(timesteps) <= control_guidance_end ) noise_pred = self.unet( sample=latent_model_input, timestep=t, encoder_hidden_states=prompt_embeds, controlnet_cond=image, conditioning_scale=controlnet_conditioning_scale, cross_attention_kwargs=cross_attention_kwargs, return_dict=True, apply_control=apply_control, ).sample # perform guidance if do_classifier_free_guidance: noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0] if callback_on_step_end is not None: callback_kwargs = {} for k in callback_on_step_end_tensor_inputs: callback_kwargs[k] = locals()[k] callback_outputs = callback_on_step_end(self, i, t, callback_kwargs) latents = callback_outputs.pop("latents", latents) prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds) negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds) if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): progress_bar.update() # If we do sequential model offloading, let's offload unet and controlnet # manually for max memory savings if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None: self.unet.to("cpu") self.controlnet.to("cpu") torch.cuda.empty_cache() if not output_type == "latent": image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[ 0 ] image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype) else: image = latents has_nsfw_concept = None if has_nsfw_concept is None: do_denormalize = [True] * image.shape[0] else: do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept] image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize) # Offload all models self.maybe_free_model_hooks() if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
import React, { useState, useEffect, useContext } from 'react'; import axios from 'axios'; import { useNavigate } from 'react-router-dom'; import { toast } from 'react-toastify'; import { Input, Select, Button } from 'antd'; import { AuthContext } from "../context/auth.context"; import "./CreatePlaylist.css" const { Option } = Select; const CreatePlaylist = ({ playlistId }) => { const [description, setDescription] = useState(''); const [image, setImage] = useState(null); const [name, setName] = useState(''); const [selectedTrack, setSelectedTrack] = useState(''); const [tracks, setTracks] = useState([]); const {isLoggedIn } = useContext(AuthContext); const storedToken = localStorage.getItem("authToken") const api = axios.create({ baseURL: process.env.REACT_APP_API_URL, headers: { Authorization: `Bearer ${storedToken}`, }, }); const navigate = useNavigate(); useEffect(() => { const fetchTracks = async () => { try { const response = await api.get(`/api/track`); setTracks(response.data.tracks); } catch (err) { console.error('Error fetching tracks:', err); } }; fetchTracks(); }, []); const handleImageUpload = (e) => { const selectedImage = e.target.files[0]; setImage(selectedImage); }; const handleSubmit = async (e) => { e.preventDefault(); const formData = new FormData(); formData.append('description', description); formData.append('image', image); formData.append('name', name); formData.append('trackId', selectedTrack); try { const response = await api.post(`/api/create`, formData, { headers: { 'Content-Type': 'multipart/form-data', }, }); if (response.status === 201) { toast.success('Playlist created successfully.'); navigate('/playlist'); } else { toast.error('Error creating playlist. Please try again.'); } } catch (err) { toast.error('Error creating playlist. Please try again.'); console.error('Error creating playlist:', err); } }; return ( <div> <h5>Create Playlist</h5> <div className='create-playlist'> <form onSubmit={handleSubmit}> <div> <label>Description:</label> <Input type="text" name="description" value={description} onChange={(e) => setDescription(e.target.value)} /> </div> <div> <label>Image:</label> <Input type="file" name="image" accept="image/*" onChange={handleImageUpload} /> </div> <div> <label>Name:</label> <Input type="text" name="name" value={name} onChange={(e) => setName(e.target.value)} /> </div> <div> <label className='lab-playlist'>Select Track</label> <Select className="playlist-trackse" name="trackId" value={selectedTrack} onChange={(value) => setSelectedTrack(value)} // Update the selected track required > <Option value="">Select a track</Option> {tracks.map((track) => ( <Option key={track._id} value={track._id}> {track.name} by {track.artist} </Option> ))} </Select> </div> <div className='btn-playlist'> <Button type="primary" htmlType="submit"> Create Playlist </Button> </div> </form> </div> </div> ); }; export default CreatePlaylist;
# Getting Started # Mi Proyecto Spring Boot con H2 Este es un proyecto de ejemplo que utiliza Spring Boot y H2. ## Requisitos - Java 8 o superior - Gradle ## Configuración El proyecto está configurado para utilizar una base de datos H2 en memoria. La configuración de la base de datos se encuentra en el archivo `src/main/resources/application.properties`. ## Ejecución Para ejecutar el proyecto, puedes usar el plugin Spring Boot de Gradle. Con Gradle: ```bash ./gradlew bootRun ``` ## Pruebas El proyecto incluye pruebas unitarias que puedes ejecutar con Gradle. ```bash ./gradlew test ``` ## API El proyecto incluye una API REST con los siguientes endpoints: POST /api/users/register: Crea un nuevo usuario. ## Licencia Este proyecto está licenciado bajo los términos de la licencia MIT. ### Reference Documentation For further reference, please consider the following sections: * [Official Gradle documentation](https://docs.gradle.org) * [Spring Boot Gradle Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/3.2.1/gradle-plugin/reference/html/) * [Create an OCI image](https://docs.spring.io/spring-boot/docs/3.2.1/gradle-plugin/reference/html/#build-image) * [Spring Web](https://docs.spring.io/spring-boot/docs/3.2.1/reference/htmlsingle/index.html#web) * [Spring Data JPA](https://docs.spring.io/spring-boot/docs/3.2.1/reference/htmlsingle/index.html#data.sql.jpa-and-spring-data) ### Guides The following guides illustrate how to use some features concretely: * [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) * [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) * [Building REST services with Spring](https://spring.io/guides/tutorials/rest/) * [Accessing Data with JPA](https://spring.io/guides/gs/accessing-data-jpa/) ### Additional Links These additional references should also help you: * [Gradle Build Scans – insights for your project's build](https://scans.gradle.com#gradle)
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.translateFiles = void 0; const fs_1 = __importDefault(require("fs")); const translateFile_1 = require("./translateFile"); const showHelp = () => { console.log(`ERROR: Could not read \`.translationrc\` file. .translationrc should exist alongside translation files and have the format: { "source": { "file": "en.json", "language": "English" }, "destinations": [ { "file": "de.json", "language": "German" }, // and so on ], [optional] "extraPrompt": "More instructions for the LLM" [optional] "model": "gpt-3.5-turbo-1106" } `); }; const translateFiles = async (openAiKey) => { let fileMappings = {}; try { fileMappings = JSON.parse(fs_1.default.readFileSync(".translationrc", "utf8")); } catch { showHelp(); } if (!fileMappings.source || !fileMappings.destinations) { showHelp(); process.exit(1); } for (const dest of fileMappings.destinations) { const sourceFile = fileMappings.source.file; const destFile = dest.file; const sourceLanguage = fileMappings.source.language; const destLanguage = dest.language; const extraPrompt = fileMappings.extraPrompt; const model = fileMappings.model || "gpt-3.5-turbo-1106"; if (!sourceFile || !destFile || !sourceLanguage || !destLanguage || !model) { showHelp(); process.exit(1); } if (!fs_1.default.existsSync(destFile)) { fs_1.default.writeFileSync(destFile, "{}"); } console.log(`\n\nTranslating ${sourceFile} (${sourceLanguage}) to ${destFile} (${destLanguage})`); await (0, translateFile_1.translateFile)(sourceFile, destFile, sourceLanguage, destLanguage, openAiKey, model, extraPrompt); } }; exports.translateFiles = translateFiles;
package com.study.config; import org.springframework.util.StringUtils; import org.springframework.web.servlet.LocaleResolver; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Locale; public class MyLocaleResolver implements LocaleResolver { //解析请求 @Override public Locale resolveLocale(HttpServletRequest request) { //获取请求中的语言参数 String language = request.getParameter("l"); Locale locale = Locale.getDefault();//如果没有就使用默认的 //如果请求的参数携带了国际化的参数 if(StringUtils.hasLength(language)){ //zh_CN String[] split = language.split("_"); locale = new Locale(split[0], split[1]); } return locale; } @Override public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) { } }
using System; using UnityEngine; namespace Cosmos.Scene { public interface ISceneManager : IModuleManager, IModuleInstance { /// <summary> /// 异步加载场景; /// </summary> /// <param name="sceneInfo">场景信息</param> /// <param name="callback">加载完毕后的回调</param> /// <returns>协程对象</returns> Coroutine LoadSceneAsync(SceneAssetInfo sceneInfo, Action callback = null); /// <summary> /// 异步加载场景; /// </summary> /// <param name="sceneInfo">场景信息</param> /// <param name="progress">加载场景进度回调</param> /// <param name="callback">场景加载完毕回调</param> /// <returns>协程对象</returns> Coroutine LoadSceneAsync(SceneAssetInfo sceneInfo, Action<float> progress, Action callback = null); /// <summary> /// 异步加载场景; /// </summary> /// <param name="sceneInfo">场景信息</param> /// <param name="condition">场景加载完成的条件</param> /// <param name="callback">场景加载完毕回调</param> /// <returns>协程对象</returns> Coroutine LoadSceneAsync(SceneAssetInfo sceneInfo, Func<bool> condition, Action callback = null); /// <summary> /// 异步加载场景; /// </summary> /// <param name="sceneInfo">场景信息</param> /// <param name="progress">加载场景进度回调</param> /// <param name="condition">场景加载完成的条件</param> /// <param name="callback">场景加载完毕回调</param> /// <returns>协程对象</returns> Coroutine LoadSceneAsync(SceneAssetInfo sceneInfo, Action<float> progress, Func<bool> condition, Action callback = null); /// <summary> /// 异步加载场景; /// </summary> /// <param name="sceneInfo">场景信息</param> /// <param name="progressProvider">自定义的加载进度0-1</param> /// <param name="progress">加载场景进度回调</param> /// <param name="callback">场景加载完毕回调</param> /// <returns>协程对象</returns> Coroutine LoadSceneAsync(SceneAssetInfo sceneInfo, Func<float> progressProvider, Action<float> progress, Action callback = null); /// <summary> /// 异步加载场景; /// </summary> /// <param name="sceneInfo">场景信息</param> /// <param name="progressProvider">自定义的加载进度0-1</param> /// <param name="progress">加载场景进度回调</param> /// <param name="condition">场景加载完成的条件</param> /// <param name="callback">场景加载完毕回调</param> /// <returns>协程对象</returns> Coroutine LoadSceneAsync(SceneAssetInfo sceneInfo, Func<float> progressProvider, Action<float> progress, Func<bool> condition, Action callback = null); /// <summary> /// 异步卸载场景; /// </summary> /// <param name="sceneInfo">场景信息</param> /// <param name="callback">场景卸载完毕后的回调</param> /// <returns>协程对象</returns> Coroutine UnloadSceneAsync(SceneAssetInfo sceneInfo, Action callback = null); /// <summary> /// 异步卸载场景; /// </summary> /// <param name="sceneInfo">场景信息</param> /// <param name="progress">卸载场景的进度</param> /// <param name="callback">场景卸载完毕后的回调</param> /// <returns>协程对象</returns> Coroutine UnloadSceneAsync(SceneAssetInfo sceneInfo, Action<float> progress, Action callback = null); /// <summary> /// 异步卸载场景; /// </summary> /// <param name="sceneInfo">场景信息</param> /// <param name="condition">卸载场景完成的条件</param> /// <param name="callback">场景卸载完毕后的回调</param> /// <returns>协程对象</returns> Coroutine UnloadSceneAsync(SceneAssetInfo sceneInfo, Func<bool> condition, Action callback = null); /// <summary> /// 异步卸载场景; /// </summary> /// <param name="sceneInfo">场景信息</param> /// <param name="progress">卸载场景的进度</param> /// <param name="condition">卸载场景完成的条件</param> /// <param name="callback">场景卸载完毕后的回调</param> /// <returns>协程对象</returns> Coroutine UnloadSceneAsync(SceneAssetInfo sceneInfo, Action<float> progress, Func<bool> condition, Action callback = null); } }
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:widget_app/api_repository/home_repository.dart'; import 'package:widget_app/bloc/home/home_bloc.dart'; import 'package:widget_app/bloc/home/home_event.dart'; import 'package:widget_app/bloc/home/home_state.dart'; import 'package:widget_app/colors/hexColor.dart'; import 'package:widget_app/models/news/new.dart'; import '../components/home/detailNew.dart'; import '../components/home/newItem.dart'; class HomeWidget extends StatefulWidget { const HomeWidget({super.key}); @override State<HomeWidget> createState() => _HomeWidgetState(); } class _HomeWidgetState extends State<HomeWidget> { late HomeBloc homeBloc; final RefreshController _refreshController = RefreshController(initialRefresh: false); @override void initState() { super.initState(); homeBloc = HomeBloc(homeRepo: HomeRepoImpl()) ..add(const GetNewsEvent(page: 1)); } @override Widget build(BuildContext context) { return BlocProvider( create: (_) => homeBloc, child: Scaffold( appBar: AppBar( title: const Text( "What's New", style: TextStyle(fontWeight: FontWeight.bold), ), backgroundColor: HexColor.redNav, ), backgroundColor: HexColor.bgDark, body: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Image.asset( "assets/homeImage.png", fit: BoxFit.fitWidth, ), Expanded( child: SizedBox( child: BlocConsumer<HomeBloc, HomeState>( listener: (context, state) { if (_refreshController.isRefresh) { _refreshController.refreshCompleted(); } }, builder: (context, state) { if (state is NewsState) { return SmartRefresher( enablePullDown: true, controller: _refreshController, onRefresh: () { context .read<HomeBloc>() .add(const RefreshNewsEvent()); }, child: ListView.builder( padding: const EdgeInsets.symmetric( horizontal: 16, vertical: 10), itemCount: state.news.length, itemBuilder: (context, index) => NewItem( title: state.news[index].title, typeNew: state.news[index].categoryName, date: state.news[index].createdAt, isNew: state.news[index].isNew(), onTap: () { showModalBottomSheet( context: context, backgroundColor: Colors.transparent, builder: (context) { return DetailNew( detailNew: state.news[index], ); }, ); }, ), ), ); } return Container(); }, ), ), ) ], )), ); } }
import { ReactNode, createContext, useState, useContext, useEffect, } from "react"; import { UserContext } from "./UserContext"; import { DonationContext } from "./DonationContext"; import api from "../services/api"; import { IDonation } from "../interfaces/donations.interface"; import { // IAllDataDonation, IUpdateDonation, } from "../interfaces/donations.interface"; import { toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; interface IDonorContextProviderProps { children: ReactNode; } interface IDonorContextData { allDataDonations: IDonation[]; setAllDataDonations: React.Dispatch<React.SetStateAction<IDonation[]>>; newSearch: string; setNewSearch: React.Dispatch<React.SetStateAction<string>>; setSearched: React.Dispatch<React.SetStateAction<string>>; onSubmitUpdateDonation: (data: IUpdateDonation) => Promise<void>; onClickDeleteDonation: (id: string) => Promise<void>; } export const DonorContext = createContext<IDonorContextData>( {} as IDonorContextData ); export const DonorContextProvider = ({ children, }: IDonorContextProviderProps) => { const [allDataDonations, setAllDataDonations] = useState<IDonation[]>([]); const [newSearch, setNewSearch] = useState(""); const [searched, setSearched] = useState(""); const { loading } = useContext(UserContext); const { donation, setDonation } = useContext(DonationContext); const handleSetAllDataDonations = (data: IDonation[]) => { setAllDataDonations(data); }; const onSubmitUpdateDonation = async (data: IUpdateDonation) => { const food = data.food; const quantity = data.quantity; const token = localStorage.getItem("@userToken"); const id = data.id; try { api.defaults.headers.common.authorization = `Bearer ${token}`; const newDonation = await api.patch(`donations/${id}/`, { food, quantity, }); // const newDonation = await api.get<IDonation>(`donations/${id}`); setDonation(newDonation.data); toast.success("Doação editada com sucesso!"); } catch (error) { console.log(error); toast.error("Ops! Houve algum erro"); } }; const onClickDeleteDonation = async (id: string) => { const token = localStorage.getItem("@userToken"); try { api.defaults.headers.common.authorization = `Bearer ${token}`; await api.delete(`donations/${id}/`); // const result = await api.get<IDonation[]>(`donations/expand`); const result = await api.get<IDonation[]>(`donations/`); setAllDataDonations(result.data); toast.success("Doação excluída"); } catch (error) { console.log(error); toast.error("Ops! Houve algum erro"); } }; useEffect(() => { const renderSearch = async () => { try { // const result = await api.get<IDonation[]>(`donations/expand`); const result = await api.get<IDonation[]>(`donations/`); const filtered = result.data.filter( (element) => element.food .toLowerCase() .includes(searched.toLowerCase().trim()) || element.user.address.city .toLowerCase() .includes(searched.toLowerCase().trim()) || element.user.address.state .toLowerCase() .includes(searched.toLowerCase().trim()) || element.classification.name .toLowerCase() .includes(searched.toLowerCase().trim()) ); setAllDataDonations(filtered); } catch (error) { console.log(error); } }; renderSearch(); }, [searched]); useEffect(() => { const loadDonations = async () => { try { // const result = await api.get<IDonation[]>(`donations/expand`); const result = await api.get<IDonation[]>(`donations/`); handleSetAllDataDonations(result.data); } catch (error) { console.log(error); } }; loadDonations(); }, [loading, donation]); return ( <DonorContext.Provider value={{ allDataDonations, setAllDataDonations, setNewSearch, newSearch, setSearched, onSubmitUpdateDonation, onClickDeleteDonation, }} > {children} </DonorContext.Provider> ); };
import React, { useEffect } from 'react'; import './main.css'; import { Link, useNavigate } from 'react-router-dom'; import { HiOutlineLocationMarker } from 'react-icons/hi'; import { BsClipboardCheck } from 'react-icons/bs'; import { MdLanguage } from 'react-icons/md'; import Home from '../Home/Home'; import img from '../../../assets/img/img (1).jpg'; import img2 from '../../../assets/img/img (2).jpg'; import img3 from '../../../assets/img/img (3).jpg'; import img4 from '../../../assets/img/img (4).jpg'; import img5 from '../../../assets/img/img (5).jpg'; import img6 from '../../../assets/img/img (6).jpg'; import img7 from '../../../assets/img/img (7).jpg'; import img8 from '../../../assets/img/img (8).jpg'; import img9 from '../../../assets/img/img (9).jpg'; import Aos from 'aos'; import 'aos/dist/aos.css'; const Data = [ { id: 1, imgSrc: img, destTitle: 'Website bán hàng', location: 'PHP', grade: 'FullStack', fees: '$700', description: ' Website bán điện thoại là một kênh trực tuyến giúp bạn mua sắm điện thoại di động một cách tiện lợi và nhanh chóng. Website bán điện thoại thường cung cấp đa dạng các mẫu điện thoại từ nhiều thương hiệu nổi tiếng như iPhone, Samsung, Oppo, Xiaomi, Realme,... với mức giá cạnh tranh.', }, { id: 2, imgSrc: img2, destTitle: 'Website bán hàng', location: 'PHP', grade: 'FullStack', fees: '$700', description: ' Website bán điện thoại là một kênh trực tuyến giúp bạn mua sắm điện thoại di động một cách tiện lợi và nhanh chóng. Website bán điện thoại thường cung cấp đa dạng các mẫu điện thoại từ nhiều thương hiệu nổi tiếng như iPhone, Samsung, Oppo, Xiaomi, Realme,... với mức giá cạnh tranh.', }, { id: 3, imgSrc: img3, destTitle: 'Website bán hàng', location: 'PHP', grade: 'FullStack', fees: '$700', description: ' Website bán điện thoại là một kênh trực tuyến giúp bạn mua sắm điện thoại di động một cách tiện lợi và nhanh chóng. Website bán điện thoại thường cung cấp đa dạng các mẫu điện thoại từ nhiều thương hiệu nổi tiếng như iPhone, Samsung, Oppo, Xiaomi, Realme,... với mức giá cạnh tranh.', }, { id: 4, imgSrc: img4, destTitle: 'Website bán hàng', location: 'PHP', grade: 'FullStack', fees: '$700', description: ' Website bán điện thoại là một kênh trực tuyến giúp bạn mua sắm điện thoại di động một cách tiện lợi và nhanh chóng. Website bán điện thoại thường cung cấp đa dạng các mẫu điện thoại từ nhiều thương hiệu nổi tiếng như iPhone, Samsung, Oppo, Xiaomi, Realme,... với mức giá cạnh tranh.', }, { id: 5, imgSrc: img5, destTitle: 'Website bán hàng', location: 'PHP', grade: 'FullStack', fees: '$700', description: ' Website bán điện thoại là một kênh trực tuyến giúp bạn mua sắm điện thoại di động một cách tiện lợi và nhanh chóng. Website bán điện thoại thường cung cấp đa dạng các mẫu điện thoại từ nhiều thương hiệu nổi tiếng như iPhone, Samsung, Oppo, Xiaomi, Realme,... với mức giá cạnh tranh.', }, { id: 6, imgSrc: img6, destTitle: 'Website bán hàng', location: 'PHP', grade: 'FullStack', fees: '$700', description: ' Website bán điện thoại là một kênh trực tuyến giúp bạn mua sắm điện thoại di động một cách tiện lợi và nhanh chóng. Website bán điện thoại thường cung cấp đa dạng các mẫu điện thoại từ nhiều thương hiệu nổi tiếng như iPhone, Samsung, Oppo, Xiaomi, Realme,... với mức giá cạnh tranh.', }, { id: 7, imgSrc: img7, destTitle: 'Website bán hàng', location: 'PHP', grade: 'FullStack', fees: '$700', description: ' Website bán điện thoại là một kênh trực tuyến giúp bạn mua sắm điện thoại di động một cách tiện lợi và nhanh chóng. Website bán điện thoại thường cung cấp đa dạng các mẫu điện thoại từ nhiều thương hiệu nổi tiếng như iPhone, Samsung, Oppo, Xiaomi, Realme,... với mức giá cạnh tranh.', }, { id: 8, imgSrc: img8, destTitle: 'Website bán hàng', location: 'PHP', grade: 'FullStack', fees: '$700', description: ' Website bán điện thoại là một kênh trực tuyến giúp bạn mua sắm điện thoại di động một cách tiện lợi và nhanh chóng. Website bán điện thoại thường cung cấp đa dạng các mẫu điện thoại từ nhiều thương hiệu nổi tiếng như iPhone, Samsung, Oppo, Xiaomi, Realme,... với mức giá cạnh tranh.', }, { id: 9, imgSrc: img9, destTitle: 'Website bán hàng', location: 'PHP', grade: 'FullStack', fees: '$700', description: ' Website bán điện thoại là một kênh trực tuyến giúp bạn mua sắm điện thoại di động một cách tiện lợi và nhanh chóng. Website bán điện thoại thường cung cấp đa dạng các mẫu điện thoại từ nhiều thương hiệu nổi tiếng như iPhone, Samsung, Oppo, Xiaomi, Realme,... với mức giá cạnh tranh.', }, ]; const Main = () => { useEffect(() => { Aos.init({ duration: 2000 }); }, []); return ( <section className="main container section"> <div className="secContent grid"> {Data.map( ({ id, imgSrc, destTitle, location, grade, fees, description, }) => { return ( <div key={id} data-aos="fade-up" className="signleDestination" > <div className="imgeDiv"> <img src={imgSrc} alt={destTitle} /> </div> <div className="cardInfo"> <h4 className="desTitle">{destTitle}</h4> <span className="containent flex"> <MdLanguage className="icon" /> <span className="name">{location}</span> </span> <div className="fees flex"> <div className="grade"> <span>{grade}</span> </div> <div className="price"> <h5>{fees}</h5> </div> </div> <div className="desc"> <p>{description}</p> </div> <Link to={`/ShopWeb/ChiTiet/:slug`}> <button className="btn flex"> XEM NGAY{' '} <BsClipboardCheck className="icon" /> </button> </Link> </div> </div> ); }, )} </div> </section> ); }; export default Main;
======== $natural ======== .. default-domain:: mongodb Definition ---------- .. operator:: $natural Use the :operator:`$natural` operator to use :term:`natural order` for the results of a sort operation. Natural order refers to the logical :ref:`ordering <return-natural-order>` of documents internally within the database. The :operator:`$natural` operator uses the following syntax to return documents in the order they exist on disk: .. code-block:: javascript db.collection.find().sort( { $natural: 1 } ) Behavior -------- On a sharded collection the :operator:`$natural` operator returns a collection scan sorted in :ref:`natural order <return-natural-order>`, the order the database inserts and stores documents on disk. .. include:: /includes/fact-natural-parameter.rst .. include:: /includes/fact-natural-sort-order-text-query-restriction.rst Examples -------- Reverse Order ~~~~~~~~~~~~~ Use ``{ $natural: -1 }`` to return documents in the reverse order as they occur on disk: .. code-block:: javascript db.collection.find().sort( { $natural: -1 } ) Additional Information ---------------------- :method:`cursor.sort()`
Short usage notes on the R4G framework Format of this file: Long lines (essentially paragraphs), ASCII characters, UNIX line endings. All symbols of the public interface have a prefix of "r4g". That is short for "Revision Control System, 4th Generation". All header files of the public interface contain a base-35 UUID as the last part of their name. All other header files are for internal use by the framework functions only and should not be used by application code. The UUID in the header file names is part of the interface. It is guaranteed never to change, even though the "human readable" part of the file name can change at any time. In such cases, the new name can easily be found out by looking which updated new file name contains the same UUID as the known old file name. Most R4G functions expect a parameter of type "r4g" as their first argument, which is a pointer to the current resource context. It is normally called "xc", but this is just a voluntary convention. Functions with the prefix "r4g_" are expected to automatically record any resources allocated to the current resource context (represented by the r4g pointer). Such resources can be freed by a call to r4g_free() or r4g_die(). Functions which require the r4g pointer just for calling r4g_die() in case of an error, but which do not add any allocated resources to the resource context, have the prefix "r4ga_" - the "a" is for "aware". That is, such functions integrate into the R4G framework regarding error handling, but do no automatic resource management. Examples are the functions r4g_malloc() which allocates a memory block and records it in the current resource context, while r4ga_realloc() reallocates a memory block but does not track this in the resource context. Generally, "r4ga_" functions are functions otherwise unrelated to the R4G framework which have only been wrapped in order to call r4g_die() in case of an error. Before any other R4G functions can be used, a resource context must be allocated. This is accomplished by the function r4g_create(int errcode). This function allocates and returns the context and never returns in case of an error. In the latter case, it prints an error message to stderr and terminates with exit(errcode). After a resource context has been created, the remaining framework functions can be called. Before an application terminates, the recorded resources need to be freed. This can happen in 2 ways: Either by the application itself calling r4g_free(xc, 0) or by anyone calling r4g_die() which calls r4g_free internally before exiting. The various framework functions which allocate resources and register them with a resource context use the function r4g_add() for this. Each call to r4g_add() adds exactly one resource to the context. The function r4g_count() can be called to return the current number of resources in the context. The second argument to r4g_free() is the number of resources *not* to free, i. e. to keep. Every resource context is a resource itself, and contains itself as the first resource. Therefore r4g_count() will always return at least 1, and r4g_free(xc, 0) deallocates everything including the resource context itself. The resource context generally acts like a LIFO: r4g_add adds new resources at the end, and r4g_free always deallocates the resource from the end in the reverse order of which they have been allocated.
import { type TypedUseSelectorHook, useSelector, useDispatch } from 'react-redux' import { type Dispatch, type ThunkDispatch, type UnknownAction } from '@reduxjs/toolkit' import type store from '../Store' import * as ls from './ls' export const loadState = (): State => { try { const serializedStore = ls.get('YOUR_PROJECT') if (serializedStore === null || serializedStore === undefined) { return { userInfo: userInitialState } } return { ...serializedStore } } catch (e) { return { userInfo: userInitialState } } } export const saveState = (state: State): boolean => { const { ...stateToSave } = state try { ls.set('YOUR_PROJECT', stateToSave) return ls.has('YOUR_PROJECT') } catch (e) { return false } } export const userInitialState: UserStore = { user: { email: '', familyName: '', givenName: '', hd: '', id: '', locale: '', name: '', picture: '', verifiedEmail: false }, authStatus: 'idle', isUserLogged: false, token: '', errorMessage: '' } export const useAppSelector: TypedUseSelectorHook<State> = useSelector export const useAppDispatch = (): ThunkDispatch<{ userInfo: UserStore }, undefined, UnknownAction> & Dispatch<UnknownAction> => useDispatch<typeof store.dispatch>() export const formatThunkError = (e: unknown, fallback: string): string => Boolean((e as any).response.data) ? toString((e as any).response.data, fallback) : toString(e, fallback) const toString = (data: unknown, fallback: string): string => { if (typeof data === 'string') return data if (typeof data === 'object') { if (data !== null && 'message' in data) { return toString(data.message, fallback) } return fallback } else { // eslint-disable-next-line @typescript-eslint/no-explicit-any return (data as unknown as any).toString() } }
import React, {useEffect, useState} from "react"; import requests from "../../services/requests"; import functions from "../../services/functions"; import api_roliste from "../../services/api_roliste"; import {useNavigate} from "react-router-dom"; import axios from "axios"; const Inscription = ({buttonImg}) => { const [inscriptionEmailValue, setInscriptionEmailValue] = useState(""); const [inscriptionPasswordValue, setInscriptionPasswordValue] = useState(""); const [inscriptionPasswordRepeatValue, setInscriptionPasswordRepeatValue] = useState(""); const [validEmail, setValidEmail] = useState(null); const [checkEmail, setCheckEmail] = useState(null); const [testAlertEmail, setTestAlertEmail] = useState(""); const [testAlertPassword, setTestAlertPassword] = useState(""); const [testAlertClass, setTestAlertClass] = useState(""); const [passwordHashed, setPasswordHashed] = useState(""); const [registered, setRegistered] = useState(null); const storedJwt = localStorage.getItem('jwt') ? localStorage.getItem('jwt') : null; const storedRefreshToken = localStorage.getItem('refreshToken') ? localStorage.getItem('refreshToken') : null const [jwt, setJwt] = useState(storedJwt || null); const [refreshToken, setRefreshToken] = useState(storedRefreshToken || null); let navigate = useNavigate(); const hashPassword = async () => { const data = await api_roliste.postData(requests.requestHash, {"password":inscriptionPasswordValue}).then((response) => { return setPasswordHashed(response['data']["hydra:member"][0]); }).catch((error) => { console.log(error) }); } const register = async (data) => { await api_roliste.postData(requests.requestUser, data); } const login = async (data) => { let config = { headers: { "Content-Type": "application/json", } } let result = await axios.post(requests.requestLogin, data, config); setJwt(result.data.token); setRefreshToken(result.data['refresh_token']); return [result.data.token, result.data['refresh_token']]; } function setEmailIsValid() { if(functions.validateEmail(inscriptionEmailValue)) { setValidEmail(true) } else { setValidEmail(false) } } const handleChange = (event) => { if (event.target.name === "inscriptionEmail") { setInscriptionEmailValue(event.target.value); } else if (event.target.name === "inscriptionPassword") { setInscriptionPasswordValue(event.target.value); if(inscriptionPasswordRepeatValue && inscriptionPasswordValue) { if(inscriptionPasswordValue !== inscriptionPasswordRepeatValue) { setTestAlertPassword("Les mots de passe ne correspondent pas.") } } if(!inscriptionPasswordValue || !inscriptionPasswordRepeatValue) { setTestAlertPassword("") } } else if (event.target.name === "inscriptionPasswordRepeat") { setInscriptionPasswordRepeatValue(event.target.value); } } const testPassword = ( ) => { if(inscriptionPasswordRepeatValue && inscriptionPasswordValue) { if(inscriptionPasswordValue !== inscriptionPasswordRepeatValue ) { setTestAlertPassword("Les mots de passe ne correspondent pas.") } } if(inscriptionPasswordValue === "" || inscriptionPasswordRepeatValue === "") { setTestAlertPassword("") } } const handleRegister = async (event) => { event.preventDefault(); if(inscriptionPasswordValue === inscriptionPasswordRepeatValue){ let data = { "email":inscriptionEmailValue, "password":passwordHashed, "roles": {1:"ROLE_USER"} }; let registerResponse = register(data); registerResponse.then( async () => { data = { "username":inscriptionEmailValue, "password":inscriptionPasswordValue }; login(data).then( (res) => { // Si promesse acceptée : on stocke les token et on change le loged pour rediriger console.log(res[0]) setJwt(res[0]); setRefreshToken(res[1]); localStorage.setItem("jwt",res[0]); localStorage.setItem("refreshToken", res[1]); console.log(jwt) console.log(res[0]) /*setReadyToNavigateAfterLogin(true); if(readyToNavigateAfterLogin) {*/ setRegistered(true); /*}*/ }, //Si promesse rejetée : on affiche l'échec ()=> { console.log("fail") }); }) } } const testEmail = async () => { setTestAlertEmail(""); const data = await api_roliste.postData(requests.requestCheck, {"email": inscriptionEmailValue}); setCheckEmail(data['data']['hydra:member']); let testFormatEmail = functions.validateEmail(inscriptionEmailValue); if (!testFormatEmail && inscriptionEmailValue !== "") { setTestAlertEmail("Cet email n'est pas valide"); setTestAlertClass("invalid"); } else if (!data['data']['hydra:member'][0] && inscriptionEmailValue !== "") { setTestAlertEmail("Cet email est disponible"); setTestAlertClass("valid"); } else if( inscriptionEmailValue !== "") { setTestAlertEmail("Cet email est déja utilisé"); setTestAlertClass("invalid"); } else { setTestAlertEmail(""); } } useEffect(() => { setEmailIsValid() }, [inscriptionEmailValue]) useEffect( () => { hashPassword(); },[inscriptionPasswordValue]) useEffect(() => { if(registered) { navigate("/vos-aventures"); } }, [registered]); return ( <div > <h2 className={"div-title"}>S'inscrire</h2> <form className={"form"} action=""> <div className={"form-div"}> <label className={"form-label"} htmlFor="inscriptionEmail">Mail</label> <input className={"form-input"} type="email" name="inscriptionEmail" value={inscriptionEmailValue} onChange={handleChange} onBlur={testEmail}/> </div> <div className={"form-div"}> <label className={"form-label"} htmlFor="inscriptionPaswword">Mot de passe</label> <input className={"form-input"} type="password" name="inscriptionPassword" value={inscriptionPasswordValue} onChange={handleChange} onBlur={testPassword}/> </div> <div className={"form-div"}> <label className={"form-label"} htmlFor="inscriptionPasswordRepeat">Confirmation</label> <input className={"form-input"} type="password" name="inscriptionPasswordRepeat" value={inscriptionPasswordRepeatValue} onChange={handleChange} onBlur={testPassword}/> </div> <button className={"submit-button-wooden"} onClick={handleRegister} style={{ backgroundImage: `url(${process.env.PUBLIC_URL + buttonImg})`, backgroundSize: `100% 100%`}}>Inscription</button> <p className={testAlertEmail ? testAlertClass : ""}>{testAlertEmail}</p> <p className={testAlertPassword ? testAlertClass : ""}>{testAlertPassword}</p> </form> </div> ) } export default Inscription;
<!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>Leader Board</title> <link rel="stylesheet" href="styles/style.css"> <!-- Font Awesome --> <script src="https://kit.fontawesome.com/94218ccdb3.js" crossorigin="anonymous"></script> </head> <body> <header> <nav> <div class="first-part"> <img src="images/icons/logo.png" alt=""> <h4 class="idea">idea</h4> </div> <div class="second-part"> <ul> <li>Home</li> <li>About</li> <li>Works</li> <img src="images/icons/profile.png" alt=""> </ul> </div> </nav> </header> <main> <!-- First Section--> <section class=" container"> <div class="top-player"> <h2 class="section-title">Top Players</h2> <div class="players"> <div class="player"> <img src="images/players/player-1.png" alt=""> <h3 class="player-name">Top Player-1</h3> </div> <div class="player"> <img src="images/players/player-2.png" alt=""> <h3 class="player-name">Top Player-2</h3> </div> <div class="player"> <img src="images/players/player-3.png" alt=""> <h3 class="player-name">Top Player-3</h3> </div> <div class="player"> <img src="images/players/player-4.png" alt=""> <h3 class="player-name">Top Player-4</h3> </div> <div class="player"> <img src="images/players/player-5.png" alt=""> <h3 class="player-name">Top Player-5</h3> </div> <div class="player"> <img src="images/players/player-6.png" alt=""> <h3 class="player-name">Top Player-6</h3> </div> </div> </div> <hr> <div class="top-blogs"> <h2 class="section-title"> Top Blogs</h2> <div class="blogs"> <article class="blog"> <div class="thumbnail"> <img src="images/blogs/blog-1.png" alt=""> </div> <div class="blog-info"> <h3 class="blog-title">13 of My Favorite UI/UX Goodies</h3> <p class="blog-author">By <a href="">Danny Sapio</a></p> </div> </article> <article class="blog"> <div class="thumbnail"> <img src="images/blogs/blog-2.png" alt=""> </div> <div class="blog-info"> <h3 class="blog-title">13 of My Favorite UI/UX Goodies</h3> <p class="blog-author">By <a href="">Danny Sapio</a></p> </div> </article> <article class="blog"> <div class="thumbnail"> <img src="images/blogs/blog-3.png" alt=""> </div> <div class="blog-info"> <h3 class="blog-title">13 of My Favorite UI/UX Goodies</h3> <p class="blog-author">By <a href="">Danny Sapio</a></p> </div> </article> <article class="blog"> <div class="thumbnail"> <img src="images/blogs/blog-4.png" alt=""> </div> <div class="blog-info"> <h3 class="blog-title">13 of My Favorite UI/UX Goodies</h3> <p class="blog-author">By <a href="">Danny Sapio</a></p> </div> </article> </div> </div> </section> <!-- Last Section--> <section class="container"> <h2 class="section-title">Lates Course</h2> <div class="courses"> <div class="course"> <div class="course-banner"> <img src="images/courses/course-1.png" alt=""> </div> <div class="course-detail"> <div class="course-title">React - The Complete Guide 2020</div> <p class="course-author">Reed Krakoff.</p> <div class="course-info"> <div> <i class="fa-solid fa-star filled"></i> <i class="fa-solid fa-star filled"></i> <i class="fa-solid fa-star filled"></i> <i class="fa-solid fa-star filled"></i> <i class="fa-solid fa-star empty"></i> <span>4.5</span> </div> <div class="course-duration"> <i class="fa-regular fa-clock"></i> 01:30 hr </div> </div> </div> </div> <div class="course"> <div class="course-banner"> <img src="images/courses/course-2.png" alt=""> </div> <div class="course-detail"> <div class="course-title">React - The Complete Guide 2020</div> <p class="course-author">Reed Krakoff.</p> <div class="course-info"> <div> <i class="fa-solid fa-star filled"></i> <i class="fa-solid fa-star filled"></i> <i class="fa-solid fa-star filled"></i> <i class="fa-solid fa-star filled"></i> <i class="fa-solid fa-star empty"></i> <span>4.5</span> </div> <div class="course-duration"> <i class="fa-regular fa-clock"></i> 01:30 hr </div> </div> </div> </div> <div class="course"> <div class="course-banner"> <img src="images/courses/course-3.png" alt=""> </div> <div class="course-detail"> <div class="course-title">React - The Complete Guide 2020</div> <p class="course-author">Reed Krakoff.</p> <div class="course-info"> <div> <i class="fa-solid fa-star filled"></i> <i class="fa-solid fa-star filled"></i> <i class="fa-solid fa-star filled"></i> <i class="fa-solid fa-star filled"></i> <i class="fa-solid fa-star empty"></i> <span>4.5</span> </div> <div class="course-duration"> <i class="fa-regular fa-clock"></i> 01:30 hr </div> </div> </div> </div> </div> </section> </main> </body> </html>
import * as React from 'react'; import { toast } from 'react-toastify'; import { Button } from 'semantic-ui-react'; import { openModal } from '../../App/Components/Modals/modalsSlice'; import { useAppDispatch, useAppSelector } from '../../App/Store/hooks'; import { decrement, increment, selectSandboxData, selectSandboxError, selectSandboxIsLoading, selectSandboxPlace, } from './sandboxSlice'; import TestGoogleMaps from './TestGoogleMaps'; import TestGooglePlaces from './TestGooglePlaces'; const Sandbox: React.FC = () => { const data = useAppSelector(selectSandboxData); const error = useAppSelector(selectSandboxError); const isLoading = useAppSelector(selectSandboxIsLoading); const place = useAppSelector(selectSandboxPlace); const dispatch = useAppDispatch(); const [targetName, setTargetName] = React.useState(''); React.useEffect(() => { if (error) { toast.error(error.message); } }, [error]); return ( <> <h1>Testing 1, 2, 3...</h1> <h3>The data is: {data}</h3> <Button color='green' content='Increment' loading={isLoading && targetName === 'increment'} name='increment' onClick={(e) => { dispatch(increment(10)); setTargetName(e.currentTarget.name); }} /> <Button color='red' content='Decrement' loading={isLoading && targetName === 'decrement'} name='decrement' onClick={(e) => { dispatch(decrement(5)); setTargetName(e.currentTarget.name); }} /> <Button color='teal' content='Open Modal' onClick={() => dispatch(openModal({ modalType: 'TestModal', modalProps: { data } }))} /> <Button color='teal' content='Test Toast' onClick={() => toast.info('Test!')} /> <TestGooglePlaces /> <TestGoogleMaps center={place.latLng} /> </> ); }; export default Sandbox;
import React from "react"; import Form from 'react-bootstrap/Form' import Button from 'react-bootstrap/Button' import dbUtil from "../../utilities/dbUtil"; import { useHistory } from "react-router"; export default function AddMajor(){ let history = useHistory(); const newMajor = { majorID: "", departmentID: "", creditsRequired: "" } function submitChanges(e){ e.preventDefault(); for(const property in newMajor){ if(`${newMajor[property].trim()}` === ""){ window.alert("Please ensure no fields are left empty"); return("") } } dbUtil.addMajor(newMajor).then(data =>{ if(data.err){ window.alert(data.err.sqlMessage) }else if(data.affectedRows === 1){ history.push('/undergradCatalog') } }) } return( <Form id='align-center'> <h1 className="text-align">Add Major</h1> <Form.Group> <Form.Label>MajorID</Form.Label> <Form.Control onChange={e => newMajor.majorID = e.target.value}></Form.Control> <Form.Label>DepartmentID</Form.Label> <Form.Control onChange={e => newMajor.departmentID = e.target.value}></Form.Control> <Form.Label>Credits Required</Form.Label> <Form.Control onChange={e => newMajor.creditsRequired = e.target.value}></Form.Control> <Button variant='success' onClick={(e) => submitChanges(e)}>Save Changes</Button>{' '} </Form.Group> </Form> ) }
import pytest import os from django import db from base64 import b64encode from rest_framework.test import APIClient from django.core.management import call_command current_file_path = os.path.abspath(__file__) current_dir_path = os.path.dirname(current_file_path) LOCAL_IMAGE_PATH = 'test_images' def get_absolute_path(path, name): relative_path = os.path.join(path, name) return os.path.join(current_dir_path, relative_path) def _get_encoded_image_encode(image_path): with open(image_path, "rb") as f: image_data = f.read() encoded_image = b64encode(image_data) return encoded_image @pytest.fixture(scope='session') def django_db_setup(django_db_setup, django_db_blocker): with django_db_blocker.unblock(): call_command('loaddata', get_absolute_path("", 'db.json')) @pytest.fixture() def api_client(): client = APIClient() return client @pytest.fixture def test_post_values(): encoded_lower_image = _get_encoded_image_encode(get_absolute_path(LOCAL_IMAGE_PATH, "lower.jpg")) encoded_upper_image = _get_encoded_image_encode(get_absolute_path(LOCAL_IMAGE_PATH, "upper.jpg")) json_values = { "beauty_title": "пер. ", "title": "Pro", "other_titles": "Триев", "connect": "", "user": {"email": "qwerty@mail.ru", "fam": "Пупкин", "name": "Василий", "otc": "Иванович", "phone": "+7 555 55 55"}, "coords": { "latitude": "45.3842", "longitude": "7.1525", "height": "1200"}, "level": {"winter": "", "summer": "1А", "autumn": "1А", "spring": ""}, "images": [{"data": encoded_upper_image, "title": "Седловина"}, {"data": encoded_lower_image, "title": "Подъём"}] } return json_values @pytest.fixture def test_post_values_wrong_types(): encoded_lower_image = _get_encoded_image_encode(get_absolute_path(LOCAL_IMAGE_PATH, "lower.jpg")) encoded_upper_image = _get_encoded_image_encode(get_absolute_path(LOCAL_IMAGE_PATH, "upper.jpg")) json_values = { "beauty_title": "пер. ", "title": "Pro", "other_titles": "Триев", "connect": "", "user": {"email": "qwerty@mail.ru", "fam": "Пупкин", "name": "Василий", "otc": "Иванович", "phone": "+7 555 55 55"}, "coords": { "latitude": "AWs", "longitude": "aw", "height": "awa"}, "level": {"winter": "", "summer": "1А", "autumn": "1А", "spring": ""}, "images": [{"data": encoded_upper_image, "title": "Седловина"}, {"data": encoded_lower_image, "title": "Подъём"}] } return json_values
// ---------------------------------------------------------------------------- // Copyright 2023 CEA* // *Commissariat a l'Energie Atomique et aux Energies Alternatives (CEA) // // SPDX-License-Identifier: Apache-2.0 // // 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. //[END OF HEADER] // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- class axi_superset_base_sequence_c extends uvm_sequence #( axi_superset_txn_c, axi_superset_txn_c ); `uvm_object_utils( axi_superset_base_sequence_c ) protected string name; // Number of sequence_item of the sequence protected int num_txn; protected int num_rsp; // Debug variables protected int current_num_write_txn; protected int current_num_read_txn; // With this variable enabled the responses are stored in an Assocaitive // Array. This can be used to retrieve the responses specially in the case // of read protected bit enable_manage_response; // Get the handle of the sequencer to get the configuration for the // sequence_iem axi_superset_sequencer_c m_sequencer ; // Associative array of queues for storing the responses of each transactions, // for each type of transactions. Allows to to access the response protected axi_superset_txn_c write_rsp_queue[axi_sig_id_t][$]; protected axi_superset_txn_c read_rsp_queue[axi_sig_id_t][$]; // ------------------------------------------------------------------------- // Constructor for base sequences // // All sequencies are derived from this base class. // // In the constructor, the number of transactions sent by the sequence can // be configured via three options: // - the argument number_txn: when calling the function new, the user can // give the number of transaction wanted for the instance of the sequence. // - The plusargs +NUM_TXN: if the argument number_txn have its default // value, the plusargs NUM_TXN is used to configured the number of // transaction of the sequence. // - Function set_num_txn: in case the user prefer this way, there is // a function set which allow to configure the number of transaction // after the creation of the sequence. // ------------------------------------------------------------------------- function new( string name = "base_txn_seq", int number_txn = -1 ); super.new(name); this.name = name; if ( number_txn == -1 ) begin // Getting the number of transaction for the sequence from a plusargs if (!$value$plusargs("NUM_TXN=%d", num_txn )) begin num_txn = 100; end // if end else begin num_txn = number_txn; end `uvm_info( this.name, $sformatf("NUM_TXN=%0d" , num_txn), UVM_LOW ); // Activating the response handler feature : the response handler // receives the responses from the driver and its processed by a call // back which is define below in the response_handler function. use_response_handler(1); // initialising the number of response num_rsp = 0; current_num_write_txn = 0 ; current_num_read_txn = 0 ; endfunction: new // ------------------------------------------------------------------------ // Pre body task // Task in charge of getting the sequencer of the agent, to get the // configuration of the agent from the sequencer, to get if the ID are // unique or not and to get the transaction configuration for the // randomization. // ------------------------------------------------------------------------ virtual task pre_body(); if ( !$cast(m_sequencer, get_sequencer()) ) `uvm_error(this.name,"Error during the cast of the sequencer"); endtask: pre_body // ----------------------------------------------------------------------- // Body // ----------------------------------------------------------------------- virtual task post_body( ); super.post_body(); // Waiting for the reception of all responses in the case of id management wait( m_sequencer.is_id_queue_empty() == 1 ); endtask: post_body // ------------------------------------------------------------------------- // TASK: send_txn // Task in charge of sending a transaction given by the user. // For this task to work correctly, it is assumed that the transaction is // already randomized with its own constraints before giving it to the task // ------------------------------------------------------------------------- protected task send_txn ( input axi_superset_txn_c item, // Transaction to send to the driver input int txn_number = 0 // Debug input, to print the number of the transaction if this transaction is part of a bigger sequence of transactions. ); axi_superset_txn_c item_clone; if ( !$cast( item_clone, item.clone() ) ) `uvm_error(this.name,"Error during the cast of the transaction"); if ( ( m_sequencer.m_agent_config.get_axi_version() == AXI4 ) && ( item_clone.m_axi_version != AXI4 ) ) `uvm_fatal(this.name,$sformatf("The protocol version m_axi_version=%0p of the transaction is not compatible with the protocol version m_agent_config.m_axi_version=AXI4 configured in the agent", item_clone.m_axi_version ) ); if ( ( ( ( item_clone.m_txn_type == AXI_WRITE_REQ ) || ( item_clone.m_txn_type == AXI_READ_REQ ) ) && ( m_sequencer.m_agent_config.get_is_master_side() ) ) || ( ( ( item_clone.m_txn_type == AXI_WRITE_RSP ) || ( item_clone.m_txn_type == AXI_READ_RSP ) ) && ( !m_sequencer.m_agent_config.get_is_master_side() ) ) ) begin // Start the item start_item( item_clone ); // Increment the counter for debug purposes if ( item_clone.m_txn_type == AXI_WRITE_REQ ) begin current_num_write_txn++; // In the case of an atop, as there will be 2 responses for // 1 request, decrease the num_rsp to avoid ending the sequence too // soon if ( item_clone.m_atop[5] ) begin num_rsp--; current_num_read_txn++; end end else begin current_num_read_txn++; end if ( m_sequencer.m_agent_config.get_is_master_side() ) begin // Generate a unique id if ( m_sequencer.m_agent_config.get_id_management_enable()) obtain_unique_id ( item_clone ); else if ( m_sequencer.m_agent_config.get_axi_version() != AXI4 ) begin // Generate a valid ID, blocking until ID is valid obtain_valid_id ( item_clone ); end end // Send the transction to the driver finish_item( item_clone ); end // if endtask // ------------------------------------------------------------------------- // TASK: send_txn_get_rsp // Task in charge of sending a transaction given by the user. // For this task to work correctly, it is assumed that the transaction is // already randomized with its own constraints before giving it to the task // This task wait for the responses // ------------------------------------------------------------------------- protected task send_txn_get_rsp ( input axi_superset_txn_c item, // Transaction to send to the driver output axi_superset_txn_c rsp ); axi_superset_txn_c item_clone; enable_manage_response = 1; if ( !$cast( item_clone, item.clone() ) ) `uvm_error(this.name,"Error during the cast of the transaction"); if ( ( ( ( item_clone.m_txn_type == AXI_WRITE_REQ ) || ( item_clone.m_txn_type == AXI_READ_REQ ) ) && ( m_sequencer.m_agent_config.get_is_master_side() ) ) || ( ( ( item_clone.m_txn_type == AXI_WRITE_RSP ) || ( item_clone.m_txn_type == AXI_READ_RSP ) ) && ( !m_sequencer.m_agent_config.get_is_master_side() ) ) ) begin // Start the item start_item( item_clone ); // Increment the counter for debug purpose if ( item_clone.m_txn_type == AXI_WRITE_REQ ) begin current_num_write_txn++; end else begin current_num_read_txn++; end // Generate an unique id if ( m_sequencer.m_agent_config.get_id_management_enable() && m_sequencer.m_agent_config.get_is_master_side() ) obtain_unique_id ( item_clone ); // Send the transction to the driver finish_item( item_clone ); // Wait for response case(item_clone.m_txn_type) AXI_READ_REQ:get_rd_rsp(item_clone.m_id, rsp); AXI_WRITE_REQ:get_wr_rsp(item_clone.m_id, rsp); endcase end endtask // ------------------------------------------------------------------------- // TASK: send_uniflit_req // Task in charge of sending a random request. // By default, the transaction is an AXI4 request with no error. // This task should only be used in a sequence for a Master agent. // ------------------------------------------------------------------------- virtual task send_uniflit_req ( input axi_dv_ver_t ver = AXI4, input axi_dv_lite_t lite = NO_LITE, input axi_dv_err_t err = NO_ERR, input int txn_number = 0 ); axi_superset_txn_c item; // Creating the transaction and setting its configuration before the // randomization item = axi_superset_txn_c::type_id::create("item"); item.set_config( m_sequencer.get_agent_config().get_txn_config() ) ; // Randomization of the transaction if (!item.randomize() with { m_txn_type inside {AXI_WRITE_REQ, AXI_READ_REQ}; m_axi_version == ver ; m_lite == lite ; m_err == err ; m_len == 1 ; } ) `uvm_error(this.name,"Error randomizing the request metadata"); `uvm_info( this.name, $sformatf("REQ, Info: %0s", item.convert2string()) , UVM_DEBUG) send_txn( item, txn_number ); endtask // ------------------------------------------------------------------------- // TASK: send_uniflit_write // Task in charge of sending a write request // By default, the transaction is an AXI4 request with no error. // This task should only be used in a sequence for a Master agent. // ------------------------------------------------------------------------- protected task send_uniflit_write ( input axi_dv_ver_t ver = AXI4, input axi_dv_lite_t lite = NO_LITE, input axi_dv_err_t err = NO_ERR, input int txn_number = 0 ); axi_superset_txn_c item; // Creating the transaction with its configuration item = axi_superset_txn_c::type_id::create("item"); item.set_config( m_sequencer.get_agent_config().get_txn_config() ) ; // Randomizing the transaction if (!item.randomize() with { m_txn_type == AXI_WRITE_REQ ; m_axi_version == ver ; m_lite == lite ; m_err == err ; m_len == 0 ; } ) `uvm_error(this.name,"Error randomizing the write request metadata"); send_txn( item, txn_number ); endtask // ------------------------------------------------------------------------- // TASK: send_uniflit_read // Task in charge of sending a read request // By default, the transaction is an AXI4 request with no error. // This task should only be used in a sequence for a Master agent. // ------------------------------------------------------------------------- protected task send_uniflit_read ( input axi_dv_ver_t ver = AXI4, input axi_dv_lite_t lite = NO_LITE, input axi_dv_err_t err = NO_ERR, input int txn_number = 0 ); axi_superset_txn_c item; // Creating the transaction with its configuration item = axi_superset_txn_c::type_id::create("item"); item.set_config( m_sequencer.get_agent_config().get_txn_config() ) ; // Randomization of the transaction if (!item.randomize() with { m_txn_type == AXI_READ_REQ ; m_axi_version == ver ; m_lite == lite ; m_err == err ; m_len == 0 ; } ) `uvm_error(this.name,"Error randomizing the read request metadata"); // Sending the transaction via the send_txn task send_txn( item, txn_number); endtask // ------------------------------------------------------------------------- // TASK: obtain_unique_id // Task in charge of generating a unique id for the transaction. // If there is no more id for this type of transaction, the task will wait // until a unique id is released by the sequencer. // The id is then set in the transaction, and registered in the // appropriate list in the sequencer. // ------------------------------------------------------------------------- virtual task obtain_unique_id ( ref axi_superset_txn_c item ); axi_sig_id_t txn_id; // Block to set an unique id for the transaction // An unique_id is asked to the sequencer, for the corresponding type of // transaction if ( !m_sequencer.get_unique_unused_id( item.m_txn_type, txn_id, this.name ) ) begin // In the case there is no unique id left, the transaction will wait // for one to be released before trying to get its unique id wait( !m_sequencer.is_id_queue_full( item.m_txn_type ) ); if ( !m_sequencer.get_unique_unused_id( item.m_txn_type, txn_id, this.name ) ) `uvm_error(this.name,"Error in getting an unused id: an unused ID should have been released, and the function was not able to get it."); end // Set the id of the transaction, and register it with the sequencer item.set_id( txn_id ); m_sequencer.register_id( item.m_atop, item.m_txn_type, txn_id, this.name ); // If the transaction is an atop with an additional read response, the // id also needs to be registered in the read list to avoid having another // read transaction with the same id. So as the id is already registered // in the write list, the sequence will wait for this id to be released // to get/register it for a read transaction. if ( ( item.m_txn_type == AXI_WRITE_REQ ) && ( item.m_atop[5] ) ) begin // Waiting for the ID to also be free for the read list wait( !m_sequencer.is_id_used( AXI_READ_REQ, txn_id ) ); // Registering the ID in the read list m_sequencer.register_id( item.m_atop, AXI_READ_REQ, txn_id, this.name ); end // If the transaction is an AXI5 transaction, set up its idunq field to // 1 to indicate that the agent is working with unique ID item.set_idunq( 1'b1 ); endtask : obtain_unique_id // ------------------------------------------------------------------------- // TASK: obtain_valid_id // Task in charge of generating a valid id for the transaction. // If there is no more id for this type of transaction, the task will wait // until an id is released by the sequencer. // The id is then set in the transaction, and registered in the // appropriate list in the sequencer. // -------------------------------------- // ------------------------------------------------------------------------- virtual task obtain_valid_id ( ref axi_superset_txn_c item ); axi_sig_id_t txn_id; // Wait for a valid ID to be generated wait ( m_sequencer.get_unused_id( item.m_atop, txn_id, this.name ) ); if ( item.m_atop_type != ATOP_NONE ) item.set_idunq( 1'b1 ); else item.set_idunq( 1'b0 ); // Set the id of the transaction, and register it with the sequencer item.set_id( txn_id ); m_sequencer.register_id( item.m_atop, item.m_txn_type, txn_id, this.name ); // In a case of an atop, also register the id in the read list to later // release it when the response arrives if ( ( item.m_atop[5] ) && ( item.m_txn_type == AXI_WRITE_REQ ) ) m_sequencer.register_id( item.m_atop, AXI_READ_REQ, txn_id, this.name ); endtask : obtain_valid_id // ------------------------------------------------------------------------- // Function response handler // Function in charge of receiving responses from the driver. // When a response is received, its ID is released and the number of // responses received is incremented. // Description from the uvm_sequence_base class // Function: response_handler // // When the use_reponse_handler bit is set to 1, this virtual task is called // by the sequencer for each response that arrives for this sequence. // ------------------------------------------------------------------------- function void response_handler( uvm_sequence_item response ); axi_superset_txn_c axi_response; `uvm_info( this.name, $sformatf("Response handler responses=%0d" , num_rsp ), UVM_DEBUG ); // Cast the response from an uvm_sequence_axi_response to a axi_superset_txn_c if ( !$cast(axi_response, response) ) `uvm_error(this.name,"Error during the cast of the response"); // Release the id if ( m_sequencer.get_agent_config().get_id_management_enable() || m_sequencer.get_agent_config().get_axi_version() != AXI4 ) m_sequencer.release_id( axi_response.m_txn_type, axi_response.m_id, this.name ); // Stock the responses in a queue // A get_rsp(id, type) can be used to get the responses if ( enable_manage_response ) begin case ( axi_response.m_txn_type ) AXI_WRITE_RSP: write_rsp_queue[axi_response.m_id].push_back(axi_response); AXI_READ_RSP : read_rsp_queue[axi_response.m_id].push_back(axi_response); endcase end // Increment the number of response num_rsp++; endfunction : response_handler // ------------------------------ // API to get the responses // ------------------------------ virtual task get_wr_rsp(input axi_sig_id_t id, output axi_superset_txn_c rsp); // Wait until a response is seen wait (write_rsp_queue.exists(id)); wait (write_rsp_queue[id].size() > 0); rsp = write_rsp_queue[id].pop_front(); endtask virtual task get_rd_rsp(input axi_sig_id_t id, output axi_superset_txn_c rsp); // Wait until a response is seen wait (read_rsp_queue.exists(id)); wait (read_rsp_queue[id].size() > 0); rsp = read_rsp_queue[id].pop_front(); endtask // ----------------------------------------------------------------------- // Function set/get // ----------------------------------------------------------------------- // ----------------------------------------------------------------------- // num_txn // ----------------------------------------------------------------------- function void set_num_txn( int new_num_txn ); `uvm_info( this.name, $sformatf("New number of txn=%0d" , new_num_txn ), UVM_LOW ); this.num_txn = new_num_txn; endfunction : set_num_txn function int get_num_txn( ); return this.num_txn; endfunction : get_num_txn endclass // ------------------------------------------------------------------------- // Library of sequences // - axi_superset_master_sequence_c // - axi_superset_master_write_sequence_c // - axi_superset_master_read_sequence_c // ------------------------------------------------------------------------- // ----------------------------------------------------------------------- // axi_superset_master_sequence_c // Sequence which send `num_txn random request transaction from the master // ----------------------------------------------------------------------- class axi_superset_master_sequence_c extends axi_superset_base_sequence_c ; `uvm_object_utils(axi_superset_master_sequence_c) // ----------------------------------------------------------------------- // Constructor // ----------------------------------------------------------------------- function new(string name = "axi_superset_master_sequence_c", int number_txn = -1 ); super.new(name, number_txn); endfunction:new // ----------------------------------------------------------------------- // Body // ----------------------------------------------------------------------- virtual task body( ); super.body(); `uvm_info(this.name, "Sequence axi_superset_master_sequence_c is starting", UVM_DEBUG) // Sending `num_txn random transactions for ( int i = 0 ; i < num_txn ; i++ ) begin send_uniflit_req(.txn_number(i)); end // Waiting for the reception of all responses wait( num_txn == num_rsp ); `uvm_info(this.name, "Sequence axi_superset_master_sequence_c is ending", UVM_DEBUG) endtask: body endclass: axi_superset_master_sequence_c // ----------------------------------------------------------------------- // axi_superset_master_write_sequence_c // Sequence which send `num_txn random write only request transactions from the master // ----------------------------------------------------------------------- class axi_superset_master_write_sequence_c extends axi_superset_base_sequence_c ; `uvm_object_utils(axi_superset_master_write_sequence_c) // ----------------------------------------------------------------------- // Constructor // ----------------------------------------------------------------------- function new(string name = "axi_superset_master_write_sequence_c", int number_txn = -1 ); super.new(name, number_txn); endfunction:new // ----------------------------------------------------------------------- // Body // ----------------------------------------------------------------------- virtual task body( ); super.body(); `uvm_info(this.name, "Sequence axi_superset_master_write_sequence_c is starting", UVM_DEBUG) // Sending `num_txn random write only transactions for ( int i = 0 ; i < num_txn ; i++ ) begin send_uniflit_write(.txn_number(i)); end // Waiting for the reception of all responses wait( num_txn == num_rsp ); `uvm_info(this.name, "Sequence axi_superset_master_write_sequence_c is ending", UVM_DEBUG) endtask: body endclass: axi_superset_master_write_sequence_c // ----------------------------------------------------------------------- // axi_superset_master_read_sequence_c // Sequence which send `num_txn random read only request transactions from the master // ----------------------------------------------------------------------- class axi_superset_master_read_sequence_c extends axi_superset_base_sequence_c ; `uvm_object_utils(axi_superset_master_read_sequence_c) // ----------------------------------------------------------------------- // Constructor // ----------------------------------------------------------------------- function new(string name = "axi_superset_master_read_sequence_c", int number_txn = -1 ); super.new(name, number_txn); endfunction:new // ----------------------------------------------------------------------- // Body // ----------------------------------------------------------------------- virtual task body( ); super.body(); `uvm_info(this.name, "Sequence axi_superset_master_read_sequence_c is starting", UVM_DEBUG) // Sending `num_txn random read only transactions for ( int i = 0 ; i < num_txn ; i++ ) begin send_uniflit_read(.txn_number(i)); end // Waiting for the reception of all responses wait( num_txn == num_rsp ); `uvm_info(this.name, "Sequence axi_superset_master_read_sequence_c is ending", UVM_DEBUG) endtask: body endclass: axi_superset_master_read_sequence_c
import * as _ from 'lodash'; import { Component, ViewEncapsulation, Input, Output, OnInit, TemplateRef, ElementRef, EventEmitter, ChangeDetectionStrategy } from '@angular/core'; import { ThemeType } from '../theme'; import { ITabConfig, ITabEmit } from './tab.interface'; @Component({ selector: `tf-tab`, templateUrl: `tab.component.html`, styleUrls: ['../../lib.theme.scss'], encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush }) export class TFTabComponent implements OnInit { @Input() theme: ThemeType; @Input() fontColor: ThemeType; @Input() iconColor: ThemeType; @Input() icon: string; @Input() config: ITabConfig; @Input() templates: TemplateRef<ElementRef>[]; @Input() eventTrack: boolean = true; @Output() tabChangeEmit: EventEmitter<ITabEmit> = new EventEmitter<ITabEmit>(); public activatedIndex: number = 0; constructor() { } ngOnInit() { this.validation(); this.activatedIndex = _.get(this.config, 'active') || 0; } private validation() { !this.config && console.info(`%c Tab config is empty`, 'color: orange'); !this.templates && console.info(`%c Tab templates should not be empty`, 'color: orange'); if (this.config && !this.config.controls && this.config.icon && this.config.icon.list) { this.config.controls = new Array(this.config.icon.list.length); } if ( this.config && this.config.controls && this.config.controls.length && this.templates && this.templates.length && !_.isEqual(this.config.controls.length, this.templates.length)) { console.info(`%c Tab templates should equals to controls total number`, 'color: orange'); } } public onClick(index: number) { if (this.eventTrack) { this.activatedIndex = index; this.tabChangeEmit.emit({ active: index }); } } public getTheme(): string[] { const themeList: string[] = []; !_.isEmpty(this.theme) && themeList.push(`theme-${this.theme}`); !_.isEmpty(this.fontColor) && themeList.push(`color-${this.fontColor}`); !_.isEmpty(this.iconColor) && themeList.push(`icon-${this.iconColor}`); return themeList; } }
import { Action, ActionPanel, Color, Icon, List, showToast, Toast } from "@raycast/api"; import { useFetch } from "@raycast/utils"; import { useState } from "react"; import { InstallExtensionByIDAction, OpenExtensionByIDInBrowserAction, OpenExtensionByIDInVSCodeAction, UninstallExtensionByIDAction, } from "./extension-actions"; import { useLocalExtensions } from "./extensions"; import { Extension } from "./lib/vscode"; import { compactNumberFormat } from "./utils"; function InstallExtensionAction(props: { extension: GalleryExtension; afterInstall?: () => void }): JSX.Element { return ( <InstallExtensionByIDAction extensionID={getFullExtensionID(props.extension)} afterInstall={props.afterInstall} /> ); } function UninstallExtensionAction(props: { extension: GalleryExtension; afterUninstall?: () => void }): JSX.Element { return ( <UninstallExtensionByIDAction extensionID={getFullExtensionID(props.extension)} afterUninstall={props.afterUninstall} /> ); } export interface GalleryQueryResult { results: Result[]; } export interface Result { extensions: GalleryExtension[]; pagingToken: any; resultMetadata: ResultMetadaum[]; } export interface StatisticItem { statisticName: string; value: number; } export interface GalleryExtension { publisher: Publisher; extensionId: string; extensionName: string; displayName: string; flags: string; lastUpdated: string; publishedDate: string; releaseDate: string; shortDescription?: string; versions: Version[]; deploymentType: number; statistics?: StatisticItem[]; } export interface Publisher { publisherId: string; publisherName: string; displayName: string; flags: string; domain?: string; isDomainVerified: boolean; } export interface Version { version: string; flags: string; lastUpdated: string; files: File[]; properties: Property[]; assetUri: string; fallbackAssetUri: string; } export interface File { assetType: string; source: string; } export interface Property { key: string; value: string; } export interface ResultMetadaum { metadataType: string; metadataItems: MetadataItem[]; } function getFullExtensionID(extension: GalleryExtension): string { return `${extension.publisher.publisherName}.${extension.extensionName}`; } export interface MetadataItem { name: string; count: number; } function GalleryExtensionListItem(props: { extension: GalleryExtension; installedExtensions: Extension[] | undefined; reloadLocalExtensions: () => void; }): JSX.Element { const e = props.extension; const ie = props.installedExtensions; const iconURI = (): string | undefined => { if (!e.versions || e.versions.length <= 0) { return undefined; } const files = e.versions[0].files; const file = files.find((f) => f.assetType === "Microsoft.VisualStudio.Services.Icons.Default"); if (file) { return file.source; } }; const getInstallCount = (): number | undefined => { const item = e.statistics?.find((s) => s.statisticName === "install"); return item?.value; }; const installCount = getInstallCount(); const newstVersion = e.versions && e.versions.length > 0 ? e.versions[0] : undefined; const version = newstVersion ? newstVersion.version : undefined; const lastUpdated = newstVersion ? new Date(newstVersion.lastUpdated) : undefined; const installedIDs = ie ? ie.map((ext) => ext.id.toLocaleLowerCase()) : []; const alreadyInstalled = installedIDs.includes(getFullExtensionID(e).toLocaleLowerCase()); return ( <List.Item title={{ value: e.displayName, tooltip: e.shortDescription }} subtitle={e.publisher?.displayName} icon={iconURI() || "icon.png"} accessories={[ { tag: alreadyInstalled ? { value: "Installed", color: Color.Blue } : "", tooltip: alreadyInstalled ? "Already Installed" : "", }, { icon: installCount !== undefined ? Icon.Download : undefined, text: installCount !== undefined ? compactNumberFormat(installCount) : undefined, tooltip: installCount !== undefined ? `${compactNumberFormat(installCount)} Installs` : undefined, }, { tag: version, tooltip: lastUpdated ? `Last Update: ${lastUpdated?.toLocaleString()}` : "" }, ]} actions={ <ActionPanel> <ActionPanel.Section> {alreadyInstalled ? ( <UninstallExtensionAction extension={e} afterUninstall={props.reloadLocalExtensions} /> ) : ( <InstallExtensionAction extension={e} afterInstall={props.reloadLocalExtensions} /> )} <OpenExtensionByIDInVSCodeAction extensionID={getFullExtensionID(e)} /> </ActionPanel.Section> <ActionPanel.Section> <OpenExtensionByIDInBrowserAction extensionID={getFullExtensionID(e)} /> <Action.CopyToClipboard content={getFullExtensionID(e)} title="Copy Extension ID" shortcut={{ modifiers: ["cmd", "shift"], key: "." }} /> </ActionPanel.Section> </ActionPanel> } /> ); } function getTotalResultCount(data: GalleryQueryResult | undefined): number | undefined { if (!data || !data?.results || data.results.length <= 0) { return; } const result = data.results[0]; const resultCountObject = result.resultMetadata?.find((e) => e.metadataType === "ResultCount"); if (resultCountObject) { const totalCountObject = resultCountObject.metadataItems.find((e) => e.name === "TotalCount"); if (totalCountObject) { return totalCountObject.count; } } } export default function InstallExtensionRootCommand(): JSX.Element { const [searchText, setSearchText] = useState(""); const { extensions: installExtensions, refresh } = useLocalExtensions(); const { isLoading, error, data } = useGalleryQuery(searchText); if (error) { showToast({ style: Toast.Style.Failure, title: "Error", message: error }); } const extensions = data?.results ? data?.results[0].extensions : undefined; const totalExtensionCount = getTotalResultCount(data); return ( <List isLoading={isLoading} searchBarPlaceholder="Search by Name or ID in VS Code Marketplace" onSearchTextChange={setSearchText} throttle > <List.Section title="Found Extensions" subtitle={ totalExtensionCount !== undefined ? `${extensions?.length}/${totalExtensionCount}` : `${extensions?.length}` } > {extensions?.map((e) => ( <GalleryExtensionListItem key={e.extensionId} extension={e} installedExtensions={installExtensions} reloadLocalExtensions={refresh} /> ))} </List.Section> </List> ); } enum Flags { None = 0x0, IncludeVersions = 0x1, IncludeFiles = 0x2, IncludeCategoryAndTags = 0x4, IncludeSharedAccounts = 0x8, IncludeVersionProperties = 0x10, ExcludeNonValidated = 0x20, IncludeInstallationTargets = 0x40, IncludeAssetUri = 0x80, IncludeStatistics = 0x100, IncludeLatestVersionOnly = 0x200, Unpublished = 0x1000, } enum FilterType { Tag = 1, ExtensionId = 4, Category = 5, ExtensionName = 7, Target = 8, Featured = 9, SearchText = 10, ExcludeWithFlags = 12, } function flagsToString(...flags: Flags[]): string { return String(flags.reduce((r, f) => r | f, 0)); } function useGalleryQuery(searchText: string): { data: GalleryQueryResult | undefined; error: string | undefined; isLoading: boolean; } { // reference for impl. https://github.com/microsoft/vscode/blob/12ae331012923024bedaf873ba4259a8c64db020/src/vs/platform/extensionManagement/common/extensionGalleryService.ts const url = "https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery?api-version=3.0-preview.1"; const headers = { "content-type": "application/json", "accept-encoding": "gzip", }; const allFlags: Flags[] = [ Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeCategoryAndTags, Flags.IncludeFiles, Flags.IncludeVersionProperties, Flags.ExcludeNonValidated, ]; const flags = allFlags.reduce((r, f) => r | f, 0); const request = { filters: [ { criteria: [ { filterType: FilterType.Target, value: "Microsoft.VisualStudio.Code", }, { filterType: FilterType.SearchText, value: searchText, }, { filterType: FilterType.ExcludeWithFlags, value: flagsToString(Flags.Unpublished), }, ], pageNumber: 1, pageSize: 100, sortBy: 0, sortOrder: 0, }, ], assetTypes: [], flags: flags, }; const body = JSON.stringify(request); const execute = searchText.length > 0; const { isLoading, error, data } = useFetch<GalleryQueryResult | undefined>(url, { headers: headers, body: body, method: "POST", keepPreviousData: false, execute: execute, }); return { isLoading: execute ? isLoading : false, error: error?.message, data: searchText.length <= 0 ? undefined : data, }; }
import { render, screen } from '@testing-library/react'; import { createMemoryHistory } from 'history'; import { configureMockStore } from '@jedmao/redux-mock-store'; import { Provider } from 'react-redux'; import HistoryRouter from '../../components/history-router/history-router'; import { AuthorizationStatus } from '../../const'; import Header from './header'; const mockStore = configureMockStore(); describe('Component: Header', () => { it('should render correctly', () => { const history = createMemoryHistory(); const store = mockStore({ USER: { authorizationStatus: AuthorizationStatus.Auth, userEmail: 'ma@ya.ru', }, DATA: { favoriteOffers: [], } }); render( <Provider store={store}> <HistoryRouter history={history}> <Header /> </HistoryRouter> </Provider>, ); const headerElement = screen.getByText('ma@ya.ru'); expect(headerElement).toBeInTheDocument(); }); });
# Java 代码面试完全指南(四) > 原文:[`zh.annas-archive.org/md5/2AD78A4D85DC7F13AC021B920EE60C36`](https://zh.annas-archive.org/md5/2AD78A4D85DC7F13AC021B920EE60C36) > > 译者:[飞龙](https://github.com/wizardforcel) > > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) # 第十一章:链表和映射 本章涵盖了在编码面试中遇到的涉及映射和链表的最受欢迎的编码挑战。由于在技术面试中更喜欢使用单向链表,本章中的大多数问题将利用它们。但是,您可以挑战自己,尝试在双向链表的情况下解决每个问题。通常,对于双向链表来说,问题变得更容易解决,因为双向链表为每个节点维护两个指针,并允许我们在列表内前后导航。 通过本章结束时,您将了解涉及链表和映射的所有热门问题,并且将具有足够的知识和理解各种技术,以帮助您解决此类问题。我们的议程非常简单;我们将涵盖以下主题: + 链表简介 + 映射简介 + 编码挑战 # 技术要求 本章中的所有代码文件都可以在 GitHub 上找到,网址为[`github.com/PacktPublishing/The-Complete-Coding-Interview-Guide-in-Java/tree/master/Chapter11`](https://github.com/PacktPublishing/The-Complete-Coding-Interview-Guide-in-Java/tree/master/Chapter11)。 但在进行编码挑战之前,让我们先了解一下链表和映射。 # 链表简介 链表是表示节点序列的线性数据结构。第一个节点通常被称为**头部**,而最后一个节点通常被称为**尾部**。当每个节点指向下一个节点时,我们有一个*单向链表*,如下图所示: ![11.1:单向链表](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.1_B15403.jpg) 图 11.1 – 单向链表 当每个节点指向下一个节点和前一个节点时,我们有一个*双向链表*,如下图所示: ![11.2:双向链表](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.2_B15403.jpg) 图 11.2 – 双向链表 让我们考虑一个单向链表。如果尾部指向头部,那么我们有一个*循环单向链表*。或者,让我们考虑一个双向链表。如果尾部指向头部,头部指向尾部,那么我们有一个*循环双向链表*。 在单向链表中,一个节点保存数据(例如,整数或对象)和指向下一个节点的指针。以下代码表示单向链表的节点: ```java private final class Node {   private int data;   private Node next; } ``` 双向链表还需要指向前一个节点的指针: ```java private final class Node {   private int data;   private Node next;   private Node prev; } ``` 与数组不同,链表不提供访问第 n 个元素的常数时间。我们必须迭代 n-1 个元素才能获得第 n 个元素。我们可以在常数时间内从链表(单向和双向)的开头插入,删除和更新节点。如果我们的实现管理双向链表的尾部(称为双头双向链表),那么我们也可以在常数时间内从链表的末尾插入,删除和更新节点;否则,我们需要迭代链表直到最后一个节点。如果我们的实现管理单向链表的尾部(称为双头单向链表),那么我们可以在常数时间内在链表的末尾插入节点;否则,我们需要迭代链表直到最后一个节点。 本书的代码包包括以下应用程序(每个应用程序都公开`insertFirst()`、`insertLast()`、`insertAt()`、`delete()`、`deleteByIndex()`和`print()`方法): + *SinglyLinkedList*:双头单向链表的实现 + *SinglyLinkedListOneHead*:单头单向链表的实现 + *DoublyLinkedList*:双头双向链表的实现 + *DoublyLinkedListOneHead*:单头双向链表的实现 强烈建议您自己彻底分析这些应用程序。每个应用程序都有大量注释,以帮助您理解每个步骤。以下编码挑战依赖于这些链表实现。 # 简而言之,地图 想象一下,您正在字典中查找一个单词。这个单词本身是唯一的,可以被视为*键*。这个单词的意思可以被视为*值*。因此,这个单词及其意思形成了一个*键值对*。同样,在计算中,键值对容纳了一段数据,可以通过键来查找值。换句话说,我们知道键,我们可以用它来找到值。 地图是一个**抽象数据类型**(**ADT**),通过数组管理键值对(称为条目)。地图的特征包括以下内容: + 键是唯一的(即,不允许重复键)。 + 我们可以查看键的列表,值的列表,或两者。 + 处理地图的最常见方法是`get()`,`put()`和`remove()`。 现在我们已经简要概述了链表和地图的概念,让我们开始我们的编码挑战。 # 编码挑战 在接下来的 17 个编码挑战中,我们将涵盖涉及地图和链表的许多问题。由于链表是技术面试中更受欢迎的话题,我们将为它们分配更多的问题。然而,为了掌握地图数据结构的概念,特别是内置的 Java 地图实现,我强烈建议您购买 Packt Publishing 出版的书籍*Java 编码问题*([`www.packtpub.com/programming/java-coding-problems`](https://www.packtpub.com/programming/java-coding-problems))。除了是本书的绝佳伴侣外,*Java 编码问题*还包含以下地图问题(请注意,这不是完整的列表): + 创建不可修改/不可变集合 + 映射默认值 + 计算`Map`中值的存在/不存在 + 从`Map`中删除 + 替换`Map`中的条目 + 比较两个地图 + 对`Map`进行排序 + 复制`HashMap` + 合并两个地图 + 删除与谓词匹配的集合的所有元素 现在我们对链表和地图有了基本的了解,让我们来看看与地图和链表相关的面试中最常见的问题。 ## 编码挑战 1 - Map put,get 和 remove `put(K k, V v)`,一个名为`get(K k)`的方法,和一个名为`remove(K k)`的方法。 **解决方案**:正如您所知,地图是一个键值对数据结构。每个键值对都是地图的一个条目。因此,我们无法实现地图的功能,直到我们实现一个条目。由于一个条目包含两个信息,我们需要定义一个类来以通用的方式包装键和值。 代码非常简单: ```java private final class MyEntry<K, V> {   private final K key;   private V value;   public MyEntry(K key, V value) {     this.key = key;     this.value = value;   }   // getters and setters omitted for brevity } ``` 现在我们有了一个条目,我们可以声明一个地图。地图通过具有默认大小的条目数组来管理,这个默认大小称为地图容量。具有 16 个元素的初始容量的地图声明如下: ```java private static final int DEFAULT_CAPACITY = 16; private MyEntry<K, V>[] entries         = new MyEntry[DEFAULT_CAPACITY]; ``` 接下来,我们可以专注于使用这个数组作为客户端的地图。只有在条目的键在地图中是唯一的情况下,才能将条目放入地图中。如果给定的键存在,则只需更新其值。除此之外,只要我们没有超出地图的容量,就可以添加一个条目。在这种情况下的典型方法是将地图的大小加倍。基于这些语句的代码如下: ```java private int size; public void put(K key, V value) {   boolean success = true;   for (int i = 0; i < size; i++) {     if (entries[i].getKey().equals(key)) {       entries[i].setValue(value);       success = false;     }   }   if (success) {     checkCapacity();     entries[size++] = new MyEntry<>(key, value);   } } ``` 以下辅助方法用于将地图的容量加倍。由于 Java 数组无法调整大小,我们需要通过创建初始数组的副本,但大小加倍来解决这个问题: ```java private void checkCapacity() {   if (size == entries.length) {     int newSize = entries.length * 2;     entries = Arrays.copyOf(entries, newSize);   } } ``` 使用键来获取值。如果找不到给定的键,则返回`null`。获取值不会从地图中删除条目。让我们看一下代码: ```java public V get(K key) {   for (int i = 0; i < size; i++) {     if (entries[i] != null) {       if (entries[i].getKey().equals(key)) {         return entries[i].getValue();       }     }   }   return null; } ``` 最后,我们需要使用键来删除一个条目。从数组中删除一个元素涉及将剩余的元素向前移动一个位置。元素移动后,倒数第二个和最后一个元素相等。通过将数组的最后一个元素置空,可以避免内存泄漏。忘记这一步是一个常见的错误: ```java public void remove(K key) {   for (int i = 0; i < size; i++) {     if (entries[i].getKey().equals(key)) {       entries[i] = null;       size--;       condenseArray(i);     }   } } private void condenseArray(int start) {   int i;   for (i = start; i < size; i++) {     entries[i] = entries[i + 1];   }   entries[i] = null; // don't forget this line } ``` 地图的生产实现比这里展示的要复杂得多(例如,地图使用桶)。然而,很可能在面试中你不需要了解比这个实现更多的内容。尽管如此,向面试官提到这一点是个好主意。这样,你可以向他们展示你理解问题的复杂性,并且你意识到了这一点。 完成!完整的应用程序名为*Map*。 ## 编码挑战 2 - 映射键集和值 `keySet()`)和一个返回值集合的方法(`values()`)。 `Set`。以下代码不言自明: ```java public Set<K> keySet() {   Set<K> set = new HashSet<>();   for (int i = 0; i < size; i++) {     set.add(entries[i].getKey());   }   return set; } ``` 为了返回一个值的集合,我们循环遍历映射并将值逐个添加到`List`中。我们使用`List`,因为值可能包含重复项: ```java public Collection<V> values() {   List<V> list = new ArrayList<>();   for (int i = 0; i < size; i++) {     list.add(entries[i].getValue());   }   return list; } ``` 完成!这很简单;生产中实现的地图比这里展示的要复杂得多。例如,值被缓存而不是每次都被提取。向面试官提到这一点,让他/她看到你知道生产地图是如何工作的。花点时间检查 Java 内置的`Map`和`HashMap`源代码。 完整的应用程序名为*Map*。 ## 编码挑战 3 - 螺母和螺栓 **谷歌**,**Adobe** **问题**:给定*n*个螺母和*n*个螺栓,考虑它们之间的一一对应关系。编写一小段代码,找出螺母和螺栓之间的所有匹配项,使迭代次数最少。 **解决方案**:让我们假设螺母和螺栓分别由以下两个数组表示: ```java char[] nuts = {'$', '%', '&', 'x', '@'}; char[] bolts = {'%', '@', 'x', '$', '&'}; ``` 最直观的解决方案依赖于蛮力方法。我们可以选择一个螺母,并迭代螺栓以找到它的配偶。例如,如果我们选择`nuts[0]`,我们可以用`bolts[3]`找到它的配偶。此外,我们可以取`nuts[1]`,并用`bolts[0]`找到它的配偶。这个算法非常简单,可以通过两个`for`语句来实现,并且具有 O(n2)的时间复杂度。 或者,我们可以考虑对螺母和螺栓进行排序。这样,螺母和螺栓之间的匹配将自动对齐。这也可以工作,但不会包括最少的迭代次数。 为了获得最少的迭代次数,我们可以使用哈希映射。在这个哈希映射中,首先,我们将每个螺母作为一个键,将其在给定螺母数组中的位置作为一个值。接下来,我们迭代螺栓,并检查哈希映射是否包含每个螺栓作为一个键。如果哈希映射包含当前螺栓的键,那么我们找到了一个匹配(一对);否则,这个螺栓没有匹配。让我们看一下代码: ```java public static void match(char[] nuts, char[] bolts) {   // in this map, each nut is a key and   // its position is as value   Map<Character, Integer> map = new HashMap<>();   for (int i = 0; i < nuts.length; i++) {     map.put(nuts[i], i);   }   //for each bolt, search a nut   for (int i = 0; i < bolts.length; i++) {     char bolt = bolts[i];     if (map.containsKey(bolt)) {       nuts[i] = bolts[i];     } else {       System.out.println("Bolt " + bolt + " has no nut");     }   }   System.out.println("Matches between nuts and bolts: ");   System.out.println("Nuts: " + Arrays.toString(nuts));   System.out.println("Bolts: " +Arrays.toString(bolts)); } ``` 这段代码的运行时间是 O(n)。完整的代码名为*NutsAndBolts*。 ## 编码挑战 4 - 删除重复项 **亚马逊**,**谷歌**,**Adobe**,**微软** **问题**:考虑一个未排序的整数单向链表。编写一小段代码来删除重复项。 `Set<Integer>`。然而,在将当前节点的数据添加到`Set`之前,我们检查数据是否与`Set`的当前内容相匹配。如果`Set`已经包含该数据,我们就从链表中删除节点;否则,我们只是将其数据添加到`Set`中。从单向链表中删除节点可以通过将前一个节点链接到当前节点的下一个节点来完成。 以下图示说明了这个陈述: ![11.3: 从单向链表中删除节点](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.3_B15403.jpg) 图 11.3 - 从单向链表中删除节点 由于单链表只保存指向下一个节点的指针,我们无法知道当前节点之前的节点。技巧是跟踪两个连续的节点,从当前节点作为链表头部和前一个节点作为`null`开始。当当前节点前进到下一个节点时,前一个节点前进到当前节点。让我们看一下将这些语句组合在一起的代码: ```java // 'size' is the linked list size public void removeDuplicates() {   Set<Integer> dataSet = new HashSet<>();   Node currentNode = head;   Node prevNode = null;   while (currentNode != null) {     if (dataSet.contains(currentNode.data)) {       prevNode.next = currentNode.next;       if (currentNode == tail) {         tail = prevNode;       }       size--;     } else {       dataSet.add(currentNode.data);       prevNode = currentNode;     }     currentNode = currentNode.next;   } } ``` 这个解决方案的时间和空间复杂度为 O(n),其中*n*是链表中的节点数。我们可以尝试另一种方法,将空间复杂度降低到 O(1)。首先,让我们将以下图表作为下一步的指南: ![11.4:从单链表中移除节点](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.4_B15403.jpg) 图 11.4 - 从单链表中移除节点 这种方法使用两个指针: 1. 当前节点从链表的头部开始遍历链表,直到到达尾部(例如,在前面的图表中,当前节点是第二个节点)。 1. 奔跑者节点,从与当前节点相同的位置开始,即链表的头部。 此外,奔跑者节点遍历链表,并检查每个节点的数据是否等于当前节点的数据。当奔跑者节点遍历链表时,当前节点的位置保持不变。 如果奔跑者节点检测到重复,那么它会将其从链表中移除。当奔跑者节点到达链表的尾部时,当前节点前进到下一个节点,奔跑者节点再次从当前节点开始遍历链表。因此,这是一个 O(n2)时间复杂度的算法,但空间复杂度为 O(1)。让我们看一下代码: ```java public void removeDuplicates() {   Node currentNode = head;   while (currentNode != null) {     Node runnerNode = currentNode;     while (runnerNode.next != null) {       if (runnerNode.next.data == currentNode.data) {         if (runnerNode.next == tail) {           tail = runnerNode;         }         runnerNode.next = runnerNode.next.next;         size--;       } else {         runnerNode = runnerNode.next;       }     }     currentNode = currentNode.next;   } } ``` 完整的代码名为*LinkedListRemoveDuplicates*。 ## 编码挑战 5 - 重新排列链表 **Adobe**,**Flipkart**,**Amazon** **问题**:考虑一个未排序的整数单链表和一个给定的整数*n*。编写一小段代码,围绕*n*重新排列节点。换句话说,最后,链表将包含所有小于*n*的值,后面跟着所有大于*n*的节点。节点的顺序可以改变,*n*本身可以位于大于*n*的值之间的任何位置。 **解决方案**:假设给定的链表是 1→5→4→3→2→7→null,*n*=3。所以,3 是我们的枢轴。其余的节点应该围绕这个枢轴重新排列,符合问题的要求。解决这个问题的一个方法是逐个遍历链表节点,并将小于枢轴的每个节点放在头部,而大于枢轴的每个节点放在尾部。以下图表帮助我们可视化这个解决方案: ![11.5:链表重新排列](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.5_B15403.jpg) 图 11.5 - 链表重新排列 因此,值为 5、4 和 3 的节点被移动到尾部,而值为 2 的节点被移动到头部。最后,所有小于 3 的值都在虚线的左侧,而所有大于 3 的值都在虚线的右侧。我们可以将此算法编写成以下代码: ```java public void rearrange(int n) {   Node currentNode = head;   head = currentNode;   tail = currentNode;   while (currentNode != null) {     Node nextNode = currentNode.next;     if (currentNode.data < n) {       // insert node at the head       currentNode.next = head;       head = currentNode;     } else {       // insert node at the tail       tail.next = currentNode;       tail = currentNode;     }     currentNode = nextNode;   }   tail.next = null; } ``` 完整的应用程序名为*LinkedListRearranging*。 ## 编码挑战 6 - 倒数第 n 个节点 **Adobe**,**Flipkart**,**Amazon**,**Google**,**Microsoft** **问题**:考虑一个整数单链表和一个给定的整数*n*。编写一小段代码,返回倒数第 n 个节点的值。 **解决方案**:我们有一堆节点,我们必须找到满足给定约束的第*n*个节点。根据我们从*第八章*的经验,*递归和动态规划*,我们可以直觉地认为这个问题有一个涉及递归的解决方案。但我们也可以通过迭代解决它。由于迭代解决方案更有趣,我将在这里介绍它,而递归解决方案在捆绑代码中可用。 让我们使用以下图表来呈现算法(按照从上到下的顺序遵循图表): ![11.6: The nth to last node](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.6_B15403.jpg) 图 11.6 - 最后第 n 个节点 因此,我们有一个链表,2 → 1 → 5 → 9 → 8 → 3 → 7 → null,并且我们想要找到第五个到最后一个节点值,即 5(您可以在前面的图表顶部看到)。迭代解决方案使用两个指针;让我们将它们表示为*runner1*和*runner2*。最初,它们都指向链表的头部。在步骤 1(前面图表的中间),我们将*runner1*从头移动到第 5 个到头(或*n*到头)节点。这在`for`循环中从 0 到 5(或*n*)中很容易实现。在步骤 2(前面图表的底部),我们同时移动*runner1*和*runner2*,直到*runner1*为`null`。当*runner1*为`null`时,*runner2*将指向距离头部第五个到最后一个节点(或*n*到最后一个)节点。在代码行中,我们可以这样做: ```java public int nthToLastIterative(int n) {   // both runners are set to the start   Node firstRunner = head;   Node secondRunner = head;   // runner1 goes in the nth position   for (int i = 0; i < n; i++) {     if (firstRunner == null) {       throw new IllegalArgumentException(              "The given n index is out of bounds");     }     firstRunner = firstRunner.next;   }   // runner2 run as long as runner1 is not null   // basically, when runner1 cannot run further (is null),   // runner2 will be placed on the nth to last node   while (firstRunner != null) {     firstRunner = firstRunner.next;     secondRunner = secondRunner.next;   }   return secondRunner.data; } ``` 完整的应用程序名为*LinkedListNthToLastNode*。 ## 编码挑战 7 - 循环开始检测 **Adobe**,**Flipkart**,**Amazon**,**Google**,**Microsoft** **问题**:考虑一个包含循环的整数单链表。换句话说,链表的尾部指向之前的一个节点,定义了一个循环或循环。编写一小段代码来检测循环的第一个节点(即循环开始的节点)。 `tail.next`. 如果我们不管理尾部,那么我们可以搜索具有两个指向它的节点的节点。这也很容易实现。如果我们知道链表的大小,那么我们可以从 0 到大小进行迭代,最后一个`node.next`指向标记循环开始的节点。 ### 快跑者/慢跑者方法 然而,让我们尝试另一种需要更多想象力的算法。这种方法称为快跑者/慢跑者方法。它很重要,因为它可以用于涉及链表的某些问题。 主要的快跑者/慢跑者方法涉及使用两个指针,它们从链表的头部开始,并同时遍历列表,直到满足某些条件。一个指针被命名为**慢跑者**(**SR**),因为它逐个节点地遍历列表。另一个指针被命名为**快跑者**(**FR**),因为它在每次移动时跳过下一个节点来遍历列表。以下图表是四个移动的示例: ![11.7: Fast Runner/Slow Runner example](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.7_B15403.jpg) 图 11.7 - 快跑者/慢跑者示例 因此,在第一步移动时,*FR*和*SR*指向*head*。在第二步移动时,*SR*指向值为 1 的*head.next*节点,而*FR*指向值为 4 的*head.next.next*节点。移动继续遵循这种模式。当*FR*到达链表的尾部时,*SR*指向中间节点。 正如您将在下一个编码挑战中看到的,快跑者/慢跑者方法可以用于检测链表是否是回文。但是,现在让我们恢复我们的问题。那么,我们可以使用这种方法来检测链表是否有循环,并找到此循环的起始节点吗?这个问题引发了另一个问题。如果我们将快跑者/慢跑者方法应用于具有循环的链表,*FR*和*SR*指针会相撞或相遇吗?答案是肯定的,它们会相撞。 解释一下,假设在开始循环之前,我们有*q*个先行节点(这些节点在循环外)。对于*SR*遍历的每个*q*个节点,*FR*已经遍历了 2**q*个节点(这是显而易见的,因为*FR*在每次移动时都会跳过一个节点)。因此,当*SR*进入循环(到达循环起始节点)时,*FR*已经遍历了 2**q*个节点。换句话说,*FR*在循环部分的 2**q-q*节点处;因此,它在循环部分的*q*个节点处。让我们通过以下测试案例来形象化这一点: ![11.8: 带有循环的链表](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.8_B15403.jpg) 图 11.8 - 带有循环的链表 因此,当*SR*进入循环(到达第四个节点)时,*FR*也到达了循环的第四个节点。当然,我们需要考虑到*q*(先行非循环节点的数量)可能比循环长度要大得多;因此,我们应该将 2**q-q*表示为*Q=modulo(q, LOOP_SIZE)*。 例如,考虑*Q = modulo*(3, 8) =3,其中我们有三个非循环节点(*q*=3),循环大小为八(*LOOP_SIZE*=8)。在这种情况下,我们也可以应用 2**q-q*,因为 2*3-3=3。因此,我们可以得出*SR*距离列表开头三个节点,*FR*距离循环开头三个节点。然而,如果链表前面有 25 个节点,后面有 7 个节点的循环,那么*Q = modulo* (25, 7) = 4 个节点,而 2*25-25=25,这是错误的。 除此之外,*FR*和*SR*在循环内移动。由于它们在一个圆圈内移动,这意味着当*FR*远离*SR*时,它也在向*SR*靠近,反之亦然。下图将循环隔离出来,并展示了它们如何继续移动*FR*和*SR*直到它们相撞: ![11.9: FR and SR collision](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.9_B15403.png) 图 11.9 - FR 和 SR 碰撞 花时间追踪*SR*和*FR*直到它们到达相遇点。我们知道*FR*比*FR*落后*LOOP_SIZE - Q*个节点,*SR*比*FR*落后*Q*个节点。在我们的测试案例中,*FR*比*SR*落后 8-3=5 个节点,*SR*比*FR*落后 3 个节点。继续移动*SR*和*FR*,我们可以看到*FR*以每次移动 1 步的速度追上了。 那么,它们在哪里相遇呢?如果*FR*以每次移动 1 步的速度追上,*FR*比*SR*落后*LOOP_SIZE - Q*个节点,那么它们将在离循环头部*Q*步的地方相遇。在我们的测试案例中,它们将在距离循环头部 3 步的地方相遇,节点值为 8。 如果相遇点距离循环头部的节点数为*Q*,我们可以继续回想相遇点距离循环头部的节点数也为*q*,因为*Q=modulo(q, LOOP_SIZE)*。这意味着我们可以制定以下四步算法: 1. 从链表的头部开始*FR*和*SR*。 1. 将*SR*以 1 个节点的速度移动,*FR*以 2 个节点的速度移动。 1. 当它们相撞(在相遇点),将*SR*移动到链表的头部,保持*FR*在原地。 1. 将*SR*和*FR*以 1 个节点的速度移动,直到它们相撞(这是代表循环头部的节点)。 让我们把这写成代码: ```java public void findLoopStartNode() {   Node slowRunner = head;   Node fastRunner = head;   // fastRunner meets slowRunner   while (fastRunner != null && fastRunner.next != null) {     slowRunner = slowRunner.next;     fastRunner = fastRunner.next.next;     if (slowRunner == fastRunner) { // they met       System.out.println("\nThe meet point is at         the node with value: " + slowRunner);       break;     }   }   // if no meeting point was found then there is no loop   if (fastRunner == null || fastRunner.next == null) {     return;   }   // the slowRunner moves to the head of the linked list   // the fastRunner remains at the meeting point   // they move simultaneously node-by-node and   // they should meet at the loop start   slowRunner = head;   while (slowRunner != fastRunner) {     slowRunner = slowRunner.next;     fastRunner = fastRunner.next;   }   // both pointers points to the start of the loop   System.out.println("\nLoop start detected at       the node with value: " + fastRunner); } ``` 作为一个快速的提示,不要期望*FR*能够跳过*SR*,所以它们不会相遇。这种情况是不可能的。想象一下,*FR*已经跳过了*SR*,它在节点*a*,那么*SR*必须在节点*a*-1。这意味着,在上一步中,*FR*在节点*a*-2,*SR*在节点(*a*-1)-1=*a*-2;因此,它们已经相撞了。 完整的应用程序名为*LinkedListLoopDetection*。在这段代码中,你会找到一个名为`generateLoop()`的方法。调用这个方法可以生成带有循环的随机链表。 ## 编码挑战 8 - 回文 Adobe,Flipkart,Amazon,Google,Microsoft 如果链表是回文的,则返回`true`。解决方案应该涉及快速运行者/慢速运行者方法(这种方法在先前的编码挑战中有详细介绍)。 **解决方案**:只是一个快速提醒,回文(无论是字符串、数字还是链表)在翻转时看起来没有变化。这意味着处理(读取)回文可以从两个方向进行,得到的结果是相同的(例如,数字 12321 是一个回文,而数字 12322 不是)。 我们可以通过思考,当*FR*到达链表的末尾时,*SR*正好在链表的中间,来直观地得出使用快慢指针方法的解决方案。 如果链表的前半部分是后半部分的倒序,那么链表就是一个回文。因此,如果我们在栈中存储*FR*到达链表末尾之前*SR*遍历的所有节点,那么结果栈将包含链表前半部分的倒序。让我们通过以下图表来可视化这一点: ![11.10:使用快慢指针方法的链表回文](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.10_B15403.jpg) 图 11.10 - 使用快慢指针方法的链表回文 因此,当*FR*到达链表的末尾,*SR*到达第四个节点(链表的中间)时,栈包含值 2、1 和 4。接下来,我们可以继续以 1 个节点的速度移动*SR*,直到链表的末尾。在每次移动时,我们从栈中弹出一个值,并将其与当前节点的值进行比较。如果我们发现不匹配,那么链表就不是回文。在代码中,我们有以下内容: ```java public boolean isPalindrome() {   Node fastRunner = head;   Node slowRunner = head;   Stack<Integer> firstHalf = new Stack<>();   // the first half of the linked list is added into the stack   while (fastRunner != null && fastRunner.next != null) {     firstHalf.push(slowRunner.data);     slowRunner = slowRunner.next;     fastRunner = fastRunner.next.next;   }   // for odd number of elements we to skip the middle node   if (fastRunner != null) {     slowRunner = slowRunner.next;   }   // pop from the stack and compare with the node by node of   // the second half of the linked list   while (slowRunner != null) {     int top = firstHalf.pop();     // a mismatch means that the list is not a palindrome     if (top != slowRunner.data) {       return false;     }     slowRunner = slowRunner.next;   }   return true; } ``` 完整的应用程序名为*LinkedListPalindrome*。 ## 编码挑战 9 - 两个链表相加 **Adobe**,**Flipkart**,**Microsoft** **问题**:考虑两个正整数和两个单链表。第一个整数按位存储在第一个链表中(第一个数字是第一个链表的头)。第二个整数按位存储在第二个链表中(第一个数字是第二个链表的头)。编写一小段代码,将这两个数字相加,并将和作为一个链表返回,每个节点一个数字。 **解决方案**:让我们从一个测试案例的可视化开始: ![11.11:将两个数字作为链表相加](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.11_B15403.jpg) 图 11.11 - 将两个数字作为链表相加 如果我们逐步计算前面图表的总和,我们得到以下结果: 我们添加 7 + 7 = 14,所以我们写下 4 并携带 1: 结果链表是 4 →? 我们添加 3 + 9 + 1 = 13,所以我们写下 3 并携带 1: 结果链表是 4 → 3 →? 我们添加 8 + 8 + 1 = 17,所以我们写下 7 并携带 1: 结果链表是 4 → 3 → 7 →? 我们添加 9 + 4 + 1 = 14,所以我们写下 4 并携带 1 结果链表是 4 → 3 → 7 → 4 →? 我们添加 4 + 1 = 5,所以我们写下 5 并携带无: 结果链表是 4 → 3 → 7 → 4 → 5 →? 我们添加 1 + 0 = 1,所以我们写下 1 并携带无: 结果链表是 4 → 3 → 7 → 4 → 5 → 1 →? 我们添加 2 + 0 = 2,所以我们写下 2 并携带无: 结果链表是 4 → 3 → 7 → 4 → 5 → 1 → 2 如果我们将结果链表写成一个数字,我们得到 4374512;因此,我们需要将其反转为 2154734。虽然反转结果链表的方法(可以被视为一个编码挑战)可以在捆绑代码中找到,但以下方法以递归的方式应用了前面的步骤(如果你不擅长递归问题,请不要忘记阅读*第八章*,*递归和动态规划*)。基本上,以下递归通过逐个节点添加数据,将任何多余的数据传递到下一个节点: ```java private Node sum(Node node1, Node node2, int carry) {   if (node1 == null && node2 == null && carry == 0) {     return null;   }   Node resultNode = new Node();   int value = carry;   if (node1 != null) {     value += node1.data;   }   if (node2 != null) {     value += node2.data;   }   resultNode.data = value % 10;   if (node1 != null || node2 != null) {     Node more = sum(node1 == null         ? null : node1.next, node2 == null         ? null : node2.next, value >= 10 ? 1 : 0);     resultNode.next = more;   }   return resultNode; } ``` 完整的应用程序名为*LinkedListSum*。 ## 编码挑战 10 - 链表交集 **Adobe**,**Flipkart**,**Google**,**Microsoft** **问题**:考虑两个单链表。编写一小段代码,检查这两个列表是否相交。交集是基于引用的,而不是基于值的,但是你应该返回交集节点的值。因此,通过引用检查交集并返回值。 **解决方案**:如果你不确定*两个链表的交集*是什么意思,那么我们建议你勾画一个测试用例,并与面试官讨论细节。下面的图表展示了这样一个情况: ![11.12: 两个列表的交集](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.12_B15403.jpg) 图 11.12 – 两个列表的交集 在这个图表中,我们有两个相交的列表,它们在值为 8 的节点处相交。因为我们谈论的是引用交集,这意味着值为 9 和值为 4 的节点指向值为 8 的节点的内存地址。 主要问题是列表的大小不同。如果它们的大小相等,我们可以从头到尾遍历它们,逐个节点,直到它们相撞(直到*node_list_1.next= node_list_2.next*)。如果我们能跳过值为 2 和 1 的节点,我们的列表将是相同大小的(参考下一个图表;因为第一个列表比第二个列表长,我们应该从标记为*虚拟头*的节点开始迭代): ![11.13: Removing the first two nodes of the top list](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.13_B15403.jpg) 图 11.13 – 移除顶部列表的前两个节点 记住这个陈述,我们可以推导出以下算法: 1. 确定列表的大小。 1. 如果第一个列表(我们将其表示为*l1*)比第二个列表(我们将其表示为*l2*)长,那么将第一个列表的指针移动到(*l1-l2*)。 1. 如果第一个列表比第二个列表短,那么将第二个列表的指针移动到(*l2-l1*)。 1. 逐个移动两个指针,直到达到末尾或者它们相撞为止。 将这些步骤转化为代码是直接的: ```java public int intersection() {   // this is the head of first list   Node currentNode1 = {head_of_first_list};   // this is the head of the second list   Node currentNode2 = {head_of_second_list};   // compute the size of both linked lists   // linkedListSize() is just a helper method   int s1 = linkedListSize(currentNode1);   int s2 = linkedListSize(currentNode2);   // the first linked list is longer than the second one   if (s1 > s2) {     for (int i = 0; i < (s1 - s2); i++) {       currentNode1 = currentNode1.next;     }   } else {     // the second linked list is longer than the first one     for (int i = 0; i < (s2 - s1); i++) {       currentNode2 = currentNode2.next;     }   }   // iterate both lists until the end or the intersection node   while (currentNode1 != null && currentNode2 != null) {     // we compare references not values!     if (currentNode1 == currentNode2) {       return currentNode1.data;     }     currentNode1 = currentNode1.next;     currentNode2 = currentNode2.next;   }   return -1; } ``` 完整的应用程序名为*LinkedListsIntersection*。在代码中,你会看到一个名为`generateTwoLinkedListWithInterection()`的辅助方法。这用于生成具有交集点的随机列表。 ## 编码挑战 11 – 交换相邻节点 **亚马逊**,**谷歌** **问题**:考虑一个单链表。编写一小段代码,交换相邻的节点,使得一个列表,比如 1 → 2 → 3 → 4 → null,变成 2 → 1 → 4 → 3 → null。考虑交换相邻的节点,而不是它们的值! **解决方案**:我们可以将交换两个相邻节点*n1*和*n2*的问题简化为找到解决方案。交换两个值(例如,两个整数*v1*和*v2*)的一个众所周知的技巧依赖于一个辅助变量,并且可以写成如下形式: *aux = v1; v1 = v2; v2 = aux;* 然而,我们不能对节点应用这种简单的方法,因为我们必须处理它们的链接。仅仅写下面这样是不够的: *aux = n1; n1 = n2; n2 = aux;* 如果我们依赖这种简单的方法来交换*n1*和*n2*,那么我们将得到类似于以下图表的东西(注意,在交换*n1*和*n2*之后,我们有*n1.next* = *n3*和*n2.next* = *n1*,这是完全错误的): ![11.14: Plain swapping with broken links (1)](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.14_B15403.jpg) 图 11.14 – 交换破损链接(1) 但是我们可以修复链接,对吧?嗯,我们可以明确地设置*n1.next*指向*n2*,并设置*n2.next*指向*n3*: *n1.next = n2* *n2.next = n3* 现在应该没问题了!我们可以交换两个相邻的节点。然而,当我们交换一对节点时,我们也会破坏两对相邻节点之间的链接。下面的图表说明了这个问题(我们交换并修复了*n1-n2*对和*n3-n4*对的链接): ![11.15: Plain swapping with broken links (2)](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.15_B15403.jpg) 图 11.15 – 交换破损链接(2) 注意,在交换这两对之后,*n2.next*指向了* n4*,这是错误的。因此,我们必须修复这个链接。为此,我们可以存储*n2*,在交换*n3-n4*之后,我们可以通过设置*n2.next=n3*来修复链接。现在,一切看起来都很好,我们可以将其放入代码中: ```java public void swap() {   if (head == null || head.next == null) {     return;   }   Node currentNode = head;   Node prevPair = null;   // consider two nodes at a time and swap their links   while (currentNode != null && currentNode.next != null) {     Node node1 = currentNode;           // first node     Node node2 = currentNode.next;      // second node                         Node node3 = currentNode.next.next; // third node                 // swap node1 node2     Node auxNode = node1;     node1 = node2;     node2 = auxNode;     // repair the links broken by swapping     node1.next = node2;     node2.next = node3;     // if we are at the first swap we set the head     if (prevPair == null) {       head = node1;     } else {       // we link the previous pair to this pair       prevPair.next = node1;     }     // there are no more nodes, therefore set the tail     if (currentNode.next == null) {       tail = currentNode;     }     // prepare the prevNode of the current pair     prevPair = node2;     // advance to the next pair     currentNode = node3;   } } ``` 完整的应用程序名为*LinkedListPairwiseSwap*。考虑挑战自己交换*n*个节点的序列。 ## 编码挑战 12 - 合并两个排序的链表 **亚马逊**,**谷歌**,**Adobe**,**微软**,**Flipkart** **问题**:考虑两个排序的单链表。编写一小段代码,将这两个列表合并而不使用额外空间。 **解决方案**:所以,我们有两个排序的列表,*list1*:4 → 7 → 8 → 10 → null 和*list2*:5 → 9 → 11 → null,我们希望得到结果,4 → 5 → 7 → 8 → 9 → 10 → 11 → null。此外,我们希望在不分配新节点的情况下获得这个结果。 由于我们不能分配新节点,我们必须选择其中一个列表成为最终结果或合并的链表。换句话说,我们可以从*list1*开始作为合并的链表,并在*list1*的适当位置添加*list2*的节点。在处理每次比较后,我们将指针(*list1*)移动到合并列表的最后一个节点。 例如,我们首先比较这两个列表的头部。如果*list1*的头部小于*list2*的头部,我们选择*list1*的头部作为合并列表的头部。否则,如果*list1*的头部大于*list2*的头部,我们交换头部。以下图表说明了这一步骤: ![图 11.16 - 合并两个排序的链表(步骤 1)](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.16_B15403.jpg) 图 11.16 - 合并两个排序的链表(步骤 1) 由于*list1*的头部小于*list2*的头部(4 < 5),它成为了合并列表的头部。我们说*list1*将指向合并列表的最后一个节点;因此,下一个要比较的节点应该是*list1.next*(值为 7 的节点)和*list2*(值为 5 的节点)。以下图表显示了这个比较的结果: ![图 11.17 - 合并两个排序的链表(步骤 2)](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.17_B15403.jpg) 图 11.17 - 合并两个排序的链表(步骤 2) 因为*list1*跟随合并后的列表(最终结果),我们必须将*list1.next*移动到值为 5 的节点,但我们不能直接这样做。如果我们说*list1.next=list2*,那么我们就会失去*list1*的其余部分。因此,我们必须执行一次交换,如下所示: ```java Node auxNode = list1.next; // auxNode = node with value 7 list1.next = list2;        // list1.next = node with value 5 list2 = auxNode;           // list2 = node with value 7 ``` 接下来,我们将*list1*移动到*list1.next*,也就是值为 9 的节点。我们将*list.next*与*list2*进行比较;因此,我们将 9 与 7 进行比较。以下图表显示了这个比较的结果: ![图 11.18 - 合并两个排序的链表(步骤 3)](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.18_B15403.jpg) 图 11.18 - 合并两个排序的链表(步骤 3) 因为*list1*跟随合并后的列表(最终结果),我们必须将*list1.next*移动到值为 7 的节点(因为 7 < 9),我们使用之前讨论过的交换来完成。接下来,我们将*list1*移动到*list1.next*,也就是值为 8 的节点。我们将*list.next*与*list2*进行比较;因此,我们将 8 与 9 进行比较。以下图表显示了这个比较的结果: ![图 11.19 - 合并两个排序的链表(步骤 4)](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.19_B15403.jpg) 图 11.19 - 合并两个排序的链表(步骤 4) 由于 8 < 9,不需要交换。我们将*list1.next*移动到下一个节点(值为 10 的节点)并将 10 与 9 进行比较。下一个图表显示了这个比较的结果: ![图 11.20 - 合并两个排序的链表(步骤 5)](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.20_B15403.jpg) 图 11.20 - 合并两个排序的链表(步骤 5) 作为*list1*跟随合并后的列表(最终结果),我们必须将*list1.next*移动到值为 9 的节点(因为 9 < 10),我们使用之前讨论过的交换来完成。接下来,我们将*list1*移动到*list1.next*,这是值为 11 的节点。我们将*list.next*与*list2*进行比较;因此,我们将 11 与 10 进行比较。下一个图表显示了这个比较的结果: ![11.21:合并两个排序的链表(第 6 步)](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.21_B15403.jpg) 图 11.21 - 合并两个排序的链表(第 6 步) 因为*list1*跟随合并后的列表(最终结果),我们必须将*list1.next*移动到值为 10 的节点(因为 10 < 11),我们使用之前讨论过的交换来完成。接下来,我们将*list1*移动到*list1.next*,这是`null`;因此,我们从*list2*中复制剩余部分。下一个图表显示了这个比较的结果: ![11.22:合并两个排序的链表(最后一步)](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.22_B15403.jpg) 图 11.22 - 合并两个排序的链表(最后一步) 此时,合并后的链表已经完成。现在是时候揭示代码了(这个方法被添加到了著名的`SinglyLinkedList`中): ```java public void merge(SinglyLinkedList sll) {   // these are the two lists   Node list1 = head;      // the merged linked list   Node list2 = sll.head;  // from this list we add nodes at                           // appropriate place in list1   // compare heads and swap them if it is necessary   if (list1.data < list2.data) {     head = list1;   } else {     head = list2;     list2 = list1;     list1 = head;   }   // compare the nodes from list1 with the nodes from list2   while (list1.next != null) {     if (list1.next.data > list2.data) {       Node auxNode = list1.next;       list1.next = list2;       list2 = auxNode;     }     // advance to the last node in the merged linked list                   list1 = list1.next;   }   // add the remaining list2   if (list1.next == null) {     list1.next = list2;   } } ``` 完整的应用程序名为*LinkedListMergeTwoSorted*。类似的问题可能要求您通过递归合并两个排序的链表。虽然您可以找到名为*LinkedListMergeTwoSortedRecursion*的应用程序,但我建议您挑战自己尝试一种实现。此外,基于这种递归实现,挑战自己合并*n*个链表。完整的应用程序名为*LinkedListMergeNSortedRecursion*。 ## 编码挑战 13 - 去除多余路径 **问题**:考虑一个存储矩阵中路径的单链表。节点的数据类型为(*行,列*)或简写为(*r,c*)。路径只能是水平(按*列*)或垂直(按*行*)。完整路径由所有水平和垂直路径的终点给出;因此,中间点(或中间的点)是多余的。编写一小段代码,删除多余的路径。 **解决方案**:让我们考虑一个包含以下路径的链表:(0, 0) → (0, 1) → (0, 2) → (1, 2) → (2, 2) → (3, 2) → (3, 3) → (3, 4) → null。多余的路径包括以下节点:(0, 1),(1, 2),(2, 2)和(3, 3)。因此,在移除多余路径后,我们应该保留一个包含四个节点的列表:(0, 0) → (0, 2) → (3, 2) → (3, 4) → null。下一个图表表示了多余的路径: ![11.23:多余的路径](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.23_B15403.jpg) 图 11.23 - 多余的路径 去除多余路径后,我们得到以下图表: ![11.24:去除冗余后的剩余路径](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.24_B15403.jpg) 图 11.24 - 去除冗余后的剩余路径 前面的图表应该提供了这个问题的解决方案。请注意,定义垂直路径的节点具有相同的列,因为我们只在行上下移动,而定义水平路径的节点具有相同的行,因为我们只在列左右移动。这意味着,如果我们考虑具有相同列或行的值的三个连续节点,那么我们可以移除中间节点。对相邻三元组重复此过程将移除所有多余节点。代码应该非常简单易懂: ```java public void removeRedundantPath() {   Node currentNode = head;   while (currentNode.next != null           && currentNode.next.next != null) {     Node middleNode = currentNode.next.next;     // check for a vertical triplet (triplet with same column)     if (currentNode.c == currentNode.next.c             && currentNode.c == middleNode.c) {       // delete the middle node       currentNode.next = middleNode;     } // check for a horizontal triplet     else if (currentNode.r == currentNode.next.r             && currentNode.r == middleNode.r) {       // delete the middle node       currentNode.next = middleNode;     } else {       currentNode = currentNode.next;     }   } } ``` 完整的应用程序名为*LinkedListRemoveRedundantPath*。 ## 编码挑战 14 - 将最后一个节点移到最前面 **问题**:考虑一个单链表。编写一小段代码,通过两种方法将最后一个节点移到最前面。因此,链表的最后一个节点变为头节点。 **解决方案**:这是一个听起来简单并且确实简单的问题。第一种方法将遵循以下步骤: 1. 将指针移动到倒数第二个节点(我们将其表示为*currentNode*)。 1. 存储*currentNode.next*(我们将其表示为*nextNode* - 这是最后一个节点)。 1. 将`cu`*rrentNode.next*设置为`null`(因此,最后一个节点变为尾部)。 1. 将新的头部设置为存储的节点(因此,头部变为*nextNode*)。 在代码行中,我们有以下内容: ```java public void moveLastToFront() {         Node currentNode = head;   // step 1   while (currentNode.next.next != null) {     currentNode = currentNode.next;   }   // step 2   Node nextNode = currentNode.next;   // step 3   currentNode.next = null;   // step 4   nextNode.next = head;   head = nextNode; } ``` 第二种方法可以通过以下步骤执行: 1. 将指针移动到倒数第二个节点(我们将其表示为*currentNode*)。 1. 将链表转换为循环列表(将*currentNode.next.next*链接到头部)。 1. 将新的头部设置为*currentNode.next*。 1. 通过将*currentNode.next*设置为`null`来打破循环性。 在代码行中,我们有以下内容: ```java public void moveLastToFront() {   Node currentNode = head;   // step 1   while (currentNode.next.next != null) {     currentNode = currentNode.next;   }   // step 2   currentNode.next.next = head;   // step 3   head = currentNode.next;   // step 4 currentNode.next = null; } ``` 完整的应用程序名为*LinkedListMoveLastToFront*。 ## 编码挑战 15 - 以 k 组反转单链表 **Amazon**,**Google**,**Adobe**,**Microsoft** **问题**:考虑一个单链表和一个整数*k*。编写一小段代码,以*k*组反转链表的节点。 **解决方案**:假设给定的链表是 7 → 4 → 3 → 1 → 8 → 2 → 9 → 0 → null,*k*=3。结果应为 3 → 4 → 7 → 2 → 8 → 1 → 0 → 9 → null。 让我们考虑给定的*k*等于链表的大小。在这种情况下,我们将问题简化为反转给定的链表。例如,如果给定的列表是 7 → 4 → 3 → null,*k*=3,则结果应为 3 → 4 → 7 → null。那么,我们如何获得这个结果呢? 为了反转节点,我们需要当前节点(*current*)、当前节点旁边的节点(*next*)和当前节点之前的节点(*previous*),并且我们应用以下代表节点重新排列的算法: 1. 从 0 开始计数。 1. 作为*当前*节点(最初是头节点)不是`null`,并且我们还没有达到给定的*k*,发生以下情况: a. *next*节点(最初为`null`)变为*current*节点旁边的节点(最初是头节点)。 b. *current*节点(最初是头节点)旁边的节点变为*previous*节点(最初为`null`)。 c. *previous*节点变为*current*节点(最初是头节点)。 d. *current*节点变为*next*节点(*步骤 2a*的节点)。 e. 增加计数器。 因此,如果我们应用此算法,我们可以反转整个列表。但是我们需要按组反转它;因此,我们必须解决我们所做的*k*个子问题。如果这对你来说听起来像递归,那么你是对的。在前述算法的末尾,设置为*步骤 2a*(*next*)的节点指向计数器所指向的节点。我们可以说我们已经反转了前*k*个节点。接下来,我们通过递归从*next*节点开始继续下一组*k*节点。以下图表说明了这个想法: ![11.25:以 k 组(k=3)反转列表](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.25_B15403.jpg) 图 11.25 - 以 k 组(k=3)反转列表 以下代码实现了这个想法: ```java public void reverseInKGroups(int k) {   if (head != null) {     head = reverseInKGroups(head, k);   } } private Node reverseInKGroups(Node head, int k) {   Node current = head;   Node next = null;   Node prev = null;   int counter = 0;   // reverse first 'k' nodes of linked list   while (current != null && counter < k) {     next = current.next;                             current.next = prev;                 prev = current;     current = next;     counter++;   }   // 'next' points to (k+1)th node               if (next != null) {     head.next = reverseInKGroups(next, k);   }   // 'prev' is now the head of the input list   return prev; } ``` 这段代码运行时间为 O(n),其中*n*是给定列表中的节点数。完整的应用程序名为*ReverseLinkedListInGroups*。 ## 编码挑战 16 - 反转双向链表 **Microsoft**,**Flipkart** **问题**:考虑一个双向链表。编写一小段代码来反转它的节点。 **解决方案**:反转双向链表可以利用双向链表维护到前一个节点的链接的事实。这意味着我们可以简单地交换每个节点的前指针和后指针,如下面的代码所示: ```java public void reverse() {   Node currentNode = head;   Node prevNode = null;   while (currentNode != null) {     // swap next and prev pointers of the current node     Node prev = currentNode.prev;     currentNode.prev = currentNode.next;     currentNode.next = prev;     // update the previous node before moving to the next node     prevNode = currentNode;     // move to the next node in the doubly linked list                 currentNode = currentNode.prev;   }   // update the head to point to the last node   if (prevNode != null) {     head = prevNode;   } } ``` 完整的应用程序名为*DoublyLinkedListReverse*。要对单链表和双链表进行排序,请参考*第十四章*,*排序和搜索*。 ## 编码挑战 17 - LRU 缓存 **Amazon**,**Google**,**Adobe**,**Microsoft**,**Flipkart** **问题**:编写一小段代码来实现固定大小的 LRU 缓存。LRU 缓存代表最近最少使用的缓存。这意味着,当缓存已满时,添加新条目将指示缓存自动驱逐最近最少使用的条目。 **解决方案**:任何缓存实现必须提供一种快速有效的检索数据的方式。这意味着我们的实现必须遵守以下约束: + **固定大小**:缓存必须使用有限的内存。因此,它需要一些限制(例如,固定大小)。 + **快速访问数据**:插入和搜索操作应该快速;最好是 O(1)复杂度时间。 + **快速驱逐数据**:当缓存已满(达到其分配的限制)时,缓存应该提供一个有效的算法来驱逐条目。 在最后一个要点的背景下,从 LRU 缓存中驱逐意味着驱逐最近最少使用的数据。为了实现这一点,我们必须跟踪最近使用的条目和长时间未使用的条目。此外,我们必须确保插入和搜索操作的 O(1)复杂度时间。在 Java 中没有内置的数据结构可以直接给我们提供这样的缓存。 但是我们可以从`HashMap`数据结构开始。在 Java 中,`HashMap`允许我们在 O(1)时间内按键插入和搜索(查找)数据。因此,使用`HashMap`解决了问题的一半。另一半,即跟踪最近使用的条目和长时间未使用的条目,无法通过`HashMap`完成。 然而,如果我们想象一个提供快速插入、更新和删除的数据结构,那么我们必须考虑双向链表。基本上,如果我们知道双向链表中节点的地址,那么插入、更新和删除可以在 O(1)时间内完成。 这意味着我们可以提供一个实现,它依赖于`HashMap`和双向链表之间的共生关系。基本上,对于 LRU 缓存中的每个条目(键值对),我们可以在`HashMap`中存储条目的键和关联链表节点的地址,而这个节点将存储条目的值。以下图表是对这一陈述的可视化表示: ![11.26:使用 HashMap 和双向链表的 LRU 缓存](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_11.26_B15403.jpg) 图 11.26 - 使用 HashMap 和双向链表的 LRU 缓存 但是双向链表如何帮助我们跟踪最近使用的条目呢?秘密在于以下几点: + 在缓存中插入新条目将导致将相应的节点添加到双向链表的头部(因此,双向链表的头部保存了最近使用的值)。 + 当访问一个条目时,我们将其对应的节点移动到双向链表的头部。 + 当我们需要驱逐一个条目时,我们驱逐双向链表的尾部(因此,双向链表的尾部保存了最近最少使用的值)。 基于这些陈述,我们可以提供以下直接的实现: ```java public final class LRUCache {   private final class Node {     private int key;     private int value;     private Node next;     private Node prev;   }   private final Map<Integer, Node> hashmap;   private Node head;   private Node tail;   // 5 is the maximum size of the cache   private static final int LRU_SIZE = 5;   public LRUCache() {     hashmap = new HashMap<>();   }   public int getEntry(int key) {     Node node = hashmap.get(key);     // if the key already exist then update its usage in cache     if (node != null) {       removeNode(node);       addNode(node);       return node.value;     }     // by convention, data not found is marked as -1     return -1;   }   public void putEntry(int key, int value) {     Node node = hashmap.get(key);     // if the key already exist then update     // the value and move it to top of the cache                      if (node != null) {       node.value = value;       removeNode(node);       addNode(node);     } else {       // this is new key       Node newNode = new Node();       newNode.prev = null;       newNode.next = null;       newNode.value = value;       newNode.key = key;       // if we reached the maximum size of the cache then       // we have to remove the  Least Recently Used       if (hashmap.size() >= LRU_SIZE) {         hashmap.remove(tail.key);         removeNode(tail);         addNode(newNode);       } else {         addNode(newNode);       }       hashmap.put(key, newNode);     }   }   // helper method to add a node to the top of the cache   private void addNode(Node node) {     node.next = head;     node.prev = null;     if (head != null) {       head.prev = node;     }     head = node;     if (tail == null) {       tail = head;     }   }   // helper method to remove a node from the cache   private void removeNode(Node node) {     if (node.prev != null) {       node.prev.next = node.next;     } else {       head = node.next;     }     if (node.next != null) {       node.next.prev = node.prev;     } else {       tail = node.prev;     }   }    } ``` 完整的应用程序名为*LRUCache*。 好了,这是本章的最后一个编码挑战。是时候总结本章了! # 摘要 本章引起了您对涉及链表和映射的最常见问题的注意。在这些问题中,首选涉及单向链表的问题;因此,本章主要关注了这一类编码挑战。 在下一章中,我们将解决与堆栈和队列相关的编码挑战。 # 第十二章:栈和队列 本章涵盖了涉及栈和队列的最受欢迎的面试编码挑战。主要是,您将学习如何从头开始提供栈/队列实现,以及如何通过 Java 的内置实现来解决编码挑战,例如`Stack`类和`Queue`接口实现,特别是`ArrayDeque`。通常,此类别的编码挑战将要求您构建栈/队列,或者要求您使用 Java 的内置实现解决特定问题。根据问题的不同,它可能明确禁止您调用某些内置方法,这将导致您找到一个简单的解决方案。 通过本章结束时,您将深入了解栈和队列,能够利用它们的功能,并且能够识别和编写依赖于栈和队列的解决方案。 在本章中,您将学习以下主题: + 概述栈 + 概述队列 + 编码挑战 让我们首先简要介绍栈的数据结构。 # 技术要求 本章中提供的所有代码文件都可以在 GitHub 上找到,网址为[`github.com/PacktPublishing/The-Complete-Coding-Interview-Guide-in-Java/tree/master/Chapter12`](https://github.com/PacktPublishing/The-Complete-Coding-Interview-Guide-in-Java/tree/master/Chapter12)。 # 概述栈 栈是一种使用**后进先出**(**LIFO**)原则的线性数据结构。想象一堆需要清洗的盘子。您从顶部取出第一个盘子(最后添加的盘子),然后清洗它。然后,您从顶部取出下一个盘子,依此类推。这正是现实生活中的栈(例如,一堆盘子,一堆书,一堆 CD 等)。 因此,从技术上讲,在栈中,元素只能从一端添加(称为**push**操作)和移除(称为**pop**操作)(称为**top**)。 在栈中执行的最常见操作如下: + `push(E e)`: 将元素添加到栈的顶部 + `E pop()`: 移除栈顶的元素 + `E peek()`: 返回(但不移除)栈顶的元素 + `boolean isEmpty()`: 如果栈为空则返回`true` + `int size()`: 返回栈的大小 + `boolean isFull()`: 如果栈已满则返回`true` 与数组不同,栈不以常数时间提供对第 n 个元素的访问。但是,它确实提供了添加和移除元素的常数时间。栈可以基于数组甚至基于链表实现。这里使用的实现是基于数组的,并命名为`MyStack`。该实现的存根如下所示: ```java public final class MyStack<E> {   private static final int DEFAULT_CAPACITY = 10;   private int top;   private E[] stack;   MyStack() {     stack = (E[]) Array.newInstance(              Object[].class.getComponentType(),              DEFAULT_CAPACITY);     top = 0; // the initial size is 0   }   public void push(E e) {}   public E pop() {}   public E peek() {}   public int size() {}   public boolean isEmpty() {}   public boolean isFull() {}   private void ensureCapacity() {} } ``` 将元素推入栈意味着将该元素添加到基础数组的末尾。在推入元素之前,我们必须确保栈不是满的。如果满了,我们可以通过消息/异常来表示这一点,或者我们可以增加其容量,如下所示: ```java // add an element 'e' in the stack public void push(E e) {   // if the stack is full, we double its capacity   if (isFull()) {     ensureCapacity();   }   // adding the element at the top of the stack   stack[top++] = e; } // used internally for doubling the stack capacity private void ensureCapacity() {   int newSize = stack.length * 2;   stack = Arrays.copyOf(stack, newSize); } ``` 如您所见,每当我们达到栈的容量时,我们都会将其大小加倍。从栈中弹出一个元素意味着我们返回最后添加到基础数组中的元素。通过将最后一个索引置空来从基础数组中移除该元素,如下所示: ```java // pop top element from the stack public E pop() {   // if the stack is empty then just throw an exception   if (isEmpty()) {     throw new EmptyStackException();   }   // extract the top element from the stack                   E e = stack[--top];   // avoid memory leaks   stack[top] = null;   return e; } ``` 从栈中查看元素意味着返回最后添加到基础数组中的元素,但不从该数组中移除它: ```java // return but not remove the top element in the stack public E peek() {   // if the stack is empty then just throw an exception   if (isEmpty()) {     throw new EmptyStackException();   }   return stack[top - 1]; } ``` 由于此实现可能代表您在面试中可能遇到的编码挑战,建议您花时间分析其代码。完整的应用程序称为*MyStack*。 # 概述队列 队列是一种使用**先进先出**(**FIFO**)原则的线性数据结构。想象排队购物的人。您还可以想象成蚂蚁在队列中行走。 因此,从技术上讲,元素的移除顺序与它们添加的顺序相同。在队列中,添加到一端的元素称为后端(这个操作称为入队操作),从另一端移除的元素称为前端(这个操作称为出队或轮询操作)。 队列中的常见操作如下: + `enqueue(E e)`: 将元素添加到队列的末尾 + `E dequeue()`: 删除并返回队列前面的元素 + `E peek()`: 返回(但不删除)队列前面的元素 + `boolean isEmpty()`: 如果队列为空则返回`true` + `int size()`: 返回队列的大小 + `boolean isFull()`:如果队列已满则返回`true` 与数组不同,队列不提供以常量时间访问第 n 个元素的功能。但是,它确实提供了添加和删除元素的常量时间。队列可以基于数组实现,甚至可以基于链表或堆栈(堆栈是基于数组或链表构建的)实现。这里使用的实现是基于数组的,并且命名为`MyQueue`。这个实现的存根在这里列出: ```java public final class MyQueue<E> {   private static final int DEFAULT_CAPACITY = 10;   private int front;   private int rear;   private int count;   private int capacity;   private E[] queue;   MyQueue() {     queue = (E[]) Array.newInstance(                 Object[].class.getComponentType(),                 DEFAULT_CAPACITY);   count = 0; // the initial size is 0   front = 0;   rear = -1;   capacity = DEFAULT_CAPACITY;   }   public void enqueue(E e) {}   public E dequeue() {}   public E peek() {}   public int size() {}   public boolean isEmpty() {}   public boolean isFull() {}   private void ensureCapacity() {} } ``` 将元素加入队列意味着将该元素添加到底层数组的末尾。在将元素加入队列之前,我们必须确保队列不是满的。如果满了,我们可以通过消息/异常来表示,或者我们可以增加其容量,如下所示: ```java // add an element 'e' in the queue public void enqueue(E e) {   // if the queue is full, we double its capacity   if (isFull()) {     ensureCapacity();   }   // adding the element in the rear of the queue   rear = (rear + 1) % capacity;   queue[rear] = e;   // update the size of the queue   count++; } // used internally for doubling the queue capacity private void ensureCapacity() {         int newSize = queue.length * 2;   queue = Arrays.copyOf(queue, newSize);   // setting the new capacity   capacity = newSize; } ``` 从队列中出列一个元素意味着从底层数组的开头返回下一个元素。该元素从数组中删除: ```java // remove and return the front element from the queue public E dequeue() {   // if the queue is empty we just throw an exception   if (isEmpty()) {     throw new EmptyStackException();   }   // extract the element from the front   E e = queue[front];   queue[front] = null;   // set the new front   front = (front + 1) % capacity;   // decrease the size of the queue   count--;   return e; } ``` 从队列中窥视一个元素意味着从底层数组的开头返回下一个元素,而不将其从数组中删除: ```java // return but not remove the front element in the queue public E peek() {   // if the queue is empty we just throw an exception   if (isEmpty()) {     throw new EmptyStackException();   }   return queue[front]; } ``` 由于这个实现可以代表你在面试中可能遇到的编码挑战,建议你花时间来分析它的代码。完整的应用程序称为*MyQueue*。 # 编码挑战 在接下来的 11 个编码挑战中,我们将涵盖在过去几年中出现在面试中的涉及栈和队列的最流行问题,这些问题涉及到各种雇佣 Java 开发人员的公司。其中最常见的问题之一,*使用一个数组实现三个栈*,在*第十章**,数组和字符串*中有所涉及。 以下编码挑战的解决方案依赖于 Java 内置的`Stack`和`ArrayDeque`API。所以,让我们开始吧! ## 编码挑战 1 - 反转字符串 **问题**:假设你有一个字符串。使用堆栈将其反转。 **解决方案**:使用堆栈反转字符串可以按以下方式完成: 1. 从左到右循环字符串,并将每个字符推入堆栈。 1. 循环堆栈并逐个弹出字符。每个弹出的字符都放回字符串中。 基于这两个步骤的代码如下: ```java public static String reverse(String str) {   Stack<Character> stack = new Stack();   // push characters of the string into the stack   char[] chars = str.toCharArray();   for (char c : chars) {     stack.push(c);   }   // pop all characters from the stack and   // put them back to the input string   for (int i = 0; i < str.length(); i++) {     chars[i] = stack.pop();   }   // return the string   return new String(chars); } ``` 完整的应用程序称为*StackReverseString*。 ## 编码挑战 2 - 大括号堆栈 **亚马逊**,**谷歌**,**Adobe**,**微软**,**Flipkart** 包含大括号的字符串。编写一小段代码,如果有匹配的大括号对,则返回`true`。如果我们可以找到适当顺序的闭合大括号来匹配开放的大括号,那么我们可以说有一个匹配的对。例如,包含匹配对的字符串如下:{{{}}}{}{{}}。 `false`。其次,如果它们的数量相等,则它们必须按适当的顺序;否则,我们返回`false`。按适当的顺序,我们理解最后打开的大括号是第一个关闭的,倒数第二个是第二个关闭的,依此类推。如果我们依赖于堆栈,那么我们可以详细说明以下算法: 1. 对于给定字符串的每个字符,做出以下决定之一: a. 如果字符是一个开放的大括号,{,那么将其放入堆栈。 b. 如果字符是闭合大括号,},则执行以下操作: i. 检查堆栈顶部,如果是{,则弹出并将其移动到下一个字符。 ii. 如果不是{,则返回`false`。 1. 如果堆栈为空,则返回`true`(我们找到了所有配对);否则返回`false`(堆栈包含不匹配的大括号)。 将这些步骤转化为代码,结果如下: ```java public static boolean bracesMatching(String bracesStr) {   Stack<Character> stackBraces = new Stack<>();   int len = bracesStr.length();   for (int i = 0; i < len; i++) {     switch (bracesStr.charAt(i)) {       case '{':         stackBraces.push(bracesStr.charAt(i));         break;       case '}':         if (stackBraces.isEmpty()) { // we found a mismatch           return false;         }         // for every match we pop the corresponding '{'         stackBraces.pop();         break;       default:         return false;     }   }   return stackBraces.empty(); } ``` 完整的应用程序称为*StackBraces*。通过实现类似的问题,但是对于多种类型的括号(例如,在相同的给定字符串中允许(){}[]),来挑战自己。 ## 编程挑战 3 - 堆叠盘 **亚马逊**,**谷歌**,**Adobe**,**微软**,**Flipkart** `push()`和`pop()`方法将像单个堆栈一样工作。另外,编写一个`popAt(int stackIndex)`方法,它会从堆栈中弹出一个值,如`stackIndex`所示。 **解决方案**:我们知道如何处理单个堆栈,但是如何将多个堆栈链接在一起呢?嗯,既然我们需要*链接*,那么链表怎么样?如果链表中每个节点都包含一个堆栈,那么节点的下一个指针将指向下一个堆栈。以下图表可视化了这个解决方案: ![图 12.1 - 堆栈的链表](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_12.1_B15403.jpg) 图 12.1 - 堆栈的链表 每当当前堆栈容量超过时,我们就创建一个新节点并将其附加到链表中。Java 的内置链表(`LinkedList`)通过`getLast()`方法使我们可以访问最后一个节点。换句话说,通过`LinkedList#getLast()`,我们可以轻松操作当前堆栈(例如,我们可以推送或弹出一个元素)。通过`LinkedList#add()`方法很容易添加一个新的堆栈。基于这些语句,我们可以实现`push()`方法,如下所示: ```java private static final int STACK_SIZE = 3; private final LinkedList<Stack<Integer>> stacks   = new LinkedList<>(); public void push(int value) {   // if there is no stack or the last stack is full   if (stacks.isEmpty() || stacks.getLast().size()       >= STACK_SIZE) {     // create a new stack and push the value into it     Stack<Integer> stack = new Stack<>();     stack.push(value);     // add the new stack into the list of stacks     stacks.add(stack);   } else {     // add the value in the last stack     stacks.getLast().push(value);   } } ``` 如果我们想要弹出一个元素,那么我们必须从最后一个堆栈中这样做,所以`LinkedList#getLast()`在这里非常方便。这里的特殊情况是当我们从最后一个堆栈中弹出最后一个元素时。当这种情况发生时,我们必须删除最后一个堆栈,在这种情况下,倒数第二个(如果有的话)将成为最后一个。以下代码说明了这一点: ```java public Integer pop() {   // find the last stack   Stack<Integer> lastStack = stacks.getLast();   // pop the value from the last stack   int value = lastStack.pop();   // if last stack is empty, remove it from the list of stacks   removeStackIfEmpty();   return value; } private void removeStackIfEmpty() {   if (stacks.getLast().isEmpty()) {       stacks.removeLast();   } } ``` 最后,让我们专注于实现`popAt(int stackIndex)`方法。我们可以通过简单调用`stacks.get(stackIndex).pop()`从`stackIndex`堆栈中弹出。一旦我们弹出一个元素,我们必须移动剩余的元素。下一个堆栈的底部元素将成为由`stackIndex`指向的堆栈的顶部元素,依此类推。如果最后一个堆栈包含单个元素,则移动其他元素将消除最后一个堆栈,并且其前面的堆栈将成为最后一个堆栈。让我们通过代码来看一下: ```java public Integer popAt(int stackIndex) {   // get the value from the correspondind stack   int value = stacks.get(stackIndex).pop();   // pop an element -> must shift the remaining elements           shift(stackIndex);   // if last stack is empty, remove it from the list of stacks   removeStackIfEmpty();   return value; } private void shift(int index) {   for (int i = index; i<stacks.size() - 1; ++i) {     Stack<Integer> currentStack = stacks.get(i);     Stack<Integer> nextStack = stacks.get(i + 1);     currentStack.push(nextStack.remove(0));   } } ``` 完整的应用程序称为*StackOfPlates*。 ## 编程挑战 4 - 股票跨度 **亚马逊**,**谷歌**,**Adobe**,**微软**,**Flipkart** **问题**:假设你已经获得了一个单一股票连续多天的价格数组。股票跨度由前几天(今天)的股票价格小于或等于当前天(今天)的股票价格的天数表示。例如,考虑股票价格覆盖 10 天的情况;即{55, 34, 22, 23, 27, 88, 70, 42, 51, 100}。结果的股票跨度是{1, 1, 1, 2, 3, 6, 1, 1, 2, 10}。注意,对于第一天,股票跨度始终为 1。编写一小段代码,计算给定价格列表的股票跨度。 **解决方案**:我们可以从给定的示例开始,尝试将其可视化,如下所示: ![图 12.2 - 10 天的股票跨度](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_12.2_B15403.jpg) 图 12.2 - 10 天的股票跨度 从前面的图表中,我们可以观察到以下内容: + 对于第一天,跨度始终为 1。 + 对于第 2 天,价格为 34。由于 34 小于前一天(55)的价格,第 2 天的股票跨度也是 1。 + 对于第 3 天,价格为 22。由于 22 小于前一天(34)的价格,第 3 天的股票跨度也是 1。第 7 天和第 8 天也属于同样的情况。 + 对于第 4 天,价格是 23。由于 23 大于前一天的价格(22),但小于第 2 天的价格,所以股票跨度为 2。第 9 天与第 4 天类似。 + 对于第 5 天,价格是 27。由于这个价格大于第 3 天和第 4 天的价格,但小于第 2 天的价格,所以股票跨度为 3。 + 对于第 6 天,价格是 88。这是迄今为止最高的价格,所以股票跨度是 6。 + 对于第 10 天,价格是 100。这是迄今为止最高的价格,所以股票跨度是 10。 注意,我们计算当前天的股票跨度,是当前天的索引与对应于最后一个最大股价的那一天的索引之间的差。在追踪这种情况之后,我们可能会有这样的第一个想法:对于每一天,扫描它之前的所有天,直到股价大于当前天。换句话说,我们使用了蛮力方法。正如我在本书中早些时候提到的,蛮力方法应该在面试中作为最后的手段使用,因为它的性能较差,面试官不会感到印象深刻。在这种情况下,蛮力方法的时间复杂度为 O(n2)。 然而,让我们换个角度来思考。对于每一天,我们想找到一个之前的一天,它的价格比当前天的价格高。换句话说,我们要找到最后一个价格比当前天的价格高的那一天。 在这里,我们应该选择一个后进先出的数据结构,它允许我们按降序推入价格并弹出最后推入的价格。一旦我们做到这一点,我们可以遍历每一天,并将栈顶的价格与当前天的价格进行比较。直到栈顶的价格小于当前天的价格,我们可以从栈中弹出。但是如果栈顶的价格大于当前天的价格,那么我们计算当前天的股票跨度,就是当前天和栈顶价格对应的那一天之间的天数差。如果我们按降序将价格推入栈中,这将起作用 - 最大的价格在栈顶。然而,由于我们可以将股票跨度计算为当前天的索引与对应于最后一个最大股价的那一天的索引之间的差(我们用`i`表示),我们可以简单地将`i`索引存储在栈中;`stackPrices[i]`(我们将价格数组表示为`stackPrices`)将返回第*i*天的股票价格。 这可以通过以下算法实现: 1. 第一天的股票跨度为 1,索引为 0 - 我们将这个索引推入栈中(我们将其表示为`dayStack`;因此,`dayStack.push(0)`)。 1. 我们循环剩余的天数(第 2 天的索引为 1,第 3 天的索引为 2,依此类推)并执行以下操作: a. 当`stockPrices[i] > stockPrices[dayStack.peek()]`并且`!dayStack.empty()`时,我们从栈中弹出(`dayStack.pop()`)。 1. 如果`dayStack.empty()`,那么`i+1`的股票跨度。 1. 如果`stockPrices[i] <= stockPrices[dayStack.peek()]`,那么股票跨度就是`i - dayStack.peek()`。 1. 将当前天的索引`i`推入栈中(`dayStack`)。 让我们看看这个算法如何适用于我们的测试案例: 1. 第一天的股票跨度为 1,索引为 0 - 我们将这个索引推入栈中,`dayStack.push(0)`。 1. 对于第 2 天,`stockPrices[1]=34`,`stockPrices[0]=55`。由于 34 < 55,第 2 天的股票跨度为`i - dayStack.peek()` = 1 - 0 = 1。我们将 1 推入栈中,`dayStack.push(1)`。 1. 对于第三天,`stockPrices[2]`=22,`stockPrices[1]`=34。由于 22 < 34,第 3 天的股票跨度为 2 - 1 = 1。我们将 1 推入栈中,`dayStack.push(2)`。 1. 对于第 4 天,`stockPrices[3]`=23,`stockPrices[2]`=22。由于 23 > 22 并且栈不为空,我们弹出栈顶,所以我们弹出值 2。由于 23 < 34(`stockPrices[1]`),第 4 天的股票跨度为 3 - 1 = 2。我们将 3 推入栈中,`dayStack.push(3)`。 1. 对于第五天,`stockPrices[4]`=27 和 `stockPrices[3]`=23。由于 27 > 23 并且栈不为空,我们弹出栈顶,所以我们弹出值 3。接下来,27 < 34(记住我们在上一步弹出了值 2,所以下一个栈顶的值为 1),第 5 天的股票跨度为 4 - 1 = 3。我们在栈中推入 4,`dayStack.push(4)`。 1. 对于第六天,`stockPrices[5]`=88 和 `stockPrices[4]`=27。由于 88 > 27 并且栈不为空,我们弹出栈顶,所以我们弹出值 4。接下来,88 > 34 并且栈不为空,所以我们弹出值 1。接下来,88 > 55 并且栈不为空,所以我们弹出值 0。接下来,栈为空,第 6 天的股票跨度为 5 + 1 = 6。 好了,我想你已经明白了,现在,挑战自己,继续到第 10 天。目前,我们有足够的信息将这个算法转化为代码: ```java public static int[] stockSpan(int[] stockPrices) {   Stack<Integer> dayStack = new Stack();   int[] spanResult = new int[stockPrices.length];   spanResult[0] = 1; // first day has span 1   dayStack.push(0);   for (int i = 1; i < stockPrices.length; i++) {     // pop until we find a price on stack which is     // greater than the current day's price or there     // are no more days left     while (!dayStack.empty()       && stockPrices[i] > stockPrices[dayStack.peek()]) {       dayStack.pop();     }     // if there is no price greater than the current     // day's price then the stock span is the numbers of days     if (dayStack.empty()) {         spanResult[i] = i + 1;     } else {       // if there is a price greater than the current       // day's price then the stock span is the       // difference between the current day and that day         spanResult[i] = i - dayStack.peek();     }     // push current day onto top of stack      dayStack.push(i);   }   return spanResult; } ``` 完整的应用程序称为 *StockSpan*。 ## 编码挑战 5 – 栈最小值 **亚马逊**,**谷歌**,**Adobe**,**微软**,**Flipkart** `push()`、`pop()` 和 `min()` 方法应在 O(1) 时间内运行。 `push()` 和 `pop()` 在 O(1) 时间内运行。 符合问题约束的解决方案需要一个额外的栈来跟踪最小值。主要是,当推送的值小于当前最小值时,我们将这个值添加到辅助栈(我们将其表示为 `stackOfMin`)和原始栈中。如果从原始栈中弹出的值是 `stackOfMin` 的栈顶,则我们也从 `stackOfMin` 中弹出它。在代码方面,我们有以下内容: ```java public class MyStack extends Stack<Integer> {   Stack<Integer> stackOfMin;   public MyStack() {     stackOfMin = new Stack<>();   }   public Integer push(int value) {     if (value <= min()) {        stackOfMin.push(value);     }     return super.push(value);   }   @Override   public Integer pop() {     int value = super.pop();     if (value == min()) {        stackOfMin.pop();     }     return value;   }   public int min() {    if (stackOfMin.isEmpty()) {       return Integer.MAX_VALUE;     } else {       return stackOfMin.peek();     }   } } ``` 完成!我们的解决方案以 O(1) 复杂度时间运行。完整的应用程序称为 *MinStackConstantTime*。与此相关的一个问题要求您在常数时间和空间内实现相同的功能。这个问题的解决方案施加了几个限制,如下: + `pop()` 方法返回 `void`,以避免返回不正确的值。 + 给定值乘以 2 不应超出 `int` 数据类型的范围。 简而言之,这些限制是由解决方案本身造成的。我们不能使用额外的空间;因此,我们将使用初始值栈来存储最小值。此外,我们需要将给定值乘以 2,因此我们应确保不超出 `int` 范围。为什么我们需要将给定值乘以 2? 让我们来解释一下这个问题!假设我们需要将一个值推入一个具有特定最小值的栈中。如果这个值大于或等于当前最小值,那么我们可以简单地将它推入栈中。但是如果它小于最小值,那么我们推入 2**值-最小值*,这应该小于值本身。然后,我们将当前最小值更新为值。 当我们弹出一个值时,我们必须考虑两个方面。如果弹出的值大于或等于最小值,那么这是之前推送的真实值。否则,弹出的值不是推送的值。真正推送的值存储在最小值中。在我们弹出栈顶(最小值)之后,我们必须恢复先前的最小值。先前的最小值可以通过 2**最小值 - 栈顶* 获得。换句话说,由于当前栈顶是 2**值 - 先前的最小值*,而值是当前最小值,先前的最小值是 2**当前最小值 - 栈顶*。以下代码说明了这个算法: ```java public class MyStack {   private int min;   private final Stack<Integer> stack = new Stack<>();   public void push(int value) {     // we don't allow values that overflow int/2 range     int r = Math.addExact(value, value);     if (stack.empty()) {       stack.push(value);       min = value;     } else if (value > min) {       stack.push(value);     } else {       stack.push(r - min);       min = value;     }   }   // pop() doesn't return the value since this may be a wrong     // value (a value that was not pushed by the client)!   public void pop() {     if (stack.empty()) {       throw new EmptyStackException();     }     int top = stack.peek();     if (top < min) {       min = 2 * min - top;     }     stack.pop();   }   public int min() {     return min;   } } ``` 完整的应用程序称为 *MinStackConstantTimeAndSpace*。 ## 编码挑战 6 – 通过栈实现队列 **谷歌**,**Adobe**,**微软**,**Flipkart** **问题**:通过两个栈设计一个队列。 **解决方案**:为了找到这个问题的合适解决方案,我们必须从队列和栈之间的主要区别开始。我们知道队列按照先进先出的原则工作,而栈按照后进先出的原则工作。接下来,我们必须考虑主要的操作(推入、弹出和查看)并确定它们之间的区别。 它们都以相同的方式推送新元素。当我们将一个元素推入队列时,我们是从一端(队列的后端)推入的。当我们将一个元素推入栈时,我们是从栈的新顶部推入的,这可以被视为与队列的后端相同。 当我们从栈中弹出或查看一个值时,我们是从顶部这样做的。然而,当我们在队列上执行相同的操作时,我们是从前面这样做的。这意味着,当弹出或查看一个元素时,一个反转的栈将充当队列。以下图表说明了这一点: ![图 12.3 - 通过两个栈实现队列](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_12.3_B15403.jpg) 图 12.3 - 通过两个栈实现队列 因此,每个新元素都被推入*enqueue stack*作为新的顶部。当我们需要弹出或查看一个值时,我们使用*dequeue*栈,这是*enqueue stack*的反转版本。请注意,我们不必在每次弹出/查看操作时都反转*enqueue stack*。我们可以让元素停留在*dequeue stack*中,直到我们绝对必须反转元素。换句话说,对于每个弹出/查看操作,我们可以检查*dequeue stack*是否为空。只要*dequeue stack*不为空,我们就不需要反转*enqueue stack*,因为我们至少有一个元素可以弹出/查看。 让我们用代码来看一下: ```java public class MyQueueViaStack<E> {   private final Stack<E> stackEnqueue;   private final Stack<E> stackDequeue;   public MyQueueViaStack() {     stackEnqueue = new Stack<>();     stackDequeue = new Stack<>();   }   public void enqueue(E e) {     stackEnqueue.push(e);   }   public E dequeue() {     reverseStackEnqueue();     return stackDequeue.pop();   }   public E peek() {     reverseStackEnqueue();     return stackDequeue.peek();   }   public int size() {     return stackEnqueue.size() + stackDequeue.size();   }   private void reverseStackEnqueue() {     if (stackDequeue.isEmpty()) {       while (!stackEnqueue.isEmpty()) {         stackDequeue.push(stackEnqueue.pop());       }     }   } } ``` 完整的应用程序称为*QueueViaStack*。 ## 编码挑战 7 - 通过队列实现栈 **Google**,**Adobe**,**Microsoft** **问题**:设计一个通过两个队列实现的栈。 **解决方案**:为了找到这个问题的合适解决方案,我们必须从栈和队列之间的主要区别开始。我们知道栈是后进先出,而队列是先进先出。接下来,我们必须考虑主要操作(推入、弹出和查看)并确定它们之间的区别。 它们都以相同的方式推送新元素。当我们将一个元素推入栈时,我们是从栈的新顶部推入的。当我们将一个元素推入队列时,我们是从一端(队列的后端)推入的。队列的后端就像栈的顶部。 当我们从队列中弹出或查看一个值时,我们是从前面这样做的。然而,当我们在栈上执行相同的操作时,我们是从顶部这样做的。这意味着,当我们从充当栈的队列中弹出或查看一个元素时,我们需要轮询除最后一个元素之外的所有元素。最后一个元素就是我们弹出/查看的元素。以下图表说明了这一点: ![图 12.4 - 通过两个队列实现栈](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_12.4_B15403.jpg) 图 12.4 - 通过两个队列实现栈 正如前面的图表左侧所显示的,将一个元素推入栈和队列是一个简单的操作。前面图表的右侧显示了当我们想要从充当栈的队列中弹出/查看一个元素时会出现问题。主要是,在弹出/查看元素之前,我们必须将队列(在前面的图表中标记为*queue1*)中的元素(*rear*-1 和*front*之间)移动到另一个队列(在前面的图表中标记为*queue2*)。在前面的图表中,右侧,我们从*queue1*中轮询元素 2、5、3 和 1,并将它们添加到*queue2*中。接下来,我们从*queue1*中弹出/查看最后一个元素。如果我们弹出元素 6,那么*queue1*就会保持为空。如果我们查看元素 6,那么*queue1*就会保留这个元素。 现在,剩下的元素都在*queue2*中,所以为了执行另一个操作(推入、查看或弹出),我们有两个选项: + 将*queue2*中剩余的元素移回*queue1*,恢复*queue1*。 + 使用*queue2*就像它是*queue1*一样,这意味着交替使用*queue1*和*queue2*。 在第二个选项中,我们避免了将*queue2*中的元素移回*queue1*的开销,目的是在*queue1*上执行下一个操作。虽然你可以挑战自己来实现第一个选项,但让我们更多地关注第二个选项。 如果我们考虑到我们应该使用的下一个操作的队列是不空的,那么可以交替使用*queue1*和*queue2*。由于我们在这两个队列之间移动元素,其中一个始终为空。因此,当我们查看一个元素时,会出现问题,因为查看操作不会移除元素,因此其中一个队列仍然保留该元素。由于没有一个队列是空的,我们不知道下一个操作应该使用哪个队列。解决方案非常简单:我们弹出最后一个元素,即使是对于查看操作,我们也将其存储为实例变量。随后的查看操作将返回此实例变量。推送操作将在推送给定值之前将此实例变量推回队列,并将此实例变量设置为`null`。弹出操作将检查此实例变量是否为`null`。如果不是`null`,那么这就是要弹出的元素。 让我们看看代码: ```java public class MyStackViaQueue<E> {   private final Queue<E> queue1;   private final Queue<E> queue2;   private E peek;   private int size;   public MyStackViaQueue() {     queue1 = new ArrayDeque<>();     queue2 = new ArrayDeque<>();   }   public void push(E e) {     if (!queue1.isEmpty()) {       if (peek != null) {         queue1.add(peek);       }       queue1.add(e);     } else {       if (peek != null) {         queue2.add(peek);       }       queue2.add(e);     }     size++;     peek = null;   }   public E pop() {     if (size() == 0) {       throw new EmptyStackException();     }     if (peek != null) {       E e = peek;       peek = null;       size--;       return e;     }     E e;     if (!queue1.isEmpty()) {       e = switchQueue(queue1, queue2);     } else {       e = switchQueue(queue2, queue1);     }     size--;     return e;   }   public E peek() {     if (size() == 0) {       throw new EmptyStackException();     }     if (peek == null) {       if (!queue1.isEmpty()) {         peek = switchQueue(queue1, queue2);       } else {         peek = switchQueue(queue2, queue1);       }     }     return peek;   }   public int size() {     return size;   }   private E switchQueue(Queue from, Queue to) {     while (from.size() > 1) {       to.add(from.poll());     }     return (E) from.poll();   } } ``` 完整的应用程序称为*StackViaQueue*。 ## 编码挑战 8 - 最大直方图面积 **亚马逊**,**谷歌**,**Adobe**,**微软**,**Flipkart** **问题**:假设你已经得到了下图中显示的直方图: ![图 12.5 - 直方图,类间隔等于 1](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_12.5_B15403.jpg) 图 12.5 - 直方图,类间隔等于 1 我们将直方图定义为一个矩形条的图表,其中面积与某个变量的频率成比例。条的宽度称为直方图类间隔。例如,前面图像中的直方图的类间隔等于 1。有六个宽度均为 1,高度分别为 4、2、8、6、5 和 3 的条。 假设你已经得到了这些高度作为整数数组(这是问题的输入)。编写一小段代码,使用栈来计算直方图中最大的矩形区域。为了更好地理解这一点,下图突出显示了几个(不是全部)可以形成的矩形: ![图 12.6 - 直方图的矩形](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_12.6_B15403.jpg) 图 12.6 - 直方图的矩形 在前面的图像中,最大的矩形区域(即最大的矩形)是中间的一个,3 x 5 = 15。 **解决方案**:这个问题比起初看起来要困难得多。首先,我们需要分析给定的图像并制定几个声明。例如,非常重要的是要注意,只有当某个条的高度小于或等于该区域的高度时,该条才能成为矩形区域的一部分。此外,对于每个条,我们可以说,所有左侧高于当前条的条都可以与当前条形成一个矩形区域。同样,所有右侧高于当前条的条都可以与当前条形成一个矩形区域。 这意味着每个矩形区域由*左*和*右*边界限定,而(*右 - 左*) ** current_bar*给出了这个区域的值。我们应该计算所有可能的区域,并选择最高的区域作为我们实现的输出。以下图像突出显示了 3 x 5 矩形的左右边界: ![图 12.7 - 左右边界](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_12.7_B15403.jpg) 图 12.7 - 左右边界 请记住,我们必须使用栈来解决这个问题。现在我们有了一些可以引导我们解决问题的声明,是时候把栈引入讨论了。主要是,我们可以使用栈来计算左右边界。 我们从第一个条开始,将其索引(索引 0)推入栈中。我们继续处理剩下的条,并执行以下操作: 1. 重复*步骤 1a*、*1b*和*1c*,直到当前条小于栈顶部并且栈不为空: a.我们弹出栈顶部。 b.我们计算左边界。 c. 我们计算可以在计算的左边界条和当前条之间形成的矩形区域的宽度。 d. 我们计算面积为计算的宽度乘以我们在*步骤 1a*中弹出的条的高度。 e. 如果这个区域比以前的大,那么我们存储这个区域。 1. 将当前条的索引推入栈中。 1. 重复从*步骤 1*直到每个条都被处理。 让我们看看代码方面的情况: ```java public static int maxAreaUsingStack(int[] histogram) {   Stack<Integer> stack = new Stack<>();   int maxArea = 0;   for (int bar = 0; bar <= histogram.length; bar++) {     int barHeight;     if (bar == histogram.length) {       barHeight = 0; // take into account last bar     } else {       barHeight = histogram[bar];     }     while (!stack.empty()           && barHeight < histogram[stack.peek()]) {       // we found a bar smaller than the one from the stack                       int top = stack.pop();       // find left boundary       int left = stack.isEmpty() ? -1 : stack.peek();       // find the width of the rectangular area       int areaRectWidth = bar - left - 1;       // compute area of the current rectangle       int area = areaRectWidth * histogram[top];       maxArea = Integer.max(area, maxArea);     }     // add current bar (index) into the stack     stack.push(bar);   }           return maxArea; } ``` 这段代码的时间复杂度是 O(n)。此外,额外的空间复杂度是 O(n)。完整的应用程序称为*StackHistogramArea*。 ## 编码挑战 9 - 最小数字 **问题**:考虑到你已经得到一个表示*n*位数的字符串。编写一小段代码,删除给定的*k*位数后打印出最小可能的数字。 **解决方案**:让我们假设给定的数字是*n*=4514327 和*k*=4。在这种情况下,删除四位数字后的最小数字是 127。如果*n*=2222222,那么最小数字是 222。 解决方案可以通过`Stack`和以下算法轻松实现: 1. 从左到右迭代给定的数字,逐位数字。 a. 只要给定的*k*大于 0,栈不为空,并且栈中的顶部元素大于当前遍历的数字: i. 从栈中弹出顶部元素。 ii. 将*k*减 1。 b. 将当前数字推入栈中。 1. 当给定的*k*大于 0 时,执行以下操作(处理特殊情况,如 222222): a. 从栈中弹出元素。 b. 将*k*减 1。 在代码方面,我们有以下内容: ```java public static void smallestAfterRemove(String nr, int k) {   int i = 0;   Stack<Character> stack = new Stack<>();   while (i < nr.length()) {     // if the current digit is less than the previous     // digit then discard the previous one     while (k > 0 && !stack.isEmpty()           && stack.peek() > nr.charAt(i)) {       stack.pop();       k--;     }     stack.push(nr.charAt(i));     i++;   }   // cover corner cases such as '2222'   while (k > 0) {     stack.pop();     k--;   }   System.out.println("The number is (as a printed stack; "       + "ignore leading 0s (if any)): " + stack);   } } ``` 完整的应用程序称为*SmallestNumber*。 ## 编码挑战 10 - 岛屿 **亚马逊**,**Adobe** **问题**:考虑到你已经得到一个包含只有 0 和 1 的*m*x*n*矩阵。按照惯例,1 表示陆地,0 表示水。编写一小段代码来计算岛屿的数量。岛屿被定义为由 0 包围的 1 组成的区域。 **解决方案**:让我们想象一个测试案例。以下是一个包含 6 个岛屿的 10x10 矩阵,分别标记为 1、2、3、4、5 和 6: ![图 12.8 - 10x10 矩阵中的岛屿](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_12.8_B15403.jpg) 图 12.8 - 10x10 矩阵中的岛屿 为了找到岛屿,我们必须遍历矩阵。换句话说,我们必须遍历矩阵的每个单元格。由于一个单元格由行(我们将其表示为*r*)和列(我们将其表示为*c*)来表示,我们观察到,从一个单元格(*r, c*),我们可以朝八个方向移动:(*r-*1*, c-*1), (*r-*1*, c*), (*r-*1*, c+*1), (*r, c-*1), (*r, c+*1), (*r+*1*, c-*1), (*r+*1*, c*), 和 (*r+*1*, c+*1)。这意味着从当前单元格(*r, c*),我们可以移动到(*r+ROW*[*k*]*, c+COL*[*k*]),只要`ROW`和`COL`是下面的数组,且 0 ≤ *k* ≤ 7: ```java // top, right, bottom, left and 4 diagonal moves private static final int[] ROW = {-1, -1, -1, 0, 1, 0, 1, 1}; private static final int[] COL = {-1, 1, 0, -1, -1, 1, 0, 1}; ``` 只要我们做到以下几点,移动到一个单元格就是有效的: + 不要从网格上掉下来。 + 踩在代表陆地的单元格上(一个 1 的单元格)。 + 没有在该单元格之前。 为了确保我们不多次访问同一个单元格,我们使用一个布尔矩阵表示为`flagged[][]`。最初,这个矩阵只包含`false`的值,每次我们访问一个单元格(`r`, `c`)时,我们将相应的`flagged[r][c]`翻转为`true`。 以下是代码形式中的前三个要点: ```java private static booleanisValid(int[][] matrix,       int r, int c, boolean[][] flagged) {   return (r >= 0) && (r < flagged.length)     && (c >= 0) && (c < flagged[0].length)     && (matrix[r][c] == 1 && !flagged[r][c]); } ``` 到目前为止,我们知道如何决定从当前单元格移动到另一个单元格(从八个可能的移动中)。此外,我们必须定义一个算法来确定移动模式。我们知道从一个单元格(*r, c*),我们可以在相邻单元格中的八个方向移动。因此,最方便的算法是尝试从当前单元格移动到所有有效的邻居,如下所示: 1. 从一个空队列开始。 1. 移动到一个有效的单元格(*r, c*),将其入队,并标记为已访问 - 起始点应该是单元格(0, 0)。 1. 出队当前单元并解决其周围的八个相邻单元 - 解决单元意味着如果有效则将其入队并标记为已访问。 1. 重复*步骤 3*直到队列为空。当队列为空时,这意味着我们找到了一个岛屿。 1. 重复从*步骤 2*直到没有更多有效单元格。 在代码方面,我们有以下内容: ```java private static class Cell {   int r, c;   public Cell(int r, int c) {     this.r = r;     this.c = c;   } } // there are 8 possible movements from a cell     private static final int POSSIBLE_MOVEMENTS = 8; // top, right, bottom, left and 4 diagonal moves private static final int[] ROW = {-1, -1, -1, 0, 1, 0, 1, 1}; private static final int[] COL = {-1, 1, 0, -1, -1, 1, 0, 1}; public static int islands(int[][] matrix) {   int m = matrix.length;   int n = matrix[0].length;   // stores if a cell is flagged or not   boolean[][] flagged = new boolean[m][n];   int island = 0;   for (int i = 0; i < m; i++) {     for (int j = 0; j < n; j++) {       if (matrix[i][j] == 1 && !flagged[i][j]) {         resolve(matrix, flagged, i, j);         island++;       }     }   }   return island; } private static void resolve(int[][] matrix,         boolean[][] flagged, int i, int j) {   Queue<Cell> queue = new ArrayDeque<>();   queue.add(new Cell(i, j));   // flag source node   flagged[i][j] = true;   while (!queue.isEmpty()) {     int r = queue.peek().r;     int c = queue.peek().c;     queue.poll();     // check for all 8 possible movements from current     // cell and enqueue each valid movement     for (int k = 0; k < POSSIBLE_MOVEMENTS; k++) {       // skip this cell if the location is invalid       if (isValid(matrix, r + ROW[k], c + COL[k], flagged)) {         flagged[r + ROW[k]][c + COL[k]] = true;         queue.add(new Cell(r + ROW[k], c + COL[k]));       }     }   } } ``` 完整的应用程序称为*QueueIslands*。 ## 编码挑战 11-最短路径 **亚马逊**,**谷歌**,**Adobe** **问题**:假设给定一个只包含 0 和 1 的矩阵*m* x *n*。按照惯例,1 表示安全土地,而 0 表示不安全的土地。更准确地说,0 表示不应该被激活的传感器。此外,所有八个相邻的单元格都可以激活传感器。编写一小段代码,计算从第一列的任何单元格到最后一列的任何单元格的最短路径。您只能一次移动一步;向左、向右、向上或向下。结果路径(如果存在)应只包含值为 1 的单元格。 **解决方案**:让我们想象一个测试案例。以下是一个 10 x 10 的矩阵。 在下图的左侧,您可以看到给定的矩阵。请注意,值为 0 表示不应该被激活的传感器。在右侧,您可以看到应用程序使用的矩阵和可能的解决方案。这个矩阵是通过扩展传感器的覆盖区域从给定的矩阵中获得的。请记住,传感器的八个相邻单元格也可以激活传感器。解决方案从第一列(单元格(4,0))开始,以最后一列(单元格(9,9))结束,并包含 15 个步骤(从 0 到 14)。您可以在下图中看到这些步骤: ![图 12.9 - 给定矩阵(左侧)和解析矩阵(右侧)](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_12.9_B15403.jpg) 图 12.9 - 给定矩阵(左侧)和解析矩阵(右侧) 从坐标(*r,c*)的安全单元格,我们可以朝四个安全方向移动:(*r*-1*,c*),(*r,c*-1),(*r*+1*,c*)和(*r,c*+1)。如果我们将可能的移动视为方向(边)并将单元格视为顶点,则可以在图的上下文中可视化这个问题。边是可能的移动,而顶点是我们可以到达的可能单元格。每次移动都保持从当前单元格到起始单元格的距离(起始单元格是第一列的单元格)。对于每次移动,距离增加 1。因此,在图的上下文中,问题可以简化为在图中找到最短路径。因此,我们可以使用**广度优先搜索(BFS)**方法来解决这个问题。在*第十三章**,树和图*中,您已经了解了 BFS 算法的描述,并且另一个问题也是以与此处解决的问题相同的方式解决的- *国际象棋骑士*问题。 现在,根据前面问题提供的经验,我们可以详细说明这个算法: 1. 从一个空队列开始。 1. 将第一列的所有安全单元格入队,并将它们的距离设置为 0(这里,0 表示每个单元格到自身的距离)。此外,这些单元格被标记为已访问或标记。 1. 只要队列不为空,执行以下操作: a. 弹出表示队列顶部的单元格。 b. 如果弹出的单元格是目的地单元格(即在最后一列),则简单地返回其距离(从目的地单元格到第一列源单元格的距离)。 c. 如果弹出的单元格不是目的地,则对该单元格的四个相邻单元格中的每一个,将每个有效单元格(安全且未访问)入队到队列中,并标记为已访问。 d. 如果我们处理了队列中的所有单元格但没有到达目的地,则没有解决方案。返回-1。 由于我们依赖 BFS 算法,我们知道所有最短路径为 1 的单元格首先被访问。接下来,被访问的单元格是具有最短路径为 1+1=2 等的相邻单元格。因此,具有最短路径的单元格等于其父级的最短路径+1。这意味着当我们第一次遍历目标单元格时,它给出了我们的最终结果。这就是最短路径。让我们看看代码中最相关的部分: ```java private static int findShortestPath(int[][] board) {   // stores if cell is visited or not   boolean[][] visited = new boolean[M][N];   Queue<Cell> queue = new ArrayDeque<>();   // process every cell of first column   for (int r1 = 0; r1 < M; r1++) {     // if the cell is safe, mark it as visited and     // enqueue it by assigning it distance as 0 from itself     if (board[r1][0] == 1) {       queue.add(new Cell(r1, 0, 0));       visited[r1][0] = true;     }   }   while (!queue.isEmpty()) {     // pop the front node from queue and process it     int rIdx = queue.peek().r;     int cIdx = queue.peek().c;     int dist = queue.peek().distance;     queue.poll();     // if destination is found then return minimum distance     if (cIdx == N - 1) {       return (dist + 1);     }     // check for all 4 possible movements from     // current cell and enqueue each valid movement     for (int k = 0; k < 4; k++) {       if (isValid(rIdx + ROW_4[k], cIdx + COL_4[k])             && isSafe(board, visited, rIdx + ROW_4[k],                 cIdx + COL_4[k])) {         // mark it as visited and push it into         // queue with (+1) distance         visited[rIdx + ROW_4[k]][cIdx + COL_4[k]] = true;         queue.add(new Cell(rIdx + ROW_4[k],           cIdx + COL_4[k], dist + 1));       }     }   }   return -1; } ``` 完整的应用程序称为*ShortestSafeRoute*。 # 中缀、后缀和前缀表达式 前缀、后缀和中缀表达式在当今并不是一个非常常见的面试话题,但它可以被认为是任何开发人员至少应该涵盖一次的一个话题。以下是一个快速概述: + **前缀表达式**:这是一种表示法(代数表达式),用于编写算术表达式,其中操作数在其运算符之后列出。 + **后缀表达式**:这是一种表示法(代数表达式),用于编写算术表达式,其中操作数在其运算符之前列出。 + **中缀表达式**:这是一种表示法(代数表达式),通常用于算术公式或语句中,其中运算符写在其操作数之间。 如果我们有三个运算符 a、b 和 c,我们可以写出下图中显示的表达式: ![图 12.10 - 中缀、后缀和前缀](https://github.com/OpenDocCN/freelearn-java-zh/raw/master/docs/cpl-code-itw-gd-java/img/Figure_12.10_B15403.jpg) 图 12.10 - 中缀、后缀和前缀 最常见的问题涉及评估前缀和后缀表达式以及在前缀、中缀和后缀表达式之间进行转换。所有这些问题都有依赖于堆栈(或二叉树)的解决方案,并且在任何专门致力于基本算法的严肃书籍中都有涵盖。花些时间,收集一些关于这个主题的资源,以便熟悉它。由于这个主题在专门的书籍中得到了广泛的涵盖,并且在面试中并不常见,我们将不在这里进行涵盖。 # 摘要 本章涵盖了任何准备进行 Java 开发人员技术面试的候选人必须了解的堆栈和队列问题。堆栈和队列出现在许多实际应用中,因此掌握它们是面试官将测试您的顶级技能之一。 在下一章《树、Trie 和图形》中,您将看到堆栈和队列经常用于解决涉及树和图形的问题,这意味着它们也值得您的关注。
// ignore_for_file: public_member_api_docs, sort_constructors_first import 'dart:convert'; class VideoDataModel { String? url; String? title; String? siteName; String? description; String? mediaType; String? contentType; List<dynamic>? images; List<dynamic>? videos; List<dynamic>? favicons; String? charset; String? responseTime; VideoDataModel({ this.url, this.title, this.siteName, this.description, this.mediaType, this.contentType, this.images, this.videos, this.favicons, this.charset, this.responseTime, }); Map<String, dynamic> toMap() { return <String, dynamic>{ 'url': url, 'title': title, 'siteName': siteName, 'description': description, 'mediaType': mediaType, 'contentType': contentType, 'images': images, 'videos': videos, 'favicons': favicons, 'charset': charset, 'responseTime': responseTime, }; } factory VideoDataModel.fromMap(Map<String, dynamic> map) { return VideoDataModel( url: map['url'] != null ? map['url'] as String : null, title: map['title'] != null ? map['title'] as String : null, siteName: map['siteName'] != null ? map['siteName'] as String : null, description: map['description'] != null ? map['description'] as String : null, mediaType: map['mediaType'] != null ? map['mediaType'] as String : null, contentType: map['contentType'] != null ? map['contentType'] as String : null, images: map['images'] != null ? List<dynamic>.from((map['images'] as List<dynamic>)) : null, videos: map['videos'] != null ? List<dynamic>.from((map['videos'] as List<dynamic>)) : null, favicons: map['favicons'] != null ? List<dynamic>.from((map['favicons'] as List<dynamic>)) : null, charset: map['charset'] != null ? map['charset'] as String : null, responseTime: map['responseTime'] != null ? map['responseTime'] as String : null, ); } String toJson() => json.encode(toMap()); factory VideoDataModel.fromJson(String source) => VideoDataModel.fromMap(json.decode(source) as Map<String, dynamic>); }
@c -*-texinfo-*- @c @c GNU libavl - library for manipulation of binary trees. @c Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004 Free Software @c Foundation, Inc. @c Permission is granted to copy, distribute and/or modify this document @c under the terms of the GNU Free Documentation License, Version 1.2 @c or any later version published by the Free Software Foundation; @c with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. @c A copy of the license is included in the section entitled "GNU @c Free Documentation License". @node Search Algorithms, Binary Search Trees, The Table ADT, Top @chapter Search Algorithms In @libavl{}, we are primarily concerned with binary search trees and balanced binary trees. If you're already familiar with these concepts, then you can move right into the code, starting from the next chapter. But if you're not, then a little motivation and an explanation of exactly what a binary search tree is can't hurt. That's the goal of this chapter. More particularly, this chapter concerns itself with algorithms for searching. Searching is one of the core problems in organizing a table. As it will turn out, arranging a table for fast searching also facilitates some other table features. @menu * Sequential Search:: * Sequential Search with Sentinel:: * Sequential Search of Ordered Array:: * Sequential Search of Ordered Array with Sentinel:: * Binary Search of Ordered Array:: * Binary Search Tree in Array:: * Dynamic Lists:: @end menu @node Sequential Search, Sequential Search with Sentinel, Search Algorithms, Search Algorithms @section Sequential Search Suppose that you have a bunch of things (books, magazines, CDs, @dots{}) in a pile, and you're looking for one of them. You'd probably start by looking at the item at the top of the pile to check whether it was the one you were looking for. If it wasn't, you'd check the next item down the pile, and so on, until you either found the one you wanted or ran out of items. In computer science terminology, this is a @gloss{sequential search}. It is easy to implement sequential search for an array or a linked list. If, for the moment, we limit ourselves to items of type |int|, we can write a function to sequentially search an array like this: @<Sequentially search an array of |int|s@> = /* Returns the smallest |i| such that |array[i] == key|, @ or |-1| if |key| is not in |array[]|. |array[]| must be an array of |n int|s. */ int @ seq_search (int array[], int n, int key) @ { int i; for (i = 0; i < n; i++) if (array[i] == key) return i; return -1; } @ We can hardly hope to improve on the data requirements, space, or complexity of simple sequential search, as they're about as good as we can want. But the speed of sequential search leaves something to be desired. The next section describes a simple modification of the sequential search algorithm that can sometimes lead to big improvements in performance. @references @bibref{Knuth 1998b}, algorithm 6.1S; @bibref{Kernighan 1976}, section 8.2; @bibref{Cormen 1990}, section 11.2; @bibref{Bentley 2000}, sections 9.2 and 13.2, appendix 1. @exercise Write a simple test framework for |seq_search()|. It should read sample data from |stdin| and collect them into an array, then search for each item in the array in turn and compare the results to those expected, reporting any discrepancies on |stdout| and exiting with an appropriate return value. You need not allow for the possibility of duplicate input values and may limit the maximum number of input values. @answer The following program can be improved in many ways. However, we will implement a much better testing framework later, so this is fine for now. @(seq-test.c@> = @<Program License@> #include <stdio.h> #define MAX_INPUT 1024 @<Sequentially search an array of |int|s@> int @ main (void) @ { int array[MAX_INPUT]; int n, i; for (n = 0; n < MAX_INPUT; n++) if (scanf ("%d", &array[n]) != 1) break; for (i = 0; i < n; i++) @ {@- int result = seq_search (array, n, array[i]); if (result != i) printf ("seq_search() returned %d looking for %d - expected %d\n", result, array[i], i); }@+ return 0; } @ @end exercise @node Sequential Search with Sentinel, Sequential Search of Ordered Array, Sequential Search, Search Algorithms @section Sequential Search with Sentinel Try to think of some ways to improve the speed of sequential search. It should be clear that, to speed up a program, it pays to concentrate on the parts that use the most time to begin with. In this case, it's the loop. Consider what happens each time through the loop: @enumerate 1 @item The loop counter |i| is incremented and compared against |n|. @item |array[i]| is compared against |key|. @end enumerate If we could somehow eliminate one of these comparisons, the loop might be a lot faster. So, let's try@dots{} why do we need step 1? It's because, otherwise, we might run off the end of |array[]|, causing undefined behavior, which is in turn because we aren't sure that |key| is in |array[]|. If we knew that |key| was in |array[]|, then we could skip step 1. But, hey!@: we @emph{can} ensure that the item we're looking for is in the array. How? By putting a copy of it at the end of the array. This copy is called a @gloss{sentinel}, and the search technique as a whole is called @gloss{sequential search with sentinel}. Here's the code: @<Sequentially search an array of |int|s using a sentinel@> = /* Returns the smallest |i| such that |array[i] == key|, @ or |-1| if |key| is not in |array[]|. |array[]| must be an modifiable array of |n int|s @ with room for a |(n + 1)|th element. */ int @ seq_sentinel_search (int array[], int n, int key) @ { int *p; array[n] = key; for (p = array; *p != key; p++) /* Nothing to do. */; return p - array < n ? p - array : -1; } @ Notice how the code above uses a pointer, |int *p|, rather than a counter |i| as in @<Sequentially search an array of |int|s@> earlier. For the most part, this is simply a style preference: for iterating through an array, C programmers usually prefer pointers to array indexes. Under older compilers, code using pointers often compiled into faster code as well, but modern C compilers usually produce the same code whether pointers or indexes are used. The |return| statement in this function uses two somewhat advanced features of C: the conditional or ``ternary'' operator |?:| and pointer arithmetic. The former is a bit like an expression form of an |if| statement. The expression |a ? b : c| first evaluates |a|. Then, if @w{|a != 0|}, |b| is evaluated and the expression takes that value. Otherwise, |a == 0|, |c| is evaluated, and the result is the expression's value. Pointer arithmetic is used in two ways here. First, the expression |p++| acts to advance |p| to point to the next |int| in |array|. This is analogous to the way that |i++| would increase the value of an integer or floating point variable |i| by one. Second, the expression |p - array| results in the ``difference'' between |p| and |array|, i.e., the number of |int| elements between the locations to which they point. For more information on these topics, please consult a good C reference, such as @bibref{Kernighan 1988}. Searching with a sentinel requires that the array be modifiable and large enough to hold an extra element. Sometimes these are inherently problematic---the array may not be modifiable or it might be too small---and sometimes they are problems because of external circumstances. For instance, a program with more than one concurrent @gloss{thread} cannot modify a shared array for sentinel search without expensive locking. Sequential sentinel search is an improvement on ordinary sequential search, but as it turns out there's still room for improvement---especially in the runtime for unsuccessful searches, which still always take |n| comparisons. In the next section, we'll see one technique that can reduce the time required for unsuccessful searches, at the cost of longer runtime for successful searches. @references @bibref{Knuth 1998b}, algorithm 6.1Q; @bibref{Cormen 1990}, section 11.2; @bibref{Bentley 2000}, section 9.2. @node Sequential Search of Ordered Array, Sequential Search of Ordered Array with Sentinel, Sequential Search with Sentinel, Search Algorithms @section Sequential Search of Ordered Array Let's jump back to the pile-of-things analogy from the beginning of this chapter (@pxref{Sequential Search}). This time, suppose that instead of being in random order, the pile you're searching through is ordered on the property that you're examining; e.g., magazines sorted by publication date, if you're looking for, say, the July 1988 issue. Think about how this would simplify searching through the pile. Now you can sometimes tell that the magazine you're looking for isn't in the pile before you get to the bottom, because it's not between the magazines that it otherwise would be. On the other hand, you still might have to go through the entire pile if the magazine you're looking for is newer than the newest magazine in the pile (or older than the oldest, depending on the ordering that you chose). Back in the world of computers, we can apply the same idea to searching a sorted array: @<Sequentially search a sorted array of |int|s@> = /* Returns the smallest |i| such that |array[i] == key|, @ or |-1| if |key| is not in |array[]|. |array[]| must be an array of |n| |int|s sorted in ascending order. */ int @ seq_sorted_search (int array[], int n, int key) @ { int i; for (i = 0; i < n; i++) if (key <= array[i]) return key == array[i] ? i : -1; return -1; } @ At first it might be a little tricky to see exactly how |seq_sorted_search()| works, so we'll work through a few examples. Suppose that |array[]| has the four elements |{3, 5, 6, 8}|, so that |n| is 4. If |key| is 6, then the first time through the loop the |if| condition is |6 <= 3|, or false, so the loop repeats with |i == 1|. The second time through the loop we again have a false condition, |6 <= 5|, and the loop repeats again. The third time the |if| condition, |6 <= 6|, is true, so control passes to the |if| statement's dependent |return|. This |return| verifies that |6 == 6| and returns |i|, or |2|, as the function's value. On the other hand, suppose |key| is 4, a value not in |array[]|. For the first iteration, when |i| is 0, the |if| condition, |4 <= 3|, is false, but in the second iteration we have |4 <= 5|, which is true. However, this time |key == array[i]| is |4 == 5|, or false, so |-1| is returned. @references @bibref{Sedgewick 1998}, program 12.4. @node Sequential Search of Ordered Array with Sentinel, Binary Search of Ordered Array, Sequential Search of Ordered Array, Search Algorithms @section Sequential Search of Ordered Array with Sentinel When we implemented sequential search in a sorted array, we lost the benefits of having a sentinel. But we can reintroduce a sentinel in the same way we did before, and obtain some of the same benefits. It's pretty clear how to proceed: @<Sequentially search a sorted array of |int|s using a sentinel@> = /* Returns the smallest |i| such that |array[i] == key|, @ or |-1| if |key| is not in |array[]|. |array[]| must be an modifiable array of |n int|s, @ sorted in ascending order, with room for a |(n + 1)|th element at the end. */ int @ seq_sorted_sentinel_search (int array[], int n, int key) @ { int *p; array[n] = key; for (p = array; *p < key; p++) /* Nothing to do. */; return p - array < n && *p == key ? p - array : -1; } @ With a bit of additional cleverness we can eliminate one objection to this sentinel approach. Suppose that instead of using the value being searched for as the sentinel value, we used the maximum possible value for the type in question. If we did this, then we could use almost the same code for searching the array. The advantage of this approach is that there would be no need to modify the array in order to search for different values, because the sentinel is the same value for all searches. This eliminates the potential problem of searching an array in multiple contexts, due to nested searches, threads, or signals, for instance. (In the code below, we will still put the sentinel into the array, because our generic test program won't know to put it in for us in advance, but in real-world code we could avoid the assignment.) We can easily write code for implementation of this technique: @<Sequentially search a sorted array of |int|s using a sentinel (2)@> = /* Returns the smallest |i| such that |array[i] == key|, @ or |-1| if |key| is not in |array[]|. |array[]| must be an array of |n int|s, @ sorted in ascending order, with room for an |(n + 1)|th element to set to |INT_MAX|. */ int @ seq_sorted_sentinel_search_2 (int array[], int n, int key) @ { int *p; array[n] = INT_MAX; for (p = array; *p < key; p++) /* Nothing to do. */; return p - array < n && *p == key ? p - array : -1; } @ @exercise When can't the largest possible value for the type be used as a sentinel? @answer Some types don't have a largest possible value; e.g., arbitrary-length strings. @end exercise @node Binary Search of Ordered Array, Binary Search Tree in Array, Sequential Search of Ordered Array with Sentinel, Search Algorithms @section Binary Search of Ordered Array At this point we've squeezed just about all the performance we can out of sequential search in portable C. For an algorithm that searches faster than our final refinement of sequential search, we'll have to reconsider our entire approach. What's the fundamental idea behind sequential search? It's that we examine array elements in order. That's a fundamental limitation: if we're looking for an element in the middle of the array, we have to examine every element that comes before it. If a search algorithm is going to be faster than sequential search, it will have to look at fewer elements. One way to look at search algorithms based on repeated comparisons is to consider what we learn about the array's content at each step. Suppose that |array[]| has |n| elements in sorted order, without duplicates, that |array[j]| contains |key|, and that we are trying to learn the value |j|. In sequential search, we learn only a little about the data set from each comparison with |array[i]|: either |key == array[i]| so that |i == j|, or |key != array[i]| so that |i != j| and therefore |j > i|. As a result, we eliminate only one possibility at each step. Suppose that we haven't made any comparisons yet, so that we know nothing about the contents of |array[]|. If we compare |key| to |array[i]| for arbitrary |i| such that |0 @<= i < n|, what do we learn? There are three possibilities: @itemize @bullet @item |key < array[i]|: Now we know that |key < array[i] < array[i + 1] < | @math{@cdots{}} | < |@w{|array[n - 1]|.}@footnote{This sort of notation means very different things in C and mathematics. In mathematics, writing |a < b < c| asserts both of the relations |a < b| and |b < c|, whereas in C, it expresses the evaluation of |a < b|, then the comparison of the 0 or 1 result to the value of |c|. In mathematics this notation is invaluable, but in C it is rarely meaningful. As a result, this book uses this notation only in the mathematical sense.} Therefore, |0 @<= j < i|. @item |key == array[i]|: We're done: |j == i|. @item |key > array[i]|: Now we know that |key > array[i] > array[i - 1] > | @math{@cdots{}} | > array[0]|. Therefore, |i < j < n|. @end itemize So, after one step, if we're not done, we know that |j > i| or that |j < i|. If we're equally likely to be looking for each element in |array[]|, then the best choice of |i| is |n / 2|: for that value, we eliminate about half of the possibilities either way. (If |n| is odd, we'll round down.) After the first step, we're back to essentially the same situation: we know that |key| is in |array[j]| for some |j| in a range of about |n / 2|. So we can repeat the same process. Eventually, we will either find |key| and thus |j|, or we will eliminate all the possibilities. Let's try an example. For simplicity, let |array[]| contain the values 100 through 114 in numerical order, so that |array[i]| is |100 + i| and |n| is |15|. Suppose further that |key| is 110. The steps that we'd go through to find |j| are described below. At each step, the facts are listed: the known range that |j| can take, the selected value of |i|, the results of comparing |key| to |array[i]|, and what was learned from the comparison. @enumerate @item |0 @<= j @<= 14|: |i| becomes |(0 + 14) / 2 @= 7|. |110 > array[i] @= 107|, so now we know that |j > 7|. @item |8 @<= j @<= 14|: |i| becomes |(8 + 14) / 2 @= 11|. |110 < array[i] @= 111|, so now we know that @w{|j < 11|}. @item |8 @<= j @<= 10|: |i| becomes |(8 + 10) / 2 @= 9|. |110 > array[i] @= 109|, so now we know that |j > 9|. @item |10 @<= j @<= 10|: |i| becomes |(10 + 10) / 2 @= 10|. |110 @= array[i] @= 110|, so we're done and @w{|i @= j @= 10|}. @end enumerate In case you hadn't yet figured it out, this technique is called @gloss{binary search}. We can make an initial C implementation pretty easily: @<Binary search of ordered array@> = /* Returns the offset within |array[]| of an element equal to |key|, @ or |-1| if |key| is not in |array[]|. |array[]| must be an array of |n| |int|s sorted in ascending order. */ int @ binary_search (int array[], int n, int key) @ { int min = 0; int max = n - 1; while (max >= min) @ {@- int i = (min + max) / 2; if (key < array[i]) @ max = i - 1; else if (key > array[i]) @ min = i + 1; else @ return i; }@+ return -1; } @ The maximum number of comparisons for a binary search in an array of |n| elements is about @tex $\log_2n$, @end tex @ifnottex log2(n), @end ifnottex as opposed to a maximum of |n| comparisons for sequential search. For moderate to large values of |n|, this is a lot better. On the other hand, for small values of |n|, binary search may actually be slower because it is more complicated than sequential search. We also have to put our array in sorted order before we can use binary search. Efficiently sorting an |n|-element array takes time proportional to @tex $n\log_2n$ @end tex @ifnottex n * log2(n) @end ifnottex for large |n|. So binary search is preferred if |n| is large enough (see the answer to @value{benchmarkbrief} for one typical value) and if we are going to do enough searches to justify the cost of the initial sort. Further small refinements are possible on binary search of an ordered array. Try some of the exercises below for more information. @c FIXME: exercise: assembly instructions for linear search @references @bibref{Knuth 1998b}, algorithm 6.2.1B; @bibref{Kernighan 1988}, section 3.3; @bibref{Bentley 2000}, chapters 4 and 5, section 9.3, appendix 1; @bibref{Sedgewick 1998}, program 12.6. @exercise Function |binary_search()| above uses three local variables: |min| and |max| for the ends of the remaining search range and |i| for its midpoint. Write and test a binary search function that uses only two variables: |i| for the midpoint as before and |m| representing the width of the range on either side of |i|. You may require the existence of a dummy element just before the beginning of the array. Be sure, if so, to specify what its value should be. @answer Knuth's name for this procedure is ``uniform binary search.'' The code below is an almost-literal implementation of his Algorithm U. The fact that Knuth's arrays are 1-based, but C arrays are 0-based, accounts for most of the differences. The code below uses |for (;;)| to assemble an ``infinite'' loop, a common C idiom. @<Uniform binary search of ordered array@> = /* Returns the offset within |array[]| of an element equal to |key|, @ or |-1| if |key| is not in |array[]|. |array[]| must be an array of |n| |int|s sorted in ascending order, @ with |array[-1]| modifiable. */ int @ uniform_binary_search (int array[], int n, int key) @ { int i = (n + 1) / 2 - 1; int m = n / 2; array[-1] = INT_MIN; for (;;) @ {@- if (key < array[i]) @ {@- if (m == 0) return -1; i -= (m + 1) / 2; m /= 2; }@+ else if (key > array[i]) @ {@- if (m == 0) return -1; i += (m + 1) / 2; m /= 2; }@+ else @ return i >= 0 ? i : -1; }@+ } @ @references @bibref{Knuth 1998b}, section 6.2.1, Algorithm U. @end exercise @exercise The standard C library provides a function, |bsearch()|, for searching ordered arrays. Commonly, |bsearch()| is implemented as a binary search, though ANSI C does not require it. Do the following: @enumerate a @item Write a function compatible with the interface for |binary_search()| that uses |bsearch()| ``under the hood.'' You'll also have to write an additional callback function for use by |bsearch()|. @item Write and test your own version of |bsearch()|, implementing it using a binary search. (Use a different name to avoid conflicts with the C library.) @end enumerate @answer a This actually uses |blp_bsearch()|, implemented in part (b) below, in order to allow that function to be tested. You can replace the reference to |blp_bsearch()| by |bsearch()| without problem. @<Binary search using |bsearch()|@> = @<blp's implementation of |bsearch()|@> /* Compares the |int|s pointed to by |pa| and |pb| and returns positive if |*pa > *pb|, negative if |*pa < *pb|, or zero if |*pa == *pb|. */ static int @ compare_ints (const void *pa, const void *pb) @ { const int *a = pa; const int *b = pb; if (*a > *b) @ return 1; else if (*a < *b) @ return -1; else @ return 0; } /* Returns the offset within |array[]| of an element equal to |key|, @ or |-1| if |key| is not in |array[]|. |array[]| must be an array of |n| |int|s sorted in ascending order. */ static int @ binary_search_bsearch (int array[], int n, int key) @ { int *p = blp_bsearch (&key, array, n, sizeof *array, compare_ints); return p != NULL ? p - array : -1; } @ @answer b This function is named using the author of this book's initials. Note that the implementation below assumes that |count|, a |size_t|, won't exceed the range of an |int|. Some systems provide a type called @b{ssize_t} for this purpose, but we won't assume that here. (|long| is perhaps a better choice than |int|.) @<blp's implementation of |bsearch()|@> = /* Plug-compatible with standard C library |bsearch()|. */ static void *@ blp_bsearch (const void *key, const void *array, size_t count, size_t size, int (*compare) (const void *, const void *)) @ { int min = 0; int max = count; while (max >= min) @ {@- int i = (min + max) / 2; void *item = ((char *) array) + size * i; int cmp = compare (key, item); if (cmp < 0) @ max = i - 1; else if (cmp > 0) @ min = i + 1; else @ return item; }@+ return NULL; } @ @end exercise @exercise An earlier exercise presented a simple test framework for |seq_search()|, but now we have more search functions. Write a test framework that will handle all of them presented so far. Add code for timing successful and unsuccessful searches. Let the user specify, on the command line, the algorithm to use, the size of the array to search, and the number of search iterations to run. @answer Here's an outline of the entire program: @(srch-test.c@> = @<Program License@> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <time.h> @<Search functions@> @<Array of search functions@> @<Timer functions@> @<Search test functions@> @<Search test main program@> @ We need to include all the search functions we're going to use: @<Search functions@> = @<Sequentially search an array of |int|s@> @<Sequentially search an array of |int|s using a sentinel@> @<Sequentially search a sorted array of |int|s@> @<Sequentially search a sorted array of |int|s using a sentinel@> @<Sequentially search a sorted array of |int|s using a sentinel (2)@> @<Binary search of ordered array@> @<Uniform binary search of ordered array@> @<Binary search using |bsearch()|@> @<Cheating search@> @ We need to make a list of the search functions. We start by defining the array's element type: @<Array of search functions@> = /* Description of a search function. */ struct search_func @ {@- const char *name; int (*search) (int array[], int n, int key); };@+ @ Then we define the list as an array: @<Array of search functions@> += /* Array of all the search functions we know. */ struct search_func search_func_tab[] = @ {@- {"seq_search()", seq_search}, {"seq_sentinel_search()", seq_sentinel_search}, {"seq_sorted_search()", seq_sorted_search}, {"seq_sorted_sentinel_search()", seq_sorted_sentinel_search}, {"seq_sorted_sentinel_search_2()", seq_sorted_sentinel_search_2}, {"binary_search()", binary_search}, {"uniform_binary_search()", uniform_binary_search}, {"binary_search_bsearch()", binary_search_bsearch}, {"cheat_search()", cheat_search}, };@+ /* Number of search functions. */ const size_t n_search_func = sizeof search_func_tab / sizeof *search_func_tab; @ We've added previously unseen function |cheat_search()| to the array. This is a function that ``cheats'' on the search because it knows that we are only going to search in a array such that |array[i] == i|. The purpose of |cheat_search()| is to allow us to find out how much of the search time is overhead imposed by the framework and the function calls and how much is actual search time. Here's |cheat_search()|: @<Cheating search@> = /* Cheating search function that knows that |array[i] == i|. |n| must be the array size and |key| the item to search for. |array[]| is not used. Returns the index in |array[]| where |key| is found, @ or |-1| if |key| is not in |array[]|. */ int @ cheat_search (int array[], int n, int key) @ { return key >= 0 && key < n ? key : -1; } @ We're going to need some functions for timing operations. First, a function to ``start'' a timer: @<Timer functions@> = /* ``Starts'' a timer by recording the current time in |*t|. */ static void @ start_timer (clock_t *t) @ { clock_t now = clock (); while (now == clock ()) /* Do nothing. */; *t = clock (); } @ Function |start_timer()| waits for the value returned by |clock()| to change before it records the value. On systems with a slow timer (such as PCs running MS-DOS, where the clock ticks only 18.2 times per second), this gives more stable timing results because it means that timing always starts near the beginning of a clock tick. We also need a function to ``stop'' the timer and report the results: @<Timer functions@> += /* Prints the elapsed time since |start|, set by |start_timer()|. */ static void @ stop_timer (clock_t start) @ { clock_t end = clock (); printf ("%.2f seconds\n", ((double) (end - start)) / CLOCKS_PER_SEC); } @ The value reported by |clock()| can ``wrap around'' to zero from a large value. |stop_timer()| does not allow for this possibility. We will write three tests for the search functions. The first of these just checks that the search function works properly: @<Search test functions@> = /* Tests that |f->search| returns |expect| when called to search for @ |key| within |array[]|, which has |n| elements such that |array[i] == i|. */ static void @ test_search_func_at (struct search_func *f, int array[], int n, int key, int expect) @ { int result = f->search (array, n, key); if (result != expect) printf ("%s returned %d looking for %d - expected %d\n", f->name, result, key, expect); } /* Tests searches for each element in |array[]| having |n| elements such that @ |array[i] == i|, and some unsuccessful searches too, all using function |f->search|. */ static void @ test_search_func (struct search_func *f, int array[], int n) @ { static const int shouldnt_find[] = {INT_MIN, -20, -1, INT_MAX}; int i; printf ("Testing integrity of %s... ", f->name); fflush (stdout); /* Verify that the function finds values that it should. */ for (i = 0; i < n; i++) test_search_func_at (f, array, n, i, i); /* Verify that the function doesn't find values it shouldn't. */ for (i = 0; i < (int) (sizeof shouldnt_find / sizeof *shouldnt_find); i++) test_search_func_at (f, array, n, shouldnt_find[i], -1); printf ("done\n"); } @ The second test function finds the time required for searching for elements in the array: @<Search test functions@> += /* Times a search for each element in |array[]| having |n| elements such that |array[i] == i|, repeated |n_iter| times, using function |f->search|. */ static void @ time_successful_search (struct search_func *f, int array[], int n, int n_iter) @ { clock_t timer; printf ("Timing %d sets of successful searches... ", n_iter); fflush (stdout); start_timer (&timer); while (n_iter-- > 0) @ {@- int i; for (i = 0; i < n; i++) f->search (array, n, i); }@+ stop_timer (timer); } @ The last test function finds the time required for searching for values that don't appear in the array: @<Search test functions@> += /* Times |n| search for elements not in |array[]| having |n| elements such that |array[i] == i|, repeated |n_iter| times, using function |f->search|. */ static void @ time_unsuccessful_search (struct search_func *f, int array[], @ int n, int n_iter) @ { clock_t timer; printf ("Timing %d sets of unsuccessful searches... ", n_iter); fflush (stdout); start_timer (&timer); while (n_iter-- > 0) @ {@- int i; for (i = 0; i < n; i++) f->search (array, n, -i); }@+ stop_timer (timer); } @ Here's the main program: @<Search test main program@> = @<Usage printer for search test program@> @<String to integer function |stoi()|@> int @ main (int argc, char *argv[]) @ { struct search_func *f; /* Search function. */ int *array, n; /* Array and its size. */ int n_iter; /* Number of iterations. */ @<Parse search test command line@> @<Initialize search test array@> @<Run search tests@> @<Clean up after search tests@> return 0; } @ @<Parse search test command line@> = if (argc != 4) @ usage (); { long algorithm = stoi (argv[1]) - 1; if (algorithm < 0 || algorithm > (long) n_search_func) @ usage (); f = &search_func_tab[algorithm]; } n = stoi (argv[2]); n_iter = stoi (argv[3]); if (n < 1 || n_iter < 1) @ usage (); @ @<String to integer function |stoi()|@> = /* |s| should point to a decimal representation of an integer. Returns the value of |s|, if successful, or 0 on failure. */ static int @ stoi (const char *s) @ { long x = strtol (s, NULL, 10); return x >= INT_MIN && x <= INT_MAX ? x : 0; } @ When reading the code below, keep in mind that some of our algorithms use a sentinel at the end and some use a sentinel at the beginning, so we allocate two extra integers and take the middle part. @<Initialize search test array@> = array = malloc ((n + 2) * sizeof *array); if (array == NULL) @ {@- fprintf (stderr, "out of memory\n"); exit (EXIT_FAILURE); }@+ array++; { int i; for (i = 0; i < n; i++) array[i] = i; } @ @<Run search tests@> = test_search_func (f, array, n); time_successful_search (f, array, n, n_iter); time_unsuccessful_search (f, array, n, n_iter); @ @<Clean up after search tests@> = free (array - 1); @ @<Usage printer for search test program@> = /* Prints a message to the console explaining how to use this program. */ static void @ usage (void) @ { size_t i; fputs ("usage: srch-test <algorithm> <array-size> <n-iterations>\n" "where <algorithm> is one of the following:\n", stdout); for (i = 0; i < n_search_func; i++) printf (" %u for %s\n", (unsigned) i + 1, search_func_tab[i].name); fputs (" <array-size> is the size of the array to search, and\n" " <n-iterations> is the number of times to iterate.\n", stdout); exit (EXIT_FAILURE); } @ @end exercise @exercise benchmark Run the test framework from the previous exercise on your own system for each algorithm. Try different array sizes and compiler optimization levels. Be sure to use enough iterations to make the searches take at least a few seconds each. Analyze the results: do they make sense? Try to explain any apparent discrepancies. @answer Here are the results on the author's computer, a Pentium II at 233 MHz, using GNU C 2.95.2, for 1024 iterations using arrays of size 1024 with no optimization. All values are given in seconds rounded to tenths. @multitable @columnfractions .33 .33 .33 @item @strong{Function} @tab @strong{Successful searches} @tab @strong{Unsuccessful searches} @item |seq_search()| @tab 18.4 @tab 36.3 @item |seq_sentinel_search()| @tab 16.5 @tab 32.8 @item |seq_sorted_search()| @tab 18.6 @tab 0.1 @item |seq_sorted_sentinel_search()| @tab 16.4 @tab 0.2 @item |seq_sorted_sentinel_search_2()| @tab 16.6 @tab 0.2 @item |binary_search()| @tab 1.3 @tab 1.2 @item |uniform_binary_search()| @tab 1.1 @tab 1.1 @item |binary_search_bsearch()| @tab 2.6 @tab 2.4 @item |cheat_search()| @tab 0.1 @tab 0.1 @end multitable Results of similar tests using full optimization were as follows: @multitable @columnfractions .33 .33 .33 @item @strong{Function} @tab @strong{Successful searches} @tab @strong{Unsuccessful searches} @item |seq_search()| @tab 6.3 @tab 12.4 @item |seq_sentinel_search()| @tab 4.8 @tab 9.4 @item |seq_sorted_search()| @tab 9.3 @tab 0.1 @item |seq_sorted_sentinel_search()| @tab 4.8 @tab 0.2 @item |seq_sorted_sentinel_search_2()| @tab 4.8 @tab 0.2 @item |binary_search()| @tab 0.7 @tab 0.5 @item |uniform_binary_search()| @tab 0.7 @tab 0.6 @item |binary_search_bsearch()| @tab 1.5 @tab 1.2 @item |cheat_search()| @tab 0.1 @tab 0.1 @end multitable Observations: @itemize @bullet @item In general, the times above are about what we might expect them to be: they decrease as we go down the table. @item Within sequential searches, the sentinel-based searches have better search times than non-sentinel searches, and other search characteristics (whether the array was sorted, for instance) had little impact on performance. @item Unsuccessful searches were very fast for sorted sequential searches, but the particular test set used always allowed such searches to terminate after a single comparison. For other test sets one might expect these numbers to be similar to those for unordered sequential search. @item Either of the first two forms of binary search had the best overall performance. They also have the best performance for successful searches and might be expected to have the best performance for unsuccessful searches in other test sets, for the reason given before. @item Binary search using the general interface |bsearch()| was significantly slower than either of the other binary searches, probably because of the cost of the extra function calls. Items that are more expensive to compare (for instance, long text strings) might be expected to show less of a penalty. @end itemize Here are the results on the same machine for 1,048,576 iterations on arrays of size 8 with full optimization: @multitable @columnfractions .33 .33 .33 @item @strong{Function} @tab @strong{Successful searches} @tab @strong{Unsuccessful searches} @item |seq_search()| @tab 1.7 @tab 2.0 @item |seq_sentinel_search()| @tab 1.7 @tab 2.0 @item |seq_sorted_search()| @tab 2.0 @tab 1.1 @item |seq_sorted_sentinel_search()| @tab 1.9 @tab 1.1 @item |seq_sorted_sentinel_search_2()| @tab 1.8 @tab 1.2 @item |binary_search()| @tab 2.5 @tab 1.9 @item |uniform_binary_search()| @tab 2.4 @tab 2.3 @item |binary_search_bsearch()| @tab 4.5 @tab 3.9 @item |cheat_search()| @tab 0.7 @tab 0.7 @end multitable For arrays this small, simple algorithms are the clear winners. The additional complications of binary search make it slower. Similar patterns can be expected on most architectures, although the ``break even'' array size where binary search and sequential search are equally fast can be expected to differ. @end exercise @node Binary Search Tree in Array, Dynamic Lists, Binary Search of Ordered Array, Search Algorithms @section Binary Search Tree in Array Binary search is pretty fast. Suppose that we wish to speed it up anyhow. Then, the obvious speed-up targets in @<Binary search of ordered array@> above are the |while| condition and the calculations determining values of |i|, |min|, and |max|. If we could eliminate these, we'd have an incrementally faster technique, all else being equal. And, as it turns out, we @emph{can} eliminate both of them, the former by use of a sentinel and the latter by precalculation. Let's consider precalculating |i|, |min|, and |max| first. Think about the nature of the choices that binary search makes at each step. Specifically, in @<Binary search of ordered array@> above, consider the dependence of |min| and |max| upon |i|. Is it ever possible for |min| and |max| to have different values for the same |i| and |n|? The answer is no. For any given |i| and |n|, |min| and |max| are fixed. This is important because it means that we can represent the entire ``state'' of a binary search of an |n|-element array by the single variable |i|. In other words, if we know |i| and |n|, we know all the choices that have been made to this point and we know the two possible choices of |i| for the next step. This is the key insight in eliminating calculations. We can use an array in which the items are labeled with the next two possible choices. An example is indicated. Let's continue with our example of an array containing the 16 integers 100 to 115. We define an entry in the array to contain the item value and the array index of the item to examine next for search values smaller and larger than the item: @<Binary search tree entry@> = /* One entry in a binary search tree stored in an array. */ struct binary_tree_entry @ {@- int value; /* This item in the binary search tree. */ int smaller; /* Array index of next item for smaller targets. */ int larger; /* Array index of next item for larger targets. */ };@+ @ Of course, it's necessary to fill in the values for |smaller| and |larger|. A few moments' reflection should allow you to figure out one method for doing so. Here's the full array, for reference: @<Anonymous@> = const struct binary_tree_entry bins[16] = @ {@- {100, 15, 15}, @ {101, 0, 2}, @ {102, 15, 15}, @ {103, 1, 5}, @ {104, 15, 15}, {105, 4, 6}, @ {106, 15, 15}, @ {107, 3, 11}, @ {108, 15, 15}, @ {109, 8, 10}, {110, 15, 15}, @ {111, 9, 13}, @ {112, 15, 15}, @ {113, 12, 14}, @ {114, 15, 15}, {0, 0, 0}, };@+ @ For now, consider only |bins[]|'s first 15 rows. Within these rows, the first column is |value|, the item value, and the second and third columns are |smaller| and |larger|, respectively. Values 0 through 14 for |smaller| and |larger| indicate the index of the next element of |bins[]| to examine. Value 15 indicates ``element not found''. Element |array[15]| is not used for storing data. Try searching for |key == 110| in |bins[]|, starting from element 7, the midpoint: @enumerate @item |i == 7: 110 > bins[i].value == 107|, so let |i = bins[i].larger|, or 11. @item |i == 11: 110 < bins[i].value == 111|, so let |i = bins[i].smaller|, or 10. @item |i == 10: 110 == bins[i].value == 110|, so we're done. @end enumerate We can implement this search in C code. The function uses the common C idiom of writing |for (;;)| for an ``infinite'' loop: @<Search of binary search tree stored as array@> = /* Returns |i| such that |array[i].value == key|, @ or -1 if |key| is not in |array[]|. |array[]| is an array of |n| elements forming a binary search tree, with its root at |array[n / 2]|, @ and space for an |(n + 1)|th value at the end. */ int @ binary_search_tree_array (struct binary_tree_entry array[], int n, @ int key) @ { int i = n / 2; array[n].value = key; for (;;) if (key > array[i].value) @ i = array[i].larger; else if (key < array[i].value) @ i = array[i].smaller; else @ return i != n ? i : -1; } @ Examination of the code above should reveal the purpose of |bins[15]|. It is used as a sentinel value, allowing the search to always terminate without the use of an extra test on each loop iteration. The result of augmenting binary search with ``pointer'' values like |smaller| and |larger| is called a @gloss{binary search tree}. @exercise Write a function to automatically initialize |smaller| and |larger| within |bins[]|. @answer Here is one easy way to do it: @<Initialize |smaller| and |larger| within binary search tree@> = /* Initializes |larger| and |smaller| within range |min|@dots{}|max| of @ |array[]|, which has |n| real elements plus a |(n + 1)|th sentinel element. */ int @ init_binary_tree_array (struct binary_tree_entry array[], int n, @ int min, int max) @ { if (min <= max) @ {@- /* The `|+ 1|' is necessary because the tree root must be at |n / 2|, and on the first call we have |min == 0| and |max == n - 1|. */ int i = (min + max + 1) / 2; array[i].larger = init_binary_tree_array (array, n, i + 1, max); array[i].smaller = init_binary_tree_array (array, n, min, i - 1); return i; }@+ else @ return n; } @ @end exercise @exercise Write a simple automatic test program for |binary_search_tree_array()|. Let the user specify the size of the array to test on the command line. You may want to use your results from the previous exercise. @answer @(bin-ary-test.c@> = @<Program License@> #include <limits.h> #include <stdio.h> #include <stdlib.h> @<Binary search tree entry@> @<Search of binary search tree stored as array@> @<Initialize |smaller| and |larger| within binary search tree@> @<Show @file{bin-ary-test} usage message@> @<String to integer function |stoi()|@> @<Main program to test |binary_search_tree_array()|@> @ @<Main program to test |binary_search_tree_array()|@> = int @ main (int argc, char *argv[]) @ { struct binary_tree_entry *array; int n, i; /* Parse command line. */ if (argc != 2) @ usage (); n = stoi (argv[1]); if (n < 1) @ usage (); /* Allocate memory. */ array = malloc ((n + 1) * sizeof *array); if (array == NULL) @ {@- fprintf (stderr, "out of memory\n"); return EXIT_FAILURE; }@+ /* Initialize array. */ for (i = 0; i < n; i++) array[i].value = i; init_binary_tree_array (array, n, 0, n - 1); /* Test successful and unsuccessful searches. */ for (i = -1; i < n; i++) @ {@- int result = binary_search_tree_array (array, n, i); if (result != i) printf ("Searching for %d: expected %d, but received %d\n", i, i, result); }@+ /* Clean up. */ free (array); return EXIT_SUCCESS; } @ @<Show @file{bin-ary-test} usage message@> = /* Print a helpful usage message and abort execution. */ static void @ usage (void) @ { fputs ("Usage: bin-ary-test <array-size>\n" "where <array-size> is the size of the array to test.\n", stdout); exit (EXIT_FAILURE); } @ @end exercise @node Dynamic Lists, , Binary Search Tree in Array, Search Algorithms @section Dynamic Lists Up until now, we've considered only lists whose contents are fixed and unchanging, that is, @gloss{static} lists. But in real programs, many lists are @gloss{dynamic}, with their contents changing rapidly and unpredictably. For the case of dynamic lists, we need to reconsider some of the attributes of the types of lists that we've examined.@footnote{These uses of the words ``static'' and ``dynamic'' are different from their meanings in the phrases ``static allocation'' and ``dynamic allocation.'' @xref{Glossary}, for more details.} Specifically, we want to know how long it takes to insert a new element into a list and to remove an existing element from a list. Think about it for each type of list examined so far: @c FIXME: Dann Corbit: @c Mention heaps, skip lists, hash tables. @table @b @item Unordered array Adding items to the list is easy and fast, unless the array grows too large for the block and has to be copied into a new area of memory. Just copy the new item to the end of the list and increase the size by one. Removing an item from the list is almost as simple. If the item to delete happens to be located at the very end of the array, just reduce the size of the list by one. If it's located at any other spot, you must also copy the element that is located at the very end onto the location that the deleted element used to occupy. @item Ordered array In terms of inserting and removing elements, ordered arrays are mechanically the same as unordered arrays. The difference is that insertions and deletions can only be at one end of the array if the item in question is the largest or smallest in the list. The practical upshot is that dynamic ordered arrays are only efficient if items are added and removed in sorted order. @item Binary search tree Insertions and deletions are where binary search trees have their chance to shine. Insertions and deletions are efficient in binary search trees whether they're made at the beginning, middle, or end of the lists. @end table Clearly, binary search trees are superior to ordered or unordered arrays in situations that require insertion and deletion in random positions. But insertion and deletion operations in binary search trees require a bit of explanation if you've never seen them before. This is what the next chapter is for, so read on.
/* * AMRIT – Accessible Medical Records via Integrated Technology * Integrated EHR (Electronic Health Records) Solution * * Copyright (C) "Piramal Swasthya Management and Research Institute" * * This file is part of AMRIT. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see https://www.gnu.org/licenses/. */ import { Component, OnInit, ChangeDetectorRef, AfterViewInit, ElementRef, ViewChild, Input } from '@angular/core'; import { Location } from '@angular/common'; import { Router, ActivatedRoute } from '@angular/router'; import { ConfirmationService } from '../../../core/services/confirmation.service'; import { MdDialogRef, MdDialog, MdDialogConfig } from '@angular/material'; import { DoctorService } from '../../shared/services/doctor.service'; import { PrintPageSelectComponent } from '../../print-page-select/print-page-select.component'; import { BeneficiaryDetailsService } from '../../../core/services/beneficiary-details.service'; import { SetLanguageComponent } from 'app/app-modules/core/components/set-language.component'; import { HttpServiceService } from 'app/app-modules/core/services/http-service.service'; @Component({ selector: 'app-cancer-case-sheet', templateUrl: './cancer-case-sheet.component.html', styleUrls: ['./cancer-case-sheet.component.css'] }) export class CancerCaseSheetComponent implements OnInit { @Input('previous') previous: any; @Input('serviceType') serviceType: any; printPagePreviewSelect = { caseSheetHistory: true, caseSheetExamination: true, caseSheetCovidVaccinationDetails: true } visitCategory: string; hideBack: Boolean = false; getCaseSheetDataVisit: any; languageComponent: SetLanguageComponent; currentLanguageSet: any; constructor( private doctorService: DoctorService, private dialog: MdDialog, private location: Location, private route: ActivatedRoute, private confirmationService: ConfirmationService, private httpServiceService:HttpServiceService) { } ngOnInit() { this.fetchLanguageResponse(); let dataStore = this.route.snapshot.params['printablePage'] || 'previous'; let caseSheetRequest; if (dataStore == 'current') { caseSheetRequest = { "VisitCategory": localStorage.getItem('caseSheetVisitCategory'), "benFlowID": localStorage.getItem('caseSheetBenFlowID'), "benVisitID": localStorage.getItem('caseSheetVisitID'), "beneficiaryRegID": localStorage.getItem('caseSheetBeneficiaryRegID'), "visitCode": localStorage.getItem('visitCode') } this.getCaseSheetDataVisit = { benVisitID: localStorage.getItem('caseSheetVisitID'), benRegID: localStorage.getItem('caseSheetBeneficiaryRegID'), benFlowID: localStorage.getItem('caseSheetBenFlowID') } this.visitCategory = localStorage.getItem('caseSheetVisitCategory'); this.getCurrentRole(); this.getCaseSheetData(caseSheetRequest); } if (dataStore == 'previous') { this.hideBack = true; caseSheetRequest = { "VisitCategory": localStorage.getItem('previousCaseSheetVisitCategory'), "benFlowID": localStorage.getItem('previousCaseSheetBenFlowID'), "beneficiaryRegID": localStorage.getItem('previousCaseSheetBeneficiaryRegID'), "visitCode": localStorage.getItem('previousCaseSheetVisitCode') } this.getCaseSheetDataVisit = { benVisitID: localStorage.getItem('previousCaseSheetVisitID'), benRegID: localStorage.getItem('previousCaseSheetBeneficiaryRegID'), benFlowID: localStorage.getItem('previousCaseSheetBenFlowID'), } this.visitCategory = localStorage.getItem('previousCaseSheetVisitCategory'); this.getCurrentRole(); this.getCaseSheetData(caseSheetRequest); } } // ngDoCheck() { // this.assignSelectedLanguage(); // } assignSelectedLanguage() { const getLanguageJson = new SetLanguageComponent(this.httpServiceService); getLanguageJson.setLanguage(); this.currentLanguageSet = getLanguageJson.currentLanguageObject; } ngOnDestroy() { if (this.caseSheetSubs) this.caseSheetSubs.unsubscribe(); // localStorage.removeItem('currentRole'); } oncologistRemarks: any; getCurrentRole() { let currentRole = localStorage.getItem('currentRole'); if (currentRole && currentRole === 'Oncologist') { this.oncologistRemarks = true; } } caseSheetData: any; caseSheetDiagnosisData: any; caseSheetSubs: any; getCaseSheetData(caseSheetRequest) { if (this.serviceType == 'TM') { this.getTMCasesheetData(caseSheetRequest) } if (this.serviceType == 'MMU') { this.getMMUCasesheetData(caseSheetRequest); } } getMMUCasesheetData(caseSheetRequest) { this.caseSheetSubs = this.doctorService.getMMUCasesheetData(caseSheetRequest) .subscribe(res => { if (res && res.statusCode == 200 && res.data) { this.caseSheetData = res.data; console.log('caseSheetData', JSON.stringify(this.caseSheetData, null, 4)); } }); } getTMCasesheetData(caseSheetRequest) { this.caseSheetSubs = this.doctorService.getTMCasesheetData(caseSheetRequest) .subscribe(res => { if (res && res.statusCode == 200 && res.data) { this.caseSheetData = res.data; console.log('caseSheetData', JSON.stringify(this.caseSheetData, null, 4)); } }); } getOncologistRemarks() { let value = undefined; if (this.caseSheetDiagnosisData && this.caseSheetDiagnosisData.provisionalDiagnosisOncologist) { value = this.caseSheetDiagnosisData.provisionalDiagnosisOncologist; } this.confirmationService .editRemarks( this.currentLanguageSet.casesheet.oncologistObservation, value ) .subscribe(result => { if (result) { if (!this.caseSheetDiagnosisData) { this.caseSheetDiagnosisData = {}; } result = result.slice(0, result.lastIndexOf('.')); this.caseSheetDiagnosisData.provisionalDiagnosisOncologist = result; this.saveOncologistRemarks(result); } }); } saveOncologistRemarks(result) { this.doctorService.postOncologistRemarksforCancerCaseSheet(result, this.getCaseSheetDataVisit.benVisitID, this.getCaseSheetDataVisit.benRegID) .subscribe((res) => { if (res.statusCode == 500 || res.statusCode == 5000) { this.confirmationService.alert(res.errorMessage, 'error'); } else if (res.statusCode == 200) { if (this.caseSheetData && this.caseSheetData.doctorData) { this.caseSheetData = { ...this.caseSheetData, doctorData: { ...this.caseSheetData.doctorData, diagnosis: { ...this.caseSheetData.doctorData.diagnosis, provisionalDiagnosisOncologist: result } } } } this.confirmationService.alert(res.data.response, 'success'); } }) } selectPrintPage() { let mdDialogRef: MdDialogRef<PrintPageSelectComponent> = this.dialog.open(PrintPageSelectComponent, { width: '420px', disableClose: false, data: { printPagePreviewSelect: this.printPagePreviewSelect, visitCategory: this.visitCategory } }); mdDialogRef.afterClosed().subscribe(result => { if (result) { this.printPagePreviewSelect.caseSheetExamination = result.caseSheetExamination; this.printPagePreviewSelect.caseSheetHistory = result.caseSheetHistory; this.printPagePreviewSelect.caseSheetCovidVaccinationDetails = result.caseSheetCovidVaccinationDetails; } }); } printPage() { window.print(); } goToTop() { window.scrollTo(0, 0); } goBack() { this.location.back(); } // AV40085804 13/10/2021 Integrating Multilingual Functionality -----Start----- ngDoCheck() { this.fetchLanguageResponse(); } fetchLanguageResponse() { this.languageComponent = new SetLanguageComponent(this.httpServiceService); this.languageComponent.setLanguage(); this.currentLanguageSet = this.languageComponent.currentLanguageObject; } // -----End------ }
/** @format */ "use client"; import { EmptyBoards } from "./emptyBoards"; import { EmptyFavrt } from "./emptyFavrt"; import { EmptySearch } from "./emptySearch"; import { useQuery } from "convex/react"; import { api } from "@/convex/_generated/api"; import { BoardCard } from "./boardCard"; import { NewBoardBtn } from "./newBoardBtn"; interface BoardListProps { orgId: string; query: { search?: string; favourites?: string; }; } export const BoardList = ({ orgId, query }: BoardListProps) => { const data = useQuery(api.boards.get, { orgId, ...query }); // Loading state if (data === undefined) { return ( <div> <h2 className="text-3xl"> {query.favourites ? "Favourite Boards" : "Team Boards"} </h2> <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-5 mt-8 pb-10"> <NewBoardBtn orgId={orgId} disabled /> <BoardCard.Skeleton /> <BoardCard.Skeleton /> <BoardCard.Skeleton /> <BoardCard.Skeleton /> <BoardCard.Skeleton /> </div> </div> ); } if (!data?.length && query.search) { return <EmptySearch />; } if (!data?.length && query.favourites) { return <EmptyFavrt />; } if (!data?.length) { return <EmptyBoards />; } return ( <div> {/* {JSON.stringify(data)} */} <h2 className="text-3xl"> {query.favourites ? "Favourite Boards" : "Team Boards"} </h2> <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-5 mt-8 pb-10"> <NewBoardBtn orgId={orgId} /> {data?.map((board) => ( <BoardCard key={board._id} id={board._id} title={board.title} imageUrl={board.imageUrl} authorId={board.authorId} authorName={board.authorName} createdAt={board._creationTime} orgId={board.orgId} isFavourite={board.isFavourite} /> ))} </div> </div> ); };
import { Autocomplete } from "@equinor/eds-core-react"; import { InputAdornment, TextField } from "@material-ui/core"; import React, { useContext, useEffect, useState } from "react"; import OperationContext from "../../contexts/operationContext"; import { HideModalAction } from "../../contexts/operationStateReducer"; import OperationType from "../../contexts/operationType"; import { itemStateTypes } from "../../models/itemStateTypes"; import { riskAffectedPersonnel } from "../../models/riskAffectedPersonnel"; import { riskCategory } from "../../models/riskCategory"; import RiskObject from "../../models/riskObject"; import { riskSubCategory } from "../../models/riskSubCategory"; import { riskType } from "../../models/riskType"; import JobService, { JobType } from "../../services/jobService"; import formatDateString from "../DateFormatter"; import { DateTimeField } from "./DateTimeField"; import ModalDialog from "./ModalDialog"; import { PropertiesModalMode, validText } from "./ModalParts"; export interface RiskPropertiesModalProps { mode: PropertiesModalMode; riskObject: RiskObject; dispatchOperation: (action: HideModalAction) => void; } const RiskPropertiesModal = (props: RiskPropertiesModalProps): React.ReactElement => { const { mode, riskObject, dispatchOperation } = props; const { operationState: { timeZone, dateTimeFormat } } = useContext(OperationContext); const [editableRiskObject, setEditableRiskObject] = useState<RiskObject>(null); const [isLoading, setIsLoading] = useState<boolean>(false); const [dTimStartValid, setDTimStartValid] = useState<boolean>(true); const [dTimEndValid, setDTimEndValid] = useState<boolean>(true); const editMode = mode === PropertiesModalMode.Edit; useEffect(() => { setEditableRiskObject({ ...riskObject, dTimStart: formatDateString(riskObject.dTimStart, timeZone, dateTimeFormat), dTimEnd: formatDateString(riskObject.dTimEnd, timeZone, dateTimeFormat), commonData: { ...riskObject.commonData, dTimCreation: formatDateString(riskObject.commonData.dTimCreation, timeZone, dateTimeFormat), dTimLastChange: formatDateString(riskObject.commonData.dTimLastChange, timeZone, dateTimeFormat) } }); }, [riskObject]); const onSubmit = async (updatedRisk: RiskObject) => { setIsLoading(true); const wellboreRiskJob = { risk: updatedRisk }; await JobService.orderJob(JobType.ModifyRisk, wellboreRiskJob); setIsLoading(false); dispatchOperation({ type: OperationType.HideModal }); }; return ( <> {editableRiskObject && ( <ModalDialog heading={editMode ? `Edit properties for ${editableRiskObject.name}` : `New Log`} content={ <> <TextField disabled id="wellUid" label="well uid" defaultValue={editableRiskObject.wellUid} fullWidth /> <TextField disabled id="wellName" label="well name" defaultValue={editableRiskObject.wellName} fullWidth /> <TextField disabled id="wellboreUid" label="wellbore uid" defaultValue={editableRiskObject.wellboreUid} fullWidth /> <TextField disabled id="wellboreName" label="wellbore name" defaultValue={editableRiskObject.wellboreName} fullWidth /> <TextField disabled id="dateTimeCreation" label="created" defaultValue={editableRiskObject.commonData.dTimCreation} fullWidth /> <TextField disabled id="dateTimeLastChange" label="last changed" defaultValue={editableRiskObject.commonData.dTimLastChange} fullWidth /> <TextField disabled id={"uid"} label={"risk uid"} required defaultValue={editableRiskObject.uid} fullWidth /> <TextField id={"name"} label={"name"} required value={editableRiskObject.name ? editableRiskObject.name : ""} error={editableRiskObject.name.length === 0} helperText={editableRiskObject.name.length === 0 ? "The risk name must be 1-64 characters" : ""} fullWidth inputProps={{ minLength: 1, maxLength: 64 }} onChange={(e) => setEditableRiskObject({ ...editableRiskObject, name: e.target.value })} /> <Autocomplete id="type" label="Select a type" options={riskType} initialSelectedOptions={[editableRiskObject.type]} onOptionsChange={({ selectedItems }) => { setEditableRiskObject({ ...editableRiskObject, type: selectedItems[0] }); }} /> <Autocomplete id="category" label="Select a category" options={riskCategory} initialSelectedOptions={[editableRiskObject.category]} onOptionsChange={({ selectedItems }) => { setEditableRiskObject({ ...editableRiskObject, category: selectedItems[0] }); }} /> <Autocomplete id="subCategory" label="Select a sub category" options={riskSubCategory} initialSelectedOptions={[editableRiskObject.subCategory]} onOptionsChange={({ selectedItems }) => { setEditableRiskObject({ ...editableRiskObject, subCategory: selectedItems[0] }); }} /> <TextField id="extendCategory" label="extendCategory" value={editableRiskObject.extendCategory ? editableRiskObject.extendCategory : ""} fullWidth inputProps={{ minLength: 1 }} onChange={(e) => setEditableRiskObject({ ...editableRiskObject, extendCategory: e.target.value })} /> <Autocomplete id="affectedPersonnel" label="Select multiple affected personnel" selectedOptions={editableRiskObject.affectedPersonnel ? editableRiskObject.affectedPersonnel.split(", ") : []} options={riskAffectedPersonnel} multiple onOptionsChange={({ selectedItems }) => { setEditableRiskObject({ ...editableRiskObject, affectedPersonnel: selectedItems.join(", ") }); }} /> <DateTimeField value={editableRiskObject.dTimStart} label="dTimStart" updateObject={(dateTime: string, valid: boolean) => { setEditableRiskObject({ ...editableRiskObject, dTimStart: dateTime }); setDTimStartValid(valid); }} timeZone={timeZone} /> <DateTimeField value={editableRiskObject.dTimEnd} label="dTimEnd" updateObject={(dateTime: string, valid: boolean) => { setEditableRiskObject({ ...editableRiskObject, dTimEnd: dateTime }); setDTimEndValid(valid); }} timeZone={timeZone} /> <TextField id={"mdBitStart"} label={"mdBitStart"} type="number" fullWidth InputProps={{ startAdornment: <InputAdornment position="start">{editableRiskObject.mdBitStart ? editableRiskObject.mdBitStart.uom : ""}</InputAdornment> }} disabled={!editableRiskObject.mdBitStart} value={editableRiskObject.mdBitStart?.value} onChange={(e) => setEditableRiskObject({ ...editableRiskObject, mdBitStart: { value: isNaN(parseFloat(e.target.value)) ? undefined : parseFloat(e.target.value), uom: editableRiskObject.mdBitStart.uom } }) } /> <TextField id={"mdBitEnd"} label={"mdBitEnd"} type="number" fullWidth InputProps={{ startAdornment: <InputAdornment position="start">{editableRiskObject.mdBitEnd ? editableRiskObject.mdBitEnd.uom : ""}</InputAdornment> }} disabled={!editableRiskObject.mdBitEnd} value={editableRiskObject.mdBitEnd?.value} onChange={(e) => setEditableRiskObject({ ...editableRiskObject, mdBitEnd: { value: isNaN(parseFloat(e.target.value)) ? undefined : parseFloat(e.target.value), uom: editableRiskObject.mdBitEnd.uom } }) } /> <TextField id="severityLevel" label="severityLevel" value={editableRiskObject.severityLevel ? editableRiskObject.severityLevel : ""} error={editableRiskObject.severityLevel?.length === 0} helperText={editableRiskObject.severityLevel?.length === 0 ? "The risk severityLevel must be at least 1 character" : ""} fullWidth inputProps={{ minLength: 1 }} onChange={(e) => setEditableRiskObject({ ...editableRiskObject, severityLevel: e.target.value })} /> <TextField id="probabilityLevel" label="probabilityLevel" value={editableRiskObject.probabilityLevel ? editableRiskObject.probabilityLevel : ""} error={editableRiskObject.probabilityLevel?.length === 0} helperText={editableRiskObject.probabilityLevel?.length === 0 ? "The risk probabilityLevel must be at least 1 character" : ""} fullWidth inputProps={{ minLength: 1 }} onChange={(e) => setEditableRiskObject({ ...editableRiskObject, probabilityLevel: e.target.value })} /> <TextField id="summary" label="summary" required value={editableRiskObject.summary ? editableRiskObject.summary : ""} error={editableRiskObject.summary?.length === 0} helperText={editableRiskObject.summary?.length === 0 ? "The risk summary must be at least 1 character" : ""} fullWidth inputProps={{ minLength: 1 }} onChange={(e) => setEditableRiskObject({ ...editableRiskObject, summary: e.target.value })} /> <TextField id="details" label="details" value={editableRiskObject.details ? editableRiskObject.details : ""} error={editableRiskObject.details?.length === 0} multiline helperText={editableRiskObject.details?.length === 0 ? "The risk details must be between 1 and 256 characters" : ""} fullWidth inputProps={{ minLength: 1, maxLength: 256 }} onChange={(e) => setEditableRiskObject({ ...editableRiskObject, details: e.target.value })} /> <TextField id="sourceName" label="sourceName" value={editableRiskObject.commonData.sourceName ? editableRiskObject.commonData.sourceName : ""} fullWidth onChange={(e) => { const commonData = { ...editableRiskObject.commonData, sourceName: e.target.value }; setEditableRiskObject({ ...editableRiskObject, commonData }); }} /> <Autocomplete id="itemState" label="Select an item state" options={itemStateTypes} initialSelectedOptions={[editableRiskObject.commonData.itemState ? editableRiskObject.commonData.itemState : ""]} onOptionsChange={({ selectedItems }) => { const commonData = { ...editableRiskObject.commonData, itemState: selectedItems[0] ?? null }; setEditableRiskObject({ ...editableRiskObject, commonData }); }} /> </> } confirmDisabled={!validText(editableRiskObject.name) || !dTimStartValid || !dTimEndValid} onSubmit={() => onSubmit(editableRiskObject)} isLoading={isLoading} /> )} </> ); }; export default RiskPropertiesModal;
import { h, defineComponent, computed, mergeProps } from "vue"; import "./style"; import { buttonProps } from "./types"; import { pxToVw } from "@moxui/utils/utils"; export default defineComponent({ name: "MoButton", props: buttonProps, setup(props, { slots }) { const buttonTxt = computed(() => { return props.txt ? props.txt : props.type === "confirm" ? "确认" : "取消"; }); const buttonStyle = computed(() => { const height = props.height ? pxToVw(props.height) : undefined; const width = props.width ? pxToVw(props.width) : undefined; return { width, height, backgroundColor: props.backgroundColor, color: props.color, }; }); // render const baseClass = "mo-button"; return () => { return h( "button", { class: [ baseClass, `${baseClass}__${props.type}`, `${baseClass}__${props.size}`, { [baseClass + "__disabled"]: props.disabled }, ], style: buttonStyle.value, disabled: props.disabled, }, slots.default ? slots.default() : buttonTxt.value ); }; }, });
""" Customtkinter documentation: https://customtkinter.tomschimansky.com/documentation/widgets/button Appearance: customtkinter forest-ttk-theme (used for treeview table) """ import tkinter as tk from tkinter import ttk import customtkinter import ctypes # dots per inch awareness from my_functions import MyFunctions from gecko_functions import GeckoFunctions from data_processing_functions import DataProcessingFunctions import matplotlib.pyplot as plt import matplotlib.dates as mdates from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import pandas as pd import numpy as nps class Gui(customtkinter.CTk, GeckoFunctions): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # accessing crypto data self.gf = GeckoFunctions() self.mf = MyFunctions() self.dpf = DataProcessingFunctions() # dots per inch awareness - to fix blurry text on GUI ctypes.windll.shcore.SetProcessDpiAwareness(1) # hide initial window self.iconify() # window self.window = tk.Tk() self.window.title('Crypto Project') self.window.geometry('1000x600') self.window['background'] = '#1A1A1A' self.window.state('zoomed') customtkinter.set_appearance_mode('Dark') # configure grid self.window.grid_columnconfigure(0, weight=1) self.window.grid_columnconfigure(1, weight=5) self.window.grid_rowconfigure(0, weight=1) # create navigation frame self.navigation_frame = customtkinter.CTkFrame(master=self.window, corner_radius=8) self.navigation_frame.grid(row=0, column=0, padx=15, pady=15, sticky='news') self.navigation_frame.grid_columnconfigure(0, weight=1) self.navigation_frame.grid_rowconfigure(10, weight=1) self.navigation_frame_label_0 = customtkinter.CTkLabel(self.navigation_frame, text='Navigation Bar', anchor='center', font=customtkinter.CTkFont(size=25, weight='bold')) self.navigation_frame_label_0.grid(row=0, column=0, padx=20, pady=20, sticky='news') self.home_button = customtkinter.CTkButton(self.navigation_frame, corner_radius=0, height=40, text="Home", fg_color="transparent", text_color=("gray10", "gray90"), hover_color=("gray70", "gray30"), command=self.home_button_event) self.home_button.grid(row=1, column=0, sticky="ew") self.graph_button = customtkinter.CTkButton(self.navigation_frame, corner_radius=0, height=40, text="Graphs", fg_color="transparent", text_color=("gray10", "gray90"), hover_color=("gray70", "gray30"), command=self.graph_button_event) self.graph_button.grid(row=2, column=0, sticky="ew") # create home frame home_frame <- tree_frame <- tree_scroll + tree_view # self.home_frame = customtkinter.CTkFrame(master=self.window, corner_radius=8, fg_color=('gray70', 'gray10')) self.home_frame = customtkinter.CTkFrame(master=self.window, corner_radius=8, fg_color=('gray70', 'gray17')) self.home_frame.grid(row=0, column=1, padx=(0,15), pady=10, sticky="news") self.home_frame.grid_columnconfigure(0, weight=1) self.home_frame.grid_rowconfigure(0, weight=1) # create tree frame self.tree_frame = customtkinter.CTkFrame(master=self.home_frame, corner_radius=8) self.tree_frame.grid_columnconfigure(0, weight=1) self.tree_frame.grid_rowconfigure(0, weight=1) self.tree_frame.grid(row=0, column=0, padx=5, pady=5) self.treeScroll = ttk.Scrollbar(self.tree_frame) self.treeScroll.pack(side='right', fill='y') # apply Azure theme to tree_frame style = ttk.Style(self.tree_frame) self.tree_frame.tk.call('source', 'Azure/azure.tcl') self.tree_frame.tk.call('set_theme', 'dark') # set up column and data into treeview cols = ('Rank', 'ID', 'Symbol', 'Market Cap', 'Total Volume', '24h', 'Price' ) self.treeview = ttk.Treeview(self.tree_frame, show='headings', yscrollcommand=self.treeScroll.set, columns=cols, height=100) self.treeview.heading('Rank', text='Rank', anchor=tk.W) self.treeview.heading('ID', text='ID', anchor=tk.W) self.treeview.heading('Symbol', text='Symbol', anchor=tk.W) self.treeview.heading('Market Cap', text='Market Cap', anchor=tk.W) self.treeview.heading('Total Volume', text='Total Volume', anchor=tk.W) self.treeview.heading('24h', text='24h', anchor=tk.W) self.treeview.heading('Price', text='Price', anchor=tk.W) self.treeview.column('Rank', width=50) self.treeview.column('Symbol', width=80) self.treeview.column('Market Cap', width=150) self.treeview.column('Total Volume', width=150) self.treeview.column('24h', width=80) self.treeview.pack() self.treeScroll.config(command=self.treeview.yview) self.load_data() # create background frame to host chart_frame - this allows for corner_radius to be applied self.back_frame = customtkinter.CTkFrame(master=self.window, corner_radius=8, fg_color='#2B2B2B') self.back_frame.grid_columnconfigure(0, weight=1) self.back_frame.grid_rowconfigure(0, weight=1) # create graph frame self.graph_frame = customtkinter.CTkFrame(master=self.back_frame, corner_radius=8, fg_color="#2B2B2B") self.graph_frame.grid_columnconfigure(0, weight=1) self.graph_frame.grid_rowconfigure(0, weight=1) #print(plt.rcParams) # set plot theme for matplotlib with plt.rc_context({ # 'figure.facecolor':'#2B2B2B', # 'axes.facecolor':'#2B2B2B', # 'xtick.color':'white', # 'ytick.color':'white', # 'axes.titlecolor':'white', # 'axes.labelcolor':'white', # 'axes.edgecolor':'#333333', # 'grid.color':'#333333', # 'axes.titlelocation':'left', # 'text.color': 'white', 'axes.labelpad': '8.0', 'font.size': '10.0', 'axes.xmargin': '0.1', 'axes.ymargin': '0.1', 'grid.linewidth': '1.5', 'axes.linewidth': '1.5', 'xtick.major.width': '1.5', 'xtick.major.size': '4.0', 'xtick.minor.width': '1.0', 'xtick.minor.size': '2.0', 'ytick.major.width': '1.5', 'ytick.major.size': '4.0', }): # create embedded matplotlib graph - graph_frame <- canvas <- fig <- ax self.fig, self.ax = plt.subplots() self.canvas = FigureCanvasTkAgg(self.fig, master=self.graph_frame) self.plotGraph(self.ax, self.fig, self.canvas, self.gf, self.dpf) self.toplevel_toolbar_window = None # select default frame self.select_frame_by_name("home") def select_frame_by_name(self, name): # set button color for selected button self.home_button.configure(fg_color=("gray75", "gray25") if name == "home" else "transparent") self.graph_button.configure(fg_color=("gray75", "gray25") if name == "graph" else "transparent") # show selected frame or frame and toplevel window if name == "home": self.home_frame.grid(row=0, column=1, padx=(0,15), pady=10, sticky="news") else: self.home_frame.grid_forget() if name == "graph": self.back_frame.grid(row=0, column=1, padx=(0,15), pady=15, sticky="nsew") self.graph_frame.grid(row=0, column=0, padx=4, pady=4, sticky="nsew") self.open_toplevel_graph_toolbar() else: self.back_frame.grid_forget() self.graph_frame.grid_forget() def graph_button_event(self): self.select_frame_by_name("graph") def home_button_event(self): self.select_frame_by_name("home") # loading data into treeview def load_data(self): list = self.dpf.tree_view_data('usd',1,2) for i in list: self.treeview.insert('', tk.END, values=i) def plotGraph(self, ax, fig, canvas, gf, dpf): data = gf.get_coin_data_days('bitcoin', 'usd', 10000) human_time, price = ([] for i in range(2)) for i in data['prices']: human_time.append(dpf.human_time(i[0])) price.append(i[1]) self.ax.title.set_text('Bitcoin') self.ax.set_ylabel(r'Price [\$]') self.ax.plot(human_time, price) #ax.set_yscale('log') self.ax.grid(visible=True, which='major', axis='both') # Major ticks every half year, minor ticks every month, self.ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=(1))) self.ax.xaxis.set_minor_locator(mdates.MonthLocator()) self.ax.set_title('Manual DateFormatter', loc='left', y=0.85, x=0.02, fontsize='medium') # Text in the x-axis will be displayed in 'YYYY' format. self.ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y')) self.canvas.draw() self.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True) def open_toplevel_graph_toolbar(self): if self.toplevel_toolbar_window is None or not self.toplevel_toolbar_window.winfo_exists(): self.toplevel_toolbar_window = ToplevelGraphToolBar(self) # create window if its None or destroyed else: self.toplevel_toolbar_window.focus() # if window exists focus it def on_closing_event(self): print('on_closing_event ___________ destroyed self.window and initial window') self.window.destroy() self.destroy() exit() # "1968159393536check_dpi_scaling" on cmd after closing. This message was displayed when matplotlib graph was embedded. class ToplevelGraphToolBar(customtkinter.CTkToplevel): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # configure grid self.grid_columnconfigure(0, weight=1) self.grid_columnconfigure(1, weight=1) self.grid_rowconfigure(8, weight=1) self.geometry("400x300") self.title('Toolbar') self.toolbar_frame = customtkinter.CTkLabel(master=self) self.toolbar_frame.grid(row=0, column=0, sticky='news') self.toolbarLabel = customtkinter.CTkLabel(self.toolbar_frame, text='Toolbar', anchor='center', font=customtkinter.CTkFont(size=25, weight='bold')) self.toolbarLabel.grid(row=0, column=0, sticky='news') self.switch_var_yscale_on = customtkinter.StringVar(value="on") self.switch_var_yscale_off = customtkinter.StringVar(value="off") self.switch_yscale = customtkinter.CTkSwitch(master=self.toolbar_frame, text="Log", command=self.switch_yscale_event, variable=self.switch_var_yscale_on, onvalue="on", offvalue="off") self.switch_yscale.grid(row=0, column=1, sticky='news') def switch_yscale_event(self): if self.switch_var_yscale_on.get() == 'on': print('switch is on') self.ax.set_yscale('log') elif self.switch_var_yscale_off.get() == 'off': print('switch if off') if __name__ == "__main__": gui = Gui() gui.window.protocol("WM_DELETE_WINDOW", gui.on_closing_event) gui.mainloop()
IO.puts "Hello World" # => Hello World # => :ok 40 + 2 # => 42 "hello" <> " world" # => "hello world" 10 / 2 # => 5.0 div(10, 2) # => 5 rem 10, 3 # => 1 0b1010 # => 10 0b1 # => 1 0b10 # => 2 round 3.58 # => 4 trunc 3.58 # => 3 true == false # => false is_boolean false # => true is_boolean 1.0 # => false :hello == :world # => false :true == true # => true is_atom true # => true "hello #{:world}" # => "hello world" "hello \nworld" # => "hello \nworld" IO.puts "hello \nworld" # => hello # => world # => :ok is_binary("hello") # => true byte_size("hellお") # => 7 String.length("hellお") # => 5 byte_size("ハロー") # => 9 String.length("ハロー") # => 3 add = fn a, b -> a + b end # => #Function<12.54118792/2 in :erl_eval.expr/5> is_function(add) # => true is_function(add, 2) # => true is_function(add, 1) # => false add.(1, 2) # => 3 add_two = fn a -> add.(a, 2) end # => #Function<6.54118792/1 in :erl_eval.expr/5> add_two.(2) # => 4 x = 42 (fn -> x = 0 end).() x # => 42 length [1, 2, true, 3] # => 4 list = [1, 2, 3] hd(list) # => 1 tl(list) # => [2, 3] hd [] # => %ArgumentError{message: "argument error"} tuple = {:ok, "hello"} # => {:ok, "hello"} elem(tuple, 1) # => "hello" elem(tuple, 0) # => :ok put_elem(tuple, 1, "world") # => {:ok, "world"} tuple # => {:ok, "hello"} list = [1|[2|[3|[]]]] # => [1, 2, 3] [0] ++ list # => [0, 1, 2, 3] list ++ [4] # => [1, 2, 3, 4] File.read("/etc/hosts") # => {:ok, # => "##\n# Host Database\n#\n# localhost is used to configure the loopback interface\n# when the system is booting. Do not change this entry.\n##\n127.0.0.1\tlocalhost\n255.255.255.255\tbroadcasthost\n::1 localhost \n"} File.read("~/.vimrc") # => {:error, :enoent} # データ構造が持っている要素数を数える場合,Elixirは単純な規則: 操作が一定時間 # になる(つまり値があらかじめ計算されている)ものを関数名sizeと呼び,明示的に計 # 算が必要なものは関数名lengthと呼ぶという規則に従います. [1, 2, 3] ++ [4, 5, 6] # => [1, 2, 3, 4, 5, 6] [1, 2, 3] -- [2] # => [1, 3] "foo" <> "bar" # => "foobar" true and true # => true false or is_atom(:example) # => true 1 and true # => %ArgumentError{message: "argument error: 1"} false and raise("This error will never be raised") # => false 1 || true # => 1 false || 11 # => 11 nil && 13 # => nil true && 17 # => 17 !true # => false !1 # => false !nil # => true 1 == 1 # => true 1 != 2 # => true 1 < 2 # => true 1 == 1.0 # => true 1 === 1.0 # => false 1 < :atom # => true # number < atom < reference < functions < port < pid < tuple < maps < list < bitstring
package tracing import ( "context" "fmt" texporter "github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/trace" gcppropagator "github.com/GoogleCloudPlatform/opentelemetry-operations-go/propagator" "go.opentelemetry.io/contrib/detectors/gcp" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/sdk/resource" sdktrace "go.opentelemetry.io/otel/sdk/trace" semconv "go.opentelemetry.io/otel/semconv/v1.21.0" "go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace/noop" ) type Configuration struct { Enabled bool ApplicationName string ProjectID string } func Init(configuration Configuration) (trace.Tracer, error) { if !configuration.Enabled { return &noop.Tracer{}, nil } exporter, err := texporter.New(texporter.WithProjectID(configuration.ProjectID)) if err != nil { return nil, fmt.Errorf("texporter.New error: %v", err) } res, err := resource.New(context.Background(), resource.WithDetectors(gcp.NewDetector()), resource.WithTelemetrySDK(), resource.WithAttributes( semconv.ServiceNameKey.String(configuration.ApplicationName), ), ) if err != nil { return nil, fmt.Errorf("resource.New error: %w", err) } tp := sdktrace.NewTracerProvider( sdktrace.WithBatcher(exporter), sdktrace.WithResource(res), ) otel.SetTextMapPropagator( propagation.NewCompositeTextMapPropagator( gcppropagator.CloudTraceFormatPropagator{}, propagation.TraceContext{}, propagation.Baggage{}, ), ) otel.SetTracerProvider(tp) tracer := tp.Tracer(configuration.ApplicationName) return tracer, nil }
<!doctype html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title>User Centre</title> <meta name="description" content="" /> <meta name="viewport" content="width=device-width" /> <base href="/" /> </head> <link href="/mystylesheet.css" th:href="@{css/modalpopup.css}" rel="stylesheet" type="text/css"> <link href="/mycss.css" th:href="@{css/typewriter-effect.css}" rel="stylesheet" type="text/css" /> <head th:replace="fragments/header :: headHeader"> </head> <body> <div th:replace="fragments/header :: navForViewer"></div> <div> <form> <div class="container"> <h1>Add skill</h1> <div class="form-group row"> <label for="skillName" class="col-sm-2 col-form-label">Skill category</label> <div class="form-group col-md-4"> <select id="skillCategory" class="form-control"> <option>Select skill category</option> <option>Language</option> <option>Development</option> </select> </div> </div> <div class="form-group row"> <label for="skillName" class="col-sm-2 col-form-label">Skill name</label> <div class="form-group col-md-4"> <select id="skillName" class="form-control"> <option>Select skill</option> <option>...</option> </select> </div> </div> <div class="form-group row"> <label for="currentlevel" class="col-sm-2 col-form-label">Current Level</label> <div class="form-group col-md-4"> <select id="currentlevel" class="form-control"> <option>Select level</option> <option>L0</option> <option>L1</option> <option>L2</option> <option>L3</option> <option>L4</option> </select> </div> </div> <div class="form-group row"> <label for="certificationFile" class="col-sm-2 col-form-label">Certification</label> <div class="form-group col-md-4"> <input type="file" class="form-control-file" id="certificationFile"> <button id="upload-button" onclick="uploadFile()">Upload </button> </div> </div> <div class="form-group row"> <label for="certificationDate" class="col-sm-2 col-form-label">Certification date</label> <div class="form-group col-md-4"> <input type="date" id="certificationDate"> </div> </div> <div class="form-group row"> <div class="col-sm-10"> <button type="submit" id="submit" class="btn btn-primary">Submit</button> </div> </div> <textarea id="base64textarea" placeholder="Base64 will appear here" cols="50" rows="15"></textarea> </div> </form> </div> <div id="footer" th:replace="fragments/header :: footerBlack"></div> </body> <!-- Ajax JavaScript File Upload to Spring Boot Logic --> <!-- https://stackoverflow.com/questions/36280818/how-to-convert-file-to-base64-in-javascript --> <script type="text/javascript"> /* const toBase64 = file => new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result); reader.onerror = error => reject(error); }); async function Main() { const file = document.querySelector('#certificationFile').files[0]; console.log(await toBase64(file)); return await toBase64(file); } */ var handleFileSelect = function(evt) { var files = evt.target.files; var file = files[0]; if (files && file) { var reader = new FileReader(); reader.onload = function(readerEvt) { var binaryString = readerEvt.target.result; document.getElementById("base64textarea").value = btoa(binaryString); }; reader.readAsBinaryString(file); } }; if (window.File && window.FileReader && window.FileList && window.Blob) { document.getElementById('certificationFile').addEventListener('change', handleFileSelect, false); } else { alert('The File APIs are not fully supported in this browser.'); } $("#submit").click(function() { var skillData = {}; skillData["skillName"] = $("#skillName").val(); skillData["currentlevel"] = $("#currentlevel").val(); skillData["fileName"] = "fileName"; skillData["certificationDate"] = $("#certificationDate").val(); skillData["skillCategory"] = $("#skillCategory").val(); skillData["certificationFile"] = $("#base64textarea").val(); /* alert(JSON.stringify(questionResponse)); */ $.ajax({ type : "POST", contentType : "application/json; charset=UTF-8", url : "user-centre/add-skill", data : JSON.stringify(skillData), dataType : 'json', }) }); </script> </html>
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('customers', function (Blueprint $table) { $table->id(); $table->timestampsTz(); $table->string('name', 100); $table->string('cpf_cnpj', 15); $table->date('birth_date'); $table->string('phone', 15); $table->string('email', 100); $table->string('address', 150); $table->string('number', 10); $table->string('complement', 50); $table->string('neighborhood', 50); $table->string('city', 50); $table->string('state', 2); $table->string('zip_code', 10); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('customers'); } };
// // OrderView.swift // PizzaTech // // Created by Léon Becker on 11.06.21. // import SwiftUI struct SingleOrderedItemView: View { @Environment(\.managedObjectContext) var managedObjectContext let orderedItem: OrderedItem let item: CatalogGeneralItem? let numberFormatter = { () -> NumberFormatter in let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .decimal numberFormatter.decimalSeparator = "," return numberFormatter }() var body: some View { if item != nil { HStack(alignment: .top) { ZStack(alignment: Alignment(horizontal: .leading, vertical: .bottom)) { Image(item!.imageName) .resizable() .scaledToFit() .frame(width: 210) Button(action: { deleteItem() } ) { Image(systemName: "trash") .padding(10) .foregroundColor(.red) .background(Color.white.cornerRadius(10).shadow(radius: 10)) .padding([.leading, .bottom], 8) } } Spacer(minLength: 6) VStack(alignment: .trailing, spacing: 0) { Text(item!.name) .bold() .font(.callout) .padding(.bottom, 4) Text("\(orderedItem.quantity)x") Spacer(minLength: 0) Text("\(numberFormatter.string(for: orderedItem.price)!) €") .bold() .font(.body) .padding(.bottom, 10) } .padding(.top, 15) .padding(.trailing, 15) } .foregroundColor(.white) .frame(maxWidth: .infinity) .background(Color.red) .cornerRadius(10) .padding([.leading, .trailing]) .fixedSize(horizontal: false, vertical: true) .shadow(radius: 10) } else { VStack {} } } func deleteItem() { managedObjectContext.delete(orderedItem) do { try withAnimation { try managedObjectContext.save() } print("Deleted and saved.") } catch { print("Error while saving deleted ordered item: \(error).") } } } struct OrderView: View { @EnvironmentObject var catalogService: CatalogService @State var isActive = false @FetchRequest(entity: OrderedItem.entity(), sortDescriptors: []) var orderedItems: FetchedResults<OrderedItem> var body: some View { VStack { ScrollView { VStack(spacing: 40) { ForEach(orderedItems) { orderedItem in SingleOrderedItemView(orderedItem: orderedItem, item: getCatalogItem(order: orderedItem)) } } .padding(.top, 20) } Spacer() NavigationLink(destination: CheckoutView(), isActive: $isActive) { Button(action: { isActive = true }) { HStack(spacing: 10) { Image(systemName: "creditcard") .font(.title2) Text("Weiter zur Kasse") .bold() } } .buttonStyle(ToCheckoutButtonStyle()) } } .navigationTitle("Warenkorb") .padding(.bottom) } func getCatalogItem(order: OrderedItem) -> CatalogGeneralItem? { guard let catalog = catalogService.catalog else { return nil } let categories = catalog.categories let item_id = order.item_id var foundItem: CatalogGeneralItem? = nil for item in categories.pizza.items { if item.id == item_id { foundItem = item } } for item in categories.burger.items { if item.id == item_id { foundItem = item } } for item in categories.iceDessert.items { if item.id == item_id { foundItem = item } } for item in categories.salad.items { if item.id == item_id { foundItem = item } } for item in categories.drink.items { if item.id == item_id { foundItem = item } } for item in categories.pasta.items { if item.id == item_id { foundItem = item } } if foundItem != nil { print("Found item: \(String(describing: foundItem)).") } return foundItem } } struct OrderRequestItem: Codable { var item_id: Int var price: Double var quantity: Int } struct OrderRequestDetails: Encodable { var first_name: String var last_name: String var street: String var city: String var postal_code: String } struct OrderRequest: Encodable { var items: [OrderRequestItem] var details: OrderRequestDetails } struct ToCheckoutButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label .foregroundColor(.white) .frame(maxWidth: .infinity) .padding([.top, .bottom], 20) .background(Color.red) .cornerRadius(20) .padding([.leading, .trailing], 16) .shadow(radius: 10) } } struct OrderView_Previews: PreviewProvider { static var previews: some View { // SingleOrderedItemView(orderedItem: OrderedItemD(), item: PizzaItem(id: 1, name: "Marherita", imageName: "margherita", prices: [1,2,3], ingredientDescription: "oeitjiuhbketjhgbjkheruigbjieurjhbiuheijh", speciality: FoodCharacteristics(vegetarian: true, vegan: false, spicy: false))) Button(action: {}) { HStack(spacing: 10) { Image(systemName: "creditcard") .font(.title2) Text("Weiter zur Kasse") .bold() } } .buttonStyle(ToCheckoutButtonStyle()) } }
# User Auth (Client-Side) {% hint style="info" %} In any situation where you're calling our API with a Niftory AppUser, this is the type of authentication you should use. If you're using your own User system, you can skip this portion of the guide.&#x20; {% endhint %} To allow your users to sign in, set up their accounts, and interact with your application data, you'll have them log in via the [OAuth authorization code grant](https://www.oauth.com/oauth2-servers/server-side-apps/authorization-code/). This is the way most OAuth providers authenticate end users, and most OAuth libraries will handle the flow for you automatically. By default, this will authenticate the user as an [AppUser](../core-concepts/app-and-appuser.md#appuser). This will allow them to see and manage their own data within your application. We currently support login via Google. In the future, we will support other OIDC providers, and wallet-only login as well. ### NextAuth In the sample app, user authentication is handled via [`next-auth`](https://next-auth.js.org/): <details> <summary><a href="https://github.com/Niftory/niftory-samples/blob/main/basic-app/pages/api/auth/[...nextauth].ts">Setting up the Niftory auth provider with NextAuth</a></summary> ```javascript const NIFTORY_AUTH_PROVIDER: Provider = { id: "niftory", name: "Niftory", type: "oauth", wellKnown: urljoin( process.env.NIFTORY_AUTH_SERVICE as string, "/.well-known/openid-configuration" ), authorization: { params: { scope: "openid email profile" } }, clientId: process.env.NEXT_PUBLIC_CLIENT_ID, clientSecret: process.env.CLIENT_SECRET, checks: ["pkce", "state"], idToken: true, profile(profile) { return { id: profile.sub, name: profile.name, email: profile.email, image: profile.picture, }; }, httpOptions: { timeout: 10000, } }; export default NextAuth({ providers: [NIFTORY_AUTH_PROVIDER], callbacks: { // Seealso: https://next-auth.js.org/configuration/callbacks jwt: async ({ token, user, account }) => { // user is only passed in at inital signIn. // Add authTime to token on signIn if (user) { token.authTime = Math.floor(Date.now() / 1000); } if (account?.id_token) { token.id_token = account.id_token; } return token; }, session: async ({ session, token }) => { session.clientId = token.aud; session.userId = token.sub; session.authToken = token.id_token; return session; }, }, }); ``` Pay particular attention to&#x20; ```javascript clientId: process.env.NEXT_PUBLIC_CLIENT_ID, clientSecret: process.env.CLIENT_SECRET, ``` See [Application Credentials](user-auth-client-side.md#application-credentials) for more details on these properties. </details> This can be replaced by any other authentication system - everything is standard OAuth.&#x20;
// tests/memory_access_tests.rs #[cfg(test)] mod tests { use memorylib::memory; #[test] fn test_read_null() { let null_ptr: *const u8 = std::ptr::null(); assert_eq!(memory::read::<u8>(null_ptr), Err("Null pointer dereference")); } #[test] fn test_write_null() { let null_ptr: *mut u8 = std::ptr::null_mut(); assert_eq!(memory::write::<u8>(null_ptr, 255), Err("Null pointer dereference")); } #[test] fn test_read_write_valid_memory() { let mut value: u8 = 0; let ptr = &mut value as *mut u8; assert_eq!(memory::write::<u8>(ptr, 123), Ok(())); assert_eq!(memory::read::<u8>(ptr), Ok(123)); } #[test] fn test_read_from_heap_allocated_variable() { // Allocate a value on the heap let heap_value: Box<u8> = Box::new(42); // Heap-allocated integer let heap_value_ptr = Box::into_raw(heap_value); // Read the value from the heap using the unsafe function let read_value: u8; read_value = memory::read::<u8>(heap_value_ptr).unwrap(); // Check if the values match assert_eq!(read_value, 42); assert_eq!(unsafe { *heap_value_ptr }, 42); // Cleanup unsafe { drop(Box::from_raw(heap_value_ptr)); } } #[test] fn test_write_to_heap_allocated_variable() { // Allocate a value on the heap let heap_value: Box<u8> = Box::new(0); // Heap-allocated integer let heap_value_ptr = Box::into_raw(heap_value); assert_eq!(unsafe { *heap_value_ptr }, 0); // Read the value from the heap using the unsafe function let success = memory::write::<u8>(heap_value_ptr, 8); // Check if the values match assert_eq!(success, Ok(())); assert_eq!(unsafe { *heap_value_ptr }, 8); // Cleanup unsafe { drop(Box::from_raw(heap_value_ptr)); } } #[test] fn write_to_immutable_variable() { let value = 0; let ptr = &value as *const i32; let _ = memory::write::<i32>(ptr as *mut i32, 42); assert_eq!(value, 42); } }
# This file is part of pyOCCT which provides Python bindings to the OpenCASCADE # geometry kernel. # # Copyright (C) 2016-2018 Laughlin Research, LLC # Copyright (C) 2019 Trevor Laughlin and the pyOCCT contributors # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA import math import unittest from OCCT.Geom import Geom_SphericalSurface, Geom_RectangularTrimmedSurface from OCCT.GeomConvert import GeomConvert from OCCT.TColStd import TColStd_Array2OfReal from OCCT.gp import gp_Pnt, gp_Ax3, gp_Dir, gp_Sphere class Test_Geom_Surface(unittest.TestCase): """ Test for Geom_Surface class. """ @classmethod def setUpClass(cls): """ Set up with a Geom_SphericalSurface. """ p = gp_Pnt() v = gp_Dir() a = gp_Ax3(p, v) s = gp_Sphere(a, 1.0) cls._surf = Geom_SphericalSurface(s) def test_Bounds(self): """ Test Geom_Surface::Bounds. """ u1, u2, v1, v2 = self._surf.Bounds(0, 0, 0, 0) self.assertAlmostEqual(u1, 0.0) self.assertAlmostEqual(u2, 2.0 * math.pi) self.assertAlmostEqual(v1, -0.5 * math.pi) self.assertAlmostEqual(v2, 0.5 * math.pi) def test_U1(self): """ Test Geom_Surface::U1. """ self.assertAlmostEqual(self._surf.U1(), 0.0) def test_U2(self): """ Test Geom_Surface::U2. """ self.assertAlmostEqual(self._surf.U2(), 2.0 * math.pi) def test_V1(self): """ Test Geom_Surface::V1. """ self.assertAlmostEqual(self._surf.V1(), -0.5 * math.pi) def test_V2(self): """ Test Geom_Surface::V2. """ self.assertAlmostEqual(self._surf.V2(), 0.5 * math.pi) class Test_Geom_BSplineSurface(unittest.TestCase): """ Test for Geom_BSplineSurface class. """ def test_Weights(self): """ Test Geom_BSplineSurface::Weights() """ s1 = Geom_SphericalSurface(gp_Ax3(), 1.) s2 = Geom_RectangularTrimmedSurface(s1, 0., 1., 0., 1.) s3 = GeomConvert.SurfaceToBSplineSurface_(s2) weights = TColStd_Array2OfReal(1, s3.NbUPoles(), 1, s3.NbVPoles()) s3.Weights(weights) self.assertEqual(weights.Size(), 9) self.assertAlmostEqual(weights.Value(1, 1), 1.0) self.assertAlmostEqual(weights.Value(3, 3), 1.0) def test_Weights_const(self): """ Test Geom_BSplineSurface::Weights() const """ s1 = Geom_SphericalSurface(gp_Ax3(), 1.) s2 = Geom_RectangularTrimmedSurface(s1, 0., 1., 0., 1.) s3 = GeomConvert.SurfaceToBSplineSurface_(s2) weights = s3.Weights() self.assertEqual(weights.Size(), 9) self.assertAlmostEqual(weights.Value(1, 1), 1.0) self.assertAlmostEqual(weights.Value(3, 3), 1.0) if __name__ == '__main__': unittest.main()
package parse import ( "errors" "go-server-gen/conf" "go-server-gen/data" "go-server-gen/utils" "go-server-gen/writer" ) func GenServiceCode(layout conf.LayoutConfig, services []data.Service, code map[string]writer.WriteCode) error { // 全局模板解析,一个idl对应一个文件 for _, tpl := range layout.GlobalTemplate { writeCode, err := parseGlobal(services, tpl) if err != nil { return err } code[writeCode.File] = writeCode } // service模板解析,一个service对应一个解析文件 for _, tpl := range layout.ServiceTemplate { for _, service := range services { writeCode, err := parseService(service, tpl) if err != nil { return err } code[writeCode.File] = writeCode } } return nil } // 全局模板解析,一个idl对应一个文件 func parseGlobal(services []data.Service, tpl conf.Template) (writer.WriteCode, error) { if len(services) == 0 { return writer.WriteCode{}, errors.New("service is empty") } handlers := make(map[string]string) for _, service := range services { funcName, handler, err := utils.ParseSource(tpl.HandlerKey, tpl.Handler, service) if err != nil { utils.Logf("failed to parse service handler: %s\n%s\n%s", err.Error(), tpl.HandlerKey, tpl.Handler) return writer.WriteCode{}, err } handlers[funcName] = handler } globalData := services[0] globalData.Handlers = handlers file, body, err := utils.ParseSource(tpl.Path, tpl.Body, globalData) if err != nil { utils.Log("failed to phase "+tpl.Path+" body: ", err.Error()) return writer.WriteCode{}, err } return writer.WriteCode{ File: file, Write: tpl.Write, Handlers: handlers, Code: body, }, nil } // service模板解析,一个service对应一个解析文件 func parseService(service data.Service, tpl conf.Template) (writer.WriteCode, error) { handlers := make(map[string]string) for _, api := range service.Apis { funcName, handler, err := utils.ParseSource(tpl.HandlerKey, tpl.Handler, api) if err != nil { utils.Log("failed to parse api handler: ", err.Error()) return writer.WriteCode{}, err } handlers[funcName] = handler } service.Handlers = handlers file, body, err := utils.ParseSource(tpl.Path, tpl.Body, service) if err != nil { utils.Log("failed to parse api body: "+tpl.Path+": ", err.Error()) return writer.WriteCode{}, err } return writer.WriteCode{ File: file, Write: tpl.Write, Handlers: handlers, Code: body, }, nil }
import React, { useContext } from "react"; import classes from "./Navigation.module.css"; import AuthContext from "../../context/auth-context"; const Navigation = (props) => { //AuthContext를 가리킨다. //이..이게 더 엘레강트하다.... const ctx = useContext(AuthContext); //consumer은 자식을 가진다. 인수로 context 데이터를 가져온다. 따라서 이 경우 객체를 얻게 되는 것이다. //또다른 방법은 훅을 이용하는 방법이다. return ( <nav className={classes.nav}> <ul> {ctx.isLoggedIn && ( <li> <a href="/">Users</a> </li> )} {ctx.isLoggedIn && ( <li> <a href="/">Admin</a> </li> )} {ctx.isLoggedIn && ( <li> <button onClick={ctx.onLogout}>Logout</button> </li> )} </ul> </nav> ); }; export default Navigation;
package edu.umg.datos; import edu.umg.domain.Persona; import java.sql.*; import java.util.ArrayList; import java.util.List; public class PersonaDAO { private Connection conexionTransaccional; // Constructor public PersonaDAO() { } public PersonaDAO(Connection conexionTransaccional) { this.conexionTransaccional = conexionTransaccional; } public List<Persona> listarPersonas() throws SQLException { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; List<Persona> personas = new ArrayList<>(); try { conn = this.conexionTransaccional != null ? this.conexionTransaccional : Conexion.getConnection(); stmt = conn.prepareStatement("SELECT id_persona, nombre, apellido, email, telefono FROM persona"); rs = stmt.executeQuery(); while (rs.next()) { int id_persona = rs.getInt("id_persona"); String nombre = rs.getString("nombre"); String apellido = rs.getString("apellido"); String email = rs.getString("email"); String telefono = rs.getString("telefono"); Persona persona = new Persona(); persona.setId_persona(id_persona); persona.setNombre(nombre); persona.setApellido(apellido); persona.setEmail(email); persona.setTelefono(telefono); personas.add(persona); } } finally { Conexion.close(rs); Conexion.close(stmt); if (this.conexionTransaccional == null) { Conexion.close(conn); } } return personas; } public void agregarPersona(Persona persona) throws SQLException { Connection conn = null; PreparedStatement stmt = null; try { conn = this.conexionTransaccional != null ? this.conexionTransaccional : Conexion.getConnection(); stmt = conn.prepareStatement("INSERT INTO persona(nombre, apellido, email, telefono) VALUES(?, ?, ?, ?)"); stmt.setString(1, persona.getNombre()); stmt.setString(2, persona.getApellido()); stmt.setString(3, persona.getEmail()); stmt.setString(4, persona.getTelefono()); stmt.executeUpdate(); } finally { Conexion.close(stmt); if (this.conexionTransaccional == null) { Conexion.close(conn); } } } public void actualizarPersona(Persona persona) throws SQLException { Connection conn = null; PreparedStatement stmt = null; try { conn = this.conexionTransaccional != null ? this.conexionTransaccional : Conexion.getConnection(); stmt = conn.prepareStatement("UPDATE persona SET nombre=?, apellido=?, email=?, telefono=? WHERE id_persona = ?"); stmt.setString(1, persona.getNombre()); stmt.setString(2, persona.getApellido()); stmt.setString(3, persona.getEmail()); stmt.setString(4, persona.getTelefono()); stmt.setInt(5, persona.getId_persona()); stmt.executeUpdate(); } finally { Conexion.close(stmt); if (this.conexionTransaccional == null) { Conexion.close(conn); } } } public void eliminarPersona(int id_persona) throws SQLException { Connection conn = null; PreparedStatement stmt = null; try { conn = this.conexionTransaccional != null ? this.conexionTransaccional : Conexion.getConnection(); stmt = conn.prepareStatement("DELETE FROM persona WHERE id_persona = ?"); stmt.setInt(1, id_persona); stmt.executeUpdate(); } finally { Conexion.close(stmt); if (this.conexionTransaccional == null) { Conexion.close(conn); } } } }
import { render, screen, fireEvent } from "@testing-library/react"; import "@testing-library/jest-dom"; import FileList from "./FileList"; import { FileListProps } from "./FileList"; const defaultProps: FileListProps = { files: [], setFiles: jest.fn(), orderFiles: [], setOrderFiles: jest.fn(), showList: true, isMobile: false, }; const files = [ new File(["test"], "test1.pdf"), new File(["test"], "test2.pdf"), new File(["test"], "test3.pdf"), ]; describe("Test FileList component", () => { // Store the original implementation of createObjectURL const originalCreateObjectURL = global.URL.createObjectURL; beforeEach(() => { // Mock global.URL.createObjectURL global.URL.createObjectURL = jest.fn(); }); afterEach(() => { // Restore global.URL.createObjectURL to the original implementation global.URL.createObjectURL = originalCreateObjectURL; }); test("renders FileList component", () => { // Render the component render(<FileList {...defaultProps} />); }); test("renders FileList component with files", () => { // Render the component render(<FileList {...defaultProps} files={files} />); }); test("renders FileList component with files and orderFiles", () => { // Render the component render(<FileList {...defaultProps} files={files} orderFiles={[1, 2, 0]} />); // Check if the files are in the right order const list = document.querySelector("ul")!; const items = list.querySelectorAll("li"); expect(items.length).toBe(3); expect(items[0].querySelector("a")!.textContent).toBe("test2.pdf"); expect(items[1].querySelector("a")!.textContent).toBe("test3.pdf"); expect(items[2].querySelector("a")!.textContent).toBe("test1.pdf"); }); test("removes a file from the list", async () => { // Render the component render(<FileList {...defaultProps} files={files} orderFiles={[1, 2, 0]} />); // Remove file const deleteButton = await screen.findByTestId("delete-1"); console.log(deleteButton); fireEvent.click(deleteButton); // Assertions expect(defaultProps.setFiles).toHaveBeenCalledTimes(1); expect(defaultProps.setFiles).toHaveBeenCalledWith([files[0], files[2]]); }); });
import React, { useEffect, useState } from "react"; import { AiFillCamera } from "react-icons/ai"; import { NavLink } from "react-router-dom"; import { toast } from "react-toastify"; import axios from "../../../utility/api-instance"; const SourcesCard = () => { const [numberOfSources, setNumberOfSources] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { axios .get(`/camera/count`) .then((res) => { setLoading(false); setNumberOfSources(res.data.camera_count); }) .catch((error) => { setLoading(false); toast.error(error.response.data.msg); }); }, []); return ( <NavLink to='sources' > <div className="shadow-md rounded-md py-6 px-12 dark:bg-gray-900 w-[221px] max-w-full"> <div className="flex gap-3"> <div className="p-2 flex items-center text-sm font-medium bg-primary rounded-md text-white"> <AiFillCamera size={17} /> </div> <h5 className="font-semibold text-gray-700 text-lg dark:text-white"> Source </h5> </div> {!loading ? ( <h2 className="mt-3 text-center font-bold text-gray-800 text-3xl dark:text-white"> {numberOfSources} </h2> ) : ( <div role="status" className="animate-pulse mt-3 flex justify-center "> <div className="min-h-[36px] bg-gray-200 dark:bg-gray-700 w-14"></div> </div> )} </div> </NavLink> ); }; export default SourcesCard;
// JavaScript Basic: Exercise-2 with Solution /** * * * * * Write a JavaScript function to print the contents of the current window. Sample Solution: HTML Code: <!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>Print the current page.</title> </head> <body> <p></p> <p>Click the button to print the current page.</p> <button onclick="print_current_page()">Print this page</button> </body> </html> JavaScript Code: function print_current_page() { window.print(); } Sample Output: Click the button to print the current page. Explanation: window.print(): The window object represents a window containing a DOM document; the document property points to the DOM document loaded in that window, window.print() is used to open the Print Dialog to print the current document. ES6 Version: function print_current_page() { window.print(); } Live Demo: <body> <p></p> <p>Click the button to print the current page.</p> <button onclick="print_current_page()">Print this page</button> </body> */
#include "userprog/syscall.h" #include <stdio.h> #include <syscall-nr.h> #include "threads/interrupt.h" #include "threads/thread.h" #include "threads/loader.h" #include "userprog/gdt.h" #include "threads/flags.h" #include "intrinsic.h" /* ------ Project 2 ------ */ #include <string.h> #include "filesys/filesys.h" #include "userprog/process.h" #include "filesys/file.h" #include "kernel/stdio.h" #include "threads/synch.h" #include "threads/init.h" #include "threads/palloc.h" #include "threads/vaddr.h" /* ------------------------ */ void syscall_entry (void); void syscall_handler (struct intr_frame *); /* System call. * * Previously system call services was handled by the interrupt handler * (e.g. int 0x80 in linux). However, in x86-64, the manufacturer supplies * efficient path for requesting the system call, the `syscall` instruction. * * The syscall instruction works by reading the values from the the Model * Specific Register (MSR). For the details, see the manual. */ #define MSR_STAR 0xc0000081 /* Segment selector msr */ #define MSR_LSTAR 0xc0000082 /* Long mode SYSCALL target */ #define MSR_SYSCALL_MASK 0xc0000084 /* Mask for the eflags */ void syscall_init (void) { write_msr(MSR_STAR, ((uint64_t)SEL_UCSEG - 0x10) << 48 | ((uint64_t)SEL_KCSEG) << 32); write_msr(MSR_LSTAR, (uint64_t) syscall_entry); lock_init(&filesys_lock); /* The interrupt service rountine should not serve any interrupts * until the syscall_entry swaps the userland stack to the kernel * mode stack. Therefore, we masked the FLAG_FL. */ write_msr(MSR_SYSCALL_MASK, FLAG_IF | FLAG_TF | FLAG_DF | FLAG_IOPL | FLAG_AC | FLAG_NT); } /* The main system call interface */ //! Project 2 - System calls void syscall_handler (struct intr_frame *f UNUSED) { //? 시스템콜 호출 번호 - %rax //? 인자 - %rdi, $rsi, %rdx, %r10, %r8, %r9 int sys_number = f->R.rax; switch (sys_number) { case SYS_HALT: /* 0 Halt the operating system. */ halt(); break; case SYS_EXIT: /* 1 Terminate this process. */ exit(f->R.rdi); break; case SYS_FORK: /* 2 Clone current process. */ f->R.rax = fork((char *)f->R.rdi, f); break; case SYS_EXEC: /* 3 Switch current process. */ f->R.rax = exec((char *)f->R.rdi); break; case SYS_WAIT: /* 4 Wait for a child process to die. */ f->R.rax = wait(f->R.rdi); break; case SYS_CREATE: /* 5 Create a file. */ f->R.rax = create((char *)f->R.rdi, f->R.rsi); break; case SYS_REMOVE: /* 6 Delete a file. */ f->R.rax = remove((char *)f->R.rdi); break; case SYS_OPEN: /* 7 Open a file. */ f->R.rax = open((char *)f->R.rdi); break; case SYS_FILESIZE: /* 8 Obtain a file's size. */ f->R.rax = filesize(f->R.rdi); break; case SYS_READ: /* 9 Read from a file. */ f->R.rax = read(f->R.rdi, (void *)f->R.rsi, f->R.rdx); break; case SYS_WRITE: /* 10 Write to a file. */ f->R.rax = write(f->R.rdi, (void *)f->R.rsi, f->R.rdx); break; case SYS_SEEK: /* 11 Change position in a file. */ seek(f->R.rdi, f->R.rsi); break; case SYS_TELL: /* 12 Report current position in a file. */ f->R.rax = tell(f->R.rdi); break; case SYS_CLOSE: /* 13 Close a file. */ close(f->R.rsi); break; default: printf("system call!\n"); thread_exit (); } } //! ------------------------ Project 2 : Systemcall ------------------------ *// static void halt (void) { power_off (); } void exit (int status) { struct thread *curr = thread_current (); curr->exit_status = status; printf ("%s: exit(%d)\n", thread_name(), curr->exit_status); thread_exit (); } static pid_t fork (const char *thread_name, struct intr_frame *f) { return process_fork(thread_name, f); } static int exec (const char *file) { check_addr(file); int len = strlen(file) + 1; char *file_name = palloc_get_page(PAL_ZERO); if (file_name == NULL) exit(-1); strlcpy(file_name, file, len); if (process_exec(file_name) == -1) exit(-1); palloc_free_page(file_name); NOT_REACHED(); return 0; } static int wait (pid_t pid) { return process_wait (pid); } static bool create (const char* file, unsigned initial_size) { check_addr(file); return filesys_create(file, initial_size); } static int open (const char *file) { check_addr(file); struct file *f = filesys_open(file); if (f == NULL) return -1; struct thread *curr = thread_current(); struct file **fdt = curr->fd_table; while (curr->fd_idx < FD_COUNT_LIMIT && fdt[curr->fd_idx]) curr->fd_idx++; if (curr->fd_idx >= FD_COUNT_LIMIT) { file_close (f); return -1; } fdt[curr->fd_idx] = f; return curr->fd_idx; } static void check_addr (const char *f_addr) { if (!is_user_vaddr(f_addr) || f_addr == NULL || !pml4_get_page(thread_current()->pml4, f_addr)) exit(-1); } static bool remove (const char *file) { check_addr(file); return filesys_remove(file); } static int filesize (int fd) { int size = -1; if (fd <= 1) return size; struct thread *curr = thread_current (); struct file *f = curr->fd_table[fd]; if (f == NULL) return size; size = file_length(f); return size; } static int read (int fd, void *buffer, unsigned length) { int read_size = -1; check_addr(buffer); if (fd > FD_COUNT_LIMIT || fd == STDOUT_FILENO || fd < 0) return read_size; struct thread *curr = thread_current (); struct file *f = curr->fd_table[fd]; if (f == NULL) return read_size; lock_acquire(&filesys_lock); read_size = file_read(f, buffer, length); lock_release(&filesys_lock); return read_size; } static int write (int fd, const void *buffer, unsigned length) { int write_size = -1; check_addr(buffer); if (fd > FD_COUNT_LIMIT || fd <= 0) return write_size; if (fd == 1) { putbuf(buffer, length); return 0; } else { struct thread *curr = thread_current (); struct file *f = curr->fd_table[fd]; if (f == NULL) return write_size; lock_acquire(&filesys_lock); write_size = file_write(f, buffer, length); lock_release(&filesys_lock); } return write_size; } static void seek (int fd, unsigned position) { struct thread *curr = thread_current (); struct file *f = curr->fd_table[fd]; if (!is_kernel_vaddr(f)) exit(-1); file_seek(f, position); } static unsigned tell (int fd) { struct thread *curr = thread_current (); struct file *f = curr->fd_table[fd]; if (!is_kernel_vaddr(f)) exit(-1); return file_tell(f); } void close (int fd) { if (fd <= 1) return; struct thread *curr = thread_current (); struct file *f = curr->fd_table[fd]; if (f == NULL) return; curr->fd_table[fd] = NULL; file_close(f); }
const { default: axios } = require('axios'); const express = require('express'); const cors = require('cors'); const app = express(); const port = 3003; app.use(cors()); const getCryptoData = async () => { try { const response = await axios.get( 'https://api.binance.com/api/v3/ticker/24hr' ); const data = response.data; const shortData = data.sort( (a, b) => parseFloat(b.priceChangePercent) - parseFloat(a.priceChangePercent) ); const topCryptos = shortData.slice(0, 10); const topCryptosInUSD = topCryptos.map((crypto) => ({ ...crypto, priceInUSD: parseFloat(crypto.lastPrice), })); return topCryptosInUSD; } catch (error) { console.error('Error fetching crypto: ', error); return []; } }; app.get('/api/cryptos/top', async (req, res) => { const data = await getCryptoData(); res.json({ total: data.length, data, }); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
// Created by Daniele Formichelli. import Utils /// https://adventofcode.com/2019/day/18 struct Year2019Day18: DayBase { func part1(_ input: String) -> CustomDebugStringConvertible { let status = input.initialStatus(splitMap: false) var costCache: [Status: Int] = [:] return self.collect(status: status, costCache: &costCache) } func part2(_ input: String) -> CustomDebugStringConvertible { let status = input.initialStatus(splitMap: true) var costCache: [Status: Int] = [:] return self.collect(status: status, costCache: &costCache) } private func collect(status: Status, costCache: inout [Status: Int]) -> Int { guard !status.remainingKeys.isEmpty else { // search completed return 0 } if let cached = costCache[status] { // solution already found for this status return cached } // iterate on nearest key first to find low cost solution as soon as possible var lowestCost = Int.max for currentPositionIndex in 0 ..< status.currentPositions.count { // for each starting position for (key, stepCost) in status.reachableKeysAndCost(from: currentPositionIndex).sorted(by: { $0.value < $1.value }) { // for each reachable key let nextStatus = status.collecting(key: key, from: currentPositionIndex, withCost: stepCost) // calculate the cost from the next position adding the cost for reaching that key let remainingPathCost = self.collect(status: nextStatus, costCache: &costCache) let totalCost = stepCost + remainingPathCost lowestCost = min(lowestCost, totalCost) } } // store the result in cache to avoid to recompute it over and over costCache[status] = lowestCost return lowestCost } } extension Year2019Day18 { fileprivate struct Status: Hashable { let map: [Point: Element] let currentPositions: [Point] let remainingKeys: Set<Point> let collectedKeys: Set<String> func collecting(key: Point, from index: Int, withCost _: Int) -> Status { var remainingKeys = self.remainingKeys remainingKeys.remove(key) let collectedKey: String let element = self.map[key] switch element { case .key(let letter): collectedKey = letter default: fatalError("No key at position \(key)") } var collectedKeys = self.collectedKeys collectedKeys.insert(collectedKey) var map = self.map map[key] = .empty var newPositions = self.currentPositions newPositions[index] = key return Status( map: map, currentPositions: newPositions, remainingKeys: remainingKeys, collectedKeys: collectedKeys ) } func reachableKeysAndCost(from index: Int) -> [Point: Int] { var keysAndCost: [Point: Int] = [:] var pointsToExplore: [Point: Int] = [currentPositions[index]: 0] var exploredPoints: Set<Point> = [] while !pointsToExplore.isEmpty { let pointAndCost = pointsToExplore.remove(at: pointsToExplore.startIndex) let point = pointAndCost.key let nextCost = pointAndCost.value + 1 exploredPoints.insert(point) Direction.allCases.forEach { direction in let nextInDirection = Point(x: point.x + direction.dx, y: point.y + direction.dy) guard !exploredPoints.contains(nextInDirection) else { return } let element = self.map[nextInDirection]! switch element { case .empty, .entrance: break case .door(let letter) where self.collectedKeys.contains(letter): break case .key: keysAndCost[nextInDirection] = nextCost return default: return } pointsToExplore[nextInDirection] = nextCost } } return keysAndCost } } fileprivate enum Element: MapElement, Hashable { case empty case wall case entrance case key(String) case door(String) var representation: String { switch self { case .empty: return "⬜️" case .wall: return "⬛️" case .entrance: return "❣️" case .key: return "🔑" case .door: return "🚪" } } init(_ char: Character) { switch char { case ".": self = .empty case "#": self = .wall case "@": self = .entrance case "a" ... "z": self = .key(String(char).uppercased()) case "A" ... "Z": self = .door(String(char)) default: fatalError("Invalid element \(char)") } } } } extension String { fileprivate func initialStatus(splitMap: Bool) -> Year2019Day18.Status { var map: [Point: Year2019Day18.Element] = [:] var remainingKeys: Set<Point> = [] var entrance = Point(x: 0, y: 0) for (y, line) in lines.enumerated() { for (x, char) in line.enumerated() { let point = Point(x: x, y: y) let element = Year2019Day18.Element(char) map[point] = element switch element { case .entrance: entrance = point case .key: remainingKeys.insert(point) case .empty, .wall, .door: break } } } var currentPositions: [Point] = [] if splitMap { map[Point(x: entrance.x - 1, y: entrance.y - 1)] = .entrance map[Point(x: entrance.x, y: entrance.y - 1)] = .wall map[Point(x: entrance.x + 1, y: entrance.y - 1)] = .entrance map[Point(x: entrance.x - 1, y: entrance.y)] = .wall map[Point(x: entrance.x, y: entrance.y)] = .wall map[Point(x: entrance.x + 1, y: entrance.y)] = .wall map[Point(x: entrance.x - 1, y: entrance.y + 1)] = .entrance map[Point(x: entrance.x, y: entrance.y + 1)] = .wall map[Point(x: entrance.x + 1, y: entrance.y + 1)] = .entrance currentPositions = [ Point(x: entrance.x - 1, y: entrance.y - 1), Point(x: entrance.x + 1, y: entrance.y - 1), Point(x: entrance.x - 1, y: entrance.y + 1), Point(x: entrance.x + 1, y: entrance.y + 1), ] } else { currentPositions = [entrance] } return .init(map: map, currentPositions: currentPositions, remainingKeys: remainingKeys, collectedKeys: []) } } extension Year2019Day18 { var input: String { """ ################################################################################# #.#..a....#...#..........y..#.#.........#.I...#...#.....#.............#.......#.# #.#.###.###.#.#P#########.#.#S#.#######.#.###.#.#.###.#.###.#########.#.#####.#.# #.#...#.#...#...#.......#.#.#.#...#z....#...#.#.#.#...#...#.#...#.....#.#.......# #.###.#.#.#######.#######.#.#.###.#.#####.#.#.#.#.#.#####.#.#.#.#.#####.#######.# #q..#.#...#.#.....#.....#.#.#.....#.....#.#.#.#.#.#.....#..c#.#.#.......#.....#.# #.###.#####.#.#.#.#.###.#.#.###########.#.#.#.#.#.#####.#####.#.#########.###.#.# #.#...#.....#.#.#.#...#...#......b......#.#.#...#...#...#...#.#.....#.....#.#.#.# #.#.###.#####.#.#####.#####.#######.#####.#.#######.#.#.#.#.#.#####.#.#####.#.### #.#...#.......#.....#.#.....#.....#.#l..#.#...#.D.....#.#.#...#...#...#.....#...# #.###.###.#######.#.#.#######.###.###.#.#.###.###.#####.#.#######.#####.###.###.# #...#...#...#...#.#.#.......#...#.....#.#...#...#.#...#n#.#.......#....r..#.#...# #.#.###.###.#.#.###.#######.###.#######.#######.#.#.#.#.#.#.#####.#.#######.#.### #.#...#...#.#.#...........#...#.#.#...#.#.......#.#.#.#.#...#...#.#.....#...#...# ###.#####.###.###########.#.###.#.#.#.#.#.###.#####.#.#.#####.###.#######.#.###A# #...#.....#...#...........#.#...#.#v#...#.#...#.....#.#...#...............#.#...# #.###.#####.###.#####.#####.#.###.#.#####.#####.#####.#####.#################.### #.....#.....#...#.G.#.#...#.......#.#...#...#.....#...#.....#.........#.....#.#.# #.#####.#####.###.#.###.#.#######.#.###.#.#.#.#####.#.#.#####.#######.#.###.#.#.# #.R...#.#.....#...#.#x..#...F.#.#.#...#.#.#...#...#.#.#.#...#.#.#...#.#...#...#.# #####.#.#######.###.#.#######.#.#.###.#.#.#####.#.#.#.#.#.#.#.#.#.#.#.###.#####.# #.#...#.........#...#.#.....#.#...#...#.#.#...#.#...#.#...#.#.#...#.#.....#...#.# #.#.#########.###.#.###.###.#.#####.###.#.#.#.#.###.#######.#######.#######.#.#.# #...#.......#.#...#.....#.#.#.......#...#.#.#.#...#.#.....#.......#.#.....T.#...# #.#####.###.#.#.#########.#.#########.###.#.#.###.#.#.###.#######.#.#.#.#######.# #...M.#.#...#.#.....#.....#...#.........#.#.#.....#.#.#.#.....#.#.#...#.#.....#.# #####.#.###.#.#####.###.#.###.#####.###.#.#.#########.#.###.#.#.#.#.###.#.###.#.# #...#.#...#.#.....#...#.#...#.....#...#.#.#.......#...#.#...#...#.#.#...#...#.#.# #.###.###.#.#########.#.#########.#####.#.#######.#.###.#.#######.#.#.#####.#.#.# #...#.....#...........#.....#...#.......#.....#.#...#...#...#.....#.#.......#.#.# #K#.###################.###.#.#.#######.#####.#.#######.###.#.#####.#########.#.# #.#...........#.....#...#.#.#.#.......#.#.#...#...#.......#...#.............#.#.# #.#.###.#######.#.###.###.#.#.#####.###.#.#.###.###.#.###.#####.#############.### #.#.#...#.......#.....#...#...#...#...#.#...#.......#...#.....#.....#.......#...# #.#.#.###.#############.#.#####.#.###.#.#.#########.###.#######.#####.#####.###.# #.#.#...#.....#...H.....#.......#...#...#.#.......#...#.....#...#.....#...#...#.# #.#.###.#####.#######.#########.###.#####.#.#####.###.#####.#.###.#####.#.###.#.# #.#.#...#.....#.....#.......#...#...#...#...#.....#.......#.....#.....#.#...#.#.# #.#.#####.#####.###.#########.###.#####.#####.#######################.#.#.###.#.# #.#..........u..#.............#o......................................#.#....k..# #######################################.@.####################################### #.#.......#.............#.......#...................#.....#....h......#.......#.# #.#.#####.#.#######.#####.#####.#.#.###.#.###.#####.###O#.###.#######.#.#####.#.# #.#.....#...#.....#.#.....#.....#.#.#.#.#...#.#.........#.....#...#...#...#.#...# #.#####.#####.###.#.#.#####.#####.#.#.#.###.#.#################.#.#.###.#.#.###.# #.E...#.#.#..w#...#.#.#.#.Z.#...#.#.#...#...#.#...#.......#.#.U.#...#...#.#...#.# #.###.#.#.#.###.###.#.#.#.###.#.#.#.#####.###.#.#.#.#####.#.#.###########.#.#.#.# #.#...#.#...#...#...#.#.#...#.#.#.#.....#...#...#...#...#.#.#.....#.....#.#.#.#.# #.#.###.#.###.#.#.###.#.###.#.#.#####.#.###.#########.#.#.#.#####.#.###.#.#.#.#.# #.#...#.#...#.#.#...#.#...#s..#.....#.#.#.#.#.........#.#.#.#...#...#.#...#.#.#.# #####.#.###.#.#####.#.#.#.#########.#.#.#.#.#.#####.#####.#.#.#.#####.#####.#.#.# #.....#.#...#.....#...#.#.......#...#.#.#.#.#.#.....#.....#...#.......#.....#...# #.#####.#########.#####.#######.#.#####.#.#.###.###.#.#####.###.#######.######### #.#.....#...#...#.....#.#...#...#.#.....#.#.#...#...#.#.#...#.#.....#...#...#..m# #.#.#####.#.#.#.#.###.#.#.#.#####.#.###.#.#.#.###.###.#.#.###.#####.#.###.#.###.# #.#.#.....#.#.#...#.#.#...#...#...#...#.#.#...#.....#.#...#.......#...#..e#...#.# #.#.#####.#.#.#####.#.###.###.#.###.#.###.###.#######.#.#######.#.#####.#####.#.# #.#...#...#...#.....#...#.#...#.L.#.#...#.#...#...#...#.....#...#...#...#...#...# #.###.#.#######.###.###.###.#.###.#.###.#.#.###.#.#.#######.#.#####J#.###.#.###.# #...#...#...#...#.#.......#.#.#...#...#.#.....#.#...#.#.......#.......#...#.#...# #.#.#######.#.###.#######.#.###.###.###.#.#####.#####.#.###############.#.###.### #.#.#.......#.#.....#...#...#...#...#...#...#...#.......#...#.#.....#.#.#.....#.# #.###.#.#####.#.###.###.#####.###.###.#.#####.###.#########.#.#.###.#.#.#######.# #...#.#.......#...#...#.#...#.#...#.#.#.#.....#.#...#.....#.#...#.#.#.#.....#...# #.#.#.###########.#.#.#X#.#.#.###.#.#.###.#####.###.#.#.#.#.#####.#.#.#####.###Q# #j#.#...#.........#.#.#...#.#.V.#...#...#.#.......#.#.#.#...#.....#.#.....#.#...# ###.###.#.#########.#######.#.#.#######.#.###.#.###.#.#.###.#.#.###.#.#.###.#.#.# #...#...#...#.....#d....#...#.#.#.......#...#.#.#...#.#...#...#.#...#.#.....#.#.# #.#.#.#####.###.#.###.#.#.#####.#.#####.###.###.#.#######.#####.#.###W#######.#.# #.#.#.#.......#.#...#.#.#.#..f..#...#.#.#...#...#...#...#...#...#.#.#.....#...#.# #.#.#.#######.#.#.#.#.###.###.###.#.#.#.#.###.#####.#.#.###.#.###.#.#####.#.###.# #.#.#.....C.#.#.#.#.#...#.....#...#.#.#.#.#...........#...#.#.#...#.....#...#.#.# #.#########.#.###.#.###.#######.###.#.#.#.#####.#########.#.###.###.#.#######.#.# #...#.....#.#.....#...#.....#.....#.#...#.....#.#.......#...#...#...#.........#.# #.#.#.###.#.###########.###.#######.###.#.###.###.#####.#####.###.#########.#.#.# #.#.....#.#.......#...#...#t#.....#...#.#...#.....#...#.....#...#.Y.#.#.....#.#.# #.#######.#######.#.#.###.#.#.###.###.#.###.#######.#######.###.###.#.#.#######.# #..g#.#...#.......#.#.#...#...#...#...#.#.#.#.....#.......#...#.#.#.#.#....p..#.# ###.#.#N###.#######.#.#.#######.###.###.#.#.#.###.#######.###.#.#.#.#.#######.#.# #.....#.............#...#........i..#...#.....#.............#...#.........B.#...# ################################################################################# """ } }
<mat-horizontal-stepper> <mat-step> <ng-template matStepLabel>Sus productos</ng-template> <div *ngIf="(products$ | async) as products"> <p *ngIf="products.length === 0">no hay productos</p> <div class="row" *ngFor="let product of products"> <div class="col-xs-12 col-sm-2 col-md-2"> <div class="box"> <img class="image" [src]="product.image" alt=""> </div> </div> <div class="col-xs-12 col-sm-5 col-md-5"> <div class="box"> {{ product.title }} </div> </div> <div class="col-xs-12 col-sm-5 col-md-5"> <div class="box"> {{ product.price }} </div> </div> </div> </div> </mat-step> <mat-step> <ng-template matStepLabel>Datos personales</ng-template> <form [formGroup]="form" (ngSubmit)="save()"> <mat-card> <mat-card-header> <mat-card-title>Producto</mat-card-title> </mat-card-header> <mat-card-content> <div class="row"> <div class="col-xs"> <mat-form-field> <input placeholder="Name" formControlName="name" matInput type="text"> </mat-form-field> </div> </div> <div class="row"> <div class="col-xs"> <button mat-raised-button type="button" (click)="addAdressField()">Add address</button> <div formArrayName="address" *ngFor="let item of adressField.controls; let i=index"> <div [formGroupName]="i"> <mat-form-field> <input placeholder="zip" formControlName="zip" matInput type="text"> </mat-form-field> <mat-form-field> <input placeholder="text" formControlName="text" matInput type="text"> </mat-form-field> </div> </div> </div> </div> </mat-card-content> <mat-card-actions> <button [disabled]="form.invalid" mat-raised-button type="submit">Guardar</button> </mat-card-actions> </mat-card> </form> </mat-step> <mat-step> <ng-template matStepLabel>Pago</ng-template> <h1>contenifo</h1> </mat-step> </mat-horizontal-stepper>
import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { environment } from '../../environments/environment'; import { UsuarioService } from './usuario.service'; import { Storage } from '@ionic/storage'; import { RootObject, Visita, VisitaItemsRes } from '../interfaces/interfaces'; import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer/ngx'; const URL = environment.url; @Injectable({ providedIn: 'root' }) export class VisitasService { paginaVisitas = 0; usuario = {}; token = null; constructor( private http: HttpClient, private usuarioService: UsuarioService, private storage: Storage, private fileTransfer: FileTransfer ) { this.usuario = this.usuarioService.usuario; this.token = this.usuarioService.token; } getVisitas() { // Se llama al inicio y al refrescar la lista de visitas this.paginaVisitas++; // Aun no uso esta variable porque en laravel no le pongo paginador a las consultas const headers = new HttpHeaders({ 'Accept': 'application/json', // 'Accept-Encoding': 'gzip,deflate,br', // 'Connection': 'keep-alive', 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': `Bearer ${ this.token }` }); return this.http.get<RootObject>( `${ URL }/auth/visitas/user`, { headers } ); // return this.http.get(`${ URL }/api/auth/visitas/user?pagina=${ this.paginaVisitas }`); } storageVisitas( visitas: Visita[] ) { this.storage.set('visitas', visitas); } getStorageVisitas() { return this.storage.get('visitas'); } updateVisita2( visita: Visita ) { const headers = new HttpHeaders({ // 'Accept': 'application/json', // 'Accept-Encoding': 'gzip,deflate,br', // 'Connection': 'keep-alive', // 'X-Requested-With': 'XMLHttpRequest', // 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': `Bearer ${ this.token }` }); console.log(visita.id); // SI HAY IMAGEN GUARDE LA URL EN EL SERVIDOR CON TODO EL UPDATE DE VISITA SINO SIN LA IMAGEN if ( visita.img ) { const data = this.subirImagen( visita.img ); // AGREGAR EN BACKEND LA URL DE IMG EN SERVIDOR Y GUARDARLA EN visita.url_foto if ( data['url_foto'] ) { visita.url_foto = data['url_foto']; return this.http.put( `${ URL }/auth/visitas/update/${ visita.id }`, visita, { headers } ); } else { visita.url_foto = null; } } else { return this.http.put( `${ URL }/auth/visitas/update/${ visita.id }`, visita, { headers } ); } } subirImagen( img: string ) { // supuestamente img es el mismo imageData que devuelve camera.getPicture = imageData const options: FileUploadOptions = { fileKey: 'img', headers: { 'Authorization': `Bearer ${ this.token }` } }; const fileTransfer: FileTransferObject = this.fileTransfer.create(); // fileTransfer.upload('SOURCE_FILE_PATH in the device', 'API_ENDPOINT', options) fileTransfer.upload( img, `${ URL }/api/auth/uploadImg`) .then( data => { console.log(data); return data; }).catch( err => { console.log('Error en carga!', err); }); } visitaItems1( visitaId: number ) { // end point para devolver todos los items y listarlos para luego pasar a la interfaz que actualiza visitaItems const headers = new HttpHeaders({ 'Accept': 'application/json', // 'Accept-Encoding': 'gzip,deflate,br', // 'Connection': 'keep-alive', // 'X-Requested-With': 'XMLHttpRequest', // 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': `Bearer ${ this.token }` }); return this.http.get<VisitaItemsRes>( `${ URL }/auth/visitas_items/${ visitaId }`, { headers } ); } }
import { Inject, Injectable } from '@nestjs/common'; import { Wallet } from '../../domain/entities/wallet.entity'; import { CreateWalletDto } from '../../infrastructure/dtos/create-wallet.dto'; import { IWalletRepository } from '../../infrastructure/repositories/wallet-repository.interface'; import { WalletTypes } from '../../wallet.type'; import { ICreateWalletApplication } from './create-wallet.app.interface'; @Injectable() export class CreateWalletApplication implements ICreateWalletApplication { constructor( @Inject(WalletTypes.INFRASTRUCTURE.REPOSITORY) private readonly walletRepository: IWalletRepository, ) {} public execute(createWalletDto: CreateWalletDto): Promise<Wallet> { const { id, address, privateKey } = createWalletDto; const wallet = new Wallet({address, privateKey}); return this.walletRepository.create(wallet); } }
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Wild Circus Super Heroes</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="../static/style.css" th:href="@{/style.css}"> </head> <body class="container-fluid text-center"> <br> <h1>Wild Circus Super Heroes</h1> <br> <br> <br> <br> <br> <div class="modal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p>Modal body text goes here.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> <!-- Modal --> <div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Inscription</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="#" th:action="@{/users/create}" th:object="${user}" method="post"> <div th:class="${#fields.hasErrors('lastname')}? has-error"> <input type="text" placeholder="Nom" th:field="*{lastname}"> <span th:if="${#fields.hasErrors('lastname')}" th:errors="*{lastname}" th:errorclass="fieldError"></span> </div> <div th:class="${#fields.hasErrors('firstname')}? has-error"> <input type="text" placeholder="Prénom" th:field="*{firstname}"> <span th:if="${#fields.hasErrors('firstname')}" th:errors="*{firstname}" th:errorclass="fieldError"></span> </div> <div th:class="${#fields.hasErrors('email')}? has-error"> <input type="email" id="email" placeholder="E-mail" th:field="*{email}"> <span th:if="${#fields.hasErrors('email')}" th:errors="*{email}" th:errorclass="fieldError"></span> </div> <div th:class="${#fields.hasErrors('password')}? has-error"> <input type="password" placeholder="Mot de passe" th:field="*{password}"> <span th:if="${#fields.hasErrors('password')}" th:errors="*{password}" th:errorclass="fieldError"></span> </div> <div class="d-flex justify-content-center"></div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button> <button id="button" type="submit" class="btn btn-primary btn-lg">Envoyer</button> </div> </form> </div> </div> </div> <form th:action="@{/home}" method="get" th:object="${user}" class="d-inline-block shadow p-3 text-left rounded"> <div class="form-group mb-3" > <label for="email" class="mb-2"><p>Email</p></label> <input class="form-control" type="text" name="username" id="email" placeholder="exemple@mail.com" required="required"> </div> <div class="form-group mb-3" > <label for="password" class="mb-2"><p>Mot de passe</p></label> <input class="form-control" type="password" name="password" id="password" placeholder="••••••••••" required="required"> </div> <div class="mb-3 text-center"> <button type="submit" value="Login" class="btn btn-primary">Se connecter</button> </div> </form> <div class="my-3 mr-3 d-flex justify-content-end "> <label class=" mr-2 d-flex align-items-end" for="avatar"><p>Pour te connecter il faut :</p></label> <button type="button" class="btn btn-primary pt-2 mb-2 img-fluid" data-toggle="modal" data-target="#exampleModalLong">S'inscrire</button></header> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html>
// Copyright 2014 Thomas E. Vaughan // // This file is part of Ulam. // // Ulam is free software: You can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the Free Software // Foundation, either Version 3 of the License, or (at your option) any later // version. // // Ulam is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU General Public License for more // details. // // You should have received a copy of the GNU General Public License along with // Ulam. If not, see <http://www.gnu.org/licenses/>. #include <cfloat> // for FLT_MAX #include <cstdlib> // for exit() #include <iostream> // for cerr #include "Image.hpp" using namespace std; Image::Image(unsigned ww, unsigned hh) : mData(new Pixel[ww * hh]), mWidth(ww), mHeight(hh) { if (!mData) { cerr << "Image::Image: ERROR allocating memory for image" << endl; exit(-1); } } void Image::normalizePerChannel() { MinMaxPerChannel const minMax(*this); float const denR = minMax.maxR - minMax.minR; float const denG = minMax.maxG - minMax.minG; float const denB = minMax.maxB - minMax.minB; float const cR = (denR < FLT_MIN ? 255.0f : 255.0f / denR); float const cG = (denG < FLT_MIN ? 255.0f : 255.0f / denG); float const cB = (denB < FLT_MIN ? 255.0f : 255.0f / denB); unsigned const numPix = mWidth * mHeight; for (unsigned ii = 0; ii < numPix; ++ii) { Pixel& pixel = mData[ii]; float const rr = pixel.r(); float const gg = pixel.g(); float const bb = pixel.b(); pixel.r((rr - minMax.minR) * cR); pixel.g((gg - minMax.minG) * cG); pixel.b((bb - minMax.minB) * cB); } } void Image::normalize() { MinMaxPerPixel const minMax(*this); float const den = minMax.max - minMax.min; float const cc = (den < FLT_MIN ? 255.0f : 255.0f / den); unsigned const numPix = mWidth * mHeight; for (unsigned ii = 0; ii < numPix; ++ii) { Pixel& pixel = mData[ii]; float const rr = pixel.r(); float const gg = pixel.g(); float const bb = pixel.b(); pixel.r((rr - minMax.min) * cc); pixel.g((gg - minMax.min) * cc); pixel.b((bb - minMax.min) * cc); } } void Image::writePpm() { normalizePerChannel(); cout << "P6\n" << mWidth << " " << mHeight << "\n255\n"; unsigned const numPix = mWidth * mHeight; for (unsigned ii = 0; ii < numPix; ++ii) { Pixel const& pixel = mData[ii]; cout.put(unsigned(pixel.r() + 0.5) & 0xFF); cout.put(unsigned(pixel.g() + 0.5) & 0xFF); cout.put(unsigned(pixel.b() + 0.5) & 0xFF); } } void Image::writeAscii(int chan) const { if (chan < 0 || chan > 2) { cerr << "Image::writeAscii: ERROR: illegal Channel " << chan << endl; exit(-1); } int off = -1; for (unsigned row = 0; row < mHeight; ++row) { for (unsigned col = 0; col < mWidth; ++col) { cout << " " << char(unsigned(mData[++off].c[chan] + 0.5) & 0xFF); } cout << "\n"; } } MinMaxPerChannel::MinMaxPerChannel(Image const& img) : minR(+FLT_MAX) , minG(+FLT_MAX) , minB(+FLT_MAX) , maxR(-FLT_MAX) , maxG(-FLT_MAX) , maxB(-FLT_MAX) { for (unsigned ir = 0; ir < img.height(); ++ir) { for (unsigned ic = 0; ic < img.width(); ++ic) { Pixel const& pixel = img(ic, ir); float const rr = pixel.r(); float const gg = pixel.g(); float const bb = pixel.b(); if (rr > maxR) maxR = rr; if (gg > maxG) maxG = gg; if (bb > maxB) maxB = bb; if (rr < minR) minR = rr; if (gg < minG) minG = gg; if (bb < minB) minB = bb; } } } MinMaxPerPixel::MinMaxPerPixel(Image const& img) : min(+FLT_MAX), max(-FLT_MAX) { #define COLOR_DEBUG 1 #if COLOR_DEBUG float minR, minG, minB, maxR, maxG, maxB; minR = minG = minB = +FLT_MAX; maxR = maxG = maxB = -FLT_MAX; #endif for (unsigned ir = 0; ir < img.height(); ++ir) { for (unsigned ic = 0; ic < img.width(); ++ic) { Pixel const& pixel = img(ic, ir); float const rr = pixel.r(); float const gg = pixel.g(); float const bb = pixel.b(); if (rr > max) max = rr; if (gg > max) max = gg; if (bb > max) max = bb; if (rr < min) min = rr; if (gg < min) min = gg; if (bb < min) min = bb; #if COLOR_DEBUG if (rr > maxR) maxR = rr; if (gg > maxG) maxG = gg; if (bb > maxB) maxB = bb; if (rr < minR) minR = rr; if (gg < minG) minG = gg; if (bb < minB) minB = bb; #endif } } #if COLOR_DEBUG cerr << "minR=" << minR << " minG=" << minG << " minB=" << minB << endl; cerr << "maxR=" << maxR << " maxG=" << maxG << " maxB=" << maxB << endl; #endif }
<%= bob_header 'Overview' %> <p class='commentable' id="general"> In general, object is the a structure with its own properties (it can carry the data which represents and describes the object) and methods (functions or procedures associated with the object). For example, you may want to have object <code>Server</code>, represents the machine in the network you manage. In this case, this object is a model of reality: it represents the physical box standing deep in the vault of your server room. Such object may contain data fields like <code>name</code>, <code>domain</code> and methods like <code>get_ip</code> (the function returning IP of the machine, based on name and domain). Notice there is no need to pass the server name and domain to <code>get_ip</code> method, because the method itself has an access to the object properties. </p> <%= bob_header 'Classes' %> <p class='commentable' id="class1"> Object must have the defnition - it is called the <strong>class</strong>. You may think about the class as a <strong>type of the object</strong>. In Ruby class is a contant, so must begin with uppercase letter and, by convention, it is good to use CamelCase for class names. <%= bob_left_span %> <%= bob_code filename: '3.2.server_object.rb' %> <%= bob_right_span %> <p> <em>The class contains only one method. Note the <code>get_ip</code> is a mock method for now, it returns constant string, not the proper IP address.</em> </p> <%= bob_end_spans %> </p> <p class='commentable' id="class2"> In Ruby, there is no need to define class in one piece. You can extend definition of a class wherever you want, just remember that new method definition overwrites the previous one. <%= bob_left_span %> <%= bob_code filename: '3.2.server_object_2.rb' %> <%= bob_right_span %> <p> <em>This code defines class Server with three methods: <code>get_ip</code>, <code>domain</code> and <code>name</code>. Method <code>name</code> will return 'unknown name' string, as this version was defined later and overwrites the definition from lines 5 - 7.</em> </p> <%= bob_end_spans %> </p> <%= bob_header "Instance" %> <p class='commentable' id="instance"> If Server is something like a type, can we create a variable with this type? First, we need to allocate the memory for the object and create an object there. This representation in the memory is called the <strong>instance</strong> of the object, and the process of constructing it by language interpreter is called <strong>object creation</strong>. To create a new, empty instance and assign it to variable we can use the class method called <code>new</code>: <%= bob_code brush: :ruby do %> server = Server.new() <% end %> </p> <%= bob_header 'Class Definitions in Irb' %> <p class='commentable' id="irb"> For practice and debug, you can write a script, run it and observe the result. But you can use Irb as well - it is possible to define class or methods directly there: <%= bob_code brush: :ruby do %> class Server def get_ip 'unknown ip' end end #=> nil server = Server.new #=> #&lt;Server:0x007fc6bc1d4978&gt; server.get_ip #=> "unknown ip" <% end %> </p> <p> Notice that <code>irb</code> is changing the continuation level number in a prompt (the last number), to help you remember you are inside a definition of class or a method. </p> <p class='commentable' id="irb-load"> Another way to debug a script is to load it to Irb. To do it, use <code>load</code> command - this will run the given file, so every definition of classes, methods, variables will be accessible from Irb session. <%= bob_code brush: :ruby do %> load 'server_object.rb' #=> true server = Server.new #=> #&lt;Server:0x007fb76bb0a548&gt; server.get_ip #=> "unknown IP" <% end %> </p> <p class='commentable' id="value1"> When you check the value of <code>server</code> variable in Irb, it will show human readable representation of the instance, such like <code>#&lt;Server:0x007fb76bb0a548&gt;</code>. This is the object's class name with the instance identifier (hexadecimal representation of the memory address). </p> <%= bob_header 'Instance variables' %> <p class='commentable' id="varialbles1"> For now, we defined the <code>Server</code> object with only few methods: it is not storing any data in it. The purpose of the object is to represent (to model) the real world. Real servers have some properties like the name and the domain. Such information should be stored in the <strong>instance variable</strong>, so every instance of Server class can have its own name properties. Instance variables syntax is the same as normal, local variables: lowercase, snake_case symbol but followed by character <code>@</code>. In the example below there are two new methods to set server name and server address: <%= bob_left_span %> <%= bob_code filename: '3.2.instance_variables.rb' %> <%= bob_right_span %> <p> <em> Methods to set and get instance variables are called <u>setters</u> and <u>getters</u>. </em> </p> <%= bob_end_spans %> </p> <p class='commentable' id="variables2"> Try to construct an object with instance properties in Irb. When you inspect it, you will see the representation of the object changed. You will get now something like <code>#&lt;Server:0x007fc688e2ebd0 @name="vader", @domain=".starwars.com"&gt;</code> - it is showing the instance variable content for better readability. </p> <p class='commentable' id="setters"> Setters and getters like above are not very elegant. It would be much better to just have a direct access to instance variable, to set its value with <code>server.name = 'vader'</code> and get it with simple <code>server.name</code>. In Ruby there is no direct access to the instance variables, but why not to write the setters and getters in more readable format: <%= bob_code filename: '3.2.setters_getters.rb' %> </p> <p class='commentable' id="setters-again"> It looks like a direct access to object properties, but it is not - when calling <code>object.some_method = ...</code> Ruby invokes method called <code>some_method=</code>, the one with equal sign at the end. For getter, it is much easier: the method name is just the same as the instance variable name. </p> <%= bob_header 'attr_accessor, attr_writter and attr_reader' %> <p class='commentable' id="attr"> In a big projects writing getters and setters for every instance variable in the way like above might be quite boring. Why don't let Ruby do it for us? There are special functions for creating setters and getters for the given variable names: <code>attr_writter</code> creates the setter, <code>attr_reader</code> produces a getter and <code>attr_accessor</code> - both setter and getter. <%= bob_left_span %> <%= bob_code filename: '3.2.attr_accessor.rb' %> <%= bob_right_span %> <p> <em> <code>attr_*</code> methods are taking the list of variable names as the arguments. You can give this name as a string (like 'name' in the example), but much better is to use Ruby symbols. Symbols are the kind of strings, written with colon at the beggining (<code>:name</code> in the example), but unlike the strings they are not mutable - you can't change it. They are commonly used to pass the method names, variable named etc. </em> </p> <%= bob_end_spans %> <%= bob_header 'Instance Constructor' %> <p class='commentable' id="constructor"> We now know how to create a new instance with <code>new</code> class method. It is possible to control the object creation code: if Ruby found a method called <code>initialize</code> it lauches it while creating an object. In the example below the instance variables are set to default values while constructing an object: <%= bob_code filename: '3.2.initialize.rb' %> </p> <p class='commentable' id="constructor-args"> You can pass the arguments to <code>new</code> class method - Ruby will pass them to the <code>initialize</code> instance method. This is commonly use for passing the initialization values for the class variables. Notice that the number of arguments in <code>new</code> must equal the number of arguments in <code>initialize</code>: <%= bob_code filename: '3.2.initialize_args.rb' %> </p> <%= bob_header 'Class Methods and Variables' %> <p class='commentable' id="class-methods"> So far we have created the <strong>instance methods</strong>, which are functions running on object instance, having an access to all its properties - but only in the scope of the current object. <strong>Class methods</strong> are different - they are running on the class, not on the object instance, and they do not need any instance initialized. You know one of the class method - the object constructor, <code>new</code>. It is invoked on the class, like <code>Server.new</code>. This method must be a class method - before the first initialization with <code>new</code> there is no instance to run the function on. To define class method, use <code>self.</code> syntax before method name.<br> Class variables are like the instance variables, but with the scope on the class, not on the specific object. That means all of the objects of specific class have an access to this values - it is shared between them. Class variables are defined with double 'at' symbol <code>@@</code> before the variable name.<br> Class methods are commonly used for object initialization, besides <code>Object.new</code> there are many of this kind, for example <code>File.open(filename)</code> which creates an object representing the file with the given path. Class variables might be useful when you need to do something on all the object of a kind, for example to count all defined servers: <%= bob_code filename: '3.2.class_methods.rb', highlight_lines: [2, 8, 11, 12, 13] %> </p> <%= bob_header 'Self' %> <p class='commentable' id="mysefl"> <code>self</code> is a keyword to represent a current object instance. You can use it in the class definition to access the instance itself. In the example below, method <code>url</code> calls the method <code>full_name</code> on the same object. <%= bob_code filename: '3.2.self.rb' %> </p> <p class='commentable' id="myself2"> Just to call the method in the example above you may skip the <code>self</code> keyword. Ruby is searching for a method in the current object instance first, so this will work as well: <%= bob_code brush: :ruby do %> def url 'http://' + full_name end <% end %> </p> <%= bob_header 'Object Inheritance' %> <p class='commentable' id="inherit1"> Inheritance is a very important concept in the object-oriented programming. When the class (we will call it subclass) <strong>inherits</strong> another class (called superclass or ancestor), it is getting the whole structure of the parent class, all the code: variables, methods etc. This provides the class hierarchy, where most general classes are at the top, and the detailed ones at the bottom of hierarchy tree. <br> The syntax for inheritance in Ruby is <code>class SubClassName &lt; SuperClassName</code>.<br> Assume we want to have two new classes, adding more details to our servers model. We can create two classes, <code>WindowsServer</code> and <code>UnixServer</code>, which we want to behave the same as a general Server class: <%= bob_code filename: '3.2.inheritance.rb' %> </p> <p class='commentable' id="inherit2"> Lines 1 - 9 provides us the well know implementation of the <code>Server</code> object. Then comes the definition of <code>WindowsServer</code> class comes, which is a subclass of the <code>Server</code>. That means this class now have the same implementation like its superclass - it has the same methods and variables like the <code>Server</code>. So we can create it with arguments (line 20) just like the <code>Server</code>, run the method from the superclass (line 24) - all of this code <code>WindowsServer</code> inherits from the ancestor. <br> The similar is for <code>UnixServer</code> class - it has all the methods and variables inherited from <code>Server</code>. In addition, this class have one more instance method - <code>execute_via_ssh</code> (now it is not doing nothing, except the nasty information). You can call this method, but only on <code>UnixServer</code> object! It is not available in objects of <code>WindowsServer</code> or even <code>Server</code> class. </p> <p> The method from the superclass can be overwritten in the subclass. For example, you may want to change behaviour of the <code>full_name</code> method - in case it is Windows server, you want to be the server name only, without a domain, upper-case. <%= bob_left_span %> <%= bob_code filename: '3.2.overwritting.rb' %> <%= bob_right_span %> <p> <em> <code>upcase</code> is an instance method of String object to change all the characters of the string to uppercase. </em> </p> <%= bob_end_spans %> </p> <p class='commentable' id="inherit-search"> Ruby searches for a method first in the current object and only when not found the interpreter start searching in the superclasses. So after the changes above the method gives the desired server name for <code>WindowsServer</code> object: <%= bob_code brush: :ruby do %> irb(main):025:0> win = WindowsServer.new('yoda', '.starwars.com') #=>#&lt;WindowsServer:0x007fb83a0c7318 @name="yoda", @domain=".starwars.com"&gt; irb(main):027:0> win.full_name #=>"YODA" <% end %> </p> <p class='commentable' id="inherit-summary"> Inheritance (and similar techniques, like mixins) is really important in Ruby. Remember the method <code>new</code> to create a new instance? It magically appears in the newly defined <code>Server</code> class. Well, this particular method comes from <code>Class</code> class. Refer to following documentation <%=bob_link_to 'http://ruby-doc.org/core-2.0.0/Class.html' %> to learn more. </p> <%= bob_header 'Object Operators' %> <p class='commentable' id="operators"> In Ruby, most operators are actually the method calls on the objects. Thus <code>a + b</code> means run the method called <code>+</code> on object <code>a</code> with argument <code>b</code> - this is another way to write <code>a.+(b)</code> or <code>a.+ b</code>. You can try it in Irb, instead of typing <code>2 + 2</code> you can calculate this by directly calling the method <code>+</code> on object instance <code>2</code> with the argument of object instance <code>2</code>: <code>2.+(2)</code>. It works!<br> Sometimes the operator does not makes sense for the specified kind of object. We can add numbers, strings (to concatenate), but we cannot add servers one to each other. Thats why we need to find out another operator to play with the examples. Lets discuss the equality operator <code>==</code>. Can we check if two servers are equal? Yes, if the servers have the same name and domain, they must be the same machines. By default, we have the <code>==</code> defined for every object, but it does not work as we expect: <%= bob_code brush: :ruby do %> server1 = Server.new('yoda','.starwars.com') #=> #&lt;Server:0x007fdf22830af0 @name="yoda", @domain=".starwars.com"> server2 = Server.new('yoda','.starwars.com') #=> #&lt;Server:0x007fdf219f34d8 @name="yoda", @domain=".starwars.com"> server1 == server2 #=> false <% end %> </p> <p class='commentable' id="opers2"> This is because we defined two object instances and, from the Ruby point of view, these are a different constructs. Just observe the identificator (the memory address) of <code>server1</code> and <code>server2</code>. To fix this behaviour it is time to override the equality operator: <%= bob_code '3.2.operator.rb' %> </p> <p class='commentable' id="opers3"> Line 7 defines operator as an instance method on object <code>Server</code>. It is the only one line of code (line 8), which means: "return true if my name equals the other name AND if my domain equals the other domain". In this line operator <code>==</code> checks equality of String objects (@name and @domain are the character strings). To better understanding, we can write this line in different way: <code>(self.name == other.name) && (self.domain == other.domain)</code> or with if-then-else statement: <%= bob_code brush: :ruby do %> if name == other.name && domain == other.domain return true else return false end <% end %> <p> But because the method always returns the value of the last statement, there is no need to bother with if-then-else. Simplicity first! </p> <%= bob_header 'Inspect' %> <p class='commentable' id="inspect"> By default objects in <code>irb</code> are shown by the class name, the instance identifier (the unique identifier for all objects) and the instance variables, if any. This is quite handy, but we can do better. To show this value, <code>irb</code> runs method <code>inspect</code> on the specified instance. If you define your own, you can output better human-readable description of the object. In this case, we want our Server object to be shown as <code>* [class name]: [server and domain] *</code> <%= bob_code brush: :ruby do %> server = Server.new('yoda', '.starwars.com') #=> #&lt;Server:0x007ff231124fa0 @name="yoda", @domain=".starwars.com"&gt; # default inspect value class Server def inspect # our own inspect "* " + self.class.to_s + ": " + @name + @domain + " *" # * [class name]: [server and domain] * end end server #=> * Server: yoda.starwars.com * # works as expected! <% end %> </p> <%= bob_header 'Hacking the Math' %> <p class='commentable' id="hackthemath1"> At the end of this long and boring chapter, let's have some fun! Who said that "2 + 2" must always give "4"? Well, by default, Ruby claims it is "4": <%= bob_code brush: :ruby do %> 2 + 2 #=> 4 <% end %> </p> <p class='commentable' id="hasck2"> But as we said, everything in Ruby is an object and have its class. Number 2 is an instance of class <class>Fixnum</class>. <%= bob_code brush: :ruby do %> 2.class #=> Fixnum <% end %> </p> <p class='commentable' id="hack3"> So why not to redefine the <code>+</code> operator, which is in fact the instance method on <code>Fixnum</code> class. <%= bob_code brush: :ruby do %> class Fixnum def +(other) 42 end end <% end %> </p> <p class='commentable' id="hack4"> Voila! What is the result of "2 + 2" now? <%= bob_code brush: :ruby do %> 2 + 2 #=> 42 <% end %> </p>
import { useRecoilState } from 'recoil'; import { Switch } from '~/components/ui/Switch'; import useLocalize from '~/hooks/useLocalize'; import store from '~/store'; export default function SendMessageKeyEnter({ onCheckedChange, }: { onCheckedChange?: (value: boolean) => void; }) { const [enterToSend, setEnterToSend] = useRecoilState<boolean>(store.enterToSend); const localize = useLocalize(); const handleCheckedChange = (value: boolean) => { setEnterToSend(value); if (onCheckedChange) { onCheckedChange(value); } }; return ( <div className="flex items-center justify-between"> <div> {localize('com_nav_enter_to_send')} </div> <Switch id="enterToSend" checked={enterToSend} onCheckedChange={handleCheckedChange} className="ml-4 mt-2" data-testid="enterToSend" /> </div> ); }
import { SubmitHandler, useForm } from 'react-hook-form'; import { BG_COLORS, BG_IMAGES } from '../../const/const'; import { useCreateBoardMutation } from '../../store/reducers/workspace/workspace.api'; import { showErrorToast, showLoadingToast, showSuccessToast } from '../../utils/toast'; import './CreateBoardForm.scss'; type NewBoard = { title: string; theme: string; }; type CreateBoardFormProps = { workspaceId: string; onClose: () => void; }; const DELIMITER = '↕'; function CreateBoardForm({ onClose, workspaceId }: CreateBoardFormProps) { const [createBoard, { isLoading }] = useCreateBoardMutation(); const { register, handleSubmit, formState: { errors, isValid }, } = useForm<NewBoard>({ defaultValues: { theme: `backgroundColor${DELIMITER}${BG_COLORS[0]}`, }, mode: 'all', }); const handleFormSubmit: SubmitHandler<NewBoard> = async (data, evt) => { evt?.preventDefault(); const { theme, title } = data; const [name, value] = theme.split(DELIMITER); const toastId = showLoadingToast('Создание доски...'); try { await createBoard({ title, workspaceId, [name]: value, }).unwrap(); showSuccessToast(toastId, 'Доска создана успешно!'); } catch (err) { showErrorToast({ id: toastId, err, fallbackMsg: 'Произошла ошибка при создании доски.', }); } onClose(); }; return ( <form className="create-board-form" onSubmit={handleSubmit(handleFormSubmit)}> <h3 className="create-board-form__title">Создание доски</h3> <h4 className="create-board-form__field-name">Название доски</h4> <label htmlFor="title" className="auth-form__label create-board-form__label"> <input className="auth-form__input" {...register('title', { required: 'Данное поле обязательно для заполнения', minLength: { value: 3, message: 'Минимальная длина поля 3 символа', }, })} type="text" placeholder="Введите название доски" /> {errors?.title && <p className="auth-form__input-error">{errors?.title?.message}</p>} </label> <h4 className="create-board-form__field-name">Фон доски</h4> <div className="create-board-form__bg"> <div className="create-board-form__images"> {BG_IMAGES.map((image, id) => { const inputID = `rbi-${id}`; const value = `backgroundImage${DELIMITER}url(${image})`; return ( <label key={inputID} htmlFor={inputID} style={{ backgroundImage: `url(${image})` }} className="cb-bg-radio-button" > <input type="radio" id={inputID} className="cb-bg-radio-button__input" value={value} {...register('theme')} /> <span /> </label> ); })} </div> <div className="create-board-form__colors"> {BG_COLORS.map((color, id) => { const inputID = `rbc-${id}`; const value = `backgroundColor${DELIMITER}${color}`; return ( <label key={inputID} htmlFor={inputID} style={{ backgroundColor: color }} className="cb-color-radio-button" > <input type="radio" id={inputID} className="cb-color-radio-button__input" value={value} {...register('theme')} /> <span /> </label> ); })} </div> </div> <div className="create-workspace-form__controls"> <button type="button" className="create-workspace-form__cancel-btn" onClick={onClose}> Отмена </button> <button type="submit" className="form-btn form-btn--small" disabled={!isValid || isLoading}> Создать </button> </div> </form> ); } export default CreateBoardForm;
# Raindrops Welcome to Raindrops on Exercism's Python Track. If you need help running the tests or submitting your code, check out `HELP.md`. ## Instructions Your task is to convert a number into a string that contains raindrop sounds corresponding to certain potential factors. A factor is a number that evenly divides into another number, leaving no remainder. The simplest way to test if a one number is a factor of another is to use the [modulo operation](https://en.wikipedia.org/wiki/Modulo_operation). The rules of `raindrops` are that if a given number: - has 3 as a factor, add 'Pling' to the result. - has 5 as a factor, add 'Plang' to the result. - has 7 as a factor, add 'Plong' to the result. - _does not_ have any of 3, 5, or 7 as a factor, the result should be the digits of the number. ## Examples - 28 has 7 as a factor, but not 3 or 5, so the result would be "Plong". - 30 has both 3 and 5 as factors, but not 7, so the result would be "PlingPlang". - 34 is not factored by 3, 5, or 7, so the result would be "34". ## Source ### Contributed to by - @behrtam - @BethanyG - @bsoyka - @cmccandless - @Dog - @ikhadykin - @kytrinyx - @lowks - @N-Parsons - @pheanex - @sjakobi - @tqa236 - @yawpitch ### Based on A variation on FizzBuzz, a famous technical interview question that is intended to weed out potential candidates. That question is itself derived from Fizz Buzz, a popular children's game for teaching division. - https://en.wikipedia.org/wiki/Fizz_buzz
package com.zuitem.controller; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.zuitem.domain.*; import com.zuitem.domain.util.Result; import com.zuitem.service.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class ApplyoutController { @Autowired private ApplyoutService applyoutService; @Autowired private ItemlistService itemlistService; @Autowired private HetongService hetongService; @Autowired private CheckoutService checkoutService; @Autowired private ZulistService zulistService; @RequestMapping("/applyout") public PageInfo<Applyout> selectAll(@RequestParam(defaultValue = "", value = "search") String search, @RequestParam(defaultValue = "1", value = "cur") int cur, @RequestParam(defaultValue = "10", value = "size") int size) { PageHelper.startPage(cur, size); List<Applyout> applyout = applyoutService.findAll(search); PageInfo<Applyout> p = new PageInfo<Applyout>(applyout); System.out.println(applyout); return p; } /** * 管理员同意退租申请 * * @param model * @param id * @return */ @RequestMapping("/agreeapplyout") public Result agreeapplyout(@RequestParam("id") String id) { System.out.println("id==>" + id); // 修改 itemlist 状态 未租赁 Applyout applyout = applyoutService.findByItem_idApplyout(id); Itemlist item = itemlistService.findItem(Integer.parseInt(applyout.getItem_id())); item.setStatus("未租赁"); itemlistService.editItem(item); // 添加 已退租 列表 Checkout checkout = new Checkout(); checkout.setItem_id(applyout.getItem_id()); checkout.setIname(applyout.getIname()); checkout.setStatus("已退租"); checkout.setUser_id(applyout.getUser_id()); checkoutService.addCheckout(checkout); // 修改 退租 申请 ==> 已同意 applyout.setStatus("已同意"); applyoutService.updateapplyoutbyitem(applyout); // 删除 合同列表 hetongService.delHetong(id); // 删除 已出租 列表 zulistService.deleteByItem_id(applyout.getItem_id()); return new Result(200, "成功^v^"); } /** * 申请退租信息 * * @param model * @return */ @RequestMapping("/addApplyout") public Result insertapplyout(@RequestParam("item_id") String item_id) { System.out.println("addApplyout=》》》》》》》》》》》》》》》》》》》》》"); System.out.println(item_id); Zulist zulist = zulistService.findByItem_idZulist(item_id); System.out.println(zulist); Applyout applyout = new Applyout(); applyout.setItem_id(zulist.getItem_id()); applyout.setIname(zulist.getIname()); applyout.setStatus("申请中"); applyout.setUser_id(zulist.getUser_id()); System.out.println(applyout); applyoutService.addApplyout(applyout); return new Result(200, "申请成功"); } /** * 拒绝退租 * @return */ @RequestMapping("/jujueApplyout") public Result jujueApplyout(@RequestParam("aoid") String aoid) { System.out.println("addApplyout=》》》》》》》》》》》》》》》》》》》》》"); System.out.println(aoid); Applyout byItemIdApplyout = applyoutService.findByItem_idApplyout(aoid); byItemIdApplyout.setStatus("已拒绝"); applyoutService.updateapplyoutbyitem(byItemIdApplyout); return new Result(200, "操作成功"); } /** * 删除 退租列表 * * @return */ @RequestMapping("/delapplyout") public Result delapplyout(@RequestParam("item_id") String item_id) { System.out.println("item_id=》》》》》》》》》》》》》》》》》》》》》"); System.out.println(item_id); // 删除 --退租列表 applyoutService.delapplyout(item_id); return new Result(200, "申请成功"); } }
import { Dialog, Transition } from '@headlessui/react'; import { Fragment, useState } from 'react'; import { useForm } from 'react-hook-form'; import axios from 'axios'; import { toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; export default function ForgotPasswordModal({ isOpen, closeModal }) { const { register, handleSubmit, formState: { errors } } = useForm(); const onSubmit = async (data) => { try { const response = await axios.post('https://localhost:7276/api/Auth/forgot-password', data); toast.success("Password reset link sent to your email!"); closeModal(); } catch (error) { toast.error("Failed to send password reset link. Please try again."); } }; return ( <Transition appear show={isOpen} as={Fragment}> <Dialog as="div" className="relative z-10" onClose={closeModal}> <Transition.Child as={Fragment} enter="ease-out duration-300" enterFrom="opacity-0" enterTo="opacity-100" leave="ease-in duration-200" leaveFrom="opacity-100" leaveTo="opacity-0" > <div className="fixed inset-0 bg-black/25" /> </Transition.Child> <div className="fixed inset-0 overflow-y-auto"> <div className="flex min-h-full items-center justify-center pt-20"> <Transition.Child as={Fragment} enter="ease-out duration-300" enterFrom="opacity-0 scale-95" enterTo="opacity-100 scale-100" leave="ease-in duration-200" leaveFrom="opacity-100 scale-100" leaveTo="opacity-0 scale-95" > <Dialog.Panel className="w-1/2 transform overflow-hidden rounded-md shadow-xl transition-all bg-white p-6"> <h2 className="text-2xl font-semibold mb-4">Forgot Password</h2> <form onSubmit={handleSubmit(onSubmit)}> <label className="block mb-2">Username</label> <input type="text" placeholder="Enter your username" className="text-gray-700 p-2 rounded-lg border-2 border-zinc-400 w-full mb-4" {...register('username', { required: true })} /> {errors.username && <p className="text-red-400 text-sm italic">This field is required!</p>} <label className="block mb-2">Email</label> <input type="email" placeholder="Enter your email" className="text-gray-700 p-2 rounded-lg border-2 border-zinc-400 w-full mb-4" {...register('email', { required: true })} /> {errors.email && <p className="text-red-400 text-sm italic">This field is required!</p>} <button type="submit" className="bg-orange-500 text-white rounded-lg px-4 py-2 mt-4 w-full"> Send Reset Link </button> </form> </Dialog.Panel> </Transition.Child> </div> </div> </Dialog> </Transition> ); }
/// <reference types="vitest/globals" /> import { render } from '../renderer.js' describe('dropdown.toggle', () => { it('renders dropdown toggle button with default props', async () => { const html = await render('<ui:dropdown.toggle>Toggle</ui:dropdown.toggle>') expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false"> Toggle</button>" `) }) it('renders dropdown toggle button with additional classes', async () => { const html = await render( "<ui:dropdown.toggle class='foo'>Toggle</ui:dropdown.toggle>" ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn dropdown-toggle foo" data-bs-toggle="dropdown" aria-expanded="false"> Toggle</button>" `) }) it('renders split-style toggle button when split prop is true', async () => { const html = await render( '<ui:dropdown.toggle split>Toggle</ui:dropdown.toggle>' ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn text-nowrap"> Toggle </button> <button type="button" class="btn dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false"> <span class="visually-hidden">Toggle Dropdown</span> </button>" `) }) it('renders split-style toggle button with additional classes', async () => { const html = await render( "<ui:dropdown.toggle split class='foo'>Toggle</ui:dropdown.toggle>" ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn text-nowrap foo"> Toggle </button> <button type="button" class="btn dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false"> <span class="visually-hidden">Toggle Dropdown</span> </button>" `) }) it('renders dropdown toggle button with variant prop', async () => { const html = await render( "<ui:dropdown.toggle variant='primary'>Toggle</ui:dropdown.toggle>" ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false"> Toggle</button>" `) }) it('renders split-style toggle button with variant prop', async () => { const html = await render( "<ui:dropdown.toggle variant='primary' split>Toggle</ui:dropdown.toggle>" ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn btn-primary text-nowrap"> Toggle </button> <button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false"> <span class="visually-hidden">Toggle Dropdown</span> </button>" `) }) it('renders dropdown toggle button with size prop', async () => { const html = await render( "<ui:dropdown.toggle size='sm'>Toggle</ui:dropdown.toggle>" ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn btn-sm dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false"> Toggle</button>" `) }) it('renders split-style toggle button with size prop', async () => { const html = await render( "<ui:dropdown.toggle size='sm' split>Toggle</ui:dropdown.toggle>" ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn btn-sm text-nowrap"> Toggle </button> <button type="button" class="btn btn-sm dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false"> <span class="visually-hidden">Toggle Dropdown</span> </button>" `) }) it('renders dropdown toggle button with nowrap prop', async () => { const html = await render( '<ui:dropdown.toggle nowrap>Toggle</ui:dropdown.toggle>' ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn text-nowrap dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false"> Toggle</button>" `) }) it('renders split-style toggle button with nowrap prop', async () => { const html = await render( '<ui:dropdown.toggle nowrap split>Toggle</ui:dropdown.toggle>' ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn text-nowrap"> Toggle </button> <button type="button" class="btn dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false"> <span class="visually-hidden">Toggle Dropdown</span> </button>" `) }) it('renders dropdown toggle button with active prop', async () => { const html = await render( '<ui:dropdown.toggle active>Toggle</ui:dropdown.toggle>' ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn active dropdown-toggle" data-bs-toggle="dropdown" aria-pressed="true" aria-expanded="false"> Toggle</button>" `) }) it('renders split-style toggle button with active prop', async () => { const html = await render( '<ui:dropdown.toggle active split>Toggle</ui:dropdown.toggle>' ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn active text-nowrap"> Toggle </button> <button type="button" class="btn active dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-pressed="true" aria-expanded="false"> <span class="visually-hidden">Toggle Dropdown</span> </button>" `) }) it('renders dropdown toggle button with disabled prop', async () => { const html = await render( '<ui:dropdown.toggle disabled>Toggle</ui:dropdown.toggle>' ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn dropdown-toggle" data-bs-toggle="dropdown" disabled aria-expanded="false"> Toggle</button>" `) }) it('renders split-style toggle button with disabled prop', async () => { const html = await render( '<ui:dropdown.toggle disabled split>Toggle</ui:dropdown.toggle>' ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn text-nowrap" disabled> Toggle </button> <button type="button" class="btn dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" disabled="true" aria-expanded="false"> <span class="visually-hidden">Toggle Dropdown</span> </button>" `) }) it('renders dropdown toggle button with autoclose prop', async () => { const html = await render( '<ui:dropdown.toggle autoclose>Toggle</ui:dropdown.toggle>' ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn dropdown-toggle" data-bs-toggle="dropdown" data-bs-autoclose="true" aria-expanded="false"> Toggle</button>" `) }) it('renders split-style toggle button with autoclose prop', async () => { const html = await render( '<ui:dropdown.toggle autoclose split>Toggle</ui:dropdown.toggle>' ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn text-nowrap"> Toggle </button> <button type="button" class="btn dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" data-bs-autoclose="true" aria-expanded="false"> <span class="visually-hidden">Toggle Dropdown</span> </button>" `) }) it('renders dropdown toggle button with static prop', async () => { const html = await render( '<ui:dropdown.toggle static>Toggle</ui:dropdown.toggle>' ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn dropdown-toggle" data-bs-toggle="dropdown" data-bs-display="static" aria-expanded="false"> Toggle</button>" `) }) it('renders split-style toggle button with static prop', async () => { const html = await render( '<ui:dropdown.toggle static split>Toggle</ui:dropdown.toggle>' ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn text-nowrap"> Toggle </button> <button type="button" class="btn dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" data-bs-display="static" aria-expanded="false"> <span class="visually-hidden">Toggle Dropdown</span> </button>" `) }) it('renders dropdown toggle button with offset prop', async () => { const html = await render( "<ui:dropdown.toggle offset='10,20'>Toggle</ui:dropdown.toggle>" ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn dropdown-toggle" data-bs-toggle="dropdown" data-bs-offset="10,20" aria-expanded="false"> Toggle</button>" `) }) it('renders split-style toggle button with offset prop', async () => { const html = await render( "<ui:dropdown.toggle offset='10,20' split>Toggle</ui:dropdown.toggle>" ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn text-nowrap"> Toggle </button> <button type="button" class="btn dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" data-bs-offset="10,20" aria-expanded="false"> <span class="visually-hidden">Toggle Dropdown</span> </button>" `) }) it('renders dropdown toggle button with reference prop', async () => { const html = await render( "<ui:dropdown.toggle reference='parent'>Toggle</ui:dropdown.toggle>" ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn dropdown-toggle" data-bs-toggle="dropdown" data-bs-reference="parent" aria-expanded="false"> Toggle</button>" `) }) it('renders split-style toggle button with reference prop', async () => { const html = await render( "<ui:dropdown.toggle reference='parent' split>Toggle</ui:dropdown.toggle>" ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn text-nowrap"> Toggle </button> <button type="button" class="btn dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" data-bs-reference="parent" aria-expanded="false"> <span class="visually-hidden">Toggle Dropdown</span> </button>" `) }) it('renders dropdown toggle button without toggler', async () => { const html = await render( '<ui:dropdown.toggle no-toggler>Toggle</ui:dropdown.toggle>' ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn" data-bs-toggle="dropdown" aria-expanded="false"> Toggle</button>" `) }) it('renders split-style toggle button with without toggler', async () => { const html = await render( '<ui:dropdown.toggle no-toggler split>Toggle</ui:dropdown.toggle>' ) expect(html).toMatchInlineSnapshot(` "<button type="button" class="btn text-nowrap"> Toggle </button> <button type="button" class="btn dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false"> <span class="visually-hidden">Toggle Dropdown</span> </button>" `) }) })
from typing import List from pydantic import BaseModel class Blog(BaseModel): title : str body : str class User(BaseModel): name : str email : str password : str class ShowUser(BaseModel): name : str email : str blogs : List[Blog] = [] class Config(): orm_mode = True class ShowBlog(Blog): creator : ShowUser class Config(): orm_mode = True class Login(BaseModel): username : str password : str class Token(BaseModel): access_token: str token_type: str class TokenData(BaseModel): email: str | None = None
import React from 'react' import { SectionTitle, Product } from '@/components' import { productService } from '@/services/product.service' import { Product as IProduct } from '@/types/product.types' import type { NextPage, NextPageContext } from 'next' import Head from 'next/head' import styles from './produto.module.css' interface ProdutoProps { product: IProduct; } const Produto: NextPage<ProdutoProps> = ({ product }: ProdutoProps) => { return ( <div> <Head> <title>{product.name} | Renner</title> <meta name="description" content={product.description} /> </Head> <Product product={product} /> <hr /> <SectionTitle>DETALHES</SectionTitle> <div className={styles.details} dangerouslySetInnerHTML={{ __html: product.summary }} /> </div> ) } export async function getServerSideProps (context: NextPageContext) { const { id } = context.query const product = await productService.getById(parseInt(id as string, 10)) return { props: { product } } } export default Produto
// while 문 : 가장 기본적인 반복문 // while 문 실행 시 while 문 밖에 초기화 변수를 선언하고, while 안에서 초기화 변수의 카운트가 필요함 import java.util.Scanner; public class While { public static void main(String[] args) { System.out.println("\n----- while 문 -----\n"); int hit = 0; // 초기화 변수 while (hit < 10){ // 히트가 10보다 작다 -> true System.out.println("나무를 " + hit + "번 찍었습니다."); if (hit == 10) { System.out.println("나무가 넘어갑니다."); } hit++; // hit + (+) } // while 사용 시 주의점 // hit 위치는 보통 재일 마지막에 넣는걸 추천 // 1. 초기화 변수의 카운트 부분의 위치에 따라 결과가 달라진다 // 1.1 프로그램이 익숙하지않을 경우 변수의 카운트 부분을 고정해서 사용하는 것이 좋다 // 2. while 문을 탈출할수 있는 조건을 반드시 명시해야 한다(무한 루프에 빠질수 있다) // 2.1 break 문을 사용하여 탈출 (예시에서는 while 문 안에 if문 = break) System.out.println("\n----- while 문 사용 시 주의점 -----\n"); hit = 0; while (hit < 5){ // 히트가 5 보다 작다 -> true // // hit++; System.out.println("나무를 " + hit + "번 찍었습니다."); hit++; if (hit == 5) { System.out.println("나무가 넘어갑니다."); } } // 문제 2) while 문을 사용하여 1 ~ 10까지 화면에 출력하는 프로그램을 작성하세요 System.out.println("\n----- 문제2 -----\n"); int count = 1; while (count<11) { System.out.println(count); count++; } // 문제 3) while 문을 사용하여 1 ~ 10까지의 총합을 구하는 프로그램을 작성하세요 System.out.println("\n----- 문제3 -----\n"); count = 1; int total =0; while (count < 11) { total = total + count; System.out.println("count : " + count + "\ttotal : " + total); count++; } System.out.println("\ntotal : " + total); Scanner scanner = new Scanner(System.in); count = 0; int n = 0; // 숫자입력 정수 double sum = 0.0; // 평균값 소수점 실수 System.out.println("정수를 입력하고 마지막에 0을 입력하세요."); // while 문의 조건식에 탈출 조건까지 함께 지정 // 키보드 입력을 통한 데이터가 0이 아닐경우 아래 while 문 실행, 0이면 while문 종료 while ((n = scanner.nextInt()) !=0) { sum = sum + n; count++; } System.out.println("수의 개수는 " + count + "개 이며"); // 총합이 저장된 변수 sum은 double형 // 입력된 데이터의 수가 저장된 변수 count는 int형 // double형과 int형의 연산이 수행되면 자동형변환이 발생하여 double형으로 데이터가 만들어 짐 System.out.println("평균은 " + sum/count + "입니다"); // 문제 4) while 문을 사용하여 지정한 구구단 단수의 구구단을 출력하세요 // 출력형태 : 5 * 1 = 5 ~ 5 * 9 = 45 System.out.println("출력하고자 하는 구구단의 단수를 입력하세요."); int dan = scanner.nextInt(); count = 1; while (count <10) { System.out.println(dan + " * " + count + " = " + (dan * count) ); count++; } // 다중 while문 : 하나의 while 문 안에 또 다른 while문이 있는 형태의 while문을 뜻함 System.out.println("\n----- 다중 while 문 -----\n"); int i = 0; while (i < 5) { int j = 0; while (j < 5) { System.out.println("i : " + i + "\tj : " + j); j++; // j = 0 ~ 4 } i++; // i = 0 ~ 4 } // 문제 5) while문을 사용하여 2 ~ 9 단까지의 구구단을 모두 출력하는 프로그램을 작성하세요 // 다중 while 문 사용 // 출력 형태 : 5 * 1 = 5 ~ 5 * 9 = 45 i = 2; while (i <= 9) { System.out.println("-----" + i + "단 -----"); int j = 1; while (j < 10) { System.out.println(i + " * " + j + " = "+ (i * j)); j++; } i++; } // do ~ while : 기본적으로 while 문과 동일한 반복문, 무조건 1번은 실행이 되는 while문, 반복 조건을 작성해 확인 System.out.println("\n ----- do ~ while 문 사용하기 -----\n"); // 조건을 먼저 확인 System.out.println("----- 일반 while 문 -----"); int c1 = 10; while (c1 < 5) { System.out.println(c1); c1++; } // 조건을 나중에 확인 System.out.println(" ----- do ~ while 문 -----"); int c2 = 10; do { System.out.println(c2); c2++; } while (c2 < 5); } }
<!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"> <link rel="stylesheet" href="main.css"> <!-- Swiper --> <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css"/> <!-- Font Awesome --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <title>Hexashop</title> </head> <body> <!-- Esta es una prueba --> <!-- Colocar el hamburguer menu aqui --> <div class="menu-btn"> <i class="fa-solid fa-bars"></i> </div> <div class="container"> <nav class="navbar"> <div class="imagen"> <img class="logo" src="images/logo.png" alt=""> </div> <ul class="navbar__items"> <li><a href="">Home</a></li> <li><a href="">Men's</a></li> <li><a href="">Women's</a></li> <li><a href="">Kid's</a></li> <li><a href="">Pages</a></li> <li><a href="">Features</a></li> <li><a href="">Explore</a></li> </ul> </nav> </div> <hr> <div class="container-main m-5"> <section class="main"> <div class="grid"> <div class="left"> <div class="text"> <h2 style="text-align: center;">We Are Hexashop</h2> <p>Awesome, clean & creative HTML5 Template</p> <button class="btn">Purchase now!</button> </div> </div> <div class="top1"> <div class="text"> <h3>Women</h3> <p>Best Clothes For Women</p> </div> <div class="details"> <h3>Women</h3> <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit.</p> <button class="btn">Discover</button> </div> </div> <div class="top2"> <div class="text"> <h3>Men</h3> <p>Best Clothes For Men</p> </div> <div class="details"> <h3>Men</h3> <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit.</p> <button class="btn">Discover</button> </div> </div> <div class="bottom1"> <div class="text"> <h3>Kids</h3> <p>Best Clothes For Kids</p> </div> <div class="details"> <h3>Kids</h3> <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit.</p> <button class="btn">Discover</button> </div> </div> <div class="bottom2"> <div class="text"> <h3>Accesories</h3> <p>Best Trend For Accesorries</p> </div> <div class="details"> <h3>Accesories</h3> <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit.</p> <button class="btn">Discover</button> </div> </div> </div> </div> </section> </div> <hr> <div class="container"> <section class="men"> <h2 class="header">Men's Latest</h2> <p class="title">Details to details is what makes Hexashop different from the other themes.</p> <div class="swiper mySwiper"> <div class="swiper-wrapper"> <div class="swiper-slide"> <img src="images/men-01.jpg" alt=""> <div class="swiper__text"> <h2>Classic Spring</h2> <div class="stars"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </div> <p class="title">$120.00</p> <div class="details_swiper"> <div class="icon"> <i class="fa-solid fa-eye"></i> </div> <div class="icon"> <i class="fa-solid fa-star"></i> </div> <div class="icon"> <i class="fa-solid fa-cart-shopping"></i> </div> </div> </div> <div class="swiper-slide"> <img src="images/men-02.jpg" alt=""> <div class="swiper__text"> <h2>Air Force 1 X</h2> <div class="stars"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </div> <p class="title">$90.00</p> <div class="details_swiper"> <div class="icon"> <i class="fa-solid fa-eye"></i> </div> <div class="icon"> <i class="fa-solid fa-star"></i> </div> <div class="icon"> <i class="fa-solid fa-cart-shopping"></i> </div> </div> </div><div class="swiper-slide"> <img src="images/men-03.jpg" alt=""> <div class="swiper__text"> <h2>Love Nana '20</h2> <div class="stars"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </div> <p class="title">$150.00</p> <div class="details_swiper"> <div class="icon"> <i class="fa-solid fa-eye"></i> </div> <div class="icon"> <i class="fa-solid fa-star"></i> </div> <div class="icon"> <i class="fa-solid fa-cart-shopping"></i> </div> </div> </div><div class="swiper-slide"> <img src="images/men-01.jpg" alt=""> <div class="swiper__text"> <h2>Classic Spring</h2> <div class="stars"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </div> <p class="title">$120.00</p> <div class="details_swiper"> <div class="icon"> <i class="fa-solid fa-eye"></i> </div> <div class="icon"> <i class="fa-solid fa-star"></i> </div> <div class="icon"> <i class="fa-solid fa-cart-shopping"></i> </div> </div> </div> <div class="swiper-slide"> <img src="images/men-02.jpg" alt=""> <div class="swiper__text"> <h2>Air Force 1 X</h2> <div class="stars"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </div> <p class="title">$90.00</p> <div class="details_swiper"> <div class="icon"> <i class="fa-solid fa-eye"></i> </div> <div class="icon"> <i class="fa-solid fa-star"></i> </div> <div class="icon"> <i class="fa-solid fa-cart-shopping"></i> </div> </div> </div> <div class="swiper-slide"> <img src="images/men-03.jpg" alt=""> <div class="swiper__text"> <h2>Classic Spring</h2> <div class="stars"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </div> <p class="title">$120.00</p> <div class="details_swiper"> <div class="icon"> <i class="fa-solid fa-eye"></i> </div> <div class="icon"> <i class="fa-solid fa-star"></i> </div> <div class="icon"> <i class="fa-solid fa-cart-shopping"></i> </div> </div> </div> </div> <div class="swiper-pagination"></div> <!-- <div class="swiper-button-next"></div> <div class="swiper-button-prev"></div> --> </div> </section> </div> <hr> <!-- Women --> <div class="container"> <section class="men"> <h2 class="header">Women's Latest</h2> <p class="title">Details to details is what makes Hexashop different from the other themes.</p> <div class="swiper mySwiper"> <div class="swiper-wrapper"> <div class="swiper-slide"> <img src="images/women-01.jpg" alt=""> <div class="swiper__text"> <h2>Classic Spring</h2> <div class="stars"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </div> <p class="title">$120.00</p> <div class="details_swiper"> <div class="icon"> <i class="fa-solid fa-eye"></i> </div> <div class="icon"> <i class="fa-solid fa-star"></i> </div> <div class="icon"> <i class="fa-solid fa-cart-shopping"></i> </div> </div> </div> <div class="swiper-slide"> <img src="images/women-01.jpg" alt=""> <div class="swiper__text"> <h2>New Green Jacket</h2> <div class="stars"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </div> <p class="title">$75.00</p> <div class="details_swiper"> <div class="icon"> <i class="fa-solid fa-eye"></i> </div> <div class="icon"> <i class="fa-solid fa-star"></i> </div> <div class="icon"> <i class="fa-solid fa-cart-shopping"></i> </div> </div> </div><div class="swiper-slide"> <img src="images/women-02.jpg" alt=""> <div class="swiper__text"> <h2>Classic Dress</h2> <div class="stars"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </div> <p class="title">$45.00</p> <div class="details_swiper"> <div class="icon"> <i class="fa-solid fa-eye"></i> </div> <div class="icon"> <i class="fa-solid fa-star"></i> </div> <div class="icon"> <i class="fa-solid fa-cart-shopping"></i> </div> </div> </div><div class="swiper-slide"> <img src="images/women-03.jpg" alt=""> <div class="swiper__text"> <h2>Spring Collection</h2> <div class="stars"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </div> <p class="title">$130.00</p> <div class="details_swiper"> <div class="icon"> <i class="fa-solid fa-eye"></i> </div> <div class="icon"> <i class="fa-solid fa-star"></i> </div> <div class="icon"> <i class="fa-solid fa-cart-shopping"></i> </div> </div> </div> <div class="swiper-slide"> <img src="images/women-01.jpg" alt=""> <div class="swiper__text"> <h2>Classic Spring</h2> <div class="stars"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </div> <p class="title">$90.00</p> <div class="details_swiper"> <div class="icon"> <i class="fa-solid fa-eye"></i> </div> <div class="icon"> <i class="fa-solid fa-star"></i> </div> <div class="icon"> <i class="fa-solid fa-cart-shopping"></i> </div> </div> </div> <div class="swiper-slide"> <img src="images/women-01.jpg" alt=""> <div class="swiper__text"> <h2>New Green Jacket</h2> <div class="stars"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </div> <p class="title">$120.00</p> <div class="details_swiper"> <div class="icon"> <i class="fa-solid fa-eye"></i> </div> <div class="icon"> <i class="fa-solid fa-star"></i> </div> <div class="icon"> <i class="fa-solid fa-cart-shopping"></i> </div> </div> </div> </div> <div class="swiper-pagination"></div> <!-- <div class="swiper-button-next"></div> <div class="swiper-button-prev"></div> --> </div> </section> </div> <hr> <!-- Kids --> <div class="container"> <section class="men"> <h2 class="header">Kid's Latest</h2> <p class="title">Details to details is what makes Hexashop different from the other themes.</p> <div class="swiper mySwiper"> <div class="swiper-wrapper"> <div class="swiper-slide"> <img src="images/kid-01.jpg" alt=""> <div class="swiper__text"> <h2>School Collection</h2> <div class="stars"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </div> <p class="title">$80.00</p> <div class="details_swiper"> <div class="icon"> <i class="fa-solid fa-eye"></i> </div> <div class="icon"> <i class="fa-solid fa-star"></i> </div> <div class="icon"> <i class="fa-solid fa-cart-shopping"></i> </div> </div> </div> <div class="swiper-slide"> <img src="images/kid-02.jpg" alt=""> <div class="swiper__text"> <h2>Summer Camp</h2> <div class="stars"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </div> <p class="title">$12.00</p> <div class="details_swiper"> <div class="icon"> <i class="fa-solid fa-eye"></i> </div> <div class="icon"> <i class="fa-solid fa-star"></i> </div> <div class="icon"> <i class="fa-solid fa-cart-shopping"></i> </div> </div> </div><div class="swiper-slide"> <img src="images/kid-03.jpg" alt=""> <div class="swiper__text"> <h2>Classic Kid</h2> <div class="stars"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </div> <p class="title">$30.00</p> <div class="details_swiper"> <div class="icon"> <i class="fa-solid fa-eye"></i> </div> <div class="icon"> <i class="fa-solid fa-star"></i> </div> <div class="icon"> <i class="fa-solid fa-cart-shopping"></i> </div> </div> </div><div class="swiper-slide"> <img src="images/kid-01.jpg" alt=""> <div class="swiper__text"> <h2>Classic Spring</h2> <div class="stars"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </div> <p class="title">$120.00</p> <div class="details_swiper"> <div class="icon"> <i class="fa-solid fa-eye"></i> </div> <div class="icon"> <i class="fa-solid fa-star"></i> </div> <div class="icon"> <i class="fa-solid fa-cart-shopping"></i> </div> </div> </div> <div class="swiper-slide"> <img src="images/kid-01.jpg" alt=""> <div class="swiper__text"> <h2>School Collection</h2> <div class="stars"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </div> <p class="title">80.00</p> <div class="details_swiper"> <div class="icon"> <i class="fa-solid fa-eye"></i> </div> <div class="icon"> <i class="fa-solid fa-star"></i> </div> <div class="icon"> <i class="fa-solid fa-cart-shopping"></i> </div> </div> </div> <div class="swiper-slide"> <img src="images/kid-02.jpg" alt=""> <div class="swiper__text"> <h2>Summer Camp</h2> <div class="stars"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> </div> </div> <p class="title">$12.00</p> <div class="details_swiper"> <div class="icon"> <i class="fa-solid fa-eye"></i> </div> <div class="icon"> <i class="fa-solid fa-star"></i> </div> <div class="icon"> <i class="fa-solid fa-cart-shopping"></i> </div> </div> </div> </div> <div class="swiper-pagination"></div> <!-- <div class="swiper-button-next"></div> <div class="swiper-button-prev"></div> --> </div> </section> </div> <hr> <div class="container"> <section class="products"> <div class="grid"> <div class="left__products"> <h2 class="header">Explore Our Products</h2> <p class="normal">You are allowed to use this HexaShop HTML CSS template. You can feel free to modify or edit this layout. You can convert this template as any kind of ecommerce CMS theme as you wish.</p> <div class="quote"> <i class="fa-solid fa-quote-left"></i> <p>You are not allowed to redistribute this template ZIP file on any other website.</p> </div> <p class="normal">There are 5 pages included in this HexaShop Template and we are providing it to you for absolutely free of charge at our TemplateMo website. There are web development costs for us.</p> <p class="normal">If this template is beneficial for your website or business, please kindly support us a little via PayPal. Please also tell your friends about our great website. Thank you.</p> <button class="btn more">Discover More</button> </div> <div class="top1__products"> <h3 class="f-1">Leather Pags</h3> <p>Latest Collection</p> </div> <div class="top2__products"></div> <div class="bottom1__products"></div> <div class="bottom2__products"> <h3 class="f-1">Different Types</h3> <p>Over 304 Products</p> </div> </div> </section> </div> <hr> <div class="container"> <section class="media"> <h2 class="header">Social Media</h2> <p>Details to details is what makes Hexashop different from the other themes.</p> <div class="grid"> <div class="img__content"> <img src="images/instagram-01.jpg" alt=""> <div class="img__details"> <p class="normal">Fashion</p> <i class="fa-brands fa-instagram"></i> </div> </div> <div class="img__content"> <img src="images/instagram-02.jpg" alt=""> <div class="img__details"> <p class="normal">Fashion</p> <i class="fa-brands fa-instagram"></i> </div> </div> <div class="img__content"> <img src="images/instagram-03.jpg" alt=""> <div class="img__details"> <p class="normal">Fashion</p> <i class="fa-brands fa-instagram"></i> </div> </div> <div class="img__content"> <img src="images/instagram-04.jpg" alt=""> <div class="img__details"> <p class="normal">Fashion</p> <i class="fa-brands fa-instagram"></i> </div> </div> <div class="img__content"> <img src="images/instagram-05.jpg" alt=""> <div class="img__details"> <p class="normal">Fashion</p> <i class="fa-brands fa-instagram"></i> </div> </div> <div class="img__content"> <img src="images/instagram-06.jpg" alt=""> <div class="img__details"> <p class="normal">Fashion</p> <i class="fa-brands fa-instagram"></i> </div> </div> </div> </section> </div> <hr> <!-- Subscribe --> <div class="container"> <section class="sub"> <div class="grid"> <div class="left__sub"> <h2 class="header">By Subscribing To Our Newsletter You Can Get 30% Off</h2> <p>Details to details is what makes Hexashop different from the other themes.</p> <form action=""> <input class="name" type="name" placeholder="Your Name"> <input class="email" type="email" placeholder="Your Email Addres"> <button class="enviar" value="Send"><i class="fa-brands fa-telegram"></i></button> </form> </div> <div class="right1__sub"> <h4>Store Location:</h4> <p class="normal">Sunny Isles Beach, FL 33160, United States</p> <h4>Phone:</h4> <p class="normal">010-020-0340</p> <h4>Office Location:</h4> <p class="normal">North Miami Beach</p> </div> <div class="right2__sub"> <h4>Work Hours:</h4> <p class="normal">07:30 AM - 9:30 PM Daily </p> <h4>Email:</h4> <p class="normal">info@company.com</p> <h4>Social Media:</h4> <p class="normal">Facebook, Instagram, Behance, Linkedin</p> </div> </div> </section> </div> <footer> <div class="container"> <div class="grid"> <div class="column"> <img src="images/white-logo.png" alt=""> <p class="normal">16501 Collins Ave, Sunny Isles Beach, FL 33160, United States</p> <p class="normal">hexashop@company.com</p> <p class="normal">010-020-0340</p> </div> <div class="column"> <h4>Shopping & Categories</h4> <ul> <li>Men's Shopping</li> <li>Womens's Shopping</li> <li>Kid's Shopping</li> </ul> </div> <div class="column"> <h4>Useful Links</h4> <ul> <li>Homepage</li> <li>About Us</li> <li>Help</li> <li>Contact Us</li> </ul> </div> <div class="column"> <h4>Help & Information</h4> <ul> <li>Help</li> <li>FAQ'S</li> <li>Shipping</li> <li>Tracking ID</li> </ul> </div> </div> <div class="copy"> <p>Copyright © 2022 HexaShop Co., Ltd. All Rights Reserved.</p> <i class="fa-brands fa-instagram"></i> <i class="fa-brands fa-linkedin"></i> <i class="fa-brands fa-twitter"></i> <i class="fa-brands fa-facebook"></i> </div> </div> </footer> <!-- Swiper Js --> <script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script> <script> var swiper = new Swiper(".mySwiper", { slidesPerView: 3, spaceBetween: 30, pagination: { el: ".swiper-pagination", clickable: true, }, breakpoints: { 1080: { slidesPerView: 3, spaceBetween: 20 }, 768: { slidesPerView: 2, spaceBetween: 40, }, 500: { slidesPerView: 1, spaceBetween: 20, }, 310: { slidesPerView: 1, spaceBetween: 20, } }, }); </script> <script src="app.js"></script> </body> </html>
///How much power it costs to deconstruct an item. #define DESTRUCTIVE_ANALYZER_POWER_USAGE (BASE_MACHINE_IDLE_CONSUMPTION * 2.5) ///The 'ID' for deconstructing items for Research points instead of nodes. #define DESTRUCTIVE_ANALYZER_DESTROY_POINTS "research_points" /** * ## Destructive Analyzer * It is used to destroy hand-held objects and advance technological research. */ /obj/machinery/rnd/destructive_analyzer name = "destructive analyzer" desc = "Learn science by destroying things!" icon_state = "d_analyzer" base_icon_state = "d_analyzer" circuit = /obj/item/circuitboard/machine/destructive_analyzer /obj/machinery/rnd/destructive_analyzer/Initialize(mapload) . = ..() register_context() /obj/machinery/rnd/destructive_analyzer/add_context(atom/source, list/context, obj/item/held_item, mob/living/user) if(loaded_item) context[SCREENTIP_CONTEXT_ALT_LMB] = "Remove Item" else if(!isnull(held_item)) context[SCREENTIP_CONTEXT_LMB] = "Insert Item" return CONTEXTUAL_SCREENTIP_SET /obj/machinery/rnd/destructive_analyzer/attackby(obj/item/weapon, mob/living/user, params) if(user.combat_mode) return ..() if(!is_insertion_ready(user)) return ..() if(!user.transferItemToLoc(weapon, src)) to_chat(user, span_warning("\The [weapon] is stuck to your hand, you cannot put it in the [name]!")) return TRUE busy = TRUE loaded_item = weapon to_chat(user, span_notice("You add the [weapon.name] to the [name]!")) flick("[base_icon_state]_la", src) addtimer(CALLBACK(src, PROC_REF(finish_loading)), 1 SECONDS) return TRUE /obj/machinery/rnd/destructive_analyzer/AltClick(mob/user) . = ..() unload_item() /obj/machinery/rnd/destructive_analyzer/update_icon_state() icon_state = "[base_icon_state][loaded_item ? "_l" : null]" return ..() /obj/machinery/rnd/destructive_analyzer/ui_interact(mob/user, datum/tgui/ui) ui = SStgui.try_update_ui(user, src, ui) if(!ui) ui = new(user, src, "DestructiveAnalyzer") ui.open() /obj/machinery/rnd/destructive_analyzer/ui_data(mob/user) var/list/data = list() data["server_connected"] = !!stored_research data["node_data"] = list() if(loaded_item) data["item_icon"] = icon2base64(getFlatIcon(image(icon = loaded_item.icon, icon_state = loaded_item.icon_state), no_anim = TRUE)) data["indestructible"] = !(loaded_item.resistance_flags & INDESTRUCTIBLE) data["loaded_item"] = loaded_item data["already_deconstructed"] = !!stored_research.deconstructed_items[loaded_item.type] var/list/points = techweb_item_point_check(loaded_item) data["recoverable_points"] = techweb_point_display_generic(points) var/list/boostable_nodes = techweb_item_unlock_check(loaded_item) for(var/id in boostable_nodes) var/datum/techweb_node/unlockable_node = SSresearch.techweb_node_by_id(id) var/list/node_data = list() node_data["node_name"] = unlockable_node.display_name node_data["node_id"] = unlockable_node.id node_data["node_hidden"] = !!stored_research.hidden_nodes[unlockable_node.id] data["node_data"] += list(node_data) else data["loaded_item"] = null return data /obj/machinery/rnd/destructive_analyzer/ui_static_data(mob/user) var/list/data = list() data["research_point_id"] = DESTRUCTIVE_ANALYZER_DESTROY_POINTS return data /obj/machinery/rnd/destructive_analyzer/ui_act(action, params, datum/tgui/ui) . = ..() if(.) return var/mob/user = usr switch(action) if("eject_item") if(busy) balloon_alert(user, "already busy!") return TRUE if(loaded_item) unload_item() return TRUE if("deconstruct") if(!user_try_decon_id(params["deconstruct_id"])) say("Destructive analysis failed!") return TRUE //This allows people to put syndicate screwdrivers in the machine. Secondary act still passes. /obj/machinery/rnd/destructive_analyzer/screwdriver_act(mob/living/user, obj/item/tool) return FALSE ///Drops the loaded item where it can and nulls it. /obj/machinery/rnd/destructive_analyzer/proc/unload_item() if(!loaded_item) return FALSE playsound(loc, 'sound/machines/terminal_insert_disc.ogg', 30, FALSE) loaded_item.forceMove(drop_location()) loaded_item = null update_appearance(UPDATE_ICON) return TRUE ///Called in a timer callback after loading something into it, this handles resetting the 'busy' state back to its initial state ///So the machine can be used. /obj/machinery/rnd/destructive_analyzer/proc/finish_loading() update_appearance(UPDATE_ICON) reset_busy() /** * Destroys an item by going through all its contents (including itself) and calling destroy_item_individual * Args: * gain_research_points - Whether deconstructing each individual item should check for research points to boost. */ /obj/machinery/rnd/destructive_analyzer/proc/destroy_item(gain_research_points = FALSE) if(QDELETED(loaded_item) || QDELETED(src)) return FALSE flick("[base_icon_state]_process", src) busy = TRUE addtimer(CALLBACK(src, PROC_REF(reset_busy)), 2.4 SECONDS) use_power(DESTRUCTIVE_ANALYZER_POWER_USAGE) var/list/all_contents = loaded_item.get_all_contents() for(var/innerthing in all_contents) destroy_item_individual(innerthing, gain_research_points) loaded_item = null update_appearance(UPDATE_ICON) return TRUE /** * Destroys the individual provided item * Args: * thing - The thing being destroyed. Generally an object, but it can be a mob too, such as intellicards and pAIs. * gain_research_points - Whether deconstructing this should give research points to the stored techweb, if applicable. */ /obj/machinery/rnd/destructive_analyzer/proc/destroy_item_individual(obj/item/thing, gain_research_points = FALSE) if(isliving(thing)) var/mob/living/mob_thing = thing if(mob_thing.stat != DEAD) mob_thing.investigate_log("has been killed by a destructive analyzer.", INVESTIGATE_DEATHS) mob_thing.death() var/list/point_value = techweb_item_point_check(thing) if(point_value && !stored_research.deconstructed_items[thing.type]) stored_research.deconstructed_items[thing.type] = TRUE stored_research.add_point_list(list(TECHWEB_POINT_TYPE_GENERIC = point_value)) qdel(thing) /** * Attempts to destroy the loaded item using a provided research id. * Args: * id - The techweb ID node that we're meant to unlock if applicable. */ /obj/machinery/rnd/destructive_analyzer/proc/user_try_decon_id(id) if(!istype(loaded_item)) return FALSE if(isnull(id)) return FALSE if(id == DESTRUCTIVE_ANALYZER_DESTROY_POINTS) if(!destroy_item(gain_research_points = TRUE)) return FALSE return TRUE var/datum/techweb_node/node_to_discover = SSresearch.techweb_node_by_id(id) if(!istype(node_to_discover)) return FALSE if(!destroy_item()) return FALSE SSblackbox.record_feedback("nested tally", "item_deconstructed", 1, list("[node_to_discover.id]", "[loaded_item.type]")) stored_research.unhide_node(node_to_discover) return TRUE #undef DESTRUCTIVE_ANALYZER_DESTROY_POINTS #undef DESTRUCTIVE_ANALYZER_POWER_USAGE
const hobbies = ['watching anime', 'gaming', 'cooking'] console.log(hobbies) // Accessing array elements const famousSayings = ['Fortune favors the brave.', 'A joke is a very serious thing.', 'Where there is love there is life.'] let listItem = famousSayings[0] console.log(famousSayings[2]) // Update Elements let groceryList = ['bread', 'tomatoes', 'milk'] groceryList[1] = 'avocados' console.log(groceryList) // Arrays with let and const let condiments = ['Ketchup', 'Mustard', 'Soy Sauce', 'Sriracha'] const utensils = ['Fork', 'Knife', 'Chopsticks', 'Spork'] condiments[0] = 'Mayo' console.log(condiments) condiments = ['Mayo'] console.log(condiments) utensils[3] = 'Spoon' console.log(utensils) // The .push() Method const chores = ['wash dishes', 'do laundry', 'take out trash']; chores.push('sweep', 'clean') console.log(chores) // the .pop() Method const chores2 = ['wash dishes', 'do laundry', 'take out trash', 'cook dinner', 'mop floor']; chores2.pop() // More Array Methods const groceryList2 = ['orange juice', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains']; groceryList2.shift() groceryList2.unshift('popcorn') // console.log(groceryList2.slice(1, 4)) const pastaIndex = groceryList2.indexOf('pasta') console.log(pastaIndex)
import 'package:flutter/material.dart'; import 'package:fwc_album_app/app/core/ui/styles/button_styles.dart'; import 'package:fwc_album_app/app/core/ui/styles/colors_app.dart'; import 'package:fwc_album_app/app/core/ui/styles/text_styles.dart'; import 'package:fwc_album_app/app/core/ui/widgets/button.dart'; import 'package:fwc_album_app/app/pages/home/presenter/home_presenter.dart'; import 'package:fwc_album_app/app/pages/home/view/home_view_impl.dart'; import 'package:fwc_album_app/app/pages/home/widgets/status_tile.dart'; import 'widgets/sticker_percent_widget.dart'; class HomePage extends StatefulWidget { final HomePresenter presenter; const HomePage({super.key, required this.presenter}); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends HomeViewImpl { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: context.colors.primary, appBar: AppBar( elevation: 0, backgroundColor: context.colors.primary, actions: [ IconButton( onPressed: () => widget.presenter.logout(), icon: const Icon(Icons.logout), color: Colors.white, ) ], ), body: Container( decoration: const BoxDecoration( image: DecorationImage( image: AssetImage('assets/images/background.png'), fit: BoxFit.cover, ), ), child: LayoutBuilder( builder: (_, constrains) { return ConstrainedBox( constraints: BoxConstraints( minHeight: constrains.maxHeight, ), child: Center( child: SingleChildScrollView( child: Column( children: [ Container( padding: const EdgeInsets.only(bottom: 35), width: MediaQuery.of(context).size.width, child: Image.asset('assets/images/bola.png', fit: BoxFit.cover), ), StickerPercentWidget( percent: user?.totalCompletePercent ?? 0, ), const SizedBox( height: 20, ), Text( '${user?.totalStickers ?? 0} figurinhas', style: context.textStyles.titleWhite, ), const SizedBox( height: 20, ), StatusTile( icon: Image.asset('assets/images/all_icon.png'), label: 'All', value: user?.totalAlbum ?? 0, ), const SizedBox( height: 20, ), StatusTile( icon: Image.asset('assets/images/missing_icon.png'), label: 'Missing', value: user?.totalComplete ?? 0, ), const SizedBox( height: 20, ), StatusTile( icon: Image.asset('assets/images/repeated_icon.png'), label: 'Repeated', value: user?.totalDuplicates ?? 0, ), const SizedBox( height: 40, ), Button( label: 'My stickers', onPressed: () { Navigator.of(context).pushNamed('/my-stickers'); }, width: MediaQuery.of(context).size.width * .9, outline: true, style: context.buttonStyles.yellowOutlineButton, labelStyle: context.textStyles.textSecondaryExtraBold .copyWith(color: context.colors.yellow), ) ], ), ), ), ); }, )), ); } }
autoload :Money, "money" module Gilt class Sku CURRENCY = "USD" FOR_SALE = "for sale" RESERVED = "reserved" SOLD_OUT = "sold out" def initialize(sku_response) @sku = sku_response end def id @sku["id"].to_i end def inventory_status @sku["inventory_status"] end def for_sale? inventory_status == FOR_SALE end def sold_out? inventory_status == SOLD_OUT end def reserved? inventory_status == RESERVED end def msrp_price to_dollars @sku["msrp_price"] end def sale_price to_dollars @sku["sale_price"] end def shipping_surcharge surcharge = @sku["shipping_surcharge"] to_dollars surcharge.nil? ? 0 : surcharge end def subtotal sale_price + shipping_surcharge end def attributes pairs = @sku["attributes"].map do |pair| [pair["name"].intern, pair["value"]] end Hash[pairs] end def sale? sale_price != msrp_price end private def to_dollars(price) ::Money.from_string(price, CURRENCY) end end end
import React, { useEffect } from 'react'; import PropTypes from 'prop-types'; import { useTranslation } from 'react-i18next'; import config from 'config/config'; import { Select } from 'components/UI'; import axiosInstance from 'auth/axiosInstance'; import { useRouter } from 'next/router'; import { useSavedState } from 'hooks'; export default function CompanySearch({ companyId, fetchReport, ...reset }) { const { t } = useTranslation('common'); const [defaultOptions, setDefaultOptions, clearDefaultOptions] = useSavedState([], "telgani-b2b-company-cache"); const router = useRouter(); const language = router.locale.toLowerCase(); useEffect(() => { const fetchData = async () => { await axiosInstance.get(`${config.apiGateway.API_URL_TELGANI}/v2/supplier/business/company/collection`) .then(({ data }) => { const company = (data?.data || [])?.map((c) => { return { value: c.uuid, label: language == 'en' ? c.name.en : c.name.ar, }; }); setDefaultOptions(company) }); }; !defaultOptions.length && fetchData(); }, []) return ( <Select label={t('company_key')} // mandatory // async={true} // loadOptions={CompanySearch} options={defaultOptions} isDisabled={false} value={companyId.value} onChange={(value) => { companyId.changeValue(value); fetchReport && fetchReport({ companyId: value }); }} {...reset} // defaultValue={[{label:"ss",value:"va"}]} /> ); } CompanySearch.propTypes = { companyId: PropTypes.shape({ value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), changeValue: PropTypes.func, }).isRequired, fetchReport: PropTypes.func, }; // import React, { useEffect, useState } from 'react'; // import PropTypes from 'prop-types'; // import { useTranslation } from 'react-i18next'; // import config from 'config/config'; // import { Select } from 'components/UI'; // import axiosInstance from 'auth/axiosInstance'; // import { useRouter } from 'next/router'; // export default function CompanySearch({ companyId, fetchReport, ...reset }) { // const { t } = useTranslation('common'); // const [defaultOptions, setDefaultOptions] = useState([]); // const router = useRouter(); // const language = router.locale.toLowerCase(); // useEffect(() => { // const fetchData = async () => { // await CompanySearch("a", (data) => setDefaultOptions(data)); // }; // fetchData(); // }, []) // const CompanySearch = (inputValue, callback) => { // if (!inputValue) { // return callback([]); // } else { // axiosInstance // .get( // `${config.apiGateway.API_URL_TELGANI}/v2/supplier/business/company/collection?search[value]=${inputValue}&start=0&length=10&is_export=false` // ) // .then(({ data }) => { // const company = data.data; // if (!company?.length) { // return callback([]); // } // return callback( // [...company]?.map((c) => { // return { // value: c.uuid, // label: language == 'en' ? c.name.en : c.name.ar, // }; // }) // ); // }); // } // }; // return ( // <Select // label={t('company_key')} // mandatory // async={true} // loadOptions={CompanySearch} // isDisabled={false} // value={companyId.value} // onChange={(value) => { // companyId.changeValue(value); // fetchReport && fetchReport({ company: value }); // }} // {...reset} // defaultOptions={defaultOptions} // // defaultValue={[{label:"ss",value:"va"}]} // /> // ); // } // CompanySearch.propTypes = { // companyId: PropTypes.shape({ // value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), // changeValue: PropTypes.func, // }).isRequired, // fetchReport: PropTypes.func, // };
# Current Thread Scheduler import time import logging import threading from datetime import timedelta from rx import config from rx.core import Scheduler from rx.internal import PriorityQueue from .schedulerbase import SchedulerBase from .scheduleditem import ScheduledItem log = logging.getLogger('Rx') class Trampoline(object): @classmethod def run(cls, queue): while len(queue): item = queue.dequeue() if not item.is_cancelled(): diff = item.duetime - item.scheduler.now while diff > timedelta(0): seconds = diff.seconds + diff.microseconds / 1E6 + diff.days * 86400 log.warning("Do not schedule blocking work!") time.sleep(seconds) diff = item.duetime - item.scheduler.now if not item.is_cancelled(): item.invoke() class CurrentThreadScheduler(SchedulerBase): """Represents an object that schedules units of work on the current thread. You never want to schedule timeouts using the CurrentThreadScheduler since it will block the current thread while waiting.""" def __init__(self): """Gets a scheduler that schedules work as soon as possible on the current thread.""" self.queues = dict() self.lock = config["concurrency"].RLock() def schedule(self, action, state=None): """Schedules an action to be executed.""" log.debug("CurrentThreadScheduler.schedule(state=%s)", state) return self.schedule_relative(timedelta(0), action, state) def schedule_relative(self, duetime, action, state=None): """Schedules an action to be executed after duetime.""" duetime = self.to_timedelta(duetime) dt = self.now + SchedulerBase.normalize(duetime) si = ScheduledItem(self, state, action, dt) queue = self.queue if queue is None: queue = PriorityQueue(4) queue.enqueue(si) self.queue = queue try: Trampoline.run(queue) finally: self.queue = None else: queue.enqueue(si) return si.disposable def schedule_absolute(self, duetime, action, state=None): """Schedules an action to be executed at duetime.""" duetime = self.to_datetime(duetime) return self.schedule_relative(duetime - self.now, action, state=None) def get_queue(self): ident = threading.current_thread().ident with self.lock: return self.queues.get(ident) def set_queue(self, queue): ident = threading.current_thread().ident with self.lock: self.queues[ident] = queue queue = property(get_queue, set_queue) def schedule_required(self): """Test if scheduling is required. Gets a value indicating whether the caller must call a schedule method. If the trampoline is active, then it returns False; otherwise, if the trampoline is not active, then it returns True. """ return self.queue is None def ensure_trampoline(self, action): """Method for testing the CurrentThreadScheduler.""" if self.schedule_required(): return self.schedule(action) else: return action(self, None) Scheduler.current_thread = current_thread_scheduler = CurrentThreadScheduler()
#include <stdio.h> #include <ncurses.h> #define WIDTH 30 #define HEIGHT 10 #define ENTER 10 int startx = 0; int starty = 0; char *choices[] = { "Play Game", /*"Set Bodies",*/ "Exit", }; int n_choices = sizeof(choices) / sizeof(char *); void print_menu(WINDOW *menu_win, int highlight); int game_menu(); int game_menu() { WINDOW *menu_win; int highlight = 1; int choice = 0; int c; int X_MAX, Y_MAX; initscr(); clear(); noecho(); cbreak(); /* Line buffering disabled. pass on everything */ getmaxyx(stdscr, Y_MAX, X_MAX); startx = (X_MAX - WIDTH) / 2; starty = (Y_MAX - HEIGHT) / 2; menu_win = newwin(HEIGHT, WIDTH, starty, startx); keypad(menu_win, TRUE); print_menu(menu_win, highlight); while(1) { c = wgetch(menu_win); switch(c) { case KEY_UP: if(highlight == 1) highlight = n_choices; else --highlight; clear(); refresh(); break; case KEY_DOWN: if(highlight == n_choices) highlight = 1; else ++highlight; clear(); refresh(); break; case ENTER: choice = highlight; clear(); refresh(); break; default: mvprintw(Y_MAX/2 + n_choices + 3, X_MAX/2 - 21, "Press UP, DOWN to choose & ENTER to select"); refresh(); break; } print_menu(menu_win, highlight); if(choice != 0) /* User did a choice come out of the infinite loop */ break; } clrtoeol(); refresh(); endwin(); return choice; } void print_menu(WINDOW *menu_win, int highlight) { int x, y, i; x = 2; y = 2; box(menu_win, 0, 0); for(i = 0; i < n_choices; ++i) { if(highlight == i + 1) /* High light the present choice */ { wattron(menu_win, A_REVERSE); mvwprintw(menu_win, y, x, "%s", choices[i]); wattroff(menu_win, A_REVERSE); } else mvwprintw(menu_win, y, x, "%s", choices[i]); ++y; } wrefresh(menu_win); }
import { extractIngredients, sanitize } from "./recipeUtilities.js"; export const getTitle = async (page, requestURL) => { const titleElement = await page.locator("h1"); if (!titleElement) { throw new Error(`Title not found on this page ${requestURL}`); } const rawTitle = await titleElement.textContent(); const title = sanitize(rawTitle); return title; }; export const getImage = async (page, requestURL) => { const imageElements = await page.$$(".relative > img"); if (!imageElements || imageElements.length === 0) { throw new Error(`Images not found on this page ${requestURL}`); } const imageElement = imageElements[1]; if (!imageElement) { throw new Error(`Image not found on this page ${requestURL}`); } const rawImageURL = await imageElement.getAttribute("srcset"); if (!rawImageURL) { throw new Error("Raw Image URL not found on this page"); } const imageURL = rawImageURL.split("?")[0]; if (!imageURL) { throw new Error(`Image URL not found on this page ${requestURL}`); } return imageURL; }; export const getIngredients = async (page, requestURL) => { const ingredientElements = await page.$$(".cts-impression-item > div"); if (!ingredientElements) { throw new Error(`Ingredients not found on this page ${requestURL}`); } const ingredients = await extractIngredients(ingredientElements); const stringifiedIngredients = JSON.stringify(ingredients); return stringifiedIngredients; }; export const getRecipeCharacteristics = async (page, requestURL) => { const characteristicsElements = await page.$$( "span.text-1r6.text-ui-greyscale-grey-7.whitespace-nowrap.print\\:text-black" ); if (!characteristicsElements || characteristicsElements.length === 0) { throw new Error(`Category not found on this page ${requestURL}`); } const characteristics = []; for (const characteristicElement of characteristicsElements) { const characteristic = await characteristicElement.textContent(); characteristics.push(characteristic); } return characteristics; }; export const getInstructions = async (page, requestURL) => { const instructionsElements = await page.$$(".mt-0r6.leading-normal"); if (!instructionsElements || instructionsElements.length === 0) { throw new Error(`Instructions not found on this page ${requestURL}`); } const instructions = []; for (const instructionElement of instructionsElements) { const instruction = await instructionElement.textContent(); instructions.push(sanitize(instruction)); } const stringifiedInstructions = JSON.stringify(instructions); return stringifiedInstructions; };
import styles from "./Home.module.css"; import Footer from "../components/Footer"; import Hero from "../components/Hero"; import NavBar from "../components/NavBar"; import ProductCard from "./ProductCard"; import products from "../assets/products.js"; function Home() { return ( <> <NavBar /> {/* <Hero/> */} <Hero first="tecnología" second="renovada -Hola mundo" /> <main> <div className={styles["product-container"]} id="products"> {/* <a className={styles["product-card"]} href="./details.html"> <img className={styles["product-img"]} src="https://i.postimg.cc/kX8PKZpq/ipad2.jpg" alt="iPad Pro 12.9" /> <div className={styles["product-info"]}> <span className={styles["product-title"]}>iPad Pro 12.9</span> <span className={styles["product-description"]}>Silver</span> <div className={styles["product-price-block"]}> <span className={styles["product-price"]}>900000</span> <span className={styles["product-discount"]}>50% Off</span> </div> <div className={styles["product-tax-policy"]}> Incluye impuesto País y percepción AFIP </div> </div> </a> <a className={styles["product-card"]} href="./details.html"> <img className={styles["product-img"]} src="https://i.postimg.cc/kX8PKZpq/ipad2.jpg" alt="iPad Pro 12.9" /> <div className={styles["product-info"]}> <span className={styles["product-title"]}>iPad Pro 12.9</span> <span className={styles["product-description"]}>Silver</span> <div className={styles["product-price-block"]}> <span className={styles["product-price"]}>900000</span> <span className={styles["product-discount"]}>50% Off</span> </div> <div className={styles["product-tax-policy"]}> Incluye impuesto País y percepción AFIP </div> </div> </a> <a className={styles["product-card"]} href="./details.html"> <img className={styles["product-img"]} src="https://i.postimg.cc/kX8PKZpq/ipad2.jpg" alt="iPad Pro 12.9" /> <div className={styles["product-info"]}> <span className={styles["product-title"]}>iPad Pro 12.9</span> <span className={styles["product-description"]}>Silver</span> <div className={styles["product-price-block"]}> <span className={styles["product-price"]}>900000</span> <span className={styles["product-discount"]}>50% Off</span> </div> <div className={styles["product-tax-policy"]}> Incluye impuesto País y percepción AFIP </div> </div> </a> <a className={styles["product-card"]} href="./details.html"> <img className={styles["product-img"]} src="https://i.postimg.cc/kX8PKZpq/ipad2.jpg" alt="iPad Pro 12.9" /> <div className={styles["product-info"]}> <span className={styles["product-title"]}>iPad Pro 12.9</span> <span className={styles["product-description"]}>Silver</span> <div className={styles["product-price-block"]}> <span className={styles["product-price"]}>900000</span> <span className={styles["product-discount"]}>50% Off</span> </div> <div className={styles["product-tax-policy"]}> Incluye impuesto País y percepción AFIP </div> </div> </a> <a className={styles["product-card"]} href="./details.html"> <img className={styles["product-img"]} src="https://i.postimg.cc/kX8PKZpq/ipad2.jpg" alt="iPad Pro 12.9" /> <div className={styles["product-info"]}> <span className={styles["product-title"]}>iPad Pro 12.9</span> <span className={styles["product-description"]}>Silver</span> <div className={styles["product-price-block"]}> <span className={styles["product-price"]}>900000</span> <span className={styles["product-discount"]}>50% Off</span> </div> <div className={styles["product-tax-policy"]}> Incluye impuesto País y percepción AFIP </div> </div> </a> <a className={styles["product-card"]} href="./details.html"> <img className={styles["product-img"]} src="https://i.postimg.cc/kX8PKZpq/ipad2.jpg" alt="iPad Pro 12.9" /> <div className={styles["product-info"]}> <span className={styles["product-title"]}>iPad Pro 12.9</span> <span className={styles["product-description"]}>Silver</span> <div className={styles["product-price-block"]}> <span className={styles["product-price"]}>900000</span> <span className={styles["product-discount"]}>50% Off</span> </div> <div className={styles["product-tax-policy"]}> Incluye impuesto País y percepción AFIP </div> </div> </a> */} {/* <ProductCard/> <ProductCard/> <ProductCard/> <ProductCard/> <ProductCard/> <ProductCard/> <ProductCard/> <ProductCard/> */} {/* {console.log("PRODUCTOS")} {console.log(products)} */} {products.map((product) => ( <ProductCard key={product.id} id={product.id} title={product.title} price={product.price} color={product.colors[0]} image={product.images[0]} /> ))} {/* Paréntesis en lugar de llaves: Usamos paréntesis () después de la flecha => para implicar que estamos retornando JSX directamente desde la función flecha. */} {/* Retorno Implícito: Al usar paréntesis, se está retornando implícitamente el JSX sin necesidad de una declaración return. */} {/* {products.map((each) => { return ( <ProductCard key={each.id} id={each.id} title={each.title} price={each.price} color={each.colors[0]} image={each.images[0]} /> ); })} */} {/* Para renderizar una lista de componentes en React, simplemente se usa map para devolver un arreglo de componentes JSX, y React se encargará de renderizarlos correctamente en el DOM. No se necesita usar .join('') para unir los elementos del arreglo, ya que React maneja los arreglos de elementos JSX de manera adecuada. */} </div> </main> <Footer /> </> ); } export default Home;
import React from 'react' import { ToastContainer, toast } from 'react-toastify' import 'react-toastify/dist/ReactToastify.css' import { useNavigate } from 'react-router-dom' import { Box, Button, Container, Flex, FormControl, FormLabel, Image, Input, Text, } from '@chakra-ui/react' import { Link } from 'react-router-dom' import { useState } from 'react' import { EmailIcon, ViewIcon } from '@chakra-ui/icons' const LoginPage = () => { const [userdetails, setuserdetails] = useState({ email: '', password: '' }) const handlechange = (e) => { const { name, value } = e.target setuserdetails({ ...userdetails, [name]: value }) } const [loading, setloading] = useState(false) const notify = () => toast('Login Succesfull', { autoClose: 1000, }) const navigate = useNavigate() const handlesubmit = async () => { setloading(true) let res = await fetch(`https://netmeds.onrender.com/login`, { method: 'POST', body: JSON.stringify(userdetails), headers: { 'Content-type': 'application/json', }, }) let data = await res.json() let decode = await fetch(`https://netmeds.onrender.com/decode`, { method: 'POST', body: JSON.stringify(data), headers: { 'Content-type': 'application/json', }, }) let decodejson = await decode.json() localStorage.setItem('userDetails', JSON.stringify(decodejson.user)) localStorage.setItem('cartid', JSON.stringify(decodejson.user._id)) localStorage.setItem('isLoggedIn', true); console.log(decodejson) setloading(false) if (data != undefined) { notify() navigate('/') } } const { email, password } = userdetails return ( <Flex bg={'rgb(247 246 246)'} height="100vh" flexDirection={'column'} alignItems="center" > <ToastContainer /> <Container bg={'white'} centerContent borderRadius={'16px'} width="70%" maxW="4xl" margin={'60px'} mb="20px" height="28rem" > <Flex> <Box height="25rem"> <Image width="140%" maxW={'988px'} position="relative" left="-4rem" borderRadius="16px" src="https://www.netmeds.com/images/cms/wysiwyg/cms/1588773798_sign-in-banner-new.png" /> </Box> <FormControl mt="3rem" ml="4rem"> <Text ml="15px" fontSize={'13px'} color="#24aeb1" paddingBlock={'3px'} > EMAIL </Text> <Flex> <EmailIcon mt="4px" alignItems={'center'} mr="10px" /> <Input paddingBlock={'3px'} height="24px" placeholder="Enter your email" fontSize={'16px'} value={email} variant={'flushed'} type="email" name="email" onChange={handlechange} /> </Flex> <br /> <Text ml="15px" fontSize={'13px'} color="#24aeb1" paddingBlock={'3px'} > PASSWORD </Text> <Flex> <ViewIcon mt="4px" alignItems={'center'} mr="10px"></ViewIcon> <Input paddingBlock={'3px'} height="24px" placeholder="Enter your Password" fontSize={'16px'} value={password} variant={'flushed'} name="password" type="password" onChange={handlechange} /> </Flex> <Button onClick={handlesubmit} mt="34px" bg={'rgb(50,174,177)'} color="white" fontSize="16px" paddingBlock={'10px'} height="41px" width={'100%'} _hover={{ background: 'rgb(50,174,177)' }} isLoading={loading} > LOGIN </Button> <br /> <br /> <Text textAlign={'center'}> If you don't have an account{' '} <Link style={{ color: 'rgb(240, 105, 154) ' }} to="/Signup"> Create an account </Link> </Text> <br /> <Container fontSize={'12px'} centerContent> <Text> By continuing you agree to our{' '} <Link color="rgb(240,105,154)"> Terms of service</Link> </Text> <Text> and{' '} <Link color="rgb(240,105,154)"> Privacy & Legal Policy</Link>. </Text> </Container> </FormControl> </Flex> </Container> </Flex> ) } export default LoginPage
--- title: <resolution> slug: Web/CSS/resolución tags: - CSS - CSS tipo de datos - Diseño - Estilos - Referencia translation_of: Web/CSS/resolution --- <div><section class="Quick_links" id="Quick_Links"><ol><li><strong><a href="/es/docs/Web/CSS">CSS</a></strong></li><li><strong><a href="/es/docs/Web/CSS/Reference">Referencia CSS</a></strong></li><li><strong><a href="/es/docs/Web/CSS/CSS_Types">CSS Types</a></strong></li><li class="toggle"><details open><summary>Propiedades</summary><ol><li><a href="/es/docs/Web/CSS/angle"><code>&lt;angle&gt;</code></a></li><li><a href="/es/docs/Web/CSS/basic-shape"><code>&lt;basic-shape&gt;</code></a></li><li><a href="/es/docs/Web/CSS/blend-mode"><code>&lt;blend-mode&gt;</code></a></li><li><a href="/es/docs/Web/CSS/custom-ident"><code>&lt;custom-ident&gt;</code></a> <a style="opacity: 0.5;" href="/es/docs/Web/CSS/custom-ident$translate">[Traducir]</a></li><li><a href="/es/docs/Web/CSS/frequency"><code>&lt;frequency&gt;</code></a></li><li><a href="/es/docs/Web/CSS/Gradiente"><code>&lt;gradient&gt;</code></a></li><li><a href="/es/docs/Web/CSS/image"><code>&lt;image&gt;</code></a></li><li><a href="/es/docs/Web/CSS/integer"><code>&lt;integer&gt;</code></a></li><li><a href="/es/docs/Web/CSS/length"><code>&lt;length&gt;</code></a></li><li><a href="/es/docs/Web/CSS/number"><code>&lt;number&gt;</code></a></li><li><a href="/es/docs/Web/CSS/porcentaje"><code>&lt;percentage&gt;</code></a></li><li><a href="/es/docs/Web/CSS/ratio"><code>&lt;ratio&gt;</code></a> <a style="opacity: 0.5;" href="/es/docs/Web/CSS/ratio$translate">[Traducir]</a></li><li><a href="/es/docs/Web/CSS/resoluci%C3%B3n"><code>&lt;resolution&gt;</code></a></li><li><span class="sidebar-icon"><span title="This deprecated API should no longer be used, but will probably still work."><i class="icon-thumbs-down-alt"> </i></span></span><a href="/es/docs/Web/CSS/shape"><code>&lt;shape&gt;</code></a> <a style="opacity: 0.5;" href="/es/docs/Web/CSS/shape$translate">[Traducir]</a></li><li><a href="/es/docs/Web/CSS/string"><code>&lt;string&gt;</code></a> <a style="opacity: 0.5;" href="/es/docs/Web/CSS/string$translate">[Traducir]</a></li><li><a href="/es/docs/Web/CSS/time"><code>&lt;time&gt;</code></a></li><li><a href="/es/docs/Web/CSS/timing-function"><code>&lt;timing-function&gt;</code></a> <a style="opacity: 0.5;" href="/es/docs/Web/CSS/timing-function$translate">[Traducir]</a></li><li><a href="/es/docs/Web/CSS/transform-function"><code>transform-function</code></a></li><li><a href="/es/docs/Web/CSS/url"><code>&lt;url&gt;</code></a> <a style="opacity: 0.5;" href="/es/docs/Web/CSS/url$translate">[Traducir]</a></li><li><a href="/es/docs/Web/CSS/color"><code>color</code></a></li><li><a href="/es/docs/Web/CSS/flex"><code>flex</code></a></li><li><a href="/es/docs/Web/CSS/position"><code>position</code></a></li></ol></details></li></ol></section></div> <h2 id="Summary" name="Summary">Resumen</h2> <p>El tipo de dato <a href="/en-US/docs/Web/CSS">CSS</a> <code>&lt;resolution&gt;</code>, usado en <a href="/en-US/docs/Web/Guide/CSS/Media_queries">media queries</a>,  define la densidad de píxeles de un dispositivo de salida, su resolución. Es un <a href="/es/docs/Web/CSS/number" title="Un valor para una propiedad CSS, un número incluyendo un valor entero integer."><code>&lt;number&gt;</code></a> inmediatamente seguido por una unidad de resolución (<code>dpi</code>, <code>dpcm</code>, ...). Como para cualquier dimensión CSS, no hay espacio entre la unidad literal y el número.</p> <p>En pantallas, la longitud está relacionada a centímetros, pulgadas o píxeles CSS, no en valores físicos.</p> <p>Incluso si todas las unidades representan la misma resolución para el valor 0, la unidad no se puede omitir en este caso, ya que no es un <a href="/es/docs/Web/CSS/length" title="El tipo de dato CSS &lt;length&gt; denota medidas de distancia. Es un valor &lt;number&gt; seguido por una unidad de longitud (px, em, pc, in, mm, …). Al igual que en cualquier dimensión CSS, no debe haber espacio entre la unidad y el número. La unidad de longitud es opcional después del valor &lt;number&gt; 0."><code>&lt;length&gt;</code></a>: <code>0</code> es inválida y no representa <code>0dpi</code>, <code>0dpcm</code>, ni <code>0dppx</code>.</p> <h2 id="Units" name="Units">Unidades</h2> <dl> <dt><code><a name="dpi">dpi</a></code></dt> <dd>Esta unidad representa el número de <a href="http://en.wikipedia.org/wiki/Dots_per_inch">dots per inch</a> (ppp en español), puntos por pulgada . A screen typically contains 72 or 96 dpi; a printed document usually reach much greater dpi. As 1 inch is 2.54 cm, <code>1dpi ≈ 0.39dpcm</code>.</dd> <dt><code><a name="dpcm">dpcm</a></code></dt> <dd>Esta unidad representa el número de  <a href="http://en.wikipedia.org/wiki/Dots_per_centimetre">dots per centimeter</a> (ppc en español), puntos por cm. 1 inch(pulgada) son 2.54 cm, <code>1dpcm ≈ 2.54dpi</code>.</dd> <dt><code><a name="dppx">dppx</a></code></dt> <dd>Esta unidad representa el número de puntos por unidad px. Debido a la relación fija de 1:96 CSS para CSS px, 1 px es equivalente a 96 dpi, que corresponde a la resolución predeterminada de las imágenes mostradas en CSS como se define por <a href="/es/docs/Web/CSS/image-resolution" title="La documentación acerca de este tema no ha sido escrita todavía . ¡Por favor considera contribuir !"><code>image-resolution</code></a>.</dd> </dl> <h2 id="Examples" name="Examples">Ejemplos</h2> <p>Éstos son algunos de los usos correctos de valores <code>&lt;resolution&gt;</code>:</p> <pre>96dpi Uso correcto: a <a href="/es/docs/Web/CSS/number" title="Un valor para una propiedad CSS, un número incluyendo un valor entero integer."><code>&lt;number&gt;</code></a> (here an <a href="/es/docs/Web/CSS/integer" title="Un valor entero usado para algunas propiedades CSS que no tiene unidades."><code>&lt;integer&gt;</code></a>) followed by the unit. @media print and (min-resolution: 300dpi) { ... } El uso correcto en el contexto de una <a href="/en-US/docs/Web/Guide/CSS/Media_queries">media query</a>. </pre> <p>Here are some incorrect uses:</p> <pre>72 dpi Incorecto: no hay espacios entre <a href="/es/docs/Web/CSS/number" title="Un valor para una propiedad CSS, un número incluyendo un valor entero integer."><code>&lt;number&gt;</code></a> y la unidad. ten dpi Incorecto: sólo deben ser utilizados dígitos. 0 Incorecto: la unidad se puede omitir por 0 sólo para valores <a href="/es/docs/Web/CSS/length" title="El tipo de dato CSS &lt;length&gt; denota medidas de distancia. Es un valor &lt;number&gt; seguido por una unidad de longitud (px, em, pc, in, mm, …). Al igual que en cualquier dimensión CSS, no debe haber espacio entre la unidad y el número. La unidad de longitud es opcional después del valor &lt;number&gt; 0."><code>&lt;length&gt;</code></a>. </pre> <h2 id="Specifications" name="Specifications">Especificación</h2> <table class="standard-table"> <thead> <tr> <th scope="col">Especificación</th> <th scope="col">Estado</th> <th scope="col">Comentario</th> </tr> </thead> <tbody> <tr> <td><a lang="en" href="https://drafts.csswg.org/css-values-3/#resolution" class="external" hreflang="en">CSS Values and Units Module Level 3<br><small lang="es">La definición de &apos;&lt;resolution&gt;&apos; en esta especificación.</small></a></td> <td><span class="spec-CR">Candidate Recommendation</span></td> <td>Factorización del tipo en una especificación más genérica. Ningún cambio</td> </tr> <tr> <td><a lang="en" href="https://drafts.csswg.org/css-images-3/#resolution-units" class="external" hreflang="en">CSS Images Module Level 3<br><small lang="es">La definición de &apos;&lt;resolution&gt;&apos; en esta especificación.</small></a></td> <td><span class="spec-CR">Candidate Recommendation</span></td> <td>Añadida la unidad <code>dppx</code></td> </tr> <tr> <td><a lang="en" href="https://drafts.csswg.org/mediaqueries-3/#resolution" class="external" hreflang="en">Media Queries<br><small lang="es">La definición de &apos;&lt;resolution&gt;&apos; en esta especificación.</small></a></td> <td><span class="spec-REC">Recommendation</span></td> <td>Definición inicial</td> </tr> </tbody> </table> <h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad de navegadores</h2> <div><div class="warning notecard"><strong><a href="https://github.com/mdn/browser-compat-data">We&apos;re converting our compatibility data into a machine-readable JSON format</a></strong>. This compatibility table still uses the old format, because we haven&apos;t yet converted the data it contains. <strong><a href="/es/docs/MDN/Contribute/Structures/Compatibility_tables">Find out how you can help!</a></strong></div> <div class="htab"> <a id="AutoCompatibilityTable" name="AutoCompatibilityTable"></a> <ul> <li class="selected"><a>Escritorio</a></li> <li><a>Móvil</a></li> </ul> </div></div> <div id="compat-desktop"> <table class="compat-table"> <tbody> <tr> <th>Característica</th> <th>Chrome</th> <th>Firefox (Gecko)</th> <th>Internet Explorer</th> <th>Opera</th> <th>Safari (WebKit)</th> </tr> <tr> <td>Soporte básico</td> <td>29</td> <td>3.5 (1.9.1)<sup>[1]</sup></td> <td>9</td> <td>9.5</td> <td><span style="color: #f00;">Sin soporte</span><sup>[2]</sup></td> </tr> <tr> <td><code>dppx</code></td> <td>29</td> <td><a href="/en-US/Firefox/Releases/16">16.0</a> (16.0)</td> <td><span style="color: rgb(255, 153, 0);" title="Compatibilidad desconocida, por favor actualízala.">?</span></td> <td>12.10</td> <td><span style="color: rgb(255, 153, 0);" title="Compatibilidad desconocida, por favor actualízala.">?</span></td> </tr> </tbody> </table> </div> <div id="compat-mobile"> <table class="compat-table"> <tbody> <tr> <th>Característica</th> <th>Android</th> <th>Firefox Mobile (Gecko)</th> <th>IE Phone</th> <th>Opera Mobile</th> <th>Safari Mobile</th> </tr> <tr> <td>Soporte básico</td> <td><span style="color: #f00;">Sin soporte</span><sup>[2]</sup></td> <td><span style="color: #888;" title="Por favor actualiza esto con la versión más reciente que de soporte.">(Yes)</span></td> <td><span style="color: rgb(255, 153, 0);" title="Compatibilidad desconocida, por favor actualízala.">?</span></td> <td><span style="color: #888;" title="Por favor actualiza esto con la versión más reciente que de soporte.">(Yes)</span></td> <td><span style="color: #f00;">Sin soporte</span><sup>[2]</sup></td> </tr> <tr> <td><code>dppx</code></td> <td><span style="color: rgb(255, 153, 0);" title="Compatibilidad desconocida, por favor actualízala.">?</span></td> <td>16.0 (16.0)</td> <td><span style="color: rgb(255, 153, 0);" title="Compatibilidad desconocida, por favor actualízala.">?</span></td> <td>12.10</td> <td><span style="color: rgb(255, 153, 0);" title="Compatibilidad desconocida, por favor actualízala.">?</span></td> </tr> </tbody> </table> </div> <p>[1] Antes de Firefox 8 (Gecko 8.0), era erroneamente aceptado sólo dimensiones CSS que fueran <a href="/es/docs/Web/CSS/integer" title="Un valor entero usado para algunas propiedades CSS que no tiene unidades."><code>&lt;integer&gt;</code></a> seguidos por la unidad. A partir de esa versión, es compatible con cualquier dimensión (<a href="/es/docs/Web/CSS/number" title="Un valor para una propiedad CSS, un número incluyendo un valor entero integer."><code>&lt;number&gt;</code></a> CSS válido seguido inmediatamente por la unidad).</p> <p>[2] El Webkit engine no soporta resolución CSS  en la especificación, es necesario el uso del no estandar <code>device-pixel-ratio</code> query para el navegador Safari, ver <a href="https://bugs.webkit.org/show_bug.cgi?id=16832">bug 16832</a>.</p> <h2 id="See_also" name="See_also">Ver también</h2> <ul> <li><a href="/en-US/docs/Web/Guide/CSS/Media_queries">CSS Media Queries</a></li> </ul>
import { Component, OnInit } from '@angular/core'; import { HttpResponse } from '@angular/common/http'; import { FormBuilder, Validators } from '@angular/forms'; import { ActivatedRoute } from '@angular/router'; import { Observable } from 'rxjs'; import { finalize, map } from 'rxjs/operators'; import { IPessoa, Pessoa } from '../pessoa.model'; import { PessoaService } from '../service/pessoa.service'; import { IUser } from 'app/entities/user/user.model'; import { UserService } from 'app/entities/user/user.service'; import { ICidade } from 'app/entities/cidade/cidade.model'; import { CidadeService } from 'app/entities/cidade/service/cidade.service'; @Component({ selector: 'jhi-pessoa-update', templateUrl: './pessoa-update.component.html', }) export class PessoaUpdateComponent implements OnInit { isSaving = false; nomeUser: string=""; nomeCidade: string=""; usersSharedCollection: IUser[] = []; cidadesSharedCollection: ICidade[] = []; editForm = this.fb.group({ id: [], cpf: [null, [Validators.required]], dataNascimento: [null, [Validators.required]], telefone: [null, [Validators.required]], rua: [null, [Validators.required, Validators.minLength(5)]], numero: [], bairro: [null, [Validators.required, Validators.minLength(5)]], cep: [null, [Validators.required, Validators.minLength(10)]], user: [], cidade: [], }); constructor( protected pessoaService: PessoaService, protected userService: UserService, protected cidadeService: CidadeService, protected activatedRoute: ActivatedRoute, protected fb: FormBuilder ) {} ngOnInit(): void { this.activatedRoute.data.subscribe(({ pessoa }) => { this.updateForm(pessoa); this.loadRelationshipsOptions(); this.nomeUser=pessoa.user.firstName; this.nomeCidade=pessoa.cidade.nomeCidade; }); } previousState(): void { window.history.back(); } save(): void { this.isSaving = true; const pessoa = this.createFromForm(); if (pessoa.id !== undefined) { this.subscribeToSaveResponse(this.pessoaService.update(pessoa)); } else { this.subscribeToSaveResponse(this.pessoaService.create(pessoa)); } } trackUserById(_index: number, item: IUser): number { return item.id!; } trackCidadeById(_index: number, item: ICidade): number { return item.id!; } protected subscribeToSaveResponse(result: Observable<HttpResponse<IPessoa>>): void { result.pipe(finalize(() => this.onSaveFinalize())).subscribe({ next: () => this.onSaveSuccess(), error: () => this.onSaveError(), }); } protected onSaveSuccess(): void { this.previousState(); } protected onSaveError(): void { // Api for inheritance. } protected onSaveFinalize(): void { this.isSaving = false; } protected updateForm(pessoa: IPessoa): void { this.editForm.patchValue({ id: pessoa.id, cpf: pessoa.cpf, dataNascimento: pessoa.dataNascimento, telefone: pessoa.telefone, rua: pessoa.rua, numero: pessoa.numero, bairro: pessoa.bairro, cep: pessoa.cep, user: pessoa.user, cidade: pessoa.cidade, }); this.usersSharedCollection = this.userService.addUserToCollectionIfMissing(this.usersSharedCollection, pessoa.user); this.cidadesSharedCollection = this.cidadeService.addCidadeToCollectionIfMissing(this.cidadesSharedCollection, pessoa.cidade); } protected loadRelationshipsOptions(): void { this.userService .query() .pipe(map((res: HttpResponse<IUser[]>) => res.body ?? [])) .pipe(map((users: IUser[]) => this.userService.addUserToCollectionIfMissing(users, this.editForm.get('user')!.value))) .subscribe((users: IUser[]) => (this.usersSharedCollection = users)); this.cidadeService .query() .pipe(map((res: HttpResponse<ICidade[]>) => res.body ?? [])) .pipe(map((cidades: ICidade[]) => this.cidadeService.addCidadeToCollectionIfMissing(cidades, this.editForm.get('cidade')!.value))) .subscribe((cidades: ICidade[]) => (this.cidadesSharedCollection = cidades)); } protected createFromForm(): IPessoa { return { ...new Pessoa(), id: this.editForm.get(['id'])!.value, cpf: this.editForm.get(['cpf'])!.value, dataNascimento: this.editForm.get(['dataNascimento'])!.value, telefone: this.editForm.get(['telefone'])!.value, rua: this.editForm.get(['rua'])!.value, numero: this.editForm.get(['numero'])!.value, bairro: this.editForm.get(['bairro'])!.value, cep: this.editForm.get(['cep'])!.value, user: this.editForm.get(['user'])!.value, cidade: this.editForm.get(['cidade'])!.value, }; } }
import { FrappeError, useFrappeGetCall } from 'frappe-react-sdk' import { PropsWithChildren, createContext } from 'react' import { useParams } from 'react-router-dom' import { KeyedMutator } from 'swr' export type Member = { name: string full_name: string user_image: string | null first_name: string is_admin: 1 | 0 } export type ChannelMembers = { [name: string]: Member } export interface ChannelMembersContextType { channelMembers: ChannelMembers, mutate: KeyedMutator<{ message: ChannelMembers }>, error?: FrappeError, isLoading: boolean } export const ChannelMembersContext = createContext<ChannelMembersContextType | null>(null) export const ChannelMembersProvider = ({ children, channelID }: PropsWithChildren<{ channelID: string}>) => { const channelMembers = useFetchChannelMembers(channelID) if (channelID) { return ( <ChannelMembersContext.Provider value={channelMembers}> {children} </ChannelMembersContext.Provider> ) } return null } const useFetchChannelMembers = (channelID: string): ChannelMembersContextType | null => { const { data, error, isLoading, mutate } = useFrappeGetCall<{ message: ChannelMembers }>('raven.api.chat.get_channel_members', { channel_id: channelID }, undefined, { revalidateOnFocus: false }) return { channelMembers: data?.message ?? {}, error, isLoading, mutate } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateInformationTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('information', function (Blueprint $table) { $table->id(); $table->string('user_id'); $table->string('nama_user'); $table->string('email_user')->unique(); $table->string('nomor'); $table->text('alamat'); $table->string('tempat_lahir'); $table->date('tanggal_lahir'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('information'); } }
import React from 'react'; import { Avatar, CssBaseline, Box, Typography, Container, } from '@material-ui/core'; import LockOutlinedIcon from '@material-ui/icons/LockOutlined'; import { makeStyles } from '@material-ui/core/styles'; import Copyright from '../../Copyright'; import { useMediaQuery } from 'react-responsive'; const useAuthStyles = makeStyles((theme) => ({ paper: { marginTop: theme.spacing(8), display: 'flex', flexDirection: 'column', alignItems: 'center', }, avatar: { margin: theme.spacing(1), backgroundColor: theme.palette.secondary.main, }, form: { width: '100%', // Fix IE 11 issue. marginTop: theme.spacing(3), }, submit: { margin: theme.spacing(3, 0, 2), }, })); function AuthPage(props) { const classes = useAuthStyles(); const isTabletOrMobile = useMediaQuery({ query: '(max-width: 1224px)' }); return ( <Container component="main" maxWidth={isTabletOrMobile ? 'xs' : "sm"}> <CssBaseline /> <div className={classes.paper}> <Avatar className={classes.avatar}> <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h4"> {props.title} </Typography> {props.form} </div> <Box mt={5}> <Copyright /> </Box> </Container> ); } export { useAuthStyles }; export default AuthPage;
'use client' import { useLoginModal } from '@/app/hooks/useLoginModal' import { useRegisterModal } from '@/app/hooks/useRegisterModal' import axios from 'axios' import { signIn } from 'next-auth/react' import { useCallback, useState } from 'react' import { FieldValues, SubmitHandler, useForm } from 'react-hook-form' import { toast } from 'react-hot-toast' import { AiFillGithub } from 'react-icons/ai' import { FcGoogle } from 'react-icons/fc' import Button from '../Button' import Heading from '../Heading' import Input from '../inputs/Input' import Modal from './Modal' interface Props {} const RegisterModal = (props: Props) => { const registerModal = useRegisterModal() const loginModal = useLoginModal() const [isLoading, setIsLoading] = useState(false) const { register, handleSubmit, formState: { errors }, } = useForm<FieldValues>({ defaultValues: { name: '', email: '', password: '', }, }) const onSubmit: SubmitHandler<FieldValues> = (data) => { setIsLoading(true) axios .post('/api/register', data) .then(() => registerModal.onClose()) .catch((e) => toast.error('Something went wrong')) .finally(() => setIsLoading(false)) } const toggle = useCallback(() => { registerModal.onClose() loginModal.onOpen() }, [loginModal, registerModal]) const bodyContent = ( <div className="flex flex-col gap-4"> <Heading title="Welcome to Airbnb" subtitle="Create an account!" /> <Input register={register} id="email" label="Email" disabled={isLoading} errors={errors} required type="email" /> <Input register={register} id="name" label="Name" disabled={isLoading} errors={errors} required /> <Input register={register} id="password" label="Password" disabled={isLoading} errors={errors} required type={'password'} /> </div> ) const footerContent = ( <div className="mt-3 flex flex-col gap-4"> <hr /> <Button outline label="Continue with Google" icon={FcGoogle} onClick={() => signIn('google')} /> <Button outline label="Continue with Github" icon={AiFillGithub} onClick={() => signIn('github')} /> <div className="font-lite mt-4 text-neutral-500"> <div className="flex flex-row items-center justify-center gap-2"> <div>Already have an account</div> <div onClick={toggle} className="cursor-pointer text-neutral-800 hover:underline"> Login </div> </div> </div> </div> ) return ( <Modal disabled={isLoading} isOpen={registerModal.isOpen} title="Register" actionLabel="Continue" onClose={registerModal.onClose} onSubmit={handleSubmit(onSubmit)} body={bodyContent} footer={footerContent} /> ) } export default RegisterModal
import React, { useState } from 'react' const Question = (props) => { const { title, info } = props const [isToggleOn, setIsToggleOn] = useState(false) const toggleInfoVisibility = () => { if (isToggleOn) { setIsToggleOn(false) } else { setIsToggleOn(true) } } return ( <article className="question"> <header> <h4>{title}</h4> <button onClick={toggleInfoVisibility} className="btn"> {isToggleOn ? '-' : '+'} </button> </header> {isToggleOn && <p>{info}</p>} </article> ) } export default Question
import mongoose, { Schema } from 'mongoose'; import Config from '../../../config'; import { CartI, ProductCart, CartBaseClass } from '../cart.interface'; export const CartSchema = new mongoose.Schema<CartI>({ userId: { type: Schema.Types.ObjectId, required: true, unique: true, }, productos: [ { _id: { type: Schema.Types.ObjectId, require: true, }, cantidad: { type: Number, require: true, }, timeStamps: { type: Number, require: true, }, }, ], direccion: { calle: { type: String, required: true, }, altura: { type: Number, require: true, }, codigoPostal: { type: Number, required: true, }, piso: { type: String, required: false, }, departamento: { type: String, required: false, }, }, }); export class CartsAtlasDAO implements CartBaseClass { private srv: string; private Carts; constructor(local: boolean = false) { if (local) this.srv = `mongodb://localhost:27017/${Config.MONGO_LOCAL_DBNAME}`; else this.srv = Config.MONGO_ATLAS_SRV; mongoose.connect(this.srv); this.Carts = mongoose.model<CartI>('cart', CartSchema); } async get(userId: string): Promise<CartI> { const result = await this.Carts.findOne({ userId }); if (!result) throw new Error('id not found'); return result; } async createCart(userId: string): Promise<CartI> { const newCart = new this.Carts({ userId, productos: [], }); await newCart.save(); return newCart; } productExist(cart: CartI, productId: string): boolean { const index = cart.productos.findIndex( (aProduct) => aProduct._id === productId ); if (index < 0) return false; return true; } async addProduct(userId: string, product: ProductCart): Promise<CartI> { const cart = await this.Carts.findById(userId); if (!cart) throw new Error('Cart not found'); const index = cart.productos.findIndex((aProduct) => { const idMongo: any = aProduct._id.toString(); const idProdAdd = product._id; return idMongo === idProdAdd; }); if (index < 0) cart.productos.push(product); else cart.productos[index].cantidad += product.cantidad; await cart.save(); return cart; } async deleteProduct(cartId: string, product: ProductCart): Promise<CartI> { const cart = await this.Carts.findById(cartId); if (!cart) throw new Error('Cart not found'); const index = cart.productos.findIndex((aProduct) => { const idMongo: any = aProduct._id.toString(); const idProdAdd = product._id; return idMongo === idProdAdd; }); if (index < 0) throw new Error('Product not found'); if (cart.productos[index].cantidad <= product.cantidad) throw new Error('Product amount invalid'); else cart.productos[index].cantidad -= product.cantidad; await cart.save(); return cart; } }
import React, { useEffect } from 'react'; import { useState } from 'react'; import { Text, View, Alert, ActivityIndicator, ScrollView, Pressable, } from 'react-native'; import { colors, CLEAR, ENTER } from '../../constants'; import Keyboard from '../Keyboard'; import styles from './Game.styles'; import { copyArray, getGameKey } from '../../utils'; import AsyncStorage from '@react-native-async-storage/async-storage'; import Endscreen from '../EndScreen/EndScreen'; import Animated, { SlideInLeft, ZoomIn, FlipInEasyY, } from 'react-native-reanimated'; import * as Haptics from 'expo-haptics'; const NUMBER_OF_TRIES: number = 6; const gameKey = getGameKey(); const Game = ({ navigation, chosenWord, isHard }: any) => { const wordLength = 5; const api_key = 'd9gxdj3y5lflq8mxyo7mpow8rw29oilgvt9dz4sy0g9a3b9vz'; //AsyncStorage.removeItem("@game"); //const word = testWord; const [rows, setRows] = useState<string[][]>([]); const [word, setWord] = useState<string>(''); const [letters, setLetters] = useState<string[]>([]); const [currentRowIndex, setCurrentRowIndex] = useState<number>(0); const [currentColIndex, setCurrentColIndex] = useState<number>(0); const [gameState, setGameState] = useState<string>('playing'); // won, lost, playing const [loaded, setLoaded] = useState<boolean>(false); const [loadedGame, setLoadedGame] = useState<boolean>(false); const [loadedWord, setLoadedWord] = useState<boolean>(false); const [despClue, setDespClue] = useState<string>(''); const [definition, setDefinition] = useState<string>(''); const [wordType, setWordType] = useState<string>(''); const [showEmergencyBtn, setShowEmergencyBtn] = useState<boolean>(false); useEffect(() => { if (currentRowIndex > 0) { checkGameState(); } }, [currentRowIndex]); useEffect(() => { if (loaded) { persistState(); } }, [rows, currentRowIndex, currentColIndex, gameState]); useEffect(() => { if (loadedGame && loadedWord) { setLoaded(true); } }, [loadedGame, loadedWord]); useEffect(function() { console.log(chosenWord); if (chosenWord !== "random") { setWord(chosenWord); setLetters(chosenWord.split('')); setLoadedWord(true); setRows(new Array(NUMBER_OF_TRIES).fill(new Array(chosenWord.split('').length).fill(''))); } else { requestRandomWord(); } readState(); }, []); useEffect(() => { getWordDef(); }, [word]); const requestRandomWord = () => { const url = 'https://api.wordnik.com/v4/words.json/randomWord?hasDictionaryDef=true&maxCorpusCount=-1&minDictionaryCount=1&minLength=' + wordLength + '&maxLength=' + wordLength + '&api_key=' + api_key; const makeCall = function () { const Http = new XMLHttpRequest(); Http.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { const resJson = JSON.parse(Http.response); const wordRegex = new RegExp("^[a-z]+$"); if(wordRegex.test(resJson.word)) { console.log(resJson.word); setWord(resJson.word); setLetters(resJson.word.split('')); setLoadedWord(true); setRows(new Array(NUMBER_OF_TRIES).fill(new Array(resJson.word.split('').length).fill(''))); } else { makeCall(); } } else { console.log(this.status); } }; Http.open('GET', url); Http.setRequestHeader('Access-Control-Allow-Origin', '*'); Http.setRequestHeader('Referrer-Policy', 'no-referrer'); Http.setRequestHeader( 'X-Mashape-Key', 'ef6672f706mshb271b1cd03264c9p14b189jsn050169b0933a' ); Http.send(); } makeCall(); }; const persistState = async () => { // write all the state variables in AsyncStorage const currentData = { rows, currentRowIndex, currentColIndex, gameState, }; try { const existingStateString = await AsyncStorage.getItem('@game'); const existingState = existingStateString ? JSON.parse(existingStateString) : {}; existingState[gameKey] = currentData; const dataString = JSON.stringify(existingState); console.log('Saving', dataString); await AsyncStorage.setItem('@game', dataString); } catch (e) { console.log('Failed to write data to Async Storage: ', e); } }; const readState = async () => { const dataString = await AsyncStorage.getItem('@game'); try { const data = JSON.parse(dataString || '{}'); } catch (e) { console.log("Couldn't parse the state."); } setLoadedGame(true); }; const checkGameState = () => { if (checkIfWon() && gameState != 'won') { setGameState('won'); } else if (checkIfLost() && gameState != 'lost') { setGameState('lost'); } }; const checkIfWon = () => { const row = rows[currentRowIndex - 1]; if (row) { return row.every((letter: string, i: number) => letter === letters[i]); } else { return false; } }; const checkIfLost = () => { return !checkIfWon() && currentRowIndex === rows.length; }; const onKeyPressed = (key: string): void => { if (gameState != 'playing') { return; } const updateRows = copyArray(rows); if (key === CLEAR) { const prevCol = currentColIndex - 1; if (prevCol >= 0) { updateRows[currentRowIndex][prevCol] = ''; setRows(updateRows); setCurrentColIndex(prevCol); } return; } if (key === ENTER) { const row = rows[currentRowIndex]; if (row) { const input = row.join(''); if (input.length < 5) { Alert.alert('Ouch', 'Insert a word of five letters'); return; } else { wordExists(input); } } } if (rows[0]) { if (currentColIndex < rows[0].length) { updateRows[currentRowIndex][currentColIndex] = key; setRows(updateRows); setCurrentColIndex(currentColIndex + 1); } } }; const wordExists = function (input: string) { const Http = new XMLHttpRequest(); const url = 'https://api.wordnik.com/v4/word.json/' + input + '/definitions?limit=1&includeRelated=false&useCanonical=false&includeTags=false&api_key=' + api_key; Http.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { actionIfWordExists(); } else if (this.readyState == 4 && this.status == 404) { Alert.alert('Ouch', "This is not a word... press 'Clear' to retry!"); return; } }; Http.open('GET', url); Http.setRequestHeader('Access-Control-Allow-Origin', '*'); Http.setRequestHeader( 'X-Mashape-Key', 'ef6672f706mshb271b1cd03264c9p14b189jsn050169b0933a' ); Http.send(); } function actionIfWordExists() { if (isHard && currentRowIndex !== 0) { const currRow = rows[currentRowIndex]; const prevRow = rows[currentRowIndex - 1]; if (currRow && prevRow) { if (!validateHardWord(letters, currRow, prevRow)) { Alert.alert( 'Ouch', 'In hard mode you should use all the correct letters from previous word!' ); return; } } } if (rows[0]) { if (currentColIndex === rows[0].length) { setCurrentRowIndex(currentRowIndex + 1); setCurrentColIndex(0); } } if (currentRowIndex === NUMBER_OF_TRIES - 1) { console.log('Almost out of tries'); setShowEmergencyBtn(true); } return; } const isCellActive = (row: number, col: number) => { return row === currentRowIndex && col === currentColIndex; }; const getCellBGColor = (row: number, col: number) => { return getColor(letters, rows, row, col); }; const validateHardWord = (testWord: string[], currInputWord: string[], prevInputWord: string[]) => { for (var i = 0; i < prevInputWord.length; i++) { // se è verde la lettera nella parola precedente verifico lo sia anche nella parola corrente if ( testWord[i] === prevInputWord[i] && testWord[i] !== currInputWord[i] ) { return false; } var letter = prevInputWord[i]; if (letter) { var prevYellowCount = getYellowCount(testWord, prevInputWord, letter); var currYellowCount = getYellowCount(testWord, currInputWord, letter); var prevGreenCount = getGreenCount(testWord, prevInputWord, letter); var currGreenCount = getGreenCount(testWord, currInputWord, letter); if (prevYellowCount > currGreenCount + currYellowCount - prevGreenCount) { return false; } } } return true; }; const getYellowCount = (testWord: string[], inputWord: string[], letter: string) => { // conto quante lettere verdi e altre occorenze ci sono per la lettera passata var greenLetterCount = 0; var testWordLetterCount = 0; var inputWordLetterCount = 0; for (var i = 0; i < inputWord.length; i++) { if (inputWord[i] === letter && testWord[i] === letter) { greenLetterCount++; } if (inputWord[i] === letter) { inputWordLetterCount++; } if (testWord[i] === letter) { testWordLetterCount++; } } var testWordNotGreenLetterCount = testWordLetterCount - greenLetterCount; var inputWordNotGreenLetterCount = inputWordLetterCount - greenLetterCount; return Math.min(testWordNotGreenLetterCount, inputWordNotGreenLetterCount); }; const getGreenCount = (testword: string[], inputWord: string[], letter: string) => { // conto quante lettere verdi ci sono per la lettera passata var greenLetterCount = 0; for (var i = 0; i < inputWord.length; i++) { if (inputWord[i] === letter && testword[i] === letter) { greenLetterCount++; } } return greenLetterCount; }; const getColor = (letters: string[], rows: string[][], rowIndex: number, colIndex: number) => { if (rowIndex >= currentRowIndex) { return colors.black; } let row = rows[rowIndex]; if (!row) { return colors.darkgrey; } const letter = row[colIndex]; if (letter === letters[colIndex]) { return colors.primary; } let recurrenceWrongPositionInLettersCount = 0; let prevUnmatchedLetterCount = 0; for (let i = 0; i < letters.length; i++) { if (letters[i] !== row[i]) { if (letters[i] === letter) { recurrenceWrongPositionInLettersCount++; } if (i < colIndex && letter === row[i]) { prevUnmatchedLetterCount++; } } } if (recurrenceWrongPositionInLettersCount === 0) { return colors.darkgrey; } if (recurrenceWrongPositionInLettersCount > prevUnmatchedLetterCount) { return colors.secondary; } return colors.darkgrey; }; const getAllLettersWithColor = (color: string) => { return rows.flatMap((row, i) => row.filter((cell: any, j: any) => getCellBGColor(i, j) === color) ); }; const greenCaps = getAllLettersWithColor(colors.primary); const yellowCaps = getAllLettersWithColor(colors.secondary); const greyCaps = getAllLettersWithColor(colors.darkgrey); const getCellStyle = (i: any, j: any) => [ styles.cell, { borderColor: isCellActive(i, j) ? colors.grey : colors.darkgrey, backgroundColor: getCellBGColor(i, j), }, ]; const getWordDef = () => { Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); const Http = new XMLHttpRequest(); const url = 'https://api.wordnik.com/v4/word.json/' + word + '/definitions?limit=1&includeRelated=false&useCanonical=false&includeTags=false&api_key=' + api_key; Http.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { const resJson = JSON.parse(Http.response); const def = resJson.meanings[0].definitions[0].definition; setDefinition(def); } else if (this.readyState == 4 && this.status == 404) { Alert.alert('Ouch', "This is not a word... press 'Clear' to retry!"); } }; Http.open('GET', url); Http.setRequestHeader('Access-Control-Allow-Origin', '*'); Http.setRequestHeader( 'X-Mashape-Key', 'ef6672f706mshb271b1cd03264c9p14b189jsn050169b0933a' ); Http.send(); }; const getWordType = () => { Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); const Http = new XMLHttpRequest(); const url = 'https://api.wordnik.com/v4/word.json/' + word + '/definitions?limit=1&includeRelated=false&useCanonical=false&includeTags=false&api_key=' + api_key; Http.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { const resJson = JSON.parse(Http.response); const type = resJson[0].partOfSpeech; setWordType(type); } else if (this.readyState == 4 && this.status == 404) { setWordType('No type found for this word :\'('); } }; Http.open('GET', url); Http.setRequestHeader('Access-Control-Allow-Origin', '*'); Http.setRequestHeader( 'X-Mashape-Key', 'ef6672f706mshb271b1cd03264c9p14b189jsn050169b0933a' ); Http.send(); }; const getWordSyn = () => { Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); const Http = new XMLHttpRequest(); const url = 'https://api.wordnik.com/v4/word.json/' + word + '/relatedWords?useCanonical=false&relationshipTypes=synonym&limitPerRelationshipType=1&api_key=' + api_key; Http.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { const resJson = JSON.parse(Http.response); const clue = resJson[0].words[0]; setDespClue(clue); } else if (this.readyState == 4 && this.status == 404) { setDespClue('No clue found for this word :\'('); } }; Http.open('GET', url); Http.setRequestHeader('Access-Control-Allow-Origin', '*'); Http.setRequestHeader( 'X-Mashape-Key', 'ef6672f706mshb271b1cd03264c9p14b189jsn050169b0933a' ); Http.send(); }; if (!loaded) { return <ActivityIndicator />; } if (gameState !== 'playing') { return ( <Endscreen won={gameState === 'won'} rows={rows} getCellBGColor={getCellBGColor} wordDef={definition} /> ); } return <> <ScrollView style={styles.map}> {rows.map((row, i) => ( <Animated.View entering={SlideInLeft.delay(i * 30)} key={`row-${i}`} style={styles.row}> {row.map((letter: any, j: any) => ( <> {i < currentRowIndex && ( <Animated.View entering={FlipInEasyY.delay(j * 100)} key={`cell-color-${i}-${j}`} style={getCellStyle(i, j)}> <Text style={styles.cellText}>{letter.toUpperCase()}</Text> </Animated.View> )} {i === currentRowIndex && !!letter && ( <Animated.View entering={ZoomIn} key={`cell-active-${i}-${j}`} style={getCellStyle(i, j)}> <Text style={styles.cellText}>{letter.toUpperCase()}</Text> </Animated.View> )} {!letter && ( <View key={`cell-${i}-${j}`} style={getCellStyle(i, j)}> <Text style={styles.cellText}>{letter.toUpperCase()}</Text> </View> )} </> ))} </Animated.View> ))} </ScrollView> <Animated.View entering={SlideInLeft.delay(200).springify().mass(0.5)} style={{ flexDirection: 'row', padding: 10 }}> <Text style={{ color: colors.lightgrey, fontSize: 20, fontWeight: 'bold', flex: 1, justifyContent: 'center', }}> {despClue} </Text> <Text style={{ color: colors.lightgrey, fontSize: 20, fontWeight: 'bold', flex: 1, justifyContent: 'center', }}> {wordType} </Text> </Animated.View> <Animated.View entering={SlideInLeft.delay(200).springify().mass(0.5)} style={{ flexDirection: 'row', padding: 10 }}> {showEmergencyBtn ? ( <Pressable onPress={getWordSyn} style={{ flex: 1, backgroundColor: colors.secondary, borderRadius: 20, alignItems: 'center', justifyContent: 'center', height: 45, width: 120, }}> <Text style={{ color: colors.lightgrey, fontWeight: 'bold' }}> Desperate Clue </Text> </Pressable> ) : null} <Pressable onPress={getWordType} style={{ flex: 1, backgroundColor: colors.primary, borderRadius: 20, alignItems: 'center', justifyContent: 'center', height: 45, width: 120, }}> <Text style={{ color: colors.lightgrey, fontWeight: 'bold' }}> Clue </Text> </Pressable> </Animated.View> <Keyboard onKeyPressed={onKeyPressed} greenCaps={greenCaps} yellowCaps={yellowCaps} greyCaps={greyCaps} /> </>; }; export default Game;
using System.ComponentModel.DataAnnotations; using BookShopAPI.Models.Requests; using BookShopAPI.Models.Responses; using BookShopAPI.Services; using Microsoft.AspNetCore.Mvc; namespace BookShop.Controllers; [Route("api/v1/employees")] public class EmployeeController : ControllerBase { private readonly IEmployeeService _employeeService; public EmployeeController(IEmployeeService employeeService) { _employeeService = employeeService; } /// <summary> /// Create a employee /// </summary> [HttpPost] public Response<EmployeeResponse> Create(EmployeeCreateRequest request) { var result = _employeeService.Create(request); HttpContext.Response.StatusCode = result.Code; return result; } /// <summary> /// Get all employees /// </summary> [HttpGet] public Response<List<EmployeeResponse>> GetAll() { var result = _employeeService.GetAll(); HttpContext.Response.StatusCode = result.Code; return result; } /// <summary> /// Delete a employee /// </summary> [HttpDelete] public Response<EmployeeResponse> Delete([Required] string id) { var result = _employeeService.Delete(id); HttpContext.Response.StatusCode = result.Code; return result; } /// <summary> /// Update a employee /// </summary> [HttpPut] public Response<EmployeeResponse> Update(EmployeeUpdateRequest req) { var result = _employeeService.Update(req); HttpContext.Response.StatusCode = result.Code; return result; } }
import { combineReducers, createStore } from "redux"; import { accountReducer } from "./features/accounts/accountSlice"; import { customerReducer } from "./features/customers/customerSlice"; const rootReducer = combineReducers({ account: accountReducer, customer: customerReducer, }); const store = createStore(rootReducer); store.dispatch({ type: "account/deposit", payload: 500 }); store.dispatch({ type: "account/requestLoan", payload: { amount: 1000, purpose: "buy a car", }, }); export default store;
// @strictNullChecks: true // @noimplicitany: true // @declaration: true declare type Box<T> = { value: T; }; declare type Boxified<T> = { [P in keyof T]: Box<T[P]>; }; declare function box<T>(x: T): Box<T>; declare function unbox<T>(x: Box<T>): T; declare function boxify<T>(obj: T): Boxified<T>; declare function unboxify<T>(obj: Boxified<T>): T; declare function assignBoxified<T>(obj: Boxified<T>, values: T): void; declare function validate<T>(obj: { [P in keyof T]?: T[P] }): T; declare function clone<T>(obj: { readonly [P in keyof T]: T[P] }): T; declare function validateAndClone<T>(obj: { readonly [P in keyof T]?: T[P] }): T; type Foo = { a?: number; readonly b: string; } function f10(foo: Foo) { let x = validate(foo); // { a: number, readonly b: string } let y = clone(foo); // { a?: number, b: string } let z = validateAndClone(foo); // { a: number, b: string } } // Repro from #12606 type Func<T> = (...args: any[]) => T; type Spec<T> = { [P in keyof T]: Func<T[P]> | Spec<T[P]>; }; /** * Given a spec object recursively mapping properties to functions, creates a function * producing an object of the same structure, by mapping each property to the result * of calling its associated function with the supplied arguments. */ declare function applySpec<T>(obj: Spec<T>): (...args: any[]) => T; // Infers g1: (...args: any[]) => { sum: number, nested: { mul: string } } var g1 = applySpec({ sum: (a: any) => 3, nested: { mul: (b: any) => "n" } }); // Infers g2: (...args: any[]) => { foo: { bar: { baz: boolean } } } var g2 = applySpec({foo: {bar: {baz: (x: any) => true}}}); // Repro from #12633 const foo = <T>(object: T, partial: Partial<T>) => object; let o = {a: 5, b: 7}; foo(o, {b: 9}); o = foo(o, {b: 9}); // Inferring to { [P in K]: X }, where K extends keyof T, produces same inferences as // inferring to { [P in keyof T]: X }. declare function f20<T, K extends keyof T>(obj: Pick<T, K>): T; declare function f21<T, K extends keyof T>(obj: Pick<T, K>): K; declare function f22<T, K extends keyof T>(obj: Boxified<Pick<T, K>>): T; declare function f23<T, U extends keyof T, K extends U>(obj: Pick<T, K>): T; declare function f24<T, U, K extends keyof T | keyof U>(obj: Pick<T & U, K>): T & U; let x0 = f20({foo: 42, bar: "hello"}); let x1 = f21({foo: 42, bar: "hello"}); let x2 = f22({foo: {value: 42}, bar: {value: "hello"}}); let x3 = f23({foo: 42, bar: "hello"}); let x4 = f24({foo: 42, bar: "hello"});
package fit.asta.health.designsystem.atomic import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CornerBasedShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Immutable import androidx.compose.runtime.compositionLocalOf import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.Shape import androidx.compose.ui.unit.dp /** * This Model Class contains all the different values for the default Spaces in the app */ @Immutable data class AppShape( val rectangle: Shape = RectangleShape, val circle: Shape = CircleShape, val level0: CornerBasedShape = RoundedCornerShape(4.dp), val level1: CornerBasedShape = RoundedCornerShape(8.dp), val level2: CornerBasedShape = RoundedCornerShape(16.dp), val level3: CornerBasedShape = RoundedCornerShape(24.dp) ) internal val LocalAppShape = compositionLocalOf { AppShape() }
/** * @jest-environment jsdom */ import "@testing-library/jest-dom"; import { fireEvent, screen, waitFor } from "@testing-library/dom"; import NewBillUI from "../views/NewBillUI.js"; import NewBill from "../containers/NewBill.js"; import { localStorageMock } from "../__mocks__/localStorage.js"; import router from "../app/Router.js"; import mockStore from "../__mocks__/store.js"; import { ROUTES_PATH, ROUTES } from "../constants/routes.js"; import userEvent from "@testing-library/user-event"; describe("Given I am connected as an employee", () => { describe("When I am on NewBill Page", () => { //Test de la surbrillance de l'icône test("Then the new bill icon should be highlighted", async () => { Object.defineProperty(window, "localStorage", { value: localStorageMock, }); window.localStorage.setItem( "user", JSON.stringify({ type: "Employee", }) ); const root = document.createElement("div"); root.setAttribute("id", "root"); document.body.append(root); router(); window.onNavigate(ROUTES_PATH.NewBill); await waitFor(() => screen.findByTestId("icon-mail")); const iconMail = screen.getByTestId("icon-mail"); expect(iconMail.classList.contains("active-icon")).toBeTruthy(); }); //Test d'envoie d'un fichier qui n'est pas une image test("Then I try to upload a file that is not an image", async () => { //Création de la page const html = NewBillUI(); document.body.innerHTML = html; //Nécessaire pour init la fonction handleChangeFile const newBill = new NewBill({ document, }); //Récupération de l'input const inputFile = await screen.findByTestId("file"); //Création d'un fichier text const file = new File(["test"], "test.txt", { type: "text/plain" }); //Simulation d'envoie de fichier fireEvent.change(inputFile, { target: { files: [file], }, }); /* await new Promise(resolve => process.nextTick(resolve)); semble bloquer le test dans certains cas a la place un timeout très bref est utilisé pour s'assurer que l'objet newBill a bien fini de traiter le fichier */ await new Promise(resolve => setTimeout(resolve, 0)); //Si la propriété fileUrl de newBill est null, alors le fichier n'a pas été enregistré et un message d'erreur devrait s'afficher sur la page //Note : l'erreur "invalid file" dans la console est normale expect(newBill.fileUrl).toBeNull(); expect(screen.getByTestId("errorMsg")).toBeVisible(); }); //Test d'envoie d'un fichier est une image test("Then I can upload a file of the correct type", async () => { const onNavigate = (pathname) => { document.body.innerHTML = ROUTES({ pathname }); }; document.body.innerHTML = NewBillUI(); var newBill = new NewBill({ document, onNavigate: onNavigate, store: mockStore, }); const inputFile = await screen.findByTestId("file"); const file = new File(["test"], "testUpload.jpg", { type: "image/jpg" }); userEvent.upload(inputFile, file); expect(inputFile.files.length).toEqual(1); expect(inputFile.files[0].name).toBe("testUpload.jpg"); /* await new Promise(resolve => process.nextTick(resolve)); semble bloquer le test dans certains cas a la place un timeout très bref est utilisé pour s'assurer que l'objet newBill a bien fini de traiter le fichier */ await new Promise(resolve => setTimeout(resolve, 0)); //Si l'envoie a fonctionné, alors l'objet newBill doit avoir une valeur non vide dans fileUrl expect(newBill.fileUrl).toBeTruthy(); expect(screen.getByTestId("errorMsg")).not.toBeVisible(); }); // Test de soumission d'une nouvelle facture et redirection vers "Bills" test("Then submitting a correct form should call handleSubmit method and redirect user on Bill page", async () => { document.body.innerHTML = NewBillUI(); // Navigation et soumission du formulaire const onNavigate = (pathname) => { document.body.innerHTML = ROUTES({ pathname }); }; const newBill = new NewBill({ document, onNavigate, store: mockStore, }); //On surveille la fonction qui gère le formulaire const handleSubmitSpy = jest.spyOn(newBill, "handleSubmit"); //Initialisation du bouton d'envoye const formNewBill = screen.getByTestId("form-new-bill"); formNewBill.addEventListener("submit", newBill.handleSubmit); //Récupération des inputs const inputExpenseType = screen.getByTestId("expense-type"); const inputExpenseName = screen.getByTestId("expense-name"); const inputDatepicker = screen.getByTestId("datepicker"); const inputAmount = screen.getByTestId("amount"); const inputVAT = screen.getByTestId("vat"); const inputPCT = screen.getByTestId("pct"); const inputCommentary = screen.getByTestId("commentary"); const inputFile = screen.getByTestId("file"); // Données à insérer const inputData = { type: "Transports", name: "TestForm", datepicker: "2023-04-24", amount: "1000", vat: "20", pct: "20", commentary: "Test Mocked Data", file: new File(["test"], "testForm.jpeg", { type: "image/jpeg" }), }; console.log("Form test"); // Insérer les données simulées fireEvent.change(inputExpenseType, { target: { value: inputData.type }, }); fireEvent.change(inputExpenseName, { target: { value: inputData.name }, }); fireEvent.change(inputDatepicker, { target: { value: inputData.datepicker }, }); fireEvent.change(inputAmount, { target: { value: inputData.amount } }); fireEvent.change(inputVAT, { target: { value: inputData.vat } }); fireEvent.change(inputPCT, { target: { value: inputData.pct } }); fireEvent.change(inputCommentary, { target: { value: inputData.commentary }, }); userEvent.upload(inputFile, inputData.file); // Vérifier les valeurs insérées expect(inputExpenseType.value).toBe(inputData.type); expect(inputExpenseName.value).toBe(inputData.name); expect(inputDatepicker.value).toBe(inputData.datepicker); expect(inputAmount.value).toBe(inputData.amount); expect(inputVAT.value).toBe(inputData.vat); expect(inputPCT.value).toBe(inputData.pct); expect(inputCommentary.value).toBe(inputData.commentary); expect(inputFile.files[0]).toBe(inputData.file); //Déclenchement de l'envoi du formulaire fireEvent.submit(formNewBill); //Si le texte "Mes notes de frais" est affiché alors on a bien été redirigé vers la page des factures await waitFor(() => screen.getByText("Mes notes de frais")); expect(screen.getByText("Mes notes de frais")).toBeTruthy(); expect(handleSubmitSpy).toHaveBeenCalled(); }); }); }); describe("Given I am connected as an employee on the dashboard", () => { describe("When an user create a new bill", () => { test("Then add a bill from mock API POST", async () =>{ //Espionnage de l'API const postSpy = jest.spyOn(mockStore, "bills"); //Création d'une facture fictive de test const bill = { "id": "47qAXb6fIm2zOKkLzMro", "vat": "80", "fileUrl": "https://firebasestorage.googleapis.com/v0/b/billable-677b6.a…f-1.jpg?alt=media&token=c1640e12-a24b-4b11-ae52-529112e9602a", "status": "pending", "type": "Hôtel et logement", "commentary": "séminaire billed", "name": "encore", "fileName": "preview-facture-free-201801-pdf-1.jpg", "date": "2004-04-04", "amount": 400, "commentAdmin": "ok", "email": "a@a", "pct": 20 }; //Mise à jour de la facture via l'API const postBills = await mockStore.bills().update(bill); //Vérification que l'API a bien été appelé expect(postSpy).toHaveBeenCalled(); //Vérification que la facture reçu correspond a celle envoyé expect(postBills).toStrictEqual(bill); }); }); });