text
stringlengths
184
4.48M
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> #include <sys/types.h> #include <unistd.h> void func(int connfd) { char buffer[80]; int n; for (;;) { bzero(buffer, sizeof(buffer)); read(connfd, buffer, sizeof(buffer)); printf("From Client: %s", buffer); bzero(buffer, sizeof(buffer)); printf("To Client: "); n = 0; while ((buffer[n++] = getchar()) != '\n'); write(connfd, buffer, sizeof(buffer)); if (strncmp(buffer, "exit", 4) == 0) { printf("Server Exit...\n"); break; } } } int main() { struct sockaddr_in server, client; int sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) { printf("socket creation failed...\n"); exit(0); } else printf("Socket successfully created..\n"); bzero(&server, sizeof(server)); server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(INADDR_ANY); server.sin_port = htons(8080); if (bind(sockfd, (struct sockaddr * ) & server, sizeof(server)) < 0) { printf("socket bind failed...\n"); exit(0); } else printf("Socket successfully binded..\n"); if (listen(sockfd, 5) < 0) { printf("Listen failed...\n"); exit(0); } else printf("Server listening..\n"); int len = sizeof(client); int connfd = accept(sockfd, (struct sockaddr *) & client, & len); if (connfd < 0) { printf("server accept failed...\n"); exit(0); } else printf("server accept the client...\n"); func(connfd); close(sockfd); } /* joswin@LAPTOP:~/TCP$ gcc server.c -o server joswin@LAPTOP:~/TCP$ ./server Socket successfully created.. Socket successfully binded.. Server listening.. server accept the client... From client: Message 1 To client : Message 2 From client: Message 3 To client : exit Server Exit... */
===== scope of variables ===== Variables have a certain **scope**, where they can exist. This can be at top-level, inside a function or inside a class. A Variable inside a class instance (usually prefix with ''self.'' ) is called an **attribute**. * by default, variables have local scope, meaning if a variable is declared inside a function, only code inside this function can access this variable * [[en:glossary:g:global]] variables have global scope, meaning when you declare a global variable inside a function, code at top-level or inside other functions can access the variable. As the scope of variables is a very powerful feature of object-oriented programming, use global variables only if you have no other alternative. * [[en:glossary:c:class variables]] act like global variables * code inside a scope (like inside a function) can read (and sometimes even manipulate!) variables of a higher scope (like of top-level) A python function can access (read) a variable when this variable was declared at **top-level**. It is important to know that each function in python has it's own **scope** for variables. All variables declared inside a function are **local** and can not be seen by any other function, nor by code at top-level. Meaning you can have a variable at top-level, and you can declare inside a function a **a local variable** with the same name. Both variables are separated by python. Interesting is the fact that you can not only read, but also manipulate (changing the value of) a top-level variables inside a function...and the manipulation will be visible at top-level! This only works with **mutable** types, like ''list'' (square brackets). A ''tuple'' (round bracket) on the other hand is **immutable**. Important is not to confuse those two things: * Declaring a variable: like <code python; gutter:false> x = 4</code> * Manipulation a mutable variable: like <code python; gutter:false>cells[2] = "x"</code> In short, as soon as you declare a variable inside a function, you create a new **local** variable. Independent of the fact that a variable with the same name exist at top-level. You best try out this interactive python shell session below. Several functions will be declared and used, to check if they could manipulate variables from top-level. <code python; gutter:false> cells = [1,2,3,4] # top-level >>> def adder(): """adding 5 to cells""" cells.append(5) >>> print(cells) [1, 2, 3, 4] >>> adder() >>> print(cells) [1, 2, 3, 4, 5] </code> As can be seen in the example above, the function ''adder()'' was able to manipulate the top-level variable ''cells''. Because cells is a list and lists are mutable. <code python; gutter:false> >>> def local_adder(): cells = [1,2,3] cells.append(77) >>> local_adder() >>> print(cells) [1, 2, 3, 4, 5] </code> Contrary, in the example above nothing new was added to ''cells'' by the function ''local_adder()''. Because ''local_adder()'' **declared a local variable inside a function**. At this moment, a **local** ''cells'' existed and the **top-level** ''cells''. Only the local ''cells'' got the 77 added, but the function itself had no ''print()'' to show this. After the function call, the **top-level** ''cells'' had excatly the same values as before. <code python; gutter:false> >>> coordinates = (44,55) >>> print(coordinates) (44, 55) >>> def invert_coordinates(): coordinates = (-coordinates[0], -coordinates[1]) >>> invert_coordinates() Traceback (most recent call last): File "<pyshell#25>", line 1, in <module> invert_coordinates() File "<pyshell#22>", line 2, in invert_coordinates coordinates = (-coordinates[0], -coordinates[1]) UnboundLocalError: local variable 'coordinates' referenced before assignment </code> Manipulating an immutable tuple is not possible, but in the example above the problem is not the **type** of ''coordinates'' but the **scope**: Inside the ''invert_coordinates()'' function, a new **local** variable ''coordinates'' is declared. The the function tries to assign it the (inverted) value of the **top-level** variable with the same name. And this same name is the problem: python can not access the top-level variable ''coordinate'' anymore because the name is **overwritten** by the **local** variable ''coordinate''! <code python; gutter:false> >>> def invert_coordinates(): coordinates = (-1,-2) >>> coordinates (44, 55) >>> invert_coordinates() >>> coordinates (44, 55) </code> The example above shows that a local variable (with same name as existing top-level variable) can be created inside a function without manipulating the top-level variable at all. This all with an immutable tuple. <code python; gutter:false> >>> def creator(): secret="i am local only" print("inside function:", secret) >>> secret Traceback (most recent call last): File "<pyshell#35>", line 1, in <module> secret NameError: name 'secret' is not defined >>> creator() inside function: i am local only >>> secret Traceback (most recent call last): File "<pyshell#37>", line 1, in <module> secret NameError: name 'secret' is not defined </code> The example above shows the same fact from another perspective: the local variable ''secret'' is well visible....but inside it's function only. not at top-level. <code python; gutter:false> >>> cells [1, 2, 3, 4, 66] >>> def creator2(): cells = [-1,-2,-3] print("local cells:", cells) >>> creator2() local cells: [-1, -2, -3] >>> cells [1, 2, 3, 4, 66] </code> Again, a local variable can be declared inside a function, without conflicts with top-level variable of the same time. This time the variables are of the mutable type list. <code python; gutter:false> >>> def creator3(): cells = [cells[-1], cells[0]] print("local cells:", cells) >>> cells [1, 2, 3, 4, 66] >>> creator3() Traceback (most recent call last): File "<pyshell#51>", line 1, in <module> creator3() File "<pyshell#49>", line 2, in creator3 cells = [cells[-1], cells[0]] UnboundLocalError: local variable 'cells' referenced before assignment </code> In the example above, again the problem of overwriting ''cells'' inside the function with a local variable ''cells'' and then trying to access the **top-level** ''cells'': Not possible, because the name ''cells'' inside the function is already overwritten. It would work by choosing another name for the local variable. <code python; gutter:false> >>> coordinates (44, 55) >>> def swapper(original): return (original[-1],original[0]) >>> coordinates (44, 55) >>> new_c = swapper(coordinates) >>> new_c (55, 44) >>> def doubler(): return (coordinates[0]*2, coordinates[1]*2) >>> coordinates (44, 55) >>> c2 = doubler() >>> c2 (88, 110) </code> And finally how it should be done: If a function want to manipulate an immutable top-level variable, it should use the ''return'' statement and the function caller should assign the returned value to a variable.
import os import os.path as path from glob import glob import cv2 import numpy as np import pandas as pd import streamlit as st import script.data as data import script.utility as util BOX_INFO_FILE = "/mnt/bigdata/00_students/kazuma_nis/box_rec/config/box.csv" SRC_DIR = "/mnt/nict-dbp-2/20231123work/scripts/imgs/" TGT_DIR = "/mnt/bigdata/01_projects/box_dataset/" def _back_states(box_num: int) -> None: st.session_state["box_idx"] -= 1 if st.session_state["box_idx"] == -1: st.session_state["img_idx"] -= 1 st.session_state["box_idx"] = box_num - 1 def _next_states(box_num: int) -> None: st.session_state["box_idx"] += 1 if st.session_state["box_idx"] == box_num: st.session_state["img_idx"] += 1 st.session_state["box_idx"] = 0 def _reset_states() -> None: st.session_state["img_idx"] = 0 st.session_state["box_idx"] = 0 def _check_exist(box_num: int) -> None: while True: if len(glob(path.join(TGT_DIR, f"*_{st.session_state['img_idx']}_{st.session_state['box_idx']}_*.jpg"))) > 0: _next_states(box_num) else: break def _save_box_img(box_num: int, img: np.ndarray, label: str, usr_name: str): file_name = f"{usr_name}_{st.session_state['img_idx']}_{st.session_state['box_idx']}_{label}.jpg" if cv2.imwrite(path.join(TGT_DIR, file_name), img): st.success(f"saved to {file_name}") else: st.error("failed to save image") _next_states(box_num) def _label_btn(box_num: int, img: np.ndarray, label: str, usr_name: str) -> None: st.button(label, on_click=lambda: _save_box_img(box_num, img, label, usr_name)) def _undo(box_num: int, usr_name: str) -> None: _back_states(box_num) files = glob(path.join(TGT_DIR, f"{usr_name}_{st.session_state['img_idx']}_{st.session_state['box_idx']}_*.jpg")) if len(files) > 0: os.remove(files[0]) st.info(f"deleted {path.basename(files[0])}") def render() -> None: if len(st.session_state) == 0: _reset_states() st.title("Dataset Creator") box_info = pd.read_csv(BOX_INFO_FILE) usr_name = st.text_input("input your name") if usr_name != "": files = glob(path.join(SRC_DIR, f"????-??-??U-?????-{st.session_state['img_idx']:04d}.jpg")) if len(files) == 0: st.write(f"image {st.session_state['img_idx']} was not found") else: for f in files: _check_exist(len(box_info)) frm = cv2.imread(f) box_img = util.extract_box(box_info, frm)[st.session_state["box_idx"]] st.image(cv2.rectangle(frm, (box_info.loc[st.session_state["box_idx"], "x0"], box_info.loc[st.session_state["box_idx"], "y0"]), (box_info.loc[st.session_state["box_idx"], "x1"], box_info.loc[st.session_state["box_idx"], "y1"]), (0, 255, 0), thickness=4), channels="BGR") st.write(f"showing box {st.session_state['box_idx']} on image {st.session_state['img_idx']}") st.image(box_img, width=256, channels="BGR") for i, c in enumerate(st.columns(len(data.USAGE))): with c: _label_btn(len(box_info), box_img, tuple(data.USAGE.keys())[i], usr_name) cols = st.columns(8) with cols[0]: st.button("undo", on_click=lambda: _undo(len(box_info), usr_name)) with cols[1]: st.button("skip", on_click=lambda: _next_states(len(box_info))) new_img_idx = st.text_input("img_idx") if new_img_idx != "": st.session_state["img_idx"] = int(new_img_idx) st.session_state["box_idx"] = 0 if __name__ == "__main__": render()
<template> <div> <div :class="$store.state.About?'animacion-about':''"> <v-responsive class="d-flex align-center mx-auto " height="100%" max-width="100%" style="margin-top: 55px;" > <v-card-title class=" d-flex justify-center mb-2"> <div style="width: 50px; height: 6px; background-color: orange;"></div> </v-card-title> <v-card-title class="text-h3 d-flex justify-center" style="color:#0d70b7; font-weight:450"> CONTACTANOS </v-card-title> <v-container > <div class="d-flex justify-space-around " style="flex-wrap: wrap; "> <div class="d-flex align-center pa-3" style="flex-direction: column;"> <v-avatar color="black" size="50"> <v-icon dark> mdi-map-marker </v-icon> </v-avatar> <div class="d-flex align-center" style="flex-direction: column;"> <strong>Direccion</strong> <span style="color:#0d70b7;">MZ B1 Asoc. Risso </span> <span style="color:#0d70b7;"> Vitarte, Lima</span> </div> </div> <div class="d-flex align-center pa-3" style="flex-direction: column;"> <v-avatar color="black" size="50"> <v-icon dark> mdi-phone </v-icon> </v-avatar> <div class="d-flex align-center" style="flex-direction: column;"> <strong>Telefonos</strong> <span style="color:#0d70b7"> +51 995 484 268</span> <span style="color:#0d70b7;">+51 963 903 492</span> <span style="color:#0d70b7;">+51 941 706 977</span> </div> </div> <div class="d-flex align-center pa-3" style="flex-direction: column;"> <v-avatar color="black" size="50"> <v-icon dark> mdi-email </v-icon> </v-avatar> <div class="d-flex align-center" style="flex-direction: column;"> <strong>Correo</strong> <a href="mailto:gerencia@isapesac.com" style="color:#0d70b7; text-decoration: none;">gerencia@isapesac.com</a> </div> </div> </div> </v-container> </v-responsive> <v-container> <v-row> <v-col cols="12" md="5"> <v-card> <v-card-title> Envíanos un mensaje </v-card-title> <v-card-text> <form @submit.prevent="submit"> <v-row class="py-0 my-0"> <v-col cols="12" class="py-0" > <v-text-field label="Nombre y Apellidos" required outlined dense v-model="form.nombre" ></v-text-field> <v-text-field label="correo" dense required type="email" outlined v-model="form.correo" ></v-text-field> <v-text-field label="asunto" outlined dense required v-model="form.subject" ></v-text-field> <v-textarea label="Mensaje" auto-grow required dense outlined v-model="form.mensaje" > </v-textarea> </v-col> </v-row> <v-alert :type="type" :color="color" dense dismissible class="mx-auto my-0 py-o" v-if="mensaje" > {{ mensaje }} {{ verificaralert }} </v-alert> <v-card-actions> <v-btn color="warning" class="text-capitalize" type="submit" :loadin="loader" :disabled="loader" >Enviar mensaje </v-btn> </v-card-actions> </form> </v-card-text> </v-card> </v-col> <v-col cols="12" md="7" class="d-flex justify-center align-center"> <div style="width: 90%; height: 500px;"> <mapa /> </div> </v-col> </v-row> </v-container> <div class="mt-16"> </div> </div> </div> </template> <script> import mapa from '../../components/mapa.vue' export default{ components:{ mapa, }, metaInfo () { return { title: 'Contacto -' } }, data(){ return{ form:{ nombre:'', correo:'', subject:'', mensaje:'', }, loader:false, mensaje:'', type:'', color:'', } }, methods:{ async submit(){ try{ this.loader=true; this.type='success' this.color='green accent-3' this.mensaje=''; const response = await fetch('https://formspree.io/f/xpzeelqj', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(this.form) }); if (response.ok) { this.mensaje = 'Mensaje enviado'; this.loader=false; this.form.correo = ''; this.form.subject = ''; this.form.mensaje = ''; } else { throw new Error('Error en el envío del formulario'); } }catch(error){ this.mensaje = 'Error al enviar el mensaje'; this.type='error' this.color='red' this.loader=false; } }, desctivaralert(){ setTimeout(() => { this.mensaje =''; },3000); } }, computed:{ verificaralert(){ if(this.mensaje && !this.loader){ this.desctivaralert() } return '.'; } } } </script> <style> </style>
package com.bajaj.jpalearning.controller; import com.bajaj.jpalearning.beans.ResponseHandler; import com.bajaj.jpalearning.models.Address; import com.bajaj.jpalearning.models.CartItems; import com.bajaj.jpalearning.models.Product; import com.bajaj.jpalearning.services.AddressServices; import com.bajaj.jpalearning.services.CartItemsServices; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/v1/cart_items") public class CartItemsController { @Autowired CartItemsServices cartItemsServices; @PostMapping("/") public ResponseEntity<Object> create(@RequestBody CartItems cartItems) { Object items = cartItemsServices.create(cartItems); if (items != null) { return ResponseHandler.createResponse("Items added", HttpStatus.CREATED, items); } return ResponseHandler.createResponse("Items already exist", HttpStatus.CONFLICT, null); } @GetMapping("/") public ResponseEntity<Object> getAll() { return ResponseHandler.createResponse("Items found", HttpStatus.OK, cartItemsServices.getAll()); } @GetMapping("/{id}") public ResponseEntity<?> get(@PathVariable Long id) { CartItems items = cartItemsServices.get(id); return ResponseHandler.createResponse("Items Found", HttpStatus.OK, items); } // Fetch cartItems on the basis of customerID @GetMapping("/customer/{customerID}") public ResponseEntity<?> getByCustomerID(@PathVariable Long customerID) { List<CartItems> items = cartItemsServices.getByCustomerId(customerID); return ResponseHandler.createResponse("Items found", HttpStatus.OK, items); } @GetMapping("/customer_id/{id}") public ResponseEntity<?> getByCustomer(@PathVariable Long id) { List<Product> products = cartItemsServices.getCustomerCart(id); return ResponseHandler.createResponse("Items found", HttpStatus.OK, products); } }
<template> <button class="button" @click="emitirClick" :disabled="desabilitado"> <span class="icon"> <i :class="iconeClasse"></i> </span> <span>{{ texto }}</span> </button> </template> <script lang='ts'> import { defineComponent } from "vue"; export default defineComponent({ name: "MeuBotao", emits: ["AoBotaoClicado"], //emite um evento props: { //onde importamos proprs desabilitado: { type: Boolean, default: false, }, texto: { type: String, default: "", }, iconeClasse: { type: String, default: "fas fa-stop", }, }, methods: { emitirClick() { this.$emit("AoBotaoClicado"); //nome e payload para emitir console.log(this.texto); }, }, }); </script> <style scoped> </style>
# AF_XDP Performance Evaluation [![DOI](https://zenodo.org/badge/448600339.svg)](https://zenodo.org/badge/latestdoi/448600339) ## Build For Ubuntu ```bash apt install clang llvm libelf-dev libpcap-dev gcc-multilib build-essential linux-tools-common linux-tools-generic linux-headers-$(uname -r) m4 libnuma-dev ``` For RHEL/CentOS ```bash sudo yum --enablerepo=powertools install llvm clang elfutils-libelf-devel libpcap-devel m4 numactl-devel ``` ```bash git clone --recursive https://github.com/jalalmostafa/afxdp_perfeval.git cd afxdp_perfeval/src make ``` ## Experimentation ### t-rex T-Rex is used to measure latency. Docs how to setup, build, and run t-rex are available in [docs/trex](docs/trex.md) ### pktgen-dpdk Pktgen-dpdk is used to generate packets of different packet sizes. A guide how to setup and run with configuration is available in [docs/pktgen-dpdk](docs/pktgen-dpdk.md). ### Using veth We provide scripts to run our benchmarks using virtual interfaces on the same machine (just for testing purposes). Details in [docs/veth](docs/veth.md) ### `mlx5` MPWQE Inlining Algorithm Disable `mlx5` MPWQE Inlining Algorithm in the source code using the patch available in `mlx5-disable-inlining.patch`. Apply the patch using: `patch -p0 < mlx5-disable-inlining.patch` in the kernel source code, compile and install the modified kernel then restart the server using this kernel. ## Running ```bash Usage: ./dqdk -i <interface_name> -q <hardware_queue_id> Arguments: -d <duration> Set the run duration in seconds. Default: 3 secs -i <interface> Set NIC to work on -q <qid[-qid]> Set range of hardware queues to work on e.g. -q 1 or -q 1-3. Specifying multiple queues will launch a thread for each queue except if -p poll -m <native|offload|generic> Set XDP mode to 'native', 'offload', or 'generic'. Default: native -c Enforce XDP Copy mode, default is zero-copy mode -v Verbose -b <size> Set batch size. Default: 64 -w Use XDP need wakeup flag -p <poll|rtc> Enforce poll or run-to-completion mode. Default: rtc -s <nb_xsks> Set number of sockets working on shared umem -t <tx-packet-size> Set txonly packet size -u Use unaligned memory for UMEM -A <irq1,irq2,...> Set affinity mapping between application threads and drivers queues e.g. q1 to irq1, q2 to irq2,... -I <irq_string> `grep` regex to read and count interrupts of interface from /proc/interrupts -M <rxdrop|txonly|l2fwd> Set Microbenchmark. Default: rxdrop -B Enable NAPI busy-poll -D <dmac> Set destination MAC address for txonly -H Considering Hyper-threading is enabled, this flag will assign affinity of softirq and the app to two logical cores of the same physical core. -G Activate Huge Pages for UMEM allocation -S Run IRQ and App on same core ``` ## Driver Support (as of Linux v6.5-rc2) | Vendor | Driver | Mode | Need Wake Up | | ------------------------ | ---------------- | -------------- | ----------------- | | Intel | i40e | ZC/C | Y | | | ice | ZC/C | Y | | | igb | C | N | | | igc | ZC/C | Y | | | ixgbe | ZC/C | Y | | | ixgbevf | C | N | | NVIDIA/Mellanox | mlx5 | ZC/C | Y | | | mlx4 | C | N | | Broadcom | bnxt | C | N | | Netronome/Corigine | nfp | ZC/C | N | | Marvell | mvneta | C | N | | | mvpp2 | C | N | | | octeontx2 | C | N | | Qlogic (now Marvell) | qede | C | N | | Cavium (now Marvell) | thunder | C | N | | Aquantia (now Marvell) | atlantic | C | N | | MediaTek | mtk | C | N | | MicroChip | lan966x | C | N | | SolarFlare (now Xilinx) | efx | C | N | | | siena-efx | C | N | | SocioNext | netsec | C | N | | STMicroelectronics | stmmac | ZC/C | Y | | Texas Instruments | cpsw | C | N | | Freescale (now NXP) | dpaa | C | N | | | dpaa2 | ZC/C | N | | | enetc | C | N | | | fec | C | N | | Engleder | tsnep | ZC/C | Y | | Fungible (now Microsoft) | funeth | C | N | | Microsoft | mana | C | N | | Microsoft Hyper-V | netvsc | C | N | | Amazon | ena | C | N | | Google | gve | ZC/C | only on TX path | | Xen | netfront | C | N | | VirtIO | virtio\_net | C | N | | Linux | tun | C | N | | | veth | C | N | | | bonding | C | N | | | netdevsim | C | N |
import React, { useState } from 'react' import { faArrowLeft } from '@fortawesome/free-solid-svg-icons' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { Head, Heading, Cross } from '../Cart/Cart.style' import { Field, FieldContainer, Container, FormContainer, Verify, DoLater } from './Login.style' import { useDispatch } from "react-redux" import Actions from '../../redux/actions' const Login = ({ toast, closeCart }) => { const [phone, setPhone] = useState(""); const [otp, setOtp] = useState("00000"); const [conOtp, setConOtp] = useState(""); const dispatch = useDispatch(); const generateOTP = () => { if (phone.length === 10) { let otp = (Math.random() * 9999).toFixed(0); if (otp < 1000) { otp = "0" + otp; } else if (otp < 100) { otp = "00" + otp; } else if (otp < 10) { otp = "000" + otp; } else if (otp === 0) { otp = "0000"; } setOtp(otp); toast.info("Your otp is: " + otp, { autoClose: 3000 }); } else { toast.warning("Enter your Mobile Number", { autoClose: 3000 }); } } const handleSubmit = () => { if (otp === "0000" || conOtp === "") { toast.error("Login failed!", { autoClose: 3000 }) } else if (conOtp === otp) { toast.success("Login successfully!", { autoClose: 3000 }); dispatch(Actions.loggedin()) closeCart(); } } return ( <Container> <Head> <Cross onClick={closeCart}><FontAwesomeIcon icon={faArrowLeft} size="xl" /></Cross> <Heading>Login Details</Heading> </Head> <FormContainer> <FieldContainer> <Field placeholder='Enter your Mobile Number' type="text" name="phone" id="phone" value={phone} onChange={(e) => setPhone(e.target.value)} /> <Verify type="verify" onClick={generateOTP}>Verify</Verify> </FieldContainer> <FieldContainer> { phone.length !== 10 && otp !== "0000" ? <Field placeholder='Click verify to generate OTP' type="number" name="otp" id="otp" value={conOtp} onChange={(e) => setConOtp(e.target.value)} disabled /> : <Field placeholder='Enter OTP' type="number" name="otp" id="otp" value={conOtp} onChange={(e) => setConOtp(e.target.value)} /> } </FieldContainer> <FieldContainer> <Verify type="Submit" onClick={handleSubmit}>Submit</Verify> </FieldContainer> <DoLater onClick={closeCart}>I'll do it later</DoLater> </FormContainer> </Container> ) } export default Login
import React, { FC, ReactNode } from "react"; import Link from "next/link"; interface ILink { children: ReactNode; url: string; classLink?: string; target?: "_blank" | "_self" | "_parent" | "_top"; download?: string; onClick?: (event: Event) => void; disabled?: boolean; className?: string; } const LinkContainer: FC<ILink> = ({ children, url = "", classLink = "", target, download = "", }) => { const downloader = download ? { download: download } : {}; return ( <Link href={{ pathname: url }} as={url} passHref> <a className={classLink} target={target} {...downloader}> {children} </a> </Link> ); }; export { LinkContainer };
//imports const { ethers , run, network} = require("hardhat") //async func async function main(){ const SimpleStorageFactory = await ethers.getContractFactory("SimpleStorage") console.log("Deploying Contract in 3 2 1 ...") const simpleStorage= await SimpleStorageFactory.deploy() await simpleStorage.deployed() console.log(`Deployed Contract to: ${simpleStorage.address}`) console.log(network.config) if(network.config.chainId === 5 && process.env.ETHERSCAN_API_KEY){ await simpleStorage.deployTransaction.wait(6) await verify(simpleStorage.address, []) } const currentValue = await simpleStorage.retrieve(); console.log(`Current Age is :${currentValue}`); const transactionResponse= await simpleStorage.store(17); //updating the value await transactionResponse.wait(1); const updatedValue = await simpleStorage.retrieve() console.log(`Updated Age is : ${updatedValue}`) } async function verify(contractAddress, args) { console.log("Verifying Contract ...") try { await run("verify:verify", { address: contractAddress, ConstructorArguments: args, }) } catch(e){ if (e.mesage.toLowerCase().includes("slready verified")){ console.log("Already Verified!") }else{ console.log(e) } } } //main main().then(() => process.exit(0)) .catch((error) => { console.error(error) process.exit(1); });
import { ComponentProps, ReactElement, ReactNode } from 'react'; import { Box, Tooltip, Popover, PopoverTrigger, PopoverContent, IconButton, Stack, Button, PopoverHeader, PlacementWithLogical, PopoverProps, Text, } from '@chakra-ui/react'; import { ReactComponent as CheckIcon } from '../../../../../assets/icons/check.svg'; import { ReactComponent as ChevronDownIcon } from '../../../../../assets/icons/chevron_down.svg'; import { PopoverWrapper } from '../PopoverWrapper'; type DropdownPopoverOption = { value: any; label: string; icon?: ReactElement; }; type DropdownPopoverOptions = Array<DropdownPopoverOption>; interface DropdownPopoverProps extends Partial<PopoverProps> { w?: string | number; buttonWidth?: string | number; selectedIndex: number; options: DropdownPopoverOptions; toolbarIcon?: ReactElement; label: string; onSelect?: (value?: any) => void; showSelectedIcon?: boolean; selectedIcon?: ReactElement; // icon to display for the selected option header?: ReactNode; placement?: PlacementWithLogical; buttonVariant?: string; optionsButtonVariant?: string; buttonOptionProps?: ComponentProps<typeof Button>; triggerSelectOnSameValue?: boolean; // Call onSelect even if we click on the already selected value } /** * DROPDOWN POPOVER COMPONENT * * This component renders a Chakra icon button that when clicked will * display a Chakra Popover component with dropdown options specified by * 'options' prop. * * If no icon is defined, a text button will render as the trigger. */ export const DropdownPopover = ({ selectedIndex, options, toolbarIcon, label, header, selectedIcon, placement, buttonVariant, optionsButtonVariant, onSelect = () => {}, w = '8.5rem', buttonOptionProps = {}, showSelectedIcon = false, triggerSelectOnSameValue = true, ...popoverProps }: DropdownPopoverProps) => { const handleSelect = (e: React.SyntheticEvent<HTMLButtonElement>): void => { const value = e.currentTarget.dataset.value; // Don't call onSelect for non-changed values. if (!triggerSelectOnSameValue && selectedIndex === options.findIndex((option) => option.value === value)) { return; } onSelect(value); }; const selectedLabel = options[selectedIndex].label; return ( <PopoverWrapper> <Popover placement={placement || 'bottom-start'} closeOnBlur={true} closeOnEsc={true} {...popoverProps}> {({ isOpen }) => ( <> <Tooltip hasArrow placement={'bottom'} label={label} bg='black'> <Box> <PopoverTrigger> {toolbarIcon ? ( <IconButton variant={'icon-btn-toolbar-option'} isActive={isOpen} aria-label={label} icon={toolbarIcon} size='sm' /> ) : ( <Button leftIcon={options[selectedIndex]?.icon} variant={buttonVariant || 'outline'} rightIcon={<ChevronDownIcon />} isActive={isOpen} size={'xs'} width={w} _focus={{ boxShadow: 'outline' }} > <Text fontSize={'sm'} fontWeight={'500'} flexGrow='1' textAlign='left'> {selectedLabel} </Text> </Button> )} </PopoverTrigger> </Box> </Tooltip> {/* TODO add zindex hierarchy */} <Box zIndex={1001}> <PopoverContent w={w} boxShadow='md' padding='0'> {header && <PopoverHeader p={2}>{header}</PopoverHeader>} <Stack p={2}> {options.map((opt, i) => ( <Button leftIcon={opt.icon} onClick={handleSelect} data-value={opt.value} size={'xs'} key={opt.value} isActive={i === selectedIndex} variant={optionsButtonVariant || 'toolbar-dropdown-item'} rightIcon={showSelectedIcon && i === selectedIndex ? selectedIcon || <CheckIcon /> : undefined} {...buttonOptionProps} > {opt.label} </Button> ))} </Stack> </PopoverContent> </Box> </> )} </Popover> </PopoverWrapper> ); };
<?php namespace App\Http\Middleware; use App\Providers\RouteServiceProvider; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Symfony\Component\HttpFoundation\Response; class RedirectIfAuthenticated { /** * Handle an incoming request. * * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next */ public function handle(Request $request, Closure $next, string ...$guards): Response { $guards = empty($guards) ? [null] : $guards; foreach ($guards as $guard) { if (Auth::guard($guard)->check()) { $role = Auth::user()->RelasiRoles->name; switch ($role) { case 'admin': return redirect()->route('home'); break; case 'kepala upt': return redirect()->route('home_kepala_upt'); break; case 'jaringan': return redirect()->route('home_jaringan'); break; case 'koordinator': return redirect()->route('home_koordinator'); break; default: return redirect()->route('login'); } } } return $next($request); } }
# Formating in LLM Apps There are a diverse landscape of formats used in LLM apps and we must emphasize the importance of choosing the best fit for each specific application. Determining the dominant format in LLM apps isn't straightforward as it depends on several factors like the app's purpose, functionality, and target audience. However, here's a breakdown of some common formats and their prevalence: 1. Plain Text: Most widespread: Simple text remains the default format for many LLM applications, particularly those focused on text generation, translation, and summarization. Its simplicity ensures compatibility and ease of processing by the models. Limitations: Lack of formatting options makes it less suitable for complex content or user interfaces. 2. HTML: Common for user interfaces: When LLM apps involve interactive elements or visual presentation, HTML becomes essential for building UI components and integrating dynamic content. Complexity: Requires development knowledge and can limit platform accessibility. 3. JSON: Data exchange and model communication: Internal data structures and communication between LLM models and different app components often rely on JSON for its standardized syntax and efficiency. Not user-facing: Primarily for inter-system communication and not directly visible to users. 4. Markdown: Increasing adoption: Markdown's simplicity and clarity are gaining traction in LLM apps for presenting prompts, instructions, and generated text, especially in text-focused tools and chatbots. Limitations: Not ideal for complex formatting or visual elements. 5. Proprietary formats: Specific app needs: Some LLM apps might develop their own custom formats to handle specific data types, model outputs, or user interactions. Limited reach and compatibility: Can restrict interoperability with other tools and platforms. Therefore, there's no single "dominant" format. Plain text and HTML reign supreme in various situations, while Markdown and JSON contribute to specific functionalities. Choosing the appropriate format depends on the app's purpose, target audience, and desired level of complexity. In building an LLM app/api we commonly use JSON as a request and response format, should we use html or markdown to represent visual and/or generated fields, in other words shoud use markdown or html inside JSON? While both HTML and Markdown have their merits, the most suitable choice for representing visual and generated fields within JSON responses in an LLM app/API depends on several factors: ### Markdown: Pros: Readability: Human-friendly, plain text format, easy to read and edit. Cross-Platform Compatibility: Well-supported by various platforms and libraries. Version Control Friendliness: Text-based nature makes it easier to track changes. Security: Less prone to injection vulnerabilities than HTML. Cons: Limited Formatting: Supports basic formatting, might not suffice for complex layouts. Rendering Requirement: Needs a Markdown parser to convert to formatted text. ### HTML: Pros: Rich Formatting: Enables intricate visual layouts and styles. Direct Rendering: Can be directly displayed in web browsers and many other contexts. Extensibility: Wide range of tags and attributes for diverse content types. Cons: Complexity: More verbose and less human-readable than Markdown. Security Concerns: Requires careful sanitization to prevent injection attacks. ### Key Considerations: Complexity of Formatting: For basic formatting, Markdown often suffices. For complex visual layouts, HTML is necessary. Security: Prioritize Markdown if security is paramount. If using HTML, implement robust sanitization measures. Target Platforms: Markdown is more adaptable across platforms. Rendering Context: If direct rendering in browsers or HTML-aware environments is crucial, HTML is a better fit. Version Control: Markdown's text-based nature facilitates version control. Control Over Rendering: HTML offers more granular control over appearance. ### Additional Considerations: Hybrid Approach: Consider using Markdown for core content and embedding HTML elements where fine-grained control is needed. Alternative Formats: Evaluate other markup formats like AsciiDoc or Textile, which offer varying levels of formatting and readability. API Design: Structure your API responses to enable clients to choose their preferred rendering method. Ultimately, the best choice depends on your specific application requirements and priorities. Carefully assess these factors to make an informed decision.
import React from 'react'; import {LucideIcon} from "lucide-react"; import {cva, type VariantProps} from "class-variance-authority"; import {cn} from "@/lib/utils"; // cva is a function that returns a function that returns a string. It's used to create a class variance authority. const backgroundVariants = cva( "rounded-full flex items-center justify-center", { variants: { variant: { default: "bg-sky-100", green: "bg-green-100", rose: "bg-rose-100", yellow: "bg-yellow-100", blue: "bg-blue-100", }, size: { default: "p-2", sm: "p-1", lg: "p-3", }, }, defaultVariants: { variant: "default", size: "default", } } ); const iconVariants = cva( "", { variants: { variant: { default: "text-sky-500", green: "text-green-500", rose: "text-rose-500", yellow: "text-yellow-500", blue: "text-blue-500", }, size: { default: "w-6 h-6", sm: "w-4 h-4", lg: "w-8 h-8", }, }, defaultVariants: { variant: "default", size: "default", } } ); type BackgroundVariantProps = VariantProps<typeof backgroundVariants>; type IconVariantProps = VariantProps<typeof iconVariants>; interface IconBadgeProps extends BackgroundVariantProps, IconVariantProps { icon: LucideIcon; } const IconBadge = ({icon: Icon, variant, size}: IconBadgeProps) => { return ( // Here, the div is being used as a background for the icon. // cn is used to concatenate the classes. <div className={cn(backgroundVariants({variant: variant, size: size}))}> <Icon className={cn(iconVariants({variant: variant, size: size}))}/> </div> ); }; export default IconBadge;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dominik Horut</title> <link rel="icon" href="img/icon.ico" type="image/x-icon"> <link rel="stylesheet" href="css/style.css" type="text/css" /> <!-- Font awesome --> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"> <link rel="stylesheet" href="css/style.css"> <!-- Fonts import --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Open+Sans:ital,wght@0,300..800;1,300..800&family=Roboto+Mono:ital,wght@0,100..700;1,100..700&family=Sedgwick+Ave&display=swap" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <header> <a id="logo" href="http://www.stud.fit.vutbr.cz/~xhorut01/"> <img src="./img/logo.png" alt="logo-normal"> </a> <h1>Dominik <span>Horut</span></h1> <nav> <ul> <li><a href="#">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#skills">Skills</a></li> <li><a href="#hobbies">Hobies</a></li> </ul> </nav> <i id="hamburger" class="fa-solid fa-bars"></i> <nav class="hamburger-menu"> <ul class="hamburger-list"> <li><a href="#">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#skills">Skills</a></li> <li><a href="#hobbies">Hobies</a></li> </ul> </nav> </header> <section id="intro"> <div class="section-content"> <h1 id="hey">Hey</h1> <h1 id="iam">I'M <span>DOMINIK</span></h1> <h1>Passionate CS student</h1> </div> </section> <section id="about"> <div class="section-content"> <div id="introduction"> <h2>Few words about me</h2> <p> Maecenas libero. Aenean id metus id velit ullamcorper pulvinar. Integer rutrum, orci vestibulum ullamcorper ultricies, lacus quam ultricies odio, vitae placerat pede sem sit amet enim. Nunc auctor. Etiam dui sem, fermentum vitae, sagittis id, malesuada in, quam. Maecenas sollicitudin. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Phasellus enim erat, vestibulum vel, aliquam a, posuere eu, velit. Sed ac dolor sit amet purus malesuada congue. Duis pulvinar. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Mauris dictum facilisis augue. </p> <img src="./img/about-pic.png" alt="my-picture"> </div> </div> </section> <section id="timeline"> <div class="section-content"> <h2>My journey</h2> <div id="line"> <div class="dot-container"> <div class="dot-pulse"></div> <div class="dot"></div> <img src="./img/line-1.svg" alt="dashed-line"> </div> <div class="dot-container"> <div class="dot-pulse"></div> <div class="dot"></div> <img src="./img/line-1.svg" alt="dashed-line"> </div> <div class="dot-container"> <div class="dot-pulse"></div> <div class="dot"></div> <img src="./img/line-1.svg" alt="dashed-line"> </div> <div class="dot-container"> <div class="dot-pulse"></div> <div class="dot"></div> </div> </div> </div> </section> <section id="skills"> <div class="section-content"> <div id="soft-skills"> <h2>Soft skills</h2> <div class="roll a"><i class="a fa-solid fa-angles-down"></i></div> <div class="skill-list"> <div class="skill"> <i class="fa-regular fa-comments"></i> <h3>Communication</h3> <p>skill level</p> <div class="rating"> <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-half-stroke"></i> <i class="fa-regular fa-star"></i> </div> </div> <div class="skill"> <i class="fa-regular fa-face-grin-wink"></i> <h3>Emotional intelligence</h3> <p>skill level</p> <div class="rating"> <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-regular fa-star"></i> </div> </div> <div class="skill"> <i class="fa-solid fa-handshake-angle"></i> <h3>Collaboration</h3> <p>skill level</p> <div class="rating"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-regular fa-star"></i> <i class="fa-regular fa-star"></i> </div> </div> <div class="skill"> <i class="fa-regular fa-hourglass-half"></i> <h3>Time management</h3> <p>skill level</p> <div class="rating"> <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-half-stroke"></i> </div> </div> </div> </div> <div id="hard-skills"> <h2>Hard skills</h2> <div class="roll b"><i class="b fa-solid fa-angles-down"></i></div> <div class="skill-list"> <div class="skill"> <i class="fa-brands fa-python"></i> <h3>Python</h3> <p>skill level</p> <div class="rating"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-regular fa-star"></i> <i class="fa-regular fa-star"></i> </div> </div> <div class="skill"> <i class="fa-brands fa-php"></i> <h3>PHP</h3> <p>skill level</p> <div class="rating"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-regular fa-star"></i> <i class="fa-regular fa-star"></i> </div> </div> <div class="skill"> <img src="img/c.png" alt="clang" width="72" height="82"> <h3>C/C++</h3> <p>skill level</p> <div class="rating"> <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-regular fa-star"></i> </div> </div> <div class="skill"> <i class="fa-brands fa-java"></i> <h3>Java</h3> <p>skill level</p> <div class="rating"> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star"></i> <i class="fa-solid fa-star-half-stroke"></i> <i class="fa-regular fa-star"></i> <i class="fa-regular fa-star"></i> </div> </div> <div class="skill"> <i class="fa-brands fa-linux"></i> <h3>Linux</h3> <p>skill level</p> <div class="rating"> <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-half-stroke"></i> <i class="fa-regular fa-star"></i> </div> </div> <div class="skill"> <i class="fa-brands fa-git-alt"></i> <h3>Git</h3> <p>skill level</p> <div class="rating"> <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-regular fa-star"></i> </div> </div> </div> </div> </div> </section> <section id="hobbies"> <div class="section-content"> <h2>What I love to do when I am not coding</h2> <div id="hobby-list"> <div class="hobby"> <div class="pic a"> <img src="./img/mountain.jpg" alt="mountain"> <a class="click-me a">Click me</a> </div> <div class="paragraph a"> <h3>Mountains</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque euismod nisi urna, eget laoreet elit tincidunt quis.</p> <a class="back a">Back</a> </div> </div> <div class="hobby"> <div class="pic b"> <img src="./img/guitar.jpg" alt="guitar"> <a class="click-me b">Click me</a> </div> <div class="paragraph b"> <h3>Music</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque euismod nisi urna, eget laoreet elit tincidunt quis.</p> <a class="back b">Back</a> </div> </div> <div class="hobby"> <div class="pic c"> <img src="./img/hockey.jpg" alt="hockey"> <a class="click-me c">Click me</a> </div> <div class="paragraph c"> <h3>Ice hockey</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque euismod nisi urna, eget laoreet elit tincidunt quis.</p> <a class="back c">Back</a> </div> </div> </div> </div> </section> <footer> <div class="section-content"> <a id="img" href="#"> <img src="./img/logo-dark-blue.png" alt="blue-logo"> </a> <div id="copyright"> <i class="fa-regular fa-copyright"></i> <p>2024 Dominik Horut</p> </div> <div id="structure"> <h3>Structure</h3> <a href="#">Home</a> <a href="#about">About</a> <a href="#skills">Skills</a> <a href="#hobbies">Hobies</a> </div> <div id="socials"> <h3>Follow Me</h3> <div id="soc-refs"> <a href="https://www.instagram.com/domis_horut/"> <i class="fa-brands fa-instagram"></i> </a> <a href="https://www.facebook.com/profile.php?id=100008627406692"> <i class="fa-brands fa-facebook"></i> </a> <a href="https://github.com/PanHorut"> <i class="fa-brands fa-github"></i> </a> </div> </div> <div id="contact"> <h3>Let's stay in touch</h3> <div id="send-email"> <input id="email" name="email" type="email" placeholder="Your email" required> <div id="submit">Submit</div> </div> </div> </div> <div class="thank-note"> <h3>Thank you for submiting</h3> <p>In the following days, expect email from</p> <p id="address">xhorut01@vutbr.cz</p> </div> </footer> <script src="script.js"></script> </body> </html>
package com.example.agrishopapp; import static android.content.ContentValues.TAG; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.ScrollView; import android.widget.Toast; import com.example.adapters.HomeAdapter; import com.example.adapters.PopularAdapters; import com.example.adapters.ViewAllAdapter; import com.example.models.HomeCategory; import com.example.models.PopularModel; import com.example.models.ViewAllModel; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.Query; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import java.util.ArrayList; import java.util.List; public class HomeFragment extends Fragment { ScrollView scrollView; ProgressBar progressBar; RecyclerView popularRec, homeCatRec; FirebaseFirestore db; // Popular Items List<PopularModel> popularModelList; PopularAdapters popularAdapters; EditText search_box; List<ViewAllModel> viewAllModelList; RecyclerView recyclerViewSearch; ViewAllAdapter viewAllAdapter; // Home Category List<HomeCategory> categoryList; HomeAdapter homeAdapter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View root = inflater.inflate(R.layout.fragment_home, container, false); db = FirebaseFirestore.getInstance(); popularRec = root.findViewById(R.id.pop_rec); homeCatRec = root.findViewById(R.id.explore_rec); scrollView = root.findViewById(R.id.scroll_view); progressBar = root.findViewById(R.id.progressbar); progressBar.setVisibility(View.VISIBLE); scrollView.setVisibility(View.GONE); // popular items popularRec.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.HORIZONTAL, false)); popularModelList = new ArrayList<>(); popularAdapters = new PopularAdapters(getActivity(), popularModelList); popularRec.setAdapter(popularAdapters); db.collection("popularProducts") .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { PopularModel popularModel = document.toObject(PopularModel.class); popularModelList.add(popularModel); popularAdapters.notifyDataSetChanged(); progressBar.setVisibility(View.GONE); scrollView.setVisibility(View.VISIBLE); } } else { Toast.makeText(getActivity(), "Error" + task.getException(), Toast.LENGTH_SHORT).show(); } } }); // Home Category items homeCatRec.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.HORIZONTAL, false)); categoryList = new ArrayList<>(); homeAdapter = new HomeAdapter(getActivity(), categoryList); homeCatRec.setAdapter(homeAdapter); db.collection("HomeCategory") .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { HomeCategory homeCategory = document.toObject(HomeCategory.class); categoryList.add(homeCategory); homeAdapter.notifyDataSetChanged(); } } else { Toast.makeText(getActivity(), "Error" + task.getException(), Toast.LENGTH_SHORT).show(); } } }) ; recyclerViewSearch = root.findViewById(R.id.search_rec); search_box = root.findViewById(R.id.search_box); viewAllModelList = new ArrayList<>(); viewAllAdapter = new ViewAllAdapter(getContext(), viewAllModelList); recyclerViewSearch.setLayoutManager(new LinearLayoutManager(getContext())); recyclerViewSearch.setAdapter(viewAllAdapter); recyclerViewSearch.setHasFixedSize(true); // // Set the click listener on the search icon search_box.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_search, 0, 0, 0); search_box.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Call the searchProduct method with the current text in the search box searchProduct(search_box.getText().toString()); } }); search_box.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (s.toString().isEmpty()) { viewAllModelList.clear(); viewAllAdapter.notifyDataSetChanged(); } else { searchProduct(s.toString()); } } }); return root; } private void searchProduct(String name) { if (!name.isEmpty()) { db.collection("AllProducts") .whereEqualTo("name",name) .orderBy("datetime", Query.Direction.DESCENDING) .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { viewAllModelList.clear(); viewAllAdapter.notifyDataSetChanged(); for (QueryDocumentSnapshot document : task.getResult()) { ViewAllModel viewAllModel = document.toObject(ViewAllModel.class); viewAllModelList.add(viewAllModel); viewAllAdapter.notifyDataSetChanged(); } } } }); } } }
@calculator Feature: Calculator Background: Given User is on login page When User input username "admin" When User input password "admin" When User click login button Then User successfully login @addition Scenario: Sum of the 1st and 2nd digits Given User is on calculator page When User input 3 as first number When User selected sum option When User input 4 as second number When User click equal to button Then Result showing as expected sum @subtraction Scenario: Subtraction of the 1st and 2nd digits Given User is on calculator page When User input 20 as first number When User selected subtraction option When User input 5 as second number When User click equal to button Then Result showing as expected subtraction @multiple Scenario: Multiplication of the 1st and 2nd digits Given User is on calculator page When User input 5 as first number When User selected multiplication option When User input 6 as second number When User click equal to button Then Result showing as expected multiplication @division Scenario: Division of the 1st and 2nd digits Given User is on calculator page When User input 100 as first number When User selected division option When User input 25 as second number When User click equal to button Then Result showing as expected division
//import styled from 'styled-components'; import { Component } from 'react'; import Statistics from './FeedbackComponents/Statistics'; import FeedbackOptions from './FeedbackComponents/FeedbackOptions'; import Section from './Section/Section'; import Notification from './FeedbackComponents/Notification'; import { Box } from './Box/Box'; export class App extends Component { state = { good: 0, neutral: 0, bad: 0, }; clickOnBtn = feedback => { this.setState(prevState => { return { [feedback]: prevState[feedback] + 1, }; }); }; countTotalFeedback = () => { return Object.values(this.state).reduce((acc, feedback) => { return acc + feedback; }, 0); }; countPositiveFeedbackPercentage = () => { return `${ Math.round((this.state.good / this.countTotalFeedback()) * 100) || 0 }%`; }; countNegativeFeedbackPercentage = () => { return `${ Math.round((this.state.bad / this.countTotalFeedback()) * 100) || 0 }%`; }; render() { return ( <Box as="main" px={5}> <Section title="Please leave feedback"> <FeedbackOptions options={this.state} onLeaveFeedback={this.clickOnBtn} /> </Section> <Section title="Statistics"> {this.countTotalFeedback() ? ( <Statistics good={this.state.good} neutral={this.state.neutral} bad={this.state.bad} total={this.countTotalFeedback()} positivePercentage={this.countPositiveFeedbackPercentage()} negativePercentage={this.countNegativeFeedbackPercentage()} /> ) : ( <Notification text="There is no feedback" /> )} </Section> </Box> ); } }
require('dotenv').config(); const mongoose = require('mongoose'); const mongoString = process.env.DATABASE_URL mongoose.connect(mongoString); const database = mongoose.connection; database.on('error',(e)=>{ console.log(e) }); database.once('connected',()=>{ console.log('Database Connected'); }); //routes const Model = require("../Model/model"); const router = require("./Routes"); //post router.post('/post',async(req,res)=>{ const data = new Model({ name: req.body.name, age: req.body.age }) try { const dataToSave = await data.save(); res.status(200).json(dataToSave); } catch (error) { res.status(400).json(error.message); } }); //get all router.get('/getAll', async(req,res)=>{ try { const data = await Model.find(); res.json(data); } catch (error) { res.status(500).json({message:error.message}); } }) //get by id router.get('/getOne/:id',async(req,res)=>{ try { const data = await Model.findById(req.params.id); res.json(data); } catch (error) { res.status(500).json({message:error.message}); } }) //update by it router.patch('/update/:id',async (req,res)=>{ try { const data = req.body; const id = req.params.id; const options = {new : true}; const result = await Model.findByIdAndUpdate(id, data, options); res.json(result); } catch (error) { res.status(400).json({message:error.message}); } }); //delete by id router.delete('/delete/:id',async(req,res)=>{ try { const id = req.params.id; const result = await Model.findByIdAndDelete(id); res.send(`Document with ${result.name} sucessfully deleted`); } catch (error) { res.status(400).json({message:error.message}); } }); module.exports = router;
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://unpkg.com/vue@2"></script> <title>Listas v1 - 'v-for' iterando sobre um array</title> </head> <body> <div id="app"> <ul> <li v-for="cor in cores">{{ cor }}</li> </ul> </div> <script> new Vue({ el: '#app', data: { cores: ['Vermelho', 'Verde', 'Amarelo', 'Azul'], pessoas: [ { nome: 'Ana', idade: 26, peso: 59 }, { nome: 'Guilherme', idade: 22, peso: 89 } ] } }); </script> </body> </html>
import React from "react"; import '../../styles/Controles.css' export default function Controles({ fn, countries }) { const [filter, setFilter] = React.useState({ gender: "", serBy: "name", country: "", minAge: 0, maxAge: 120, }); React.useEffect(() => { fn(filter); }, [filter, fn]); const countriesOptions = countries.sort().map((country, index) => <option className="count-opt" key={index} value={country}>{country}</option>) return ( <div className="controls-bar"> <p className="categ-title">Categorias</p> <ul className="categ-list"> <li onClick={() => setFilter((oldFilter) => ({ ...oldFilter, gender: oldFilter.gender === "" ? "male" : oldFilter.gender === "male" ? "female" : "", })) } className="categ-list-item" > Genero <span className="icon">{filter.gender !== "" ? filter.gender === "male" ? "🤠" : "🤢" : ""}</span> </li> <li onClick={() => setFilter((oldFilter) => ({ ...oldFilter, serBy: "name" })) } className="categ-list-item" > Nombre {filter.serBy === "name" && <span className="icon"> ✔️</span>} </li> <li onClick={() => setFilter((oldFilter) => ({ ...oldFilter, serBy: "country" })) } className="categ-list-item" > Pais {filter.serBy === "country" && <span className="icon"> ✔️</span>} </li> <li className="categ-list-item"> <select onChange={(e) => setFilter(oldFilter => ({...oldFilter, country: e.target.value}))} value={filter.country} name="" id=""> <option value="" >Cualquiera</option> {countriesOptions} </select> </li> <li className="categ-list-item slider-wrapper"> <label htmlFor="min-range">Edad Minima | {filter.minAge}</label> <input className="slider" onChange={e => setFilter(oldFilter => ({...oldFilter, minAge: e.target.valueAsNumber > oldFilter.maxAge ? oldFilter.maxAge : e.target.valueAsNumber}))} value={filter.minAge} min={0} max={120} type="range" id="min-range" /> <label htmlFor="max-range">Edad Maxima | {filter.maxAge}</label> <input className="slider" onChange={e => setFilter(oldFilter => ({...oldFilter, maxAge: e.target.valueAsNumber < oldFilter.minAge ? oldFilter.minAge : e.target.valueAsNumber}))} value={filter.maxAge} min={0} max={120}type="range" id="max-range" /> </li> </ul> </div> ); }
import { Body, Controller, Get, Param, Post, Query, Req, UseGuards, } from '@nestjs/common'; import { TaskService } from './tasks.service'; import { AuthGuard } from 'src/auth/guards/auth.guard'; import { newTask, pagination } from './task.dto'; import { JwtService } from '@nestjs/jwt'; @Controller('api/task') export class TaskController { constructor( private readonly service: TaskService, private readonly jwtService: JwtService, ) {} @Post('/create') @UseGuards(AuthGuard) async createTask(@Req() req: any, @Body() newTask: newTask) { if ( !newTask.receiver || newTask.receiver === '' || newTask.task === '' || !newTask.task ) { return { status: 0, message: 'Vui lòng chọn nhiệm vụ và người nhận', }; } return await this.service.taskForAdvise( req.user.sub, newTask.receiver, newTask.task, ); } @Post('/create/for-consultation') @UseGuards(AuthGuard) async createTaskForConsultation(@Req() req: any, @Body() newTask: newTask) { if ( !newTask.receiver || newTask.receiver === '' || newTask.task === '' || !newTask.task ) { return { status: 0, message: 'Vui lòng chọn nhiệm vụ và người nhận', }; } return await this.service.taskForConsultation( req.user.sub, newTask.receiver, newTask.task, ); } @Get('/get-task') @UseGuards(AuthGuard) async getReceiverTask(@Req() req: any, @Query() pagination: pagination) { return await this.service.getReceivertTask(req.user.sub, pagination); } @Get('/owner-task') @UseGuards(AuthGuard) async getOwnerTask(@Req() req: any, @Query() pagination: pagination) { return await this.service.getOwnerTask(req.user.sub, pagination); } @Get('/owner-task-consultation') @UseGuards(AuthGuard) async getOwnerTaskConsultation( @Req() req: any, @Query() pagination: pagination, ) { return await this.service.getOwnerTaskForConsultation( req.user.sub, pagination, ); } @Get('/task-for-consultation') @UseGuards(AuthGuard) async getReceiverTaskForConsultation( @Req() req: any, @Query() pagination: pagination, ) { return await this.service.getReceiverTaskForConsultation( req.user.sub, pagination, ); } @Post('/confirm/:id') @UseGuards(AuthGuard) async confirmTask( @Param('id') id: string, @Query('status') status: number, @Req() req: any, @Body() body: any, ) { return await this.service.confirmTask( status, id, req.user.sub, body.adviseStatus, ); } }
export interface Product { productId: string; productName: string; stockLevel: number; totalValue: number; totalOrders: number; totalCost: number; totalRevenue: number; totalProfit: number; } export interface RestockProduct { productId: string; productName: string; quantity: number; unitPrice: number; totalPrice: number; } export interface Order { date: string; productName: string; quantity: number; cost: number; profit: number; } export interface OrderPreview { productName: string; quantity: number; revenue: number; } export interface CustomerOrder { dateOrdered: string; datePaid: Date | string | null; productName: string; quantity: number; value: number; paid: string; } export interface Customer { customerId: string; customerName: string; balance: number; dueDate: string; totalOrders: number; totalRevenue: number; } export type CustomerPreview = Pick< Customer, 'customerId' | 'customerName' | 'balance' >; export interface TableColumns { Header: string; columns: { Header: string; accessor: string; }[]; } export type ProductPreview = Pick< Product, 'productId' | 'productName' | 'stockLevel' >; export type ProductOrder = Pick<Order, 'productName' | 'quantity'>; export interface OrderInfo { customerName: string; orderTotal: number; items: ProductOrder[]; }
class ReviewsController < ApplicationController before_action :get_restaurant def new @review = Review.new end def create @review = Review.new(review_params) @review.restaurant = @restaurant if @review.save redirect_to restaurant_path(@restaurant) else render :new end end # --------------------- private def get_restaurant @restaurant = Restaurant.find(params[:restaurant_id]) end def review_params params.require(:review).permit(:rating, :content) end end
// // MockAuthenticationService.swift // // SAMPLE MOCK AUTHENTATION SERVICE import swiftarcstdlib import Foundation class MockAuthenticationService: AuthenticationService { private struct UserAccountEntry: Codable { var user: ActiveUser var password: String init(user: ActiveUser, password: String) { self.user = user self.password = password } } private var allUsers: [UserAccountEntry] init() { allUsers = Self.readAllUsers() } func login(with userName: String, _ password: String) async throws -> ActiveUser { try await Task.sleep(seconds: 2) let userData = allUsers.first( where: { $0.user.email == userName && $0.password == password } ) guard let userData else { throw AuthenticationError.credentialsInvalid } let activeUser = userData.user Self.write(activeUser: activeUser) return activeUser } func logout() throws { // Delete active user UserDefaults.standard.removeObject(forKey: Self.activeUserKey()) } func signup(with userName: String, _ name: String, _ password: String) async throws -> ActiveUser { // Test case for failure during signup guard UserDefaults.standard.data(forKey: Self.activeUserKey()) == nil else { throw AuthenticationError.unhandledError(error: "Attepting to sign up while already logged in") } guard allUsers.contains(where: {$0.user.email == userName}) == false else { throw AuthenticationError.accountFailedCreating } try await Task.sleep(seconds: 2) let activeUser = ActiveUser(name: name, email: userName) Self.write(activeUser: activeUser) allUsers.append(.init(user: activeUser, password: password)) Self.write(allUsers: allUsers) return activeUser } private static func activeUserKey() -> String { "authActiveUser" } private static func write(allUsers: [UserAccountEntry]) { do { let encoder = JSONEncoder() let data = try encoder.encode(allUsers) let userDefaults = UserDefaults.standard userDefaults.set(data, forKey: "allUsers") } catch { Logger.error(topic: .authentication, message: "Cannot write MOCK allUsers - \(error)") } } private static func readAllUsers() -> [UserAccountEntry] { do { guard let data = UserDefaults.standard.data(forKey: "allUsers") else { throw "No allUsers data is available..." } // Convert to data type let decoder = JSONDecoder() let value = try decoder.decode([UserAccountEntry].self, from: data) return value } catch { Logger.error(topic: .authentication, message: "Cannot read MOCK allUsers - \(error)") return [] } } private static func write(activeUser: ActiveUser) { do { let encoder = JSONEncoder() let data = try encoder.encode(activeUser) let userDefaults = UserDefaults.standard userDefaults.set(data, forKey: Self.activeUserKey()) } catch { Logger.error(topic: .authentication, message: "Cannot write MOCK active user - \(error)") } } private static func readActiveUser() -> ActiveUser? { do { guard let data = UserDefaults.standard.data(forKey: Self.activeUserKey()) else { throw "No active user is available..." } // Convert to data type let decoder = JSONDecoder() let value = try decoder.decode(ActiveUser.self, from: data) return value } catch { Logger.error(topic: .authentication, message: "Cannot read MOCK active user - \(error)") return nil } } func delete(user userName: String, _ password: String) async throws { do { guard UserDefaults.standard.value(forKey: Self.activeUserKey()) != nil else { throw "User data does not exists :\(Self.activeUserKey())" } let userExists = allUsers.contains( where: { $0.user.email == userName && $0.password == password } ) guard userExists else { throw "Invalid Credentials" } allUsers.removeAll(where: {$0.user.email == userName}) Self.write(allUsers: allUsers) } catch { Logger.error(topic: .authentication, message: "Cannot read MOCK active user - \(error)") throw "Failed deleting user data: \(error)" } } func changePassword( for userName: String, from oldUserName: String, to newUserName: String ) async throws { try? await Task.sleep(seconds: 2) } func resetPasswordRequest(for userName: String) async throws { try await Task.sleep(seconds: 1) } }
using API.Models; using API.Services.Interfaces; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using Microsoft.Extensions.Configuration; using System; namespace API.Services { /// <summary> /// Provides token generation services for <see cref="Employee"/> entities. /// </summary> public class EmployeeTokenService : ITokenService<Employee> { private readonly IConfiguration _configuration; /// <summary> /// Initializes a new instance of the <see cref="EmployeeTokenService"/> class. /// </summary> /// <param name="configuration">The configuration containing the JWT settings.</param> public EmployeeTokenService(IConfiguration configuration) { _configuration = configuration; } /// <summary> /// Generates a JWT token for the specified <see cref="Employee"/>. /// </summary> /// <param name="item">The <see cref="Employee"/> for which the token is generated.</param> /// <returns>The generated JWT token as a string.</returns> public string GenerateToken(Employee item) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_configuration["Jwt:EmployeeSecret"]); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim("Id", item.EmployeeId.ToString()), new Claim(ClaimTypes.Name, item.EmployeeName) }), Expires = DateTime.UtcNow.AddDays(100), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } } }
// // WorkoutDayExercisesScreen.swift // Healtho Gym // // Created by CodeForAny on 27/03/24. // import SwiftUI struct WorkoutDayExercisesScreen: View { @Environment(\.presentationMode) var mode: Binding<PresentationMode> @State var listArr = [ [ "name": "Bench Press", "sets": "3", "reps": "12 - 10 - 0", "rest": "30 Sec", "image": "d1", "is_complete": false, ],[ "name": "Bench Press", "sets": "3", "reps": "12 - 10 - 0", "rest": "30 Sec", "image": "d2", "is_complete": true, ],[ "name": "Bench Press", "sets": "3", "reps": "12 - 10 - 0", "rest": "30 Sec", "image": "d3", "is_complete": false, ],[ "name": "Bench Press", "sets": "3", "reps": "12 - 10 - 0", "rest": "30 Sec", "image": "d4", "is_complete": false, ],[ "name": "Bench Press", "sets": "3", "reps": "12 - 10 - 0", "rest": "30 Sec", "image": "d5", "is_complete": false, ], ] @State var showDetal = false var body: some View { ZStack{ VStack{ HStack{ Button(action: { mode.wrappedValue.dismiss() }, label: { Image("back_white") .resizable() .scaledToFit() .frame(width: 20, height: 20) }) Text("Week 1 - Day 1") .font(.customfont(.regular, fontSize: 18)) .maxLeft Button(action: { }, label: { Text("Reset") .font(.customfont(.regular, fontSize: 14)) .maxLeft }) } .foregroundColor(Color.white) .horizontal20 .vertical15 .topWithSafe .background(Color.secondaryApp) ScrollView{ LazyVStack(spacing: 15){ ForEach(0 ..< listArr.count, id:\.self) { index in let obj = listArr[index] let isComplete = obj["is_complete"] as? Bool ?? false Button { showDetal = true } label: { VStack{ HStack(spacing: 8){ Image(obj["image"] as? String ?? "" ) .resizable() .scaledToFill() .frame(width: 70, height: 70) .cornerRadius(10) VStack(spacing: 4) { Text( obj["name"] as? String ?? "" ) .font(.customfont(.regular, fontSize: 14)) .maxLeft HStack{ Text( "Sets" ) .font(.customfont(.semiBold, fontSize: 12)) .frame(width: 50, alignment: .leading) Text( obj["sets"] as? String ?? "" ) .font(.customfont(.regular, fontSize: 12)) .maxLeft } HStack{ Text( "Reps" ) .font(.customfont(.semiBold, fontSize: 12)) .frame(width: 50, alignment: .leading) Text( obj["reps"] as? String ?? "" ) .font(.customfont(.regular, fontSize: 12)) .maxLeft } HStack{ Text( "Rest" ) .font(.customfont(.semiBold, fontSize: 12)) .frame(width: 50, alignment: .leading) Text( obj["rest"] as? String ?? "" ) .font(.customfont(.regular, fontSize: 12)) .maxLeft } } .foregroundColor(.primaryText) .padding(.leading, 25) Image("next") .resizable() .scaledToFit() .frame(width: 12, height: 12) } .vertical8 .horizontal20 Divider() HStack{ Image( isComplete ? "check_tick" : "uncheck" ) .resizable() .scaledToFit() .frame(width: 20, height: 20) Text( "Make as Completed" ) .font(.customfont(.regular, fontSize: 17)) .foregroundColor(isComplete ? .green : .placeholder ) } .maxCenter .horizontal15 .bottom8 } } .background(Color.txtBG) .cornerRadius(10) .overlay( RoundedRectangle(cornerRadius: 10).stroke(Color.board, lineWidth: 1) ) } } .all15 .bottomWithSafe } } } .bgNavLink(content: ExerciseDetailsScreen(), isAction: $showDetal) .navHide } } #Preview { WorkoutDayExercisesScreen() }
import { User } from "../modals/userModal.js"; import { v4 as uuidv4 } from 'uuid'; import { createToken } from "../utils/token.js"; export const insertUser = async (req, res) => { try { const { user_name, user_email, user_password, user_image, } = req.body; if(user_name === ""){ return res.status(400).json({success:false,message:"username cannot be blank"}) } if(user_email === ""){ return res.status(400).json({success:false,message:"email cannot be blank"}) } if(user_password === ""){ return res.status(400).json({success:false,message:"password cannot be blank"}) } if(user_image === ""){ return res.status(400).json({success:false,message:"image cannot be blank"}) }; const userExists = await User.findOne({user_email}); if(userExists){ return res.status(409).json({ success:false, message:"Email id already in use" }) } const user_id = uuidv4(); const total_orders =Math.floor(Math.random()*100); const userData = { user_id : uuidv4(), user_name, user_email, user_password, user_image, total_orders : Math.floor(Math.random()*100), created_at: new Date(Date.now()), last_logged_in:null }; const saveData = await User.create(userData); if(!saveData){ return res.status(400).json({success:false,message:"Unable to save data, Please try again"}) } const token = await createToken(user_id,user_email); const options = { httpOnly: true, expires: new Date(Date.now() + process.env.JWT_COOKIE_EXPIRY * 24 * 60 * 60 * 1000), }; res.status(201).cookie("token",token,options).json({ success:true, message:"User registered successfully", data:{ user_id, user_name, user_email, user_image, total_orders, token } }); } catch (error) { res.status(500).send({success:false,message:error.message}) } }; export const loginUser = async (req,res) => { try { const {user_email,user_password} = req.body; if(user_email ===""){ return res.status(400).json({ success:false, message:"email cannot be blank" }) } if(user_password ===""){ return res.status(400).json({ success:false, message:"password cannot be blank" }) } const userExists = await User.findOne({user_email,user_password}); if(!userExists){ return res.status(404).json({ success:false, message:"No user found" }) }; const token =await createToken(userExists.user_id,userExists.user_email); userExists.last_logged_in = new Date(Date.now()); await userExists.save(); const options = { httpOnly: true, expires: new Date(Date.now() + process.env.JWT_COOKIE_EXPIRY * 24 * 60 * 60 * 1000), }; return res.status(200).cookie("token",token,options).json({ success:false, message:"user login successfully", token }); } catch (error) { res.status(500).json({ success:false, message:error.message }) } }; export const userDetails = async(req,res)=>{ try { const {user_id}= req.params; if( user_id === ":user_id"){ return res.status(400).json({ success:false, message:"user id cannot be blank" }) }; const userData = await User.findOne({user_id}).select("-user_password -user_id -_id -created_at -last_logged_in -__v"); if(!userData){ return res.status(404).json({ success:false, message:"No user found" }) }; return res.status(200).json({ success:true, message:"fetch user details successfully", userData:userData }); } catch (error) { return res.status(500).json({ success:false, message:error.message }) } }; export const updateUser = async(req,res) => { try { const userId = req.userId; const {user_name,user_password,user_image} = req.body; const userExists = await User.findOne({user_id:userId}); if (userId !== userExists.user_id) { return res.status(403).json({ success: false, message: "Unauthorized access", }); }; if(user_name==="" && user_image==="" && user_password===""){ return res.status(400).json({ success:false, message:"updation fields cannot be empty" }) } if(user_name !== ""){ userExists.user_name=user_name; }; if(user_image!==""){ userExists.user_image=user_image; }; if(user_password!==""){ userExists.user_password=user_password; }; const updatedData = await userExists.save(); console.log(updatedData) return res.status(200).json({ success:true, message:"User updated successfully", updatedData:{ user_name:updatedData.user_name, user_email:updatedData.user_email, user_password:updatedData.user_password, user_image:updatedData.user_image } }) } catch (error) { return res.status(500).json({ success:false, message:error.messge, }) } }; export const getImage = async(req,res) => { try { const {user_id} = req.params; if( user_id === ":user_id"){ return res.status(400).json({ success:false, message:"user id cannot be blank" }) }; const userData = await User.findOne({user_id:user_id}); if(!userData){ return res.status(404).json({ success:false, message:"No such user" }) } return res.status(200).json({ success:true, message:"User image fetched successfully", userImage:{ user_image:userData.user_image } }) } catch (error) { return res.status(500).json({ success:false, message:error.messge, }) } }; export const deleteUser = async(req,res) => { try { const {user_id}= req.params; if( user_id === ":user_id"){ return res.status(400).json({ success:false, message:"user id cannot be blank" }) }; const userData = await User.findOne({user_id}); if(!userData){ return res.status(404).json({ success:false, message:"No user found" }) }; const deleteData = await User.deleteOne({user_id}); return res.status(200).json({ success:true, message:"User deleted successfully", }) } catch (error) { return res.status(500).json({ success:false, message:error.messge, }) } };
package com.example.repository; import com.example.dto.Location; import lombok.AllArgsConstructor; import org.mariadb.jdbc.MariaDbPoolDataSource; import org.springframework.stereotype.Repository; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @Repository @AllArgsConstructor public class LocationRepository { private List<Location> locations; private MariaDbPoolDataSource source; protected List<Location> locationMapper(PreparedStatement statement) throws SQLException { ResultSet resultSet = statement.executeQuery(); locations.clear(); while (resultSet.next()) { locations.add(Location.builder() .id(resultSet.getInt("location_id")) .street(resultSet.getString("street_address")) .postalCode(resultSet.getString("postal_code")) .city(resultSet.getString("city")) .stateProvince(resultSet.getString("state_province")) .build()); } return new CopyOnWriteArrayList<>(locations); } public List<Location> getAllLocations() { try (Connection connection = source.getConnection()) { PreparedStatement statement = connection.prepareStatement("SELECT * FROM locations"); locationMapper(statement); } catch (SQLException e) { throw new RuntimeException(e); } return locations; } public List<Location> getLocationsByCity(String city) { try (Connection connection = source.getConnection()) { PreparedStatement statement = connection.prepareStatement("SELECT * FROM locations WHERE city = ?"); statement.setString(1, city); locationMapper(statement); } catch (SQLException e) { throw new RuntimeException(e); } return locations; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <!--头--> <div style="display: flex; justify-content: center"> <div style="width: 904px; height: 50px; border: 1px solid gray; border-radius: 5px 5px 0 0"> <div id="userInfo" style="height: 30px"></div> <div id="toUserInfo" style="height: 20px;display: flex;justify-content: center"></div> </div> </div> <!--框--> <div style="display: flex; justify-content: center"> <div style="width: 904px; height: 604px; border: 1px solid gray; border-radius: 0 0 5px 5px"> <!--聊天区--> <div id="chat_k" style="visibility: hidden; width: 600px; height: 602px; border: 1px solid gray; border-radius: 0 0 0 5px; float: left"> <div id="chatting" style="width: 600px; height: 400px; border: 1px solid gray;"> </div> <div style="width: 600px; height: 200px; border: 1px solid gray;"> <textarea id="chat_msg" placeholder="请输入你要发送的消息..." style="width: 594px;height: 163px"></textarea> <button id="submit_msg" style="float: right">发送</button> </div> </div> <!--好友列表--> <div style="width: 300px; height: 300px; border: 1px solid gray; float: right"> <span>好友列表</span> <ul id="hyList" style="overflow: auto"> </ul> </div> <!--系统消息--> <div style="width: 300px; height: 300px; border: 1px solid gray; border-radius: 0 0 5px 0; float: right"> <span>系统消息</span> <ul id="xtList" style="overflow: auto"> </ul> </div> </div> </div> </body> <script src="/js/jquery-3.6.1.min.js"></script> <script type="text/javascript"> var toName = ''; var username = ''; // 展示聊天区 function showChat(chatName){ toName = chatName; $("#toUserInfo").html("<span>正在和 "+chatName+" 聊天</span>"); $("#chat_k").css("visibility","visible"); //从sessionStorage中获取历史信息 let chatData = sessionStorage.getItem(toName); if (chatData != null){ $("#chatting").html(chatData); }else { $("#chatting").html(""); } } // page init load $(function (){ // get username $.ajax({ url:"getUsername", success:function (res) { username = res; }, async:false //同步请求,只有上面好了才会接着下面 }); //建立websocket连接 //获取host解决后端获取httpsession的空指针异常 var host = window.location.host; var ws = new WebSocket("ws://"+host+"/chat"); ws.onopen = function (evt) { $("#userInfo").html("用户:"+username+"<span style='float: right;color: green'>-在线</span>"); } //接受消息 ws.onmessage = function (evt) { //获取服务端推送的消息 let dataStr = evt.data; //将dataStr转换为json对象 let res = JSON.parse(dataStr); console.log(res); //判断是否是系统消息 if(res.system){ // 系统消息 //1.好友列表展示 let hyMsg = ''; //2.系统广播的展示 let xtMsg = ''; for(let name of res.message){ if (name != username){ hyMsg += "<li><a onclick='showChat(\"" + name + "\")'>" + name + "</a></li>"; xtMsg += "<li>你的好友 "+name+" 上线了</li>"; } } // 渲染 $("#hyList").html(hyMsg); $("#xtList").html(xtMsg); }else { //不是系统消息 let str = "<span style='border:1px solid grey; border-radius: 3px; float: left'>&emsp;"+ res.message +"&emsp;</span></br>"; if (toName === res.fromName) { $("#chatting").append(str); } var chatData = sessionStorage.getItem(res.fromName); if (chatData != null){ str = chatData + str; } //保存聊天消息 sessionStorage.setItem(res.fromName,str); }; } ws.onclose = function () { $("#userInfo").html("<span style='float: right;color: red'>-离线</span>"); } //发送消息 $("#submit_msg").click(function () { //1.获取输入的内容 let data = $("#chat_msg").val(); //2.清空发送框 $("#chat_msg").val(""); let json = {"toName": toName ,"message": data}; //将数据展示在聊天区 let str = "<span style='border:1px solid grey; border-radius: 3px; float: right'>&emsp;"+ data +"&emsp;</span></br>"; $("#chatting").append(str); let chatData = sessionStorage.getItem(toName); if (chatData != null){ str = chatData + str; } sessionStorage.setItem(toName,str); //3.发送数据 ws.send(JSON.stringify(json)); }) }) </script> </html>
import { Box, Button, Chip, Divider, Grid, TableCell, TableRow, Typography } from '@mui/material'; import React, { useCallback, useEffect, useState } from 'react'; import AddOutlinedIcon from '@mui/icons-material/AddOutlined'; import BasicTable from '../../components/table/Table'; import { ordersHeadCells } from '../../utils'; import InputLabel from '@mui/material/InputLabel'; import MenuItem from '@mui/material/MenuItem'; import FormControl from '@mui/material/FormControl'; import Select from '@mui/material/Select'; import TextField from '@mui/material/TextField'; import SearchIcon from '@mui/icons-material/Search'; import DateRangeIcon from '@mui/icons-material/DateRange'; import Checkbox from '../../components/checkbox/Checkbox'; import { useApi } from '../../hooks/useAPI'; import { getOrders } from '../../services/api'; import './orders.css'; import Loader from '../../components/loader/Loader'; const Orders = () => { const [age, setAge] = useState(''); const [ordersData, setOrdersData] = useState([]); const [ordersLoading, ordersError, callOrdersApi] = useApi(); const getOrdersData = useCallback(() => { callOrdersApi(() => getOrders()).then((res) => { setOrdersData(res.data); }); }, [callOrdersApi]); useEffect(() => { getOrdersData(); }, [getOrdersData]); const handleChange = (event) => { setAge(event.target.value); }; return ( <Box className="orders-page"> <Grid container marginBottom={2}> <Grid xs={7} item> <Typography className="orders-heading"> Orders</Typography> </Grid> <Grid className="mr-15" xs={1.5} item> <Button fullWidth sx={{ padding: '10px 14px 10px 6px', marginRight: '23px', textTransform: 'none' }} variant="outlined" > Export to excel </Button> </Grid> <Grid className="mr-15" xs={1.5} item> <Button fullWidth sx={{ padding: '10px 14px 10px 6px', marginRight: '23px', textTransform: 'none' }} variant="outlined" > Import Orders </Button> </Grid> <Grid className="mr-15" xs={1.5} item> <Button fullWidth sx={{ padding: '10px 14px 10px 6px', marginRight: '23px', textTransform: 'none' }} variant="contained" > <AddOutlinedIcon /> New Orders </Button> </Grid> </Grid> <Divider /> <Grid container marginBottom={2} padding={2}> <Grid xs={4} item> <TextField fullWidth variant="outlined" placeholder="Search order Id" InputProps={{ startAdornment: <SearchIcon fontSize="25px" sx={{ mr: 1 }} /> }} /> </Grid> <Grid xs={3.5} item></Grid> <Grid xs={3} item display="flex" alignItems="center"> <DateRangeIcon className="calendar-icon" /> <Box className="mr-15" sx={{ minWidth: 120 }}> <FormControl sx={{ width: '100%' }}> <InputLabel id="demo-simple-select-label">Sales</InputLabel> <Select labelId="demo-simple-select-label" id="demo-simple-select" value={age} label="Sales" onChange={handleChange} > <MenuItem value={10}>Ten</MenuItem> <MenuItem value={20}>Twenty</MenuItem> <MenuItem value={30}>Thirty</MenuItem> </Select> </FormControl> </Box> <Box className="mr-15" sx={{ minWidth: 120 }}> <FormControl sx={{ width: '100%' }}> <InputLabel id="demo-simple-select-label">Status</InputLabel> <Select labelId="demo-simple-select-label" id="demo-simple-select" value={age} label="Status" onChange={handleChange} > <MenuItem value={10}>Ten</MenuItem> <MenuItem value={20}>Twenty</MenuItem> <MenuItem value={30}>Thirty</MenuItem> </Select> </FormControl> </Box> <Box className="mr-15" sx={{ minWidth: 120 }}> <FormControl sx={{ width: '100%' }}> <InputLabel id="demo-simple-select-label">Filter</InputLabel> <Select labelId="demo-simple-select-label" id="demo-simple-select" value={age} label="Filter" onChange={handleChange} > <MenuItem value={10}>Ten</MenuItem> <MenuItem value={20}>Twenty</MenuItem> <MenuItem value={30}>Thirty</MenuItem> </Select> </FormControl> </Box> </Grid> </Grid> <Divider sx={{ mb: 2 }} /> <Grid container marginBottom={2}> <Grid xs={12} item> {ordersLoading ? ( <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '200px' }} > <Loader /> </Box> ) : ordersError ? ( <div className="error">{ordersError}</div> ) : ( <BasicTable showCheckBox headcells={ordersHeadCells}> {ordersData.map((o) => { return ( <TableRow key={o.orderID}> <TableCell component="th" scope="row"> <Checkbox /> </TableCell> <TableCell component="th" scope="row"> {o.orderID} </TableCell> <TableCell>{o.date}</TableCell> <TableCell>{o.customer}</TableCell> <TableCell>{o.salesChannel}</TableCell> <TableCell>{o.destination}</TableCell> <TableCell>{o.items}</TableCell> <TableCell> <Chip sx={{ width: '90px' }} color={ o.status === 'Completed' ? 'success' : 'secondary' } label={o.status} /> </TableCell> </TableRow> ); })} {/* <TableRow> <TableCell component="th" scope="row"> <Checkbox /> </TableCell> <TableCell component="th" scope="row"> Order ID </TableCell> <TableCell>Product</TableCell> <TableCell>Catagory</TableCell> <TableCell>Sales channel</TableCell> <TableCell>Instruction</TableCell> <TableCell>Items</TableCell> <TableCell> <Chip sx={{ width: '90px' }} color="success" label="Completed" /> </TableCell> </TableRow> */} </BasicTable> )} </Grid> </Grid> </Box> ); }; export default Orders;
import { useState, useEffect } from "react"; import { Plus, Trash } from "react-feather"; import Flatpickr from "react-flatpickr"; import Select from "react-select"; import classnames from "classnames"; import axios from "axios"; import "react-slidedown/lib/slidedown.css"; import "flatpickr/dist/themes/airbnb.css"; import { useForm, useFieldArray, Controller } from "react-hook-form"; import * as yup from "yup"; import { yupResolver } from "@hookform/resolvers/yup"; import { Row, Col, Card, CardBody, Form, FormFeedback, FormGroup, Label, Input, Button, Badge, CustomInput, } from "reactstrap"; import MultipleInputSelect from "../../core/multiple-input-select/MultipleInputSelect"; import moment from "moment-timezone"; import { backPage, getClassroomFromBlade, getClassroomId, getQuestionCategoryOptions, getSubQuestionCategoryOptions, getScheduleSessionOptions, } from "./utility/form-utils"; const classroom = getClassroomFromBlade(); const isBTWEdutechClass = classroom?.tags?.includes("btwedutech"); const isCPNSClass = classroom?.tags?.includes("cpns"); const isP3KClass = classroom?.tags?.includes("pppk") || classroom?.tags?.includes("PPPK"); const scheduleZoomMeetingOptions = [ { label: "Buat zoom meeting baru untuk jadwal ini", value: true, }, { label: "Gunakan zoom meeting dari jadwal yang sudah ada", value: false, }, ]; const getEmptyForm = () => { return { title: "", start_date: "", end_date: "", teacher_id: "", input_topics: "", topics: [], classroom_id: getClassroomId(), material_id: "", is_pre_test: false, is_post_test: false, program: "", is_skd: true, create_new_zoom_meeting: undefined, is_require_passcode: false, zoom_host_id: "", zoom_passcode: "", parent_schedules: [], selected_parent_schedule: undefined, parent_schedule_id: "", parent_classroom_id: "", question_category: "", sub_question_category: "", session: "", }; }; const getZoomUserType = (zoom_user_type) => { switch (zoom_user_type) { case 1: return "Basic"; case 2: return "Licensed"; case 3: return "On-prem"; case 99: return "None"; default: return "Unknown"; } }; const getZoomUserMaxMeetingDuration = (zoom_user_type) => { switch (zoom_user_type) { case 2: case 3: case 99: return "30 hours"; default: return "40 minutes"; } }; const getCsrf = () => { return document.querySelector('meta[name="csrf-token"]').content; }; const FormAddSchedule = () => { const [teachers, setTeachers] = useState([]); const [materials, setMaterials] = useState([]); const [programs, setPrograms] = useState([]); const [zoomUsers, setZoomUsers] = useState([]); const [isLoadingZoomUsers, setIsLoadingZoomUsers] = useState(false); const [topics, setTopics] = useState([]); const [selectedZoomUser, setSelectedZoomUser] = useState(null); const [isSubmitting, setIsSubmitting] = useState(false); const [isSubmitButtonDisabled, setIsSubmitButtonDisabled] = useState( classroom?.is_online ); const [classrooms, setClassrooms] = useState([]); const [questionCategories, setQuestionCategories] = useState([]); const [subQuestionCategories, setSubQuestionCategories] = useState([]); const formSchema = yup.object().shape({ title: yup.string().required("Judul harus diisi"), start_date: yup.string().required("Waktu mulai harus diisi"), end_date: yup.string().required("Waktu selesai harus diisi"), teacher_id: yup.string().required("Pengajar harus dipilih"), is_skd: yup.bool().optional(), is_require_passcode: yup.bool().optional(), zoom_host_id: yup.string().when(["create_new_zoom_meeting"], { is: (createNewZoomMeeting) => createNewZoomMeeting, then: (schema) => schema.required("Zoom host harus dipilih"), otherwise: (schema) => schema.notRequired().nullable(), }), zoom_passcode: yup.string().when(["is_require_passcode"], { is: (isRequirePasscode) => isRequirePasscode, then: (schema) => schema.required("Passcode harus diisi"), }), program: yup.string().when(["is_skd"], { is: (isSkd) => !!isSkd, then: yup.string().required("Program harus dipilih"), }), material_id: yup.string().when(["is_skd"], { is: (isSkd) => !!isSkd, then: yup.string().required("Materi harus dipilih"), }), }); const fieldsSchema = yup.object().shape({ schedules: yup .array() .of(formSchema) .required("Harus ada jadwal") .min(1, "Minimal 1"), }); const { control, handleSubmit, setError, watch, setValue, reset } = useForm({ defaultValues: { schedules: [getEmptyForm()] }, resolver: yupResolver(fieldsSchema), }); const { fields, append, remove } = useFieldArray({ control, name: "schedules", }); const watchedForm = watch(); const getTeachers = async () => { try { const response = await axios.get("/api/learning/teacher"); const data = await response.data; return data?.data ?? []; } catch { return []; } }; const getPrograms = async () => { try { // const response = await axios.get("/api/internal/programs"); // const data = await response.data; // return data ?? []; return isCPNSClass ? [ { id: "cpns", text: "SKD-CPNS" }, { id: "cpns-skb", text: "SKB-CPNS" }, ] : [ { id: "skd", text: "SKD" }, { id: "tps", text: "TPS" }, { id: "pppk", text: "PPPK" }, { id: "utbk", text: "UTBK" }, ]; } catch (error) { return []; } }; const getMaterials = async () => { try { let url = `/api/exam/study-material`; if (isP3KClass) url = `/api/study-material/material`; if (isCPNSClass) url = `/api/exam-cpns/study-material`; const response = await axios.get(url); const data = await response.data; return ( data.filter( (value) => !value.hasOwnProperty("deleted_at") || !value.deleted_at ) ?? [] ); } catch (error) { return []; } }; const getZoomUsers = async () => { try { setIsLoadingZoomUsers(true); const response = await axios.get("/api/zoom/users"); const data = await response.data; const filteredData = data?.users?.length ? data?.users.filter((value) => value.type !== 1 && value.type !== 99) : []; return filteredData; } catch (error) { return []; } finally { setIsLoadingZoomUsers(false); } }; const getSelectedZoomUserData = async (zoom_user_id) => { try { const response = await axios.get(`/api/zoom/users/${zoom_user_id}`); const data = await response.data; return data ?? null; } catch (error) { console.error(error); return null; } }; const getSelectedZoomUserSettings = async (zoom_user_id) => { try { const response = await axios.get( `/api/zoom/users/${zoom_user_id}/settings` ); const data = await response.data; return data ?? null; } catch (error) { console.error(error); return null; } }; const getClassrooms = async () => { try { const response = await axios.get("/api/learning/classroom", { params: { is_online: "1", status: "ONGOING", }, }); const data = await response.data; return data?.data?.length ? data?.data?.filter((value) => value._id !== getClassroomId()) : []; } catch (error) { console.error(error); return []; } }; const getParentClassSchedules = async (classroom_id) => { try { const response = await axios.get( `/api/learning/classroom/${classroom_id}/available-online-schedules`, { params: { child_classroom_id: getClassroomId(), }, } ); const data = await response.data; return data?.data ?? []; } catch (error) { console.error(error); return []; } }; useEffect(() => { (async () => { setTeachers(await getTeachers()); setMaterials(await getMaterials()); setPrograms(await getPrograms()); if (!classroom || !classroom?.is_online) return; setClassrooms(await getClassrooms()); setZoomUsers(await getZoomUsers()); })(); }, []); const getMaterialByProgram = (program = null) => { if (!program) return materials; if (program === "cpns") program = "skd"; if (program === "cpns-skb") program = "skb"; const filtered = materials.filter((m) => m.program == program); return [...filtered]; }; const handleIsSkdChanged = (index, value) => { setValue(`schedules.${index}.is_skd`, value); setValue(`schedules.${index}.material_id`, ""); setValue(`schedules.${index}.program`, ""); setValue(`schedules.${index}.is_pre_test`, false); setValue(`schedules.${index}.is_post_test`, false); }; const handleIsRequirePasscodeChanged = (index, value) => { setValue(`schedules.${index}.is_require_passcode`, value); }; const handleZoomHostIdChanged = async (index, value) => { try { setIsSubmitButtonDisabled(true); setSelectedZoomUser(null); if (!value) return; setValue(`schedules.${index}.zoom_host_id`, value); const account = await getSelectedZoomUserData(value); const settings = await getSelectedZoomUserSettings(value); setSelectedZoomUser({ account, settings, }); setIsSubmitButtonDisabled(account?.type !== 2); } catch (error) { console.error(error); setIsSubmitButtonDisabled(true); } }; const handleZoomMeetingSettingsChanged = async (index, value) => { if (!value) { setSelectedZoomUser(null); setValue(`schedules.${index}.is_require_passcode`, false); setValue(`schedules.${index}.zoom_passcode`, ""); setValue(`schedules.${index}.parent_classroom_id`, ""); setValue(`schedules.${index}.parent_schedule_id`, ""); setValue(`schedules.${index}.parent_schedules`, []); setValue(`schedules.${index}.selected_parent_schedule`, undefined); } setValue(`schedules.${index}.create_new_zoom_meeting`, value); }; const handleGetParentClassSchedules = async (index, value) => { if (!value) return; setIsSubmitButtonDisabled(true); setValue(`schedules.${index}.parent_classroom_id`, ""); setValue(`schedules.${index}.parent_schedule_id`, ""); setValue(`schedules.${index}.parent_schedules`, []); setValue(`schedules.${index}.selected_parent_schedule`, undefined); const schedules = await getParentClassSchedules(value); setValue(`schedules.${index}.parent_classroom_id`, value); setValue(`schedules.${index}.parent_schedules`, schedules); }; const handleSelectParentClassSchedule = async (index, value) => { if (!value) return; setValue(`schedules.${index}.parent_schedule_id`, value); setValue( `schedules.${index}.selected_parent_schedule`, watchedForm?.schedules[index]?.parent_schedules?.filter( (val) => val._id == value )[0] ?? undefined ); setIsSubmitButtonDisabled(false); }; const handleProgramChanged = (index, value) => { setQuestionCategories([]); setValue(`schedules.${index}.question_category`, ""); setValue(`schedules.${index}.sub_question_category`, ""); setValue(`schedules.${index}.program`, value?.id); setQuestionCategories(getQuestionCategoryOptions(value?.id)); }; const handleQuestionCategoryChanged = (index, value) => { setSubQuestionCategories([]); setValue( `schedules.${index}.question_category`, value?.value?.toLowerCase() ?? "" ); setValue(`schedules.${index}.sub_question_category`, ""); setSubQuestionCategories( getSubQuestionCategoryOptions(value?.value?.toLowerCase()) ); }; const onSubmit = async ({ schedules }) => { try { schedules = schedules.map((data) => { let scheduleTags = []; let topicTags = [...data.topics].filter((item) => { return !/^(KATEGORI:|SUB_KATEGORI:|PERTEMUAN_SUB_KATEGORI:)/i.test( item ); }); if (data?.question_category?.value) { scheduleTags.push(`KATEGORI:${data?.question_category?.value}`); } if (data?.sub_question_category?.value) { scheduleTags.push( `SUB_KATEGORI:${data?.sub_question_category?.value}` ); } if (data?.session?.value) { scheduleTags.push(`PERTEMUAN_SUB_KATEGORI:${data?.session?.value}`); } if (isCPNSClass) { topicTags.push("cpns"); } const payload = { ...data, start_date: moment(data.start_date).tz("Asia/Jakarta", true), end_date: moment(data.end_date).tz("Asia/Jakarta", true), topics: [...scheduleTags, ...topicTags], }; if (classroom?.is_online && data.create_new_zoom_meeting) { const selectedZoomHost = zoomUsers?.find( (value) => value.id === data.zoom_host_id ); payload.zoom_host_name = `${selectedZoomHost.first_name} ${selectedZoomHost.last_name}`; payload.zoom_host_email = selectedZoomHost.email; } return payload; }); setIsSubmitting(true); const response = await axios.post( "/api/learning/schedule/many", { schedules }, { headers: { "X-CSRF-TOKEN": getCsrf() } } ); await response.data; backPage(); } catch (error) { const isValidationError = error?.response?.status === 422; if (isValidationError) { const errors = error?.response?.data?.errors; Object.entries(errors).forEach(([key, value]) => setError(key, { type: "manual", message: value[0] ?? "", }) ); return; } console.error(error); } finally { setIsSubmitting(false); } }; return ( <Card> <CardBody> <Form onSubmit={handleSubmit(onSubmit)}> {fields.map((field, index) => ( <Row key={field.id} className="justify-content-between align-items-end" > {!classroom?.is_online && ( <Col md={1} className="align-self-start"> <Badge color="primary" className="mb-2 mt-1 d-flex justify-content-center align-items-center" style={{ fontSize: "1.5rem", width: "40px", height: "40px", }} > {index + 1} </Badge> </Col> )} <Col md={9}> <Controller control={control} name={`schedules.${index}.title`} render={({ field, fieldState: { error } }) => ( <FormGroup> <Label>Judul</Label> <Input {...field} invalid={Boolean(error)} placeholder="Pelajaran SKD" /> <FormFeedback>{error?.message}</FormFeedback> </FormGroup> )} /> <Controller control={control} name={`schedules.${index}.start_date`} render={({ field: { onChange, ref, value }, fieldState: { error }, }) => ( <FormGroup> <Label>Waktu Mulai (WIB)</Label> <Flatpickr className={classnames("form-control", { "is-invalid": error, })} data-enable-time ref={ref} value={value} readOnly={false} onChange={(date) => onChange(date[0].toISOString())} /> <FormFeedback>{error?.message}</FormFeedback> </FormGroup> )} /> <Controller control={control} name={`schedules.${index}.end_date`} render={({ field: { onChange, ref, value }, fieldState: { error }, }) => ( <FormGroup> <Label>Waktu Selesai (WIB)</Label> <Flatpickr className={classnames("form-control", { "is-invalid": error, })} data-enable-time ref={ref} value={value} readOnly={false} onChange={(date) => onChange(date[0].toISOString())} /> <FormFeedback>{error?.message}</FormFeedback> </FormGroup> )} /> <Controller control={control} name={`schedules.${index}.teacher_id`} render={({ field: { onChange }, fieldState: { error } }) => ( <FormGroup> <Label>Pilih Pengajar</Label> <Select className={classnames("react-select", { "is-invalid": error, })} classNamePrefix="select" options={teachers} isClearable={false} getOptionValue={(option) => option.sso_id} getOptionLabel={(option) => option.name} onChange={(val) => onChange(val.sso_id)} menuPortalTarget={document.body} styles={{ menuPortal: (base) => ({ ...base, zIndex: 9999 }), }} /> <FormFeedback>{error?.message}</FormFeedback> </FormGroup> )} /> <Controller control={control} name={`schedules.${index}.is_skd`} render={({ field: { onChange, value } }) => ( <FormGroup> <CustomInput checked={value} onChange={(e) => handleIsSkdChanged(index, e.target.checked) } inline type="checkbox" label="Pilih Materi Pembelajaran" id={`is_skd_${index}`} /> </FormGroup> )} /> {watchedForm?.schedules[index]?.is_skd && ( <> <Controller control={control} name={`schedules.${index}.program`} render={({ field: { onChange }, fieldState: { error }, }) => ( <FormGroup> <Label>Pilih Program Materi Belajar</Label> <Select className={classnames("react-select", { "is-invalid": error, })} classNamePrefix="select" options={programs} isClearable={false} getOptionValue={(option) => option.id} getOptionLabel={(option) => option.text} onChange={(option) => { onChange(option.id); if (option.id !== "skd") { setValue( `schedules.${index}.question_category`, null ); setValue( `schedules.${index}.sub_question_category`, null ); } }} menuPortalTarget={document.body} styles={{ menuPortal: (base) => ({ ...base, zIndex: 9999 }), }} /> <FormFeedback>{error?.message}</FormFeedback> </FormGroup> )} /> {["skd", "cpns"].some( (program) => watchedForm?.schedules[index]?.program === program ) && ( <> <Controller control={control} name={`schedules.${index}.question_category`} render={({ field, fieldState: { error } }) => ( <FormGroup> <Label> Pilih Kategori Materi Belajar (Opsional) </Label> <Select {...field} className={classnames("react-select", { "is-invalid": error, })} classNamePrefix="select" options={getQuestionCategoryOptions("skd")} isClearable={true} onChange={(option) => { field.onChange(option); setValue( `schedules.${index}.sub_question_category`, null ); }} menuPortalTarget={document.body} styles={{ menuPortal: (base) => ({ ...base, zIndex: 9999, }), }} /> <FormFeedback>{error?.message}</FormFeedback> </FormGroup> )} /> <Controller control={control} name={`schedules.${index}.sub_question_category`} render={({ field, fieldState: { error } }) => ( <FormGroup> <Label> Pilih Sub Kategori Materi Belajar (Opsional) </Label> <Select {...field} className={classnames("react-select", { "is-invalid": error, })} isClearable={true} classNamePrefix="select" options={getSubQuestionCategoryOptions( watchedForm?.schedules[ index ]?.question_category?.value?.toLowerCase() ?? "" )} menuPortalTarget={document.body} styles={{ menuPortal: (base) => ({ ...base, zIndex: 9999, }), }} /> <FormFeedback>{error?.message}</FormFeedback> </FormGroup> )} /> </> )} <Controller control={control} name={`schedules.${index}.material_id`} render={({ field: { onChange, value }, fieldState: { error }, }) => ( <FormGroup> <Label>Pilih Materi Belajar</Label> <Select className={classnames("react-select", { "is-invalid": error, })} classNamePrefix="select" options={getMaterialByProgram( watchedForm?.schedules[index]?.program )} isClearable={false} getOptionValue={(option) => option?._id ?? option?.id } getOptionLabel={(option) => option.title} onChange={(val) => onChange(val._id ?? val.id)} menuPortalTarget={document.body} styles={{ menuPortal: (base) => ({ ...base, zIndex: 9999 }), }} /> <FormFeedback>{error?.message}</FormFeedback> </FormGroup> )} /> <Controller control={control} name={`schedules.${index}.is_pre_test`} render={({ field: { onChange, value } }) => ( <FormGroup className="mt-1"> <CustomInput value={value} onChange={(e) => onChange(e.target.checked)} inline type="checkbox" label="Pre Test" id={`is_pre_test_${index}`} /> </FormGroup> )} /> <Controller control={control} name={`schedules.${index}.is_post_test`} render={({ field: { onChange, value } }) => ( <FormGroup className="mt-1"> <CustomInput value={value} onChange={(e) => onChange(e.target.checked)} inline type="checkbox" label="Post Test" id={`is_post_test_${index}`} /> </FormGroup> )} /> </> )} <Controller control={control} name={`schedules.${index}.session`} render={({ field, fieldState: { error } }) => ( <FormGroup> <Label>Pilih Pertemuan (Opsional)</Label> <Select {...field} className={classnames("react-select", { "is-invalid": error, })} classNamePrefix="select" options={getScheduleSessionOptions()} isClearable={true} menuPortalTarget={document.body} styles={{ menuPortal: (base) => ({ ...base, zIndex: 9999 }), }} /> <FormFeedback>{error?.message}</FormFeedback> </FormGroup> )} /> <Controller isClearable control={control} name={`schedules.${index}.input_topics`} render={({ field, fieldState: { error } }) => ( <FormGroup className="mt-1"> <Label> Topik <small>(Opsional)</small> </Label> <MultipleInputSelect setValue={setValue} fieldName={field.name} valueName={`schedules.${index}.topics`} currentValue={field.value} changeHandler={field.onChange} /> <FormFeedback>{error?.message}</FormFeedback> </FormGroup> )} /> {classroom && classroom?.is_online && ( <> <hr className="my-2" /> <Controller control={control} name={`schedules.${index}.create_new_zoom_meeting`} render={({ field: { onChange }, fieldState: { error }, }) => ( <FormGroup> <Label>Pengaturan Zoom Meeting</Label> <Select className={classnames("react-select", { "is-invalid": error, })} classNamePrefix="select" options={scheduleZoomMeetingOptions} menuPortalTarget={document.body} styles={{ menuPortal: (base) => ({ ...base, zIndex: 9999 }), }} onChange={(val) => handleZoomMeetingSettingsChanged(index, val.value) } /> <FormFeedback>{error?.message}</FormFeedback> </FormGroup> )} /> {watchedForm?.schedules[index]?.create_new_zoom_meeting === true && ( <> <Controller control={control} name={`schedules.${index}.zoom_host_id`} render={({ field: { onChange }, fieldState: { error }, }) => ( <FormGroup> <Label>Akun Host Zoom</Label> <Select className={classnames("react-select", { "is-invalid": error, })} classNamePrefix="select" options={zoomUsers} isLoading={isLoadingZoomUsers} disabled={isLoadingZoomUsers} isClearable={false} getOptionLabel={(option) => `${option.first_name} ${ option?.last_name ?? "" } (${option.email})` } getOptionValue={(option) => option.id} onChange={(val) => handleZoomHostIdChanged(index, val.id) } menuPortalTarget={document.body} styles={{ menuPortal: (base) => ({ ...base, zIndex: 9999, }), }} /> <FormFeedback>{error?.message}</FormFeedback> {!isSubmitButtonDisabled && selectedZoomUser ? ( <p className="text-info"> User type:{" "} {getZoomUserType( selectedZoomUser.account.type )} , meeting participant quota: { selectedZoomUser.settings.feature .meeting_capacity } , max meeting duration: {getZoomUserMaxMeetingDuration( selectedZoomUser.account.type )} </p> ) : null} <hr className="my-1" /> </FormGroup> )} /> <div className="d-flex mt-1"> <Controller control={control} name={`schedules.${index}.is_require_passcode`} render={({ field: { onChange, value } }) => ( <FormGroup className="mt-50"> <CustomInput checked={value} inline type="checkbox" label="Passcode" id={`is_require_passcode_${index}`} onChange={(e) => handleIsRequirePasscodeChanged( index, e.target.checked ) } /> </FormGroup> )} /> {watchedForm?.schedules[index] ?.is_require_passcode && ( <Controller control={control} name={`schedules.${index}.zoom_passcode`} defaultValue="" render={({ field, fieldState: { error } }) => ( <FormGroup className="mb-0"> <Input {...field} invalid={Boolean(error)} placeholder="" maxLength={10} /> <FormFeedback>{error?.message}</FormFeedback> </FormGroup> )} /> )} </div> </> )} {watchedForm?.schedules[index]?.create_new_zoom_meeting === false && ( <> <Controller control={control} name={`schedules.${index}.parent_classroom_id`} render={({ field: { onChange }, fieldState: { error }, }) => ( <FormGroup> <Label>Pilih Kelas</Label> <Select className={classnames("react-select", { "is-invalid": error, })} classNamePrefix="select" options={classrooms} isClearable={false} getOptionLabel={(option) => `${option.title} (${option.branch_code})` } getOptionValue={(option) => option._id} onChange={(val) => { handleGetParentClassSchedules(index, val._id); }} menuPortalTarget={document.body} styles={{ menuPortal: (base) => ({ ...base, zIndex: 9999, }), }} /> <FormFeedback>{error?.message}</FormFeedback> </FormGroup> )} /> {watchedForm?.schedules[index]?.parent_schedules ?.length > 0 && ( <Controller control={control} name={`schedules.${index}.parent_schedule_id`} render={({ field: { onChange }, fieldState: { error }, }) => ( <FormGroup> <Label>Pilih Jadwal</Label> <Select className={classnames("react-select", { "is-invalid": error, })} classNamePrefix="select" options={ watchedForm?.schedules[index] ?.parent_schedules ?? [] } getOptionLabel={(option) => `${option.title}`} getOptionValue={(option) => option._id} isClearable={false} onChange={(val) => { handleSelectParentClassSchedule( index, val._id ); }} menuPortalTarget={document.body} styles={{ menuPortal: (base) => ({ ...base, zIndex: 9999, }), }} /> <FormFeedback>{error?.message}</FormFeedback> </FormGroup> )} /> )} {watchedForm?.schedules[index] ?.selected_parent_schedule && ( <> <FormGroup> <Label>Zoom Meeting ID</Label> <Input disabled={true} value={ watchedForm?.schedules[index] ?.selected_parent_schedule ?.online_class_meeting?.zoom_meeting_id ?? "-" } /> </FormGroup> <FormGroup> <Label>Zoom Meeting Password</Label> <Input disabled={true} value={ watchedForm?.schedules[index] ?.selected_parent_schedule ?.online_class_meeting ?.zoom_meeting_password ?? "-" } /> </FormGroup> <FormGroup> <Label>Zoom Meeting Host Email</Label> <Input disabled={true} value={ watchedForm?.schedules[index] ?.selected_parent_schedule ?.online_class_meeting?.zoom_host_email ?? "-" } /> </FormGroup> </> )} </> )} </> )} </Col> <Col md={2}> <Col md={12}> {fields.length > 1 && ( <Button color="danger" className="text-nowrap px-1 mb-1" onClick={() => remove(index)} outline > <Trash size={14} /> </Button> )} </Col> </Col> <Col sm={12}> <hr /> </Col> </Row> ))} {/* Add New Button */} {!classroom?.is_online && ( <Button className="btn-icon" color="primary" onClick={() => append(getEmptyForm())} > <Plus size={14} /> <span className="align-middle ml-25">Tambah Baru</span> </Button> )} {/* Submit button */} {fields.length && ( <Button disabled={isSubmitting || isSubmitButtonDisabled} style={{ marginLeft: "1rem" }} className="btn-icon ml-24" color="success" type="submit" > <span className="align-middle ml-24"> {isSubmitting ? "Menyimpan..." : "Simpan"} </span> </Button> )} </Form> </CardBody> </Card> ); }; export default FormAddSchedule;
import * as THREE from 'three' import { PointerLockControls } from 'three-stdlib' import { checkCollision } from './boundaries' import { KeysPressed } from '../types/types' import { KEYSPRESSED, MEDIA, WALLS } from '../settings/settings' import nipplejs, { type JoystickManagerOptions } from 'nipplejs' import { startAudio, stopAudio } from '../audio/audioGuide' import { PointerLockState } from '../events/pointerEventsLock' const overlay = document.getElementById('overlay') const joystickZoneMovement = document.getElementById( 'zone_joystick-movement' ) as HTMLElement const MOVEMENT_SPEED = 8.0 const JUMP_FORCE = 6.0 const GRAVITY = -9.8 // Upwards direction is positive, so gravity is negative. let canJump = false let velocity = new THREE.Vector3() let lastTouchX = 0 let lastTouchY = 0 const touchSensitivity = 0.8 export const addKeyboardControls = (controls: PointerLockControls) => { document.addEventListener('keydown', (event) => { if (!PointerLockState.getIsLocked()) return if (event.key in KEYSPRESSED) { KEYSPRESSED[event.key as keyof KeysPressed] = true } if (event.key === ' ' && canJump === true) { velocity.y += JUMP_FORCE // Adjust the '20' to set the jump speed. canJump = false } if (event.key === 'g') { startAudio() } if (event.key === 'p') { stopAudio() } if (event.key === 'm') { // if the "m" key is pressed showMenuAndOtherOptions() controls.unlock() // unlock the pointer } }) document.addEventListener('keyup', (event) => { if (!PointerLockState.getIsLocked()) return if (event.key in KEYSPRESSED) { KEYSPRESSED[event.key as keyof KeysPressed] = false } }) controls.addEventListener('lock', function () { canJump = true }) controls.addEventListener('unlock', function () { canJump = false }) } export const addTouchControls = (controls: PointerLockControls) => { document.addEventListener( 'touchstart', function (event) { lastTouchX = event.touches[0].pageX lastTouchY = event.touches[0].pageY }, false ) document.addEventListener( 'touchmove', function (event) { event.preventDefault() const touchX = event.touches[0].pageX const touchY = event.touches[0].pageY const deltaX = (touchX - lastTouchX) * touchSensitivity const deltaY = (touchY - lastTouchY) * touchSensitivity // Get current Euler angle, adjust, and set it back const currentEuler = new THREE.Euler().setFromQuaternion( controls.getObject().quaternion, 'YXZ' ) currentEuler.y -= deltaX * 0.002 currentEuler.x -= deltaY * 0.002 controls.getObject().quaternion.setFromEuler(currentEuler) lastTouchX = touchX lastTouchY = touchY }, { passive: false } ) } let joystickInitialized = false const joystickOptions: JoystickManagerOptions = { zone: joystickZoneMovement, // active zone mode: 'semi', size: 100, // size of joystick position: { left: '50%', top: '50%' }, restOpacity: 0.8, } let joystick = nipplejs.create(joystickOptions) const setupJoystickEvents = ( controls: PointerLockControls, moveSpeed: number, camera: THREE.Camera, wallsFromScene: THREE.Group, mediaElements: THREE.Group[] ) => { if (joystickInitialized) return joystickInitialized = true try { joystick.on('hidden', function () { // your existing logic here... console.log(moveSpeed) }) joystick.on('move', function (_evt, data) { const speed = 0.2 const previousPosition = camera.position.clone() // Save previous position if (data.angle.degree > 45 && data.angle.degree < 135) { // move forward controls.moveForward(speed) } else if (data.angle.degree > 225 && data.angle.degree < 315) { // move backward controls.moveForward(-speed) } else if (data.angle.degree <= 45 || data.angle.degree >= 315) { // move right controls.moveRight(speed) } else if (data.angle.degree >= 135 && data.angle.degree <= 225) { // move left controls.moveRight(-speed) } if (checkCollision(camera, wallsFromScene)) { camera.position.copy(previousPosition) } mediaElements.forEach((mediaGroup) => { if (checkCollision(camera, mediaGroup)) { camera.position.copy(previousPosition) } }) }) joystick.on('end', function () { // your existing logic here... }) } catch (error) { console.error('An error occurred in the joystick logic: ', error) } } /** * Updates the camera position and checks for collisions. * @param scene - Three.js scene instance. * @param delta - Time delta for movements. * @param camera - Camera for the view. * @param controls - PointerLockControls for handling movements. */ export const updateMovement = ( scene: THREE.Scene, delta: number, camera: THREE.Camera, controls: PointerLockControls ) => { const moveSpeed = MOVEMENT_SPEED * delta const previousPosition = camera.position.clone() const wallsFromScene = scene.getObjectByName(WALLS) as THREE.Group const mediaElements = scene.getObjectsByProperty( 'name', MEDIA ) as THREE.Group[] velocity.y += GRAVITY * delta setupJoystickEvents( controls, moveSpeed, camera, wallsFromScene, mediaElements ) if (KEYSPRESSED.w || KEYSPRESSED.W || KEYSPRESSED.ArrowUp) { controls.moveForward(moveSpeed) } if (KEYSPRESSED.s || KEYSPRESSED.S || KEYSPRESSED.ArrowDown) { controls.moveForward(-moveSpeed) } if (KEYSPRESSED.a || KEYSPRESSED.A || KEYSPRESSED.ArrowLeft) { controls.moveRight(-moveSpeed) } if (KEYSPRESSED.d || KEYSPRESSED.D || KEYSPRESSED.ArrowRight) { controls.moveRight(moveSpeed) } controls.getObject().position.y += velocity.y * delta if (checkCollision(camera, wallsFromScene)) { camera.position.copy(previousPosition) } mediaElements.forEach((mediaGroup) => { if (checkCollision(camera, mediaGroup)) { camera.position.copy(previousPosition) } }) if (controls.getObject().position.y <= 0) { velocity.y = 0 controls.getObject().position.y = 0 canJump = true } } export const initGalleryExperience = ( clock: THREE.Clock, controls: PointerLockControls ) => { const playButton = document.getElementById('play_button') as HTMLButtonElement function startExperience() { hideMenuAndOtherOptions() clock.start() controls.lock() } playButton?.addEventListener('click', startExperience) } export function hideMenu() { const menu = document.getElementById('menu') as HTMLDivElement if (!menu) return menu.style.display = 'none' } export function showMenu() { const menu = document.getElementById('menu') as HTMLDivElement if (!menu) return menu.style.display = 'block' } export function showMenuAndOtherOptions() { setTimeout(() => { showMenu() overlay?.classList.add('active') joystickZoneMovement?.classList.remove('active') }, 1000) } export async function hideMenuAndOtherOptions() { hideMenu() overlay?.classList.remove('active') joystickZoneMovement?.classList.add('active') }
local fn = require('steovim.some_functionality') local leader_keymap = { prefix = '<leader>', { key= 'pv', what= 'Project View', how= function() vim.cmd.Ex() end }, { key= 'h', what= 'Go To Left Pane', how= '<C-w>h' }, { key= 'j', what= 'Go To Down Pane', how= '<C-w>j' }, { key= 'k', what= 'Go To Up Pane', how= '<C-w>k' }, { key= 'l', what= 'Go To Right Pane', how= '<C-w>l' }, { key= 'vrm', what= 'Vim Re-Map (source keymaps.lua)', how= ':so ~/.config/nvim/lua/steovim/keymaps.lua<CR>' }, { key= 'tc', what= 'Tab Close', how= ':tabclose<CR>' }, { key= 'p', what= 'Paste without overriding buffer', how= [["_dP]] }, { mode= {'n', 'v'}, key= 'y', what= 'Yank to clipboard', how= '"+y' }, { mode= {'n', 'v'}, key= 'd', what= 'Delete to clipboard', how= '"+d' }, { key= 'yp', what= 'Yank file Path to clipboard', how= ':!echo -n "%" | pbcopy<CR>' }, { key= 'yg', what= 'Yank blob link to clipboard', how= ':!get-blob-link "%:p" | pbcopy<CR>' }, { key= 'grs', what= 'Git Rebase Squash', how= ':s/^\\w\\+ /squash /<CR>' }, { key= 'grf', what= 'Git Rebase Fixup', how= ':s/^\\w\\+ /fixup /<CR>' }, { key= 's', what= 'Set' }, { key= 'slr', what= 'Vim Line number Relative', how= function() vim.opt.relativenumber = true end }, { key= 'sla', what= 'Vim Line number Absolute', how= function() vim.opt.relativenumber = false end }, { key= 'sfj', what= 'Set Filetype JSON', how= ':set filetype=json<CR>' }, { mode= {'n', 'v'}, key= 'c', what= 'Code-notes' }, { key= 'cr', what= 'Code-notes create Ref-file', how= ':!code-notes "%" ref-file --create<CR>' }, { key= 'cn', what= 'Code-notes create Note', how= ':!code-notes "%" code-snippet --create | pbcopy<CR>' }, { mode= 'v', key= 'cyp', what= 'Code-notes Yank Permalink to clipboard', how= fn.get_github_permalink_for_visual_block }, } local no_prefix_keymap = { { mode= {'n', 'v', 'i'}, key= '<C-s>', what= '', how= '<Esc>:w<CR>' }, { mode= 'n', key= 'L', what= '', how= '$' }, { mode= 'n', key= 'H', what= '', how= '^' }, } local lsp_keymaps = { { { key= "gd", what= 'desc="Goto Definition"', how= function() vim.lsp.buf.definition() end }, { key= "gi", what= 'desc="Goto Implementation"', how= function() vim.lsp.buf.implementation() end }, { key= "K", what= '', how= function() vim.lsp.buf.hover() end }, { key= "]d", what= '', how= function() vim.diagnostic.goto_next() end }, { key= "[d", what= '', how= function() vim.diagnostic.goto_prev({}) end }, { mode= "i", key= "<C-h>", what= '', how= function() vim.lsp.buf.signature_help() end }, { mode= {"n", "i"}, key= "<C-p>", what= '', how= function() vim.lsp.buf.signature_help() end }, }, { prefix='<leader>', { key= "gd", what= "Don't Goto Definition", how= function() print_definition_positions() end }, { key= "vws", what= 'Vim Workspace Symbol', how= function() vim.lsp.buf.workspace_symbol('') end }, { key= "vd", what= 'Vim Diagnostic', how= function() vim.diagnostic.open_float() end }, { key= "vca", what= 'Vim Code Action', how= function() vim.lsp.buf.code_action() end }, { key= "vrr", what= 'Vim RefeRences', how= function() vim.lsp.buf.references() end }, { key= "vrn", what= 'Vim ReName', how= function() vim.lsp.buf.rename() end }, { key= "vfm", what= 'Vim ForMat', how= function() vim.lsp.buf.format() end }, { key= "vhl", what= 'Vim HighLight', how= function() fn.toggle_lsp_highlight() end }, } } local config_helpers = require('steovim.config_helpers') config_helpers.set_keymaps(leader_keymap) config_helpers.set_keymaps(no_prefix_keymap) local M = {} function M.set_lsp_keymaps(bufnr) for _, keymap in ipairs(lsp_keymaps) do config_helpers.set_keymaps(keymap, { buffer=bufnr }) end end return M
#' Plot massdiffhist histogram with named adducts labeled #' #' Plot massdiff histogram with option of labeling peaks corresponding to known #' adducts or chemical transformations. The best-matching adducts for each #' histogram bin are found internally with \code{\link{adductMatch.histogram}}. #' #' @param hist Histogram of a massdiff object produced by #' \code{\link{hist.massdiff}} #' @param add data.frame; adduct data to use to annotate the mass diff peaks, #' (default: built-in data set \code{adducts}) #' @param labels numeric; label histogram peaks with top N adducts from the #' adduct table specified to option \code{add} (default: NULL - no labels) #' @param pch Plot character to use for highlighting adduct peaks #' @param col Color for labels and text #' @param cex Character scaling for labelled points and text #' @param pos Position of text label, values 1, 2, 3, 4 are below, left, above, #' and to the right of points respectively. #' @param main character; Title for histogram plot #' @param xlab character; X-axis label #' @param ... Other parameters to pass to plot #' #' @export plot.massdiffhist <- function(hist, add=mass2adduct::adducts, labels=NULL, pch=0, col="blue", cex=0.5, pos=4, main="Mass difference histogram", xlab="mass difference (m/z)", ...) { # Plot histogram graphics:::plot.histogram(hist, main=main, xlab=xlab, ...) # Overlay points and text labels # Calculate top adducts if (!is.null(labels)) { matches <- adductMatch(x=hist, add=add, density=FALSE) matches <- matches[order(matches$counts,decreasing=T),] matches <- matches[1:labels,] # Take the top N hits points(x=matches$mass, y=matches$counts, pch=pch, col=col, cex=cex) graphics::text(x=matches$mass, y=matches$counts, label=as.character(matches$name), pos=pos, col=col, cex=cex) } }
// // AddNotificationView.swift // NotificationsLab // // Created by Cory Tripathy on 5/22/23. // import SwiftUI import CoreLocation import MapKit struct AddNotificationView: View { @Environment(\.dismiss) var dismiss @ObservedObject var vm: ViewModel var body: some View { NavigationStack { Form { Section { Picker("Notification Type", selection: $vm.notificatonSelected) { ForEach(ViewModel.NotificationSelection.allCases) { Text($0.rawValue) .tag($0) } } switch vm.notificatonSelected { case .date: DatePicker("Date", selection: $vm.date) case .location: Map(mapRect: $vm.mapArea, showsUserLocation: true) .frame(height: 400) .onAppear { vm.requestLocation() } case .timer: Picker("Timer", selection: $vm.timeInterval) { ForEach(0...120, id: \.self) { Text("\($0.description) min") } } } TextField("Title", text: $vm.title) TextField("Content", text: $vm.body) } Section { Button("Schedule Notification") { // TODO: (bonus) Could we handle this try! expression in a safer way? Task { try! await vm.scheduleNotification() } dismiss() } .disabled(vm.title.isEmpty || vm.body.isEmpty) .frame(maxWidth: .infinity, alignment: .center) } } .navigationTitle("Create a Notification") .navigationBarTitleDisplayMode(.inline) } } } struct AddNotificationView_Previews: PreviewProvider { static var previews: some View { AddNotificationView(vm: ViewModel()) } }
import { expect } from "@jest/globals" import CourtCase from "services/entities/CourtCase" import type { ResolutionStatus } from "types/ResolutionStatus" describe("CourtCase", () => { it("Should be locked by another user when error is locked by another user", () => { const courtCase = new CourtCase() courtCase.errorLockedByUsername = "Another username" const result = courtCase.isLockedByAnotherUser("username") expect(result).toBe(true) }) it("Should be locked by another user when trigger is locked by another user", () => { const courtCase = new CourtCase() courtCase.triggerLockedByUsername = "Another username" const result = courtCase.isLockedByAnotherUser("username") expect(result).toBe(true) }) it("Should not be locked by another user when error is locked by the user", () => { const courtCase = new CourtCase() courtCase.errorLockedByUsername = "username" const result = courtCase.isLockedByAnotherUser("username") expect(result).toBe(false) }) it("Should not be locked by another user when trigger is locked by the user", () => { const courtCase = new CourtCase() courtCase.triggerLockedByUsername = "username" const result = courtCase.isLockedByAnotherUser("username") expect(result).toBe(false) }) it("Should not be locked by another user when error and trigger are not locked by any user", () => { const courtCase = new CourtCase() const result = courtCase.isLockedByAnotherUser("username") expect(result).toBe(false) }) test.each([ { expectedResult: false, triggers: "Resolved", exceptions: "Resolved", triggersLockedByAnotherUser: "are NOT", exceptionLockedByAnotherUser: "are NOT" }, { expectedResult: false, triggers: "Resolved", exceptions: "Submitted", triggersLockedByAnotherUser: "are NOT", exceptionLockedByAnotherUser: "are NOT" }, { expectedResult: false, triggers: "Resolved", exceptions: "Unresolved", triggersLockedByAnotherUser: "are NOT", exceptionLockedByAnotherUser: "are" }, { expectedResult: false, triggers: "Unresolved", exceptions: "Submitted", triggersLockedByAnotherUser: "are", exceptionLockedByAnotherUser: "are NOT" }, { expectedResult: true, triggers: "Unresolved", exceptions: "Unresolved", triggersLockedByAnotherUser: "are NOT", exceptionLockedByAnotherUser: "are NOT" }, { expectedResult: true, triggers: "Unresolved", exceptions: "Resolved", triggersLockedByAnotherUser: "are NOT", exceptionLockedByAnotherUser: "are" }, { expectedResult: true, triggers: "Resolved", exceptions: "Unresolved", triggersLockedByAnotherUser: "are", exceptionLockedByAnotherUser: "are NOT" } ])( "It should return $expectedResult when triggers are $triggers and $triggersLockedByAnotherUser locked by another user and exceptions are $exceptions and $exceptionLockedByAnotherUser locked by another user", ({ expectedResult, triggers, exceptions, triggersLockedByAnotherUser, exceptionLockedByAnotherUser }) => { const courtCase = new CourtCase() courtCase.triggerStatus = triggers as ResolutionStatus courtCase.errorStatus = exceptions as ResolutionStatus courtCase.triggerLockedByUsername = triggersLockedByAnotherUser === "are" ? "Bichard02" : "" courtCase.errorLockedByUsername = exceptionLockedByAnotherUser === "are" ? "Bichard02" : "" const result = courtCase.canReallocate("Bichard01") expect(result).toBe(expectedResult) } ) })
import { Roboto } from 'next/font/google' const roboto = Roboto({ weight: ['100', '300', '400', '500', '700', '900'], subsets: ['latin'] }) type Props = { state: string, setState: React.Dispatch<React.SetStateAction<string>> } const DashboardTextarea = ({ state, setState }: Props) => { const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => { setState(e.target.value) } return ( <textarea className={`dashboard-input description width-95 margin-vertical-10 ${roboto.className}`} value={state} onChange={handleChange} placeholder="Enter a description" /> ) } export default DashboardTextarea
package com.example.itrequest import android.annotation.SuppressLint import android.os.Bundle import android.widget.ArrayAdapter import android.widget.Button import android.widget.EditText import android.widget.ListView import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.room.* @Dao interface RequestDao { @Query("SELECT * FROM requests") fun getAll(): List<Request> @Insert fun insert(request: Request) @Update fun update(request: Request) } @Database(entities = [Request::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun requestDao(): RequestDao } class ManageActivity : AppCompatActivity() { private lateinit var db: AppDatabase private lateinit var requestDao: RequestDao private lateinit var adapter: ArrayAdapter<String> private val requestTitles: MutableList<String> = mutableListOf() private val requests: MutableList<Request> = mutableListOf() var userCurrent = User("", "", "") @SuppressLint("MissingInflatedId") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_manage) ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } val dbUserCurrent = DbITrequest(this, null) db = Room.databaseBuilder(applicationContext, AppDatabase::class.java, "itrequest-db").build() requestDao = db.requestDao() val listData: EditText = findViewById(R.id.ListData) val askList: ListView = findViewById(R.id.AskList) val addButton: Button = findViewById(R.id.AddList) adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, requestTitles) askList.adapter = adapter loadRequests() askList.setOnItemClickListener { _, _, position, _ -> val selectedRequest = requests[position] val dialogView = layoutInflater.inflate(R.layout.dialog_edit_description, null) val descriptionEditText: EditText = dialogView.findViewById(R.id.Description) descriptionEditText.setText(selectedRequest.description) val descriptionAccept: TextView = dialogView.findViewById(R.id.AcceptedRequest) descriptionAccept.text = selectedRequest.login val users = dbUserCurrent.getAllUsers() val size = users.size userCurrent = users.get(size - 1) when (userCurrent.jobTitle) { "manager" -> { AlertDialog.Builder(this) .setTitle("Изменить Описание") .setView(dialogView) .setPositiveButton("Сохранить") { dialog, _ -> selectedRequest.description = descriptionEditText.text.toString() Thread { requestDao.update(selectedRequest) runOnUiThread { loadRequests() } }.start() dialog.dismiss() } .setNegativeButton("Отменить") { dialog, _ -> dialog.dismiss() } .create() .show() } "teacher" -> { AlertDialog.Builder(this) .setTitle("Подробности") .setView(dialogView) .setPositiveButton("Принять") { dialog, _ -> selectedRequest.login = userCurrent.login Thread { requestDao.update(selectedRequest) runOnUiThread { loadRequests() } }.start() dialog.dismiss() } .create() .show() } } } addButton.setOnClickListener { if (userCurrent.jobTitle == "manager") { val text = listData.text.toString().trim() if (text.isNotEmpty()) { val newRequest = Request(title = text, description = "", login = "") Thread { requestDao.insert(newRequest) runOnUiThread { loadRequests() } }.start() listData.setText("") } } } } private fun loadRequests() { Thread { requests.clear() requestTitles.clear() requests.addAll(requestDao.getAll()) requestTitles.addAll(requests.map { it.title }) runOnUiThread { adapter.notifyDataSetChanged() } }.start() } }
import React, {useEffect, useState} from 'react'; import { ActivityIndicator, Text, TouchableOpacity, View, Alert, } from 'react-native'; import {useDispatch, useSelector} from 'react-redux'; import {clearPermissionAction, logoutAction} from '../redux/actions'; import Header from '../header/header'; import LoginScreen from './login'; function ProfileScreen({navigation, route}) { const dispatch = useDispatch(); const [loading, setLoading] = useState(false); const [firstName, setFirstName] = useState(false); const [lastName, setLastName] = useState(false); const isLoggedIn = useSelector((state) => state.login.isLoggedIn); const permission = useSelector((state) => state.perm.permission); const getUserDetails = async () => { const response = await fetch('http://192.168.1.103:3000/user/profile', { method: 'GET', headers: { 'Content-Type': 'application/json', }, }); const json = await response.json(); setFirstName(json['data'][0]['First_Name']); setLastName(json['data'][0]['Last_Name']); }; useEffect(() => { if (isLoggedIn) { getUserDetails(); } }, [isLoggedIn]); const getProductByID = async (productID) => { const response = await fetch('http://192.168.1.103:3000/product/getById', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({'ID': productID}), }); const json = await response.json(); return json['data'][0]['Brand']+' '+ json['data'][0]['Brand_series']; }; const getAllMyReviews = async () => { try { const response = await fetch('http://192.168.1.103:3000/review/getReviewByLoggedInUser', { method: 'GET', headers: { 'Content-Type': 'application/json', }, }); if (!response.ok) { setLoading(false); throw new Error('Spróbuj ponownie później'); } const json = await response.json(); const reviews = json['data']; for (let i = 0; i < reviews.length; i++) { reviews[i]['Brand'] = await getProductByID(reviews[i]['Product_ID']); } return reviews; } catch (error) { setLoading(false); Alert.alert('Błąd', error.message); } }; const myReviewsRedirect = async () => { setLoading(true); const reviews = await getAllMyReviews(); setLoading(false); navigation.navigate('MyReviews', {reviews}); }; const logoutAPI = async () => { setLoading(true); await fetch('http://192.168.1.103:3000/user/logout', { method: 'DELETE', headers: { 'Content-Type': 'application/json', }, }); dispatch(logoutAction()); dispatch(clearPermissionAction()); setLoading(false); navigation.navigate('Home'); }; const AdminButtons = () => { return ( <View className='w-56 mx-auto mt-10'> <TouchableOpacity className='bg-blue-500 rounded-md h-14 justify-center' onPress={() => navigation.navigate('CreateUser')} > <Text className='text-center p-3 text-white font-bold text-lg' >Tworzenie użytkownika</Text> </TouchableOpacity> </View> ); }; if (!isLoggedIn) { return <LoginScreen navigation={navigation} />; } else { return ( <View className='flex-1' > <Header navigation={navigation} /> <View> <Text className='text-3xl text-center mt-10 font-bold text-gray-900' >Cześć! {firstName} {lastName}</Text> </View> <View> <View className='w-56 mx-auto mt-10'> <TouchableOpacity className='bg-blue-500 rounded-md h-14 justify-center' onPress={myReviewsRedirect} > <Text className='text-center p-3 text-white font-bold text-lg' >Moje recenzje</Text> </TouchableOpacity> </View> <View className='w-56 mx-auto mt-10'> <TouchableOpacity className='bg-blue-500 rounded-md h-14 justify-center' onPress={() => navigation.navigate('EditEmail')} > <Text className='text-center p-3 text-white font-bold text-lg' >Zmień adres email</Text> </TouchableOpacity> </View> <View className='w-56 mx-auto mt-10'> <TouchableOpacity className='bg-blue-500 rounded-md h-14 justify-center' onPress={() => navigation.navigate('EditPassword')} > <Text className='text-center p-3 text-white font-bold text-lg' >Zmień hasło</Text> </TouchableOpacity> </View> {permission === 'admin' ? <AdminButtons/> : null} <View className='w-56 mx-auto mt-10'> <TouchableOpacity className='bg-blue-500 rounded-md h-14 justify-center' onPress={() => logoutAPI()} > <Text className='text-center p-3 text-white font-bold text-lg' >Wyloguj</Text> </TouchableOpacity> </View> </View> {loading && <View className='flex-1 justify-center content-center block w-full h-full absolute bg-gray-800 opacity-50'> <ActivityIndicator size='large'/> </View> } </View> ); } } export default ProfileScreen;
// 2331. Evaluate Boolean Binary Tree use std::rc::Rc; use std::cell::RefCell; fn main() { fn create_node(val: i32, left: Option<Rc<RefCell<TreeNode>>>, right: Option<Rc<RefCell<TreeNode>>>) -> Rc<RefCell<TreeNode>> { Rc::new(RefCell::new(TreeNode { val, left, right, })) } let root = Some(create_node(2, Some(create_node(1, None, None)), Some(create_node(3, Some(create_node(0, None, None)), Some(create_node(1, None, None)) )) )); let result = Solution::evaluate_tree(root); println!("result = {}", result); } // Definition for a binary tree node. #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<TreeNode>>>, pub right: Option<Rc<RefCell<TreeNode>>>, } impl TreeNode { #[inline] pub fn new(val: i32) -> Self { TreeNode { val, left: None, right: None } } } struct Solution; impl Solution { pub fn evaluate_tree(root: Option<Rc<RefCell<TreeNode>>>) -> bool { // Leaf nodes have either the value 0 or 1, where 0 represents False and 1 represents True. // Non-leaf nodes have either the value 2 or 3, where 2 represents the boolean OR and 3 represents the boolean AND. if let Some(node) = root { let node = node.borrow(); if node.left.is_none() && node.right.is_none() { return node.val == 1; } let left = Solution::evaluate_tree(node.left.clone()); let right = Solution::evaluate_tree(node.right.clone()); match node.val { 2 => left || right, 3 => left && right, _ => false, } } else { false } } }
import axios from "axios"; import React from "react"; import { Link, useNavigate } from "react-router-dom"; import { logout } from "../../redux/store/user"; import { toast } from "react-toastify"; import { useAppDispatch } from "../../redux/store"; const AdminDashboard = () => { const navigate = useNavigate(); const dispatch = useAppDispatch(); //logout start const handlerLogout = async () => { const values: string = ""; await axios .post( `${process.env.REACT_APP_SERVER_ENDPOINT}/auth/logout`, { values }, { withCredentials: true, } ) .then((response) => { if (response.data.code === 200) { toast.success(response.data.message, { position: "top-left", }); dispatch(logout()); navigate("/login"); } else { toast.error("Logout Error"); } }) .catch((error) => { console.log({ error }); toast.error(error.message); }); }; //logout end return ( <div className="container"> <nav className="navbar navbar-expand-lg navbar-light bg-light"> <div className="container-fluid"> <span className="navbar-brand">Navbar</span> <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" > <span className="navbar-toggler-icon"></span> </button> <div className="collapse navbar-collapse" id="navbarSupportedContent"> <ul className="navbar-nav me-auto mb-2 mb-lg-0"> <li className="nav-item"> <Link className="nav-link active" aria-current="page" to="#"> Home </Link> </li> <li className="nav-item"> <Link className="nav-link" to="#"> Link </Link> </li> </ul> <div className="d-flex justify-content-between"> <button className="btn btn-outline-success " type="button" onClick={handlerLogout} > Logout </button> </div> </div> </div> </nav> <h1>Home Page</h1> </div> ); }; export default AdminDashboard;
import dayjs from 'dayjs'; import { useEffect, useState } from 'react'; import { api } from '~/lib/axios'; import { generateDates } from '~/utils/generate-dates'; import { HabitDay } from './HabitDay'; const weekDays = ['D', 'S', 'T', 'Q', 'Q', 'S', 'S']; const summaryDates = generateDates(); const minimumSummaryDatesSize = 18 * 7; const amountOfDaysToFull = minimumSummaryDatesSize - summaryDates.length; type Summary = { id: string; date: string; amount: number; completed: number; }[]; export const SummaryTable = function SummaryTableComponent() { const [summary, setSummary] = useState<Summary>([]); useEffect(() => { api.get('summary').then(response => { setSummary(response.data); }); }, []); return ( <div className='flex w-full overflow-auto pb-6'> <div className='grid-row-7 grid grid-flow-row gap-3'> {weekDays.map((weekDay, index) => { return ( <div key={`${weekDay}-${index}`} className='flex h-10 w-10 items-center justify-center text-xl font-bold text-zinc-400' > {weekDay} </div> ); })} </div> <div className='grid-rows-7 grid grid-flow-col gap-3'> {summary.length > 0 && summaryDates.map(date => { const dayInSummary = summary.find(day => { return dayjs(date).isSame(day.date, 'day'); }); return ( <HabitDay key={date.toString()} date={date} amount={dayInSummary?.amount} defaultCompleted={dayInSummary?.completed} /> ); })} {amountOfDaysToFull > 0 && Array.from({ length: amountOfDaysToFull }).map((_, index) => { return ( <div key={index} className='h-10 w-10 cursor-not-allowed rounded-lg border-2 border-zinc-800 bg-zinc-900 opacity-40' /> ); })} </div> </div> ); };
#pragma once #include <core/math.h> #include <utils/ref.h> namespace mv { /* Camera interface, to create a camera simply create a */ /* parent class that inherit from the `Camera` class and */ /* then implement all the pure virtual functions. */ class Camera : public SharedObject { protected: Camera( void ) {} virtual ~Camera( void ) {} public: /* return the projection matrix */ virtual glm::mat4 projection( void ) const = 0; /* return the camera view matrix */ virtual glm::mat4 view( void ) const = 0; /* A generic update function that is called every */ /* frame, you can do anything you want in this. */ virtual void update( void ) = 0; /* called in case the window is resized */ virtual void resize( glm::vec2 new_size ) = 0; }; }
package AdvJavaPractice.waitnotify; import java.util.concurrent.Semaphore; public class SemaphorePr { /* Semaphore bir kaynağa erişebilen iş parçacığı sayısını kısıtlamak için kullanılır. Yani, synchronized sadece bir iş parçacığının kilitlenmesi ve senkronize blok / yöntemi yürütmesine izin verirken, Semaphore n iş parçacığına kadar izin verir ve diğerlerini engeller. senaryo:deneme kabini/ödeme kasası Mağazanın 3 deneme kabini var. 5 kişi mağazanın deneme kabinini kullanmak istiyor. Bu 5 tane işlem için 5 thread kullanılsın. */ public static void main(String[] args) { Semaphore semaphore = new Semaphore(3); Person person1 = new Person("Fred",semaphore); Person person2= new Person("wilma",semaphore); Person person3 = new Person("betty",semaphore); Person person4 = new Person("cakil",semaphore); Person person5 = new Person("dino",semaphore); person1.start(); person2.start(); person3.start(); person4.start(); person5.start(); } } class Person extends Thread{ private String name; private Semaphore semaphore; public Person(String name, Semaphore semaphore) { this.name = name; this.semaphore = semaphore; } @Override public void run() { System.out.println(name+ " kabine girmek istiyor"); try { semaphore.acquire(); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println(name+ " kabine girdi"); System.out.println(name+ " kabini kullaniyor"); try { Thread.sleep(2000); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println(name+ " kabinden cikiyor..."); semaphore.release(); } }
import 'package:app_mobile/pages/statistics/components/pie_chart/components/indicator.dart'; import 'package:fl_chart/fl_chart.dart'; import 'package:flutter/material.dart'; class PieChartCircle extends StatefulWidget { const PieChartCircle({Key key}) : super(key: key); @override State<StatefulWidget> createState() => _PieChartState(); } class _PieChartState extends State { int touchedIndex = -1; @override Widget build(BuildContext context) { return AspectRatio( aspectRatio: 1.7, child: Card( color: Colors.white, child: Row( children: <Widget>[ Expanded( child: AspectRatio( aspectRatio: 1, child: PieChart( PieChartData( pieTouchData: PieTouchData(touchCallback: (FlTouchEvent event, pieTouchResponse) { setState(() { if (!event.isInterestedForInteractions || pieTouchResponse == null || pieTouchResponse.touchedSection == null) { touchedIndex = -1; return; } touchedIndex = pieTouchResponse .touchedSection.touchedSectionIndex; }); }), borderData: FlBorderData( show: false, ), sectionsSpace: 2, centerSpaceRadius: 12, sections: showingSections()), ), ), ), Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Indicator( color: Color(0xff0293ee), text: 'Ảnh (20)', isSquare: true, ), SizedBox( height: 4, ), Indicator( color: Color(0xfff8b250), text: 'Tài liệu (12)', isSquare: true, ), SizedBox( height: 4, ), Indicator( color: Color(0xff845bef), text: 'Hồ sơ (41)', isSquare: true, ), SizedBox( height: 4, ), Indicator( color: Color(0xff13d38e), text: 'Video (120)', isSquare: true, ), SizedBox( height: 18, ), ], ), const SizedBox( width: 28, ), ], ), ), ); } List<PieChartSectionData> showingSections() { return List.generate(4, (i) { final isTouched = i == touchedIndex; final fontSize = isTouched ? 20.0 : 12.0; final radius = isTouched ? 65.0 : 50.0; switch (i) { case 0: return PieChartSectionData( color: const Color(0xff0293ee), value: 40, title: '40%', radius: radius, titleStyle: TextStyle( fontSize: fontSize, fontWeight: FontWeight.bold, color: const Color(0xffffffff)), ); case 1: return PieChartSectionData( color: const Color(0xfff8b250), value: 30, title: '30%', radius: radius, titleStyle: TextStyle( fontSize: fontSize, fontWeight: FontWeight.bold, color: const Color(0xffffffff)), ); case 2: return PieChartSectionData( color: const Color(0xff845bef), value: 15, title: '15%', radius: radius, titleStyle: TextStyle( fontSize: fontSize, fontWeight: FontWeight.bold, color: const Color(0xffffffff)), ); case 3: return PieChartSectionData( color: const Color(0xff13d38e), value: 15, title: '15%', radius: radius, titleStyle: TextStyle( fontSize: fontSize, fontWeight: FontWeight.bold, color: const Color(0xffffffff)), ); default: throw Error(); } }); } }
# Entity-Attribute-Value (EAV) in Magento 2 Entity-Attribute-Value (EAV) is a database design pattern used in Magento 2 to store complex and highly customizable data. It's commonly employed for managing product attributes, categories, and custom attributes in the database. EAV provides a flexible way to handle a wide range of data types and configurations without the need to modify the database schema for each new attribute. ## Key Components of EAV in Magento 2 1. **Entities:** In Magento 2, entities represent the main data objects, such as products, customers, and categories. Each entity type has a corresponding table in the database. 2. **Attributes:** Attributes define the properties or characteristics of entities. In EAV, attributes can be of various types, including text, numeric, date, and more. Examples of attributes in Magento 2 include product names, prices, and descriptions. 3. **Attribute Sets:** Attribute sets are collections of related attributes that define how an entity (e.g., a product) should be structured. Attribute sets allow for easy configuration and management of product attributes. 4. **Attribute Groups:** Within an attribute set, attributes are organized into attribute groups. Attribute groups help streamline attribute management by grouping related attributes together. ## Advantages of EAV in Magento 2 1. **Flexibility:** EAV provides a high degree of flexibility, allowing administrators to add, modify, or delete attributes without altering the database schema. This flexibility is crucial for e-commerce platforms like Magento, where product attributes can vary significantly. 2. **Customizability:** EAV enables the creation of custom attributes to meet specific business requirements. This is particularly useful for adding unique attributes to products or other entities. 3. **Scalability:** As the number of attributes and entities grows, the EAV model remains scalable, ensuring efficient data storage and retrieval. 4. **Localization:** EAV supports attribute values in multiple languages and locales, making it suitable for global e-commerce stores. ## Example of EAV in Magento 2 A common example of EAV usage in Magento 2 is the storage of product attributes. Each product attribute, such as size or color, is stored as a separate record in the database, allowing for dynamic attribute creation and management. While EAV offers flexibility and customizability, it's essential to use it judiciously, as it can introduce complexities in data retrieval and querying. Proper indexing and database optimization are crucial for maintaining good performance in EAV-based systems. In summary, Entity-Attribute-Value (EAV) is a fundamental database model in Magento 2 that enables the storage of dynamic and customizable data, making it a powerful tool for managing product attributes and other complex data structures in e-commerce applications. # Magento 2 EAV Model The Entity-Attribute-Value (EAV) model in Magento 2 is a database design pattern used to store and manage complex and highly customizable data structures. It provides a flexible way to handle entities with a variable number of attributes, such as products, customers, and categories. The EAV model is a fundamental part of Magento's architecture, allowing for dynamic and extensible data management. ## Key Concepts ### 1. Entities In the EAV model, entities are the objects that you want to store data for. In Magento 2, common entities include products, customers, categories, and more. Each entity is uniquely identified by an entity type code, such as "catalog_product" for products or "customer" for customers. ### 2. Attributes Attributes represent properties or characteristics of an entity. In Magento, attributes can be broadly categorized as system attributes (built-in attributes) and custom attributes (created by administrators or developers). For products, attributes could include name, price, color, size, etc. Attributes are uniquely identified by an attribute code. ### 3. Attribute Sets Attribute sets are groups of related attributes that are assigned to an entity type. For example, a "Clothing" attribute set for products might include attributes like "size" and "color," while an "Electronics" attribute set might include "weight" and "power consumption." ### 4. Attribute Values Attribute values store the actual data associated with an entity's attributes. These values are linked to both the entity and the attribute. For instance, for a product entity, the attribute "color" might have a value of "red." ### 5. Entity Types Entity types define the type of entity being managed. Magento 2 supports various entity types, such as catalog_product, customer, category, and more. Each entity type has its own set of attributes and attribute sets. ## Use Cases The EAV model is particularly useful in scenarios where entities have a wide range of attributes, and not all attributes apply to every entity of that type. Some common use cases for the EAV model in Magento 2 include: ### 1. Product Attributes Products in an e-commerce store often have numerous attributes, but not all products share the same attributes. The EAV model allows for dynamic creation and management of product attributes. ### 2. Customer Attributes In cases where additional information needs to be stored for customers, such as loyalty points, preferences, or membership levels, the EAV model provides flexibility. ### 3. Category Attributes Categories can have various attributes like image, description, or metadata. The EAV model enables the addition of custom attributes to categories. ### 4. Extensibility The EAV model supports the extensibility of data structures without altering the core database schema. This is crucial for accommodating customizations and third-party extensions. ## Implementation To work with the EAV model in Magento 2, developers need to define attributes, attribute sets, and entity types. They can create custom attributes, assign them to attribute sets, and then associate those sets with specific entity types. The EAV model requires careful planning and management of attribute data. In summary, the Magento 2 EAV model is a flexible and extensible approach to managing complex and customizable data structures within the platform. It plays a crucial role in handling entities like products, customers, and categories by allowing dynamic attribute management and customization. # More info --> https://bsscommerce.com/confluence/magento-2-eav-model/
<?php declare(strict_types=1); namespace App\Model\Images\Post\Domain\Entity; use App\Model\Images\Author\Domain\Entity\Author; use App\Model\Images\Post\Infrastructure\Repository\PostRepository; use App\Model\Shared\Domain\Entity\AggregateRoot; use App\Model\Shared\Domain\Entity\EventsTrait; use App\Model\Shared\Domain\Entity\ValueObject\Id; use DateTimeImmutable; use Doctrine\ORM\Mapping as ORM; use DomainException; #[ORM\Entity(repositoryClass: PostRepository::class)] #[ORM\Table(name: '`images_posts`')] class Post implements AggregateRoot { use EventsTrait; #[ORM\Id] #[ORM\Column(type: 'uuid_id')] private Id $id; #[ORM\ManyToOne(targetEntity: Author::class, cascade: ['persist'])] private Author $author; #[ORM\Column(type: 'string', length: 255, nullable: false)] private string $avatar; #[ORM\Column(type: 'text', nullable: false)] private string $description; #[ORM\Column(type: 'datetime_immutable')] private DateTimeImmutable $date; public function __construct(Id $id, Author $author, string $avatar, string $description, DateTimeImmutable $date) { $this->id = $id; $this->author = $author; $this->avatar = $avatar; $this->description = $description; $this->date = $date; $this->recordEvent( new \App\Model\Images\Post\Domain\Entity\Event\PostCreated( $author->getId(), $this->id, ) ); } public function delete(Author $author): void { if (!$this->getAuthor()->getId()->isEqual($author->getId())) { throw new DomainException('Only the author can delete a post.'); } $this->recordEvent( new \App\Model\Images\Post\Domain\Entity\Event\PostDeleted($this->id, $this->author->getId()) ); } public function getId(): Id { return $this->id; } public function getDate(): DateTimeImmutable { return $this->date; } public function getAuthor(): Author { return $this->author; } public function getAvatar(): string { return $this->avatar; } public function setAvatar(string $avatar): void { $this->avatar = $avatar; } public function getDescription(): string { return $this->description; } public function setDescription(string $description): void { $this->description = $description; } }
import { useEffect, useState } from "react"; import TasksEdit from "./TasksEdit"; import dateFormatter from "../utils/utils"; function Task({todo = {}, onDelete, onChange, onChecked }) { const {id, title, completed, time = new Date(2024, 4, 0, 13, 48, 15)} = todo; const [statusState, setStatusState] = useState(''); useEffect(() => { if(completed) { setStatusState('completed'); } }, []) function handleChange(e) { completed ? setStatusState('') : setStatusState('completed'); onChecked(id, e); } function handleKeyDown(event) { const status = completed ? 'completed' : ''; if(event.key === 'Enter') { setStatusState(status); } } return ( <> <li className={statusState}> <div className="view"> <input className="toggle" type="checkbox" onChange={handleChange} checked={completed} /> <label> <span className="description">{title}</span> <span className="created">{`created ${dateFormatter(time)} ago`}</span> </label> <button className='icon icon-edit' onClick={() => setStatusState('editing')}></button> <button className='icon icon-destroy' onClick={() => onDelete(id)}></button> </div> {statusState === 'editing' && <TasksEdit id={id} title={title} onChange={onChange} onKeyDown={handleKeyDown} />} </li> </> ) } export default Task;
/* GStreamer * Copyright (C) 2024 Seungha Yang <seungha@centricular.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <gst/gst.h> #include <gst/check/gstcheck.h> #include <gst/d3d12/gstd3d12.h> #include <wrl.h> #include <mutex> #include <condition_variable> /* *INDENT-OFF* */ using namespace Microsoft::WRL; /* *INDENT-ON* */ GST_START_TEST (test_device_equal) { auto device = gst_d3d12_device_new (0); fail_unless (GST_IS_D3D12_DEVICE (device)); auto other_device = gst_d3d12_device_new (0); fail_unless (GST_IS_D3D12_DEVICE (other_device)); fail_unless (gst_d3d12_device_is_equal (device, other_device)); auto handle = gst_d3d12_device_get_device_handle (device); auto other_handle = gst_d3d12_device_get_device_handle (other_device); fail_unless_equals_pointer (handle, other_handle); gst_object_unref (device); gst_object_unref (other_device); } GST_END_TEST; struct DeviceRemovedData { std::mutex lock; std::condition_variable cond; guint removed_count = 0; }; static void on_device_removed (GstD3D12Device * device, GParamSpec * pspec, DeviceRemovedData * data) { HRESULT hr = S_OK; g_object_get (device, "device-removed-reason", &hr, nullptr); fail_unless (FAILED (hr)); std::lock_guard <std::mutex> lk (data->lock); data->removed_count++; data->cond.notify_all (); } GST_START_TEST (test_device_removed) { auto device = gst_d3d12_device_new (0); fail_unless (GST_IS_D3D12_DEVICE (device)); ComPtr<ID3D12Device5> device5; auto handle = gst_d3d12_device_get_device_handle (device); fail_unless (handle != nullptr); handle->QueryInterface (IID_PPV_ARGS (&device5)); if (!device5) { gst_object_unref (device); return; } auto other_device = gst_d3d12_device_new (0); DeviceRemovedData data; g_signal_connect (device, "notify::device-removed-reason", G_CALLBACK (on_device_removed), &data); g_signal_connect (other_device, "notify::device-removed-reason", G_CALLBACK (on_device_removed), &data); /* Emulate device removed case */ device5->RemoveDevice (); device5 = nullptr; /* Callback will be called from other thread */ { std::unique_lock <std::mutex> lk (data.lock); while (data.removed_count != 2) data.cond.wait (lk); } /* This will fail since we are holding removed device */ auto null_device = gst_d3d12_device_new (0); fail_if (null_device); gst_object_unref (device); gst_object_unref (other_device); /* After releasing all devices, create device should be successful */ device = gst_d3d12_device_new (0); fail_unless (GST_IS_D3D12_DEVICE (device)); gst_object_unref (device); } GST_END_TEST; static gboolean check_d3d12_available (void) { auto device = gst_d3d12_device_new (0); if (!device) return FALSE; gst_object_unref (device); return TRUE; } /* ID3D12Device5::RemoveDevice requires Windows10 build 20348 or newer */ static gboolean check_remove_device_supported (void) { OSVERSIONINFOEXW osverinfo = { }; typedef NTSTATUS (WINAPI fRtlGetVersion) (PRTL_OSVERSIONINFOEXW); gboolean ret = FALSE; memset (&osverinfo, 0, sizeof (OSVERSIONINFOEXW)); osverinfo.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEXW); auto hmodule = LoadLibraryW (L"ntdll.dll"); if (!hmodule) return FALSE; auto RtlGetVersion = (fRtlGetVersion *) GetProcAddress (hmodule, "RtlGetVersion"); if (RtlGetVersion) { RtlGetVersion (&osverinfo); if (osverinfo.dwMajorVersion > 10 || (osverinfo.dwMajorVersion == 10 && osverinfo.dwBuildNumber >= 20348)) { ret = TRUE; } } FreeLibrary (hmodule); return ret; } static Suite * d3d12device_suite (void) { Suite *s = suite_create ("d3d12device"); TCase *tc_basic = tcase_create ("general"); suite_add_tcase (s, tc_basic); if (!check_d3d12_available ()) return s; tcase_add_test (tc_basic, test_device_equal); if (check_remove_device_supported ()) tcase_add_test (tc_basic, test_device_removed); return s; } GST_CHECK_MAIN (d3d12device);
import React from "react"; import { connect } from "react-redux"; import { Route, Redirect, withRouter } from "react-router"; const Auth = ({ component: Component, path, signedIn, exact }) => { return( <Route path={path} exact={exact} render={props => ( !signedIn ? <Component {...props}/> : <Redirect to='/feed'/> )} /> )} const Protected = ({ component: Component, path, signedIn, exact }) => { return( <Route path={path} exact={exact} render={props => ( signedIn ? <Component {...props} /> : <Redirect to="/" /> )} /> )}; const mSTP = state => ({ signedIn: Boolean(state.session.currentUserId) }) export const AuthRoute = withRouter(connect(mSTP)(Auth)) export const ProtectedRoute = withRouter(connect(mSTP)(Protected))
import { atom, selector, atomFamily, selectorFamily } from "recoil"; import _ from "lodash"; import data from "../data/data.json"; import { DropdownValue } from "../lib/types"; import { ProductRequest } from "../lib/types/index"; import { filterProductRequestByStatus, filterProductRequestByCategory, getCommentCount, } from "./utils"; const { currentUser, productRequests } = data; export const requestsAPI = atom({ key: "requestsAPI", default: productRequests, }); export const activeUser = atom({ key: "currentUser", default: currentUser, }); export const roadMapSelector = selector({ key: "roadMapSelector", get: ({ get }) => { const requests = get(requestsAPI); return filterProductRequestByStatus(requests); }, }); export const filterSelector = selector({ key: "filterSelector", get: ({ get }) => { const requests = get(requestsAPI); return filterProductRequestByCategory(requests); }, }); export const activeFiltersState = atom({ key: "activeFilters", default: ["all"], }); export const filteredRequests = selector({ key: "filteredRequests", get: ({ get }) => { const data = get(requestsAPI); const filters = get(activeFiltersState); const { value, orderBy } = get(sortByState); const filtered = filters[0] === "all" ? data : data.filter((el) => filters.includes(el.category)); const ouptut = getCommentCount(filtered); return _.orderBy(ouptut, [value], [orderBy]); }, }); export const sortByState = atom<DropdownValue>({ key: "sortBy", default: { label: "Most Upvotes", value: "upvotes", orderBy: "desc", }, }); export const requestItemState = atomFamily({ key: "requestItem", default: selectorFamily({ key: "requestItem/Default", get: (param: string | undefined) => ({ get }) => { if (!param) return null; const requests = get(requestsAPI); const filtered = requests.filter((el) => el.id === param)[0]; return filtered; }, }), }); export const toggleDrawerState = atom<boolean>({ key: "toggleDrawerState", default: false, }); export const replyToState = atom<{ username: string; commentId: string; }>({ key: "replyToState", default: { username: "", commentId: "", }, }); interface Upvotes { [key: string]: boolean; } export const clickedUpvoteState = atom<Upvotes>({ key: "clickedUpvoteState", default: {}, });
from flask import Blueprint, request, jsonify # Errors from src.utils.errors.CustomException import CustomException # Security from src.utils.Security import Security # Services from src.services import ProductoService main = Blueprint('producto_blueprint', __name__) @main.route('/', methods=['GET']) def get_productos(): try: productos = ProductoService.get_productos() if (len(productos) > 0): return jsonify([producto.to_json() for producto in productos]) else: return jsonify({'message': "NOTFOUND", 'success': True}) except CustomException: return jsonify({'message': "ERROR", 'success': False}) @main.route('/<int:id_producto>', methods=['GET']) def get_producto_unique(id_producto: int): try: producto = ProductoService.get_producto_unique(id_producto) if producto: return jsonify(producto.to_json()) else: return jsonify({'message': "NOTFOUND", 'success': True}) except CustomException: return jsonify({'message': "ERROR", 'success': False}) @main.route('/', methods=['POST']) @Security.custom_middleware(required_keys=['nombre', 'descripcion', 'precio', 'proveedores', 'cantidad']) def post_producto(): has_access = Security.verify_token(request.headers) if has_access: try: data = request.get_json() nombre = data.get('nombre') descripcion = data.get('descripcion') precio = data.get('precio') cantidad = data.get('cantidad') proveedores = data.get('proveedores', []) producto = ProductoService.post_producto(nombre = nombre, descripcion = descripcion, precio = precio, proveedores = proveedores, cantidad = cantidad) return jsonify(producto.to_json()), 201 except CustomException: return jsonify({'message': "ERROR", 'success': False}) else: response = jsonify({'message': 'Unauthorized'}) return response, 401 @main.route('/<int:id_producto>', methods=['PUT']) @Security.custom_middleware(required_keys=['nombre', 'descripcion', 'precio', 'proveedores', 'cantidad']) def put_producto(id_producto: int): has_access = Security.verify_token(request.headers) if has_access: try: data = request.get_json() nombre = data.get('nombre', None) descripcion = data.get('descripcion', None) precio = data.get('precio', None) proveedores = data.get('proveedores', None) cantidad = data.get('cantidad', None) producto = ProductoService.put_producto(id_producto, nombre, descripcion, precio, proveedores, cantidad) return jsonify(producto.to_json()), 201 except CustomException: return jsonify({'message': "ERROR", 'success': False}) else: response = jsonify({'message': 'Unauthorized'}) return response, 401 @main.route('/<int:id_producto>', methods = ['DELETE']) @Security.custom_middleware() def delete_producto(id_producto: int): has_access = Security.verify_token(request.headers) if has_access: try: ProductoService.delete_producto(id_producto) return jsonify({'message': "Producto borrado exitosamente"}), 200 except CustomException: return jsonify({'message': "ERROR", 'success': False}) else: response = jsonify({'message': 'Unauthorized'}) return response, 401
function sortear(){// Criando a função sortear let quantidade = parseInt(document.getElementById('quantidade').value); //recuperando os documentos o valor .value para transformar o campo em string let de = parseInt(document.getElementById('de').value);//e também o parseInt para converter a string para um número inteiro. let ate = parseInt(document.getElementById('ate').value); if (de >= ate) {// função para verificar se o valor de "de" é maior que o de "até" alert('Campo "Do número" deve ser inferior ao campo "Até o número". Verifique!'); limparCampos(); return; } if (quantidade > (ate - de + 1)) {// verifica se o número do intervalo se a quantidade é menor que até - de +1 para apresentar o erro de loop infinito alert('Campo "Quantidade" deve ser menor ou igual ao intervalo informado no campo "Do número" até o campo "Até o número". Verifique!'); limparCampos(); return; } let sorteados = []; // criando a lista let numero;// criando a variavel numero para receber o número aleatório for(let i = 0; i < quantidade; i++){ // criando a repetição para preencher a lista e recuperar os numeros. enquanto i for menor que a quantidade digitada, adicionar +1 numero = obterNumeroAleatorio(de, ate); // variavel que recebe a função que recebe o número aleatorio que vai das variaveis que são o mínimo e máximo. while(sorteados.includes(numero)){ numero = obterNumeroAleatorio(de, ate); } sorteados.push(numero); // a lista recebe o retorno do preenchimento da lista } let resultado = document.getElementById('resultado');//resultado recebe o que foi gerado no campo resultado alterarStatusBotao();// starta a função reiniciar criada abaixo para alterar o status do botão reinciciar. resultado.innerHTML = `<label class="texto__paragrafo">Números sorteados: ${sorteados}</label>`; } function obterNumeroAleatorio(min, max){ // Função para criar o número aleatório pesquisando na internet... google e documentação js return Math.floor(Math.random() * (max - min + 1)) + min; // Criando um número randomico para a função. } function alterarStatusBotao() {// Função para alterar o numero do botão. let botao = document.getElementById('btn-reiniciar');// Recebendo o botão do arquivo html if (botao.classList.contains('container__botao-desabilitado')) {// Caso, Botão contenha a string ('container botao desabilitado') botao.classList.remove('container__botao-desabilitado');//botao vai remover a desabilitação botao.classList.add('container__botao');//botão vai adicionar botão habilitado } else {//senao botao.classList.remove('container__botao');//botão vai remover botão habilitado botao.classList.add('container__botao-desabilitado');// botão vai adicionar botão desabilitado } } function reiniciar(){//função de limpar os campos limparCampos(); alterarStatusBotao();// alterar o status do botão para começar um novo jogo. } function limparCampos(){ document.getElementById('quantidade').value = '';// limpando os campos document.getElementById('de').value = ''; document.getElementById('ate').value = ''; document.getElementById('resultado').innerHTML = '<label class="texto__paragrafo">Números sorteados: nenhum até agora</label>';// reiniciar o texto inicial do campo de texto }
import React, { useMemo } from 'react'; import { Box } from '@chakra-ui/react'; import ReactMarkdown from 'react-markdown'; import RemarkGfm from 'remark-gfm'; import RemarkMath from 'remark-math'; import RehypeKatex from 'rehype-katex'; import { event } from '@/utils/plugin/eventbus'; import 'katex/dist/katex.min.css'; import styles from '../index.module.scss'; import Image from '../img/Image'; function Link(e: any) { const href = e.href; const text = String(e.children); return ( <Box as={'li'} py={1} m={0}> <Box as={'span'} color={'blue.600'} textDecoration={'underline'} cursor={'pointer'} onClick={() => { if (href) { return window.open(href, '_blank'); } event.emit('guideClick', { text }); }} > {text} </Box> </Box> ); } const Guide = ({ text }: { text: string }) => { const formatText = useMemo(() => text.replace(/\[(.*?)\]($|\n)/g, '[$1]()\n'), [text]); return ( <ReactMarkdown className={`markdown ${styles.markdown}`} remarkPlugins={[RemarkGfm, RemarkMath]} rehypePlugins={[RehypeKatex]} components={{ a: Link, img: Image }} > {formatText} </ReactMarkdown> ); }; export default React.memo(Guide);
// // MediaDetailsViewController.swift // YoungTalent // // Created by admin on 3.04.2023. // import AVFoundation import UIKit class MediaDetailsViewController: UIViewController { // MARK: - Properties @IBOutlet var imageView: UIImageView! @IBOutlet var backButton: UIButton! @IBOutlet var videoView: UIView! @IBOutlet var playerView: UIView! @IBOutlet var timeSlider: UISlider! @IBOutlet var playButton: UIButton! @IBOutlet var rewindButton: UIButton! @IBOutlet var fastForwardButton: UIButton! @IBOutlet var increaseSoundButton: UIButton! @IBOutlet var decreaseSoundButton: UIButton! @IBOutlet var videoTimeLabel: UILabel! @IBOutlet var videoControlStackView: UIStackView! @IBOutlet var videoDurationView: UIView! private var player: AVPlayer? private var playerLayer: AVPlayerLayer? var viewingMode: ViewingMode? private var isPlaying: Bool = false private lazy var videoSupplementaryViews: [UIView] = [ backButton, videoDurationView, videoControlStackView ] enum ViewingMode { case image case video } var index: Int = 0 var image: UIImage? // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() setupView() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() playerLayer?.frame = playerView.bounds } // MARK: - Handlers private func setupView() { guard let viewingMode else { displayError(title: "viewingMode found nil!", message: "") return } switch viewingMode { case .image: guard let image else { return } videoView.isHidden = true imageView.isHidden = false imageView.image = image case .video: imageView.isHidden = true videoView.isHidden = false setupVideoView() } } private func setupVideoView() { let tap = UITapGestureRecognizer(target: self, action: #selector(toggleSupplementaryViews)) view.addGestureRecognizer(tap) let videoURL = URL( fileURLWithPath: Bundle.main.path( forResource: "testVideo", ofType: "mp4" )! ) player = AVPlayer(url: videoURL) playerLayer = AVPlayerLayer(player: player) playerLayer?.videoGravity = .resize guard let playerLayer else { return } videoView.layer.addSublayer(playerLayer) let interval = CMTime(seconds: 0.5, preferredTimescale: CMTimeScale(NSEC_PER_SEC)) guard let current = player?.currentItem else { return } _ = player?.addPeriodicTimeObserver(forInterval: interval, queue: .main, using: { [weak self] _ in self?.timeSlider.maximumValue = Float(current.duration.seconds) self?.timeSlider.minimumValue = 0 self?.timeSlider.value = Float(current.currentTime().seconds) self?.videoTimeLabel.text = "\(current.currentTime().durationText) / \(current.duration.durationText)" }) NotificationCenter.default.addObserver( forName: .AVPlayerItemDidPlayToEndTime, object: current, queue: .main ) { [weak self] _ in self?.playButton.setTitle("Play", for: .normal) self?.isPlaying = false self?.player?.seek(to: .zero) } } @objc private func toggleSupplementaryViews() { videoSupplementaryViews.forEach { view in view.isHidden.toggle() } videoView.layoutIfNeeded() } @IBAction func backButtonPressed(_ sender: UIButton) { navigationController?.popViewController(animated: true) } @IBAction func playButtonPressed(_ sender: UIButton) { if isPlaying { player?.pause() } else { player?.play() } isPlaying.toggle() let buttonText = !isPlaying ? "Play" : "Pause" sender.setTitle(buttonText, for: .normal) } @IBAction func backForwardPressed(_ sender: UIButton) { guard let player, let videoDuration = player.currentItem?.duration else { return } let currentTime = CMTimeGetSeconds(player.currentTime()) let newTime = sender == fastForwardButton ? currentTime + 10 : currentTime - 10 if newTime < CMTimeGetSeconds(videoDuration) || newTime > 0 { let time = CMTimeMake( value: Int64(newTime * 1000), timescale: 1000 ) player.seek(to: time) } } @IBAction func timeSliderChangedValue(_ sender: UISlider) { player?.seek(to: CMTimeMake(value: Int64(sender.value * 1000), timescale: 1000)) } @IBAction func changeSoundPressed(_ sender: UIButton) { guard let player else { return } if sender == decreaseSoundButton, player.volume > 0 { player.volume -= 0.1 } else if sender == increaseSoundButton, player.volume < 1 { player.volume += 0.1 } print("Player Volume:", player.volume) } private func displayError(title: String, message: String) { presentAlert(title: title, message: message) navigationController?.popViewController(animated: true) } }
package com.itemapplication.application.Service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.itemapplication.application.Model.Item; import com.itemapplication.application.Repositiory.ItemRepository; import java.util.List; @Service public class ItemServiceMySQL implements ItemService { private final ItemRepository itemRepository; public ItemServiceMySQL( @Autowired ItemRepository itemRepository) { this.itemRepository = itemRepository; } @Override public Item save(Item item) { return itemRepository.save(item); } @Override public void delete(int itemId) { itemRepository.deleteById(itemId); } @Override public List<Item> all() { return (List<Item>) itemRepository.findAll(); } @Override public Item findById(int itemId) { return itemRepository.findById(itemId).orElse(null); } }
package org.jeecg.modules.valuable.entity; import java.io.Serializable; import java.util.Date; import java.math.BigDecimal; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableLogic; import lombok.Data; import com.fasterxml.jackson.annotation.JsonFormat; import org.springframework.format.annotation.DateTimeFormat; import org.jeecgframework.poi.excel.annotation.Excel; import org.jeecg.common.aspect.annotation.Dict; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * @Description: 阿里客户表 * @Author: jeecg-boot * @Date: 2024-01-19 * @Version: V1.0 */ @Data @TableName("val_alibaba_client") @Accessors(chain = true) @EqualsAndHashCode(callSuper = false) @ApiModel(value = "val_alibaba_client对象", description = "阿里客户表") public class ValAlibabaClient implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(type = IdType.ASSIGN_ID) @ApiModelProperty(value = "主键") private String id; /** * 创建人 */ @ApiModelProperty(value = "创建人") private String createBy; /** * 创建日期 */ @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @ApiModelProperty(value = "创建日期") private Date createTime; /** * 更新人 */ @ApiModelProperty(value = "更新人") private String updateBy; /** * 更新日期 */ @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @ApiModelProperty(value = "更新日期") private Date updateTime; /** * 平台账号 */ @Excel(name = "平台账号", width = 15) @ApiModelProperty(value = "平台账号") private String account; /** * 公司名称 */ @Excel(name = "公司名称", width = 15) @ApiModelProperty(value = "公司名称") private String name; /** * 一级行业 */ @Excel(name = "一级行业", width = 15) @ApiModelProperty(value = "一级行业") private String firstIndustry; /** * 二级行业 */ @Excel(name = "二级行业", width = 15) @ApiModelProperty(value = "二级行业") private String secondIndustry; /** * 三级行业 */ @Excel(name = "三级行业", width = 15) @ApiModelProperty(value = "三级行业") private String thirdIndustry; /** * 国际站网址 */ @Excel(name = "国际站网址", width = 15) @ApiModelProperty(value = "国际站网址") private String siteUrl; /** * 工贸类型 */ @Excel(name = "工贸类型", width = 15) @ApiModelProperty(value = "工贸类型") private String industryTradeType; /** * 联系人 */ @Excel(name = "联系人", width = 15) @ApiModelProperty(value = "联系人") private String contact; /** * 联系电话 */ @Excel(name = "联系电话", width = 15) @ApiModelProperty(value = "联系电话") private String phone; /** * 地址 */ @Excel(name = "地址", width = 15) @ApiModelProperty(value = "地址") private String address; /** * 区域 */ @Excel(name = "区域", width = 15) @ApiModelProperty(value = "区域") private String area; /** * 渠道类型 */ @Excel(name = "渠道类型", width = 15) @ApiModelProperty(value = "渠道类型") private String channelType; /** * 渠道名称 */ @Excel(name = "渠道名称", width = 15) @ApiModelProperty(value = "渠道名称") private String channelName; /** * 阿里会员服务类型:金品/出口通 */ @Excel(name = "阿里会员服务类型:金品/出口通", width = 15) @ApiModelProperty(value = "阿里会员服务类型:金品/出口通") private String serviceType; /** * 合同开始时间 */ @Excel(name = "合同开始时间", width = 15, format = "yyyy-MM-dd") @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd") @DateTimeFormat(pattern = "yyyy-MM-dd") @ApiModelProperty(value = "合同开始时间") private Date contractStart; /** * 合同结束时间 */ @Excel(name = "合同结束时间", width = 15, format = "yyyy-MM-dd") @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd") @DateTimeFormat(pattern = "yyyy-MM-dd") @ApiModelProperty(value = "合同结束时间") private Date contractEnd; /** * 年投入金额 */ @Excel(name = "年投入金额", width = 15) @ApiModelProperty(value = "年投入金额") private BigDecimal annualAmount; /** * 客户经理 */ @Excel(name = "客户经理", width = 15) @ApiModelProperty(value = "客户经理") private String manager; /** * 运营 */ @Excel(name = "运营", width = 15) @ApiModelProperty(value = "运营") private String operator; /** * 客户类型 */ @Excel(name = "客户类型", width = 15) @ApiModelProperty(value = "客户类型") private String clientType; /** * 业务类型 */ @Excel(name = "业务类型", width = 15) @ApiModelProperty(value = "业务类型") private String businessType; /** * 是否有人跟进,0-否,1-是 */ @Excel(name = "是否有人跟进,0-否,1-是", width = 15) @ApiModelProperty(value = "是否有人跟进,0-否,1-是") private Integer isFollow; /** * 是否为公海客户,0-否,1-是 */ @Excel(name = "是否为公海客户,0-否,1-是", width = 15) @ApiModelProperty(value = "是否为公海客户,0-否,1-是") private Integer isPublic; /** * 是否为业务员添加,0-否,1-是 */ @Excel(name = "是否为业务员添加,0-否,1-是", width = 15) @ApiModelProperty(value = "是否为业务员添加,0-否,1-是") private Integer isPrivate; /** * 逻辑删除,0-否,1-是 */ @Excel(name = "逻辑删除,0-否,1-是", width = 15) @ApiModelProperty(value = "逻辑删除,0-否,1-是") @TableLogic private Integer delFlag; }
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/customer-profiles/CustomerProfiles_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/customer-profiles/model/SourceConnectorType.h> #include <aws/customer-profiles/model/IncrementalPullConfig.h> #include <aws/customer-profiles/model/SourceConnectorProperties.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace CustomerProfiles { namespace Model { class AWS_CUSTOMERPROFILES_API SourceFlowConfig { public: SourceFlowConfig(); SourceFlowConfig(Aws::Utils::Json::JsonView jsonValue); SourceFlowConfig& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; inline const Aws::String& GetConnectorProfileName() const{ return m_connectorProfileName; } inline bool ConnectorProfileNameHasBeenSet() const { return m_connectorProfileNameHasBeenSet; } inline void SetConnectorProfileName(const Aws::String& value) { m_connectorProfileNameHasBeenSet = true; m_connectorProfileName = value; } inline void SetConnectorProfileName(Aws::String&& value) { m_connectorProfileNameHasBeenSet = true; m_connectorProfileName = std::move(value); } inline void SetConnectorProfileName(const char* value) { m_connectorProfileNameHasBeenSet = true; m_connectorProfileName.assign(value); } inline SourceFlowConfig& WithConnectorProfileName(const Aws::String& value) { SetConnectorProfileName(value); return *this;} inline SourceFlowConfig& WithConnectorProfileName(Aws::String&& value) { SetConnectorProfileName(std::move(value)); return *this;} inline SourceFlowConfig& WithConnectorProfileName(const char* value) { SetConnectorProfileName(value); return *this;} inline const SourceConnectorType& GetConnectorType() const{ return m_connectorType; } inline bool ConnectorTypeHasBeenSet() const { return m_connectorTypeHasBeenSet; } inline void SetConnectorType(const SourceConnectorType& value) { m_connectorTypeHasBeenSet = true; m_connectorType = value; } inline void SetConnectorType(SourceConnectorType&& value) { m_connectorTypeHasBeenSet = true; m_connectorType = std::move(value); } inline SourceFlowConfig& WithConnectorType(const SourceConnectorType& value) { SetConnectorType(value); return *this;} inline SourceFlowConfig& WithConnectorType(SourceConnectorType&& value) { SetConnectorType(std::move(value)); return *this;} inline const IncrementalPullConfig& GetIncrementalPullConfig() const{ return m_incrementalPullConfig; } inline bool IncrementalPullConfigHasBeenSet() const { return m_incrementalPullConfigHasBeenSet; } inline void SetIncrementalPullConfig(const IncrementalPullConfig& value) { m_incrementalPullConfigHasBeenSet = true; m_incrementalPullConfig = value; } inline void SetIncrementalPullConfig(IncrementalPullConfig&& value) { m_incrementalPullConfigHasBeenSet = true; m_incrementalPullConfig = std::move(value); } inline SourceFlowConfig& WithIncrementalPullConfig(const IncrementalPullConfig& value) { SetIncrementalPullConfig(value); return *this;} inline SourceFlowConfig& WithIncrementalPullConfig(IncrementalPullConfig&& value) { SetIncrementalPullConfig(std::move(value)); return *this;} inline const SourceConnectorProperties& GetSourceConnectorProperties() const{ return m_sourceConnectorProperties; } inline bool SourceConnectorPropertiesHasBeenSet() const { return m_sourceConnectorPropertiesHasBeenSet; } inline void SetSourceConnectorProperties(const SourceConnectorProperties& value) { m_sourceConnectorPropertiesHasBeenSet = true; m_sourceConnectorProperties = value; } inline void SetSourceConnectorProperties(SourceConnectorProperties&& value) { m_sourceConnectorPropertiesHasBeenSet = true; m_sourceConnectorProperties = std::move(value); } inline SourceFlowConfig& WithSourceConnectorProperties(const SourceConnectorProperties& value) { SetSourceConnectorProperties(value); return *this;} inline SourceFlowConfig& WithSourceConnectorProperties(SourceConnectorProperties&& value) { SetSourceConnectorProperties(std::move(value)); return *this;} private: Aws::String m_connectorProfileName; bool m_connectorProfileNameHasBeenSet; SourceConnectorType m_connectorType; bool m_connectorTypeHasBeenSet; IncrementalPullConfig m_incrementalPullConfig; bool m_incrementalPullConfigHasBeenSet; SourceConnectorProperties m_sourceConnectorProperties; bool m_sourceConnectorPropertiesHasBeenSet; }; } // namespace Model } // namespace CustomerProfiles } // namespace Aws
<?php /** * @file * Theme functions for the Elearning module. */ /** * Implements theme_HOOK(). * * Theme function for the answer field table. */ function theme_elearning_question_field_form_table($variables) { $element = $variables['element']; $delta = $element['#delta']; $columns = $element['#table_columns']; $row_count = count(element_children($element['key'])); $header = $columns; $rows = array(); for ($i = 0; $i < $row_count; $i++) { $array = array(); foreach ($header as $column => $column_name) { $array[] = array('data' => $element[$column][$i]); } $rows[] = $array; } $return = theme('table', array('header' => $header, 'rows' => $rows)); $return .= render($element['add_row']); $return .= render($element['remove_row']); return $return; } /** * Implements theme_HOOK(). */ function theme_elearning_progress($variables) { $progress = $variables['progress']; $result = $variables['result']; if ($result && $result->status != ELEARNING_STATUS_UNSTARTED) { if ($progress >= 1): $message = t('Completed!'); else: $message = t('@percentage complete', array('@percentage' => (round($progress * 100)) . '%')); endif; $output = '<div class="progress">'; $output .= $message; $output .= '<div class="progress-bar-wrapper"> <div class="progress-bar" style="width:' . $progress * 100 . '%"> </div> </div> </div>'; return $output; } } /** * Implements theme_HOOK(). */ function theme_elearning_score($variables) { $score = $variables['score']; $status = $variables['status']; return "<div class='score $status'><div class='inner'>" . round($score * 100) . "%</div></div>"; }
"use client"; /* -------------------------------------------------------------------------- */ /* External Dependency */ /* -------------------------------------------------------------------------- */ import { type ReactElement } from "react"; import type * as z from "zod"; import { Controller, type SubmitHandler, type UseFormReturn, } from "react-hook-form"; import { Button, Input } from "pakt-ui"; /* -------------------------------------------------------------------------- */ /* Internal Dependency */ /* -------------------------------------------------------------------------- */ import { Spinner } from "../../common"; import { useUpdateAccount } from "@/lib/api/account"; import { type editProfileFormSchema } from "@/lib/validations"; import ProfessionalInfo from "../../settings/profile/professional-info"; import DeleteAccount from "../../settings/profile/delete-account"; import CountryDropdown from "./dropdowns/countries"; import StateDropdown from "./dropdowns/states"; type EditProfileFormValues = z.infer<typeof editProfileFormSchema>; interface FormProps { form: UseFormReturn<EditProfileFormValues>; updateAccountFunc: (values: EditProfileFormValues) => void; } const ProfileForm = ({ form, updateAccountFunc }: FormProps): ReactElement => { const updateAccount = useUpdateAccount(); const loading = updateAccount.isLoading || form.formState.isLoading; const onSubmit: SubmitHandler<EditProfileFormValues> = (values) => { updateAccountFunc(values); }; // Get country form value const countryValue = form.watch("country"); return ( <form className="flex min-h-full w-4/5 flex-col overflow-y-auto" onSubmit={form.handleSubmit(onSubmit)} > <div className="mb-4 rounded-lg bg-white p-4"> <div className="mb-4 flex h-[50px] flex-row items-center justify-between"> <p className="text-lg font-bold text-title"> Edit Profile Details </p> <Button title="Save Changes" variant="secondary" size="xs" type="submit" className="min-h-[37px] min-w-[132px]" > {loading ? <Spinner size={18} /> : "Save Changes"} </Button> </div> <div className="flex"> <div className="relative mx-auto mb-8 flex w-full flex-col gap-6"> <div id="input-row" className="flex w-full flex-row justify-between gap-4" > <div className="relative w-1/2"> <Input {...form.register("firstName")} className="w-full !border-[#E8E8E8] !bg-[#FCFCFD]" placeholder="enter first name" label="First Name" /> <span className="absolute -bottom-6 flex w-full"> {form.formState.errors.firstName ?.message && ( <span className="text-sm text-red-500"> { form.formState.errors.firstName ?.message } </span> )} </span> </div> <div className="relative w-1/2"> <Input {...form.register("lastName")} className="w-full !border-[#E8E8E8] !bg-[#FCFCFD]" placeholder="enter last name" label="Last Name" /> <span className="absolute -bottom-6 flex w-full"> {form.formState.errors.lastName ?.message && ( <span className="text-sm text-red-500"> { form.formState.errors.lastName ?.message } </span> )} </span> </div> </div> <div id="input-row" className="flex w-full flex-row justify-between gap-4" > <div className="relative w-1/2"> <Input {...form.register("title")} className="w-full !border-[#E8E8E8] !bg-[#FCFCFD]" placeholder="e.g Developer" label="Job Title" /> <span className="absolute -bottom-6 flex w-full"> {form.formState.errors.title?.message && ( <span className="text-sm text-red-500"> { form.formState.errors.title ?.message } </span> )} </span> </div> <div className="relative w-1/2"> <Input {...form.register("email")} className="w-full !border-[#E8E8E8] !bg-[#FCFCFD]" placeholder="Email Address" label="Email Address" readOnly /> <span className="absolute -bottom-6 flex w-full"> {form.formState.errors.email?.message && ( <span className="text-sm text-red-500"> { form.formState.errors.email ?.message } </span> )} </span> </div> </div> <div id="input-row" className="flex w-full flex-row justify-between gap-4" > <div className="relative w-1/2"> <Controller name="country" control={form.control} render={({ field: { onChange, value }, }) => { return ( <div className="flex w-full flex-col gap-2"> <label>Country</label> <CountryDropdown onChange={onChange} value={value} /> </div> ); }} /> <span className="absolute -bottom-6 flex w-full"> {form.formState.errors.country?.message && ( <span className="text-sm text-red-500"> { form.formState.errors.country ?.message } </span> )} </span> </div> <div className="relative w-1/2"> <Controller name="location" control={form.control} render={({ field: { onChange, value }, }) => { return ( <div className="flex w-full flex-col gap-2"> <label>Region</label> <StateDropdown onChange={onChange} value={value} countryValue={countryValue} /> </div> ); }} /> <span className="absolute -bottom-6 flex w-full"> {form.formState.errors.location ?.message && ( <span className="text-sm text-red-500"> { form.formState.errors.location ?.message } </span> )} </span> </div> </div> </div> </div> </div> <ProfessionalInfo form={form} /> <DeleteAccount /> </form> ); }; export default ProfileForm;
#include <stdio.h> #include <stdlib.h> struct Student { int rollNumber; char name[50]; float marks; }; int main() { int numStudents; printf("Enter the number of students: "); scanf("%d", &numStudents); struct Student *students = (struct Student *)malloc(numStudents * sizeof(struct Student)); if (students == NULL) { printf("Memory allocation failed. Exiting the program.\n"); return 1; } printf("Enter the details of students:\n"); for (int i = 0; i < numStudents; i++) { printf("Student %d:\n", i + 1); printf("Roll Number: "); scanf("%d", &(students[i].rollNumber)); printf("Name: "); scanf("%s", students[i].name); printf("Marks: "); scanf("%f", &(students[i].marks)); } printf("\nStudent Details:\n"); printf("---------------------------------------------------------\n"); printf("| %-10s | %-20s | %-10s |\n", "Roll No", "Name", "Marks"); printf("---------------------------------------------------------\n"); for (int i = 0; i < numStudents; i++) { printf("| %-10d | %-20s | %-10.2f |\n", students[i].rollNumber, students[i].name, students[i].marks); } printf("---------------------------------------------------------\n"); free(students); return 0; }
import React from "react"; interface PostSchema { id: number; title: string; body: string; } interface postArr { posts: PostSchema[]; } const Posts = ({ posts }: postArr) => { return ( <div className="grid grid-cols-4 gap-5"> {posts.map((post) => ( <div className="bg-gray-100 p-5 rounded" key={post.id}> <h5 className="text-xl font-bold ">{post.title}</h5> <p>{post.body}</p> </div> ))} </div> ); }; export default Posts;
import React from 'react'; import { Table, Alert } from 'antd'; import { connect } from 'dva'; import PropTypes from 'prop-types'; import consts from '../../config/const.js'; import { changePagination, decimalTo4, decimalTo2, taxRateFormater } from '../../utils/util.js'; import packageConst from './packageConst.js'; function DataTable({ dispatch, list, loading, selectedRowKeysArr, total, queryParams, }) { const tdWidth = { width: 80 }; const columns = [ { title: '过账时间', key: 'createDate', dataIndex: 'createDate', width: 160, }, { title: '法人主体', key: 'legalEntityName', dataIndex: 'legalEntityName', width: 150, }, { title: '核销单号', key: 'certificationOrderId', dataIndex: 'certificationOrderId', width: 200, }, { title: '部门', key: 'departmentName', dataIndex: 'departmentName', width: 250, }, { title: '成本中心', key: 'departmentGroupName', dataIndex: 'departmentGroupName', width: 100, }, { title: '调拨单号', key: 'allotOrderId', dataIndex: 'allotOrderId', ...tdWidth, }, { title: '在途仓', key: 'transitWarehouseName', dataIndex: 'transitWarehouseName', ...tdWidth, }, { title: '账号', key: 'amazonAccountId', dataIndex: 'amazonAccountId', ...tdWidth, }, { title: '大区', key: 'amazonAccountName', dataIndex: 'amazonAccountName', width: 110, }, { title: 'shipmentID', key: 'shipmentId', dataIndex: 'shipmentId', width: 130, }, { title: 'FNSKU', key: 'fnsku', dataIndex: 'fnsku', width: 150, }, { title: 'SKU', key: 'sku', dataIndex: 'sku', width: 110, }, { title: 'UPC', key: 'upc', dataIndex: 'upc', width: 130, }, { title: '核销数量', key: 'certificationQuantity', dataIndex: 'certificationQuantity', width: 150, }, { title: '核销金额', key: 'certificationAmount', dataIndex: 'certificationAmount', width: 100, }, { title: '核销状态', key: 'certificationStatusId', dataIndex: 'certificationStatusId', ...tdWidth, render: (value) => { if (!value) { return '' }; let result = ''; switch (value) { case 1: result = '待核销'; break; case 2: result = '审核拒绝'; break; case 3: result = '审核同意'; break; case 4: result = '已过账'; break; default: result = value; } return result; }, }, { title: '申请人', key: 'createUserName', dataIndex: 'createUserName', width: 150, }, { title: '审核人', key: 'auditUserName', dataIndex: 'auditUserName', ...tdWidth, }, { title: '过账人', key: 'closeUserName', dataIndex: 'closeUserName', ...tdWidth, }]; const onSelectChange = (selectedRowKeys, selectedRows) => { dispatch({ type: `${packageConst.modelNameSapce}/selectedRowKeys`, payload: selectedRowKeys }); dispatch({ type: `${packageConst.modelNameSapce}/selectedRows`, payload: selectedRows }); }; const rowSelection = { selectedRowKeys: selectedRowKeysArr, onChange: onSelectChange, getCheckboxProps: record => ({ disabled: record.createDate === '本页合计' || record.createDate === '全部合计', name: record.name, }), }; const changePaginationHandle = (page, pageSize) => { changePagination(page, pageSize, dispatch, `${packageConst.modelNameSapce}`, queryParams); }; const pageSizeChangeHandle = (current, size) => { // dispatch({ type: `${packageConst.modelNameSapce}/tableData`, payload: { offset: 0, limit: size } }); changePagination(current, size, dispatch, `${packageConst.modelNameSapce}`, queryParams); }; return ( <div> <Alert message={`已选择${selectedRowKeysArr.length}项`} type="info" showIcon style={{ marginTop: '10px' }} /> <Table columns={columns} // dataSource={list} dataSource={list} // bordered // table必须有key属性,可以将设置id为key rowKey="id" rowSelection={rowSelection} loading={loading} className="nestedTable" style={{ marginTop: '20px' }} scroll={Object.assign(consts.globalTableScroll, { x: 3100 })} pagination={{ total, defaultPageSize: consts.defaultPageSize, pageSizeOptions: consts.pageSizeOptions, showSizeChanger: true, hideOnSinglePage: false, onChange: changePaginationHandle, onShowSizeChange: pageSizeChangeHandle, showTotal: () => (consts.GlobalShowTotal(total)), }} /> </div> ); } DataTable.PropTypes = { queryParams: PropTypes.object, }; export default connect()(DataTable);
<!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>html_020_form</title> <style> div { width: 600px; margin-top: 10px; } table, td, th { border: 1px solid black; } table { width: 600px; } caption { text-align: left; font-weight: bolder; margin-bottom: 10px; } </style> </head> <body> <form action="#" method="get"> <table> <caption> 기본정보 입력 </caption> <tbody> <tr> <td>이름</td> <td><input type="text" /></td> </tr> <tr> <td>아이디</td> <td> <input type="text" />&nbsp;<input type="button" value="중복체크" onclick="idck('이미 사용중인 아이디 입니다.')" /> </td> </tr> <tr> <td>비밀번호</td> <td><input type="password" /></td> </tr> <tr> <td>비밀번호확인</td> <td><input type="password" /></td> </tr> <tr> <td>이메일</td> <td> <input type="text" />@ <select name="g_email"> <option>선택해주세요</option> <option value="naver.com">naver.com</option> <option value="daum.net">daum.net</option> <option value="nate.com">nate.com</option> <input type="text" /> </select> </td> </tr> <tr> <td>연락처</td> <td><input type="text" /></td> </tr> <tr> <td>메일수신여부</td> <td> <input type="radio" name="email" value="ok" /> 받음 <input type="radio" name="email" value="no" /> 받지않음 </td> </tr> <tr> <td>관심분야</td> <td> <input type="checkbox" name="group" value="java" /> 자바 <input type="checkbox" name="group" value="c++" /> C++ <input type="checkbox" name="group" value="phython" /> 파이썬 <input type="checkbox" name="group" value="android" /> 안드로이드 </td> </tr> </tbody> </table> <br /> <div> <input type="reset" value="취소" onclick="alert('취소되었습니다.')" /> <input type="submit" value="저장" onclick="alert('저장되었습니다.')" /> </div> </form> </body> </html>
import { Inject, Injectable, Logger, NotFoundException, forwardRef } from '@nestjs/common'; import * as bcrypt from 'bcrypt'; import { UserEntity } from './entity/user.entity'; import { UserRepository } from './repository/user.repository'; import { CreateUserDto } from './dto/create-user.dto'; import { UserRankingDto } from './dto/user-ranking.dto'; import { UpdateUserActivityByIdDto, UpdateUserActivityByNameDto, } from './dto/update-user-activity.dto'; import { ErrorMessage } from 'src/common/enum/error-message.enum'; import { RotationsService } from '../rotation/rotations.service'; @Injectable() export class UserService { private readonly logger = new Logger(UserService.name); constructor( private readonly userRepository: UserRepository, @Inject(forwardRef(() => RotationsService)) private readonly rotationsService: RotationsService, ) {} async findOneByEmail(email: string): Promise<UserEntity | null> { this.logger.debug(`findOneByEmail [email: ${email}]`); return this.userRepository.findOneByEmail(email); } async findOneByUid(id: number): Promise<UserEntity | null> { this.logger.debug(`findOneByUid [id: ${id}]`); return this.userRepository.findOneById(id); } async findOneById(id: number): Promise<UserEntity | null> { this.logger.debug(`findOneById [id: ${id}]`); return await this.userRepository.findOneById(id); } async findOneByIntraId(intraId: string): Promise<UserEntity | null> { this.logger.debug(`findOneByIntraId [intraId: ${intraId}]`); return await this.userRepository.findOneByIntraId(intraId); } async createUser(user: CreateUserDto): Promise<UserEntity> { return this.userRepository.createUser(user); } async getAllActiveUser(): Promise<UserEntity[]> { return await this.userRepository.getAllActiveUser(); } /* find refresh token from database with user id if refresh token is not expired, return refresh token */ async isRefreshTokenVaild(refreshToken: string, userUid: number): Promise<UserEntity | null> { const user: UserEntity | null = await this.findOneByUid(userUid); if (user === null || user.refreshToken === null) { return null; } const isRefreshTokenValid: boolean = await bcrypt.compare(refreshToken, user.refreshToken); if (isRefreshTokenValid === false) { return null; } return user; } async updateRefreshToken(userUid: number, refreshToken: string): Promise<void> { const hashedRefreshToken: string = await this.hashedRefreshToken(refreshToken); const currentDate: Date = new Date(); const refreshTokenExpiredAt: Date = new Date(currentDate.getTime() + 1000 * 60 * 60 * 24 * 7); await this.userRepository.updateRefreshToken( userUid, hashedRefreshToken, refreshTokenExpiredAt, ); } async deleteRefreshToken(userUid: number): Promise<void> { await this.userRepository.deleteRefreshToken(userUid); } private async hashedRefreshToken(refreshToken: string): Promise<string> { const saltRounds = 10; try { const hashedRefreshToken: string = await bcrypt.hash(refreshToken, saltRounds); return hashedRefreshToken; } catch (error) { this.logger.error(`hashedRefreshToken [error: ${error.message}]`); throw error; } } async getUserRanking() { // TODO: 쿼리빌더가 타입 반환을 any로 반환하는 것을 해결하기 const userRanking = await this.userRepository.getUserRanking(); const userRankingDto: UserRankingDto[] = userRanking.map((ranking) => { return { ...ranking, meetingPoint: +ranking.meetingPoint, eventPoint: +ranking.eventPoint, totalPoint: +ranking.totalPoint, }; }); return userRankingDto; } async updateUserActivity( updateUserActiviyDto: UpdateUserActivityByIdDto | UpdateUserActivityByNameDto, ) { let user: UserEntity; const { isActive } = updateUserActiviyDto; if ('userId' in updateUserActiviyDto) { user = await this.userRepository.findOneById(updateUserActiviyDto.userId); } else if ('nickname' in updateUserActiviyDto) { user = await this.userRepository.findOneByIntraId(updateUserActiviyDto.nickname); } if (!user) { throw new NotFoundException(ErrorMessage.USER_NOT_FOUND); } await this.userRepository.updateUserActivity(user.id, isActive); if (isActive) { const rotationAttendee = await this.rotationsService.findRotationAttendeeByUserId(user.id); if (!rotationAttendee) { await this.rotationsService.createRegistration({ attendLimit: JSON.parse('[]') }, user.id); } } else { await this.rotationsService.removeRegistration(user.id); } return 'hi'; } }
<template> <DatePicker v-model="internalValue" :time-picker="timePickerProp" :enable-time-picker="enableTimePickerProp" :range="rangeProp" :week-picker="weekPickerProp" :month-picker="monthPickerProp" :year-picker="yearPickerProp" :locale="locale" text-input :enable-seconds="enableSeconds" :format="formatDateLabel" :partial-range="false" :placeholder="placeholder" :disabled="disabled" class="date-input" :class="{ 'has-error': hasError }" :month-change-on-scroll="false" :clearable="nullable" :auto-apply="autoApply" :name="name" :week-numbers="weekNumbers" :select-text="chooseLabel" :cancel-text="cancelLabel" :month-name-format="longMonthNames ? 'long' : 'short'" > <template #input-icon> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="ml-2.5 w-5 h-5"> <path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5" /> </svg> </template> <!--<template #clear-icon="{ clear }">--> <!-- <button @click.prevent="clear">--> <!-- <svg class="w-5 h-5 mr-2 mt-1 text-danger-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">--> <!-- <path fill-rule="evenodd" d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25zm-1.72 6.97a.75.75 0 10-1.06 1.06L10.94 12l-1.72 1.72a.75.75 0 101.06 1.06L12 13.06l1.72 1.72a.75.75 0 101.06-1.06L13.06 12l1.72-1.72a.75.75 0 10-1.06-1.06L12 10.94l-1.72-1.72z" clip-rule="evenodd" />--> <!-- </svg>--> <!-- </button>--> <!--</template>--> <template #arrow-left> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6"> <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" /> </svg> </template> <template #arrow-right> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6"> <path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" /> </svg> </template> <template #clock-icon> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6"> <path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> </template> <template #calendar-icon> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6"> <path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5m-9-6h.008v.008H12v-.008zM12 15h.008v.008H12V15zm0 2.25h.008v.008H12v-.008zM9.75 15h.008v.008H9.75V15zm0 2.25h.008v.008H9.75v-.008zM7.5 15h.008v.008H7.5V15zm0 2.25h.008v.008H7.5v-.008zm6.75-4.5h.008v.008h-.008v-.008zm0 2.25h.008v.008h-.008V15zm0 2.25h.008v.008h-.008v-.008zm2.25-4.5h.008v.008H16.5v-.008zm0 2.25h.008v.008H16.5V15z" /> </svg> </template> <template #arrow-up> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6"> <path stroke-linecap="round" stroke-linejoin="round" d="M4.5 15.75l7.5-7.5 7.5 7.5" /> </svg> </template> <template #arrow-down> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6"> <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" /> </svg> </template> </DatePicker> <InputError :error="error" /> </template> <script setup lang="ts"> import { computed, ref, watch } from "vue" import InputError from "./InputError.vue" import DatePicker from '@vuepic/vue-datepicker' import { format, getHours, getMinutes, getMonth, getSeconds, getYear, parse, setHours, setMinutes, setMonth, setSeconds, setYear } from "date-fns"; type Mode = 'date' | 'datetime' | 'time' | 'daterange' | 'datetimerange' | 'timerange' | 'week' | 'month' | 'year' | 'monthrange' | 'yearrange' type TimeStruct = { hours: number, minutes: number, seconds: number } type MonthStruct = { month: number, year: number } const emit = defineEmits(['change', 'update:modelValue']) const props = withDefaults(defineProps<{ name?: string error?: string modelValue?: string|Array<string>|number locale: string mode: Mode enableSeconds?: boolean placeholder: string disabled?: boolean nullable: boolean autoApply: boolean weekNumbers: boolean chooseLabel: string cancelLabel: string longMonthNames: boolean }>(), { mode: 'date', locale: 'en-US', placeholder: 'Select date…', nullable: true, autoApply: true, weekNumbers: false, chooseLabel: 'Choose', cancelLabel: 'Cancel', longMonthNames: true }) const timePickerProp = computed(() => props.mode == 'time' || props.mode == 'timerange' ? true : undefined ) const enableTimePickerProp = computed(() => props.mode == 'date' || props.mode == 'daterange' ? false : undefined ) // mode == 'time' ? undefined : mode == 'datetime' const rangeProp = computed(() => props.mode == 'monthrange' || props.mode == 'yearrange' || props.mode == 'daterange' || props.mode == 'datetimerange' || props.mode == 'timerange' || undefined) const weekPickerProp = computed(() => props.mode == 'week' || undefined) const monthPickerProp = computed(() => props.mode == 'month' || props.mode == 'monthrange' || undefined) const yearPickerProp = computed(() => props.mode == 'year' || props.mode == 'yearrange' || undefined) const hasError = computed(() => !!props.error) const resolveFormattingLabel = (configurations: Record<Mode, string|undefined> ) => { return configurations[props.mode] } const enableSeconds = computed(() => !!props.enableSeconds) const formatDateLabel = computed(() => resolveFormattingLabel({ date: 'dd.MM.yyyy', datetime: enableSeconds.value ? 'dd.MM.yyyy HH:mm:ss' : 'dd.MM.yyyy HH:mm', daterange: 'dd.MM.yyyy', month: undefined, time: undefined, datetimerange: enableSeconds.value ? 'dd.MM.yyyy HH:mm:ss' : 'dd.MM.yyyy HH:mm', monthrange: undefined, week: 'dd.MM.yyyy', year: undefined, timerange: undefined, yearrange: undefined, })) const resolveFormattingToken = () => { const tokens: Record<Mode, string> = { date: 'yyyy-MM-dd', datetime: enableSeconds.value ? 'yyyy-MM-dd HH:mm:ss' : 'yyyy-MM-dd HH:mm', daterange: 'yyyy-MM-dd', month: 'yyyy-MM', time: enableSeconds.value ? 'HH:mm:ss' : 'HH:mm', datetimerange: enableSeconds.value ? 'yyyy-MM-dd HH:mm:ss' : 'yyyy-MM-dd HH:mm', monthrange: 'yyyy-MM', week: 'yyyy-MM-dd', year: '', timerange: enableSeconds.value ? 'HH:mm:ss' : 'HH:mm', yearrange: '', } return tokens[props.mode] } const formatTime = (time: TimeStruct) => { let date = new Date() date = setHours(date, time.hours) date = setMinutes(date, time.minutes) date = setSeconds(date, time.seconds) return format(date, resolveFormattingToken()) } const resolveTimeStructFromDateObject = (date: Date) => { if (props.enableSeconds) { return { hours: getHours(date), minutes: getMinutes(date), seconds: getSeconds(date) } } else { return { hours: getHours(date), minutes: getMinutes(date), seconds: 0 } } } const formatMonth = (month: MonthStruct) => { let date = new Date() date = setYear(date, month.year) date = setMonth(date, month.month) return format(date, resolveFormattingToken()) } const resolveMonthStructFromDateObject = (date: Date) => { return { month: getMonth(date), year: getYear(date) } } const resolveSelectedValue = (value: null|undefined|number|Date|Array<Date>|TimeStruct|MonthStruct) => { if (value === null || value === undefined) { return null } if (typeof value == 'number' || props.mode == 'year') { return value } else if (value instanceof Date) { return format(value, resolveFormattingToken()) } else if (Array.isArray(value)) { return value.map(it => { if (typeof it == 'number' && props.mode == 'yearrange') { return it } else if (it instanceof Date) { return format(it, resolveFormattingToken()) } else if (props.mode == 'timerange') { return formatTime(it as any) } else if (props.mode == 'monthrange') { return formatMonth(it as any) } else { return null } }) } else if (typeof value == 'object') { if (props.mode == 'time') { return formatTime(value as TimeStruct) } if (props.mode == 'month') { return formatMonth(value as MonthStruct) } } throw new Error("The format of the value could not be resolved.") } const resolveInternalValue = (value: null|undefined|string|number|Array<string>) => { if (value === null || value === undefined) { return null } if (typeof value == 'number') { if (props.mode == 'year') { return value } } else if (typeof value == 'string') { if (props.mode == 'date') { return parse(value, 'yyyy-MM-dd', new Date()) } else if (props.mode == 'datetime') { return parse(value, props.enableSeconds ? 'yyyy-MM-dd HH:mm:ss' : 'yyyy-MM-dd HH:mm' , new Date()) } else if (props.mode == 'time') { return resolveTimeStructFromDateObject(parse(value, props.enableSeconds ? 'HH:mm:ss' : 'HH:mm', new Date())) } else if (props.mode == 'month') { return resolveMonthStructFromDateObject(parse(value, 'yyyy-MM', new Date())) } } else if (Array.isArray(value) && value.length == 2) { return value.map(it => { if (props.mode == 'daterange') { return parse(it, 'yyyy-MM-dd', new Date()) } else if (props.mode == 'datetimerange') { return parse(it, props.enableSeconds ? 'yyyy-MM-dd HH:mm:ss' : 'yyyy-MM-dd HH:mm', new Date()) } else if (props.mode == 'timerange') { return resolveTimeStructFromDateObject(parse(it, props.enableSeconds ? 'HH:mm:ss' : 'HH:mm', new Date())) } else if (props.mode == 'week') { return parse(it, 'yyyy-MM-dd', new Date()) } else if (props.mode == 'monthrange') { return resolveMonthStructFromDateObject(parse(it, 'yyyy-MM', new Date())) } else if (typeof it == 'number' && props.mode == 'yearrange') { return it } }) } throw new Error("The v-model value is invalid.") } const internalValue = ref<any>(resolveInternalValue(props.modelValue)) watch(internalValue, value => { emit('change', resolveSelectedValue(value as any)) emit('update:modelValue', resolveSelectedValue(value as any)) }) watch(props, newProps => { if (JSON.stringify(resolveInternalValue(newProps.modelValue)) != JSON.stringify(internalValue.value)) { internalValue.value = resolveInternalValue(props.modelValue) } }) </script>
import 'dotenv/config' interface BotConfiguration { twitterConfig: { appKey: string, appSecret: string, }, deletePosted: boolean, postTitle: boolean, titlePrefix: string, timeout: string, } /** * Retrieve an environment variable and throw an error if the variable is unset * @param name the name of the variable * @returns the value stored in that env var */ const getEnv = (name: string): string => { const value = process.env[name] if (!value) throw `Environment Variable "${name}" is unset!` return value } /** * Load the configuration from the environment file * * @returns */ const createConfig = (): BotConfiguration => { return { twitterConfig: { appKey: getEnv("TWITTER_BOT_APP_KEY"), appSecret: getEnv("TWITTER_BOT_APP_SECRET"), }, deletePosted: getEnv("TWITTER_BOT_DELETE_POSTED").toUpperCase() == "TRUE", postTitle: getEnv("TWITTER_BOT_POST_TITLE").toUpperCase() == "TRUE", titlePrefix: getEnv("TWITTER_BOT_TITLE_PREFIX"), timeout: getEnv("TWITTER_BOT_CRONTAB") } } let config: BotConfiguration /** * Only load the configuration once * @returns the bot's configuration */ const getConfig = () => { if (!config) { config = createConfig() } return config } export default getConfig
<script setup> import { ref, onMounted } from 'vue'; import { timer, setActive, checkActive } from '../slider.js'; let testimonials = ref([ { name: "faith", word: "perfect hotel to stay" }, { name: "bandolo", word: "perfect ito stay" } ]); let active = ref(0); let weird = null; function check(index){ return checkActive(index, active); } function setA(index){ weird = setActive(index, active, weird, testimonials); } onMounted(()=>{ weird = timer(active, testimonials); }); </script> <template> <section class="testimonial"> <img src="../assets/back2.jpeg" class="testimonial__image" alt=""> <div class="testimonial__texts"> <p class="testimonial__texts-header">WHAT THE CLIENT SAYS</p> <!-- <p class="testimonial__texts-normal">this are reviews by our clients</p> --> </div> <div class="testimonial__boxControl"> <div class="testimonial__box" v-for="(review, index) in testimonials" :key=index v-show="check(index)"> <p class="testimonial__box-word">{{ review.word }}</p> <p class="testimonial__box-name">- {{ review.name }}</p> </div> <div class="testimonial__box-dots"> <span :class="['testimonial__box-dot', {'testimonial__box-dotActive': check(n-1)}]" v-for="n in testimonials.length" @click="setA(n-1)" :data-id="n"></span> </div> </div> </section> </template> <style lang="scss" scoped> .testimonial{ position: relative; width: 100%; height: 50vh; display: flex; align-items: center; justify-content: center; flex-direction: column; row-gap: 5vh; &::after{ position: absolute; content: ""; top: 0; bottom: 0; left: 0; right: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); } &__image{ width: 100%; height: 100%; position: absolute; object-fit: cover; } &__box{ background-color: rgba(0, 0, 0, 0.75); padding: 1em 2vw 1em 2vw; min-width: 50%; text-align: center; border-radius: 0.5em; font-size: 1.2em; &Control{ width: 100%; display: flex; flex-direction: column; align-items: center; row-gap: 1em; } &-word{ color: var(--vt-c-white-mute); } &-name{ color: var(--vt-c-white-dark); // font-style: italic; } &-dots{ z-index: 3; display: flex; column-gap: 1vw; } &-dot{ display: flex; width: 1.2vmin; height: 1.2vmin; border-radius: 50%; color: blue; background-color: darken($color: white, $amount: 40); cursor: pointer; &:hover{ background-color: var(--vt-c-white-mute); } &Active{ background-color: var(--vt-c-white-mute); } } } &__texts{ color: var(--vt-c-text-dark-1); /*position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);*/ z-index: 3; text-align: center; &-header{ font-size: calc(1em + 2.5vmin); font-weight: 300; } &-normal{ font-size: calc(0.5em + 1vmin); font-weight: 300; } } &__box{ // position: absolute; z-index: 3; /*top: 50%; left: 50%; transform: translate(-50%, -50%);*/ } } </style>
<?php namespace App\Security; use App\Entity\Token; use App\Entity\User; use App\Stellar\Soroban\Contract\InteractManager; use Doctrine\ORM\EntityManagerInterface; use Soneso\StellarSDK\Crypto\KeyPair; use Soneso\StellarSDK\Util\FriendBot; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException; use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface; use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge; use Symfony\Component\Security\Http\Authenticator\Passport\Passport; use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport; class WalletAuthenticator implements AuthenticatorInterface { public const LOGIN_ROUTE = 'app_get_login'; public function __construct( private readonly UrlGeneratorInterface $urlGenerator, private readonly EntityManagerInterface $em, private readonly InteractManager $interactManager ){} public function supports(Request $request): ?bool { return $request->isMethod('POST') && $this->getLoginUrl($request) === $request->getBaseUrl().$request->getPathInfo(); } public function authenticate(Request $request): Passport { $jsonContent = json_decode($request->getContent(), true); if(!isset($jsonContent['address']) ) { throw new CustomUserMessageAuthenticationException('Missing credentials'); } $user = $this->em->getRepository(User::class)->findOneBy(['address' => $jsonContent['address'] ]); if(!$user) { $keyPair = KeyPair::random(); FriendBot::fundTestAccount($keyPair->getAccountId()); $user = new User(); $user->setEnabled(true); $user->setAddress($jsonContent['address']); $user->setSecret($keyPair->getSecretSeed()); $user->setCreatedAt(new \DateTimeImmutable()); $this->em->persist($user); $this->em->flush(); // we have to mint user if we create it $token = $this->em->getRepository(Token::class)->findOneBy(['name' => 'MyToken']); $this->interactManager->mintUserWithToken($token->getAddress(), $user, 5000000); } return new SelfValidatingPassport(new UserBadge($jsonContent['address'])); } public function createToken(Passport $passport, string $firewallName): TokenInterface { return new UsernamePasswordToken($passport->getUser(), $firewallName, $passport->getUser()->getRoles()); } public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response { return null; } public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response { return new JsonResponse(['error' => $exception->getMessage()], JsonResponse::HTTP_UNAUTHORIZED); } protected function getLoginUrl(Request $request): string { return $this->urlGenerator->generate(self::LOGIN_ROUTE); } }
/** * * @author Alisha Garric * @description Headline section * */ // Core import React from "react"; // Styles import { HeadlineClassName, HeadlineStyle } from "./styles.scss"; import { sectionSpacing } from "../../../utils/sectionSpacing"; import { CMNC_SectionSpacingObject } from "../../../constants/Types"; import { CMNC_SectionTheme } from "../../../constants/Types"; import { PortableText } from "../../../utils/sanity"; // Begin Component type CMNC_Headline_Schema = CMNC_SectionSpacingObject & { headline?: string; subheadline?: string; body?: string; layout?: "split" | "left" | "right"; sectionTheme?: CMNC_SectionTheme; }; type CMNC_Headline = { schema: CMNC_Headline_Schema; addClass?: string; }; export const Headline: React.FunctionComponent<CMNC_Headline> = ({ schema, addClass, }) => { let { headline, subheadline, body, layout, spacing, sectionTheme } = schema; return ( <HeadlineStyle className={`${HeadlineClassName} ${ layout ? `__layout-${layout}` : "" } ${sectionSpacing(spacing)} ${addClass} ${ sectionTheme ? `__theme-${sectionTheme}` : "" }`} > {(headline || subheadline) && ( <div className={`${HeadlineClassName}__header`}> {headline && <h3>{headline}</h3>} {subheadline && ( <h3 className={`${HeadlineClassName}__header__subheadline`}> {subheadline} </h3> )} </div> )} {body && ( <div className={`${HeadlineClassName}__body`}> <PortableText blocks={body} /> </div> )} </HeadlineStyle> ); }; Headline.displayName = "Headline"; // End Component
package net.peterd.soundswap.syncadapter; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import net.peterd.soundswap.Preferences; import net.peterd.soundswap.R; import android.accounts.Account; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.widget.Toast; /** * Service to handle Account sync. This is invoked with an intent with action * ACTION_AUTHENTICATOR_INTENT. It instantiates the syncadapter and returns its * IBinder. */ public class SyncService extends Service { private static final Object sSyncAdapterLock = new Object(); private static SyncAdapter sSyncAdapter = null; private final Executor mExecutor = Executors.newSingleThreadExecutor(); @Override public void onCreate() { super.onCreate(); synchronized (sSyncAdapterLock) { if (sSyncAdapter == null) { sSyncAdapter = new SyncAdapter(getApplicationContext(), true); } } } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); final Preferences preferences = new Preferences(this); mExecutor.execute(new Runnable() { public void run() { Account account = preferences.getAccount(); if (account != null) { synchronized (sSyncAdapterLock) { sSyncAdapter.onPerformSync(account, null, null, null, null); } } } }); Toast.makeText(this, R.string.synchronizing, Toast.LENGTH_LONG).show(); return START_NOT_STICKY; } @Override public IBinder onBind(Intent intent) { return sSyncAdapter.getSyncAdapterBinder(); } }
import 'package:chat_app/src/screens/register/register_controller.dart'; import 'package:chat_app/src/widgets/my_button.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class RegisterScreen extends StatefulWidget { @override _RegisterScreenState createState() => _RegisterScreenState(); } class _RegisterScreenState extends State<RegisterScreen> { RegisterController _registerController; @override void initState() { super.initState(); _registerController = RegisterController(context: context); } @override Widget build(BuildContext context) { return StreamBuilder<Object>( stream: _registerController.streamController.stream, builder: (context, snapshot) { return Scaffold( body: SafeArea( child: Container( child: ListView( children: <Widget>[ Padding( padding: const EdgeInsets.all(15), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Container( child: IconButton( alignment: Alignment.centerLeft, padding: EdgeInsets.all(0), color: Colors.blue, onPressed: () { Navigator.of(context).pop(); }, icon: Icon( Icons.arrow_back, color: Colors.black, ), ), alignment: Alignment.centerLeft, ), Text( 'Create', style: TextStyle( color: Colors.black, fontSize: 26, fontWeight: FontWeight.bold, ), ), SizedBox( height: 5, ), Text( 'Create an account on ViliChatApp.', style: TextStyle( fontSize: 14, ), ), SizedBox( height: 60, ), TextField( cursorColor: Theme.of(context).primaryColor, controller: _registerController.nameController, decoration: InputDecoration(labelText: 'Full name'), ), SizedBox( height: 15, ), TextField( cursorColor: Theme.of(context).primaryColor, controller: _registerController.usernameController, decoration: InputDecoration(labelText: 'User name'), ), SizedBox( height: 15, ), TextField( cursorColor: Theme.of(context).primaryColor, controller: _registerController.passwordController, decoration: InputDecoration(labelText: 'Password'), obscureText: true, ), SizedBox( height: 45, ), MyButton( title: _registerController.formSubmitting ? 'CREATING...' : 'CREATE AN ACCOUNT', onTap: _registerController.submitForm, disabled: !_registerController.isFormValid || _registerController.formSubmitting, ), ], ), ), ], ), ), ), ); }); } }
import React from 'react'; // material ui import Button from '@material-ui/core/Button'; import CircularProgress from '@material-ui/core/CircularProgress'; // components import GroupedInput from 'components/auth/groupedInput/GroupedInput.js'; const Form = ({ formClick, inputChange, input, loading, checkboxChange }) => { return ( <form> <GroupedInput inputChange={inputChange} name="firstname" type="text" label="first name" value={input.firstname} isRequired={true} /> <GroupedInput inputChange={inputChange} name="lastname" type="text" label="last name" value={input.lastname} isRequired={true} /> <GroupedInput inputChange={inputChange} name="email" type="email" label="email" value={input.email} isRequired={true} /> <GroupedInput inputChange={inputChange} name="password" type="password" label="password" value={input.password} isRequired={true} /> <GroupedInput inputChange={inputChange} name="confirmpassword" type="password" label="confirm password" value={input.confirmpassword} isRequired={true} /> <div className="register__role"> <input type="checkbox" id="role" name="role" onChange={(e) => checkboxChange(e)} /> <label htmlFor="role"> Register as a Captcha Watcher</label> </div> {loading ? ( <CircularProgress disableShrink /> ) : ( <Button onClick={(e) => formClick(e)} className="form-button normal-3" type="submit"> Register </Button> )} </form> ); }; export default Form;
/** * Copyright (C) 2019-2023 Ubiqube. * * 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/>. */ package com.ubiqube.etsi.mano.em.v431.model.vnflcm; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.ubiqube.etsi.mano.em.v431.model.vnflcm.NotificationLink; import io.swagger.v3.oas.annotations.media.Schema; import org.springframework.validation.annotation.Validated; import jakarta.validation.Valid; import jakarta.validation.constraints.*; /** * This type represents the links to resources that a notification can contain. */ @Schema(description = "This type represents the links to resources that a notification can contain. ") @Validated public class LccnLinks { @JsonProperty("vnfInstance") private NotificationLink vnfInstance = null; @JsonProperty("subscription") private NotificationLink subscription = null; @JsonProperty("vnfLcmOpOcc") private NotificationLink vnfLcmOpOcc = null; public LccnLinks vnfInstance(NotificationLink vnfInstance) { this.vnfInstance = vnfInstance; return this; } /** * Get vnfInstance * @return vnfInstance **/ @Schema(required = true, description = "") @NotNull @Valid public NotificationLink getVnfInstance() { return vnfInstance; } public void setVnfInstance(NotificationLink vnfInstance) { this.vnfInstance = vnfInstance; } public LccnLinks subscription(NotificationLink subscription) { this.subscription = subscription; return this; } /** * Get subscription * @return subscription **/ @Schema(required = true, description = "") @NotNull @Valid public NotificationLink getSubscription() { return subscription; } public void setSubscription(NotificationLink subscription) { this.subscription = subscription; } public LccnLinks vnfLcmOpOcc(NotificationLink vnfLcmOpOcc) { this.vnfLcmOpOcc = vnfLcmOpOcc; return this; } /** * Get vnfLcmOpOcc * @return vnfLcmOpOcc **/ @Schema(description = "") @Valid public NotificationLink getVnfLcmOpOcc() { return vnfLcmOpOcc; } public void setVnfLcmOpOcc(NotificationLink vnfLcmOpOcc) { this.vnfLcmOpOcc = vnfLcmOpOcc; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LccnLinks lccnLinks = (LccnLinks) o; return Objects.equals(this.vnfInstance, lccnLinks.vnfInstance) && Objects.equals(this.subscription, lccnLinks.subscription) && Objects.equals(this.vnfLcmOpOcc, lccnLinks.vnfLcmOpOcc); } @Override public int hashCode() { return Objects.hash(vnfInstance, subscription, vnfLcmOpOcc); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class LccnLinks {\n"); sb.append(" vnfInstance: ").append(toIndentedString(vnfInstance)).append("\n"); sb.append(" subscription: ").append(toIndentedString(subscription)).append("\n"); sb.append(" vnfLcmOpOcc: ").append(toIndentedString(vnfLcmOpOcc)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
clc clear close all % display a clock based on an hour and minute % loop through times to animate clock moving % starting hour hour = 0; % setup to make clock face look nice theta = linspace(0, 2*pi, 101); polarplot(theta, ones(1, 101)*10, 'LineWidth', 4, 'Color', 'Black'); % clock border hold on polarplot(theta, ones(1, 101)*0.1, 'LineWidth', 4, 'Color', 'Black'); % clock center pax = gca; pax.ThetaZeroLocation = 'top'; pax.RLim = [0 10]; pax.ThetaTick = []; pax.RTick = []; pax.ThetaDir = 'clockwise'; % display numbers on clock % offset is to fix top and bottom text position offset = 0.08; text(0 - offset, 9, "12", 'fontsize', 20) text(pi/2, 8.75, "3", 'fontsize', 20) text(pi + offset/2, 9, "6", 'fontsize', 20) text(-pi/2, 9.25, "9", 'fontsize', 20) % initalize these before so deleting them doesn't throw error minute_hand_line = []; hour_hand_line = []; % loop over 12 hours in 1 minute increments for minute = 0 : 1 : 12*60 delete(minute_hand_line) delete(hour_hand_line) % adjust hour and minute to handle hours > 12, and minutes > 60 % this lets me loop through only minutes and not worry about hours hour_adjust = mod(hour, 12) + floor(minute / 60); minute_adjust = mod(minute, 60); % minute hand angle is determined by minute: % increases at rate of 6 deg/min % hour hand angle is determined by minute and hour: % increases at rate of 30 deg/hour % increases at rate of 0.5 deg/min minute_hand_angle = minute_adjust / 60 * 360; hour_hand_angle = hour_adjust / 12 * 360 + minute_adjust / 2; % convert degrees to radians minute_hand_angle = (minute_hand_angle) * pi/180; hour_hand_angle = (hour_hand_angle) * pi/180; minute_hand_line = polarplot([minute_hand_angle, minute_hand_angle], [0,8], 'LineWidth', 2, 'Color', 'Red'); hour_hand_line = polarplot([hour_hand_angle, hour_hand_angle], [0,4], 'LineWidth', 2, 'Color', 'Blue'); pause(0.01); end
import java.util.*; class Node { int data; Node next; public Node(int data) { this.data=data; this.next=null; } } class LL { public void print(Node head) { Node curr=head; while(curr!=null) { System.out.print(curr.data+"->"); curr=curr.next; } System.out.print("null"); System.out.println(); } public Node reverseInGroup(Node head,int k) { Node prev=null; Node curr=head; Node next=null; int count=1; while(curr!=null && count<=k) { next=curr.next; curr.next=prev; prev=curr; curr=next; count++; } // if linked list have more nodes after first k-nodes if(next!=null) { head.next=reverseInGroup(next,k); } return prev; } } public class Main { public static void main(String[] args) { Scanner s=new Scanner(System.in); LL ll=new LL(); int n=s.nextInt(); Node head=new Node(s.nextInt()); Node tail=head; while(n!=1) { tail.next=new Node(s.nextInt()); tail=tail.next; n--; } int k=s.nextInt(); ll.print(head); head=ll.reverseInGroup(head,k); ll.print(head); } }
<?php namespace app\controllers; use Yii; use app\models\Department; use app\models\DepartmentSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; use yii\filters\AccessControl; use yii\helpers\Json; use himiklab\sortablegrid\SortableGridAction; class DepartmentController extends Controller { public function actions() { return [ 'sort' => [ 'class' => SortableGridAction::className(), 'modelName' => Department::className(), ], ]; } public function behaviors() { return [ 'verbs' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'actions' => ['index','view','create','update','delete','sort','get-document-type'], 'allow' => true, 'roles' => ['@'], 'matchCallback' => function(){ if(Yii::$app->user->isGuest){ return false; }else{ return true; } } ], ], ], ]; } public function actionIndex() { // Checkbox if(isset($_POST['checkbox'])){ $id = isset($_POST['id']) ? $_POST['id'] : NULL; $value = isset($_POST['value']) ? $_POST['value'] : NULL; if($id != NULL){ $model = Department::find() ->where('dep_id = :ID',[':ID' => $id]) ->one(); if($_POST["type"] == "publish"){ $model->publish = $value; $model->save(false); } } exit(); } $searchModel = new DepartmentSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } public function actionView($id) { return $this->render('view', [ 'model' => $this->findModel($id), ]); } public function actionCreate() { $model = new Department(); if ($model->load(Yii::$app->request->post()) && $model->save()) { Yii::$app->session->setFlash('success', "Created Success"); return $this->redirect(['index']); } return $this->render('create', [ 'model' => $model, ]); } public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { Yii::$app->session->setFlash('success', "Updated Success"); return $this->redirect(['index']); } return $this->render('update', [ 'model' => $model, ]); } public function actionDelete($id) { $model = $this->findModel($id); $model->active = 0; $model->save(); return "success"; } protected function findModel($id) { if (($model = Department::findOne($id)) !== null) { return $model; } throw new NotFoundHttpException('The requested page does not exist.'); } }
Chapter 5 Distributed Git Now that you have a remote Git repository set up as a point for all the developers to share their code, and you’re familiar with basic Git commands in a local workflow, you’ll look at how to utilize some of the distributed workflows that Git affords you. In this chapter, you’ll see how to work with Git in a distributed environment as a contributor and an integrator. That is, you’ll learn how to contribute code successfully to a project and make it as easy on you and the project maintainer as possible, and also how to maintain a project successfully with a number of developers contributing. Distributed Workflows Unlike Centralized Version Control Systems (CVCSs), the distributed nature of Git allows you to be far more flexible in how developers collaborate on projects. In centralized systems, every developer is a node working more or less equally on a central hub. In Git, however, every developer is potentially both a node and a hub—that is, every developer can both contribute code to other repositories and maintain a public repository on which others can base their work and which they can contribute to. This opens a vast range of workflow possibilities for your project and/or your team, so we’ll cover a few common paradigms that take advantage of this flexibility. We’ll go over the strengths and possible weaknesses of each design; you can choose a single one to use, or you can mix and match features from each. Centralized Workflow In centralized systems, there is generally a single collaboration model—the centralized workflow. One central hub, or repository, can accept code, and everyone synchronizes their work to it. A number of developers are nodes— consumers of that hub—and synchronize to that one place. Figure 5-1. Centralized workflow Chapter 5 ■ DistributeD Git 98 This means that if two developers clone from the hub and both make changes, the first developer to push their changes back up can do so with no problems. The second developer must merge in the first one’s work before pushing changes up, so as not to overwrite the first developer’s changes. This concept is as true in Git as it is in Subversion (or any CVCS), and this model works perfectly well in Git. If you are already comfortable with a centralized workflow in your company or team, you can easily continue using that workflow with Git. Simply set up a single repository, and give everyone on your team push access; Git won’t let users overwrite each other. Say John and Jessica both start working at the same time. John finishes his change and pushes it to the server. Then Jessica tries to push her changes, but the server rejects them. She is told that she’s trying to push non−fast-forward changes and that she won’t be able to do so until she fetches and merges. This workflow is attractive to a lot of people because it’s a paradigm that many are familiar and comfortable with. This is also not limited to small teams. With Git’s branching model, it’s possible for hundreds of developers to successfully work on a single project through dozens of branches simultaneously. Integration-Manager Workflow Because Git allows you to have multiple remote repositories, it’s possible to have a workflow where each developer has write access to their own public repository and read access to everyone else’s. This scenario often includes a canonical repository that represents the “official” project. To contribute to that project, you create your own public clone of the project and push your changes to it. Then, you can send a request to the maintainer of the main project to pull in your changes. The maintainer can then add your repository as a remote, test your changes locally, merge them into their branch, and push back to their repository. The process works as follows: 1. The project maintainer pushes to their public repository. 2. A contributor clones that repository and makes changes. 3. The contributor pushes to their own public copy. 4. The contributor sends the maintainer an e-mail asking them to pull changes. 5. The maintainer adds the contributor’s repo as a remote and merges locally. 6. The maintainer pushes merged changes to the main repository. Figure 5-2. Integration-manager workflow This is a very common workflow with hub-based tools such as GitHub or GitLab, where it’s easy to fork a project and push your changes into your fork for everyone to see. One of the main advantages of this approach is that you can continue to work, and the maintainer of the main repository can pull in your changes at any time. Contributors don’t have to wait for the project to incorporate their changes—each party can work at their own pace. Chapter 5 ■ DistributeD Git 99 Dictator and Lieutenants Workflow This is a variant of a multiple-repository workflow. It’s generally used by huge projects with hundreds of collaborators; one famous example is the Linux kernel. Various integration managers are in charge of certain parts of the repository; they’re called lieutenants. All the lieutenants have one integration manager known as the benevolent dictator. The benevolent dictator’s repository serves as the reference repository from which all the collaborators need to pull. The process works like this: 1. Regular developers work on their topic branch and rebase their work on top of master. The master branch is that of the dictator. 2. Lieutenants merge the developers’ topic branches into their master branch. 3. The dictator merges the lieutenants’ master branches into the dictator’s master branch. 4. The dictator pushes their master to the reference repository so the other developers can rebase on it. Figure 5-3. Benevolent dictator workflow This kind of workflow isn’t common, but can be useful in very big projects, or in highly hierarchical environments. It allows the project leader (the dictator) to delegate much of the work and collect large subsets of code at multiple points before integrating them. Workf lows Summary These are some commonly used workflows that are possible with a distributed system like Git, but you can see that many variations are possible to suit your particular real-world workflow. Now that you can (hopefully) determine which workflow combination may work for you, we’ll cover some more specific examples of how to accomplish the main roles that make up the different flows. In the next section, you’ll learn about a few common patterns for contributing to a project. Chapter 5 ■ DistributeD Git 100 Contributing to a Project The main difficulty with describing how to contribute to a project is that there are a huge number of variations on how it’s done. Because Git is very flexible, people can and do work together in many ways, and it’s problematic to describe how you should contribute—every project is a bit different. Some of the variables involved are active contributor count, chosen workflow, your commit access, and possibly the external contribution method. The first variable is active contributor count—how many users are actively contributing code to this project, and how often? In many instances, you’ll have two or three developers with a few commits a day, or possibly less for somewhat dormant projects. For larger companies or projects, the number of developers could be in the thousands, with hundreds or thousands of commits coming in each day. This is important because with more and more developers, you run into more issues with making sure your code applies cleanly or can be easily merged. Changes you submit may be rendered obsolete or severely broken by work that is merged in while you were working or while your changes were waiting to be approved or applied. How can you keep your code consistently up to date and your commits valid? The next variable is the workflow in use for the project. Is it centralized, with each developer having equal write access to the main codeline? Does the project have a maintainer or integration manager who checks all the patches? Are all the patches peer-reviewed and approved? Are you involved in that process? Is a lieutenant system in place, and do you have to submit your work to them first? The next issue is your commit access. The workflow required in order to contribute to a project is much different if you have write access to the project than if you don’t. If you don’t have write access, how does the project prefer to accept contributed work? Does it even have a policy? How much work are you contributing at a time? How often do you contribute? All these questions can affect how you contribute effectively to a project and what workflows are preferred or available to you. We’ll cover aspects of each of these in a series of use cases, moving from simple to more complex; you should be able to construct the specific workflows you need in practice from these examples. Commit Guidelines Before we start looking at the specific use cases, here’s a quick note about commit messages. Having a good guideline for creating commits and sticking to it makes working with Git and collaborating with others a lot easier. The Git project provides a document that lays out a number of good tips for creating commits from which to submit patches— you can read it in the Git source code in the Documentation/SubmittingPatches file. First, you don’t want to submit any whitespace errors. Git provides an easy way to check for this—before you commit, run git diff --check, which identifies possible whitespace errors and lists them for you. Figure 5-4. Output of git diff -check Chapter 5 ■ DistributeD Git 101 If you run that command before committing, you can tell if you’re about to commit whitespace issues that may annoy other developers. Next, try to make each commit a logically separate changeset. If you can, try to make your changes digestible – don’t code for a whole weekend on five different issues and then submit them all as one massive commit on Monday. Even if you don’t commit during the weekend, use the staging area on Monday to split your work into at least one commit per issue, with a useful message per commit. If some of the changes modify the same file, try to use git add --patch to partially stage files. The project snapshot at the tip of the branch is identical whether you do one commit or five, as long as all the changes are added at some point, so try to make things easier on your fellow developers when they have to review your changes. This approach also makes it easier to pull out or revert one of the changesets if you need to later. The last thing to keep in mind is the commit message. Getting in the habit of creating quality commit messages makes using and collaborating with Git a lot easier. As a general rule, your messages should start with a single line that’s no more than about 50 characters and that describes the changeset concisely, followed by a blank line, followed by a more detailed explanation. The Git project requires that the more detailed explanation include your motivation for the change and contrast its implementation with previous behavior—this is a good guideline to follow. It’s also a good idea to use the imperative present tense in these messages. In other words, use commands. Instead of “I added tests for” or “Adding tests for,” use “Add tests for.” Here is a template originally written by Tim Pope: Short (50 chars or less) summary of changes More detailed explanatory text, if necessary. Wrap it to about 72 characters or so. In some contexts, the first line is treated as the subject of an email and the rest of the text as the body. The blank line separating the summary from the body is critical (unless you omit the body entirely); tools like rebase can get confused if you run the two together. Further paragraphs come after blank lines. - Bullet points are okay, too - Typically a hyphen or asterisk is used for the bullet, preceded by a single space, with blank lines in between, but conventions vary here If all your commit messages look like this, things will be a lot easier for you and the developers you work with. The Git project has well-formatted commit messages—try running git log --no-merges there to see what a nicely formatted project-commit history looks like. In the following examples, and throughout most of this book, for the sake of brevity this book doesn’t have nicely formatted messages like this; instead, we use the -m option to git commit. Do as we say, not as we do. Private Small Team The simplest setup you’re likely to encounter is a private project with one or two other developers. “Private,” in this context, means closed-source—not accessible to the outside world. You and the other developers all have push access to the repository. In this environment, you can follow a workflow similar to what you might do when using Subversion or another centralized system. You still get the advantages of things like offline committing and vastly simpler branching and merging, but the workflow can be very similar; the main difference is that merges happen client-side rather than on Chapter 5 ■ DistributeD Git 102 the server at commit time. Let’s see what it might look like when two developers start to work together with a shared repository. The first developer, John, clones the repository, makes a change, and commits locally. (The protocol messages have been replaced with . . . in these examples to shorten them somewhat.) # John's Machine $ git clone john@githost:simplegit.git Initialized empty Git repository in /home/john/simplegit/.git/ ... $ cd simplegit/ $ vim lib/simplegit.rb $ git commit -am 'removed invalid default value' [master 738ee87] removed invalid default value 1 files changed, 1 insertions(+), 1 deletions(-) The second developer, Jessica, does the same thing—clones the repository and commits a change: # Jessica's Machine $ git clone jessica@githost:simplegit.git Initialized empty Git repository in /home/jessica/simplegit/.git/ ... $ cd simplegit/ $ vim TODO $ git commit -am 'add reset task' [master fbff5bc] add reset task 1 files changed, 1 insertions(+), 0 deletions(-) Now, Jessica pushes her work up to the server: # Jessica's Machine $ git push origin master ... To jessica@githost:simplegit.git 1edee6b..fbff5bc master -> master John tries to push his change up, too: # John's Machine $ git push origin master To john@githost:simplegit.git ! [rejected] master -> master (non-fast forward) error: failed to push some refs to 'john@githost:simplegit.git' John isn’t allowed to push because Jessica has pushed in the meantime. This is especially important to understand if you’re used to Subversion, because you’ll notice that the two developers didn’t edit the same file. Although Subversion automatically does such a merge on the server if different files are edited, in Git you must merge the commits locally. John has to fetch Jessica’s changes and merge them in before he will be allowed to push: $ git fetch origin ... From john@githost:simplegit + 049d078...fbff5bc master -> origin/master Chapter 5 ■ DistributeD Git 103 John has a reference to the changes Jessica pushed up, but he has to merge them into his own work before he is allowed to push: $ git merge origin/master Merge made by recursive. TODO | 1 + 1 files changed, 1 insertions(+), 0 deletions(-) The merge goes smoothly. John’s commit history now looks like this: Figure 5-5. John’s divergent history Figure 5-6. John’s repository after merging origin/master At this point, John’s local repository looks something like this: Chapter 5 ■ DistributeD Git 104 Now, John can test his code to make sure it still works properly, and then he can push his new merged work up to the server: $ git push origin master ... To john@githost:simplegit.git fbff5bc..72bbc59 master -> master Finally, John’s commit history looks like this: Figure 5-7. John’s history after pushing to the origin server In the meantime, Jessica has been working on a topic branch. She’s created a topic branch called issue54 and done three commits on that branch. She hasn’t fetched John’s changes yet, so her commit history looks like this: Jessica's topic branch. Figure 5. Jessica’s topic branch. Jessica wants to sync up with John, so she fetches: # Jessica's Machine $ git fetch origin ... From jessica@githost:simplegit fbff5bc..72bbc59 master -> origin/master That pulls down the work John has pushed up in the meantime. Jessica’s history now looks like this: Figure 5-8. Jessica’s history after fetching John’s changes Chapter 5 ■ DistributeD Git 105 Jessica thinks her topic branch is ready, but she wants to know what she has to merge into her work so that she can push. She runs git log to find out: $ git log --no-merges issue54..origin/master commit 738ee872852dfaa9d6634e0dea7a324040193016 Author: John Smith <jsmith@example.com> Date: Fri May 29 16:01:27 2009 -0700 removed invalid default value The issue54..origin/master syntax is a log filter that asks Git to only show the list of commits that are on the latter branch (in this case origin/master) that are not on the first branch (in this case issue54). For now, we can see from the output that there is a single commit that John has made that Jessica has not merged in. If she merges origin/master, that is the single commit that will modify her local work. Now, Jessica can merge her topic work into her master branch, merge John’s work (origin/master) into her master branch, and then push back to the server again. First, she switches back to her master branch to integrate all this work: $ git checkout master Switched to branch "master" Your branch is behind 'origin/master' by 2 commits, and can be fast-forwarded. She can merge either origin/master or issue54 first—they’re both upstream, so the order doesn’t matter. The end snapshot should be identical no matter which order she chooses; only the history will be slightly different. She chooses to merge in issue54 first: $ git merge issue54 Updating fbff5bc..4af4298 Fast forward README | 1 + lib/simplegit.rb | 6 +++++ 2 files changed, 6 insertions(+), 1 deletions(-) No problems occur; as you can see it, was a simple fast-forward. Now Jessica merges in John’s work (origin/master): $ git merge origin/master Auto-merging lib/simplegit.rb Merge made by recursive. lib/simplegit.rb | 2 + 1 files changed, 1 insertions(+), 1 deletions(-) Chapter 5 ■ DistributeD Git 106 Now origin/master is reachable from Jessica’s master branch, so she should be able to successfully push (assuming John hasn’t pushed again in the meantime): $ git push origin master ... To jessica@githost:simplegit.git 72bbc59..8059c15 master -> master Each developer has committed a few times and merged each other’s work successfully. Figure 5-9. Jessica’s history after merging John’s changes Figure 5-10. Jessica’s history after pushing all changes back to the server Everything merges cleanly, and Jessica’s history looks like this: Chapter 5 ■ DistributeD Git 107 That is one of the simplest workflows. You work for a while, generally in a topic branch, and merge into your master branch when it’s ready to be integrated. When you want to share that work, you merge it into your own master branch, then fetch and merge origin/master if it has changed, and finally push to the master branch on the server. The general sequence is something like this: Figure 5-11. General sequence of events for a simple multiple-developer Git workflow Chapter 5 ■ DistributeD Git 108 Private Managed Team In this next scenario, you’ll look at contributor roles in a larger private group. You’ll learn how to work in an environment where small groups collaborate on features and then those team-based contributions are integrated by another party. Let’s say that John and Jessica are working together on one feature, while Jessica and Josie are working on a second. In this case, the company is using a type of integration-manager workflow where the work of the individual groups is integrated only by certain engineers, and the master branch of the main repo can be updated only by those engineers. In this scenario, all work is done in team-based branches and pulled together by the integrators later. Let’s follow Jessica’s workflow as she works on her two features, collaborating in parallel with two different developers in this environment. Assuming she already has her repository cloned, she decides to work on featureA first. She creates a new branch for the feature and does some work on it there: # Jessica's Machine $ git checkout -b featureA Switched to a new branch "featureA" $ vim lib/simplegit.rb $ git commit -am 'add limit to log function' [featureA 3300904] add limit to log function 1 files changed, 1 insertions(+), 1 deletions(-) At this point, she needs to share her work with John, so she pushes her featureA branch commits up to the server. Jessica doesn’t have push access to the master branch—only the integrators do—so she has to push to another branch in order to collaborate with John: $ git push -u origin featureA ... To jessica@githost:simplegit.git * [new branch] featureA -> featureA Jessica e-mails John to tell him that she’s pushed some work into a branch named featureA and he can look at it now. While she waits for feedback from John, Jessica decides to start working on featureB with Josie. To begin, she starts a new feature branch, basing it off the server’s master branch: # Jessica's Machine $ git fetch origin $ git checkout -b featureB origin/master Switched to a new branch 'featureB' Now, Jessica makes a couple of commits on the featureB branch: $ vim lib/simplegit.rb $ git commit -am 'made the ls-tree function recursive' [featureB e5b0fdc] made the ls-tree function recursive 1 files changed, 1 insertions(+), 1 deletions(-) $ vim lib/simplegit.rb $ git commit -am 'add ls-files' [featureB 8512791] add ls-files 1 files changed, 5 insertions(+), 0 deletions(-) Chapter 5 ■ DistributeD Git 109 She’s ready to push up her work, but gets an e-mail from Josie that a branch with some initial work on it was already pushed to the server as featureBee. Jessica first needs to merge those changes in with her own before she can push to the server. She can then fetch Josie’s changes down with git fetch: $ git fetch origin ... From jessica@githost:simplegit * [new branch] featureBee -> origin/featureBee Jessica can now merge this into the work she did with git merge: $ git merge origin/featureBee Auto-merging lib/simplegit.rb Merge made by recursive. lib/simplegit.rb | 4 ++++ 1 files changed, 4 insertions(+), 0 deletions(-) There is a bit of a problem—she needs to push the merged work in her featureB branch to the featureBee branch on the server. She can do so by specifying the local branch followed by a colon (:) followed by the remote branch to the git push command: $ git push -u origin featureB:featureBee ... To jessica@githost:simplegit.git fba9af8..cd685d1 featureB -> featureBee This is called a refspec. Also notice the -u flag; this is short for --set-upstream, which configures the branches for easier pushing and pulling later. Figure 5-12. Jessica’s initial commit history Jessica’s repository looks like this: Chapter 5 ■ DistributeD Git 110 Next, John e-mails Jessica to say he’s pushed some changes to the featureA branch and ask her to verify them. She runs a git fetch to pull down those changes: $ git fetch origin ... From jessica@githost:simplegit 3300904..aad881d featureA -> origin/featureA Then, she can see what has been changed with git log: $ git log featureA..origin/featureA commit aad881d154acdaeb2b6b18ea0e827ed8a6d671e6 Author: John Smith <jsmith@example.com> Date: Fri May 29 19:57:33 2009 -0700 changed log output to 30 from 25 Finally, she merges John’s work into her own featureA branch: $ git checkout featureA Switched to branch "featureA" $ git merge origin/featureA Updating 3300904..aad881d Fast forward lib/simplegit.rb | 10 +++++++++1 files changed, 9 insertions(+), 1 deletions(-) Jessica wants to tweak something, so she commits again and then pushes this back up to the server: $ git commit -am 'small tweak' [featureA ed774b3] small tweak 1 files changed, 1 insertions(+), 1 deletions(-) $ git push ... To jessica@githost:simplegit.git 3300904..ed774b3 featureA -> featureA Chapter 5 ■ DistributeD Git 111 Jessica, Josie, and John inform the integrators that the featureA and featureBee branches on the server are ready for integration into the mainline. After the integrators merge these branches into the mainline, a fetch will bring down the new merge commit, making the history look like this: Figure 5-13. Jessica’s history after committing on a feature branch Figure 5-14. Jessica’s history after merging both her topic branches Jessica’s commit history now looks something like this: Chapter 5 ■ DistributeD Git 112 Many groups switch to Git because of this ability to have multiple teams working in parallel, merging the different lines of work late in the process. The ability of smaller subgroups of a team to collaborate via remote branches without necessarily having to involve or impede the entire team is a huge benefit of Git. The sequence for the workflow you saw here is something like this: Figure 5-15. Basic sequence of this managed-team workf low Chapter 5 ■ DistributeD Git 113 Public Project, Fork Contributing to public projects is a bit different. Because you don’t have the permissions to directly update branches on the project, you have to get the work to the maintainers some other way. This first example describes contributing via forking on Git hosts that support easy forking. Many hosting sites support this (including GitHub, BitBucket, Google Code, repo.or.cz, and others), and many project maintainers expect this style of contribution. The next section deals with projects that prefer to accept contributed patches via e-mail. First, you’ll probably want to clone the main repository, create a topic branch for the patch or patch series you’re planning to contribute, and do your work there. The sequence looks basically like this: $ git clone (url) $ cd project $ git checkout -b featureA # (work) $ git commit # (work) $ git commit Note ■ You may want to use rebase -i to squash your work down to a single commit, or rearrange the work in the commits to make the patch easier for the maintainer to review. When your branch work is finished and you’re ready to contribute it back to the maintainers, go to the original project page and click the “Fork” button, creating your own writable fork of the project. You then need to add in this new repository URL as a second remote, in this case named myfork: $ git remote add myfork (url) Then you need to push your work up to it. It’s easiest to push the remote branch you’re working on up to your repository, rather than merging into your master branch and pushing that up. The reason is that if the work isn’t accepted or is cherry picked, you don’t have to rewind your master branch. If the maintainers merge, rebase, or cherry-pick your work, you’ll eventually get it back via pulling from their repository anyhow: $ git push -u myfork featureA When your work has been pushed up to your fork, you need to notify the maintainer. This is often called a pull request, and you can either generate it via the website—GitHub has it’s own Pull Request mechanism that we’ll go over in Chapter 6—or you can run the git request-pull command and e-mail the output to the project maintainer manually. The request-pull command takes the base branch into which you want your topic branch pulled and the Git repository URL you want them to pull from, and outputs a summary of all the changes you’re asking to be pulled in. For instance, if Jessica wants to send John a pull request, and she’s done two commits on the topic branch she just pushed up, she can run this: $ git request-pull origin/master myfork The following changes since commit 1edee6b1d61823a2de3b09c160d7080b8d1b3a40: John Smith (1): added a new function Chapter 5 ■ DistributeD Git 114 are available in the git repository at: git://githost/simplegit.git featureA Jessica Smith (2): add limit to log function change log output to 30 from 25 lib/simplegit.rb | 10 +++++++++ 1 files changed, 9 insertions(+), 1 deletions(-) The output can be sent to the maintainer—it tells them where the work was branched from, summarizes the commits, and tells where to pull this work from. On a project for which you’re not the maintainer, it’s generally easier to have a branch like master always track origin/master and to do your work in topic branches that you can easily discard if they’re rejected. Having work themes isolated into topic branches also makes it easier for you to rebase your work if the tip of the main repository has moved in the meantime and your commits no longer apply cleanly. For example, if you want to submit a second topic of work to the project, don’t continue working on the topic branch you just pushed up—start over from the main repository’s master branch: $ git checkout -b featureB origin/master # (work) $ git commit $ git push myfork featureB # (email maintainer) $ git fetch origin Now, each of your topics is contained within a silo—similar to a patch queue—that you can rewrite, rebase, and modify without the topics interfering or interdepending on each other, like so: Figure 5-16. Initial commit history with featureB work Let’s say the project maintainer has pulled in a bunch of other patches and tried your first branch, but it no longer cleanly merges. In this case, you can try to rebase that branch on top of origin/master, resolve the conflicts for the maintainer, and then resubmit your changes: $ git checkout featureA $ git rebase origin/master $ git push -f myfork featureA This rewrites your history to now look like Commit history after featureA work. Chapter 5 ■ DistributeD Git 115 Because you rebased the branch, you have to specify the -f to your push command in order to be able to replace the featureA branch on the server with a commit that isn’t a descendant of it. An alternative would be to push this new work to a different branch on the server (perhaps called featureAv2). Let’s look at one more possible scenario: the maintainer has looked at work in your second branch and likes the concept but would like you to change an implementation detail. You’ll also take this opportunity to move the work to be based off the project’s current master branch. You start a new branch based off the current origin/master branch, squash the featureB changes there, resolve any conflicts, make the implementation change, and then push that up as a new branch: $ git checkout -b featureBv2 origin/master^{} $ git merge --no-commit --squash featureB # (change implementation) $ git commit $ git push myfork featureBv2 The --squash option takes all the work on the merged branch and squashes it into one non-merge commit on top of the branch you’re on. The --no-commit option tells Git not to automatically record a commit. This allows you to introduce all the changes from another branch and then make more changes before recording the new commit. Now you can send the maintainer a message that you’ve made the requested changes and they can find those changes in your featureBv2 branch. Figure 5-17. Commit history after featureA work Figure 5-18. Commit history after featureBv2 work Chapter 5 ■ DistributeD Git 116 Public Project, E-Mail Many projects have established procedures for accepting patches—you’ll need to check the specific rules for each project, because they will differ. Since there are several older, larger projects which accept patches via a developer mailing list, we’ll go over an example of that now. The workflow is similar to the previous use case—you create topic branches for each patch series you work on. The difference is how you submit them to the project. Instead of forking the project and pushing to your own writable version, you generate e-mail versions of each commit series and e-mail them to the developer mailing list: $ git checkout -b topicA # (work) $ git commit # (work) $ git commit Now you have two commits that you want to send to the mailing list. You use git format-patch to generate the mbox-formatted files that you can e-mail to the list—it turns each commit into an e-mail message with the first line of the commit message as the subject and the rest of the message plus the patch that the commit introduces as the body. The nice thing about this is that applying a patch from an e-mail generated with format-patch preserves all the commit information properly. $ git format-patch -M origin/master 0001-add-limit-to-log-function.patch 0002-changed-log-output-to-30-from-25.patch The format-patch command prints out the names of the patch files it creates. The -M switch tells Git to look for renames. The files end up looking like this: $ cat 0001-add-limit-to-log-function.patch From 330090432754092d704da8e76ca5c05c198e71a8 Mon Sep 17 00:00:00 2001 From: Jessica Smith <jessica@example.com> Date: Sun, 6 Apr 2008 10:17:23 -0700 Subject: [PATCH 1/2] add limit to log function Limit log functionality to the first 20 -- lib/simplegit.rb | 2 + 1 files changed, 1 insertions(+), 1 deletions(-) diff --git a/lib/simplegit.rb b/lib/simplegit.rb index 76f47bc..f9815f1 100644 --- a/lib/simplegit.rb +++ b/lib/simplegit.rb @@ -14,7 +14,7 @@ class SimpleGit end def log(treeish = 'master') - command("git log #{treeish}") + command("git log -n 20 #{treeish}") end def ls_tree(treeish = 'master') -2.1.0 Chapter 5 ■ DistributeD Git 117 You can also edit these patch files to add more information for the e-mail list that you don’t want to show up in the commit message. If you add text between the --- line and the beginning of the patch (the diff --git line), then developers can read it; but applying the patch excludes it. To e-mail this to a mailing list, you can either paste the file into your e-mail program or send it via a command-line program. Pasting the text often causes formatting issues, especially with “smarter” clients that don’t preserve newlines and other whitespace appropriately. Luckily, Git provides a tool to help you send properly formatted patches via IMAP, which may be easier for you. We’ll demonstrate how to send a patch via Gmail, which happens to be the e-mail agent we know best; you can read detailed instructions for a number of mail programs at the end of the aforementioned Documentation/SubmittingPatches file in the Git source code. First, you need to set up the imap section in your ~/.gitconfig file. You can set each value separately with a series of git config commands, or you can add them manually, but in the end your config file should look something like this: [imap] folder = "[Gmail]/Drafts" host = imaps://imap.gmail.com user = user@gmail.com pass = p4ssw0rd port = 993 sslverify = false If your IMAP server doesn’t use SSL, the last two lines probably aren’t necessary, and the host value will be imap:// instead of imaps://. When that is set up, you can use git send-email to place the patch series in the Drafts folder of the specified IMAP server: $ git send-email *.patch 0001-added-limit-to-log-function.patch 0002-changed-log-output-to-30-from-25.patch Who should the emails appear to be from? [Jessica Smith <jessica@example.com>] Emails will be sent from: Jessica Smith <jessica@example.com> Who should the emails be sent to? jessica@example.com Message-ID to be used as In-Reply-To for the first email? y Then, Git spits out a bunch of log information looking something like this for each patch you’re sending: (mbox) Adding cc: Jessica Smith <jessica@example.com> from \line 'From: Jessica Smith <jessica@example.com>' OK. Log says: Sendmail: /usr/sbin/sendmail -i jessica@example.com From: Jessica Smith <jessica@example.com> To: jessica@example.com Subject: [PATCH 1/2] added limit to log function Date: Sat, 30 May 2009 13:29:15 -0700 Message-Id: <1243715356-61726-1-git-send-email-jessica@example.com> X-Mailer: git-send-email 1.6.2.rc1.20.g8c5b.dirty In-Reply-To: <y> References: <y> Result: OK Chapter 5 ■ DistributeD Git 118 At this point, you should be able to go to your Drafts folder, change the To field to the mailing list you’re sending the patch to, possibly CC the maintainer or person responsible for that section, and send it off. Summary This section has covered a number of common workflows for dealing with several very different types of Git projects you’re likely to encounter, and introduced a couple of new tools to help you manage this process. Next, you’ll see how to work the other side of the coin: maintaining a Git project. You’ll learn how to be a benevolent dictator or integration manager. Maintaining a Project In addition to knowing how to effectively contribute to a project, you’ll likely need to know how to maintain one. This can consist of accepting and applying patches generated via format-patch and e-mailed to you, or integrating changes in remote branches for repositories you’ve added as remotes to your project. Whether you maintain a canonical repository or want to help by verifying or approving patches, you need to know how to accept work in a way that is clearest for other contributors and sustainable by you over the long run. Working in Topic Branches When you’re thinking of integrating new work, it’s generally a good idea to try it out in a topic branch—a temporary branch specifically made to try out that new work. This way, it’s easy to tweak a patch individually and leave it if it’s not working until you have time to come back to it. If you create a simple branch name based on the theme of the work you’re going to try, such as ruby_client or something similarly descriptive, you can easily remember it if you have to abandon it for a while and come back later. The maintainer of the Git project tends to namespace these branches as well—such as sc/ruby_client, where sc is short for the person who contributed the work. As you’ll remember, you can create the branch based off your master branch like this: $ git branch sc/ruby_client master Or, if you want to also switch to it immediately, you can use the checkout -b option: $ git checkout -b sc/ruby_client master Now you’re ready to add your contributed work into this topic branch and determine if you want to merge it into your longer-term branches. Applying Patches from E-mail If you receive a patch over e-mail that you need to integrate into your project, you need to apply the patch in your topic branch to evaluate it. There are two ways to apply an e-mailed patch: with git apply or with git am. Applying a Patch with apply If you received the patch from someone who generated it with the git diff or a Unix diff command (which is not recommended; see the next section), you can apply it with the git apply command. Assuming you saved the patch at /tmp/patch-ruby-client.patch, you can apply the patch like this: $ git apply /tmp/patch-ruby-client.patch Chapter 5 ■ DistributeD Git 119 This modifies the files in your working directory. It’s almost identical to running a patch -p1 command to apply the patch, although it’s more paranoid and accepts fewer fuzzy matches than patch. It also handles file adds, deletes, and renames if they’re described in the git diff format, which patch won’t do. Finally, git apply is an “apply all or abort all” model where either everything is applied or nothing is, whereas patch can partially apply patchfiles, leaving your working directory in a weird state. git apply is overall much more conservative than patch. It won’t create a commit for you—after running it, you must stage and commit the changes introduced manually. You can also use git apply to see if a patch applies cleanly before you try actually applying it—you can run git apply --check with the patch: $ git apply --check 0001-seeing-if-this-helps-the-gem.patch error: patch failed: ticgit.gemspec:1 error: ticgit.gemspec: patch does not apply If there is no output, then the patch should apply cleanly. This command also exits with a non-zero status if the check fails, so you can use it in scripts if you want. Applying a Patch with am If the contributor is a Git user and was good enough to use the format-patch command to generate their patch, then your job is easier because the patch contains author information and a commit message for you. If you can, encourage your contributors to use format-patch instead of diff to generate patches for you. You should only have to use git apply for legacy patches and things like that. To apply a patch generated by format-patch, you use git am. Technically, git am is built to read an mbox file, which is a simple, plain-text format for storing one or more e-mail messages in one text file. It looks something like this: From 330090432754092d704da8e76ca5c05c198e71a8 Mon Sep 17 00:00:00 2001 From: Jessica Smith <jessica@example.com> Date: Sun, 6 Apr 2008 10:17:23 -0700 Subject: [PATCH 1/2] add limit to log function Limit log functionality to the first 20 This is the beginning of the output of the format-patch command that you saw in the previous section. This is also a valid mbox e-mail format. If someone has e-mailed you the patch properly using git send-email, and you download that into an mbox format, then you can point git am to that mbox file, and it will start applying all the patches it sees. If you run a mail client that can save several e-mails out in mbox format, you can save entire patch series into a file and then use git am to apply them one at a time. However, if someone uploaded a patch file generated via format-patch to a ticketing system or something similar, you can save the file locally and then pass that file saved on your disk to git am to apply it: $ git am 0001-limit-log-function.patch Applying: add limit to log function You can see that it applied cleanly and automatically created the new commit for you. The author information is taken from the e-mail’s From and Date headers, and the message of the commit is taken from the Subject and body (before the patch) of the e-mail. For example, if this patch was applied from the mbox example above, the commit generated would look something like this: $ git log --pretty=fuller -1 commit 6c5e70b984a60b3cecd395edd5b48a7575bf58e0 Chapter 5 ■ DistributeD Git 120 Author: Jessica Smith <jessica@example.com> AuthorDate: Sun Apr 6 10:17:23 2008 -0700 Commit: Scott Chacon <schacon@gmail.com> CommitDate: Thu Apr 9 09:19:06 2009 -0700 add limit to log function Limit log functionality to the first 20 The Commit information indicates the person who applied the patch and the time it was applied. The Author information is the individual who originally created the patch and when it was originally created. But it’s possible that the patch won’t apply cleanly. Perhaps your main branch has diverged too far from the branch the patch was built from, or the patch depends on another patch you haven’t applied yet. In that case, the git am process will fail and ask you what you want to do: $ git am 0001-seeing-if-this-helps-the-gem.patch Applying: seeing if this helps the gem error: patch failed: ticgit.gemspec:1 error: ticgit.gemspec: patch does not apply Patch failed at 0001. When you have resolved this problem run "git am --resolved". If you would prefer to skip this patch, instead run "git am --skip". To restore the original branch and stop patching run "git am --abort". This command puts conflict markers in any files it has issues with, much like a conflicted merge or rebase operation. You solve this issue much the same way—edit the file to resolve the conflict, stage the new file, and then run git am --resolved to continue to the next patch: $ (fix the file) $ git add ticgit.gemspec $ git am --resolved Applying: seeing if this helps the gem If you want Git to try a bit more intelligently to resolve the conflict, you can pass a -3 option to it, which makes Git attempt a three-way merge. This option isn’t on by default because it doesn’t work if the commit the patch says it was based on isn’t in your repository. If you do have that commit—if the patch was based on a public commit—then the -3 option is generally much smarter about applying a conflicting patch: $ git am -3 0001-seeing-if-this-helps-the-gem.patch Applying: seeing if this helps the gem error: patch failed: ticgit.gemspec:1 error: ticgit.gemspec: patch does not apply Using index info to reconstruct a base tree... Falling back to patching base and 3-way merge... No changes -- Patch already applied. In this case, this patch had already been applied. Without the -3 option, it looks like a conflict. If you’re applying a number of patches from an mbox, you can also run the am command in interactive mode, which stops at each patch it finds and asks if you want to apply it: $ git am -3 -i mbox Chapter 5 ■ DistributeD Git 121 Commit Body is: -------------------------seeing if this helps the gem -------------------------Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all This is nice if you have a number of patches saved, because you can view the patch first if you don’t remember what it is, or not apply the patch if you’ve already done so. When all the patches for your topic are applied and committed into your branch, you can choose whether and how to integrate them into a longer-running branch. Checking Out Remote Branches If your contribution came from a Git user who set up their own repository, pushed a number of changes into it, and then sent you the URL to the repository and the name of the remote branch the changes are in, you can add them as a remote and do merges locally. For instance, if Jessica sends you an e-mail saying that she has a great new feature in the ruby-client branch of her repository, you can test it by adding the remote and checking out that branch locally: $ git remote add jessica git://github.com/jessica/myproject.git $ git fetch jessica $ git checkout -b rubyclient jessica/ruby-client If she e-mails you again later with another branch containing another great feature, you can fetch and check out because you already have the remote setup. This is most useful if you’re working with a person consistently. If someone only has a single patch to contribute once in a while, then accepting it over e-mail may be less time consuming than requiring everyone to run their own server and having to continually add and remove remotes to get a few patches. You’re also unlikely to want to have hundreds of remotes, each for someone who contributes only a patch or two. However, scripts and hosted services may make this easier—it depends largely on how you develop and how your contributors develop. The other advantage of this approach is that you get the history of the commits as well. Although you may have legitimate merge issues, you know where in your history their work is based; a proper three-way merge is the default rather than having to supply a -3 and hope the patch was generated off a public commit to which you have access. If you aren’t working with a person consistently but still want to pull from them in this way, you can provide the URL of the remote repository to the git pull command. This does a one-time pull and doesn’t save the URL as a remote reference: $ git pull https://github.com/onetimeguy/project From https://github.com/onetimeguy/project * branch HEAD -> FETCH_HEAD Merge made by recursive. Determining What Is Introduced Now you have a topic branch that contains contributed work. At this point, you can determine what you’d like to do with it. This section revisits a couple of commands so you can see how you can use them to review exactly what you’ll be introducing if you merge this into your main branch. Chapter 5 ■ DistributeD Git 122 It’s often helpful to get a review of all the commits that are in this branch but that aren’t in your master branch. You can exclude commits in the master branch by adding the --not option before the branch name. This does the same thing as the master..contrib format that we used earlier. For example, if your contributor sends you two patches and you create a branch called contrib and applied those patches there, you can run this: $ git log contrib --not master commit 5b6235bd297351589efc4d73316f0a68d484f118 Author: Scott Chacon <schacon@gmail.com> Date: Fri Oct 24 09:53:59 2008 -0700 seeing if this helps the gem commit 7482e0d16d04bea79d0dba8988cc78df655f16a0 Author: Scott Chacon <schacon@gmail.com> Date: Mon Oct 22 19:38:36 2008 -0700 updated the gemspec to hopefully work better To see what changes each commit introduces, remember that you can pass the -p option to git log and it will append the diff introduced to each commit. To see a full diff of what would happen if you were to merge this topic branch with another branch, you may have to use a weird trick to get the correct results. You may think to run this: $ git diff master This command gives you a diff, but it may be misleading. If your master branch has moved forward since you created the topic branch from it, then you’ll get seemingly strange results. This happens because Git directly compares the snapshots of the last commit of the topic branch you’re on and the snapshot of the last commit on the master branch. For example, if you’ve added a line in a file on the master branch, a direct comparison of the snapshots will look like the topic branch is going to remove that line. If master is a direct ancestor of your topic branch, this isn’t a problem; but if the two histories have diverged, the diff will look like you’re adding all the new stuff in your topic branch and removing everything unique to the master branch. What you really want to see are the changes added to the topic branch—the work you’ll introduce if you merge this branch with master. You do that by having Git compare the last commit on your topic branch with the first common ancestor it has with the master branch. Technically, you can do that by explicitly figuring out the common ancestor and then running your diff on it: $ git merge-base contrib master 36c7dba2c95e6bbb78dfa822519ecfec6e1ca649 $ git diff 36c7db However, that isn’t convenient, so Git provides another shorthand for doing the same thing: the triple-dot syntax. In the context of the —command, you can put three periods after another branch to do a —between the last commit of the branch you’re on and its common ancestor with another branch: $ git diff master...contrib This command shows you only the work your current topic branch has introduced since its common ancestor with master. That is a very useful syntax to remember. Chapter 5 ■ DistributeD Git 123 Integrating Contributed Work When all the work in your topic branch is ready to be integrated into a more mainline branch, the question is how to do it. Furthermore, what overall workflow do you want to use to maintain your project? You have a number of choices, so we’ll cover a few of them. Merging Workflows One simple workflow merges your work into your master branch. In this scenario, you have a master branch that contains basically stable code. When you have work in a topic branch that you’ve done or that someone has contributed and you’ve verified, you merge it into your master branch, delete the topic branch, and then continue the process. If we have a repository with work in two branches named ruby_client and php_client that looks like History with several topic branches. and merge ruby_client first and then php_client next, then your history will end up looking like after a topic branch merge. Figure 5-19. History with several topic branches Figure 5-20. After a topic branch merge Chapter 5 ■ DistributeD Git 124 That is probably the simplest workflow, but it can possibly be problematic if you’re dealing with larger or more stable projects where you want to be really careful about what you introduce. If you have a more important project, you might want to use a two-phase merge cycle. In this scenario, you have two long-running branches, master and develop, in which you determine that master is updated only when a very stable release is cut and all new code is integrated into the develop branch. You regularly push both of these branches to the public repository. Each time you have a new topic branch to merge in (before a topic branch merge), you merge it into develop (after a topic branch merge); then, when you tag a release, you fast-forward master to wherever the now-stable develop branch is (after a project release). Figure 5-21. Before a topic branch merge Figure 5-22. After a topic branch merge Chapter 5 ■ DistributeD Git 125 Figure 5-23. After a project release Figure 5-24. Managing a complex series of parallel contributed topic branches This way, when people clone your project’s repository, they can either check out master to build the latest stable version and keep up to date on that easily, or they can check out develop, which is the more cutting-edge stuff. You can also continue this concept, having an integrate branch where all the work is merged together. Then, when the codebase on that branch is stable and passes tests, you merge it into a develop branch; and when that has proven itself stable for a while, you fast-forward your master branch. Large-Merging Workflows The Git project has four long-running branches: master, next, and pu (proposed updates) for new work, and maint for maintenance backports. When new work is introduced by contributors, it’s collected into topic branches in the maintainer’s repository in a manner similar to what we’ve described. At this point, the topics are evaluated to determine whether they’re safe and ready for consumption or whether they need more work. If they’re safe, they’re merged into next, and that branch is pushed up so everyone can try the topics integrated together. Chapter 5 ■ DistributeD Git 126 If the topics still need work, they’re merged into pu instead. When it’s determined that they’re totally stable, the topics are re-merged into master and are then rebuilt from the topics that were in next but didn’t yet graduate to master. This means master almost always moves forward, next is rebased occasionally, and pu is rebased even more often: Figure 5-25. Merging contributed topic branches into long-term integration branches When a topic branch has finally been merged into master, it’s removed from the repository. The Git project also has a maint branch that is forked off from the last release to provide backported patches in case a maintenance release is required. Thus, when you clone the Git repository, you have four branches that you can check out to evaluate the project in different stages of development, depending on how cutting edge you want to be or how you want to contribute; and the maintainer has a structured workflow to help them vet new contributions. Rebasing and Cherry Picking Workflows Other maintainers prefer to rebase or cherry-pick contributed work on top of their master branch, rather than merging it in, to keep a mostly linear history. When you have work in a topic branch and have determined that you want to integrate it, you move to that branch and run the rebase command to rebuild the changes on top of your current master (or develop, and so on) branch. If that works well, you can fast-forward your master branch, and you’ll end up with a linear project history. Chapter 5 ■ DistributeD Git 127 If you want to pull commit e43a6 into your master branch, you can run $ git cherry-pick e43a6fd3e94888d76779ad79fb568ed180e5fcdf Finished one cherry-pick. [master]: created a0a41a9: "More friendly message when locking the index fails." 3 files changed, 17 insertions(+), 3 deletions(-) This pulls the same change introduced in e43a6, but you get a new commit SHA-1 value, because the date applied is different. Now your history looks like this: Figure 5-26. Example history before a cherry-pick Figure 5-27. History after cherry-picking a commit on a topic branch Now you can remove your topic branch and drop the commits you didn’t want to pull in. The other way to move introduced work from one branch to another is to cherry-pick it. A cherry-pick in Git is like a rebase for a single commit. It takes the patch that was introduced in a commit and tries to reapply it on the branch you’re currently on. This is useful if you have a number of commits on a topic branch and you want to integrate only one of them, or if you only have one commit on a topic branch and you’d prefer to cherry-pick it rather than run rebase. For example, suppose you have a project that looks like this: Chapter 5 ■ DistributeD Git 128 Rerere If you’re doing lots of merging and rebasing, or you’re maintaining a long-lived topic branch, Git has a feature called “rerere” that can help. Rerere stands for “reuse recorded resolution” and it’s a way of shortcutting manual conflict resolution. When rerere is enabled, Git will keep a set of pre- and post-images from successful merges, and if it notices that there’s a conflict that looks exactly like one you’ve already fixed, it’ll just use the fix from last time, without bothering you with it. This feature comes in two parts: a configuration setting and a command. The configuration setting is rerere.enabled, and it’s handy enough to put in your global config: $ git config --global rerere.enabled true Now, whenever you do a merge that resolves conflicts, the resolution will be recorded in the cache in case you need it in the future. If you need to, you can interact with the rerere cache using the git rerere command. When it’s invoked alone, Git checks its database of resolutions and tries to find a match with any current merge conflicts and resolve them (although this is done automatically if rerere.enabled is set to true). There are also subcommands to see what will be recorded, to erase specific resolution from the cache, and to clear the entire cache. Tagging Your Releases When you’ve decided to cut a release, you’ll probably want to drop a tag so you can re-create that release at any point going forward. You can create a new tag. If you decide to sign the tag as the maintainer, the tagging may look something like this: $ git tag -s v1.5 -m 'my signed 1.5 tag' You need a passphrase to unlock the secret key for user: "Scott Chacon <schacon@gmail.com>" 1024-bit DSA key, ID F721C45A, created 2009-02-09 If you do sign your tags, you may have the problem of distributing the public PGP key used to sign your tags. The maintainer of the Git project has solved this issue by including their public key as a blob in the repository and then adding a tag that points directly to that content. To do this, you can figure out which key you want by running gpg --list-keys: $ gpg --list-keys /Users/schacon/.gnupg/pubring.gpg --------------------------------pub 1024D/F721C45A 2009-02-09 [expires: 2010-02-09] uid Scott Chacon <schacon@gmail.com> sub 2048g/45D02282 2009-02-09 [expires: 2010-02-09] Then, you can directly import the key into the Git database by exporting it and piping that through git hash-object, which writes a new blob with those contents into Git and gives you back the SHA-1 of the blob: $ gpg -a --export F721C45A | git hash-object -w --stdin 659ef797d181633c87ec71ac3f9ba29fe5775b92 Chapter 5 ■ DistributeD Git 129 Now that you have the contents of your key in Git, you can create a tag that points directly to it by specifying the new SHA-1 value that the hash-object command gave you: $ git tag -a maintainer-pgp-pub 659ef797d181633c87ec71ac3f9ba29fe5775b92 If you run git push --tags, the maintainer-pgp-pub tag will be shared with everyone. If anyone wants to verify a tag, they can directly import your PGP key by pulling the blob directly out of the database and importing it into GPG: $ git show maintainer-pgp-pub | gpg --import They can use that key to verify all your signed tags. Also, if you include instructions in the tag message, running git show <tag> will let you give the end user more specific instructions about tag verification. Generating a Build Number Because Git doesn’t have monotonically increasing numbers like v123 or the equivalent to go with each commit, if you want to have a human-readable name to go with a commit, you can run git describe on that commit. Git gives you the name of the nearest tag with the number of commits on top of that tag and a partial SHA-1 value of the commit you’re describing: $ git describe master v1.6.2-rc1-20-g8c5b85c This way, you can export a snapshot or build and name it something understandable to people. In fact, if you build Git from source code cloned from the Git repository, git --version gives you something that looks like this. If you’re describing a commit that you have directly tagged, it gives you the tag name. The git describe command favors annotated tags (tags created with the -a or -s flag), so release tags should be created this way if you’re using git describe, to ensure the commit is named properly when described. You can also use this string as the target of a checkout or show command, although it relies on the abbreviated SHA-1 value at the end, so it may not be valid forever. For instance, the Linux kernel recently jumped from 8 to 10 characters to ensure SHA-1 object uniqueness, so older git describe output names were invalidated. Preparing a Release Now you want to release a build. One of the things you’ll want to do is create an archive of the latest snapshot of your code for those poor souls who don’t use Git. The command to do this is git archive: $ git archive master --prefix='project/' | gzip > `git describe master`.tar.gz $ ls *.tar.gz v1.6.2-rc1-20-g8c5b85c.tar.gz If someone opens that tarball, they get the latest snapshot of your project under a project directory. You can also create a zip archive in much the same way, but by passing the --format=zip option to git archive: $ git archive master --prefix='project/' --format=zip > `git describe master`.zip Chapter 5 ■ DistributeD Git 130 You now have a nice tarball and a zip archive of your project release that you can upload to your website or e-mail to people. The Shortlog It’s time to e-mail your mailing list of people who want to know what’s happening in your project. A nice way of quickly getting a sort of changelog of what has been added to your project since your last release or e-mail is to use the git shortlog command. It summarizes all the commits in the range you give it; for example, the following gives you a summary of all the commits since your last release, if your last release was named v1.0.1: $ git shortlog --no-merges master --not v1.0.1 Chris Wanstrath (8): Add support for annotated tags to Grit::Tag Add packed-refs annotated tag support. Add Grit::Commit#to_patch Update version and History.txt Remove stray `puts` Make ls_tree ignore nils Tom Preston-Werner (4): fix dates in history dynamic version method Version bump to 1.0.2 Regenerated gemspec for version 1.0.2 You get a clean summary of all the commits since v1.0.1, grouped by author, that you can e-mail to your list. Summary You should feel fairly comfortable contributing to a project in Git as well as maintaining your own project or integrating other users' contributions. Congratulations on being an effective Git developer! In the next chapter, you’ll learn about how to use the largest and most popular Git hosting service, GitHub.
<!-- - Jellyplot Copyright (c) 2022. --> <template> <section v-cloak class="bg-white"> <div class="grid grid-cols-2 gap-2 px-5 py-2 text-primary-color"> <div class="grid grid-cols-2 gap-4"> <div class=""> <select @change="this.changeLapse" class="w-full capitalize text-black dark:text-white dark:bg-gray-900 focus:ring-primary-color focus:border-primary-color rounded-md text-xs border-gray-300 dark:border-gray-700" id="lapse" v-model="this.lapse.name"> <option v-for="value in lapses" :value="value" >{{ value }}</option> </select> </div> <!--Year & Month--> <div v-if="this.lapse.name === 'year' || this.lapse.name === 'month'" class="flex gap-2 items-center"> <!--Month--> <div v-if="this.lapse.name === 'month'" class="flex justify-end items-center"> <!--BackMonth <div v-if="this.months[this.month] !== months[0]" @click="this.backMonth()" class="px-1 cursor-pointer"> <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" /> </svg> </div>--> <select class="text-black dark:text-white dark:bg-gray-900 focus:ring-primary-color focus:border-primary-color rounded-md text-xs border-gray-300 dark:border-gray-700" id="month" v-model="this.month" @change="this.updateMonth()"> <option v-for="month in months" :value="this.months.indexOf(month)+1">{{ month }}</option> </select> <!--BackMonth <div v-show="this.months[this.month] !== months[months.length - 1]" @click="this.nextMonth()" class="px-1 cursor-pointer"> <svg @click="this.nextYear()" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" /> </svg> </div>--> </div> <!--Year--> <!--BackYear <div v-if="this.year !== years[0]" @click="this.backYear()" class="px-1 cursor-pointer"> <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" /> </svg> </div> --> <select class="text-black dark:text-white dark:bg-gray-900 focus:ring-primary-color focus:border-primary-color rounded-md text-xs border-gray-300 dark:border-gray-700" id="year" v-model="this.year" @change="this.updateYear()"> <option v-for="year in years" :value="year">{{ year }}</option> </select> <!--NextYear <div v-show="this.year !== years[years.length - 1]" @click="this.nextYear()" class="px-1 cursor-pointer"> <svg @click="this.nextYear()" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" /> </svg> </div> --> </div> </div> <div> <div class="flex justify-end"> <select @change="this.changeType" class="capitalize text-black dark:text-white dark:bg-gray-900 focus:ring-primary-color focus:border-primary-color rounded-md text-xs border-gray-300 dark:border-gray-700" id="type" v-model="this.type.name"> <option v-for="value in types" :value="value" >{{ value }}</option> </select> </div> </div> </div> <div class="bg-white p-2 text-black rounded-b-md"> <canvas id="user-projects-contribution" width="400" height="400"></canvas> </div> </section> </template> å <script> import Chart from 'chart.js/auto'; const Utils = require("moment"); const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; export default { name: "UserContributionComponent", props: { user: { type: [Object, Array], required: true, }, team: { type: [Object, Array], required: true, } }, data: function () { return { year: new Date(Date.now()).getFullYear(), month: new Date().getMonth() + 1, lapse: { id: 0, name:"year", }, type: { id: 0, name: "line", }, chartLabels: Utils.months(), } }, watch:{ userProjectsCount(newValue) { let array = { label: 'Projects', backgroundColor: [ 'rgba(255, 99, 132, 0.2)', ], borderColor: [ 'rgb(255, 99, 132)', ], borderWidth: 1, data: newValue.slice() } this.chart.data.datasets.push(array); this.chart.update(0) }, userResourcesCount(newValue) { let array = { label: 'Resources', backgroundColor: [ 'rgba(255, 205, 86, 0.2)', ], borderColor: [ 'rgb(255, 159, 64)', ], borderWidth: 1, data: newValue.slice() } this.chart.data.datasets.push(array); this.chart.update(0) }, userCustomersCount(newValue){ let array = { label: 'Customers', backgroundColor: [ 'rgba(75, 192, 192, 0.2)', ], borderColor: [ 'rgb(54, 162, 235)', ], borderWidth: 1, data: newValue.slice() } this.chart.data.datasets.push(array); this.chart.update(0) }, userEquipmentCount(newValue){ let array = { label: 'Equipment', backgroundColor: [ 'rgba(153, 102, 255, 0.2)', ], borderColor: [ 'rgb(153, 102, 255)', ], borderWidth: 1, data: newValue.slice() } this.chart.data.datasets.push(array); this.chart.update(0) } }, methods: { fillData: function () { let delayed; const ctx = document.getElementById('user-projects-contribution'); this.chart = new Chart(ctx, { type: this.type.name, data: { labels: this.chartLabels, datasets:[], }, options: { legend: { labels: { color: "#ffffff", fontSize: 24 } }, animation: { onComplete: () => { delayed = true; }, delay: (context) => { let delay = 0; if (context.type === 'data' && context.mode === 'default' && !delayed) { delay = context.dataIndex * 300 + context.datasetIndex * 100; } return delay; }, }, responsive: true, maintainAspectRatio: false, scales: { y: { beginAtZero: true, ticks: { precision: 0, } }, }, }, }); }, getApiData: function() { switch (this.lapse.name) { case "year": this.chartLabels = Utils.months(); this.apiContributionRequestYear(); break; case "month": let value = new Date(this.year, this.month + 1 ,0).getDate(); this.chartLabels = Array.from({length: value}, (_, i) => i + 1); this.apiContributionRequestMonth(); break; case "today": this.chartLabels = this.range(0, 23) this.apiContributionRequestDay(); break; } }, range: function (start, end) { return Array(end - start + 1). fill(). map((_, idx) => start + idx) }, /** * API Requests */ apiContributionRequestYear: function() { this.$store.dispatch('fetchUserContributionYearProjectsCount', {'userID': this.user.id, 'yearValue': this.year}); this.$store.dispatch('fetchUserContributionYearResourcesCount', {'userID': this.user.id, 'yearValue': this.year}); this.$store.dispatch('fetchUserContributionYearCustomersCount', {'userID': this.user.id, 'yearValue': this.year}); this.$store.dispatch('fetchUserContributionYearEquipmentCount', {'userID': this.user.id, 'yearValue': this.year}); }, apiContributionRequestMonth: function() { this.$store.dispatch('fetchUserContributionMonthProjectsCount', {'userID': this.user.id, 'yearValue': this.year, 'monthValue': this.month}); this.$store.dispatch('fetchUserContributionMonthResourcesCount', {'userID': this.user.id, 'yearValue': this.year, 'monthValue': this.month}); this.$store.dispatch('fetchUserContributionMonthEquipmentCount', {'userID': this.user.id, 'yearValue': this.year, 'monthValue': this.month}); this.$store.dispatch('fetchUserContributionMonthCustomersCount', {'userID': this.user.id, 'yearValue': this.year, 'monthValue': this.month}); }, apiContributionRequestDay: function() { let today = new Date().getDate(); this.$store.dispatch('fetchUserContributionDayProjectsCount', {'userID': this.user.id, 'yearValue': this.year, 'monthValue': this.month, 'dayValue': today}); this.$store.dispatch('fetchUserContributionDayResourcesCount', {'userID': this.user.id, 'yearValue': this.year, 'monthValue': this.month, 'dayValue': today}); this.$store.dispatch('fetchUserContributionDayCustomersCount', {'userID': this.user.id, 'yearValue': this.year, 'monthValue': this.month, 'dayValue': today}); this.$store.dispatch('fetchUserContributionDayEquipmentCount', {'userID': this.user.id, 'yearValue': this.year, 'monthValue': this.month, 'dayValue': today}); }, updateYear: function() { while (this.chart.data.datasets.length) { this.chart.data.datasets.pop(); } this.getApiData(); }, updateMonth: function() { while (this.chart.data.datasets.length) { this.chart.data.datasets.pop(); } this.getApiData(); }, updateDay: function() { while (this.chart.data.datasets.length) { this.chart.data.datasets.pop(); } this.getApiData(); }, changeLapse: function(){ this.chart.destroy(); this.getApiData(); this.fillData() }, changeType: function(){ this.chart.destroy(); this.getApiData(); this.fillData() }, backYear: function (){ if(this.year !== this.years[0]) { this.year = this.year - 1; this.updateYear(); } }, nextYear: function (){ if(this.year !== this.years[this.years.length - 1]) { this.year = this.year + 1; this.updateYear(); } }, backMonth: function (){ if(this.month !== 0) { this.month = this.month - 1; this.updateMonth(); } }, nextMonth: function (){ if(this.month !== this.months.length - 1) { this.month = this.month+ 1; this.updateMonth(); } } }, computed: { years: function() { const year = new Date().getFullYear() return Array.from({length: year - 2009}, (value, index) => 2010 + index) }, months: function() { return Utils.months() }, types: function(){ return ['line','bar', 'radar']; }, lapses: function(){ return ['year', 'month', 'today'] }, userProjectsCount: function (){ return this.$store.getters.userContributionProjectsCount; }, userResourcesCount: function (){ return this.$store.getters.userContributionResourcesCount; }, userCustomersCount: function (){ return this.$store.getters.userContributionCustomersCount; }, userEquipmentCount: function (){ return this.$store.getters.userContributionEquipmentCount; }, }, beforeMount() { this.getApiData(); }, async mounted() { this.fillData() }, } </script>
/* * SettingsActivity.java * * Original work Copyright (C) 2014 Philipp Dreimann * Modified work Copyright (C) 2015 Bjoern Petri * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.freifunk.android.discover; import android.annotation.TargetApi; import android.content.Context; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceCategory; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import android.view.MenuItem; import android.support.v4.app.NavUtils; import net.freifunk.android.discover.helper.Database; import net.freifunk.android.discover.helper.EventBus; import net.freifunk.android.discover.model.MapMaster; import net.freifunk.android.discover.model.NodeMap; import net.freifunk.android.discover.model.NodeMapComparator; import net.freifunk.android.discover.model.NodeResult; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * A {@link PreferenceActivity} that presents a set of application settings. On * handset devices, settings are presented as a single list. On tablets, * settings are split by category, with category headers shown to the left of * the list of settings. * <p> * See <a href="http://developer.android.com/design/patterns/settings.html"> * Android Design: Settings</a> for design guidelines and the <a * href="http://developer.android.com/guide/topics/ui/settings.html">Settings * API Guide</a> for more information on developing a Settings UI. */ public class SettingsActivity extends PreferenceActivity { /** * Determines whether to always show the simplified settings UI, where * settings are presented in a single list. When false, settings are shown * as a master/detail two-pane view on tablets. When true, a single pane is * shown on tablets. */ private static final boolean ALWAYS_SIMPLE_PREFS = false; private static final String TAG = SettingsActivity.class.getName(); @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_data_sync); // get data via the key ArrayList<NodeMap> nodeMapArrayList = new ArrayList<NodeMap>(MapMaster.getInstance().getMaps().values()); PreferenceCategory communities = (PreferenceCategory) findPreference("communities"); // sort by Name Collections.sort(nodeMapArrayList, new NodeMapComparator()); if (nodeMapArrayList != null && communities != null) { for (final NodeMap nm : nodeMapArrayList ) { PreferenceScreen communityPreferenceScreen = getPreferenceManager().createPreferenceScreen(SettingsActivity.this); communityPreferenceScreen.setTitle(nm.getMapName()); communityPreferenceScreen.setKey(nm.getMapName()); final CheckBoxPreference deactivateCommunityPreference = new CheckBoxPreference(SettingsActivity.this); // TODO: move Strings to resources deactivateCommunityPreference.setTitle("Community aktiv"); deactivateCommunityPreference.setSummary("deaktivieren, falls Community nicht auf der Karte angezeigt werden soll"); deactivateCommunityPreference.setKey("community_deactivate_" + nm.getMapName()); deactivateCommunityPreference.setChecked(nm.isActive()); deactivateCommunityPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { Database db = Database.getInstance(null); boolean newActive = newValue.toString().equals("true") ? true : false; nm.setActive(newActive); db.addNodeMap(nm); // reload if set to active if (newActive) { nm.loadNodes(); } else { nm.updateNodes(); } return true; } }); EditTextPreference editCommunityPreference = new EditTextPreference(SettingsActivity.this); // TODO: move Strings to resources editCommunityPreference.setTitle("URL bearbeiten"); editCommunityPreference.setSummary("aendern, falls eine andere Quelle genutzt werden soll."); editCommunityPreference.setKey("community_edit_" + nm.getMapName()); editCommunityPreference.setText(nm.getMapUrl()); editCommunityPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { Database db = Database.getInstance(null); // remove old nodes from map nm.setActive(false); EventBus.getInstance().post(new NodeResult(NodeResult.NodeResultType.UPDATE_NODES, nm)); // we should probably do this async as well db.deleteAllNodesForMap(nm); // load new nodes NodeMap newMap = new NodeMap(nm.getMapName(), (String) newValue, true); db.addNodeMap(newMap); //HashMap<String, NodeMap> nodeResult = new HashMap<String, NodeMap>(1); //nodeResult.put(nm.getMapName(), nm); newMap.updateNodes(); //EventBus.getInstance().post(new NodeResult(NodeResult.NodeResultType.LOAD_NODES, nm)); //EventBus.getInstance().post(new NodeResult(NodeResult.NodeResultType.UPDATE_MAP, nodeResult)); return true; } }); communityPreferenceScreen.addPreference(deactivateCommunityPreference); communityPreferenceScreen.addPreference(editCommunityPreference); communities.addPreference(communityPreferenceScreen); } } setupActionBar(); } /** * Set up the {@link android.app.ActionBar}, if the API is available. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupActionBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Show the Up button in the action bar. getActionBar().setDisplayHomeAsUpEnabled(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // // TODO: If Settings has multiple levels, Up should navigate up // that hierarchy. NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } /** {@inheritDoc} */ @Override public boolean onIsMultiPane() { return isXLargeTablet(this) && !isSimplePreferences(this); } /** * Helper method to determine if the device has an extra-large screen. For * example, 10" tablets are extra-large. */ private static boolean isXLargeTablet(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE; } /** * Determines whether the simplified settings UI should be shown. This is * true if this is forced via {@link #ALWAYS_SIMPLE_PREFS}, or the device * doesn't have newer APIs like {@link PreferenceFragment}, or the device * doesn't have an extra-large screen. In these cases, a single-pane * "simplified" settings UI should be shown. */ private static boolean isSimplePreferences(Context context) { return ALWAYS_SIMPLE_PREFS || Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB || !isXLargeTablet(context); } /** {@inheritDoc} */ @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void onBuildHeaders(List<Header> target) { if (!isSimplePreferences(this)) { loadHeadersFromResource(R.xml.pref_headers, target); } } /** * A preference value change listener that updates the preference's summary * to reflect its new value. */ private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object value) { String stringValue = value.toString(); if (preference instanceof ListPreference) { // For list preferences, look up the correct display value in // the preference's 'entries' list. ListPreference listPreference = (ListPreference) preference; int index = listPreference.findIndexOfValue(stringValue); // Set the summary to reflect the new value. preference.setSummary( index >= 0 ? listPreference.getEntries()[index] : null); } else { // For all other preferences, set the summary to the value's // simple string representation. preference.setSummary(stringValue); } return true; } }; /** * Binds a preference's summary to its value. More specifically, when the * preference's value is changed, its summary (line of text below the * preference title) is updated to reflect the value. The summary is also * immediately updated upon calling this method. The exact display format is * dependent on the type of preference. * * @see #sBindPreferenceSummaryToValueListener */ private static void bindPreferenceSummaryToValue(Preference preference) { // Set the listener to watch for value changes. preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener); // Trigger the listener immediately with the preference's // current value. sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, PreferenceManager .getDefaultSharedPreferences(preference.getContext()) .getString(preference.getKey(), "")); } /** * This fragment shows data and sync preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static class DataSyncPreferenceFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_data_sync); // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference("sync_wifi")); bindPreferenceSummaryToValue(findPreference("sync_frequency")); } } }
# Hey emacs! This is a -*- Perl -*- script! # Lintian::Deb822::Parser -- Perl utility functions for parsing deb822 files # Copyright © 1998 Christian Schwarz # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, you can find it on the World Wide # Web at http://www.gnu.org/copyleft/gpl.html, or write to the Free # Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, # MA 02110-1301, USA. package Lintian::Deb822::Parser; use v5.20; use warnings; use utf8; use constant { DCTRL_DEBCONF_TEMPLATE => 1, DCTRL_NO_COMMENTS => 2, DCTRL_COMMENTS_AT_EOL => 4, }; our %EXPORT_TAGS = (constants => [qw(DCTRL_DEBCONF_TEMPLATE DCTRL_NO_COMMENTS DCTRL_COMMENTS_AT_EOL)],); our @EXPORT_OK = (qw( visit_dpkg_paragraph_string parse_dpkg_control_string parse_dpkg_control_string_lc read_dpkg_control read_dpkg_control_lc ), @{ $EXPORT_TAGS{constants} }); use Exporter qw(import); use Const::Fast; use Unicode::UTF8 qw(encode_utf8); const my $EMPTY => q{}; const my $NUMBER_SIGN => q{#}; =head1 NAME Lintian::Deb822::Parser - Lintian's generic Deb822 parser functions =head1 SYNOPSIS use Lintian::Deb822::Parser qw(read_dpkg_control); my (@paragraphs); eval { @paragraphs = read_dpkg_control('some/debian/ctrl/file'); }; if ($@) { # syntax error etc. die encode_utf8("ctrl/file: $@"); } foreach my $para (@paragraphs) { my $value = $para->{'some-field'}; if (defined $value) { # ... } } =head1 DESCRIPTION This module contains a number of utility subs that are nice to have, but on their own did not warrant their own module. Most subs are imported only on request. =head2 Debian control parsers At first glance, this module appears to contain several debian control parsers. In practise, there is only one real parser (L</visit_dpkg_paragraph_string>) - the rest are convenience functions around it. =over 4 =item Use L</read_dpkg_control> when You have a debian control file (such I<debian/control>) and you want a number of paragraphs from it. =back =head1 CONSTANTS The following constants can be passed to the Debian control file parser functions to alter their parsing flag. =over 4 =item DCTRL_DEBCONF_TEMPLATE The file should be parsed as debconf template. These have slightly syntax rules for whitespace in some cases. =item DCTRL_NO_COMMENTS The file do not allow comments. With this flag, any comment in the file is considered a syntax error. =back =head1 FUNCTIONS =over 4 =item read_dpkg_control(FILE[, FLAGS[, LINES]]) This is a convenience function to ease using L</parse_dpkg_control> with paths to files (rather than open handles). The first argument must be the path to a FILE, which should be read as a debian control file. If the file is empty, an empty list is returned. Otherwise, this behaves like: use autodie; open(my $fd, '<:encoding(UTF-8)', FILE); # or '<' my @p = parse_dpkg_control($fd, FLAGS, LINES); close($fd); return @p; This goes without saying that may fail with any of the messages that L</parse_dpkg_control(HANDLE[, FLAGS[, LINES]])> do. It can also emit autodie exceptions if open or close fails. =cut sub read_dpkg_control { my ($file, $flags, $field_starts) = @_; open(my $handle, '<:utf8_strict', $file) or die encode_utf8("Cannot open $file"); local $/ = undef; my $string = <$handle>; close $handle; my @result; my $visitor = sub { my ($paragraph, $line) = @_; push(@result, $paragraph); push(@{$field_starts}, $line) if defined $field_starts; }; visit_dpkg_paragraph_string($visitor, $string, $flags); return @result; } =item read_dpkg_control_lc(FILE[, FLAGS[, LINES]]) =cut sub read_dpkg_control_lc { my ($file, $flags, $field_starts) = @_; my @result = read_dpkg_control($file, $flags, $field_starts); lowercase_field_names(\@result); lowercase_field_names($field_starts); return @result; } =item parse_dpkg_control_string(STRING[, FLAGS[, LINES]]) Reads debian control data from STRING and returns a list of paragraphs in it. A paragraph is represented via a hashref, which maps (lower cased) field names to their values. FLAGS (if given) is a bitmask of the I<DCTRL_*> constants. Please refer to L</CONSTANTS> for the list of constants and their meaning. The default value for FLAGS is 0. If LINES is given, it should be a reference to an empty list. On return, LINES will be populated with a hashref for each paragraph (in the same order as the returned list). Each hashref will also have a special key "I<START-OF-PARAGRAPH>" that gives the line number of the first field in that paragraph. These hashrefs will map the field name of the given paragraph to the line number where the field name appeared. This is a convenience sub around L</visit_dpkg_paragraph> and can therefore produce the same errors as it. Please see L</visit_dpkg_paragraph> for the finer semantics of how the control file is parsed. NB: parse_dpkg_control does I<not> close the handle for the caller. =cut sub parse_dpkg_control_string { my ($string, $flags, $field_starts) = @_; my @result; my $c = sub { my ($para, $line) = @_; push(@result, $para); push(@{$field_starts}, $line) if defined $field_starts; }; visit_dpkg_paragraph_string($c, $string, $flags); return @result; } =item parse_dpkg_control_string_lc(STRING[, FLAGS[, LINES]]) =cut sub parse_dpkg_control_string_lc { my ($string, $flags, $field_starts) = @_; my @result = parse_dpkg_control_string($string, $flags, $field_starts); lowercase_field_names(\@result); lowercase_field_names($field_starts); return @result; } =item lowercase_field_names =cut sub lowercase_field_names { my ($arrayref) = @_; return unless $arrayref; for my $paragraph (@{$arrayref}) { # magic marker should only appear in field starts my @fields = grep { $_ ne 'START-OF-PARAGRAPH' } keys %{$paragraph}; my @mixedcase = grep { $_ ne lc($_) } @fields; for my $old (@mixedcase) { $paragraph->{lc $old} = $paragraph->{$old}; delete $paragraph->{$old}; } } return; } =item visit_dpkg_paragraph_string (CODE, STRING[, FLAGS]) Reads debian control data from STRING and passes each paragraph to CODE. A paragraph is represented via a hashref, which maps (lower cased) field names to their values. FLAGS (if given) is a bitmask of the I<DCTRL_*> constants. Please refer to L</CONSTANTS> for the list of constants and their meaning. The default value for FLAGS is 0. If the file is empty (i.e. it contains no paragraphs), the method will contain an I<empty> list. The deb822 contents may be inside a I<signed> PGP message with a signature. visit_dpkg_paragraph will require the PGP headers to be correct (if present) and require that the entire file is covered by the signature. However, it will I<not> validate the signature (in fact, the contents of the PGP SIGNATURE part can be empty). The signature should be validated separately. visit_dpkg_paragraph will pass paragraphs to CODE as they are completed. If CODE can process the paragraphs as they are seen, very large control files can be processed without keeping all the paragraphs in memory. As a consequence of how the file is parsed, CODE may be passed a number of (valid) paragraphs before parsing is stopped due to a syntax error. NB: visit_dpkg_paragraph does I<not> close the handle for the caller. CODE is expected to be a callable reference (e.g. a sub) and will be invoked as the following: =over 4 =item CODE->(PARA, LINE_NUMBERS) The first argument, PARA, is a hashref to the most recent paragraph parsed. The second argument, LINE_NUMBERS, is a hashref mapping each of the field names to the line number where the field name appeared. LINE_NUMBERS will also have a special key "I<START-OF-PARAGRAPH>" that gives the line number of the first field in that paragraph. The return value of CODE is ignored. If the CODE invokes die (or similar) the error is propagated to the caller. =back I<On syntax errors>, visit_dpkg_paragraph will call die with the following string: "syntax error at line %d: %s\n" Where %d is the line number of the issue and %s is one of: =over =item Duplicate field %s The field appeared twice in the paragraph. =item Continuation line outside a paragraph (maybe line %d should be " .") A continuation line appears outside a paragraph - usually caused by an unintended empty line before it. =item Whitespace line not allowed (possibly missing a ".") An empty continuation line was found. This usually means that a period is missing to denote an "empty line" in (e.g.) the long description of a package. =item Cannot parse line "%s" Generic error containing the text of the line that confused the parser. Note that all non-printables in %s will be replaced by underscores. =item Comments are not allowed A comment line appeared and FLAGS contained DCTRL_NO_COMMENTS. =item PGP signature seen before start of signed message A "BEGIN PGP SIGNATURE" header is seen and a "BEGIN PGP MESSAGE" has not been seen yet. =item Two PGP signatures (first one at line %d) Two "BEGIN PGP SIGNATURE" headers are seen in the same file. =item Unexpected %s header A valid PGP header appears (e.g. "BEGIN PUBLIC KEY BLOCK"). =item Malformed PGP header An invalid or malformed PGP header appears. =item Expected at most one signed message (previous at line %d) Two "BEGIN PGP MESSAGE" headers appears in the same message. =item End of file but expected an "END PGP SIGNATURE" header The file ended after a "BEGIN PGP SIGNATURE" header without being followed by an "END PGP SIGNATURE". =item PGP MESSAGE header must be first content if present The file had content before PGP MESSAGE. =item Data after the PGP SIGNATURE The file had data after the PGP SIGNATURE block ended. =item End of file before "BEGIN PGP SIGNATURE" The file had a "BEGIN PGP MESSAGE" header, but no signature was present. =back =cut sub visit_dpkg_paragraph_string { my ($code, $string, $flags) = @_; $flags//=0; my $field_starts = {}; my $section = {}; my $open_section = 0; my $last_tag; my $debconf = $flags & DCTRL_DEBCONF_TEMPLATE; my $signed = 0; my $signature = 0; my @lines = split(/\n/, $string); my $position = 1; my $line; while (defined($line = shift @lines)) { chomp $line; if (substr($line, 0, 1) eq $NUMBER_SIGN) { next unless $flags & DCTRL_NO_COMMENTS; die encode_utf8("No comments allowed (line $position).\n"); } # empty line? if ($line eq $EMPTY || (!$debconf && $line =~ /^\s*$/)) { if ($open_section) { # end of current section # pass the current section to the handler $code->($section, $field_starts); $section = {}; $field_starts = {}; $open_section = 0; } } # pgp sig? Be strict here (due to #696230) # According to http://tools.ietf.org/html/rfc4880#section-6.2 # The header MUST start at the beginning of the line and MUST NOT have # any other text (except whitespace) after the header. elsif ($line =~ m/^-----BEGIN PGP SIGNATURE-----[ \r\t]*$/) { # skip until end of signature my $saw_end = 0; die encode_utf8("PGP signature before message (line $position).\n") unless $signed; die encode_utf8( "Found two PGP signatures (line $signature and line $position).\n" )if $signature; $signature = $position; while (defined($line = shift @lines)) { if ($line =~ /^-----END PGP SIGNATURE-----[ \r\t]*$/) { $saw_end = 1; last; } }continue { ++$position; } # The "at line X" may seem a little weird, but it keeps the # message format identical. die encode_utf8("Cannot find END PGP SIGNATURE header.\n") unless $saw_end; } # other pgp control? elsif ($line =~ /^-----(?:BEGIN|END) PGP/) { # At this point it could be a malformed PGP header or one # of the following valid headers (RFC4880): # * BEGIN PGP MESSAGE # - Possibly a signed Debian CTRL, so okay (for now) # * BEGIN PGP {PUBLIC,PRIVATE} KEY BLOCK # - Valid header, but not a Debian CTRL file. # * BEGIN PGP MESSAGE, PART X{,/Y} # - Valid, but we don't support partial messages, so # bail on those. unless ($line =~ /^-----BEGIN PGP SIGNED MESSAGE-----[ \r\t]*$/) { # Not a (full) PGP MESSAGE; reject. my $key = qr/(?:BEGIN|END) PGP (?:PUBLIC|PRIVATE) KEY BLOCK/; my $msgpart = qr{BEGIN PGP MESSAGE, PART \d+(?:/\d+)?}; my $msg = qr/(?:BEGIN|END) PGP (?:(?:COMPRESSED|ENCRYPTED) )?MESSAGE/; if ($line =~ /^-----($key|$msgpart|$msg)-----[ \r\t]*$/) { die encode_utf8( "Unexpected $1 header (line $position).\n"); } die encode_utf8("Malformed PGP header (line $position).\n"); } else { die encode_utf8( "Multiple PGP messages (line $signed and line $position).\n" )if $signed; # NB: If you remove this, keep in mind that it may # allow two paragraphs to merge. Consider: # # Field-P1: some-value # -----BEGIN PGP SIGNATURE----- # # Field-P2: another value # # At the time of writing: If $open_section is # true, it will remain so until the empty line # after the PGP header. die encode_utf8( "Expected PGP MESSAGE header (line $position).\n") if $last_tag; $signed = $position; } # skip until the next blank line while (defined($line = shift @lines)) { last if $line =~ /^\s*$/; }continue { ++$position; } } # did we see a signature already? We allow all whitespace/comment lines # outside the signature. elsif ($signature) { # Accept empty lines after the signature. next if $line =~ /^\s*$/; # NB: If you remove this, keep in mind that it may allow # two paragraphs to merge. Consider: # # Field-P1: some-value # -----BEGIN PGP SIGNATURE----- # [...] # -----END PGP SIGNATURE----- # Field-P2: another value # # At the time of writing: If $open_section is true, it # will remain so until the empty line after the PGP # header. die encode_utf8("Data after PGP SIGNATURE (line $position).\n"); } # new empty field? elsif ($line =~ /^([^: \t]+):\s*$/) { $field_starts->{'START-OF-PARAGRAPH'} = $position unless $open_section; $open_section = 1; my $tag = $1; $section->{$tag} = $EMPTY; $field_starts->{$tag} = $position; $last_tag = $tag; } # new field? elsif ($line =~ /^([^: \t]+):\s*(.*)$/) { $field_starts->{'START-OF-PARAGRAPH'} = $position unless $open_section; $open_section = 1; # Policy: Horizontal whitespace (spaces and tabs) may occur # immediately before or after the value and is ignored there. my $tag = $1; my $value = $2; # trim right $value =~ s/\s+$//; if (exists $section->{$tag}) { # Policy: A paragraph must not contain more than one instance # of a particular field name. die encode_utf8("Duplicate field $tag (line $position).\n"); } $value =~ s/#.*$// if $flags & DCTRL_COMMENTS_AT_EOL; $section->{$tag} = $value; $field_starts->{$tag} = $position; $last_tag = $tag; } # continued field? elsif ($line =~ /^([ \t].*\S.*)$/) { die encode_utf8( "Continuation line not in paragraph (line $position). Missing a dot on the previous line?\n" )unless $open_section; # Policy: Many fields' values may span several lines; in this case # each continuation line must start with a space or a tab. Any # trailing spaces or tabs at the end of individual lines of a # field value are ignored. my $value = $1; # trim right $value =~ s/\s+$//; $value =~ s/#.*$// if $flags & DCTRL_COMMENTS_AT_EOL; $section->{$last_tag} .= "\n" . $value; } # None of the above => syntax error else { die encode_utf8( "Unexpected whitespace (line $position). Missing a dot?\n") if $line =~ /^\s+$/; # Replace non-printables and non-space characters with # "_" - just in case. $line =~ s/[^[:graph:][:space:]]/_/g; die encode_utf8("Cannot parse line $position: $line\n"); } }continue { ++$position; } # pass the last section (if not already done). $code->($section, $field_starts) if $open_section; # Given the API, we cannot use this check to prevent any # paragraphs from being emitted to the code argument, so we might # as well just do this last. die encode_utf8("Cannot find BEGIN PGP SIGNATURE\n.") if $signed && !$signature; return; } =back =head1 SEE ALSO lintian(1) =cut 1; # Local Variables: # indent-tabs-mode: nil # cperl-indent-level: 4 # End: # vim: syntax=perl sw=4 sts=4 sr et
import { Meta, Source, ArgTypes } from '@storybook/blocks' <Meta title="Core/Utilities/Utilities" /> # Utilities The core package bundles some utility functions for miscellaneous use. These functions are used internally, but they may also be relevant for developing custom charts. **`range`** prepares an array of integers, providing similar functionality as the eponymous python function. <Source language="js" code={` range(4) // [0, 1, 2, 3] range(2, 5) // [2, 3, 4] `} /> **indexes** creates an array with integer indexes to match an input array. <Source language="js" code={` indexes(["a", "b", "c"]) // [0, 1, 2] indexes([]) // [] `} /> **sortedIndex** performs a binary search in a sorted array to find an suitable for a target value. <Source language="js" code={` sortedIndex([0, 1, 2, 5, 10], 5) // 3 sortedIndex([0, 1, 2, 5, 10], 4) // 3 `} />
<?php namespace allatnet\yii2\modules\extendedrights\models; use Yii; /** * This is the model class for table "hk_user". * * @property integer $id * @property string $fieldName * @property string $title */ class UserFields extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%user_fields}}'; } /** * @inheritdoc */ public function rules() { return [ [['fieldName', 'title'], 'required'], [['fieldName', 'title'], 'string', 'max' => 255], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'fieldName' => 'Feld Name', 'title' => 'Titel', ]; } }
<template> <div class="layout_container"> <!-- 左侧菜单 --> <div class="layout_slider"> <Logo></Logo> <el-scrollbar class="scrollbar"> <!-- 表单组件 --> <el-menu :default-active="$route.path" background-color="#001529" text-color="white" router> <Menu :menuList="userStore.menuRoutes"></Menu> </el-menu> </el-scrollbar> </div> <!-- 顶部导航 --> <div class="layout_tabbar"> <Tabbar></Tabbar> </div> <!-- 内容展示区域 --> <div class="layout_main"> <Main></Main> </div> </div> </template> <script setup lang='ts'> // 引入顶部导航 import Tabbar from './components/tabbar.vue' // 引入main组件 import Main from './components/main.vue' // 引入logo组件 import Logo from './components/logo.vue' // 引入菜单组件 import Menu from './components/menu.vue' // 获取用户相关的小仓库 import useUserStore from '../store/modules/user'; // 获取路由对象 import { useRoute } from 'vue-router'; const userStore = useUserStore(); const $route = useRoute() </script> <script lang="ts"> export default { name: 'layout' } </script> <style scoped lang="scss"> .layout_container { width: 100%; height: 100%; .layout_slider { width: $base-menu-width; height: 100vh; color: white; background: $base-menu-background; .scrollbar { width: 100%; height: calc(100vh - $base-menu-logo-height); .el-menu { border-right: none; } } } .layout_tabbar { position: fixed; width: calc(100% - $base-menu-width); height: $base-tabbar-height; top: 0px; left: $base-menu-width; } .layout_main { position: absolute; width: calc(100% - $base-menu-width); height: calc(100% - $base-tabbar-height); left: $base-menu-width; top: $base-tabbar-height; padding: 20px; overflow: hidden; } } </style>
import Card from "./Card.js"; import CardGame from "./CardGame.js" // const CardGame = require('./CardGame.js'); describe('After game is initiated ', () => { beforeEach(() => { // Before each test case is executed }); test('userturn function updates boolean value of isUserTurn',() => { const cardGameObj = new CardGame(); let initialVal = cardGameObj.isUserTurn; cardGameObj.userTurn(); expect(cardGameObj.isUserTurn).toBe(!initialVal); }) test('display message when user decides to stay',() => { const cardGameObj = new CardGame(); console.log = jest.fn(); cardGameObj.isUserStay = true; cardGameObj.handleStayScenario(); expect(console.log).toHaveBeenCalledWith('User has decided to stay'); }) test('isGamover variable updated if userscore is 25', () => { const cardGameObj = new CardGame(); cardGameObj.userScore = 25; const cardObj = new Card(0); cardGameObj.checkTotalScore(cardObj); expect(cardGameObj.isGameOver).toBe(true); }) test('console show user lost message if user score is more than 25', () => { const cardGameObj = new CardGame(); console.log = jest.fn(); cardGameObj.userScore = 26; const cardObj = new Card(0); cardGameObj.checkTotalScore(cardObj); expect(console.log).toHaveBeenCalledWith('user lost'); }) test('User stays the game if userscore is more than 20', () => { const cardGameObj = new CardGame(); cardGameObj.userScore = 21; const cardObj = new Card(0); cardGameObj.checkTotalScore(cardObj); expect(cardGameObj.isUserStay).toBe(true); }) test('Computer stays the game if computerscore is more than 20', () => { const cardGameObj = new CardGame(); cardGameObj.computerScore = 22; const cardObj = new Card(0); cardGameObj.checkTotalScore(cardObj); expect(cardGameObj.isComputerStay).toBe(true); }) test('Computer has decided to stay message is shown when isComputerStay variable is true', () => { const cardGameObj = new CardGame(); console.log = jest.fn(); cardGameObj.isComputerStay = true; cardGameObj.handleStayScenario(); expect(console.log).toHaveBeenCalledWith('Computer has decided to stay'); }) test('Userscore is updated when a new card is picked by the user', () => { const cardGameObj = new CardGame(); cardGameObj.userScore = 10; cardGameObj.isUserTurn = true; cardGameObj.isUserStay = false; let cardObj = new Card(5); cardGameObj.updateScores(cardObj); expect(cardGameObj.userScore).toBe(15); }) test('Display user won message when both user and computer stayed, both scores are less than 25 and userscore is more than computerscore', () => { const cardGameObj = new CardGame(); console.log = jest.fn(); cardGameObj.isComputerStay = true; cardGameObj.isUserStay = true; cardGameObj.userScore = 24; cardGameObj.computerScore = 22; cardGameObj.handleDisplayResult(); expect(console.log).toHaveBeenCalledWith('winner is User'); }) test('Display computer won message when both user and computer stayed, both scores are less than 25 and computer score is more than userscore', () => { const cardGameObj = new CardGame(); // console.log = jest.fn(); const spy = jest.spyOn(console,'log'); cardGameObj.isComputerStay = true; cardGameObj.isUserStay = true; cardGameObj.userScore = 22; cardGameObj.computerScore = 24; cardGameObj.handleDisplayResult(); // expect(console.log).toHaveBeenCalledWith('winner is computer'); expect(spy).toHaveBeenCalledWith('winner is computer'); }) test('Display game draw message when both user and computer stayed, both scores are less than 25 and computer score is same as userscore', () => { const cardGameObj = new CardGame(); console.log = jest.fn(); cardGameObj.isComputerStay = true; cardGameObj.isUserStay = true; cardGameObj.userScore = 22; cardGameObj.computerScore = 22; cardGameObj.handleDisplayResult(); expect(console.log).toHaveBeenCalledWith('score draw'); }) })
import React, { useContext, useEffect, useRef, useState } from 'react'; import { Image, ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View, } from 'react-native'; import { useForm } from '../hooks/useForm'; import { StackScreenProps } from '@react-navigation/stack'; import { ProductsStackParams } from '../navigation/ProductsNavigator'; import { Picker } from '@react-native-picker/picker'; import { useCategories } from '../hooks/useCategories'; import { ProductsContext } from '../context/ProductsContext'; import { Cam } from '../components/Camera'; interface Props extends StackScreenProps<ProductsStackParams, 'ProductScreen'> {} export const ProductScreen = ({ route, navigation }: Props) => { const [imageTemp, setImageTemp] = useState(null); const { id = '', name = '' } = route.params; const { categories } = useCategories(); const [openCam, setOpenCam] = useState(false); const { loadProductsByid, addProduct, updateProduct } = useContext(ProductsContext); const { _id, categoriaId, nombre, img, form, onChange, setFormValue } = useForm({ _id: id, categoriaId: '', nombre: name, img: '', }); useEffect(() => { navigation.setOptions({ title: name ? name : 'Nuevo producto', }); }, []); useEffect(() => { loadProduct(); }, []); const loadProduct = async () => { if (id.length === 0) return; const product = await loadProductsByid(id); setFormValue({ _id: id, categoriaId: product.categoria._id, img: product.img || '', nombre, }); }; const saveOrUpdate = async () => { if (id.length > 0) { updateProduct(categoriaId, nombre, id); } else { const tempCategoriaId = categoriaId || categories[0]._id; const newProduct = await addProduct(tempCategoriaId, nombre); onChange(newProduct._id, '_id'); } }; return ( <View style={styles.container}> {openCam ? ( <Cam image={imageTemp!} setImageTemp={setImageTemp} setOpenCam={setOpenCam} id={_id} /> ) : ( <ScrollView showsVerticalScrollIndicator={false}> <Text style={styles.label}>Nombre del producto:</Text> <TextInput placeholder="Ingrese nombre del producto" style={styles.textInput} value={nombre} onChangeText={(value) => onChange(value, 'nombre')} /> <Text style={styles.label}>Categoria:</Text> <Picker selectedValue={categoriaId} onValueChange={(value) => onChange(value, 'categoriaId')} > {categories.map((category) => ( <Picker.Item label={category.nombre} value={category._id} key={category._id} /> ))} </Picker> <TouchableOpacity activeOpacity={0.7} style={styles.button} onPress={saveOrUpdate} > <Text style={styles.textButton}>Guardar</Text> </TouchableOpacity> {_id.length > 0 && ( <View style={styles.containerButtons}> <TouchableOpacity activeOpacity={0.7} style={{ ...styles.button, width: 120 }} onPress={() => setOpenCam(true)} > <Text style={styles.textButton}>Cámara</Text> </TouchableOpacity> <TouchableOpacity activeOpacity={0.7} style={{ ...styles.button, width: 120 }} > <Text style={styles.textButton}>Galeria</Text> </TouchableOpacity> </View> )} {img.length > 0 && !imageTemp && ( <Image source={{ uri: img }} style={{ width: '100%', height: 300, }} /> )} {/* //TODO: Mostrar imagen temporal */} {imageTemp && ( <Image source={{ uri: imageTemp }} style={{ width: '100%', height: 300, marginTop: 30, marginBottom: 30, }} /> )} </ScrollView> )} </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, marginTop: 10, marginHorizontal: 20, }, label: { fontSize: 16, fontWeight: 'bold', }, textInput: { borderWidth: 1, paddingHorizontal: 10, paddingVertical: 5, borderRadius: 20, borderColor: 'rgba(0,0,0,0.2)', height: 45, marginTop: 5, marginBottom: 15, }, button: { height: 45, borderWidth: 1, borderRadius: 20, justifyContent: 'center', alignItems: 'center', backgroundColor: 'black', }, textButton: { fontSize: 16, fontWeight: 'bold', color: 'white', }, containerButtons: { flexDirection: 'row', justifyContent: 'space-between', marginTop: 10, }, select: { borderColor: 'rgba(0,0,0,0.2)', borderRadius: 20, marginTop: 5, marginBottom: 15, }, });
package exercise_solutions.E02_CalculateStatistics; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class CalculateStatistics_04 { public void start() { // String fileName = "exercise_solutions/E02_CalculateStatistics/data01.txt"; // String fileName = "exercise_solutions/E02_CalculateStatistics/data02.txt"; String fileName = "exercise_solutions/E02_CalculateStatistics/data03.txt"; try { List<Double> vals = readData(fileName); reportStats(vals); } catch (FileNotFoundException e) { System.err.println("Nonexistent file: " + fileName); } catch (IOException e) { e.printStackTrace(); } } private List<Double> readData(String fileName) throws FileNotFoundException, IOException { BufferedReader reader = new BufferedReader(new FileReader(fileName)); Iterator<String> lines = reader.lines().iterator(); List<Double> data = new ArrayList<>(); while (lines.hasNext()) { try { data.add(Double.parseDouble(lines.next())); } catch (Exception e) {} } reader.close(); return data; } private double calculate_range(List<Double> vals) { return vals.get(vals.size()-1) - vals.get(0); } private double calculate_variance(List<Double> vals) { double sum = 0; double mean = calculate_average(vals); for (Double val : vals) { double x = val - mean; sum += x*x; } return sum / vals.size(); } private double calculate_average(List<Double> vals) { double sum = 0; for (Double val : vals) { sum += val; } return sum / vals.size(); } private List<Double> calculate_mode(List<Double> vals) { int max_frequency = 0; Map<Double, Integer> frequencies = new HashMap<>(); for (Double val : vals) { int occurances = frequencies.getOrDefault(val, 0) + 1; frequencies.put(val, occurances); if (occurances > max_frequency) { max_frequency = occurances; } } List<Double> mode = new ArrayList<>(); for (Entry<Double, Integer> frequency : frequencies.entrySet()) { if (frequency.getValue() == max_frequency) { mode.add(frequency.getKey()); } } return mode; } private double find_value_at(List<Double> vals, int num, int denom) { int len = vals.size(); return (vals.get((num*len)/denom) + vals.get((num*(len+1))/denom)) / 2; } private double calculate_median(List<Double> vals) { return find_value_at(vals, 1, 2); } private double calculate_iqr(List<Double> vals) { return find_value_at(vals, 3, 4) - find_value_at(vals, 1, 4); } private void reportStats(List<Double> vals) { if (vals.size() == 0) { System.err.println("Unable to process data due to: data length is 0"); return; } List<Double> sorted_vals = new ArrayList<>(vals); Collections.sort(sorted_vals); System.out.println("Max: " + sorted_vals.get(0)); System.out.println("Min: " + sorted_vals.get(sorted_vals.size()-1)); System.out.println("Range: " + calculate_range(sorted_vals)); System.out.println("Inter-quartile Range: " + calculate_iqr(sorted_vals)); System.out.println("Average: " + calculate_average(vals)); System.out.println("Median: " + calculate_median(sorted_vals)); System.out.println("Mode: " + calculate_mode(sorted_vals)); System.out.println("Variance: " + calculate_variance(vals)); System.out.println("Standard deviation: " + Math.sqrt(calculate_variance(vals))); } }
package com.sirma.itt.javacourse.ds.lists; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; /** * @author Sinan Mustafov */ public class DoublyLinkedListTest { @Test public void addFirst_Should_WorkProperly_WithOneElement() { DoublyLinkedList<Integer> list = new DoublyLinkedList<>(); list.addFirst(10); assertEquals(Integer.valueOf(10), list.first()); assertEquals(Integer.valueOf(10), list.last()); assertEquals(1, list.size()); } @Test public void addFirst_Should_WorkProperly_WithMultipleElements() { DoublyLinkedList<Integer> list = new DoublyLinkedList<>(); list.addFirst(10); list.addFirst(20); list.addFirst(30); list.addFirst(40); list.addFirst(50); assertEquals(Integer.valueOf(50), list.first()); assertEquals(Integer.valueOf(10), list.last()); assertEquals(5, list.size()); } @Test public void addLast_Should_WorkProperly_WithOneElement() { DoublyLinkedList<Integer> list = new DoublyLinkedList<>(); list.addLast(10); assertEquals(Integer.valueOf(10), list.first()); assertEquals(Integer.valueOf(10), list.last()); assertEquals(1, list.size()); } @Test public void addLast_Should_WorkProperly_WithMultipleElements() { DoublyLinkedList<String> list = new DoublyLinkedList<>(); list.addLast("first"); list.addLast("second"); list.addLast("third"); list.addLast("forth"); assertEquals("first", list.first()); assertEquals("forth", list.last()); assertEquals(4, list.size()); } @Test public void removeFirst_Should_ReturnNull_When_ListIsEmpty() { DoublyLinkedList<String> list = new DoublyLinkedList<>(); assertEquals(0, list.size()); assertNull(list.removeFirst()); assertEquals(0, list.size()); } @Test public void removeFirst_Should_LeaveEmptyList_When_HasOneElement() { DoublyLinkedList<Integer> list = new DoublyLinkedList<>(); list.addFirst(2); assertEquals(Integer.valueOf(2), list.removeFirst()); assertEquals(0, list.size()); } @Test public void removeFirst_Should_WorkProperly_WithMultipleAdds() { DoublyLinkedList<Integer> list = new DoublyLinkedList<>(); list.addFirst(10); list.addLast(20); list.addFirst(30); list.addLast(40); list.addFirst(50); assertEquals(Integer.valueOf(50), list.removeFirst()); assertEquals("30 10 20 40", list.toString()); } @Test public void first_Should_ReturnNull_When_ListIsEmpty() { DoublyLinkedList<Integer> list = new DoublyLinkedList<>(); assertNull(list.first()); } @Test public void last_Should_ReturnNull_When_ListIsEmpty() { DoublyLinkedList<Integer> list = new DoublyLinkedList<>(); assertNull(list.last()); } @Test public void should_WorkWithAlotOfElements() { DoublyLinkedList<Integer> list = new DoublyLinkedList<>(); for (int i = 0; i < 100; i++) { list.addLast(i); } assertEquals(100, list.size()); assertEquals(Integer.valueOf(0), list.first()); assertEquals(Integer.valueOf(99), list.last()); for (int i = 0; i < 100; i++) { assertEquals(Integer.valueOf(i), list.removeFirst()); } assertEquals(0, list.size()); assertNull(list.first()); assertNull(list.last()); } }
import { createRouter, createWebHistory } from 'vue-router' import HomePage from '@/views/HomePage.vue' const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { path: '/', name: 'home', component: HomePage, }, { path: '/new', name: 'new-product', component: () => import('@/views/NewProductPage.vue'), }, { path: '/product/:id', name: 'edit-product', component: () => import('@/views/EditProductPage.vue'), }, { path: '/sign-in', name: 'sign-in', component: () => import('@/views/SignInPage.vue'), }, { path: '/sign-up', name: 'sign-up', component: () => import('@/views/SignUpPage.vue'), }, ], }) export default router
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { NavbarComponent } from './components/navbar/navbar.component'; import { FaIconLibrary, FontAwesomeModule, } from '@fortawesome/angular-fontawesome'; import { faBook, faCompass, faHouse, faUserGear, faArrowLeft, } from '@fortawesome/free-solid-svg-icons'; import { HeaderComponent } from './components/header/header.component'; @NgModule({ declarations: [AppComponent, NavbarComponent, HeaderComponent], imports: [BrowserModule, AppRoutingModule, FontAwesomeModule], providers: [], bootstrap: [AppComponent], }) export class AppModule { constructor(library: FaIconLibrary) { library.addIcons(faHouse, faBook, faCompass, faUserGear, faArrowLeft); } }
# PWR002: Declare scalar variables in the smallest possible scope ### Issue A scalar variable should be declared in the smallest [scope](../../Glossary/Variable-scope.md) possible. In computer programming, the term scope of a variable usually refers to the part of the code where the variable can be used (e.g. a function, a loop). During the execution of a program, a variable cannot be accessed from outside of its scope. This effectively limits the visibility of the variable, which prevents its value from being read or written in other parts of the code. ### Actions Move the declaration to the smallest possible scope. ### Relevance Explicitly declaring scalar variables in the smallest scope possible simplifies data flow analysis, which may be difficult, time-consuming and error-prone especially in big code bases that contain many function calls spread along multiple files. It makes it easier for the compiler to track the usage of variables. By minimizing the number of statements where the value can be modified, it is easier to diagnose why a variable is taking an erroneous value. Additionally, it reduces the likelihood of reusing variables for multiple, incompatible purposes, making code testing significantly easier. >**Note** >In the context of parallel programming, one of the biggest challenges is to do >data scoping correctly and decide on how to manage all the variables of the >code properly. For example, it is very important to determine if a variable >needs to be declared as private to the threads or if it needs to be shared >among all the threads. Not doing so may introduce race conditions during the >parallel execution, which makes the result of the code wrong in unpredictable >ways. ### Code examples #### C In the following code, the function `example` declares a variable `t` used in each iteration of the loop to hold a value that is then assigned to the array `result`. The variable `t` is not used outside of the loop. ```c void example() { int t; int result[10]; for (int i = 0; i < 10; i++) { t = i + 1; result[i] = t; } } ``` In this code, the smallest possible scope for the variable `t` is within the loop body. The resulting code would be as follows: ```c void example() { int result[10]; for (int i = 0; i < 10; i++) { int t = i + 1; result[i] = t; } } ``` From the perspective of parallel programming, moving the declaration of variable `t` to the smallest possible scope helps to prevent potential race conditions. For example, in the OpenMP parallel implementation shown below there is no need to use the clause `private(t)`, as the declaration scope of `t` inherently dictates that it is private to each thread. This avoids potential race conditions because each thread modifies its own copy of the variable `t`. ```c void example() { int result[10]; #pragma omp parallel for default(none) shared(result) for (int i = 0; i < 10; i++) { int t = i + 1; result[i] = t; } } ``` #### Fortran Fortran 2008 introduced the `BLOCK` construct. This feature allows to organize code within larger programs by grouping sections together. Conveniently, `BLOCK` supports new variable declarations within those sections. In the following code, the subroutine `example` declares a variable `t` used in each iteration of the loop to hold a value that is then assigned to the array `result`. The variable `t` is not used outside of the loop. ```f90 subroutine example() implicit none integer :: t integer, dimension(10) :: result integer :: i do i = 1, 10 t = i + 1 result(i) = t end do end subroutine example ``` However, the smallest possible scope for the variable `t` is within the loop body. The resulting code with the `BLOCK` construct would be as follows: ```f90 subroutine example() implicit none integer, dimension(10) :: result integer :: i do i = 1, 10 block integer :: t t = i + 1 result(i) = t end block end do end subroutine example ``` From the perspective of parallel programming, moving the declaration of variable `t` to the smallest possible scope helps to prevent potential race conditions. For example, in the OpenMP parallel implementation shown below there is no need to use the clause `private(t)`, as the declaration scope of `t` inherently dictates that it is private to each thread. This avoids potential race conditions because each thread modifies its own copy of the variable `t`. ```f90 subroutine example() implicit none integer, dimension(10) :: result integer :: i !$omp parallel do default(none) shared(result) private(i) do i = 1, 10 block integer :: t t = i + 1 result(i) = t end block end do !$omp end parallel do end subroutine example ``` ### Related resources * [PWR002 examples](../PWR002) ### References * [Scope of variables](https://users.cs.cf.ac.uk/Dave.Marshall/PERL/node52.html)
<!DOCTYPE html> <html lang="en-US" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Book Exchange</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <link rel="stylesheet" th:href="@{/css/addbook.css}"> </head> <body> <!-- NavBar --> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#">MyBookExchangePortal</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <form class="d-flex"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> <div class="d-flex"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-1"> <li class="nav-item"> <a class="nav-link" aria-current="page" th:href="@{'/home/' + ${user.id}}">Home</a> </li> <li class="nav-item"> <a class="nav-link" aria-current="page" th:href="@{'/add/' + ${user.id}}">Add Book</a> </li> <li class="nav-item"> <a class="nav-link" href="../wallet/wallet.html">Wallet</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Profile </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" th:href="@{'/borrowed/' + ${user.id}}">Borrowed books</a></li> <li><a class="dropdown-item" th:href="@{'/books/' + ${user.id}}">My books</a></li> <!-- <li><a class="dropdown-item" href="#">Borrowed books</a></li> --> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" th:href="@{'/profile/' + ${user.id}}">UserProfile</a></li> <li><a class="dropdown-item" th:href="@{editprofile}">Edit Profile</a></li> </ul> </li> <li class="nav-item"> <a class="nav-link active" aria-current="page" th:href="@{logout}">Logout</a> </li> </ul> </div> </div> </div> </nav> <!-- Sign UP --> <div class="container mt-5 mb-5 p-0" id="container"> <div class="form-container sign-up-container"> <form th:action="@{'/borrowbk/' + ${user.id} +'/' +${currbook.bookid}}" th:object="${dummy}" method="POST"> <h2>Request Book</h2> <h2 th:text="${currbook.title}"></h2> <!-- <div class="social-container"> <a href="#" class="social"><i class="fab fa-facebook-f"></i></a> <a href="#" class="social"><i class="fab fa-google-plus-g"></i></a> <a href="#" class="social"><i class="fab fa-linkedin-in"></i></a> </div> --> <input type="text" th:field="${dummy.start}" placeholder="Start Date (yyyy-mm-dd)" /> <input type="text" th:field="${dummy.end}" placeholder="End Date (yyyy-mm-dd)" /> <button type="submit">Request</button> </form> </div> </div> </body> </html>
import { useState } from 'react' import { Button } from '@/components/button' import Loader from '@/components/loader' import usePurchaseHistory from '@/graphql/user/purchase-history' import requestRefundMutation from '@/graphql/user/request-refund' import capitalizeFirstLetters from '@/lib/capitalize-first-letters' import { useTranslation } from 'next-i18next' import toast from 'react-hot-toast' interface HistoryProps { subscriptionOnly?: boolean } const History = ({ subscriptionOnly = false }: HistoryProps) => { const { data, isLoading } = usePurchaseHistory({ subscriptionOnly, }) const [expandedId, setExpandedId] = useState<string | null>(null) const { i18n } = useTranslation() const { t } = useTranslation('user-ticket') return ( <div className=""> <div className="grid grid-cols-[2fr_1fr_1fr] border-b border-neutral-200 pb-2 px-4"> <p className="font-medium"> {t('ride')} </p> <p className="font-medium"> {t('price')} </p> <p className="font-medium"> {t('Date')} </p> </div> {isLoading && ( <div className="mt-7"> <Loader /> </div> )} {data?.length === 0 && !isLoading && ( <div className="mt-7 flex flex-col"> <p className="text-center text-neutral-500"> {t('NoHistory')} </p> </div> )} {/* eslint-disable-next-line @typescript-eslint/no-explicit-any */} {data?.map((ticket: any) => { const ticketDate = new Date(ticket.date) const now = new Date() const oneHourBeforeDeparture = new Date(ticketDate.getTime() - 60 * 60 * 1000) const isRefundable = ticket.refundRequest === null && now < oneHourBeforeDeparture return ( <div key={ticket.id}> <button className="w-full hover:bg-neutral-100 transition-colors duration-200 ease-in-out" onClick={() => setExpandedId(prev => { if (prev === ticket.id) return null return ticket.id })} > <div className="w-full text-left grid grid-cols-[2fr_1fr_1fr] border-b border-neutral-200 py-3 px-4 "> <p className="ltr:text-left rtl:text-right"> {i18n.language === 'ar' ? ticket.from.name_ar : ticket.from.name} {t('to')} {i18n.language === 'ar' ? ticket.to.name_ar : ticket.to.name} </p> <p className="text-neutral-500 ltr:text-left rtl:text-right"> {ticket.price.toLocaleString([i18n.language === 'ar' ? 'ar-EG' : 'en-US'], { minimumFractionDigits: 2, maximumFractionDigits: 2, })} {' '} {t('EGP')} </p> <p className="text-neutral-500 ltr:text-left rtl:text-right"> {new Date(ticket.date).toLocaleDateString( i18n.language === 'ar' ? 'ar-EG' : 'en-US', { day: 'numeric', year: 'numeric', month: 'long', }, )} {' '} {t('at')} {' '} {new Date(ticket.date).toLocaleTimeString( i18n.language === 'ar' ? 'ar-EG' : 'en-US', { hour: 'numeric', minute: 'numeric', }, )} </p> </div> </button> {expandedId === ticket.id && ( <div className="px-4 py-2 ml-5 text-sm text-neutral-500 mb-4 flex flex-col items-start gap-2"> <div> <p className="font-medium"> {t('passengers')} </p> <p> {ticket?.adults} {' '} {t('adults')} </p> <p> {ticket?.seniors} {' '} {t('seniors')} </p> <p> {ticket?.children} {' '} {t('children')} </p> </div> <div className="flex flex-col gap-1"> {ticket.refundRequest ? ( <> <p className="font-medium mt-4"> {t('Refund')} {t('Request')} </p> <div> <p className="font-medium"> {t('Status')} </p> <p> {capitalizeFirstLetters(ticket.refundRequest.status)} </p> </div> <div> <p className="font-medium"> {t('RequestedAt')} </p> <p> {new Date(ticket.refundRequest.createdAt).toLocaleDateString( i18n.language === 'ar' ? 'ar-EG' : 'en-US', { day: 'numeric', year: 'numeric', month: 'long', }, )} {' '} {t('at')} {' '} {new Date(ticket.refundRequest.createdAt).toLocaleTimeString( i18n.language === 'ar' ? 'ar-EG' : 'en-US', { hour: 'numeric', minute: 'numeric', }, )} </p> </div> {ticket.refundRequest.status !== 'PENDING' && ( <div> <p className="font-medium"> {t('ReviewedAt')} </p> <p> {new Date(ticket.refundRequest.updatedAt).toLocaleDateString( i18n.language === 'ar' ? 'ar-EG' : 'en-US', { day: 'numeric', year: 'numeric', month: 'long', }, )} {' '} {t('at')} {' '} {new Date(ticket.refundRequest.updatedAt).toLocaleTimeString( i18n.language === 'ar' ? 'ar-EG' : 'en-US', { hour: 'numeric', minute: 'numeric', }, )} </p> </div> )} </> ) : ( <> {isRefundable && ( <Button useLoading variant="linkSecondary" className="!px-0 !py-0 min-w-[7.7em]" onClick={async () => { try { await requestRefundMutation({ id: ticket.id, ticketType: { ticketType: 'TICKET', }, }) toast.success('Refund request sent successfully') setExpandedId(null) } catch (e) { toast.error('Something went wrong') } }} > {t('Request')} {t('Refund')} </Button> )} </> )} </div> </div> )} </div> ) })} </div> ) } export default History
import React ,{useState} from 'react'; import TodoForm from './TodoForm'; import {v4 as uuidv4} from 'uuid' import Todo from './Todo'; uuidv4(); const TodoWaper = () => { const [todos , setTodos] = useState([ ]) const addTodo = todo => { setTodos([...todos , {id: uuidv4() , task: todo , completed: false , isEditing : false}]) console.log(todos) } const toggleCompleted = id => { setTodos(todos.map(todo => todo.id === id ? { todo,completed: ! todo.completed }: todo)) } return ( <div className='TodoWaper'> <div className='container-sm'> <div className='Card' style={{ width: '30rem' ,margin: '0 auto' , }}> <h1 className='title' style={{textAlign: 'center'}}>TODO LIST</h1> <TodoForm addTodo={addTodo}/> {todos.map((todo , index) => ( <Todo task = {todo} key = {index} toggleCompleted = {toggleCompleted}/> ))} </div> </div> </div> ); }; export default TodoWaper;
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>VJHS::View Teachers</title> </head> <body> <jsp:include page="vjhstop.jsp" /> <c:set var="page" scope="request" value="TEACHER" /> <jsp:include page="vjhsmenu.jsp" /> <div class="mainBody"> <div class="mainBodyStyle"> <div class="mainLeftBodyStyle"> <div class="leftPaneHeadding">Manage Teachers</div> <ul> <li><a href="add.teacher">Add Teachers</a></li> <li class="activeLeftPane"><a href="view.teacher">View Teachers</a></li> <li><a href="attendance.teacher">Attendance</a></li> <li><a href="viewtt.teacher">Time Table</a></li> </ul> </div> <div class="mainRightBodyStyle"> <div> <fieldset> <legend>View Teachers</legend> <table class="example display compact"> <thead> <tr> <th>Emp ID</th> <th>Emp Name</th> <th>DOJ</th> <th>Mobile</th> <th>Qualification</th> <th>Class Teacher</th> <th>Exp</th> <th>Modify</th> <th>Delete</th> </tr> </thead> <!-- <tfoot> <tr> <th>Emp ID</th> <th>Emp Name</th> <th>DOJ</th> <th>Mobile</th> <th>Qualification</th> <th>Class Teacher</th> <th>Exp</th> <th>Modify</th> <th>Delete</th> </tr> </tfoot> --> <tbody> <c:forEach items="${teacherList}" var="teacher"> <c:url value="modifyTeacher.teacher" var="modifyTeacher"> <c:param name="empId" value="${teacher.employeeId}" /> </c:url> <c:url value="deleteTeacher.teacher" var="deleteTeacher"> <c:param name="empId" value="${teacher.employeeId}" /> </c:url> <tr> <td><c:out value="${teacher.employeeId}"></c:out></td> <td><c:out value="${teacher.teacherName}"></c:out></td> <td><c:out value="${teacher.dateOfJoining}"></c:out></td> <td><c:out value="${teacher.phone}"></c:out></td> <td><c:out value="${teacher.qualification}"></c:out></td> <td><c:out value="${teacher.class_teacher}"></c:out></td> <td><c:out value="${teacher.experiance}"></c:out></td> <td><a href="<c:out value="${modifyTeacher}"></c:out>">Modify</a></td> <td><a href="<c:out value="${deleteTeacher}"></c:out>">Delete</a></td> </tr> </c:forEach> </tbody> </table> </fieldset> </div> <div class="minHeightDiv"></div> </div> </div> </div> <jsp:include page="vjhsbottom.jsp" /> <script type="text/javascript"> $(function() { $('.example').dataTable(); }); </script> </body> </html>
import Container from "@/components/ui/container"; import ProductCard from "@/components/routes/product-card"; import CategoryTabs from "../components/routes/category-tabs"; import { Button } from "@/components/ui/button"; import { ChevronRight, FileVolume, HomeIcon, Music, Shirt } from "lucide-react"; import { merch } from "@/constants/merch"; export default function Home() { return ( <Container> <div className="mt-28 flex items-center justify-center rounded-3xl bg-[radial-gradient(ellipse_at_top_right,_var(--tw-gradient-stops))] from-amber-200 via-violet-600 to-sky-900 p-8 md:justify-start lg:p-14"> <div className="md:w-1/2"> <div> <h1 className="bg-gradient-to-r from-amber-200 via-pink-300 to-pink-100 bg-clip-text text-3xl font-extrabold text-transparent md:text-5xl md:leading-[3.3rem]"> Explore The New Merch </h1> </div> <div className="mt-5"> <p className="leading-7"> Fdipisicing ipsumds dolor sit amet consectetur adipisicing elit. Cluptates lorem tenetur odio voluptatem hic repellat eligendi! Lorem ipsum dolor sit amet. </p> {/* <Button className="mt-5 w-full md:w-1/2" size={"lg"}> Shop Collection <span className="ml-2"> <ChevronRight size={23} /> </span> </Button> */} </div> </div> </div> <div className="mt-10 grid grid-cols-1 gap-5 md:grid-cols-4"> <CategoryTabs category="All" icon={<HomeIcon />} /> <CategoryTabs category="Merch" icon={<Shirt />} /> <CategoryTabs className="cursor-not-allowed" category="Albums" icon={<Music />} /> <CategoryTabs className="cursor-not-allowed" category="Beats" icon={<FileVolume />} /> </div> <div className="mt-10"> <h1 className="text-3xl font-semibold">Merch</h1> <div className="gap-10 sm:grid sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4"> {merch.map((element) => { return ( <ProductCard key={element.id} title={element.title} category={element.category} price={element.price} imageSrc={element.imageSrc} /> ); })} </div> </div> </Container> ); }
// 소수 구하기 // M 이상 N 이하의 소수 모두 출력 // 에라토스테네스의 체 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class BJ_1929 { public static void main(String[] args) throws IOException{ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(bf.readLine()); int m, n; m = Integer.parseInt(st.nextToken()); n = Integer.parseInt(st.nextToken()); bf.close(); if(m>n){ System.out.println("M is bigger than N"); return; } /* arr[i]의 값이 0이면 소수 */ int[] arr = new int[n+1]; arr[1] = 1; // 1은 소수가 아님. for(int i=2; i<=n; i++){ // 숫자 i에 대하여 소수 여부 저장 if(arr[i] != 1) for(int j=2; i*j<=n; j++){ // 범위 내에서, 소수가 아닌 수 1로 저장 arr[i*j] = 1; } } for(int j=m; j<=n; j++) if(arr[j] != 1) System.out.println(j); } } /* // 시간 복잡도 O(N^2) public class Main { public static void checkPrimeNum(int x){ if(x<2){ return; } for(int i=2; i<=x/2; i++){ if(x%i == 0) return; } System.out.println(x); } public static void main(String[] args) throws IOException{ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(bf.readLine()); int m, n; m = Integer.parseInt(st.nextToken()); n = Integer.parseInt(st.nextToken()); System.out.println(m+" " + n); if(m>n){ System.out.println("M is bigger than N"); return; } for(int i=m; i<=n; i++) checkPrimeNum(i); } } */
import { OkPacketParams } from "mysql2"; import db from "../../../config/db"; import { Class, ClassToAdd, ClassToEdit } from "./types"; import { ApiFeaturesOptions, ApiFeaturesResult } from "../../../types"; import ApiFeatures from "../../../utils/ApiFeatures"; class ClassesModel { static features = (query: ApiFeaturesOptions) => { return new ApiFeatures(query) .filter(["school_id", `teacher_id`, "course_id", "is_terminated"]) .pagination() .sort(["start_date"]) .search(["class_name"]) .fields([ `id`, `class_name`, `school_id`, `school_name`, `course_id`, `course_title`, `teacher_id`, `teacher_name`, `start_date`, `is_terminated`, `terminate_date`, `reports_visible`, ]); }; static async getAll(queryResult: ApiFeaturesResult) { const sql = ` SELECT ${queryResult.fields} from classes_view WHERE 1=1 ${queryResult.query}`; const [classes] = await db.query(sql); return classes as Class[]; } static async getNumber(queryString: string) { const sql = ` SELECT COUNT(id) as count from classes_view WHERE 1=1 ${queryString} `; const [result] = await db.query(sql); return (result as { count: number }[])[0].count; } static async getById(id: number) { const sql = `SELECT * FROM classes_view WHERE id = ?`; const values = [id]; const [classes] = await db.query(sql, values); return classes as Class[]; } static async add(class_: ClassToAdd) { const sql = `INSERT INTO classes(school_id, course_id, teacher_id, start_date) VALUES (?,?,?,?)`; const values = [ class_.school_id, class_.course_id, class_.teacher_id, class_.start_date, ]; await db.query(sql, values); } static async editById(class_id: number, class_: ClassToEdit) { const sql = `UPDATE classes_view SET ? WHERE id = ?`; const values = [class_, class_id]; const [result] = await db.query(sql, values); return result as OkPacketParams; } static async deleteById(class_id: number) { const sql = `CALL delete_class(?)`; const values = [class_id]; const [result] = await db.query(sql, values); return result as OkPacketParams; } static async terminateById(class_id: number) { const sql = `UPDATE classes_view SET is_terminated = true , terminate_date = utc_timestamp() WHERE id = ?`; const values = [class_id]; const [result] = await db.query(sql, values); return result as OkPacketParams; } static async enrollStudents(classId: number, studentsIds: number[]) { const sql = ` INSERT IGNORE INTO class_enrollment (class_id,student_id) SELECT ? as class_id , id as student_id FROM students WHERE school = (SELECT school_id FROM classes WHERE id = ? ) AND id IN (?) `; const values = [classId, classId, studentsIds]; await db.query(sql, values); } static async removeEnrolledStudents( classId: number, studentsIds: number[] ) { const sql = `DELETE FROM class_enrollment WHERE class_id = ? AND student_id IN (?)`; const values = [classId, studentsIds]; await db.query(sql, values); } static async getEnrolledStudents(classId: number, queryString: string) { const sql = `SELECT s.id , name , photo FROM class_enrollment c INNER JOIN students s on student_id = s.id WHERE c.class_id = ? ${queryString}`; const values = [classId]; const [students] = await db.query(sql, values); return students as { id: number; name: string }[]; } static async getEnrolledStudentsNumber( classId: number, queryString: string ) { const sql = `SELECT COUNT(s.id) as count FROM class_enrollment c INNER JOIN students s on student_id = s.id WHERE c.class_id = ? ${queryString}`; const values = [classId]; const [result] = await db.query(sql, values); return (result as { count: number }[])[0].count; } static checkExists = async (id: number) => { const sql = `SELECT IF(COUNT(id)>0,true,false) as exist FROM classes WHERE id = ?`; const values = [id]; const [result] = await db.query(sql, values); return result as { exist: boolean }[]; }; static async getSchoolAndTeacherOfClass(classId: number) { const sql = "SELECT school_id , teacher_id FROM classes WHERE id = ?"; const values = [classId]; const [result] = await db.query(sql, values); return result as { school_id: number; teacher_id: number }[]; } static async checkStudentEnrolledInClass( studentId: number, classId: number ) { const sql = "SELECT IF(COUNT(student_id)>0,true,false) as enrolled FROM class_enrollment WHERE student_id = ? AND class_id = ? "; const values = [studentId, classId]; const [result] = await db.query(sql, values); return result as { enrolled: boolean }[]; } static checkClassIsTerminated = async (classId: number) => { const sql = "SELECT is_terminated FROM classes_view WHERE id = ?"; const values = [classId]; const [result] = await db.query(sql, values); return result as { is_terminated: boolean }[]; }; static classesNumberOfTeacherAndStudent = async ( teacherId: number, studentId: number ) => { const sql = `SELECT COUNT(*) as count FROM students_count_in_class_of_teacher WHERE teacher_id = ? AND student_id = ?`; const values = [teacherId, studentId]; const [result] = await db.query(sql, values); return result as { count: number }[]; }; } export default ClassesModel;
import {Container, Spinner} from "react-bootstrap"; import {useState} from "react"; import useChuckNorrisService from "../../service/use-chuck-norris-service"; import JokesTable from "../jokes-table/Jokes-table"; const JokePage = () => { const [joke, setJoke] = useState('joke') const {getJoke, loading} = useChuckNorrisService() const onClick = (e) => { e.preventDefault(); getJoke() .then(({data: {joke}}) => setJoke(joke)) } const spinner = loading? <Spinner className={'d-block mx-auto'} /> : null return ( <Container className={'py-5'}> <h1 className="text-center mb-4">Chuck Norris jokes Api</h1> <div className="row"> <button onClick={onClick} type="button" className="btn btn-primary offset-5 col-2">get joke</button> </div> <div style={{whiteSpace: 'pre-wrap'}} className="alert alert-light text-center mt-5 offset-3 col-6" > {spinner} {joke} </div> <JokesTable joke={joke} /> </Container> ) } export default JokePage;